query
stringlengths
7
9.55k
document
stringlengths
10
363k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
GET /surgeries/1 GET /surgeries/1.json
def show end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @surgeries = Surgery.all\n end", "def index\n @surgeries = Surgery.all\n end", "def surgery_name_list\n\t\tsurgeries = current_user.surgeries\n\t\tif surgeries.present?\n\t\t# response to the JSON\n \t render json: { success: true, response: {surgeries: surgeries.collect(&:name).as_json } },:status=> 200\n\t else\n\t render :json=> { success: false, message: \"Surgeries are not present\" },:status=> 203\n\t end \n\tend", "def show\n @surgery = Surgery.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @surgery }\n end\n end", "def show\n @village = Village.find(params[:id])\n @collections = @village.collections\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @village }\n end\n end", "def allergies\n raise UserNotAuthenticated unless access_token\n\n get('records/allergies')\n end", "def show\n @grumble = Grumble.find(params[:id])\n render status: 200, json: @grumble.to_json\n end", "def show\n @sundry_grn = SundryGrn.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @sundry_grn }\n end\n end", "def badges\n get(\"user/#{user_id}/badges.json\")\n end", "def index_by_age\n @age = Age.find(params[:age_id])\n @gifts = @age.gifts\n render json: @gifts, include: :ages, status: :ok\n end", "def index\n @allergies = Allergy.all\n end", "def show\n @county = County.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @county }\n end\n end", "def index\n @specialties = Specialty.all\n\n render json: @specialties\n end", "def uni_years\n @uni_years = UniYear.where(university_id: params[:university_id])\n \n respond_to do |format|\n format.json { render json: @uni_years }\n end\n end", "def show\n\t\trecords = University.where(['name LIKE ?', \"#{params[:name]}%\"])\n\t\tschools = Array.new\n\n\t\trecords.each do |record|\n\t\t\tcents_rating = RatesSchool.find_by_sql [\n\t\t\t\t'SELECT avg(rating) AS average\n\t\t\t\tFROM rates_schools\n\t\t\t\tWHERE university_id = ?',\n\t\t\t\trecord.id\n\t\t\t]\n\t\t\trecord = record.as_json\n\t\t\trecord[:average_rating] = cents_rating[0][:average].to_f\n\t\t\tschools << record.except('id', 'created_at', 'updated_at')\n\t\tend\n\n\t\tif schools.present?\n\t\t\treturn render json: schools, status: 200\n\t\telse\n\t\t\treturn render json: [], status: 404\n\t\tend\n\tend", "def show\n @badge = Badge.find(params[:id])\n @users = @badge.users\n respond_with @badge\n end", "def show\n @gage = Gage.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gage }\n end\n end", "def show\n render json: Agent.find(params[:id]).buyers\n end", "def semesters\n uni_year = UniYear.find_by_id(params[:uni_year_id])\n @semesters = uni_year ? uni_year.semesters : []\n \n respond_to do |format|\n format.json { render json: @semesters }\n end\n end", "def index\n @guys = Guy.all\n respond_to do |format|\n format.json { render json: @guys }\n end\n end", "def search_surgery\n\t\t# Searching for surgery as per user entered term\n\t\tif Surgery.where(user_type: \"admin\").any_of({ :name => /^#{params[:term]}/i }).present?\n\t\t\t# if search show from the admin then the search term from surgery of admin\n\t\t\tsurgeries = Surgery.where(user_type: \"admin\").any_of({ :name => /^#{params[:term]}/i }).all.collect{|surgery| {label: surgery.name}}.uniq.to_json\n\t\telse\n\t\t\t# else the term is not equal to the admin surgery then that search from the user term\n\t\t\tsurgeries = current_user.surgeries.any_of({ :name => /^#{params[:term]}/i }).all.collect{|surgery| {label: surgery.name}}.uniq.to_json \n\t\tend\n\t\t# render to the surgery name page\n\t\trespond_to do |format|\n\t\t format.json { render :json => surgeries }\n\t\tend\n\tend", "def surveys\n person_id = params[:person_id]\n \n surveys = SurveyService.findSurveysForPerson person_id\n \n render json: surveys.to_json, :content_type => 'application/json'\n end", "def index\n @universities = University.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @universities }\n end\n end", "def show\n @county = Entity.where(id: params[:id]).where(entity_type: 'County').first\n respond_with(@county) do |format|\n format.geojson { render text: @county.to_geojson }\n end\n end", "def index\n load_county or raise \"county not found\"\n\n breadcrumbs.add(:url=>@state.to_url, :title=>@state.name)\n breadcrumbs.add(:url=>@county.to_url, :title=>@county.name)\n self.page_title = \"#{@county.fancy_name_with_state} Cemetery Map\"\n\n @graveyards = @county.graveyards.includes(:main_photo).includes(:county)\n\n respond_to do |fmt|\n @visits=UserVisitsCollection.new(current_user)\n @visits.add_graveyards(@graveyards)\n fmt.json do\n render :json => {\n status: :success,\n locations: @graveyards.sort_by(&:name).map(&:map_data).map { |g|\n if v = @visits.visit_for(g[:id])\n g[:visit] = v.as_json(:only=> [\n :id, :status, :visited_on,\n :expedition_id, :ordinal, :quality\n ])\n end\n g\n },\n # visits: @visits\n }\n end\n fmt.html { render :action=>:index }\n end\n end", "def show\n survivor = Suvivor.find(params[:id])\n render json: {status: 'SUCCESS', message:'Survivor founded', data:survivor},status: :ok\n end", "def index\n @blood_pressures = BloodPressure.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @blood_pressures }\n end\n end", "def show\n @gastracker = Gastracker.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gastracker }\n end\n end", "def index\n @universes = Universe.all.page(params[:page]).per(25)\n respond_to do |format|\n format.html\n format.json { render json: @universes }\n end\n end", "def show\r\n @venue = Venue.fetch(params[:id])\r\n render json: @venue\r\n end", "def serv_json\n \"http://api.dribbble.com/shots/popular?page=1\"\n end", "def show\n @grocery = Grocery.find(params[:id])\n\n render json: @grocery\n end", "def show\n @gopy = Gopy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gopy }\n end\n end", "def show\n @citation = Citation.find(params[:id])\n @galaxies = @citation.galaxies\n @citation.galaxy_ids_array\n\n respond_to do |format|\n format.html { render :show }\n format.json { render :json => @citation.to_json(\n :only => [:title, :author, :bibtex, :journal, :year,\n :volume, :pages, :month, :note, :key],\n :methods => [:galaxy_ids_array]\n )\n }\n end\n end", "def index_single_gift\n render json: @gift, include: :ages, status: :ok\n end", "def show\n animal = Animal.find(params[:id])\n #return all the sightings for the animal\n render json: animal.to_json(include: :sightings)\nend", "def index_by_user\n @gifts = @current_user.gifts\n render json: @gifts, include: :ages, status: :ok\n end", "def show\n @golfer = Golfer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @golfer }\n end\n end", "def show\n @nurse = Nurse.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @nurse }\n end\n end", "def getbatteries\n puts params\n buildid = params[\"buildingid\"]\n\n batteries = Battery.where(:building_id => buildid)\n\n puts batteries.inspect\n puts \"#################################################\"\n \n respond_to do |format|\n format.json { render json: batteries }\n end\n end", "def new\n @year_insurances = YearInsurance.active.joins(:family)\n @reimbursement = Reimbursement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @reimbursement }\n end\n end", "def show\n @zombie_sighting = ZombieSighting.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @zombie_sighting }\n end\n end", "def show\n @galaxies_lenticular_galaxy = Galaxies::LenticularGalaxy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @galaxies_lenticular_galaxy }\n end\n end", "def show\n render json: @weapon\n end", "def show\n @gauge = Gauge.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gauge }\n end\n end", "def index\n render json: Seller.all\n end", "def show\n render json: @championship\n end", "def show\n render json: @grade\n end", "def index\n @grannies = policy_scope(Granny)\n if params[:query].present?\n @grannies = Granny.where(district: params[:query])\n else\n @grannies = Granny.all\n end\n end", "def show\n @baggage = Baggage.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @baggage }\n end\n end", "def index\n @injuries = Injury.all\n end", "def show\n @holy_book = HolyBook.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @holy_book }\n end\n end", "def show\n @surg = Surg.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @surg }\n end\n end", "def show\n @guardianship = Guardianship.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @guardianship }\n end\n end", "def show\n #@restroom = Restroom.find(params[:id])\n @venue = client.venue(:query => params[:venue_id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @restroom }\n end\n end", "def new\n @fridge = Fridge.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fridge }\n end\n end", "def index\n @guardianships = Guardianship.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @guardianships }\n end\n end", "def show\n @gig = Gig.find(params[:id])\n\n respond_to do |format|\n format.html {render json: @gig, status: :ok}\n format.json { render json: @gig, status: :ok }\n end\n end", "def index\n @undergraduate_majors = UndergraduateMajor.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @undergraduate_majors }\n end\n end", "def index\n @upcoming_harvests = Harvest.upcoming\n @past_harvests = Harvest.past\n\n if params[:person_id]\n @person = Person.find(params[:person_id])\n @upcoming_harvests = @person.upcoming_harvests\n @past_harvests = @person.past_harvests\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @harvests }\n end\n end", "def show\n @warrior = Warrior.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @warrior }\n end\n end", "def show\n @warrior = Warrior.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @warrior }\n end\n end", "def show\n @venue = Venue.find(params[:id])\n\n render json: @venue\n end", "def show\n render json: @sighting\n end", "def index\n @chargers = Charger.all\n render json: @chargers\n end", "def index\n @pledges = Pledge.where('user_id = ?', current_user.id)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pledges }\n end\n end", "def index\n @registrations = Tournament.find(params[:tournament_id]).registrations\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @registrations }\n end\n end", "def index\n @registries = Registry.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @registries }\n end\n end", "def badges(id)\n get(\"users/#{id}/badges\")\n end", "def show\n @tagging = Tagging.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tagging }\n end\n end", "def show_location\n\t\trecords = University.where(['state LIKE ?', \"%#{params[:location]}%\"])\n\t\tschools = Array.new\n\n\t\trecords.each do |record|\n\t\t\tcents_rating = RatesSchool.find_by_sql [\n\t\t\t\t'SELECT avg(rating) AS average\n\t\t\t\tFROM rates_schools\n\t\t\t\tWHERE university_id = ?',\n\t\t\t\trecord.id\n\t\t\t]\n\t\t\trecord = record.as_json\n\t\t\trecord[:average_rating] = cents_rating[0][:average].to_f\n\t\t\tschools << record.except('id', 'created_at', 'updated_at')\n\t\tend\n\n\t\tif schools.present?\n\t\t\treturn render json: schools, status: 200\n\t\telse\n\t\t\treturn render json: [], status: 404\n\t\tend\n\tend", "def show\n sighting = Sighting.find(params[:id])\n #render json: sighting.to_json(:include => {:bird => {:only =>[:name, :species]}, :location => {:only =>[:latitude, :longitude]}}, :except => [:updated_at])\n end", "def index\n @sightings = Sighting.all\n render json: @sightings\n end", "def index\n @admin_villages = Admin::Village.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @admin_villages }\n end\n end", "def show\n @badge = Badge.find_by_key(params[:id])\n respond_to do |format|\n format.html\n end\n end", "def show\n animal = Animal.find(params[:id])\n render json: animal.as_json(include: :sightings) \n end", "def index\n @user = User.find(session[:user_id])\n @schools = @user.schools\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @schools }\n end\n end", "def show\n @ugroupe = Ugroupe.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ugroupe }\n end\n end", "def index\n base_url = 'https://www.googleapis.com/books/v1/volumes?q=fiction&maxResults=20'\n and_key = '&key='\n key = ENV['GOOGLE_BOOKS_API_KEY'] \n googleurl = base_url + and_key + key\n\n response = RestClient.get(googleurl)\n @books = JSON.parse(response)\n\n respond_to do |format|\n format.html\n format.json { render json: @books }\n end\n\nend", "def show\n @country = Country.includes(:regions).find(params[:id])\n @tours = Tour.search(params.merge({ region: @country.region_ids}))\n @attractions = @country.regions.map { |i| i.attractions }.flatten\n @hotels = @country.regions.map { |i| i.hotels }.flatten\n @photos = @country.regions.map { |i| i.gallery.photos if i.gallery }.flatten.uniq.compact\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @country }\n end\n end", "def show\n @bird = Bird.joins(:sightings).find(params[:id])\n if @bird\n render json: {\n \"bird\": @bird,\n \"sightings\": [@bird.sightings]\n }, status: :ok\n else\n render json: @bird.errors, status: :unprocessable_entity\n end\n end", "def show\n @golf_cource = GolfCource.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @golf_cource }\n end\n end", "def show\n @revenue = Revenue.find(params[:id])\n\n render json: @revenue\n end", "def show\n render json: @endorsement\n end", "def index\n @reviews = Review.find(params[:burger_place_id])\n\n render json: @reviews\n end", "def show\n @gid2name = Gid2name.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gid2name }\n end\n end", "def destroy\n @surgery = Surgery.find(params[:id])\n @surgery.destroy\n\n respond_to do |format|\n format.html { redirect_to surgeries_url }\n format.json { head :no_content }\n end\n end", "def index\n @goods = Good.where(user: current_user.building.users)\n respond_to do |format|\n format.html\n format.json do\n render json: {\n goods: @goods.map{|g|g.attributes.merge(image: url_for(g.user.profile.pic), ownerId: g.user.id)}\n }\n end\n end\n end", "def index\n @surgery_supplies = SurgerySupply.all\n end", "def index\n @clues = Clue.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @clues }\n end\n end", "def gist(id)\n get \"/gists/#{id}\"\n end", "def show\n @fridge = Fridge.find(params[:id])\n @items = @fridge.fridge_items # for _item_list.html.erb\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fridge }\n end\n end", "def new\n @village = Village.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @village }\n end\n end", "def show\n @household = Household.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @household }\n end\n end", "def gist_url\n \"#{api_url}/gists/%s\"\n end", "def show\n\t\t@household = Household.find(params[:id])\n\t\t@people = @household.people\n\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.json { render json: @household }\n\t\tend\n\tend", "def index\n @bounties = Bounty.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @bounties }\n end\n end", "def new\n @insurer = Insurer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @insurer }\n end\n end", "def index\n @registrations = Registration.order(:last_name).where(\"created_at >= ?\", Date.today.beginning_of_year)\n\n respond_to do |format|\n format.html\n format.json { render json: @registrations, include: { students: { only: [:first_name, :last_name, :shirt_size]}} }\n end\n end", "def index\n @girlfriends = Girlfriend.all\n render json: @girlfriends, status: 200 \n end", "def index\n @gig_rosters = GigRoster.all\n end" ]
[ "0.68215907", "0.68215907", "0.64664173", "0.60792726", "0.5848986", "0.58368206", "0.575722", "0.57187206", "0.56963193", "0.56569594", "0.5653277", "0.5641617", "0.5638659", "0.56322944", "0.56272936", "0.56244427", "0.5617362", "0.5598971", "0.5576895", "0.5540252", "0.5534605", "0.5529379", "0.5521145", "0.550562", "0.5494817", "0.5492965", "0.54860896", "0.5482153", "0.54662", "0.5450259", "0.54470795", "0.54402775", "0.5437804", "0.5429678", "0.54292667", "0.54244584", "0.54106295", "0.5401003", "0.53977805", "0.53975606", "0.53920317", "0.5388932", "0.53850526", "0.53703284", "0.53684396", "0.5365562", "0.53648335", "0.5359777", "0.53571737", "0.5353485", "0.5351989", "0.53517276", "0.5347374", "0.53459656", "0.5337442", "0.53369725", "0.533377", "0.5332893", "0.5331196", "0.53304577", "0.53286195", "0.53286195", "0.53275126", "0.5325464", "0.53253406", "0.53180116", "0.5317126", "0.53096366", "0.53087723", "0.52932787", "0.5292175", "0.5290263", "0.52879447", "0.5277572", "0.5276263", "0.5275079", "0.5270871", "0.52703595", "0.52701426", "0.52691215", "0.5268614", "0.5268243", "0.5264588", "0.5259983", "0.52599424", "0.5255879", "0.52495897", "0.5249484", "0.52463144", "0.52440935", "0.5240515", "0.52398247", "0.5235232", "0.5231767", "0.5231197", "0.5227585", "0.5227482", "0.5225339", "0.52180487", "0.5214507", "0.5212383" ]
0.0
-1
POST /surgeries POST /surgeries.json
def create # Initializing the surgery the params @surgery = devise_current_user.surgeries.new(surgery_params) # saving the surgery save after that redirect to the surgeries index page if @surgery.save redirect_to surgeries_path else # else redirect to the same page of the surgery redirect_to :back end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @surgeries = Surgery.all\n end", "def index\n @surgeries = Surgery.all\n end", "def create\n @surgery = Surgery.new(params[:surgery])\n\n respond_to do |format|\n if @surgery.save\n format.html { redirect_to @surgery, notice: 'Surgery was successfully created.' }\n format.json { render json: @surgery, status: :created, location: @surgery }\n else\n format.html { render action: \"new\" }\n format.json { render json: @surgery.errors, status: :unprocessable_entity }\n end\n end\n end", "def surgery_name_list\n\t\tsurgeries = current_user.surgeries\n\t\tif surgeries.present?\n\t\t# response to the JSON\n \t render json: { success: true, response: {surgeries: surgeries.collect(&:name).as_json } },:status=> 200\n\t else\n\t render :json=> { success: false, message: \"Surgeries are not present\" },:status=> 203\n\t end \n\tend", "def create\n @surgical = Surgical.new(surgical_params)\n\n respond_to do |format|\n if @surgical.save\n format.html { redirect_to surgicals_url, notice: 'Surgical was successfully created.' }\n # format.json { render :show, status: :created, location: @surgical }\n else\n format.html { render :new }\n format.json { render json: @surgical.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @surgery = Surgery.new(surgery_params)\n\n respond_to do |format|\n if @surgery.save\n format.html { redirect_to @surgery, notice: 'Surgery was successfully created.' }\n format.json { render :show, status: :created, location: @surgery }\n else\n format.html { render :new }\n format.json { render json: @surgery.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @injury = Injury.new(injury_params)\n\n respond_to do |format|\n if @injury.save\n format.html { redirect_to injuries_url, notice: 'Injury was successfully created.' }\n # format.json { render :show, status: :created, location: @injury }\n else\n format.html { render :new }\n format.json { render json: @injury.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sundry_grn = SundryGrn.new(params[:sundry_grn])\n\n respond_to do |format|\n if @sundry_grn.save\n format.html { redirect_to @sundry_grn, :notice => 'Sundry grn was successfully created.' }\n format.json { render :json => @sundry_grn, :status => :created, :location => @sundry_grn }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @sundry_grn.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @reimbursement = Reimbursement.new(params[:reimbursement])\n @year_insurances = YearInsurance.active.joins(:family)\n respond_to do |format|\n if @reimbursement.save\n format.html { redirect_to reimbursements_path, notice: 'Reimbursement was successfully created.' }\n format.json { render json: @reimbursement, status: :created, location: @reimbursement }\n else\n format.html { render action: \"new\" }\n format.json { render json: @reimbursement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fridge = Fridge.new(params[:fridge])\n\n respond_to do |format|\n if @fridge.save\n format.html { redirect_to @fridge, notice: 'Fridge was successfully created.' }\n format.json { render json: @fridge, status: :created, location: @fridge }\n else\n format.html { render action: \"new\" }\n format.json { render json: @fridge.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @souvenior = Souvenior.new(souvenior_params)\n\n respond_to do |format|\n if @souvenior.save\n format.html { redirect_to root_path, notice: 'Souvenior was successfully created.' }\n format.json { render :show, status: :created, location: @souvenior }\n else\n format.html { render :new }\n format.json { render json: @souvenior.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @agency = Agency.new(agency_params)\n\n if @agency.save\n render json: @agency, status: :created, location: @agency\n else\n render json: @agency.errors, status: :unprocessable_entity\n end\n end", "def create\n @insurer = Insurer.new(params[:insurer])\n\n respond_to do |format|\n if @insurer.save\n format.html { redirect_to @insurer, notice: 'Insurer was successfully created.' }\n format.json { render json: @insurer, status: :created, location: @insurer }\n else\n format.html { render action: \"new\" }\n format.json { render json: @insurer.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @surgical_profile = SurgicalProfile.new(surgical_profile_params)\n\n # TODO: minimize into single query\n @patient = Patient.query_one_by_id(\n current_user, @surgical_profile.patient_id\n )\n @surgeon = User.find(@surgical_profile.user_id)\n\n respond_to do |format|\n if @surgical_profile.preprocess_and_save()\n format.html { redirect_to patient_surgical_profiles_path(@patient), notice: 'Surgical profile was successfully created.' }\n format.json { render action: 'show', status: :created, location: @surgical_profile }\n else\n format.html { render action: 'new' }\n format.json { render json: @surgical_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @surgery_state = SurgeryState.new(surgery_state_params)\n\n respond_to do |format|\n if @surgery_state.save\n format.html { redirect_to @surgery_state, notice: 'Surgery state was successfully created.' }\n format.json { render :show, status: :created, location: @surgery_state }\n else\n format.html { render :new }\n format.json { render json: @surgery_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @surgery_supply = SurgerySupply.new(surgery_supply_params)\n\n respond_to do |format|\n if @surgery_supply.save\n format.html { redirect_to @surgery_supply, notice: 'Surgery supply was successfully created.' }\n format.json { render :show, status: :created, location: @surgery_supply }\n else\n format.html { render :new }\n format.json { render json: @surgery_supply.errors, status: :unprocessable_entity }\n end\n end\n end", "def createCharities\n\tcharity_list = [\"Direct Relief\", \"Catholic Medical Mission Board\", \"MAP International\", \"United Nations Foundation\", \"The Rotary Foundation of Rotary International\", \"Samaritan's Purse\", \"Institute of International Education\", \"International Rescue Committee\", \"Compassion International\", \"United States Fund for UNICEF\"]\n\tcharity_list.each do |charity|\n\t\tRestClient.post 'http://api.reimaginebanking.com/merchants?key=e0486a76005721ee6d86b140eaea2a40', { \"name\": \"#{charity}\"}.to_json, :content_type => :json, :accept => :json\n\tend\nend", "def create\n @allergy = Allergy.new(allergy_params)\n\n respond_to do |format|\n if @allergy.save\n format.html { redirect_to new_allergy_path, notice: t('allergies.created') }\n format.json { render :show, status: :created, location: @allergy }\n else\n format.html { render :new, alert: t('errors.messages.empty') }\n format.json { render json: @allergy.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sighting = Sighting.new(sighting_params)\n\n if @sighting.save\n render json: @sighting, status: :created, location: @sighting\n else\n render json: @sighting.errors, status: :unprocessable_entity\n end\n end", "def create\n @society_recuritment = SocietyRecuritment.new(society_recuritment_params)\n\n respond_to do |format|\n if @society_recuritment.save\n format.html { redirect_to @society_recuritment, notice: 'Society recuritment was successfully created.' }\n format.json { render :show, status: :created, location: @society_recuritment }\n else\n format.html { render :new }\n format.json { render json: @society_recuritment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @rigging = Rigging.new(rigging_params)\n\n respond_to do |format|\n if @rigging.save\n format.html { redirect_to @rigging, notice: 'Rigging was successfully created.' }\n format.json { render :show, status: :created, location: @rigging }\n else\n format.html { render :new }\n format.json { render json: @rigging.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @surah = Surah.new(surah_params)\n\n respond_to do |format|\n if @surah.save\n format.html { redirect_to @surah, notice: 'Surah was successfully created.' }\n format.json { render action: 'show', status: :created, location: @surah }\n else\n format.html { render action: 'new' }\n format.json { render json: @surah.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\r\n\t\t\t\tsurvivor = Survivor.new(survivor_create_params)\r\n\t\t\t\tsurvivor.abducted = false\r\n\t\t\t\tsurvivor.abduction_reports = 0\r\n\t\t\t\tif survivor.save\r\n\t\t\t\t\trender json: {status: 'SUCCESS', message:'Survivor Registrado', data:survivor},status: :ok\r\n\t\t\t\telse\r\n\t\t\t\t\trender json: {status: 'ERROR', message:'Survivor não registrado com sucesso', data:survivor.erros},status: :unprocessable_entity\r\n\t\t\t\tend\r\n\t\t\tend", "def create\n @stilage = Stilage.new(stilage_params)\n respond_to do |format|\n if @stilage.save\n format.html { redirect_to @stilage, notice: 'Stilage was successfully created.' }\n format.json { render :show, status: :created, location: @stilage }\n else\n format.html { render :new }\n format.json { render json: @stilage.errors, status: :unprocessable_entity }\n end\n end\n end", "def create(params = {})\n wrapped_params = { insurance: params }\n @client.make_request(:post, 'insurances', MODEL_CLASS, wrapped_params)\n end", "def create\n @sighting = Sighting.new(sighting_params)\n\n if @sighting.save\n render json: @sighting, status: :created, location: @sighting\n else\n render json: @sighting.errors, status: :unprocessable_entity\n end\n end", "def create\n @garrage = Garrage.new(garrage_params)\n @garrage.user_id = current_user.id\n\n respond_to do |format|\n if @garrage.save\n format.html { redirect_to garrage_stuffs_path(@garrage), notice: 'Garrage was successfully created.' }\n format.json { render :show, status: :created, location: @garrage }\n else\n format.html { render :new }\n format.json { render json: @garrage.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @county = County.new(params[:county])\n\n respond_to do |format|\n if @county.save\n format.html { redirect_to @county, notice: 'County was successfully created.' }\n format.json { render json: @county, status: :created, location: @county }\n else\n format.html { render action: \"new\" }\n format.json { render json: @county.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fellowship = Fellowship.new(fellowship_params)\n @fellowship.users << current_user\n\n # Capitalize fellowship name\n @fellowship.fellowship_name = @fellowship.fellowship_name.titleize\n\n respond_to do |format|\n if @fellowship.save\n format.html { redirect_to @fellowship, notice: 'Fellowship was successfully created.' }\n format.json { render :show, status: :created, location: @fellowship }\n else\n format.html { render :new }\n format.json { render json: @fellowship.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @surgery = Surgery.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @surgery }\n end\n end", "def create\n @injurylocation = Injurylocation.new(injurylocation_params)\n\n respond_to do |format|\n if @injurylocation.save\n format.html { redirect_to injurylocations_path, notice: 'Injurylocation was successfully created.' }\n format.json { render :show, status: :created, location: @injurylocation }\n else\n format.html { render :new }\n format.json { render json: @injurylocation.errors, status: :unprocessable_entity }\n end\n end\n end", "def search_surgery\n\t\t# Searching for surgery as per user entered term\n\t\tif Surgery.where(user_type: \"admin\").any_of({ :name => /^#{params[:term]}/i }).present?\n\t\t\t# if search show from the admin then the search term from surgery of admin\n\t\t\tsurgeries = Surgery.where(user_type: \"admin\").any_of({ :name => /^#{params[:term]}/i }).all.collect{|surgery| {label: surgery.name}}.uniq.to_json\n\t\telse\n\t\t\t# else the term is not equal to the admin surgery then that search from the user term\n\t\t\tsurgeries = current_user.surgeries.any_of({ :name => /^#{params[:term]}/i }).all.collect{|surgery| {label: surgery.name}}.uniq.to_json \n\t\tend\n\t\t# render to the surgery name page\n\t\trespond_to do |format|\n\t\t format.json { render :json => surgeries }\n\t\tend\n\tend", "def create\n @garrison = Garrison.new(garrison_params)\n @garrison.kingdom_id = current_user.current_kingdom.id\n @garrison.recruted = true\n\n respond_to do |format|\n if @garrison.save\n format.html { redirect_to @garrison, notice: 'Garrison was successfully created.' }\n format.json { render action: 'show', status: :created, location: @garrison }\n else\n format.html { render action: 'new' }\n format.json { render json: @garrison.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @badge = Badge.new(params[:badge])\n\n respond_to do |format|\n if @badge.save\n format.html { redirect_to @badge, :notice => 'Badge was successfully created.' }\n format.json { render :json => @badge, :status => :created, :location => @badge }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @badge.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @insurance_facility = InsuranceFacility.new(insurance_facility_params)\n\n respond_to do |format|\n if @insurance_facility.save\n format.html { redirect_to @insurance_facility, notice: 'Insurance facility was successfully created.' }\n format.json { render :show, status: :created, location: @insurance_facility }\n else\n format.html { render :new }\n format.json { render json: @insurance_facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sponsorship_level = SponsorshipLevel.new(sponsorship_level_params)\n\n respond_to do |format|\n if @sponsorship_level.save\n format.html { redirect_to @sponsorship_level, notice: 'Sponsorship level was successfully created.' }\n format.json { render :show, status: :created, location: @sponsorship_level }\n else\n format.html { render :new }\n format.json { render json: @sponsorship_level.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @badge = Badge.new(params[:badge])\n \n\n respond_to do |format|\n if @badge.save\n format.html { redirect_to @badge, notice: 'Badge was successfully created.' }\n format.json { render json: @badge, status: :created, location: @badge }\n else\n format.html { render action: \"new\" }\n format.json { render json: @badge.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @investigationinjurylocation = Investigationinjurylocation.new(investigationinjurylocation_params)\n\n respond_to do |format|\n if @investigationinjurylocation.save\n format.html { redirect_to @investigationinjurylocation.investigation, notice: 'Investigationinjurylocation was successfully created.' }\n format.json { render :show, status: :created, location: @investigationinjurylocation }\n else\n format.html { render :new }\n format.json { render json: @investigationinjurylocation.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sigurance = Sigurance.new(sigurance_params)\n @sigurance.save!\n\n SiguranceMailer.new_sigurance(@sigurance).deliver_now\n\n respond_to do |format|\n if @sigurance.save\n format.html { redirect_to @sigurance, notice: 'Sigurance was successfully created.' }\n format.json { render :show, status: :created, location: @sigurance }\n else\n format.html { render :new }\n format.json { render json: @sigurance.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n passenger = Passenger.new(:name => params[:name], :contact_number => params[:contact_number], :nationality => params[:nationality], :meal_pref => params[:meal_pref])\n passenger.save\n render :json => passenger\n end", "def new\n tournament = Tournament.find(params[:tournament_id])\n @registration = Registration.new(tournament:tournament)\n tournament.draws.order('draws.is_single DESC, draws.title').each do |draw|\n @registration.draw_registrations.build(draw_id: draw.id)\n end\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @registration }\n end\n end", "def create\n @undergraduate = Undergraduate.new(undergraduate_params)\n\n respond_to do |format|\n if @undergraduate.save\n format.html { redirect_to @undergraduate, notice: 'Undergraduate was successfully created.' }\n format.json { render :show, status: :created, location: @undergraduate }\n else\n format.html { render :new }\n format.json { render json: @undergraduate.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @souvenir = Souvenir.new(souvenir_params)\n\n respond_to do |format|\n if @souvenir.save\n format.html { redirect_to @souvenir, notice: 'Souvenir was successfully created.' }\n format.json { render :show, status: :created, location: @souvenir }\n else\n format.html { render :new }\n format.json { render json: @souvenir.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @surfari = Surfari.new(surfari_params)\n\n respond_to do |format|\n if @surfari.save\n format.html { redirect_to surfaris_path, notice: 'Surfari was successfully created.' }\n format.json { render :show, status: :created, location: @surfari }\n else\n format.html { render :new }\n format.json { render json: @surfari.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sponsorship = Sponsorship.new(sponsorship_params)\n\n respond_to do |format|\n if @sponsorship.save\n format.html { redirect_to \"/sponsorships/new\", notice: 'Thanks for contacting. We will get back to you as soon as possible.' }\n format.json { render :new, status: :created, location: @sponsorship }\n else\n format.html { render :new }\n format.json { render json: @sponsorship.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @nurse = Nurse.new(params[:nurse])\n\n respond_to do |format|\n if @nurse.save\n format.html { redirect_to @nurse, notice: 'Nurse was successfully created.' }\n format.json { render json: @nurse, status: :created, location: @nurse }\n else\n format.html { render action: \"new\" }\n format.json { render json: @nurse.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @injurytype = Injurytype.new(injurytype_params)\n\n respond_to do |format|\n if @injurytype.save\n format.html { redirect_to injurytypes_path, notice: 'Injurytype was successfully created.' }\n format.json { render :show, status: :created, location: @injurytype }\n else\n format.html { render :new }\n format.json { render json: @injurytype.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @rogue = Rogue.new(rogue_params)\n\n respond_to do |format|\n if @rogue.save\n format.html { redirect_to @rogue, notice: \"Rogue was successfully created.\" }\n format.json { render :show, status: :created, location: @rogue }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @rogue.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @surprise = Surprise.new(surprise_params)\n\n respond_to do |format|\n if @surprise.save\n format.html { redirect_to @surprise, notice: 'Surprise was successfully created.' }\n format.json { render :show, status: :created, location: @surprise }\n else\n format.html { render :new }\n format.json { render json: @surprise.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @surgery = Surgery.find(params[:id])\n @surgery.destroy\n\n respond_to do |format|\n format.html { redirect_to surgeries_url }\n format.json { head :no_content }\n end\n end", "def create\n @rogue = Rogue.new(rogue_params)\n\n respond_to do |format|\n if @rogue.save\n format.html { redirect_to @rogue, notice: 'Rogue was successfully created.' }\n format.json { render :show, status: :created, location: @rogue }\n else\n format.html { render :new }\n format.json { render json: @rogue.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @enqury = Enqury.new(enqury_params)\n\n respond_to do |format|\n if @enqury.save\n format.html { redirect_to @enqury, notice: 'Enqury was successfully created.' }\n format.json { render :show, status: :created, location: @enqury }\n else\n format.html { render :new }\n format.json { render json: @enqury.errors, status: :unprocessable_entity }\n end\n end\n end", "def surveys\n person_id = params[:person_id]\n \n surveys = SurveyService.findSurveysForPerson person_id\n \n render json: surveys.to_json, :content_type => 'application/json'\n end", "def new\n @year_insurances = YearInsurance.active.joins(:family)\n @reimbursement = Reimbursement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @reimbursement }\n end\n end", "def create\n #create venues trought users controller\n end", "def create\n # get the foursquare venue id\n fsvid = params[:itinerary][:venue_id]\n\n foursquare_connect\n \n # get the venue's information from foursquare\n response = @client.venues.find(fsvid)\n \n # prep the data for being sent to google\n street_address = response.location.address.gsub(' ', '+')\n city = response.location.city.gsub(' ', '+')\n state = response.location.state.gsub(' ', '+')\n \n # get a response from google\n unformatted_response = Net::HTTP.get_response(\"maps.googleapis.com\", \"/maps/api/geocode/json?address=#{street_address},+#{city},+#{state}&sensor=false\")\n # convert the response to JSON\n info = ActiveSupport::JSON.decode(unformatted_response.body)\n \n if info['status'] == \"OK\" # pull data only if the data is there to be pulled\n latitude = info.results[0].geometry.location.lat\n longitude = info.results[0].geometry.location.lng\n end\n \n # try to find if this venue exists\n venue = Venue.where(:fsvid => fsvid)\n unless venue.exists? # skip if venue already exists\n # create a new venue with many null values\n newvenue = Venue.create(:fsvid => fsvid, :latitude => latitude, :longitude => longitude)\n if newvenue.save # successfully saved\n venue = Venue.where(:fsvid => fsvid)\n else # there was an error\n respond_to do |format|\n format.html { render :action => \"new\" }\n end\n end\n end\n \n # set the itinerarie's venue_id to either the venue that was found with the appropriate\n # foursquare venue_id or the newly created one -- overwrite the fsvid value\n \n params[:itinerary][:venue_id] = venue[0].id \n params[:itinerary][:start_date] = DateTime.strptime(params[:itinerary][:start_date], \"%Y-%m-%d %H:%M:%S\")\n \n # finally create the itinerary\n @itinerary = current_user.itineraries.create(params[:itinerary])\n\n respond_to do |format|\n if @itinerary.save\n @itinerary.plans[0].update_attribute(:parent_id, current_user.id)\n format.html { redirect_to(new_itinerary_invite_path(@itinerary), :notice => 'Itinerary was successfully created.') }\n format.xml { render :xml => new_itinerary_invite_path(@itinerary), :status => :created, :location => @itinerary }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @itinerary.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @village = Village.new(params[:village])\n\n respond_to do |format|\n if @village.save\n format.html { redirect_to @village, notice: 'Village was successfully created.' }\n format.json { render json: @village, status: :created, location: @village }\n else\n format.html { render action: \"new\" }\n format.json { render json: @village.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stage_population = StagePopulation.new(params[:stage_population])\n\n respond_to do |format|\n if @stage_population.save\n format.html { redirect_to @stage_population, notice: 'Stage population was successfully created.' }\n format.json { render json: @stage_population, status: :created, location: @stage_population }\n else\n format.html { render action: \"new\" }\n format.json { render json: @stage_population.errors, status: :unprocessable_entity }\n end\n end\n end", "def survivor_params\n params.require(:survivor).permit(:name, :age, :sex, :captured)\n end", "def data_to_api(snack_name, snack_location, snack_optional)\n RestClient.post ENV['NERDERY_API'], { name: snack_name,\n location: snack_location,\n optional: snack_optional\n }.to_json, content_type: :json\n end", "def bridges_create(params = {})\n post \"bridges\", params\n end", "def create\n @grooming = Grooming.new(grooming_params)\n\n respond_to do |format|\n if @grooming.save\n format.html { redirect_to @grooming, notice: 'Visit was successfully created.' }\n format.json { render :show, status: :created, location: @grooming }\n else\n format.html { render :new }\n format.json { render json: @grooming.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @agency = Agency.new(agency_params)\n\n if @agency.save\n render json: @agency, status: :created, location: @agency\n else\n render json: @agency.errors, status: :unprocessable_entity\n end\n end", "def create\n @surgery_type_instrument_type = SurgeryTypeInstrumentType.new(surgery_type_instrument_type_params)\n\n respond_to do |format|\n if @surgery_type_instrument_type.save\n format.html { redirect_to @surgery_type_instrument_type, notice: 'Surgery type instrument type was successfully created.' }\n format.json { render :show, status: :created, location: @surgery_type_instrument_type }\n else\n format.html { render :new }\n format.json { render json: @surgery_type_instrument_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gig_roster = GigRoster.new(gig_roster_params)\n\n respond_to do |format|\n if @gig_roster.save\n format.html { redirect_to @gig_roster, notice: 'Gig roster was successfully created.' }\n format.json { render :show, status: :created, location: @gig_roster }\n else\n format.html { render :new }\n format.json { render json: @gig_roster.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @g_anewby = GAnewbie.new(g_anewby_params)\n\n respond_to do |format|\n if @g_anewby.save\n format.html { redirect_to @g_anewby, notice: 'G anewbie was successfully created.' }\n format.json { render action: 'show', status: :created, location: @g_anewby }\n else\n format.html { render action: 'new' }\n format.json { render json: @g_anewby.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @uasg = Uasg.new(uasg_params)\n\n respond_to do |format|\n if @uasg.save\n format.html { redirect_to @uasg, notice: 'Uasg was successfully created.' }\n format.json { render :show, status: :created, location: @uasg }\n else\n format.html { render :new }\n format.json { render json: @uasg.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @interest = Interest.new(params[:interest])\n \n respond_to do |format|\n if @interest.save\n format.json { render :json => @interest,\n :status => :created, :location => @interest }\n else\n format.json { render :json => @interest.errors,\n :status => :unprocessable_entity }\n end\n end\n end", "def create\n @ugroupe = Ugroupe.new(params[:ugroupe])\n respond_to do |format|\n if @ugroupe.save\n format.html { redirect_to ugroupes_path }\n format.json { render json: @ugroupe, status: :created, location: @ugroupe }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ugroupe.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @graduation = Graduation.new(graduation_params)\n\n respond_to do |format|\n if @graduation.save\n format.html { redirect_to @graduation, notice: 'Graduation was successfully created.' }\n format.json { render :show, status: :created, location: @graduations }\n else\n format.html { render :new }\n format.json { render json: @graduation.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @rebateable = find_rebateable\n @rebate = @rebateable.rebates.build(params[:rebate])\n @sector_names = params[:sector_names] || []\n @industry_names = params[:industry_names] || []\n @rebate.tag_names = @sector_names.join(',') + \",\" + @industry_names.join(',')\n\n respond_to do |format|\n if @rebate.save\n format.html { redirect_to :id => nil }\n format.json { render json: @rebate, status: :created, location: @rebate }\n else\n format.html { render action: \"new\" }\n format.json { render json: @rebate.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @surrender = @insurance.surrenders.new(surrender_params)\n\n respond_to do |format|\n if @surrender.save\n format.html { redirect_to [@surrender.insurance, @surrender], notice: 'Surrender was successfully created.' }\n format.json { render :show, status: :created, location: [@surrender.insurance, @surrender] }\n else\n format.html { render :new }\n format.json { render json: @surrender.errors, status: :unprocessable_entity }\n end\n end\n end", "def survivor_params\n params.require(:survivor).permit(:name, :age, :gender, :latitude, :longitude, :infected, :water_amount, :ammunition_amount, :medication_amount, :food_amount)\n end", "def create\n @groep = Groep.new(params[:groep])\n @lesgevers = Lesgever.order('name').all\n @dags = Dag.all\n @niveaus = Niveau.order('position').all\n respond_to do |format|\n if @groep.save\n format.html { redirect_to @groep, notice: 'Groep werd succesvol aangemaakt.' }\n format.json { render json: @groep, status: :created, location: @groep }\n else\n format.html { render action: \"new\" }\n format.json { render json: @groep.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gin = Gin.new(gin_params)\n if params[:gin][:distillery_id].blank? && params[:distillery_name].present?\n @distillery = Distillery.find_or_create_by(name: params[:distillery_name])\n params[:gin][:distillery_id] = @distillery.id\n end\n\n respond_to do |format|\n if @gin.save\n format.html { redirect_to @gin, notice: 'Gin was successfully created.' }\n format.json { render :show, status: :created, location: @gin }\n else\n format.html { render :new }\n format.json { render json: @gin.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gastracker = Gastracker.new(params[:gastracker])\n\n respond_to do |format|\n if @gastracker.save\n format.html { redirect_to @gastracker, notice: 'Gastracker was successfully created.' }\n format.json { render json: @gastracker, status: :created, location: @gastracker }\n else\n format.html { render action: \"new\" }\n format.json { render json: @gastracker.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sponsor = Sponsor.new(sponsor_params)\n\n respond_to do |format|\n if @sponsor.save\n format.html { redirect_to sponsors_url, notice: 'El auspiciante se creó correctamente.' }\n format.json { render :show, status: :created, location: sponsors_url }\n else\n format.html { render :new }\n format.json { render json: @sponsor.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @warrior = Warrior.new\n @warrior.build_address\n @regions=Region.all\n @warrior_region=nil\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @warrior }\n end\n end", "def survivor_params\n params.require(:survivor).permit(:name, :age, :gender, :lonlat, :infected?)\n end", "def create\n @siritori = Siritori.new(siritori_params)\n\n respond_to do |format|\n if @siritori.save\n format.html { redirect_to @siritori, notice: 'Siritori was successfully created.' }\n format.json { render :show, status: :created, location: @siritori }\n else\n format.html { render :new }\n format.json { render json: @siritori.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @seniority = Seniority.new(seniority_params)\n\n respond_to do |format|\n if @seniority.save\n format.html { redirect_to @seniority, notice: \"Seniority was successfully created.\" }\n format.json { render :show, status: :created, location: @seniority }\n else\n format.html { render :new }\n format.json { render json: @seniority.errors, status: :unprocessable_entity }\n end\n end\n end", "def surgery_search\n # Search for the speciality names\n @surgeries = find_surgery_term(params[:surgeryterm])\n # respond to rendering the pages\n respond_to do |format|\n format.js\n end\n end", "def create\n @zombie_sighting = ZombieSighting.new(lat: params[:lat],\n lng: params[:lng])\n\n respond_to do |format|\n if @zombie_sighting.save\n format.html { redirect_to action: \"index\", notice: 'Zombie sighting was successfully created.' }\n format.json { render json: @zombie_sighting, status: :created, location: @zombie_sighting }\n else\n format.html { render action: \"new\" }\n format.json { render json: @zombie_sighting.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @buyer = Buyer.new(params[:buyer])\n @locals = User.where(:city => @buyer.city)\n @users = @locals.random(5)\n respond_to do |format|\n if @buyer.save\n @users.each do |user|\n BuyerMailer.registration_welcome(@buyer, user).deliver\n Buyer.increment_counter(\"times_forwarded\", @buyer.id)\n end\n format.html { redirect_to :submitted_page, :notice => 'Seller was successfully created.' }\n format.json { render :json => @buyer, :status => :created, :location => @buyer }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @buyer.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @village = Village.new(village_params)\n\n respond_to do |format|\n if @village.save\n format.html { redirect_to @village, notice: 'Village was successfully created.' }\n format.json { render :show, status: :created, location: @village }\n else\n format.html { render :new }\n format.json { render json: @village.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @grade = Grade.new(grade_params)\n\n if @grade.save\n render json: @grade, status: :created, location: @grade\n else\n render json: @grade.errors, status: :unprocessable_entity\n end\n end", "def create\n @unemployment_insurance = UnemploymentInsurance.new(unemployment_insurance_params)\n\n respond_to do |format|\n if @unemployment_insurance.save\n format.html { redirect_to @unemployment_insurance, notice: 'Unemployment insurance was successfully created.' }\n format.json { render :show, status: :created, location: @unemployment_insurance }\n else\n format.html { render :new }\n format.json { render json: @unemployment_insurance.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @guardianship = Guardianship.new(params[:guardianship])\n\n respond_to do |format|\n if @guardianship.save\n format.html { redirect_to @guardianship, notice: 'Guardianship was successfully created.' }\n format.json { render json: @guardianship, status: :created, location: @guardianship }\n else\n format.html { render action: \"new\" }\n format.json { render json: @guardianship.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @population = Population.new(population_params)\n\n respond_to do |format|\n if @population.save\n format.html { redirect_to @population, notice: 'Population was successfully created.' }\n format.json { render :show, status: :created, location: @population }\n else\n format.html { render :new }\n format.json { render json: @population.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @persons_release = PersonsRelease.new(params[:persons_release])\n\n respond_to do |format|\n if @persons_release.save\n format.html { redirect_to @persons_release, notice: 'Persons release was successfully created.' }\n format.json { render json: @persons_release, status: :created, location: @persons_release }\n else\n format.html { render action: \"new\" }\n format.json { render json: @persons_release.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @renter = Renter.new(params[:renter])\n @locals = User.where(:city => @buyer.city)\n @users = @locals.random(5)\n respond_to do |format|\n if @renter.save\n @users.each do |user|\n RenterMailer.registration_welcome(@renter, user).deliver\n Renter.increment_counter(\"times_forwarded\", @renter.id)\n end\n format.html { redirect_to :submitted_page, :notice => 'Seller was successfully created.' }\n format.json { render :json => @renter, :status => :created, :location => @renter }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @renter.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @fragrance = Fragrance.find(params[:fragrance_id])\n @rating = Rating.new(rating_params)\n @rating.user = @current_user\n @rating.fragrance = @fragrance\n\n if @rating.save\n render json: @rating, status: :created\n else\n render json: @rating.errors, status: :unprocessable_entity\n end\n end", "def create\n @surg = Surg.new(params[:surg])\n\n respond_to do |format|\n if @surg.save\n format.js\n format.xml { render :xml => @surg, :status => :created, :location => @surg }\n else\n\t puts \"ERRORS ! ! ! ! ! ! : \"\n\t puts @surg.errors.count\n\t\tputs @surg.errors.full_messages\n format.js { render :controller => \"application\", :action => \"errdisplay\" }\n format.xml { render :xml => @surg.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @life_insurance = LifeInsurance.new(params[:life_insurance])\n\n respond_to do |format|\n if @life_insurance.save\n format.html { redirect_to @life_insurance, notice: 'Life insurance was successfully created.' }\n format.json { render json: @life_insurance, status: :created, location: @life_insurance }\n else\n format.html { render action: \"new\" }\n format.json { render json: @life_insurance.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @paper_venue = PaperVenue.new(params[:paper_venue])\n\n respond_to do |format|\n if @paper_venue.save\n format.html { redirect_to @paper_venue, :notice => 'Paper venue was successfully created.' }\n format.json { render :json => @paper_venue, :status => :created, :location => @paper_venue }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @paper_venue.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @nursery_table = NurseryTable.new(nursery_table_params)\n\n respond_to do |format|\n if @nursery_table.save\n format.html { redirect_to @nursery_table, notice: \"Nursery table was successfully created.\" }\n format.json { render :show, status: :created, location: @nursery_table }\n else\n format.html { render :new }\n format.json { render json: @nursery_table.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @reimbursement = Reimbursement.new(params[:reimbursement])\n\n respond_to do |format|\n if @reimbursement.save\n format.html { redirect_to @reimbursement, notice: 'Reimbursement was successfully created.' }\n format.json { render json: @reimbursement, status: :created, location: @reimbursement }\n else\n format.html { render action: \"new\" }\n format.json { render json: @reimbursement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @glucose = Glucose.new(glucose_params)\n @glucose.user = current_user unless @glucose.user_id\n\n if @glucose.save\n render json: @glucose, status: :created\n else\n render json: @glucose.errors, status: :unprocessable_entity\n end\n end", "def create\n @sluzby = Sluzby.new(params[:sluzby])\n\n respond_to do |format|\n if @sluzby.save\n format.html { redirect_to @sluzby, notice: 'Sluzby was successfully created.' }\n format.json { render json: @sluzby, status: :created, location: @sluzby }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sluzby.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n get_school\n @school_vocational = @school.vocationals.create(params[:school_vocational])\n end" ]
[ "0.61305094", "0.61305094", "0.6031113", "0.5936804", "0.58223677", "0.5785059", "0.5736796", "0.5622155", "0.54896826", "0.54663295", "0.54391634", "0.5414384", "0.5395321", "0.53423953", "0.53045684", "0.52957374", "0.52830577", "0.5280918", "0.5242118", "0.5230695", "0.5220089", "0.5218212", "0.52181816", "0.5211284", "0.5203564", "0.51998603", "0.5198511", "0.51945204", "0.5190299", "0.5189639", "0.5184191", "0.5179511", "0.5177168", "0.5176343", "0.5175074", "0.51726097", "0.5170561", "0.5163136", "0.51581347", "0.51538956", "0.5118299", "0.51138115", "0.51132506", "0.5108088", "0.5104668", "0.5104051", "0.51035565", "0.5100078", "0.5091887", "0.50904584", "0.50897735", "0.50799376", "0.5073897", "0.5060207", "0.50547683", "0.5049572", "0.5049174", "0.5044941", "0.50366163", "0.5036271", "0.50328296", "0.5032827", "0.50274616", "0.50221074", "0.50112206", "0.50072384", "0.50031126", "0.50006515", "0.49968028", "0.4993102", "0.49893957", "0.49884632", "0.49843392", "0.49840707", "0.4983523", "0.4983159", "0.49795625", "0.49794036", "0.49788326", "0.49737507", "0.49668452", "0.49658254", "0.4957768", "0.4955145", "0.4954098", "0.4950654", "0.49494708", "0.4948554", "0.49445456", "0.49440894", "0.49422738", "0.4936282", "0.49307388", "0.4929814", "0.49290457", "0.4926254", "0.4920162", "0.49194375", "0.49192545", "0.49170732" ]
0.60885787
2
PATCH/PUT /surgeries/1 PATCH/PUT /surgeries/1.json
def update # Updating the particular surgery and after update redirecto toe surgries page if @surgery.update(surgery_params) redirect_to surgeries_path else # else redirect to the same page surgery redirect_to :back end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n if @person.seat\n render json: {errors: 'Cannot update a seated person'}, status: 422\n else\n @person.update person_params\n render json: @person\n end\n end", "def update\n @surgery = Surgery.find(params[:id])\n\n respond_to do |format|\n if @surgery.update_attributes(params[:surgery])\n format.html { redirect_to @surgery, notice: 'Surgery was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @surgery.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fridge = Fridge.find(params[:id])\n\n respond_to do |format|\n if @fridge.update_attributes(params[:fridge])\n format.html { redirect_to @fridge, notice: 'Fridge was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fridge.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @surgical.update(surgical_params)\n format.html { redirect_to surgicals_url, notice: 'Surgical was successfully updated.' }\n # format.json { render :show, status: :ok, location: @surgical }\n else\n format.html { render :edit }\n format.json { render json: @surgical.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @agency = Agency.find(params[:id])\n\n if @agency.update(agency_params)\n #head :no_content\n render json: @agency, status: :accepted, location: @agency #sera? status accepted? \n else\n render json: @agency.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @allergy.update(allergy_params)\n format.html { redirect_to @allergy, notice: t('allergies.update_success') }\n format.json { render :show, status: :ok, location: @allergy }\n else\n format.html { render :edit }\n format.json { render json: @allergy.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @surgery.update(surgery_params)\n format.html { redirect_to @surgery, notice: 'Surgery was successfully updated.' }\n format.json { render :show, status: :ok, location: @surgery }\n else\n format.html { render :edit }\n format.json { render json: @surgery.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n render json: Company.update(params[\"id\"], params[\"company\"])\n end", "def update\n @recipe.allergies.destroy_all\n params[:recipe][:allergy].each do |key,value|\n if value[\"name\"] == \"1\"\n allergy = Allergy.find(key)\n @recipe.allergies << allergy\n end\n end\n\n if params[:recipe][:concentrate] == '1' || params[:recipe][:recipe_category_id] == RecipeCategory.find_by(name: \"Concentrates\").id\n @recipe.concentrate = true\n else\n @recipe.concentrate = false\n end\n\n respond_to do |format|\n if @recipe.update(recipe_params)\n @allergies = Allergy.all\n format.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }\n format.json { render :show, status: :ok, location: @recipe }\n else\n @allergies = Allergy.all\n format.html { render :edit }\n format.json { render json: @recipe.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @agency = Agency.find(params[:id])\n\n if @agency.update(agency_params)\n #head :no_content\n render json: @agency, status: :accepted, location: @agency #sera? status accepted? \n else\n render json: @agency.errors, status: :unprocessable_entity\n end\n end", "def update\n if request.content_type == \"application/json\"\n # .update is like a \"update people set ...\" in sql\n if @person.update(person_params)\n render json: @person\n else\n render json: @person.errors, status: :not_found\n end\n else\n render status: :bad_request\n end\n end", "def update\n @allergy = Allergy.find(params[:id])\n\n respond_to do |format|\n if @allergy.update_attributes(params[:allergy])\n format.html { redirect_to(@allergy, :notice => 'Allergy was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @allergy.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def update\n @animal.update(animal_params)\n respond_with(@shelter)\n end", "def update\n #Finding the specific chore where the id matches the one we pass in with the body\n @v1_chore = Chore.where(id: params[:id]).first\n #Here we're checking if we have user_id in our body, and if we do, we'll change the selected chore's properties\n #with the parameters of the body, we go through the specific group to our specific chore with the path\n if v1_chore_params[:user_id]\n @v1_chore.user_id = params[:user_id]\n @v1_chore.assigned = true\n if @v1_chore.save\n render :show, status: :ok\n end\n else\n render json: @v1_chore.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @surgery_supply.update(surgery_supply_params)\n format.html { redirect_to @surgery_supply, notice: 'Surgery supply was successfully updated.' }\n format.json { render :show, status: :ok, location: @surgery_supply }\n else\n format.html { render :edit }\n format.json { render json: @surgery_supply.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @agency.update_attributes(params[:agency])\n format.html { redirect_to @agency, notice: 'Agency was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @agency.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_initiative.update(api_v1_initiative_params)\n format.html { redirect_to @api_v1_initiative, notice: 'Initiative was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_initiative }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_initiative.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @golfer = Golfer.find(params[:id])\n\n respond_to do |format|\n if @golfer.update_attributes(params[:golfer])\n format.html { redirect_to @golfer, notice: 'Golfer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @golfer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @agency.update(agency_params)\n format.html { redirect_to @agency, notice: 'Agency was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @agency.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @supermarket = Supermarket.find(params[:id]) \n respond_to do |format|\n if @supermarket.update(supermarket_params)\n format.json { render json: @supermarket, status: :ok }\n end\n end\n end", "def update\n @person = Person.find(params[:id]) \n respond_to do |format|\n if @person.update(person_params)\n format.json { render json: @person, status: :ok }\n else\n format.json { render json: @person.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @initiative = Initiative.find(params[:id])\n \n respond_to do |format|\n if @initiative.update_attributes(params[:initiative])\n \n format.html { redirect_to @initiative, notice: 'Initiative was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @initiative.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n # { clinic: {id: references, \"license_id\"=>nil, \"name\"=>string } }\n \n if @clinic.update_attributes(params[:clinic].except(:api_license_id))\n head :no_content\n else\n render json: clinic.errors.full_messages, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @surprise.update(surprise_params)\n format.html { redirect_to @surprise, notice: 'Surprise was successfully updated.' }\n format.json { render :show, status: :ok, location: @surprise }\n else\n format.html { render :edit }\n format.json { render json: @surprise.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @souvenior.update(souvenior_params)\n format.html { redirect_to @souvenior, notice: 'Souvenior was successfully updated.' }\n format.json { render :show, status: :ok, location: @souvenior }\n else\n format.html { render :edit }\n format.json { render json: @souvenior.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @dog_poly.update(dog_poly_params)\n format.html { redirect_to @dog_poly, notice: 'Dog poly was successfully updated.' }\n format.json { render :show, status: :ok, location: @dog_poly }\n else\n format.html { render :edit }\n format.json { render json: @dog_poly.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @survivor = Survivor.find(params[:id])\n @profile = @survivor.profile\n \n @survivor.location = Location.find(params[:survivor][:location_id]); params[:survivor].delete(:location_id)\n \n respond_to do |format|\n if @survivor.update_attributes(params[:survivor]) and @profile.update_attributes(params[:profile])\n flash[:notice] = 'Survivor was successfully updated.'\n format.fbml { redirect_to(@survivor) }\n format.xml { head :ok }\n else\n format.fbml { render :action => \"edit\" }\n format.xml { render :xml => @survivor.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end", "def update\n @badge = Badge.find(params[:id])\n\n respond_to do |format|\n if @badge.update_attributes(params[:badge])\n format.html { redirect_to @badge, notice: 'Badge was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @badge.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fellowship.update(fellowship_params)\n format.html { redirect_to @fellowship, notice: 'Fellowship was successfully updated.' }\n format.json { render :show, status: :ok, location: @fellowship }\n else\n format.html { render :edit }\n format.json { render json: @fellowship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @society.update(society_params)\n format.html { redirect_to @society }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @society.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_initiative_update.update(api_v1_initiative_update_params)\n format.html { redirect_to @api_v1_initiative_update, notice: 'Initiative update was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_initiative_update }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_initiative_update.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @agency.update(agency_params)\n format.html { redirect_to @agency, notice: \"Agency was successfully updated.\" }\n format.json { render :show, status: :ok, location: @agency }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @agency.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @registering_agency.update(registering_agency_params)\n format.html { redirect_to @registering_agency, notice: 'Registering agency was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @registering_agency.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @subscriber = Subscriber.where(openid: volunteer_params[:openid]).first\n @volunteer = @subscriber.volunteer\n @volunteer.name = volunteer_params[:name]\n @volunteer.tel = volunteer_params[:tel]\n @volunteer.commun = volunteer_params[:commun]\n @volunteer.neighborhood = volunteer_params[:neighborhood]\n respond_to do |format|\n if @volunteer.save\n # format.html { redirect_to @volunteer, notice: 'Volunteer was successfully updated.' }\n format.html { render \"volunteers/success\" }\n format.json { render :show, status: :ok, location: @volunteer }\n else\n format.html { render :edit }\n format.json { render json: @volunteer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @therapist.specialty_ids = params[:therapist][:specialty_ids]\n respond_to do |format|\n if @therapist.update(therapist_params)\n format.html { redirect_to root_path, notice: \"therapist was successfully updated.\" }\n else\n format.html { render :edit }\n end\n end\n end", "def update\n respond_to do |format|\n if @society.update(society_params)\n format.html { redirect_to @society, notice: 'Society was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @society.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @guy.update(guy_params)\n format.html { redirect_to @guy, notice: 'Guy was successfully updated.' }\n format.json { render :show, status: :ok, location: @guy }\n else\n format.html { render :edit }\n format.json { render json: @guy.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n ingredient.update(ingredient_params)\n render json: ingredient\n end", "def update\n @county = County.find(params[:id])\n\n respond_to do |format|\n if @county.update_attributes(params[:county])\n format.html { redirect_to @county, notice: 'County was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @county.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @rental = Rental.friendly.find(params[:rental_id])\n \n\n respond_to do |format|\n if @feature.update(feature_params)\n format.html { redirect_to rental_path(@rental), notice: 'Feature was successfully updated.' }\n format.json { render :show, status: :ok, location: @feature }\n else\n format.html { render :edit }\n format.json { render json: @feature.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @suscriber.update(suscriber_params)\n format.html { redirect_to @suscriber, notice: 'Suscriber was successfully updated.' }\n format.json { render :show, status: :ok, location: @suscriber }\n else\n format.html { render :edit }\n format.json { render json: @suscriber.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @village = Village.find(params[:id])\n\n respond_to do |format|\n if @village.update_attributes(params[:village])\n format.html { redirect_to @village, notice: 'Village was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @village.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @grocery = Grocery.find(params[:id])\n\n if @grocery.update(grocery_params)\n head :no_content\n else\n render json: @grocery.errors, status: :unprocessable_entity\n end\n end", "def update\n @person.update_attributes(params[:person])\n respond_with(@person)\n end", "def update\n respond_to do |format|\n if @injury.update(injury_params)\n format.html { redirect_to injuries_url, notice: 'Injury was successfully updated.' }\n # format.json { render :show, status: :ok, location: @injury }\n else\n format.html { render :edit }\n format.json { render json: @injury.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fucker = Fucker.find(params[:id])\n\n respond_to do |format|\n if @fucker.update_attributes(params[:fucker])\n format.json { head :no_content }\n else\n format.json { render json: @fucker.errors, status: :internal_server_error }\n end\n end\n end", "def update\n render json: Alien.update(params[\"id\"], params[\"alien\"])\n end", "def update_surgery_name\n\t\t@surgery.update(surgery_params)\n\t\tredirect_to surgery_name_list_profiles_path\n\tend", "def update\n @surg = Surg.find(params[:id])\n\n respond_to do |format|\n if @surg.update_attributes(params[:surg])\n format.js\n format.xml { head :ok }\n else\n format.js { render :controller => \"application\", :action => \"errdisplay\" }\n format.xml { render :xml => @surg.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n logger.info('PUT Update:')\n logger.info(request_body)\n new_pub = hashed_request\n old_pub = Publication.find_by(id: params[:id])\n if old_pub.blank?\n head :not_found\n return\n elsif old_pub.deleted?\n head :gone\n return\n end\n if old_pub.harvested_pub? # only manually entered (i.e. non-harvested) publications may be updated with this method\n render json: {\n error: \"This record SulPubID #{old_pub.id} may not be modified. If you had originally entered details for the record, \" \\\n 'it has been superceded by a central record.'\n },\n status: :forbidden, format: 'json'\n return\n elsif !validate_or_create_authors(new_pub[:authorship])\n render json: { error: 'You have not supplied a valid authorship record.' }, status: :not_acceptable,\n format: 'json'\n return\n end\n logger.info(\"Update manual publication #{old_pub.inspect} with BibJSON:\")\n logger.info(request_body)\n old_pub.update_manual_pub_from_pub_hash(new_pub, request_body)\n old_pub.save!\n old_pub.reload\n logger.debug(\"resulting pub hash: #{old_pub.pub_hash}\")\n render json: old_pub.pub_hash, status: :accepted\n end", "def update(url, data)\n RestClient.put url, data, :content_type => :json\nend", "def update\n respond_to do |format|\n if @garrage.update(garrage_params)\n format.html { redirect_to @garrage, notice: 'Garrage was successfully updated.' }\n format.json { render :show, status: :ok, location: @garrage }\n else\n format.html { render :edit }\n format.json { render json: @garrage.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @sire = Sire.find(params[:id])\n @breeds = Breed.find(:all)\n \n respond_to do |format|\n if @sire.update_attributes(params[:sire])\n format.html { redirect_to(sires_path, :notice => 'Sire was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @sire.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update \n pastry = Pastry.find(params[:id])\n pastry.update(pastry_params)\n render json: pastry\n end", "def update\n @person = Person.find(params[:id])\n @treasury = @person.treasury\n return if needs_treasury_supervisor(@treasury)\n\n respond_to do |format|\n if @person.update_attributes(person_params)\n format.html { redirect_to @treasury }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: { errors: @person.errors }, status: :unprocessable_entity }\n end\n end\n end", "def update\n @interest = Interest.find(params[:id])\n \n respond_to do |format|\n if @interest.update_attributes(params[:interest])\n format.json { head :ok }\n else\n format.json { render :json => @interest.errors,\n :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @doggy.update(doggy_params)\n format.html { redirect_to @doggy, notice: 'Doggy was successfully updated.' }\n format.json { render :show, status: :ok, location: @doggy }\n else\n format.html { render :edit }\n format.json { render json: @doggy.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @rigging.update(rigging_params)\n format.html { redirect_to @rigging, notice: 'Rigging was successfully updated.' }\n format.json { render :show, status: :ok, location: @rigging }\n else\n format.html { render :edit }\n format.json { render json: @rigging.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_by_body\n @person = Person.find(person_update_params[:id])\n\n if @person.update_attributes(person_update_params)\n render json: { status: 'PUT Success' }, status: :ok\n else\n render json: { status: 'Error', message:'Error updating person', person: @person.errors }, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @sour.update(sour_params)\n format.html { redirect_to swits_path, notice: 'sour <3.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @sour.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n render json: Location.update(params[\"id\"], params[\"location\"])\n end", "def update\n @enhancement = Enhancement.find(params[:id])\n\n respond_to do |format|\n if @enhancement.update_attributes(params[:enhancement])\n format.html { redirect_to @enhancement, notice: 'Enhancement was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @enhancement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @hoge = Hoge.find(params[:id])\n\n respond_to do |format|\n if @hoge.update_attributes(params[:hoge])\n format.html { redirect_to @hoge, notice: 'Hoge was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @hoge.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @garply.update(garply_params)\n format.html { redirect_to @garply, notice: 'Garply was successfully updated.' }\n format.json { render :show, status: :ok, location: @garply }\n else\n format.html { render :edit }\n format.json { render json: @garply.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @injury.update(injury_params)\n format.html { redirect_to @injury, notice: 'Injury was successfully updated.' }\n format.json { render :show, status: :ok, location: @injury }\n else\n format.html { render :edit }\n format.json { render json: @injury.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @sprint.update!(sprint_params)\n json_response(@sprint)\n end", "def update\n @gage = Gage.find(params[:id])\n\n respond_to do |format|\n if @gage.update_attributes(params[:gage])\n format.html { redirect_to @gage, notice: 'Gage was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @gage.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_initiative_field.update(api_v1_initiative_field_params)\n format.html { redirect_to @api_v1_initiative_field, notice: 'Initiative field was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_initiative_field }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_initiative_field.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(resource,identifier,json)\n raise 'Not Yet Implemented'\n end", "def update\n respond_to do |format|\n if @surgical_profile.preprocess_and_update(surgical_profile_params)\n format.html { redirect_to patient_surgical_profile_path(@patient, @surgical_profile),\n notice: 'Surgical profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @surgical_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @holy_book = HolyBook.find(params[:id])\n\n respond_to do |format|\n if @holy_book.update_attributes(params[:holy_book])\n format.html { redirect_to @holy_book, notice: 'Holy book was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @holy_book.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @rogue.update(rogue_params)\n format.html { redirect_to @rogue, notice: 'Rogue was successfully updated.' }\n format.json { render :show, status: :ok, location: @rogue }\n else\n format.html { render :edit }\n format.json { render json: @rogue.errors, status: :unprocessable_entity }\n end\n end\n end", "def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end", "def update\n respond_to do |format|\n if @surah.update(surah_params)\n format.html { redirect_to @surah, notice: 'Surah was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @surah.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @sundry_grn = SundryGrn.find(params[:id])\n\n respond_to do |format|\n if @sundry_grn.update_attributes(params[:sundry_grn])\n format.html { redirect_to @sundry_grn, :notice => 'Sundry grn was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @sundry_grn.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @house = House.find(params[:id])\n\n respond_to do |format|\n if @house.update_attributes(params[:house])\n format.html { redirect_to @house, notice: 'Gig was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @house.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @rogue.update(rogue_params)\n format.html { redirect_to @rogue, notice: \"Rogue was successfully updated.\" }\n format.json { render :show, status: :ok, location: @rogue }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @rogue.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n get_school\n @school_vocational = @school.vocationals.find(params[:id])\n @school_vocational.update_attributes(params[:school_vocational])\n end", "def update\n respond_to do |format|\n if @fish_poly.update(fish_poly_params)\n format.html { redirect_to @fish_poly, notice: 'Fish poly was successfully updated.' }\n format.json { render :show, status: :ok, location: @fish_poly }\n else\n format.html { render :edit }\n format.json { render json: @fish_poly.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @village.update(village_params)\n format.html { redirect_to @village, notice: 'Village was successfully updated.' }\n format.json { render :show, status: :ok, location: @village }\n else\n format.html { render :edit }\n format.json { render json: @village.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @client.update(client_params)\n render json: @client\n end", "def update\n\t\t# updating the surgery location attribute\n\t\tif @surgery_location.update(surgery_location_params)\n\t\t# response to the JSON\n\t\t\trender json: { success: true,message: \"Surgery Location Successfully Updated.\", response: SurgeryLocationSerializer.new(@surgery_location).as_json(root: false) },:status=>200\n\t else\n\t render :json=> { success: false, message: \"Surgery Location is not available\" },:status=> 404\n\t end\n\tend", "def update\n respond_to do |format|\n if @hood.update(hood_params)\n format.html { redirect_to @hood, notice: 'Hood was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @hood.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @stationeryrequest = Stationeryrequest.find(params[:id])\n #\n @stationeryrequest.hotelsuppliesrequests.each do |hotelsuppliesrequests|\n \n end\n\n respond_to do |format|\n if @stationeryrequest.update_attributes(params[:stationeryrequest])\n format.html { redirect_to @stationeryrequest, notice: 'Stationeryrequest was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @stationeryrequest.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @bracket_golfer.update(bracket_golfer_params)\n format.html { redirect_to @bracket_golfer, notice: 'Bracket golfer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @bracket_golfer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n respond_to do |format|\n if @insurer.update_attributes(params[:insurer])\n format.html { redirect_to @insurer, notice: 'Insurer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @insurer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n @family.slug=nil\n if @family.update(family_params)\n format.html { redirect_to @family, notice: 'La familia fue actualizada exitosamente.' }\n format.json { render :show, status: :ok, location: @family }\n else\n format.html { render :edit }\n format.json { render json: @family.errors, status: :unprocessable_entity }\n end\n end\n end", "def jsonapi_update!(attributes)\n assign_jsonapi_attributes(attributes)\n save!\n end", "def update\n @rooster = Rooster.find(params[:id])\n\n respond_to do |format|\n if @rooster.update_attributes(params[:rooster])\n format.html { redirect_to @rooster, notice: 'Rooster was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @rooster.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @volunteer.update(volunteer_params)\n format.html { redirect_to @volunteer, notice: 'Volunteer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @volunteer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @garrison.update(garrison_params)\n format.html { redirect_to @garrison, notice: 'Garrison was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @garrison.errors, status: :unprocessable_entity }\n end\n end\n end", "def UpdateView params = {}\n \n APICall(path: 'views.json',method: 'PUT',payload: params.to_json)\n \n end", "def update\n budgets = update_budgets(params[:budgets])\n\n render json: budgets, status: :ok\n end", "def update\n goal = Goal.find params[:id]\n if goal.update(goal_params)\n render json: goal, status: 200\n else\n render json: goal.errors.full_messages, status: 422\n end\n end", "def update\n respond_to do |format|\n if @stilage.update(stilage_params)\n format.html { redirect_to @stilage, notice: 'Stilage was successfully updated.' }\n format.json { render :show, status: :ok, location: @stilage }\n else\n format.html { render :edit }\n format.json { render json: @stilage.errors, status: :unprocessable_entity }\n end\n end\n end", "def update \n sneaker = find_sneaker\n # update! exceptions will be handled by the rescue_from ActiveRecord::RecordInvalid code\n sneaker.update(sneaker_params)\n render json: sneaker\n end", "def update\n feature.update_attributes(feature_params)\n\n respond_with(feature)\n end", "def update\n respond_to do |format|\n if @golf.update(golf_params)\n format.html { redirect_to @golf, notice: 'Golf was successfully updated.' }\n format.json { render :show, status: :ok, location: @golf }\n else\n format.html { render :edit }\n format.json { render json: @golf.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.642432", "0.64216095", "0.6362022", "0.6230579", "0.6190886", "0.61774284", "0.6166517", "0.60608333", "0.60224664", "0.6012223", "0.5957312", "0.5900556", "0.58719105", "0.58699477", "0.5867168", "0.5848815", "0.5847209", "0.58368814", "0.5827533", "0.581599", "0.5770683", "0.5765652", "0.57529294", "0.573641", "0.5727832", "0.5723313", "0.5712572", "0.57125145", "0.5707294", "0.57014996", "0.56984663", "0.569483", "0.5689535", "0.56817335", "0.5673504", "0.56648624", "0.5654735", "0.5653599", "0.5648342", "0.56359196", "0.56281775", "0.5627683", "0.5624813", "0.56214154", "0.56185454", "0.561445", "0.56042963", "0.559908", "0.55979645", "0.5588745", "0.55886906", "0.5583792", "0.55823195", "0.5564775", "0.55624306", "0.55598366", "0.5559447", "0.5554766", "0.55505246", "0.554699", "0.5543496", "0.5542486", "0.55409825", "0.5540063", "0.5534115", "0.55338985", "0.5530679", "0.552933", "0.5526207", "0.55234283", "0.5516327", "0.5514194", "0.5512079", "0.55109036", "0.5508977", "0.55089253", "0.55085444", "0.5506208", "0.55061764", "0.5504985", "0.55013496", "0.5491513", "0.54912955", "0.54879373", "0.5486439", "0.548363", "0.5482605", "0.54818", "0.5480283", "0.547714", "0.54766923", "0.547567", "0.5473448", "0.5470318", "0.54699475", "0.54697555", "0.5462761", "0.54617566", "0.5461656", "0.5461237" ]
0.57580376
22
DELETE /surgeries/1 DELETE /surgeries/1.json
def destroy @surgery.destroy respond_to do |format| format.html { redirect_to surgeries_url, notice: 'Surgery was successfully destroyed.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @surgery = Surgery.find(params[:id])\n @surgery.destroy\n\n respond_to do |format|\n format.html { redirect_to surgeries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @fridge = Fridge.find(params[:id])\n @fridge.destroy\n\n respond_to do |format|\n format.html { redirect_to fridges_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @surgical.destroy\n respond_to do |format|\n format.html { redirect_to surgicals_url, notice: 'Surgical was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @society.destroy\n respond_to do |format|\n format.html { redirect_to societies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @gopy = Gopy.find(params[:id])\n @gopy.destroy\n\n respond_to do |format|\n #format.html { redirect_to gopies_url }\n format.html { redirect_to hienthi_gopies_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @allergy.destroy\n respond_to do |format|\n format.html { redirect_to allergies_url, notice: t('allergies.destroy_success') }\n format.json { head :no_content }\n end\n end", "def destroy\n @bustour.destroy\n respond_to do |format|\n format.html { redirect_to bustours_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @subsidy = Subsidy.find(params[:id])\n @subsidy.destroy\n\n respond_to do |format|\n format.html { redirect_to subsidies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @goody = Goody.find(params[:id])\n @goody.destroy\n\n respond_to do |format|\n format.html { redirect_to goodies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @village = Village.find(params[:id])\n @village.destroy\n\n respond_to do |format|\n format.html { redirect_to villages_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @gauge = Gauge.find(params[:id])\n @gauge.destroy\n\n respond_to do |format|\n format.html { redirect_to gauges_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @county = County.find(params[:id])\n @county.destroy\n\n respond_to do |format|\n format.html { redirect_to counties_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @surah.destroy\n respond_to do |format|\n format.html { redirect_to surahs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @badge = Badge.find(params[:id])\n @badge.destroy\n\n respond_to do |format|\n format.html { redirect_to badges_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @district_chief = DistrictChief.find(params[:id])\n @district_chief.destroy\n\n respond_to do |format|\n format.html { redirect_to district_chiefs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @forest.destroy\n respond_to do |format|\n format.html { redirect_to forests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @house = House.find(params[:id])\n @house.destroy\n\n respond_to do |format|\n format.html { redirect_to gigs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @graveyard.destroy\n respond_to do |format|\n format.html { redirect_to graveyards_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @graveyard.destroy\n respond_to do |format|\n format.html { redirect_to graveyards_url }\n format.json { head :no_content }\n end\n end", "def soccer_delete\n base_delete(params, \"Soccer\")\n end", "def destroy\n @hoge = Hoge.find(params[:id])\n @hoge.destroy\n\n respond_to do |format|\n format.html { redirect_to hoges_url }\n format.json { head :ok }\n end\n end", "def destroy\n @stilage.destroy\n respond_to do |format|\n format.html { redirect_to stilages_url, notice: 'Stilage was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @sundry_grn = SundryGrn.find(params[:id])\n @sundry_grn.destroy\n\n respond_to do |format|\n format.html { redirect_to sundry_grns_url }\n format.json { head :ok }\n end\n end", "def destroy\n @sondage.destroy\n respond_to do |format|\n format.html { redirect_to sondages_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @allergy = Allergy.find(params[:id])\n @allergy.destroy\n\n respond_to do |format|\n format.html { redirect_to(allergies_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @survivor = Survivor.find(params[:id])\n @survivor.destroy\n \n respond_to do |format|\n format.fbml { redirect_to(survivors_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @member_village.destroy\n respond_to do |format|\n format.html { redirect_to member_villages_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @registering_agency.destroy\n respond_to do |format|\n format.html { redirect_to registering_agencies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @society_recuritment.destroy\n respond_to do |format|\n format.html { redirect_to society_recuritments_url, notice: 'Society recuritment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @rigging.destroy\n respond_to do |format|\n format.html { redirect_to riggings_url, notice: 'Rigging was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def incident_delete(statuspage_id, incident_id)\n data = {}\n data['statuspage_id'] = statuspage_id\n data['incident_id'] = incident_id\n\n request :method => :post,\n :url => @url + 'incident/delete',\n :payload => data\n end", "def destroy\n @society.destroy\n respond_to do |format|\n format.html { redirect_to societies_url, notice: 'Se ha eliminado exitosamente.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @society.destroy\n respond_to do |format|\n format.html { redirect_to societies_url, notice: 'Society was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @zombie_sighting = ZombieSighting.find(params[:id])\n @zombie_sighting.destroy\n\n respond_to do |format|\n format.html { redirect_to zombie_sightings_url }\n format.json { head :ok }\n end\n end", "def destroy\n @hood.destroy\n respond_to do |format|\n format.html { redirect_to hoods_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @grumble.destroy\n respond_to do |format|\n format.html { redirect_to grumbles_url, notice: 'Grumble was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @household.destroy\n respond_to do |format|\n format.html { redirect_to households_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @badge = Badge.find(params[:id])\n @badge.destroy\n\n respond_to do |format|\n format.html { redirect_to(organization_segment_badges_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n franchise.destroy\n\n respond_to do |format|\n format.html { redirect_to franchises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @forest = Forest.find(params[:id])\n @forest.destroy\n\n respond_to do |format|\n format.html { redirect_to forests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @house_hunter.destroy\n respond_to do |format|\n format.html { redirect_to house_hunters_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @garrison.destroy\n respond_to do |format|\n format.html { redirect_to garrisons_path_for(@garrison) }\n format.json { head :no_content }\n end\n end", "def destroy\n @garply.destroy\n respond_to do |format|\n format.html { redirect_to garplies_url, notice: 'Garply was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @golfer = Golfer.find(params[:id])\n @golfer.destroy\n\n respond_to do |format|\n format.html { redirect_to golfers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @subsidiary.destroy\n respond_to do |format|\n format.html { redirect_to subsidiaries_url, notice: \"Subsidiary was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @surgical_profile.destroy\n respond_to do |format|\n format.html { redirect_to patient_surgical_profiles_path(@patient) }\n format.json { head :no_content }\n end\n end", "def destroy\n @gage = Gage.find(params[:id])\n @gage.destroy\n\n respond_to do |format|\n format.html { redirect_to gages_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @franchisee_royalty.destroy\n respond_to do |format|\n format.html { redirect_to franchisee_royalties_url, notice: 'Franchisee royalty was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @village.destroy\n respond_to do |format|\n format.html { redirect_to villages_url, notice: 'Village was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @life_insurance.destroy\n\n respond_to do |format|\n format.html { redirect_to life_insurances_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @nurse = Nurse.find(params[:id])\n @nurse.destroy\n\n respond_to do |format|\n format.html { redirect_to nurses_url }\n format.json { head :no_content }\n end\n end", "def delete(id:)\n id_check(:id, id)\n\n cf_delete(path: \"/organizations/#{org_id}/railguns/#{id}\")\n end", "def destroy\n @gastracker = Gastracker.find(params[:id])\n @gastracker.destroy\n\n respond_to do |format|\n format.html { redirect_to gastrackers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @doggy.destroy\n respond_to do |format|\n format.html { redirect_to doggies_url, notice: 'Doggy was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @undergraduate.destroy\n respond_to do |format|\n format.html { redirect_to undergraduates_url, notice: 'Undergraduate was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end", "def destroy\n @geocach = Geocach.find(params[:id])\n @geocach.destroy\n\n respond_to do |format|\n format.html { redirect_to geocaches_url }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Company.delete(params[\"id\"])\n end", "def destroy\n @surprise.destroy\n respond_to do |format|\n format.html { redirect_to surprises_url, notice: 'Surprise was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @uginuce.sheep.update status:'na farmi'\n @uginuce.destroy\n respond_to do |format|\n format.html { redirect_to uginuces_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @barangay_population.destroy\n respond_to do |format|\n format.html { redirect_to barangay_populations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @agency.destroy\n respond_to do |format|\n format.html { redirect_to agencies_url, notice: \"Agency was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @gpath = Gpath.find(params[:id])\n @gpath.destroy\n\n respond_to do |format|\n format.html { redirect_to gpaths_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @barrels_income.destroy\n respond_to do |format|\n format.html { redirect_to barrels_incomes_url }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n @life_insurance.destroy\n respond_to do |format|\n format.html { redirect_to life_insurances_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @herald.destroy\n respond_to do |format|\n format.html { redirect_to heralds_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ruby.destroy\n respond_to do |format|\n format.html { redirect_to rubies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @surg = Surg.find(params[:id])\n @surg.destroy\n\n respond_to do |format|\n format.js\n format.xml { head :ok }\n end\n end", "def destroy\n @nightclub.destroy\n respond_to do |format|\n format.html { redirect_to nightclubs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @county = County.find(params[:id])\n @county.destroy\n\n respond_to do |format|\n format.html { redirect_to(counties_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @regulatory.destroy\n respond_to do |format|\n format.html { redirect_to regulatories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @suscriber.destroy\n respond_to do |format|\n format.html { redirect_to suscribers_url, notice: 'Suscriber was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @bracket_golfer.destroy\n respond_to do |format|\n format.html { redirect_to bracket_golfers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @badge = Badge.find(params[:id])\n @badge.destroy\n\n respond_to do |format|\n format.html { redirect_to(badges_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @bounty.destroy\n respond_to do |format|\n format.html { redirect_to bounties_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @great.destroy\n respond_to do |format|\n format.html { redirect_to greats_url, notice: 'Great was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @house.destroy\n respond_to do |format|\n format.html { redirect_to houses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @house.destroy\n respond_to do |format|\n format.html { redirect_to houses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @uriy.destroy\n respond_to do |format|\n format.html { redirect_to uriys_url }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @blood_donor.destroy\r\n respond_to do |format|\r\n format.html { redirect_to blood_donors_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @agency_type = AgencyType.find(params[:id])\n @agency_type.destroy\n\n respond_to do |format|\n format.html { redirect_to agency_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @fellowship.destroy\n respond_to do |format|\n format.html { redirect_to fellowships_url, notice: 'Fellowship was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_v1_initiative.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_initiatives_url, notice: 'Initiative was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @sigurance.destroy\n respond_to do |format|\n format.html { redirect_to sigurances_url, notice: 'Sigurance was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Alien.delete(params[\"id\"])\n end", "def destroy\n @g_anewby.destroy\n respond_to do |format|\n format.html { redirect_to g_anewbies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @guardianship = Guardianship.find(params[:id])\n @guardianship.destroy\n\n respond_to do |format|\n format.html { redirect_to guardianships_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @franchise.destroy\n respond_to do |format|\n format.html { redirect_to client_location_franchises_path(@client, @location) }\n format.json { head :no_content }\n end\n end", "def destroy\n @cage.destroy\n\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_village = Admin::Village.find(params[:id])\n @admin_village.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_villages_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @seniority.destroy\n respond_to do |format|\n format.html { redirect_to seniorities_url, notice: \"Seniority was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @spatial_coverages = SpatialCoverages.find(params[:id])\n @spatial_coverages.destroy\n\n respond_to do |format|\n format.html { redirect_to spatial_coverage_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @alley.destroy\n\n respond_to do |format|\n format.html { redirect_to alleys_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @lounge.destroy\n respond_to do |format|\n format.html { redirect_to lounges_url, notice: 'Lounge was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @sponsorship_level.destroy\n respond_to do |format|\n format.html { redirect_to sponsorship_levels_url, notice: 'Sponsorship level was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @sluzby = Sluzby.find(params[:id])\n @sluzby.destroy\n\n respond_to do |format|\n format.html { redirect_to sluzbies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @competency.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @rider = Rider.find(params[:id])\n @rider.destroy\n\n respond_to do |format|\n format.html { redirect_to riders_url }\n format.json { head :no_content }\n end\n end" ]
[ "0.7182643", "0.67730254", "0.67230374", "0.6630993", "0.6616279", "0.66024643", "0.65978736", "0.6595678", "0.6594261", "0.6591922", "0.6575546", "0.6570498", "0.6569284", "0.654879", "0.65446955", "0.65432924", "0.65346247", "0.6517912", "0.6517912", "0.6482941", "0.6481099", "0.64726114", "0.64529264", "0.64501053", "0.6446912", "0.6435739", "0.6433316", "0.6427612", "0.6424307", "0.6411156", "0.6410192", "0.64030135", "0.6401401", "0.63938874", "0.63934916", "0.639075", "0.63905865", "0.639012", "0.6389729", "0.63849306", "0.6384565", "0.63821375", "0.63812786", "0.6381031", "0.6381025", "0.637862", "0.6377956", "0.63779265", "0.63763463", "0.63760144", "0.6373129", "0.6372052", "0.6366584", "0.63655037", "0.6365015", "0.63631487", "0.6362109", "0.6361032", "0.6354484", "0.6348183", "0.63372284", "0.6336765", "0.6334193", "0.6333088", "0.63308114", "0.6329749", "0.6327919", "0.6324096", "0.63205856", "0.631676", "0.63152194", "0.63150394", "0.63138396", "0.6312368", "0.63116646", "0.6310721", "0.6301131", "0.62951577", "0.62951577", "0.6294118", "0.6292216", "0.6292099", "0.629159", "0.62914884", "0.62895197", "0.6288046", "0.62833214", "0.6276909", "0.6276614", "0.6275187", "0.62716484", "0.6267504", "0.62641656", "0.62631166", "0.6262289", "0.625902", "0.6258756", "0.6257508", "0.6256899" ]
0.64824486
21
Method for search the surgery names
def surgery_search # Search for the speciality names @surgeries = find_surgery_term(params[:surgeryterm]) # respond to rendering the pages respond_to do |format| format.js end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def search_surgery\n\t\t# Searching for surgery as per user entered term\n\t\tif Surgery.where(user_type: \"admin\").any_of({ :name => /^#{params[:term]}/i }).present?\n\t\t\t# if search show from the admin then the search term from surgery of admin\n\t\t\tsurgeries = Surgery.where(user_type: \"admin\").any_of({ :name => /^#{params[:term]}/i }).all.collect{|surgery| {label: surgery.name}}.uniq.to_json\n\t\telse\n\t\t\t# else the term is not equal to the admin surgery then that search from the user term\n\t\t\tsurgeries = current_user.surgeries.any_of({ :name => /^#{params[:term]}/i }).all.collect{|surgery| {label: surgery.name}}.uniq.to_json \n\t\tend\n\t\t# render to the surgery name page\n\t\trespond_to do |format|\n\t\t format.json { render :json => surgeries }\n\t\tend\n\tend", "def find_surgery_term surgeryterm\n # Search the surgery terms\n Surgery.where(user_type: \"admin\").any_of({ :name => /^#{surgeryterm}/i }) \n end", "def surgery_name_list\n\t\t@surgeries = devise_current_user.surgeries.to_a.uniq {|surgery| surgery.name}\n\tend", "def profile_specialist_search\n\t\t# search the the speciality name according to the terms\n\t\tspecialities = Speciality.any_of({ :name => /^#{params[:term]}/i }).all.collect{|speciality| {label: speciality.name ,value: speciality.id.to_s}}.to_json \n\t\t# render to the surgery name page\n\t\trespond_to do |format|\n\t\t format.json { render :json => specialities }\n\t\tend\n\tend", "def surgery_name_list\n\t\tsurgeries = current_user.surgeries\n\t\tif surgeries.present?\n\t\t# response to the JSON\n \t render json: { success: true, response: {surgeries: surgeries.collect(&:name).as_json } },:status=> 200\n\t else\n\t render :json=> { success: false, message: \"Surgeries are not present\" },:status=> 203\n\t end \n\tend", "def recipe_name_search\n key_word = User.prompt.ask(\"Please piece of recipe name\")\n key_word == nil ? (key_word = 'bdncjkascndxasklxnasmndxb') : (key_word)\n recipe_query = Recipe.all.filter{|recipe| recipe.name.include?(key_word.capitalize())}\n\n if recipe_query != []\n recipe_viewer(recipe_query)\n else\n puts 'Invalid Search!'.colorize(:red);\n end\n end", "def search_by_name(name)\n name = name.capitalize\n result_name = []\n @name_list.each_value do |element|\n if element.include? name\n result_name.push(element)\n end\n end\n if result_name.empty?\n puts \"Nobody has name is #{name}\"\n else\n puts \"\\nList member of #{name} keyword\"\n result_name.each do |element|\n index = @name_list.values.index(element)\n show_profile(index, @name_list, @dob_list)\n end\n puts \"\\n\"\n end\n end", "def search_person(name = \"\")\n\t\t@nutshell.search_person(name)\n\tend", "def names\n @searches.names\n end", "def name\n search_string = (params[:search_string] || '').upcase\n @drugs = Drug.where([\"name LIKE ?\", '%' + search_string + '%']).select(\"name\")\n render plain: \"<li>\" + @drugs.map{|drug| drug.name }.join(\"</li><li>\") + \"</li>\"\n end", "def name_search # :nologin: :norobots:\n pattern = params[:pattern].to_s\n if pattern.match(/^\\d+$/) and\n (name = Name.safe_find(pattern))\n redirect_to(:action => 'show_name', :id => name.id)\n else\n query = create_query(:Name, :pattern_search, :pattern => pattern)\n @suggest_alternate_spellings = pattern\n show_selected_names(query)\n end\n end", "def searchByName\n\t\turl = request.original_url\n\t\t\n\t\tbegin\n\n\t\t\tprms = CGI.parse(URI.parse(url).query)\n\n\t\t\tresults = Doctor.where(\"first_name LIKE ?\", \"%#{prms['name'][0]}%\")\n\n\t\t\trender json: results\n\t\trescue Exception => e\n\t\t\trender json: { errors: \"Some errors\" }, status: 422\n\t\tend\n\tend", "def find_by_name(entry)\n names = []\n self.all.each do |item|\n if item.name.downcase.include? entry\n names << item \n end\n end\n names\n end", "def search\n # figure out if the search parameter looks like a first or last name only, or both\n @search = params[:search]\n if @search && !@search.empty?\n \tnames = @search.strip.split(' ')\n \tconditions = [[],[]]\n \tif (names.size > 1)\n\t \tfirst = names[0].to_s\n \t\tlast = names[1].to_s\n\t \tconditions[0] << \"#{_(:last_name, :person)} LIKE ? AND #{_(:first_name, :person)} LIKE ? \"\n\t \tconditions[1] << last + \"%\"\n\t \tconditions[1] << first + \"%\"\n\t \telse\n\t \t name = names.join\n\t \t\tconditions[0] << \"(#{_(:last_name, :person)} LIKE ? OR #{_(:first_name, :person)} LIKE ?) \"\n\t \t\tconditions[1] << name+'%'\n\t \t\tconditions[1] << name+'%' \n\t \tend\n\t \tif params[:filter_ids].present?\n\t \t conditions[0] << \"#{_(:id, :person)} NOT IN(?)\"\n\t \t conditions[1] << params[:filter_ids]\n \t end\n \t \n \t # Scope by the user's ministry / campus involvements\n \t involvement_condition = \"(\"\n \t if my_campus_ids.present?\n \t involvement_condition += \"#{CampusInvolvement.table_name}.#{_(:campus_id, :campus_involvement)} IN(?) OR \" \n \t \tconditions[1] << my_campus_ids\n \t end\n \t involvement_condition += \"#{MinistryInvolvement.table_name}.#{_(:ministry_id, :ministry_involvement)} IN(?) )\" \n \t \n\t \tconditions[0] << involvement_condition\n\t \tconditions[1] << current_ministry.self_plus_descendants.collect(&:id)\n\t \t\n\t \t@conditions = [ conditions[0].join(' AND ') ] + conditions[1]\n \n includes = [:current_address, :campus_involvements, :ministry_involvements]\n\t \t@people = Person.find(:all, :order => \"#{_(:last_name, :person)}, #{_(:first_name, :person)}\", :conditions => @conditions, :include => includes)\n\t \trespond_to do |format|\n\t \t if params[:context]\n\t \t format.js {render :partial => params[:context] + '/results', :locals => {:people => @people, :type => params[:type], :group_id => params[:group_id]}}\n \t else\n \t format.js {render :action => 'results'}\n\t end\n\t \tend\n\t else\n\t render :nothing => true\n\t end\n end", "def search; end", "def search(name)\n\t\tresult = []\n\t\tpeople.each do |person|\n\t\t \tif person.name.include?(name)\n\t\t \tputs \"tel: #{person.phone}\"\n\t\t \tresult << person\n\t\t\tend\n\t\tend\n\t\tresult\n\tend", "def return_name_search_results(names)\n if names == []\n puts \"Sorry, nothing found by that name.\"\n self.search_not_found\n else\n names.each do |item|\n puts \"#{names.index(item) + 1}. #{item.name }\"\n end \n end \n end", "def getname\n @name = params[:name]\n @highestsponsorshipofcsievent = Institute.where(\"name like ?\", \"%#{@name}%\").first\n end", "def search\n\n end", "def name_search(search)\n words = search.split(' ')\n results = where(\"UPPER(name) LIKE ?\", \"%#{words[0]}%\")\n for i in 1...words.size\n results = results.where(\"UPPER(name) LIKE ?\", \"%#{words[i]}%\")\n end\n return results\n end", "def search \n\n end", "def searchName\n @nombre=params[:nombre]\n @death_record_items=buscarNombre(@nombre)\n end", "def search_gen(input_arr,artists)\n len = input_arr.count\n singer_name = input_arr[2,len - 1] * \" \"\n if(artists.key?(singer_name))\n puts artists[singer_name]\n else\n puts \"Invalid artist name.\"\n end\n end", "def search_a_family_member_for_spending_list\n puts \"Enter a first name\"\n fname = gets\n\n result = self.search_family_member_by_first_name(fname.chomp)\n if result.class != String\n \tputs result\n \tputs result.spending_list_to_s\n else\n \tputs \"No record\"\n end\n end", "def action_search( contacts )\n puts\n pattern = ask \"Search for? \"\n puts\n contacts.each do |contact|\n\n #Patttern works on the first letter of first/sur name\n if contact[:name] =~ /\\b#{pattern}/i\n show ( contact )\n puts\n end\n end\nend", "def search\n end", "def get_university_name(text)\n name = nil\n @universities.reverse.each do |u|\n if text.downcase.include?(u.downcase)\n name = u\n end\n end\n return name\nend", "def starring(whazzername)\n # Find the movies with an actor who had a name like `whazzername`.\n # A name is like whazzername if the actor's name contains all of the\n # letters in whazzername, ignoring case, in order.\n\n # ex. \"Sylvester Stallone\" is like \"sylvester\" and \"lester stone\" but\n # not like \"stallone sylvester\" or \"zylvester ztallone\"\n\nend", "def auto_complete_for_ingredient_name\n value = params[:ingredient][:name]\n @ingredients = Ingredient.find(:all, \n :conditions => [ 'LOWER(name) LIKE ?',\n '%' + value.downcase + '%' ], \n :order => 'name ASC',\n :limit => 8)\n render :partial => 'ingredient_name_matches'\n end", "def search(word)\n \n end", "def search_by_name\n puts 'Enter a name to search for'\n lookup_name = gets.chomp\n result = @search.name(lookup_name)\n puts \"\\n#{formatted_search_result(result)}\"\n rescue EntryNotFoundError => e\n puts e.message\n end", "def search_keywords\n @developer_id = Developer.find_by_gamer_id(current_gamer.id).id\n @projects = Project.where(owner_id: @developer_id).all\n @project_id = params[:project_id]\n @search_keyword = params[\"search\"]\n if(!@search_keyword.blank?)\n @search_keyword = @search_keyword.strip\n @search_keyword = @search_keyword.split(\" \").join(\" \")\n if Keyword.find_by_name(@search_keyword)\n redirect_to search_path, search: @search_keyword\n end\n @similar_keywords =\n Keyword.get_similar_keywords(@search_keyword, [])\n end\n end", "def myfind (str)\n if str.match(/^[[:graph:]]+$/)\n Provider.where(\"lower(name) like ?\", \"%#{str}%\")\n end\n end", "def find_by_name(name)\n results = []\n search = name.downcase #vamios a igual todo en minusculas\n contacts.each do |contact|\n if contact.full_name.downcase.include?(search)#para los string, tenemos el metodo include, que lo comprar y busca en otro string\n results.push(contact)\n end\n end\n=begin\n #Imprimimos el resultado en pantalla\n puts \"Resultado de la busqueda (#{search})\"\n #Iteramos sobre el resultado\n results.each do |contact|\n puts contact.to_s('full_name')\n contact.print_phone_numbers\n contact.print_addresses\n puts \"\\n\"\n=end\nprint_results(\"Búsqueda de contacto: (#{search})\", results)\n\n \n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search_name(name)\n PeopleSearch.search_name(name, @api_key, @https)\n end", "def edit_surgery_name\n\tend", "def find_by_name(name)\n #iterate over each contact in the contact list and if the name matches the arguemnt to this method we will return that contact\n #start w/empty array of search results which = the contacts in our contact list\n results = []\n #make em all lowercase\n search = name.downcase\n #iterate thru contact if they match append them to the results []\n #add that loop yo\n contacts.each do |contact|\n #then if the first name (downcase that shite) matches our search...\n if contact.full_name.downcase.include?(search)\n #append our results\n results.push(contact)\n end\n end\n #now print out the results NOT resluts bitches\n print_results(\"Name search results (#{search})\", results)\n #now iterate over the result\n# results.each do |contact|\n# puts contact.to_s('full_name')\n# contact.print_phone_numbers\n# contact.print_addresses\n# puts \"\\n\"\n# end\n end", "def extract_name_by_multi_name\n name = ''\n names_arr = []\n @text.scan(/(Family|FAMILY|family|First|first|FIRST|Given|GIVEN|given|LAST|Last|last){1}[\\s|\\W]{0,}(name|Name|NAME){1}([\\:|\\s|\\,|\\W]{1,})+([A-Z]{1}[A-Za-z]+)/) do | track |\n names_arr << track\n end \n if names_arr.size == 2\n name = names_arr[0][-1] + names_arr[1][-1]\n end\n return name \n end", "def search\n\n end", "def search\r\nend", "def linear_search(input)\n \n search_name = input.downcase.split(' ')\n search_name.each do |name_el|\n \n entries.each do |entry|\n \n name_array = entry.name.downcase.split(' ')\n \n if name_array.include?(name_el)\n return entry\n end\n end\n end\n return nil\n end", "def name\n \tlogger.debug(\"\\n****************************testiiiiiiiiiiiing Name ****************************\\n\")\n\n \t@trainers=Trainer.joins(:user).where(\"fName like ? or lName like ?\",\"%#{params[:name]}%\",\"%#{params[:name]}%\").select(:fName)\n \tjson_response(@trainers)\n \t\n end", "def advanced_search # :nologin: :norobots:\n begin\n query = find_query(:Name)\n show_selected_names(query)\n rescue => err\n flash_error(err.to_s) if !err.blank?\n redirect_to(:controller => 'observer', :action => 'advanced_search_form')\n end\n end", "def family_name_matches\n filtered_matches(ignore: [:first_name], partial_or_perfect: [:family_name], perfect: [:street, :city])\n end", "def names_for_mushroom_app # :nologin: :norobots:\n number_of_names = params[:number_of_names].blank? ? 1000 : params[:number_of_names]\n minimum_confidence = params[:minimum_confidence].blank? ? 1.5 : params[:minimum_confidence]\n minimum_observations = params[:minimum_observations].blank? ? 5 : params[:minimum_observations]\n rank_condition = params[:include_higher_taxa].blank? ?\n '= \"Species\"' :\n 'NOT IN (\"Subspecies\", \"Variety\", \"Form\", \"Group\")'\n\n data = Name.connection.select_rows(%(\n SELECT y.name, y.rank, SUM(y.number)\n FROM (\n SELECT n.text_name AS name,\n n.rank AS rank,\n x.number AS number\n FROM (\n SELECT n.id AS name_id,\n n.synonym_id AS synonym_id,\n COUNT(o.id) AS number\n FROM names n, observations o\n WHERE o.name_id = n.id\n AND o.vote_cache >= #{minimum_confidence}\n GROUP BY IF(n.synonym_id IS NULL, n.id, -n.synonym_id)\n ) AS x\n LEFT OUTER JOIN names n ON IF(x.synonym_id IS NULL, n.id = x.name_id, n.synonym_id = x.synonym_id)\n WHERE n.deprecated = FALSE\n AND x.number >= #{minimum_observations}\n AND n.rank #{rank_condition}\n GROUP BY IF(n.synonym_id IS NULL, n.id, -n.synonym_id)\n ) AS y\n GROUP BY y.name\n ORDER BY SUM(y.number) DESC\n LIMIT #{number_of_names}\n ))\n\n genera = data.map do |name, rank, number|\n name.split(' ').first\n end.uniq\n\n families = {}\n for genus, classification in Name.connection.select_rows(%(\n SELECT text_name, classification FROM names\n WHERE rank = 'Genus'\n AND COALESCE(classification,'') != ''\n AND text_name IN ('#{genera.join(\"','\")}')\n ))\n for rank, name in Name.parse_classification(classification).reverse\n if rank == :Family\n families[genus] = name\n break\n end\n end\n end\n\n report = FasterCSV.generate(:col_sep => \"\\t\") do |csv|\n csv << ['name', 'rank', 'number_observations', 'family']\n data.each do |name, rank, number|\n genus = name.split(' ').first\n family = families[genus] || ''\n csv << [name, rank, number.round.to_s, family]\n end\n end\n send_data(report,\n :type => 'text/csv',\n :charset => 'UTF-8',\n :header => 'present',\n :disposition => 'attachment',\n :filename => \"#{action_name}.csv\"\n )\n\n rescue => e\n render(:text => e.to_s, :layout => false, :status => 500)\n end", "def autocomplete_sn\n render :partial => 'autocomplete', :object => Scientificname.find(:all, :conditions => ['name ILIKE ?', params[:sn] + '%' ])\n end", "def find_by_name\n query = '%'+params[:query]+'%'\n\n parents_found = Parent.where(\"f_name LIKE ? OR l_name LIKE ? OR CONCAT(f_name,' ',l_name) LIKE ?\", query, query, query)\n render json: parents_found\n end", "def search(word)\r\n \r\n end", "def search_names(logins)\n logins.select { |x| x[0].end_with?(\"_\")}\nend", "def search_through_names\r\n\t\tprofile_list = Array.new\r\n\t\ti=0.0\r\n\t\tnf = File.open(@name_file)\r\n\t\tnf.each_line do |line|\r\n\t\t\tif line != nil\r\n\t\t\t\ti = i + 1.0\r\n\t\t\t\turl_to_search = construct_search_url(line.chomp)\r\n\t\t\t\tif url_to_search != false\r\n\t\t\t\turl_list_to_scrape = get_profile_url_list(url_to_search)\r\n\t\t\t\tif url_list_to_scrape != nil #just check that there are profiles to scrape in this list...\r\n\t\t\t\t\turl_list_to_scrape.each do |profile_url|#could parrelize at this level.\r\n\t\t\t\t\t\ti=i+0.1\r\n\t\t\t\t\t\tprofile_list << scrape_profile(profile_url.to_s,i)\r\n\t\t\t\t\tend\t\r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\t\tend\r\n\t\tend\r\n\t\tsave_profiles_to_xml(profile_list)\r\n\tend", "def search_for_summoner\n\t\tbegin\n\t\t#remove punctuation to sanitize string\n\t\tsum_name = params[:summoner_name].gsub(/[!@#$%^&*()-=_+|;':\",.<>?']/, '')\n\t\t@summoners = Summoner.select(\"*\").where(\"name = '#{sum_name}'\")\n\t\t@page_params = Pp.new(1, Summoner.count, \"asc\", \"id\")\n\t\trender 'index'\n\t\trescue Exception => ex\n\t\t\tlogger.error(ex.message)\n\t\t\tflash[:notice] = \"Something went wrong, returning you to the index page.\"\n\t\t\tredirect_to(:action => 'index')\n\t\tend\n\tend", "def name_filter(results, search)\n words = search.split(' ')\n for i in 0...words.size\n results = results.where(\"UPPER(name) LIKE ?\", \"%#{words[i]}%\")\n end\n return results\n end", "def special_find(names)\n results = @restaurants.find_all do |restaurant|\n names.detect { |name| name.casecmp(restaurant.name) == 0 }\n end\n # Add separators\n results.join(\"\\n\" + (\"-\" * 80) + \"\\n\")\n end", "def search\n\n \t@matches = []\n\n\t\tpattern = params[:search].downcase\n \tfind = Regexp.new(Regexp.quote(pattern))\n\t\t\n \tPlayer.all.each do |p|\t\t\t\n\t\t\tplayer_matches = false\n \tif p.name.downcase =~ find\n \t\tplayer_matches = true\n \t\t@matches << [p.name]\n \t\tbreak\n \tend\n end\n \n \trender :text => @matches.to_json()\n \tend", "def search\n\n # extract the terms from params\n terms = params[:search_terms]\n\n # redirect to root in case of missing terms\n redirect_to root_path && return if terms.blank?\n\n # extract the terms to an array\n # delete('-') because phones are saved without '-' (numbers only)\n terms_array = params[:search_terms].delete('-').split(' ')\n\n # extract the params using private methods\n age = age_param(terms_array)\n phone = phone_param(terms_array)\n names_array = name_param_array(terms)\n\n # find the people available for the search terms\n @peoples = People.search_by_terms(names_array, phone, age)\n\n # renders 'search.js'\n end", "def search\nend", "def searchBySpeciality\n\t\turl = request.original_url\n\t\t\n\t\tbegin\n\n\t\t\tprms = CGI.parse(URI.parse(url).query)\n\n\n\t\t\tresults = Doctor.where(\"speciality LIKE ?\", \"%#{prms['speciality'][0]}%\")\n\t\t\trender json: results\n\t\trescue Exception => e\n\t\t\trender json: { errors: \"Some errors\" }, status: 422\n\t\tend\n\tend", "def parse_search; end", "def term_to_name_string(term)\n self.search_string ? sstring = self.search_string : sstring = terms[term]\n if not sstring.blank?\n names = sstring.split(/, +|[,\\^\\- ]/).collect do |e|\n Regexp.escape(e)\n end\n names.uniq\n else\n []\n end\n end", "def index\n @nutrients = Nutrient.name_containing(params.dig(:q, :name_cont)).order(name: :asc)\n end", "def searching\n \t@temp = Account.all\n \t@own_temp = Account.find_by_aid(session[:id])\n \t@temp.delete(@own_temp)\n \t\n \t@after_lowercase = (params[:search][:search_input]).downcase\n \t@splited = @after_lowercase.split\n \t@first_s = params[:search]\n \t@second_s = params[:search_input]\n \n \t@result = Array.new\n \t\n \tif (@splited.size() > 2)\n \t\t\tflash[:error] = \"Too many arguments... follow this format : first_name last_name\"\n \t\t\tredirect_to :action => :profile\n \telsif (@splited.size() == 0)\n \t\t\tflash[:error] = \"I need at least one argument!!\"\n \t\t\tredirect_to :action => :profile\n \t\t\t/(jon){1}/\n \t\t\t\n \telsif (@splited.size() == 1) \t\n \t\t@temp.each do |re| \n \t\t\tif (re.first_name.downcase =~ /#{@splited[0]}{1}/)\n \t\t\t\t@result.push(re)\n \t\t\telsif (re.last_name.downcase =~ /#{@splited[0]}{1}/ && false == @result.include?(re))\n \t\t\t\t@result.push(re)\n \t\t\tend\n \t\tend\n \telsif (@splited.size() == 2)\t\n \t\t@temp.each do |re|\n \t\t\tif (re.first_name.downcase =~ /#{@splited[0]}{1}/ || re.last_name.downcase =~ /#{@splited[1]}{1}/)\n \t\t\t\t@result.push(re)\n \t\t\tend\n \t\tend\n \t\n \tend\n \t\n\n \tif @result == nil\n \t\t\tflash[:error] = \"no match\"\n \t\t\tredirect_to :action => :profile\n \tend\n\n end", "def find_surgery_location\n\t\t# Find the surgeon location based on the profile\n\t\t@surgery_locations = current_user.setting.surgery_locations.all\n\tend", "def search_by_name(database, name)\n\tsearch_result = database.execute(<<-SQL \n\t\t\tSELECT * FROM restaurants WHERE name LIKE \"#{name}%\" ORDER BY name\n\t\tSQL\n\t\t) \n\tprint(search_result, \"name\")\t\nend", "def find_surgery\n\t\t@surgery = Surgery.find(params[:id])\n\tend", "def search_for_group\n @groups = @login_user.all_groups(params[:term])\n @usernames = []\n @groups.collect{|group| @usernames << group.name}\n respond_to do |format|\n format.json { render :json => @usernames }\n end\n end", "def names name = \"\"\n find_all_by_name( name ).map(&:name)\n end", "def find_cartridges(name)\n logger.debug \"Finding cartridge #{name}\" if @mydebug\n regex = nil\n if name.is_a?(Hash)\n name = name[:name] if name[:name]\n regex = name[:regex] if name[:regex]\n end\n\n filtered = Array.new\n cartridges.each do |cart|\n if regex\n filtered.push(cart) if cart.name.match(regex)\n else\n filtered.push(cart) if cart.name == name\n end\n end\n return filtered\n end", "def search_params\n params[:name]\n end", "def myfind (str)\n if str.match(/^[[:graph:]]+$/) # name of the vaccine\n Vaccine.where(\"lower(name) like ?\", \"%#{str.downcase}%\")\n end\n end", "def autocomplete_venue_name\n term = params[:term]\n if term && !term.empty?\n items = Venue.verified.select(\"name\").\n where(\"name like ?\", '%' + term.downcase + '%').\n limit(10).order(:name)\n else\n items = {}\n end\n render :json => json_for_autocomplete(items, :name)\n end", "def get_names\n\t face = html.search(\".student .card\")\n\t students = []\n\t face.collect do |element|\n\t students << element.text\n\t end\n\t end", "def searchEvent\n input = @searchText.value\n\n begin\n output = \"\"\n db = SQLite3::Database.open \"drugs.db\"\n\n # Fuzzy matches the user input against the db entries\n matches = db.execute \"SELECT Name,EqClass FROM Drugs WHERE Name LIKE '#{input}%';\"\n output = \"No Results\" if matches.empty?\n\n # For each match found in the db, looks up which Carriers cover it\n matches.each do |match|\n output += \"#{match[0].upcase}\"\n\n if not match[1].nil?\n equivalents = db.execute \"SELECT Name FROM Drugs WHERE EqClass = #{match[1]}\"\n output += \"(\"\n equivalents.each do |eqDrug|\n output += eqDrug[0]+\", \" if not eqDrug[0].include? match[0]\n end\n output.chop!.chop!\n output.chop! if output[-1] == \"(\"\n output += \")\" if output[-1] != \"(\"\n end\n output += \":\\n\"\n\n coverage = db.execute \"SELECT Carriers.Name, CoverageTier\n FROM Carriers, Drugs, Covers\n WHERE Carriers.Id = Covers.CarrierId\n AND Drugs.Id = Covers.DrugId\n AND Drugs.Name = '#{match[0]}';\"\n\n coverage.each do |carrier|\n output += \"#{carrier[0]} (tier #{carrier[1]})\\n\"\n end\n output += \"_________________________________________\\n\\n\"\n end unless matches.empty?\n\n rescue SQLite3::Exception => e\n puts \"Exception occured\"\n puts e\n ensure\n db.close if db\n @allResults = output\n setResultsText(0)\n end unless input.empty?\n\n\n return true\n end", "def specific_gyms\n Membership.all.select {|member_info| member_info.member_name == self}.map{|member_info| member_info.gym_name.name}\n end", "def search_result\n freelancers = find_all FREELANCERS\n end", "def search_string\n @search_string\n end", "def guardians_name\n\t\tguardiansname = guardians_names.delete_if(&:blank?).join(' ')\n\t\t( guardiansname.blank? ) ? '[name not available]' : guardiansname\n\tend", "def index\n if params[:search]\n @groups = Group.search((params[:search]).to_s.downcase)\n end\n end", "def searchtitle\n end", "def search\n super.merge(string: \"#{self.system_name}\")\n end", "def index \n @customizing_names = CustomizingName.where(nil) # creates an anonymous scope\n # Filteranfragen beantworten\n if params[:name_search_text].present?\n @customizing_names = CustomizingName.where('name LIKE ?', '%' + params[:name_search_text] + '%').all\n else\n @customizing_names = CustomizingName.all\n end\n end", "def search_results\n @individual = Individual.by_uid( params[:'names-search-uid'] )\n if @individual\n redirect_to display_path( @individual.uid )\n else\n redirect_to :search\n end\n end", "def find\n puts params[:search_string]\n @results = Clientworkout.where(client_name: params[:search_string])\n #@results = Clientworkout.where('lower(client_name)=?' params[:search_string])\n end", "def name_conditions\n [\"(lower(users.first_name) LIKE ? AND lower(users.last_name) LIKE ?) OR (lower(users.first_name) LIKE ? AND lower(users.last_name) LIKE ?)\", \"%#{first_name}%\", \"%#{last_name}%\", \"%#{last_name}%\", \"%#{first_name}%\"] unless name.blank?\n end", "def search_firstname(input)\n \n search_name = input.downcase\n lower = 0\n upper = entries.length - 1\n \n while lower<= upper\n mid = (upper+lower)/2\n mid_name_array = entries[mid].name.split(' ').map! { |el| el.downcase }\n \n if search_name == mid_name_array[0]\n return entries[mid]\n elsif search_name < mid_name_array[0]\n upper = mid - 1\n elsif search_name > mid_name_array[0]\n lower = mid + 1\n end\n end\n return nil\n end", "def search_people(searchterm,params={})\n @opensearch.search_people(searchterm,params) \n end", "def search_for_track_name(tracks, search_name)\n\tfound_index = -1\n\ti = 0\n\twhile i < tracks.length\n\t\ttrack = tracks[i]\n\t\tif track.name.downcase.chomp.include? search_name.chomp.downcase\n\t\t\tfound_index = i\n\t\tend\n\t\ti = i + 1\n\tend\n\n found_index\nend", "def search\n @patients = Patient.where(name: params[:search][:name])\n render :index\n end", "def results\n @students = Student.where('name LIKE ?', \"%#{params[:q]}%\")\n end", "def search_results\n search_name = params[\"customer\"]\n @customers = Customer.where(florist_id: session[\"found_florist_id\"]).where(\"name ilike ?\",\"%#{params[\"customer\"]}%\") \n render(:search_results) and return\n end", "def extract_names(content)\n names = []\n \n # Split content into words.\n words = content.split(/[^-_a-z0-9]+/i).select {|v| v.index(/^[-a-z]+$/i)}\n \n # Loop over each bigram and check if the words are title cased and if at\n # least one of the words is a first or last name.\n words.each_with_index do |first_name, index|\n surname = full_surname = words[index+1] || ''\n \n # Skip to the next word if we have a couple of the next words.\n if ['van', 'von'].index(surname)\n surname = words[index+2] || ''\n full_surname = \"#{full_surname} #{surname}\"\n end\n \n # Only look at two words that are titlecase and neither one is a stopword.\n next if !first_name.titlecase? || !surname.titlecase?\n next if !stopwords.index(first_name.upcase).nil? || !stopwords.index(surname.upcase).nil?\n \n # Check if either the first name or last name is a recognized common name.\n if Matlock::Data.first_name?(first_name) || Matlock::Data.surname?(surname)\n full_name = \"#{first_name} #{full_surname}\"\n names << full_name if names.index(full_name).nil?\n end\n end\n \n return names\n end" ]
[ "0.70865774", "0.6948414", "0.6447701", "0.6417929", "0.63556087", "0.6207575", "0.6091319", "0.60365766", "0.60101146", "0.60049766", "0.5953369", "0.5876188", "0.58475107", "0.58171266", "0.5816419", "0.5768957", "0.5758103", "0.5746169", "0.57448435", "0.5700687", "0.5679415", "0.5675254", "0.56720513", "0.5642723", "0.56418914", "0.56341344", "0.56205904", "0.5596439", "0.5594924", "0.5585468", "0.5584778", "0.5572707", "0.55632424", "0.5561347", "0.5557848", "0.5557848", "0.5557848", "0.5557848", "0.5557848", "0.5557848", "0.5557848", "0.5557848", "0.5557848", "0.5557848", "0.5551417", "0.5551117", "0.5536948", "0.55194116", "0.5513497", "0.5494642", "0.54850686", "0.54837924", "0.547942", "0.5473818", "0.5468653", "0.54658043", "0.5463319", "0.5451922", "0.5444235", "0.54415625", "0.543944", "0.54348373", "0.5429872", "0.5426046", "0.53973824", "0.53901243", "0.5388025", "0.53789884", "0.5375", "0.53663784", "0.53588897", "0.5357569", "0.5348477", "0.53373516", "0.53369325", "0.53335774", "0.5330094", "0.53252745", "0.5324021", "0.5320331", "0.53162134", "0.53055006", "0.5303461", "0.53034365", "0.5302293", "0.5299576", "0.5296988", "0.5293458", "0.52866554", "0.5285425", "0.5281545", "0.5280229", "0.527425", "0.527397", "0.52728295", "0.5272094", "0.5271283", "0.52548164", "0.52525246", "0.525009" ]
0.669805
2
Use callbacks to share common setup or constraints between actions.
def set_surgery @surgery = Surgery.find(params[:id]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_required_actions\n # TODO: check what fields change to asign required fields\n end", "def action_hook; end", "def run_actions; end", "def define_action_hook; end", "def actions; end", "def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end", "def add_actions; end", "def callbacks; end", "def callbacks; end", "def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end", "def define_action_helpers; end", "def post_setup\n end", "def action_methods; end", "def action_methods; end", "def action_methods; end", "def before_setup; end", "def action_run\n end", "def execute(setup)\n @action.call(setup)\n end", "def define_action_helpers?; end", "def set_actions\n actions :all\n end", "def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end", "def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end", "def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end", "def before_actions(*logic)\n self.before_actions = logic\n end", "def setup_handler\n end", "def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end", "def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end", "def action; end", "def action; end", "def action; end", "def action; end", "def action; end", "def workflow\n end", "def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end", "def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end", "def before(action)\n invoke_callbacks *self.class.send(action).before\n end", "def process_action(...)\n send_action(...)\n end", "def before_dispatch(env); end", "def after_actions(*logic)\n self.after_actions = logic\n end", "def setup\n # override and do something appropriate\n end", "def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end", "def setup(_context)\n end", "def setup(resources) ; end", "def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end", "def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end", "def determine_valid_action\n\n end", "def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end", "def startcompany(action)\n @done = true\n action.setup\n end", "def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end", "def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end", "def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end", "def define_tasks\n define_weave_task\n connect_common_tasks\n end", "def setup(&block)\n define_method(:setup, &block)\n end", "def setup\n transition_to(:setup)\n end", "def setup\n transition_to(:setup)\n end", "def action\n end", "def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend", "def config(action, *args); end", "def setup\n @setup_proc.call(self) if @setup_proc\n end", "def before_action \n end", "def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end", "def action\n end", "def matt_custom_action_begin(label); end", "def setup\n # override this if needed\n end", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end", "def after(action)\n invoke_callbacks *options_for(action).after\n end", "def pre_task\n end", "def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end", "def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end", "def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end", "def setup_signals; end", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end", "def initialize(*args)\n super\n @action = :set\nend", "def after_set_callback; end", "def setup\n #implement in subclass;\n end", "def lookup_action; end", "def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end", "def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end", "def release_actions; end", "def around_hooks; end", "def save_action; end", "def setup(easy)\n super\n easy.customrequest = @verb\n end", "def action_target()\n \n end", "def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end", "def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end", "def before_setup\n # do nothing by default\n end", "def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end", "def default_action; end", "def setup(&blk)\n @setup_block = blk\n end", "def callback_phase\n super\n end", "def advice\n end", "def _handle_action_missing(*args); end", "def duas1(action)\n action.call\n action.call\nend", "def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end", "def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end", "def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend" ]
[ "0.6163163", "0.6045976", "0.5946146", "0.591683", "0.5890051", "0.58349305", "0.5776858", "0.5703237", "0.5703237", "0.5652805", "0.5621621", "0.54210985", "0.5411113", "0.5411113", "0.5411113", "0.5391541", "0.53794575", "0.5357573", "0.53402257", "0.53394014", "0.53321576", "0.53124547", "0.529654", "0.5296262", "0.52952296", "0.52600986", "0.52442724", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.5232394", "0.523231", "0.5227454", "0.52226824", "0.52201617", "0.5212327", "0.52079266", "0.52050185", "0.51754695", "0.51726824", "0.51710224", "0.5166172", "0.5159343", "0.51578903", "0.51522785", "0.5152022", "0.51518047", "0.51456624", "0.51398855", "0.5133759", "0.5112076", "0.5111866", "0.5111866", "0.5110294", "0.5106169", "0.509231", "0.50873137", "0.5081088", "0.508059", "0.50677156", "0.50562143", "0.5050554", "0.50474834", "0.50474834", "0.5036181", "0.5026331", "0.5022976", "0.5015441", "0.50121695", "0.5000944", "0.5000019", "0.4996878", "0.4989888", "0.4989888", "0.49864885", "0.49797225", "0.49785787", "0.4976161", "0.49683493", "0.4965126", "0.4958034", "0.49559742", "0.4954353", "0.49535993", "0.4952725", "0.49467874", "0.49423352", "0.49325448", "0.49282882", "0.49269363", "0.49269104", "0.49252945", "0.4923091", "0.49194667", "0.49174926", "0.49173003", "0.49171105", "0.4915879", "0.49155936" ]
0.0
-1
Never trust parameters from the scary internet, only allow the white list through.
def surgery_params params.require(:surgery).permit(:name) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def strong_params\n params.require(:user).permit(param_whitelist)\n end", "def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end", "def allow_params_authentication!; end", "def allowed_params\n ALLOWED_PARAMS\n end", "def default_param_whitelist\n [\"mode\"]\n end", "def param_whitelist\n [:role, :title]\n end", "def expected_permitted_parameter_names; end", "def safe_params\n params.except(:host, :port, :protocol).permit!\n end", "def strong_params\n params.require(:team_member).permit(param_whitelist)\n end", "def permitir_parametros\n \t\tparams.permit!\n \tend", "def strong_params\n params.require(:community).permit(param_whitelist)\n end", "def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end", "def strong_params\n params.require(:education).permit(param_whitelist)\n end", "def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end", "def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end", "def param_whitelist\n [:rating, :review]\n end", "def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end", "def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end", "def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end", "def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end", "def valid_params_request?; end", "def strong_params\n params.require(:experience).permit(param_whitelist)\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end", "def allowed_params\n params.require(:allowed).permit(:email)\n end", "def permitted_params\n []\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end", "def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend", "def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end", "def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end", "def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end", "def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end", "def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end", "def safe_params\n params.require(:user).permit(:name)\n end", "def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend", "def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end", "def check_params; true; end", "def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end", "def quote_params\n params.permit!\n end", "def valid_params?; end", "def paramunold_params\n params.require(:paramunold).permit!\n end", "def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend", "def filtered_parameters; end", "def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end", "def filtering_params\n params.permit(:email, :name)\n end", "def check_params\n true\n end", "def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend", "def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend", "def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end", "def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end", "def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end", "def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend", "def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end", "def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end", "def active_code_params\n params[:active_code].permit\n end", "def filtering_params\n params.permit(:email)\n end", "def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end", "def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end", "def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end", "def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end", "def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end", "def list_params\n params.permit(:name)\n end", "def filter_parameters; end", "def filter_parameters; end", "def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end", "def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end", "def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end", "def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end", "def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end", "def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end", "def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end", "def url_whitelist; end", "def admin_social_network_params\n params.require(:social_network).permit!\n end", "def filter_params\n params.require(:filters).permit(:letters)\n end", "def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end", "def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end", "def sensitive_params=(params)\n @sensitive_params = params\n end", "def permit_request_params\n params.permit(:address)\n end", "def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end", "def secure_params\n params.require(:location).permit(:name)\n end", "def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end", "def question_params\n params.require(:survey_question).permit(question_whitelist)\n end", "def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end", "def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end", "def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end", "def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end", "def url_params\n params[:url].permit(:full)\n end", "def backend_user_params\n params.permit!\n end", "def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend", "def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end", "def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end", "def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end", "def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end", "def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end", "def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end", "def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end", "def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end" ]
[ "0.69792545", "0.6781151", "0.67419964", "0.674013", "0.6734356", "0.6591046", "0.6502396", "0.6496313", "0.6480641", "0.6477825", "0.64565", "0.6438387", "0.63791263", "0.63740575", "0.6364131", "0.63192815", "0.62991166", "0.62978333", "0.6292148", "0.6290449", "0.6290076", "0.62894756", "0.6283177", "0.6242471", "0.62382483", "0.6217549", "0.6214457", "0.6209053", "0.6193042", "0.6177802", "0.6174604", "0.61714715", "0.6161512", "0.6151757", "0.6150663", "0.61461", "0.61213595", "0.611406", "0.6106206", "0.6105114", "0.6089039", "0.6081015", "0.6071004", "0.60620916", "0.6019971", "0.601788", "0.6011056", "0.6010898", "0.6005122", "0.6005122", "0.6001556", "0.6001049", "0.59943926", "0.5992201", "0.59909594", "0.5990628", "0.5980841", "0.59669393", "0.59589154", "0.5958826", "0.5957911", "0.5957385", "0.5953072", "0.59526145", "0.5943361", "0.59386164", "0.59375334", "0.59375334", "0.5933856", "0.59292704", "0.59254247", "0.5924164", "0.59167904", "0.59088355", "0.5907542", "0.59064597", "0.5906243", "0.5898226", "0.589687", "0.5896091", "0.5894501", "0.5894289", "0.5891739", "0.58860534", "0.5882406", "0.587974", "0.58738774", "0.5869024", "0.58679986", "0.5867561", "0.5865932", "0.5864461", "0.58639693", "0.58617616", "0.5861436", "0.5860451", "0.58602303", "0.5854586", "0.58537364", "0.5850427", "0.5850199" ]
0.0
-1
Method for search the surgery term
def find_surgery_term surgeryterm # Search the surgery terms Surgery.where(user_type: "admin").any_of({ :name => /^#{surgeryterm}/i }) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def search_surgery\n\t\t# Searching for surgery as per user entered term\n\t\tif Surgery.where(user_type: \"admin\").any_of({ :name => /^#{params[:term]}/i }).present?\n\t\t\t# if search show from the admin then the search term from surgery of admin\n\t\t\tsurgeries = Surgery.where(user_type: \"admin\").any_of({ :name => /^#{params[:term]}/i }).all.collect{|surgery| {label: surgery.name}}.uniq.to_json\n\t\telse\n\t\t\t# else the term is not equal to the admin surgery then that search from the user term\n\t\t\tsurgeries = current_user.surgeries.any_of({ :name => /^#{params[:term]}/i }).all.collect{|surgery| {label: surgery.name}}.uniq.to_json \n\t\tend\n\t\t# render to the surgery name page\n\t\trespond_to do |format|\n\t\t format.json { render :json => surgeries }\n\t\tend\n\tend", "def search_term\n params[:searchTerm]\n end", "def searchterm\r\n @@st.get_searchterm(referer)\r\n end", "def search(word)\n \n end", "def surgery_search\n # Search for the speciality names\n @surgeries = find_surgery_term(params[:surgeryterm])\n # respond to rendering the pages\n respond_to do |format|\n format.js\n end\n end", "def search\n\n end", "def search; end", "def search(word)\r\n \r\n end", "def search(query); end", "def search \n\n end", "def search(term)\n raise \"Must be overridden\"\n end", "def search\n end", "def do_search\n @search_text = params[:q]\n\n # Doctoring for the view to find matches:\n @q = @search_text\n @q.chop! if params[:q] =~ /\\*$/\n @q = @q[1..-1] if params[:q] =~ /^\\*/\n\n # TODO: we'll want some whitelist filtering here later:\n # params[:q] = \"#{@q}*\" unless params[:q] =~ /\\*$/ or params[:q] =~ /^[-+]/ or params[:q] =~ /\\s/\n params[:q] = I18n.transliterate(params[:q]).downcase\n\n # TODO: This search suggestions block is large; extract.\n\n # First step (and, yes, this will be slow—we will optimize later), look for\n # search suggestions that match the query:\n words = params[:q].split # TODO: we might want to remove words with ^-\n # TODO: we might also want to remove stopwords e.g.: https://github.com/brenes/stopwords-filter\n suggestions = []\n # YUCK! This is the best way to do this in Searchkick at the moment, though.\n # :S\n words.each do |word|\n word_search = SearchSuggestion.search(word, fields: [{ match: :exact }])\n suggestions += word_search.results if word_search.respond_to?(:results)\n end\n\n # If we only found one thing and they only asked for one thing:\n if suggestions.size == 1 && params[:q] !~ /\\s/\n Rails.logger.warn(\"One suggestion.\")\n # TODO: move this to a helper? It can't go on the model...\n suggestion = suggestions.first\n suggestion = suggestion.synonym_of if suggestion.synonym_of\n where = case suggestion.type\n when :page\n suggestion.page\n when :object_term\n term_records_path(uri: suggestion.object_term, object: true)\n when :path\n suggestion.path\n when :wkt_string\n flash[:notice] = \"Unimplemented, sorry.\"\n \"/\"\n end\n return redirect_to(where)\n elsif suggestions.size >= 2 && params[:q] =~ /\\s/\n Rails.logger.warn(\"Multiple suggestions.\")\n groups = suggestions.group_by(&:type)\n # Easier to handle:\n groups[:page] ||= []\n groups[:object_term] ||= []\n groups[:path] ||= []\n groups[:wkt_string] ||= []\n if groups[:page].size > 1\n Rails.logger.warn(\"Multiple PAGE suggestions.\")\n # We can't use suggestions if there's more than one species. Sorry.\n flash[:notice] = t(\"search.flash.more_than_one_species\",\n species: groups[:page].map(&:match).to_sentence)\n else\n Rails.logger.warn(\"0 or 1 Page suggestions.\")\n clade = groups[:page].try(:first).try(:page_id)\n Rails.logger.warn(\"Page suggestion: #{clade}\") if clade\n if groups[:object_term].size > 2\n Rails.logger.warn(\"Over two TERM suggestions.\")\n flash[:notice] = t(\"search.flash.more_than_two_terms\",\n terms: groups[:object_term].map(&:match).to_sentence)\n elsif groups[:path].size > 0\n Rails.logger.warn(\"...had PATH suggestions.\")\n flash[:notice] = t(\"search.flash.cannot_combine_paths\",\n path: groups[:path].map(&:match).to_sentence)\n else # NOTE: this assumes we only have OBJECT term suggestions, not predicates.\n Rails.logger.warn(\"Usable suggestions...\")\n (first, second) = groups[:object_term] # Arbitrary which is first...\n Rails.logger.warn(\"First term: #{first.object_term}\")\n Rails.logger.warn(\"Second term: #{second.object_term}\") if second\n return redirect_to(term_records_path(uri: first.object_term, object: true,\n and_object: second.try(:object_term), clade: clade))\n end\n end\n end\n\n @clade = if params[:clade]\n puts \"*\" * 100\n puts \"** Filtering by clade #{params[:clade]}\"\n # It doesn't make sense to filter some things by clade:\n params[:only] = if params[:only]\n Array(params[:only]) - [:collections, :users, :predicates, :object_terms]\n else\n [:pages, :media]\n end\n puts \"Only param should now be: #{params[:only]}\"\n Page.find(params[:clade])\n else\n nil\n end\n\n default = params.has_key?(:only)? false : true\n @types = {}\n [ :pages, :collections, :articles, :images, :videos, :videos, :sounds, :links, :users, :predicates, :object_terms ].\n each do |sym|\n @types[sym] = default\n end\n\n @types[params[:only].to_sym] = true if params.has_key?(:only)\n\n # if params.has_key?(:only)\n # Array(params[:only]).each { |type| @types[type.to_sym] = true }\n # elsif params.has_key?(:except)\n # Array(params[:except]).each { |type| @types[type.to_sym] = false }\n # end\n\n # NOTE: no search is performed unless the @types hash indicates a search for\n # that class is required:\n\n @pages = if @types[:pages]\n fields = %w[preferred_vernacular_strings^20 vernacular_strings^20 preferred_scientific_names^10 scientific_name^10 synonyms^10 providers resource_pks]\n match = words.size == 1 ? :text_start : :phrase\n basic_search(Page, boost_by: [:page_richness, :specificity, :depth], match: match, fields: fields,\n where: @clade ? { ancestry_ids: @clade.id } : nil,\n includes: [:preferred_vernaculars, :medium, { native_node: { node_ancestors: :ancestor } }])\n else\n nil\n end\n\n\n @collections = if @types[:collections]\n basic_search(Collection, fields: [\"name^5\", \"description\"])\n else\n nil\n end\n\n @articles = if @types[:articles]\n basic_search(Searchkick,\n fields: [\"name^5\", \"resource_pk^10\", \"owner\", \"description^2\"],\n where: @clade ? { ancestry_ids: @clade.id } : nil,\n index_name: [Article])\n else\n nil\n end\n\n @images = if @types[:images]\n media_search(\"image\")\n else\n nil\n end\n\n @videos = if @types[:videos]\n media_search(\"video\")\n else\n nil\n end\n\n @sounds = if @types[:sounds]\n media_search(\"sound\")\n else\n nil\n end\n\n # @links = if @types[:links]\n # basic_search(Searchkick,\n # fields: [\"name^5\", \"resource_pk^10\", \"owner\", \"description^2\"],\n # where: @clade ? { ancestry_ids: @clade.id } : nil,\n # index_name: [Link])\n # else\n # nil\n # end\n\n @users = if @types[:users]\n basic_search(User, fields: [\"username^6\", \"name^4\", \"tag_line\", \"bio^2\"])\n else\n nil\n end\n\n Searchkick.multi_search([@pages, @articles, @images, @videos, @sounds, @collections, @users].compact)\n\n @pages = PageSearchDecorator.decorate_collection(@pages) if @pages\n @articles = ArticleSearchDecorator.decorate_collection(@articles) if @articles\n @images = ImageSearchDecorator.decorate_collection(@images) if @images\n @videos = VideoSearchDecorator.decorate_collection(@videos) if @videos\n @sounds = SoundSearchDecorator.decorate_collection(@sounds) if @sounds\n @collections = CollectionSearchDecorator.decorate_collection(@collections) if @collections\n @users = UserSearchDecorator.decorate_collection(@users) if @users\n\n # if @types[:predicates]\n # @predicates_count = TraitBank.count_predicate_terms(@q)\n # # NOTE we use @q here because it has no wildcard.\n # @predicates = Kaminari.paginate_array(\n # TraitBank.search_predicate_terms(@q, params[:page], params[:per_page]),\n # total_count: @predicates_count\n # ).page(params[:page]).per(params[:per_page] || 50)\n # end\n #\n # if @types[:object_terms]\n # @object_terms_count = TraitBank.count_object_terms(@q)\n # # NOTE we use @q here because it has no wildcard.\n # @object_terms = Kaminari.paginate_array(\n # TraitBank.search_object_terms(@q, params[:page], params[:per_page]),\n # total_count: @object_terms_count\n # ).page(params[:page]).per(params[:per_page] || 50)\n # end\n\n respond_to do |fmt|\n fmt.html do\n @page_title = t(:page_title_search, query: @q)\n end\n\n fmt.js { }\n\n # TODO: JSON results for other types! TODO: move; this is view logic...\n fmt.json do\n render json: JSON.pretty_generate(@pages.results.as_json(\n except: :native_node_id,\n methods: :scientific_name,\n include: {\n preferred_vernaculars: { only: [:string],\n include: { language: { only: :code } } },\n # NOTE I'm excluding a lot more for search than you would want for\n # the basic page json:\n top_media: { only: [ :id, :guid, :owner, :name ],\n methods: [:small_icon_url, :medium_icon_url],\n include: { provider: { only: [:id, :name] },\n license: { only: [:id, :name, :icon_url] } } }\n }\n ))\n end\n end\n end", "def perform_search\n terms = { vehicle_year: 2006,\n vehicle_brand: \"Yamaha\",\n vehicle_model: \"Yz250\",\n vehicle_submodel: \"-- Base\",\n category_name: \"Complete Wheel Assembly\" }\n perform_search(terms)\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n\n end", "def search_keywords\n @developer_id = Developer.find_by_gamer_id(current_gamer.id).id\n @projects = Project.where(owner_id: @developer_id).all\n @project_id = params[:project_id]\n @search_keyword = params[\"search\"]\n if(!@search_keyword.blank?)\n @search_keyword = @search_keyword.strip\n @search_keyword = @search_keyword.split(\" \").join(\" \")\n if Keyword.find_by_name(@search_keyword)\n redirect_to search_path, search: @search_keyword\n end\n @similar_keywords =\n Keyword.get_similar_keywords(@search_keyword, [])\n end\n end", "def search_term\n if params[:props]\n params[:props][:search_term]\n else\n return nil\n end\n end", "def search_people(searchterm,params={})\n @opensearch.search_people(searchterm,params) \n end", "def profile_specialist_search\n\t\t# search the the speciality name according to the terms\n\t\tspecialities = Speciality.any_of({ :name => /^#{params[:term]}/i }).all.collect{|speciality| {label: speciality.name ,value: speciality.id.to_s}}.to_json \n\t\t# render to the surgery name page\n\t\trespond_to do |format|\n\t\t format.json { render :json => specialities }\n\t\tend\n\tend", "def search\n @search = Sunspot.search(Job) do\n keywords(params[:searchterm])\n end\n end", "def search\r\nend", "def editor_search\n @results = Soc_med.where text: params[:term]\n redirect_to '/dashboard'\n end", "def search\nend", "def parse_search(q)\n # TODO continue\n end", "def term\r\n Riddle::Query.escape params[:term]\r\n end", "def term\r\n Riddle::Query.escape params[:term]\r\n end", "def search_string\n @search_string\n end", "def parse_search; end", "def search\n unless params[:search].blank?\n @search = Sunspot.search(KyuEntry) do\n fulltext params[:search]\n end\n @kyu = @search.results\n end\n end", "def search_text_field\n @page.find('search_term')\n end", "def search_terms\n return @search_terms\n end", "def keyword_query_string\n processed_terms = []\n self.search_terms.each do |search_val|\n # spaces or dashes (-) need to be quoted to be treated as single values\n term = search_val.match?(/[\\s-]/) ? \"\\\"#{search_val}\\\"\" : search_val\n processed_terms << term\n end\n processed_terms.join(' ')\n end", "def search(target)\n end", "def query\n\t\t\t[@search_term,@filter].compact.join(\" \")\n\t\tend", "def term\n @term\n end", "def query_param\n return unless search_query\n \"search=#{search_query}&phrase=true\"\n end", "def search_process\n @search_text =params[:q].to_s\n all =params[:all].to_s\n exact =params[:exact].to_s\n any =params[:any].to_s\n none =params[:none].to_s\n advanced_query=\"\"\n\n if all != \"\"\n all =all.split(' ')\n all_like =all.map { |x| \"keyword like \" + \"'%\" + x + \"%'\" }\n all_like =all_like.join(' and ')\n advanced_query=all_like\n end\n\n if exact != \"\" && all != \"\"\n exact =\"'%\"+exact+\"%'\"\n advanced_query = advanced_query + \" and keyword like \" + exact\n end\n\n if exact != \"\" && all == \"\"\n exact =\"'%\"+exact+\"%'\"\n advanced_query = \"keyword like \" + exact\n end\n\n if any != \"\" and (all != \"\" or exact != \"\")\n any =any.split(' ')\n any_like =any.map { |x| \"keyword like \" + \"'%\" + x + \"%'\" }\n any_like =any_like.join(' or ')\n advanced_query = advanced_query + \" and (\" + any_like + \")\"\n end\n\n if any != \"\" and all == \"\" and exact == \"\"\n any =any.split(' ')\n any_like =any.map { |x| \"keyword like \" + \"'%\" + x + \"%'\" }\n any_like =any_like.join(' or ')\n advanced_query = \"(\" + any_like + \")\"\n end\n\n if none != \"\" and (all != \"\" or exact != \"\" or any != \"\")\n none =none.split(' ')\n none_not_like=none.map { |x| \"keyword not like \" + \"'%\" + x + \"%'\" }\n\n none_not_like=none_not_like.join(' and ')\n\n advanced_query=advanced_query + \" and \" + none_not_like\n\n end\n\n if none != \"\" and all == \"\" and exact == \"\" and any == \"\"\n none =none.split(' ')\n none_not_like=none.map { |x| \"keyword not like \" + \"'%\" + x + \"%'\" }\n\n none_not_like=none_not_like.join(' and ')\n\n advanced_query= none_not_like\n end\n\n\n advanced_query = \"SELECT Model_ID FROM keyword_symbol_tables WHERE \"+advanced_query\n\n parameter_search_text=@search_text.split.join(\" \")\n keyword_array =parameter_search_text.split(' ')\n keyword_count =keyword_array.size\n\n connection = ActiveRecord::Base.connection\n\n if all != \"\" or exact != \"\" or any != \"\" or none != \"\"\n @resultset = connection.execute(\"#{advanced_query}\");\n else\n @resultset = connection.execute(\"call keyword_search('#{parameter_search_text}',#{keyword_count})\");\n end\n\n ActiveRecord::Base.clear_active_connections!\n\n @resultset_strings = @resultset.map { |result| result.to_s.gsub(/[^0-9A-Za-z]/, '') }\n\n @model_ids =Array.new\n @model_names =Array.new\n @model_types =Array.new\n\n @resultset_strings.each do |result|\n\n substring=result[0..4]\n\n if substring == \"NMLCL\"\n cell=Cell.find_by_Cell_ID(result.to_s)\n name=cell.Cell_Name\n type=\"Cell\"\n end\n\n if substring == \"NMLCH\"\n channel=Channel.find_by_Channel_ID(result.to_s)\n name =channel.Channel_Name\n type =\"Channel\"\n end\n\n\n if substring == \"NMLNT\"\n network=Network.find_by_Network_ID(result.to_s)\n name =network.Network_Name\n type =\"Network\"\n end\n\n if substring == \"NMLSY\"\n synapse=Synapse.find_by_Synapse_ID(result.to_s)\n name =synapse.Synapse_Name\n type =\"Synapse\"\n end\n\n @model_ids.push(result)\n @model_names.push(name)\n @model_types.push(type)\n\n end\n\n if @model_ids.count != 0\n\n render :partial => 'keyword_results_list',\n :locals => {\n :model_ids => @model_ids,\n :model_names => @model_names,\n :model_types => @model_types\n }\n\n else\n\n render :partial => 'no_results'\n\n end\n\n end", "def medley_search\n\t\t@keywords = params[:keywords].downcase.gsub(/[^a-z\\s]/, '')\n\t\t@keywords_array = @keywords.strip.split(/\\s+/)\n\t\t@formatted_search = ''\n\t\t@keywords_array.each do |keyword|\n\t\t\t@formatted_search = @formatted_search + keyword.to_s + '|'\n\t\tend\n\t\t@formatted_search = @formatted_search.chop\n\t\t@medleys = Medley.advanced_search(@formatted_search).order('votes DESC').joins(:user).limit(15)\n\t\t@medleys = medley_extra_formatter(@medleys)\n\t\t# Build Custom Item URLs Here...\n\tend", "def search\n\n # extract the terms from params\n terms = params[:search_terms]\n\n # redirect to root in case of missing terms\n redirect_to root_path && return if terms.blank?\n\n # extract the terms to an array\n # delete('-') because phones are saved without '-' (numbers only)\n terms_array = params[:search_terms].delete('-').split(' ')\n\n # extract the params using private methods\n age = age_param(terms_array)\n phone = phone_param(terms_array)\n names_array = name_param_array(terms)\n\n # find the people available for the search terms\n @peoples = People.search_by_terms(names_array, phone, age)\n\n # renders 'search.js'\n end", "def search\n @search_keyword = params[\"search\"]\n @project_id = params[:project_id]\n @country = params[\"country\"]\n @age_from = params[\"age_from\"]\n @age_from = @age_from.to_i if !@age_from.blank?\n @age_to = params[\"age_to\"]\n @age_to = @age_to.to_i if !@age_to.blank?\n if !@age_from.blank? && !@age_to.blank? && @age_from > @age_to\n temp = @age_from\n @age_from = @age_to\n @age_to = temp\n end\n @gender = params[\"gender\"]\n @education = params[\"education\"]\n if !@search_keyword.blank?\n @search_keyword = @search_keyword.strip\n @search_keyword = @search_keyword.split(\" \").join(\" \")\n @no_synonyms_found = false\n @search_keyword_model = Keyword.find_by_name(@search_keyword)\n if !@search_keyword_model.blank?\n @synonyms, @votes =\n @search_keyword_model.retrieve_synonyms(@country, @age_from, @age_to, @gender, @education)\n @no_synonyms_found = true if @synonyms.blank?\n @total_votes = 0\n @votes.each { |synonym_id, synonym_votes| @total_votes += synonym_votes }\n else\n redirect_to search_keywords_path(search: @search_keyword)\n end\n else\n redirect_to search_keywords_path\n end\n end", "def search_term\n return StringFunctions.cn_normalize(query_param) if browsing_call_numbers?\n\n query_param.normalize_em\n end", "def search\r\n\t\t\t$browser.text_field(:id => 'sb_form_q')\r\n\t\tend", "def kitties_search( q )\r\n \"https://www.cryptokitties.co/search?include=sale,sire,other&search=#{q}\"\r\nend", "def query\n Riddle::Query.escape params[:search_txt]\n end", "def search\n return @search\n end", "def search_for_term(term)\n self.search_field = term\n self.search\n wait_for_ajax\n end", "def find_jobs_by_term\n\n print \"\\nEnter a search term to filter jobs by: \".blue\n search_term = gets.strip\n\n jobs = FreelancerFinder::Job.all.find_all do |job|\n job.title.include?(\"#{search_term}\") || job.short_description.include?(\"#{search_term}\") || !!job.tags.detect {|tag| tag.include?(\"#{search_term}\")}\n end\n\n jobs\n end", "def search\n @search_term = params[:srch]\n @products = Product.find(:all, :conditions => ['description LIKE ?', \"%#{@search_term}%\"])\n end", "def search_process\r\nsearch_text=params[:q].to_s\r\nall=params[:all].to_s\r\nexact=params[:exact].to_s\r\nany=params[:any].to_s\r\nnone=params[:none].to_s\r\nadvanced_query=\"\"\r\n\r\nif all != \"\"\r\nall=all.split(' ')\r\nall_like=all.map {|x| \"keyword like \" + \"'%\" + x + \"%'\" }\r\nall_like=all_like.join(' and ')\r\nadvanced_query=all_like\r\nend\r\n\r\nif exact != \"\" && all != \"\"\r\nexact=\"'%\"+exact+\"%'\"\r\nadvanced_query = advanced_query + \" and keyword like \" + exact\r\nend\r\n\r\nif exact != \"\" && all == \"\"\r\nexact=\"'%\"+exact+\"%'\"\r\nadvanced_query = \"keyword like \" + exact\r\nend\r\n\r\nif any != \"\" and ( all != \"\" or exact != \"\" )\r\nany=any.split(' ')\r\nany_like=any.map { |x| \"keyword like \" + \"'%\" + x + \"%'\" }\r\nany_like=any_like.join(' or ')\r\nadvanced_query = advanced_query + \" and (\" + any_like + \")\"\r\nend\r\n\r\nif any != \"\" and all == \"\" and exact == \"\"\r\nany=any.split(' ')\r\nany_like=any.map { |x| \"keyword like \" + \"'%\" + x + \"%'\" }\r\nany_like=any_like.join(' or ')\r\nadvanced_query = \"(\" + any_like + \")\"\r\nend\r\n\r\nif none != \"\" and (all != \"\" or exact != \"\" or any != \"\")\r\nnone=none.split(' ')\r\nnone_not_like=none.map { |x| \"keyword not like \" + \"'%\" + x + \"%'\" }\r\n\r\nnone_not_like=none_not_like.join(' and ')\r\n\r\nadvanced_query=advanced_query + \" and \" + none_not_like\r\n\r\nend\r\n\r\nif none != \"\" and all == \"\" and exact == \"\" and any == \"\"\r\nnone=none.split(' ')\r\nnone_not_like=none.map { |x| \"keyword not like \" + \"'%\" + x + \"%'\" }\r\n\r\nnone_not_like=none_not_like.join(' and ')\r\n\r\nadvanced_query= none_not_like\r\nend\r\n\r\n\r\n\r\n\r\n\r\nadvanced_query = \"SELECT Model_ID FROM keyword_symbol_tables WHERE \"+advanced_query\r\nputs \"\\n\\n***********************************\\n\\n\"+advanced_query+\"\\n\\n**********************\\n\\n\"\r\n\r\nparameter_search_text=search_text.split.join(\" \")\r\n keyword_array=parameter_search_text.split(' ')\r\n keyword_count=keyword_array.size\r\n\r\nconnection = ActiveRecord::Base.connection();\r\nif all != \"\" or exact != \"\" or any != \"\" or none != \"\"\r\n@resultset = connection.execute(\"#{advanced_query}\");\r\nelse\r\n@resultset = connection.execute(\"call keyword_search('#{parameter_search_text}',#{keyword_count})\");\r\nend\r\nActiveRecord::Base.clear_active_connections!()\r\n\r\n@resultset.each do |res|\r\nputs res\r\nend\r\n@resultset_strings = @resultset.map { |result| result.to_s.gsub(/[^0-9A-Za-z]/, '')}\r\n@model_ids=Array.new\r\n@model_names=Array.new\r\n@model_types=Array.new\r\n@resultset_strings.each do |result|\r\nsubstring=result[0..4]\r\nputs\"\\n\\n************\"+substring\r\nif substring == \"NMLCL\"\r\ncell=Cell.find_by_Cell_ID(result.to_s)\r\nname=cell.Cell_Name\r\ntype=\"Cell\"\r\nend\r\n\r\nif substring == \"NMLCH\"\r\nchannel=Channel.find_by_Channel_ID(result.to_s)\r\nname=channel.Channel_Name\r\ntype=\"Channel\"\r\nend\r\n\r\n\r\nif substring == \"NMLNT\"\r\nnetwork=Network.find_by_Network_ID(result.to_s)\r\nname=network.Network_Name\r\ntype=\"Network\"\r\nend\r\n\r\n#if substring == \"NMLSY\"\r\n#name=Synapse.find_by_Synapse_ID(result.to_s)\r\n#type=\"Syanpse\"\r\n#end\r\n\r\n@model_ids.push(result)\r\n@model_names.push(name)\r\n@model_types.push(type)\r\nputs \"result-\"+result+\"name-\"+name.to_s\r\nend\r\n\r\nif @model_ids.count != 0\r\nrender :partial => 'keyword_results_list',:locals => {:model_ids => @model_ids,:model_names => @model_names,:model_types => @model_types}\r\nelse\r\nrender :partial => 'no_results'\r\nend\r\n\r\n\r\n end", "def search_process\r\nsearch_text=params[:q].to_s\r\nall=params[:all].to_s\r\nexact=params[:exact].to_s\r\nany=params[:any].to_s\r\nnone=params[:none].to_s\r\nadvanced_query=\"\"\r\n\r\nif all != \"\"\r\nall=all.split(' ')\r\nall_like=all.map {|x| \"keyword like \" + \"'%\" + x + \"%'\" }\r\nall_like=all_like.join(' and ')\r\nadvanced_query=all_like\r\nend\r\n\r\nif exact != \"\" && all != \"\"\r\nexact=\"'%\"+exact+\"%'\"\r\nadvanced_query = advanced_query + \" and keyword like \" + exact\r\nend\r\n\r\nif exact != \"\" && all == \"\"\r\nexact=\"'%\"+exact+\"%'\"\r\nadvanced_query = \"keyword like \" + exact\r\nend\r\n\r\nif any != \"\" and ( all != \"\" or exact != \"\" )\r\nany=any.split(' ')\r\nany_like=any.map { |x| \"keyword like \" + \"'%\" + x + \"%'\" }\r\nany_like=any_like.join(' or ')\r\nadvanced_query = advanced_query + \" and (\" + any_like + \")\"\r\nend\r\n\r\nif any != \"\" and all == \"\" and exact == \"\"\r\nany=any.split(' ')\r\nany_like=any.map { |x| \"keyword like \" + \"'%\" + x + \"%'\" }\r\nany_like=any_like.join(' or ')\r\nadvanced_query = \"(\" + any_like + \")\"\r\nend\r\n\r\nif none != \"\" and (all != \"\" or exact != \"\" or any != \"\")\r\nnone=none.split(' ')\r\nnone_not_like=none.map { |x| \"keyword not like \" + \"'%\" + x + \"%'\" }\r\n\r\nnone_not_like=none_not_like.join(' and ')\r\n\r\nadvanced_query=advanced_query + \" and \" + none_not_like\r\n\r\nend\r\n\r\nif none != \"\" and all == \"\" and exact == \"\" and any == \"\"\r\nnone=none.split(' ')\r\nnone_not_like=none.map { |x| \"keyword not like \" + \"'%\" + x + \"%'\" }\r\n\r\nnone_not_like=none_not_like.join(' and ')\r\n\r\nadvanced_query= none_not_like\r\nend\r\n\r\n\r\n\r\n\r\n\r\nadvanced_query = \"SELECT Model_ID FROM keyword_symbol_tables WHERE \"+advanced_query\r\nputs \"\\n\\n***********************************\\n\\n\"+advanced_query+\"\\n\\n**********************\\n\\n\"\r\n\r\nparameter_search_text=search_text.split.join(\" \")\r\n keyword_array=parameter_search_text.split(' ')\r\n keyword_count=keyword_array.size\r\n\r\nconnection = ActiveRecord::Base.connection();\r\nif all != \"\" or exact != \"\" or any != \"\" or none != \"\"\r\n@resultset = connection.execute(\"#{advanced_query}\");\r\nelse\r\n@resultset = connection.execute(\"call keyword_search('#{parameter_search_text}',#{keyword_count})\");\r\nend\r\nActiveRecord::Base.clear_active_connections!()\r\n\r\n@resultset.each do |res|\r\nputs res\r\nend\r\n@resultset_strings = @resultset.map { |result| result.to_s.gsub(/[^0-9A-Za-z]/, '')}\r\n@model_ids=Array.new\r\n@model_names=Array.new\r\n@model_types=Array.new\r\n@resultset_strings.each do |result|\r\nsubstring=result[0..4]\r\nputs\"\\n\\n************\"+substring\r\nif substring == \"NMLCL\"\r\ncell=Cell.find_by_Cell_ID(result.to_s)\r\nname=cell.Cell_Name\r\ntype=\"Cell\"\r\nend\r\n\r\nif substring == \"NMLCH\"\r\nchannel=Channel.find_by_Channel_ID(result.to_s)\r\nname=channel.Channel_Name\r\ntype=\"Channel\"\r\nend\r\n\r\n\r\nif substring == \"NMLNT\"\r\nnetwork=Network.find_by_Network_ID(result.to_s)\r\nname=network.Network_Name\r\ntype=\"Network\"\r\nend\r\n\r\n#if substring == \"NMLSY\"\r\n#name=Synapse.find_by_Synapse_ID(result.to_s)\r\n#type=\"Syanpse\"\r\n#end\r\n\r\n@model_ids.push(result)\r\n@model_names.push(name)\r\n@model_types.push(type)\r\nputs \"result-\"+result+\"name-\"+name.to_s\r\nend\r\n\r\nif @model_ids.count != 0\r\nrender :partial => 'keyword_results_list',:locals => {:model_ids => @model_ids,:model_names => @model_names,:model_types => @model_types}\r\nelse\r\nrender :partial => 'no_results'\r\nend\r\n\r\n\r\n end", "def search(word, options)\n session.options = adapt_to_dev_env(options)\n session.get(\"/publications?keyword=#{CGI.escape(word)}\")\n end", "def search(value)\n # YOUR WORK HERE\n end", "def term_to_query(term)\n \"%#{term}%\"\nend", "def query\n sanitize search_params['query']\n end", "def search_for(search_term)\n type_into TestElements.search_box, search_term\n type_into TestElements.search_box, :return\n end", "def searchdescription\n end", "def get_search_terms(string)\n\treturn \"q=\"+string.join(\"+\")\nend", "def full_text_search\n @attributes[:full_text_search]\n end", "def search_any_term\n render json: Article.with_any_terms(params[:query]).map(&:title)\n end", "def search_track\n term = params[:search_track][:term].strip # remove trailing spaces\n unless term.empty?\n @term = term\n #logger.debug \"searching for: \" + @term\n @tracks = Track.search @term \n render \"/searches/track_results\"\n else\n redirect_to root_url, :notice => \"You must enter a search term.\"\n end\n end", "def searchtitle\n end", "def search(term)\n contacts_index(Contact.search(term))\n end", "def search\n expose Challenge.search(@oauth_token, params[:keyword])\n end", "def search_keywords\n @categories = params[:categories]\n @project_id = params[:project_id]\n if @categories.present?\n categories_array = @categories.split(/,/)\n categories_array.map! { |x| x.strip }\n categories_array.reject! { |x| x.blank? }\n categories_array.uniq!\n else\n categories_array = []\n end\n @search_keyword = params[\"search\"]\n if(!@search_keyword.blank?)\n @search_keyword = @search_keyword.strip\n @search_keyword = @search_keyword.split(\" \").join(\" \")\n end\n @similar_keywords =\n Keyword.get_similar_keywords(@search_keyword, categories_array)\n @categories = categories_array.join(\", \")\n end", "def deal_search_word_params\n params[:deal_search_word]\n end", "def search(search_string)\n\n # Convert to a get-paramenter\n search_string = CGI.escapeHTML search_string\n search_string.gsub!(\" \", \"&nbsp;\")\n\n results = []\n \n return results\n end", "def term(string)\n @request.q = string\n end", "def modify_search_query\n query_data = params['q'] && params['q'][Garage::SearchPredicate]\n if query_data.present?\n params['q'][Garage::SearchPredicate] = query_data.split(' ')\n end\n end", "def index\n # @search = Shelter.search do\n # fulltext params[:search]\n # end\n # @shelters = @search.results\n @shelters = Shelter.all\nend", "def search(word)\n Parser.new(query(word)).parse\n end", "def search\n @term = sname = request.query_parameters[\"search\"].to_s.downcase\n @data = search_term(sname)\n render partial: \"shared/search\"\n end", "def search(keyword)\n $logger.info(\"HomePage: search for #{keyword}\")\n search_field.send_keys keyword\n search_field.submit\n FreelancerSearchResultsPage.new(@driver, $logger)\n end", "def search\n terms = @authority.search(url_search)\n render json: terms\n end", "def findorsuggest()\n \n end", "def search_results search\n search = normalize search\n @searches[search.to_s]\n end", "def search_word\n @words =\n if login?\n current_user.words.search params[:term]\n else\n Word.search params[:term]\n end\n end", "def get_search_terms(array_of_terms)\n\t\treturn \"q=\"+array_of_terms.join(\"+\")\n\tend", "def search\n terms = params[:query].split\n query = terms.map { |term| \"title like '%#{term}%' OR body like '%#{term}%' OR tags like '%#{term}%'\" }.join(\" OR \")\n \n @posts = Post.where(query).order(\"created_at DESC\").first(10)\n end", "def search\n if params[:search].present?\n @residentials = Residential.search(params[:search])\n else\n @residentials = Residential.all\n end\n end", "def search(term, location)\n url = \"#{API_HOST}#{SEARCH_PATH}\"\n params = {\n term: term,\n location: location,\n limit: SEARCH_LIMIT\n }\n#this takes info from params hash\n response = HTTP.auth(bearer_token).get(url, params: params)\n response.parse[\"businesses\"]\nend", "def search_terms=(value)\n @search_terms = value\n end", "def find_glossary_term!\n @glossary_term = find_or_goto_index(GlossaryTerm,\n params[:id].to_s)\n end", "def run_query(terms)\n return Book.run_search(terms)\nend", "def searchauthor\n end", "def search\n @users = User.search(@search_term)\n @tweets = Tweet.search(@search_term)\n @tags = Tag.search(@search_term)\n end", "def formatSearchTerm(term)\n term.gsub!(\" at Zappos.com\", \"\")\n term.gsub!(\" - Zappos Couture\", \"\")\n term.gsub!(\" - Zappos.com Free Shipping BOTH Ways\", \"\")\n term.gsub!(\" at Couture.Zappos.com\", \"\")\n term.gsub!(\" - Zappos Couture\", \"\")\n term.gsub!(\" - Search Zappos.com\", \"\")\n term\n end", "def search(term)\n url = \"#{API_HOST}#{SEARCH_PATH}\"\n params = {\n term: term,\n # location: DEFAULT_LOCATION,\n latitude: 37.784517,\n longitude: -122.397194,\n limit: SEARCH_LIMIT,\n open_now: true\n }\n\n response = HTTP.auth(ENV[\"AUTHORIZATION\"]).get(url, params: params)\n\n response.parse\n end", "def searchBySpeciality\n\t\turl = request.original_url\n\t\t\n\t\tbegin\n\n\t\t\tprms = CGI.parse(URI.parse(url).query)\n\n\n\t\t\tresults = Doctor.where(\"speciality LIKE ?\", \"%#{prms['speciality'][0]}%\")\n\t\t\trender json: results\n\t\trescue Exception => e\n\t\t\trender json: { errors: \"Some errors\" }, status: 422\n\t\tend\n\tend", "def search_with_filters\n @search_keyword = params[\"search\"]\n @project_id = params[\"project_id\"]\n @developer_id = Developer.find_by_gamer_id(current_gamer.id).id\n @projects = Project.where(owner_id: @developer_id).all\n @country = params[\"country\"]\n @age_from = params[\"age_from\"]\n @age_from = @age_from.to_i if !@age_from.blank?\n @age_to = params[\"age_to\"]\n @age_to = @age_to.to_i if !@age_to.blank?\n @gender = params[\"gender\"]\n @education = params[\"education\"]\n @synonym_type = params[\"synonym_type\"]\n\n if !@age_from.blank? && !@age_to.blank? && @age_from.to_i > @age_to.to_i\n temp = @age_from\n @age_from = @age_to\n @age_to = temp\n end\n\n if @synonym_type == \"0\"\n @synonym_type = nil\n elsif @synonym_type == \"1\"\n @synonym_type = true\n elsif @synonym_type == \"2\"\n @synonym_type = false\n end\n\n if !@search_keyword.blank?\n @search_keyword = @search_keyword.strip\n @search_keyword = @search_keyword.split(\" \").join(\" \")\n\n @search_keyword_model = Keyword.find_by_name(@search_keyword)\n if !@search_keyword_model.blank?\n \n if !current_developer.my_subscription\n .can_search_word(@search_keyword_model.id)\n \n flash[:error] = t(:search_not_allowed)\n redirect_to search_keywords_path, flash: flash\n return\n end\n\n @synonyms, @votes =\n @search_keyword_model.retrieve_synonyms(@country, @age_from, \n @age_to, @gender, @education, @synonym_type)\n\n @no_synonyms_found = true if @synonyms.blank?\n\n @total_votes = 0\n @votes.each { |synonym_id, synonym_votes| @total_votes += synonym_votes }\n\n @categories =\n @search_keyword_model.categories.map { |c| c.get_name_by_locale }\n\n @category_ids = @search_keyword_model.categories.map { |c| c.id }\n\n if !@no_synonyms_found\n @charts = @synonyms.map{ |s| { s.id => \n [piechart_gender(s.id, @gender, @country, @education, @age_from, @age_to), \n piechart_country(s.id, @gender, @country, @education, @age_from, @age_to),\n piechart_age(s.id, @gender, @country, @education, @age_from, @age_to), \n piechart_education(s.id, @gender, @country, @education, @age_from,@age_to)] } }\n end \n\n if request.xhr?\n render \"filtered_results.js\"\n end\n else\n redirect_to search_keywords_path(search: @search_keyword)\n end\n else\n redirect_to search_keywords_path\n end\n end", "def search(*args)\n end" ]
[ "0.7489109", "0.71838355", "0.7124443", "0.7071348", "0.7062752", "0.68411064", "0.6829328", "0.6821051", "0.6799708", "0.6770622", "0.67631733", "0.6725981", "0.671604", "0.66948384", "0.66834325", "0.66834325", "0.66834325", "0.66834325", "0.66834325", "0.66834325", "0.66834325", "0.66834325", "0.66834325", "0.66834325", "0.66673696", "0.6618464", "0.6606563", "0.65996", "0.65952045", "0.65510195", "0.6547135", "0.6518349", "0.6466355", "0.6465467", "0.643814", "0.643814", "0.63861406", "0.6373497", "0.6345309", "0.6315237", "0.631269", "0.62536687", "0.6236133", "0.62346345", "0.62339586", "0.6203165", "0.62027466", "0.61701304", "0.6165987", "0.6157474", "0.6145831", "0.6144575", "0.6143634", "0.61431515", "0.6136349", "0.6126514", "0.612148", "0.61056465", "0.60839856", "0.60839856", "0.6080581", "0.6077311", "0.6072912", "0.6070984", "0.6068415", "0.6051901", "0.6051624", "0.6047944", "0.6026862", "0.6012792", "0.601114", "0.60088104", "0.60044765", "0.59957206", "0.59872997", "0.59834975", "0.5962828", "0.5952466", "0.5951429", "0.59447426", "0.5937751", "0.5925382", "0.59132534", "0.5905994", "0.58984315", "0.5891989", "0.5891429", "0.5890933", "0.58895123", "0.58791435", "0.5876437", "0.587265", "0.5866798", "0.586565", "0.5863403", "0.5861516", "0.5860034", "0.5856661", "0.58556426", "0.58517593" ]
0.7859314
0
Method for cheking the user type
def check_user_type # find the user user = User.find(@surgery.user_id) # condition for checking the admin is present or not if user.admin == true # if admin then update the user type as admin @surgery.update(user_type: "admin") else # else user then update the user type as user @surgery.update(user_type: "user") end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def user_type; end", "def check_user_type\n if self.user_type.present?\n self.contractor = self.user_type.to_s.downcase.include? \"contractor\"\n else\n self.contractor = false\n end\n end", "def user_type\n\t\tif (current_user.type == 'Trainer')\n\t\t\ttrainer\n\t\telsif (current_user.type == 'Client')\n\t\t\tclient\n\t\t\t\n\t\tend\n\t\t\n\tend", "def user_type\n if self.class.name == \"PubcookieUser\"\n type = self.identity_type == \"Student\" ? self.identity_type : \"UW Standard user\"\n else\n type = \"External user\"\n end\n type\n end", "def user_type\n @user_type || NORMAL_USER\n end", "def set_user_type\n @user_type = UserType.find(params[:id])\n end", "def set_user_type\n @user_type = params[:user_type]\n end", "def user_type\n params[:user_type].downcase\n end", "def user_class\n \"#{params[:user_type]}\".classify.constantize\n end", "def set_typeofuser\n @typeofuser = Typeofuser.find(params[:id])\n end", "def user_type(t_obj, value)\n t_obj.receiver_type = \"Student\" if value.downcase == \"s\"\n t_obj.receiver_type = \"Employee\" if value.downcase == \"e\"\n end", "def any_user *types\n types = types.flatten.select_labels.map(&:to_sym)\n types = types & ::CanTango.config.users.registered\n users = types.map do |type|\n meth = :\"current_#{type}\"\n send(meth) if respond_to?(meth) && (types.empty? || types.include?(type))\n end\n chosen_user = users.compact.first\n chosen_user || guest_user\n end", "def is_user?\n usertype == 'user'\n end", "def build_user_type(user_type)\n #\n # instantiate the user type if not already exists\n self.send(\"#{user_type}\")\n # \n # #\n # # roles_users_options for caregivers\n # # checkboxes for existence of caregivers\n # if user_type =~ /^senior$/\n # self.subscriber_is_user = subscribed_for_self? # (subscriber_is_user.nil? || [\"1\", true].include?(subscriber_is_user))\n # \n # elsif user_type =~ /^subscriber$/\n # self.subscriber_is_caregiver = caregiving_subscriber? # (!subscriber_is_caregiver.nil? && [\"1\", true].include?( subscriber_is_caregiver))\n # \n # elsif user_type =~ /^caregiver/\n # _index = user_type[-1..-1].to_i\n # _existing = self.send(\"no_caregiver_#{_index}\") # check existing value\n # self.send(\"no_caregiver_#{_index}=\", ( _user.blank? || [\"1\", nil, true].include?(_existing) || _user.nothing_assigned? ))\n # #\n # # role options will be instantiated when called\n # end\n end", "def user_type\n @user_type ||= self.class.user_type_from_groups(@groups)\n end", "def users_types= value ; @users_types = value end", "def user_type\n user_types = []\n if admin\n user_types << \"Admin\"\n end\n if agent\n user_types << \"Agent\"\n end\n if customer\n user_types << \"Customer\"\n end\n user_types.join(\" / \")\n end", "def set_user_type\n if user_type_id.blank?\n customer_type_id = UserType.find_by(code: 'CUSTOMER').id\n self.user_type_id = customer_type_id\n end\n end", "def current_user_type\n User::TYPES.each do |mapping|\n user = send(\"current_#{mapping.to_s.downcase}\")\n return mapping unless user.nil?\n end\n :guest\n end", "def user_type\n return session[:user_type] if session[:user_type]\n # return logged_user.class.name if logged_user\n end", "def get_user_type(user)\n userExists = User.find_by_id(user.id)\n if userExists && user.permission_level == 1\n return \"Admin\"\n elsif userExists && user.permission_level == 0\n return \"Standard\"\n end\n end", "def fix_type\n self.type ||= self.partner_connection.imap_provider.class_for(User).to_s\n end", "def user_type\n # The user type can't be handled by the method_missing magic\n # from OctocatHerder::Base, since 'type' is the deprecated form\n # of the method 'class'.\n @raw['type']\n end", "def insist_on(type = nil, user = nil)\n case type\n when :logged_in\n if anon?\n flash[:danger] = \"please sign in first\"\n shunt_to_root\n end\n when :logged_out\n unless anon?\n flash[:danger] = \"cannot perform this action while logged in\"\n shunt_to_root\n end\n when :permission\n users = user.is_a?(ActiveRecord::Relation)? user : [user]\n users.each do |user|\n user ||= User.new(name: params[User.slug] || \"any other user\")\n unless can_modify? user\n flash[:danger] = \"you are #{anon?? \"not signed in\" : \"signed in as #{current_user.name}\"} and are not allowed to view or modify #{user.name}'s personal records\"\n shunt_to_root\n end\n end\n when :existence\n unless user\n flash[:danger] = \"no such user\"\n shunt_to_root\n end\n else\n unless Proc.new.call\n flash[:danger] = \"you do not have permission to do that\"\n shunt_to_root\n end\n end\n end", "def insist_on(type = nil, user = nil)\n case type\n when :logged_in\n if anon?\n flash[:danger] = \"please sign in first\"\n shunt_to_root\n end\n when :logged_out\n unless anon?\n flash[:danger] = \"cannot perform this action while logged in\"\n shunt_to_root\n end\n when :permission\n users = user.is_a?(ActiveRecord::Relation)? user : [user]\n users.each do |user|\n user ||= User.new(name: params[User.slug] || \"any other user\")\n unless can_modify? user\n flash[:danger] = \"you are #{anon?? \"not signed in\" : \"signed in as #{current_user.name}\"} and are not allowed to view or modify #{user.name}'s personal records\"\n shunt_to_root\n end\n end\n when :existence\n unless user\n flash[:danger] = \"no such user\"\n shunt_to_root\n end\n else\n unless Proc.new.call\n flash[:danger] = \"you do not have permission to do that\"\n shunt_to_root\n end\n end\n end", "def current_usertype\n current_account.user_type\n end", "def check_user(type, type_id)\n\t\n\t\tif admin_authorized?\n\t\t\treturn true\n\t\tend\n\t\t\n\t\tcase type \n\t\t\twhen \"idea\"\n\t\t\t\t@user_id = Idea.find_by_id(type_id).user_id\n\t\t\twhen \"project\"\n\t\t\t\t@user_id = Project.find_by_id(type_id).user_id\n\t\t\twhen \"innovation\"\n\t\t\t\t@user_id = Innovation.find_by_id(type_id).user_id\n\t\t\telse\n\t\t\t\treturn false\n\t\tend\n\n\t\t\n\t\tif @user_id == current_user.id\n\t\t\treturn true\n\t\telse\n\t\t\treturn false\n\t\tend\n\t\t\n\tend", "def user_type_id=(value)\n self[:user_type_id] = value\n\n type = UserType.where(id: value).first\n set_user_type_relation(type.name)\n end", "def user?\n type == :user_id\n end", "def user?\n type == :user_id\n end", "def user_type\n # if self.is_vendor\n # \"vendor\"\n # else\n # \"customer\"\n # end\n\n self.is_vendor ? 'vendor' : 'customer'\n end", "def update_type(user)\n if (self.is_self_auditor?(user) && self.is_self_audit?)\n :self\n elsif (self.is_peer_auditor?(user) && self.is_peer_audit?)\n :peer\n else\n :none\n end\n end", "def check_usertype(user_type, tree)\n error_cleared!\n check_rule_usertype(user_type.to_s, tree, false)\n end", "def check_privilege(type=0)\n # if type is greater than equal to 0, display all types or just the last\n\n if type >= 0\n $user_types[type] || $user_types.last\n else\n $user_types.first\n end\nend", "def sender\n self.user_type.constantize.find(self.user_id)\n end", "def allowed_types\n [Tapir::Entities::User]\nend", "def get_user\n instance_variable_get(\"@#{user_type}\")\n end", "def user_type\n return Sessions.type(session[:session_id])\nend", "def get_user_type\n uri = URI.parse(\"#{BASE_URL}/users/info\")\n response = JSON.parse(@client.get(uri).body)\n return response['type'] if response['success']\n\n throw_error(response)\n end", "def update_types\n\t[User]\nend", "def user_type\n return Sessions.type(session[:session_id])\nend", "def check_type(required_user_type)\n\n if current_user.type != required_user_type\n\n session[:denied_url] = \"#{SITE}#{request.request_uri}\"\n redirect_to(\"/agencies/#{session[:agencyId]}/denied\") if current_user.type == 'AgencyUser'\n redirect_to(\"/approverdashboard/denied\") if current_user.type == 'ApproverUser'\n redirect_to(\"/contractors/#{current_user.id}/denied\") if current_user.type == 'ContractorUser'\n\n end\n\n end", "def user_should_be(type)\n unless logged_in?\n store_location\n redirect_to log_in_path and return\n end\n\n return true if current_user.class == type\n redirect_to root_path and return\n end", "def change_type\n\t\t\trender json: User.update_type_by_id(params[:id], params[:type], params[:is])\n\t\tend", "def allowed_types\n [SearchString, User]\nend", "def allowed_types\n [ Entities::Username ]\nend", "def allowed_types\n [User]\nend", "def allowed_types\n\treturn [User]\nend", "def determine_user_class\n @user_class = options[\"user-class\"].presence ||\n ask(\"What will be the name for your user class? [User]\").presence ||\n 'User'\n end", "def validate_type(type)\n return true if type == :normal\n return admin if type == :admin\n return registrar if type == :registrar\n raise \"Unknown login type #{type}\"\n end", "def check_privilege(type)\n\nif type.floor == 1\n\t\"seller\"\n\nelsif type.floor == 2\n\t\"manager\"\n\nelsif type.floor == 3 \n\t\"admin\"\n\nelse \n \t\"user\"\n\n\tend\nend", "def register (userType)\r\n puts \"Name: \"\r\n name = gets.chomp\r\n puts \"E-mail: \"\r\n email = gets.chomp\r\n puts \"Password: \"\r\n pwd = gets.chomp\r\n\r\n if (@BetESS.fValidateEmail(email))\r\n case userType\r\n when \"punter\" then @BetESS.fAddPunter(name,email,pwd)\r\n when \"bookie\" then @BetESS.fAddBookie(name,email,pwd)\r\n when \"admin\" then @BetESS.fAddAdmin(name,email,pwd)\r\n end\r\n puts \"Your registration was successful!\"\r\n else puts \"That e-mail already exists!\"\r\n end\r\n end", "def select_question_type\n set_user_input\n if @user_input == 0\n @response = Registration.question_type_selection(@screen_id)\n @session.update_attributes(question_type_id: nil, req_no: @req_no - 1)\n else\n @question_type = QuestionType.find_by_ussd_id(@user_input)\n if @question_type\n @session.update_attributes(question_type_id: @question_type.id, req_no: @req_no)\n if URI.escape(@question_type.name) == URI.escape(\"Révision scolaire\")\n @response = Registration.select_academic_level(@screen_id)\n else\n @response = Registration.confirm_registration(@session, @screen_id)\n end\n else\n @response = Error.invalid_question_type(@screen_id)\n end\n end\n end", "def account_type\n User.account_type(current_user)\n end", "def check_user_address(user, type)\n addr = user.send(type)\n\n if addr && addr.user_id && addr.user_id != user.id\n Rails.logger.warn \"BUG!!! User #{user.id} does not own their #{type} #{addr.id}.\"\n end\n\n addr\n end", "def userize\n self.becomes(User)\n end", "def new\n user_param = request.path_parameters[:type]\n if user_param.nil? || !([\"fan\",\"artist\"].include? user_param )\n @user_type = \"fan\"\n else\n @user_type = user_param.html_safe\n end\n super\n end", "def user_class()\n @user\n end", "def set_exercise_types_in_user\n @exercise_types_in_user = ExerciseTypesInUser.find(params[:id])\n end", "def set_web_user_type\r\n @web_user_type = WebUserType.find(params[:id])\r\n end", "def type(type); end", "def set_type\n case @type\n when :password\n I18n.t('hidden_password')\n when :currency\n formatted_value_currency(@value)\n when :breakable\n formatted_value_breakable(@value, @break_character)\n else\n # Other types can be autodetected\n formatted_value_other(@value, @type)\n end\n end", "def create_user_type(type)\n if User.find_by_username(type).nil?\n User.create({ \n email: \"#{type}@#{type}.com\", \n username: \"#{type}\",\n university: University.first,\n role: User.roles[type],\n password: 'password',\n encrypted_password: Devise.bcrypt(User, 'password')\n })\n end\nend", "def current_usertype\n\t \n\t if current_admin\n\t @current_usertype = current_admin\n\t return @current_usertype\n\t end\n\t \n\t\taccount = current_user\n\n\t\tif account\n\t\t\tif account.account_type == Account.roles[:user]\n\t\t\t\t@current_usertype ||= User.find_by_account_id(account.id)\n\t\t\telsif account.account_type == Account.roles[:npo]\n\t\t\t\t@current_usertype ||= Npo.find_by_account_id(account.id)\n\t\t\tend\n\t\tend\n\n\t\t@current_usertype\n\tend", "def create\n super do |user|\n if User.where(user_type: 0).empty?\n user.user_type = 0\n resource_saved = user.save\n end\n end\n end", "def loaded_user\n user_type == 'MeetupUser' ? meetup_user : bridgetroll_user\n end", "def current_user\n User::TYPES.each do |mapping|\n user = self.send(\"current_#{mapping.to_s.downcase}\")\n return user unless user.nil?\n end\n end", "def get_identification_type\n if user_signed_in?\n @identification_type = current_user.cvs.find_by(params[:identification_type])\n end\n end", "def check_type\n \t self.type = TYPES[0] if !TYPES.include?(self.type)\n\t end", "def must_belong_to_user_type\n if user_type_class.where(user_id: self.id).empty?\n errors.add(:base, \"User Type object not created: #{user_type_class.to_s}\")\n return false\n end\n\n return true\n end", "def type(group)\n membership = Membership.find_by(user: self, group: group)\n if membership #if the user is a member of that group...\n membership.user_type # ... then return their membership type\n end\n end", "def user_class\n if @@user_class.is_a?(Class)\n raise \"You can no longer set Cadenero.user_class to be a class. Please use a string instead.\"\n elsif @@user_class.is_a?(String)\n begin\n Object.const_get(@@user_class)\n rescue NameError\n @@user_class.constantize\n end\n end\n end", "def restricted?\n return ( self.user_type == User::USER_TYPE_NORMAL )\n end", "def autofill_user_login(user_type = \"\")\n unless user_type.blank?\n user = self.send(\"#{user_type}\") # local copy, to keep code clean\n user.autofill_login unless user.blank? # || user.nothing_assigned?\n # #\n # # user_intake validation will fail if this is removed from here\n # if user && user.login.blank? && !user.email.blank? # !user.blank? && user.login.blank?\n # hex = Digest::MD5.hexdigest((Time.now.to_i+rand(9999999999)).to_s)[0..20]\n # # only when user_type is not nil, but login is\n # user.send(\"login=\".to_sym, \"_AUTO_#{hex}\") # _AUTO_xxx is treated as blank\n # user.send(\"password=\".to_sym, hex)\n # user.send(\"password_confirmation=\".to_sym, hex)\n # end\n end\n end", "def method_missing(method_id, *arguments)\n if match = /^is_(\\w+)_type\\?$/.match(method_id.to_s)\n types = match[1].split('_or_')\n types.include?(self.account_type)\n else\n super\n end\n end", "def show\n @user = User.find(params[:id])\nuser = User.find_by_id(session[:user_id])\n @user_type = user.user_type\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end", "def method_missing( name, *args )\n if !!(ret = my_data[ :\"user_#{ name }\" ])\n ret\n else\n super\n end\n end", "def export_users_fields\n case params[:type]\n when 'SALE'\n User.seller\n when 'CANDIDATE'\n User.hh\n end\n end", "def type_authentication!()\n @type = TAC_PLUS_AUTHEN\n end", "def set_api_v1_user_type\n @api_v1_user_type = Api::V1::UserType.find(params[:id])\n end", "def current_user_type_to_s\n stringa_res= \"\"\n if current_user == nil\n stringa_res= \"nil\"\n else\n stringa_res= current_user.class.to_s\n end\n stringa_res\n end", "def user_key?\n key_type == KEY_TYPE_USER\n end", "def get_type\n\n end", "def show\n @group_user = @current_user.user_groups.find_by_group_id(@group.id)\n @user_type = @group_user ? @group_user.user_type : nil\n end", "def can_issue?(user, type = self.type.to_sym)\n Punishment.can_issue?(user, type)\n end", "def user_kind\n UserKind.find(user_kind_id)\n end", "def new_typed_user\n user = self.imap_provider.class_for(User).new\n self.users << user\n user\n end", "def dataTypes(user)\n puts \"Your computer has to interpret data differently depending on what type is is.\"\n sleep(2)\n puts \"We all know Numbers are different to Words and Letters, but how does a computer??\"\n sleep(2.5)\n puts \"Luckily we can specify the difference to the computer\"\n sleep(2)\n puts \"Let's collect some data first!\"\n sleep(1)\n prompt = TTY::Prompt.new\n user.age = prompt.ask(\"How old are you?\".colorize(:green), convert: :int, default: ENV[\"User\"])\n puts \"Awesome so that would look like:\"\n sleep(1)\n puts \"age = #{user.age}\".colorize(:blue)\n sleep(1)\n puts \"Let's get some more data\"\n sleep(1)\n user.favouriteColour = prompt.ask(\"What's your favourite colour?\".colorize(:green), default: ENV[\"User\"])\n puts \"Awesome so that would look like:\"\n sleep(1)\n puts \"favourite_colour = '#{user.favouriteColour}'\".colorize(:blue)\n sleep(2)\n puts \"Now the reason favourite_color is in quotation marks, is because thats how we tell the computer,\"\n sleep(2)\n puts \"that it is a 'String' \"\n sleep(1.5)\n puts \"A String can be any amount of characters wrapped in quotation marks\"\n sleep(1.5)\n puts \"'This is a String'\".colorize(:magenta)\n sleep(1.5)\n puts \"'Th1s 1s 4ls0 4 5tring'\".colorize(:magenta)\n sleep(1.5)\n puts \"'This is also a String 123456 --==-- '\".colorize(:magenta)\n sleep(1.5)\n puts \"Another commonly used data type is an Integer\"\n sleep(2.5)\n puts \"An Integer is any whole number\"\n sleep(1.5)\n puts \"So that means your_age = #{user.age} would be considered an Integer\"\n sleep(2)\n puts \"Aslong as the number isn't wrapped in quotation marks it is considered a Integer\"\n sleep(2.5)\n puts \"24 is an Integer\".colorize(:cyan)\n sleep(1.5)\n puts \"'24' is a String\".colorize(:magenta)\n sleep(1)\n puts \"-1283982 is an Integer\".colorize(:cyan)\n sleep(1.5)\n puts \"'-2' is a String\".colorize(:magenta)\n sleep(1)\n puts \"See the difference??\"\n sleep(2.5)\n puts \"Something that commonly gets confused with Integers are Floats\"\n sleep(3)\n puts \"Floats are similar to Integers but instead of being whole numbers\"\n sleep(2)\n puts \"They are decimal place numbers\"\n sleep(1.5)\n puts \"299.1 is a Float\".colorize(:light_green)\n sleep(1)\n puts \"299 is an Integer\".colorize(:cyan)\n sleep(1.5)\n puts \"2.0 is a Float\".colorize(:light_green)\n sleep(1)\n puts \"2 is an Integer\".colorize(:cyan)\n sleep(3.5)\n puts \"They are similar but not the same\"\n sleep(2.5)\n puts \"Another common Data type is Boolean\"\n sleep(2)\n puts \"Boolean just means true or false - for example: \"\n sleep(1.5)\n afraid = prompt.select(\"You are afraid of spiders\".colorize(:green), %w(True False))\n\n if afraid == \"True\"\n user.afraidOfSpiders = true\n else\n user.afraidOfSpiders = false\n end\n\n sleep(1)\n puts \"Awesome so that would look like\"\n sleep(2)\n puts \"Afraid_of_spiders = #{user.afraidOfSpiders}\".colorize(:blue)\n end", "def security_type\n SecurityType.find_by_type self[:type]\n end", "def user\n return unless user_id && user_type\n return @user if instance_variable_defined?('@user')\n\n @user = user_type.constantize.find_by(id: user_id)\n end", "def person_type\n \"Member\"\n end", "def flagged_by\n if user_id.nil?\n return \"system\"\n else\n return User.find_name(user_id)\n end\n end", "def user_set_to_default_app_type\n return if @current_user.app_type_valid?\n\n current_user.app_type_id = all_user_app_type_ids.first\n current_user.save\n end", "def index\n check_user\n if @user['u_type'] == 1\n @users = User.all\n elsif @user['u_type'] == 2\n @users = User.where.not(u_type: [1])\n end\n\n end", "def instructor_or_student\n user_type = PROMPT.select(\"Are you a Student or Instructor?\", \n [\"Student\",\"Instructor\"])\nend", "def check_and_set_model_type\n if %w[user organisation project].include? params[:type]\n @type = params[:type]\n case @type\n when 'organisation'\n @model_object = Organisation.find(params[:id])\n when 'project'\n @model_object = Project.find(params[:id])\n when 'user'\n users_organisation = UsersOrganisation.find_by(organisation_id: params[:id])\n @model_object = current_user\n redirect_to :root unless users_organisation.user_id == current_user.id\n end\n else\n redirect_to :root\n end\n end", "def sid_type=(stype)\n if stype.is_a?(String)\n @sid_type = stype.downcase\n else\n case stype\n when Admin::SidTypeUser\n @sid_type = 'user'\n when Admin::SidTypeGroup\n @sid_type = 'group'\n when Admin::SidTypeDomain\n @sid_type = 'domain'\n when Admin::SidTypeAlias\n @sid_type = 'alias'\n when Admin::SidTypeWellKnownGroup\n @sid_type = 'well_known_group'\n when Admin::SidTypeDeletedAccount\n @sid_type = 'deleted_account'\n when Admin::SidTypeInvalid\n @sid_type = 'invalid'\n when Admin::SidTypeUnknown\n @sid_type = 'unknown'\n when Admin::SidTypeComputer\n @sid_type = 'computer'\n else\n @sid_type = 'not_found'\n end\n end\n end", "def set_user_iconable\n unless params[:context_type].nil?\n @user_iconable = context_object( :include => :user_icons )\n end\n end", "def type\n return nil if checktype.nil?\n checktype.name \n end", "def check_user(user)\r\n user = Arango::User.new(user: user) if user.is_a?(String)\r\n return user\r\n end" ]
[ "0.7675585", "0.75585", "0.7380855", "0.72564244", "0.725392", "0.71342456", "0.71238893", "0.70644027", "0.7029367", "0.69523215", "0.68518215", "0.6832593", "0.6791029", "0.67834175", "0.6770133", "0.67578083", "0.6734221", "0.67315376", "0.67299163", "0.67034715", "0.6701126", "0.6689629", "0.66441053", "0.6641895", "0.6641895", "0.66268027", "0.6621128", "0.6588753", "0.6564167", "0.6564167", "0.65511405", "0.6532539", "0.6474062", "0.64440286", "0.6326536", "0.6318315", "0.6301201", "0.6289407", "0.6285699", "0.6283802", "0.62469", "0.61912805", "0.61830765", "0.613583", "0.61174035", "0.60866976", "0.60858876", "0.60695875", "0.60677373", "0.6066742", "0.6041104", "0.5986839", "0.5971756", "0.59309494", "0.59146893", "0.59110105", "0.5899527", "0.5898674", "0.58935386", "0.5888627", "0.5887575", "0.58680266", "0.5865572", "0.5852003", "0.58168024", "0.5807729", "0.58039105", "0.58034813", "0.5803125", "0.5801271", "0.57951957", "0.5784691", "0.5777097", "0.57723385", "0.57692987", "0.57643205", "0.5751661", "0.574604", "0.5744319", "0.57404166", "0.5735815", "0.57038176", "0.5702429", "0.56814784", "0.56709266", "0.56656003", "0.56591827", "0.5645473", "0.5645208", "0.5626616", "0.5625343", "0.562265", "0.5613427", "0.5610455", "0.5608121", "0.55974215", "0.5596718", "0.55947715", "0.55872333", "0.55695975" ]
0.71222055
7
Renames the Service type from "type" to "service_type" to avoid conflicts
def rename_service_type(hash) hash["service_type"] = hash["type"] hash.delete("type") hash end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def service_name\n raise TypeError, 'no type on this reply' unless\n instance_variable_defined? :@type\n\n @type.split('.').first.sub '_', ''\n end", "def service_type_name\n \"\" \n end", "def set_service_type\n @service_type = ServiceType.find(params[:id])\n end", "def _service_type\n self.class.service_type\n end", "def update!(**args)\n @service_type = args[:service_type] if args.key?(:service_type)\n end", "def service_name\n self[:name].gsub(/\\.|,/, '_').gsub(/\\s/, '').underscore.to_sym if self[:name]\n end", "def fix_unknown_service\n new_services = Types::Base.new\n services.each do |service_name, service|\n unless data_types[service_name]\n service.operations.each do |operation_name, operation|\n if data_types[operation.request]\n new_services[operation.request] ||= Types::Base.new( :operations => {} )\n new_services[operation.request].operations[operation_name] = operation\n elsif data_types[operation.response]\n new_services[operation.response] ||= Types::Base.new( :operations => {} )\n new_services[operation.response].operations[operation_name] = operation\n end\n end\n end\n end\n services.merge!(new_services)\n end", "def set_service_type\n @category = Category.find(params[:category_id])\n @service_type = ServiceType.find(params[:id])\n end", "def service_type\n return nil unless self.service_type_id \n ServiceType.find(self.service_type_id)\n end", "def service_name(name)\n verify_subclass!\n key_name = name.to_sym\n raise DuplicateNameError, \"The service #{self.name} is trying to define a service_name of #{name} when it has already been defined by #{all_services[key_name].klass.name}\" if all_services.has_key?(key_name)\n\n # remove the old entry\n all_services.delete(service_description.name) if service_description.present?\n\n self.service_description ||= ServiceDescription.new\n service_description.update(key_name, self)\n\n # save off reference\n all_services[service_description.name] = service_description\n end", "def service_type_name\n \"REST\"\n end", "def service_naming(service, new_service_name=nil, new_service_description)\n log(:info, \"Processing service_naming...\", true)\n unless new_service_name.blank?\n log(:info, \"Changing Service name: #{service.name} to #{new_service_name}\")\n else\n new_service_name = \"#{service.name}-#{Time.now.strftime('%Y%m%d-%H%M%S')}\"\n log(:info, \"Changing Service name: #{service.name} to #{new_service_name}\")\n end\n service.name = new_service_name\n unless new_service_description.blank?\n log(:info, \"Changing Service description from #{service.description} to #{new_service_description}\")\n service.description = new_service_description\n end\n log(:info, \"Processing service_naming...Complete\", true)\n end", "def update_service(service_name, new_value)\n self.services[service_name.to_s] = new_value\n self.update_attribute :services, self.services\n end", "def normalize_type\n if self.type.present?\n self.type = self.type.to_s.underscore.strip\n end\n end", "def service_type_name(account_name, name)\n map_opts = get_acct_catalog_map(account_name)\n case map_opts[:provider]\n when \"hp\"\n service_name = name\n unless map_opts[:catalog].nil?\n service_catalog_key = name.to_s.downcase.gsub(' ','_').to_sym\n service_name = map_opts[:catalog][service_catalog_key] if map_opts[:catalog].has_key?(service_catalog_key)\n end\n return service_name\n else\n return name\n end\n end", "def service_class_for( entity_type )\n entity_map_cache[ entity_type.to_sym ]\n end", "def wsdl_constantize(type)\n type = type.split(':').last\n type = 'int' if %w[long short byte].include?(type)\n type = 'float' if type == 'double'\n type = 'binary' if type == 'base64Binary'\n type = 'ManagedObject' if type == 'ManagedObjectReference'\n\n type = type.camelcase\n type.safe_constantize || \"RbVmomi::BasicTypes::#{type}\".safe_constantize || \"#{wsdl_to_rbvmomi_namespace(@wsdl)}::#{type}\".safe_constantize\n end", "def set_service\n @service = Service.find(params[:id])\n @service = @service.becomes(@service.type.constantize) if @service.valid?\n @service.current_request = request\n end", "def resolve_service_type(service_type, residential)\n if residential && (service_type == ServiceTypes::FEDEX_GROUND)\n ServiceTypes::GROUND_HOME_DELIVERY\n else\n service_type\n end\n end", "def set_type\n new_type = [sport.name, \"Infrastructure\"].join('')\n\n begin\n new_type.constantize\n self.type = new_type\n rescue NameError\n self.type = nil\n end\n\n end", "def type_name\n @type_name ||= self.name.demodulize.underscore\n end", "def set_counter_service_type\n @counter_service_type = CounterServiceType.find(params[:id])\n end", "def type(type = nil)\n @type = type if type\n @type || name.split('::').last.gsub(/Resource$/, '').underscore\n end", "def fix_person_type\n self.person_type = self.person.class.name\n end", "def service_types\n get_info :service_types\n end", "def service_name=(value)\n @service_name = value\n end", "def changeType(newType)\n\t\t\t#remove accessors for old type\n\t\t\tremoveAccessors()\n\t\t\t@type = newType\n\n\t\t\t#produce accessors for the newly set type\n\t\t\tproduceAccessors()\n\t\tend", "def service_types_generated\n [\n ServiceTypeValue['fulltext'],\n ServiceTypeValue['holding'],\n ServiceTypeValue['highlighted_link'],\n ServiceTypeValue['disambiguation'],\n ServiceTypeValue['site_message']\n ]\n end", "def service_naming(service, dialogs_tags_hash, dialogs_options_hash)\n log(:info, \"Processing service_naming...\", true)\n new_service_name = dialogs_options_hash[0][:dialog_service_name] rescue nil\n new_service_description = dialogs_options_hash[0][:dialog_service_description] rescue nil\n\n if new_service_name.blank?\n new_service_name = \"#{service.name}-#{Time.now.strftime('%Y%m%d-%H%M%S')}\"\n end\n log(:info, \"Service name: #{new_service_name}\")\n service.name = new_service_name\n\n unless new_service_description.blank?\n log(:info, \"Service description #{new_service_description}\")\n service.description = new_service_description\n end\n log(:info, \"Processing service_naming...Complete\", true)\nend", "def type_name( type )\n @type_name_cache[type] ||= begin\n type = \"\" if type.nil?\n type = $1 if type =~ /^(.*?)\\(/\n type.upcase\n end\n end", "def type_name\n @type_name ||= StringHelpers.underscore(StringHelpers.demodulize(@value.class.name)).to_sym\n end", "def typeclass(type)\n tcmap = {\n 'A' => Resolv::DNS::Resource::IN::A,\n 'PTR' => Resolv::DNS::Resource::IN::PTR,\n 'CNAME' => Resolv::DNS::Resource::IN::CNAME,\n 'MX' => Resolv::DNS::Resource::IN::MX,\n 'SRV' => Resolv::DNS::Resource::IN::SRV,\n }\n raise ArgumentError, 'dns_resource::nsupdate.typeclass invalid type' unless tcmap.keys.include?(type)\n tcmap[type]\n end", "def set_service_info(service, app, app_type)\n @services[service] = {\n 'app' => app,\n 'app_type' => app_type\n }\n\n return unless Datadog::Tracer.debug_logging\n Datadog::Tracer.log.debug(\"set_service_info: service: #{service} app: #{app} type: #{app_type}\")\n end", "def change_type(prev_type, new_type, key)\n require_writeable_layers!\n file = get(prev_type, key)\n store_immediately!(new_type, file)\n layers.immediate.writeable.each do |layer|\n layer.delete(prev_type, key)\n end\n if layers.delayed.writeable.any?\n Dis::Jobs::ChangeType.perform_later(prev_type, new_type, key)\n end\n key\n end", "def service_naming(service, dialogs_options_hash)\n log(:info, \"Processing service_naming...\", true)\n new_service_name = dialogs_options_hash[0][:dialog_service_name] rescue nil\n new_service_description = dialogs_options_hash[0][:dialog_service_description] rescue nil\n\n if new_service_name.blank?\n new_service_name = \"#{service.name}-#{Time.now.strftime('%Y%m%d-%H%M%S')}\"\n end\n log(:info, \"Service name: #{new_service_name}\")\n service.name = new_service_name\n\n unless new_service_description.blank?\n log(:info, \"Service description #{new_service_description}\")\n service.description = new_service_description\n end\n log(:info, \"Processing service_naming...Complete\", true)\nend", "def service_type_params\n params.require(:service_type).permit(:name)\n end", "def build_service\n {'Code' => SERVICE_TYPES[@opts[:service_type]]}\n end", "def type=(new_type)\n @type = new_type.to_sym\n end", "def service_name; end", "def service_types_generated \n types = [ ServiceTypeValue[:fulltext], ServiceTypeValue[:holding], ServiceTypeValue[:table_of_contents], ServiceTypeValue[:relevant_link] ]\n \n return types\n end", "def parse_inst_type(type)\n return type.downcase.gsub(\"_\", \".\")\n end", "def service_key\n (is_a?(Module) ? name : self.class.name).demodulize.underscore.to_sym\n end", "def service_key\n (is_a?(Module) ? name : self.class.name).demodulize.underscore.to_sym\n end", "def _update(type, current_name, metadata={})\n type = type.to_s.camelize\n request :update do |soap|\n soap.body = {\n :metadata => {\n :current_name => current_name,\n :metadata => prepare(metadata),\n :attributes! => { :metadata => { 'xsi:type' => \"ins0:#{type}\" } }\n }\n }\n end\n end", "def type_name\n @type_name ||= name.underscore\n end", "def set_type_name\n @type_name = TypeName.find(params[:id])\n end", "def type=(type)\n @type = type.to_sym\n end", "def sort_services(service_data)\n services = {}\n\n service_data[\"services\"].each do |service|\n service_type = service[\"type\"]\n if services[service_type].nil?\n services[service_type] = [service]\n else\n services[service_type] << service\n end\n end\n return services\n end", "def type= new_type\n @gapi.update! type: verify_type(new_type)\n end", "def set_property_service_type\n @property_service_type = PropertyServiceType.find(params[:id])\n end", "def set_type\n @type = controller_name.classify\n end", "def set_type\n @type = controller_name.classify\n end", "def remove_type(column_with_type)\n column_with_type.sub(/\\((\\w+)\\)::\\w+/, '\\1')\n end", "def MapOracleToOSSCR_RelationshipSubjObjType(type)\n type.gsub!(\"PERSON\",\"INDIVIDUAL\") if (type==\"PERSON\")\n type.gsub!(\"ORGANIZATION\",\"INSTITUTION\") if (type==\"ORGANIZATION\")\n return type\nend", "def initialize\n @type = self.class.to_s.demodulize.downcase\n end", "def get_ai_service_base_name(options)\n service_base_name = options['service']\n if service_base_name.match(/i386|sparc/)\n service_base_name = service_base_name.gsub(/i386/,\"\")\n service_base_name = service_base_name.gsub(/sparc/,\"\")\n service_base_name = service_base_name.gsub(/_$/,\"\")\n end\n return service_base_name\nend", "def set_Service(value)\n set_input(\"Service\", value)\n end", "def service_name=(_arg0); end", "def revert_generic_type( type )\n case type\n when /\\Avarchar/\n return :String, :default_size => 255\n when /\\Achar/\n return :String, :fixed => true, :default_size => 255\n when /\\Atext\\z/\n return :String, :text => true\n when /\\A(\\w+)\\([\\s\\d,]+\\)\\z/\n return $1.to_sym\n when /\\A\\w+\\z/\n return type.to_sym\n end\n end", "def type_key\n type.demodulize.underscore\n end", "def service_name_full\n fix_namespace api, \"#{main_service.service_name_full}::Rest\"\n end", "def name\n type.to_s.capitalize\n end", "def type=(type)\n type = type.intern\n super type\n end", "def set_grocer_service_type\n @grocer_service_type = GrocerServiceType.find(params[:id])\n end", "def remap_resource_type\n return unless is_a?(Bulkrax::CsvFileSetEntry)\n\n parsed_metadata.delete('resourceType_attributes')\n parsed_metadata['resource_type'] = raw_metadata['resourcetype']&.split(/\\s*[|]\\s*/)\n end", "def type_name_resolver; end", "def es_type_name\n self.name.pluralize.downcase\n end", "def authentication_service_type=(authentication_service_type)\n validator = EnumAttributeValidator.new('String', [\"AuthAnvil\", \"GoogleAuthenticator\"])\n unless validator.valid?(authentication_service_type)\n fail ArgumentError, \"invalid value for 'authentication_service_type', must be one of #{validator.allowable_values}.\"\n end\n @authentication_service_type = authentication_service_type\n end", "def service_name(name)\n @name = name\n end", "def add_service_name(current_string)\n add_if_present(@service_name, current_string, \" #{@service_name}\")\n end", "def changeMetadataType\n begin\n old_type = params[:metadatatypename].to_s.strip.downcase\n new_type = params[:new_metadata_type].to_s.strip.downcase\n puts \"old_t: \" + old_type\n puts \"new_t: \" + new_type\n\n if old_type == \"\"\n render :text => \"Type of metadata not given\", :status => 404\n return\n end\n\n if new_type == \"\"\n render :text => \"Type of new metadata not given\", :status => 404\n return\n end\n\n # Find old metadata type\n @metadatatype = MetadataType.find_by_name(old_type)\n\n # If old metadata type was not found\n if @metadatatype == nil\n render :text => \"Old metadata type not found\", :status => 404\n return\n end\n\n # Check that new type doesn't exist already\n # @@existing_metadata_types listed in the beginning of file\n if MetadataType.find_by_name(new_type) or @@existing_metadata_types.include?(new_type)\n render :text => \"Type of new metadata already exists\", :status => 404\n return\n end\n\n # Change metadata type name\n @metadatatype.update_attribute(:name, new_type)\n render :text => \"Metadata type changed\", :status => 200\n return\n\n rescue => e\n puts \"Error in changing metadatatype: #{e.to_s}\".background(:red)\n render :text => \"Conflict\", :status => 409\n return\n end\n end", "def read_service_types()\n types = []\n @client.services.each do |type|\n types << type.label\n end\n\n types\n end", "def update\n @service_type = ServiceType.find(params[:id])\n\n respond_to do |format|\n if @service_type.update_attributes(params[:service_type])\n format.html { redirect_to @service_type, notice: 'Service type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @service_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def service_code\n \"#{shipment_mode_code}#{service_type_code}#{services_code}\"\n end", "def type\n _type.split(\"::\").last.downcase\n end", "def service=(value)\n @service = value\n end", "def update_page_name\n if self.service_id.present?\n self.name = \"#{self.title} (#{self.service.name})\"\n else\n self.name = self.title\n end\n end", "def basic_service_name\n return @basic_service_name if @basic_service_name\n basic_service_name = name\n basic_service_name = service_name unless name_equals_title?\n if basic_service_name.start_with? 'p_'\n basic_service_name = basic_service_name.gsub(/^p_/, '')\n end\n debug \"Using '#{basic_service_name}' as the basic service name for the primitive '#{name}'\"\n @basic_service_name = basic_service_name\n end", "def service_name=(service_name)\n allowed_values = [\"ContactCenter\", \"ContentManagement\", \"PeoplePermissions\", \"Quality\", \"LanguageUnderstanding\", \"TopicsDefinitions\", \"PredictiveEngagement\", \"WorkforceManagement\", \"Triggers\", \"ResponseManagement\"]\n if service_name && !allowed_values.include?(service_name)\n fail ArgumentError, \"invalid value for 'service_name', must be one of #{allowed_values}.\"\n end\n @service_name = service_name\n end", "def type_name=(val)\n self['type_name'] = val\n end", "def service(name)\n \"#{SERVICE_NAME} #{name}\"\n end", "def service(nickname, reserved, distribution, type)\n end", "def type\n @types ||= strip(:type)\n end", "def get_service_types\n if @servicetypes.any?\n @servicetypes.flat_map(&:servicetype).compact\n elsif @servicetype\n [@servicetype]\n else\n []\n end\n end", "def type\n self.class.to_s.split('::').last.downcase.to_sym\n end", "def my_type(type)\n case type\n when /bond/i\n \"Bonds\"\n when /stock/i\n \"Stocks\"\n when /alternative/i\n \"Alternatives\"\n else\n \"Unclassified\"\n end\n end", "def set_service_song_type\n @service_song_type = ServiceSongType.find(params[:id])\n end", "def get_type(type)\n TYPES[type.downcase]\n end", "def service\n self.original_service or Service.find_by_name(\"FieldStatus\")\n end", "def change_type\n\t\t\trender json: User.update_type_by_id(params[:id], params[:type], params[:is])\n\t\tend", "def format_service\n\n end", "def service_start_type(service_name)\n start_type = nil\n open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG) do |service|\n query_config(service) do |config|\n start_type = SERVICE_START_TYPES[config[:dwStartType]]\n end\n end\n # if the service has type AUTO_START, check if it's a delayed service\n if start_type == :SERVICE_AUTO_START\n open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG) do |service|\n query_config2(service, SERVICE_CONFIG_DELAYED_AUTO_START_INFO) do |config|\n return :SERVICE_DELAYED_AUTO_START if config[:fDelayedAutostart] == 1\n end\n end\n end\n if start_type.nil?\n raise Puppet::Error.new(_(\"Unknown start type '%{start_type}' for '%{service_name}'\") % { start_type: start_type.to_s, service_name: service_name})\n end\n start_type\n end", "def name_and_id_from_options(options, type) #:nodoc:\n options[:name] = (options[:prefix] || DEFAULT_PREFIX) + (options[:discard_type] ? '' : \"[#{type}]\")\n options[:id] = options[:name].gsub(/([\\[\\(])|(\\]\\[)/, '_').gsub(/[\\]\\)]/, '').gsub(/\\./, '_').gsub(/_+/, '_')\n end", "def set_service_type_master\n @service_type_master = ServiceTypeMaster.find(params[:id])\n end", "def service\n @service ||=\n if (c = self_class)\n name = c.safe_const_get(:SERVICE_NAME)\n name ||= c.module_parent_name.underscore.remove(/_service$/)\n name&.to_sym || super\n end\n end", "def service=(service)\n @service = service\n end", "def set_type\n end", "def name_and_id_from_options(options, type) #:nodoc:\n options[:name] = (options[:prefix] || DEFAULT_PREFIX) + (options[:discard_type] ? '' : \"[#{type}]\")\n options[:id] = options[:name].gsub(/([\\[\\(])|(\\]\\[)/, '_').gsub(/[\\]\\)]/, '').gsub(/\\./, '_').gsub(/_+/, '_')\n end", "def add_to_services(name, type, description)\n data = {\n 'OS-KSADM:service' => {\n 'name' => name,\n 'type' => type,\n 'description' => description\n }\n }\n return post_request(address(\"/OS-KSADM/services\"), data, token())\n end", "def parse_svc_offering_type(service_offering)\n job_type = service_offering.extra[:type] if service_offering.extra.present?\n\n raise \"Missing service_offering's type: #{service_offering.inspect}\" if job_type.blank?\n job_type\n end" ]
[ "0.6752241", "0.6633492", "0.6623655", "0.65550786", "0.6356624", "0.6350679", "0.6260855", "0.61445904", "0.6143448", "0.61054903", "0.6100868", "0.6057287", "0.5906334", "0.58981097", "0.58810383", "0.58692807", "0.5853573", "0.5847273", "0.5810481", "0.5793755", "0.57255083", "0.57165366", "0.57073927", "0.57065135", "0.56985843", "0.5690877", "0.56671256", "0.5655463", "0.5654023", "0.56356996", "0.5615723", "0.5607903", "0.5586401", "0.55784345", "0.5577145", "0.5557888", "0.5538833", "0.5538802", "0.55324525", "0.55233717", "0.5515664", "0.55135924", "0.55135924", "0.5507696", "0.5506149", "0.55015355", "0.54965496", "0.5492192", "0.54622763", "0.54470974", "0.5434785", "0.5434785", "0.5424468", "0.5421798", "0.5413796", "0.54079926", "0.5406706", "0.5404706", "0.5385292", "0.5373985", "0.53594637", "0.53576684", "0.5341797", "0.53372234", "0.53350395", "0.53349155", "0.53322816", "0.5324497", "0.5323613", "0.5285285", "0.52777493", "0.5277283", "0.52749026", "0.52734184", "0.5259154", "0.52472216", "0.5245999", "0.5243718", "0.5242869", "0.52414894", "0.52373487", "0.52348536", "0.5219675", "0.5207349", "0.5206842", "0.52047193", "0.5192561", "0.5187068", "0.51832914", "0.5182105", "0.51806945", "0.5180245", "0.51795256", "0.51684964", "0.5168249", "0.51680285", "0.51638734", "0.5163415", "0.5162943", "0.5156093" ]
0.8576102
0
Create a new successful response
def success(output) respond_with(Response::Success, output) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_success_response\n response = {\n body: {\n status: \"ok\"\n },\n status: 200\n }\n return response\n end", "def new_response\n {:success => true}\n end", "def create_success_response(message='')\n message = message.present? ? message : 'ok'\n response = {\n body: {\n status: message\n },\n status: 200\n }\n return response\n end", "def build_response\n { status: :success, data: {} }\n end", "def return_success(response)\n {\n 'status' => OK,\n 'response' => response\n }\n end", "def succes_response\n {\n status: 'success'\n }\n end", "def sample_create_account_response(success)\n if success\n raw_response = OpenStruct.new(\n parsed_response: {\n \"success\"=>true,\n \"account\"=> {\n \"identifier\"=>\"asdfasdfasdf\",\n \"email\"=>\"asdfasdf@asdfasdf.com\",\n \"customer\"=>\"bonusly\",\n \"available_balance\"=>0\n }\n },\n code: 200\n )\n else\n raw_response = OpenStruct.new(\n parsed_response: {\n \"success\"=>false,\n \"error_message\"=>\"The account already exists for the platform.\"\n },\n code: 403\n )\n end\n Tangocard::Response.new(raw_response)\n end", "def create_response(request)\n response = Response.new\n end", "def response_created(data = {})\n render status: 201, json: data\n end", "def success\n [200, { 'Content-Type' => 'text/plain'}, ['OK']]\n end", "def create_response(response)\r\n\r\n#\r\n#\tSetup default response values.\r\n#\r\n message = nil\r\n authorization = nil\r\n success = false\r\n exception = nil\r\n#\r\n#\tExtract key elements from the response.\r\n#\r\n reasonCode = response.Get(RocketGate::GatewayResponse::REASON_CODE);\r\n message = @@response_codes[('r' + reasonCode).to_sym] || \"ERROR - \" + reasonCode\r\n responseCode = response.Get(RocketGate::GatewayResponse::RESPONSE_CODE);\r\n if ((responseCode != nil) && (responseCode == \"0\"))\r\n success = true; # Transaction succeeded\r\n authorization = response.Get(RocketGate::GatewayResponse::TRANSACT_ID);\r\n else\r\n exception = response.Get(RocketGate::GatewayResponse::EXCEPTION);\r\n end\r\n\r\n#\r\n#\tExtract values that are not dependent up success/failure.\r\n#\r\n avsResponse = response.Get(RocketGate::GatewayResponse::AVS_RESPONSE)\r\n cvv2Response = response.Get(RocketGate::GatewayResponse::CVV2_CODE)\r\n fraudResponse = response.Get(RocketGate::GatewayResponse::SCRUB_RESULTS)\r\n\r\n#\r\n#\tCreate the response object.\r\n#\r\n card_hash = response.Get(RocketGate::GatewayResponse::CARD_HASH)\r\n Response.new(success, message, {:result => responseCode, :exception => exception, :card_hash => card_hash},\r\n :test => test?,\r\n :authorization => authorization,\r\n :avs_result => {:code => avsResponse},\r\n :cvv_result => cvv2Response,\r\n :fraud_review => fraudResponse\r\n )\r\n end", "def success\n {:response=>:success}\n end", "def send\n http_response.code == 201\n end", "def create\n json authentication_response, :status => authentication_response_status\n end", "def create_response(response, first_response=nil)\n message = message_from(response)\n\n # This allows the second response to grab the auth info from the first\n first_response ||= response\n\n Response.new(!response.has_key?(:ErrCode), message, response,\n :test => test?,\n # The AccessPass and AccessID are used for all alterations to a\n # transaction, so we store that as the authorization instead of TranID\n :authorization => \"#{first_response[:AccessID]}-#{first_response[:AccessPass]}\"\n )\n end", "def after_create_response(success)\n if success\n flash[:notice] = t('muck.services.oai_endpoint_successfully_created')\n respond_to do |format|\n format.html { redirect_to oai_endpoint_path(@oai_endpoint) }\n format.pjs { redirect_to oai_endpoint_path(@oai_endpoint, :layout => 'popup') }\n format.json { render :json => @oai_endpoint.as_json }\n format.xml { head :created, :location => oai_endpoint_url(@oai_endpoint) }\n end\n else\n respond_to do |format|\n format.html { render :template => \"oai_endpoints/new\" }\n format.pjs { render :template => \"oai_endpoints/new\", :layout => false }\n format.json { render :json => @oai_endpoint.as_json }\n format.xml { render :xml => @oai_endpoint.errors.to_xml }\n end\n end\n end", "def handle_post\n make_response(201, {message: 'New resource created'})\nend", "def ok(response)\n [200, headers, [response]]\n end", "def initialize success, body\n @success = success || false\n @body = body.fetch('RESPONSE', {})\n end", "def make_response(status, body)\n {\n statusCode: status,\n body: JSON.generate(body)\n }\nend", "def create\n @response = Verify::Response.translate(saml_response: params[\"SAMLResponse\"], request_id: session[:verify_request_id], level_of_assurance: \"LEVEL_2\")\n report_redacted_response\n if @response.verified?\n parser = Claim::VerifyResponseParametersParser.new(@response.parameters)\n current_claim.update!(parser.attributes)\n redirect_to claim_url(current_policy_routing_name, \"verified\")\n else\n redirect_to verify_path_for_response_scenario(@response.scenario)\n end\n end", "def make_response(status, body)\r\n {\r\n statusCode: status,\r\n body: JSON.generate(body)\r\n }\r\nend", "def make_response(status, body)\n {\n statusCode: status,\n body: JSON.generate(body)\n }\nend", "def make_response(status, body)\n {\n statusCode: status,\n body: JSON.generate(body)\n }\nend", "def create\n @response = Verify::Response.translate(saml_response: params[\"SAMLResponse\"], request_id: session[:verify_request_id], level_of_assurance: \"LEVEL_2\")\n if @response.verified?\n current_claim.update!(@response.claim_parameters)\n redirect_to claim_url(\"verified\")\n else\n redirect_to verify_path_for_response_scenario(@response.scenario)\n end\n end", "def create_Found_Response(request_path)\n\tbody = File.read(request_path)\n\tinitial = generic_Generate_Initial(200)\n\theaders = generic_Generate_Headers(body)\n\tgeneric_Generate_Response(initial,headers,body)\nend", "def check_response!(response, object_name)\n if response.status.success?\n puts \" - Created #{object_name}\"\n else\n puts \" - Failed to create #{object_name}\"\n exit 1\n end\nend", "def create_resource_response(resource)\n respond_to do |format|\n if resource.save\n format.html { redirect_to resource, notice: \"#{resource.class.name.titlecase} was successfully created.\" }\n format.json { render action: 'show', status: :created, location: resource }\n else\n resource_response_error(resource, :new, format)\n end\n end\n end", "def create\n @response = event_user.responses.new(response_params)\n new_was_successful = @response.save\n\n respond_with [event_user, @response] do |format|\n format.html{\n if new_was_successful\n redirect_to(event_users_path, :notice => 'The Response was created')\n else\n render 'new', :notice => 'Some input was not valid.'\n end\n }\n end\n end", "def ok_response\n {\n statusCode: 200,\n headers: {'Content-Type': 'application/json'},\n body: {ok: true}.to_json\n }\nend", "def build_success_output(data)\n\t \t{data: data, code: 200, result: \"success\"}\n\t end", "def build_success_result\n result = {success: true, error_message: \"\"}\n end", "def _success(data,code)\n status code\n response.headers['Content-Type'] = 'application/json'\n body(data.to_json)\n end", "def create\n @response = Response.new(response_params)\n\n @response.user_id = @current_user.id\n\n if @response.title.to_s == \"\" || @response.language.to_s == \"\" || @response.industry.to_s == \"\" || @response.level.to_s == \"\" || @response.avatar.to_s == \"\" || @response.response_type.to_s == \"\"\n return redirect_to new_response_path, notice: \"Please fill in all required fields\"\n end\n\n # data = {:message => @response, :status => \"false\"}\n # return render :json => data, :status => :ok\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to responses_path, notice: 'Response was successfully created.' }\n format.json { render :show, status: :created, location: @response }\n else\n # data = {:message => @response.errors, :status => \"false\"}\n # return render :json => data, :status => :ok\n format.html { render :new }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def intitiate_response_object \n response_object = Hash.new\n response_object[:status] = \"failure\"\n response_object[:statusCode] = 500\n response_object[:response] = \"\"\n response_object[:message] = \"The server encountered an unexpected condition which prevented it from fulfilling the request\"\n return response_object\n end", "def handle_post()\n make_response(201, \"New resource created\")\nend", "def create_response(sender, options={}, force=false)\n response = nil\n if force || allows_response?(sender)\n response = self.responses.create(response_options(sender, options))\n response.activate! if response.valid?\n end\n response\n end", "def success_response(api_response, response)\n @response_details = response[:create_pickup_reply]\n end", "def success() Success.new(id) end", "def response_factory(data)\n\t\t\t\t\t\treturn Response.new(data)\n\t\t\t\t\tend", "def create_b2bua_response(session, orig_response=session.iresponse)\n peer_session = get_peer_session(session)\n if peer_session\n r = peer_session.create_response(orig_response.code)\n r.copy_from(orig_response, :content, :content_type, :path, :service_route, :privacy, :warning)\n return r\n else\n @ilog.warn(\"No peer session found, cannot create the response\") if @ilog.warn?\n raise \"Unable to create response\"\n end \n end", "def make_response(status, body)\n {\n statusCode: status,\n body: JSON.pretty_generate(body)\n }\nend", "def _create_http_response(mock_response, code, message)\n mock_response.stub!(:code).and_return(code)\n mock_response.stub!(:message).and_return(message)\n mock_response.stub!(:is_a?).and_return(true) if [\"200\", \"201\"].member?(code)\nend", "def success_response(api_response, response)\n @response_details = response[:envelope][:body][:create_pickup_reply]\n end", "def success_response code, meta, data\n render status: code,\n json: {\n meta: meta,\n data: data\n }\n end", "def respond_for usecase, &block\n resp = {\n object: usecase.build_object,\n errors: usecase.errors,\n message: usecase.errors? ? \"Error\" : \"Success\"\n }\n if block_given?\n pp yield(resp)\n end\n Response.new( resp )\n end", "def create\n @response = @bbs_thread.responses.build(response_params)\n\n respond_to do |format|\n if @response.save\n write_session\n\n format.html { redirect_to bbs_thread_path(@bbs_thread.id), notice: t('notice.response.create') }\n format.json { render :show, status: :created, location: @bbs_response }\n else\n format.html { redirect_to bbs_thread_path(@bbs_thread.id), alert: @response.errors.full_messages }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @response = Response.new(response_params)\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to @response, notice: 'Response was successfully created.' }\n format.json { render action: 'show', status: :created, location: @response }\n else\n format.html { render action: 'new' }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @response = Response.new(response_params)\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to @response }\n format.json { render :show, status: :created, location: @response }\n else\n format.html { render :new }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_response\n\t\t@response = Response.create(player_id: current_player.id, option_id: params[:option])\n\t\t@question = @response.option.question\n\t\t@total_questions = @question.artist.questions.count\n\t\t@answered = params[:correct].to_i\n\t\tif (@response.option.correct) && (@answered < @total_questions) \n\t\t\t@answered += 1\n\t\t\tredirect_to category_artist_path(last_question: @question.id, correct: @answered,\n\t\t\tcategory_id: @question.artist.category.id, id: @question.artist.id)\n\t\telsif @response.option.correct\n\t\t\tredirect_to category_path(@question.artist.category)\n\t\telse\n\t\t\tartist = @response.option.question.artist\n\t\t\tredirect_to category_path(artist.category), notice: \"Sorry try again!\"\n\t\tend\n\tend", "def success_object\n {:success => true}\n end", "def ok; @status = 200 end", "def ok; @status = 200 end", "def success_response(data={}, opts={})\n status = opts.delete(:status) || 200 # Status code is 200 by default\n \n {\n status: status,\n json: {\n status: \"success\",\n data: data\n }\n }\n end", "def create\n @response = Response.new\n \n reason = Reason.new\n reason.why = params[:response][:reason][:why]\n reason.critique = params[:response][:reason][:critique]\n @response.reasons = [reason]\n\n @response.who = params[:response][:who]\n @response.ip_address = request.remote_ip\n @response.user_agent = request.env['HTTP_USER_AGENT']\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to root_url, notice: 'Your response was successfully submitted! Thanks for taking the time to affect change in our government.' }\n format.json { render json: @response, status: :created, location: @response }\n else\n format.html { render action: \"new\" }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @response = current_user.responses.build(response_params)\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to session.delete(:return_to), notice: 'Response was successfully created.' }\n else\n format.html { redirect_to requests_path, notice: 'Response was not saved.' }\n end\n end\n end", "def generic_Generate_Response(initial,headers,body)\n\ts=initial\n\ts << \"\\r\\n\" << headers # headers start in second line\n\tif body.length>0\n\t\ts << \"\\r\\n\" << body # body start after a blank line, first \\r\\n is for change line from headers, second is for blank line\n\tend\n\treturn s\nend", "def create\n @response = Admin::Response.new(params[:admin_response])\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to @response, notice: 'Response was successfully created.' }\n format.json { render json: @response, status: :created, location: @response }\n else\n format.html { render action: \"new\" }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # binding.pry # debug用コマンド\n @response = Response.new(response_params)\n url = request.env[\"HTTP_REFERER\"]\n\n begin\n Response.transaction do\n respond_to do |format|\n if @response.save!\n format.html { redirect_to url, notice: '投稿に成功しました。' }\n format.json { render :show, status: :created, location: @response[:thread_board_id] }\n else\n format.html { redirect_to url, notice: '投稿に失敗しました。' }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end\n rescue => ex\n return redirect_to url, notice: ex.message\n end\n end", "def create_questionnaire_response(data)\n attrs = data.to_h.with_indifferent_access\n response = questionnaire_response_service.create(attrs)\n\n response.tap do |resp|\n if resp.response[:code] == SUCCESS_STATUS\n questionnaire_response.tap do |qr|\n qr.user_uuid = user.uuid\n qr.user_account = user.user_account\n qr.appointment_id = attrs.dig(:appointment, :id)\n qr.questionnaire_response_id = resp.resource.id\n qr.user = user\n qr.questionnaire_response_data = data\n\n qr.save\n end\n end\n end\n end", "def success_from(response)\n response[:status] == :success || response[:status] == :new\n end", "def response(arguments = {})\n Response.new(self, arguments)\n end", "def successful_response_to\n attempts = 0\n loop do\n random_response = yield\n if random_response.success?\n return random_response\n elsif attempts > 2\n raise 'Unable to get a successful response'\n else\n assert_equal 'Declined_(General).', random_response.params.fetch('error')\n attempts += 1\n end\n end\n end", "def generate_response(sha1, last_update)\n if sha1.empty?\n response = {:error => ERROR_MESSAGE}\n else\n response = {:code => {:sha1 => \"#{sha1}\",:updated_at => \"#{last_update}\"}}\n end\n response\n end", "def create\n @response = Response.new(response_params)\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to survey_responses_path(@survey), notice: 'Thanks for your response!' }\n format.json { render :show, status: :created, location: @response }\n else\n format.html { render :new }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def request_successful(response)\n\t\tresponse.code == \"200\"\n\tend", "def create\n @response = Response.new(response_params)\n @response.user = 'Anonymous' if @response.user.nil? or @response.user.empty?\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to root_path, notice: 'Response was successfully created.' }\n format.json { render :show, status: :created, location: @response }\n else\n format.html { render :new }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n question_response = QuestionResponse.build_response_essay(current_user, params)\n\n if question_response.try :save\n render json: { message: \"answer saved\" }\n else\n render json: { message: \"error\" }, status: :unprocessable_entity\n end\n end", "def response\n [ @_status || DEFAULT_RESPONSE_CODE, headers, @_body || DEFAULT_RESPONSE_BODY.dup ]\n end", "def response\n [ @_status || DEFAULT_RESPONSE_CODE, headers, @_body || DEFAULT_RESPONSE_BODY.dup ]\n end", "def build_response(resource_name)\n response = yield\n resource = response_successful?(response) ? resource_name : \"error\"\n\n response_object = Montage::Response.new(response.status, response.body, resource)\n\n set_token(response_object.token.value) if resource_name == \"token\" && response.success?\n\n response_object\n end", "def create\n @response = Response.new(params[:response])\n\n respond_to do |format|\n if @resp.save\n flash[:notice] = 'Response was successfully created.'\n format.html { redirect_to(response_url(@questionnaire, @resp)) }\n format.xml { render :xml => @resp, :status => :created, :location => @resp }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @resp.errors, :status => :unprocessable_entity }\n end\n end\n end", "def render_create_success\n render json: @resource, status: :created\n end", "def test_new_creates_something\n @response = CToolsDirectResponse.new(@@empty_response, Hash.new)\n refute_nil @response, \"get connector object\"\n refute_nil @@testFileDir, \"locate test file directory\"\n end", "def create_response(api_response, errors)\n Rails.logger.error \"#{Time.now} ERRORS: #{errors}\"\n api_response[:code] = 99 if errors.length >= 1\n unless errors.empty?\n long_error = \"\"\n errors.each do |error|\n long_error += \"#{error} \"\n end\n api_response[:result] = long_error\n end\n return api_response\n end", "def mock_success\n head :ok\n end", "def check_for_response_code!(response)\n return if response.status == 201\n\n raise(\n UserEngage::CreateNotSuccessfulException,\n response.body\n )\n end", "def base_response(custom_response={})\n resp = {\n message: nil\n }\n resp.merge!(custom_response)\n status = 200\n [resp, status]\n end", "def create\n @response = Response.new(params[:response])\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to @response, notice: 'Response was successfully created.' }\n format.json { render json: @response, status: :created, location: @response }\n else\n format.html { render action: \"new\" }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def new_response(info_request, incoming_message)\n # Don't use login link here, just send actual URL. This is\n # because people tend to forward these emails amongst themselves.\n url = main_url(incoming_message_url(incoming_message))\n\n @from = contact_from_name_and_email\n headers 'Return-Path' => blackhole_email, 'Reply-To' => @from, # not much we can do if the user's email is broken\n 'Auto-Submitted' => 'auto-generated' # http://tools.ietf.org/html/rfc3834\n @recipients = info_request.user.name_and_email\n @subject = \"New response to your FOI request - \" + info_request.title\n @body = { :incoming_message => incoming_message, :info_request => info_request, :url => url }\n end", "def create\n puts \"\\n\\n\\nBack where I come from\\n\\n\\n\\n\\n\"\n @response = Response.new(response_params)\n puts \"\\n\\n\\n\\n THESE ARE THE RESPONSE PARAMS \\n\\n\\n\\n\"\n puts response_params\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to @response, notice: 'Response was successfully created.' }\n format.json { render action: 'show', status: :created, location: @response }\n else\n format.html { render action: 'new' }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @response = Response.new(response_params)\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to thanks_path, notice: 'Your response was successfully saved.' }\n format.json { render :show, status: :created, location: @response }\n else\n format.html { render :new }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def commit\n data = parse(post)\n Freemium.log_test_msg(\"RESPONSE\\n data: #{data.inspect}\")\n # from BT API: 1 means approved, 2 means declined, 3 means error\n success = data['response'].to_i == 1\n @response = Freemium::Response.new(success, data)\n @response.billing_key = data['customer_vault_id']\n @response.message = data['responsetext']\n return self\n end", "def success?\n @response.code == \"200\"\n end", "def create\n @response = Response.new(response_params)\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to @response, notice: 'Response was successfully created.' }\n format.json { render :show, status: :created, location: @response }\n else\n format.html { render :new }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @response = Response.new(response_params)\n\n respond_to do |format|\n if @response.save\n format.html { redirect_to @response, notice: 'Response was successfully created.' }\n format.json { render :show, status: :created, location: @response }\n else\n format.html { render :new }\n format.json { render json: @response.errors, status: :unprocessable_entity }\n end\n end\n end", "def success_response(objects = {})\n response = SuccessResponse.new\n\n objects.each do |key, value|\n response.add_data(key, value)\n end\n\n response\n end", "def json_success(response_params = {})\n json_response 'success', response_params\n end", "def create_response(request, http_response, body = nil)\n HttpOperationResponse.new(request, http_response, body)\n end", "def success(result)\n Success.new(result)\n end", "def successfully_authenticated\n unless self.ok == true\n self.errors.add(:ok, \"Response must include ok true!\")\n end\n end", "def response_for_offer_create(params)\n {\"response\" => { \"status\" => 1, \"data\" => rand(1_000_000).to_s } }\n end", "def create\n @payment_request = Payment_request.new(payment_request_params)\n new_was_successful = @payment_request.save\n\n respond_with [@payment_request] do |format|\n format.html{\n if new_was_successful\n redirect_to(admin_payment_requests_path, :notice => 'The Payment_request was created')\n else\n render 'new', :notice => 'Some input was not valid.'\n end\n }\n end\n\n end", "def prepare_response(response)\n response\n end", "def generate_response(code, format)\n @message = \"Returning code #{code} in #{format} format\"\n response_data = case format\n when \"txt\"\n content_type 'text/plain'\n @message\n when \"json\"\n content_type 'application/json'\n { message: @message }.to_json\n when \"xml\"\n content_type 'application/xml'\n erb :'status.xml', layout: false\n else\n erb :status\n end\n [code.to_i, response_data]\nend", "def set_response!\n get_responding_methods\n self.responding_object = @responding_object\n if successful?\n self.status_message ||= (@success_message || \"Status: successful\")\n else\n self.status_message ||= (@failure_message || \"Status: unsuccessful\")\n end\n return true\n end", "def handle_create_message(message, obj, response)\n new_name = message[:name] || message[:hrn]\n msg_props = message.properties.merge({ hrn: new_name })\n\n obj.create(message[:type], msg_props, &lambda do |new_obj|\n begin\n response[:res_id] = new_obj.resource_address\n response[:uid] = new_obj.uid\n\n # Getting property status, for preparing inform msg\n add_prop_status_to_response(new_obj, msg_props.keys, response)\n\n if (cred = new_obj.certificate)\n response[:cert] = cred.to_pem_compact\n end\n # self here is the parent\n self.inform(:creation_ok, response)\n rescue => ex\n err_resp = message.create_inform_reply_message(nil, {}, src: resource_address)\n err_resp[:reason] = ex.to_s\n error \"Encountered exception, returning ERROR message\"\n debug ex.message\n debug ex.backtrace.join(\"\\n\")\n return self.inform(:error, err_resp)\n end\n end)\n end", "def API_RESPONSE(status, body)\n JSON.generate({:status => status, :body => body});\nend", "def respond_with(status_code)\n response.status = status_code\n response.write \"\"\n nil\n end" ]
[ "0.8080813", "0.8046698", "0.75259787", "0.7169528", "0.6976638", "0.69230324", "0.6897721", "0.68887573", "0.68688375", "0.6812383", "0.6774347", "0.6754712", "0.6728282", "0.6692494", "0.6669174", "0.6579711", "0.6570765", "0.6559044", "0.65308756", "0.65150386", "0.65105623", "0.64973325", "0.64883727", "0.64883727", "0.6473308", "0.6464209", "0.64585423", "0.6456491", "0.6455189", "0.64348793", "0.64335173", "0.6393877", "0.6378215", "0.637224", "0.63643837", "0.6363163", "0.63615394", "0.63297975", "0.63197803", "0.63131994", "0.6310455", "0.63062143", "0.6292933", "0.62711895", "0.62631947", "0.62604076", "0.62265474", "0.622166", "0.62130183", "0.62009454", "0.6196971", "0.61910516", "0.61910516", "0.6190089", "0.61894494", "0.61725366", "0.61702514", "0.6159985", "0.61584485", "0.61568916", "0.615193", "0.6143851", "0.613965", "0.61357206", "0.61207044", "0.61174524", "0.61151546", "0.6108585", "0.610387", "0.610387", "0.6100611", "0.6098549", "0.60915136", "0.6091477", "0.60895735", "0.60885453", "0.6088021", "0.6081053", "0.60797924", "0.6076893", "0.60763025", "0.6064806", "0.60484904", "0.6036855", "0.6031697", "0.6031697", "0.6030452", "0.6029186", "0.60196996", "0.6018961", "0.60185385", "0.60131055", "0.6011291", "0.59987956", "0.59804136", "0.59604007", "0.5952005", "0.59446526", "0.5938072" ]
0.6431265
32
Create a new failure response
def error(output) respond_with(Response::Failure, output) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def failure\n {:response=>:failure}\n end", "def fail_response(data={})\n status = data.delete(:status) || 400\n {\n status: status,\n json: {\n status: \"fail\",\n data: data\n }\n }\n end", "def create_response(api_response, errors)\n Rails.logger.error \"#{Time.now} ERRORS: #{errors}\"\n api_response[:code] = 99 if errors.length >= 1\n unless errors.empty?\n long_error = \"\"\n errors.each do |error|\n long_error += \"#{error} \"\n end\n api_response[:result] = long_error\n end\n return api_response\n end", "def fail_response(errno, reason)\n n = NaElement.new(\"results\")\n n.attr_set(\"status\", \"failed\")\n n.attr_set(\"reason\", reason)\n n.attr_set(\"errno\", errno)\n n\n end", "def intitiate_response_object \n response_object = Hash.new\n response_object[:status] = \"failure\"\n response_object[:statusCode] = 500\n response_object[:response] = \"\"\n response_object[:message] = \"The server encountered an unexpected condition which prevented it from fulfilling the request\"\n return response_object\n end", "def build_fail_output(data)\n\t \t{data: nil, code: 401, result: \"fail\"}\n\t end", "def failure(message:, statusCode: 404)\n {\n isBase64Encoded: false,\n statusCode: statusCode,\n body: {\n error: message\n }.to_json\n }\nend", "def failure() Failure.new(id) end", "def test_create_fail\n post '/resources'\n assert_equal 400, last_response.status\n last_response.headers['Content-Type'].must_equal 'application/json;charset=utf-8'\n assert_json_match error_message_pattern, last_response.body\n end", "def json_fail(response_params = {})\n json_response 'failed', response_params\n end", "def failure_response(api_response, response)\n error_message = if response[:create_pickup_reply]\n [response[:create_pickup_reply][:notifications]].flatten.first[:message]\n else\n \"#{api_response[\"Fault\"][\"detail\"][\"fault\"][\"reason\"]}\\n--#{Array(api_response[\"Fault\"][\"detail\"][\"fault\"][\"details\"][\"ValidationFailureDetail\"][\"message\"]).join(\"\\n--\")}\"\n end rescue $1\n raise RateError, error_message\n end", "def failure_response errors = [], status = 403, args = {}\n resp = errors.empty? ? {:success => false} : {:success => false, :errors => errors}\n respond_to do |format|\n format.json do\n render({:json => resp, :status => status}.merge(args))\n end\n end\n end", "def failure_response(api_response, response)\n error_message = if response[:envelope][:body][:create_pickup_reply]\n [response[:envelope][:body][:create_pickup_reply][:notifications]].flatten.first[:message]\n else\n \"#{api_response[\"Fault\"][\"detail\"][\"fault\"][\"reason\"]}\\n--#{Array(api_response[\"Fault\"][\"detail\"][\"fault\"][\"details\"][\"ValidationFailureDetail\"][\"message\"]).join(\"\\n--\")}\"\n end rescue $1\n raise RateError, error_message\n end", "def create_response(response)\r\n\r\n#\r\n#\tSetup default response values.\r\n#\r\n message = nil\r\n authorization = nil\r\n success = false\r\n exception = nil\r\n#\r\n#\tExtract key elements from the response.\r\n#\r\n reasonCode = response.Get(RocketGate::GatewayResponse::REASON_CODE);\r\n message = @@response_codes[('r' + reasonCode).to_sym] || \"ERROR - \" + reasonCode\r\n responseCode = response.Get(RocketGate::GatewayResponse::RESPONSE_CODE);\r\n if ((responseCode != nil) && (responseCode == \"0\"))\r\n success = true; # Transaction succeeded\r\n authorization = response.Get(RocketGate::GatewayResponse::TRANSACT_ID);\r\n else\r\n exception = response.Get(RocketGate::GatewayResponse::EXCEPTION);\r\n end\r\n\r\n#\r\n#\tExtract values that are not dependent up success/failure.\r\n#\r\n avsResponse = response.Get(RocketGate::GatewayResponse::AVS_RESPONSE)\r\n cvv2Response = response.Get(RocketGate::GatewayResponse::CVV2_CODE)\r\n fraudResponse = response.Get(RocketGate::GatewayResponse::SCRUB_RESULTS)\r\n\r\n#\r\n#\tCreate the response object.\r\n#\r\n card_hash = response.Get(RocketGate::GatewayResponse::CARD_HASH)\r\n Response.new(success, message, {:result => responseCode, :exception => exception, :card_hash => card_hash},\r\n :test => test?,\r\n :authorization => authorization,\r\n :avs_result => {:code => avsResponse},\r\n :cvv_result => cvv2Response,\r\n :fraud_review => fraudResponse\r\n )\r\n end", "def create_response(response, first_response=nil)\n message = message_from(response)\n\n # This allows the second response to grab the auth info from the first\n first_response ||= response\n\n Response.new(!response.has_key?(:ErrCode), message, response,\n :test => test?,\n # The AccessPass and AccessID are used for all alterations to a\n # transaction, so we store that as the authorization instead of TranID\n :authorization => \"#{first_response[:AccessID]}-#{first_response[:AccessPass]}\"\n )\n end", "def create_success_response\n response = {\n body: {\n status: \"ok\"\n },\n status: 200\n }\n return response\n end", "def failure(msg)\n Detail::Fail.new(msg)\n end", "def stuff_999_response(env, err)\n env.tap do\n _1.reason_phrase = \"#{err.class} #{err.message}\"\n _1.response_body = ''\n _1.response_headers = Faraday::Utils::Headers.new\n _1.status = HTTPDisk::ERROR_STATUS\n end\n Faraday::Response.new(env)\n end", "def resource_save_failure_response\n error_string = \"\"\n resource.errors.full_messages.each do |msg| #Concatinating error message into 1 string.\n error_string += msg\n end\n render :json => {:success => \"false\",\n :message => \"Something went wrong. Please try again later. #{error_string}\"}\n end", "def new_response\n {:success => true}\n end", "def _create_http_response(mock_response, code, message)\n mock_response.stub!(:code).and_return(code)\n mock_response.stub!(:message).and_return(message)\n mock_response.stub!(:is_a?).and_return(true) if [\"200\", \"201\"].member?(code)\nend", "def ret_fail(text)\n {'response'=>false, 'report'=> text}\nend", "def failure_json\n { errors: 'Sorry you are not eligible for WellMatch' }\n end", "def failure\n failure = {failure: \"Uh oh! Looks like something didn't go quite right.\"}\n render json: failure\n end", "def failed_body\n %{\n responseEnvelope.ack=FAILURE&responseEnvelope.timestamp=2010-07-27T17%3a46%3a58&responseEnvelope.version=1.0&errorList.error(0).errorId=580028&errorList.error(0).message=A+URL+supplied+is+malformed&errorList.error(0).parameter=returnUrl&errorList.error(1).errorId=580029&errorList.error(1).message=A+required+parameter+was+not+provided&errorList.error(1).parameter=returnUrl&errorList.error(2).errorId=580028&errorList.error(2).message=A+URL+supplied+is+malformed&errorList.error(2).parameter=cancelUrl&errorList.error(3).errorId=580029&errorList.error(3).message=A+required+parameter+was+not+provided&errorList.error(3).parameter=cancelUrl&errorList.error(4).errorId=580029&errorList.error(4).message=A+required+parameter+was+not+provided&errorList.error(4).parameter=memo&errorList.error(5).errorId=580022&errorList.error(5).message=Invalid+parameter&errorList.error(5).parameter=memo&errorList.error(6).errorId=580022&errorList.error(6).message=Invalid+parameter&errorList.error(6).parameter=senderEmail&errorList.error(7).errorId=580029&errorList.error(7).message=A+required+parameter+was+not+provided&errorList.error(7).parameter=senderEmail&errorList.error(8).errorId=580029&errorList.error(8).message=A+required+parameter+was+not+provided&errorList.error(8).parameter=senderFirstname&errorList.error(9).errorId=580029&errorList.error(9).message=A+required+parameter+was+not+provided&errorList.error(9).parameter=senderLastname\n }\n end", "def to_failure msg:, warnings: [], depreciations: [], **values\n self.class.new \\\n failed: true,\n msg: msg,\n warnings: (self.warnings + warnings),\n depreciations: (self.depreciations + depreciations)\n end", "def create\n access(:create)\n checked_params = check_params(FAILURE_PROPERTIES)\n checked_params[\"device\"] = Device.find(failure_params[\"device_id\"])\n checked_params[\"announcer\"] = Employee.find(failure_params[\"announcer_id\"])\n @failure = Failure.new(checked_params)\n respond_to do |format|\n if @failure.save\n format.html { redirect_to @failure}\n format.json { render :show, status: :created, location: @failure }\n else\n format.html { render :new }\n format.json { render json: @failure.errors, status: :unprocessable_entity }\n end\n end\n end", "def failure_response(api_response, response)\n error_message = if response[:cancel_pickup_reply]\n [response[:cancel_pickup_reply][:notifications]].flatten.first[:message]\n else\n \"#{api_response[\"Fault\"][\"detail\"][\"fault\"][\"reason\"]}\\n--#{Array(api_response[\"Fault\"][\"detail\"][\"fault\"][\"details\"][\"ValidationFailureDetail\"][\"message\"]).join(\"\\n--\")}\"\n end rescue $1\n raise RateError, error_message\n end", "def failure(response)\n catch_throttling_error(response)\n parsed_response = JSON.parse(response.body.to_s)\n raise RequestError, parsed_response['detail']\n rescue JSON::ParserError\n raise RequestError, response.status\n end", "def build_error_response(error)\n error_messages = messages_from_error(error)\n\n JsonRender.convert(:status => :error, :messages => error_messages)\n end", "def exception_response\n { ok: false, message: 'Error processing request' }\n end", "def invalid_json_response\n <<~RESPONSE\n {\n foo : bar\n }\n RESPONSE\n end", "def failure_wrap(message)\n begin\n payload = unpack(message)\n yield payload\n rescue => e\n error \"Unexpected error encountered processing custom resource - #{e.class}: #{e.message}\"\n debug \"#{e.class}: #{e}\\n#{e.backtrace.join(\"\\n\")}\"\n cfn_resource = payload.get(:data, :cfn_resource)\n cfn_response = build_response(cfn_resource)\n cfn_response['Status'] = 'FAILED'\n cfn_response['Reason'] = \"Unexpected error encountered [#{e.message}]\"\n respond_to_stack(cfn_response, cfn_resource[:response_url])\n message.confirm!\n end\n end", "def create_b2bua_response(session, orig_response=session.iresponse)\n peer_session = get_peer_session(session)\n if peer_session\n r = peer_session.create_response(orig_response.code)\n r.copy_from(orig_response, :content, :content_type, :path, :service_route, :privacy, :warning)\n return r\n else\n @ilog.warn(\"No peer session found, cannot create the response\") if @ilog.warn?\n raise \"Unable to create response\"\n end \n end", "def failure(message, extra = nil)\n flash[:error] = message\n form_response_params = { success: false, errors: { message: message } }\n form_response_params[:extra] = extra unless extra.nil?\n FormResponse.new(**form_response_params)\n end", "def failure\n # TODO, create failure.html.erb\n end", "def create_response(request)\n response = Response.new\n end", "def failure_notice(message)\n { type: 'error', message: message }\n end", "def handle_response(result)\n unless result.success\n #if result.error_class\n # TODO needs to be constantized first (see TODO in lib/rjr/message)\n # raise result.error_class.new(result.error_msg) unless result.success\n #else\n fail result.error_msg\n #end\n end\n return result.result\n end", "def validate_response(response) \n case response.code\n when '200' \n return\n when '400' # Bad Request error - invalid request\n raise ResponseError::BadRequestError.new(extact_error_message(response.body))\n when '401' # Unauthorised error\n raise ResponseError::UnauthorisedError.new(extact_error_message(response.body))\n when '403' # Forbidden error - valid request but server is refusing, may be due to lack of permissions (RETRY enabled)\n raise ResponseError::ForbiddenError.new(extact_error_message(response.body))\n when '404' # Not Found error - server is unable to locate the resource to serve\n raise ResponseError::NotFoundError.new(extact_error_message(response.body))\n when '500' # Internal Server error - error due to unknown reason\n raise ResponseError::InternalServerError.new(extact_error_message(response.body))\n when '502' # Bad Gateway error - error due to not receiving valid response from backend server \n raise ResponseError::BadGatewayError.new(extact_error_message(response.body))\n when '503' # Service Unavailable error - server is overloded or under maintainance (RETRY enabled)\n raise ResponseError::ServiceUnavailableError.new(extact_error_message(response.body))\n when '504' # Gateway Timeout error - not receiving response within the allowed time period (RETRY enabled)\n raise ResponseError::GatewayTimeoutError.new(extact_error_message(response.body))\n else\n raise ResponseError::UnexpectedError.new(extact_error_message(response.body))\n end\n end", "def create_Not_Found_Response(request_path)\n\tbody = ''\n\tinitial = generic_Generate_Initial(404)\n\theaders = generic_Generate_Headers(body)\n\tgeneric_Generate_Response(initial,headers,body)\nend", "def failure\n @status = FAILURE_FLAG if @status == SUCCESS_FLAG\n end", "def json_fail(message)\n { status: 'fail', data: { message: message } }\n end", "def save_failed\n response = {\n status: 422,\n message: \"Failed to create user!, due to #{ self.errors.full_messages }\",\n user: self\n }\n end", "def create_success_response(message='')\n message = message.present? ? message : 'ok'\n response = {\n body: {\n status: message\n },\n status: 200\n }\n return response\n end", "def show\n respond_with(failures)\n end", "def negative_failure_message\n<<-EOS\nexpected the response from #{@response.request.url}\nnot to have the status 200 Ok and body 'Allowed Access'\"\nEOS\n end", "def make_adapter_response(response)\n adapter_response = Response.new\n case response\n when Net::HTTPSuccess \n adapter_response.body = JSON.parse(response.body)\n adapter_response.success = true\n when Net::HTTPServerError \n adapter_response.success = false\n adapter_response.error = :server_error\n when Net::HTTPClientError \n adapter_response.success = false\n adapter_response.error = :client_error\n else\n adapter_response.success = false\n adapter_response.error = :unknown\n end\n adapter_response\n end", "def make_error(type, response, url: 'http://example.com', request_body: '{\"msg\": \"The request body\"}')\n error = nil\n\n begin\n begin\n raise Faraday::ClientError, \"The original error\"\n rescue Faraday::ClientError => e\n request = RestfulResource::Request.new(:get, url, body: request_body)\n raise type.new(request, response)\n end\n rescue Exception => e\n error = e\n end\n\n error\n end", "def new\n @aiaioo_failure = AiaiooFailure.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @aiaioo_failure }\n end\n end", "def check_for_response_code!(response)\n return if response.status == 201\n\n raise(\n UserEngage::CreateNotSuccessfulException,\n response.body\n )\n end", "def resource_failed(new_resource, action, exception)\n description = Formatters::ErrorMapper.resource_failed(new_resource, action, exception)\n @error_description = description.for_json\n end", "def response_factory(data)\n\t\t\t\t\t\treturn Response.new(data)\n\t\t\t\t\tend", "def failure_message; end", "def failure_message; end", "def failure_message; end", "def failure_message; end", "def failure_message; end", "def failure_message; end", "def failure_message; end", "def populate_error resp\n code = resp.http_response.status\n if EMPTY_BODY_ERRORS.include?(code) and empty_response_body?(resp.http_response.body)\n error_class = EMPTY_BODY_ERRORS[code]\n resp.error = error_class.new(resp.http_request, resp.http_response)\n else\n super\n end\n end", "def status_code; 422; end", "def status_code; 422; end", "def status_code; 422; end", "def status_code; 422; end", "def postContractPaymentFailure( contract_id, failure_reason, payment_date, amount, currency, response)\n params = Hash.new\n params['contract_id'] = contract_id\n params['failure_reason'] = failure_reason\n params['payment_date'] = payment_date\n params['amount'] = amount\n params['currency'] = currency\n params['response'] = response\n return doCurl(\"post\",\"/contract/payment/failure\",params)\n end", "def base_response(custom_response={})\n resp = {\n message: nil\n }\n resp.merge!(custom_response)\n status = 200\n [resp, status]\n end", "def test_service_error_response\n twerr = Twirp::Error.invalid_argument('foo')\n resp = Twirp::Service.error_response(twerr)\n assert_equal 400, resp[0]\n assert_equal 'application/json', resp[1]['Content-Type']\n assert_equal '{\"code\":\"invalid_argument\",\"msg\":\"foo\"}', resp[2][0]\n end", "def transform_error2_response(error)\n response = [\"#{error.message}: #{error.http_body}\", error.http_code]\n def response.body\n self[0]\n end\n def response.code\n self[1]\n end\n response\n end", "def build_error_response_body(message) \n JSON.generate({\n \"findItemsByKeywordsResponse\": [\n {\n \"ack\": 'failure',\n \"version\": '1.0.0',\n \"timestamp\": Time.now.utc,\n \"error_message\": message,\n \"searchResult\": [\n \"count\": 0,\n \"item\": []\n ]\n }\n ] \n })\n end", "def successful_response_to\n attempts = 0\n loop do\n random_response = yield\n if random_response.success?\n return random_response\n elsif attempts > 2\n raise 'Unable to get a successful response'\n else\n assert_equal 'Declined_(General).', random_response.params.fetch('error')\n attempts += 1\n end\n end\n end", "def sample_create_account_response(success)\n if success\n raw_response = OpenStruct.new(\n parsed_response: {\n \"success\"=>true,\n \"account\"=> {\n \"identifier\"=>\"asdfasdfasdf\",\n \"email\"=>\"asdfasdf@asdfasdf.com\",\n \"customer\"=>\"bonusly\",\n \"available_balance\"=>0\n }\n },\n code: 200\n )\n else\n raw_response = OpenStruct.new(\n parsed_response: {\n \"success\"=>false,\n \"error_message\"=>\"The account already exists for the platform.\"\n },\n code: 403\n )\n end\n Tangocard::Response.new(raw_response)\n end", "def custom_failure!\n @custom_failure = true\n end", "def failure_message\n build_failure_message(negated: false)\n end", "def from_response(response)\n\n payload = response.body\n @error = payload['error']\n @error_code = payload['error_code']\n @details = payload['details']\n @response = response\n\n logger.error(\"Request failed with status #{response.code.to_s}: '#{@error_code} #{@error}': #{response.body}\")\n\n self\n end", "def resp_error(message = '')\n # {code: 300, message: message}\n error!({code: 300, message: message}, 300)\n end", "def build_error(msg, status)\n {\n json: {\n errors: [\n {\n \"status\": Rack::Utils::SYMBOL_TO_STATUS_CODE[status].to_s,\n \"title\": msg,\n \"detail\": msg\n }\n ]\n },\n content_type: 'application/vnd.api+json',\n status: status\n }\n end", "def initialize(response)\n response.error = self\n @response = response\n\n message = []\n\n if response.parsed.is_a?(Hash)\n @code = response.parsed['error']\n @description = response.parsed['error_description']\n message << \"#{@code}: #{@description}\"\n end\n\n message << response.body.force_encoding(\"UTF-8\")\n\n super(message.join(\"\\n\"))\n end", "def raise_api_error_msg(res)\n \"HTTP status code: #{res.status}, \" \\\n \"Error message: #{res.body['message']}, \" \\\n \"Reference: #{res.body['reference']}\"\n end", "def test_a_noticeable_error_is_not_created_on_failure_if_a_segment_is_absent\n multi = Curl::Multi.new\n request = OpenStruct.new\n error = [OpenStruct.new(name: 'name'), 'last']\n prep_on_failure(request)\n def multi.remove_failure_callback(request); end\n # if noticeable error creation attempt, explode\n NewRelic::Agent::NoticeableError.stub(:new, -> { raise 'kaboom' }) do\n multi.install_failure_callback(request, nil, nil)\n end\n end", "def failure\n render json: {status: 1, data: nil}\n end", "def do_token_fail(ticket, reason)\n # Call Authlete's /auth/token/fail API.\n response = call_token_fail_api(ticket, reason)\n\n # The content of the response to the client.\n content = response[\"responseContent\"]\n\n # \"action\" denotes the next action.\n case response[\"action\"]\n when \"INTERNAL_SERVER_ERROR\"\n # 500 Internal Server Error\n # The API request from this implementation was wrong\n # or an error occurred in Authlete.\n return WebResponse.new(500, content).json.to_response\n\n when \"BAD_REQUEST\"\n # 400 Bad Request\n # Authlete successfully generated an error response\n # for the client application.\n return WebResponse.new(400, content).json.to_response\n\n else\n # This never happens.\n return WebResponse.new(500, \"Unknown action\").plain.to_response\n end\nend", "def response!\n return response if !response.errors?\n\n raise response.to_exception\n end", "def initialize(response)\n @response = response\n\n if outcome\n @code = outcome[:reason_code]\n message = outcome[:reason_message]\n else\n message = \"the server responded with status #{response[:status]}\"\n end\n\n super(message)\n end", "def failure_message\n<<-EOS\nexpected the response from #{@response.request.url}\nto have the status 200 OK and body 'Allowed Access'\"\nbut the status is #{@response.status} and the body is '#{@response.body}'\"\nEOS\nend", "def validate(response)\n case response.code\n when 400 then fail(Error::BadRequest.new, error_message(response))\n when 401 then fail(Error::Unauthorized.new, error_message(response))\n when 403 then fail(Error::Forbidden.new, error_message(response))\n when 404 then fail(Error::NotFound.new, error_message(response))\n when 405 then fail(Error::MethodNotAllowed.new, error_message(response))\n when 409 then fail(Error::Conflict.new, error_message(response))\n when 500 then fail(Error::InternalServerError.new, error_message(response))\n when 502 then fail(Error::BadGateway.new, error_message(response))\n when 503 then fail(Error::ServiceUnavailable.new, error_message(response))\n end\n response.parsed_response\n end", "def error_response(opts={}, message=\"Server Error\")\n status = opts.delete(:status) || 500\n {\n status: status,\n json: {\n status: \"error\",\n message: message\n }\n }\n end", "def failed_purchase_response\n <<~RESPONSE\n {\n \"error\": {\n \"message\": \"The card number is invalid. Make sure the number entered matches your credit card.\",\n \"caused_by\": \"buyer\",\n \"param\": \"number\",\n \"type\": \"card_error\",\n \"code\": \"incorrect_number\"\n }\n }\n RESPONSE\n end", "def _error(message,code) \n status code\n response.headers['Content-Type'] = 'application/json'\n body({:error=>{:message=>message}}.to_json)\n end", "def response_with_unprocessable\n error_response( message: @group_event.errors.full_messages.to_sentence,\n fields_errors: @group_event.errors.full_messages,\n status: 422\n )\n end", "def return_failure(code, message)\n halt_with_json_response(code, Errors::HTTPErrors::PLUGIN_ERROR, message)\n end", "def build_excon_response(body, status = 200)\n response = Excon::Response.new(:body => body, :status => status)\n if body && body.key?(\"error\")\n msg = \"Google Cloud did not return an error message\"\n\n if body[\"error\"].is_a?(Hash)\n response.status = body[\"error\"][\"code\"]\n if body[\"error\"].key?(\"errors\")\n msg = body[\"error\"][\"errors\"].map { |error| error[\"message\"] }.join(\", \")\n elsif body[\"error\"].key?(\"message\")\n msg = body[\"error\"][\"message\"]\n end\n elsif body[\"error\"].is_a?(Array)\n msg = body[\"error\"].map { |error| error[\"code\"] }.join(\", \")\n end\n\n case response.status\n when 404\n raise Fog::Errors::NotFound.new(msg)\n else\n raise Fog::Errors::Error.new(msg)\n end\n end\n\n response\n end", "def create\n @aiaioo_failure = AiaiooFailure.new(params[:aiaioo_failure])\n\n respond_to do |format|\n if @aiaioo_failure.save\n format.html { redirect_to @aiaioo_failure, notice: 'Aiaioo failure was successfully created.' }\n format.json { render json: @aiaioo_failure, status: :created, location: @aiaioo_failure }\n else\n format.html { render action: \"new\" }\n format.json { render json: @aiaioo_failure.errors, status: :unprocessable_entity }\n end\n end\n end", "def do_authorization_fail(ticket, reason)\n # Call Authlete's /auth/authorization/fail API.\n response = call_authorization_fail_api(ticket, reason)\n\n # The content of the response to the client.\n content = response[\"responseContent\"]\n\n # \"action\" denotes the next action.\n case response[\"action\"]\n when \"INTERNAL_SERVER_ERROR\"\n # 500 Internal Server Error\n # The API request from this implementation was wrong\n # or an error occurred in Authlete.\n return WebResponse.new(500, content).json.to_response\n\n when \"BAD_REQUEST\"\n # 400 Bad Request\n # The ticket is no longer valid (deleted or expired)\n # and the reason of the invalidity was probably due\n # to the end-user's too-delayed response to the\n # authorization UI.\n return WebResponse.new(400, content).json.to_response\n\n when \"LOCATION\"\n # 302 Found\n # The authorization request was invalid and the error\n # is reported to the redirect URI using Location header.\n return WebResponse.new(302).location(content).to_response\n\n when \"FORM\"\n # 200 OK\n # The authorization request was invalid and the error\n # is reported to the redirect URI using HTML Form Post.\n return WebResponse.new(200, content).html.to_response\n\n else\n # This never happens.\n return WebResponse.new(500, \"Unknown action\").plain.to_response\n end\nend", "def check_failure(code)\n assert_response code\n body = JSON.parse(response.body)\n body['error'].should_not == nil\nend", "def respond_bad_request; make_response(nil, false, 400, \"Bad Request\") end", "def create\n json authentication_response, :status => authentication_response_status\n end", "def assign_errors_from_response( response )\n response.errors.each do |key, value|\n value.each do |message|\n errors[key.to_sym] = message \n end\n end \n end", "def validate_response_status(status_kind)\r\n #TODO: make the difinition of success variable, 2006/10/13 shino\r\n unless @response.kind_of?(status_kind)\r\n error_message = \"HTTP Response FAILURE, \" +\r\n \"status [#{@response.code} #{@response.message}]\"\r\n logger.error(error_message)\r\n logger.info{@response.to_yaml}\r\n #TODO: must create AP4R specific Exception class, 2006/10/12 shino\r\n raise StandardError.new(error_message)\r\n end\r\n end" ]
[ "0.7212774", "0.7067432", "0.70068365", "0.6946382", "0.6822346", "0.6742092", "0.660483", "0.6565303", "0.6549323", "0.6520697", "0.64870495", "0.64820105", "0.64443636", "0.64108276", "0.6385243", "0.63821274", "0.62842053", "0.62665963", "0.6264063", "0.6239963", "0.62303853", "0.6220622", "0.621877", "0.62001723", "0.6184967", "0.6184275", "0.61793184", "0.61607915", "0.61367095", "0.6118552", "0.60821116", "0.6078455", "0.6063386", "0.6050181", "0.6043229", "0.60334957", "0.602244", "0.6022305", "0.6003355", "0.600289", "0.60010624", "0.5980947", "0.59781796", "0.5966967", "0.59525377", "0.59502816", "0.59406894", "0.5935217", "0.5932626", "0.593199", "0.5924753", "0.5920801", "0.59204745", "0.59123063", "0.59123063", "0.59123063", "0.59123063", "0.59123063", "0.59123063", "0.59123063", "0.5903032", "0.5890012", "0.5890012", "0.5890012", "0.5890012", "0.587018", "0.58481777", "0.58335334", "0.5821616", "0.58150333", "0.58085436", "0.58007205", "0.5797439", "0.5793388", "0.5789081", "0.5782235", "0.5777861", "0.57773185", "0.5770325", "0.57699907", "0.5753813", "0.5751722", "0.5748219", "0.5746419", "0.5745134", "0.5743191", "0.5741755", "0.57367", "0.57335025", "0.5732461", "0.5730582", "0.5729589", "0.5726554", "0.5714532", "0.571195", "0.5710595", "0.5702928", "0.5697933", "0.5694182" ]
0.67707795
5
Instantiate an instance of +klass+ and pass +output+
def respond_with(klass, output) klass.new(self, output) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def initialize(output)\n @output = output\n end", "def initialize(output)\n @output = output\n end", "def initialize(output)\n @output = output\n end", "def initialize(output)\n @output = output\n end", "def initialize(output)\n @output = output\n end", "def initialize(*output)\n @output = output\n end", "def build_markup\n Object.const_get(output_class).new\n end", "def compileclass(output,classname)\n #File.open(output, \"a\") { |f| f.write \"<class>\\n <\" }\n end", "def output(*args)\n self::Output.new(*args)\n end", "def initialize(input, output)\n @input = input\n @output = output\n end", "def initialize(output = $stdout)\n @output = output\n end", "def initialize(output, options = {})\n @output = output\n @options = options\n end", "def instantiate(*args)\n clazz.new(*args)\n end", "def initialize(output)\n super(output)\n @testcases_data = {}\n end", "def add_output(type, *args)\n class_name = type.to_s.capitalize\n klass = Drone::Interfaces.const_get(class_name)\n @output_modules << klass.new(*args)\n end", "def test_output_method_creates_a_new_output_target\n Crd::Spec.new 'Testing' do |s|\n s.output = 'some/output/File.swf'\n assert_instance_of( Crd::Target, s.output )\n end\n end", "def run input, params = {}\n @klass.new(input, options).process\n end", "def initialize(output, escape_from = nil)\n @output = output\n @escape_from = escape_from\n end", "def class() end", "def output\n @output ||= Output.new\n end", "def instantiate!; end", "def initialize( out = $stdout )\n @out = out\n end", "def generate\n classes = registry.all(:class)\n classes.each do |c|\n data = methods(c)\n output(data, c.to_s)\n end\n end", "def create_output(params = {})\n Bitmovin::Output.create(params)\n end", "def class=(_arg0); end", "def def_class(superklass=Object, methodname='result')\n cls = Class.new(superklass)\n def_method(cls, methodname, @filename || '(ERB)')\n cls\n end", "def create( target_class, *args )\n @class_loader.newInstance(target_class, *args )\n end", "def initialize(out = $stdout)\n @out = out\n end", "def initialize(output)\n @output = output\n @total_points = 0\n @passed_points = 0\n @current_test_case = nil # when an example starts, this gets set to a hash that will capture example's results\n @results = {\n # optional fields:\n #\"score\" => 100.0, # total; required if not on each test case below. Overrides total if specified.\n # \"execution_time\" => 0, # seconds\n # \"output\" => \"Text relevant to the entire submission\",\n # \"visibility\" => \"after_due_date\", # visibility setting\n # \"stdout_visibility\" => \"visible\", # stdout visibility setting, if tests write things on stdout\n # \"extra_data\" => {}, # Optional extra data to be stored\n \"tests\" => [ ] # Optional, but required if no top-level score\n }\n end", "def spawn_class(a_class, *args, reader: last_pipe, writer: next_pipe)\n spawn_process(a_class, *args, readers: [reader], writers: [writer])\n end", "def create_class(classname, superclass); end", "def initialize(*)\n super\n @output = @opts[:output] ? @opts[:output] : String.new\n end", "def initialize(output, results, message_compiler, path)\n @output = output\n @results = results\n @message_compiler = message_compiler\n @path = path\n end", "def __output(*args, **opt, &block)\n __output_impl(*args, **opt, &block)\nend", "def output\n send(\"output_#{@type}\")\n end", "def initialize(outputs:)\n @outputs = outputs.to_h\n end", "def initialize( output ) # :notnew:\n\t\tsuper\n\t\t@previous_nesting_depth = 0\n\t\t@failcounter = 0\n\t\t@snippet_extractor = RSpec::Core::Formatters::HtmlSnippetExtractor.new\n\t\t@example_templates = {\n\t\t\t:passed => self.load_template(PASSED_EXAMPLE_TEMPLATE),\n\t\t\t:failed => self.load_template(FAILED_EXAMPLE_TEMPLATE),\n\t\t\t:pending => self.load_template(PENDING_EXAMPLE_TEMPLATE),\n\t\t\t:pending_fixed => self.load_template(PENDFIX_EXAMPLE_TEMPLATE),\n\t\t}\n\n\t\t@deprecation_stream = []\n\t\t@summary_stream = []\n\t\t@failed_examples = []\n\n\t\t@deprecations = Set.new\n\n\t\tThread.current['logger-output'] = []\n\tend", "def klass_config(output_class)\n @klass_config[output_class] ||= build_klass_config(output_class)\n end", "def initialize(input:, output:)\n @ui = UI.new(input, output)\n end", "def initialize(input:, output:)\n @ui = UI.new(input, output)\n end", "def initialize(out, configuration)\n @raw_out = out || $stderr\n @configuration = configuration\n end", "def instantiate(klass, locals = nil)\n unwrapped_klass = klass.is_a?(Array) ? klass.last : klass\n instance = unwrapped_klass.allocate\n proc = instance.method(:initialize).to_proc\n\n klass.is_a?(Array) ? (klass[-1] = proc) : (klass = proc)\n\n invoke(klass, instance, locals)\n instance\n end", "def generate_class klass, template_file = nil\n setup\n\n current = klass\n\n template_file ||= @template_dir + 'class.rhtml'\n\n debug_msg \" working on %s (%s)\" % [klass.full_name, klass.path]\n out_file = @outputdir + klass.path\n rel_prefix = @outputdir.relative_path_from out_file.dirname\n search_index_rel_prefix = rel_prefix\n search_index_rel_prefix += @asset_rel_path if @file_output\n\n asset_rel_prefix = rel_prefix + @asset_rel_path\n svninfo = get_svninfo(current)\n\n @title = \"#{klass.type} #{klass.full_name} - #{@options.title}\"\n\n debug_msg \" rendering #{out_file}\"\n render_template template_file, out_file do |io|\n here = binding\n # suppress 1.9.3 warning\n here.local_variable_set(:asset_rel_prefix, asset_rel_prefix)\n here.local_variable_set(:svninfo, svninfo)\n here\n end\n end", "def initialize output=nil\n @object_properties = configatron.objectProperties.to_hash\n @object_namespaces = configatron.namespaces.to_hash\n @class_map = configatron.classMap.to_hash\n @output=output\n @version=\"0.0.2\"\n @json_hash = Hash.new\n @output_json = nil;\n @base_uri = \"http://example.com/\"\n end", "def <<(output)\n print(output)\n self\n end", "def initialize(output)\n super(output)\n @group_level = 0\n @index_offset = 0\n @cumulative_failed_examples = []\n @failed_examples = []\n end", "def create(klass, *args, &block)\n\t\t\t#puts caller\n\t\t\tc = klass\n\t\t\t#go through rules\n\t\t\t#ask each replace? klass\n\n\t\t\tif(@rules)\n\t\t\t\t@rules.each { |r| \n\t\t\t\t\tx = r.replace?(klass)\n\t\t\t\t\tif x && r.test?(klass,*args,&block) then c = x end}\n\t\t\tend\n\n\t\t\tif(!c.is_a?(Class)) then\n\t\t\t\traise \"ClassConductor asked to init something which isn't a class: #{c}\"\n\t\t\tend\n\t\t\t\n\t\t\tobj = c.class_conductor_aliased_new(*args,&block)\n\t\t\t\n\t\t\tif(@rules)\n\t\t\t\t@rules.each {|r| if r.wrap?(obj) then obj = r.dowrap(obj) end}\n\t\t\tend\n\t\t\tobj\n\t\tend", "def instantiate_subclasses(klass); end", "def parse(klass)\n Parser.new(self, klass).result\n end", "def initialize(output)\n @output = output\n @console = Console.new\n @current_player = 'x'\n end", "def factory(klass, *args)\n klass.new(*args)\n end", "def render_class out, store, klass, also_in # :nodoc:\n comment = klass.comment\n # TODO the store's cache should always return an empty Array\n class_methods = store.class_methods[klass.full_name] || []\n instance_methods = store.instance_methods[klass.full_name] || []\n attributes = store.attributes[klass.full_name] || []\n\n if comment.empty? and\n instance_methods.empty? and class_methods.empty? then\n also_in << store\n return\n end\n\n add_from out, store\n\n class_document_comment out, comment\n\n if class_methods or instance_methods or not klass.constants.empty? then\n out << RDoc::Markup::Rule.new(1)\n end\n\n class_document_constants out, klass\n\n add_method_list out, class_methods, 'Class methods'\n add_method_list out, instance_methods, 'Instance methods'\n add_method_list out, attributes, 'Attributes'\n\n add_method_documentation out, klass if @show_all\n end", "def define_compiler(base_class, args, &block)\n\t\t\tcompiler_class = Class.new(base_class)\n\t\t\tcompiler_class.class_eval(&block)\n\t\t\tcompiler = compiler_class.new(args)\n\t\t\toutput_dir = ''\n\t\t\toutput_tags = []\n\t\t\tif args[:output_dir]\n\t\t\t\toutput_dir = args[:output_dir]\n\t\t\telsif args[:output_name]\n\t\t\t\toutput_dir, args[:output_name] = File.split(args[:output_name])\n\t\t\t\toutput_tags << $1 if args[:output_name] =~ /(\\.[^\\.]+)$/\n\t\t\tend\n\t\t\toutput_tags << args[:output_tag] if args[:output_tag]\n\t\t\toutput_tags.concat(args[:output_tags]) if args[:output_tags]\n\t\t\t\n\t\t\traise LaceError.new(\"Compiler definition is missing an :input_pattern\") unless args[:input_pattern]\n\t\n\t\t\tadd_compiler(output_dir, compiler, args[:input_pattern], args[:dependency_pattern], output_tags)\n\t\t\treturn compiler_class\n\t\tend", "def klass=(_arg0); end", "def output\n self.class.output\n end", "def initialize(input)\n @input = input\n end", "def initialize(output: nil, errors: {})\n @errors = errors\n @exceptions = {}\n @information = {}\n @executions = []\n @output = output\n end", "def create_object\n sut.send(:new)\n end", "def initialize(output: nil, fields: {})\n @fields = fields\n @config = if block_given?\n conf = Config.new\n yield(conf)\n conf\n else\n self.class.config\n end\n @level = @config.level\n @handlers = @config.handlers\n @output = output || @config.output\n @ready_handlers = []\n\n @handlers.each do |handler|\n add_handler(handler)\n end\n end", "def output\n Pry::Output.new(self)\n end", "def output=(_arg0); end", "def output=(_arg0); end", "def output=(_arg0); end", "def output=(_arg0); end", "def output=(_arg0); end", "def output=(_arg0); end", "def output=(_arg0); end", "def output=(_arg0); end", "def output=(_arg0); end", "def output=(_arg0); end", "def output=(_arg0); end", "def output=(_arg0); end", "def comp_class\n # set field count to zero\n @field_count = 0\n @i += 1\n # instantiate new Codewrite instance\n $cw = CodeWriter.new\n $st = ST.new\n # set cw.@class_name to class name\n $cw.set_class_name(@tokens[@i].val)\n @class = @tokens[@i].val\n @i += 1\n while @i < @tokens.length\n @constructor = true if @tokens[@i].val == 'constructor'\n @method = true if @tokens[@i].val == 'method'\n case @tokens[@i].val\n # add class variables to symbol table\n when 'static', 'field'\n comp_class_var_dec\n next\n when 'constructor', 'function', 'method'\n comp_subroutine\n next\n else\n @i += 1\n end\n end\n $cw.close_file\n end", "def single_class_test(testing_class)\n cur_testing_class = Generator.new(testing_class, @traversal)\n TestFile.open(testing_class,[],@output_dir) do |file|\n cur_testing_class.test_class do |test|\n file << test << \"\\n\"\n end\n end\n end", "def to_make\n Target.new(@output, @objects, [command, \"ranlib #{output}\"])\n end", "def process_class exp\n exp\n end", "def output_create(payload, opts = {})\n data, _status_code, _headers = output_create_with_http_info(payload, opts)\n data\n end", "def build\n klass = create_class(@class_name, @options)\n klass.new\n end", "def result(output)\n output\n end", "def call(input)\n evaluator_klass.new(self, input)\n end", "def input(*args)\n self::Input.new(*args)\n end", "def test_input_method_creates_a_new_input_target\n Crd::Spec.new 'Testing' do |s|\n s.input = 'test/fixtures/target/Input.as'\n assert_instance_of( Crd::Target, s.input )\n end\n end", "def add_class out, name, classes\n heading = if classes.all? { |klass| klass.module? } then\n name\n else\n superclass = classes.map do |klass|\n klass.superclass unless klass.module?\n end.compact.shift || 'Object'\n \"#{name} < #{superclass}\"\n end\n out << RDoc::Markup::Heading.new(1, heading)\n out << RDoc::Markup::BlankLine.new\n end", "def initialize(output)\n # This is the accumulation buffer. It's a holding pen so\n # consecutive lines of the right type can get stuck together\n # without intervening newlines.\n @buffer = \"\"\n\n # This stack is used to do proper outline numbering of\n # headlines.\n @headline_number_stack = []\n\n @output = output\n @output_type = :start\n @list_indent_stack = []\n @mode_stack = []\n @code_block_indent = nil\n\n @logger = Logger.new(STDERR)\n if ENV['DEBUG'] or $DEBUG\n @logger.level = Logger::DEBUG\n else\n @logger.level = Logger::WARN\n end\n\n @re_help = RegexpHelper.new\n end", "def initialize(&block)\n @out = []\n instance_eval(&block) if block_given?\n end", "def initialize(out: $stdout, verbose: false)\n @out = out\n @verbose = verbose\n end", "def initialize(output_path)\n @output_path = output_path\n end", "def construct\n end", "def make data_object_class, opts={}\n data_object_class.new @browser, opts\n end", "def add_class out, name, classes\n heading = if classes.all? { |klass| klass.module? } then\n name\n else\n superclass = classes.map do |klass|\n klass.superclass unless klass.module?\n end.compact.shift || 'Object'\n\n superclass = superclass.full_name unless String === superclass\n\n \"#{name} < #{superclass}\"\n end\n\n out << RDoc::Markup::Heading.new(1, heading)\n out << RDoc::Markup::BlankLine.new\n end", "def select_output(output)\n case output\n when \"chef\"\n ProductDeploy::OutputChef.new \n when \"stdout\"\n STDOUT\n when \"array\"\n ProductDeploy::Output.new\n else\n raise(\"select chef, array or stdout\")\n end\n end", "def create_class(name) \n AsmProxyClass.new(name)\n end", "def myAnotherInstance = new ObjectOrientedProgramming()", "def output=(output)\n @_output = output\n end", "def output\n @output.call\n end", "def output\n @output.call\n end", "def klass\n @klass ||= Class.new(Parslet::Parser)\n end", "def print_class(*) end", "def compile\n @instance ||= new\n end" ]
[ "0.7180216", "0.699429", "0.699429", "0.699429", "0.6947501", "0.6887096", "0.6884629", "0.67193204", "0.66616166", "0.6391762", "0.6358704", "0.6208677", "0.6205884", "0.6191878", "0.61585855", "0.6156144", "0.61158764", "0.60943145", "0.6093336", "0.6046234", "0.59016114", "0.5896406", "0.5896352", "0.5891541", "0.58803666", "0.5829395", "0.58101237", "0.5794254", "0.57855445", "0.5771641", "0.5764448", "0.5685341", "0.56364655", "0.5607967", "0.55977404", "0.5591027", "0.5579754", "0.5570474", "0.55614036", "0.55614036", "0.55476993", "0.5542055", "0.5540783", "0.55320966", "0.5529924", "0.55294937", "0.55277205", "0.55107385", "0.54949903", "0.547547", "0.5471682", "0.5470902", "0.54622734", "0.5442678", "0.5429447", "0.5428515", "0.5407777", "0.540606", "0.53944033", "0.5386758", "0.53821725", "0.53821725", "0.53821725", "0.53821725", "0.53821725", "0.53821725", "0.53821725", "0.53821725", "0.53821725", "0.53821725", "0.53821725", "0.53821725", "0.53730243", "0.533719", "0.53328776", "0.5332803", "0.5326719", "0.532477", "0.53133297", "0.5312053", "0.5294857", "0.52826214", "0.52727145", "0.5266392", "0.5261216", "0.5257272", "0.52545863", "0.5248658", "0.524132", "0.5239012", "0.52383214", "0.52337015", "0.5227972", "0.52271557", "0.5225535", "0.5225535", "0.52186024", "0.5217171", "0.5214943" ]
0.7288034
0
This method is responsible for receiving the exchange_rate of a specific currency to the GBP from an API.
def find_rate() uri_string = "https://free.currconv.com/api/v7/convert?q=GBP_"\ "#{@currency}&compact=ultra&apiKey=2d46a9b5b650dca0dbb1" uri = URI(uri_string) res = Net::HTTP.get_response(uri) return(JSON.parse(res.body)["GBP_#{@currency}"]/100.0) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def exchange_rate(to_currency)\n self.bank.exchange(self.base_currency, to_currency)\n end", "def conv_exchange_rate\n currency_exchange.exchange_rate\n end", "def get_exchange_rate(currencyCode)\n begin\n exhash = JSON.parse(exchange_rate)\n BigDecimal(exhash[currencyCode])\n rescue\n raise OrderCurrencyConversionFailure\n end\n end", "def currency_rates\n response['rates'][currency.target_currency.to_s]\n end", "def report_currency_exchange_rate\n # If exchange reate has been locked use that\n if self.exchange_rate.present?\n self.exchange_rate\n else\n Currency.get_exchange_for(self.project.account.account_setting.default_currency, self.currency)\n end\n end", "def fetch_currency_rate(currency_type)\n if currency_type == \"EUR\"\n product_price_details\n else\n fetch_updated_currency_rate(currency_type)\n end\n end", "def add_exchange_rate_if_necessary(amount_currency)\n # get exchange rate in case currencies don't match\n Money.bank.add_rate(amount_currency, self.currency,\n ExchangeRate.get(amount_currency, self.currency)\n ) if self.currency != amount_currency && !Money.bank.get_rate(amount_currency, self.currency)\n end", "def amount_from_exchange_rate(amount, currency:, btc_denomination: :satoshi)\n currency = self.default_currency if currency.nil?\n btc_denomination = :satoshi if btc_denomination.nil?\n currency = currency.to_s.upcase\n if currency == 'BTC'\n return Satoshi.new(amount, from_unit: btc_denomination).to_i\n end\n\n begin\n try_adapters(\n @exchange_rate_adapters,\n type: \"exchange rate\",\n priority_exception: Straight::ExchangeRate::Adapter::CurrencyNotSupported\n ) do |a|\n a.convert_from_currency(amount, currency: currency)\n end\n # At least one Bitcoin exchange adapter works, but none returned exchange rate for given currency\n rescue Straight::ExchangeRate::Adapter::CurrencyNotSupported\n amount_in_cross_currency = try_adapters(@forex_rate_adapters, type: \"forex rate\") do |a|\n a.convert_from_currency(amount, currency: currency)\n end\n try_adapters(@exchange_rate_adapters, type: \"exchange rate\") do |a|\n a.convert_from_currency(amount_in_cross_currency, currency: Straight::ExchangeRate::FiatAdapter::CROSS_RATE_CURRENCY)\n end\n end\n end", "def rate\n if(specific_rate?)\n if(rate_cents < 0)\n task_list.default_rate.to_money\n else\n specific_rate.to_money\n end\n else\n Money.new(0, \"USD\")\n end\n end", "def exchange_rate\n http = Net::HTTP.new('themoneyconverter.com', 443)\n http.use_ssl = true\n\n url = \"/CurrencyConverter.aspx?from=#{from_currency.to_s.upcase}&to=#{to_currency.to_s.upcase}\"\n response = http.get(url)\n\n doc = Nokogiri::HTML(response.body)\n result = doc.css('div.cc-rate div#cc-ratebox').first.text\n\n regexp = Regexp.new('(\\\\d+(?:\\\\.\\\\d+)?)')\n regexp.match result\n\n return $1\n rescue Timeout::Error\n raise StandardError, 'Please check your internet connection'\n end", "def price action\n result = api_customers_command\n exchange_rate = result[:exchange_rate]\n exchange_rate.to_f\n end", "def rates_for_usd\n rates_for 'USD'\n end", "def exchange_rates\n Currency::Exchange.exchange_rates\n end", "def fetch_updated_currency_rate(currency_type)\n currency_rate = nil\n ApplicationController.new.fetch_currency_rates.select{ |currency| currency_rate = currency if currency[:currency] == currency_type }\n if currency_rate.present?\n actual_price = price.to_f * currency_rate[:rate].to_f\n currency_details = {:currency => currency_type, :price => actual_price.round(2)}\n else\n currency_details = product_price_details\n end\n currency_details\n end", "def conversion_rate(target_currency)\n if DaMoney::Money.conversion_rates.key? self.currency\n if DaMoney::Money.conversion_rates[self.currency].key? target_currency\n DaMoney::Money.conversion_rates[self.currency][target_currency].to_f\n else\n raise Exception.new(\"Conversion rate from '#{self.currency}' to '#{target_currency}'\" +\n \" if not configured!\")\n end\n else\n raise Exception.new(\"Curreny '#{self.currency}' is not configured!\")\n end\n end", "def get_rate(currency_iso_from, currency_iso_to); end", "def rate(original, target)\n if SimpleXurrency.cache_enabled?\n cached_result = SimpleXurrency.cache_get(\"#{original}_#{target}\")\n\n if !cached_result.nil?\n return cached_result \n end\n end\n\n api_url = \"http://xurrency.com/api/#{[original, target].join('/')}/1\"\n \n api_url << \"?key=#{SimpleXurrency.key}\" if !SimpleXurrency.key.nil?\n \n uri = URI.parse(api_url)\n\n retries = 10\n json_response = nil\n begin\n Timeout::timeout(1){\n json_response = uri.open.read || nil # Returns the raw response\n }\n rescue Timeout::Error\n retries -= 1\n retries > 0 ? sleep(0.42) && retry : raise\n end\n \n return nil unless json_response && parsed_response = Crack::JSON.parse(json_response)\n if parsed_response['status'] == 'fail'\n raise parsed_response['message']\n end\n\n value = Hash.new\n \n value[:rate] = parsed_response['result']['value'].to_f\n value[:updated_at] = parsed_response['result']['updated_at'].to_s\n \n SimpleXurrency.cache_add(\"#{original}_#{target}\", value) if SimpleXurrency.cache_enabled?\n \n value\n end", "def currency_rate(date, currency)\n return 1 if currency == @base_currency\n\n @exchange_rates[date.strftime(\"%Y-%m-%d\")][currency]\n end", "def price(_currency = 'USD')\n raise Sibit::NotSupportedError, 'Btc.com API doesn\\'t provide prices'\n end", "def exchange_rate\n url = \"/currencyconverter/convert/?Amount=1&From=#{from_currency.to_s.upcase}&To=#{to_currency.to_s.upcase}\"\n uri = URI.parse('https://www.xe.com')\n\n request = Net::HTTP.new(uri.host, uri.port)\n request.use_ssl = true\n response = request.get(url)\n\n doc = Nokogiri::HTML(response.body)\n result = doc.css('span.uccResultAmount').text\n\n regexp = Regexp.new('(\\\\d+(?:\\\\.\\\\d+)?)')\n regexp.match result\n\n return $1\n rescue Timeout::Error\n raise StandardError, 'Please check your internet connection'\n end", "def set_exchange_rate\n # pluck is like .select but doesn't return id field.\n # This attribute is a string.\n self.exchange_rate = payment_method.btc_rates.pluck(:code, :rate).to_h.to_json\n end", "def extract_rate(data)\n request_hash = JSON.parse(data)\n error = request_hash['error']\n raise JsonRatesRequestError, request_hash['error'] unless (error.nil? || error.empty?)\n BigDecimal.new(request_hash['rate'])\n end", "def exchange_with(from, to_currency)\n rate = get_rate(from.currency, to_currency)\n unless rate\n from_base_rate = get_rate(\"EUR\", from.currency)\n to_base_rate = get_rate(\"EUR\", to_currency)\n rate = to_base_rate / from_base_rate\n end\n Money.new((from.cents * rate).round, to_currency)\n end", "def refresh_exchange_rates\n CurrencyConverter.cache_current_exchange_rates!\n end", "def set_currency_exchange_rate\n @currency_exchange_rate = CurrencyExchangeRate.find(params[:id])\n end", "def update_rates\n clear_rates\n add_currency_rate(\"EUR\", 1)\n add_currency_rates(config[\"exchange_rates\"]) # rates from bank.yml\n \n fetch_rates.each do |currency_rate|\n add_currency_rate(currency_rate[:currency], currency_rate[:rate].to_f)\n end\n @@config['exchange_rates']\n end", "def get_exchange_rates\r\n begin\r\n @logger.info(\"get_exchange_rates called.\")\r\n\r\n # prepare query url\r\n @logger.info(\"Preparing query URL for get_exchange_rates.\")\r\n _query_builder = Configuration.get_base_uri().clone\r\n _query_builder << '/exchangerates'\r\n _query_url = APIHelper.clean_url _query_builder\r\n\r\n # prepare and execute HttpRequest\r\n @logger.info('Preparing and executing HttpRequest for get_exchange_rates.')\r\n _request = @http_client.get _query_url\r\n BasicAuth.apply(_request)\r\n _context = execute_request(_request, name: 'get_exchange_rates')\r\n validate_response(_context)\r\n\r\n # return appropriate response type\r\n @logger.info(\"Returning response for get_catalog.\")\r\n decoded = APIHelper.json_deserialize(_context.response.raw_body)\r\n return decoded['exchangeRates'].map do |rate|\r\n ExchangeRateModel.from_hash(rate)\r\n end\r\n rescue Exception => e\r\n @logger.error(e)\r\n raise e\r\n end\r\n end", "def rates_for(currency_code)\n # Retrieve the actual rates from the external source\n rates = all_rates\n\n adjusted_currency = currency_code.to_s.upcase.to_sym \n unless rates.include?(adjusted_currency)\n raise Errors::CurrencyNotAvailable, \"#{adjusted_currency.to_s} was not available in this Source (#{self.to_s}), please use a different Source\"\n end\n\n adjusted_rates = {}\n\n # Add the currency we are converting to...\n adjusted_rates[adjusted_currency] = 1.0\n\n # Work out the exchange from our desired currency to our base currency. So if our base was EUR and we wanted USD this would \n # be how many Euros are in one US dollar.\n adjustment_factor = 1.0 / rates[adjusted_currency]\n adjusted_rates[base_currency] = adjustment_factor\n\n # Now remove it, since we've already done it.\n rates.delete(base_currency)\n\n # Now convert the rest\n rates.each do |currency, rate|\n adjusted_rates[currency] = rate * adjustment_factor\n end\n\n adjusted_rates\n end", "def update_currency_rate\n current_rate = CurrencyRate.current_rate ||\n CurrencyRate.create(rate: 57.00, is_force: false)\n return if current_rate.force?\n current_rate.update!(rate: actual_rate.to_f)\n ActionCable.server.broadcast 'actual_rate', rate: current_rate.rate, from: 'Update currency in service'\n current_rate\n end", "def exchange_rates\n doc = JSON.parse(read_from_cache || read_from_url)\n if doc['error'] && ERROR_MAP.key?(doc['message'].to_sym)\n raise ERROR_MAP[doc['message'].to_sym]\n end\n\n self.rates_timestamp = doc[TIMESTAMP_KEY]\n @oer_rates = doc[RATES_KEY]\n end", "def currency_exchange_rate_params\n params.require(:currency_exchange_rate).permit(:currency_exchange_rate_id, :base_currency_id, :secondary_currency_id, :exchange_rate, :start_date, :end_date, :exchange_rate_status)\n end", "def fetch_rate(from, to)\n xe_client.fetch_rate(from.iso_code, to.iso_code)\n rescue StandardError => e\n raise XeCurrencyFetchError, e.message\n end", "def get_openexchangerates(currency_code,base_code,key)\n # this is tested as working and so far is seen as the best in the lot \n # this one when free will only do lookups compared to USD, also limits to 1000 lookup per month so only 1 per hour\n # at $12/month Hourly Updates, 10,000 api request/month\n # at $47/month 30-minute Updates, 100,000 api request/month\n # at $97/month 10-minute Updates, unlimited api request/month + currency conversion requests\n # does lookup more than one currency at a time\n #https://openexchangerates.org/api/latest.json?app_id=xxxxxxx\n # see: https://openexchangerates.org/\n # example usage:\n # result = get_openexchangerates(\"THB\",\"JPY\", openexchangerates_key)\n # puts \"rate: \" + result[\"rate\"].to_s ; rate: 2.935490234019467\n #\n # inputs: \n # currency_code: the currency code to lookup example THB\n # base_code: the currency base to use in calculating exchange example USD or THB or BTC\n # key: the api authentication key obtained from https://openexchangerates.org\n #\n # return results:\n # rate: the calculated rate of exchange\n # timestamp: time the rate was taken in seconds_since_epoch_integer format (not sure how accurate as the time is the same for all asset currency)\n # datetime: time in standard human readable format example: 2016-09-15T08:00:14+07:00\n # base: the base code of the currency being calculated example USD\n # example if 1 USD is selling for 34.46 THB then rate will return 34.46 for base USD\n # example#2 if 1 USD is selling for 101.19 KES then rate will return 101.19 for base of USD\n # example#3 with the same values above 1 THB is selling for 2.901 KES so rate will return 2.901 for base of KES \n puts \"get_openexchangerates started\"\n url_start = \"https://openexchangerates.org/api/latest.json?app_id=\"\n url_end = \"\"\n send = url_start + key\n #puts \"sending: #{send}\"\n begin\n #postdata = RestClient.get send , { :Accept => '*/*', 'accept-encoding' => \"gzip, deflate\", :user_agent => \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0\"}\n postdata = RestClient.get send , { :Accept => '*/*', 'accept-encoding' => \"gzip, deflate\"}\n rescue => e\n puts \"fail in get_openexchangerate at RestClient.get error: #{e}\"\n data_out = {}\n data_out[\"service\"] = \"openexchangerates.org\"\n data_out[\"status\"] = \"fail\"\n return data_out\n end\n #puts \"postdata: \" + postdata\n data = JSON.parse(postdata)\n data_out = {}\n data_out[\"status\"] = \"pass\"\n if (base_code == \"USD\")\n #defaults to USD\n data_out[\"currency_code\"] = currency_code\n data_out[\"base\"] = base_code\n data_out[\"datetime\"] = Time.at(data[\"timestamp\"]).to_datetime.to_s\n #date[\"rate\"] = data[\"rates\"][currency_code]\n data_out[\"rate\"] = (data[\"rates\"][currency_code]).to_s\n data_out[\"ask\"] = data_out[\"rate\"]\n data_out[\"bid\"] = data_out[\"rate\"]\n data_out[\"service\"] = \"openexchangerates.org\"\n puts \"data_out: #{data_out}\"\n return data_out\n end\n puts \"here??\"\n usd_base_rate = data[\"rates\"][currency_code]\n base_rate = data[\"rates\"][base_code]\n rate = base_rate / usd_base_rate\n data_out[\"currency_code\"] = currency_code\n #data_out[\"rate\"] = rate.to_s\n #data_out[\"ask\"] = data_out[\"rate\"]\n #data_out[\"bid\"] = data_out[\"rate\"]\n data_out[\"rate\"] = (1.0 / rate.to_f)\n data_out[\"ask\"] = data_out[\"rate\"].to_f\n data_out[\"bid\"] = data_out[\"rate\"].to_f\n data_out[\"base\"] = base_code\n data_out[\"datetime\"] = Time.at(data[\"timestamp\"]).to_datetime.to_s\n data_out[\"service\"] = \"openexchangerates.org\"\n puts \"data_out: #{data_out}\"\n return data_out\nend", "def get_openexchangerates(currency_code,base_code,key)\n # this is tested as working and so far is seen as the best in the lot \n # this one when free will only do lookups compared to USD, also limits to 1000 lookup per month so only 1 per hour\n # at $12/month Hourly Updates, 10,000 api request/month\n # at $47/month 30-minute Updates, 100,000 api request/month\n # at $97/month 10-minute Updates, unlimited api request/month + currency conversion requests\n # does lookup more than one currency at a time\n #https://openexchangerates.org/api/latest.json?app_id=xxxxxxx\n # see: https://openexchangerates.org/\n # example usage:\n # result = get_openexchangerates(\"THB\",\"JPY\", openexchangerates_key)\n # puts \"rate: \" + result[\"rate\"].to_s ; rate: 2.935490234019467\n #\n # inputs: \n # currency_code: the currency code to lookup example THB\n # base_code: the currency base to use in calculating exchange example USD or THB or BTC\n # key: the api authentication key obtained from https://openexchangerates.org\n #\n # return results:\n # rate: the calculated rate of exchange\n # timestamp: time the rate was taken in seconds_since_epoch_integer format (not sure how accurate as the time is the same for all asset currency)\n # datetime: time in standard human readable format example: 2016-09-15T08:00:14+07:00\n # base: the base code of the currency being calculated example USD\n # example if 1 USD is selling for 34.46 THB then rate will return 34.46 for base USD\n # example#2 if 1 USD is selling for 101.19 KES then rate will return 101.19 for base of USD\n # example#3 with the same values above 1 THB is selling for 2.901 KES so rate will return 2.901 for base of KES \n puts \"get_openexchangerates started\"\n url_start = \"https://openexchangerates.org/api/latest.json?app_id=\"\n url_end = \"\"\n send = url_start + key\n #puts \"sending: #{send}\"\n begin\n #postdata = RestClient.get send , { :Accept => '*/*', 'accept-encoding' => \"gzip, deflate\", :user_agent => \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0\"}\n postdata = RestClient.get send , { :Accept => '*/*', 'accept-encoding' => \"gzip, deflate\"}\n rescue => e\n puts \"fail in get_openexchangerate at RestClient.get error: #{e}\"\n data_out = {}\n data_out[\"service\"] = \"openexchangerates.org\"\n data_out[\"status\"] = \"fail\"\n return data_out\n end\n #puts \"postdata: \" + postdata\n data = JSON.parse(postdata)\n data_out = {}\n data_out[\"status\"] = \"pass\"\n if (base_code == \"USD\")\n #defaults to USD\n data_out[\"currency_code\"] = currency_code\n data_out[\"base\"] = base_code\n data_out[\"datetime\"] = Time.at(data[\"timestamp\"]).to_datetime.to_s\n #date[\"rate\"] = data[\"rates\"][currency_code]\n data_out[\"rate\"] = (data[\"rates\"][currency_code]).to_s\n data_out[\"ask\"] = data_out[\"rate\"]\n data_out[\"bid\"] = data_out[\"rate\"]\n data_out[\"service\"] = \"openexchangerates.org\"\n puts \"data_out: #{data_out}\"\n return data_out\n end\n puts \"here??\"\n usd_base_rate = data[\"rates\"][currency_code]\n base_rate = data[\"rates\"][base_code]\n rate = base_rate / usd_base_rate\n data_out[\"currency_code\"] = currency_code\n #data_out[\"rate\"] = rate.to_s\n #data_out[\"ask\"] = data_out[\"rate\"]\n #data_out[\"bid\"] = data_out[\"rate\"]\n data_out[\"rate\"] = (1.0 / rate.to_f)\n data_out[\"ask\"] = data_out[\"rate\"].to_f\n data_out[\"bid\"] = data_out[\"rate\"].to_f\n data_out[\"base\"] = base_code\n data_out[\"datetime\"] = Time.at(data[\"timestamp\"]).to_datetime.to_s\n data_out[\"service\"] = \"openexchangerates.org\"\n puts \"data_out: #{data_out}\"\n return data_out\nend", "def add_rate(currency_iso_from, currency_iso_to, rate); end", "def get_date_rate(date, currency)\n api_data = get_api_data(date)\n api_data[\"rates\"][currency]\n end", "def rates(coin='Bitcoin', currencies: %w(EUR GBP))\r\n \r\n jeg = JustExchangeRates.new(base: 'USD', app_id: @exchangerate_key, \r\n debug: @debug)\r\n usd = self.price(coin).round(2)\r\n ([:USD] + currencies.map(&:to_sym)).zip(\r\n [usd, *currencies.map {|currency| (usd * jeg.rate(currency)).round(2) }]\r\n ).to_h\r\n \r\n end", "def exchange_rate_params\n params.require(:exchange_rate).permit(:rate, :date, :bank_id, :currency_id, :user_id)\n end", "def update_values\n response_hash = run_json_http_request\n @currency = 'CNY'\n @rate = BtcExchange.get_exchange_rate @currency, 'USD'\n @last = response_hash['ticker']['last'].to_f * @rate\n @vol = response_hash['ticker']['vol'].to_f\n @high = response_hash['ticker']['high'].to_f * @rate\n @low = response_hash['ticker']['low'].to_f * @rate\n @buy = response_hash['ticker']['buy'].to_f * @rate\n @sell = response_hash['ticker']['sell'].to_f * @rate\n end", "def rates\n base_currency_rates.map(&:conversion_rate)\n end", "def rate(from, to)\n exchange = []\n exchange << (Currency.find(from) or raise ArgumentError.new(\"Unknown +from+ currency #{from.inspect}.\"))\n exchange << (Currency.find(to) or raise ArgumentError.new(\"Unknown +to+ currency #{to.inspect}.\"))\n return BigDecimal.new(1.to_s) if exchange.uniq.size == 1 || exchange.find{|c| c == Currency::XXX}\n\n id = exchange.map{|c| c.code}.join(':')\n if cache && rate = cache[id]\n return rate\n end\n\n service = @@services.reverse.find do |service|\n !!exchange.reject{|c| service.currencies.include?(c)}\n end\n\n service or raise ConversionError # TODO: Message?\n rate = BigDecimal.new(service.read_rate(*exchange).to_s)\n\n cache[id] = rate if cache\n rate\n end", "def update_rates\n currencies(true).each_pair do |currency, data|\n rate = data[:middle_rate_for_commercial_transactions]\n add_rate(\"EUR\", currency, rate) if known_currencies.include?(currency)\n end\n rates\n end", "def updated_cached_exchange_rate\n if self.quote_status == 0\n self.exchange_rate = nil\n self.exchange_rate_updated_at = nil\n else\n if self.exchange_rate.blank?\n to_currency = Currency.find_by_iso_code(self.currency)\n self.exchange_rate = Currency.get_exchange_for(self.project.account.account_setting.default_currency, self.currency)\n self.exchange_rate_updated_at = to_currency.updated_at\n end\n end\n end", "def get_rate(from_currency, to_currency, opts = {})\n super if opts[:call_super]\n expire_rates\n rate = get_rate_or_calc_inverse(from_currency, to_currency, opts)\n rate || calc_pair_rate_using_base(from_currency, to_currency, opts)\n end", "def update\r\n\t\t@currency = Currency.find(params[:id])\r\n\t\t@currency.update_exchange_rate\r\n\t\trender :partial => 'exchange_rate', :locals => { :currency => @currency }\r\n\tend", "def get_usd_exchange_rate\n Sidekiq.logger.debug \"get_usd_exchange_rate\"\n begin\n today = Time.now.strftime '%d/%m/%Y'\n uri = \"http://www.cbr.ru/scripts/XML_daily.asp?date_req=#{today}\"\n doc = Nokogiri::XML(open(uri))\n text = doc.xpath('//ValCurs/Valute[@ID=\"R01235\"]/Value').text\n return text.gsub(',', '.')\n rescue Exception => excp\n Sidekiq.logger.error \"rate loading error: #{excp}\"\n return \"\"\n end\n end", "def rate_source\n @rate_source ||= DatabaseBank::RateSource::EuCentralBank\n end", "def convert(euros, exchange_rate)\n euros * (exchange_rate / 100)\nend", "def set_exchange_rate\n @exchange_rate = ExchangeRate.find(params[:id])\n end", "def set_exchange_rate\n @exchange_rate = ExchangeRate.find(params[:id])\n end", "def currency_rates\n @currency_rates = fetch_currency_rates\n end", "def fetch_rate(code)\n currency_rates[code]\n end", "def actual_rate\n retrying_num = 0\n begin\n logger.info('Try to get rate JSON')\n json = JSON.parse(open(URL_FOR_UPDATE, read_timeout: TIMEOUT_SEC).read)\n logger.info('JSON was get successful')\n json['rates']['RUB']\n rescue StandardError\n retrying_num += 1\n logger.info(\"JSON was not download, retry #{retrying_num}\")\n if retrying_num >= MAX_RETRYING_OPEN\n return CurrencyRate.current_online_rate.rate\n end\n retry\n end\n end", "def get_price_exchange(price, cur)\n exrate = Currency.count_exchange_rate(cur, current_user.currency.name)\n rate_cur = Currency.count_exchange_prices({:exrate => exrate, :prices => [price.to_d]})\n return rate_cur.to_d\n end", "def get_consumer_rate(options={})\n post 'rates', options.merge(rate_filter: 'consumer')\n end", "def exchange_rates\n @exchange_rates ||= Nordea::ExchangeRates.new\n end", "def get_exchange_rates(options = {})\n body = {\n cmd: \"rates\"\n }\n body[:short] = 1 if options[:short]\n body[:accepted] = 1 if options[:accepted]\n response = post body, openstruct: false\n if options[:accepted_only]\n response.to_h.delete_if { |_k, v| v[:accepted] == 0 }\n else\n response.to_h\n end\n end", "def get_user_rate(currency, current_user)\n user_currency = User.get_currency(current_user)\n\n return 1 if user_currency.iso_code == currency\n\n return CurrencyRate.get_rate(currency, user_currency.iso_code)\n end", "def update_values\n response_hash = run_json_http_request\n \n # check to make sure we're using the correct currency\n currency = response_hash['return']['last']['currency']\n if @currency != currency\n @currency = currency\n @rate = BtcExchange.get_exchange_rate @currency, 'USD'\n end\n \n # set the values\n @last = response_hash['return']['last']['value'].to_f * @rate\n @vol = response_hash['return']['vol']['value'].to_f\n @high = response_hash['return']['high']['value'].to_f * @rate\n @low = response_hash['return']['low']['value'].to_f * @rate\n @buy = response_hash['return']['buy']['value'].to_f * @rate\n @sell = response_hash['return']['sell']['value'].to_f * @rate\n end", "def set_exchange\n if session[:locale] == \"vi\"\n vnd = 1\n usd = 1\n else\n vnd = 20800\n usd = 1\n end\n $exchange_rate = vnd/usd\n end", "def extract_rate(data)\n json_data = JSON.parse(data)\n raise GoogleCurrencyFetchError unless json_data.present?\n\n return json_data.values[0]['val']\n end", "def consume_rate(amount=1, api=nil)\n Yat.consume_rate(amount, api)\n end", "def exchange(cents, from_currency, to_currency)\n from_currency.upcase!\n to_currency.upcase!\n if !@rates[from_currency] or !@rates[to_currency] \n raise Money::UnknownRate, \"No conversion rate known for '#{from_currency}' -> '#{to_currency}'\"\n end\n ((cents / @rates[from_currency]) * @rates[to_currency]).round\n end", "def fetch_rates\n rates = {}\n begin\n if @force_expire\n Timeout.timeout(60) do\n doc = Hpricot.XML(open('http://themoneyconverter.com/USD/rss.xml'))\n (doc/:item).each do |item|\n country = (item/:title).inner_html.split('/')[0]\n conversion_match = (item/:description).inner_html[/=.?(\\d+\\.?\\d*)/]\n # 1 USD country rate 'in USD'\n rates[country] = 1.0 / $1.to_f\n end\n rates.update({'USD' => 1.0})\n persist_rates(rates)\n end\n else\n rates = fetch_persisted_rates\n end\n rescue Exception\n rates = fetch_persisted_rates\n end\n rates\n end", "def get_rates(source)\n\t\t\trequire 'money/bank/open_exchange_rates_bank'\n\t\t\toxr = Money::Bank::OpenExchangeRatesBank.new\n\t\t\toxr.app_id = Rails.application.credentials.openexchangerates[:api_key]\n\t oxr.source = source\n\t oxr.update_rates\n\n\t oxr.cache = '/tmp/cache/exchange_rates.json'\n\t oxr.ttl_in_seconds = 86400\n\n\t return oxr.rates\n\t\tend", "def raw_exchange_rates\n table_rows = Oga.parse_html(response.body).css('#ratesContainer li')\n # ADIB porvide 5 currencies on the home page (and 4 rows of info)\n fail ResponseError, 'Unknown HTML' unless table_rows&.size == 5\n currencies(table_rows).zip(rates(table_rows))\n end", "def bank\n unless @bank\n @bank = Money::Bank::VariableExchange.new\n base_cents = price_currency == 'JPY' ? (price_cents.to_f * 100) : price_cents.to_f\n unless alt1_price_currency.blank?\n alt1_cents = alt1_price_currency == 'JPY' ? (alt1_price_cents.to_f * 100) : alt1_price_cents.to_f\n @bank.add_rate(price_currency, alt1_price_currency, alt1_cents / base_cents)\n @bank.add_rate(alt1_price_currency, price_currency, base_cents / alt1_cents)\n end\n unless alt2_price_currency.blank?\n alt2_cents = alt2_price_currency == 'JPY' ? (alt2_price_cents.to_f * 100) : alt2_price_cents.to_f\n @bank.add_rate(price_currency, alt2_price_currency, alt2_cents / base_cents)\n @bank.add_rate(alt2_price_currency, price_currency, base_cents / alt2_cents)\n end\n if !alt1_price_currency.blank? && !alt2_price_currency.blank?\n @bank.add_rate(alt1_price_currency, alt2_price_currency, alt2_cents / alt1_cents)\n @bank.add_rate(alt2_price_currency, alt1_price_currency, alt1_cents / alt2_cents)\n end\n end\n @bank\n end", "def price(currency = 'USD')\n best_of('price') do |api|\n api.price(currency)\n end\n end", "def add_rate(from_currency, to_currency, rate)\n default_bank.add_rate(from_currency, to_currency, rate)\n end", "def fetch_rate(from, to, args = {})\n from = Money::Currency.wrap(from)\n to = Money::Currency.wrap(to)\n uri = build_uri(from, to, args)\n\n data = JSON.parse(uri.read)\n\n rate = data.fetch(\"rates\").fetch(to.iso_code)\n rate = 1 / extract_rate(build_uri(to, from).read) if rate < 0.1\n rate\n end", "def exchange(date, base, counter, source)\n fetch_rates(source).at(date).from(base).to(counter).rates\n end", "def exchange(from, to, fixnum)\n @from_currency = from.upcase.to_sym\n @to_currency = to.upcase.to_sym\n\n validate_currency\n\n ex_rate = exchange_rate\n\n validate_rate(ex_rate)\n\n ex_rate.to_f * fixnum\n end", "def exchange(from, to, fixnum)\n @from_currency = from.upcase.to_sym\n @to_currency = to.upcase.to_sym\n\n validate_currency\n\n ex_rate = exchange_rate\n\n validate_rate(ex_rate)\n\n ex_rate.to_f * fixnum\n end", "def exchange(cents, from_currency, to_currency)\n rate = get_rate(from_currency, to_currency)\n if !rate\n raise Money::UnknownRate, \"No conversion rate known for '#{from_currency}' -> '#{to_currency}'\"\n end\n (cents * rate).floor\n end", "def billing_rate\n return_value =\n case project.billing\n when 'user'\n user.billing_rate\n when 'project'\n project.billing_rate\n when 'non_billable'\n 0\n else\n raise \"invalid billing option.\"\n end\n return return_value\n end", "def convert_order_to_historical_rate(total_order_value, rate, conversion_date)\n fx = OpenExchangeRates::Rates.new\n if currency == \"USD\"\n new_value = fx.convert(total_order_value, from: \"USD\", to: rate, on: conversion_date.to_s)\n elsif currency == \"EUR\"\n new_value = fx.convert(total_order_value, from: \"EUR\", to: rate, on: conversion_date.to_s)\n else\n return total_order_value\n end\n return new_value\n end", "def calculate_fiat_value_for_exchange_rate(btc_to_dollar_exchange_rate, amount_of_btc_to_purchase = 0.01)\n (amount_of_btc_to_purchase * btc_to_dollar_exchange_rate).round(2)\n end", "def calculate_conversion\n converted_amount = nil\n\n # checking parameters before calculating the conversion rate\n if currency_converter_params[:rate_date] != \"\" or currency_converter_params[:from_cur] != \"\" or currency_converter_params[:to_cur] != \"\"\n rate = ExchangeRate.at( currency_converter_params[:rate_date].to_date, currency_converter_params[:from_cur], currency_converter_params[:to_cur])\n converted = false\n # rate is not nil go on and do the conversion\n if rate\n converted_amount = currency_converter_params[:amount].to_f * rate\n # rounding the amount to 5 decimal places\n converted_amount = converted_amount.round(5)\n converted = true\n\n # write the success message\n message = I18n.t('success_message', amount: converted_amount.to_s).html_safe\n else\n # failure message\n message = I18n.t('failure').html_safe\n end\n else\n # missing data message\n converted = false\n message = I18n.t('missed_data').html_safe\n end\n respond_to do |format|\n if converted\n format.json {render json: {success: true, message: message, amount: converted_amount} }\n else\n format.json {render json: {success: false, message: message, amount: \"\"}, status: 422 }\n end\n end\n end", "def bank\n @bank ||= lambda {\n bank = Money::Bank::VariableExchange.new\n bank.import_rates(:json, self.exchange_rate || \"{}\")\n bank\n }.call\n end", "def retrieve_rate(currency_a, currency_b, date)\n redis = Redis.new\n key = \"usd_rates:#{date.to_s}\"\n halt(404, 'No rates for given date') unless redis.exists key\n \n rate_a = redis.hget(key, currency_a.downcase)\n rate_b = redis.hget(key, currency_b.downcase)\n\n rate_b.to_f / rate_a.to_f # TODO: precision\nend", "def get_currency_history\n conversion_rate = ConversionRate.new(@params) if @params[:currency].present?\n get_conversion_rate = conversion_rate.get_conversion_rate if conversion_rate.present?\n render :json => get_conversion_rate\n end", "def set_default_rate\n currency_rates[base_currency] = DEFAULT_RATE\n end", "def get_rate(date, base, target)\n uri = make_uri(date, base, target)\n data = get_cached_data(uri)\n data['rates'][target]\n end", "def get_rates(origin, destination, items, booking_type)\n base_url = \"http://www.e-go.com.au/calculatorAPI\"\n puts(\"origin EgoApiWrapper:get_rates is #{origin.class.to_s}\") if Rails.env.test?\n pickup = origin.postal_code\n delivery=destination.postal_code\n \n rates = Array.new\n items.each do |item|\n width=item[:width].to_f.round(0).to_i\n height=item[:height].to_f.round(0).to_i\n length=item[:length].to_f.round(0).to_i\n weight_grams=item[:grams].to_i\n weight_kg = (weight_grams.to_f / 1000).ceil\n quan = item[:quantity].to_i\n \n #only get rate for one box\n query = \"#{base_url}?pickup=#{pickup}&delivery=#{delivery}&type=Carton&width=#{width}&height=#{height}&depth=#{length}&weight=#{weight_kg.to_s}&items=1\"\n \n \n \n unless booking_type.blank?\n query+= \"&bookingtype=#{booking_type}\"\n end\n puts(\"Qeury is #{query}\")\n uri = URI.parse(query)\n \n http = Net::HTTP.new(uri.host, uri.port)\n request = Net::HTTP::Get.new(uri.request_uri)\n\n response = http.request(request) \n \n ret = parse_response(response.body)\n \n ret[:price] = ret[:price].to_f * quan unless ret.nil?\n rates << ret unless ret.nil?\n end\n \n return_array = Array.new\n service_name =\"E-Go\"\n\n if (rates.empty?)\n return_array = [{\"service_name\" => \"ERROR getting rates from e-go\", 'service_code'=> \"E-go\", 'total_price' => 0.0, 'currency' => \"AUD\"}]\n else\n return_array = rates.collect{ |r| {\"service_name\" => \"#{service_name} (#{r[:eta]})\", 'service_code'=> r[:eta], 'total_price' => r[:price].to_f*100, 'currency' => \"AUD\"} }\n end\n puts(\"return_array is #{return_array.to_s}\") if Rails.env.test?\n \n return return_array \n end", "def base_rate_on_date(currency, date)\n return 1 if @base_currency == currency\n\n rate = get_base_rate(currency, date) ||\n fetch_stored_base_rate(currency, date) ||\n fetch_provider_base_rate(currency, date)\n\n if rate.nil?\n raise UnknownRate, \"Rate from #{currency} to #{@base_currency} \"\\\n \"on #{date} not found\"\n end\n\n rate\n end", "def exchange_rate_params\n params.require(:exchange_rate).permit(:account_id)\n end", "def get_rate(from_currency, to_currency, datetime = yesterday_utc)\n from_currency = Currency.wrap(from_currency)\n to_currency = Currency.wrap(to_currency)\n\n date = datetime_to_date(datetime)\n\n rate_on_date(from_currency, to_currency, date)\n end", "def call_api\n url = \"#{@base_uri}/stock\"\n params = {symbol: @symbol, api_token: @api_key}\n\n if @exchange\n params[:stock_exchange] = @exchange\n end\n\n Lita.logger.debug \"call_api: #{url} #{params.inspect}\"\n\n @response = RestClient.get url, {params: params}\n\n Lita.logger.debug \"response: #{@response}\"\n end", "def rate(rated_currency, base_currency, trans, pay_currency, search_id = nil)\n\n# Rails.cache.fetch(\"#{self.id}-#{rated_currency}-#{base_currency}-#{trans}-#{pay_currency}\", expires_in: 0.5.hour) do\n\n# puts \"Not cached yet: inside rate(#{self.id}-#{rated_currency}-#{base_currency}-#{trans}-#{pay_currency})\" unless Rails.env.production?\n\n result = {\n rated_currency: rated_currency,\n base_currency: base_currency,\n buy: nil,\n sell: nil,\n cc_fee: self.cc_fee,\n delivery_charge: self.delivery_charge,\n transaction: trans,\n pay_currency: pay_currency,\n error: nil,\n rates_update: nil,\n source: nil,\n exchange_id: self.id,\n bank_fee: nil,\n offer_update: Time.now\n }\n\n rated_rates = find_rate(rated_currency, trans, search_id)\n if rated_rates[:error]\n result[:error] = rated_rates[:error]\n# Rails.cache.write(\"#{self.id}-#{rated_currency}-#{base_currency}-#{trans}-#{pay_currency}\", result, expires_in: 0.5.hour)\n return result\n end\n\n base_rates = find_rate(base_currency, trans, search_id)\n if base_rates[:error]\n result[:error] = base_rates[:error]\n# Rails.cache.write(\"#{self.id}-#{rated_currency}-#{base_currency}-#{trans}-#{pay_currency}\", result, expires_in: 0.5.hour)\n return result\n end\n\n\n result[:buy] = !base_rates[:buy] || base_rates[:buy] == 0 || !rated_rates[:buy] ? 0 : (rated_rates[:buy] / base_rates[:buy])\n result[:sell] = !base_rates[:sell] || base_rates[:sell] == 0 || !rated_rates[:sell] ? 0 : (rated_rates[:sell] / base_rates[:sell])\n if trans == 'mixed'\n if rated_currency == pay_currency\n result[:mixed] = rated_rates[:buy] / base_rates[:sell]\n else\n result[:mixed] = rated_rates[:sell] / base_rates[:buy]\n end\n else\n result[:mixed] = nil\n end\n result[:rates_update] = [base_rates[:rate_update], rated_rates[:rate_update]].min\n result[:source] = rated_rates[:source] || base_rates[:source]\n result[:bank_fee] = self.bank? ? (self.bank_fee || 0) : nil\n\n result\n\n# end\n\n end", "def get_exchange\n params_hash = {\n # Mandatory\n 'x_login' => @x_login_for_webpaystatus,\n 'x_trans_key' => @x_trans_key_for_webpaystatus,\n 'x_country' => country,\n 'x_amount' => amount\n }\n\n astro_curl(@astro_urls['exchange'], params_hash)\n end", "def as_us_dollar\n exchange_to(\"USD\")\n end", "def as_us_dollar\n exchange_to(\"USD\")\n end", "def as_us_dollar\n exchange_to(\"USD\")\n end", "def as_us_dollar\n exchange_to(\"USD\")\n end", "def currency\n params['X-CURRENCY']\n end", "def price(currency)\n h = Sibit::Json.new(http: @http, log: @log).get(\n URI('https://blockchain.info/ticker')\n )[currency]\n raise Error, \"Unrecognized currency #{currency}\" if h.nil?\n price = h['15m']\n @log.info(\"The price of BTC is #{price} USD\")\n price\n end", "def get_account_rate(params, account, currency, transferred)\n if params[:type] == 'transfer'\n return 1 unless transferred\n return params[:rate_from_to]\n end\n\n return 1 if account.currency == currency\n\n return params[:rate]\n end", "def rate_on_date(from_currency, to_currency, date)\n return 1 if from_currency == to_currency\n\n # 1 EUR = 1.21 USD => 1 USD = 1/1.21 EUR\n from_base_to_from_rate = base_rate_on_date(from_currency, date)\n # 1 EUR = 0.83 GBP\n from_base_to_to_rate = base_rate_on_date(to_currency, date)\n\n # 1 USD = 1/1.21 EUR = (1/1.21) * 0.83 GBP = 0.83/1.21 GBP\n from_base_to_to_rate / from_base_to_from_rate\n end", "def refresh_rates\n read_from_url\n end", "def exchange_params\n params.require(:exchange).permit(:to_date, :buy_value, :ratetype_id, :rateclass_id, :coin, :saleprice)\n end" ]
[ "0.7444457", "0.7184691", "0.70807207", "0.6828173", "0.673572", "0.67350835", "0.66884565", "0.66806954", "0.66609746", "0.6636957", "0.6605665", "0.6591344", "0.6559951", "0.65384525", "0.65216565", "0.64503866", "0.64170665", "0.6379565", "0.63773113", "0.635374", "0.6345516", "0.63309216", "0.6325531", "0.6320286", "0.6319354", "0.6316154", "0.6310407", "0.6308334", "0.6301446", "0.6286215", "0.6246428", "0.62429225", "0.6240261", "0.6240261", "0.62279224", "0.6227585", "0.62171334", "0.62138236", "0.61432457", "0.6137843", "0.61272395", "0.6112794", "0.60861933", "0.6069951", "0.60545796", "0.60489476", "0.60488206", "0.604557", "0.6044978", "0.6044978", "0.60401744", "0.60398096", "0.603097", "0.6019558", "0.60177445", "0.6016077", "0.60014814", "0.59998894", "0.5994561", "0.5986324", "0.5963672", "0.5932376", "0.59318537", "0.5931804", "0.5911941", "0.5899484", "0.5893255", "0.58867484", "0.58861953", "0.58837605", "0.58826584", "0.5880845", "0.5880845", "0.58793557", "0.5878346", "0.5864567", "0.5864366", "0.5854828", "0.58338225", "0.5831806", "0.58276063", "0.5809352", "0.57634115", "0.5750524", "0.5740745", "0.57387984", "0.57199776", "0.5718881", "0.5707361", "0.5701154", "0.5686219", "0.5686219", "0.5686219", "0.5686219", "0.56835616", "0.568299", "0.56798387", "0.5678501", "0.56727874", "0.56705385" ]
0.72135526
1
puts "This is my first method!" end my_first_method def maths_two number = 2 + 2 puts number end maths_two
def my_math_method(num1, num2) number = num1 + num2 puts number end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def my_math_method(num1, num2)\n sum = num1 + num2\n\tputs \"The sum of 2 + 2 is #{sum}\"\nend", "def first_method(num_1, num_2)\n puts num_1 + num_2\nend", "def my_math_method(num1, num2)\n\tanswer = num1 + num2\n\tputs \"The sum of #{num1} and #{num2} is #{answer}.\"\nend", "def second_method\n puts \"This is my second method\"\n \"Hello\"\nend", "def add_two num\n p num + 2\nend", "def my_math_method(num1, num2)\n number = num1 + num2\n puts number\nend", "def my_math_method(num1, num2)\n number = num1 + num2\n puts number\nend", "def addition_method(num1, num2)\n\tputs num1 + num2\nend", "def first_method(name, age)\n puts \"Hello #{name}. You are #{age} years old\"\nend", "def sum_method(a, b)\n puts \"Adding #{a} + #{b}\"\n puts a + b\nend", "def maths2(firstNum, secondNum)\n total = firstNum + secondNum\n puts \"firstNum is #{firstNum}\"\n puts \"the secondnum is #{secondNum}\"\n puts \"and the total is #{total} \"\n puts firstNum\n puts secondNum\n puts total\n puts \"firstNum is firstNum\"\n puts \"the secondnum is secondNum\"\n puts \"and the total is total\"\nend", "def say_addition\n\tnum1 = 1\n\tnum2 = 2\n\tputs num1 + num2\nend", "def add_two(num1, num2)\n\tnumber = num1 + num2\n\tputs number\nend", "def add_two_numbers(num1, num2)\n puts \"OK, I'm solving your math problem!\"\n # if return is not in method, the method\n # will return the last expression. here puts ...\n return num1 + num2\n\n # could be dropped for\n # num1 + num2 only, as that will be the last\n # operation the method runs.\nend", "def add(num_1, num_2)\n p num_1 + num_2\nend", "def calc_sum_two(first, second)\n\n puts \"the sum of #{first} and #{second} is #{first + second}\"\n\nend", "def add(a, b)\n\t# a method that adds two numbers together\n\tputs \"ADDING #{a} + #{b}\"\n\treturn a + b\nend", "def firstMethod()\n p \"hey this is first method ok\"\n p \"here i show how can create method in ruby\"\n p \" know time end \"\nend", "def do_addition(number_1, number_2)\n\tfinal_number = number_1 + number_2\n\tputs \"Your first number, #{$first_number}, plus your second number, #{$second_number}, equals #{final_number}.\"\nend", "def add_two_numbers( x, y )\n puts x + y\nend", "def add\n puts 2+2\nend", "def add_two_numbers (x,y)\n puts x + y\nend", "def addition num1,num2 #num1 and num2 are known as parameters\nputs num1 + num2 \nend", "def yet_another_method\n puts \"I'm a method\"\nend", "def summator(x, y)\n p x + y\nend", "def sum_two(num1, num2)\n p \"#{num1} + #{num2} = #{num1 + num2}\"\nend", "def two_numbers(one, two)\n p \"This is the sum of #{one} and #{two}\"\nend", "def add_two_numbers(x,y)\n puts x + y\nend", "def add(number_1, number_2)\n p number_1 + number_2\nend", "def numbers(num1, num2)\n p num1 + num2\nend", "def second_method\n\tputs \"This is my second method\"\n\t\"Hello\" #Ruby methods returns the last value automatically\n\t#if you want to return more than one vlaue, you need an explicit return statement\nend", "def add_two(x)\n\tx + 5\nend", "def add(num_1, num_2)\n num_1 = 2\n num_2 = 3\n p num_1 + num_2\nend", "def addition(input_number1, input_number2)\n\tsum = input_number1 + input_number2\n\tputs \"The sum of #{input_number1} and #{input_number2} is #{sum}\"\n\tputs \"Thank you for using the calculator. Goodbye!\"\nend", "def addition1(num1, num2)\n\tprint \"addition1 gets call: \"\n\treturn num1 + num2\nend", "def calculator\n puts \"Welcome to the DPL Ruby Calculator!\"\n puts \"Type 'clear' to clear the calculator at anytime\"\n puts \"Type 'exit' to exit the calculator at anytime\"\n first_number\n get_modifier\n second_number\n put_result \nend", "def addition(num1, num2)\n p num1 + num2\nend", "def sum(num1, num2)\n puts \"Really? #{num1 + num2} foxes?!\"\nend", "def some_method_two\n puts \"Some more details.\"\n end", "def addition(a, b)\n puts a + b\nend", "def add(num1, num2)\n puts num1 + num2\nend", "def add(num_one,num_two)\n puts \"#{num_one} + #{num_two} = #{num_one + num_two}\"\nend", "def mathy\n print \"what is the first number?\"\n first = gets.chomp.to_i\n\n print \"what is the second number\"\n second = gets.chomp.to_i\n\n puts \"\\n #{first} + #{second} = #{first + second}\\n\n #{first} - #{second} = #{first - second} \\n\n #{first} * #{second} = #{first * second} \\n\n #{first} / #{second} = #{first / second}\"\nend", "def hello\n\tputs 10\nend", "def add_numbers(num1, num2)\n p num1 + num2\nend", "def main\n one = first_number\n two = second_number\n addit(one, two)\nend", "def another_greetings\n puts 'Hello'; puts 'Motherfucker'\nend", "def add(num_1, num_2)\n puts num_1 + num_2\nend", "def my_method\n puts \"ayyy\"\n puts \"joe\"\nend", "def plusOne(x)\n\tputs x+1\nend", "def add_num(a, b)\n puts a + b\nend", "def numbers(a, b)\n puts \"First number is #{a}\"\n puts \"Second number is #{b}\"\n return a + b\nend", "def add_two(number)\n number + 2 # res of last line will be returned\nend", "def addition(a,b)\n puts a + b\nend", "def add(a,b)\n puts \"Adding #{a} + #{b}\"\n a + b\nend", "def add(a, b)\n puts \"Add #{a} + #{b}\"\n return a + b\nend", "def print_two(thing, another_thing)\n\t# this is where the method's code goes.\n\tputs \"thing 1: #{thing}, thing 2: #{another_thing}\"\nend", "def add(x, y)\n puts \"Adding #{x}, #{y}\"\n return x + y\nend", "def sum(a, b)\n puts \"Sum total: #{a} + #{b} = #{10 + 20}\"\n\nend", "def add(x, y)\n p x+y\nend", "def add(number1, number2)\n number1+number2\nend", "def simple_method\n puts \"I am a simple method!\"\nend", "def addition(x, y)\n puts \"Addition: #{x} + #{y}\"\n return x + y\nend", "def add(a, b)\n\tputs \"Adding #{a} + #{b}\\n\"\n\treturn a + b\n\nend", "def add(a, b)\n puts \"addng #{a} + #{b}\"\n return a + b\nend", "def sum_two_num(a, b)\n puts a + b\nend", "def meal \n 'dinner'\n puts 'dinner'\nend", "def math_problem(num1, num2)\n p \"I am solving this hard math problem\"\n return num1 + num2\n p num1 - num2 #this won't get executed\nend", "def sum(num1, num2)\n puts num1 + num2\nend", "def add(a, b)\n puts \"SUM #{a} + #{b}\"\n return a + b\nend", "def add(a, b)\n #puts a + b\n return a + b\nend", "def hello\n puts 'Hello! Im Caz the calculator. I can help you do simple calculations. Lets begin.'\nend", "def add (a, b)\n puts \"Adding #{a} + #{b}\"\n return a+b\nend", "def add(a,b)\n p (a + b)\nend", "def sum_these_numbers(num1,num2)\n p num1 + num2\nend", "def somma(a, b)\n puts \"SOMMANDO #{a} + #{b}\"\n a + b\nend", "def numbers(a, b)\n p \"#{a} + #{b}\"\n return a + b\nend", "def add(a, b)\n puts \"ADDING #{a} + #{b}\"\n a + b\nend", "def introduce_myself\n puts \"My name is Anndony Quemag\"\n puts \"My age is 23\"\n puts \"Im work at kommit\"\nend", "def sum_numbers(num_1,num_2)\n puts \"The sum of #{num_1} and #{num_2} is #{num_1 + num_2}\"\nend", "def double(my_number)\n return puts my_number * 2\nend", "def numbers(num1, num2)\n puts \"#{num1} + #{num2}\"\n return num1 + num2\nend", "def number(num)\n\ta = 8\n\tputs \"method #{a}\"\nend", "def add(number1, number2)\n number1 + number2\nend", "def add(number1, number2)\n number1 + number2\nend", "def add(x, y)\n puts \"The sum of x & y is: #{x} + #{y}\"\n return x + y\nend", "def add(a, b)\n p \"ADDING #{a} + #{b}\"\n return a + b\nend", "def add(a, b)\n puts \"adding #{a} and #{b}:\"\n return a + b\nend", "def sum(a, b)\n p a + b\nend", "def sum(a, b)\n p a + b\nend", "def add(a, b)\n puts \"ADDING #{a} + #{b}\"\n return a + b\nend", "def add(a, b)\n puts \"ADDING #{a} + #{b}\"\n return a + b\nend", "def total(num1, num2)\n puts num1 + num2\nend", "def add_nums(num1, num2)\n p \"Addition of #{num1} + #{num2} = #{num1 + num2}\"\nend", "def addition\nprint \"What is your first number? \"\nfirst_num = gets().to_i\n\nprint \"What is the second number? \"\nsecond_num = gets().to_i\n\nresult = first_num + second_num\nputs \"#{first_num} + #{second_num} = #{result}\"\nend", "def add(a,b)\n puts \"Adding #{a} and #{b}:\"\n return a + b\nend", "def add(num1, num2)\n num1+num2\nend", "def double (my_number)\n puts my_number * 2\nend", "def sub\n\tputs 2-2\nend" ]
[ "0.80283225", "0.7977191", "0.79619974", "0.7734897", "0.7718372", "0.7708104", "0.77013636", "0.75006264", "0.74790674", "0.73886573", "0.73772085", "0.7348514", "0.73257035", "0.7293632", "0.7219465", "0.7195867", "0.71928096", "0.7190184", "0.71810865", "0.71699834", "0.71307635", "0.7129395", "0.71192145", "0.71173304", "0.7102914", "0.7101079", "0.70930874", "0.7075778", "0.70679605", "0.70636064", "0.704771", "0.7030182", "0.7029995", "0.7022497", "0.70197666", "0.70128155", "0.7010757", "0.70018196", "0.6994458", "0.69919896", "0.699062", "0.6988801", "0.69830745", "0.6975324", "0.69703084", "0.6962654", "0.6957686", "0.69484466", "0.6945615", "0.6943726", "0.6930903", "0.6928971", "0.69164544", "0.69124055", "0.6907442", "0.6898832", "0.689784", "0.6897694", "0.6894918", "0.6894275", "0.6885623", "0.68833196", "0.6875911", "0.6868603", "0.6868274", "0.6865601", "0.68609434", "0.68566954", "0.68538344", "0.68518704", "0.6849657", "0.6849383", "0.68391615", "0.68377686", "0.6837112", "0.683592", "0.68227285", "0.682045", "0.6818405", "0.6800813", "0.67978126", "0.67948425", "0.6793401", "0.6781294", "0.6781294", "0.6778599", "0.67732394", "0.6772963", "0.677219", "0.677219", "0.6771347", "0.6771347", "0.67708665", "0.67628443", "0.67542595", "0.6752819", "0.6751946", "0.6751341", "0.6750831" ]
0.7958045
4
Forces the request format to be :mobile
def force_mobile_format unless request.xhr? request.format = :mobile session[:mobile_view] = true if session[:mobile_view].nil? end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def handle_mobile\n return if session[:mobylette_override] == :ignore_mobile\n if respond_as_mobile?\n request.format = set_mobile_format\n end\n end", "def set_mobile_format\n if !mobile_exempt? && is_mobile_device? && !request.xhr?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def handle_mobile\n return if session[:mobylette_override] == :ignore_mobile\n if respond_as_mobile?\n\n original_format = request.format.to_sym\n request.format = :mobile\n if self.mobylette_options[:fall_back] != false\n request.formats << Mime::Type.new(self.mobylette_options[:fall_back] || original_format)\n end\n end\n end", "def handle_mobile\n return if session[:mobylette_override] == :ignore_mobile\n if respond_as_mobile?\n\n original_format = request.format.to_sym\n request.format = :mobile\n if self.mobylette_options[:fall_back] != false\n request.formats << Mime::Type.new(self.mobylette_options[:fall_back] || original_format)\n end\n end\n end", "def set_mobile_format\n if is_mobile_device?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def set_mobile_format\n if is_mobile_device? && !request.xhr?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def set_mobile_format\n if is_mobile_device?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def set_mobile_format\n if is_mobile_device? && !request.xhr?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def prepare_for_mobile\r\n session[:mobile_param] = params[:mobile] if params[:mobile]\r\n request.format = :mobile if mobile_device?\r\n end", "def prepare_for_mobile\n session[:mobile_param] = params[:mobile] if params[:mobile]\n request.format = :mobile if mobile_device?\n end", "def set_mobile_format\n if self.mobylette_options[:fallback_chains]\n self.mobylette_options[:fallback_chains].keys.each do |device|\n return device if request_device?(device)\n end\n end\n :mobile \n end", "def in_mobile_view?\n request.format.to_sym == :mobile\n end", "def adjust_format_for_iphone\n if request.format == :html\n request.format = :iphone if mobile_device?\n end\n end", "def in_mobile_view?\n request.format.to_sym == :mobile\n end", "def in_mobile_view?\n request.format.to_sym == :mobile\n end", "def prepare_for_mobile\n if Rails.env.development?\n session[:mobile_param] = params[:mobile] if params[:mobile]\n request.format = :mobile if mobile_device?\n end\n end", "def adjust_format_for_iphone \n request.format = :iphone if iphone_request?\n end", "def force_iphone_format\n request.format = :iphone\n end", "def adjust_format_for_iphone\n request.format = :iphone if iphone_request?\n end", "def adjust_format_for_iphone\n request.format = :iphone if iphone_request?\n end", "def determine_format\n mobile_request? ? mobile_format.to_sym : request.format.to_sym\n end", "def mobile?\n return params[:format] == 'm'\n end", "def mobile?\n return params[:format] == 'm'\n end", "def respond_as_mobile?\n processing_xhr_requests? and skip_mobile_param_not_present? and (force_mobile_by_session? or is_mobile_request? or (params[:format] == 'mobile'))\n end", "def respond_as_mobile?\n processing_xhr_requests? and skip_mobile_param_not_present? and (force_mobile_by_session? or allow_mobile_response? or (params[:format] == 'mobile'))\n end", "def in_mobile_view?\n return false unless request.format\n request.format.to_sym == :mobile\n end", "def is_mobile_view?\n request.format.to_sym == :mobile\n end", "def is_mobile_view?\n true if (params[:format] == \"mobile\") || (request.format.to_s == \"mobile\")\n end", "def respond_as_mobile?\n impediments = stop_processing_because_xhr? || stop_processing_because_param?\n (not impediments) && (force_mobile_by_session? || is_mobile_request? || params[:format] == 'mobile')\n end", "def is_mobile_view?\n true if (request.format.to_s == \"mobile\") or (params[:format] == \"mobile\")\n end", "def is_mobile_view?\n true if (request.format.to_s == \"mobile\") or (params[:format] == \"mobile\")\n end", "def mobile\n _auth(true)\n end", "def mobile_format\n strfphone(MOBILE_FORMAT)\n end", "def set_iphone_format\n if is_iphone_request? || is_iphone_format? || is_iphone_subdomain?\n request.format = cookies[\"browser\"] == \"desktop\" ? :html : :iphone \n end\n end", "def mobile_param_value\n mobile_request? ? mobile_path_prefix : nil\n end", "def mobile_phone\n return unless @user.loa3?\n\n dig_out('telephones', 'phone_type', VAProfile::Models::Telephone::MOBILE)\n end", "def mobile_standard\n if request.env[\"HTTP_X_MOBILE_GATEWAY\"]\n out = nil\n else\n\n # request.env[\"HTTP_USER_AGENT\"].match(\"iPhone\") ? \"mobile\" : \"callc\"\n if session[:layout_t]\n if session[:layout_t].to_s == \"mini\"\n\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n if session[:layout_t].to_s == \"full\" or session[:layout_t].to_s == nil\n out = \"callc\"\n end\n if session[:layout_t].to_s == \"callcenter\"\n out = \"callcenter\"\n end\n else\n if !(request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\") or request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPod\"))\n out = \"callc\"\n end\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n end\n return out\n end", "def show\n respond_to do |format|\n format.html.phone {\n render layout: 'mobile'\n }\n format.html {\n }\n format.json\n end\n end", "def mobile_phone=(value)\n @mobile_phone = value\n end", "def set_Mobile(value)\n set_input(\"Mobile\", value)\n end", "def all_mobile_params\n params.require(:all_mobile).permit(:mobile, :client_id)\n end", "def new\n @phone_number = @kontact_information.phone_numbers.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.mobile\n format.xml { render :xml => @phone_number }\n end\n end", "def setUseMobileUserAgent(value)\n @fields['use_mobile_user_agent'] = value\n self\n end", "def setUseMobileUserAgent(value)\n @fields['use_mobile_user_agent'] = value\n self\n end", "def mobile?\n true\n end", "def mobile?\n true\n end", "def is_mobile?\n country.is_mobile? \"#{area_code}#{number}\"\n end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ Regexp.union(MOBILE_USER_AGENTS)\n end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ /#{MOBILE_USER_AGENTS}/\n end", "def mobile_request?\n @mobile_request ||= !!(request.path =~ /^\\/#{mobile_path_prefix}(\\/.*)?$/)\n end", "def is_mobile_request?\n (not user_agent_excluded?) && !(request.user_agent.to_s.downcase =~ @@mobylette_options[:mobile_user_agents].call).nil?\n end", "def mobile?\n @mobile\n end", "def is_mobile?(number)\n return true if mobile_format.nil?\n number =~ mobile_number_regex ? true : false\n end", "def mobile?\n user_agent = request.user_agent.to_s.downcase rescue \"false\"\n return false if user_agent =~ /ipad/\n user_agent =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def mobile_url(url = request.url)\n mobile_path(url)\n end", "def new\n @mobile = Mobile.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @mobile }\n end\n end", "def create\n @mobile = Mobile.new(params[:mobile])\n\n respond_to do |format|\n if @mobile.save\n format.html { redirect_to @mobile, notice: 'Mobile was successfully created.' }\n format.json { render json: @mobile, status: :created, location: @mobile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @mobile.errors, status: :unprocessable_entity }\n end\n end\n end", "def uses_mobile?(phone_number)\n PhoneNumber::MOBILE_PREFIXES.any? { |prefix| phone_number.starts_with?(prefix) }\n end", "def mobile_no_formatting(arg)\n if arg.present? \n if arg.downcase.include?('toll') || arg.downcase.include?('phone') || arg.downcase.include?('direct') || arg.downcase.include?('office')\n return number_to_phone(arg.gsub(/[^\\d,\\.]/, '').to_i, area_code: true)\n elsif arg.downcase.include?('ext')\n phone_number = arg.downcase.split('ext')\n phone = if phone_number[0].to_i == 0 || phone_number[0].to_i.to_s.size < 10\n ph = phone_number[0].gsub!(/[^0-9A-Za-z]/, '')\n ph = ph[1..10] if ph.length > 10\n number_to_phone(ph, area_code: true)\n else\n number_to_phone(phone_number[0].to_i, area_code: true)\n end\n return phone.to_s + ' Ext'+ remove_unnecessary_keywords(phone_number[1])\n elsif arg.include?('(') || arg.include?(')') || arg.include?('-') || arg.include?('.') || arg.include?(' ')\n arg = arg.gsub!(/[^0-9A-Za-z]/, '')\n arg = arg[1..10] if arg.length > 10\n return number_to_phone(arg.to_i, area_code: true) \n elsif arg.include?('x') || arg.include?('�')\n arg = arg.gsub('�', '') if arg.include?('�')\n arg = arg[1..10] if arg.length > 10\n return number_to_phone(arg.to_i, area_code: true)\n else\n arg = arg[1..10] if arg.length > 10\n return number_to_phone(arg.to_i, area_code: true) \n end\n end\n\n end", "def mobile?\n agent_str = request.env[\"HTTP_USER_AGENT\"].to_s.downcase\n return false if agent_str =~ /ipad/\n agent_str =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def mobile_phone\n return @mobile_phone\n end", "def update_mobile_phone_number\n begin\n self.mobile_phone_number = self.mobile_phone.tr('^0-9', '')\n rescue\n return nil\n end\n end", "def new\n @mobile_user = MobileUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @mobile_user }\n end\n end", "def set_variant\n # request.variant = :phone if request.user_agent.include?('iPhone')\n # o con la gema browser\n request.variant = :phone if browser.device.mobile?\n end", "def skip_mobile_param_not_present?\n params[:skip_mobile] != 'true'\n end", "def skip_mobile_param_not_present?\n params[:skip_mobile] != 'true'\n end", "def mobile?\n os_parser.mobile?\n end", "def check_platform\n mobile_override = params[:mobile] && params[:mobile] == \"1\"\n desktop_override = params[:mobile] && params[:mobile] == \"0\"\n if ( (browser.mobile? and !browser.ipad?) or mobile_override ) and !request.xhr? and !desktop_override\n @platform = 'mobile'\n request.format = :mobile\n else\n @platform = 'desktop'\n end\n end", "def phone_params\n params.require(:phone).permit(:mobile)\n end", "def is_iphone_format?\n request.format.to_sym == :iphone\n end", "def to_mobile( str )\n\tstr.dup\nend", "def redirect_for_mobile\n if request.mobile?\n pa = params.dup\n pa[:controller] = \"/mobile\"\n pa[:action] = \"index\"\n redirect_to pa\n end\n end", "def mobile?\n return false if number.nil?\n self.number = self.number.gsub(' ', '')\n MOBILE_PREFIXES.any? { |prefix| number.starts_with?(prefix) }\n end", "def mobile_phone\n self.dig_for_string(\"agentSummary\", \"mobilePhone\")\n end", "def mobile_device?\n if session[:mobile_param]\n session[:mobile_param] == \"1\"\n else\n if request.user_agent =~ /Mobile|webOS/\n session[:mobile_param] = \"1\"\n return true\n else\n return false\n end\n end\n end", "def authorize_mobile!\n doorkeeper_authorize! :full_access, :mobile\n end", "def force_mobile_by_session?\n session[:mobylette_override] == :force_mobile\n end", "def is_mobile_device?\n Handset.is_mobile? request.user_agent\n end", "def mobile_device?\r\n if session[:mobile_param]\r\n session[:mobile_param] == \"1\"\r\n else\r\n request.user_agent =~ /Mobile|webOS/\r\n end\r\n end", "def force_mobile_by_session?\n session[:mobylette_override] == :force_mobile\n end", "def force_mobile_by_session?\n session[:mobylette_override] == :force_mobile\n end", "def message_type\n 'sms'\n end", "def process_page_with_mobile(page)\n page.app = app?\n page.mobile = app? || mobile?\n process_page_without_mobile(page)\n end", "def is_mobile_device()\n res = self.send_request 'is_mobile_device'\n return res.body\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.mobile\n format.xml { render :xml => @email }\n end\n end", "def create\n @mobile = Mobile.new(params[:mobile])\n\n respond_to do |format|\n if @mobile.save\n format.html { redirect_to(@mobile, :notice => 'Mobile was successfully created.') }\n format.xml { render :xml => @mobile, :status => :created, :location => @mobile }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @mobile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def is_mobile?\n !!self.mobile_device_name\n end", "def mobile_optional(&block)\n scope(\"(:mobile)\", {\n defaults: { mobile: nil },\n mobile: /(#{mobile_path_prefix})?/\n }, &block)\n end", "def customer_phone\n params['mobileNo']\n end", "def mobile_number\n \"#{mobile_phone_prefix}-#{short_phone_number}\"\n end", "def mobile_path(path = request.path)\n path.gsub(/^(.*?\\/\\/.*?)?\\/(#{mobile_path_prefix}\\/?)?(.*)$/) do\n \"#{$1}/#{mobile_path_prefix}/#{$3}\"\n end.freeze\n end", "def mobile_request?\n #hack for request.domain in case issue with subdomain\n request.subdomains.first == 'm' || request.domain.first == 'm'\n end", "def set_mobile_phone\n @mobile_phone = MobilePhone.friendly.find(params[:id])\n end", "def create_mobile\n @user = User.new(params[:user])\n @user.timezone = params[:timezone]\n if @user.save\n #render :json => @user\n respond_with(@user)\n else \n logger.debug(\"errror creating user in API\")\n end\n end", "def mobile_modifier()\n if browser.device.mobile?\n return '-mobile'\n else\n return ''\n end\n end", "def new\n @mobile = Mobile.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @mobile }\n end\n end", "def new\n @mobile = Mobile.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @mobile }\n end\n end", "def is_mobile_browser?\n Handset.is_mobile? request.user_agent\n end", "def create\n @mobile = Mobile.new(params[:mobile])\n\n respond_to do |format|\n if @mobile.save\n flash[:notice] = 'Mobile was successfully created.'\n format.html { redirect_to(@mobile) }\n format.xml { render :xml => @mobile, :status => :created, :location => @mobile }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @mobile.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
[ "0.7999035", "0.77233654", "0.76544625", "0.76544625", "0.76067305", "0.7598015", "0.7591584", "0.7575264", "0.74661297", "0.73907405", "0.7111284", "0.7108537", "0.7048257", "0.7028259", "0.7027514", "0.6986914", "0.6967916", "0.69441617", "0.69310933", "0.69310933", "0.6923758", "0.6896372", "0.6896372", "0.6887991", "0.68832874", "0.68703306", "0.6849834", "0.6831963", "0.67420256", "0.66570556", "0.66570556", "0.66201746", "0.64990264", "0.6460172", "0.63123226", "0.62815005", "0.625576", "0.6184069", "0.60832554", "0.60789067", "0.60747236", "0.60580426", "0.59991777", "0.59991777", "0.5967609", "0.5967609", "0.5950248", "0.5920533", "0.5916746", "0.5887444", "0.5881825", "0.587987", "0.5842014", "0.5838971", "0.58298796", "0.5820315", "0.5807201", "0.5789512", "0.5783071", "0.5768718", "0.57548577", "0.5728737", "0.5728116", "0.57238024", "0.5708883", "0.5708883", "0.5692079", "0.56879395", "0.56796646", "0.566019", "0.56594974", "0.56539464", "0.5649572", "0.5647737", "0.5615428", "0.5593165", "0.55909956", "0.5584358", "0.556705", "0.5560765", "0.5560765", "0.5555179", "0.55542177", "0.55498934", "0.5547816", "0.5547179", "0.554693", "0.553908", "0.553806", "0.5530055", "0.5524985", "0.55201745", "0.5516014", "0.5513408", "0.54822457", "0.547839", "0.547839", "0.5468555", "0.54587346" ]
0.7713949
3
Determines the request format based on whether the device is mobile or if the user has opted to use either the 'Standard' view or 'Mobile' view.
def set_mobile_format if is_mobile_device? && !request.xhr? request.format = session[:mobile_view] == false ? :html : :mobile session[:mobile_view] = true if session[:mobile_view].nil? end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def determine_format\n mobile_request? ? mobile_format.to_sym : request.format.to_sym\n end", "def in_mobile_view?\n return false unless request.format\n request.format.to_sym == :mobile\n end", "def is_mobile_view?\n request.format.to_sym == :mobile\n end", "def handle_mobile\n return if session[:mobylette_override] == :ignore_mobile\n if respond_as_mobile?\n\n original_format = request.format.to_sym\n request.format = :mobile\n if self.mobylette_options[:fall_back] != false\n request.formats << Mime::Type.new(self.mobylette_options[:fall_back] || original_format)\n end\n end\n end", "def handle_mobile\n return if session[:mobylette_override] == :ignore_mobile\n if respond_as_mobile?\n\n original_format = request.format.to_sym\n request.format = :mobile\n if self.mobylette_options[:fall_back] != false\n request.formats << Mime::Type.new(self.mobylette_options[:fall_back] || original_format)\n end\n end\n end", "def set_mobile_format\n if !mobile_exempt? && is_mobile_device? && !request.xhr?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def in_mobile_view?\n request.format.to_sym == :mobile\n end", "def is_mobile_view?\n true if (params[:format] == \"mobile\") || (request.format.to_s == \"mobile\")\n end", "def set_mobile_format\n if is_mobile_device? && !request.xhr?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def in_mobile_view?\n request.format.to_sym == :mobile\n end", "def set_mobile_format\n if is_mobile_device?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def in_mobile_view?\n request.format.to_sym == :mobile\n end", "def set_mobile_format\n if is_mobile_device?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def is_mobile_view?\n true if (request.format.to_s == \"mobile\") or (params[:format] == \"mobile\")\n end", "def is_mobile_view?\n true if (request.format.to_s == \"mobile\") or (params[:format] == \"mobile\")\n end", "def mobile_standard\n if request.env[\"HTTP_X_MOBILE_GATEWAY\"]\n out = nil\n else\n\n # request.env[\"HTTP_USER_AGENT\"].match(\"iPhone\") ? \"mobile\" : \"callc\"\n if session[:layout_t]\n if session[:layout_t].to_s == \"mini\"\n\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n if session[:layout_t].to_s == \"full\" or session[:layout_t].to_s == nil\n out = \"callc\"\n end\n if session[:layout_t].to_s == \"callcenter\"\n out = \"callcenter\"\n end\n else\n if !(request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\") or request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPod\"))\n out = \"callc\"\n end\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n end\n return out\n end", "def handle_mobile\n return if session[:mobylette_override] == :ignore_mobile\n if respond_as_mobile?\n request.format = set_mobile_format\n end\n end", "def set_mobile_format\n if self.mobylette_options[:fallback_chains]\n self.mobylette_options[:fallback_chains].keys.each do |device|\n return device if request_device?(device)\n end\n end\n :mobile \n end", "def adjust_format_for_iphone\n if request.format == :html\n request.format = :iphone if mobile_device?\n end\n end", "def force_mobile_format\n unless request.xhr?\n request.format = :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def force_mobile_format\n unless request.xhr?\n request.format = :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def mobile?\n return params[:format] == 'm'\n end", "def mobile?\n return params[:format] == 'm'\n end", "def set_iphone_format\n if is_iphone_request? || is_iphone_format? || is_iphone_subdomain?\n request.format = cookies[\"browser\"] == \"desktop\" ? :html : :iphone \n end\n end", "def determine_request_type\n if request.request_method == 'GET'\n case params[:format] # explicit format parameter\n when 'html'\n return :html\n when 'json'\n return :json\n end\n end\n all_ok = request.accept.include?('*/*')\n json_ok = request.accept.find { |header| header =~ /json/ }\n html_ok = request.accept.find { |header| header =~ /html/ }\n\n if all_ok\n if request.xhr?\n :json\n else\n :html\n end\n elsif json_ok and not html_ok\n :json\n elsif html_ok and not json_ok\n :html\n else\n :html\n end\n end", "def respond_as_mobile?\n processing_xhr_requests? and skip_mobile_param_not_present? and (force_mobile_by_session? or allow_mobile_response? or (params[:format] == 'mobile'))\n end", "def check_platform\n mobile_override = params[:mobile] && params[:mobile] == \"1\"\n desktop_override = params[:mobile] && params[:mobile] == \"0\"\n if ( (browser.mobile? and !browser.ipad?) or mobile_override ) and !request.xhr? and !desktop_override\n @platform = 'mobile'\n request.format = :mobile\n else\n @platform = 'desktop'\n end\n end", "def respond_as_mobile?\n processing_xhr_requests? and skip_mobile_param_not_present? and (force_mobile_by_session? or is_mobile_request? or (params[:format] == 'mobile'))\n end", "def is_iphone_format?\n request.format.to_sym == :iphone\n end", "def respond_as_mobile?\n impediments = stop_processing_because_xhr? || stop_processing_because_param?\n (not impediments) && (force_mobile_by_session? || is_mobile_request? || params[:format] == 'mobile')\n end", "def adjust_format_for_iphone\n request.format = :iphone if iphone_request?\n end", "def adjust_format_for_iphone\n request.format = :iphone if iphone_request?\n end", "def adjust_format_for_iphone \n request.format = :iphone if iphone_request?\n end", "def device_type\n case request.user_agent\n when /mobile/i\n \"mobile\"\n when /iPad/i\n \"tablet\"\n when /Android/i\n \"tablet\"\n else\n \"desktop\"\n end\n end", "def determine_layout\n mobile_request? ? mobile_layout : desktop_layout\n end", "def set_variant\n if request.user_agent =~\n /mobile|android|touch|webos|hpwos|iphone|iPhone|iPad|ipod|\n android|blackberry|opera|mini|windows\\sce|palm|smartphone|iemobile|\n ipad|android 3.0|xoom|sch-i800|playbook|tablet|kindle/\n\n request.variant = :mobile\n else\n request.variant = :desktop\n end\n end", "def set_request_variant\n request.variant = :mobile if request.user_agent =~ /android|Android|blackberry|iphone|ipod|iemobile|mobile|webos/\n request.variant = :android_app if request.user_agent =~ /AndroidApp/\n puts \"--------------\"+request.variant.to_s+\"--------------\"\n end", "def format\n \n # If &format= is present we let that win\n if params.size > 0 and params.key?(\"format\")\n format = params[\"format\"]\n else\n # No &format, let Accept header win for GET, DELETE and\n\n if [\"PUT\", \"POST\"].include? request_method\n # Use Content-Type for POST, PUT\n format = media_format\n else\n # GET and DELETE, use Accept header\n format = accept_format\n end\n end\n \n if format.empty?\n # Still no format, go for .format\n format = format_from_path\n end\n \n # Still empty, set to \"\"\n if format.empty?\n format = \"\"\n end\n format\n end", "def format?\n # if :custom\n if self.conventional?\n :conventional\n elsif self.relaxed?\n :relax\n elsif self.redacted?\n :redacted\n elsif self.standard?\n :standard\n else\n :invalid\n end\n end", "def mobile_format\n strfphone(MOBILE_FORMAT)\n end", "def media_format\n media_format = \"\"\n if media_type =~ /[\\/]/\n media_format = media_type.split(\"/\")[1]\n if \"x-www-form-urlencoded\" == media_format\n media_format = format # use regular format instead, we never want form data\n end\n end\n \n media_format\n end", "def mobile_viewer?\n mobile_param = params[:mobile]\n viewer = params[:viewer]\n\n (mobile_param == 'true') || (viewer == 'android') || (viewer == 'ios')\n end", "def prepare_for_mobile\r\n session[:mobile_param] = params[:mobile] if params[:mobile]\r\n request.format = :mobile if mobile_device?\r\n end", "def prepare_for_mobile\n session[:mobile_param] = params[:mobile] if params[:mobile]\n request.format = :mobile if mobile_device?\n end", "def prepare_for_mobile\n if Rails.env.development?\n session[:mobile_param] = params[:mobile] if params[:mobile]\n request.format = :mobile if mobile_device?\n end\n end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ Regexp.union(MOBILE_USER_AGENTS)\n end", "def mobile_detect\n logger.info(\"request from tablet device\") if is_tablet_device?\n logger.info(\"request from mobile device\") if is_mobile_device?\n\n #for header in request.env.select {|k,v| k.match(\"^HTTP.*\")}\n # puts \"#{header} = #{request.env[header]}\"\n #end\n\n # first use mobile-fu methods to determine if we have a mobile device at all.\n if is_mobile_or_tablet?\n # find out device and ppi\n # attempt 1: check LifeSize cookie\n screen_data = ScreenData.new(cookies[ApplicationController::LIFESIZE_COOKIE])\n stored_config = screen_data.first_config # on mobile, there should only ever be one screen config in the cookie\n\n device = nil\n if stored_config\n # found a device config in cookie, attempt to look it up. Even though the ppi is stored in the cookie,\n # we'll use the value from the database since it may have been changed/corrected.\n # We also use the Device to get the display name\n device = Device.by_device_id(stored_config[:name])\n logger.info(\"detected device #{device.display_name} from cookie\") if device\n end\n if !(device && device.can_render_images_on?)\n # no stored config or device couldn't be found. Use handset detection to find it\n device = lookup_mobile_device\n if device\n logger.info(\"detected device #{device.display_name} using handsetdetection\")\n else\n # give up, couldn't look up mobile device. Render non-mobile view instead\n logger.error(\"problem with handsetdetection, unable to detect mobile device for request with user agent: #{request.headers['user-agent']}\")\n request.format = :html\n return true\n end\n end\n\n # use the device pixel ratio from the Device model, unless that device has not yet been verified\n # AND the device pixel ratio was set in the request\n device_pixel_ratio = device.device_pixel_ratio\n if params[:r]\n if !device.verified?\n # device isn't verified yet, use pixel ratio from request\n device_pixel_ratio = params[:r].to_f\n logger.info(\"device #{device.display_name} not yet verified, using device pixel ratio #{device_pixel_ratio} from request\")\n elsif params[:r].to_f != device_pixel_ratio\n # known pixel ratio for this device is not the same as what we received in the request. Log this, but don't act on it:\n # assume the info in our db to be accurate.\n logger.warn(\"verified #{device.display_name} has pixel ratio #{device_pixel_ratio}, but doesn't match value from request: #{params[:r]}\")\n end\n end\n\n config = nil\n if device && device.can_render_images_on?\n # only if we have a device and PPI and resolution is known\n config = { :width => (device.resolution_x / device_pixel_ratio).round,\n :height => (device.resolution_y / device_pixel_ratio).round,\n :ppi => device.ppi / device_pixel_ratio,\n :name => device.device_id\n }\n @mobile_match = true\n @mobile_device_name = device.display_name\n else\n # couldn't detect device. See if we can detect it locally\n config = local_handheld_detect\n if config\n logger.info(\"able to detect mobile/tablet #{config[:name]} with local matchers\")\n @mobile_match = true\n @mobile_device_name = I18n.t(\".screen.#{config[:name]}\")\n else\n logger.info(\"unable to detect handset\")\n config = { :ppi => 160, :name => 'unknown', :width => 0, :height => 0 }\n @mobile_match = false\n @mobile_device_name = 'Unknown'\n end\n end\n screen_data.clear # delete any previously stored screens\n cookie = screen_data.save_screen_config(config[:width], config[:height], {:ppi => config[:ppi], :name => config[:name]})\n cookies[ApplicationController::LIFESIZE_COOKIE] = cookie\n\n request.format = :mobile\n @lifesize = LifeSize.new(config)\n end\n true\n end", "def set_variant\n # request.variant = :phone if request.user_agent.include?('iPhone')\n # o con la gema browser\n request.variant = :phone if browser.device.mobile?\n end", "def handable_format?\n @request.format.symbol.nil? || (@request.format.symbol == :html)\n end", "def set_device\n # if HTTP_USER_AGENT is blank/nil defaults to blank, i.e. desktop \n agent = request.env[\"HTTP_USER_AGENT\"].blank? ? \"\" : request.env[\"HTTP_USER_AGENT\"].downcase \n if agent =~ tablet_agents\n \"tablet\"\n elsif (agent =~ mobile_agents_one) || (agent[0..3] =~ mobile_agents_two)\n \"mobile\"\n else\n \"desktop\"\n end \n end", "def show\n respond_to do |format|\n format.html.phone {\n render layout: 'mobile'\n }\n format.html {\n }\n format.json\n end\n end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ /#{MOBILE_USER_AGENTS}/\n end", "def find_device_type\n case request.user_agent\n # when /mac|ios/i\n # :ios\n when /android/i\n :android\n else\n nil\n end\n end", "def is_mobile_request?\n (not user_agent_excluded?) && !(request.user_agent.to_s.downcase =~ @@mobylette_options[:mobile_user_agents].call).nil?\n end", "def set_variant_template\n request.variant = :mobile if request.user_agent =~ /iPad/\n end", "def is_device? type\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def guess_content_type\n ua = request.user_agent\n if ua.include? \"WebKit\"\n if ua.include?(\"iPhone\") && !ua.include?(\"Safari\")\n :webkit_native\n else\n :webkit\n end\n else\n :html\n end\n end", "def mobile?\n os_parser.mobile?\n end", "def response_format()\n params.has_key?(:format) ? params[:format] : :html\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include? type.to_s.downcase\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include? type.to_s.downcase\n end", "def accept_format\n return \"\" if env['HTTP_ACCEPT'].nil?\n \n format = env['HTTP_ACCEPT'].scan(/[^;,\\s]*\\/[^;,\\s]*/)[0].split(\"/\")[1]\n \n # Exception for HTML if path contains .format\n if format == 'html' and path_info =~ /.\\w+$/\n path_format = path_info.split(\".\").last\n if path_format != 'html'\n format = path_format\n end\n end\n \n if format =~ /[+]/\n format = format.split(\"+\")[0]\n end\n \n format\n end", "def force_iphone_format\n request.format = :iphone\n end", "def is_device?(type)\n\t\trequest.user_agent.to_s.downcase.include?(type.to_s.downcase)\n\tend", "def device_type\n matching = {\n ScreenSize::IOS_35 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_35,\n ScreenSize::IOS_40 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_40,\n ScreenSize::IOS_47 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_47, # also 7 & 8\n ScreenSize::IOS_55 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_55, # also 7 Plus & 8 Plus\n ScreenSize::IOS_58 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_58,\n ScreenSize::IOS_65 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_65,\n ScreenSize::IOS_IPAD => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPAD_97,\n ScreenSize::IOS_IPAD_10_5 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPAD_105,\n ScreenSize::IOS_IPAD_11 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPAD_PRO_3GEN_11,\n ScreenSize::IOS_IPAD_PRO => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPAD_PRO_129,\n ScreenSize::IOS_IPAD_PRO_12_9 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPAD_PRO_3GEN_129,\n ScreenSize::MAC => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::DESKTOP\n }\n return matching[self.screen_size]\n end", "def mobile_device?\n request.user_agent =~ /Mobile|webOS/\n end", "def mobile_device?\n if session[:mobile_override]\n session[:mobile_override] == '1'\n else\n (request.user_agent =~ /Mobile|webOS/) && (request.user_agent !~ /iPad/)\n end\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def is_mobile_browser?\n Handset.is_mobile? request.user_agent\n end", "def mobile_device?\n if session[:mobile_override].present?\n session[:mobile_override] == \"1\"\n else\n (request.user_agent =~ /Mobile|webOS/) && (request.user_agent !~ /iPad/) ? true : false\n end\n end", "def is_mobile_device?\n Handset.is_mobile? request.user_agent\n end", "def is_browser_mobile(request)\n user_agent = request.headers['HTTP_USER_AGENT']\n return true if /android/i.match(user_agent)\n return true if /iphone/i.match(user_agent)\n return true if /ipad/i.match(user_agent)\n return false\n end", "def preferred_contact_detail\n return nil if preferred_contact_method.blank?\n if preferred_contact_method == (\"Home Phone\")\n number_to_phone(phone_home)\n elsif preferred_contact_method == (\"Mobile Phone\")\n number_to_phone(phone_mobile)\n elsif preferred_contact_method.include?(\"Email\")\n email\n end\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def detect_browser\n if APP_CONFIG.force_mobile_ui\n return true\n end\n \n mobile_browsers = [\"android\", \"ipod\", \"opera mini\", \"blackberry\", \n\"palm\",\"hiptop\",\"avantgo\",\"plucker\", \"xiino\",\"blazer\",\"elaine\", \"windows ce; ppc;\", \n\"windows ce; smartphone;\",\"windows ce; iemobile\", \n\"up.browser\",\"up.link\",\"mmp\",\"symbian\",\"smartphone\", \n\"midp\",\"wap\",\"vodafone\",\"o2\",\"pocket\",\"kindle\", \"mobile\",\"pda\",\"psp\",\"treo\"]\n if request.headers[\"HTTP_USER_AGENT\"]\n\t agent = request.headers[\"HTTP_USER_AGENT\"].downcase\n\t mobile_browsers.each do |m|\n\t\t return true if agent.match(m)\n\t end \n end\n return false\n end", "def get_device_type(request)\n return nil if disabled_by_referer_set?(request) ||\n disabled_by_referer_matching?(request) ||\n disabled_by_referer_not_matching?(request)\n\n @rules.each do |regex, device_type|\n return device_type if request.url =~ regex\n end\n nil\n end", "def verify_requested_format!\n mimes = collect_mimes_from_class_level\n collector = ActionController::MimeResponds::Collector.new(mimes, request.variant)\n\n unless collector.negotiate_format(request)\n raise ActionController::UnknownFormat\n end\n end", "def check_for_mobile\n#\tuse_mobile_pages # For development only: controls if I see mobile or desktop version of a page. Uncomment line below for production.\n\tuse_mobile_pages unless desktop? # priority is to use a pages from the 'views_mobile' folder over those from the 'views' folder\n end", "def format_to_use(request)\n unless header = accept_header(request)\n raise ArgumentError, \"An Accept header must be provided to pick the right format\"\n end\n\n format = nil\n header.split(/,\\s*/).each do |name|\n next unless format = Puppet::Network::FormatHandler.format(name)\n next unless format.suitable?\n return format\n end\n\n raise \"No specified acceptable formats (#{header}) are functional on this machine\"\n end", "def mobile?\n user_agent = request.user_agent.to_s.downcase rescue \"false\"\n return false if user_agent =~ /ipad/\n user_agent =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def mobile?\n agent_str = request.env[\"HTTP_USER_AGENT\"].to_s.downcase\n return false if agent_str =~ /ipad/\n agent_str =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def ios_device_type\n case request.user_agent\n when /(iPad)/\n t('device.ios.ipad')\n when /(iPhone)/\n t('device.ios.iphone')\n when /(iPod)/\n t('device.ios.ipod')\n else\n t('device.ios.ios_device')\n end\n end", "def prefered_http_accept\n Rack::Utils.best_q_match(@request.env[\"HTTP_ACCEPT\"], %w(text/html application/json))\n end", "def mobile?\n true\n end", "def mobile?\n true\n end", "def mobile_device?\n ua = request.user_agent.to_s.downcase\n ua =~ Regexp.new(positive_markers.join('|')) && ua =~ Regexp.new(required_markers.join('|')) && ua !~ Regexp.new(negative_markers.join('|'))\n end", "def determined_by_request\n if request.xhr?\n return false\n else\n 'application'\n end\n end", "def check_request_format\n unless request.content_type == 'application/json'\n error = ErrorSerializer.serialize({ format: \"Invalid request format. Only JSON requests are supported.\" })\n render json: error, status: :unsupported_media_type\n end\n end", "def mobile?\n @mobile\n end", "def format\n if ControlledVocabulary.for(:geo_image_format).include? geo_mime_type\n ControlledVocabulary.for(:geo_image_format).find(geo_mime_type).label\n elsif ControlledVocabulary.for(:geo_raster_format).include? geo_mime_type\n ControlledVocabulary.for(:geo_raster_format).find(geo_mime_type).label\n elsif ControlledVocabulary.for(:geo_vector_format).include? geo_mime_type\n ControlledVocabulary.for(:geo_vector_format).find(geo_mime_type).label\n end\n end", "def request_format(scope)\n format = format_from_params(scope)\n format ||= format_from_request(scope)\n return format if (format && self.respond_to?(\"to_#{format}\"))\n DEFAULT_FORMAT\n end", "def mobile_device?\r\n if session[:mobile_param]\r\n session[:mobile_param] == \"1\"\r\n else\r\n request.user_agent =~ /Mobile|webOS/\r\n end\r\n end", "def response_media_type(options={})\n options = {:halt_if_unacceptable => false}.merge(options)\n accept = env['HTTP_ACCEPT']\n if accept =~ /\\S/\n begin\n best_media_type = env['rack-accept.request'].best_media_type(supported_media_types)\n rescue RuntimeError => e\n # TODO: this is a crappy way to recognize this exception \n raise unless e.message =~ /Invalid header value/\n end\n if best_media_type\n best_media_type\n else\n if options[:halt_if_unacceptable]\n logger.error \"received Accept header of #{accept.inspect}; halting with 406\"\n message = I18n.t('app.errors.request.accept',\n :default => \"The request indicated that no supported media type is acceptable. Supported media types are: %{supported_media_types}. The request specified Accept: %{accept}\",\n :accept => accept,\n :supported_media_types => supported_media_types.join(', ')\n )\n halt_error(406, {'Accept' => [message]})\n else\n supported_media_types.first\n end\n end\n else\n supported_media_types.first\n end\n end", "def default_format_json\n if(request.headers['HTTP_ACCEPT'].nil? && params[:format].nil?) ||\n (request.headers['HTTP_ACCEPT'] != 'application/xml' && params[:format] != 'xml')\n request.format = 'json'\n end\n end", "def mobile_device?\n !!(request.user_agent =~ /Mobile|webOS/i)\n end", "def is_mobile?\n !!self.mobile_device_name\n end", "def mobile?\n is_mobile_device?\n end", "def platform\n case number\n when /whatsapp/\n 'whatsapp'\n when /messenger/\n 'messenger'\n else\n 'sms'\n end\n end", "def is_mobile_or_tablet?\n # mobile_fu's method\n is_mobile_device? || is_tablet_device?\n end", "def set_default_format\n if request.format.symbol.nil? || request.format.to_s == '*/*'\n logger.debug \"[ApplicationController] Request format set to #{request.format.to_s.inspect}, forcing 'text/plain'\"\n request.format = :text\n end\n end" ]
[ "0.8514575", "0.76423806", "0.760539", "0.7587628", "0.7587628", "0.7584652", "0.755119", "0.7549973", "0.7497575", "0.74893177", "0.74883425", "0.7488262", "0.74511087", "0.7411899", "0.7411899", "0.73184055", "0.7303132", "0.7218012", "0.71842897", "0.7073713", "0.7073713", "0.7017318", "0.7017318", "0.68569696", "0.6831155", "0.672009", "0.67106104", "0.6653394", "0.65667087", "0.6525135", "0.6454597", "0.6454597", "0.64373946", "0.6415032", "0.6401875", "0.6372125", "0.62900186", "0.6227317", "0.61968994", "0.60883796", "0.6085321", "0.60323995", "0.60141706", "0.59807116", "0.586013", "0.584796", "0.5847294", "0.5825348", "0.58165723", "0.57997465", "0.5775107", "0.5771392", "0.57713026", "0.5763996", "0.57284015", "0.5728095", "0.5716723", "0.5701184", "0.5691036", "0.5686131", "0.5686131", "0.56740063", "0.56541777", "0.5648903", "0.5635308", "0.5631396", "0.56288195", "0.5627338", "0.5626262", "0.56228805", "0.55792695", "0.55769247", "0.55726606", "0.55702513", "0.5542229", "0.55403125", "0.5535453", "0.5528781", "0.55057144", "0.54973656", "0.5493696", "0.5471787", "0.5468169", "0.5463449", "0.5463449", "0.5458609", "0.5455492", "0.545023", "0.5444507", "0.5439967", "0.54374045", "0.54369164", "0.54321337", "0.5427559", "0.5417358", "0.5415728", "0.5401021", "0.5378585", "0.5375686", "0.5350679" ]
0.75309813
8
Returns either true or false depending on whether or not the format of the request is either :mobile or not.
def in_mobile_view? request.format.to_sym == :mobile end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mobile?\n return params[:format] == 'm'\n end", "def mobile?\n return params[:format] == 'm'\n end", "def in_mobile_view?\n request.format.to_sym == :mobile\n end", "def respond_as_mobile?\n processing_xhr_requests? and skip_mobile_param_not_present? and (force_mobile_by_session? or is_mobile_request? or (params[:format] == 'mobile'))\n end", "def respond_as_mobile?\n processing_xhr_requests? and skip_mobile_param_not_present? and (force_mobile_by_session? or allow_mobile_response? or (params[:format] == 'mobile'))\n end", "def is_mobile_view?\n true if (params[:format] == \"mobile\") || (request.format.to_s == \"mobile\")\n end", "def in_mobile_view?\n return false unless request.format\n request.format.to_sym == :mobile\n end", "def is_mobile_view?\n request.format.to_sym == :mobile\n end", "def is_mobile_view?\n true if (request.format.to_s == \"mobile\") or (params[:format] == \"mobile\")\n end", "def is_mobile_view?\n true if (request.format.to_s == \"mobile\") or (params[:format] == \"mobile\")\n end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ Regexp.union(MOBILE_USER_AGENTS)\n end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ /#{MOBILE_USER_AGENTS}/\n end", "def respond_as_mobile?\n impediments = stop_processing_because_xhr? || stop_processing_because_param?\n (not impediments) && (force_mobile_by_session? || is_mobile_request? || params[:format] == 'mobile')\n end", "def mobile_request?\n @mobile_request ||= !!(request.path =~ /^\\/#{mobile_path_prefix}(\\/.*)?$/)\n end", "def is_mobile?(number)\n return true if mobile_format.nil?\n number =~ mobile_number_regex ? true : false\n end", "def mobile?\n os_parser.mobile?\n end", "def mobile?\n @mobile\n end", "def mobile?\n user_agent = request.user_agent.to_s.downcase rescue \"false\"\n return false if user_agent =~ /ipad/\n user_agent =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def mobile?\n agent_str = request.env[\"HTTP_USER_AGENT\"].to_s.downcase\n return false if agent_str =~ /ipad/\n agent_str =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def mobile?\n true\n end", "def mobile?\n true\n end", "def mobile?\n return false if number.nil?\n self.number = self.number.gsub(' ', '')\n MOBILE_PREFIXES.any? { |prefix| number.starts_with?(prefix) }\n end", "def is_mobile?\n country.is_mobile? \"#{area_code}#{number}\"\n end", "def mobile_request?\n #hack for request.domain in case issue with subdomain\n request.subdomains.first == 'm' || request.domain.first == 'm'\n end", "def is_mobile_request?\n (not user_agent_excluded?) && !(request.user_agent.to_s.downcase =~ @@mobylette_options[:mobile_user_agents].call).nil?\n end", "def mobile_device?\n ua = request.user_agent.to_s.downcase\n ua =~ Regexp.new(positive_markers.join('|')) && ua =~ Regexp.new(required_markers.join('|')) && ua !~ Regexp.new(negative_markers.join('|'))\n end", "def uses_mobile?(phone_number)\n PhoneNumber::MOBILE_PREFIXES.any? { |prefix| phone_number.starts_with?(prefix) }\n end", "def mobile_device?\n if session[:mobile_param]\n session[:mobile_param] == \"1\"\n else\n if request.user_agent =~ /Mobile|webOS/\n session[:mobile_param] = \"1\"\n return true\n else\n return false\n end\n end\n end", "def is_mobile?\n !!self.mobile_device_name\n end", "def is_mobile_device?\n Handset.is_mobile? request.user_agent\n end", "def mobile_device?\r\n if session[:mobile_param]\r\n session[:mobile_param] == \"1\"\r\n else\r\n request.user_agent =~ /Mobile|webOS/\r\n end\r\n end", "def mobile_device?\n request.user_agent =~ /Mobile|webOS/\n end", "def mobile?\n @prefix =~ /\\A1/\n end", "def mobile?\n is_mobile_device?\n end", "def mobile_device?\n !!(request.user_agent =~ /Mobile|webOS/i)\n end", "def is_mobile_browser?\n Handset.is_mobile? request.user_agent\n end", "def is_mobile_device()\n res = self.send_request 'is_mobile_device'\n return res.body\n end", "def mobile_present?\n !mobile_number.nil?\n end", "def is_mobile_device?\n !!mobile_device\n end", "def is_mobile_device?\n !!mobile_device\n end", "def handle_mobile\n return if session[:mobylette_override] == :ignore_mobile\n if respond_as_mobile?\n request.format = set_mobile_format\n end\n end", "def mobile_viewer?\n mobile_param = params[:mobile]\n viewer = params[:viewer]\n\n (mobile_param == 'true') || (viewer == 'android') || (viewer == 'ios')\n end", "def mobile_device?\n if Rails.env.development?\n if session[:mobile_param] \n session[:mobile_param] == \"1\" \n else \n request.user_agent =~ /Mobile/ \n end\n else\n false\n end \n end", "def is_browser_mobile(request)\n user_agent = request.headers['HTTP_USER_AGENT']\n return true if /android/i.match(user_agent)\n return true if /iphone/i.match(user_agent)\n return true if /ipad/i.match(user_agent)\n return false\n end", "def iphone_request?\n return (request.subdomains.first == \"iphone\" || params[:format] == \"iphone\")\n end", "def is_mobile_device?\n return false if session[:force_agent] == :html\n return true if session[:force_agent] == :mobile\n \n get_device unless @device\n return @device.is_mobile? if @device\n return false\n end", "def determine_format\n mobile_request? ? mobile_format.to_sym : request.format.to_sym\n end", "def iphone_request?\n return (request.subdomains.first == \"i\" || params[:format] == \"iphone\")\n end", "def mobile_device?\n if session[:mobile_override].present?\n session[:mobile_override] == \"1\"\n else\n (request.user_agent =~ /Mobile|webOS/) && (request.user_agent !~ /iPad/) ? true : false\n end\n end", "def is_iphone_format?\n request.format.to_sym == :iphone\n end", "def valid_indian_mobile_number?(mobile_no)\n is_valid_mobile_no?(mobile_no) ? is_valid_data_with_format?(mobile_no, /^([9]{1}|[8]{1}|[7]{1})([0-9]{9})$/, \"Mobile no.\") : false\nend", "def mobile_device?\n if session[:mobile_override]\n session[:mobile_override] == '1'\n else\n (request.user_agent =~ /Mobile|webOS/) && (request.user_agent !~ /iPad/)\n end\n end", "def is_iphone_request?\n request.user_agent.downcase =~ /(mobile\\/.+safari)|(iphone)|(ipod)|(blackberry)|(symbian)|(series60)|(android)|(smartphone)|(wap)|(mobile)/\n end", "def is_mobile_device?\n self.class.supported_devices.any? do |os, version_range|\n mobile_device_info.operating_system == os &&\n version_range.member?(mobile_device_info.version)\n end\n end", "def skip_mobile_param_not_present?\n params[:skip_mobile] != 'true'\n end", "def skip_mobile_param_not_present?\n params[:skip_mobile] != 'true'\n end", "def iphone?\r\n\t\trequest.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\r\n\tend", "def handle_mobile\n return if session[:mobylette_override] == :ignore_mobile\n if respond_as_mobile?\n\n original_format = request.format.to_sym\n request.format = :mobile\n if self.mobylette_options[:fall_back] != false\n request.formats << Mime::Type.new(self.mobylette_options[:fall_back] || original_format)\n end\n end\n end", "def handle_mobile\n return if session[:mobylette_override] == :ignore_mobile\n if respond_as_mobile?\n\n original_format = request.format.to_sym\n request.format = :mobile\n if self.mobylette_options[:fall_back] != false\n request.formats << Mime::Type.new(self.mobylette_options[:fall_back] || original_format)\n end\n end\n end", "def check_platform\n mobile_override = params[:mobile] && params[:mobile] == \"1\"\n desktop_override = params[:mobile] && params[:mobile] == \"0\"\n if ( (browser.mobile? and !browser.ipad?) or mobile_override ) and !request.xhr? and !desktop_override\n @platform = 'mobile'\n request.format = :mobile\n else\n @platform = 'desktop'\n end\n end", "def is_valid_mobile_no?(mobile_no)\n (mobile_no.to_i > 0) ? valid_mobile_no_length?(mobile_no) : false\nend", "def set_mobile_format\n if !mobile_exempt? && is_mobile_device? && !request.xhr?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def desktop_request?\n !mobile_request?\n end", "def china_mobile?\n country_code == '86'\n end", "def iphone?\n request.user_agent =~ /iPhone/i\n end", "def set_mobile_format\n if is_mobile_device? && !request.xhr?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def request_device?(device)\n (request.user_agent.to_s.downcase =~ (Mobylette.devices.device(device) || %r{not_to_be_matched_please}) ? true : false)\n end", "def force_mobile_by_session?\n session[:mobylette_override] == :force_mobile\n end", "def force_mobile_by_session?\n session[:mobylette_override] == :force_mobile\n end", "def set_mobile_format\n if is_mobile_device?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def set_mobile_format\n if is_mobile_device? && !request.xhr?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def mobile_verification_missing?\n return false if test_user? && ENV[\"TEST_USERS_SKIP_MOBILE_VERIFICATION\"]\n return !mobile_phone_verified?\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def set_mobile_format\n if is_mobile_device?\n request.format = session[:mobile_view] == false ? :html : :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def force_mobile_by_session?\n session[:mobylette_override] == :force_mobile\n end", "def windows_phone?\n !!(ua =~ /Windows Phone/)\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] &&\n request.env[\"HTTP_USER_AGENT\" ][/(Mobile\\/.+Safari)/]\n end", "def sms?\n message_type&.to_sym == :sms\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def is_iphone_request?\n request.user_agent =~ /(Mobile\\/.+Safari)/\n end", "def windows_mobile?\n !!(ua =~ /Windows CE/)\n end", "def mobile_device?\n # We CAN'T check if the device is an +Appium::Driver+ since it is not a RemoteWebDriver. Because of that we use a\n # flag we got as an option in the constructor.\n @is_mobile_device\n end", "def prepare_for_mobile\r\n session[:mobile_param] = params[:mobile] if params[:mobile]\r\n request.format = :mobile if mobile_device?\r\n end", "def mobile_detect\n logger.info(\"request from tablet device\") if is_tablet_device?\n logger.info(\"request from mobile device\") if is_mobile_device?\n\n #for header in request.env.select {|k,v| k.match(\"^HTTP.*\")}\n # puts \"#{header} = #{request.env[header]}\"\n #end\n\n # first use mobile-fu methods to determine if we have a mobile device at all.\n if is_mobile_or_tablet?\n # find out device and ppi\n # attempt 1: check LifeSize cookie\n screen_data = ScreenData.new(cookies[ApplicationController::LIFESIZE_COOKIE])\n stored_config = screen_data.first_config # on mobile, there should only ever be one screen config in the cookie\n\n device = nil\n if stored_config\n # found a device config in cookie, attempt to look it up. Even though the ppi is stored in the cookie,\n # we'll use the value from the database since it may have been changed/corrected.\n # We also use the Device to get the display name\n device = Device.by_device_id(stored_config[:name])\n logger.info(\"detected device #{device.display_name} from cookie\") if device\n end\n if !(device && device.can_render_images_on?)\n # no stored config or device couldn't be found. Use handset detection to find it\n device = lookup_mobile_device\n if device\n logger.info(\"detected device #{device.display_name} using handsetdetection\")\n else\n # give up, couldn't look up mobile device. Render non-mobile view instead\n logger.error(\"problem with handsetdetection, unable to detect mobile device for request with user agent: #{request.headers['user-agent']}\")\n request.format = :html\n return true\n end\n end\n\n # use the device pixel ratio from the Device model, unless that device has not yet been verified\n # AND the device pixel ratio was set in the request\n device_pixel_ratio = device.device_pixel_ratio\n if params[:r]\n if !device.verified?\n # device isn't verified yet, use pixel ratio from request\n device_pixel_ratio = params[:r].to_f\n logger.info(\"device #{device.display_name} not yet verified, using device pixel ratio #{device_pixel_ratio} from request\")\n elsif params[:r].to_f != device_pixel_ratio\n # known pixel ratio for this device is not the same as what we received in the request. Log this, but don't act on it:\n # assume the info in our db to be accurate.\n logger.warn(\"verified #{device.display_name} has pixel ratio #{device_pixel_ratio}, but doesn't match value from request: #{params[:r]}\")\n end\n end\n\n config = nil\n if device && device.can_render_images_on?\n # only if we have a device and PPI and resolution is known\n config = { :width => (device.resolution_x / device_pixel_ratio).round,\n :height => (device.resolution_y / device_pixel_ratio).round,\n :ppi => device.ppi / device_pixel_ratio,\n :name => device.device_id\n }\n @mobile_match = true\n @mobile_device_name = device.display_name\n else\n # couldn't detect device. See if we can detect it locally\n config = local_handheld_detect\n if config\n logger.info(\"able to detect mobile/tablet #{config[:name]} with local matchers\")\n @mobile_match = true\n @mobile_device_name = I18n.t(\".screen.#{config[:name]}\")\n else\n logger.info(\"unable to detect handset\")\n config = { :ppi => 160, :name => 'unknown', :width => 0, :height => 0 }\n @mobile_match = false\n @mobile_device_name = 'Unknown'\n end\n end\n screen_data.clear # delete any previously stored screens\n cookie = screen_data.save_screen_config(config[:width], config[:height], {:ppi => config[:ppi], :name => config[:name]})\n cookies[ApplicationController::LIFESIZE_COOKIE] = cookie\n\n request.format = :mobile\n @lifesize = LifeSize.new(config)\n end\n true\n end", "def prepare_for_mobile\n session[:mobile_param] = params[:mobile] if params[:mobile]\n request.format = :mobile if mobile_device?\n end", "def force_mobile_format\n unless request.xhr?\n request.format = :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def force_mobile_format\n unless request.xhr?\n request.format = :mobile\n session[:mobile_view] = true if session[:mobile_view].nil?\n end\n end", "def valid_format_email_or_phone?\n email_or_phone =~ email_fromat || email_or_phone =~ mobile_fromat || email_or_phone.blank?\n end", "def stop_processing_because_param?\n return true if params[:skip_mobile] == 'true'\n false\n end", "def mobile\n _auth(true)\n end", "def smsable?\n properties.include?(\"smsable\")\n end", "def is_mobile_or_tablet?\n # mobile_fu's method\n is_mobile_device? || is_tablet_device?\n end", "def valid?\n\t\t\t\t((request.format.symbol == :json) || (params[\"format\"] != nil && params[\"format\"] == \"json\")) && params[\"email\"]\n\t\t\tend", "def set_mobile_format\n if self.mobylette_options[:fallback_chains]\n self.mobylette_options[:fallback_chains].keys.each do |device|\n return device if request_device?(device)\n end\n end\n :mobile \n end", "def iphone_user_agent?\n return false if ipad_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"] =~ /(Mobile\\/.+Safari)/\n end", "def mobile_phone_verified?\n mobile_phone&.verified\n end", "def mobile_standard\n if request.env[\"HTTP_X_MOBILE_GATEWAY\"]\n out = nil\n else\n\n # request.env[\"HTTP_USER_AGENT\"].match(\"iPhone\") ? \"mobile\" : \"callc\"\n if session[:layout_t]\n if session[:layout_t].to_s == \"mini\"\n\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n if session[:layout_t].to_s == \"full\" or session[:layout_t].to_s == nil\n out = \"callc\"\n end\n if session[:layout_t].to_s == \"callcenter\"\n out = \"callcenter\"\n end\n else\n if !(request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\") or request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPod\"))\n out = \"callc\"\n end\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n end\n return out\n end" ]
[ "0.816326", "0.816326", "0.80765265", "0.8076151", "0.8042823", "0.79404104", "0.78978485", "0.78556645", "0.7846801", "0.7846801", "0.78075576", "0.77295065", "0.7670152", "0.763183", "0.75345737", "0.7499576", "0.74253076", "0.7413261", "0.74080706", "0.7351661", "0.7351661", "0.7318609", "0.7301482", "0.7224321", "0.721039", "0.7155229", "0.71373755", "0.71070397", "0.7087287", "0.7052707", "0.69336295", "0.69280803", "0.6919799", "0.68892723", "0.68589365", "0.6852105", "0.68272656", "0.68232465", "0.6787086", "0.6787086", "0.67622834", "0.6734714", "0.6701998", "0.6664974", "0.6661167", "0.6613615", "0.6538825", "0.65235573", "0.6521527", "0.6447009", "0.6435944", "0.64292973", "0.6415523", "0.6412845", "0.6402994", "0.6402994", "0.6360805", "0.6339142", "0.6339142", "0.63016105", "0.6295259", "0.6266782", "0.6246259", "0.62077963", "0.618525", "0.6180102", "0.61733294", "0.61398554", "0.61398554", "0.61277497", "0.61255157", "0.61238784", "0.6108263", "0.6108263", "0.6108263", "0.60895914", "0.60827565", "0.6077572", "0.60772836", "0.60564405", "0.60445124", "0.60307187", "0.6022379", "0.60078573", "0.59884864", "0.59823", "0.5968817", "0.5966953", "0.5966953", "0.59490716", "0.5941649", "0.59137785", "0.58941597", "0.5886959", "0.5885081", "0.5876248", "0.58696884", "0.58645934", "0.58535343" ]
0.80171365
5
Returns either true or false depending on whether or not the user agent of the device making the request is matched to a device in our regex.
def is_mobile_device? !!mobile_device end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def request_device?(device)\n (request.user_agent.to_s.downcase =~ (Mobylette.devices.device(device) || %r{not_to_be_matched_please}) ? true : false)\n end", "def user_agent_match(req, pattern)\n req.user_agent && req.user_agent[pattern]\n end", "def match?\n ua.match?(/SogouMobileBrowser/i) || ua.match?(/\\bSE\\b/)\n end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ Regexp.union(MOBILE_USER_AGENTS)\n end", "def mobile?\n agent_str = request.env[\"HTTP_USER_AGENT\"].to_s.downcase\n return false if agent_str =~ /ipad/\n agent_str =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def mobile_device?\n ua = request.user_agent.to_s.downcase\n ua =~ Regexp.new(positive_markers.join('|')) && ua =~ Regexp.new(required_markers.join('|')) && ua !~ Regexp.new(negative_markers.join('|'))\n end", "def mobile_device?\n request.user_agent =~ /Mobile|webOS/\n end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ /#{MOBILE_USER_AGENTS}/\n end", "def is_device? type\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def mobile?\n user_agent = request.user_agent.to_s.downcase rescue \"false\"\n return false if user_agent =~ /ipad/\n user_agent =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def mobile_device?\n !!(request.user_agent =~ /Mobile|webOS/i)\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] &&\n request.env[\"HTTP_USER_AGENT\" ][/(Mobile\\/.+Safari)/]\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def is_device?(type)\n\t\trequest.user_agent.to_s.downcase.include?(type.to_s.downcase)\n\tend", "def is_device?(type)\n request.user_agent.to_s.downcase.include? type.to_s.downcase\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include? type.to_s.downcase\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def good_browser?(agent = /Firefox|Safari|Chrome/)\n request.env['HTTP_USER_AGENT'] =~ agent\n end", "def iphone_user_agent?\n return false if ipad_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"] =~ /(Mobile\\/.+Safari)/\n end", "def detect_browser\n if APP_CONFIG.force_mobile_ui\n return true\n end\n \n mobile_browsers = [\"android\", \"ipod\", \"opera mini\", \"blackberry\", \n\"palm\",\"hiptop\",\"avantgo\",\"plucker\", \"xiino\",\"blazer\",\"elaine\", \"windows ce; ppc;\", \n\"windows ce; smartphone;\",\"windows ce; iemobile\", \n\"up.browser\",\"up.link\",\"mmp\",\"symbian\",\"smartphone\", \n\"midp\",\"wap\",\"vodafone\",\"o2\",\"pocket\",\"kindle\", \"mobile\",\"pda\",\"psp\",\"treo\"]\n if request.headers[\"HTTP_USER_AGENT\"]\n\t agent = request.headers[\"HTTP_USER_AGENT\"].downcase\n\t mobile_browsers.each do |m|\n\t\t return true if agent.match(m)\n\t end \n end\n return false\n end", "def iphone?\n request.user_agent =~ /iPhone/i\n end", "def is_iphone_request?\n request.user_agent.downcase =~ /(mobile\\/.+safari)|(iphone)|(ipod)|(blackberry)|(symbian)|(series60)|(android)|(smartphone)|(wap)|(mobile)/\n end", "def iphone?\r\n\t\trequest.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\r\n\tend", "def mac?(req)\n user_agent_match(req, /(Macintosh)/)\n end", "def is_mobile_request?\n (not user_agent_excluded?) && !(request.user_agent.to_s.downcase =~ @@mobylette_options[:mobile_user_agents].call).nil?\n end", "def android_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Android)/]\n end", "def from_iphone?\n app_matcher = /(DustTag|Dust Tag|Fat Tag|Katsu)/\n test = !(self.gml_application =~ app_matcher || self.application =~ app_matcher).blank?\n # puts \"from_iphone?(#{self.gml_application} || #{self.application}) = #{test}\"\n return test\n end", "def match?(request)\n match_library?(request) &&\n match_location?(request) &&\n match_current_location?(request) &&\n match_types?(request)\n end", "def allows_redirect?\n [\n %r{cyberduck}i,\n %r{konqueror}i\n ].any? do |regexp|\n (request.respond_to?(:user_agent) ? request.user_agent : request.env['HTTP_USER_AGENT']).to_s =~ regexp\n end\n end", "def iphone_user_agent?\n (cookies[:iphone] == 'true') || \n (request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/] && cookies[:iphone] != 'false')\n end", "def mobile_device?\r\n if session[:mobile_param]\r\n session[:mobile_param] == \"1\"\r\n else\r\n request.user_agent =~ /Mobile|webOS/\r\n end\r\n end", "def IsCompatible\r\n\t\tsAgent = @useragent\r\n\t\t\r\n\t\tif Php4r.strpos(sAgent, 'MSIE') != false and Php4r.strpos(sAgent, 'mac') == false and Php4r.strpos(sAgent, 'Opera') == false\r\n\t\t\tiVersion = Php4r.substr(sAgent, Php4r.strpos(sAgent, 'MSIE') + 5, 3).to_f\r\n\t\t\treturn (iVersion >= 5.5)\r\n\t\telsif Php4r.strpos(sAgent, 'Gecko/') != false\r\n\t\t\tiVersion = Php4r.substr(sAgent, Php4r.strpos(sAgent, 'Gecko/') + 6, 8)\r\n\t\t\treturn (iVersion.to_i >= 20030210)\r\n\t\telsif Php4r.strpos(sAgent, 'Opera/') != false\r\n\t\t\tfVersion = Php4r.substr(sAgent, Php4r.strpos(sAgent, 'Opera/') + 6, 4)\r\n\t\t\treturn (fVersion >= 9.5)\r\n\t\telsif sAgent and sAgent.match(/AppleWebKit\\/([0-9]+)/)\r\n\t\t\tmatches = sAgent.match(/AppleWebKit\\/([0-9]+)/)\r\n\t\t\treturn (matches[1].to_i >= 522)\r\n\t\telse\r\n\t\t\treturn false\r\n\t\tend\r\n\tend", "def is_browser_mobile(request)\n user_agent = request.headers['HTTP_USER_AGENT']\n return true if /android/i.match(user_agent)\n return true if /iphone/i.match(user_agent)\n return true if /ipad/i.match(user_agent)\n return false\n end", "def mobile_request?\n @mobile_request ||= !!(request.path =~ /^\\/#{mobile_path_prefix}(\\/.*)?$/)\n end", "def ipad_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"].include?('iPad')\n end", "def mobile_request?\n #hack for request.domain in case issue with subdomain\n request.subdomains.first == 'm' || request.domain.first == 'm'\n end", "def valid_browser? user_agent\n !user_agent.blank? && VALID_BROWSERS.any? {|browser| user_agent.downcase.include? browser }\n end", "def robot?\n user_agent = self.headers[\"User-Agent\"]\n escaped_bots = GentleREST::HttpRequest.robots.map do |bot|\n Regexp.escape(bot)\n end\n bots_regexp = Regexp.new(\n \"(#{escaped_bots.join(\"|\")})\", Regexp::IGNORECASE)\n return !!(user_agent =~ bots_regexp)\n end", "def robot?\n bot = /(Baidu|bot|Google|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)/i\n request.user_agent =~ bot\n end", "def mobile_device?\n if session[:mobile_param]\n session[:mobile_param] == \"1\"\n else\n if request.user_agent =~ /Mobile|webOS/\n session[:mobile_param] = \"1\"\n return true\n else\n return false\n end\n end\n end", "def is_iphone_request?\n request.user_agent =~ /(Mobile\\/.+Safari)/\n end", "def mobile?\n os_parser.mobile?\n end", "def request_ipad?\n request.user_agent.match(/iPad/)\n end", "def matches?(req)\n regex = Regexp.new(@pattern.to_s)\n match_data = regex.match(req.path)\n if match_data.nil?\n return false\n else\n req.request_method.downcase.to_sym == @http_method\n end\n end", "def is_mobile_device?\n Handset.is_mobile? request.user_agent\n end", "def match?(_request)\n true\n end", "def matches?(req)\n @pattern.to_s.match(req.path) && @http_method.to_s.match(req.request_method.downcase)\n end", "def is_mobile_browser?\n Handset.is_mobile? request.user_agent\n end", "def matches?(req)\n !!(req.request_method.downcase.to_sym == @http_method && @pattern.match(req.path))\n end", "def windows_phone?\n !!(ua =~ /Windows Phone/)\n end", "def is?(match)\n match === RbConfig::CONFIG[\"host_os\"]\n end", "def matches?(request)\n (http_method == request.request_method.downcase.to_sym) &&\n !!(pattern =~ request.path)\n end", "def mobile_device?\n if session[:mobile_override].present?\n session[:mobile_override] == \"1\"\n else\n (request.user_agent =~ /Mobile|webOS/) && (request.user_agent !~ /iPad/) ? true : false\n end\n end", "def windows_mobile?\n !!(ua =~ /Windows CE/)\n end", "def matches?(req)\n match_method = req.request_method.downcase.to_sym == @http_method\n # match_pattern = req.path.match(Regexp.new(@pattern))\n match_pattern = req.path =~ @pattern\n match_method && match_pattern\n end", "def matchers?(req)\n @default || req.headers['Accept'].include?(\"application/vnd.glass.v#{@version}\")\n end", "def mobile_device?\n if Rails.env.development?\n if session[:mobile_param] \n session[:mobile_param] == \"1\" \n else \n request.user_agent =~ /Mobile/ \n end\n else\n false\n end \n end", "def mobile?\n @prefix =~ /\\A1/\n end", "def valid_robot? user_agent\n !user_agent.blank? && VALID_ROBOTS.any? {|robot| user_agent.downcase.include? robot }\n end", "def current_agent_allowed?(uri)\n # be a good net citizen and set your user-agent!\n if @user_agent.nil? || @user_agent.empty?\n # log to logger that the user agent wasn't set\n log('*'*5 + ' ROBOTO: cannot determine if your bot is allowed since you did not ser the user-agent. \n Set it in the open_r options hash like so\n \\'user-agent\\' => \\'YOUR BOT\\'s NAME\\' and try again.')\n return false\n end\n \n # This will also bring us the user-agent * (for everyone) and any matches we find\n user_agents = @perms.keys.select {|k| (@user_agent == k) || (@user_agent.include?(k.gsub(/(\\*.*)/, ''))) }\n user_agents.each do |ua|\n @perms[ua]['disallow'].each do |r|\n return true if r == ''\n return false if r == '/' || uri.include?(r) || uri.include?(r.gsub(/\\*/, ''))\n end\n end\n \n # the uri isn't specifially disallowed for this user-agent \n # so let it through\n true\n end", "def matches?(req)\n !(@pattern =~ req.path).nil? && req.request_method.downcase == @http_method.to_s.downcase\n end", "def is_mobile_device?\n return false if session[:force_agent] == :html\n return true if session[:force_agent] == :mobile\n \n get_device unless @device\n return @device.is_mobile? if @device\n return false\n end", "def mobile_device?\n if session[:mobile_override]\n session[:mobile_override] == '1'\n else\n (request.user_agent =~ /Mobile|webOS/) && (request.user_agent !~ /iPad/)\n end\n end", "def request_match?(request_uri)\n uri = request_uri.is_a?(URI) ? request_uri : URI.parse(request_uri)\n domain_match(uri.host) && path_match(uri.path) && port_match(uri.port)\n end", "def iphone_request?\n return (request.subdomains.first == \"i\" || params[:format] == \"iphone\")\n end", "def matches?(req)\n @pattern.match?(req.path) && @http_method.to_s.downcase == req.request_method.downcase\n end", "def matches?(request)\n @default || request.headers['Accept'].include?(\"application/vnd.medexprimereemr.v#{@version}\")\n end", "def iphone_request?\n return (request.subdomains.first == \"iphone\" || params[:format] == \"iphone\")\n end", "def match!(env)\n return false unless @http_methods.include?(env[\"REQUEST_METHOD\"])\n return false unless @path =~ env[\"PATH_INFO\"]\n return false unless @host.nil? || @host =~ env[\"HTTP_HOST\"]\n\n true\n end", "def check_whether_requested_from_android_webview\n\t\tuser_agent = request.user_agent\n\t\tif(user_agent.include?(\"CLASSTALK_ANDROID_APP\"))\n\t\t\treturn true\n\t\telse\n\t\t\treturn false\n\t\tend\n\tend", "def matches?(req)\n !(req.path =~ @pattern).nil? && \n req.request_method.downcase.to_sym == @http_method\n end", "def chrome_os?\n !!(ua =~ /CrOS/)\n end", "def matches?(request)\n !!@rule.call(request) # rubocop:disable Style/DoubleNegation\n end", "def user_agent_excluded?\n request.user_agent.to_s.downcase =~ Regexp.union([self.mobylette_options[:skip_user_agents]].flatten.map(&:to_s))\n end", "def matches?(req)\n\n @method == req.request_method.downcase.to_sym && @pattern.match(req.path)\n end", "def is_os? os\n Os.is_os? request.user_agent, os\n end", "def matches?(request)\n request.headers.fetch(:accept).include?(\"application/vnd.pieforproviders.v#{version}+json\")\n end", "def regexp_match( dialstring )\n\t\t\treturn !! @regexp.match( dialstring.to_s )\n\t\tend", "def matches?(req)\n req.path =~ pattern && http_method == req.request_method.downcase.to_sym\n end", "def matches?(req)\n req.path =~ pattern && req.request_method.to_s.upcase == http_method\n end", "def is_mobile_device()\n res = self.send_request 'is_mobile_device'\n return res.body\n end", "def mobile_viewer?\n mobile_param = params[:mobile]\n viewer = params[:viewer]\n\n (mobile_param == 'true') || (viewer == 'android') || (viewer == 'ios')\n end", "def matches?(req)\n pattern.match(req.path) && req.request_method.downcase == http_method.to_s\n end", "def respond_as_mobile?\n processing_xhr_requests? and skip_mobile_param_not_present? and (force_mobile_by_session? or is_mobile_request? or (params[:format] == 'mobile'))\n end", "def respond_as_mobile?\n processing_xhr_requests? and skip_mobile_param_not_present? and (force_mobile_by_session? or allow_mobile_response? or (params[:format] == 'mobile'))\n end", "def set_device\n # if HTTP_USER_AGENT is blank/nil defaults to blank, i.e. desktop \n agent = request.env[\"HTTP_USER_AGENT\"].blank? ? \"\" : request.env[\"HTTP_USER_AGENT\"].downcase \n if agent =~ tablet_agents\n \"tablet\"\n elsif (agent =~ mobile_agents_one) || (agent[0..3] =~ mobile_agents_two)\n \"mobile\"\n else\n \"desktop\"\n end \n end", "def is_mobile_view?\n request.format.to_sym == :mobile\n end", "def in_mobile_view?\n request.format.to_sym == :mobile\n end", "def robots_allowed?(uri); end", "def user_agent\n \"Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3\"\n end", "def mobile_device?\n # We CAN'T check if the device is an +Appium::Driver+ since it is not a RemoteWebDriver. Because of that we use a\n # flag we got as an option in the constructor.\n @is_mobile_device\n end", "def matches?(request)\n # this treats */* as html request\n return false unless request.format\n return false unless request.format.html?\n\n @exceptions.each {|p|\n return false if p.match request.path\n }\n\n true\n end", "def supports_regexp?\n true\n end", "def supports_regexp?\n true\n end", "def valid?\n (uri.host =~ LINK_REGEX || uri.host =~ LINK_IP_REGEX) ? true : false\n end", "def matches?(req)\n @default || (req.try(:headers).try(:[],'Accept') &&\n req.headers['Accept'].include?(\"application/api.brightwheel.v#{@version}\"))\n end", "def is_browser? browser\n Browser.is_browser? request.user_agent, browser\n end" ]
[ "0.78794944", "0.7647633", "0.75884247", "0.75001377", "0.7395123", "0.73902845", "0.722873", "0.7225667", "0.7104287", "0.70859146", "0.70817584", "0.70780754", "0.70533675", "0.70259815", "0.70259815", "0.70259815", "0.69556886", "0.6915082", "0.6915082", "0.68802434", "0.6837947", "0.6813854", "0.68116874", "0.6797071", "0.67920816", "0.67890525", "0.67716795", "0.6765338", "0.6759356", "0.6663093", "0.6648552", "0.66103655", "0.6590016", "0.6557382", "0.64783174", "0.6465523", "0.64332205", "0.643133", "0.63928723", "0.6385452", "0.6377057", "0.6356693", "0.634639", "0.6341771", "0.63158256", "0.63107055", "0.62939805", "0.62833476", "0.6271383", "0.62663877", "0.6221566", "0.61865765", "0.617791", "0.61772704", "0.6175578", "0.6116387", "0.6116321", "0.6107973", "0.6079346", "0.6069285", "0.60661644", "0.6054218", "0.605121", "0.60480624", "0.60372275", "0.6031199", "0.6023745", "0.59946084", "0.59643", "0.5949538", "0.59160274", "0.5907051", "0.5906562", "0.590039", "0.5895027", "0.5891242", "0.5887206", "0.5886408", "0.58781874", "0.5851435", "0.58343375", "0.5819822", "0.5818671", "0.5814901", "0.58052206", "0.580245", "0.57932574", "0.5766964", "0.5751299", "0.5746508", "0.5744026", "0.5741435", "0.5728983", "0.57228565", "0.57214326", "0.57180107", "0.57104194", "0.57077223", "0.57045436", "0.57015955", "0.5691585" ]
0.0
-1
Can check for a specific user agent e.g., is_device?('iphone') or is_device?('mobileexplorer')
def is_device?(type) request.user_agent.to_s.downcase.include? type.to_s.downcase end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_device\n # if HTTP_USER_AGENT is blank/nil defaults to blank, i.e. desktop \n agent = request.env[\"HTTP_USER_AGENT\"].blank? ? \"\" : request.env[\"HTTP_USER_AGENT\"].downcase \n if agent =~ tablet_agents\n \"tablet\"\n elsif (agent =~ mobile_agents_one) || (agent[0..3] =~ mobile_agents_two)\n \"mobile\"\n else\n \"desktop\"\n end \n end", "def detect_browser\n if APP_CONFIG.force_mobile_ui\n return true\n end\n \n mobile_browsers = [\"android\", \"ipod\", \"opera mini\", \"blackberry\", \n\"palm\",\"hiptop\",\"avantgo\",\"plucker\", \"xiino\",\"blazer\",\"elaine\", \"windows ce; ppc;\", \n\"windows ce; smartphone;\",\"windows ce; iemobile\", \n\"up.browser\",\"up.link\",\"mmp\",\"symbian\",\"smartphone\", \n\"midp\",\"wap\",\"vodafone\",\"o2\",\"pocket\",\"kindle\", \"mobile\",\"pda\",\"psp\",\"treo\"]\n if request.headers[\"HTTP_USER_AGENT\"]\n\t agent = request.headers[\"HTTP_USER_AGENT\"].downcase\n\t mobile_browsers.each do |m|\n\t\t return true if agent.match(m)\n\t end \n end\n return false\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def good_browser?(agent = /Firefox|Safari|Chrome/)\n request.env['HTTP_USER_AGENT'] =~ agent\n end", "def mobile_device?\n request.user_agent =~ /Mobile|webOS/\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] &&\n request.env[\"HTTP_USER_AGENT\" ][/(Mobile\\/.+Safari)/]\n end", "def android_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Android)/]\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def user_agent_match(req, pattern)\n req.user_agent && req.user_agent[pattern]\n end", "def iphone_user_agent?\n (cookies[:iphone] == 'true') || \n (request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/] && cookies[:iphone] != 'false')\n end", "def is_device? type\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def mobile?\n agent_str = request.env[\"HTTP_USER_AGENT\"].to_s.downcase\n return false if agent_str =~ /ipad/\n agent_str =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def valid_browser? user_agent\n !user_agent.blank? && VALID_BROWSERS.any? {|browser| user_agent.downcase.include? browser }\n end", "def is_device?(type)\n\t\trequest.user_agent.to_s.downcase.include?(type.to_s.downcase)\n\tend", "def iphone_user_agent?\n return false if ipad_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"] =~ /(Mobile\\/.+Safari)/\n end", "def mobile_device?\n !!(request.user_agent =~ /Mobile|webOS/i)\n end", "def mobile_device?\n ua = request.user_agent.to_s.downcase\n ua =~ Regexp.new(positive_markers.join('|')) && ua =~ Regexp.new(required_markers.join('|')) && ua !~ Regexp.new(negative_markers.join('|'))\n end", "def request_device?(device)\n (request.user_agent.to_s.downcase =~ (Mobylette.devices.device(device) || %r{not_to_be_matched_please}) ? true : false)\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def user_agent\n headers[\"HTTP_USER_AGENT\"] || headers[\"USER-AGENT\"]\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def mobile?\n user_agent = request.user_agent.to_s.downcase rescue \"false\"\n return false if user_agent =~ /ipad/\n user_agent =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def user_agent_on_header\n request.headers['HTTP_USER_AGENT']\n end", "def user_agent(value)\n value || DEFAULT_USER_AGENT\n end", "def is_browser_mobile(request)\n user_agent = request.headers['HTTP_USER_AGENT']\n return true if /android/i.match(user_agent)\n return true if /iphone/i.match(user_agent)\n return true if /ipad/i.match(user_agent)\n return false\n end", "def some_user_agent\n \"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.3) Gecko/20090920 Firefox/3.5.3 (Swiftfox)\"\n end", "def user_agent\n \"Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3\"\n end", "def user_agent\n @user_agent || USER_AGENT\n end", "def user_agent\n @user_agent || USER_AGENT\n end", "def find_device_type\n case request.user_agent\n # when /mac|ios/i\n # :ios\n when /android/i\n :android\n else\n nil\n end\n end", "def ipad_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"].include?('iPad')\n end", "def user_agent (value = nil)\n\t\tif value\n\t\t\traise_if_error C.glyr_opt_useragent(to_native, value)\n\t\telse\n\t\t\tto_native[:useragent]\n\t\tend\n\tend", "def check_browser_type(platform, browser_type)\n if platform == 'desktop'\n if !%w(ff ie chrome safari opera).include? browser_type\n print_error_desktop\n end\n else\n if !%w(native chrome safari).include? browser_type\n print_error_mobile\n end\n end\nend", "def detect_browser(http_user_agent)\n result = http_user_agent\n if result =~ /Safari/\n if result =~ /Chrome/\n version = result.split('Chrome/')[1].split(' ').first.split('.').first\n browser = 'Chrome'\n else\n browser = 'Safari'\n version = result.split('Version/')[1].split(' ').first.split('.').first\n end\n elsif result =~ /Firefox/\n browser = 'Firefox'\n version = result.split('Firefox/')[1].split('.').first\n elsif result =~ /Opera/\n browser = 'Opera'\n version = result.split('Version/')[1].split('.').first\n elsif result =~ /MSIE/\n browser = 'MSIE'\n version = result.split('MSIE')[1].split(' ').first\n end\n\n [browser,version]\n end", "def user_agent; end", "def user_agent; end", "def user_agent; end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ Regexp.union(MOBILE_USER_AGENTS)\n end", "def get_user_agent\n user_agent\n end", "def is_iphone_request?\n request.user_agent.downcase =~ /(mobile\\/.+safari)|(iphone)|(ipod)|(blackberry)|(symbian)|(series60)|(android)|(smartphone)|(wap)|(mobile)/\n end", "def user_agent\n @agent.user_agent\n end", "def iphone?\r\n\t\trequest.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\r\n\tend", "def is_mobile_browser?\n Handset.is_mobile? request.user_agent\n end", "def mobile_device?\r\n if session[:mobile_param]\r\n session[:mobile_param] == \"1\"\r\n else\r\n request.user_agent =~ /Mobile|webOS/\r\n end\r\n end", "def user_agent_string(id)\n case id\n when :ie\n 'MSIE'\n when :safari\n 'Safari'\n when :chrome\n 'Chrome'\n when :opera\n 'Opera'\n when :firefox\n 'Firefox'\n else\n raise \"Define mising browser agent: #{id.inspect}\"\n end\nend", "def ua\n @ua ||= begin\n request.env['HTTP_USER_AGENT'].downcase\n rescue\n ''\n end\n end", "def get_user_agent\n # If `browser` method is called from a rails view\n if defined?(controller)\n controller.view_context.request.user_agent\n\n # Else `browser` method was called from a ruby component\n elsif defined?(view_context)\n view_context.request.user_agent\n end\n end", "def IsCompatible\r\n\t\tsAgent = @useragent\r\n\t\t\r\n\t\tif Php4r.strpos(sAgent, 'MSIE') != false and Php4r.strpos(sAgent, 'mac') == false and Php4r.strpos(sAgent, 'Opera') == false\r\n\t\t\tiVersion = Php4r.substr(sAgent, Php4r.strpos(sAgent, 'MSIE') + 5, 3).to_f\r\n\t\t\treturn (iVersion >= 5.5)\r\n\t\telsif Php4r.strpos(sAgent, 'Gecko/') != false\r\n\t\t\tiVersion = Php4r.substr(sAgent, Php4r.strpos(sAgent, 'Gecko/') + 6, 8)\r\n\t\t\treturn (iVersion.to_i >= 20030210)\r\n\t\telsif Php4r.strpos(sAgent, 'Opera/') != false\r\n\t\t\tfVersion = Php4r.substr(sAgent, Php4r.strpos(sAgent, 'Opera/') + 6, 4)\r\n\t\t\treturn (fVersion >= 9.5)\r\n\t\telsif sAgent and sAgent.match(/AppleWebKit\\/([0-9]+)/)\r\n\t\t\tmatches = sAgent.match(/AppleWebKit\\/([0-9]+)/)\r\n\t\t\treturn (matches[1].to_i >= 522)\r\n\t\telse\r\n\t\t\treturn false\r\n\t\tend\r\n\tend", "def iphone?\n request.user_agent =~ /iPhone/i\n end", "def robot?\n bot = /(Baidu|bot|Google|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)/i\n request.user_agent =~ bot\n end", "def user_agent\n @data[\"user_agent\"]\n end", "def is_desktop_browser?\n !Handset.is_mobile? request.user_agent\n end", "def user_agent(string)\n string = string.to_s\n return nil if string.empty?\n UserAgent.new(string)\n end", "def user_agent=(user_agent); end", "def valid_robot? user_agent\n !user_agent.blank? && VALID_ROBOTS.any? {|robot| user_agent.downcase.include? robot }\n end", "def user_os_simple\n @user_os_simple ||= begin\n ua = ''\n ua = request.env['HTTP_USER_AGENT'].downcase if request.env['HTTP_USER_AGENT']\n if ua.index('win')\n \"Windows\"\n elsif ua.index('linux')\n \"Linux\"\n elsif ua.index('macintosh')\n \"Macintosh\"\n elsif ua.index('ipod') # iPod Touch\n \"iPod\"\n elsif ua.index('iphone')\n \"iPhone\"\n elsif ua.index('ipad')\n \"iPad\"\n else\n \"unknown\"\n end\n end\n end", "def match?\n ua.match?(/SogouMobileBrowser/i) || ua.match?(/\\bSE\\b/)\n end", "def user_os_simple\r\n ua = request.env['HTTP_USER_AGENT'].downcase\r\n return \"Windows\" if ua.index('win')\r\n return \"Linux\" if ua.index('Linux')\r\n return \"Macintosh\" if ua.index('Macintosh')\r\n return \"unknown\"\r\n end", "def is_browser? browser\n Browser.is_browser? request.user_agent, browser\n end", "def user_agent(vendor: T.unsafe(nil)); end", "def is_mobile_device?\n Handset.is_mobile? request.user_agent\n end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ /#{MOBILE_USER_AGENTS}/\n end", "def os\n Agent.os_for_user_agent string\n end", "def current_agent_allowed?(uri)\n # be a good net citizen and set your user-agent!\n if @user_agent.nil? || @user_agent.empty?\n # log to logger that the user agent wasn't set\n log('*'*5 + ' ROBOTO: cannot determine if your bot is allowed since you did not ser the user-agent. \n Set it in the open_r options hash like so\n \\'user-agent\\' => \\'YOUR BOT\\'s NAME\\' and try again.')\n return false\n end\n \n # This will also bring us the user-agent * (for everyone) and any matches we find\n user_agents = @perms.keys.select {|k| (@user_agent == k) || (@user_agent.include?(k.gsub(/(\\*.*)/, ''))) }\n user_agents.each do |ua|\n @perms[ua]['disallow'].each do |r|\n return true if r == ''\n return false if r == '/' || uri.include?(r) || uri.include?(r.gsub(/\\*/, ''))\n end\n end\n \n # the uri isn't specifially disallowed for this user-agent \n # so let it through\n true\n end", "def device_type\n case request.user_agent\n when /mobile/i\n \"mobile\"\n when /iPad/i\n \"tablet\"\n when /Android/i\n \"tablet\"\n else\n \"desktop\"\n end\n end", "def is_mobile_or_tablet?\n # mobile_fu's method\n is_mobile_device? || is_tablet_device?\n end", "def mac?(req)\n user_agent_match(req, /(Macintosh)/)\n end", "def bot_user_agent(vendor: T.unsafe(nil)); end", "def user_agent\n @request['User-Agent']\n end", "def http_user_agent\n # User agent is required for cookie validation\n request.env['HTTP_USER_AGENT'].to_s\n end", "def user_agent\n kernel = Facter[:kernel] ? Facter[:kernel].value : 'unknown'\n kvers = Facter[:kernelversion] ? Facter[:kernelversion].value : 'unknown'\n values = {\n 'razor' => MK::VERSION,\n 'facter' => Facter.version, # sigh\n 'ruby' => RUBY_VERSION,\n 'kernel' => \"#{kernel}-#{kvers}\"\n }.reject{|k,v| v.nil?}.map{|k,v| k+'/'+v}.join(' ')\n end", "def browser_supported_by_metamask?\n browser.chrome? || browser.firefox?\n end", "def is_mobile_request?\n (not user_agent_excluded?) && !(request.user_agent.to_s.downcase =~ @@mobylette_options[:mobile_user_agents].call).nil?\n end", "def is_brand? brand\n Handset.is_brand? request.user_agent, brand\n end", "def user_agent\n @headers['User-Agent']\n end", "def user_agent\n @headers['User-Agent']\n end", "def user_agent\n @headers['User-Agent']\n end", "def validate_user_agent(_item)\n nil\n end", "def touch_device\n return 'iphone' if request.user_agent.to_s.downcase =~ /iphone/\n return 'android' if request.user_agent.to_s.downcase =~ /android/\n nil\n end", "def mobile_device?\n if session[:mobile_override].present?\n session[:mobile_override] == \"1\"\n else\n (request.user_agent =~ /Mobile|webOS/) && (request.user_agent !~ /iPad/) ? true : false\n end\n end", "def check_platform\n mobile_override = params[:mobile] && params[:mobile] == \"1\"\n desktop_override = params[:mobile] && params[:mobile] == \"0\"\n if ( (browser.mobile? and !browser.ipad?) or mobile_override ) and !request.xhr? and !desktop_override\n @platform = 'mobile'\n request.format = :mobile\n else\n @platform = 'desktop'\n end\n end", "def device(user_agent)\n Device.\n devices.select { |d| }\n end", "def request_ipad?\n request.user_agent.match(/iPad/)\n end", "def compare_user_agents(session_user_agent)\n return true if session_user_agent == @request.user_agent\n\n # DamerauLevenshtein.distance() takes two strings and an optional\n # argument. The optional argument specifies which algorithm should\n # be used to calculate the distance between the two strings.\n # Here we pass in 0 to use the Levenshtein distance.\n distance = DamerauLevenshtein.distance(@request.user_agent, session_user_agent, 0)\n\n distance < MAX_LEVENSHTEIN_DISTANCE\n end", "def mobile_device?\n if session[:mobile_param]\n session[:mobile_param] == \"1\"\n else\n if request.user_agent =~ /Mobile|webOS/\n session[:mobile_param] = \"1\"\n return true\n else\n return false\n end\n end\n end", "def user_agent(user_agent)\n @user_agent = user_agent\n end", "def client_browser_name \n user_agent = (request.env['HTTP_USER_AGENT'] || \"\").downcase \n if user_agent =~ /msie/i \n \"Internet Explorer\" \n elsif user_agent =~ /applewebkit/i \n \"Safari\" \n elsif user_agent =~ /konqueror/i \n \"Konqueror\" \n elsif user_agent =~ /gecko/i \n \"Mozilla\" \n elsif user_agent =~ /opera/i \n \"Opera\" \n else \n \"Unknown\" \n end \n end", "def user_agent\n @request[FUA]\n end", "def is_os? os\n Os.is_os? request.user_agent, os\n end", "def mobile_device?\n if session[:mobile_override]\n session[:mobile_override] == '1'\n else\n (request.user_agent =~ /Mobile|webOS/) && (request.user_agent !~ /iPad/)\n end\n end", "def is_iphone_request?\n request.user_agent =~ /(Mobile\\/.+Safari)/\n end", "def browser_user_agent(browser, agent, orientation)\nsetup_watir_webdriver\nbrowser =\"firefox\"\nagent = \"iphone\"\norientation=\"portrait\"\nrequire 'watir-webdriver'\nrequire 'webdriver-user-agent'\ndriver = Webdriver::UserAgent.driver(:browser => :\"#{browser}\", :agent => :\"#{agent}\", :orientation => :\"#{orientation}\")\nbrowser = Watir::Browser.new(driver)\nend", "def mobile_viewer?\n mobile_param = params[:mobile]\n viewer = params[:viewer]\n\n (mobile_param == 'true') || (viewer == 'android') || (viewer == 'ios')\n end", "def ipad\n 'Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10'\nend", "def client_browser_name\n user_agent = request.env['HTTP_USER_AGENT'].downcase\n if user_agent =~ /msie/i\n \"Microsoft\"\n elsif user_agent =~ /applewebkit/i\n \"Apple or Google\"\n elsif user_agent =~ /Chrome/i\n \"Google\"\n elsif user_agent =~ /Mozilla/i\n \"Mozilla\"\n else\n \"your browser\"\n end\n end", "def mobile_device?\n if Rails.env.development?\n if session[:mobile_param] \n session[:mobile_param] == \"1\" \n else \n request.user_agent =~ /Mobile/ \n end\n else\n false\n end \n end", "def ios_device_type\n case request.user_agent\n when /(iPad)/\n t('device.ios.ipad')\n when /(iPhone)/\n t('device.ios.iphone')\n when /(iPod)/\n t('device.ios.ipod')\n else\n t('device.ios.ios_device')\n end\n end" ]
[ "0.75859034", "0.75070226", "0.74954325", "0.7490642", "0.7376007", "0.73159945", "0.7292912", "0.7280186", "0.7280186", "0.7280186", "0.7184447", "0.7179834", "0.7133441", "0.71235406", "0.7061011", "0.70328015", "0.69874", "0.6967959", "0.69402933", "0.6939325", "0.69107175", "0.68943846", "0.686719", "0.6819607", "0.68057305", "0.6794671", "0.67523956", "0.67522115", "0.6740599", "0.6680357", "0.6680357", "0.66727716", "0.66718346", "0.66582394", "0.66546685", "0.6645546", "0.66437376", "0.66437376", "0.66437376", "0.66419375", "0.6634626", "0.66187596", "0.6610552", "0.65800565", "0.6573174", "0.6564561", "0.65446806", "0.65445423", "0.6542269", "0.6539137", "0.6529194", "0.65230113", "0.6522994", "0.6510573", "0.6496465", "0.64933914", "0.6492928", "0.64795977", "0.6474805", "0.64693105", "0.6442489", "0.6427187", "0.6407776", "0.6402203", "0.64008796", "0.6395995", "0.6363188", "0.6361015", "0.6349099", "0.63446444", "0.63296187", "0.63177264", "0.6314262", "0.6313943", "0.6313174", "0.62886983", "0.62859297", "0.62859297", "0.62859297", "0.6278712", "0.6265986", "0.6262368", "0.6258306", "0.625444", "0.62494093", "0.6245915", "0.62352985", "0.62330145", "0.62324625", "0.6219212", "0.6210262", "0.618854", "0.6177726", "0.61767745", "0.61005694", "0.60954344", "0.6087828", "0.60772717", "0.6066804" ]
0.6968986
18
Zip def my_zip(arr) result_arr = [] self.my_each do |el| end Rotate
def my_rotate(num = 1) offset = num % self.length self.drop(offset) + self.take(offset) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def my_zip(*arrs)\n zipped = []\n self.each_with_index do |ele, i|\n sub = [ele]\n arrs.each do |arr|\n sub << arr[i]\n end\n zipped << sub\n end\n zipped\n end", "def zip(*arr)\n (0...arr[0].length).map do |i|\n arr.map {|arr| arr[i]}\n end\nend", "def my_zip(*given_arrays)\n result = []\n\n self.each_with_index do |el, idx|\n internal_array = [el]\n given_arrays.each { |given_array| internal_array << given_array[idx] }\n result << internal_array\n end\n\n result\n end", "def my_zip(*args)\n zipped = Array.new(self.length) {[]}\n\n self.each_with_index { |el, i_arr| zipped[i_arr] << el}\n args.each_with_index do |arg, i_arg|\n (zipped.length).times {|i_arg_el| zipped[i_arg_el] << arg[i_arg_el]}\n end\n zipped\n end", "def my_zip(*arr)\n answer = Array.new([])\n each_with_index do |item, index|\n answer[index] = [item]\n arr.each do |elem|\n answer[index] << elem[index]\n end\n end\n answer\n end", "def zip(*arr)\n new_arr = []\n i = 0\n while i < arr[0].length\n temp = []\n arr.each do |subarray|\n temp << subarray[i]\n end\n new_arr << temp\n i += 1\n end\n new_arr\nend", "def zip(*rest) end", "def my_zip(*arrays)\n i = 0\n zipped = []\n while i < self.length\n nest = [self[i]]\n arrays.my_each do |arr|\n if i < arr.length\n nest << arr[i]\n else\n nest << nil\n end\n end\n zipped << nest\n i += 1\n end\n return zipped\n end", "def zip(arr_1, arr_2)\n new_arr = []\n arr_1.size.times do |i|\n new_arr << [arr_1[i], arr_2[i]]\n end\n new_arr\nend", "def zip(array1, array2)\n iterations = array1.size\n results = []\n iterations.times do |index|\n results << [array1[index], array2[index]]\n end\n results\nend", "def zip(*arrs)\n return [] if arrs.any?(&:empty?)\n [arrs.map(&:first)] + zip(arrs.first.drop(1), arrs.last.drop(1))\nend", "def zip(arr1, arr2)\n zipped = []\n arr1.each_with_index do |el, i|\n zipped << [el, arr2[i]]\n end\n zipped\nend", "def zip(arr1, arr2)\n Array.new(arr1.size) do |idx|\n [arr1[idx], arr2[idx]]\n end\nend", "def interzip(array1, array2)\n array1.zip(array2).flatten\nend", "def zip(first, second)\n first.zip(second)\nend", "def zip(arr1, arr2)\n zipped = []\n arr1.each_with_index { |ele, ind| zipped << [ele, arr2[ind]] }\n zipped\nend", "def custom_zip(arr1, arr2)\n result = []\n arr1.each_with_index do |item, index|\n result << [arr1[index], arr2[index]]\n end\n result\nend", "def zip(arr1, arr2)\n index = 0\n zipped = []\n while index < arr1.length\n zipped << [arr1[index], arr2[index]]\n index += 1\n end\n zipped\nend", "def zipper(arr1, arr2)\n arr1.map.with_index { |val, idx| [val] << arr2[idx] }\nend", "def zany_zip(*arr)\n max_length = 0\n arr.each do |x|\n if x.length > max_length\n max_length = x.length\n end\n end\n result = []\n i = 0\n while i < max_length\n temp = []\n arr.each do |subarray|\n temp << subarray[i]\n end\n result << temp\n i += 1\n end\n result\nend", "def custom_zip (arr1, arr2)\n final = []\n arr1.each_with_index do |item, index|\n final << [item, arr2[index]]\n end\n final\nend", "def zip(*args)\n \n multi = Array.new(args[0].length) {[]}\n\n (0...args.length).each do |i|\n (0...args[0].length).each do |j|\n multi[j] << args[i][j]\n end\n end\n multi\nend", "def zip(arr1, arr2)\n arr1.each_with_index.with_object([]) do |(el, i), z|\n z << [el, arr2[i]]\n end\nend", "def zip(array1, array2)\n results = []\n array1.each_with_index do |current_element, current_index|\n results << [current_element, array2[current_index]]\n end\n results\nend", "def zip(ar1, ar2)\n zip_rec = ->(ar1, ar2, result) do\n case [ar1, ar2]\n when [[], []]\n result\n else\n zip_rec.(ar1[1..-1], ar2[1..-1], result << [ar1[0], ar2[0]])\n end\n end\n zip_rec.(ar1, ar2, [])\nend", "def zip(first, second)\n first.zip(second).flatten\nend", "def custom_zip(arr1, arr2)\n final = []\n arr1.each_with_index do |value, index|\n final << [value, arr2[index]]\n end\n final\nend", "def zip(arr1, arr2)\n arr1.each_with_index.with_object([]) do |(el, idx), arr|\n arr << [el, arr2[idx]]\n end\nend", "def zip(arr1, arr2)\n arr1.each_with_index.reduce([]) { |result, (el, idx)| result << [el, arr2[idx]] }\nend", "def zip first, second\n first.zip(second).flatten()\nend", "def zip(arr1, arr2)\n result = []\n idx = 0\n loop do\n result << [arr1[idx], arr2[idx]]\n idx += 1\n break if idx == arr1.size\n end\n result\nend", "def zip\n end", "def lecturer_zip(arr1,arr2)\n final = []\n arr1.each_with_index { |value, index| final << [value, arr2[index]] }\n final\nend", "def zip( *other_arrays, & block )\n\n load_parent_state\n \n return super\n \n end", "def zip\n end", "def custom_zip(arr1, arr2)\n final=[]\n arr1.each_with_index do |item, index|\n nested_array= []\n arr2.each_with_index do |item2, index2|\n if index == index2\n nested_array << item\n nested_array << item2\n final << nested_array\n end\n end\n end\n final\nend", "def zany_zip(*args)\n length = args.map(&:length).max\n multi = Array.new(length) {[]}\n\n (0...args.length).each do |i|\n (0...length).each do |j|\n if j >= args[i].length\n multi[j] << nil\n else\n multi[j] << args[i][j]\n end\n end\n end\n multi\nend", "def custom_zip(arr1, arr2)\n final = []\n arr1.each_with_index { |name, index| final << [name, arr2[index]] }\n final\nend", "def zipper(arr1, arr2)\n arr1.map.with_index { |elem, ndx| [elem, arr2[ndx]] }\nend", "def zip(arr1, arr2)\n arr1.map.with_index { |el1, idx| [el1, arr2[idx]] }\nend", "def custom_zip(arr1, arr2, arr3)\n arr = []\n nest_arr = []\n arr1.each do |i|\n k = [] #initialize a temporary array\n k.push(i) #pushed first val\n k.push(arr2[arr1.index(i)]) #pushed 2nd val\n k.push(arr3[arr1.index(i)]) #pushed 3rd val\n nest_arr = k #assigned to nest_arr\n arr.push(nest_arr) # pushed nest_arr to arr in order to nest in\n end\n\n p arr\nend", "def array_align (arr, *data)\n arr.zip(*data)\nend", "def interleave(arr1,arr2)\n arr1.zip(arr2).flatten\nend", "def paralell_array(*enums)\n zip(*enums)\n end", "def zip_with(a, b, &op)\n result = []\n a.zip(b){ |aa,bb| result << op.call(aa,bb)}\n result\nend", "def custom_zip(arr1, arr2)\n new_nested = []\n arr1.each_with_index do | arr1_value, arr1_index |\n arr2.each_with_index do | arr2_value, arr2_index |\n if arr1_index == arr2_index\n arr3 = [arr1[arr1_index], arr2[arr2_index]]\n new_nested << arr3\n end # end of if\n end # end of do (array 2)\n end # end of do (array 1)\n new_nested\nend", "def interleave(array1, array2)\n p array1.zip(array2).flatten\nend", "def interleave(arr_1, arr_2)\n arr_1.zip(arr_2).flatten\nend", "def zip first, second\n answer = Array.new\n first.each.with_index do |letter, index|\n answer << first[index]\n answer << second[index]\n end\n answer\nend", "def interleave(ary1, ary2)\n ary1.zip(ary2).flatten\nend", "def interleave(arr1, arr2)\n arr1.zip(arr2).flatten\nend", "def interleave(arr1, arr2)\n arr1.zip(arr2).flatten\nend", "def interleave(arr1, arr2)\n arr1.zip(arr2).flatten\nend", "def interleave(arr1, arr2)\n arr1.zip(arr2).flatten\nend", "def interleave(arr1, arr2)\n arr1.zip(arr2).flatten\nend", "def interleave(arr1, arr2)\n arr1.zip(arr2).flatten\nend", "def interleave(arr1, arr2)\n return_array = arr1.zip(arr2).flatten\nend", "def interleave(array1, array2)\n array1.zip(array2).flatten\nend", "def interleave(array1, array2)\n array1.zip(array2).flatten\nend", "def interleave(array1, array2)\n array1.zip(array2).flatten\nend", "def interleave(arr1, arr2)\n # new_arr = []\n # arr1.size.times do |count|\n # new_arr << arr1[count] << arr2[count]\n # end\n # new_arr\n\n # using Array#zip and Array#flatten\n arr1.zip(arr2).flatten\nend", "def rotate_array(arr)\n results = arr.map { |n| n }\n results << results.shift\nend", "def rotate_array1(arr)\n rotated_arr = arr.map { |element| element }\n rotated_arr.push(rotated_arr.shift)\n\n rotated_arr\nend", "def rotate(arr)\n\nend", "def interleave2(arr1, arr2)\n arr1.zip(arr2).flatten\nend", "def rotate_arr(arr)\n result_arr = arr.map{|num| num}\n result_arr << result_arr[0]\n result_arr.shift\n result_arr\nend", "def rotate_array(ary)\n ary[1..-1] + [ary[0]] # need to concatenate 2 arrays\nend", "def interleave2(array1, array2)\n array1.zip(array2).flatten\nend", "def multiply_list_zip(array1,array2)\n array1.zip(array2).map {|element| element.reduce(:*)}\n # array 1's element would be spread out into three arrays, 3,5 and 7 being the first elements. Zip then iterates through the argument\n # and mergers these elements into array1 one by one. The documentation then states if a block is given it invoked for EACH ARRAY, so in this case\n # the combined arrays we have now created.\nend", "def rotate_array(ary)\n new_ary = []\n ary.each { |e| new_ary << e}\n new_ary << new_ary.shift\n new_ary\nend", "def zip_sum(array, array2)\n new_arr = []\n array.length.times do |index|\n new_arr.push(array[index] + array2[index])\n end\n new_arr\nend", "def rotate_array(arr, num)\n num.times do \n ele = arr.pop \n arr.unshif(ele)\n end\n return arr \nend", "def interleave(arr1, arr2)\n results = []\n arr1.each.with_index do |el,idx|\n results << el << arr2[idx]\n end\n results\nend", "def interleave(arr1, arr2)\n return_array = []\n arr1.each_with_index do |element, index|\n return_array << element << arr2[index]\n end\nend", "def interleave(arr1, arr2)\n arr3 = []\n arr1.each_with_index do |element, idx|\n arr3 << element << arr2[idx]\n end\n arr3\nend", "def my_transpose\n transposed = []\n\n i = 0\n until transposed.length == length\n current = []\n self.each do |arr|\n current << arr[i]\n end\n i += 1\n transposed << current\n end\n\n transposed\n end", "def zip(*args, &result_selector)\n args.unshift(self)\n Observable.zip(*args, &result_selector)\n end", "def interleave(arr1, arr2)\r\n combined_arr = []\r\n counter = 0\r\n arr1.size.times do\r\n combined_arr << arr1[counter]\r\n combined_arr << arr2[counter]\r\n counter += 1\r\n end\r\n combined_arr\r\nend", "def interleave(a, b)\n a.zip(b).flatten\nend", "def rotate_array(arr)\nnew_arr = []\narr.each do |num|\nnew_arr << num\nend\t\nnew_arr << new_arr.shift\nend", "def interleave(arr1, arr2)\n count = arr1.size\n interleaved = []\n count.times do\n interleaved << arr1.shift\n interleaved << arr2.shift\n end\n interleaved\nend", "def interleave(arr1, arr2)\n output_arr = []\n arr1.size.times do |idx|\n output_arr << arr1[idx]\n output_arr << arr2[idx]\n end\n output_arr\nend", "def zip_and_flatten(array1,array2)\t\n\t\t(array1.zip(array2)).flatten(1).reject{|x| x.nil?}\n\tend", "def combine_zip(a, b)\n if a.length < b.length\n # fill in if a shorter than b\n a += Array.new(b.length - a.length)\n end\n a.zip(b).flatten!\nend", "def interleave(arr1, arr2)\n index = 0\n results = []\n arr1.size.times do\n results << arr1[index] << arr2[index]\n index += 1\n end\n results\nend", "def zip\n @zip\n end", "def interleave(array1, array2)\n result = []\n array1.each_with_index do |element, index|\n result << element << array2[index]\n end\n result\nend", "def interleave(array1, array2)\n result = []\n array1.each_with_index do |element, index|\n result << element << array2[index]\n end\n result\nend", "def interleave(array_1, array_2)\n interwoven_array = []\n\n array_1.each_with_index do |element, index|\n interwoven_array << element << array_2[index]\n end\n\n interwoven_array\nend", "def interleave(a1, a2)\n # new_array = []\n # index = 0\n # while index < a1.size\n # new_array.push(a1[index])\n # new_array.push(a2[index])\n # index += 1\n # end\n # new_array\n # LS solution\n # result = []\n # array1.each_with_index do |element, index|\n # result << element << array2[index]\n # end\n # result\n a1.zip(a2).flatten\nend", "def rotate_array(numbers)\n new_numbers = []\n new_numbers << numbers[1,numbers.size] << numbers[0]\n new_numbers.flatten\nend", "def alternate!\n return self if size.zero?\n first = self[0]\n return self.clear << [first] if size == 1\n ary1, ary2 = populate_alternate_arrays\n self.clear << ary1 << ary2\n end", "def rotate_array(ary)\r\n ary[1..-1] << ary[0]\r\nend", "def interleave(array1, array2)\n result = []\n array1.each_with_index do |value, index|\n result << value << array2[index]\n end\n result\nend", "def interleave(arr1, arr2)\n results = []\n\n arr1.each_with_index do |el, i|\n results << el << arr2[i]\n # results << el << arr2[arr1.index(el)] ## if you wanted to do it without index as block param\n end\n\n results\nend", "def interleave(arr1, arr2)\n new_array = []\n for i in 1..(arr1.size)\n new_array << arr1[(i-1)]\n new_array << arr2[(i-1)]\n end\n new_array\nend", "def rotate_array(arr)\n array = arr.dup\n array << array.shift\nend", "def interleave(*arrays)\n return [] if arrays.empty?\n inter_array = []\n\n arrays.max_by(&:length).size.times do |index|\n arrays.each { |array| inter_array << array[index] }\n end\n\n inter_array\nend", "def interleave(arr1, arr2)\n result = []\n arr1.each_with_index do |elem, indx|\n result << elem << arr2[indx]\n end\n result\nend", "def zip_to_length(length, *arrays)\n (0...length).map do |i|\n arrays[-1].map { |array| array[i] }\n end\nend", "def my_transpose(trans_arr)\n i, j = 0, 1\n array_copy = trans_arr.dup\n (i...trans_arr.length-1).each do |index_one|\n (j...trans_arr.length).each do |index_two|\n array_copy[index_one][index_two], array_copy[index_two][index_one] =\n array_copy[index_two][index_one], array_copy[index_one][index_two]\n end\n end\n array_copy\n end" ]
[ "0.8540384", "0.80693436", "0.8067127", "0.8039325", "0.7993101", "0.784742", "0.7763381", "0.7663384", "0.75189614", "0.74319786", "0.7428339", "0.7375697", "0.7319816", "0.7308451", "0.72927517", "0.72720647", "0.72638446", "0.72536325", "0.7252348", "0.7243587", "0.72239625", "0.72163856", "0.7206489", "0.71980596", "0.71898144", "0.71554244", "0.7130175", "0.7096328", "0.70923245", "0.7002402", "0.69707984", "0.69319445", "0.69242334", "0.69199866", "0.68852067", "0.6816381", "0.679452", "0.6784263", "0.67720556", "0.6721008", "0.665974", "0.6565927", "0.6553881", "0.6548766", "0.65417796", "0.65240526", "0.651124", "0.6508332", "0.6445227", "0.6440288", "0.6420234", "0.6420234", "0.6420234", "0.6420234", "0.6420234", "0.6420234", "0.64101255", "0.6339673", "0.6339673", "0.6339673", "0.63304496", "0.62890327", "0.62540156", "0.6216077", "0.6213729", "0.61979234", "0.6190621", "0.6182278", "0.61671597", "0.61566484", "0.61532485", "0.6148973", "0.6136667", "0.6111249", "0.6107322", "0.6104714", "0.6102946", "0.60936695", "0.60915786", "0.609108", "0.6064065", "0.6054056", "0.60534066", "0.6051716", "0.6051533", "0.6048903", "0.6044179", "0.6044179", "0.6030763", "0.6029402", "0.60239136", "0.6023655", "0.6020469", "0.6012316", "0.6011581", "0.60111946", "0.59940124", "0.599395", "0.5992991", "0.5992569", "0.5986818" ]
0.0
-1
Get a diff that can be stored as a JSON string, persisted and retrieved to apply (by default, Diff::LCS::Changeas_json isn't very useful)
def persistable_diff(a, b) diff = Diff::LCS.diff a, b reify_diff_element(diff).as_json end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def diff\n @diff ||= begin\n commit.diffs.collect{|diff| diff.diff}.join(\"\\n\")\n end\n end", "def changes\n @changes ||= JSON.parse(File.read(ARGV[1]))\nend", "def json\n delta_pack.to_json\n end", "def diff_init(diff, path)\n Smash.new.tap do |di|\n if diff.size > 1\n updated = diff.find_all { |x| x.first == \"+\" }\n original = diff.find_all { |x| x.first == \"-\" }\n di[:original] = Array(original).map(&:last).join(\", \")\n di[:updated] = Array(updated).map(&:last).join(\", \")\n else\n diff_data = diff.first\n di[:path] = path\n if diff_data.size == 3\n di[diff_data.first == \"+\" ? :updated : :original] = diff_data.last\n else\n di[:original] = diff_data[diff_data.size - 2].to_s\n di[:updated] = diff_data.last.to_s\n end\n end\n end\n end", "def changes_for_json\n hash = {}\n changes.each do |attr_name, (_old_value, new_value)|\n new_value = (new_value.to_f * 1000).to_i if new_value.is_a? Time\n hash[attr_name.to_s] = new_value\n end\n\n hash\n end", "def generate_diff\n jsons = version_jsons.map { |j| pretty_json(j) }\n differ = Differ.send(diff_method, *jsons).format_as(:html)\n differ.gsub!('<ins', \"\\n<ins\") if diff_method == :diff_by_line\n @diff = sanitize(differ).html_safe\n end", "def pretty_json\n JSON.pretty_generate(delta_pack)\n end", "def changes(start_ref, end_ref)\n check_refs(start_ref, end_ref)\n s = Mixlib::ShellOut.new(\n \"#{@bin} diff -r #{start_ref}:#{end_ref} --summarize #{@repo_path}\")\n s.run_command.error!\n @logger.info(\"Diff between #{start_ref} and #{end_ref}\")\n s.stdout.lines.map do |line|\n m = line.match(/^(\\w)\\w?\\s+(\\S+)$/)\n fail \"Could not parse line: #{line}\" unless m\n\n {\n :status => m[1] == 'D' ? :deleted : :modified,\n :path => m[2].sub(\"#{@repo_path}/\", '')\n }\n end\n end", "def serialized_draft_changeset(my_changes)\n self.class.draft_class.object_changes_col_is_json? ? my_changes : Draftsman.serializer.dump(my_changes)\n end", "def make_my_diffs_pretty!; end", "def diffs_to_api\n return @diffs_to_api if @diffs_to_api\n @diffs_to_api = []\n\n diffs.each do |diff|\n path = diff.delta.new_file[:path]\n # Presumably only the first commit\n next if path.split('.').first.to_s.downcase == \"readme\"\n\n lines = []\n diff.each_hunk.each do |hunk|\n lines += hunk.lines\n end\n\n html = OutputRenderer.diff(lines)\n status = diff.delta.status\n\n @diffs_to_api << {\n status: status,\n path: path,\n html: html,\n content: @repo.lookup(diff.delta.new_file[:oid]).content\n }\n\n end\n\n @diffs_to_api\n end", "def changes\n @attributes[:changes]\n end", "def diff\n @diff ||= instance.client.createDiffHTML(padID: pad.id, startRev: start_rev, endRev: end_rev)\n end", "def delta\n deltas = self.class.delta_documents(@parsed)\n self.class.friendly_deltas(deltas, @parsed)\n end", "def object_changes\n object_changes = search_result.map { |obj| JSON.parse(obj.object_changes) }\n object_changes.reduce(&:merge) || {}\n end", "def get_changes(opts = {})\n data, _status_code, _headers = get_changes_with_http_info(opts)\n data\n end", "def diff\n return if diffs.empty?\n\n minimized_hunk.diff(:unified) + NEWLINE\n end", "def get_diff_for(review_num, diff_num)\n path = '/r/' + review_num.to_s + '/diff/'\n if diff_num != LATEST\n path += diff_num.to_s\n end\n path += 'raw/'\n r = http.get(path)\n return r.body\n end", "def diff_hash\n {\n diff: diff_hunk,\n new_path: file_path,\n old_path: file_path,\n\n # These fields are not displayed for LegacyDiffNote notes, so it\n # doesn't really matter what we set them to.\n a_mode: '100644',\n b_mode: '100644',\n new_file: false\n }\n end", "def recordable_object_changes(changes)\n if @record.class.paper_trail.version_class.object_changes_col_is_json?\n changes\n else\n PaperTrail.serializer.dump(changes)\n end\n end", "def diff\n \trespond_in_format Marginalia.diff(params[:id])\n end", "def call\n return if remote.keys.all? { |k| no_diff?(k) }\n {\n remote_reference: remote_reference,\n diff: build_diff\n }\n end", "def serialize_change(obj)\n if (obj.saved_changes.keys & @opts[:serialize]).any?\n serialize(obj, \"C\")\n end\n end", "def diff_to_compare; end", "def reload_diffs\n new_attributes = {}\n new_diffs = []\n\n if commits.size.zero?\n new_attributes[:state] = :empty\n else\n diff_collection = unmerged_diffs\n\n if diff_collection.overflow?\n # Set our state to 'overflow' to make the #empty? and #collected?\n # methods (generated by StateMachine) return false.\n new_attributes[:state] = :overflow\n end\n\n new_attributes[:real_size] = diff_collection.real_size\n\n if diff_collection.any?\n new_diffs = dump_diffs(diff_collection)\n new_attributes[:state] = :collected\n end\n end\n\n new_attributes[:st_diffs] = new_diffs\n\n new_attributes[:start_commit_sha] = self.target_branch_sha\n new_attributes[:head_commit_sha] = self.source_branch_sha\n new_attributes[:base_commit_sha] = branch_base_sha\n\n update_columns_serialized(new_attributes)\n\n keep_around_commits\n end", "def commit_diff(project, sha)\n get(\"/projects/#{project}/repository/commits/#{sha}/diff\") \n end", "def diff(objectish = 'HEAD', obj2 = nil)\n Git::Diff.new(self, objectish, obj2)\n end", "def diffed(old, new)\n differ = Differ.diff_by_line(new, old)\n differ.to_s[/\\{[^}]+\\}/][1...-1].gsub(/\\s{2,}/, '')\n end", "def diff_edits(diff_from_empty=false)\n edit_diffs = Hash.new\n e = Errata.find(errata.id)\n\n # synopsis field needs a special case due to being rewritten before save...\n get_errata = {\n :synopsis => lambda { |e,_| synopsis_preview(e) },\n :default => lambda { |e,field| e.send(field) }\n }\n get_params = {\n :synopsis => lambda { |_| synopsis_preview_from_params },\n :default => lambda { |field| params[:advisory][field] }\n }\n\n # NOTE: Not sure why only these fields are checked, other\n # changes like keywords, cross_references, idsfixed etc might\n # also cause the docs output to change. Is this a feature?\n [:synopsis, :topic, :description, :solution].each do |field|\n errata_read = get_errata[field] || get_errata[:default]\n params_read = get_params[field] || get_params[:default]\n if diff_from_empty\n # This part is a little confusing.\n # Compare the unedited value with an empty string.\n old = ''\n new = errata_read.call(e, field)\n else\n # This part makes more sense.\n # Compare the unedited value with the new edited value.\n old = errata_read.call(e, field)\n new = params_read.call(field)\n end\n next unless new\n text_diff = diff_as_string(old,new)\n unless text_diff.empty?\n edit_diffs[field] = text_diff\n end\n end\n edit_diffs\n end", "def differences\n @attributes[:differences]\n end", "def getPullRequestDiff(id)\n response = getUrl(@url_pullrequests + \"/\" + id.to_s + \"/diff\")\n puts response if @options[\"verbose\"]\n return response\n end", "def diff url\n parse_response HTTParty.get \"#{url}.diff\"\n end", "def audited_changes(options = {})\n audits.last.try(:latest_diff, options) || {}\n end", "def audited_changes(options = {})\n audits.last.try(:latest_diff, options) || {}\n end", "def cmd_diff\n print_tree(DiffEditor, nil, true)\n end", "def create\n @diff = Diff.new(diff_params)\n\n respond_to do |format|\n if @diff.save\n format.html { redirect_to @diff, notice: 'Diff was successfully created.' }\n format.json { render :show, status: :created, location: @diff }\n else\n format.html { render :new }\n format.json { render json: @diff.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @diff = Diff.new(diff_params)\n\n respond_to do |format|\n if @diff.save\n format.html { redirect_to @diff, notice: 'Diff was successfully created.' }\n format.json { render :show, status: :created, location: @diff }\n else\n format.html { render :new }\n format.json { render json: @diff.errors, status: :unprocessable_entity }\n end\n end\n end", "def hash\n h = {}\n h['_rm'] = removed_keys unless removed_keys.empty?\n h['_ch'] = Hash[changes.collect {|k,v| [k, v.is_a?(Diff) ? v.hash : v]}] unless\n changes.empty?\n h\n end", "def diff(scm, options={}, &block)\n scm.diff(self, options, &block)\n end", "def diff(from, to)\n @repository.diff(from, to, path)\n end", "def update\n respond_to do |format|\n if @diff.update(diff_params)\n format.html { redirect_to @diff, notice: 'Diff was successfully updated.' }\n format.json { render :show, status: :ok, location: @diff }\n else\n format.html { render :edit }\n format.json { render json: @diff.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @diff.update(diff_params)\n format.html { redirect_to @diff, notice: 'Diff was successfully updated.' }\n format.json { render :show, status: :ok, location: @diff }\n else\n format.html { render :edit }\n format.json { render json: @diff.errors, status: :unprocessable_entity }\n end\n end\n end", "def changelog_json(job_id, script, message)\n dump_json(\n digest: key.digest,\n job_id: job_id,\n script: script,\n message: message,\n time: now_f,\n )\n end", "def to_json\n to_parsed.to_json\n end", "def extract_changes(str)\n str.lines.map do |line|\n new_git_change(*Regexp.last_match.captures) if line.match(/\\t(.*:)?(.*)/)\n end.compact # in case there were any non matching lines left\n end", "def make_commit_log\n\t\t\tdiff = read_command_output( 'hg', 'diff' )\n\t\t\tfail \"No differences.\" if diff.empty?\n\n\t\t\treturn diff\n\t\tend", "def diff(from, to)\n @repo.diff(from, to).path(path)\n end", "def diff_stats\n JSON.parse(summary) if summary.present? && summary.start_with?('{', '[')\n rescue JSON::ParserError\n nil # Return nil if parsing fails (i.e., not diff_stats)\n end", "def historic_diff\n # get the two versions to diff\n @new_measure = Measure.by_user(current_user).where({:_id => params[:new_id]}).first\n unless @new_measure\n @new_measure = ArchivedMeasure.where({:measure_db_id => params[:new_id]}).first.to_measure\n end\n\n @old_measure = Measure.by_user(current_user).where({:_id => params[:old_id]}).first\n unless @old_measure\n @old_measure = ArchivedMeasure.where({:measure_db_id => params[:old_id]}).first.to_measure\n end\n\n results = {}\n results['diff'] = []\n results['pre_upload'] = { \n 'cms_id' => @old_measure.cms_id,\n 'updateTime' => (@old_measure.updated_at.tv_sec * 1000),\n 'hqmf_id' => @old_measure.hqmf_id,\n 'hqmf_version_number' => @old_measure.hqmf_version_number }\n results['post_upload'] = { \n 'cms_id' => @new_measure.cms_id,\n 'updateTime' => (@new_measure.updated_at.tv_sec * 1000),\n 'hqmf_id' => @new_measure.hqmf_id,\n 'hqmf_version_number' => @new_measure.hqmf_version_number }\n\n measure_logic_names = HQMF::Measure::LogicExtractor::POPULATION_MAP.clone\n measure_logic_names['VARIABLES'] = 'Variables'\n\n # Walk through the population sets and populations for the measure and create a\n # diffy for each populationm.\n @new_measure.populations.each_with_index do |new_population_set, population_set_index|\n old_population_set = @old_measure.populations[population_set_index]\n population_diff = []\n\n # For each population within the population set, get the population logic and\n # perform the diffy\n measure_logic_names.each_pair do |population_code, population_title|\n # if the code is for VARIABLE, leave it. If it's IPP, etc., then access the actual code name from the\n # population set (e.g. IPP_1).\n code = (population_code == 'VARIABLES') ? 'VARIABLES' : new_population_set[population_code]\n new_logic = @new_measure.measure_logic.find { |logic| logic['code'] == code }\n old_logic = @old_measure.measure_logic.find { |logic| logic['code'] == code }\n\n # skip if both are non existent\n next if !new_logic && !old_logic\n \n # Remove the first line of the measure logic, which is the the name of the population.\n old_logic_text = old_logic ? old_logic['lines'][1..-1].join() : \"\"\n new_logic_text = new_logic ? new_logic['lines'][1..-1].join() : \"\"\n\n logic_diff = Diffy::SplitDiff.new(old_logic_text, new_logic_text,\n format: :html, include_plus_and_minus_in_html: true, allow_empty_diff: false)\n\n population_diff << {code: population_code, title: population_title, pre_upload: logic_diff.left, post_upload: logic_diff.right}\n end\n\n results['diff'] << population_diff\n end\n\n render :json => results\n end", "def diffs \n @diffs ||= begin\n diff = `svn diff`.split(\"\\n\").map {|l| l.chomp}\n _diffs = {}\n in_diff = false\n in_path = false\n path = nil\n diff.each do |line|\n if /Index:/ =~ line \n path = /Index: (.*)/.match(line)[1]\n _diffs[path] = ' '\n in_path = true\n in_diff = false\n next\n end\n\n if in_path and !in_diff and /^@@/ =~ line\n in_diff = true\n next\n end\n\n if in_diff and in_path\n if /^\\+/ =~ line\n _diffs[path] += '+'\n elsif /^-/ =~ line\n _diffs[path] = _diffs[path] + '-'\n end\n end\n end\n _diffs.map do |k, v| \n _diffs[k] = v.split('').map do |chr| \n { '+' => \"#{COLOR_GREEN}+\", \n '-' => \"#{COLOR_RED}-\"}[chr]\n end.join() + \"#{COLOR_NONE}\"\n end\n _diffs\n end\n end", "def revised_embed_changes\n new_record? ? {} : collect_embed_revision_models do |item, results, fields|\n item.changes.each do |k, v|\n if fields.include?(k)\n results[k] = v.last\n end\n end\n end\n end", "def to_json\n @json ||= get_json\n end", "def html\n diff[:html]\n end", "def get_rule_diff(new_rule_hash)\n existing_rule = parse_firewall_rule(new_rule_hash['name'])\n diff = []\n new_rule_hash.each do |key, val| # Only compare fields that exist in the firewall_rule resource\n diff_rule_field(diff, existing_rule, key, val)\n end\n log_rule_diff(existing_rule, new_rule_hash, diff)\n return diff\n end", "def convert\n old = @hashes\n @hashes = Hash.new\n\n puts 'Warning: old JSON format detected, converting.'\n old.each {|i| add_hash(i[:id], i[:deletehash], 'unknown') }\n save\n end", "def changeset\n @changeset ||= git_diff.map do |diff_file|\n file_diff = FileDiff.new(diff_file)\n file_diff unless FormattingChecker.pure_formatting?(file_diff)\n end.compact\n end", "def changes\n changed? ? {'value' => [@value_was, value]} : {}\n end", "def parse_rep_changes(result)\n parse_type(result, \"rep_change\")\n end", "def show\n respond_with(create_presenter(:diff, GetDiff.new(params)))\n end", "def evaluateDiffResult()\n\n end", "def deep_clone\n if RUBY_PLATFORM == 'opal'\n JSON.parse(to_json)\n else\n Marshal.load(Marshal.dump(self))\n end\n end", "def get_links_changes(params)\n get_json(links_changes_url(params))\n end", "def differ\n @differ ||= Differ.new(externals)\n end", "def get_diff_from_previous_file\n result = \"\"\n if (@diff_filename.nil?)\n # Get both the filename for logging.\n previous_filename = self.full_path_from_edict_file(self.old_filename)\n current_filename = self.full_path_from_edict_file(@config[\"filename\"])\n\n # Only do the diff if both files actually exist\n if (File.file? previous_filename) && (File.file? current_filename)\n # We want to add the timestamp as part of the diff filename\n timestamp = DateTime.now.strftime \"%d%m%y-%H%M\"\n result = Rails.root.join(\"data/cedict/migration_history/diff#{timestamp}.txt\").to_s\n `diff '#{previous_filename}' '#{current_filename}' > '#{result}'`\n end\n @diff_filename = result\n end\n \n return @diff_filename\n end", "def diff(from, to=nil)\n scm :diff, repository, authentication, \"-r#{from}:#{to || head}\"\n end", "def diff_formatter= diff_formatter\n register_diff_formatter(/.*/, diff_formatter)\n register_diff_formatter(nil, diff_formatter)\n end", "def diff(from, to=nil)\n scm :diff, repository, authentication, \"-r#{from}:#{to || head}\"\n end", "def generate_diff_hash(base_content, revised_content)\n revised_content.compact.collect {|content_key, revised_value|\n current_value = base_content.send(content_key) || ''\n\n # Ignore unchanged contents or nil (not blank!) content attributes\n unless current_value == revised_value\n [content_key, persistable_diff(current_value, revised_value || '').to_json]\n end\n }.compact.to_h\n end", "def to_json(*)\n\t\t\t# to_json needs to not care about arguments with the C extension\n\t\t\t# version of the JSON gem.\n\t\t\t# See json-1.5.1/ext/json/ext/generator/generator.c:902\n\t\t\tto_hash.to_json\n\t\tend", "def to_html\n diff(@old, @new, @fields).reduce({}) do |diffed_output, (key, val)|\n if val.class == Hash\n diffed_output[key] = val.reduce({}) do |d_o, (k, v)|\n d_o[k] = v.to_s :html\n d_o\n end\n else\n diffed_output[key] = val.to_s :html\n end\n diffed_output\n end\n end", "def document_changes\n attributes.fetch(:documentChanges)\n end", "def document_changes\n attributes.fetch(:documentChanges)\n end", "def as_json\n JSON.parse self.to_json\n end", "def colorized_diff\n return unless diff\n\n diff.lines.map(&self.class.method(:colorize_line)).join\n end", "def diff_lines_for_serializer\n strong_memoize(:diff_lines_for_serializer) do\n lines = highlighted_diff_lines\n\n next if lines.empty?\n next if blob.nil?\n\n last_line = lines.last\n\n if last_line.new_pos < total_blob_lines(blob) && !deleted_file?\n match_line = Gitlab::Diff::Line.new(\"\", 'match', nil, last_line.old_pos, last_line.new_pos)\n lines.push(match_line)\n end\n\n lines\n end\n end", "def local_diff\n `cd #{@local_path} && git diff HEAD`\n end", "def parse_changeset(attribute, values, type, diff)\n return parse_scope_changeset(attribute, values, type, diff) if type == :scope\n\n values = parse_values(attribute, values)\n\n diff.update(\n attribute => {\n type: type,\n label: I18n.t(attribute, scope: i18n_scope),\n old_value: values[0],\n new_value: values[1]\n }\n )\n end", "def delta(rev)\n $repo.diff(commit, rev).path(@name).patch\n end", "def changes\n @changes ||= Changes.new do |msg|\n log.indent do\n log << msg\n end\n end\n end", "def diffyable\n # add appropriate diff column data for diff.right and diff.left and update other attrs to the Diffy way®\n\n w1id = self.work1\n w2id = self.work2\n w1work = Work.find(w1id)\n w2work = Work.find(w2id)\n w1md = w1work.file_content_md\n w2md = w2work.file_content_md\n w1txt = w1work.file_content_text\n w2txt = w2work.file_content_text\n\n html = Diffy::Diff.new(w1md, w2md).to_s(:html)\n md = Diffy::Diff.new(w1md, w2md).to_s\n text = Diffy::Diff.new(w1txt, w2txt).to_s\n \n lucy = Diffy::SplitDiff.new(w1md, w2md, :format => :html).left\n recha = Diffy::SplitDiff.new(w1md, w2md, :format => :html).right\n\n html.force_encoding(\"UTF-8\").scrub!\n md.force_encoding(\"UTF-8\").scrub!\n text.force_encoding(\"UTF-8\").scrub!\n\n lucy.force_encoding(\"UTF-8\").scrub!\n recha.force_encoding(\"UTF-8\").scrub!\n\n self.update_attributes(left: lucy, right: recha, diff_md: md, diff_html: html, diff_text: text)\n self.save\n end", "def to_json\n to_s.to_json\n end", "def product_get_data_changes(opts = {})\n data, _status_code, _headers = product_get_data_changes_with_http_info(opts)\n data\n end", "def sync_difference(name, diffs)\n aws = Hash[aws_resources.map { |aws| [aws.name, aws] }]\n if diffs.size > 0\n StatusCodes::set_status(StatusCodes::SYNC_DIFFS)\n\n if diffs[0].type == Common::DiffChange::UNMANAGED\n puts diffs[0]\n elsif diffs[0].type == Common::DiffChange::ADD\n puts Colors.added(\"creating #{name}...\")\n resource = create(diffs[0])\n update(resource, diffs)\n else\n puts Colors.blue(\"updating #{name}...\")\n resource = aws[name]\n update(resource, diffs)\n end\n end\n end", "def contents_for(delta, type = :dst)\n ref = if type == :src\n delta.old_file[:oid]\n elsif type == :dst\n delta.new_file[:oid]\n end\n @git.lookup(ref).content if ref != \"0000000000000000000000000000000000000000\"\n end", "def json\n @json_hash.to_json\n end", "def to_json\n return self.to_hash.to_json\n end", "def return_json_string\n @traces_json_string\n end", "def ext_to_hash\n JSON.parse(self)\n end", "def to_json(what)\n what.to_hash.to_json\n end", "def as_json\n to_s.as_json\n end", "def diff(opts)\n from, to = opts[:from], opts[:to]\n if from && !(Commit === from)\n raise ArgumentError, \"Invalid sha: #{from}\" if from !~ SHA_PATTERN\n from = Reference.new(:repository => self, :id => from)\n end\n if !(Commit === to)\n raise ArgumentError, \"Invalid sha: #{to}\" if to !~ SHA_PATTERN\n to = Reference.new(:repository => self, :id => to)\n end\n Diff.new(from, to, git_diff_tree('--root', '--full-index', '-u',\n opts[:detect_renames] ? '-M' : nil,\n opts[:detect_copies] ? '-C' : nil,\n from ? from.id : nil, to.id, '--', *opts[:path]))\n end", "def extract_changelog\n changelog = ''\n in_changelog = false\n git_show.send(LINE_ITERATOR) do |line|\n if line =~ /^diff --git/\n in_changelog = false\n elsif line =~ /^\\+\\+\\+.*changelog$/i\n in_changelog = true\n elsif in_changelog && line =~ /^\\+\\s*\\*/\n changelog << line\n end\n end\n changelog\n end", "def diff_from_parent(options = {})\n @repository.gitaly_commit_client.diff_from_parent(self, options)\n end", "def diffto(value)\n merge(rvdiffto: value.to_s)\n end", "def json_ld\n @json_ld ||= JSONLDDrop.new(self)\n end", "def set_diff\n @diff = Diff.find(params[:id])\n end", "def serialize_data\n return unless self.version_changes.nil? && previous\n\n db = CouchRest.database(\"http://208.78.99.54:5984/packages\")\n current = db.get(vname)\n prev = db.get(previous.vname)\n\n current_functions = current[\"function_hashes\"].keys\n prev_functions = prev[\"function_hashes\"].keys\n\n changes = {}\n changes[:removed] = (prev_functions - current_functions).sort\n changes[:added] = (current_functions - prev_functions).sort\n changes[:changed] = []\n\n current_functions.each do |f|\n changes[:changed] << f if current[\"function_hashes\"][f] != prev[\"function_hashes\"][f]\n end\n changes[:changed].sort!\n\n self.version_changes = changes\n\n rescue RestClient::ResourceNotFound\n self.version_changes = {}\n ensure\n save!\n end", "def changes\n result = get_modified_from_solr(first_modified: params['first_modified'], last_modified: params['last_modified'])\n render_result(result)\n end", "def changes\n ViewModel::Changes.new(\n new: new_model?,\n changed_attributes: changed_attributes,\n changed_associations: changed_associations,\n changed_nested_children: changed_nested_children?,\n changed_referenced_children: changed_referenced_children?,\n )\n end", "def to_json\n to_hash.to_json\n end" ]
[ "0.66141504", "0.6368866", "0.60854304", "0.58906037", "0.58535475", "0.584853", "0.57909197", "0.54888964", "0.5454939", "0.5436178", "0.5413507", "0.5353406", "0.53247666", "0.53161436", "0.52924263", "0.5253892", "0.52419835", "0.52074444", "0.5183777", "0.51828593", "0.51657873", "0.5155891", "0.5155704", "0.51367086", "0.5110627", "0.5091187", "0.50666004", "0.5053077", "0.50472176", "0.5046017", "0.5029781", "0.5029129", "0.5026299", "0.5026299", "0.498855", "0.49868172", "0.49868172", "0.4986721", "0.49837643", "0.49705014", "0.49701804", "0.49701804", "0.4955228", "0.49548364", "0.49364322", "0.49356237", "0.49347195", "0.4922491", "0.49206644", "0.49189216", "0.4906662", "0.49018562", "0.48972654", "0.48701942", "0.486964", "0.4868784", "0.48603395", "0.48477662", "0.48402798", "0.48365864", "0.4833953", "0.48314616", "0.48253018", "0.48233095", "0.48212314", "0.48174146", "0.48151043", "0.48121834", "0.48080236", "0.48043653", "0.47930706", "0.47930706", "0.47926518", "0.47898147", "0.47841823", "0.47734478", "0.47671363", "0.47604224", "0.47598904", "0.4759664", "0.47593674", "0.47590074", "0.47579983", "0.4756441", "0.47540003", "0.47535187", "0.47511753", "0.47435468", "0.47424406", "0.47329995", "0.47292554", "0.47248685", "0.47234514", "0.4721017", "0.47159502", "0.4714774", "0.47000286", "0.4698235", "0.46950954", "0.469353" ]
0.69219756
0
Create a Revision using revised content compared to base content
def revise_from_content(base_content, revised_content) revisions.build(diffs: generate_diff_hash(base_content, revised_content)) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_revision!\n logger.info(\"Creating a new revision for article_submission id: #{self.id}\")\n rev = self.copy(false)\n unless rev.article_submission\n rev.article_submission = self \n self.update_attribute(:last_revision,false)\n else\n rev.article_submission.article_submissions.each do |as|\n as.update_attribute(:last_revision,false)\n end\n end\n \n rev.resubmitted = nil\n rev.committed = nil\n rev.last_revision = true\n rev.save(false) \n rev.set_version!\n self.article_submission_reviewers.each do |ar|\n reviewer = ar.clone\n reviewer.change_status(ArticleSubmissionReviewer::NOT_YET_INVITED)\n rev.article_submission_reviewers << reviewer\n end\n rev.change_status(ArticleSubmission::STARTED)\n rev.increment_manuscript_rev_num\n\n return rev\n end", "def create_revision!\n revision = RevisionRecord.new(self, acts_as_revisionable_options[:encoding])\n revision.save!\n return revision\n end", "def create\n revisions do |orig_file, sha_list|\n sha_list.each_with_index do |sha, i|\n ver = (i + 1).to_s\n # Git revisioned file\n composeversions(orig_file, sha, ver) do |content, data, file_path|\n # dont re-write files\n if File.exist?(file_path)\n linecount(file_path)\n next\n end\n\n version_content = FrontMatter.new(data)\n version_content.content = content \n write(file_path, version_content.update)\n linecount(file_path)\n end\n end\n\n sha_list.map!.with_index { |sha, i| [] << sha << (i + 1) }\n # Git Diff combination files\n composediffs(orig_file, line_count, sha_list.combination(2)) do |content, data, file_path|\n content.sub!(DIFF_HEADER_REGEXP, '')\n if change?(content)\n VersionedFiles.frontmatter[\"no_change\"] = false\n styled_content = @style.style(content)\n data.merge!(@style.stats.final)\n else\n VersionedFiles.frontmatter[\"no_change\"] = \"no_change\"\n data[\"no_change\"] = true\n end\n\n fm = FrontMatter.new(data).create\n diff_file = fm << styled_content\n write(file_path, diff_file)\n end\n end\n end", "def create_revision!\n revision_options = self.class.acts_as_revisionable_options\n revision = revision_record_class.new(self, revision_options[:encoding])\n if revision_options[:meta].is_a?(Hash)\n revision_options[:meta].each do |attribute, value|\n set_revision_meta_attribute(revision, attribute, value)\n end\n elsif revision_options[:meta].is_a?(Array)\n revision_options[:meta].each do |attribute|\n set_revision_meta_attribute(revision, attribute, attribute.to_sym)\n end\n elsif revision_options[:meta]\n set_revision_meta_attribute(revision, revision_options[:meta], revision_options[:meta].to_sym)\n end\n revision.save!\n return revision\n end", "def original_content\n last_applied = revision.ancestors.find(&:applied?)\n RevisionContent.new(last_applied) if last_applied\n end", "def fetch_revision\n end", "def build_new_revision\n new_revision = Form.new(version_independent_id: version_independent_id,\n description: description, parent_id: parent_id, status: status,\n version: version + 1, name: name, oid: oid,\n created_by: created_by, control_number: control_number)\n\n new_revision\n end", "def add_revision\n attributes = get_attributes\n attributes = convert_empty_id_attributes_to_nil(attributes)\n if was_changed?\n revision = self.revision_model.create!(attributes)\n self.revisions << revision if self.respond_to?(:revisions)\n end\n set_correct_published_revision_number(revision) if self.respond_to?(:published_revision_number)\n end", "def add_revision\n attributes = get_attributes(FIELDS['page_part_revision_attributes'])\n attributes['number'] = self.page.number_of_last_revision\n attributes['filter_id'] = nil if attributes['filter_id'].blank?\n if was_changed?(attributes)\n self.revisions << PagePartRevision.create(attributes)\n end\n return true\n end", "def revision(name, msg, options = {}, &block)\n r = Revision.new(name, msg, options, &block)\n @revisions << r\n r\n end", "def do_revision\n @record = find_if_allowed(params[:id], :read)\n @current_revision_number = @record.current_revision_number\n @revision_number ||= @current_revision_number\n @rev_record_1 = @record.restore_revision(@revision_number) if @revision_number\n @rev_record_2 = @record.restore_revision(@revision_number - 1) if @revision_number > 1\n end", "def create_first_revision\n attributes = get_attributes(FIELDS['page_part_revision_attributes'])\n number = self.page.number_of_last_revision == 0 ? 1 : self.page.number_of_last_revision\n attributes['number'] = number\n self.revisions << PagePartRevision.create(attributes)\n return true\n end", "def revision\n if @new_resource.revision == 'HEAD'\n ['-A']\n else\n ['-r', @new_resource.revision]\n end\n end", "def set_revision\n @revision = find_revision(params[:id])\n end", "def create\n @revision = Revision.new(params[:revision])\n\n if @revision.save\n render json: @revision, status: :created, location: @revision\n else\n render json: @revision.errors, status: :unprocessable_entity\n end\n end", "def create\n @revision = Revision.create(params[:revision])\n redirect_to page_base_url(:page_title => @revision.page.title)\n end", "def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={}, &block)\r\n logger.debug \"<cvs> revisions path:'#{path}',identifier_from #{identifier_from}, identifier_to #{identifier_to}\"\r\n \r\n path_with_project=\"#{url}#{with_leading_slash(path)}\"\r\n cmd = \"#{CVS_BIN} -d #{root_url} rlog\"\r\n cmd << \" -d\\\">#{time_to_cvstime(identifier_from)}\\\"\" if identifier_from\r\n cmd << \" #{shell_quote path_with_project}\"\r\n shellout(cmd) do |io|\r\n state=\"entry_start\"\r\n \r\n commit_log=String.new\r\n revision=nil\r\n date=nil\r\n author=nil\r\n entry_path=nil\r\n entry_name=nil\r\n file_state=nil\r\n branch_map=nil\r\n \r\n io.each_line() do |line| \r\n \r\n if state!=\"revision\" && /^#{ENDLOG}/ =~ line\r\n commit_log=String.new\r\n revision=nil\r\n state=\"entry_start\"\r\n end\r\n \r\n if state==\"entry_start\"\r\n branch_map=Hash.new\r\n if /^RCS file: #{Regexp.escape(root_url_path)}\\/#{Regexp.escape(path_with_project)}(.+),v$/ =~ line\r\n entry_path = normalize_cvs_path($1)\r\n entry_name = normalize_path(File.basename($1))\r\n logger.debug(\"Path #{entry_path} <=> Name #{entry_name}\")\r\n elsif /^head: (.+)$/ =~ line\r\n entry_headRev = $1 #unless entry.nil?\r\n elsif /^symbolic names:/ =~ line\r\n state=\"symbolic\" #unless entry.nil?\r\n elsif /^#{STARTLOG}/ =~ line\r\n commit_log=String.new\r\n state=\"revision\"\r\n end \r\n next\r\n elsif state==\"symbolic\"\r\n if /^(.*):\\s(.*)/ =~ (line.strip) \r\n branch_map[$1]=$2\r\n else\r\n state=\"tags\"\r\n next\r\n end \r\n elsif state==\"tags\"\r\n if /^#{STARTLOG}/ =~ line\r\n commit_log = \"\"\r\n state=\"revision\"\r\n elsif /^#{ENDLOG}/ =~ line\r\n state=\"head\"\r\n end\r\n next\r\n elsif state==\"revision\"\r\n if /^#{ENDLOG}/ =~ line || /^#{STARTLOG}/ =~ line \r\n if revision\r\n \r\n revHelper=CvsRevisionHelper.new(revision)\r\n revBranch=\"HEAD\"\r\n \r\n branch_map.each() do |branch_name,branch_point|\r\n if revHelper.is_in_branch_with_symbol(branch_point)\r\n revBranch=branch_name\r\n end\r\n end\r\n \r\n logger.debug(\"********** YIELD Revision #{revision}::#{revBranch}\")\r\n \r\n yield Revision.new({ \r\n :time => date,\r\n :author => author,\r\n :message=>commit_log.chomp,\r\n :paths => [{\r\n :revision => revision,\r\n :branch=> revBranch,\r\n :path=>entry_path,\r\n :name=>entry_name,\r\n :kind=>'file',\r\n :action=>file_state\r\n }]\r\n }) \r\n end\r\n \r\n commit_log=String.new\r\n revision=nil\r\n \r\n if /^#{ENDLOG}/ =~ line\r\n state=\"entry_start\"\r\n end\r\n next\r\n end\r\n \r\n if /^branches: (.+)$/ =~ line\r\n #TODO: version.branch = $1\r\n elsif /^revision (\\d+(?:\\.\\d+)+).*$/ =~ line\r\n revision = $1 \r\n elsif /^date:\\s+(\\d+.\\d+.\\d+\\s+\\d+:\\d+:\\d+)/ =~ line\r\n date = Time.parse($1)\r\n author = /author: ([^;]+)/.match(line)[1]\r\n file_state = /state: ([^;]+)/.match(line)[1]\r\n #TODO: linechanges only available in CVS.... maybe a feature our SVN implementation. i'm sure, they are\r\n # useful for stats or something else\r\n # linechanges =/lines: \\+(\\d+) -(\\d+)/.match(line)\r\n # unless linechanges.nil?\r\n # version.line_plus = linechanges[1]\r\n # version.line_minus = linechanges[2]\r\n # else\r\n # version.line_plus = 0\r\n # version.line_minus = 0 \r\n # end \r\n else \r\n commit_log << line unless line =~ /^\\*\\*\\* empty log message \\*\\*\\*/\r\n end \r\n end \r\n end\r\n end\r\n end", "def make_last_revision_earlier(model)\n Revision.record_timestamps = false\n model.revisions.last.update_attributes :created_at => 2.seconds.ago\n Revision.record_timestamps = true\n end", "def revision\n clazz = auditable_type.constantize\n (clazz.find_by_id(auditable_id) || clazz.new).tap do |m|\n self.class.assign_revision_attributes(m, self.class.reconstruct_attributes(ancestors).merge(version: version))\n end\n end", "def copy_revision(original)\n # we only copy the RevisionFile/RevisionDirectory entries\n new_revision = MemoryRevision.new(original.revision_identifier)\n new_revision.user_id = original.user_id\n new_revision.comment = original.comment\n new_revision.files_content = {}\n new_revision.timestamp = original.timestamp\n new_revision.server_timestamp = original.server_timestamp\n # copy files objects\n original.files.each do |object|\n if object.instance_of?(Repository::RevisionFile)\n new_object = Repository::RevisionFile.new(object.from_revision.to_s, {\n name: object.name,\n path: object.path,\n last_modified_revision: object.last_modified_revision,\n changed: false, # for copies, set this to false\n user_id: object.user_id,\n last_modified_date: object.last_modified_date,\n submitted_date: object.last_modified_date\n })\n new_revision.files_content[new_object.to_s] = original.files_content[object.to_s]\n else\n new_object = Repository::RevisionDirectory.new(object.from_revision.to_s, {\n name: object.name,\n path: object.path,\n last_modified_revision: object.last_modified_revision,\n last_modified_date: object.last_modified_date,\n submitted_date: object.last_modified_date,\n changed: false, # for copies, set this to false\n user_id: object.user_id\n })\n end\n new_revision.files.push(new_object)\n end\n new_revision # return the copy\n end", "def test_revision\n get :revision, :id => 1, :rev => 2\n assert_response :success\n assert_template 'revision'\n\n assert_select 'ul' do\n assert_select 'li' do\n # link to the entry at rev 2\n assert_select 'a[href=?]', '/projects/ecookbook/repository/revisions/2/entry/test/some/path/in/the/repo', :text => 'repo'\n # link to partial diff\n assert_select 'a[href=?]', '/projects/ecookbook/repository/revisions/2/diff/test/some/path/in/the/repo'\n end\n end\n end", "def create\n @revision = Revision.new(params[:revision])\n @revision.document_id = params[:document_id]\n @revision.user_id = current_user.id\n respond_to do |format|\n if @revision.save\n expire_fragment(:controller => :documents, :action => :show, :id => @revision.document_id, :action_suffix => 'revisions')\n if @revision.document.category.is_featured\n expire_action :controller => :home, :action => :index\n end\n flash[:notice] = 'Revision was successfully created.'\n format.html { redirect_to(@revision.document) }\n format.xml { render :xml => @revision, :status => :created, :location => @revision }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @revision.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create_revision(id, bin_params)\n @rest.post(\"#{id}/save\", bin_params)\n end", "def set_revision\n @revision = Revision.find(params[:id])\n end", "def call\n clone_revision\n end", "def revisions\n raise NotImplementedError\n end", "def revision(version)\n revision_with audit_changes(version)\n end", "def body\n revision.body\n end", "def revision\n @job = Mugen::Job.find(params[:job_id]) \n @revision = Mugen::Job.revision(params[:job_id], params[:id])\n \n respond_to do |format|\n format.html {}\n format.xml { render :xml => @job }\n end\n end", "def new\n @revision = Revision.create(params[:revision])\n redirect_to page_base_url(:page_title => @revision.page.title)\n end", "def revision\n 99\n end", "def render(*args)\n if request.path_parameters['action'] == \"edit\" && params[:revision]\n # Change revision number if given revision is not existed and we have set last revision\n params[:revision] = model.set_to_revision(params[:revision])\n end\n super(*args)\n end", "def do_rev( hash, override=false )\n hash.delete(:rev) # This is omited to aleviate confusion \n # CouchDB determines _rev attribute on saving, but when #new is loading json passed from the \n # database rev needs to be added to the class. So, the :_rev param is not being deleted anymore\n end", "def revision\r\n @revision\r\n end", "def mark\n \"(echo #{revision} > #{destination}/REVISION)\"\n end", "def revisions(from_version = 1)\n audit_changes(from_version) {|attributes| revision_with(attributes) }\n end", "def revisions\n @revisions ||= RevisionCollection.new(self)\n end", "def test_version_message\n Repository.create()\n FileUtils.touch('.test_file1')\n a = ['.test_file1']\n Repository.add(a) \n Repository.commit()\n #Repository.version()\n end", "def revision(version)\n revision_with Audited.audit_class.reconstruct_attributes(audits_to(version))\n end", "def add_revision(path, ctype, msg)\n # FIXME: implement\n raise('not implemented')\n notify(EVENT_REV, path, ctype, msg)\n end", "def test_revision_at\n u = create_user\n Audit.update(u.audits.first.id, :created_at => 1.hour.ago)\n u.update_attributes :name => 'updated'\n assert_equal 1, u.revision_at(2.minutes.ago).version\n end", "def start_revision(revision)\n end", "def save_revision(revision)\n if revision.save\n revision.page.body = revision.contents\n revision.page.file_path = revision.file_path\n flash[:success] = 'Revision created.'\n redirect_to revision.page and return if revision.page.save\n else\n flash[:danger] = 'Revision failed.'\n redirect_to revision.page\n end\n end", "def add_revision\n address_containers.each { |ac| ac.add_revision }\n nil\n end", "def revision(revision)\n raise NotImplementedError\n end", "def revision\n raise NotImplementedError.new(\"revision() must be implemented by subclasses of AbstractVersionedFile.\")\n end", "def revision(version)\n revision_with ActsAsAuditable::Audit.reconstruct_attributes(audits_to(version))\n end", "def set_current_revisions!\n self.class.transaction do\n save! unless self.id\n\n t = RevisionListContent.table_name\n \n connection.execute <<\"END\"\nDELETE FROM #{t} WHERE revision_list_id = #{self.id}\nEND\n \n connection.execute <<\"END\"\nINSERT INTO #{t} ( revision_list_id, content_version_id )\nSELECT #{self.id}, content_versions.id \nFROM contents, content_versions \nWHERE content_versions.content_id = contents.id AND content_versions.version = contents.version\nEND\n\n t = RevisionListContentKey.table_name\n \n connection.execute <<\"END\"\nDELETE FROM #{t} WHERE revision_list_id = #{self.id}\nEND\n \n connection.execute <<\"END\"\nINSERT INTO #{t} ( revision_list_id, content_key_version_id )\nSELECT #{self.id}, content_key_versions.id \nFROM content_keys, content_key_versions \nWHERE content_key_versions.content_key_id = content_keys.id AND content_key_versions.version = content_keys.version\nEND\n\n end\n\n # Association caches are out-of-date.\n reload\n\n self\n end", "def render(*args)\n if request.path_parameters['action'] == \"edit\" && params[:revision]\n model.set_to_revision(params[:revision])\n end\n super(*args)\n end", "def add_revision(revision, keys)\n raise NotImplementedError\n end", "def revision_file\n @root.join('REVISION')\n end", "def logical_revision\n @logical_revision || \"rev-\" + self.rev \n end", "def update_with_revision\n store_revision do\n yield\n end\n end", "def acts_as_revision(*args, &block)\n revisable_shared_setup(args, block)\n self.send(:include, Revision) \n end", "def update_with_revision\n store_revision do\n update_without_revision\n end\n end", "def revision_setup #:nodoc:\n now = Time.current\n prev = current_revision.revisions.first\n prev.update_attribute(:revisable_revised_at, now) if prev\n self[:revisable_current_at] = now + 1.second\n self[:revisable_is_current] = false\n self[:revisable_branched_from_id] = current_revision[:revisable_branched_from_id]\n self[:revisable_type] = current_revision[:type] || current_revision.class.name\n end", "def add(contents, log, author=nil, date=nil)\n\t raise AlreadyExist.new(\"already exist: #{@file.inspect}:#{@head_rev}\") if @state != 'dead'\n\t return mkrev(contents, log, author, date, 'Exp')\n\tend", "def create_change(change)\n Change.create(:changeset => self,\n :action => change[:action],\n :path => change[:path],\n :from_path => change[:from_path],\n :from_revision => change[:from_revision])\n end", "def revision_setup #:nodoc:\n now = Time.current\n prev = current_revision.revisions.first\n prev.update(revisable_revised_at: now) if prev\n self[:revisable_current_at] = now + 1.second\n self[:revisable_is_current] = false\n self[:revisable_branched_from_id] = current_revision[:revisable_branched_from_id]\n self[:revisable_type] = current_revision[:type] || current_revision.class.name\n end", "def revision=(v)\r\n @revision = v\r\n end", "def new\n @revision = Revision.new\n @revision.document_id = params[:document_id]\n\n if !@revision.document.allowed_to_save\n redirect_back\n else\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @revision }\n end\n end\n end", "def title\n \"#{self.article_revision.title}\"\n end", "def wf_revision; h.wf_revision; end", "def revision\n # HEAD is the default, but lets just be explicit here.\n get_revision('HEAD')\n end", "def add(text, meta, journal, link, p1=nil, p2=nil)\n text = inject_metadata(text, meta)\n add_revision(text, journal, link, p1, p2)\n end", "def create\n @commit = Commit.new\n\n #walker = Rugged::Walker.new(@repo)\n #\n #walker.sorting(Rugged::SORT_TOPO | Rugged::SORT_REVERSE) # optional\n #\n #walker.push('HEAD')\n #walker.each { |c| \n # @commit = Commit.new(sha: c.oid, description:c.message,\n # author: c.author[:name], commit_date: c.author[:time])\n # @commit.save\n #}\n #walker.reset\n\n respond_to do |format|\n format.html { redirect_to @commit, notice: 'Commit was successfully created.' }\n format.json { render :show, status: :created, location: @commit }\n end\n end", "def mark\n \"(echo #{revision} > #{configuration[:release_path]}/REVISION)\"\n end", "def new_version_additional_behaviour_before_save(old, new, params)\n\t\tnew.title = old.title\n\t\tnew.description = old.description\n\t\tnew.created_at = old.created_at\n\t\tnew.updated_at = Time.now\n\t\tnew.image = old.image\n\t\tnew.popularity = old.popularity\n\n\t\t# fields\n\t\told.fields.each do |f|\n\t\t\tnew.fields.push f.copy_without_references\n\t\tend\n\n\t\t# release dates\n\t\told.release_dates.each do |rd|\n\t\t\tnew.release_dates.push rd.copy_without_references\n\t\tend\n\n\t\t# videos\n\t\told.videos.each do |v|\n\t\t\tnew.videos.push v.copy_without_references\n\t\tend\n\n\t\tscreenshot_versioning old, new, params\n\n\t\t# genres\n\t\told.genres.each do |g|\n\t\t\tnew.genres.push g\n\t\tend\n\n\t\t# platforms\n\t\told.platforms.each do |p|\n\t\t\tnew.platforms.push p\n\t\tend\n\n\t\t# media\n\t\told.media.each do |m|\n\t\t\tnew.media.push m\n\t\tend\n\n\t\t# modes\n\t\told.modes.each do |m|\n\t\t\tnew.modes.push m\n\t\tend\n\n\t\t# tags\n\t\told.tags.each do |t|\n\t\t\tnew.tags.push t\n\t\tend\n\n\tend", "def revision(version)\n if version == :previous || audits.last.version >= version\n revision_with Audited.audit_class.reconstruct_attributes(audits_to(version))\n end\n end", "def title\n revision.title\n end", "def update\n @revision = Revision.find(params[:id])\n\n if @revision.update(params[:revision])\n head :no_content\n else\n render json: @revision.errors, status: :unprocessable_entity\n end\n end", "def get_latest_revision\n raise NotImplementedError\n end", "def revision\n return changeset.rev if @changeset || @change_id\n link_rev\n end", "def create_new_version!\n if self.new?\n raise DataCatalog::Error, \"document must be saved before versioning\"\n end\n unless self.id\n raise DataCatalog::Error, \"expected document to have an id\"\n end\n copy = self.dup\n copy.id = BSON::ObjectID.new.to_s\n copy.next_id = self.id\n copy.save!\n self.previous_id = copy.id\n copy\n end", "def fetch_revision\n context.capture \"cat #{repo_path}/#{release_timestamp}_REVISION\"\n end", "def commit\n return nil unless client\n if @activity.revisions_gistid?\n update\n else\n create\n end\n rescue Octokit::Error => e\n Raven.capture_exception(e)\n nil\n end", "def revision(revision)\n \"`#{p4_cmd} changes -s submitted -m 1 ...#{rev_no(revision)} | cut -f 2 -d\\\\ `\"\n end", "def get_revisions(file_path, client)\n @log.debug \"Getting revisions of \" + file_path\n revs = []\n revisions = client.revisions file_path\n revisions.each do |rev|\n fileRev = FileRev.new\n if rev['is_deleted']\n fileRev.file_loc = rev[\"path\"]\n fileRev.is_deleted = true\n fileRev.timestamp = DateTime.parse(rev['modified'])\n fileRev.rev = rev[\"rev\"]\n @log.debug rev[\"path\"] + ' deleted ' + rev[\"rev\"] + ' ' + rev['modified']\n else \n fileRev.file_loc = rev[\"path\"]\n fileRev.is_deleted = false\n fileRev.timestamp = DateTime.parse(rev['modified'])\n fileRev.rev = rev[\"rev\"]\n @log.debug rev[\"path\"] + ' ' + rev[\"rev\"] + ' ' + rev['modified']\n end\n revs.push(fileRev)\n end\n return revs\nend", "def revision_at(date_or_time)\n audits = self.audits.up_until(date_or_time)\n revision_with Audited.audit_class.reconstruct_attributes(audits) unless audits.empty?\n end", "def revision_at(date_or_time)\n audits = self.audits.up_until(date_or_time)\n revision_with Audited.audit_class.reconstruct_attributes(audits) unless audits.empty?\n end", "def current_revision\n raise NotImplementedError\n end", "def parseRevision()\r\n pieces=@complete_rev.split(\".\")\r\n @revision=pieces.last.to_i\r\n baseSize=1\r\n baseSize+=(pieces.size/2)\r\n @base=pieces[0..-baseSize].join(\".\")\r\n if baseSize > 2\r\n @branchid=pieces[-2]\r\n end \r\n end", "def save_revision(child, revision, dl, new_path)\n modified_date = \"#{revision['modifiedDate'].to_s.gsub(/:/, '_')}\"\n output_file = \"#{new_path}/#{child.title}_\"\\\n \"#{modified_date}_\"\\\n \"#{revision['lastModifyingUserName']}\"\\\n \".#{retrieve_download_url(revision, child.mimeType)[-4, 4]}\"\n\n # Save downloaded file\n # puts \"Creating #{child.title} revision: ID #{revision.id}\"\n IO.binwrite output_file, dl.body\n end", "def update\n old_post = Post.find(params[:id])\n\n if post_params[:upload_file]\n data = post_params.delete(:upload_file)\n file_content = data.read.force_encoding(\"UTF-8\");\n post_params[:content] << file_content\n end\n\n if old_post.content == post_params[:content]\n save_success = old_post.update_attributes(post_params)\n @post = old_post\n else\n @post = old_post.create_version(post_params)\n save_success = @post.save\n unless save_success\n old_post.errors = @post.errors\n @post = old_post\n end\n end\n\n respond_to do |format|\n if save_success\n format.html {\n redirect_to @post, notice: 'New version of snippet was created.'\n }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def store_revision\n if new_record? or @revisions_disabled\n return yield\n else\n retval = nil\n revision = nil\n begin\n RevisionRecord.transaction do\n read_only = self.class.find(self.id, :readonly => true) rescue nil\n if read_only\n revision = read_only.create_revision!\n truncate_revisions!\n end\n \n disable_revisioning do\n retval = yield\n end\n \n raise 'rollback_revision' unless errors.empty?\n end\n rescue => e\n # In case the database doesn't support transactions\n if revision\n revision.destroy rescue nil\n end\n raise e unless e.message == 'rollback_revision'\n end\n return retval\n end\n end", "def revision_at(date_or_time)\n audits = self.audits.up_until(date_or_time)\n revision_with ActsAsAuditable::Audit.reconstruct_attributes(audits) unless audits.empty?\n end", "def revision_params\n params.require(:revision).permit(:rule_text, :body, :change_description, :background, :references)\n end", "def revision_params\n params.require(:revision).permit(:rule_text, :body, :change_description, :background, :references)\n end", "def set_other_revision\n @other_revision = params[:revision] ? find_revision(params[:revision]) : @revisions.first\n end", "def to_i; @revision; end", "def after_initialize\n self.revision_model = (klass.camelize + 'Revision').constantize\n revision = is_preview ? self.last_revision : self.published_revision\n self.attributes = change_attributes_to_revision_attributes(revision) if revision\n end", "def publish(revision, content=nil, &block)\n Spontaneous::Publishing::Revision.patch(self, revision, content, &block)\n end", "def sub_wf_revision; h.sub_wf_revision; end", "def save_revision(config)\n if config.fetch(:real_revision)\n @deployment.revision = config.fetch(:real_revision)\n @deployment.save!\n end\n rescue => e\n logger.important \"Could not save revision: #{e.message}\"\n end", "def revert_to(version_hash)\n tree = self.git.tree(version_hash)\n dir = tree.contents[0] # posts/\n data = dir.contents[0] # 6/\n data.contents.each do |f| # title.txt\n field = f.name.gsub(\".txt\",\"\")\n send(\"#{field.to_sym}=\", f.data)\n end\n save # hm, not sure if I want to do this\n end", "def mark\n \"echo #{revision} > #{configuration[:deploy_release]}/REVISION\"\n end", "def last_revision\n get_revision('REVISION')\n end", "def checkin(contents, log, author=nil, date=nil)\n\t raise NotExist.new(\"not exist: #{@file.inspect}:#{@head_rev}\") if @state == 'dead'\n\t return mkrev(contents, log, author, date, 'Exp')\n\tend", "def send_revision(revision, data)\n retval\n end", "def commit(newrevision, content_io=nil)\n if not get_indexfile_with_revision(newrevision).nil?\n raise \"Committing already-existing revision: #{newrevision} for #{@fname}\"\n end\n if content_io.nil?\n compress_file_lines = Deflate.deflate(File.read(@fname))\n else\n cont = content_io.read\n compress_file_lines = Deflate.deflate(cont)\n end\n\n # append current file fname to datafile\n length = IO.readlines(@datafile).size\n\n File.open(@datafile, \"a\") do |append|\n append.puts compress_file_lines\n end\n length = IO.readlines(@datafile).size - length\n\n # new version is the old version plus 1\n # new offset is the last length + last offset\n parse_last_line = parse_indexfile_line get_indexfile_with_line(-1)\n new_offset = parse_last_line[1] + parse_last_line[2]\n\n File.open(@indexfile, \"a\") do |f|\n index_write_row(f, newrevision.to_s,\n new_offset.to_s, length.to_s)\n end\n end" ]
[ "0.70113164", "0.6950661", "0.66123986", "0.6515512", "0.6488422", "0.64601314", "0.62441635", "0.6213863", "0.6176663", "0.61356765", "0.6105925", "0.6102364", "0.6084698", "0.6066202", "0.6046146", "0.604109", "0.60341835", "0.6008621", "0.6001054", "0.6000184", "0.59718364", "0.59646344", "0.59517604", "0.5912732", "0.59064245", "0.59062797", "0.58945054", "0.5884038", "0.58556706", "0.57572347", "0.57315636", "0.5727965", "0.5725114", "0.57222", "0.5687857", "0.5683074", "0.56623244", "0.56583726", "0.565059", "0.5650226", "0.56483936", "0.5618461", "0.5616885", "0.5610803", "0.5600746", "0.5599727", "0.55944955", "0.558422", "0.5582482", "0.55782145", "0.5575986", "0.55716413", "0.5564819", "0.55633456", "0.55623764", "0.5538085", "0.5531641", "0.55242854", "0.55205876", "0.5519938", "0.5511473", "0.5490854", "0.5485493", "0.54539144", "0.5452369", "0.5452164", "0.5443045", "0.54372364", "0.54354924", "0.54336596", "0.54259235", "0.5416223", "0.54117423", "0.54107785", "0.54042035", "0.54027903", "0.5402088", "0.5397364", "0.538787", "0.538787", "0.5376522", "0.53712636", "0.53693277", "0.53685063", "0.5367671", "0.53621894", "0.53556687", "0.53556687", "0.535093", "0.5341751", "0.5340268", "0.533988", "0.5332664", "0.5331245", "0.53276426", "0.5325449", "0.5324512", "0.5321534", "0.5319978", "0.53177845" ]
0.7457926
0
Generate the hash of diffs to populate a Revision
def generate_diff_hash(base_content, revised_content) revised_content.compact.collect {|content_key, revised_value| current_value = base_content.send(content_key) || '' # Ignore unchanged contents or nil (not blank!) content attributes unless current_value == revised_value [content_key, persistable_diff(current_value, revised_value || '').to_json] end }.compact.to_h end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def hash\n h = {}\n h['_rm'] = removed_keys unless removed_keys.empty?\n h['_ch'] = Hash[changes.collect {|k,v| [k, v.is_a?(Diff) ? v.hash : v]}] unless\n changes.empty?\n h\n end", "def hash\n name.hash ^ version.hash\n end", "def create\n revisions do |orig_file, sha_list|\n sha_list.each_with_index do |sha, i|\n ver = (i + 1).to_s\n # Git revisioned file\n composeversions(orig_file, sha, ver) do |content, data, file_path|\n # dont re-write files\n if File.exist?(file_path)\n linecount(file_path)\n next\n end\n\n version_content = FrontMatter.new(data)\n version_content.content = content \n write(file_path, version_content.update)\n linecount(file_path)\n end\n end\n\n sha_list.map!.with_index { |sha, i| [] << sha << (i + 1) }\n # Git Diff combination files\n composediffs(orig_file, line_count, sha_list.combination(2)) do |content, data, file_path|\n content.sub!(DIFF_HEADER_REGEXP, '')\n if change?(content)\n VersionedFiles.frontmatter[\"no_change\"] = false\n styled_content = @style.style(content)\n data.merge!(@style.stats.final)\n else\n VersionedFiles.frontmatter[\"no_change\"] = \"no_change\"\n data[\"no_change\"] = true\n end\n\n fm = FrontMatter.new(data).create\n diff_file = fm << styled_content\n write(file_path, diff_file)\n end\n end\n end", "def hash\n [author_email, author_name, author_time, branch, commit_time, committer_email, committer_name, default_branch, message, repository_url, sha, tag].hash\n end", "def hash\n return @revision.hash if @revision\n return object_id\n end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def generate_diff\n jsons = version_jsons.map { |j| pretty_json(j) }\n differ = Differ.send(diff_method, *jsons).format_as(:html)\n differ.gsub!('<ins', \"\\n<ins\") if diff_method == :diff_by_line\n @diff = sanitize(differ).html_safe\n end", "def hash\n Digest::SHA256.hexdigest( \"#{nonce}#{time}#{difficulty}#{prev}#{data}\" )\n end", "def calculate_hash!\n prefix = PREFIX_NAME_LOOKUP[self.type]\n # add special cases for refs\n self.hash_id = NodeId.sha1(\"#{prefix} #{self.size}\\0#{self.content}\")\n end", "def checksum!\n # Get a deep copy of hash to compare with\n @_original_hash = Marshal.load(Marshal.dump(to_hash))\n # create a copy of basic elements\n base = self.reject { |k,_| ['_id', '_rev', 'couchrest-hash'].include? k.to_s }\n\n result = nil\n\n flatten =\n lambda {|r|\n (recurse = lambda {|v|\n if v.is_a?(Hash) || v.is_a?(CouchRest::Document)\n v.to_a.map{|v| recurse.call(v)}.flatten\n elsif v.is_a?(Array)\n v.flatten.map{|v| recurse.call(v)}\n else\n v.to_s\n end\n }).call(r)\n }\n self['couchrest-hash'] = Digest::MD5.hexdigest(flatten.call(base).sort.join(''))\n end", "def diff_hash\n {\n diff: diff_hunk,\n new_path: file_path,\n old_path: file_path,\n\n # These fields are not displayed for LegacyDiffNote notes, so it\n # doesn't really matter what we set them to.\n a_mode: '100644',\n b_mode: '100644',\n new_file: false\n }\n end", "def hash\n source.hash ^ target.hash\n end", "def get_checksums(commit)\n # Reset @currenthash\n @currenthash = Hash.new\n path = find_relative_git_cookbook_path\n #puts \"path is '#{path}' commit hash is #{commit}\"\n #puts \"commit.tree is #{commit.tree}\"\n unless path == '.'\n tree = commit.tree / path\n git_checksum_hash(tree)\n else\n git_checksum_hash(commit.tree)\n end\n end", "def block_hash\n\t\tdigest = Digest::SHA2.new\n\n\t\tdigest << '%d' % [ self.index ]\n\t\tdigest << self.timestamp.strftime( '%s%N' )\n\t\tdigest << self.payload\n\t\tdigest << self.payload_hash\n\t\tdigest << self.proof.to_s\n\t\tdigest << self.previous_hash\n\t\t\n\t\treturn digest.hexdigest\n\tend", "def createDiffResult(working_dir, channel_cfg, vimapp, isReleaseOperator,backupRoot)\n\n remotedir = readChannelDir(channel_cfg, vimapp) + \"/\"+ File.basename(working_dir)\n puts remotedir.green\n if File.directory?(remotedir) == false\n FileUtils.mkdir_p remotedir\n end\n\n reportFile1 = \"#{remotedir}/report\"\n reportFile2 = \"#{remotedir}/rdetail\"\n lines = File.open(reportFile1, \"r:UTF-8\").each_line.to_a\n\n hashes = Array.new\n lines.each do |line|\n if line.start_with? \"hash=\"\n hashes.push line.gsub(\"hash=\",\"\").strip.chomp\n end\n end\n\n g = gitOpen(working_dir)\n \n logs = getGitLog(g)\n local_branches = getGitBranches(g)[:local]\n diff = compareHashes g, logs, hashes\n \n def getDiffDetails(diffinfo)\n puts \"diffdetails\"\n data = Array.new \n\n diffinfo[:files].each do |file|\n print \"[\"\n print file[0].cyan\n print \"] \"\n print \"[+] #{file[1][:insertions]}\".green\n print \" \"\n print \"[-] #{file[1][:deletions]}\".red\n puts\n # file, insertions, deletions\n data.push \"file=#{file[0]},#{file[1][:insertions]},#{file[1][:deletions]}\"\n end\n\n return data \n end\n\n diff_details = getDiffDetails diff[1]\n \n puts \"\\n\\n|||||||||||||||||||||||||WRITE|||||||||||||||||||||||||||||||||\\n\\n\"\n\n puts \"hash=\"+diff[2]\n puts \"hash=\"+diff[3]\n diff_details.each do |d| \n puts d\n end\n\n diffReportDir = \"#{working_dir}/.diffreport\"\n FileUtils.mkdir_p diffReportDir \n\n #write diff detail to file \n r_detail = \"#{diffReportDir}/detail\"\n\n puts \">> 222\"\n f = File.open(r_detail, \"w:UTF-8\")\n diff[0].each do |l|\n f.puts l\n end\n f.close\n\n f = File.open(r_detail+\".color\", \"w:UTF-8\")\n diff[0].each do |l|\n if isPlus(l)\n f.puts l.green\n elsif isMinus(l)\n f.puts l.red\n else\n f.puts l\n end\n end\n f.close\n\n puts \">> 111\"\n #write diff to file\n diffReport = \"#{diffReportDir}/report\"\n f = File.open(diffReport, \"w:UTF-8\")\n f.puts \"hash=\"+diff[2]\n f.puts \"hash=\"+diff[3]\n diff_details.each do |d| \n f.puts d\n end\n f.close\n puts \"\\n\\nWRITTEN\\n\\n\".green\n\n if isReleaseOperator == false\n FileUtils.cp \"#{diffReport}\", \"#{reportFile1}\"\n FileUtils.cp \"#{r_detail}\", \"#{reportFile2}\"\n else\n metaOK = FileUtils.identical?(diffReport, reportFile1)\n detailOK = FileUtils.identical?(r_detail, reportFile2)\n \n puts \n print \"[ OVERVIEWS ] \" #metaOK.to_s.red\n puts metaOK ? \"IDENTICAL\".green : \"DIFFERENT\".red\n print \"[CODE DETAILS] \"\n puts detailOK ? \"IDENTICAL\".green : \"DIFFERENT\".red\n puts\n def compare(file1, file2)\n puts \">> compare\"\n lines1 = File.open(file1, \"r:UTF-8\").each_line.to_a\n lines2 = File.open(file2, \"r:UTF-8\").each_line.to_a\n def showInclusion(lines1, lines2, i)\n lines1.each do |line|\n if lines2.include?(line) == false\n if i == true\n puts \"[YOURS] \"+ line.chomp.cyan\n else\n puts \"[REMOTE] \"+ line.chomp.yellow\n end\n end\n end\n end\n showInclusion(lines1, lines2, true)\n showInclusion(lines2, lines1, false)\n end\n compare diffReport, reportFile1\n compare r_detail, reportFile2\n end\n\n files = Array.new\n diff_details.each do |d| \n if d.start_with? \"file=\"\n files.push d.gsub(\"file=\",\"\").strip.chomp\n end\n end\n if hashes.size > 0\n #compareBackupsWithOldVersion(g, working_dir, backupRoot, files, hash) \n #compareBackupsWithOldVersion(g, working_dir,backupRoot,files, hash[1]) \n end\n end", "def git_commit\n init_structure\n sha = add_all_changes_to_git\n \n if self.attributes.has_key?(\"version\") \n self.version = sha\n self.connection.update(\"UPDATE #{self.class.table_name} SET version='#{sha}' WHERE id='#{self.id}'\")\n end\n \n return sha\n end", "def diff\n @diff ||= begin\n commit.diffs.collect{|diff| diff.diff}.join(\"\\n\")\n end\n end", "def create_hash\n require 'digest/md5'\n digest_string = [self.id, self.url, self.referrer, self.created_at].join(\"\")\n self.record_hash = Digest::MD5.hexdigest(digest_string)\n end", "def hash\n @orig.hash\n end", "def hash\n @orig.hash\n end", "def hash\n @orig.hash\n end", "def diff_init(diff, path)\n Smash.new.tap do |di|\n if diff.size > 1\n updated = diff.find_all { |x| x.first == \"+\" }\n original = diff.find_all { |x| x.first == \"-\" }\n di[:original] = Array(original).map(&:last).join(\", \")\n di[:updated] = Array(updated).map(&:last).join(\", \")\n else\n diff_data = diff.first\n di[:path] = path\n if diff_data.size == 3\n di[diff_data.first == \"+\" ? :updated : :original] = diff_data.last\n else\n di[:original] = diff_data[diff_data.size - 2].to_s\n di[:updated] = diff_data.last.to_s\n end\n end\n end\n end", "def diff_files\n hsh = {}\n @base.git.diff_files.split(\"\\n\").each do |line|\n (info, file) = line.split(\"\\t\")\n (mode_src, mode_dest, sha_src, sha_dest, type) = info.split\n hsh[file] = {:path => file, :mode_file => mode_src.to_s[1, 7], :mode_index => mode_dest,\n :sha_file => sha_src, :sha_index => sha_dest, :type => type}\n end\n hsh\n end", "def hash() source.hash ^ (target.hash+1); end", "def hash() source.hash ^ (target.hash+1); end", "def make_commit_log\n\t\t\tdiff = read_command_output( 'hg', 'diff' )\n\t\t\tfail \"No differences.\" if diff.empty?\n\n\t\t\treturn diff\n\t\tend", "def reload_diffs\n new_attributes = {}\n new_diffs = []\n\n if commits.size.zero?\n new_attributes[:state] = :empty\n else\n diff_collection = unmerged_diffs\n\n if diff_collection.overflow?\n # Set our state to 'overflow' to make the #empty? and #collected?\n # methods (generated by StateMachine) return false.\n new_attributes[:state] = :overflow\n end\n\n new_attributes[:real_size] = diff_collection.real_size\n\n if diff_collection.any?\n new_diffs = dump_diffs(diff_collection)\n new_attributes[:state] = :collected\n end\n end\n\n new_attributes[:st_diffs] = new_diffs\n\n new_attributes[:start_commit_sha] = self.target_branch_sha\n new_attributes[:head_commit_sha] = self.source_branch_sha\n new_attributes[:base_commit_sha] = branch_base_sha\n\n update_columns_serialized(new_attributes)\n\n keep_around_commits\n end", "def diff_files\n hsh = {}\n @base.git.diff_files.split(\"\\n\").each do |line|\n (info, file) = line.split(\"\\t\")\n (mode_src, mode_dest, sha_src, sha_dest, status) = info.split\n hsh[file] = {:path => file, :mode_repo => mode_src.to_s[1, 7], :mode_index => mode_dest,\n :sha_repo => sha_src, :sha_index => sha_dest, :status => status}\n end\n hsh\n end", "def version\n res = {}\n res[:branch] = @branch\n res[:history] = @history\n res[:releases] = @releases\n res[:diffs] = @diffs.keys\n res\n end", "def diffs \n @diffs ||= begin\n diff = `svn diff`.split(\"\\n\").map {|l| l.chomp}\n _diffs = {}\n in_diff = false\n in_path = false\n path = nil\n diff.each do |line|\n if /Index:/ =~ line \n path = /Index: (.*)/.match(line)[1]\n _diffs[path] = ' '\n in_path = true\n in_diff = false\n next\n end\n\n if in_path and !in_diff and /^@@/ =~ line\n in_diff = true\n next\n end\n\n if in_diff and in_path\n if /^\\+/ =~ line\n _diffs[path] += '+'\n elsif /^-/ =~ line\n _diffs[path] = _diffs[path] + '-'\n end\n end\n end\n _diffs.map do |k, v| \n _diffs[k] = v.split('').map do |chr| \n { '+' => \"#{COLOR_GREEN}+\", \n '-' => \"#{COLOR_RED}-\"}[chr]\n end.join() + \"#{COLOR_NONE}\"\n end\n _diffs\n end\n end", "def hash\n raise NotImplementedError.new(\"hash() must be implemented by subclasses of AbstractVersionedFile.\")\n end", "def initialize(diff)\n @diff = diff\n @curr_changed_file = nil\n @prev_changed_file = nil\n @changed_lines = []\n @files_and_lines = {}\n build\n end", "def hash() source.hash ^ target.hash; end", "def hash\n return Digest::MD5.hexdigest(self.describe(' '))\n end", "def historic_diff\n # get the two versions to diff\n @new_measure = Measure.by_user(current_user).where({:_id => params[:new_id]}).first\n unless @new_measure\n @new_measure = ArchivedMeasure.where({:measure_db_id => params[:new_id]}).first.to_measure\n end\n\n @old_measure = Measure.by_user(current_user).where({:_id => params[:old_id]}).first\n unless @old_measure\n @old_measure = ArchivedMeasure.where({:measure_db_id => params[:old_id]}).first.to_measure\n end\n\n results = {}\n results['diff'] = []\n results['pre_upload'] = { \n 'cms_id' => @old_measure.cms_id,\n 'updateTime' => (@old_measure.updated_at.tv_sec * 1000),\n 'hqmf_id' => @old_measure.hqmf_id,\n 'hqmf_version_number' => @old_measure.hqmf_version_number }\n results['post_upload'] = { \n 'cms_id' => @new_measure.cms_id,\n 'updateTime' => (@new_measure.updated_at.tv_sec * 1000),\n 'hqmf_id' => @new_measure.hqmf_id,\n 'hqmf_version_number' => @new_measure.hqmf_version_number }\n\n measure_logic_names = HQMF::Measure::LogicExtractor::POPULATION_MAP.clone\n measure_logic_names['VARIABLES'] = 'Variables'\n\n # Walk through the population sets and populations for the measure and create a\n # diffy for each populationm.\n @new_measure.populations.each_with_index do |new_population_set, population_set_index|\n old_population_set = @old_measure.populations[population_set_index]\n population_diff = []\n\n # For each population within the population set, get the population logic and\n # perform the diffy\n measure_logic_names.each_pair do |population_code, population_title|\n # if the code is for VARIABLE, leave it. If it's IPP, etc., then access the actual code name from the\n # population set (e.g. IPP_1).\n code = (population_code == 'VARIABLES') ? 'VARIABLES' : new_population_set[population_code]\n new_logic = @new_measure.measure_logic.find { |logic| logic['code'] == code }\n old_logic = @old_measure.measure_logic.find { |logic| logic['code'] == code }\n\n # skip if both are non existent\n next if !new_logic && !old_logic\n \n # Remove the first line of the measure logic, which is the the name of the population.\n old_logic_text = old_logic ? old_logic['lines'][1..-1].join() : \"\"\n new_logic_text = new_logic ? new_logic['lines'][1..-1].join() : \"\"\n\n logic_diff = Diffy::SplitDiff.new(old_logic_text, new_logic_text,\n format: :html, include_plus_and_minus_in_html: true, allow_empty_diff: false)\n\n population_diff << {code: population_code, title: population_title, pre_upload: logic_diff.left, post_upload: logic_diff.right}\n end\n\n results['diff'] << population_diff\n end\n\n render :json => results\n end", "def rehash() end", "def rev_properties\n {\n 'svn_updated_at' => @changeset.date,\n 'svn_updated_by' => @changeset.author,\n 'svn_updated_rev' => @changeset.revision\n }\n end", "def get_hash(machines)\n branch = get_branch_id\n hash = Digest::SHA1.hexdigest(machines.sort.join)\n \"#{branch}__#{hash}\"\n end", "def fetch_commit_hash_list()\n `git rev-list --all --reverse`.strip.split(/\\n/)\nend", "def hash\n [id, name, change_number, date_created, date_modified, date_uploaded, content_uri, workspace, created_by, uploaded_by, content_type, content_length, system_type, filename, page_count, read, caller_address, receiver_address, tags, tag_values, attributes, thumbnails, upload_status, upload_destination_uri, upload_method, lock_info, acl, sharing_status, sharing_uri, download_sharing_uri, self_uri].hash\n end", "def digest\n @digest ||= Digest::SHA1.new.update(version.to_s)\n @digest.dup\n end", "def version_history\n res = []\n event = 'create'\n author = user\n versions.each do |version|\n # some old entries still include create actions\n # TODO remove next line\n next if version.event == 'create'\n res << {\n obj: version.reify,\n event: event,\n author: author\n }\n event = version.event\n author = User.find_by_id(version.whodunnit.to_i)\n end\n res << {\n obj: self,\n event: event,\n author: author\n }\n end", "def patch(diffs)\n @hash = nil # invalidate any cached image\n\n Dir.chdir(root) do\n diffs.each do |diff|\n flag, key, v1, _ = diff\n # if key =~ /\\[/\n # keyname = key.match(/^(.*)\\[\\]$/).captures\n # elsif key =~ /\\./\n # keyname, subkey = key.match(/^(.*)\\.(.*)$/).captures\n # else\n # keyname = key\n # end\n\n dirname, filename, fieldname = Treet::Repo.filefor(key)\n filepath = \"#{dirname}/#{filename}\"\n\n case flag\n when '~'\n # change a value in place\n # load the current data & overwrite with the new value\n # idempotent: this will overwrite the file with the same contents\n if fieldname\n # hash entry\n data = File.exists?(filepath) ? JSON.load(File.open(filepath)) : {}\n data[fieldname] = v1\n File.open(filepath, \"w\") {|f| f << JSON.pretty_generate(data)}\n else\n # string entry\n File.open(filepath, \"w\") {|f| f << v1}\n end\n\n when '+'\n # add something\n if fieldname\n # writing a value into a hash\n # idempotent: this will overwrite the file with the same contents\n data = File.exists?(filepath) ? JSON.load(File.open(filepath)) : {}\n data[fieldname] = v1\n Dir.mkdir(dirname) unless Dir.exists?(dirname)\n File.open(filepath, \"w\") {|f| f << JSON.pretty_generate(data)}\n else\n # writing an entire hash into an array entry\n # idempotent: this will overwrite the file with the same contents\n subfile = \"#{dirname}/#{Treet::Hash.digestify(v1)}\"\n Dir.mkdir(dirname) unless Dir.exists?(dirname)\n case v1\n when Hash\n # hash entry\n File.open(subfile, \"w\") {|f| f << JSON.pretty_generate(v1)}\n else\n # string entry - create empty file with this name\n FileUtils.touch(subfile)\n end\n end\n\n when '-'\n # remove something\n if fieldname\n # this is a key in a subhash\n if File.exists?(filepath)\n # if the subhash is missing, there's nothing to remove, so do nothing (for idempotence)\n data = JSON.load(File.open(filepath))\n data.delete(fieldname)\n if data.empty?\n # all keys have been removed, clean up the file\n File.delete(filename)\n else\n File.open(filepath, \"w\") {|f| f << JSON.pretty_generate(data)}\n end\n end\n elsif dirname == \".\"\n # this is a top-level string\n File.delete(filename) if File.exists?(filename) # need the existence check for idempotence\n else\n # this is an array, we look for a match on the entire contents via digest\n subfile = \"#{dirname}/#{Treet::Hash.digestify(v1)}\"\n File.delete(subfile) if File.exists?(subfile) # need the existence check for idempotence\n # TODO: if dirname is now empty, should it be removed? is that worthwhile?\n end\n end\n end\n end\n\n to_hash # ?? return the patched data? or no return value? true/false for success?\n end", "def hash\n @vbits.hash\n end", "def merchanthash\n if version.to_i == 1 \n return HashGenerator::generate(merchant_hash_key, merchant_id, order_id);\n else\n return Digest::SHA512.hexdigest(\"#{merchant_hash_key},#{merchant_id},01,#{order_id},#{gross_amount}\")\n end\n end", "def file_revisions(file)\n file = file.gsub(%r{^/}, '')\n output = sh_string(\"git log --format='%h|%s|%aN|%ai' -n100 #{ShellTools.escape(file)}\")\n output.to_s.split(\"\\n\").map do |log_result|\n commit, subject, author, date = log_result.split('|')\n date = Time.parse(date.sub(' ', 'T')).utc.iso8601\n { commit: commit, subject: subject, author: author, date: date }\n end\n end", "def git_checksum_hash(tree, prefix=nil)\n\n tree.contents.each do |obj|\n if obj.class == Grit::Blob\n item = [prefix, obj.name].join\n @currenthash[item] = Digest::MD5.hexdigest(obj.data)\n #puts \"#{item} : \" + @currenthash[item]\n else\n git_checksum_hash(obj, [prefix, obj.name, \"/\"].join)\n end\n end\n\n return @currenthash\n end", "def hash(*) end", "def create_version_hash\n new_version = {}\n new_version['created'] = ''\n new_version['message'] = ''\n new_version['user'] = {}\n # user is #name, # address.\n new_version['user']['name'] = ''\n new_version['user']['address'] = ''\n new_version['state'] = {}\n new_version\n end", "def hash\n raw = [name, type, values.join('/')].join(' ')\n Digest::MD5.hexdigest(raw)\n end", "def revision_id\n Digest::SHA1.new.hexdigest(canonical_revision_string)\n end", "def sha\n @commit.sha\n end", "def digest\n digest = ''\n @entries.each { |entry| digest << entry.digest << ' ' }\n digest\n end", "def hash\n [_hash, name, owner].hash\n end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash()\n #This is a stub, used for indexing\n end", "def hash\n return (path + file_id.to_s).hash\n end", "def commit_diff(project, sha)\n get(\"/projects/#{project}/repository/commits/#{sha}/diff\") \n end", "def hash\n [ref, from, to, chg, line, loc, min, sale, plsp, incl, pror, proadj, tran, serv, dbt, adj, adjm, disc, opt, prop, bill, cust, lfln, date, qty, glref].hash\n end", "def diff_to_compare; end", "def make_diffs\n # get array of all works belonging to project except self\n neighbors = []\n self.project.works.all.each do |work|\n neighbors.push(work.id)\n end\n # remove current work.id so have the *other* neighbors\n neighbors.delete(self.id)\n neighbors.each do |neighbor| # neighbor => work id\n generate_diff(neighbor, self.id)\n end\n end", "def hash\n end", "def hash\n end", "def hash\n end", "def hash\n Zlib.crc32(to_a.map(&:to_s).sort.to_s)\n end", "def hash\n [anchor, cv, nullifier, proof, rk, spend_auth_sig].hash\n end", "def hash\n [created, changed_by, updated, id, domain, action, organization_id, webhook_id, entity_id, destination_url, format, ack_enabled, entity, changes, last_send_attempt, next_send_attempt, final_send_attempt, total_send_attempts, state, acked].hash\n end", "def hash\n digest = Digest::MD5.new\n digest << title.to_s\n digest << content.join('').to_s\n digest.to_s\n end", "def revision\n if @new_resource.revision == 'HEAD'\n ['-A']\n else\n ['-r', @new_resource.revision]\n end\n end", "def hash\n @offset.hash ^ @previous_offset.hash ^ @timestamp.hash\n end", "def to_h\n h = {\n :rev => rev,\n :log => message,\n :author => author,\n :timestamp => timestamp,\n :has_children? => has_children?,\n }\n h[:changed_paths] = changed_paths if changed_paths\n h\n end", "def hash\n @hash || calculate_hash!\n end", "def update_commitlist(h)\n h.map do |entry|\n sha = entry[\"commit\"].to_s.strip\n n = entry[\"note\"]\n # First, try to look it up in our existing repo\n if commit_exists?(sha) || sha.empty?\n entry # do nothing, put it back in the hash\n else\n # Ok, we know it doesn't exist. Now look it up in gitlog.json\n if @gitlog_json.key? sha\n m = @gitlog_json[sha][\"message\"]\n svn_id = m.lines.select {|l| l.match? /git-svn-id/ }.join.strip\n grep_cmd = <<~EOS.strip\n git -C ./tmp/src rev-list --all --grep=\"#{svn_id}\" --\n EOS\n stdout, stderr, status = Open3.capture3(grep_cmd)\n if stderr.empty?\n {\n \"commit\" => stdout.strip,\n \"note\" => <<~EOS.strip\n #{entry[\"note\"].to_s.lines.join(\"\\n\")}\n\n Formerly #{sha} before HTTPD rewrote Git history.\n EOS\n }\n else\n warn \"ERROR getting commit #{sha}. #{stderr}\"\n entry\n end\n else\n warn \"ERROR commit #{sha} does not exist in gitlog.json\"\n entry\n end\n end\n end\nend", "def versions\n return @_versions ||= Regulate::Git::Interface.commits(id)\n end", "def version_guid\n \"#{digest_type}:#{checksum}\"\n end", "def hash\n h = @e.nil? ? 0 : @e\n h = (h << 1) ^ @r.hash\n h = (h << 1) ^ @v.hash\n end", "def hash\n str = [major, minor, patch].map do |str|\n str ? str : \"0\"\n end.join(\".\")\n\n if pre\n str = \"#{str}.#{pre}\"\n end\n\n str.hash\n end", "def sha\n id.sha\n end", "def hash\n self.begin.hash ^ self.end.hash\n end", "def committed_files sha\n array_output_of \"git diff-tree --no-commit-id --name-only -r #{sha}\"\nend", "def config_hash\n digest = Digest::MD5.hexdigest(\n \"#{@x}-#{@y}-#{@hires_factor}-#{@render_type}-#{@format}-#{CONVERTER_VERSION}\")\n digest\n end", "def dev_pod_hashes_map\n @dev_pod_hashes_map ||=\n dev_pod_sources.map { |name, attribs| [name, FolderChecksum.git_checksum(attribs[:path])] }.to_h\n end", "def consistent_hash\n Zlib.crc32(self.to_yaml, 0)\n end", "def hash\n return name.hash ^ direction.hash ^ lhs.hash ^ rhs.hash\n end", "def hash\n self.class.hash ^ left.hash ^ right.hash\n end" ]
[ "0.6152752", "0.6136501", "0.61138356", "0.6078793", "0.60560924", "0.6039968", "0.6039968", "0.6039968", "0.6039968", "0.6039968", "0.6039968", "0.6039968", "0.6019143", "0.59232783", "0.5911321", "0.59080535", "0.5866775", "0.5850416", "0.5840386", "0.5827198", "0.5820805", "0.5819811", "0.5817834", "0.57873076", "0.57867086", "0.57867086", "0.57867086", "0.5785237", "0.57666767", "0.56954134", "0.56954134", "0.5675229", "0.5662478", "0.5639505", "0.5638068", "0.5621705", "0.56153774", "0.56108934", "0.5603481", "0.55996895", "0.55842555", "0.55701673", "0.55589217", "0.55545235", "0.5546267", "0.55449885", "0.55445254", "0.55421257", "0.55331045", "0.55293477", "0.5512035", "0.5482968", "0.54720587", "0.5461218", "0.5455067", "0.5454475", "0.5452747", "0.54499674", "0.54378915", "0.54316604", "0.5422302", "0.5422302", "0.5422302", "0.5422302", "0.5422302", "0.5422302", "0.5422302", "0.5422302", "0.5422302", "0.5422302", "0.5422159", "0.54183066", "0.54181725", "0.538912", "0.53880936", "0.5383445", "0.53774726", "0.53774726", "0.53774726", "0.5364477", "0.53627735", "0.53585935", "0.535446", "0.53401", "0.5330249", "0.5325402", "0.53151613", "0.53097653", "0.53002864", "0.5296971", "0.52912873", "0.52912253", "0.5275573", "0.52726835", "0.5258482", "0.5257417", "0.52549493", "0.5248126", "0.52437", "0.52361745" ]
0.6122528
2
This is a bit gross, but I didn't want to monkeypatch Diff::LCS::Change
def reify_diff_element(element) case element when Array element.collect do |el| reify_diff_element el end when Diff::LCS::Change element.to_a else element end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def changed\n _find_changed_twins!(@_changes)\n\n @_changes\n end", "def added_change what, from_start, from_end, to_start, to_end = nil\n make_fdiff_change format(added_msg_fmt, what), from_start, from_end, to_start, to_end || loctext(to_start, what)\n end", "def source_change(change, filename)\n end", "def changes(_start_ref, _end_ref)\n fail 'Not implemented'\n end", "def diff1; end", "def diff2; end", "def test_13476841\n setup_changeset_test(13476841)\n assert_equal(1, find_changes('el_type' => 'W', 'el_id' => '172609358').size)\n assert(!find_changes('el_type' => 'W', 'el_id' => '172609358')[0]['prev_tags'].nil?)\n end", "def find_changes(lines)\n # look for a `changes` marker\n if idx = lines.index{ |line| /^changes\\:?\\s*$/i =~ line }\n return idx\n end\n\n # look for an enumerated list in reverse order\n if idx = lines.reverse.index{ |line| /^1\\.\\ / =~ line }\n idx = lines.size - idx - 1\n return idx \n end\n\n # look for first outline bullet\n if idx = lines.index{ |line| /^\\*\\ / =~ line }\n return idx\n end\n\n return nil\n end", "def diff_to_compare; end", "def modified?; end", "def change_checker\n `svnlook changed #{@repo} -r #{@revision}`.split(\"\\n\")\n end", "def extract_changes(str)\n str.lines.map do |line|\n new_git_change(*Regexp.last_match.captures) if line.match(/\\t(.*:)?(.*)/)\n end.compact # in case there were any non matching lines left\n end", "def patch!(patchset)\n Diff::LCS.patch!(self, patchset)\n end", "def describe_single_change(change)\n split_path = change.path.split(/\\//)\n if change.prev_sccsid.blank?\n text \"Initial Drop\"\n else\n a(change.prev_sccsid, href: src_files_path(change.release,\n split_path,\n change.prev_sccsid))\n text ' '\n a(\"->\", href: diffs_path(change.release,\n split_path,\n change.sccsid,\n change.prev_sccsid))\n end\n text ' '\n a(change.sccsid, href: src_files_path(change.release,\n split_path,\n change.sccsid))\n text ' '\n text change.type\n text ' '\n text change.path\n end", "def patch_version; end", "def changes map_old, map_new\n\nend", "def git_changed_line\n `git diff | grep ' #{name} (' | grep '+ '`\n end", "def each_change\n old_ln = old_ln_cache = 0\n new_ln = new_ln_cache = 0\n\n @changes.each_with_index do |line, i|\n if line =~ /@ -(\\d+),\\d+ \\+(\\d+),\\d+/\n old_ln_cache = $1.to_i\n new_ln_cache = $2.to_i\n end\n\n type = LINE_TYPES[line[0]]\n case type\n when :add\n old_ln = ''\n new_ln = new_ln_cache\n new_ln_cache += 1\n when :del\n old_ln = old_ln_cache\n old_ln_cache += 1\n new_ln = ''\n when :info\n old_ln = new_ln = '...'\n else\n new_ln = new_ln_cache\n old_ln = old_ln_cache\n old_ln_cache += 1\n new_ln_cache += 1\n end\n\n yield(line, type, @index + i, old_ln, new_ln)\n end\n end", "def test_7082\n setup_changeset_test(7082)\n p find_changes('el_type' => 'W', 'el_id' => '16105282')[0]\n p find_changes('el_type' => 'W', 'el_id' => '16105282')[1]\n assert_equal(1, find_changes('el_type' => 'W', 'el_id' => '16105282').size)\n end", "def changed?\n true\n end", "def patch(patchset)\n Diff::LCS.patch(self, patchset)\n end", "def list_defect_changes(enum)\n change = enum.peek\n defect = change.defect\n loop do\n break if change.defect != defect\n li do\n describe_changes_within_release(enum)\n end\n begin\n change = enum.peek\n rescue StopIteration\n break\n end\n end\n end", "def changes\n @changes ||= Set.new\n end", "def changes\n @changes ||= Set.new\n end", "def diff=(o); end", "def make_my_diffs_pretty!; end", "def changes\n additions + deletions\n end", "def changes\n Change.all.sort! { |a, b| b.value <=> a.value }\n end", "def intuit_diff_direction(src, patchset, limit = nil)\n string = src.kind_of?(String)\n count = left_match = left_miss = right_match = right_miss = 0\n\n patchset.each do |change|\n count += 1\n\n case change\n when Diff::LCS::ContextChange\n le = string ? src[change.old_position, 1] : src[change.old_position]\n re = string ? src[change.new_position, 1] : src[change.new_position]\n\n case change.action\n when '-' # Remove details from the old string\n if le == change.old_element\n left_match += 1\n else\n left_miss += 1\n end\n when '+'\n if re == change.new_element\n right_match += 1\n else\n right_miss += 1\n end\n when '='\n left_miss += 1 if le != change.old_element\n right_miss += 1 if re != change.new_element\n when '!'\n if le == change.old_element\n left_match += 1\n else\n if re == change.new_element\n right_match += 1\n else\n left_miss += 1\n right_miss += 1\n end\n end\n end\n when Diff::LCS::Change\n # With a simplistic change, we can't tell the difference between\n # the left and right on '!' actions, so we ignore those. On '='\n # actions, if there's a miss, we miss both left and right.\n element = string ? src[change.position, 1] : src[change.position]\n\n case change.action\n when '-'\n if element == change.element\n left_match += 1\n else\n left_miss += 1\n end\n when '+'\n if element == change.element\n right_match += 1\n else\n right_miss += 1\n end\n when '='\n if element != change.element\n left_miss += 1\n right_miss += 1\n end\n end\n end\n\n break if (not limit.nil?) && (count > limit)\n end\n\n no_left = (left_match == 0) && (left_miss > 0)\n no_right = (right_match == 0) && (right_miss > 0)\n\n case [no_left, no_right]\n when [false, true]\n :patch\n when [true, false]\n :unpatch\n else\n case left_match <=> right_match\n when 1\n :patch\n when -1\n :unpatch\n else\n raise \"The provided patchset does not appear to apply to the provided value as either source or destination value.\"\n end\n end\n end", "def change\n # just use this for now\nend", "def changes_from_clone\n changes_from_document(clone_source, true)\n end", "def patch_lines\n old_line, new_line = old_start, new_start\n \n old_lines = diff.old_object && diff.old_object.data_lines\n new_lines = diff.new_object && diff.new_object.data_lines\n \n diff_data = summary.split(/(\\d+)/)\n lines = []\n i = 0\n while i < diff_data.length\n line_type, line_count = diff_data[i][0], diff_data[i + 1].to_i\n i += 2\n line_count.times do\n case line_type\n when ?+\n line = [nil, new_line, nil, nil]\n new_line += 1\n when ?-\n line = [old_line, nil, nil, nil]\n old_line += 1\n when ?\\\\\n newline_text = '\\\\ No newline at end of file'\n line = [old_line, new_line, newline_text, newline_text]\n else\n line = [old_line, new_line, nil, nil]\n old_line += 1\n new_line += 1\n end\n line[2] ||= line[0] && old_lines[line[0] - 1]\n line[3] ||= line[1] && new_lines[line[1] - 1]\n lines << line\n end\n end\n lines\n end", "def git_changes?(patchdef)\n patchdef.find {|p| p[1] =~ /^[^.]/}\n end", "def changes(start_ref, end_ref)\n check_refs(start_ref, end_ref)\n s = Mixlib::ShellOut.new(\n \"#{@bin} diff -r #{start_ref}:#{end_ref} --summarize #{@repo_path}\")\n s.run_command.error!\n @logger.info(\"Diff between #{start_ref} and #{end_ref}\")\n s.stdout.lines.map do |line|\n m = line.match(/^(\\w)\\w?\\s+(\\S+)$/)\n fail \"Could not parse line: #{line}\" unless m\n\n {\n :status => m[1] == 'D' ? :deleted : :modified,\n :path => m[2].sub(\"#{@repo_path}/\", '')\n }\n end\n end", "def changeset\n @changeset ||= git_diff.map do |diff_file|\n file_diff = FileDiff.new(diff_file)\n file_diff unless FormattingChecker.pure_formatting?(file_diff)\n end.compact\n end", "def test_12917265\n setup_changeset_test(12917265)\n assert_equal(6, find_changes('el_type' => 'N').size)\n #assert_equal(3, @tiles.size)\n end", "def diff(&block); end", "def cache_changes_before_update\n changes.each do | attr_name, values |\n message = case attr_name\n when 'name' then \"Configuration name changed\"\n when 'comments' then \"Comment updated\"\n when 'jshub_version' then \"jsHub tag version updated\"\n end\n if message\n revision_cache << \"#{message} to '#{values[1]}' (was '#{values[0]}')\"\n end\n end\n end", "def cmd_changed\n print_tree(ChangedEditor, nil, true)\n end", "def show_changes\n if error.blank?\n if changes.length == 0\n error_block(\"No changes for #{defect_name}\")\n else\n build_html do\n c_enum = changes.to_enum\n div.defect do\n describe_defect_changes(c_enum)\n end\n end\n end\n else\n error_block(error)\n end\n end", "def change(params); end", "def patch; end", "def patch; end", "def initialize(changes)\n @changes = changes\n end", "def patches\n \"https://github.com/udoprog/c10t/commit/4a392b9f06d08c70290f4c7591e84ecdbc73d902.diff\"\n end", "def describe_defect_changes(enum)\n begin\n change = enum.peek\n rescue StopIteration\n return \"\"\n end\n span do\n defect_heading(change)\n end\n ul.defect do\n list_defect_changes(enum)\n end\n end", "def changes\n @changes ||= Changes.new do |msg|\n log.indent do\n log << msg\n end\n end\n end", "def change\n attributes.fetch(:change)\n end", "def test_changed\n dir = \"changed_dir\"\n dir1 = \"changed_dir1\"\n dir2 = \"changed_dir2\"\n dir_path = File.join(@wc_path, dir)\n dir1_path = File.join(@wc_path, dir1)\n dir2_path = File.join(@wc_path, dir2)\n dir_svn_path = dir\n dir1_svn_path = dir1\n dir2_svn_path = dir2\n\n file1 = \"changed1.txt\"\n file2 = \"changed2.txt\"\n file3 = \"changed3.txt\"\n file4 = \"changed4.txt\"\n file5 = \"changed5.txt\"\n file1_path = File.join(@wc_path, file1)\n file2_path = File.join(dir_path, file2)\n file3_path = File.join(@wc_path, file3)\n file4_path = File.join(dir_path, file4)\n file5_path = File.join(@wc_path, file5)\n file1_svn_path = file1\n file2_svn_path = [dir_svn_path, file2].join(\"/\")\n file3_svn_path = file3\n file4_svn_path = [dir_svn_path, file4].join(\"/\")\n file5_svn_path = file5\n\n first_rev = nil\n\n log = \"added 3 dirs\\nanded 5 files\"\n make_context(log) do |ctx|\n\n ctx.mkdir([dir_path, dir1_path, dir2_path])\n\n FileUtils.touch(file1_path)\n FileUtils.touch(file2_path)\n FileUtils.touch(file3_path)\n FileUtils.touch(file4_path)\n FileUtils.touch(file5_path)\n ctx.add(file1_path)\n ctx.add(file2_path)\n ctx.add(file3_path)\n ctx.add(file4_path)\n ctx.add(file5_path)\n\n commit_info = ctx.commit(@wc_path)\n first_rev = commit_info.revision\n\n editor = traverse(Svn::Delta::ChangedEditor, commit_info.revision, true)\n assert_equal([\n file1_svn_path, file2_svn_path,\n file3_svn_path, file4_svn_path,\n file5_svn_path,\n ].sort,\n editor.added_files)\n assert_equal([], editor.updated_files)\n assert_equal([], editor.deleted_files)\n assert_equal([].sort, editor.updated_dirs)\n assert_equal([].sort, editor.deleted_dirs)\n assert_equal([\n \"#{dir_svn_path}/\",\n \"#{dir1_svn_path}/\",\n \"#{dir2_svn_path}/\"\n ].sort,\n editor.added_dirs)\n end\n\n log = \"deleted 2 dirs\\nchanged 3 files\\ndeleted 2 files\\nadded 3 files\"\n make_context(log) do |ctx|\n\n dir3 = \"changed_dir3\"\n dir4 = \"changed_dir4\"\n dir3_path = File.join(dir_path, dir3)\n dir4_path = File.join(@wc_path, dir4)\n dir3_svn_path = [dir_svn_path, dir3].join(\"/\")\n dir4_svn_path = dir4\n\n file6 = \"changed6.txt\"\n file7 = \"changed7.txt\"\n file8 = \"changed8.txt\"\n file9 = \"changed9.txt\"\n file10 = \"changed10.txt\"\n file6_path = File.join(dir_path, file6)\n file7_path = File.join(@wc_path, file7)\n file8_path = File.join(dir_path, file8)\n file9_path = File.join(dir_path, file9)\n file10_path = File.join(dir_path, file10)\n file6_svn_path = [dir_svn_path, file6].join(\"/\")\n file7_svn_path = file7\n file8_svn_path = [dir_svn_path, file8].join(\"/\")\n file9_svn_path = [dir_svn_path, file9].join(\"/\")\n file10_svn_path = [dir_svn_path, file10].join(\"/\")\n\n File.open(file1_path, \"w\") {|f| f.puts \"changed\"}\n File.open(file2_path, \"w\") {|f| f.puts \"changed\"}\n File.open(file3_path, \"w\") {|f| f.puts \"changed\"}\n ctx.rm_f([file4_path, file5_path])\n FileUtils.touch(file6_path)\n FileUtils.touch(file7_path)\n FileUtils.touch(file8_path)\n ctx.add(file6_path)\n ctx.add(file7_path)\n ctx.add(file8_path)\n ctx.cp(file1_path, file9_path)\n ctx.cp(file2_path, file10_path)\n ctx.mv(dir2_path, dir3_path)\n ctx.cp(dir1_path, dir4_path)\n ctx.rm(dir1_path)\n\n commit_info = ctx.commit(@wc_path)\n second_rev = commit_info.revision\n\n editor = traverse(Svn::Delta::ChangedEditor, commit_info.revision, true)\n assert_equal([file1_svn_path, file2_svn_path, file3_svn_path].sort,\n editor.updated_files)\n assert_equal([file4_svn_path, file5_svn_path].sort,\n editor.deleted_files)\n assert_equal([file6_svn_path, file7_svn_path, file8_svn_path].sort,\n editor.added_files)\n assert_equal([].sort, editor.updated_dirs)\n assert_equal([\n [file9_svn_path, file1_svn_path, first_rev],\n [file10_svn_path, file2_svn_path, first_rev],\n ].sort_by{|x| x[0]},\n editor.copied_files)\n assert_equal([\n [\"#{dir3_svn_path}/\", \"#{dir2_svn_path}/\", first_rev],\n [\"#{dir4_svn_path}/\", \"#{dir1_svn_path}/\", first_rev],\n ].sort_by{|x| x[0]},\n editor.copied_dirs)\n assert_equal([\"#{dir1_svn_path}/\", \"#{dir2_svn_path}/\"].sort,\n editor.deleted_dirs)\n assert_equal([].sort, editor.added_dirs)\n end\n end", "def old_value; end", "def changes; self.diff @pristine; end", "def things_to_diff(exp, act); end", "def no_change( x )\n return x\nend", "def method_missing(s,*a,&b)\n if @change.respond_to?(s)\n @change.send(s,*a,&b)\n else\np caller\n super(s,*a,&b)\n end\n end", "def move_diffs\n \n end", "def diffyable\n # add appropriate diff column data for diff.right and diff.left and update other attrs to the Diffy way®\n\n w1id = self.work1\n w2id = self.work2\n w1work = Work.find(w1id)\n w2work = Work.find(w2id)\n w1md = w1work.file_content_md\n w2md = w2work.file_content_md\n w1txt = w1work.file_content_text\n w2txt = w2work.file_content_text\n\n html = Diffy::Diff.new(w1md, w2md).to_s(:html)\n md = Diffy::Diff.new(w1md, w2md).to_s\n text = Diffy::Diff.new(w1txt, w2txt).to_s\n \n lucy = Diffy::SplitDiff.new(w1md, w2md, :format => :html).left\n recha = Diffy::SplitDiff.new(w1md, w2md, :format => :html).right\n\n html.force_encoding(\"UTF-8\").scrub!\n md.force_encoding(\"UTF-8\").scrub!\n text.force_encoding(\"UTF-8\").scrub!\n\n lucy.force_encoding(\"UTF-8\").scrub!\n recha.force_encoding(\"UTF-8\").scrub!\n\n self.update_attributes(left: lucy, right: recha, diff_md: md, diff_html: html, diff_text: text)\n self.save\n end", "def changed\n return added + removed unless added.nil? || removed.nil?\n return added unless added.nil?\n return removed unless removed.nil?\n end", "def diff(from, to=nil)\n from << \"..#{to}\" if to\n scm :diff, from\n end", "def test_ut_diff_source_code_02\n assert_equal(1,@diff_source_code_1.diff_result_id)\n assert_equal(1,@diff_source_code_1.original_file_id)\n assert_equal(1,@diff_source_code_1.diff_file_id)\n assert_equal(nil,@diff_source_code_1.added_lines)\n assert_equal(\"7;8;9;25;390;396;397;400;404\",@diff_source_code_1.deleted_lines)\n assert_equal(\"1,1;2,2;3,3;4,4;6,6;10,10;11,11;12,12;13,13;14,14;15,15;\",@diff_source_code_1.common_lines)\n end", "def get_changegroup(common, source)\n # Call the hooks\n run_hook :pre_outgoing, :throw => true, :source => source\n \n nodes = changelog.find_missing common\n revset = Hash.with_keys(nodes.map {|n| changelog.rev(n)})\n changegroup_info nodes, source\n \n identity = proc {|x| x }\n \n # ok so this method goes through the generic revlog, and looks for nodes\n # in the changeset(s) we're pushing. Works by the link_rev - basically,\n # the changelog says \"hey we're at revision 35\", and any changes to any\n # files in any revision logs for that commit will have a link_revision\n # of 35. So we just look for 35!\n gen_node_list = proc do |log|\n log.select {|r| revset[r.link_rev] }.map {|r| r.node_id }\n end\n \n # Ok.... I've tried explaining this 3 times and failed.\n #\n # Goal of this proc: We need to update the changed_files hash to reflect\n # which files (typically file logs) have changed since the last push.\n #\n # How it works: it generates a proc that takes a node_id. That node_id\n # will be looked up in the changelog.i file, which happens to store a\n # list of files that were changed in that commit! So really, this method\n # just takes a node_id, and adds filenamess to the list of changed files.\n changed_file_collector = proc do |changed_fileset|\n proc do |cl_node|\n c = changelog.read cl_node\n c.files.each {|fname| changed_fileset[fname] = true }\n end\n end\n \n lookup_revlink_func = proc do |revlog|\n # given a revision, return the node\n # good thing the python has a description of what this does\n #\n # *snort*\n lookup_revlink = proc do |n|\n changelog.node revlog[n].link_rev\n end\n end\n \n # This constructs a changegroup, or a list of all changed files.\n # If you're here, looking at this code, this bears repeating:\n # - Changelog\n # -- ChangeSet+\n #\n # A Changelog (history of a branch) is an array of ChangeSets,\n # and a ChangeSet is just a single revision, containing what files\n # were changed, who did it, and the commit message. THIS IS JUST A\n # RECEIPT!!!\n #\n # The REASON we construct a changegroup here is because this is called\n # when we push, and we push a changelog (usually bundled to conserve\n # space). This is where we make that receipt, called a changegroup.\n #\n # 'nuff tangent, time to fucking code\n generate_group = proc do\n result = []\n changed_files = {}\n \n coll = changed_file_collector[changed_files]\n # get the changelog's changegroups\n changelog.group(nodes, identity, coll) {|chunk| result << chunk }\n \n node_iter = gen_node_list[manifest]\n look = lookup_revlink_func[manifest]\n # get the manifest's changegroups\n manifest.group(node_iter, look) {|chunk| result << chunk }\n changed_files.keys.sort.each do |fname|\n file_revlog = file fname\n # warning: useless comment\n if file_revlog.index_size.zero?\n raise abort(\"empty or missing revlog for #{fname}\")\n end\n \n node_list = gen_node_list[file_revlog]\n \n if node_list.any?\n result << Amp::Mercurial::RevlogSupport::ChangeGroup.chunk_header(fname.size)\n result << fname\n \n lookup = lookup_revlink_func[file_revlog] # Proc#call\n # more changegroups\n file_revlog.group(node_list, lookup) {|chunk| result << chunk }\n end\n end\n result << Amp::Mercurial::RevlogSupport::ChangeGroup.closing_chunk\n \n run_hook :post_outgoing, :node => nodes[0].hexlify, :source => source\n \n result\n end\n \n s = StringIO.new \"\", Support.binary_mode(\"w+\")\n generate_group[].each {|chunk| s.write chunk }\n s.rewind\n s\n end", "def changed_at\n mark.changed_at if respond_to?(:mark) && !mark.blank?\n end", "def changes\n poll(\"Changes\")\n end", "def test_change_alias\n value_ = ::Versionomy.create([1, 8, 7, 'a', 2], :rubygems)\n value_ = value_.change(:minor => 9)\n assert_equal([1, 9, 7, 'a', 2, 0, 0, 0], value_.values_array)\n end", "def current_alter\n @current_alter\n end", "def current_alter\n @current_alter\n end", "def current_alter\n @current_alter\n end", "def current_alter\n @current_alter\n end", "def current_alter\n @current_alter\n end", "def test_ut_diff_result_02\n original_source_code = OriginalSourceCode.new(\n :original_file_id => 10,\n :line_number => 349898,\n :error_line => 4564,\n :line_content => \"123456\"\n )\n assert_equal(10,original_source_code.original_file_id)\n assert_equal(349898,original_source_code.line_number)\n assert_equal(4564,original_source_code.error_line)\n assert_equal(\"123456\",original_source_code.line_content)\n end", "def old_name; end", "def changes\n @changes ||= JSON.parse(File.read(ARGV[1]))\nend", "def changed? \n @changed == true\n end", "def changes_against(ref)\n self.class.attribute_names_for_history_changes.inject({}) do |changes, attr|\n old, new = ref.public_send(attr), self.public_send(attr)\n\n changes.tap do |c|\n changed = old.respond_to?(:history_eql?) ?\n !old.history_eql?(new) : old != new\n\n c[attr] = [old, new] if changed\n end\n end\n end", "def changes_against(ref)\n self.class.attribute_names_for_history_changes.inject({}) do |changes, attr|\n old, new = ref.public_send(attr), self.public_send(attr)\n\n changes.tap do |c|\n changed = old.respond_to?(:history_eql?) ?\n !old.history_eql?(new) : old != new\n\n c[attr] = [old, new] if changed\n end\n end\n end", "def extract_change_count_from_git_log(log_text)\n lines = log_text.split(\"\\n\" )\n change_lines=lines.find_all do | line |\n line.include?('changed')\n end\n change_lines.length\nend", "def local_changed?\n # TODO\n end", "def extract_changelog\n changelog = ''\n in_changelog = false\n git_show.send(LINE_ITERATOR) do |line|\n if line =~ /^diff --git/\n in_changelog = false\n elsif line =~ /^\\+\\+\\+.*changelog$/i\n in_changelog = true\n elsif in_changelog && line =~ /^\\+\\s*\\*/\n changelog << line\n end\n end\n changelog\n end", "def change_context(options)\n context = MetaCommit::Contracts::ChangeContext.new\n context.type = options[:line].line_origin\n context.old_lineno = options[:line].old_lineno\n context.new_lineno = options[:line].new_lineno\n context.column = options[:column]\n context.commit_id_old = options[:commit_id_old]\n context.commit_id_new = options[:commit_id_new]\n context.old_contextual_ast = options[:old_contextual_ast]\n context.new_contextual_ast = options[:new_contextual_ast]\n context.old_file_path = options[:old_file_path]\n context.new_file_path = options[:new_file_path]\n context\n end", "def diff\n @diff ||= begin\n commit.diffs.collect{|diff| diff.diff}.join(\"\\n\")\n end\n end", "def changes(start_ref, end_ref)\n valid_ref?(start_ref)\n valid_ref?(end_ref) if end_ref\n stdout = @cmd.status(start_ref, end_ref).stdout\n begin\n parse_status(stdout).compact\n rescue StandardError => e\n # We've seen some weird non-reproducible failures here\n @logger.error(\n 'Something went wrong. Please report this output.',\n )\n @logger.error(e)\n stdout.lines.each do |line|\n @logger.error(line.strip)\n end\n exit(1)\n end\n end", "def modified_files; end", "def attribute_changed_value_message=(_arg0); end", "def unified_diff(text_old, text_new, label=\"--- old\\n+++ new\\n\", context=3)\n msg = \"\\\\ No newline at end of string\"\n lines_old = _text2lines(text_old, msg)\n lines_new = _text2lines(text_new, msg)\n #\n buf = \"#{label}\"\n len = 0\n prevhunk = hunk = nil\n diffs = Diff::LCS.diff(lines_old, lines_new)\n diffs.each do |diff|\n hunk = Diff::LCS::Hunk.new(lines_old, lines_new, diff, context, len)\n if hunk.overlaps?(prevhunk)\n hunk.unshift(prevhunk)\n else\n buf << prevhunk.diff(:unified) << \"\\n\"\n end if prevhunk\n len = hunk.file_length_difference\n prevhunk = hunk\n end\n buf << prevhunk.diff(:unified) << \"\\n\" if prevhunk\n return buf\n end", "def changes(attrs1, attrs2)\n old_attrs = attrs1.slice(*GENERATED_ATTRS)\n new_attrs = attrs2.slice(*GENERATED_ATTRS)\n\n return if old_attrs == new_attrs\n old_attrs.each do |k, v|\n next if new_attrs[k] == v\n @changes << Change.new(nil, k, v, new_attrs[k]) \n end\n end", "def move_diffs\n\n end", "def all_changes_in_revisions array\n raise NotImplementedError.new('Define method :all_changes_in_revisions on your source control.')\n end", "def diff_line_class(line)\n case line[0, 1]\n when '+' then 'added'\n when '-' then 'deleted'\n end\n end", "def list_changes_within_release(enum)\n change = enum.peek\n release = change.release\n while change.release == release\n li do\n describe_single_change(change)\n end\n begin\n enum.next\n change = enum.peek\n rescue StopIteration\n break\n end\n end\n end", "def diff(other, callbacks = nil, &block)\n Diff::LCS.diff(self, other, callbacks, &block)\n end", "def changes\n if @changes\n @changes.dup\n else\n []\n end\n end", "def change(hash); end", "def test_patch\n checkout_dir =File.expand_path(File.join('..','..','..','sequence', 'repository', 'Unidata@thredds'),File.dirname(__FILE__))\n repos = Rugged::Repository.new(checkout_dir)\n from = repos.lookup('49429686c3be8c3cb0aea17fca3e6684706d5fa1')\n to = repos.lookup('f63544cc69b49664a0487bf064ce0c7f64b40641')\n puts \"from #{from}\"\n puts \"to #{to}\"\n diff = to.patch(from)\n puts diff.content\n puts \"patch\"\n diff.patch.lines do |line|\n puts line\n end\n \n #.lines.each do |line|\nend", "def diff_edits_from_empty\n diff_edits(true)\n end", "def patches\n \"https://gist.github.com/fredrikw/5858168/raw\"\n end", "def updated_source_file; end", "def updated_changelog\n # Sometimes it's a README fix, or something like that - which isn't relevant for\n # including in a project's CHANGELOG for example\n not_declared_trivial = !(danger_file.github.pr_title.include? '#trivial')\n\n no_changelog_entry = danger_file.git.modified_files.none? { |s| s.casecmp('changelog.md').zero? }\n\n return if !pr_contains_code_changes && !pr_contains_localization_changes || !no_changelog_entry || !not_declared_trivial\n return unless %w[master develop].include?(danger_file.github.branch_for_base)\n danger_file.fail('Any changes to code should be reflected in the Changelog. Please consider adding a note there.')\n end", "def changed_reason\n\t\treturn \"Struct was modified\" if @struct.modified?\n\n\t\tif self.name && self.loader.is_newer?( self.name, self.create_time )\n\t\t\treturn \"Config source (%s) has been updated since %s\" %\n\t\t\t\t[ self.name, self.create_time ]\n\t\tend\n\n\t\treturn nil\n\tend", "def changelog_has_been_modified\n\n modified = git.modified_files.include?(\"CHANGELOG.md\")\n return modified\n\nend", "def changed?; not pristine?; end", "def parse_changeset(attribute, values, type, diff)\n return parse_scope_changeset(attribute, values, type, diff) if type == :scope\n\n values = parse_values(attribute, values)\n\n diff.update(\n attribute => {\n type: type,\n label: I18n.t(attribute, scope: i18n_scope),\n old_value: values[0],\n new_value: values[1]\n }\n )\n end", "def patch=(_arg0); end" ]
[ "0.66661704", "0.66523665", "0.65853006", "0.649974", "0.63615906", "0.63281566", "0.61472815", "0.612383", "0.6118165", "0.61106163", "0.60854095", "0.6081466", "0.6068333", "0.6037956", "0.5997624", "0.599586", "0.5982023", "0.5954718", "0.59471846", "0.5915047", "0.58600897", "0.585719", "0.5836059", "0.5836059", "0.5819103", "0.57964617", "0.5793011", "0.579175", "0.5785851", "0.5781933", "0.5769084", "0.5748", "0.5738898", "0.57125586", "0.57006353", "0.56909955", "0.5677024", "0.56679595", "0.5651094", "0.5650773", "0.56472397", "0.5646207", "0.5646207", "0.56342185", "0.5625905", "0.5625811", "0.56188464", "0.5616176", "0.5615725", "0.56029165", "0.5596604", "0.5590029", "0.5561916", "0.55458295", "0.5539387", "0.55245924", "0.5517382", "0.5509065", "0.55037826", "0.5503573", "0.549803", "0.5491801", "0.5487407", "0.548137", "0.548137", "0.548137", "0.548137", "0.548137", "0.5481151", "0.5474907", "0.54720026", "0.54695326", "0.54617226", "0.54617226", "0.5455477", "0.54431343", "0.54328305", "0.54291064", "0.54262793", "0.54172623", "0.5414691", "0.5412868", "0.5410647", "0.5410003", "0.54064316", "0.5405172", "0.5399741", "0.53978395", "0.5390318", "0.538792", "0.5381655", "0.53762317", "0.5371197", "0.53667885", "0.5361054", "0.53586215", "0.5356631", "0.5349898", "0.5347317", "0.5345509", "0.53442323" ]
0.0
-1
For cooperation with ESOD
def set_esod_user_id Esodes::EsodTokenData.new(current_user.id) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def eplore\n end", "def etfs\n\n end", "def private; end", "def service; end", "def schubert; end", "def run\n super\n\n # Attach to the corpwatch service & search\n x = Client::Corpwatch::CorpwatchService.new\n corps = x.search @entity.name\n\n corps.each do |corp|\n # Create a new organization entity & attach a record\n o = create_entity Entities::Organization, { \n :name => corp.name, \n :data => corp.to_s\n }\n \n create_entity(Entities::PhysicalLocation, {\n :name => corp.address,\n :address => corp.address, \n :state => corp.state,\n :country => corp.country }\n )\n end\nend", "def specie; end", "def specie; end", "def specie; end", "def specie; end", "def bi_service\n end", "def run\n super\n # Get entity name\n ssl_certificate = _get_entity_name[/\\(([^()]*)\\)/, 1]\n\n # Make sure the key is set\n api_key = _get_task_config('spyse_api_key')\n # Set the headers\n headers = { 'Accept' => 'application/json', 'Authorization' => \"Bearer #{api_key}\" }\n\n # Set the headers\n url = \"https://api.spyse.com/v4/data/certificate/#{ssl_certificate}\"\n\n # make the request\n response = http_request(:get, url, nil, headers)\n\n # Check response code status\n if response.code.to_i == 200\n # Parse json response\n json = JSON.parse(response.body)\n\n ## Create entities\n if json['data']['items']\n json['data']['items'].each do |result|\n # Check whether it is a wildcard certificate or not\n if (result['parsed']['names']).count > 1\n # Extract list of domains sharing the same certificate\n list_of_domains_sharing_same_certificate = result['parsed']['names']\n # Extarct certificate experation date\n end_date = result['parsed']['validity']['end']\n # Extract certificate algorithm\n algorithm = result['parsed']['signature_algorithm']['name']\n # Extract certificate serial number\n serial = result['parsed']['serial_number']\n # Create entity with spyse data\n _create_entity('SslCertificate', {\n 'name' => ssl_certificate,\n 'not_after' => end_date,\n 'serial' => serial,\n 'algorithm' => algorithm,\n 'list_of_domains_sharing_same_certificate' => list_of_domains_sharing_same_certificate\n })\n end\n\n # Create DnsRecord from domains registered with same certificate\n if result['parsed']['names']\n result['parsed']['names'].each do |domain|\n _create_entity('DnsRecord', { 'name' => domain })\n end\n end\n # Create organizations related to the certificate\n if result['parsed']['subject']['organization']\n result['parsed']['subject']['organization'].each do |organization|\n _create_entity('Organization', { 'name' => organization })\n end\n end\n end\n end\n else\n _log_error \"unable to fetch response => error code: #{response.code}!\"\n end\n end", "def entities; end", "def dh; end", "def eds_init\n setup_eds_session(session)\n end", "def run\n super\n\n entity_name = _get_entity_name\n entity_type = _get_entity_type_string\n\n # Make sure the key is set\n api_key = _get_task_config(\"binary_edge_api_key\")\n\n if entity_type == \"IpAddress\"\n response = search_binaryedge_by_ip entity_name, api_key\n\n if response[\"events\"]\n response[\"events\"].each do |e|\n e[\"results\"].each do |r|\n\n # create a network service for every result\n # saving the details off as extended details\n port = r[\"target\"][\"port\"]\n proto = r[\"target\"][\"protocol\"]\n be_details = {\"extended_binaryedge\" => e }\n _create_network_service_entity(@entity,port,proto, be_details)\n\n # this should be optional...\n #if port != \"443\"\n # _create_issue({\n # name: \"#{entity_name}:#{port} [Binary Edge]\",\n # type: \"Malicious IP\",\n # severity: 3 ,\n # status: \"confirmed\",\n # description: \"Port: #{e[\"port\"]} || State:#{r[\"result\"][\"data\"][\"state\"]} || Security issue:#{r[\"result\"][\"data\"][\"security\"]}\n # || Reason:#{r[\"result\"][\"data\"][\"reason\"]} || \", #Running Service:#{r[\"result\"][\"data\"][\"service\"]}\"s\n # details: json\n # })\n #end\n\n end\n end\n end\n\n elsif entity_type == \"Domain\"\n # look for related eentities?\n dns_records = search_binaryedge_by_subdomain entity_name, api_key\n\n dns_records.each do |d|\n _create_entity \"DnsRecord\" , \"name\" => d\n end\n\n # also check for data leaks\n response = search_binaryedge_leaks_by_domain entity_name, api_key\n response[\"groups\"].each do |t|\n # create issues if we found any\n _create_linked_issue(\"leaked_data\",{\n proof: \"#{t[\"count\"]} accounts found related to #{entity_name} in #{t[\"leak\"]}\",\n detailed_description: \"#{t[\"count\"]} accounts found related to #{entity_name} in #{t[\"leak\"]}\",\n references:[\"https://binaryedge.com/\",\n \"https://askleo.com/account-involved-breach/\"] ,\n details: t\n })\n end\n\n elsif entity_type == \"EmailAddress\"\n\n # checks for data leaks\n response = search_binaryedge_leaks_by_email_address entity_name, api_key\n\n if response[\"total\"] == 0\n _log \"No results found!\"\n return\n end\n\n # create issues if we found any\n response[\"events\"].each do |u|\n ############################################\n ### Old Issue ###\n ###########################################\n # _create_issue({\n # name: \"Email Found in Data Leak #{u}\",\n # type: \"leaked_account\",\n # severity: 3,\n # status: \"confirmed\",\n # detailed_description: \"This Email has been found in this breach: #{u}, via BinaryEdge\",\n # references:\"https://binaryedge.com/\",\n # details: u\n # })\n ############################################\n ### New Issue ###\n ###########################################\n _create_linked_issue(\"leaked_data\",{\n proof: \"This Email has been found in this breach: #{u}\",\n name: \"Email Found in Data Leak #{u}\",\n type: \"leaked_email\",\n detailed_description: \"This Email has been found in this breach: #{u}, via BinaryEdge\",\n references:\"https://binaryedge.com/\",\n details: u\n })\n end\n\n elsif entity_type == \"NetBlock\"\n #do the right thing\n events = search_binaryedge_netblock(_get_entity_name, api_key, 0)\n events.each do |e|\n begin \n port = e[\"target\"][\"port\"]\n target = e[\"target\"][\"ip\"]\n protocol = e[\"target\"][\"protocol\"]\n _create_entity \"NetworkService\", {\"name\" => \"#{target}:#{port}/#{protocol}\"}\n \n rescue NoMethodError, KeyError\n # pass it on\n next\n end\n end\n \n else\n _log_error \"Unsupported entity type\"\n end\n\n end", "def weber; end", "def transport; end", "def transport; end", "def transport; end", "def run\n super\n\n #\n # This module currently uses the Free API (rate limited / response limited)\n # https://freeapi.robtex.com/ipquery/#{search_ip}\n #\n # Note that a paid version (free up to 10k queries / month) of the API is available at:\n # https://market.mashape.com/robtex/robtex\n #\n\n # Check Robtex API & create entities from returned JSON\n search_ip = _get_entity_name\n search_uri = \"https://freeapi.robtex.com/ipquery/#{search_ip}\"\n\n begin\n details = JSON.parse(http_get_body(search_uri))\n _log \"Got details: #{details}\"\n\n #status\n # Should be \"ok\"\n unless details[\"status\"] == \"ok\"\n _log_error \"Unable to continue\"\n return\n end\n\n #act\n # Active (forward) DNS\n if details[\"act\"]\n details[\"act\"].each do |forward_lookup|\n _create_entity \"DnsRecord\",{\n \"name\" => forward_lookup[\"o\"],\n \"time\" => \"#{Time.at(forward_lookup[\"t\"])}\"\n }\n end\n end\n\n #pas\n # Passive (reverse) DNS\n if details[\"pas\"]\n details[\"pas\"].each do |reverse_lookup|\n _create_entity \"DnsRecord\",{\n \"name\" => reverse_lookup[\"o\"],\n \"time\" => \"#{Time.at(reverse_lookup[\"t\"])}\"\n }\n end\n end\n\n #pash\n # Passive DNS history\n # TODO\n\n #acth\n # Active DNS history\n # TODO\n\n #as\n # Autonomous System Number\n if details[\"as\"]\n _create_entity \"AsNumber\",{\n \"name\" => \"AS#{details[\"as\"]}\",\n \"as_name\" => details[\"asname\"],\n \"as_desc\" => details[\"asdesc\"]\n }\n end\n\n # Netblock\n #\n if details[\"bgproute\"]\n _create_entity \"NetBlock\",{\"name\" => \"#{details[\"bgproute\"]}\"}\n end\n\n rescue JSON::ParserError => e\n _log_error \"Unable to get parsable response from #{search_uri}: #{e}\"\n rescue StandardError => e\n _log_error \"Error grabbing robtex details: #{e}\"\n end\n\n\n end", "def jaeger_quest; end", "def scientist; end", "def provider; end", "def strategy; end", "def isolated; end", "def isolated; end", "def suivre; end", "def sld; end", "def endpoint; end", "def endpoint; end", "def endpoint; end", "def endpoint; end", "def run\n super\n\n entity_name = _get_entity_name\n entity_type = _get_entity_type_string\n\n # Make sure the key is set\n api_key = _get_task_config(\"spyse_api_key\")\n # Set the headers\n headers = {\"api_token\" => api_key}\n\n # Returns aggregate information by subdomain word : total count of subdomains, list of IPs of subdomains and subdomain count on every IP,\n # list of countries and subdomain count from it, list of CIDRs /24, /16 and subdomain list on every CIDR.\n if entity_type == \"String\"\n url = \"https://api.spyse.com/v1/domains-starts-with-aggregate?sdword=#{entity_name}\"\n get_subdomains entity_name, api_key, headers, url\n\n # Returns aggregate information by domain: total count of subdomains, list of IPs of subdomains and subdomain count on every IP,\n # list of countries and subdomain count from it, list of CIDRs /24, /16 and subdomain list on every CIDR.\n elsif entity_type == \"Domain\"\n url = \"https://api.spyse.com/v1//subdomains-aggregate?domain=#{entity_name}\"\n get_subdomains entity_name, api_key, headers, url\n\n else\n _log_error \"Unsupported entity type\"\n end\n\n end", "def feruchemist; end", "def upc_e; end", "def apis; end", "def client\n Etapper.client\nend", "def service_endpoint; end", "def service_endpoint; end", "def run\n super\n\n entity_name = _get_entity_name\n entity_type = _get_entity_type_string\n\n # Make sure the key is set\n api_key = _get_task_config(\"spyse_api_key\")\n # Set the headers\n headers = { \"Accept\" => \"application/json\" , \"Authorization\" => \"Bearer #{api_key}\" }\n\n if entity_type == \"Domain\"\n # Search Ip for domain hosted on the same IP\n search_domain_on_same_ip entity_name,headers\n\n # Search subdomain related to the domain\n search_subdomains entity_name,headers\n else\n _log_error \"Unsupported entity type\"\n end\n\n end", "def terpene; end", "def who_we_are\r\n end", "def vendor; end", "def run\n super\n\n # Make sure the key is set\n raise \"API KEY MISSING: shodan_api_key\" unless $intrigue_config[\"shodan_api_key\"]\n\n @client = Client::Search::Shodan::ApiClient.new($intrigue_config[\"shodan_api_key\"])\n response = @client.search(_get_entity_attribute \"name\")\n\n # check to make sure we got a response.\n raise \"ERROR: No response\" unless response\n\n # Check to make sure we got results\n if response[\"matches\"]\n\n @task_log.log \"Found #{response[\"matches\"].count} matches\"\n\n # Go through the results\n response[\"matches\"].each do |r|\n\n @task_log.log \"* SHODAN Record *\"\n\n #updated_at = DateTime.new(r[\"updated\"])\n updated_at = DateTime.now\n\n #\n # Create a host record\n #\n @task_log.log \"IP: #{r[\"ip\"]}\"\n host = _create_entity(\"IpAddress\",{\n :name => \"#{r[\"ip\"]}\",\n :age => \"#{updated_at}\"\n }) if r[\"ip\"]\n\n #\n # Create a DNS record for all hostnames\n #\n r[\"hostnames\"].each do |h|\n @task_log.log \"Hostname: #{h}\"\n _create_entity(\"DnsRecord\",{ :name => \"#{h}\", :age => \"#{updated_at}\" })\n end\n\n #\n # Create a netsvc\n #\n @task_log.log \"Port: #{r[\"port\"]}\"\n\n port = _create_entity(\"NetSvc\",{\n :name => \"#{host.attributes[:name]}:#{r[\"port\"]}/tcp\",\n :proto => \"tcp\",\n :port_num => r[\"port\"],\n :fingerprint => r[\"data\"],\n :age => \"#{updated_at}\"\n }) if r[\"port\"]\n\n #\n # Create an organization\n #\n @task_log.log \"Org: #{r[\"org\"]}\"\n org = _create_entity(\"Organization\",{\n :name => \"#{r[\"org\"]}\",\n :age => \"#{updated_at}\"\n }) if r[\"org\"]\n\n #\n # Create a PhysicalLocation\n #\n @task_log.log \"Location: #{r[\"postal_code\"]}\"\n location = _create_entity(\"PhysicalLocation\",{\n :name => \"#{r[\"latitude\"]} / #{r[\"longitude\"]}\",\n :zip => \"#{r[\"postal_code\"]}\",\n :state => \"#{r[\"region_name\"]}\",\n :country => \"#{r[\"country_name\"]}\",\n :latitude => \"#{r[\"latitude\"]}\",\n :longitude => \"#{r[\"longitude\"]}\",\n :age => \"#{updated_at}\"\n }) if r[\"country_name\"]\n\n\n @task_log.log \"Port: #{r[\"port\"]}\"\n @task_log.log \"Port Data: #{r[\"data\"]}\"\n @task_log.log \"Country: #{r[\"country_name\"]}\"\n @task_log.log \"Country Code: #{r[\"country_code\"]}\"\n @task_log.log \"Region Name: #{r[\"region_name\"]}\"\n @task_log.log \"Area Code: #{r[\"area_code\"]}\"\n @task_log.log \"DMA Code: #{r[\"dma_code\"]}\"\n @task_log.log \"Postal Code: #{r[\"postal_code\"]}\"\n @task_log.log \"Org: #{r[\"org\"]}\"\n\n end\n end\n end", "def run\n _log \"Enriching... Network Service: #{_get_entity_name}\"\n\n ###\n ### First, normalize the nane - split out the various attributes\n ###\n entity_name = _get_entity_name\n\n # grab the ip, handling ipv6 gracefully\n if entity_name =~ /:/\n ip_address = entity_name.split(\":\")[0..-2].join(\":\")\n else\n ip_address = entity_name.split(\":\").first\n end\n\n port = entity_name.split(\":\").last.split(\"/\").first.to_i\n proto = entity_name.split(\":\").last.split(\"/\").first.upcase\n net_name = _get_entity_detail(\"net_name\")\n\n # check if the port is open, if not, hide this entity (its not a real NetworkService)\n unless _get_entity_detail(\"hidden_port_open_confirmed\") == true\n unless Intrigue::Ident::SimpleSocket.connect_tcp(ip_address, port, 5)\n # note that we use tcp even for udp ports, because with udp we fire & hope for the best\n # this has been tested and tcp is reliable for detecting open udp ports\n hide_value = true\n hide_reason = \"port_closed\"\n _set_entity_detail \"hide_value\", hide_value\n _set_entity_detail \"hide_reason\", hide_reason\n\n # Okay now hide based on our value\n _log \"Setting Hidden to: #{hide_value}, for reason: #{hide_reason}\"\n @entity.hidden = hide_value\n @entity.save_changes\n return\n end\n end \n \n _set_entity_detail(\"ip_address\", ip_address)\n _set_entity_detail(\"port\", port)\n _set_entity_detail(\"proto\", proto)\n\n _log \"Geolocating...\"\n location_hash = geolocate_ip(ip_address)\n if location_hash.nil? \n _log \"Unable to retrieve Gelocation.\"\n else\n _set_entity_detail(\"geolocation\", location_hash)\n end\n\n # Use Ident to fingerprint\n _log \"Grabbing banner and fingerprinting!\"\n ident = Intrigue::Ident::Ident.new\n ident_response = ident.fingerprint_service(ip_address, port)\n\n fingerprint = ident_response[\"fingerprint\"]\n\n # set entity details\n _set_entity_detail \"fingerprint\", fingerprint\n\n # Translate ident fingerprint (tags) into known issues\n create_issues_from_fingerprint_tags(fingerprint, @entity)\n\n # Create issues for any vulns that are version-only inference\n fingerprint_to_inference_issues(fingerprint)\n\n # Create issues for fingerprints that request creating an issue\n issues_from_fingerprints = fingerprint.collect{ |x| x[\"issues\"] }.flatten.compact.uniq\n _log \"Issues to be created: #{issues_from_fingerprints}\"\n (issues_from_fingerprints || []).each do |c|\n _create_linked_issue c\n end\n\n # Okay, now kick off vulnerability checks (if project allows)\n if @project.vulnerability_checks_enabled\n vuln_checks = run_vuln_checks_from_fingerprint(fingerprint, @entity)\n _set_entity_detail(\"vuln_checks\", vuln_checks)\n end\n\n ###\n ### Handle SNMP as a special treat\n ###\n enrich_snmp if port == 161 && proto.upcase == \"UDP\"\n\n ###\n ### Hide Some services based on their attributes\n ###\n\n hide_value = false\n hide_reason = \"default\"\n\n # consider these noise\n noise_networks = [\n # \"CLOUDFLARENET - CLOUDFLARE, INC., US\",\n # \"GOOGLE, US\",\n # \"CLOUDFLARENET, US\",\n # \"GOOGLE-PRIVATE-CLOUD, US\",\n \"INCAPSULA, US\",\n \"INCAPSULA - INCAPSULA INC, US\"\n ]\n\n # drop them if we don't have a fingerprint\n #\n # TODO ... this might need to be checked for a generic reset now\n #\n if noise_networks.include?(net_name)\n # always allow these ports even if we dont have a fingeprint\n unless (port == 80 || port == 443)\n hide_value = true\n hide_reason = \"noise_network\"\n end\n end\n\n # Okay now hide based on our value\n _log \"Setting Hidden to: #{hide_value}, for reason: #{hide_reason}\"\n @entity.hidden = hide_value\n @entity.save_changes\n\n end", "def user_os_complex\r\n end", "def sitemaps; end", "def sn\n end", "def site_data; end", "def req\n \n end", "def connection; end", "def connection; end", "def connection; end", "def connection; end", "def connection; end", "def connection; end", "def connection; end", "def connection; end", "def tou\n\n clnt = HTTPClient.new\n Rails.logger.info(\"es287_debug #{__FILE__} #{__LINE__} = #{Blacklight.solr_config.inspect}\")\n solr = Blacklight.solr_config[:url]\n p = {\"id\" =>params[:id] , \"wt\" => 'json',\"indent\"=>\"true\"}\n @dbString = clnt.get_content(\"#{solr}/database?\"+p.to_param)\n @dbResponse = JSON.parse(@dbString)\n @db = @dbResponse['response']['docs']\n dbcode = @dbResponse['response']['docs'][0]['dbcode']\n providercode = @dbResponse['response']['docs'][0]['providercode']\n @defaultRightsText = ''\n if dbcode.nil? or dbcode == '' #check for providerCode being nil\n @defaultRightsText = \"Use default rights text\"\n else\n @ermDBResult = ::Erm_data.where(Database_Code: \"\\'#{dbcode[0]}\\'\", Prevailing: 'true')\n if @ermDBResult.size < 1\n @ermDBResult = ::Erm_data.where(\"Provider_Code = \\'#{providercode[0]}\\' AND Prevailing = 'true' AND (Database_Code = '' OR Database_Code IS NULL)\")\n\n if @ermDBResult.size < 1\n @defaultRightsText = \"DatabaseCode and ProviderCode returns nothing\"\n end\n end\n end\n\n @column_names = ::Erm_data.column_names.collect(&:to_sym)\n\n end", "def run\n super\n\n # first, ensure we're fingerprinted\n require_enrichment\n\n uri = _get_entity_name\n\n headers = {}\n headers[\"Content-Type\"] = \"%{#context['com.opensymphony.xwork2.dispatcher.HttpServletResponse'].addHeader('X-Intrigue-Struts',888*888)}.multipart/form-data\"\n response = http_request(:get, uri, nil, headers) # no auth\n\n unless response\n _log_error \"No response received\"\n return\n end\n\n # show the response in the logs \n response.headers.each {|x| _log \"#{x}: #{response.headers[x]}\"}\n \n if response.headers['X-Intrigue-Struts'] =~ /788544/\n \n instance_details = { \n proof: \"#{response.headers['X-Intrigue-Struts']}\",\n }\n _create_linked_issue \"apache_struts_jakarta_parser\", instance_details\n end\n end", "def service_request(service); end", "def create_sesame_con\n @os_conn = EventMachine::HttpRequest.new($open_sesame_url)\n end", "def getComponentArgument(node, className) \n found = nil\n for node.each_component do |comp|\n found = comp if comp.classname == className\n end\n if found\n return comp.arguments\n puts \"No component with #{className} found on {#node.name}\"\n return []\n end\n end\n \n class RehydrateSociety < Cougaar::Action\n PRIOR_STATES = [\"SocietyRunning\"]\n RESULTANT_STATE = \"SocietyPlanning\"\n DOCUMENTATION = Cougaar.document {\n @description = \"This action is used in place of OPlan/GLS actions if you start a society from a persistent state.\"\n @example = \"do_action 'RehydrateSociety'\"\n }\n def perform\n end\n end\n \n class SendOPlan < Cougaar::Action\n PRIOR_STATES = [\"OPlanReady\"]\n RESULTANT_STATE = \"OPlanSent\"\n DOCUMENTATION = Cougaar.document {\n @description = \"Sends the OPlan to the glsinit servlet.\"\n @example = \"do_action 'SendOPlan'\"\n }\n def perform\n begin\n result = Cougaar::Communications::HTTP.get(\"http://#{@run.society.agents['NCA'].node.host.host_name}:#{@run.society.cougaar_port}/$NCA/glsinit?command=sendoplan\")\n raise_failure \"Error sending OPlan\" unless result\n rescue\n raise_failure \"Could not send OPlan\", $!\n end\n end\n end\n \n class PublishGLSRoot < Cougaar::Action\n PRIOR_STATES = [\"GLSReady\"]\n RESULTANT_STATE = \"SocietyPlanning\"\n DOCUMENTATION = Cougaar.document {\n @description = \"Publishes the GLS root task to the glsinit servlet.\"\n @example = \"do_action 'PublishGLSRoot'\"\n }\n def perform\n gls_client = @run['gls_client']\n begin\n host_uri = \"http://#{@run.society.agents['NCA'].node.host.host_name}:#{@run.society.cougaar_port}\"\n if gls_client.c0_date\n result = Cougaar::Communications::HTTP.get(\"#{host_uri}/$NCA/glsinit?command=publishgls&oplanID=#{gls_client.oplan_id}&c0_date=#{gls_client.c0_date}\")\n else\n result = Cougaar::Communications::HTTP.get(\"#{host_uri}/$NCA/glsinit?command=publishgls&oplanID=#{gls_client.oplan_id}\")\n end\n raise_failure \"Error publishing OPlan\" unless result\n rescue\n raise_failure \"Could not publish OPlan\", $!\n ensure\n gls_client.close\n end", "def platform_endpoint; end", "def ice\n\tend", "def transact; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def data\n fail NoMethodError, \"Engines need this method defined\"\n end", "def implementation; end", "def implementation; end", "def doors; end", "def operations; end", "def operations; end", "def alchemy\r\n end", "def openid_endpoint=(_arg0); end", "def service_name; end", "def entity content\n end", "def run\n super\n\n x = Ear::Client::Corpwatch::CorpwatchService.new\n corps = x.search @object.name\n\n # Attach to the first object\n @object.physical_locations << create_object(PhysicalLocation, {\n :address => corps.first.address, \n :state => corps.first.state, \n :country => corps.first.country })\n\n # Save off our raw data\n #@task_run.save_raw_result corps.join(\" \")\n\nend", "def openid_endpoint; end", "def driver; end", "def run\n super\n\n entity_name = _get_entity_name\n opt_create_entities = _get_option(\"create_entities\")\n \n # Make sure the key is set\n api_key = _get_task_config(\"publicwww_api_key\")\n\n # special case google analytics, as we can find interesting things by not \n # sending the last bit of the key\n if entity_name =~ /^ua-.*$/i\n entity_name = entity_name.split(\"-\")[0..-2].join(\"-\")\n _log \"Dropping trailing part of google user agent: #{entity_name}\"\n end\n\n\n # Craft the UniqueToken search URL to export\n query_url = \"https://publicwww.com/websites/%22#{entity_name}-%22/?export=urls&key=#{api_key}\"\n \n # Download the xport\n download = http_get_body(query_url)\n \n # read the file results\n download.split(\"\\n\").each do |found_url|\n _create_entity(\"Uri\" , \"name\" => found_url) if opt_create_entities\n end\n\n # store links as an extended detail\n _set_entity_detail(\"public_www_results\", { entity_name => download.split(\"\\n\")[1..30] } )\n\n end", "def refutal()\n end", "def credential; end", "def credential; end", "def gPXE; iPXE; end", "def context; end", "def context; end", "def context; end", "def context; end", "def context; end" ]
[ "0.6194225", "0.61586684", "0.615679", "0.6002673", "0.59442455", "0.5940392", "0.5846928", "0.5846928", "0.5846928", "0.5846928", "0.5834069", "0.5809064", "0.5748612", "0.57210004", "0.57082444", "0.5693672", "0.5679735", "0.56640464", "0.56640464", "0.56640464", "0.56262773", "0.5595417", "0.55937654", "0.55815494", "0.55774343", "0.55746543", "0.55746543", "0.55728304", "0.55701536", "0.5569336", "0.5569336", "0.5569336", "0.5569336", "0.55456334", "0.5545011", "0.55348283", "0.552144", "0.5518882", "0.5517975", "0.5517975", "0.5517683", "0.5503598", "0.5479598", "0.5459438", "0.5454739", "0.54421175", "0.54367477", "0.5429622", "0.54286927", "0.54261523", "0.54220104", "0.5412693", "0.5412693", "0.5412693", "0.5412693", "0.5412693", "0.5412693", "0.5412693", "0.5412693", "0.5411375", "0.5398249", "0.5376758", "0.5376428", "0.5372127", "0.5370708", "0.537067", "0.53589785", "0.5349018", "0.5349018", "0.5349018", "0.5349018", "0.5349018", "0.5349018", "0.5349018", "0.5349018", "0.5349018", "0.5349018", "0.5349018", "0.53488415", "0.53485423", "0.53485423", "0.53396255", "0.5336976", "0.5336976", "0.5332423", "0.53319013", "0.53212786", "0.532055", "0.53147155", "0.53112257", "0.53070945", "0.53062767", "0.53013885", "0.5300753", "0.5300753", "0.5300436", "0.5298965", "0.5298965", "0.5298965", "0.5298965", "0.5298965" ]
0.0
-1
Callback that github_jenkins uses
def build_success(commit, build, callback) repo = commit.repo_name branch = commit.branch return unless (app = @apps[repo]) return unless branch == app.auto_deploy callback.call("#{"DEPLOY".irc_cyan.irc_bold} - Attempting automatic deploy of #{app.name}") callback.call(app.deploy!(commit.pusher, callback).tap do |status| if status =~ /started for/ callback.call(SQUIRRELS.sample) plugin_send(:Notifier, :notify, "pre_deploy") plugin_send(:NewRelicDeployPerformance, :pre_deploy, app.name) end end) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def any_status_hook\n repo = params[:name]\n link = \"https://github.com/#{repo}\"\n sha = params[:sha]\n state = params[:state]\n context = params[:context]\n description = params[:description]\n target = params[:target_url]\n\n return if state == 'pending' || (state == 'success' && context == 'github/pages')\n\n if repo == 'Charcoal-SE/metasmoke' && context.start_with?('ci/circleci')\n ci_counter = Redis::CI.new(sha)\n if state == 'success'\n ci_counter.sucess_count_incr\n return unless ci_counter.sucess_count == 3\n context = 'ci/circleci'\n else\n ci_counter.sucess_count_reset\n end\n end\n\n message = \"[ [#{repo.sub('Charcoal-SE/', '')}](#{link}) ]\"\n message += \" #{context} \"\n message += if target.present?\n \"[#{state}](#{target})\"\n else\n state\n end\n message += \" on [#{sha.first(7)}](#{link}/commit/#{sha.first(10)})\"\n message += \": #{description}\" if description.present?\n\n ActionCable.server.broadcast 'smokedetector_messages', message: message\n end", "def update_hooks\n hook_url = \"https://your.domain/jira/gitlab_hook\"\n\n gl_api_endpoint = 'https://gitlab.your.domain/api/v3'\n gl_admin_token = 'xxxxxxxxxxxxxxxxxxxx'\n\n gl = Jk::Gitlabz.new(gl_api_endpoint, gl_admin_token)\n\n # Added our custom push hook url to each repo\n gl.get_project_name_id_hash().each { |repo, proj_id|\n gl.add_hook_to_proj(proj_id, hook_url)\n }\nend", "def test\n @config.for_each_bitbucket_repo do |bitbucket, repo_info|\n if repo_info[:jenkins_ci_url].nil?\n error \"Repository #{repo_info[:name]} does not have any Jenkins CI URL configured.\"\n else\n Credentials.with_credentials_for(:jenkins_ci, @logger, @logger_stderr, url: repo_info[:jenkins_ci_url]) do |jenkins_user, jenkins_password|\n # Get its config\n doc = Nokogiri::XML(URI.parse(\"#{repo_info[:jenkins_ci_url]}/config.xml\").open(http_basic_authentication: [jenkins_user, jenkins_password]).read)\n # Check that this job builds the correct Bitbucket repository\n assert_equal(\n doc.xpath('/org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject/sources/data/jenkins.branch.BranchSource/source/serverUrl').text,\n bitbucket.bitbucket_url,\n \"Job #{repo_info[:jenkins_ci_url]} does not build repository from Bitbucket\"\n )\n assert_equal(\n doc.xpath('/org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject/sources/data/jenkins.branch.BranchSource/source/repoOwner').text.downcase,\n repo_info[:project].downcase,\n \"Job #{repo_info[:jenkins_ci_url]} does not build repository from project #{repo_info[:project]}\"\n )\n assert_equal(\n doc.xpath('/org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject/sources/data/jenkins.branch.BranchSource/source/repository').text,\n repo_info[:name],\n \"Job #{repo_info[:jenkins_ci_url]} does not build repository named #{repo_info[:name]}\"\n )\n rescue\n error \"Error while checking Jenkins CI job for #{repo_info[:project]}/#{repo_info[:name]} from URL #{repo_info[:jenkins_ci_url]}: #{$ERROR_INFO}\"\n end\n end\n end\n end", "def add_hook_for_server_check target, project_name, branch = 'master', log: '/tmp/log', host: 'http://localhost'\n File.open \"#{target}/hooks/post-receive\", 'w' do |file|\n file.write <<-HOOK\n#!/bin/bash\n\nwhile read oldrev newrev refname\ndo\n branch=$(git rev-parse --symbolic --abbrev-ref $refname)\n if [ \"$branch\" == \"#{branch}\" ]; then\n echo \"curl -X PATCH '#{host}/api/projects/#{project_name}/#{branch}'\" >>\"#{log}\"\n curl -X PATCH \"#{host}/api/projects/#{project_name}/#{branch}\" >>\"#{log}\" 2>&1 &\n fi\ndone\n HOOK\n file.chmod 0755\n end\n true\n end", "def gollum_hook\n # This only fires when we want to update the charcoal-se.org website, so we just unconditionally\n # kick off a build of the charcoal-se.org website.\n APIHelper.authorized_post(\n 'https://api.github.com/repos/Charcoal-SE/charcoal-se.github.io/actions/workflows/build.yml/dispatches',\n data: { 'ref' => 'site' }\n )\n end", "def git\n\tend", "def set_hook\n @project = Project.find(params[:project_id])\n @new_repo_name = params[:repo_name]\n @new_user_name = params[:user_name]\n\n @is_linked = false\n json_repos = {}\n begin\n json_repos = JSON.parse(@project.repo_name)\n rescue \n end\n json_repos.each do |j|\n if j[\"repo\"] == @new_repo_name\n @is_linked = true\n end\n end\n\n if @is_linked\n @old_repo_name = @new_repo_name\n Project.delete_hooks(@project, @new_user_name, @new_repo_name ) \n else\n Project.change_repo_name(@project, @new_repo_name, @new_user_name)\n Project.create_hook(@project, @new_repo_name, @new_user_name)\n end\n #respond_with @project\n end", "def ci_hook\n case request.headers['HTTP_X_GITHUB_EVENT']\n when 'pull_request'\n data = JSON.parse(request.raw_post)\n pull_request = data['pull_request']\n case data['action']\n when 'opened', 'synchronize'\n commits = JSON.parse(Net::HTTP.get_response(URI.parse(pull_request['commits_url'])).body)\n commits.each do |commit|\n APIHelper.authorized_post(\n \"https://api.github.com/repos/Charcoal-SE/SmokeDetector/statuses/#{commit['sha']}\",\n state: 'pending',\n description: 'An Approve review is required before pull requests can be merged.',\n context: 'metasmoke/ci'\n )\n end\n render plain: \"#{commits.length} commits set to pending.\"\n else\n render(plain: 'Not a newly-opened or updated PR; not interested.') && return\n end\n when 'pull_request_review'\n data = JSON.parse(request.raw_post)\n pull_request = data['pull_request']\n review = data['review']\n if data['action'] == 'submitted' && review['state'] == 'approved'\n commits = JSON.parse(Net::HTTP.get_response(URI.parse(pull_request['commits_url'])).body)\n commits.each do |commit|\n APIHelper.authorized_post(\n \"https://api.github.com/repos/Charcoal-SE/SmokeDetector/statuses/#{commit['sha']}\",\n state: 'success',\n description: 'PR approved :)',\n context: 'metasmoke/ci'\n )\n end\n\n render plain: \"#{commits.length} commits approved.\"\n else\n render(plain: 'Not a submitted Approve review; not interested.') && return\n end\n else\n render(plain: \"Pretty sure we don't subscribe to that event.\") && return\n end\n end", "def github\n process_oauth_callback\n end", "def handle_repo_push_request\n return unless @repository\n\n branch_name = payload[\"ref\"].sub(%r{\\Arefs/heads/}, '')\n branch = @repository.branches.where(name: branch_name).first\n if branch.present? && branch.convergence? && @repository.run_ci?\n sha = payload[\"after\"]\n branch.kickoff_new_build_unless_currently_busy(sha)\n end\n end", "def build_status_report(sha, state)\n $github_client.create_status(\n self.repo.name, sha,\n state, \n { context: \"Perkins CI\", \n description: github_state_description , \n target_url: github_state_url \n }\n ) rescue \"error sending github state!!!! notify this\"\n puts \"Sending Github #{state} status to #{self.repo.name}\".green\n end", "def project_hook(project)\n # STUB\n end", "def github_push(payload)\n\n pushType = payload[\"repository\"][\"full_name\"].split(\"/\")[1].split(\"-\")[0]\n if pushType == \"assignment\"\n TestGraderWorker.perform_async(payload)\n end\n\n org = payload[\"repository\"][\"organization\"]\n repo = payload[\"repository\"][\"name\"]\n repo_array = repo.split(\"-\")\n\n project_name = repo_array[0]\n type = repo_array[1]\n user = repo_array[2]\n\n expected_repo = \"#{org}/#{project_name}-expected\" \n student_repo = \"#{org}/#{project_name}-#{user}\"\n grade_repo = \"#{org}/#{project_name}-grade\"\n #results_repo = \"#{org}/#{project_name}-results-#{type}\"\n\n organization = Organization.new.github_client\n case type\n when \"grader\"\n if not organization.repository?(expected_repo)\n organization.create_repository(\n \"#{project_name}-expected\", organization: org, auto_init: true)\n end\n when \"expected\"\n when \"grade\"\n #when \"results\"\n # if not organization.repository?(grade_repo)\n # organization.create_repository(\n # \"#{project_name}-grade\", organization: org, auto_init: true)\n # end\n else\n if not organization.repository?(grade_repo)\n organization.create_repository(\n \"#{project_name}-grade\", organization: org, auto_init: true)\n end\n end\n\tend", "def test\n @config.for_each_github_repo do |client, repo_info|\n log_debug \"Checking CI for Github repository #{repo_info[:slug]}\"\n last_status = client.repository_workflow_runs(repo_info[:slug])[:workflow_runs].\n select { |run| run[:head_branch] == 'master' }.\n max_by { |run| run[:created_at] }[:conclusion]\n error \"Last workflow status for repository #{repo_info[:slug]} is #{last_status}\" unless last_status == 'success'\n end\n end", "def update_github\n unless environment_is_production\n puts 'NOT updating github because environment is not production'\n return false\n end\n\n puts 'pushing database to github'\n\n @scraper_log.info \"------------------------------\"\n @scraper_log.info \"updating git\"\n @scraper_log.info \"------------------------------\"\n x = Subexec.run \"git add #{@db_dump_file} #{@status_file_name}\"\n x = Subexec.run \"git commit -m 'Updated database dump file and status.json with new hr.gov.ge data'\"\n x = Subexec.run \"git push origin master\"\nend", "def set_build_status!(repo: nil, sha: nil, state: nil, target_url: nil, description: nil, context: nil)\n state = state.to_s\n\n # Available states https://developer.github.com/v3/repos/statuses/\n available_states = [\"error\", \"failure\", \"pending\", \"success\"]\n raise \"Invalid state '#{state}'\" unless available_states.include?(state)\n\n # We auto receive the SLUG, so that the user of this class can pass a full URL also\n repo = repo.split(\"/\")[-2..-1].join(\"/\")\n\n # TODO: this will use the user's session, so their face probably appears there\n # As Josh already predicted, we're gonna need a fastlane.ci account also\n # that we use for all non-user actions.\n # This includes scheduled things, commit status reporting and probably more in the future\n\n if description.nil?\n description = \"All green\" if state == \"success\"\n description = \"Still running\" if state == \"pending\"\n\n # TODO: what's the difference?\n description = \"Something went wrong\" if state == \"failure\"\n description = \"Something went wrong\" if state == \"error\"\n end\n\n # TODO: Enable once the GitHub token is fixed\n #\n # Full docs for `create_status` over here\n # https://octokit.github.io/octokit.rb/Octokit/Client/Statuses.html\n\n task = TaskQueue::Task.new(work_block: proc {\n logger.debug(\"Setting status #{state} on #{target_url}\")\n client.create_status(repo, sha, state, {\n target_url: target_url,\n description: description,\n context: context || \"fastlane.ci\"\n })\n })\n\n @task_queue.add_task_async(task: task)\n rescue StandardError => ex\n # TODO: how do we handle GitHub errors\n # In this case `create_status` will cause an exception\n # if the user doesn't have write permission for the repo\n raise ex\n end", "def githubize\n # method goes here\n end", "def git_clone_main\n raise \"oops, not done\"\nend", "def jenkins_download(opts)\n\tputs \"### Downloading jenkins image ###\"\n\trun_in_shell \"docker pull #{opts[:source]}\"\n\tputs \"#################################\"\nend", "def git(args, &block)\n Sprout::GitTask.define_task(args, &block)\nend", "def ready\n @jenkins_url.nil? == false\n end", "def github_webhook\n payload = JSON.parse(params[:payload])\n requested_branch = payload['ref'].split('/').last\n branch_is_valid = @project.git? && @project.watched_branches.include?(requested_branch)\n if branch_is_valid\n revision = payload['after']\n other_fields = { description: 'github webhook', user_id: current_user.id }\n CommitCreator.perform_once @project.id, revision, other_fields: other_fields\n end\n respond_to do |format|\n format.json do\n render status: :ok, json: { success: branch_is_valid }\n end\n end\n end", "def stash_webhook\n unless @project.git?\n render status: :bad_request, text: 'Repository url is blank'\n return\n end\n\n revision = params[:sha]\n if revision.blank?\n render status: :bad_request, text: 'SHA is blank'\n return\n end\n\n other_fields = { description: 'Requested due to a Pull Request on Stash.' }\n CommitCreator.perform_once @project.id, revision, other_fields: other_fields\n render status: :ok, text: 'Success'\n end", "def before_sha\n Gitlab::Git::BLANK_SHA\n end", "def github_released\n puts green(\"Release completed\")\n end", "def github_push(payload)\n pushType = payload[\"repository\"][\"full_name\"].split(\"/\")[1].split(\"-\")[0]\n if pushType == \"assignment\"\n TestGraderWorker.perform_async(payload)\n end\n\tend", "def build(graphite_timer)\n jenkins_name = ENV['JOB_NAME']\n\n # The main folder where all the building will take place\n jenkins_workspace = static_workspace_dir = ENV['WORKSPACE']\n \n jenkins_root = ENV['JENKINS_ROOT']\n jenkins_root = '/mnt/jenkins-home' if jenkins_root.nil? or jenkins_root.empty?\n\n puts \"\\nJenkins root: #{jenkins_root}\"\n\n # For projects have their projects in a sub folder of the repo workspace\n static_workspace_dir = ENV['PROJECT_PATH'] if ENV['PROJECT_PATH']\n\n # Gets the real project nam\n puts \"\\nLoading up static_conf.json\"\n static_deps = StaticDependencies::build_from_filesystem(static_workspace_dir)\n static_project_name = static_deps.project_name()\n\n # Detect whether this system is using GNU tools or not to deal with\n # differences between GNU and BSD options. (Ghetto detection from\n # http://stackoverflow.com/questions/8747845/how-can-i-detect-bsd-vs-gnu-version-of-date-in-shell-script)\n is_gnu = system \"date --version >/dev/null 2>&1\"\n puts \"This system is using non-GNU commands\" unless is_gnu\n\n # First stab at using major versions\n\n # Current static version should be set in the Jenkins build (most apps\n # can let it default to 1). If this matches the major_version below,\n # then current_qa will get updated by this build.\n current_static_version = ENV['CURRENT_STATIC_VERSION'] || 1\n current_static_version = current_static_version.to_i\n\n\n # The major version of this build is set in static_conf.json as \"major_version\".\n # (again most apps can leave this blank). This is the major version of this build\n major_version = static_deps.major_version or 1\n\n # Build number stuff\n build_name = \"#{major_version}.#{ENV['BUILD_NUMBER']}\"\n build_revision = ENV['GIT_COMMIT'] or ENV['SVN_REVISION']\n rev_str = \"rev: #{build_revision}\"\n\n puts \"\\nBuilding version #{build_name} of #{jenkins_name}\"\n\n # Temp dir to contain all the static manipulations, etc\n temp_dir = \"#{jenkins_workspace}/temp-for-static\"\n system \"rm -rf #{temp_dir}\"\n system \"mkdir #{temp_dir}\"\n\n # Custom tmp directory for hs-static\n hs_static_temp_dir = \"#{temp_dir}/hs-static-tmp\"\n\n # The ouput dir that will get uploaded to s3 and tarballed\n output_dir = \"#{temp_dir}/compiled-output\"\n system \"mkdir -p #{output_dir}\"\n\n debug_output_dir = \"#{temp_dir}/compiled-debug-output\"\n system \"mkdir -p #{debug_output_dir}\"\n\n # Move the static source to the temp dir\n source_dir = \"#{temp_dir}/src/#{static_project_name}\"\n system \"mkdir -p #{source_dir}\"\n system \"mv '#{static_workspace_dir}/static' #{source_dir}\"\n\n\n # Save some logs (still make sense with jenkins?)\n # logs_dir = '%s/logs' % parent_dir\n # system 'mkdir -p %s' % logs_dir)\n\n\n # Get the latest build names and download static depencencies\n archive_dir = \"#{temp_dir}/static-archive\"\n\n archive, all_build_names = graphite_timer.start 'downloading_static_deps' do\n archive = LocalStaticArchive.new archive_dir\n all_build_names = archive.update_dependencies_for source_dir\n [archive, all_build_names]\n end\n\n # Build name params to pass to hs-static\n dep_build_name_args = \" -b #{static_project_name}:#{build_name} \"\n build_names_by_project = { static_project_name => \"static-#{build_name}\" }\n\n puts \"\\nAll build names #{all_build_names.inspect}\\n\"\n\n # Kinda assumes hash insert ordering (only available in ruby 1.9.3)\n all_build_names.each do |dep_name, dep_build_name|\n build_names_by_project[dep_name] = dep_build_name\n dep_source_dir = \"#{archive.archive_dir}/#{dep_name}/\"\n dep_build_name_args += \" -b #{dep_name}:#{dep_build_name} \"\n end\n\n static_mode = \"\"\n static_mode = \"-m compressed\" unless ENV['DONT_COMPRESS_STATIC']\n\n building_debug_assets = (not static_mode.empty?)\n \n # If we are compressing assets (which we are most of the time), also compile non-compressed versions for QA/prod hsDebug usage\n if building_debug_assets\n puts \"\\nPrecompiling assets to #{debug_output_dir}...\"\n\n cmd = \"./hs-static -m development -a #{archive_dir} -p #{source_dir} -t #{debug_output_dir} -r #{static_project_name} #{dep_build_name_args} --temp #{hs_static_temp_dir} precompile_assets_only\"\n\n puts \"(via #{cmd})\"\n\n graphite_timer.start 'precompile_debug_assets' do\n raise \"Error precompiling debug assets\" unless system cmd\n end\n end\n\n\n # Run the task to precompile assets\n puts \"\\nPrecompiling assets to #{output_dir}...\"\n\n cmd = \"./hs-static #{static_mode} -a #{archive_dir} -p #{source_dir} -t #{output_dir} -r #{static_project_name} #{dep_build_name_args} --temp #{hs_static_temp_dir} precompile\"\n\n puts \"(via #{cmd})\"\n\n graphite_timer.start 'precompile_compressed_assets' do\n raise \"Error precompiling assets\" unless system cmd\n end\n\n # Just in case it wasn't created\n system \"mkdir -p #{output_dir}/#{static_project_name}/static-#{build_name}/\"\n\n current_md5_hash = nil\n begin\n current_md5_hash = File.open(\"#{output_dir}/#{static_project_name}/static-#{build_name}/premunged-static-contents-hash.md5\", &:readline) \n rescue \n puts \"\\n Couldn't find #{output_dir}/#{static_project_name}/static-#{build_name}/premunged-static-contents-hash.md5, this might be an empty static project\"\n end\n\n former_md5_hash = graphite_timer.start 'fetch_latest_built_md5' do\n StaticDependencies::fetch_latest_built_md5_for_project(static_project_name, major_version)\n end\n\n puts \"\\ncurrent_md5_hash: #{current_md5_hash.inspect}\"\n puts \"\\nformer_md5_hash: #{former_md5_hash.inspect}\\n\"\n\n hash_is_the_same = current_md5_hash && former_md5_hash && current_md5_hash == former_md5_hash\n\n current_static_deps = all_build_names\n former_static_deps = graphite_timer.start 'fetch_latest_build_dependencies_file' do\n StaticDependencies::fetch_latest_built_dependencies(static_project_name, major_version)\n end\n\n puts \"\\n\", \"current_static_deps: #{current_static_deps.inspect}\"\n puts \"\\n\", \"former_static_deps: #{former_static_deps.inspect}\", \"\\n\"\n\n deps_are_the_same = current_static_deps && former_static_deps && current_static_deps == former_static_deps\n\n if hash_is_the_same and deps_are_the_same and not ENV['FORCE_S3_UPLOAD']\n puts \"\\nContents and depencencies are identical to previous build. Skipping s3 upload.\\n\\n\"\n\n graphite_timer.start 'fetch_previous_build_conf' do\n download_previous_build_conf static_project_name, major_version, \"#{source_dir}/static/\"\n end\n\n copy_over_conf_to_python_module static_project_name, static_workspace_dir, \"#{source_dir}/static/\"\n return false\n end\n\n if ENV['RUN_JASMINE_TESTS'] \n print \"\\n\", \"Running jasmine tests\\n\"\n graphite_timer.start 'jasmine_test_duration' do\n # Run a jasmine test using the just compiled output\n cmd = \"./hs-static -m precompiled -p #{source_dir} -t #{output_dir} --headless -a #{archive_dir} -b #{static_project_name}:#{build_name} jasmine\"\n puts \"(via #{cmd})\"\n\n # Stream the jasmine output\n IO.popen cmd do |f|\n f.each do |line|\n puts line\n end\n end\n\n exit_code = $?\n # print \"\\n\", \"Exit code: #{exit_code.inspect}\", \"\\n\\n\"\n\n raise \"Error running jasmine tests\" unless exit_code.success?\n end\n end\n\n\n now_str = Time.now.to_s\n info_str = \"#{static_project_name}-#{build_name} #{rev_str} #{now_str}\"\n\n # Log the build info for this specific build\n system \"echo #{info_str} > #{output_dir}/#{static_project_name}/static-#{build_name}/info.txt\"\n\n # Log of all of build names, dates, and revsions for each project\n # system \"echo #{info_str} >> #{logs_dir}/#{static_project_name}\"\n\n # Grab the most edge version build (of any major_version)\n current_edge_version = StaticDependencies::fetch_latest_production_build(static_project_name, nil)\n\n # If this is the first time this project has been built or if this is the most edge version, create the edge pointers\n is_edge_version = current_edge_version.nil? || StaticDependencies::compare_build_names(\"static-#{build_name}\", current_edge_version) == 1\n\n puts \"\\nThis #{build_name} > #{current_edge_version} => #{is_edge_version}\"\n\n if is_edge_version\n # Note, there should be no difference between \"-qa\" and non \"-qa\" edge pointers\n system \"echo static-#{build_name} > #{output_dir}/#{static_project_name}/latest-qa\" # Deprecated\n system \"echo static-#{build_name} > #{output_dir}/#{static_project_name}/latest\" # Deprecated\n system \"echo static-#{build_name} > #{output_dir}/#{static_project_name}/edge-qa\"\n system \"echo static-#{build_name} > #{output_dir}/#{static_project_name}/edge\"\n end\n\n system \"echo static-#{build_name} > #{output_dir}/#{static_project_name}/latest-version-#{major_version}-qa\"\n\n # Write a shortcut for \"current-qa\" if we are deploying the current version\n is_current_version = current_static_version == major_version\n\n if is_current_version\n system \"echo static-#{build_name} > #{output_dir}/#{static_project_name}/current-qa\"\n else\n puts \"\\n\", \"Current static version (#{current_static_version}) doesn't match this build's major version (#{major_version}), skipping the 'current-qa' pointer\"\n end\n\n # If this is the first time this major version has been built, create the prod pointer(s) as well\n if not StaticDependencies::fetch_latest_production_build(static_project_name, major_version)\n puts \"\\n\", \"This is the first time building major version #{major_version}, creating the prod latest-version-#{major_version} pointer\"\n\n system \"echo static-#{build_name} > #{output_dir}/#{static_project_name}/latest-version-#{major_version}\"\n\n if major_version == 1\n puts \"Also building the current pointer for the first time\"\n system \"echo static-#{build_name} > #{output_dir}/#{static_project_name}/current\"\n end\n end\n\n\n # Build a fixed-in-time static_conf.json (and prebuilt_recursive_static_conf.json) in the compiled output\n static_deps.create_static_deps_file_with_build \"#{output_dir}/#{static_project_name}/static-#{build_name}/static_conf.json\", build_name\n StaticDependencies::create_recursive_fixed_static_deps_file \"#{output_dir}/#{static_project_name}/static-#{build_name}/prebuilt_recursive_static_conf.json\", static_project_name, build_name, all_build_names\n\n # Zip up the whole compiled static dir\n archive_name = \"#{static_project_name}-static-#{build_name}.tar.gz\"\n system \"cd #{output_dir}; tar cvzf #{archive_name} --exclude=.svn --exclude=.git #{static_project_name}/\"\n\n # Copy all the latest and current pointers to the source output\n system \"cp #{output_dir}/#{static_project_name}/latest-version-* #{source_dir}/\"\n\n if is_edge_version\n system \"cp #{output_dir}/#{static_project_name}/latest* #{source_dir}/\"\n system \"cp #{output_dir}/#{static_project_name}/edge* #{source_dir}/\"\n end\n\n if is_current_version\n system \"cp #{output_dir}/#{static_project_name}/current* #{source_dir}/\"\n end\n\n # Copy over the fixed static_conf.json files and info.txt to the source output\n system \"cp #{output_dir}/#{static_project_name}/static-#{build_name}/static_conf.json #{source_dir}/static/static_conf.json\"\n system \"cp #{output_dir}/#{static_project_name}/static-#{build_name}/prebuilt_recursive_static_conf.json #{source_dir}/static/prebuilt_recursive_static_conf.json\"\n system \"cp #{output_dir}/#{static_project_name}/static-#{build_name}/info.txt #{source_dir}/static/info.txt\"\n\n copy_over_conf_to_python_module static_project_name, static_workspace_dir, \"#{source_dir}/static/\"\n\n # Copy over the two static_conf.json files to the top level workspace (so they get included in the egg)\n # TODO: I think this isn't needed anymore (the copy_over_conf_to_python_module func should handle it)\n system \"mkdir -p #{static_workspace_dir}/static/\"\n system \"cp #{output_dir}/#{static_project_name}/static-#{build_name}/static_conf.json #{static_workspace_dir}/static/static_conf.json\"\n system \"cp #{output_dir}/#{static_project_name}/static-#{build_name}/prebuilt_recursive_static_conf.json #{static_workspace_dir}/static/prebuilt_recursive_static_conf.json\"\n\n # Make the source directory have a build name\n system \"cd #{source_dir}; mv static static-#{build_name}\"\n\n puts \"\\nSed-replacing the source folder... \"\n\n # Munge build names throughout the entire source project (for all recursive deps)\n graphite_timer.start 'sed_replacements' do\n build_names_by_project.each do |dep_name, dep_build_name|\n string1 = \"#{dep_name}\\\\/static\\\\/\" \n string2 = \"#{dep_name}\\\\/#{dep_build_name}\\\\/\" \n\n sed_cmd = \"find #{source_dir}/static-#{build_name} -type f -print0 | xargs -0 sed -i'.sedbak' 's/#{string1}/#{string2}/g'\"\n puts sed_cmd\n\n unless system sed_cmd\n raise \"Error munging build names for #{dep_name} to #{dep_build_name}\"\n end\n\n system \"find #{source_dir} -type f -name '*.sedbak' -print0 | xargs -0 rm\"\n end\n end\n\n # Zip up the build-name-ified source\n source_archive_name = \"#{static_project_name}-static-#{build_name}-src.tar.gz\"\n system \"cd #{source_dir}/..; tar cvzf #{source_archive_name} --exclude=.svn --exclude=.git #{static_project_name}/\"\n system \"mv #{source_dir}/../#{source_archive_name} #{output_dir}\"\n\n # Copy over the debug assets (wait till right before the upload to not goof up the hash checking)\n if building_debug_assets and Dir.exist?(\"#{debug_output_dir}/#{static_project_name}/static-#{build_name}\")\n puts \"\\nCopying debug assets over to #{output_dir}/static-#{build_name}-debug\\n\"\n system \"mv #{debug_output_dir}/#{static_project_name}/static-#{build_name} #{output_dir}/#{static_project_name}/static-#{build_name}-debug\"\n\n # Change debug links from /static-x.y/ -> /static-x.y-debug/\n puts \"\\nPointing links in *.bundle-expanded.html to the debug folder\"\n\n string1 = \"\\\\/static-([0-9]+\\\\.[0-9]+)\\\\/\"\n string2 = \"\\\\/static-\\\\1-debug\\\\/\"\n\n sed_cmd = \"find #{output_dir}/#{static_project_name}/static-#{build_name} -type f -iname '*.bundle-expanded.html' -print0 | xargs -0 sed -i'.sedbak' -r 's/#{string1}/#{string2}/g'\"\n\n # Macs use a different flag for extended regexes\n sed_cmd.sub!(' -r ', ' -E ') unless is_gnu\n\n puts sed_cmd\n\n graphite_timer.start 'debug_build_sed_replacements' do\n puts \"Error munging build names from \\\"/static/\\\" to \\'static-#{build_name}\\\". Continuing...\" unless system sed_cmd\n end\n\n system \"find #{output_dir}/#{static_project_name}/static-#{build_name} -type f -name '*.sedbak' -print0 | xargs -0 rm\"\n end\n\n\n # upload the assets to S3 (too lazy to port to ruby at this point)\n puts \"Uploading assets to s3...\\n\\n\"\n cmd = \"cd #{output_dir}; python26 #{jenkins_root}/hubspot_static_daemon/script/upload_project_assets_to_s3_parallel.py -p \\\"#{static_project_name}\\\" \"\n\n graphite_timer.start 'uploading_to_s3' do\n raise \"Error uploading static files to S3!\" unless system cmd\n end\n\n puts \"Invalidating QA scaffolds (so that QA gets the latest code immediately)...\"\n\n cmd = \"bash #{PYTHON_DEPLOY_STATIC_PATH} #{static_project_name}\"\n puts \"Running: #{cmd}\"\n\n graphite_timer.start 'invalidate_static_scaffolds' do\n puts \"Couldn't invalidate static scaffolds on QA, updates won't show up immediately.\" unless system cmd\n end\n\n puts \"\\n\"\n return true\nend", "def process_github_clones\n repos = get_github_repos_already_cloned\n repos.each do |r|\n # SMELL: does not work if the working copy directory does\n # not match the repo name\n clone_path = configatron.dir + r.name\n set_upstream(clone_path, r.parent.html_url)\n end\nend", "def process!\n Sync::Jenkins.job_by_name(payload[\"name\"])\n end", "def giturl(project_name, repo_name) ; end", "def commit_status(sha, ref)\n # implement inside child\n end", "def my_post_build_step\n puts 'post-build step!'\nend", "def repo=(_arg0); end", "def repo=(_arg0); end", "def repo=(_arg0); end", "def repo=(_arg0); end", "def run\n super\n\n entity_name = _get_entity_name\n\n # Search users\n search_uri = \"https://api.github.com/search/users?q=#{entity_name}\"\n response = _get_response(search_uri)\n _parse_items(response[\"items\"],\"GithubUser\")\n\n # Search respositories\n search_uri = \"https://api.github.com/search/repositories?q=#{entity_name}\"\n response = _get_response(search_uri)\n _parse_items(response[\"items\"],\"GithubRepository\")\n\n #search_uri = \"https://api.github.com/search/issues?q=#{entity_name}\"\n #response = _search_github(search_uri,\"GithubIssue\")\n #_parse_items response[\"items\"]\n\n\n end", "def change_git!\n @jobs.each_value do |job|\n job[:value][:scm_branch] = \"origin/pr/#{@number}/head\"\n job[:value][:scm_params] = {} unless job[:value][:scm_params]\n job[:value][:scm_params][:refspec] = 'refs/pull/*:refs/remotes/origin/pr/*'\n end\n end", "def action_create\n job_name = \"#{@new_resource.job_name}\"\n remote_host = \"#{@new_resource.remote_host}\"\n job_config = \"#{node[:jenkins][:server][:home]}/#{@new_resource.job_name}-config.xml\"\n \n run_commands = Array.new\n to_store_scripts = Array.new\n \n @new_resource.commands.each do |command|\n if (command[:type] == 'script')\n\t to_store_scripts << \"#{command[:content]}\"\n\t command[:fullPath] = \"#{node[:jenkins][:node][:home]}/jenkins-scripts/#{command[:content]}\"\n\telse\n\t command[:fullPath] = \"#{command[:content]}\"\n\tend\n \n if (command[:type] == 'script' && command[:action] == 'run') || command[:type] == 'command'\n run_commands << command\n end\n end\n\n template job_config do\n source \"#{new_resource.config_template}\"\n variables :job_name => job_name, :remote_host => remote_host, :commands => run_commands\n\towner node[:jenkins][:server][:user]\n group node[:jenkins][:server][:group]\n end\n \n \n # Create sh files and upload them to remote host\n to_store_scripts.each do |script|\n \n # create scripts on jenkins server\n cookbook_file \"#{node[:jenkins][:server][:home]}/jenkins-scripts/#{script}\" do\n source \"#{script}\"\n owner node[:jenkins][:server][:user]\n group node[:jenkins][:server][:group]\n action :create\n\t mode \"0755\"\n end\n \n #upload scripts to host only if host is reachable\n\tbash \"upload script #{script} on server #{remote_host}\" do\n user node[:jenkins][:server][:user]\n cwd \"#{node[:jenkins][:server][:home]}/jenkins-scripts/\"\n\t code <<-EOH\nscp #{script} #{node[:jenkins][:node][:user]}@#{remote_host}:#{node[:jenkins][:node][:home]}/jenkins-scripts\nssh #{node[:jenkins][:node][:user]}@#{remote_host} chmod 755 #{node[:jenkins][:node][:home]}/jenkins-scripts/*\nEOH\n only_if \"ping -q -c1 #{remote_host}\"\n end\n end\n\n jenkins_job \"#{@new_resource.job_name}\" do\n action :update\n config job_config\n end \n \n file job_config do\n action :delete\n\tbackup false\n end\r\nend", "def push\n ensure_git_and_cucumber_available\n ensure_repository\n\n puts \"Not implemented yet... pull request for push please!\"\n end", "def build_results\n CircleCi::Project.recent_builds_branch('salsify', 'dandelion', 'develop')\n end", "def github_post\n {\n \"create\" => ->(release) { start_deployment(release) },\n \"update_status\" => ->(release) { update_deployment(release) }\n }\n end", "def trigger_build_for_job(job, params = {})\n raise RuntimeError,\n \"No Jenkins client is available\" if @jenkins_client.nil?\n\n raise RuntimeError,\n \"Jenkins client is not ready\" unless @jenkins_client.ready\n\n response = @jenkins_client.trigger_build_for_job(job, params)\n\n # HTTP 302 is success(??) message\n # anything else should be considered an error\n unless response.instance_of?(Net::HTTPFound)\n raise RuntimeError,\n \"Jenkins responded with Error Message:\\n#{response.body}\"\n end\n \n response\n end", "def capture_build\n # limit is current HB total workflow\n #TODO dont need increased limit\n cmd = if ENV['CAPTURE_CURRENTLY_RUNNING']\n \"curl 'https://circleci.com/api/v1.1/project/github/#{ORG}/#{PROJECT}/tree/#{BRANCH}?circle-token=#{CIRCLE_TOKEN}&limit=20'\"\n else\n \"curl 'https://circleci.com/api/v1.1/project/github/#{ORG}/#{PROJECT}/tree/#{BRANCH}?circle-token=#{CIRCLE_TOKEN}&limit=9'\"\n end\n puts cmd\n data = `#{cmd}`\n data = JSON.parse(data)\n if ENV['CAPTURE_CURRENTLY_RUNNING']\n # ignore all builds that aren't the current git sha\n data.reject!{ |i| (i['all_commit_details'].first==nil || !i['all_commit_details'].last['commit'].starts_with?(ENV['CAPTURE_CURRENTLY_RUNNING'])) }\n else\n data.reject!{ |i| i['start_time'].nil? || Time.iso8601(i['start_time']).to_i < (@last_built_at + 10) }\n end\n\n tests_jobs = data.select{ |job| JOBS.include?(job['workflows']['job_name']) }\n metric_job = data.select{ |job| job['workflows']['job_name']==JOBS.first }.first\n raise \"one of the jobs isn't running yet\" unless tests_jobs.length == JOBS.length\n tests_jobs.each do |job|\n raise \"still running #{job}\" unless (job['outcome']=='success' || job['outcome']=='failed')\n end\n\n outcome = if JOBS_ALL_PASS\n tests_jobs.select { |job| job['outcome']=='success' }.length == JOBS.length ? 'success' : 'failed'\n else\n metric_job['outcome']\n end\n\n puts \"recording: #{outcome}\"\n @stats << outcome\n @times << Time.iso8601(metric_job['stop_time']) - Time.iso8601(metric_job['start_time'])\n rescue => err\n puts \"waiting, #{err}\"\n sleep(15)\n retry\n end", "def perform(autobuild_id)\n autobuild = Autobuild.find(autobuild_id)\n webhook_secret = SecureRandom.hex(20)\n autobuild.update(webhook_secret: webhook_secret)\n\n if autobuild.code_repo_type == 'github'\n linked_app = autobuild.github_linked_app\n access_token = linked_app.access_token\n client = Octokit::Client.new(access_token: access_token)\n\n resp = client.create_hook(\n autobuild.code_repo_name,\n 'web',\n {\n url: \"https://#{ENV['DOMAIN_NAME']}/github/webhooks/#{autobuild.id}\",\n content_type: 'json',\n secret: webhook_secret\n },\n {\n events: ['push', 'pull_request'],\n active: true\n })\n elsif autobuild.code_repo_type == 'gitlab'\n linked_app = autobuild.gitlab_linked_app\n access_token = linked_app.access_token\n code_repo_name = autobuild.code_repo_name\n\n # TODO: Should probably use a client\n Gitlab.endpoint = \"https://gitlab.com/api/v4\"\n Gitlab.private_token = access_token\n\n begin\n user = Gitlab.user\n rescue Gitlab::Error::Unauthorized => e\n refresh_gitlab_access_token(linked_app)\n access_token = linked_app.access_token\n Gitlab.private_token = access_token\n user = Gitlab.user\n end\n\n user_id = user[\"id\"]\n\n # TODO: Rename code_repo_name to full_repo_name\n repo_name = code_repo_name.split(\"/\").last\n projects = Gitlab.get(\"/users/#{user_id}/projects?search=#{repo_name}\")\n project = projects.to_a.find { |p| p[\"name\"] == repo_name }\n response = Gitlab.add_project_hook(\n project.id,\n \"https://#{ENV['DOMAIN_NAME']}/gitlab/webhooks/#{autobuild.id}\",\n {\n push_events: 1,\n tag_push_events: 1,\n token: webhook_secret\n }\n )\n autobuild.update(webhook_config: response.to_h)\n end\n end", "def url(arg = nil)\n if arg.nil? && @url.nil?\n \"#{node['jenkins']['mirror']}/plugins/#{name}/#{version}/#{name}.hpi\"\n else\n set_or_return(:url, arg, :kind_of => String)\n end\nend", "def test()\n # Search tag for the test\n search_tag = \"herml\"\n # All errors\n errors = []\n # Get the spidering results\n results = @github_api.spider(search_tag)\n # Check if we have any errors\n if(results[:total_hits] == 0 && results[:total_pages] == 0)\n errors << self.class.name + \": No hits found (#{results[:total_hits]}) and no pages recorded (#{results[:total_pages]})\"\n else\n # Ok let's fetch the first project (should be heml)\n projects = @github_api.process_page(search_tag, 1)\n if(projects.length == 0)\n errors << self.class.name + \": No projects correctly parsed\"\n else\n # get the first project\n project = projects[0]\n # Check if the project is correct\n #project = {:author => author, :description => description, :url => url, :metadata => metadata, :hash_value => project_md5_hash, :updates => [], :downloads => []}\n if(project[:author].nil? || project[:description].nil? || project[:url].nil? || project[:metadata].nil? || project[:hash_value].nil? || project[:updates].length == 0 || project[:downloads].length == 0)\n errors << self.class.name + \": Project not being parsed correctly (including possibly updates/downloads)\"\n else\n update = project[:updates][0]\n download = project[:downloads][0]\n # Check each of these\n #{:author => commit_author, :updated_at => updated_at, :title => commit_message, :download_link => \"\", :hash_value => commit_md5_hash}\n if(update[:author].nil? || update[:updated_at].nil? || update[:title].nil? || update[:download_link].nil? || update[:hash_value].nil?)\n errors << self.class.name + \": Project Update not being parsed correctly\"\n end\n\n #{:author => \"\", :updated_at => updated_at, :title => description, :download_link => url, :hash_value => download_md5_hash, :version => version}\n if(download[:author].nil? || download[:updated_at].nil? || download[:title].nil? || download[:download_link].nil? || download[:hash_value].nil? || download[:version].nil?)\n errors << self.class.name + \": Project Download not being parsed correctly\" \n end\n end\n end\n end\n # Return all the errors\n return errors\n end", "def initialize(jenkins_url=\"\")\n\t\t\tif jenkins_url.empty?\n\t\t\t\tjenkins_url = \"https://fx-test-jenkins-dev.stage.mozaws.net:8443/\"\n\t\t\tend\n\t\t\t@jenkins_url = jenkins_url\n\t\t\t@test_repo_black_list = [\n\t\t\t\t\"https://github.com/mozilla-services/services-test/\",\n\t\t\t\t\"https://github.com/rpappalax/jenkins-job-manager/\"\n\t\t\t]\n\t\tend", "def fetch_github_information\n self.associated_commit_shas = []\n self.branch_name = nil\n self.username = nil\n\n return if self.dev_build\n\n GithubService.run(self.project.github_root_url, self.project.github_repo) do |service|\n if self.is_branch_build\n self.associated_commit_shas = service.github_commits(10, self.commit_sha)\n self.branch_name = nil\n self.username = nil\n else\n self.associated_commit_shas = []\n info = service.user_and_branch_for_pull_request(self.pull_request_number)\n self.username = info[:user]\n self.branch_name = info[:branch]\n end\n end\n end", "def trigger_pipeline\n # The review app URL\n app_url = \"http://#{docs_branch}.#{ENV[\"DOCS_REVIEW_APPS_DOMAIN\"]}/#{slug}\"\n\n # Create the cross project pipeline using CI_JOB_TOKEN\n pipeline = Gitlab.run_trigger(GITLAB_DOCS_REPO, ENV[\"CI_JOB_TOKEN\"], docs_branch, { param_name => ENV[\"CI_COMMIT_REF_NAME\"] })\n\n puts \"=> Follow the status of the triggered pipeline:\"\n puts \"\"\n puts pipeline.web_url\n puts \"\"\n puts \"=> In a few minutes, you will be able to preview your changes under the following URL:\"\n puts \"\"\n puts app_url\n puts \"\"\n puts \"=> For more information, read the documentation\"\n puts \"=> https://docs.gitlab.com/ee/development/writing_documentation.html#previewing-the-changes-live\"\n puts \"\"\n puts \"=> If something doesn't work, drop a line in the #docs chat channel.\"\n puts \"\"\nend", "def hook\n @project = Project.find(params[:id])\n c = JSON.parse(params[:payload])\n\n @project.do_hook(c)\n\n #respond 200\n end", "def repo; end", "def repo; end", "def repo; end", "def repo; end", "def trigger_build_for_job(job, params = {})\n uri = URI(uri_for_job(job))\n \n body = nil\n\n if params.size > 0\n method = :post\n body = compile_jenkins_json(params)\n else\n method = :get\n end\n\n execute_http_request(method, uri, body)\n end", "def build_snapshot\n build_dependency\n puts '### dev build ###'\n puts `gulp 2>&1`\n puts '### dev build done ###'\n post_build\nend", "def jenkins?\n @logger.info \"Jenkins Detected: #{not (ENV['WORKSPACE'].nil?)}\"\n return !ENV['WORKSPACE'].nil?\nend", "def git_sources=(_arg0); end", "def git_sources=(_arg0); end", "def buildtrigger\n branch = params[:ref].sub('refs/heads/', '')\n gitlab_id = params[:project_id]\n\n # TODO reduce business logic from controller\n @project = Project.find_by(gitlab_id: gitlab_id)\n\n if @project\n @project.flush_branche(branch)\n\n @project.vms.select { |vm| vm.status > 1 && vm.is_jenkins && vm.commit.branche.name == branch }.each do |vm|\n vm.buildtrigger\n end\n end\n\n render nothing: true\n end", "def github(name, ref = 'master')\n gitrepo \"github.com\", name, ref\nend", "def github_repo\n arguments['repo'] || [stage.project.organization.name, stage.project.name].join('/')\n end", "def jenkins_job_build_data(build_no = nil)\n build_no = \"lastBuild\" if build_no.nil?\n options = {\"username\" => SS_hudson_username, \"password\" => SS_hudson_password}\n response = rest_call(\"#{BuildServerURL}/#{build_no}/api/json\", \"get\", options)\n data = response[\"status\"] == \"success\" ? response[\"response\"] : \"#{response[\"status\"]}: #{response[\"message\"]}\"\nend", "def run_job\n end", "def git_receive_pack\n render_ok\n end", "def update_from_github(auth, cv)\n cv['email'] = auth.info.email if auth.info.email\n cv['password'] = Devise.friendly_token[0,20] if Devise.friendly_token[0,20]\n cv['name'] = auth.info.name if auth.info.name\n cv['image'] = auth.info.image if auth.info.image\n cv['biography'] = auth.extra.raw_info.bio if auth.extra.raw_info.bio\n token = auth.credentials.token if auth.credentials.token\n tmp = Array.new\n\n uri = URI(auth.extra.raw_info.repos_url)\n\n #repos = JSON.parse(open(uri.to_s, 'Authentication' => \"token #{token}\").read)\n\n HTTP.auth(\"token #{token}\")\n repos = JSON.parse(HTTP.get(uri.to_s).body)\n\n repos.each do |gitPr|\n if not gitPr['fork']\n uri = URI(gitPr['languages_url'])\n lang = JSON.parse(HTTP.get(uri.to_s).body)\n lang.each do |key,_|\n tmp << key\n end\n end\n end\n $uriTmp = auth.extra.raw_info.starred_url.to_s\n $realUri = $uriTmp.gsub(/{(.*?)}/,'')\n\n starred = JSON.parse(HTTP.get($realUri).body)\n starred.each do |gitPr|\n uri = URI(gitPr['languages_url'])\n lang = JSON.parse(HTTP.get(uri.to_s).body)\n lang.each do |key,_|\n tmp << key\n end\n end\n cv['it_languages'] = tmp.uniq\n cv['github_auth'] = true\n end", "def build_job name\n\t\t\tputs \"==> Building job for project: '#{name}'\"\n\t\t\tbegin \n\t\t\t\tbuild_response = RestClient.get \"#{@jenkins_host}:#{@jenkins_port}/job/#{name}/build?delay=0sec\"\n\t\t\t\treturn build_response.code.to_s\n\t\t\trescue Exception => e\n\t\t\t\tputs \"==> Error Building job '#{name}'\"\n\t\t\t\treturn \"500\"\n\t\t\tend\n\t\tend", "def execute(jenkins_test_runner)\n tests_passed = jenkins_test_runner.run_tests\n Kernel.exit(tests_passed ? 0 : 1)\nend", "def post_build\n puts '### gulp package ###'\n # tar up the files.\n puts `gulp package 2>&1`\n puts '### gulp package done ###'\n deploy_maven\nend", "def push(builder)\n $stderr.puts Simple::Ansi.green(\n \"Pushing: #{builder.repo}\"\n )\n end", "def prebuild(build, listener)\n end", "def prebuild(build, listener)\n end", "def prebuild(build, listener)\n end", "def jenkins_payload(job_name, build_number, phase, status, branch)\n <<-DATA.chomp\n{\"name\":\"#{job_name}\",\n \"url\":\"JobUrl\",\n \"build\":{\n \"number\":#{build_number},\n\t \"phase\":\"#{phase}\",\n\t \"status\":\"#{status}\",\n \"url\":\"job/project/5\",\n \"full_url\":\"http://ci.jenkins.org/job/project/5\",\n \"parameters\":{\"branch\":\"#{branch}\"}\n\t }\n}\n DATA\n end", "def build_gem; end", "def git_project()\n \"\"\nend", "def git_push_if_changes( names ) ## optenfootball repo names e.g. world, england, etc.\n message = \"auto-update week #{Date.today.cweek}\"\n puts message\n\n names.each do |name|\n path = \"#{SportDb::Boot.root}/openfootball/#{name}\"\n\n Gitti::GitProject.open( path ) do |proj|\n puts ''\n puts \"###########################################\"\n puts \"## trying to commit & push repo in path >#{path}<\"\n puts \"Dir.getwd: #{Dir.getwd}\"\n output = proj.changes\n if output.empty?\n puts \"no changes found; skipping commit & push\"\n else\n proj.add( '.' )\n proj.commit( message )\n proj.push\n end\n end\n end\nend", "def add_git_facts\n # see if we're in a git repo. first, we need a directory that exists\n dir = @path.expand_path.ascend.find {|p| p.directory? }\n \n Dir.chdir(dir) do\n root_result = Cmds.new \"git rev-parse --show-toplevel\"\n \n unless root_result.ok?\n @result.in_git_repo = false\n @result.is_git_root = false\n return\n end\n \n @result.in_git_repo = true\n \n git = @result.git = Result.new\n git.root = Pathname.new root_result.out.chomp\n @result.is_git_root = @path == git.root\n \n user = git.user = Result.new\n \n ['name', 'email'].each {|key|\n user[key] = begin\n Cmds.chomp! \"git config user.#{ key }\"\n rescue\n end\n }\n \n git.origin = begin\n Cmds.chomp! \"git remote get-url origin\"\n rescue\n end\n \n match = GITHUB_SSH_URL_RE.match(git.origin) ||\n GITHUB_HTTPS_URL_RE.match(git.origin)\n \n git.is_github = !! match\n \n return unless match\n \n git.owner = match['owner']\n git.name = match['name']\n git.full_name = \"#{ git.owner }/#{ git.name }\"\n \n if true == @args['github_api']\n github = git.github = Result.new\n github.api_url = \"https://api.github.com/repos/#{ git.owner }/#{ git.name }\"\n \n response = Net::HTTP.get_response URI(github.api_url)\n \n if response.is_a? Net::HTTPSuccess\n # parse response body and add everything to github result\n parsed = JSON.parse response.body\n parsed.each {|k, v| github[k] = v}\n else\n # assume it's private if we failed to find it\n github.private = true\n end\n \n end\n end\n end", "def execute(message)\n failure_wrap(message) do |payload|\n write_release(payload) if payload.get(:data, :github_kit, :release)\n write_commit_comment(payload) if payload.get(:data, :github_kit, :commit_comment)\n write_status(payload) if payload.get(:data, :github_kit, :status)\n job_completed(:github_kit, payload, message)\n end\n end", "def configure_git\n run_simple 'git config user.name Cucumber'\n run_simple 'git config user.email cucumber@`hostname --fqdn`'\nend", "def jenkins_node_manage(args)\n args = jenkins_node_defaults(args)\n\n if args[:env]\n map = args[:env].collect { |k,v| %Q(\"#{k}\":\"#{v}\") }.join(\",\")\n env = \"new jenkins.EnvVars([#{map}])\"\n else\n env = \"null\"\n end\n\n case args[:launcher]\n when \"jnlp\"\n launcher = \"new JNLPLauncher()\"\n when \"command\"\n launcher = %Q(new CommandLauncher(\"#{args[:command]}\", env))\n when \"ssh\"\n if args[:password] == nil\n password = \"null\"\n else\n password = %Q(\"#{args[:password]}\")\n end\n\n launcher = %Q(new_ssh_launcher([\"#{args[:host]}\", #{args[:port]}, \"#{args[:username]}\", #{password},\n \"#{args[:private_key]}\", \"#{args[:jvm_options]}\"] as Object[]))\n end\n\n remote_fs = args[:remote_fs].gsub('\\\\', '\\\\\\\\\\\\') # C:\\jenkins -> C:\\\\jenkins\n\n if args[:availability] == \"Demand\"\n rs_args = \"#{args[:in_demand_delay]}, #{args[:idle_delay]}\"\n else\n rs_args = \"\"\n end\n\n return <<EOF\nimport jenkins.model.*\nimport jenkins.slaves.*\n\napp = jenkins.instance\nenv = #{env}\nprops = []\n\ndef new_ssh_launcher(args) {\n jenkins.instance.pluginManager.getPlugin(\"ssh-slaves\").classLoader.\n loadClass(\"jenkins.plugins.sshslaves.SSHLauncher\").\n getConstructor([String, int, String, String, String, String] as Class[]).newInstance(args)\n}\n\nif (env != null) {\n entries = env.collect { k,v -> new EnvironmentVariablesNodeProperty.Entry(k,v) }\n props << new EnvironmentVariablesNodeProperty(entries)\n}\n\nslave = new DumbSlave(\"#{args[:name]}\", \"#{args[:description]}\", \"#{remote_fs}\",\n \"#{args[:executors]}\", Node.Mode.#{args[:mode]}, \"#{args[:labels]}\",\n #{launcher},\n new RetentionStrategy.#{args[:availability]}(#{rs_args}), props)\n\nnodes = new ArrayList(app.getNodes())\nix = nodes.indexOf(slave)\nif (ix >= 0) {\n nodes.set(ix, slave)\n}\nelse {\n nodes.add(slave)\n}\n\napp.setNodes(nodes)\n\nEOF\nend", "def build_gems; end", "def test_it_works_with_remote_automation\n Rake.cd TEST_APP\n\n github_url = 'https://github.com'\n user_and_reponame = \"ParamagicDev/#{GITHUB_REPO_NAME}/tree/#{BRANCH}\"\n\n file = 'bridgetown.automation.rb'\n\n url = \"#{github_url}/#{user_and_reponame}/#{file}\"\n\n Rake.sh('bundle exec bridgetown new . --force ')\n Rake.sh(\"bridgetown apply #{url}\")\n\n run_assertions\n end", "def github\n Log.fatal('You did not configure GitHub yet.') unless @github\n @github\n end", "def run\n current = File.dirname(__FILE__)\n gcloud = Google::Cloud.new('rocket-ci', \"#{current}/cred/rocket-ci-7a179946404e.json\")\n logging = gcloud.logging\n resource = logging.resource('gce_instance')\n logger = DEBUG ? Logger.new(STDOUT) : logging.logger('startup_log', resource)\n\n logger.info { 'メタデータを取得します' }\n hostname, instance_id, = instance_metadata(logger)\n build_number, repository_id, traffic_limit, pull_request_html_url, cache_bucket_name = external_metadata(logger)\n owner, name, pull_request_number = pull_request_url_parser(logger, pull_request_html_url)\n cache_bucket = gcloud.storage.bucket(cache_bucket_name)\n logger = DEBUG ? Logger.new(STDOUT) : logging.logger('startup_log', resource, instance_id: instance_id, instance_host_name: hostname, build_number: build_number, repository_owner: owner, repository_name: name, pull_request_number: pull_request_number)\n\n logger.info { \"#{hostname} でビルドを行います\" }\n logger.info { 'Docker のメタデータへのアクセスを禁止します' }\n refuse_access_metadata(logger)\n\n umbilical = UmbilicalClient.default_client\n logger.info { 'firebase からリポジトリ関連の情報を取得します' }\n repository, auth_user, artifact = firebase_repositories_data(logger, umbilical, repository_id, build_number)\n github = Github.new(owner, name, auth_user['access_token'])\n\n logger.info { '成果物ディレクトリをマウントします' }\n mount_artifact_dir(logger, current, repository_id, build_number)\n logger.info { \"pull/#{owner}/#{name}/pull/#{pull_request_number} をビルドします\" }\n restore_cache(logger, cache_bucket, repository_id)\n logger.info { 'github/firebase のビルドステータスを pending に変更します' }\n change_github_build_status(logger, github, { state: 'pending', description: 'building', context: 'rocket-ci', target_url: \"https://rocket-ci.com/@#{owner}/#{name}/#{build_number}\" }, artifact['hash'])\n change_firebase_build_status(logger, umbilical, repository_id, build_number, build_status: 'pending', machine_status: 'running')\n logger.info { 'private key を取得します' }\n private_key = fetch_private_key(logger, umbilical, repository_id)\n unless private_key.key?('key')\n register_private_key(logger, umbilical, github, repository_id)\n private_key = fetch_private_key(logger, umbilical, repository_id)\n end\n logger.info { 'github から pull request を取得します' }\n pull_request = fetch_pull_request(logger, github, pull_request_number)\n logger.info { \"github から #{owner}/#{name}/pull/#{pull_request_number} のソースコードを取得します\" }\n get_source(logger, Base64.decode64(private_key['key']), pull_request, artifact)\n raise 'rocket.sh がありませんでした。リポジトリのルートに rocket.sh を配置してください。ビルドを終了します' unless File.exist?(BUILD_SCRIPT_PATH)\n logger.info { 'firebase のビルドステータスを build に変更します' }\n change_firebase_build_status(logger, umbilical, repository_id, build_number, build_status: 'build', machine_status: 'running')\n docker_options = create_docker_options(logger, repository)\n FileUtils.mkdir_p('/opt/build_log')\n build_logger = DEBUG ? BuildLogger.new_logger(shift_size: 1 * 1024) : BuildLogger.new_logger\n logger.info { 'ビルドを開始します' }\n container = Docker::Image.get('android:latest').run(nil, docker_options)\n traffic_limit_monitor(logger, traffic_limit) do\n container.stop\n end\n container.streaming_logs(\n 'stdout' => true,\n 'stderr' => true,\n 'timestamps' => false,\n 'follow' => true\n ) do |_, chunk|\n build_logger.info { chunk.strip }\n end\n exit_code = Docker::Container.get(container.id).info['State']['ExitCode']\n status = exit_code.zero? ? 'success' : 'failure'\n # ビルド結果をファイルへ書き出す\n File.write('/opt/result.txt', status)\n logger.info { \"ビルドが #{status} で終了しました\" }\nrescue => e\n logger.error { \"エラーが発生しました。処理を中断します #{e.message} #{e.backtrace}\" }\nensure\n unless DEBUG\n logger.info { '全ての処理を終了してシャットダウンします' }\n `sudo shutdown -h now`\n end\nend", "def process\n check_github_token\n config.base_jobs.each do |base_job_name|\n if branch_deleted?\n Job.delete!(base_job_name, branch)\n else\n Job.find_or_create_copy(base_job_name, branch).run!\n end\n end\n end", "def get_jenkins_version\n get_root if @jenkins_version.nil?\n @jenkins_version\n end", "def perform\n @project.repo &:fetch\n end", "def report_check_run_failure\n data = params\n check_run = data[:check_run]\n check_run_status = check_run[:status]\n sha = check_run[:head_sha]\n workflow_name = check_run[:name]\n conclusion = check_run[:conclusion]\n check_run_url = check_run[:html_url]\n check_suite = check_run[:check_suite]\n app_name = check_run[:app][:name]\n details_url = check_run[:details_url]\n pull_requests = check_suite[:pull_requests]\n pull_request = pull_requests[0]\n branch = check_suite[:head_branch]\n repository = data[:repository]\n repo_name = repository[:name]\n repo_url = repository[:html_url]\n sender_login = data[:sender][:login]\n pr_number = pull_request[:number] if pull_request.present?\n branch_path = ''\n branch_path = \"/tree/#{branch}\" if branch != 'master'\n\n # We are only interested in completed non-success\n return if check_run_status != 'completed' || conclusion == 'success'\n\n message = \"[ [#{repo_name}](#{repo_url}) ]\"\n message += if app_name == 'GitHub Actions'\n \" GitHub Action workflow [#{workflow_name}](#{check_run_url}):\"\n else\n \" Check run [#{workflow_name}](#{check_run_url}):\"\n end\n message += if pull_request.present?\n \" [#{conclusion}](#{repo_url}/pull/#{pr_number}/checks?sha=#{sha})\"\n else\n \" [#{conclusion}](#{details_url})\"\n end\n message += \" on [#{sha.first(7)}](#{repo_url}/commit/#{sha.first(10)})\"\n message += \" by #{sender_login}\" if sender_login.present?\n message += \" in the [#{branch}](#{repo_url}#{branch_path}) branch\" if branch.present?\n message += \" for [PR ##{pr_number}](#{repo_url}/pull/#{pr_number})\" if pull_request.present?\n\n # We don't want to send more than one message for this workflow & sha with the same conclusion within 20 minutes.\n # This counter expires from Redis in 20 minutes.\n ci_counter = Redis::CI.new(\"check_run_#{workflow_name}_#{conclusion}_#{sha}\")\n ci_counter.sucess_count_incr\n ActionCable.server.broadcast 'smokedetector_messages', message: message if ci_counter.sucess_count == 1\n end", "def hook_result(messages); end", "def manage_all_projects\n projects= [ \n [\"barjob\", \"git@github.com/foo/bar.git\"],\n [\"quxjob\", \"git@github.com/baz/qux.git\"],\n ]\n projects.each do |project_name, git_repo|\n manage_dynamic_branches_for_project(project_name, git_repo)\n end\nend", "def travis_repo(x)\n x = $travis_conn.get 'repo/' + x\n x.travis_raise\n return MultiJson.load(x.body)\nend", "def github_url\n \"http://github.com/280north/cappuccino/commit/#{sha1}\"\n end", "def makefile_hook(makefile)\n # STUB\n end", "def execute\n if (!self.pull_request_id)\n current = GitHub::PullRequest.current\n self.pull_request_id = current.number if current\n end\n self.pull_request_id ||= cli.prompt(\"Pull Request ID: \")\n GitHub.connect do\n unless deployable? || @force\n CLI.say 'Pull request status checks have not passed. Cannot be marked deployable.'\n exit!\n end\n\n merge_result = merge\n add_deployable_label if config.deployable_label && merge_result\n end\n end", "def github_test_parameters(repo)\n {\n \"name\" => \"pry\",\n # \"type\" => \"ruby\",\n \"summary\"=>\"An IRB alternative and runtime developer console\",\n \"license\" => \"MIT\",\n \"tag\"=>\"v0.10.4\",\n \"version\" => \"0.10.4\",\n }\nend", "def on_success(&block); end", "def initialize_repo\n puts \"starting to initialize repo: '#{self.ident}' finished successfully.\"\n self.update_repo\n end", "def update_repo\n puts \"starting to update_repo: '#{self.ident}'\"\n github = JSON.parse(Curl::Easy.perform(\"https://api.github.com/repos/\" + self.ident).body_str)\n \n if github[\"message\"]\n # Something has gone wrong\n # probably: repo does not exist\n # => 1) incorrect information provided when adding a repo\n # => 2) previously existing repo has had some changes (e.g. name, ownership)\n return false\n # do: better error handling here\n # what happens if a repo has been renamed / ownership transferred / deleted\n # => set flag 'needs_an_eye' to true\n # => then jump to the next repo\n # => might be done using 'markable' gem\n else\n %w{name description homepage}.each do |field|\n # set field or fall back to defaults\n self[field] = github[field] || \"\"\n end\n %w{watchers forks}.each do |field|\n # set field or fall back to defaults\n self[field] = github[field] || 0\n end\n\n self.github_url = github[\"html_url\"]\n self.owner = github[\"owner\"][\"login\"]\n self.last_updated = github[\"pushed_at\"]\n self.save\n end\n end" ]
[ "0.63358945", "0.6151897", "0.6139544", "0.61141145", "0.6104233", "0.60940367", "0.5968304", "0.5953476", "0.5934538", "0.5878198", "0.58777976", "0.5871155", "0.584904", "0.5827009", "0.5738334", "0.57212186", "0.5713353", "0.56985116", "0.56445605", "0.5630612", "0.5619784", "0.5607207", "0.5592355", "0.5590243", "0.55772424", "0.5576265", "0.55618817", "0.55412877", "0.55384123", "0.5519393", "0.5492468", "0.5491573", "0.54864544", "0.54864544", "0.54864544", "0.54864544", "0.54803205", "0.547549", "0.547167", "0.5466888", "0.54602885", "0.5451362", "0.5445115", "0.5438806", "0.54192567", "0.5412892", "0.5401287", "0.5387367", "0.5384872", "0.53847766", "0.5377276", "0.53692645", "0.53692645", "0.53692645", "0.53692645", "0.5358696", "0.5352453", "0.535065", "0.5340819", "0.5340819", "0.53360915", "0.53291", "0.5322864", "0.5296777", "0.5288203", "0.5287164", "0.527983", "0.5278393", "0.5267003", "0.5242054", "0.5241238", "0.52405447", "0.52405447", "0.52405447", "0.52397794", "0.5230271", "0.52290565", "0.522598", "0.5214891", "0.521394", "0.5212552", "0.52034646", "0.52019054", "0.5195715", "0.51941705", "0.5187753", "0.51853377", "0.5185226", "0.518095", "0.5180644", "0.51792175", "0.51776993", "0.5171795", "0.51672006", "0.5160138", "0.51588124", "0.5153296", "0.51409477", "0.5140192", "0.51306283" ]
0.5575557
26
=begin my_basket is configured to the current user =end
def my_basket @user = current_user end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_basket\n if !current_user.nil?\n @basket = current_user.basket\n @categories = Category.all\n @total_price = @basket.total_price\n else\n redirect_to '/users/sign_up'\n end\n end", "def basket\n \t#if the user doesn't have a basket\n \t#give them an empty one\n \tif session[:basket].nil?\n \t#basket is an empty list\n \t#using set because we don't want to add the same thing twice\n \tsession[:basket]= Set.new\n end\n #actually give them the basket\n session[:basket]\n end", "def basket\n \t#if user doesnt have a basket\n \t# give them an empty one\n \tif session[:basket].nil?\n \t\t#basket is empty list of things\n \t\t#using set bcoz we dont want to add same thing twice\n \t\tsession[:basket]= Set.new\n\n \tend\n \t# actually give them the basket\n \tsession[:basket]\n\n end", "def basket\n\n \t# if the user doesn't have a basket\n \t# give them an empty one\n \tif session[:basket].nil?\n\n \t\t#basket is an empty list\n \t\t#using set beacuse we don't want to add the same thing\n \t\tsession[:basket] = Set.new\n\n \tend\n\n \t# actually give them basket\n\n \tsession[:basket]\n\n end", "def get_user_basket\n @user = Users.find(session[:current_user_id])\n @basket = Baskets.find_by(:user_id => @user.id)\nend", "def set_basket_item\n @basket_item = BasketItem.where(user: current_user).find(params[:id])\n end", "def basket\nif session[:basket].nil?\n\t#basket is an empty list, using set because we don't want to add the same thing twice(an empty array[] allows you to add the same thing twice)\n\tsession[:basket] = Set.new\nend\n#actually give them the basket\nsession[:basket]\nend", "def set_basket\n # finds the current basket using the params\n @basket = Basket.find(params[:id])\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def index\n @basket_items = current_user.basket_items.includes(:product)\n @user = current_user\n end", "def index\n @baskets = Basket.where(user_id: current_user.id)\n end", "def basketball\n\t\t@bio = Bio.where(:user_id => current_user.id).last #existing user signing in\n\t\t@sport = \"NBA:DraftKings\"\n\tend", "def set_basket_item\n @basket_item = BasketItem.find(params[:id])\n end", "def new_basket\n session[:current_basket] = nil\n end", "def current_basket\n @current_basket = current_basket_or_nil\n if @current_basket.nil?\n @current_basket = Basket.new(:kori_type => \"Order\")\n @current_basket.save!\n session[:current_basket] = @current_basket.id\n end\n @current_basket\n end", "def add_basket(basket)\n add_lines(basket.to_order_lines)\n self.basket = basket\n self.customer_note = basket.customer_note\n self.delivery_instructions = basket.delivery_instructions\n end", "def set_gasket\n @gasket = Gasket.find(params[:id])\n end", "def create\n @basket = Basket.new(basket_params)\n @basker.status = 0\n @cart_item.basket.set_price\n @basker.user = @current_user\n respond_to do |format|\n if @basket.save\n format.html { redirect_to @basket, notice: 'Basket was successfully created.' }\n format.json { render :show, status: :created, location: @basket }\n else\n format.html { render :new }\n format.json { render json: @basket.errors, status: :unprocessable_entity }\n end\n end\n end", "def check_basket(basket)\n increase_support if in_basket?(basket)\n end", "def basket_params\n params.require(:basket).permit(:user_id, :product_id)\n end", "def initialize\n\t\t@basket = []\n\tend", "def add_to_basket\n if Basket.exists?(user_id: params[:user_id], book_id: params[:book_id])\n @basket = Basket.find_by(user_id: params[:user_id], book_id: params[:book_id])\n @basket.increment!(:amount)\n else\n Basket.create(user_id: params[:user_id], book_id: params[:book_id], amount: 1)\n end\n redirect_to my_basket_path(params[:user_id])\n end", "def checkout\n # assumes that an in_process must have at least one line_item\n # and therefore a basket\n raise \"An in_process order should have a basket.\" unless basket\n\n basket.moderators_or_next_in_line.each do |user|\n UserNotifier.deliver_in_process(self, user)\n end\n\n end", "def basket_params\n params[:basket]\n end", "def basket_params\n params[:basket]\n end", "def in_basket?(basket)\n @item_ids.all? do |item_id|\n basket.include?(item_id)\n end\n end", "def add_item_to_basket(item_id)\n @session[:item_basket] << item_id unless @session[:item_basket].include? item_id\n end", "def index\n\t\t@cart_items = current_user.shoppingkarts \n\t\t#Shoppingkart.find(current_user)\n\tend", "def show\n authenticate_user!\n user_signed_in? && @order.email == current_user.email ? @allowed = true : @allowed = false\n @cart = @order.cart\n end", "def itemized_stash_data(users)\n user = users.first\n # enable stash for the user?\n end", "def index\n # if not signed in\n if current_user == nil\n redirect_to user_session_path\n else\n @product_purchased_listings = ProductPurchasedListing.where(user_id: current_user[:id])\n # cart quantity check\n @quantity = Cart.where(user_id: current_user.id).count\n # byebug\n end\n end", "def my_orders\n if current_user\n @carts = current_user.carts\n else\n redirect_to root_path\n end\n end", "def show\n @cart = current_cart\n @user = current_user\n end", "def show\n @cart = current_cart\n @user = current_user\n\n end", "def store_in_vault\n preferred_paypal_flow == 'vault'\n end", "def add_ons_basket_admin_list\n \"| \" + link_to_unless_current('orders',\n { :controller => :orders,\n :action => :index,\n :urlified_name => @current_basket.urlified_name},\n :tabindex => '2')\n end", "def setup \n @user = current_user\n end", "def set_current_shop\n if user_signed_in?\n unless current_user.shops.empty?\n session[:shopify] ||= current_user.shops.first.id\n end\n end\n end", "def create\n @basket = Basket.new(user_id: current_user.id, product_id: params[:product_id])\n @basket.save\n\n redirect_to root_url\n end", "def set_cart\n if @current_user.nil?\n redirect_to login_path\n elsif @current_user.carts.nil?\n @cart = Cart.create( user_id: @current_user.id )\n elsif @current_user.carts.where( purchase_completed: false ).empty?\n @cart = Cart.create( user_id: @current_user.id )\n else\n @cart = @current_user.carts.find_by( purchase_completed: false )\n end\n # redirect_to cart_path( @cart )\n end", "def index\r\n # make sure any changes here are copied to the menu controller\r\n @borrower = Borrower.find(session[:current_user_borrower_id])\r\n @bids = @borrower.bids.sum(\"amount\") || 0\r\n end", "def basket_params\n params.require(:basket).permit(:name, :status, :user_id, :order)\n end", "def added_to_basket\n select_size\n choose_quantity \n click_add_to_basket\n end", "def setup_cart(force_anon_cart)\n # Get the cart, keeping the anonymous cart if that's what we're working with (don't merge)\n @cart = get_cart(:merge => false, :force_anon_cart => force_anon_cart)\n\n # Create all the price modifiers that eventually are part of the order and get displayed in the cart\n @price_modifiers = []\n\n # Coupon? If so, discount is minimum of cart total or coupon amount\n coupon = get_coupon\n @coupon_amount = 0.0\n if (coupon)\n @coupon_amount = [coupon.amount, @cart.total].min\n @price_modifiers << CouponUse.new(:coupon => coupon, :amount => (@coupon_amount * -1.0))\n end\n\n # MA sales tax -- must be calculate after coupon and discount but before shipping\n if (@customer.shipping_address.state.code == 'MA')\n taxable_sub_total = @cart.taxable_total + @price_modifiers.sum(&:amount)\n @price_modifiers << Tax.new(:amount => ApplicationHelper.round_currency(taxable_sub_total * BigDecimal('0.065')))\n end\n\n @usable_account_credit = [@cart.total + @price_modifiers.sum(&:amount), @customer.credit].min\n\n # If the cart is empty either (a) it's just empty, or (b) they just finished an order, but hit reload of this page after it completed\n if (@cart.empty?)\n # See if they just finished an order, but hit reload of this page after it completed\n recent_payment = Payment.find_recent(@customer)\n win = (recent_payment && recent_payment.complete && recent_payment.successful)\n return [ CHECKOUT_SUCCESS, recent_payment.order ] if win\n return [ CHECKOUT_NO_ITEMS, nil ]\n end\n nil\n end", "def index\n @baskets = current_user.baskets\n @coupons = @baskets.map {|basket| basket.coupon}\n @companies = Company.all\n\n end", "def basket_params\n params.require(:basket).permit(:status, :type_of_delivery, :integer, :address, :text, :user_id)\n end", "def set_current_useritem useritem\n session[:useritem_id] = useritem.id\n session[:useritem_type] = useritem.class.name\n end", "def set_dish_in_basket\n @dish_in_basket = DishInBasket.find(params[:id])\n end", "def get_cart\n @cart = current_user.init_cart\n end", "def index\n # @line_items = LineItem.all\n if @cart.line_items.empty? \n respond_to do |format|\n format.html { redirect_to store_index_path, notice: \"Your Basket is empty\" }\n format.json { head :no_content }\n end\n else\n if user_signed_in? \n @line_items = LineItem.all.where(user: current_user).order(\"created_at DESC\")\n @line_item = LineItem.all.where(user: current_user).first\n else\n @line_items = LineItem.all.where(user: 0)\n end\n end\n\n\n end", "def index\n @basket_items = BasketItem.all\n end", "def shopping_cart\n Cart.new session\n end", "def my_items\n if current_user && current_user.seller\n @items = current_user.items\n @view_my_items = true \n render :index\n else\n redirect_to root_path\n end\n end", "def save_user_basket(item)\n\t\t\tif item.save \n\t\t\t\tflash[:success] = 'Product Added to Cart'\n\t\t\t\trespond_to do |format|\n\t \tformat.html { redirect_to request.referer || root_path }\n\t \tformat.js {}\n\t\t end\n\t\t\telse\n\t\t\t\tflash[:error] = 'Product not Added'\n\t\t\t\tredirect_to request.referrer || root_path\n\t\t\tend\n\t\tend", "def reset_basket(order)\n order.empty_basket\n session[:coupons] = nil\n end", "def basket_params\n params.require(:basket).permit(:product_id, :count, :agent_id, :client_id)\n end", "def app_store_block_in_app_purchases=(value)\n @app_store_block_in_app_purchases = value\n end", "def setup\n session[:user_id]=1\n end", "def current_shopping_cart\n Order.where(user_id: current_user.id, complete: false).first_or_create\n end", "def index\n @cart = current_user.cart\n end", "def count_basket(basket)\n basket.each do |item_id|\n increase_item_count(item_id)\n end\n end", "def current_user\n current_user ||= User.find(session[:user_id]) if session[:user_id]\n# OrderSummary.db_selection(current_user)\n return current_user\n end", "def show\n if Cart.edit_by?(@current_user)\n redirect_to orders_url\n return\n else\n if @current_user!=nil\n if @cart.line_items.blank?\n redirect_to books_url, notice: 'Корзина пуста.'\n return\n end\n end\n end\n end", "def set_barcart\n @barcart = Barcart.find(params[:id])\n end", "def context; { user: current_user } end", "def checkout \n \t@order_items = current_order.order_items\n end", "def current_cart\n session[:cart] ||= []\n end", "def can_update_basket?\n !(\n needs_shipping_quote? || quote? || payment_on_account? || pay_by_phone? ||\n payment_received?\n )\n end", "def login_from_config\n self.current_user = User.find(BETY_USER) if defined? BETY_USER\n end", "def add_to_cart\n if current_user.cart\n update\n else\n create\n end\n end", "def set_my_item\n # binding.pry\n @item = MyItem.find_by_user_id(payload['user_id'])\n end", "def mys_setup current, &block\n user={id:current.id, token:current.auth_token}\n timer=Time.now\n session[:logged]={user: user, master: user.dup, timer: timer}\n block.call\n end", "def show\n @cart = current_user.cart\n @all_items = @cart.items\n end", "def my_account\n @orders = current_customer.orders.includes(:product).in_order || []\n end", "def purchase(item)\n \"thank you for visiting supermarket and buying #{item}!\" # this will overwrite the mixin above\n end", "def purchase(item)\n \"thank you for visiting supermarket and buying #{item}!\" # this will overwrite the mixin above\n end", "def show\n # if not signed in\n if current_user == nil\n redirect_to user_session_path\n else\n @product_purchased_listings = ProductPurchasedListing.find(params[:id])\n # cart quantity check\n @quantity = Cart.where(user_id: current_user.id).count\n end\n end", "def multiple_items?\n self.frontend == :shopcart\n end", "def index\n #IPSocket.getaddress(\"www.sandbox.paypal.com\")\n #@cart_items = CartItem.all\n \n if current_user == nil\n @cart_items = Array.new\n if session[:music_cart] != nil\n visitedArtistId = nil\n session[:music_cart].each do |cart_item_row|\n cart_item_temp = CartItem.new\n cart_item_temp.product_id = cart_item_row[:product_id]\n cart_item_temp.product_name = cart_item_row[:product_name]\n cart_item_temp.product_final_price = cart_item_row[:product_final_price]\n visitedArtistId = cart_item_row[:product_user_id]\n @cart_items.push(cart_item_temp)\n end\n \n if visitedArtistId == nil\n @continueShoppingLink = root_path\n else\n visitedArtist = User.find(visitedArtistId)\n visitedArtistName = visitedArtist.first_name+\" \"+visitedArtist.last_name\n @continueShoppingLink = artist_dashboard_path(id: visitedArtist.id.to_s+':'+visitedArtistName.parameterize) \n end\n \n else\n @continueShoppingLink = root_path\n end\n \n else\n @cart = Cart.where(:user_id => current_user.id).first\n @continueShoppingLink = root_path\n @cart_items = []\n if @cart != nil\n lastItem = nil\n @cart.cart_items.each do |item|\n lastItem = item\n end\n @cart_items = @cart.cart_items\n if lastItem != nil\n lastItemRow = Audio.find(lastItem.product_id)\n visitedArtist = User.find(lastItemRow.user_id)\n visitedArtistName = visitedArtist.first_name+\" \"+visitedArtist.last_name\n @continueShoppingLink = artist_dashboard_path(id: lastItemRow.user_id.to_s+':'+visitedArtistName.parameterize) \n \n end \n end\n end \n \n end", "def set_installed_shops\n @installed_shops = session[:installed_shops]\n end", "def show\n set_shoppinglist\n current_user.lastlist_id= @shoppinglist.id\n end", "def index #when user goes to the /cart then the cart should be empty or full of some product.\n @product = Product\n if session[:cart] then\n @cart = session[:cart]\n else\n @cart = {}\n end\n end", "def activate\n\n Product.class_eval do\n def already_purchased?\n purchased = false\n\n user = UserSession.find.user if UserSession.find\n if user\n orders = Order.find_all_by_user_id user.id\n else\n orders = []\n end\n orders.each do |order|\n line_item = LineItem.conditions('variant_id = ? AND order_id = ?', master.id, order.id).all\n purchased = true if line_item.size > 0\n end\n purchased\n end\n end\n\n LineItem.class_eval do\n def increment_quantity\n self.quantity\n end\n\n def decrement_quantity\n self.quantity\n end\n end\n end", "def set_shop\n @shop = current_user.shops.find_by!(id: params[:id]) if current_user\n end", "def settings\n\t\tcheck_if_myself\n\t\t@user = current_user\n\tend", "def checkout\n @user = User.find(session[:user_id])\n end", "def user_buying_unsigned?\n if session[:cart_id]\n cart = Cart.find_by(id: session[:cart_id])\n # if current and devise the user just logged\n # and only gets session cart, if there is cart_offers in it\n devise_controller? && current_user && cart&.cart_offers.present?\n else\n # if session has not cart_id, the user just logged out\n false\n end\n end", "def index\n # If cart is empty, mark boolean value for view\n end", "def set_cart\n @cart = Cart.find_by(buyer_id:current_buyer.id)\n end", "def purchase_show\n if params[:product_id] == '0'\n @items = session[:cart]\n else\n @items = []\n @items << { 'product' => params[:product_id], 'quantity' => session[:quantity] }\n end\n @sum = 0\n @count = 0\n @items.each do |item|\n product = Product.find(item['product'])\n @sum += product.price * item['quantity'].to_i\n @count += item['quantity'].to_i\n end\n @address = BillAddress.find(params[:bill_address_id])\n @user = current_user\n end", "def index\n @shopping_cart_items = current_user.shopping_cart_items\n \n puts \"@shopping_cart_items\"\n puts @shopping_cart_items.inspect\n \n puts \"current_user\"\n puts current_user.inspect\n \n @total_amount = 0\n @shopping_cart_items.each do |shopping_cart_item| \n puts \"total for loop\"\n puts shopping_cart_item.quantity * shopping_cart_item.card.price\n @total_amount += shopping_cart_item.quantity * shopping_cart_item.card.price\n end\n end", "def add_to_cart\n @shopping_cart = ShoppingCart.find_by_user_id(current_user.id)\n if @shopping_cart.nil?\n @shopping_cart = ShoppingCart.new({:user_id => current_user.id, :item_list => Hash.new.to_s})\n end\n if params[:item_id].nil?\n @item = Item.find(params[:item][:item_id])\n if current_user.id == @item.user_id\n redirect_to root_path\n else\n @shopping_cart.item_list = add_to_item_list(@shopping_cart.item_list, params[:item][:item_id], params[:item][:quantity], @item.quantity)\n @shopping_cart.save\n redirect_to @shopping_cart\n end\n else\n @item = Item.find(params[:item_id])\n if current_user.id == @item.user_id\n redirect_to root_path\n else\n @shopping_cart.item_list = add_to_item_list(@shopping_cart.item_list, params[:item_id], params[:quantity], @item.quantity)\n @shopping_cart.save\n redirect_to @shopping_cart\n end\n end\n end", "def put_in_basket\n node = Node.find(params[:id])\n\n # TODO: It is probably dangerous to put the TOP node in the basket. This would probably crash the system.\n # Add some logic to fix this. Note that newly created nodes don't have a parent. These are technically\n # root nodes, and these need to be able to\n # be put in the basket as part of the copy() operation. It is only THE top node that shouldn't be put in the basket.\n node.put_in_basket()\n\n respond_to do |format|\n format.html { render 'show' }\n format.json { render json: node, status: :created, location: node }\n end\n end", "def app_store_block_in_app_purchases\n return @app_store_block_in_app_purchases\n end", "def bag_params\n params.require(:bag).permit(:user_id, :quantity, :product_id, :product_variant_id, :purchased)\n end" ]
[ "0.71763974", "0.70489395", "0.69249535", "0.6874542", "0.6844382", "0.67905056", "0.65807974", "0.6403643", "0.63191754", "0.63191754", "0.63191754", "0.63191754", "0.63191754", "0.63191754", "0.6296771", "0.61556643", "0.61149406", "0.6059588", "0.60516125", "0.59962314", "0.5994115", "0.59167516", "0.591076", "0.5862251", "0.5735454", "0.5713646", "0.5699265", "0.56602603", "0.5609681", "0.5609681", "0.55924153", "0.5485121", "0.5463562", "0.544271", "0.5432394", "0.5427611", "0.54214525", "0.5418969", "0.54181045", "0.5412997", "0.54039234", "0.53811246", "0.5368546", "0.5366807", "0.53543997", "0.5327515", "0.53219175", "0.5310651", "0.5288781", "0.52829534", "0.52714705", "0.52594423", "0.5257299", "0.524956", "0.5236957", "0.52211154", "0.5214597", "0.52129984", "0.52063704", "0.5205135", "0.520248", "0.51967365", "0.51962453", "0.5178678", "0.51748693", "0.5170172", "0.51574343", "0.51554775", "0.5150722", "0.51498955", "0.51492697", "0.5128873", "0.5124103", "0.5119981", "0.5108549", "0.5098274", "0.50846446", "0.50828457", "0.50826776", "0.5077985", "0.5077985", "0.50718105", "0.5071106", "0.5070517", "0.5066622", "0.50606436", "0.50550723", "0.50482464", "0.50467426", "0.5041297", "0.50408286", "0.50369906", "0.5029794", "0.50295323", "0.50281405", "0.50198525", "0.50104666", "0.50095856", "0.5004185", "0.4999929" ]
0.78195983
0
=begin add_to_basket includes an if statement. If the users basket already exists it adds the book details Else it will create the basket =end
def add_to_basket if Basket.exists?(user_id: params[:user_id], book_id: params[:book_id]) @basket = Basket.find_by(user_id: params[:user_id], book_id: params[:book_id]) @basket.increment!(:amount) else Basket.create(user_id: params[:user_id], book_id: params[:book_id], amount: 1) end redirect_to my_basket_path(params[:user_id]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def addBook(book)\n\t\tinventories.create(book_id: book.id)\n\tend", "def add_item_to_basket(item_id)\n @session[:item_basket] << item_id unless @session[:item_basket].include? item_id\n end", "def add_book author, title\n books = @books[author]\n if books\n if books.include? title\n puts \"That book is already in the system\"\n else\n books << title\n end\n else\n puts \"No such author\"\n end\n end", "def create\n # Check if this book is in the system\n @book = Book.find_by(id: book_item_params[:book_id])\n if @book == nil \n # Meaning this book is not added to database and \n # book_item_params[:id] is Goodread id\n @book = save_goodreads_book(book_item_params[:book_id])\n book_item_params[:book_id] = @book.id\n end\n # Check if this book_item already in this shelf\n shelf = Shelf.find(book_item_params[:shelf_id])\n @book_item = shelf.book_items.new(book_item_params)\n \n if shelf.save!\n flash[:success] = \"Book item was successfully created.\"\n redirect_to current_user\n else\n flash[:error] = \"Cannot add book to Bookshelf\"\n redirect_to current_user\n end\n end", "def basket\n \t#if user doesnt have a basket\n \t# give them an empty one\n \tif session[:basket].nil?\n \t\t#basket is empty list of things\n \t\t#using set bcoz we dont want to add same thing twice\n \t\tsession[:basket]= Set.new\n\n \tend\n \t# actually give them the basket\n \tsession[:basket]\n\n end", "def add_book(book)\n current_item = line_items.find_by(book_id: book.id)\n if current_item\n current_item.quantity +=1\n else\n current_item = line_items.build(book_id: book.id)\n end\n current_item\n end", "def add_book(book_title_str)\n # is the book not already present in @books list?\n for book_hash in @books\n if book_hash[:title] == book_title_str\n return \"Such book is already in the library\"\n end\n end\n\n new_book = {\n title: book_title_str,\n rental_details: {\n student_name: \"\",\n date: \"\"\n }}\n\n @books.push(new_book)\n\n end", "def basket\n\n \t# if the user doesn't have a basket\n \t# give them an empty one\n \tif session[:basket].nil?\n\n \t\t#basket is an empty list\n \t\t#using set beacuse we don't want to add the same thing\n \t\tsession[:basket] = Set.new\n\n \tend\n\n \t# actually give them basket\n\n \tsession[:basket]\n\n end", "def basket\n \t#if the user doesn't have a basket\n \t#give them an empty one\n \tif session[:basket].nil?\n \t#basket is an empty list\n \t#using set because we don't want to add the same thing twice\n \tsession[:basket]= Set.new\n end\n #actually give them the basket\n session[:basket]\n end", "def add(num)\n #item = '9781133049791'\n item = num.fetch(\"isbn\")\n if !Book.pluck(:isbn).include?(item)\n @res = Amazon::Ecs.item_search(item, { :search_index => 'All', :response_group => 'Medium' })\n @res.items.each do |book|\n @db = Book.create\n @db.isbn = item\n @db.author = book.get('ItemAttributes/Author')\n @db.name = book.get('ItemAttributes/Title')\n @db.edition = book.get('ItemAttributes/Edition').to_i\n @db.retail_price = ((book.get('ItemAttributes/ListPrice/Amount').to_f/100)*3.65).to_i\n @db.description = book.get('EditorialReviews/EditorialReview/Content')\n @db.photo = book.get('LargeImage/URL')\n @db.save\n end\n end\n @thisBook = Book.find(:all, :conditions => {:isbn => item})\n redirect_to @thisBook\n end", "def add_basket(basket)\n add_lines(basket.to_order_lines)\n self.basket = basket\n self.customer_note = basket.customer_note\n self.delivery_instructions = basket.delivery_instructions\n end", "def add_book_to_inventory_by_book_title(new_book_title)\n new_book_array =\n {\n title: new_book_title,\n rental_details: {\n student_name: \"\",\n date: \"\"\n }\n }\n new_book_title != @title\n @inventory.push(new_book_array)\nend", "def create\n if book_item_params[:quantity].to_i > 0 \n @book = Book.find(book_item_params[:book_id]) if !book_item_params[:book_id].blank?\n if @book.blank? \n @book = Book.find_or_create_by(goodreads_id: book_item_params[:goodreads_id])\n @book.update_goodreads_info\n end\n # Check if this book_item already in this shelf\n @book_item = BookItem.find_or_create_by(shelf_id: book_item_params[:shelf_id], book_id: @book.id)\n @book_item.quantity = book_item_params[:quantity]\n @book_item.available_count = book_item_params[:quantity]\n \n if @book_item.save!\n flash[:success] = \"You got a book.\"\n else\n flash[:error] = \"Something wrong.\"\n flash[:error] = @book_item.errors.full_messages.to_sentence\n end\n else \n book_id = (book_item_params[:book_id] || Book.find_by(goodreads_id: book_item_params[:goodreads_id].to_i).presence.try(:id))\n @book_items = BookItem.where(\"shelf_id = ? AND book_id = ?\", book_item_params[:shelf_id], book_id) if book_id.present?\n if @book_items.present?\n @book_items.destroy_all \n flash[:warning] = \"Book removed.\"\n else\n flash[:warning] = \"Mission impossible.\"\n end\n end\n redirect_to :back\n end", "def create\n @basket = Basket.new(basket_params)\n @basker.status = 0\n @cart_item.basket.set_price\n @basker.user = @current_user\n respond_to do |format|\n if @basket.save\n format.html { redirect_to @basket, notice: 'Basket was successfully created.' }\n format.json { render :show, status: :created, location: @basket }\n else\n format.html { render :new }\n format.json { render json: @basket.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_book(book)\n\t\t@books.push(book)\t\n\tend", "def add_book(book)\n self.book_lists.create(:book_id => book.id)\n end", "def check_basket(basket)\n increase_support if in_basket?(basket)\n end", "def add(book)\n\t\t @books << book\n\tend", "def create\n @book = Book.new(params[:book])\n user_session = UserSession.new\n user_session.current_user.books << @book\n\n respond_to do |format|\n if @book.save\n format.html { redirect_to @book, notice: 'Book was successfully created.' }\n format.json { render json: @book, status: :created, location: @book }\n else\n format.html { render action: \"new\" }\n format.json { render json: @book.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_book(book)\n\t\t@books << book\n\t\t@book_status[book.title] = book.get_status\n\tend", "def add_book(book)\n @books.push(book)\n puts \"You've added '#{book.title}' to the Library.\"\n puts \"You know have \" + @books.length.to_s + \" books in the Library.\"\n end", "def basket\nif session[:basket].nil?\n\t#basket is an empty list, using set because we don't want to add the same thing twice(an empty array[] allows you to add the same thing twice)\n\tsession[:basket] = Set.new\nend\n#actually give them the basket\nsession[:basket]\nend", "def add_book(book)\n @books << book\n end", "def add_book(book)\n @books.push(book)\n end", "def add_to_basket\n @page.click_button(\"ctl00_contentBody_ctl02_submit\")\n end", "def add_book_google\n book = Book.create(book_params)\n \n if book.valid?\n #Book was added to library\n #Add book to users bookshelf\n user = User.find_by_id(params[:user_id])\n \n shelf = user.bookshelves.first\n shelf.books << book\n \n shelf = user.bookshelves.first\n pp shelf.shelfitems\n \n if params[:finished] == \"true\"\n shelf.shelfitems.last.finished = true\n #shelf.shelfitems.last\n shelf.shelfitems.last.save\n end\n #si.finished = params[:finished]\n #si.save\n \n render json: {msg: \"Successfully created \" + book.title, shelf: shelf.books}, :status => :created\n else\n render json: {e: \"Error creating book\"}, :status => :error\n end\n end", "def add_item(item)\n item.item_number = @@item_number\n @@item_number += 1\n @grocery_item << item\n\n # starting the logic for finding out what type of item it is and if it will be\n # allowed to be taxed. < -- Continue here\n if @grocery_item.item_type == \"books\"\n\n end\n\n\n\nend", "def lend_books(books, user)\n\t\tif @users.include? user then\n\t\t\tbooks.uniq.each do |book| \n\t\t\t\tif inventory[book] > 0 then\n\t\t\t\t\tinventory[book] -= 1\n\t\t\t\t\tadd_a_record(user, book)\n\t\t\t\telse\n\t\t\t\t\tputs \"Sorry, <#{book.title}> is unavailable.\"\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def add_book(book_title)\n @books << {\n title: book_title,\n rental_details: {\n student_name: \"\",\n date: \"\"\n }\n }\n end", "def add( book )\n @books.add( Books::Book.new( book ))\n end", "def set_basket\n if !current_user.nil?\n @basket = current_user.basket\n @categories = Category.all\n @total_price = @basket.total_price\n else\n redirect_to '/users/sign_up'\n end\n end", "def added_to_basket\n select_size\n choose_quantity \n click_add_to_basket\n end", "def in_basket?(basket)\n @item_ids.all? do |item_id|\n basket.include?(item_id)\n end\n end", "def create\n @basket = Basket.new(user_id: current_user.id, product_id: params[:product_id])\n @basket.save\n\n redirect_to root_url\n end", "def create\n id = params[:id].to_i\n qty = params[:qty].to_i\n \n cart_books = session[:cart].map { |c| c[0] }\n \n if cart_books.include?(id)\n session[:cart][cart_books.index(id)] = [id, qty]\n else\n session[:cart] << [id, qty]\n end\n \n # @cart_qty = session[:cart][cart_books.index(id)][1].to_i\n \n redirect_back(fallback_location: root_path)\n \n # logger.debug(\"Cart Create triggered\")\n # logger.debug(\"Adding book id #{params[:id]}\")\n end", "def add_book\n\tputs \"\\nTo add a new book please enter the following requested information:\\n\"\n\tprint \"Book Title \"\n\ttitle = gets.chomp\n\tprint \"Book Author \"\n\tauthor = gets.chomp\n\tprint \"Book ISBN \"\n\tisbn = gets.chomp\n\tprint \"Book Home Library \"\n\tlibrary_id = gets.chomp.to_i\n\tlibrary_id = verify_library_exists(library_id)\n\tBook.create(title: title, author: author, isbn: isbn, library_id: library_id)\nend", "def add_book(title)\n new_book = {\n title: title,\n rental_details: {\n student_name: \"\",\n date: \"\"\n }\n }\n @books.push(new_book)\n return @books.length\n end", "def remove_from_basket\n @basket = Basket.find_by(user_id: params[:user_id], book_id: params[:book_id])\n @basket.destroy\n redirect_to my_basket_path(params[:user_id])\n end", "def tag_books(tag, books)\n puts \"Tagging #{books.length} books as #{tag}\"\n books.each do |b|\n unless Tag.exists?(book_id: b.id, name: tag)\n Tag.create(book_id: b.id, name: tag)\n end\n end\n puts \"Done tagging #{tag}\"\nend", "def create \n \n # Check to see if the user is registered/logged in\n if current_user.nil?\n session[:user_book] = params\n # Redirect the user to register/login\n redirect_to new_user_session_path \n \n else \n\n @user_book = UserBook.new(params[:user_book])\n @user_book = current_user.user_books.build(params[:user_book])\n\n respond_to do |format|\n if @user_book.save\n format.html { redirect_to new_user_book_path, notice: 'Your book was successfully added. You may add more books or go back to your shelf.' } #redirect_to @user_book\n format.json { render json: @user_book, status: :created, location: @user_book }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_book.errors, status: :unprocessable_entity }\n end\n end\n end \nend", "def create\n @book = Book.find_by_id(params[:book_id])\n # check to see if there is enough copies of the book\n if @book.total_in_library > 0\n @reservation = @user.reservations.new\n @reservation.user_id = @user.id\n @reservation.book_id = @book.id\n if @reservation.save && @book.update(total_in_library: @book.total_in_library - 1)\n redirect_to reservations_path, notice: \"#{@book.title} has been reserved\"\n else\n redirect_to book_path(@book), notice: \"Problems reserving #{@book.title}\"\n end\n else # if not enough copies return back to the show page of the book\n redirect_to book_path(@book), notice: \"Not enough copies of #{@book.title} to reserve\"\n end\n end", "def create\n @basket = Basket.new(basket_params)\n\n respond_to do |format|\n if @basket.save\n format.html { redirect_to @basket, notice: 'Basket was successfully created.' }\n format.json { render :show, status: :created, location: @basket }\n else\n format.html { render :new }\n format.json { render json: @basket.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @basket = Basket.new(basket_params)\n\n respond_to do |format|\n if @basket.save\n format.html { redirect_to @basket, notice: 'Basket was successfully created.' }\n format.json { render :show, status: :created, location: @basket }\n else\n format.html { render :new }\n format.json { render json: @basket.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_book(book)\n @books << book\n puts \"Added \" + book.title + \" to the library.\"\n end", "def new_basket\n session[:current_basket] = nil\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def set_basket\n @basket = Basket.find(params[:id])\n end", "def create\n @basket = Basket.new(params[:basket])\n\n respond_to do |format|\n if @basket.save\n format.html { redirect_to @basket, notice: 'Basket was successfully created.' }\n format.json { render json: @basket, status: :created, location: @basket }\n else\n format.html { render action: \"new\" }\n format.json { render json: @basket.errors, status: :unprocessable_entity }\n end\n end\n end", "def updateUserBooks(user_name, book_name)\n @users.each do |user|\n if user.name == user_name\n then\n user.books_borrowed.push(book_name)\n puts \"USER DETAILS:\"\n puts \"------------------------------------------\"\n puts \"ID: \" + user.id.to_s\n puts \"Name: \" + user.name\n puts \"Address: \" + user.address\n puts \"Book Limit: \" + user.book_limit.to_s\n puts \"Books Borrowed:\"\n puts user.books_borrowed\n puts \"------------------------------------------\"\n end\n end\n end", "def add_new_library_book\n\t\tputs \"To add new book to library, You need to enter book name and book's author name\"\n\t\tprint \"\\tEnter New Book name:\"\n\t\tnew_book_name=gets.chomp\n\t\tprint \"\\tEnter Author name:\"\n\t\tnew_book_author_name=gets.chomp\n\t\t@last_book_id=@last_book_id+1\n\t\tbook=Book.new(@last_book_id,new_book_name,new_book_author_name,-1)\n\t\t@books.push(book)\n\t\tputs \"New book '#{new_book_name}' has been added to library with book ID #{@last_book_id}\"\n\tend", "def add_to_wishlist(product)\n wishlist.products << product unless wishlist.products.include?(product)\n wishlist.save\n end", "def get_user_basket\n @user = Users.find(session[:current_user_id])\n @basket = Baskets.find_by(:user_id => @user.id)\nend", "def add_to_listbooks\n self.isbn.each do |isbn|\n book = Listbook.find_or_create_by(isbn: isbn)\n self.listbooks << book unless self.listbooks.include? book\n book.save!\n end\n self.pinned_isbn.each do |isbn|\n book = Listbook.find_or_create_by(isbn: isbn)\n self.listbooks << book unless self.listbooks.include? book\n book.save!\n end\n\n self.listbooks.uniq!\n end", "def find_bag # the ||= is a conditional operator, if :book_bag exists, its value is returned, otherwise a new BookBag object is created\n session[:book_bag] ||= BookBag.new\n end", "def purchase_books(newbooks)\n\t\tnewbooks.each {|book, number| inventory[book] = number}\n\tend", "def set_basket_item\n @basket_item = BasketItem.where(user: current_user).find(params[:id])\n end", "def add_book(quantity)\n \n #increase the quantity and available for loaning\n self.quantity += quantity\n self.available += quantity\n\n #save the model\n self.save\n end", "def set_basket\n # finds the current basket using the params\n @basket = Basket.find(params[:id])\n end", "def add_pet_to_stock(pet_shop, new_pet)\n pet_shop[:pets] << new_pet\nend", "def create\n @book = params[:book]\n add(@book)\n end", "def add_pet_to_stock(pet_shop, new_pet)\n pet_shop [:pets].push (new_pet)\nend", "def add_my_books(book)\n\t\t@my_books << book.title\n\tend", "def add_pet_to_stock(pet_shop, new_pet)\n pet_shop[:pets].push(new_pet)\n return pet_shop[:pets].count()\nend", "def add_book(book)\n if book.is_a? Book # This test does not work as intended. I get a NameError undefined local variable.\n @books << book\n puts \"#{book.title} by #{book.author} has been added to the library.\"\n else\n puts \"That is not a book. Try again.\"\n end\n end", "def add_books(books)\n books.each do |book|\n @books.push(book)\n end\n end", "def add_to_cart\n if current_user.cart\n update\n else\n create\n end\n end", "def add_a_record(user, book)\n\t\tnow = DateTime.now.to_date\n\t\tborrow_days = 60\n\t\tdue = now + borrow_days\n\t\t@records << Record.new(user.id, book.isbn, now, due)\n\t\tputs \"Successfully lend <#{book.title}> to #{user.name}. Due:#{due}\"\n\tend", "def create\n librarian = nil\n User.all.each do |user|\n librarian = user if user.barcode == params['librarian_barcode']\n break unless librarian.nil?\n end\n cheese = {}\n if librarian.try(:librarian?)\n @book = Book.add_by_isbn(params[:isbn])\n cheese[:isbn] = [\"ISBN is invalid\"] if @book.errors.any?\n else\n cheese[:librarian] = [\"Librarian pin is invalid.\"]\n end\n respond_to do |format|\n if @book.present? and @book.errors.empty? and @book.save\n format.html { redirect_to @book, notice: 'Book was successfully created.' }\n format.json { render json: { title: @book.title }, status: :created, location: @book }\n else\n format.html { redirect_to root_path, notice: 'Book was not created.'}\n format.json { render json: cheese , status: :unprocessable_entity }\n end\n end\n end", "def create\n checkout = current_checkout\n\n product = Product.find(params[:product_id])\n @basket_item = BasketItem.new(:product => product)\n\n scanned_at_checkout = true\n if @basket_item.save\n checkout.scan(@basket_item)\n else\n scanned_at_checkout = false\n end\n\n respond_to do |format|\n if scanned_at_checkout\n format.html { redirect_to product, notice: 'We successfully added that item to your basket.' }\n format.json { render json: @basket_item, status: :created, location: @basket_item }\n else\n format.html { redirect_to product, notice: 'Oops! We were not able to add this to your basket, contact customer services for assistance.' }\n format.json { render json: @basket_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def addbook\n book= Book.find(params[:id])\n \t if book.add_book(Integer(params[:count])) \n \n render :inline => 'Books added Sucessfully'\n\n \t#flash.now[:notice] = 'Books added Sucessfully'\n \t#render :index \n else\n render :inline => 'Books not Added'\n\n end\nend", "def add_pet_to_stock(shop, new_pet)\n shop[:pets] << new_pet\nend", "def create\n @basket = Basket.new(basket_params)\n\n respond_to do |format|\n if @basket.save\n format.html { redirect_to root_path, notice: 'Basket was successfully created.' }\n session.delete(:order_id)\n format.json { render :show, status: :created, location: @basket }\n else\n format.html { render :new }\n format.json { render json: @basket.errors, status: :unprocessable_entity }\n end\n end\n end", "def rebook item, book\n if (item.price > 0)\n # item represents new aggr_order with price\n item.order_book = book unless item.order_book\n book.add item # добавляем в стакан\n else\n # item clears previous aggr_order for given price\n item.order_book = nil\n end\n end", "def basket_params\n params.require(:basket).permit(:user_id, :product_id)\n end", "def create\n @basket_item = BasketItem.new(basket_item_params)\n\n\n respond_to do |format|\n if @basket_item.save\n format.html { redirect_to @basket_item, notice: 'Basket item was successfully created.' }\n format.json { render :show, status: :created, location: @basket_item }\n else\n format.html { render :new }\n format.json { render json: @basket_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def save_user_basket(item)\n\t\t\tif item.save \n\t\t\t\tflash[:success] = 'Product Added to Cart'\n\t\t\t\trespond_to do |format|\n\t \tformat.html { redirect_to request.referer || root_path }\n\t \tformat.js {}\n\t\t end\n\t\t\telse\n\t\t\t\tflash[:error] = 'Product not Added'\n\t\t\t\tredirect_to request.referrer || root_path\n\t\t\tend\n\t\tend", "def add_pet_to_stock(shop, new_pet)\n shop[:pets] << new_pet\nend", "def calc(basket = [])\n\t\t\n\t\tparse_basket(basket)\n\n\t\tif @total_book_qty == @book1_qty || @total_book_qty == @book2_qty || @total_book_qty == @book3_qty || @total_book_qty == @book4_qty || @total_book_qty == @book5_qty \n\t\t\t# Only one book variety is bought\n\t\t\treturn @total_book_qty * BOOK_COST\n\t\telsif @book1_qty < 2 && @book2_qty < 2 && @book3_qty < 2 && @book4_qty < 2 && @book5_qty < 2 && @total_book_qty > 0\n\t\t\t# No book is bought twice\n\t\t\treturn @total_book_qty * BOOK_COST * BOOK_DISCOUNT[@total_book_qty]\n\t\telse\n\t\t\t# Some books may be bought twice\t\t\t\t\t\t\n\n\t\t\t# --------------\n\t\t\t# Create \"stacks\"\n\t\t\t# --------------\n\t\t\t\n\t\t\t# create the correct amount of stacks\n max_number_of_stacks = basket.values.max\n\t\t\tstacks_created = false\n\t\t\tstack_hash = {}\n\n\n\t\t\t# OPTIMIZE with Ruby magic?\n\t\t\t[\n\t\t\t\t[:book1, @book1_qty],\n\t\t\t\t[:book2, @book2_qty],\n\t\t\t\t[:book3, @book3_qty],\n\t\t\t\t[:book4, @book4_qty],\n\t\t\t\t[:book5, @book5_qty]\n\t\t\t].each do |book, qty|\n\t\t\t\t\tif qty == max_number_of_stacks && !stacks_created\n\t\t\t\t\t\twhile qty > 0\n\t\t\t\t\t\t\tkey = \"s\"+qty.to_s # creating a stack s1, s2, s3 etc. containing one book of the book_type with maximum count.\n\t\t\t\t\t\t\tstack_hash[key] = [book]\n\t\t\t\t\t\t\treduce_book_quantity(book, 1)\n\t\t\t\t\t\t\tqty = qty - 1\n\t\t\t\t\t\tend\n\t\t\t\t\t\tstacks_created = true\n\t\t\t\t\tend\n\t\t\tend\n\n # add all books to one of the stacks (making sure stacks are unique)\n\t\t\t[\n\t\t\t\t[:book1, @book1_qty],\n\t\t\t\t[:book2, @book2_qty],\n\t\t\t\t[:book3, @book3_qty],\n\t\t\t\t[:book4, @book4_qty],\n\t\t\t\t[:book5, @book5_qty]\n\t\t\t].each do |book, qty|\n\t\t\t\tif qty > 0\t\t\t\t\t\n\t\t\t\t\t\t(1..max_number_of_stacks).each do |n|\n\t\t\t\t\t\t\tkey = \"s\"+n.to_s\n\t\t\t\t\t\t\tunless stack_hash[key].nil? || stack_hash[key].include?(book) || qty < 1\n\t\t\t\t\t\t\t\tstack_hash[key] << book\n\t\t\t\t\t\t\t\treduce_book_quantity(book, 1)\n\t\t\t\t\t\t\t\tqty = qty - 1\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\n # ------------------\n # optimize the stacks\n # ------------------\n # look for maximum count\n # see the minimum count\n\n max_stack_size = 0\n max_stack_name = \"\"\n min_stack_size = 100\n min_stack_name = \"\"\n\t\t\to_computed_weight = 0\n\n while max_stack_size - min_stack_size > 1 || max_stack_name == \"\"\n\n \to_computed_weight = 0\n # find the biggest and smallest stack\n stack_hash.each do |stack_name, book_array|\n\t\t\t\t\t\n\t\t\t\t\to_computed_weight = o_computed_weight + book_array.length * BOOK_DISCOUNT[book_array.length]\n\n if book_array.length > max_stack_size\n max_stack_size = book_array.length\n max_stack_name = stack_name\n end\n if book_array.length < min_stack_size\n min_stack_size = book_array.length\n min_stack_name = stack_name\n end\n end\n\n\n # doing a deep_copy\n tmp_stack_hash = Marshal.load(Marshal.dump(stack_hash))\n\n # if the difference between them is more than 2 attempt a transfer of book to different stack\n if max_stack_size - min_stack_size > 1\n \ttransfer_book(tmp_stack_hash, max_stack_name, min_stack_name) \n\t\t\t\t\t\t# reset\n \t max_stack_size = 0\n\t\t\t max_stack_name = \"\"\n\t\t\t min_stack_size = 100\n end\n\n n_computed_weight = 0\n tmp_stack_hash.each do |stack_name, book_array|\n \tn_computed_weight = n_computed_weight + book_array.length * BOOK_DISCOUNT[book_array.length]\n end\n\n if o_computed_weight > n_computed_weight\n \tstack_hash = tmp_stack_hash\n else\n break\n end\n\n end\n\n\t\t\tcost = 0\n\t\t\t# calculate cost by iterating through each hash\n\t\t\tstack_hash.each do |book_name, unique_book_list|\n\t\t\t\tbook_count = unique_book_list.length\n\t\t\t\tcase book_count \n\t\t\t\twhen 1\n\t\t\t\t\tcost = cost + (book_count * BOOK_COST)\n\t\t\t\twhen 2\n\t\t\t\t\tcost = cost + (book_count * BOOK_COST * 0.95)\n\t\t\t\twhen 3\n\t\t\t\t\tcost = cost + (book_count * BOOK_COST * 0.9)\n\t\t\t\twhen 4\n\t\t\t\t\tcost = cost + (book_count * BOOK_COST * 0.8)\n\t\t\t\twhen 5\n\t\t\t\t\tcost = cost + (book_count * BOOK_COST * 0.75)\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn cost\n\n\t\tend\n\n\n\tend", "def add_read_book(book)\n self.read_books.create(:read_book_id => book.id)\n end", "def check_out(book)\n if @checked_books.count < 3\n @checked_books.add book\n true\n else\n \"Could not add book id: #{book.get_id}, max no of books (3) reached.\"\n false\n end\n end", "def borrow(book)\n\t\t@checked_out_books << book\n\tend", "def add_pet_to_stock(pet_shop, new_pet)\n pet_shop[:pets].push(new_pet)\nend", "def add_pet_to_stock(pet_shop, new_pet)\n pet_shop[:pets].push(new_pet)\nend", "def add_pet_to_stock(pet_shop, new_pet)\n pet_shop[:pets].push(new_pet)\nend", "def add_pet_to_stock(pet_shop, new_pet)\n pet_shop[:pets].push(new_pet)\nend", "def add_pet_to_stock(pet_shop, new_pet)\n pet_shop[:pets].push(new_pet)\nend", "def create\n @book = Book.new(book_params)\n \n if @book.save\n flash[:notice] = \"Book successfully added to profile\"\n redirect_to '/'\n else\n if @book.errors[:title].include? 'has already been taken'\n flash[:notice] = \"Book was already in profile\"\n else\n flash[:alert] = \"Failed to add book to profile\"\n end\n redirect_to '/'\n end\n end", "def set_basket_item\n @basket_item = BasketItem.find(params[:id])\n end", "def add(item, quantity, grocery_list)\n if grocery_list.include?(item)\n p \"Item is already on the grocery list.\"\n else \n grocery_list[item] = quantity\n end\n #print_list(grocery_list)\nend", "def add(item, quantity, grocery_list)\n if grocery_list.include?(item)\n p \"Item is already on the grocery list.\"\n else \n grocery_list[item] = quantity\n end\n #print_list(grocery_list)\nend", "def checkout\n flag = 0 \n book = Book.find(params[:id])\n @user = User.where(:email => params[:isbn])\n @books=Book.all\n @books.each do|book|\n if (book.Lastuser == current_user.email) \n flag = 1 \n flash[:notice] = 'You have another book checked out already' \n end\n end\n if flag == 0 \n book = Book.find(params[:id])\n book.Status = !book.Status \n book.Lastuser = current_user.email\n book.save\n History.create(:book_isbn => book.ISBN, :user_email => current_user.email, :book_title => book.Title, :book_author => book.Authors, :checkout_time => DateTime.now)\n flash[:notice] = 'Book was sucessfully checked out' \n end \n redirect_to book_path(book) \n end", "def add_pet_to_stock(pet_shop,new_customer)\n pet_shop[:pets]<<new_customer\n return\nend", "def checkout_book(title)\n # find book instance by title\n searched_book = Book.find_by(title: title)\n # change book.available to false\n searched_book.update_column(:available, false)\n # create Checkout instance with student id, book id, due date, checked_out defaults to true\n Checkout.create(student_id: self.id, book_id: searched_book.id, due_date: ((Date.today)+7))\n end", "def add_pet_to_stock(shop, pet)\n shop[:pets] << pet\nend", "def add_pet_to_stock(petshop,new_pet)\n petshop[:pets].push(new_pet)\n return petshop\n end", "def create_basket items_string\n @baskets = Array.new if @baskets.nil?\n basket = SalesTaxes::Basket.new items_string\n @baskets << basket\n basket\n end" ]
[ "0.6615606", "0.649829", "0.64770126", "0.6437923", "0.637861", "0.6339421", "0.62966764", "0.6277239", "0.62671065", "0.62582695", "0.6208262", "0.6206987", "0.6176562", "0.6167054", "0.615192", "0.61467165", "0.61344904", "0.61278075", "0.6074642", "0.6066711", "0.6062431", "0.6047257", "0.6040929", "0.60253", "0.60217613", "0.6005583", "0.6002055", "0.6001316", "0.59997827", "0.5998308", "0.59670913", "0.59641945", "0.59619236", "0.5950157", "0.594292", "0.5941775", "0.592328", "0.59147775", "0.5914118", "0.588736", "0.5885006", "0.5882312", "0.5882312", "0.587323", "0.5870034", "0.58645254", "0.58645254", "0.58645254", "0.58645254", "0.58645254", "0.58645254", "0.58617985", "0.5861288", "0.58060193", "0.58024234", "0.5793306", "0.5784002", "0.578275", "0.57799965", "0.57776767", "0.5762362", "0.57611513", "0.57427746", "0.5737784", "0.57343584", "0.5727168", "0.57226497", "0.5721238", "0.56976205", "0.5665215", "0.56595254", "0.5657676", "0.56494707", "0.56372714", "0.56350875", "0.56333387", "0.5632985", "0.5623453", "0.5622375", "0.560906", "0.5594794", "0.559412", "0.5591791", "0.5584296", "0.55790985", "0.5575797", "0.5575797", "0.5575797", "0.5575797", "0.5575797", "0.5574708", "0.5574408", "0.55742425", "0.55742425", "0.55725724", "0.55725306", "0.5564024", "0.5563544", "0.5541725", "0.5538528" ]
0.8253183
0
=begin Remove basket allows the user to clear down their basket by destroying it for the given user. it then redirects them to an empty basket =end
def remove_from_basket @basket = Basket.find_by(user_id: params[:user_id], book_id: params[:book_id]) @basket.destroy redirect_to my_basket_path(params[:user_id]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n\t\t@user_basket = UserBasket.find(params[:id])\n\t\t@shop = ShopProfile.find(@user_basket.shop_profile_id);\n\t\t@price = ShopProduct.find(@user_basket.shop_product_id).selling_price\n\t\t@price *= @user_basket.quantity\n\t\t@user_basket.destroy\n\t\tif current_user.user_baskets.empty?\n\t\t\trespond_to do |format|\n \tformat.html { redirect_to root_path }\n \tformat.js {}\n\t end\n\t\telse\n\t\t\trespond_to do |format|\n \tformat.html { redirect_to request.referer || root_path }\n \tformat.js {}\n\t end\n\t\tend\n\tend", "def destroy\n @basket.destroy\n\n respond_to do |format|\n format.html {\n redirect_to checkouts_url(user_id: @basket.user.username)\n }\n format.json { head :no_content }\n end\n end", "def destroy\n @basket.destroy\n\n redirect_to baskets_url\n end", "def destroy\n @basket.destroy if @basket.id == session[:basket_id]\n session[:basket_id] = nil\n respond_to do |format|\n format.html { redirect_to wines_url,\n notice: 'Your basket is currently empty' }\n format.json { head :no_content }\n end\n end", "def destroy\n session[:user_id] = nil\n session[:basket_id] = nil\n redirect_to root_path, notice: \"Logged out\"\n end", "def destroy\n # destroys the basket\n @basket.destroy\n end", "def destroy\n current_user.selecteditems.destroy_all\n redirect_to display_cart_user_path(current_user.id)\n end", "def remove\n\t\tremove_from_cart(Item.find(params[:id]))\n\t\tredirect_to :controller => \"cart\", :action => \"index\"\n\tend", "def remove_item\n item = Item.find(params[\"format\"])\n #select the cart of the log-in user\n if user_signed_in?\n cart = current_user.cart\n #check if the item is in the cart\n if item.carts.find(cart.id)\n item.carts.delete(cart)\n end\n redirect_to carts_show_path\n else\n redirect_to root_path\n end\n end", "def destroy\n @basket = Basket.find(params[:id])\n @basket.destroy\n\n respond_to do |format|\n format.html { redirect_to baskets_url }\n format.json { head :ok }\n end\n end", "def destroy\n @basket_item = BasketItem.find(params[:id])\n @basket_item.destroy\n\n respond_to do |format|\n format.html { redirect_to basket_items_url }\n format.json { head :no_content }\n end\n end", "def remove_shopping_list\n user_id = current_user.id\n yummly_id = params[:yummly_id]\n\n shopping_list = ShoppingList.find_by(yummly_id: yummly_id, user_id: user_id)\n shopping_list.destroy\n\n redirect_to recipes_url, notice: \"Removed recipe from your shopping lists\"\n end", "def remove_from_cart\n #see if you can change number of items in cart\n item_id = params[:remove_from_cart][:item_id]\n remove_item_from_cart(item_id)\n\n redirect_to cart_path\n end", "def remove_item\n prod_id = params[:product_id].to_s\n item = cart[prod_id] || {\"Num\" => 0}\n item[\"Num\"] -=1\n cart[prod_id] = item\n cart.delete(prod_id) if item[\"Num\"] < 1\n update_cart cart\n flash[:success] = t('itm_removed')\n redirect_back fallback_location: :root\n end", "def destroy_all\n @order = current_order\n @basket_items = @order.basket_items\n @basket_items.clear\n redirect_to(:back)\n end", "def remove_item\n product_id = params[:product_id].to_s\n modify_cart_delta(product_id, -1)\n redirect_to :back\n end", "def destroy\n @basket_item.destroy\n respond_to do |format|\n format.html { redirect_to basket_items_url, notice: 'Basket item was successfully removed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n \t@user = User.find(params[:user_id])\n \t@item = @user.items.find(params[:id])\n \t@item.destroy\n \tredirect_to @user\n \tend", "def remove_from_basket\n @discount.update_attribute(:order_id, nil)\n respond_to do |format|\n format.html { redirect_to purchase_orders_url, notice: 'Promotions was successfully removed from basket.' }\n format.json { head :no_content }\n end\n end", "def remove_from_cart\n\t\tcart_hash = session[:cart]\n\n\t\tcart_hash[params[:id]][\"quantity\"] -= 1\n\t\tif cart_hash[params[:id]][\"quantity\"] === 0\n\t\t\tcart_hash.delete(params[:id])\n\t\tend\n\n\t\tredirect_to root_url\n\tend", "def new_basket\n session[:current_basket] = nil\n end", "def remove_cart\n\t\tcart = current_user.saved.carts.find(params[:cart])\n #saved.carts.delete(cart)\n cart.destroy\n redirect_to :back\n\tend", "def remove_item\r\n cart_item_id = params[:id].to_i\r\n session[:cart].delete(cart_item_id)\r\n\r\n flash[:info] = 'Item has been removed!'\r\n redirect_to cart_url\r\n end", "def clear_item_from_cart\n\t\tcart_hash = session[:cart]\n\n\t\tredirect_to root_url\n\tend", "def remove\n id = params[:id]\n cart = session[:cart]\n cart.delete id\n \n redirect_to :action => :index\n end", "def remove_item\n\tsaved = current_user.saved\n\titem = saved.items.find(params[:item])\n saved.items.delete(item)\n redirect_to :back\n\tend", "def destroy\n @basket_item.destroy\n respond_to do |format|\n format.html { redirect_to basket_items_url, notice: 'Basket item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def remove_item(item, grocery_bag)\n grocery_bag.delete(item)\n p grocery_bag\nend", "def remove_items\n system 'clear'\n CoffeeMan.stay_logo\n @@cart = @@cart.flatten\n cart_arr = @@cart \n if cart_arr.count == 0 \n puts \"Your cart is empty, please add items\"\n sleep 1\n view_cart\n end\n if cart_arr.count > 0 \n splitted_cart = cart_arr.split(\" \")\n selected_items = prompt.multi_select(\"Which item would you like to remove?\", splitted_cart)\n selected_items.each do |del| \n cart_arr.delete_at(cart_arr.index(del))\n end \n # @@cart = cart_arr\n sleep(0.6)\n view_cart\n end\n end", "def removeProduct\n id = params[:id]\n cart = session[:cart]\n cart.delete id\n redirect_to :action => :index\n \n end", "def destroy\n @basket.destroy\n respond_to do |format|\n format.html { redirect_to baskets_url, notice: 'Basket was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @basket.destroy\n respond_to do |format|\n format.html { redirect_to baskets_url, notice: 'Basket was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @basket.destroy\n respond_to do |format|\n format.html { redirect_to baskets_url, notice: 'Basket was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_item\n if current_user\n @item = Item.find(params[:id].to_i)\n current_cart.items.delete(@item)\n redirect_to cart_path\n else\n delete_item_in_guest_cart(params[:id].to_i)\n redirect_to cart_path\n end\n end", "def remove_wishlist_item\n if item = Item.find_by_id(params[:id])\n @customer.remove_item_from_wishlist(item)\n end\n render :text => ''\n end", "def destroy\n @wishlist.destroy\n\n redirect_back(fallback_location: root_path , alert: 'Product was successfully removed from wishlist.')\n end", "def remove_from_favourites\n user_id = current_user.id\n yummly_id = params[:yummly_id]\n\n user_favourite_recipe = UserFavouriteRecipe.find_by(yummly_id: yummly_id, user_id: user_id)\n user_favourite_recipe.destroy\n\n redirect_to recipes_url, notice: \"Removed recipe from your list of favourite recipes\"\n end", "def remove_from_cart\n if @cart.candle_carts.count == 1\n destroy\n else\n item = CandleCart.find(cart_params[:id])\n item.destroy\n flash[:alert] = \"Succesfully Removed\"\n redirect_back fallback_location: root_path\n end\n end", "def destroy\r\n @cart_item = CartItem.find(params[:id])\r\n if @cart_item.destroy\r\n \t@cart_item.unbuy # returns unbought items in the cart to products table\r\n \tflash[:notice] = \"Item has been removed from cart!\"\r\n end\r\n redirect_to edit_cart_item_path(@cart_item)\r\n end", "def remove_favourite(user_id, favourite_name)\n @favourites_store.destroy(user_id, favourite_name)\n end", "def remove\n\t\t# se o usuário não entiver infectado e já existir o inventário salvo, remove a quantidade no inventário\n\t\tunless User.healthy? inventory_params[:user_id]\n \t \trender json: { error: \"Denied access. User is contaminated!\" }, status: 403 and return\n\t\tend\n\n\t\tif @inventory.remove(inventory_params[:amount].to_i)\n\t\t\trender json: @inventory, status: 200\n\t\telse\n\t\t\trender json: @inventory.errors, status: :unprocessable_entity\n\t\tend\n\tend", "def destroy\n flash.notice = I18n.t(:basket_successfully_cleared)\n @order.line_items.clear\n @order.update_totals!\n after :destroy\n set_flash :destroy\n response_for :destroy\n end", "def remove_have\n if params[:id].present? and params[:remove_have].present?\n if params[:from_haves_tab] == 'true'\n @user = current_user\n # @have_items = @user.items\n item = Item.find_by_id_and_user_id(params[:id],current_user.id)\n if item.present?\n # item.destroy\n item.update_attribute(\"status\",\"DELETED\")\n end\n flash[:info] = \"Item has been removed from your Haves Board .\"\n redirect_to haves_user_path(@user, :delete => item.id)\n # elsif params[:from_my_offers_tab] == 'true'\n # @user = current_user\n # @have_items = @user.have_items\n # item = Item.find_by_id_and_user_id(params[:id],current_user.id)\n # item.destroy\n # params[:id] = params[:original_id]\n # @item = Item.find_by_id(params[:id])\n # @offer_ids = @item.current_offers.pluck(:offer_id)\n # @useritems = @user.items\n # @useritem_ids = @useritems.pluck(:id)\n # elsif params[:from_items_index] == 'true'\n # # item = Item.find_by_id(params[:id])\n # # item.destroy\n # respond_to do |format|\n # format.js\n # format.html { redirect_to items_path}\n # end\n end\n end\n end", "def basket\n \t#if the user doesn't have a basket\n \t#give them an empty one\n \tif session[:basket].nil?\n \t#basket is an empty list\n \t#using set because we don't want to add the same thing twice\n \tsession[:basket]= Set.new\n end\n #actually give them the basket\n session[:basket]\n end", "def basket\n \t#if user doesnt have a basket\n \t# give them an empty one\n \tif session[:basket].nil?\n \t\t#basket is empty list of things\n \t\t#using set bcoz we dont want to add same thing twice\n \t\tsession[:basket]= Set.new\n\n \tend\n \t# actually give them the basket\n \tsession[:basket]\n\n end", "def reset_basket(order)\n order.empty_basket\n session[:coupons] = nil\n end", "def remove_from_cart\n id = params[:id]\n session[:cart].delete(id)\n redirect_to root_path\n end", "def basket\n\n \t# if the user doesn't have a basket\n \t# give them an empty one\n \tif session[:basket].nil?\n\n \t\t#basket is an empty list\n \t\t#using set beacuse we don't want to add the same thing\n \t\tsession[:basket] = Set.new\n\n \tend\n\n \t# actually give them basket\n\n \tsession[:basket]\n\n end", "def destroy\n \tsession[:user_id] = nil\n \tredirect_to products_url, :notice => \"Logged out\"\n end", "def user_delete_item\n @item = Item.find_by_id(params[:id])\n if @item.auction_flag\n #@auction = Auction.find(@item.auction_id)\n #@auction.destroy\n redirect_to item_path(@item),:notice => \"You can't delete this item, because its auctioned and it has a bidder\"\n\n else\n @item.destroy\n redirect_to(:action => 'user_items_list')\n end\n\n end", "def unassign\n @budget_item_id = params[:budget_item_id]\n @userid = params[:user_id]\n @projectid = params[:id]\n BudgetItemUser.where(:user_id => @userid ,:budget_item_id => @budget_item_id ).destroy_all\n redirect_to(:controller => 'budget_items' ,:action => 'getProjectMembers' ,:budget_item_id => @budget_item_id , :project_id => @projectid)\n end", "def remove\n\t\tputs \"\\nWhat would you like to remove?\"\n\t\tremove_item = gets.chomp\n\t\tputs \"\\nWARNING: This will delete #{remove_item} from list...are you sure? 'y/n'\"\n\t\tconfirm = gets.chomp\n\t\tif confirm == 'n'\n\t\t\tputs \"#{remove_item} was NOT removed from your Grocery List!\"\n\t\telse\n\t\t\t@grocery_list.remove(remove_item)\n\t\t\tputs \"\\nDeleting #{remove_item} from list...\"\n\t\t\tputs \"#{remove_item.capitalize} was deleted from your Grocery List!\"\n\t\tend\n\tend", "def destroy\n @user = User.find(params[:id]) or raise ActiveRecord::RecordNotFound\n auctions = Auction.find_all_by_seller_id(@user)\n purchases = Auction.find_all_by_buyer_id(@user)\n unless auctions.size > 0\n unless purchases.size > 0\n @user.destroy\n flash[:notice] = \"Deleted user.\"\n else \n flash[:error] = \"#{@user.name} has made one or more purchases and cannot be deleted.\"\n end\n else \n flash[:error] = \"#{@user.name} has created one or more auctions and cannot be deleted.\"\n end\n redirect_to users_url\n end", "def postUserReseller_remove( user_id)\n params = Hash.new\n params['user_id'] = user_id\n return doCurl(\"post\",\"/user/reseller_remove\",params)\n end", "def remove_from_cart\n Cart.remove_from_cart(session[:cart], params[:id])\n redirect_to show_cart_products_path\n end", "def destroy\n not_found if @auth_shopping_cart_item.nil?\n puts \"the accepted is:\"\n puts @auth_shopping_cart_item.accepted.to_s\n @auth_shopping_cart_item.destroy\n respond_with @auth_shopping_cart_item\n end", "def destroy\n\t\t@cart_item.destroy\n\n\t\thead :no_content\n\tend", "def destroy\n # Use callbacks to share common setup or constraints between actions.\n\n @cart_item.destroy\n respond_to do |format|\n format.html { redirect_to basket_url(@cart_item.basket), notice: 'Диск удален из конрзины.' }\n format.json { head :no_content }\n end\n end", "def destroy\n if @shop.user_id == current_user.id\n @shop.destroy\n end\n respond_to do |format|\n format.html { redirect_to shops_url, notice: 'お手続きした商品を削除致しました。今後とも『オトクーナ』をどうぞ宜しくお願い致します。' }\n format.json { head :no_content }\n end\n end", "def destroy\n if @collect.destroy\n redirect_to collected_path(User.find(@collect.user_id)) # 重定向至关注商品列表页面\n else\n redirect_to root_path\n end\n end", "def remove_item(index)\n @in_cart_items.delete_at(index)\n @cond_cart_view -= 1\n puts \"Item has been removed\"\n cart_items\n puts 'Remove another item? y/n -->' \n choice = gets.strip.downcase\n if choice == 'y'\n if @cond_cart_view >= 1\n puts \"What item would you like to remove from your cart?\"\n @in_cart_items\n index = gets.to_i\n remove_item(index - 1)\n else \n puts 'There is nothing in your cart to remove.'\n menu\n end\n else \n menu\n end\nend", "def remove_user_ban(data); end", "def remove_user_ban(data); end", "def destroy\n\t\t# the act of logging out is performed by simply setting the key (:user_id) \n\t\t# in the session hash to a value of nil (nothing)\n\t\tsession[:user_id] = nil\n\t\t# redirect to root_path (products/index.html.erb') \n\t\tredirect_to root_path \n\tend", "def purge\n @user.destroy\n redirect_to admin_users_path\n end", "def destroy\n @sugar_bag = SugarBag.find(params[:id])\n @sugar_bag.destroy\n\n respond_to do |format|\n format.html { redirect_to sugar_bags_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @cart_item.destroy\n\n head :no_content\n end", "def clear_carts\n current_user.carts.each_with_index do |cart, i|\n cart.delete if i != current_user.carts.length - 1\n end\n end", "def clearCart\n #sets session variable to nil and bring back to index\n session[:cart] = nil\n redirect_to :action => :index\n end", "def destroy\n @book_item.destroy\n redirect_to user_path\n end", "def remove\n @order.ig_remove_order\n redirect_to admin_orders_path\n end", "def remove_item(name, cart)\n \n if cart.delete(name) != nil\n puts 'Item successfully removed!'\n else\n puts 'No such item in cart!'\n end\n \n p cart\n \nend", "def remove_user_from_quick_invoicing\n company.saved_invoice_users.delete(User.find(params[:user_id]))\n\n head :ok\n end", "def destroy\n # get the item with id and get the quantity of this item\n @item = ShoppingCart.find(params[:id]).item\n\n @item.save\n current_user.remove_item_from_cart!(@item)\n # remove the item from shopping cart\n respond_to do |format|\n format.html { redirect_to @item }\n format.js\n end\n end", "def remove(params, userid)\n id = params[\"product_id\"]\n db = connect()\n result = db.execute(\"DELETE FROM ProduCart WHERE product_id = ? AND user_id = ?\",id,userid)\n end", "def remove_item\n\n end", "def remove_from_cart\n @var_list = params[:variable_ids]\n unless @var_list.empty?\n @var_list.each do |var|\n item = CartItem.find_by_user_id_and_variable_id(current_user,var)\n if item\n item.destroy\n end \n end\n current_user.reload\n end\n @sorted_variables = Array.new\n current_user.cart_items.each do |item|\n var = Variable.find(item.variable_id)\n @sorted_variables.push(var)\n end\n variables_hash = {\"total_entries\"=>@sorted_variables.size, \"results\" => @sorted_variables.sort{|x,y| x.name <=> y.name}.collect{|variable| {\"id\" => variable.id, \"name\"=> variable.name, \"description\"=>variable.value, \"survey\"=>variable.dataset.survey.title, \"year\" => variable.dataset.survey.year, \"category\"=>variable.category, \"popularity\" => VariableList.all(:conditions=>\"variable_id=\" + variable.id.to_s).size}}}\n @variables_json = variables_hash.to_json\n if current_user.cart_items.empty?\n render :update do |page|\n page.redirect_to(:controller => \"surveys\", :action => \"index\")\n page << \"alert('You have no variables left in your cart. To create a new Data Extract you need to search for some and add to your cart.');\" \n end\n else\n render :update do |page|\n #refresh the var table with the remaining variables\n page << \"updateTable('#{@variables_json}');\"\n page.replace_html \"cart-buttons\", :partial=>\"cart/all_buttons\"\n page.replace_html \"cart-link\", :partial=>\"cart/cart_link\"\n page[:cart_button].visual_effect(:pulsate, :duration=>2)\n end\n end\n end", "def destroy\n if @user.id != current_user.id\n redirect_to '/'\n else\n @item.destroy\n respond_to do |format|\n format.html { redirect_to root_url, notice: 'Item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end\n end", "def destroy\n @wish_list = WishList.find(params[:wish_list_id])\n @item = @wish_list.items.find(params[:item_id])\n\n if @item.purchased_by == current_user\n @item.purchased_by = nil\n @item.save\n else\n flash[:alert] = \"You do not have permission to unpurchase this Item.\"\n end\n head 200\n end", "def delete\n\t\t\tuser = User.find(params[:id])\n\t\t\tuser_first = user.name || \"\"\n\t\t\tuser_last = user.lname || \"\"\n\n\t\t\tuser.reviews.each { |review| review.destroy }\n\n if(user.role == 'merchant' || user.role == 'admin')\n user.stores.each { |store| store.destroy }\n end\n\n user.destroy\n flash[:notice] = \"#{user_first} #{user_last} deleted.\"\n\n redirect_to :controller => 'users' , :action => :index \n end", "def remove_mtg_cards\n reservation = Mtg::Reservation.find(params[:id])\n unless current_cart.remove_mtg_listing(reservation, params[:quantity].to_i) # remove this listing from cart\n flash[:error] = \"there was a problem processing your request\"\n redirect_to back_path\n return\n end\n redirect_to back_path, :notice => \"Item(s) removed!\"\n return #stop method, don't display a view\n end", "def clear_cart\r\n session[:cart] = []\r\n flash[:info] = 'Cart has been emptied!'\r\n redirect_to root_url\r\n end", "def empty_cart\n puts \"========= Emptying Cart\"\n @b.goto 'http://shoppingcart.aliexpress.com/shopcart/shopcartDetail.htm'\n\n if @b.link(class: \"remove-all-product\").exists?\n @b.link(class: \"remove-all-product\").click\n @b.div(class: \"ui-window-btn\").button.click\n end\n end", "def empty_cart\n puts \"========= Emptying Cart\"\n @b.goto 'http://shoppingcart.aliexpress.com/shopcart/shopcartDetail.htm'\n\n if @b.link(class: \"remove-all-product\").exists?\n @b.link(class: \"remove-all-product\").click\n @b.div(class: \"ui-window-btn\").button.click\n end\n end", "def destroy\n @item = Item.find(params[:id])\n\n if @item.user.id == current_user.id\n @item.destroy\n redirect_to root_path\n else\n redirect_to item_path(@item)\n end\n end", "def clear\n session[:cart] = nil\n redirect_to :action => :index\n end", "def destroy\n @gasket.destroy\n respond_to do |format|\n format.html { redirect_to gaskets_url, notice: 'Gasket was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @user = User.find(params[:user_id])\n @comparison = Comparison.find(params[:id])\n @comparison.destroy\n\n respond_to do |format|\n format.html { redirect_to user_comparisons_path(@user.id), notice: 'Item was removed from list' }\n format.json { head :no_content }\n end\n end", "def destroy\n @book = Book.find(params[:id]) # Find current book and userbook associated with current book and user \n @userbook = @book.user_books.find_by(user: current_user).remove_book_from_shelves.destroy # Remove book from user shelves and user collection\n @book.destroy if @book.users.empty? # Destroy book if it is no longer associated with any users\n redirect_to user_path(current_user) # Redirect to User show page\n end", "def quit_cabal\n result=@cabal.remove_member(current_user)\n if result==0\n flash[:alert] = \"User does not exist. \"\n else\n if result==-1\n @cabal.destroy\n end\n flash[:notice] = \"Successfully exited cabal. \"\n end\n redirect_to root_url\n end", "def destroy\n @item = @user.items.find(params[:id])\n @item.destroy\n\n\n respond_to do |format|\n format.html { redirect_to user_items_path(@user) }\n format.json { head :no_content }\n end\n end", "def delete\n if logged_in?\n @item = Item.find(params[:item_id])\n @order = Order.find_by(item: @item)\n @order.destroy\n redirect_to '/cart'\n end\n end", "def destroy\n @lint_item.destroy\n respond_to do |format|\n format.html { redirect_to lint_items_url }\n format.json { head :no_content }\n end\n=begin\n @lint_item = LintItem.find(params[:id])\n @lint_item.destroy\n respond_to do |format|\n if @lint_item.cart.lint_items.empty?\n format.html { redirect_to store_url, notice: 'Your cart is empty' }\n else \n format.html { redirect_to @lint_item.cart, notice: 'Product was successfully Removed.'}\n end\n format.json { head :no_content }\n end\n=end\n end", "def destroy\n current_cart.line_items.destroy_all\n current_cart.destroy\n session[:cart_id] = nil\n session[:referer] = nil\n respond_to do |format|\n format.html { redirect_to(root_path) }\n format.xml { head :ok }\n end\n end", "def remove_item(list_item,user_list)\n user_list.delete(list_item)\n user_list\nend", "def remove_item_verify\n\n\t\twait_for_animate\n\t\tvalue3= query(\"* marked:'quantityText'\", :text)[0]\n\t\tguide_price3 = query(\"* marked:'basket_action_bar_up'\", :text)[0]\n\t\tputs \"Quantity Before remove Item : : #{value3}\"\n\t\ttouch(\"* id:'remove_btn'\")\n\t\twait_for_animate\n\t\tsleep 4\n\t\t#wait_for_elements_exist( [\"button marked:'Open basket'\"], :timeout => 40)\n\t\tvalue4 = query(\"* marked:'quantityText'\", :text)[0]\n\t\tguide_price4 = query(\"* marked:'basket_action_bar_up'\", :text)[0]\n\t\tputs \"Values guide price & Quantity(remove :After) : #{guide_price4} #{value4}\"\n\t\tputs \"Count guide price #{guide_price4}\"\n\t\tputs \"Quantity campare\"\n\t\tcampare_values(value3, value4)\n\t\t# puts \"guideprice campare\"\n\t\t# campare_values(guide_price3,guide_price4)\n\t\t#puts \"Item added successfully\"\n\tend", "def destroy\n @biz.destroy\n redirect_to bizs_url\n end", "def index \n \n @page_title = \"Register for NAETI Courses\"\n @padding = true\n retrieve_shopping_cart\n \n if current_user\n @user = current_user\n else\n @user = User.new\n end\n \n #update cart for removals\n if params[:remove]\n for id in params[:shopping_cart_item][:ids]\n @shopping_cart_item = ShoppingCartItem.where(:id=>id).first\n @shopping_cart_item.destroy\n end\n end\n \n retrieve_shopping_cart\n\n if params[:user]\n \n if current_user\n @user.update_attributes(params[:user])\n @user = set_credit_card_info(@user)\n \n if @user.valid?\n process_checkout\n else\n flash.now[:notice] = \"Please correct the indicated fields.\"\n end\n else\n \n @user = User.new(params[:user])\n @user = set_credit_card_info(@user)\n \n if @user.valid?\n @user.save\n process_checkout\n else\n flash.now[:notice] = \"Please correct the indicated fields.\"\n end\n # end\n end\n\n end\n \n end", "def cart_action(current_user_id)\n if $redis.sismember \"cart#{current_user_id}\", id\n \"Remove from\"\n else\n \"Add to\"\n end\n end", "def delete_from_cart\n cart_op {|cart| cart.delete(params[:id].to_i); cart }\n render_cart_size\n end" ]
[ "0.7578817", "0.72867954", "0.7027629", "0.6891593", "0.68793637", "0.685834", "0.67777246", "0.66327655", "0.66145456", "0.6535209", "0.65331733", "0.6470347", "0.6469474", "0.6438997", "0.6421963", "0.6398868", "0.6397889", "0.6327976", "0.6323923", "0.63047916", "0.62818044", "0.62792414", "0.6277224", "0.6274843", "0.6242583", "0.6229333", "0.62126243", "0.62011045", "0.61570317", "0.6143483", "0.6137077", "0.6137077", "0.6137077", "0.61298084", "0.611831", "0.6097206", "0.60817856", "0.60788333", "0.6064661", "0.6061178", "0.60609186", "0.6060267", "0.6046588", "0.60385805", "0.60078263", "0.5996514", "0.59962004", "0.5968133", "0.5962008", "0.59533954", "0.5946169", "0.5942528", "0.59297055", "0.59270614", "0.5920326", "0.5917751", "0.5914298", "0.5906305", "0.59017235", "0.5900569", "0.5887607", "0.5881665", "0.5881665", "0.58814836", "0.58761525", "0.5871892", "0.5865726", "0.5864779", "0.5850077", "0.58416027", "0.58402276", "0.58356327", "0.58251977", "0.58210564", "0.5818489", "0.58071655", "0.5794721", "0.57891226", "0.5782274", "0.57750314", "0.57620984", "0.5759418", "0.57558465", "0.57558465", "0.5754692", "0.5744597", "0.57445514", "0.57412636", "0.5739994", "0.57345337", "0.5728917", "0.57223475", "0.57207376", "0.5720176", "0.5716273", "0.57121676", "0.5707718", "0.57067233", "0.5704773", "0.5698691" ]
0.78387153
0
GET /socials/1 GET /socials/1.json
def show @social = Story.find(params[:id]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def indexUserSocial\n render json: User.where( id: params[:user_id] ).last.socials.page(params[:page] || 1).per(params[:per] || 10) , status: 200\n end", "def show\n render json: @social_networking\n end", "def show\n @social_network = SocialNetwork.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @social_network }\n end\n end", "def showSocial\n social = Social.where( user_id: params[:user_id] ).where( id: params[:id] ).last\n if social\n render json: social , status: 200\n else\n render json: { error: \"شبکه اجتماعی یا کاربر پیدا نشد\" } , status: 404\n end\n end", "def index\n @social_media_links = SocialMediaLink.all\n\n render json: @social_media_links\n end", "def show\n render json: @social_media_link\n end", "def social\n @data['social']\n end", "def show\n @appdotnet_social = AppdotnetSocial.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @appdotnet_social }\n end\n end", "def show\n @socialmedium = Socialmedium.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @socialmedium }\n end\n end", "def show\n @social_contract = SocialContract.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @social_contract }\n end\n end", "def fetch_social\n social_fs\n social_ts\n end", "def show\n @social1 = Social.where(id: params[:id])\n if user_signed_in?\n @urls = []\n @location = GeoIP.new('lib/GeoLiteCity.dat').city(current_user.current_sign_in_ip)\n # @location = GeoIP.new('lib/GeoLiteCity.dat').city('110.136.133.185')\n @socials = Social.where(city: @location.city_name)\n @contact_author = User.where(name: @social.creator)\n @photo = @social.photos.where(default: true)\n videos = @social.media_urls.map(&:url)\n images = @social.photos.map(&:image_url)\n media_urls = images + videos\n media_urls.each do |url|\n if url.match(Regexp.union(/youtube.com/, /vimeo.com/))\n video = VideoInfo.new(url)\n @urls << video.thumbnail_small\n elsif url.match(/soundcloud.com/)\n soundcloud = HTTParty.get(\"http://api.soundcloud.com/resolve.json?url=#{url}&client_id=8f624be8e4a0dbb19d303b829a85501b\")\n @urls << soundcloud.parsed_response['artwork_url']\n else\n @urls << url\n end\n end\n else\n @socials = Social.all\n @photo = @social.photos.where(default: true)\n @contact_author = User.where(name: @social.creator)\n end\n end", "def new\n @social_network = SocialNetwork.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @social_network }\n end\n end", "def create\n \n @social = Social.new(params[:social])\n\n respond_to do |format|\n if @social.save\n format.html { redirect_to @social, notice: 'Social was successfully created.' }\n format.json { render json: @social, status: :created, location: @social }\n else\n format.html { render action: \"new\" }\n format.json { render json: @social.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_social\n @social = Social.find(params[:id])\n end", "def set_social\n @social = Social.find(params[:id])\n end", "def index\n @social_accounts = SocialAccount.all\n end", "def show\n @admin_social_medium = Admin::SocialMedium.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @admin_social_medium }\n end\n end", "def new\n @socialmedium = Socialmedium.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @socialmedium }\n end\n end", "def show\n\t\trequire_login\n\t\t@user = User.find(params[:id])\n\t\t@socials = Social::Social_type\n\tend", "def index\n @links = @site.site_social_links\n end", "def index\n @relationships = Relationship.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @relationships }\n end\n end", "def search\n @social_networkings, @total_count = Admin::SocialNetworking.search(params[:search], params[:pagination], params[:sorting])\n\n render json: { socialNetworkings: @social_networkings, totalCount: @total_count }\n end", "def show\n @providers = @profile.providers_data\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @profile }\n end\n end", "def by_sn(socialnumber)\n Apis.client.get(\"/company?socialnumber=#{socialnumber}\")\n end", "def github\n @data['social']['github']\n end", "def serv_json\n \"http://api.dribbble.com/shots/popular?page=1\"\n end", "def friends\n #get friends page\n #get json from friends page\n #parse\n []\n end", "def index\n @api_v1_social_link_segments = Api::V1::SocialLinkSegment.all\n end", "def show\n @default_facebook = DefaultFacebook.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @default_facebook }\n end\n end", "def show\n render json: @community\n end", "def twitter\n @data['social']['twitter']\n end", "def destroy\n @social = Social.find(params[:id])\n @social.destroy\n\n respond_to do |format|\n format.html { redirect_to '/' }\n format.json { head :no_content }\n end\n end", "def index\n redirect_to social_url\n end", "def show\n profile = Profile.find(params[:id])\n render status: 200, json: profile\n end", "def getUserBy_social_media( name, id)\n params = Hash.new\n params['name'] = name\n params['id'] = id\n return doCurl(\"get\",\"/user/by_social_media\",params)\n end", "def index\n @girlfriends = Girlfriend.all\n render json: @girlfriends, status: 200 \n end", "def show\n render json: Like.find(params[\"id\"])\n end", "def show\n @community = Community.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @community }\n end\n end", "def get_default_profile \n get(\"/profiles.json/default\")\nend", "def show\n @share = Share.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @share }\n end\n end", "def index\n @profiles = Profile.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @profiles }\n end\n end", "def index\n @social_events = SocialEvent.all\n end", "def index\n @relationships = @relationships.order(created_at: :desc).page(params[:page])\n\n respond_to do |format|\n format.html { @relationships = @relationships.includes(:follower, :followed) }\n format.json {}\n end\n end", "def index\n @susu_memberships = SusuMembership.page(params[:page]).per(params[:per])\n\n render json: @susu_memberships\n end", "def show\n @graph_membership_graph = GraphMembershipGraph.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @graph_membership_graph }\n end\n end", "def index\n @facebook_user_stories = GameRules::Rules.the_rules.facebook_user_stories\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @facebook_user_stories }\n end\n end", "def destroy\n @social.destroy\n respond_to do |format|\n format.html { redirect_to socials_url }\n format.json { head :no_content }\n end\n end", "def index\n @links = current_user.links.desc :created_at\n @title = 'Shared By You'\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @links }\n end\n end", "def index\n @profiles = Profile.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @profiles }\n end\n end", "def index\n @user_shares = UserShare.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @user_shares }\n end\n end", "def index\n head 404\n # @api_v1_followers = Api::V1::Follower.all\n\n # render json: @api_v1_followers\n end", "def show\n @relationship = Relationship.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @relationship }\n end\n end", "def index\n @wusersocials = Wusersocial.all\n end", "def index\n @communities = Community.all\n render json: {items: @communities}\n end", "def index\n render json: @links\n end", "def index\n @profiles = Profile.all\n respond_to do |format|\n format.html\n format.json do\n @profiles = Profile.near(\n [\n current_user.profile.latitude,\n current_user.profile.longitude\n ], params[:radius]\n ).distinct\n @profiles = @profiles.where.not(id: current_user.profile.id)\n @profiles = @profiles.min_age(params[:min_age]) if params[:min_age].present?\n @profiles = @profiles.max_age(params[:max_age]) if params[:max_age].present?\n @profiles = @profiles.by_gender(params[:gender]) if params[:gender].present?\n @profiles = @profiles.by_activity(params[:activity])\n\n render json: @profiles.map{|profile| profile.attributes.merge(image: profile.image.url(:medium))}\n end\n end\n end", "def new\n @appdotnet_social = AppdotnetSocial.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @appdotnet_social }\n end\n end", "def show\n user = User.find(params[:id])\n friendships = user.followers + user.followees\n render json: {user: user, friendships: friendships}\n end", "def index\n @broadcaster_social_entries = Broadcaster::SocialEntry.all\n end", "def url_list\n urls = current_user.mini_urls\n if urls.count > 0\n render json: {urls: urls}, status: 200\n else\n raise Exceptions::EmptyObjectError.new('No URL found.')\n end\n rescue Exceptions::EmptyObjectError => e\n render json: {error: e}, status: 404\n end", "def show\n @profile = Profile.find(params[:id])\n render json: @profile.to_json(include_hash)\n end", "def show\n @contact = Contact.find(params[:id])\n @stories = @contact.stories.order(\"updated_at desc\")\n # @contact.stories = Story.find(params[:contact_id])\n \n if @contact.twitter.present?\n @tweet = @contact.twitter\n twitter_url = \"http://search.twitter.com/search.json?q=#{@tweet}&include_entities=true&result_type=mixed&limit=10\"\n feeds = JSON.parse(open(twitter_url).read)\n @results = feeds[\"results\"]\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @contact }\n end\n end", "def index\n @likes = target.likes.includes(:author => :profile)\n @people = @likes.map(&:author)\n\n respond_to do |format|\n format.all { render :layout => false }\n format.json { render :json => @likes.as_api_response(:backbone) }\n end\n end", "def index\n @circle = current_user.circle\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @circle }\n end\n end", "def show\n @website = Website.find(params[:id])\n\n render json: @website\n end", "def index\n if params[:single]\n\t url = \"#{API_BASE_URL}/users/#{params[:id]}.json\"\n\t response = RestClient.get(url)\n\t @user = JSON.parse(response.body)\n\telse\n\t url = \"#{API_BASE_URL}/users.json\"\t \n response = RestClient.get(url)\n @users = JSON.parse(response.body)\t\t \n\tend\n end", "def index\n @profiles = Profile.all.paginate :page => params[:page], :per_page => 3\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @profiles }\n end\n end", "def index\n p = Profile.where(:username=>session[:username]).first\n if(!p.nil?)\n @sites = Profile.mysite(p.id)\n if(p.id==1)\n @sites = Site.find(:all, :order => \"created_at DESC\")\n end\n else\n redirect_to '/' and return\n end\n @site = Site.new\n @profile_id = Profile.where(:username=>session[:username]).first.id\n @categories = p.categories.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end", "def index\n @friendships = @user.friendships\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @friendships }\n end\n end", "def show\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def show\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def show\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def index\n @user = current_user\n render json: @user.friends\n end", "def privacy\n @api_v1_pages = Api::V1::Page.where('title = \"privacy\"').first\n\n render json: @api_v1_pages\n end", "def feed\n user = User.find(params[:id])\n following_ids = \"SELECT followed_id FROM relationships\n WHERE follower_id = :user_id\"\n microposts = Micropost.where(\"user_id IN (#{following_ids})\n OR user_id = :user_id\", user_id: params[:id])\n microposts_json = microposts_as_json(microposts.paginate(page: params[:page]))\n next_page = microposts.paginate(page: params[:page]).next_page\n @package = { next_page: next_page,\n microposts: microposts_json,\n is_current_user: (user == current_user) }\n render json: @package\n end", "def social\n @user = current_user\n @links = current_user.external_links\n \n # TWITTER\n if @user.user_content.twitter_token.blank?\n clientTwitter = TwitterOAuth::Client.new(:consumer_key => TwitterEnv::API_KEY, :consumer_secret => TwitterEnv::SECRET_KEY)\n request_token = clientTwitter.request_token(:oauth_callback => TwitterEnv::CALLBACK_URL) \n session[:rtoken_twitter] = request_token.token\n session[:rsecret_twitter] = request_token.secret\n @login_twitter_url = request_token.authorize_url\n end\n \n # FACEBOOK\n @login_facebook_url = Koala::Facebook::OAuth.new.url_for_oauth_code(:permissions => 'read_stream,offline_access')\n \n if params[:code]\n @user.user_content.facebook_token = Koala::Facebook::OAuth.new.get_access_token(params[:code])\n @user.user_content.save\n end\n \n # LINKEDIN\n if params[:oauth_verifier]\n client = LinkedIn::Client.new(LinkedIn::API_KEY, LinkedIn::SECRET_KEY)\n if @user.user_content.linkedin_token.blank?\n pin = params[:oauth_verifier]\n atoken, asecret = client.authorize_from_request(session[:rtoken], session[:rsecret], pin)\n @user.user_content.linkedin_token = atoken\n @user.user_content.linkedin_secret = asecret\n @user.user_content.save\n else\n client.authorize_from_access(@user.user_content.linkedin_token, @user.user_content.linkedin_secret)\n end\n else\n client = LinkedIn::Client.new(LinkedIn::API_KEY, LinkedIn::SECRET_KEY)\n request_token = client.request_token(:oauth_callback => LinkedIn::CALLBACK_URL)\n session[:rtoken] = request_token.token\n session[:rsecret] = request_token.secret\n @login_linkedin_url = client.request_token.authorize_url\n end\n \n respond_to do |format| \n if params[:ajax] == \"true\" # Request came from ajax. Respond without layout.\n format.html { render :layout => false } # social.html.erb\n else\n format.html # social.html.erb WITH layout\n end\n end\n end", "def index\n head 404\n # @api_v1_followings = Api::V1::Following.all\n\n # render json: @api_v1_followings\n end", "def index\n render json: current_org.users\n end", "def index\n authorize Profile\n @profiles = ProfilePolicy::Scope.new(current_user, @user.profiles).resolve\n render json: @profiles\n end", "def index\n @publinks = Publink.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @publinks }\n end\n end", "def index\n @followships = Follower.all\n render json: @followships\n end", "def show\n @profile = @user.profile\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end", "def grab_info(name)\n\n\n\n\n result = HTTParty.get(\"https://graph.facebook.com/#{name}\")\n\n user_fb = JSON.parse(result)\n\n# id = result[\"id\"]\n# name = result[\"name\"]\n# gender = result[\"gender\"]\n# locale = result[\"locale\"]\n# un = result[\"username\"]\n\nend", "def show\n @social_work = SocialWork.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @social_work }\n end\n end", "def index\n @likes = Like.all\n render json: @likes, status: 200\n end", "def reddit\n @data['social']['reddit']\n end", "def index\n @social_media_accounts = SocialMediaAccount.all\n end", "def index\n links = all_links\n render json: { success: true, links: links }\n end", "def show\n @shared_url = SharedUrl.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @shared_url }\n end\n end", "def show\n @twitter_list = TwitterList.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @twitter_list }\n end\n end", "def show\n @twitter_user = TwitterUser.find(params[:id])\n @follower_ids = Twitter.follower_ids(@twitter_user.twitter_username).collection\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @twitter_user }\n end\n end", "def index\n @activities = current_user.activities\n @profile = current_user.profile # Comeback too\n @categories = Category.all\n respond_to do |format|\n format.html\n format.json { render json: @activities }\n end\n end", "def index\n @friends = Friend.all\n render json: @friends\n end", "def index\n @stars = Star.all\n render :json => @stars\n end", "def index\n @g4_dongal_board_socials = G4DongalBoardSocial.all\n end", "def index\n @activities = Activity.all\n render json: @activities\n end", "def index\n @activity = Activity.find(params[:activity_id])\n @pictures = @activity.pictures\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pictures }\n end\n end", "def my_follows\n follows = paginate Follow.where(follower_id: params[:user_id])\n\n render json: follows.to_json(:include => :following)\n end" ]
[ "0.7387056", "0.73777515", "0.709712", "0.6965081", "0.68503934", "0.6846297", "0.6760098", "0.66520447", "0.65816677", "0.64837164", "0.64611864", "0.6303543", "0.63007665", "0.6280707", "0.6156164", "0.6156164", "0.6101346", "0.6059054", "0.60487026", "0.6044441", "0.6018291", "0.6003885", "0.597941", "0.5956481", "0.5931379", "0.5925272", "0.5922854", "0.5910022", "0.59088767", "0.5904854", "0.5877", "0.58763134", "0.5824046", "0.5823718", "0.5822245", "0.58019984", "0.5794547", "0.57905364", "0.5769132", "0.57658535", "0.5764026", "0.5756281", "0.5754104", "0.575209", "0.57061183", "0.5697393", "0.5696927", "0.5695412", "0.569306", "0.5692728", "0.56858426", "0.5676229", "0.5672852", "0.5667927", "0.5660807", "0.5655759", "0.5652948", "0.5634288", "0.5630205", "0.56245184", "0.5623779", "0.5618163", "0.5612102", "0.5605236", "0.5601118", "0.55995274", "0.5594485", "0.5594398", "0.55833596", "0.55765885", "0.55761224", "0.55761224", "0.55761224", "0.55747116", "0.557398", "0.55733335", "0.55684114", "0.5563774", "0.55586797", "0.5555159", "0.55508196", "0.5547324", "0.55468965", "0.5542231", "0.5539913", "0.55389416", "0.5537288", "0.55216354", "0.55184805", "0.5510032", "0.5507488", "0.5504144", "0.55038154", "0.5503303", "0.5501771", "0.5499679", "0.54990023", "0.54979444", "0.5496439", "0.54911256" ]
0.5827854
32
POST /socials POST /socials.json
def create @social = Story.create(social_params) redirect_to social_path(@social) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n \n @social = Social.new(params[:social])\n\n respond_to do |format|\n if @social.save\n format.html { redirect_to @social, notice: 'Social was successfully created.' }\n format.json { render json: @social, status: :created, location: @social }\n else\n format.html { render action: \"new\" }\n format.json { render json: @social.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @social_networking = Admin::SocialNetworking.new(social_networking_params)\n\n if @social_networking.save\n render json: @social_networking, status: :created\n else\n render json: @social_networking.errors, status: :unprocessable_entity\n end\n end", "def create\n @social_network = SocialNetwork.new(params[:social_network])\n\n respond_to do |format|\n if @social_network.save\n format.html { redirect_to @social_network, notice: 'Social network was successfully created.' }\n format.json { render json: @social_network, status: :created, location: @social_network }\n else\n format.html { render action: \"new\" }\n format.json { render json: @social_network.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @social_media_link = SocialMediaLink.new(social_media_link_params)\n\n if @social_media_link.save\n render json: @social_media_link, status: :created\n else\n render json: @social_media_link.errors, status: :unprocessable_entity\n end\n end", "def create\n location = GeoIP.new('lib/GeoLiteCity.dat').city(current_user.current_sign_in_ip)\n # location = GeoIP.new('lib/GeoLiteCity.dat').city('110.136.133.185')\n social_params[:lat].blank? ? social_params[:lat] << location.latitude.to_s : social_params[:lat]\n social_params[:long].blank? ? social_params[:long] << location.longitude.to_s : social_params[:long]\n social_params[:country].blank? ? social_params[:country] << location.country_name : social_params[:country]\n social_params[:city].blank? ? social_params[:city] << location.city_name : social_params[:city]\n @social = Social.new(social_params)\n @social.category = params[:category]\n if params[:selected].present?\n photos = Photo.find(params[:photos_id])\n photos.default = true\n photos.save\n end\n\n respond_to do |format|\n if @social.save\n if params[:url].present?\n params[:url].each do |key, value|\n @social.media_urls.create(url: value)\n end\n end\n if params[:photos].present?\n params[:photos].each do |key, value|\n photo = Photo.find(value)\n photo.social_id = @social.id\n photo.save\n end\n end\n format.html { redirect_to @social, notice: 'Social was successfully created.' }\n format.json { render action: 'show', status: :created, location: @social }\n else\n format.html { render action: 'new' }\n format.json { render json: @social.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @appdotnet_social = AppdotnetSocial.new(params[:appdotnet_social])\n\n respond_to do |format|\n if @appdotnet_social.save\n format.html { redirect_to @appdotnet_social, notice: 'Appdotnet social was successfully created.' }\n format.json { render json: @appdotnet_social, status: :created, location: @appdotnet_social }\n else\n format.html { render action: \"new\" }\n format.json { render json: @appdotnet_social.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @rede_social = RedeSocial.new(rede_social_params)\n @profile = 'adm'\n @rede_social.artist_data_id = @artist_data.id\n \n respond_to do |format|\n if @rede_social.save\n exist_redesocial_to_user\n format.js {render :index}\n else\n format.html { render :new } \n end\n end\n end", "def social_params\n params.require(:social).permit(:title, :description, :country, :city, :postal_code, :image, :creator, :lat, :long, :project_id, :event_id, :street, :category)\n end", "def create_social_session\n social_params ||= request.env[\"omniauth.auth\"]\n if social_params\n if signed_in?\n # user is associating their FB / Twitter account with their Brevidy account \n new_network ||= current_user.social_networks.new(:provider => social_params[\"provider\"], :uid => social_params[\"uid\"], :token => social_params[\"credentials\"][\"token\"], :token_secret => social_params[\"credentials\"][\"secret\"])\n \n respond_to do |format|\n if new_network.save\n format.html { redirect_to user_account_path(current_user) }\n format.json { render :json => { :success => true,\n :message => nil,\n :user_id => current_user.id }, \n :status => :created }\n else\n error_message ||= get_errors_for_class(new_network).to_sentence\n format.html { flash[:error] = error_message; redirect_to user_account_path(current_user) }\n format.json { render :json => { :success => false,\n :message => error_message,\n :user_id => current_user.id }, \n :status => :unprocessable_entity }\n end\n end\n else\n # user is either logging in or signing up via FB / Twitter\n # check if a user with that UID already exists\n social_credentials = SocialNetwork.find_by_provider_and_uid(social_params[\"provider\"], social_params[\"uid\"])\n \n if social_credentials.blank?\n # delete any old social image cookies so we don't set an incorrect image from a prior session\n cookies.delete(:social_image_url)\n cookies.delete(:social_bio)\n \n # create a new user and redirect to step 2 of the signup process\n @user = User.create_via_fb_or_twitter(social_params)\n # set cookies to remember the user's image and bio so we can set it after they are created\n case social_params[\"provider\"]\n when \"facebook\"\n cookies[:social_image_url] = social_params[\"user_info\"][\"image\"].gsub(\"type=square\", \"type=large\") rescue nil\n cookies[:social_bio] = social_params[\"extra\"][\"user_hash\"][\"bio\"] rescue nil\n when \"twitter\"\n cookies[:social_image_url] = social_params[\"extra\"][\"user_hash\"][\"profile_image_url_https\"].gsub(\"_normal\", \"\") rescue nil\n cookies[:social_bio] = social_params[\"extra\"][\"user_hash\"][\"description\"] rescue nil\n end\n \n respond_to do |format|\n format.html { ruby_code_from_view.ruby_code_from_view do |rb_from_view|\n compact_flash_messages \n unless flash.empty? \n @flash_key \n @flash_msg \n end \n # validation error field placeholder \n # do not remove \n if defined?(social_signup) \n # these instance vars get passed into the form \n @user = user \n @provider = provider \n @uid = uid \n @oauth_token = oauth_token \n @oauth_token_secret = oauth_token_secret \n @social_signup = social_signup \n form_for(@user, :html => { :class => \"ptxs\"}, :remote => true) do |f| \n @uid \n @provider \n @oauth_token \n @oauth_token_secret \n @social_signup \n @user.location \n unless @invitation.blank? \n @invitation.token \n end \n f.label(:username, \"Username\", :class => \"login_label\") \n f.text_field(:username, :autocomplete => :off, :id => \"signupUsername\", :placeholder => \"username\", :class => \"mls ras toolTipSignup\", :title => \"\", :tabindex => 1, \"data-path\" => username_availability_path) \n f.label(:name, \"Your Name (First & Last)\", :class => \"login_label\") \n f.text_field(:name, :autocomplete => :off, :id => \"signupName\", :placeholder => \"your name\", :class => \"mls ras toolTipSignup\", :title => \"We recommend using your real name so people you know can find you.\", :tabindex => 2) \n f.label(:email, \"E-mail\", :class => \"login_label\") \n f.text_field(:email, :autocomplete => :off, :id => \"signupEmail\", :placeholder => \"email address\", :class => \"mls ras toolTipSignup\", :title => \"We will not share your e-mail address with ANYONE. Period.\", :tabindex => 3) \n f.label(:password, \"Password\", :class => \"login_label\") \n f.password_field(:password, :autocomplete => :off, :id => \"signupPassword\", :placeholder => \"password\", :class => \"mls ras toolTipSignup\", :title => \"Passwords should be longer than 6 characters.\", :tabindex => 4) \n f.label(:birthday, \"Date of Birth (age verification only)\", :class => \"ml30 login_label\") \n options_for_select((1..12).map {|m| [Date::MONTHNAMES[m], m]}) \n options_for_select((1..31)) \n options_for_select((1901..Date.today.year).to_a.reverse) \n image_tag(\"ajax_white.gif\", :size => \"16x16\", :class => \"soft_hidden signup_ajax_animation\") \n end \n unless @user.birthday.blank? \n begin \n parsed_bday = Date.parse @user.birthday.to_s \n rescue \n end \n end \n \n else \n link_to(image_tag(\"social_signup_facebook.png\", :size => \"225x43\", :class => \"left mtl\"), \"#{root_url}auth/facebook\") \n link_to(image_tag(\"social_signup_twitter.png\", :size => \"225x43\", :class => \"left mtl\"), \"#{root_url}auth/twitter\") \n form_for(@user, :html => { :class => \"ptxs\"}, :remote => true) do |f| \n @uid \n @provider \n @oauth_token \n @oauth_token_secret \n @social_signup \n @user.location \n unless @invitation.blank? \n @invitation.token \n end \n f.label(:username, \"Username\", :class => \"login_label\") \n f.text_field(:username, :autocomplete => :off, :id => \"signupUsername\", :placeholder => \"username\", :class => \"mls ras toolTipSignup\", :title => \"\", :tabindex => 1, \"data-path\" => username_availability_path) \n f.label(:name, \"Your Name (First & Last)\", :class => \"login_label\") \n f.text_field(:name, :autocomplete => :off, :id => \"signupName\", :placeholder => \"your name\", :class => \"mls ras toolTipSignup\", :title => \"We recommend using your real name so people you know can find you.\", :tabindex => 2) \n f.label(:email, \"E-mail\", :class => \"login_label\") \n f.text_field(:email, :autocomplete => :off, :id => \"signupEmail\", :placeholder => \"email address\", :class => \"mls ras toolTipSignup\", :title => \"We will not share your e-mail address with ANYONE. Period.\", :tabindex => 3) \n f.label(:password, \"Password\", :class => \"login_label\") \n f.password_field(:password, :autocomplete => :off, :id => \"signupPassword\", :placeholder => \"password\", :class => \"mls ras toolTipSignup\", :title => \"Passwords should be longer than 6 characters.\", :tabindex => 4) \n f.label(:birthday, \"Date of Birth (age verification only)\", :class => \"ml30 login_label\") \n options_for_select((1..12).map {|m| [Date::MONTHNAMES[m], m]}) \n options_for_select((1..31)) \n options_for_select((1901..Date.today.year).to_a.reverse) \n image_tag(\"ajax_white.gif\", :size => \"16x16\", :class => \"soft_hidden signup_ajax_animation\") \n end \n unless @user.birthday.blank? \n begin \n parsed_bday = Date.parse @user.birthday.to_s \n rescue \n end \n end \n \n end \n\nend\n }\n end\n else\n # user already exists with that UID/provider combo, so they just want to login\n sign_in User.find_by_id(social_credentials.user_id)\n respond_to do |format|\n format.html { redirect_back_or user_stream_path(current_user) }\n end\n end # end blank?\n end # end signed_in?\n else\n respond_to do |format|\n error_message = \"There was an error communicating with Facebook or Twitter. Please try again in a few minutes!\"\n format.html { flash[:error] = error_message; redirect_to :login }\n format.json { render :json => { :success => false,\n :message => error_message,\n :user_id => false }, \n :status => :unauthorized }\n end\n end # end check for social params\n end", "def index\n @social_media_links = SocialMediaLink.all\n\n render json: @social_media_links\n end", "def indexUserSocial\n render json: User.where( id: params[:user_id] ).last.socials.page(params[:page] || 1).per(params[:per] || 10) , status: 200\n end", "def create\n @social_account = SocialAccount.new(social_account_params)\n @social_account.user_id = 1\n\n respond_to do |format|\n if @social_account.save\n format.html { redirect_to @social_account, notice: 'Social account was successfully created.' }\n format.json { render :show, status: :created, location: @social_account }\n else\n format.html { render :new }\n format.json { render json: @social_account.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @social_network = SocialNetwork.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @social_network }\n end\n end", "def create\n @social_event = SocialEvent.new(social_event_params)\n @social_event.user = current_user\n respond_to do |format|\n if @social_event.save\n format.html { redirect_to @social_event, notice: 'Social event was successfully created.' }\n format.json { render :show, status: :created, location: @social_event }\n else\n format.html { render :new }\n format.json { render json: @social_event.errors, status: :unprocessable_entity }\n end\n end\n end", "def post_users(users)\n self.class.post('https://api.yesgraph.com/v0/users', {\n :body => users.to_json,\n :headers => @options,\n })\n end", "def create\n @wusersocial = Wusersocial.new(wusersocial_params)\n\n respond_to do |format|\n if @wusersocial.save\n format.html { redirect_to @wusersocial, notice: 'Wusersocial was successfully created.' }\n format.json { render :show, status: :created, location: @wusersocial }\n else\n format.html { render :new }\n format.json { render json: @wusersocial.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_social_network(user)\n user.user_social_networks.create(uid: session[:omniauth]['uid'], provider: session[:omniauth]['provider'])\n sign_in_and_redirect user, event: :authentication\n session.delete(:omniauth)\n end", "def social_params\n params.require(:user).permit(:facebook, :instagram)\n end", "def show\n render json: @social_networking\n end", "def save\n Account.create!(account_params.map do |data|\n {\n type: :facebook,\n user: current_user,\n name: data[:name],\n data: data\n }\n end)\n\n render json: success\n end", "def update\n if @social_networking.update(social_networking_params)\n render json: @social_networking, status: :ok\n else\n render json: @social_networking.errors, status: :unprocessable_entity\n end\n end", "def create\n @socialmedium = Socialmedium.new(params[:socialmedium])\n\n respond_to do |format|\n if @socialmedium.save\n format.html { redirect_to @socialmedium, notice: 'Socialmedium was successfully created.' }\n format.json { render json: @socialmedium, status: :created, location: @socialmedium }\n else\n format.html { render action: \"new\" }\n format.json { render json: @socialmedium.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @social_concern = SocialConcern.new(social_concern_params)\n\n respond_to do |format|\n if @social_concern.save\n format.html { redirect_to @social_concern, notice: 'Social concern was successfully created.' }\n format.json { render action: 'show', status: :created, location: @social_concern }\n else\n format.html { render action: 'new' }\n format.json { render json: @social_concern.errors, status: :unprocessable_entity }\n end\n end\n end", "def socialParams\n params.permit( :name , :link)\n end", "def create\n @facebook_share = FacebookShare.new(facebook_share_params)\n\n respond_to do |format|\n if @facebook_share.save\n format.html { redirect_to @facebook_share, notice: 'Facebook share was successfully created.' }\n format.json { render action: 'show', status: :created, location: @facebook_share }\n else\n format.html { render action: 'new' }\n format.json { render json: @facebook_share.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @social.destroy\n respond_to do |format|\n format.html { redirect_to socials_url }\n format.json { head :no_content }\n end\n end", "def create\n name = params[\"name\"]\n linkedin_connections = params[\"linkedin_connections\"].to_i\n facebook_connections = params[\"facebook_connections\"].to_i\n twitter_followers = params[\"twitter_followers\"].to_i\n\n\n newuser = User.create(\n name: name, \n linkedin_connections: linkedin_connections,\n facebook_connections: facebook_connections, \n twitter_followers: twitter_followers,\n social_connection_index: User.compute_social_connection(\n linkedin_connections,\n facebook_connections,\n twitter_followers\n )\n )\n end", "def create\n @social_network = SocialNetwork.new(admin_social_network_params)\n\n respond_to do |format|\n if @social_network.save\n format.html { redirect_to admin_videos_url, notice: 'Social network was successfully created.' }\n format.json { render :show, status: :created, location: @social_network }\n else\n format.html { render :new }\n format.json { render json: @social_network.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @rede_social = RedeSocial.new(rede_social_params)\n @rede_social.artist_data_id = @artist_data.id\n respond_to do |format|\n if @rede_social.save\n format.js \n else\n format.html { render :new }\n format.json { render json: @rede_social.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @socialmedium = Socialmedium.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @socialmedium }\n end\n end", "def social\n @data['social']\n end", "def set_social\n @social = Social.find(params[:id])\n end", "def set_social\n @social = Social.find(params[:id])\n end", "def social\n @user = current_user\n @links = current_user.external_links\n \n # TWITTER\n if @user.user_content.twitter_token.blank?\n clientTwitter = TwitterOAuth::Client.new(:consumer_key => TwitterEnv::API_KEY, :consumer_secret => TwitterEnv::SECRET_KEY)\n request_token = clientTwitter.request_token(:oauth_callback => TwitterEnv::CALLBACK_URL) \n session[:rtoken_twitter] = request_token.token\n session[:rsecret_twitter] = request_token.secret\n @login_twitter_url = request_token.authorize_url\n end\n \n # FACEBOOK\n @login_facebook_url = Koala::Facebook::OAuth.new.url_for_oauth_code(:permissions => 'read_stream,offline_access')\n \n if params[:code]\n @user.user_content.facebook_token = Koala::Facebook::OAuth.new.get_access_token(params[:code])\n @user.user_content.save\n end\n \n # LINKEDIN\n if params[:oauth_verifier]\n client = LinkedIn::Client.new(LinkedIn::API_KEY, LinkedIn::SECRET_KEY)\n if @user.user_content.linkedin_token.blank?\n pin = params[:oauth_verifier]\n atoken, asecret = client.authorize_from_request(session[:rtoken], session[:rsecret], pin)\n @user.user_content.linkedin_token = atoken\n @user.user_content.linkedin_secret = asecret\n @user.user_content.save\n else\n client.authorize_from_access(@user.user_content.linkedin_token, @user.user_content.linkedin_secret)\n end\n else\n client = LinkedIn::Client.new(LinkedIn::API_KEY, LinkedIn::SECRET_KEY)\n request_token = client.request_token(:oauth_callback => LinkedIn::CALLBACK_URL)\n session[:rtoken] = request_token.token\n session[:rsecret] = request_token.secret\n @login_linkedin_url = client.request_token.authorize_url\n end\n \n respond_to do |format| \n if params[:ajax] == \"true\" # Request came from ajax. Respond without layout.\n format.html { render :layout => false } # social.html.erb\n else\n format.html # social.html.erb WITH layout\n end\n end\n end", "def create\n @g4_dongal_board_social = G4DongalBoardSocial.new(g4_dongal_board_social_params)\n\n respond_to do |format|\n if @g4_dongal_board_social.save\n format.html { redirect_to @g4_dongal_board_social, notice: 'G4 dongal board social was successfully created.' }\n format.json { render :show, status: :created, location: @g4_dongal_board_social }\n else\n format.html { render :new }\n format.json { render json: @g4_dongal_board_social.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @share_to_user = User.find_by(username: params[:username])\n @share = @share_to_user.in_shares.create!(\n sharee_id: current_user.id,\n sharer_id: params[:sharer_id]\n )\n\n render json: @share\n end", "def show\n render json: @social_media_link\n end", "def create\n @relationships = Relationship.paginate(:page => params[:page], :per_page => 30).order('updated_at DESC')\n @relationship = Relationship.create(params[:relationship])\n end", "def create\n @social_contract = SocialContract.new(params[:social_contract])\n\n respond_to do |format|\n if @social_contract.save\n format.html { redirect_to @social_contract, notice: 'Social contract was successfully created.' }\n format.json { render json: @social_contract, status: :created, location: @social_contract }\n else\n format.html { render action: \"new\" }\n format.json { render json: @social_contract.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @social_networking.destroy\n\n render json: @social_networking, status: :ok\n end", "def create\n @user_share = UserShare.new(params[:user_share])\n if @user_share.insert(current_user.id)\n render json: @user_share, status: :created\n else\n render json: @user_share.errors, status: :unprocessable_entity\n end\n end", "def index\n redirect_to social_url\n end", "def share(users)\n users.each do |user|\n f = user.friend_feed.build(friend_id: current_user, post_id: params[:post_id])\n f.save\n end\n end", "def fetch_social\n social_fs\n social_ts\n end", "def new\n @appdotnet_social = AppdotnetSocial.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @appdotnet_social }\n end\n end", "def rede_social_params\n params.require(:rede_social).permit(:artist_data_id, :facebook, :twitter, :instagram, :googleplus, :linkedid)\n end", "def rede_social_params\n params.require(:rede_social).permit(:artist_data_id, :facebook, :twitter, :instagram, :googleplus, :linkedid)\n end", "def follow_artist\n relationship = Relationship.create(params.require(:relationship).permit(:follower_id, :followed_id))\n render json: relationship\n end", "def showSocial\n social = Social.where( user_id: params[:user_id] ).where( id: params[:id] ).last\n if social\n render json: social , status: 200\n else\n render json: { error: \"شبکه اجتماعی یا کاربر پیدا نشد\" } , status: 404\n end\n end", "def update\n respond_to do |format|\n if @social.update(social_params)\n format.html { redirect_to @social, notice: 'Social was successfully updated.' }\n format.json { render :show, status: :ok, location: @social }\n else\n format.html { render :edit }\n format.json { render json: @social.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n feed = Feed.new(:user_id => params[:user_id], :name => params[:name])\n if feed.save\n render :json => feed, :status => :created\n else\n render :json => {:ok => false, :message => feed.errors}, :status => :unprocessable_entity\n end\n end", "def create\n @api_v1_social_link_segment = Api::V1::SocialLinkSegment.new(api_v1_social_link_segment_params)\n\n respond_to do |format|\n if @api_v1_social_link_segment.save\n format.html { redirect_to @api_v1_social_link_segment, notice: 'Social link segment was successfully created.' }\n format.json { render :show, status: :created, location: @api_v1_social_link_segment }\n else\n format.html { render :new }\n format.json { render json: @api_v1_social_link_segment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @social_work = SocialWork.new(params[:social_work])\n\n respond_to do |format|\n if @social_work.save\n format.html { redirect_to(@social_work, :notice => 'Obra Social Fue Creada Exitosamente') }\n format.xml { render :xml => @social_work, :status => :created, :location => @social_work }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @social_work.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @user = current_user\n @publicacion = @user.publicacions.new(publicacion_params)\n respond_to do |format|\n if @publicacion.save\n bitly = Bitly.client\n bitId = 2\n link = bitly.shorten(\"http://propes.herokuapp.com/publicacions/#{bitId}\").short_url\n client=@publicacion.twitter\n client.update(\"#{@publicacion.titulo}, #{@publicacion.ciudad}, Precio: #{@publicacion.precio}. Conocela: #{link}\")\n format.html { redirect_to @publicacion }\n format.json { render action: 'show', status: :created, location: @publicacion }\n else\n format.html { render action: 'new' }\n format.json { render json: @publicacion.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_share(share)\n path = \"/people/~/shares\"\n defaults = {:visibility => {:code => \"anyone\"}}\n post(path, MultiJson.dump(defaults.merge(share)), \"Content-Type\" => \"application/json\")\n end", "def destroy\n @social = Social.find(params[:id])\n @social.destroy\n\n respond_to do |format|\n format.html { redirect_to '/' }\n format.json { head :no_content }\n end\n end", "def create\n # @socialmediasite = Socialmediasite.new(socialmediasite_params)\n # @socialmediasite = current_login.socialmediasites.build(params[:socialmediasite])\n @socialmediasite = current_login.socialmediasites.new(socialmediasite_params)\n respond_to do |format|\n if @socialmediasite.save\n format.html { redirect_to @socialmediasite, notice: 'Socialmediasite was successfully created.' }\n format.json { render action: 'show', status: :created, location: @socialmediasite }\n else\n format.html { render action: 'new' }\n format.json { render json: @socialmediasite.errors, status: :unprocessable_entity }\n end\n end\n end", "def social_link_params\n params.require(:social_media_link).permit(:title, :url, :image_url)\n end", "def create\n @share = Share.new(profile: current_profile, shareable: @shareable)\n\n respond_to do |format|\n if @share.save\n format.html { redirect_to @redirect_location, notice: 'Shared!' }\n format.json { head :no_content }\n else\n format.html { redirect_to @redirect_location }\n format.json { render json: @share.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @users_interests_link = UsersInterestsLink.new(users_interests_link_params)\n\n respond_to do |format|\n if @users_interests_link.save\n format.html { redirect_to @users_interests_link, notice: 'Users interests link was successfully created.' }\n format.json { render :show, status: :created, location: @users_interests_link }\n else\n format.html { render :new }\n format.json { render json: @users_interests_link.errors, status: :unprocessable_entity }\n end\n end\n end", "def publish_json\n user_array = []\n @users.each do |user|\n user_array << { :guid => user.guid,\n :social_influence_rank => user.social_influence_rank,\n :channel => user.channel,\n :phone_number => user.phone_number,\n :queue_weight => user.queue_weight,\n :twitter_profile => user.twitter_profile,\n :klout => user.klout,\n :tweet_watchword => user.tweet_watchword, # The last Tweet they did that triggered an increase in weight\n :time => user.time,\n :queue_name => user.queue_name }\n end\n \n agent_array = []\n @agents.each do |agent|\n agent_array << { :guid => agent.guid,\n :name => agent.name,\n :phone_number => agent.phone_number }\n end\n\n result = { :users => user_array, :agents => agent_array }.to_json\n @bunny.publish_socialq(result)\n result\n end", "def feed\n user = User.find(params[:id])\n following_ids = \"SELECT followed_id FROM relationships\n WHERE follower_id = :user_id\"\n microposts = Micropost.where(\"user_id IN (#{following_ids})\n OR user_id = :user_id\", user_id: params[:id])\n microposts_json = microposts_as_json(microposts.paginate(page: params[:page]))\n next_page = microposts.paginate(page: params[:page]).next_page\n @package = { next_page: next_page,\n microposts: microposts_json,\n is_current_user: (user == current_user) }\n render json: @package\n end", "def link_params\n params.require(:social_link).permit(:social_link_id, :site_id, :user_name)\n end", "def social?\n @data['social'] != {}\n end", "def create\n groups = [];\n keywords = [];\n\n params[:groups].each do |group|\n g = Group.find_by_facebook_id(group[:id]) || Group.create({\n facebook_id: group[:id],\n name: group[:name]\n })\n groups << g\n end\n\n if params[:keywords]\n params[:keywords].each do |keyword|\n k = Keyword.find_by_name(keyword) || Keyword.create(name: keyword)\n keywords << k\n end\n end\n\n oauth = Koala::Facebook::OAuth.new(ENV[\"FACEBOOK_APP_ID\"], ENV[\"FACEBOOK_APP_SECRET\"])\n long_token = oauth.exchange_access_token_info(params[:user][:authToken])[\"access_token\"]\n user = User.find_by_email(params[:user][:email]) || User.create(email: params[:user][:email])\n user.update_attributes(auth_token: long_token)\n \n r = user.requests.create\n r.groups << groups\n r.keywords << keywords\n r.save\n\n # FacebookApi.new(r)\n render nothing: true\n end", "def create\n @admin_social_medium = Admin::SocialMedium.new(params[:admin_social_medium])\n\n respond_to do |format|\n if @admin_social_medium.save\n format.html { redirect_to admin_suppliers_url }\n format.json { render json: @admin_social_medium, status: :created, location: @admin_social_medium }\n else\n format.html { render action: \"new\" }\n format.json { render json: @admin_social_medium.errors, status: :unprocessable_entity }\n end\n end\n end", "def delete_all\n socials = @current_user.socials\n if socials\n if socials.destroy_all\n render json: { success: \" تمامی شبکه های اجتماهی حذف شدند \" } , status: 202\n else\n render json: socials.errors , status: 400\n end\n else\n render json: { error: \" شبکه های اجتماعی کاربر مورد نظر یافت نشد \" } , status: 404\n end\n end", "def social_link_params\n params.require(:social_link).permit(:name, :url_pattern, :image)\n end", "def create\n get_theme\n @broadcaster_social_entry = Broadcaster::SocialEntry.new(broadcaster_social_entry_params)\n @broadcaster_social_entry.broadcaster_theme = @theme\n\n respond_to do |format|\n if @broadcaster_social_entry.save\n format.html { redirect_to @broadcaster_social_entry, notice: 'Social entry was successfully created.' }\n format.json { render :show, status: :created, location: @broadcaster_social_entry }\n else\n format.html { render :new }\n format.json { render json: @broadcaster_social_entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def user\n @user.postFacebook \"hello\"\n response = {\n :message => params[:id],\n :name => user.screen_name\n }\n respond_to do |format|\n format.json { render :json => create_json(response), :status => 200 }\n end\n end", "def follow\n if request.post?\n fo_ids = params[:follow] \n #fo_str = \"\"\n #fo_cnt = fo_ids.length - 1\n #for i in 0..fo_cnt\n # fo_str +=fo_ids[i].to_s\n # fo_str += \",\" unless fo_cnt == i\n #end\n \n fo_ids.each do |fid|\n hydra = Typhoeus::Hydra.new\n uri = \"http://api.twitter.com/1/friendships/create.json\"\n req = Typhoeus::Request.new(uri,\n :method =>\"post\",\n :params =>{:user_id=>fid, :include_entities=>\"true\"})\n \n sign_request(req,uri)\n hydra.queue(req)\n hydra.run\n #puts req.response.inspect\n end\n end\n redirect_to :action=>\"index\", :page=>\"1\" \n end", "def create\n user = user_from_token\n @tweet = user.tweets.new()\n @tweet.tweet = params[:tweet]\n if @tweet.save\n render :json => @tweet, :status => :created\n else\n render :json => @tweet.errors, :status => :unprocessable_entity\n end\n end", "def spree_social_link_params\n params.require(:social_link).permit!\n end", "def friendships_create(options = {})\n @req.post(\"/1.1/friendships/create.json\", options)\n end", "def postEntitySocialmedia( entity_id, type, website_url)\n params = Hash.new\n params['entity_id'] = entity_id\n params['type'] = type\n params['website_url'] = website_url\n return doCurl(\"post\",\"/entity/socialmedia\",params)\n end", "def create(profile,graph)\n @mobile_user = MobileUser.new\n \n #set data in the object\n @mobile_user.email = profile[\"email\"]\n @mobile_user.name = profile[\"first_name\"]\n @mobile_user.last_name = profile[\"last_name\"]\n @mobile_user.nickname = profile[\"username\"]\n @mobile_user.fb_id = profile[\"id\"]\n @mobile_user.profile_picture_url = graph.get_picture(profile[\"id\"])\n @mobile_user.link = profile[\"link\"]\n @mobile_user.birthday = profile[\"birthday\"]\n @mobile_user.gender = profile[\"gender\"]\n @mobile_user.access_token= params[:access_token]\n \n respond_to do |format|\n if profile and @mobile_user.save\n format.json { render json: @mobile_user.api_token, status: :created, location: @mobile_user.api_token, :message=> \"Inicio de sesión exitosa\" }\n\n else\n format.json { render json: @mobile_user.errors, status: :unprocessable_entity }\n end\n end\n\n end", "def create\n @social_media_account = SocialMediaAccount.new(social_media_account_params)\n\n respond_to do |format|\n if @social_media_account.save\n format.html { redirect_to @social_media_account, notice: 'Social media account was successfully created.' }\n format.json { render :show, status: :created, location: @social_media_account }\n else\n format.html { render :new }\n format.json { render json: @social_media_account.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @share = Share.new(params[:share])\n\n respond_to do |format|\n if @share.save\n format.html { redirect_to @share, notice: 'Share was successfully created.' }\n format.json { render json: @share, status: :created, location: @share }\n else\n format.html { render action: \"new\" }\n format.json { render json: @share.errors, status: :unprocessable_entity }\n end\n end\n end", "def facebook\n @user = User.find(session[:user_id])\n f = @user.facebook\n unless f.present?\n redirect_to @user, :notice => \"Please add your facebook account!\"\n return\n end\n @feed = f.feed\n @posts = []\n @feed.each do |post|\n fb_post_id = post.raw_attributes[:id].split(\"_\")[1]\n if Post.exists?(:facebook_post_id => fb_post_id)\n @posts.push(Post.find_by_facebook_post_id(fb_post_id))\n else\n p = Post.new\n p.poster_facebook_id, p.facebook_post_id = post.raw_attributes[:id].split(\"_\")\n if User.exists?(:facebook_id => post.from.raw_attributes[:id])\n p.user_id = User.find_by_facebook_id(post.from.raw_attributes[:id]).id\n else\n p.user_id = -2\n end\n p.post_type = 4\n p.created_at = post.created_time.to_datetime\n url = \"#{post.endpoint}?access_token=#{@user.facebook_oauth_token}\"\n p_json = JSON.parse(open(URI.parse(url)).read)\n if p_json['message'].present?\n p.body = p_json['message']\n elsif p_json['story'].present?\n p.body = p_json['story']\n end\n if p.body.present? && p.save!\n @posts.push(p)\n if p_json['comments'].present? && p_json['comments']['data'].present?\n p_json['comments']['data'].each do |com|\n c = Comment.new\n c.poster_facebook_id = com['from']['id']\n if User.exists?(:facebook_id => c.poster_facebook_id)\n c.user_id = User.find_by_facebook_id(c.poster_facebook_id).id\n else\n c.user_id = -3\n end\n c.body = com['message']\n c.created_at = com['created_time'].to_datetime\n c.post_id = p.id\n c.save!\n end\n end\n end\n end\n end\n\n @body_class = 'facebook-background'\n respond_to do |format|\n format.html # facebook.html.erb\n format.json { render json: @posts }\n end\n end", "def create\n user_id= params[:creator_id]\n curTime =Time.now.strftime(\"%Y-%m-%d %H:%M:%S\")#Date.today\n channel_id=params[:channel_id]\n nickname=params[:nickname]\n fans=params[:fans]\n readers=params[:readers]\n comments=params[:comments]\n praises=params[:praises]\n sql = ActiveRecord::Base.connection() \n sql.insert \"INSERT INTO social_accounts SET channel_id='#{channel_id}', nickname='#{nickname}', \n readers=#{readers},\n fans=#{fans},\n comments='#{comments}', \n praises='#{praises}',\n creator_id='#{user_id}',\n created_at='#{curTime}',updated_at='#{curTime}'\" \n respond_to do |format|\n #@social_accounts = SocialAccount.select(\"social_accounts.fans,social_accounts.readers,social_accounts.praises,social_accounts.comments, \n#social_accounts.channel_id,social_accounts.nickname,social_accounts.id,social_accounts.creator_id,social_channels.name channel_name\").joins(\" left join social_channels on social_accounts.channel_id=social_channels.id where social_accounts.creator_id=#{user_id}\")\n getsocial_accounts\n format.html { render :index, notice: 'Social account was successfully created.' }\n #format.json { render :show, status: :created, location: @social_account }\n \n end\n \n end", "def follow\r\n @relationship = Relationship.create(follower_id: current_user.id, followed_id: params[:followed_id])\r\n @relationship.create_activity key: 'relationship.follow', owner: current_user, recipient: User.find(params[:followed_id])\r\n\r\n if @relationship.save\r\n render json: @relationship\r\n else\r\n render json: { error: \"Relationship creating error\" }, status: :unprocessable_entity\r\n end\r\n end", "def create\n # debugger\n like = Like.new(like_params)\n\n if like.save\n render json: like\n else\n render json: like.errors.full_messages, status: 422\n end\n end", "def create\n @anyshare = Anyshare.new(anyshare_params)\n\n respond_to do |format|\n if @anyshare.save\n format.html { redirect_to @anyshare, notice: 'Anyshare was successfully created.' }\n format.json { render :show, status: :created, location: @anyshare }\n else\n format.html { render :new }\n format.json { render json: @anyshare.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @default_facebook = DefaultFacebook.new(params[:default_facebook])\n @default_facebook.user_id = current_user.id\n\n respond_to do |format|\n if @default_facebook.save\n format.html { redirect_to @default_facebook, notice: 'Default facebook was successfully created.' }\n format.json { render json: @default_facebook, status: :created, location: @default_facebook }\n else\n format.html { render action: \"new\" }\n format.json { render json: @default_facebook.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @relationship = current_user.relationships.build(relationship_params)\n\n respond_to do |format|\n if @relationship.save\n format.html { redirect_to @relationship, notice: 'Relationship was successfully created.' }\n format.json { render :show, status: :created, location: @relationship }\n else\n format.html { render :new }\n format.json { render json: @relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n @social = Social.find(params[:id])\n\n respond_to do |format|\n if @social.update_attributes(params[:social])\n format.html { redirect_to '/', notice: 'Social was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @social.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post_share = PostShare.new(post_share_params)\n\n respond_to do |format|\n if @post_share.save\n format.html { redirect_to @post_share, notice: 'Post share was successfully created.' }\n format.json { render :show, status: :created, location: @post_share }\n else\n format.html { render :new }\n format.json { render json: @post_share.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @facebook_pixel = FacebookPixel.new(facebook_pixel_params)\n render json: @facebook_pixel.errors unless @facebook_pixel.save\n end", "def create\n @profile = Profile.new(profile_params)\n\n if @profile.save\n render json: @profile, status: :created\n else\n render json: @profile.errors, status: :unprocessable_entity\n end\n end", "def social_entry_params\n params.require(:social_entry).permit(\n :text,\n :user_id,\n :vote,\n :tags,\n creatable_tags: []\n )\n end", "def create\n params[:url_list].each do |url|\n WebUrl.new(:url => url).save\n end\n render :json=>params[:url_list].to_json\n end", "def social_params\n params.require(:story).permit(:title, :author, :category, :body, :img, :description)\n end", "def follows\n @follows = @user.follows\n\n respond_to do |format|\n format.html\n format.json { render :json => { :follows => @follows.map{|x| x.as_json(:json => 'friendship')}, :user => @user.as_json(:json => 'wall') }}\n end\n end", "def create\n respond_to do |format|\n if @relationship.save\n format.html { redirect_to @relationship.followed, notice: \"Now following #{@relationship.followed.name}.\" }\n format.json { render :index, status: :created, location: @relationship }\n format.js\n else\n format.html { render :index }\n format.json { render json: @relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @social_events = SocialEvent.all\n end", "def create\n @membership = Membership.new(membership_params)\n\n respond_to do |format|\n if @membership.save\n format.html { redirect_to community_memberships_path(@community), notice: 'Community membership was successfully created.' }\n format.json { render :show, status: :created, location: @membership }\n else\n format.html { render :new }\n format.json { render json: @membership.errors, status: :unprocessable_entity }\n end\n end\n end", "def add(social_action)\n\t\t\tkparams = {}\n\t\t\tclient.add_param(kparams, 'socialAction', social_action)\n\t\t\tclient.queue_service_action_call('socialaction', 'add', 'KalturaUserSocialActionResponse', kparams)\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\treturn client.do_queue()\n\t\tend", "def create\n @profile = Profile.create({\n name: params['profile']['name'],\n speciality: params['profile']['speciality'],\n city: params['profile']['city'],\n user_id: current_user['id']\n })\n @profile.save\n respond_with(@profile)\n end", "def create\n @eventslist = Event.create_from_twitter\n \n redirect_to events_url\n \n end", "def social_account_params\n params.require(:social_account).permit(:user_id, :social_platform_id)\n end" ]
[ "0.74315274", "0.6608617", "0.62561065", "0.6123282", "0.61076224", "0.59671944", "0.59575886", "0.5941007", "0.5903792", "0.58661276", "0.5860758", "0.5848099", "0.58363485", "0.58124346", "0.58062637", "0.5776592", "0.5771321", "0.57707304", "0.5752828", "0.5727452", "0.56713426", "0.5645242", "0.56299734", "0.5589593", "0.55844235", "0.5556263", "0.5548526", "0.5545942", "0.55304796", "0.550524", "0.5502768", "0.5501348", "0.5501348", "0.54791695", "0.5466738", "0.5461859", "0.5457961", "0.5443254", "0.5436646", "0.53973615", "0.5383837", "0.5377615", "0.5372697", "0.5365654", "0.5353095", "0.5319056", "0.5319056", "0.531683", "0.53122073", "0.5312079", "0.5299817", "0.529963", "0.52845055", "0.5255651", "0.5255177", "0.5250598", "0.5248218", "0.52481186", "0.524635", "0.52447927", "0.5242014", "0.52386594", "0.5231348", "0.52290946", "0.5226684", "0.52195287", "0.5217172", "0.52170557", "0.52136993", "0.52022165", "0.51992583", "0.51979965", "0.51938784", "0.5184892", "0.51816493", "0.5174271", "0.5158335", "0.5146228", "0.51353765", "0.51319164", "0.5129009", "0.50982106", "0.5078061", "0.5071697", "0.50712115", "0.5065242", "0.5061101", "0.5046064", "0.5044006", "0.5042758", "0.5037888", "0.50373197", "0.503539", "0.503221", "0.5029959", "0.50262547", "0.5007642", "0.50057197", "0.49972796", "0.49938774" ]
0.6124487
3
PATCH/PUT /socials/1 PATCH/PUT /socials/1.json
def update respond_to do |format| if @social.update(social_params) format.html { redirect_to @social, notice: 'Social was successfully updated.' } format.json { render :show, status: :ok, location: @social } else format.html { render :edit } format.json { render json: @social.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n\n @social = Social.find(params[:id])\n\n respond_to do |format|\n if @social.update_attributes(params[:social])\n format.html { redirect_to '/', notice: 'Social was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @social.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @social.update(social_params)\n format.html { redirect_to @social, notice: 'Social was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @social.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @social_networking.update(social_networking_params)\n render json: @social_networking, status: :ok\n else\n render json: @social_networking.errors, status: :unprocessable_entity\n end\n end", "def update\n @appdotnet_social = AppdotnetSocial.find(params[:id])\n\n respond_to do |format|\n if @appdotnet_social.update_attributes(params[:appdotnet_social])\n format.html { redirect_to @appdotnet_social, notice: 'Appdotnet social was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @appdotnet_social.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @social_concern.update(social_concern_params)\n format.html { redirect_to @social_concern, notice: 'Social concern was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @social_concern.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @full_profile.update(social_profile_params)\n format.html { redirect_to @current_user, notice: 'Social profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @current_user }\n else\n format.html { render :edit }\n format.json { render json: @full_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @social_account.update(social_account_params)\n format.html { redirect_to @social_account, notice: 'Social account was successfully updated.' }\n format.json { render :show, status: :ok, location: @social_account }\n else\n format.html { render :edit }\n format.json { render json: @social_account.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n relationship = Relationships.find(params[:id])\n if relationship.update(relationship_params)\n render json: relationship, status: 200\n else\n render json: { errors: relationship.errors }, status: 422\n end\n end", "def update\n @social_contract = SocialContract.find(params[:id])\n\n respond_to do |format|\n if @social_contract.update_attributes(params[:social_contract])\n format.html { redirect_to @social_contract, notice: 'Social contract was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @social_contract.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @rede_social.update(rede_social_params)\n format.js { render :create}\n format.json { render :show, status: :ok, location: @rede_social }\n else\n format.html { render :edit }\n format.json { render json: @rede_social.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n respond_to do |format|\r\n if @social_account.update(social_account_params)\r\n format.html { redirect_to root_url, notice: 'Social account was successfully updated.' }\r\n format.json { render :show, status: :ok, location: @social_account }\r\n else\r\n format.html { render :edit }\r\n format.json { render json: @social_account.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n @default_facebook = DefaultFacebook.find(params[:id])\n @default_facebook = current_user.default_facebooks.find(params[:id])\n\n respond_to do |format|\n if @default_facebook.update_attributes(params[:default_facebook])\n format.html { redirect_to @default_facebook, notice: 'Default facebook was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @default_facebook.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @social_network = SocialNetwork.find(params[:id])\n\n respond_to do |format|\n if @social_network.update_attributes(params[:social_network])\n format.html { redirect_to @social_network, notice: 'Social network was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @social_network.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(url, data)\n RestClient.put url, data, :content_type => :json\nend", "def update\n if request.content_type == \"application/json\"\n # .update is like a \"update people set ...\" in sql\n if @person.update(person_params)\n render json: @person\n else\n render json: @person.errors, status: :not_found\n end\n else\n render status: :bad_request\n end\n end", "def update\n render json: User.update(params[\"id\"], params[\"user\"])\n end", "def update\n respond_to do |format|\n if @socialmediasite.update(socialmediasite_params)\n format.html { redirect_to @socialmediasite, notice: 'Socialmediasite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @socialmediasite.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n id = params[\"id\"].to_i\n name = params[\"name\"]\n linkedin_connections = params[\"linkedin_connections\"].to_i\n facebook_connections = params[\"facebook_connections\"].to_i\n twitter_followers = params[\"twitter_followers\"].to_i\n\n user = User.find(id)\n user.update(\n id: id,\n name: name, \n linkedin_connections: linkedin_connections, \n facebook_connections: facebook_connections, \n twitter_followers: twitter_followers,\n social_connection_index: User.compute_social_connection(\n linkedin_connections,\n facebook_connections,\n twitter_followers\n )\n )\n end", "def update\n @socialmedium = Socialmedium.find(params[:id])\n\n respond_to do |format|\n if @socialmedium.update_attributes(params[:socialmedium])\n format.html { redirect_to @socialmedium, notice: 'Socialmedium was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @socialmedium.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @social_event.update(social_event_params)\n format.html { redirect_to @social_event, notice: 'Social event was successfully updated.' }\n format.json { render :show, status: :ok, location: @social_event }\n else\n format.html { render :edit }\n format.json { render json: @social_event.errors, status: :unprocessable_entity }\n end\n end\n end", "def jsonapi_update!(attributes)\n assign_jsonapi_attributes(attributes)\n save!\n end", "def update\n respond_to do |format|\n if @facebook_share.update(facebook_share_params)\n format.html { redirect_to @facebook_share, notice: 'Facebook share was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @facebook_share.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def update\n render json: Like.update(params[\"id\"], params[\"like\"])\n end", "def update(attrs, path=nil)\n resp = api_client.put(path || url, JSON.dump(attrs))\n refresh(JSON.load(resp.body))\n end", "def update\n # puts \"profile_params: #{profile_params[:sport_ids]}\"\n\n respond_to do |format|\n begin\n if current_user != @profile.user\n performing_follow?\n @profile.user.toggle_followed_by(current_user)\n # the next two lines are all about the redirecting or the 'resheshing' of a page so that you can see the result of follow and unfollow without having to refresh.\n format.html { redirect_to @profile.user }\n format.json { render :show, status: :ok, location: @profile }\n end\n\n @profile.update(profile_params)\n # add skill objects and save to db\n # profile_params[:sport_ids].each do |sport_id|\n # Skill.create!(profile_id: @profile.user.id, sport_id: sport_id)\n # end\n format.html { redirect_to profile_url, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n rescue\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n render json: Company.update(params[\"id\"], params[\"company\"])\n end", "def put_update(options = {})\n options[:id] ||= @website.id\n options[:website] ||= @attributes\n\n put :update,options\n end", "def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end", "def update\n render json: @facebook_pixel.errors unless @facebook_pixel.update(facebook_pixel_params)\n end", "def update # PATCH\n raise NotImplementedError\n end", "def update\n @social_media_link = SocialMediaLink.find(params[:id])\n\n if @social_media_link.update(social_media_link_params)\n head :no_content\n else\n render json: @social_media_link.errors, status: :unprocessable_entity\n end\n end", "def update\n @admin_social_medium = Admin::SocialMedium.find(params[:id])\n\n respond_to do |format|\n if @admin_social_medium.update_attributes(params[:admin_social_medium])\n format.html { redirect_to admin_suppliers_url }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @admin_social_medium.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n render json: Users.update(params[\"id\"], params[\"user\"])\n end", "def update\n @social_work = SocialWork.find(params[:id])\n\n respond_to do |format|\n if @social_work.update_attributes(params[:social_work])\n format.html { redirect_to(@social_work, :notice => 'Obra Social Fue Editada Exitosamente') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @social_work.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @user.update(user_params) \n format.html { redirect_to \"/auth/facebook\" }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @account = Account.find(params[:id])\n\n respond_to do |format|\n if @account.update_attributes(params[:account])\n #current_user.twitter.update(@account.content) if params[:twitter] == 'yes'\n #if params[:facebook] == 'yes'\n # current_user.facebook.feed!(:message => \"test\",\n # :link => \"http://moonkey.jp\",\n # :name => \"TEST\",\n # :description => \"test\")\n #end\n format.html { redirect_to accounts_url }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @account.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_social_link_segment.update(api_v1_social_link_segment_params)\n format.html { redirect_to @api_v1_social_link_segment, notice: 'Social link segment was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_social_link_segment }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_social_link_segment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @interest = Interest.find(params[:id])\n \n respond_to do |format|\n if @interest.update_attributes(params[:interest])\n format.json { head :ok }\n else\n format.json { render :json => @interest.errors,\n :status => :unprocessable_entity }\n end\n end\n end", "def patch!\n request! :patch\n end", "def update\n respond_to do |format|\n if @community.update(params[:community].permit(:name, :about, :link, :rss, :tag_list, :category_list))\n format.html { redirect_to @community, notice: 'Community was successfully updated.' }\n format.json { render :show, status: :ok, location: @community }\n else\n format.html { render :edit }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def put!\n request! :put\n end", "def update\n question = Question.find_by!(id: params[:id])\n if question\n question.name = params[:name]\n question.description = params[:description]\n question.user_id = params[:user_id]\n question.category_id = params[:category_id]\n question.zavrseno = params[:zavrseno]\n question.uposlenik_id = params[:uposlenik_id]\n question.save\n render json: question, status: 200 \n else\n render json: { errors: \"This link is invalid.\"}, status: 404\n end\n end", "def update_profile(body={})\n perform_post(\"/account/update_profile.json\", :body => body)\nend", "def update\n new_properties = params[:d]\n profile = Profile[params[:id]]\n profile.update_with(new_properties)\n\n respond_with(profile) do |format|\n format.json { render json: profile.stripped }\n end\n end", "def update\n errors = {}\n if ! ensure_same_as_logged_person(params['user_id'])\n render_json :status => :forbidden and return\n end\n @person = Person.find_by_guid(params['user_id'])\n if ! @person\n render_json :status => :not_found and return\n end\n if params[:person]\n begin\n if @person.json_update_attributes(params[:person])\n render_json :entry => @person.to_hash(@user, @client) and return\n end\n rescue NoMethodError => e\n errors = e.to_s\n end\n end\n\n render_json :status => :bad_request, :messages => @person.errors.full_messages\n @person = nil\n end", "def update\n respond_to do |format|\n @profile = 'adm'\n if @rede_social.update(rede_social_params)\n exist_redesocial_to_user\n format.js { render :index} \n else\n format.js { render :edit } \n end\n end\n end", "def update\n @profile.update(profile_params)\n respond_with(@profile)\n end", "def update\n put :update\n end", "def update\n respond_to do |format|\n if @g4_dongal_board_social.update(g4_dongal_board_social_params)\n format.html { redirect_to @g4_dongal_board_social, notice: 'G4 dongal board social was successfully updated.' }\n format.json { render :show, status: :ok, location: @g4_dongal_board_social }\n else\n format.html { render :edit }\n format.json { render json: @g4_dongal_board_social.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n @foaf.interests.clear\n\n if(foaf_params.has_key?(:interests_attributes))\n interest_ids = foaf_params[:interests_attributes].split(\",\").map { |s| s.to_i }\n interest_ids.each do |i|\n @foaf.interests << Interest.find(i)\n #@foaf.update(Interest.find(i))\n end\n \n end\n\n respond_to do |format|\n if @foaf.update(name: foaf_params[:name], work: foaf_params[:work], \n slug: foaf_params[:slug], birthday: foaf_params[:birthday])\n format.html { redirect_to @foaf, notice: 'Foaf was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @foaf.errors, status: :unprocessable_entity }\n end\n end\n end", "def update options={}\n client.put(\"/#{id}\", options)\n end", "def update\n @share = Share.find(params[:id])\n\n respond_to do |format|\n if @share.update_attributes(params[:share])\n format.html { redirect_to @share, notice: 'Share was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @share.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @person = Person.find(params[:id]) \n respond_to do |format|\n if @person.update(person_params)\n format.json { render json: @person, status: :ok }\n else\n format.json { render json: @person.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @relationship = Relationship.find(params[:id])\n\n respond_to do |format|\n if @relationship.update_attributes(params[:relationship])\n format.html { redirect_to @relationship, notice: 'Relationship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @person = Person.find(params[:id])\n @provider = Provider.find(params[:provider_id]) unless params[:provider_id].blank?\n\n respond_to do |format|\n if @person.update_attributes(params[:person])\n\n path = people_path\n msg = 'Person was successfully updated.'\n if @participant\n path = participant_path(@participant, :anchor => \"relationships_tab\")\n msg = 'Person was successfully updated.'\n end\n if @provider\n path = provider_path(@provider)\n msg = \"Person was successfully updated for #{@provider}.\"\n end\n\n format.html { redirect_to(path, :notice => msg) }\n format.json { render :json => @person }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @person.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n user_id=session[:user_id]\n respond_to do |format|\n if @social_account.update(social_account_params)\n #@social_accounts = SocialAccount.select(\"social_accounts.fans,social_accounts.readers,social_accounts.praises,social_accounts.comments,social_channels.name,\n#social_accounts.channel_id,social_accounts.nickname,social_accounts.id,social_accounts.creator_id\").joins(\" left join social_channels on social_accounts.channel_id=social_channels.id where social_accounts.creator_id=#{user_id}\")\n getsocial_accounts\n format.html { render :index, notice: 'Social account was successfully updated.' }\n format.json { render :show, status: :ok, location: @social_account }\n else\n format.html { render :edit }\n format.json { render json: @social_account.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n @foaf.interests.clear\n\n if(foaf_params.has_key?(:interests_attributes))\n interest_ids = foaf_params[:interests_attributes].split(\",\").map { |s| s.to_i }\n interest_ids.each do |i|\n @foaf.interests << Interest.find(i)\n #@foaf.update(Interest.find(i))\n end\n \n end\n\n respond_to do |format|\n if @foaf.update(name: foaf_params[:name], work: foaf_params[:work], \n slug: foaf_params[:slug], birthday: foaf_params[:birthday])\n format.html { redirect_to @foaf, notice: 'FOAF was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @foaf.errors, status: :unprocessable_entity }\n end\n end\n end", "def modify(name: nil, avatar: nil, channel_id: nil)\n RestClient.patch(@url, { name: name, avatar: avatarise(avatar), channel_id: channel_id }.compact.to_json, content_type: :json)\n end", "def update\n @graph.update_attributes_from_request(update_params)\n head :no_content\n end", "def update(attributes = {})\n set_all(attributes)\n ensure_client && ensure_uri\n response = @client.rest_put(@data['uri'], { 'Accept-Language' => 'en_US', 'body' => @data }, @api_version)\n @client.response_handler(response)\n self\n end", "def update_by_body\n @person = Person.find(person_update_params[:id])\n\n if @person.update_attributes(person_update_params)\n render json: { status: 'PUT Success' }, status: :ok\n else\n render json: { status: 'Error', message:'Error updating person', person: @person.errors }, status: :unprocessable_entity\n end\n end", "def update\n @todo = Todo.find(params[:id])\n @todo.update_attributes(params[:todo])\n render :json => @todo\n end", "def update\n @pictures = Picture.all.order(created_at: :desc)\n @picture.update(picture_params)\n render json: @pictures\n # head :no_content\n end", "def update\n respond_to_update({thing: @author})\n end", "def update\n head 404\n # @api_v1_follower = Api::V1::Follower.find(params[:id])\n\n # if @api_v1_follower.update(api_v1_follower_params)\n # head :no_content\n # else\n # render json: @api_v1_follower.errors, status: :unprocessable_entity\n # end\n end", "def update \n user = User.find(params[:id])\n # byebug\n user.update(user_params)\n\n render json: user\n end", "def update\n @todo = Todo.find(params[:todo][:id])\n if @todo.update_attributes(user_params)\n render json: @todo\n else\n render nothing: true, status: :bad_request\n end\n end", "def update\n respond_to do |format|\n if @anyshare.update(anyshare_params)\n format.html { redirect_to @anyshare, notice: 'Anyshare was successfully updated.' }\n format.json { render :show, status: :ok, location: @anyshare }\n else\n format.html { render :edit }\n format.json { render json: @anyshare.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n contact = Contact.find(params[:id])\n\n if contact.user_id == current_user.id\n contact.update_attributes(params[:contact])\n render json: contact\n else\n render text: \"That's not your contact!\"\n end\n end", "def update\n render json: Post.update(params[\"id\"], params[\"post\"])\n end", "def update\n @person_info = PersonInfo.find(params[:id])\n\n if @person_info.update(person_info_params(params[:person_info]))\n head :no_content\n else\n render json: @person_info.errors, status: :unprocessable_entity\n end\n end", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def update\n @extra = Extra.find(params[:id])\n\n if @extra.update(extra_params)\n head :no_content\n else\n render json: @extra.errors, status: :unprocessable_entity\n end\n end", "def update(attributes = {})\n set_all(attributes)\n ensure_client && ensure_uri\n response = @client.rest_put(@data['uri'], { 'Accept-Language' => 'en_US', 'body' => @data }, @api_version)\n @client.response_handler(response)\n self\n end", "def update!(**args)\n @id = args[:id] if args.key?(:id)\n @kind = args[:kind] if args.key?(:kind)\n @name = args[:name] if args.key?(:name)\n @starred = args[:starred] if args.key?(:starred)\n @web_properties = args[:web_properties] if args.key?(:web_properties)\n end", "def clear_default_profile \n put(\"/profiles.json/default/clear\")\nend", "def update\n respond_to do |format|\n if @broadcaster_social_entry.update(broadcaster_social_entry_params)\n format.html { redirect_to @broadcaster_social_entry, notice: 'Social entry was successfully updated.' }\n format.json { render :show, status: :ok, location: @broadcaster_social_entry }\n else\n format.html { render :edit }\n format.json { render json: @broadcaster_social_entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @wusersocial.update(wusersocial_params)\n format.html { redirect_to @wusersocial, notice: 'Wusersocial was successfully updated.' }\n format.json { render :show, status: :ok, location: @wusersocial }\n else\n format.html { render :edit }\n format.json { render json: @wusersocial.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(request)\n end", "def update(request)\n end", "def update\n head 404\n # @api_v1_following = Api::V1::Following.find(params[:id])\n\n # if @api_v1_following.update(api_v1_following_params)\n # head :no_content\n # else\n # render json: @api_v1_following.errors, status: :unprocessable_entity\n # end\n end", "def update\n @profile = Profile.find(current_user.id)\n @profile.update_attributes(params[:profile])\n respond_with @profile\n end", "def update_profile! (data = {})\n check_auth :update\n \n response = connection.put do |req|\n req.url '/user/update'\n req.body = { :format => @format }.merge(data)\n end\n response\n end", "def update\n @persona = Persona.find(params[:id])\n \n respond_to do |format|\n if @persona.update_attributes(params[:persona])\n format.json { head :ok }\n else\n format.json { render :json => @persona.errors,\n :status => :unprocessable_entity }\n end\n end\n end", "def update\n @supermarket = Supermarket.find(params[:id]) \n respond_to do |format|\n if @supermarket.update(supermarket_params)\n format.json { render json: @supermarket, status: :ok }\n end\n end\n end", "def update\n respond_to do |format|\n if @relationship.update(relationship_params)\n format.html { redirect_to @relationship, notice: 'Relationship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @relationship.errors, status: :200 }\n end\n end\n end", "def update\n @circle = Circle.find(params[:id])\n\n respond_to do |format|\n if @circle.update_attributes(params[:circle])\n format.html { redirect_to @circle, :notice => 'Circle was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @circle.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n request_body_Data= '{ \"widget\":\n {\n \"name\" : \"'+params[:name]+'\",\n \"description\" : \"'+params[:description]+'\"\n }}'\n response = RestClient::Request.new({\n method: :put,\n url: ENV['API_URL'] + '/widgets/' + params[:id],\n payload: request_body_Data,\n headers: { Authorization: session[:access_token], content_type: 'application/json'}\n }).execute do |response, request, result|\n case response.code\n when 400\n [ :error, JSON.parse(response) ]\n when 200\n [ :success, JSON.parse(response) ]\n json=JSON.parse(response)\n @widget= Widget.new do |widget|\n widget.id=json[\"data\"][\"widget\"][\"id\"]\n widget.name=json[\"data\"][\"widget\"][\"name\"]\n widget.description=json[\"data\"][\"widget\"][\"description\"]\n widget.kind=json[\"data\"][\"widget\"][\"kind\"]\n widget.userid=json[\"data\"][\"widget\"][\"user\"][\"id\"]\n widget.username=json[\"data\"][\"widget\"][\"user\"][\"name\"]\n widget.owner=json[\"data\"][\"widget\"][\"owner\"]\n end\n else\n fail \"Invalid response #{response.to_str} received.\"\n end\n end\n respond_to do |format|\n if @widget\n format.html { redirect_to @widget, notice: 'Widget was successfully updated.' }\n format.json { render :show, status: :ok, location: @widget }\n else\n format.html { render :edit }\n format.json { render json: @widget.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @circle = Circle.find(params[:id])\n\n respond_to do |format|\n if @circle.update_attributes(params[:circle])\n format.html { redirect_to @circle, notice: 'Circle was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @circle.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @circle = Circle.find(params[:id])\n\n respond_to do |format|\n if @circle.update_attributes(params[:circle])\n format.html { redirect_to @circle, notice: 'Circle was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @circle.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if params.has_key? :like\n @client.put(\"/me/favorites/#{params[:id]}\")\n head :ok and return\n end\n\n if params.has_key? :unlike\n @client.delete(\"/me/favorites/#{params[:id]}\")\n head :ok and return\n end\n\n if params.has_key? :repost\n @client.put(\"/me/track_reposts/#{params[:id]}\")\n head :ok and return\n end\n\n if params.has_key? :unpost\n @client.delete(\"/me/track_reposts/#{params[:id]}\")\n head :ok and return\n end\n\n head :bad_request\n end", "def update\n # go to params hash and get the id\n the_id = params['id']\n\n # grab a single family based on the id\n family = Family.find_by(id: the_id)\n\n # update it\n if family.update!(\n first_name: params[:first_name],\n last_name: params[:last_name],\n email: params[:email],\n password: params[:password],\n phone_number: params[:phone_number],\n street_address: params[:street_address],\n secondary_address: params[:secondary_address],\n city: params[:city],\n state: params[:state],\n zip_code: params[:zip_code],\n photo: params[:photo])\n render json: family.as_json\n else\n render json: {errors: family.errors.full_messages}\n end\n end", "def patch\n headers = {\"If-Match\" => @version}\n response = @context.request :patch, \"#{@path}/#{@id}\", @data.to_json, headers\n @version += 1\n response\n # 'X-HTTP-Method-Override' => 'PATCH'\n end", "def update\n @community = Community.find(params[:id])\n\n respond_to do |format|\n if @community.update_attributes(params[:community])\n format.html { redirect_to @community, notice: 'Community was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @community.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @rest.update(rest_params)\n format.html { redirect_to @rest, notice: 'Rest was successfully updated.' }\n format.json { render :show, status: :ok, location: @rest }\n else\n format.html { render :edit }\n format.json { render json: @rest.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @go_slim = GoSlim.find(params[:id])\n\n respond_to do |format|\n if @go_slim.update_attributes(params[:go_slim])\n format.html { redirect_to @go_slim, notice: 'Go slim was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @go_slim.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n #@profile = UsersDisciplines.find(params[:id])\n @profile = Profile.find_by_user_id(current_user.id)\n \n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to users_profile_index_path, notice: t(:profile_successfully_updated) }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end" ]
[ "0.72042495", "0.70514506", "0.6772194", "0.64453024", "0.6419766", "0.6323626", "0.6231504", "0.6214845", "0.61820847", "0.61677885", "0.6157639", "0.61163336", "0.6104987", "0.6037311", "0.6006371", "0.5984298", "0.5972196", "0.5962332", "0.59486806", "0.5934311", "0.5900582", "0.5898651", "0.5896655", "0.58891225", "0.58848095", "0.5882354", "0.58559525", "0.58512276", "0.5842242", "0.58199954", "0.58162856", "0.58110356", "0.58043635", "0.5803139", "0.58018875", "0.5801245", "0.57911026", "0.57908624", "0.5786419", "0.5783904", "0.5779114", "0.57757235", "0.5774071", "0.57738197", "0.5733685", "0.5731291", "0.5717531", "0.5714397", "0.5713972", "0.5707368", "0.57071924", "0.56996536", "0.56936157", "0.5690902", "0.5689451", "0.56887937", "0.5685822", "0.5675216", "0.5675009", "0.5674045", "0.56613714", "0.5657692", "0.5653338", "0.56470597", "0.56466705", "0.56455845", "0.5642603", "0.56387925", "0.5638791", "0.56353587", "0.562954", "0.56261575", "0.561338", "0.561338", "0.5606162", "0.5601763", "0.560135", "0.55939096", "0.5591509", "0.5589266", "0.55859184", "0.55859184", "0.55826557", "0.55806357", "0.55782026", "0.5576525", "0.5571932", "0.5570267", "0.5570052", "0.5564504", "0.55604446", "0.55604446", "0.5552024", "0.5547593", "0.55442464", "0.5543044", "0.5534916", "0.5533902", "0.5533256", "0.5532254" ]
0.69970423
2
DELETE /socials/1 DELETE /socials/1.json
def destroy end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @social = Social.find(params[:id])\n @social.destroy\n\n respond_to do |format|\n format.html { redirect_to '/' }\n format.json { head :no_content }\n end\n end", "def destroy\n @social.destroy\n respond_to do |format|\n format.html { redirect_to socials_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @social_networking.destroy\n\n render json: @social_networking, status: :ok\n end", "def destroy\n @socialmediasite.destroy\n respond_to do |format|\n format.html { redirect_to socialmediasites_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @appdotnet_social = AppdotnetSocial.find(params[:id])\n @appdotnet_social.destroy\n\n respond_to do |format|\n format.html { redirect_to appdotnet_socials_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @social_account = SocialAccount.find(params[:id])\n @social_account.destroy\n\n respond_to do |format|\n format.html { redirect_to social_accounts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @social_network = SocialNetwork.find(params[:id])\n @social_network.destroy\n\n respond_to do |format|\n format.html { redirect_to social_networks_url }\n format.json { head :ok }\n end\n end", "def destroy\n @socialmedium = Socialmedium.find(params[:id])\n @socialmedium.destroy\n\n respond_to do |format|\n format.html { redirect_to socialmedia_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @rede_social.destroy\n respond_to do |format|\n format.html { redirect_to \"/show_rede_social/#{@artist_data.id}/adm/remover\", notice: 'Rede social was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n\n unless params[:id]\n render json: {message: \" اطلاعات را به صورت کامل بفرستید \"}, status: 400\n return\n end\n\n social = @current_user.socials.where( id: params[:id]).last\n\n if social\n if social.destroy\n render json: { message: \" شبکه اجتماعی حذف شد \" } , status: 200\n else\n render json: social.errors , status: 400\n end\n else\n render json: { message: \" شبکه اجتماعی مورد نظر یافت نشد \" } , status: 404\n end\n\n end", "def delete_all\n socials = @current_user.socials\n if socials\n if socials.destroy_all\n render json: { success: \" تمامی شبکه های اجتماهی حذف شدند \" } , status: 202\n else\n render json: socials.errors , status: 400\n end\n else\n render json: { error: \" شبکه های اجتماعی کاربر مورد نظر یافت نشد \" } , status: 404\n end\n end", "def destroy\n @social_concern.destroy\n respond_to do |format|\n format.html { redirect_to social_concerns_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @social_account.destroy\n respond_to do |format|\n format.html { redirect_to social_accounts_url, notice: 'Social account was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @social_account.destroy\r\n respond_to do |format|\r\n format.html { redirect_to root_url, notice: 'Social account was successfully destroyed.' }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @api_v1_social_link_segment.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_social_link_segments_url, notice: 'Social link segment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @social_network.destroy\n respond_to do |format|\n format.html { redirect_to admin_social_networks_url, notice: 'Social network was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_social_medium = Admin::SocialMedium.find(params[:id])\n @admin_social_medium.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_social_media_url }\n format.json { head :ok }\n end\n end", "def destroy\n @social_media.destroy\n respond_to do |format|\n format.html { redirect_to url_back, notice: 'social media was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n relationship = Relationships.find(params[:id])\n relationship.destroy\n head 204\n end", "def destroy\n profile = 'adm'\n @rede_social.destroy\n exist_redesocial_to_user\n respond_to do |format|\n format.js { render :index }\n end\n end", "def destroy\n @facebook_share.destroy\n respond_to do |format|\n format.html { redirect_to facebook_shares_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @social_contract = SocialContract.find(params[:id])\n @social_contract.destroy\n\n respond_to do |format|\n format.html { redirect_to social_contracts_url }\n format.json { head :ok }\n end\n end", "def destroy\n @social_media_link.destroy\n\n head :no_content\n end", "def deleteEntitySocialmedia( entity_id, gen_id)\n params = Hash.new\n params['entity_id'] = entity_id\n params['gen_id'] = gen_id\n return doCurl(\"delete\",\"/entity/socialmedia\",params)\n end", "def delete\n if params[:social_event_type_id]\n socialEventType = SocialEventType.where(id: params[:social_event_type_id]).first\n if socialEventType.delete \n render json: { message: \"deleted successfully.\" } , status: 200\n else \n render json: socialEventType.errors , status: 422\n end\n else\n render json: { message: \"send social event type id.\" } , status: 422 \n end \n end", "def destroy\n @g4_dongal_board_social.destroy\n respond_to do |format|\n format.html { redirect_to g4_dongal_board_socials_url, notice: 'G4 dongal board social was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy_intent(base_path)\n delete_json(intent_url(base_path))\n rescue GdsApi::HTTPNotFound => e\n e\n end", "def delete\n render json: Like.delete(params[\"id\"])\n end", "def destroy\n @shared_url = SharedUrl.find(params[:id])\n @shared_url.destroy\n\n respond_to do |format|\n format.html { redirect_to shared_urls_url }\n format.json { head :no_content }\n end\n end", "def delete_social\n\t\tcheck_if_myself(params[:user_id])\n\t\tSocialUser.find(params[:social_user_id]).delete\n\t\tredirect_to current_user\n\tend", "def destroy\n @wusersocial.destroy\n respond_to do |format|\n format.html { redirect_to wusersocials_url, notice: 'Wusersocial was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @share = Share.find(params[:id])\n @share.destroy\n\n respond_to do |format|\n format.html { redirect_to shares_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @social_event.destroy\n respond_to do |format|\n format.html { redirect_to social_events_url, notice: 'Social event was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n # @default_facebook = DefaultFacebook.find(params[:id])\n @default_facebook = current_user.default_facebooks.find(params[:id])\n @default_facebook.destroy\n\n respond_to do |format|\n format.html { redirect_to default_facebooks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @anyshare.destroy\n respond_to do |format|\n format.html { redirect_to anyshares_url, notice: 'Anyshare was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n api_client.delete(url)\n end", "def destroy\n @anything.destroy\n respond_to do |format|\n format.html { redirect_to anythings_url }\n format.json { head :no_content }\n end\n end", "def deleteUserSocial_network( user_id, social_network)\n params = Hash.new\n params['user_id'] = user_id\n params['social_network'] = social_network\n return doCurl(\"delete\",\"/user/social_network\",params)\n end", "def destroy\n @share.destroy\n respond_to do |format|\n format.html { redirect_to shares_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @share.destroy\n respond_to do |format|\n format.html { redirect_to shares_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @share.destroy\n\n respond_to do |format|\n format.html { redirect_to @redirect_location }\n format.json { head :no_content } \n end\n end", "def delete; rest_delete(link('self')); end", "def delete; rest_delete(link('self')); end", "def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def delete\n delete_from_server single_url\n end", "def delete\n client.delete(url)\n @deleted = true\nend", "def destroy\n @dogshare.destroy\n respond_to do |format|\n format.html { redirect_to dogshares_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @curso.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @facebooklink.destroy\n respond_to do |format|\n format.html { redirect_to facebooklinks_url, notice: 'Facebooklink was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Post.delete(params[\"id\"])\n end", "def destroy\n @go_slim = GoSlim.find(params[:id])\n @go_slim.destroy\n\n respond_to do |format|\n format.html { redirect_to go_slims_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @membership.destroy\n\n respond_to do |format|\n format.html { redirect_to edit_site_url(@membership.site) }\n format.json { head :no_content }\n end\n end", "def delete_json(url)\n JSON.parse(delete(url, :json, :json))\n end", "def destroy\n Feed.find(params[:id]).destroy\n render :json => {:ok => true}, :head => :no_content\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to disciplines_url }\n format.json { head :ok }\n end\n end", "def destroy\n @facebook_token.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @user_share = UserShare.find(params[:id])\n @user_share.destroy\n\n respond_to do |format|\n format.html { redirect_to user_shares_url }\n format.json { head :no_content }\n end\n end", "def destroy\n # @profile = Profile.find(params[:id])\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def destroy\n @socio = Socio.find(params[:id])\n @socio.destroy\n\n respond_to do |format|\n format.html { redirect_to socios_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @socio = Socio.find(params[:id])\n @socio.destroy\n\n respond_to do |format|\n format.html { redirect_to socios_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @one = One.find(params[:id])\n @one.destroy\n\n respond_to do |format|\n format.html { redirect_to ones_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @socio.destroy\n respond_to do |format|\n format.html { redirect_to socios_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @social_media_account.destroy\n respond_to do |format|\n format.html { redirect_to social_media_accounts_url, notice: 'Social media account was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @fullurl.destroy\n respond_to do |format|\n format.html { redirect_to fullurls_url, notice: 'Fullurl was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @stat = Stat.find(params[:id])\n @stat.destroy\n\n respond_to do |format|\n format.html { redirect_to stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @follow = Follow.find(params[:id])\n @follow.destroy\n\n respond_to do |format|\n format.html { redirect_to follows_url }\n format.json { head :no_content }\n end\n end", "def delete\n render json: User.delete(params[\"id\"])\n end", "def destroy\n @json.destroy\n respond_to do |format|\n format.html { redirect_to jsons_url, notice: 'Json was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @json.destroy\n respond_to do |format|\n format.html { redirect_to jsons_url, notice: 'Json was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n if @short_url.destroy\n render json: { status: \"Deleted\" }\n else\n render json: { head: \"no content\" }\n end \n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile.destroy\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @pg_first.destroy\n respond_to do |format|\n format.html { redirect_to pg_firsts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mini_url.destroy\n respond_to do |format|\n format.html { redirect_to mini_urls_url, notice: 'Mini url was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(url, headers = {})\n http :delete, \"#{url}.json\", headers\n end", "def destroy\n @stat = Stat.find(params[:id])\n @stat.destroy\n\n respond_to do |format|\n format.html { redirect_to stats_url }\n format.json { head :ok }\n end\n end", "def destroy\n @external_link = ExternalLink.find(params[:id])\n @external_link.destroy\n\n respond_to do |format|\n format.html { redirect_to(backend_social_path) }\n end\n end", "def destroy\n @personal.destroy\n respond_to do |format|\n format.html { redirect_to personals_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @relationship_status.destroy\n respond_to do |format|\n format.html { redirect_to relationship_statuses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @users_interests_link.destroy\n respond_to do |format|\n format.html { redirect_to users_interests_links_url, notice: 'Users interests link was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @first = First.find(params[:id])\n @first.destroy\n\n respond_to do |format|\n format.html { redirect_to firsts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @my_activity = MyActivity.find(params[:id])\n @my_activity.destroy\n\n respond_to do |format|\n format.html { redirect_to my_activities_url }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Users.delete(params[\"id\"])\n end", "def destroy\n streak, success = jsonapi_destroy.to_a\n\n if success\n render json: { meta: {} }\n else\n render_errors_for(streak)\n end\n end", "def delete(splat)\n bad_request if splat.empty?\n _delete resolve_uri(splat[0])\n end", "def destroy\n @gasto = Gasto.find(params[:id])\n @gasto.destroy\n\n respond_to do |format|\n format.html { redirect_to gastos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n head 404\n # @api_v1_following = Api::V1::Follower.where('following_id =? and user_id =?', @current_user.id, params[:id]).first\n # if @api_v1_following.destroy\n # head :no_content\n # else \n # render json: { error: 'not allowed' }, status: 401\n # end\n end", "def destroy\n @base_url = BaseUrl.find(params[:id])\n @base_url.destroy\n\n respond_to do |format|\n format.html { redirect_to base_urls_url }\n format.json { head :no_content }\n end\n end", "def destroy\n # @flickr_account.destroy\n # respond_to do |format|\n # format.html { redirect_to flickr_accounts_url, notice: 'Flickr account was successfully destroyed.' }\n # format.json { head :no_content }\n # end\n end", "def destroy\n @microsite.destroy\n respond_to do |format|\n format.html { redirect_to microsites_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @gist.destroy\n respond_to do |format|\n format.html { redirect_to gists_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @share.destroy\n respond_to do |format|\n format.html { redirect_to shares_url, notice: 'Successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @community.destroy\n respond_to do |format|\n format.html { redirect_to communities_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sleuth.destroy\n respond_to do |format|\n format.html { redirect_to sleuths_url, notice: 'Sleuth was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
[ "0.7830353", "0.7816142", "0.7570174", "0.74011", "0.72452354", "0.7224009", "0.7214274", "0.72115654", "0.7132446", "0.71213543", "0.704383", "0.7007332", "0.69715756", "0.69631135", "0.6919055", "0.68624973", "0.6840862", "0.68261343", "0.681191", "0.68037", "0.67761683", "0.67746776", "0.6769795", "0.6738618", "0.67378247", "0.67370695", "0.67158836", "0.6701083", "0.6697525", "0.66790724", "0.6661138", "0.6640125", "0.66276526", "0.6620931", "0.6617184", "0.6602182", "0.65928966", "0.65863943", "0.6581678", "0.6581678", "0.6579983", "0.65637577", "0.65637577", "0.6550755", "0.6545358", "0.65420073", "0.6539346", "0.6536613", "0.653538", "0.6524001", "0.6506044", "0.6502725", "0.6500468", "0.6492267", "0.64906305", "0.64905286", "0.64884037", "0.64839286", "0.6475656", "0.6473061", "0.6473061", "0.6473061", "0.6473061", "0.64622957", "0.64622957", "0.64515895", "0.644632", "0.6443626", "0.6442086", "0.6436213", "0.6435948", "0.64310193", "0.64300734", "0.6430029", "0.6430029", "0.6423572", "0.6421453", "0.64210373", "0.64210373", "0.64190334", "0.64181167", "0.64141893", "0.64105165", "0.64086914", "0.6401358", "0.6394324", "0.6393403", "0.6389193", "0.63835454", "0.6383428", "0.6382647", "0.6382452", "0.6382174", "0.6379891", "0.63792264", "0.636567", "0.636213", "0.636179", "0.63587743", "0.63537955", "0.63518953" ]
0.0
-1
Use callbacks to share common setup or constraints between actions.
def set_social @social = Social.find(params[:id]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_required_actions\n # TODO: check what fields change to asign required fields\n end", "def action_hook; end", "def run_actions; end", "def define_action_hook; end", "def actions; end", "def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end", "def add_actions; end", "def callbacks; end", "def callbacks; end", "def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end", "def define_action_helpers; end", "def post_setup\n end", "def action_methods; end", "def action_methods; end", "def action_methods; end", "def before_setup; end", "def action_run\n end", "def execute(setup)\n @action.call(setup)\n end", "def define_action_helpers?; end", "def set_actions\n actions :all\n end", "def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end", "def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end", "def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end", "def before_actions(*logic)\n self.before_actions = logic\n end", "def setup_handler\n end", "def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end", "def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end", "def action; end", "def action; end", "def action; end", "def action; end", "def action; end", "def workflow\n end", "def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end", "def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end", "def before(action)\n invoke_callbacks *self.class.send(action).before\n end", "def process_action(...)\n send_action(...)\n end", "def before_dispatch(env); end", "def after_actions(*logic)\n self.after_actions = logic\n end", "def setup\n # override and do something appropriate\n end", "def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end", "def setup(_context)\n end", "def setup(resources) ; end", "def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end", "def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end", "def determine_valid_action\n\n end", "def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end", "def startcompany(action)\n @done = true\n action.setup\n end", "def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end", "def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end", "def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end", "def define_tasks\n define_weave_task\n connect_common_tasks\n end", "def setup(&block)\n define_method(:setup, &block)\n end", "def setup\n transition_to(:setup)\n end", "def setup\n transition_to(:setup)\n end", "def action\n end", "def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend", "def config(action, *args); end", "def setup\n @setup_proc.call(self) if @setup_proc\n end", "def before_action \n end", "def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end", "def action\n end", "def matt_custom_action_begin(label); end", "def setup\n # override this if needed\n end", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end", "def after(action)\n invoke_callbacks *options_for(action).after\n end", "def pre_task\n end", "def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end", "def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end", "def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end", "def setup_signals; end", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end", "def initialize(*args)\n super\n @action = :set\nend", "def after_set_callback; end", "def setup\n #implement in subclass;\n end", "def lookup_action; end", "def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end", "def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end", "def release_actions; end", "def around_hooks; end", "def save_action; end", "def setup(easy)\n super\n easy.customrequest = @verb\n end", "def action_target()\n \n end", "def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end", "def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end", "def before_setup\n # do nothing by default\n end", "def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end", "def default_action; end", "def setup(&blk)\n @setup_block = blk\n end", "def callback_phase\n super\n end", "def advice\n end", "def _handle_action_missing(*args); end", "def duas1(action)\n action.call\n action.call\nend", "def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end", "def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end", "def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend" ]
[ "0.6163163", "0.6045976", "0.5946146", "0.591683", "0.5890051", "0.58349305", "0.5776858", "0.5703237", "0.5703237", "0.5652805", "0.5621621", "0.54210985", "0.5411113", "0.5411113", "0.5411113", "0.5391541", "0.53794575", "0.5357573", "0.53402257", "0.53394014", "0.53321576", "0.53124547", "0.529654", "0.5296262", "0.52952296", "0.52600986", "0.52442724", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.5232394", "0.523231", "0.5227454", "0.52226824", "0.52201617", "0.5212327", "0.52079266", "0.52050185", "0.51754695", "0.51726824", "0.51710224", "0.5166172", "0.5159343", "0.51578903", "0.51522785", "0.5152022", "0.51518047", "0.51456624", "0.51398855", "0.5133759", "0.5112076", "0.5111866", "0.5111866", "0.5110294", "0.5106169", "0.509231", "0.50873137", "0.5081088", "0.508059", "0.50677156", "0.50562143", "0.5050554", "0.50474834", "0.50474834", "0.5036181", "0.5026331", "0.5022976", "0.5015441", "0.50121695", "0.5000944", "0.5000019", "0.4996878", "0.4989888", "0.4989888", "0.49864885", "0.49797225", "0.49785787", "0.4976161", "0.49683493", "0.4965126", "0.4958034", "0.49559742", "0.4954353", "0.49535993", "0.4952725", "0.49467874", "0.49423352", "0.49325448", "0.49282882", "0.49269363", "0.49269104", "0.49252945", "0.4923091", "0.49194667", "0.49174926", "0.49173003", "0.49171105", "0.4915879", "0.49155936" ]
0.0
-1
Never trust parameters from the scary internet, only allow the white list through.
def social_params params.require(:story).permit(:title, :author, :category, :body, :img, :description) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def strong_params\n params.require(:user).permit(param_whitelist)\n end", "def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end", "def allow_params_authentication!; end", "def allowed_params\n ALLOWED_PARAMS\n end", "def default_param_whitelist\n [\"mode\"]\n end", "def param_whitelist\n [:role, :title]\n end", "def expected_permitted_parameter_names; end", "def safe_params\n params.except(:host, :port, :protocol).permit!\n end", "def strong_params\n params.require(:team_member).permit(param_whitelist)\n end", "def permitir_parametros\n \t\tparams.permit!\n \tend", "def strong_params\n params.require(:community).permit(param_whitelist)\n end", "def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end", "def strong_params\n params.require(:education).permit(param_whitelist)\n end", "def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end", "def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end", "def param_whitelist\n [:rating, :review]\n end", "def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end", "def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end", "def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end", "def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end", "def valid_params_request?; end", "def strong_params\n params.require(:experience).permit(param_whitelist)\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end", "def allowed_params\n params.require(:allowed).permit(:email)\n end", "def permitted_params\n []\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end", "def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend", "def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end", "def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end", "def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end", "def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end", "def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end", "def safe_params\n params.require(:user).permit(:name)\n end", "def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend", "def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end", "def check_params; true; end", "def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end", "def quote_params\n params.permit!\n end", "def valid_params?; end", "def paramunold_params\n params.require(:paramunold).permit!\n end", "def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend", "def filtered_parameters; end", "def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end", "def filtering_params\n params.permit(:email, :name)\n end", "def check_params\n true\n end", "def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend", "def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend", "def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end", "def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end", "def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end", "def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend", "def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end", "def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end", "def active_code_params\n params[:active_code].permit\n end", "def filtering_params\n params.permit(:email)\n end", "def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end", "def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end", "def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end", "def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end", "def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end", "def list_params\n params.permit(:name)\n end", "def filter_parameters; end", "def filter_parameters; end", "def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end", "def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end", "def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end", "def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end", "def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end", "def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end", "def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end", "def url_whitelist; end", "def admin_social_network_params\n params.require(:social_network).permit!\n end", "def filter_params\n params.require(:filters).permit(:letters)\n end", "def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end", "def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end", "def sensitive_params=(params)\n @sensitive_params = params\n end", "def permit_request_params\n params.permit(:address)\n end", "def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end", "def secure_params\n params.require(:location).permit(:name)\n end", "def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end", "def question_params\n params.require(:survey_question).permit(question_whitelist)\n end", "def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end", "def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end", "def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end", "def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end", "def url_params\n params[:url].permit(:full)\n end", "def backend_user_params\n params.permit!\n end", "def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend", "def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end", "def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end", "def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end", "def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end", "def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end", "def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end", "def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end", "def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end" ]
[ "0.69792545", "0.6781151", "0.67419964", "0.674013", "0.6734356", "0.6591046", "0.6502396", "0.6496313", "0.6480641", "0.6477825", "0.64565", "0.6438387", "0.63791263", "0.63740575", "0.6364131", "0.63192815", "0.62991166", "0.62978333", "0.6292148", "0.6290449", "0.6290076", "0.62894756", "0.6283177", "0.6242471", "0.62382483", "0.6217549", "0.6214457", "0.6209053", "0.6193042", "0.6177802", "0.6174604", "0.61714715", "0.6161512", "0.6151757", "0.6150663", "0.61461", "0.61213595", "0.611406", "0.6106206", "0.6105114", "0.6089039", "0.6081015", "0.6071004", "0.60620916", "0.6019971", "0.601788", "0.6011056", "0.6010898", "0.6005122", "0.6005122", "0.6001556", "0.6001049", "0.59943926", "0.5992201", "0.59909594", "0.5990628", "0.5980841", "0.59669393", "0.59589154", "0.5958826", "0.5957911", "0.5957385", "0.5953072", "0.59526145", "0.5943361", "0.59386164", "0.59375334", "0.59375334", "0.5933856", "0.59292704", "0.59254247", "0.5924164", "0.59167904", "0.59088355", "0.5907542", "0.59064597", "0.5906243", "0.5898226", "0.589687", "0.5896091", "0.5894501", "0.5894289", "0.5891739", "0.58860534", "0.5882406", "0.587974", "0.58738774", "0.5869024", "0.58679986", "0.5867561", "0.5865932", "0.5864461", "0.58639693", "0.58617616", "0.5861436", "0.5860451", "0.58602303", "0.5854586", "0.58537364", "0.5850427", "0.5850199" ]
0.0
-1
Should be used when logged in user don't have rights to perform given action
def redirect_if_not_an_admin return if current_user.admin? flash[:danger] = 'Access denied.' redirect_to root_path end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ensure_user\n current_user? || deny_access('You must be logged in to perform this action.')\n end", "def access action\n\t\tif current_user\n \treturn true\n else\n \treturn false\n end\n\n\tend", "def user_actions(user)\n can_act_as_logged_in_user(user) unless Revs::Application.config.restricted_beta # also have logged in privileges if we are not in beta\n end", "def restrict_access\t\n\t\tif current_user.owner == false\n\t\t\tredirect_to user_path(current_user), notice: \"You can't view this page, contact your box owner\"\n\t\tend\t\n\tend", "def permission_required \n render_403 unless admin? || @user == current_user\n end", "def check_permission\n redirect_to dashboard_path, notice: 'You are not authorised to perform this action.' unless current_user&.admin?\n end", "def action_allowed?(action_name, user)\n return false\n end", "def is_authorized_to_perform(action)\n permission = role.shift_management_permissions_table.read_attribute(:\"#{action}\")\n return permission != :nobody\n end", "def needs_authenticate_user?\n except_actions = %w[index show print]\n !except_actions.include?(action_name)\n end", "def allow_access\n !@current_user.nil?\n end", "def user_action\r\n\t\tif controller.nil? || !controller.respond_to?(:session) || controller.session[:user].nil?\r\n\t\t\treturn false\r\n\t\tend\r\n\t\t\r\n\t\treturn true\r\n\trescue\r\n\t\treturn false\r\n\tend", "def authorized?(user, action)\n\t\ttrue\n\tend", "def check_if_user_can_perform_action_on_user\n is_current_user = (admin_user == @item)\n current_user_is_root = admin_user.is_root? && is_current_user\n\n case params[:action]\n when 'edit'\n # Edit other items is not allowed unless current user is root\n # and is not the current user.\n not_allowed if admin_user.is_not_root? && !is_current_user\n when 'toggle', 'destroy'\n not_allowed if admin_user.is_not_root? || current_user_is_root\n when 'update'\n # Admin can update himself except setting the status to false!. Other\n # users can update their profile as the attributes (role & status)\n # are protected.\n status_as_boolean = params[@object_name][:status] == \"1\" ? true : false\n\n status_changed = !(@item.status == status_as_boolean)\n role_changed = !(@item.role == params[@object_name][:role])\n\n root_changed_his_status_or_role = current_user_is_root && (status_changed || role_changed)\n not_root_tries_to_change_another_user = admin_user.is_not_root? && !is_current_user\n\n not_allowed if root_changed_his_status_or_role || not_root_tries_to_change_another_user\n end\n end", "def authorize_user\n if @user.id != current_user.id\n redirect_to \"/\", notice: 'You are not allowed the given operation' and return\n end\n end", "def action_allowed?\n current_user_has_ta_privileges?\n end", "def action_allowed?\n current_user_has_ta_privileges?\n end", "def ensure_user_has_rights\n redirect_to root_path unless current_user\n end", "def authorize_access\n # byebug\n redirect_to root_path, alert: \"Access Denied\" unless can? :modify, Post\n end", "def check_accessible\n if current_user\n myaction=Action.find_controller_action(params[:controller], params[:action])\n raise \"Page not found\" unless !myaction || myaction.accessible(current_user) || Group.find(2).has_user(current_user) # this is a nasty hack to stop errors because there are links to actions accessible only by users. Need to sort out access management!!\n end\n end", "def access_robot\n raise 'unauthorised' if current_user != @robot.user \n end", "def action_allowed?\n current_user_has_student_privileges?\n end", "def needs_authenticate_user?\n except_actions = %w[index show]\n !except_actions.include?(action_name)\n end", "def authorise_action\n if !logged_in? or (@annotation.source != current_user)\n # TODO: return either a 401 or 403 depending on authentication\n respond_to do |format|\n flash[:error] = 'You are not allowed to perform this action.'\n format.html { redirect_to :back }\n format.xml { head :forbidden }\n end\n return false\n end\n return true\n end", "def authorise_action\n if !logged_in? or (@annotation.source != current_user)\n # TODO: return either a 401 or 403 depending on authentication\n respond_to do |format|\n flash[:error] = 'You are not allowed to perform this action.'\n format.html { redirect_to :back }\n format.xml { head :forbidden }\n end\n return false\n end\n return true\n end", "def permission_required \n render_403 unless admin? || @item.is_editable_by?(current_user)\n end", "def permiso_requerido\n if not protect?(action_name)\n return true\n end\n if @session['user'] and autorizado?(@session['user'], controller_name)\n return true\n end\n store_location\n access_denied\n return false\n end", "def restrict_access\n head :unauthorized and return false unless current_user\n end", "def action_allowed?\n case params[:action]\n when 'edit'\n @questionnaire = Questionnaire.find(params[:id])\n current_user_has_admin_privileges? ||\n (current_user_is_a?('Instructor') && current_user_id?(@questionnaire.try(:instructor_id))) ||\n (current_user_is_a?('Teaching Assistant') && session[:user].instructor_id == @questionnaire.try(:instructor_id))\n else\n current_user_has_student_privileges?\n end\n end", "def check_if_user_can_perform_action_on_resources\n if @item && @item.is_a?(Typus.user_class)\n check_if_user_can_perform_action_on_user\n else\n not_allowed if admin_user.cannot?(params[:action], @resource.model_name)\n end\n end", "def user_action_on_resource_authorized\n end", "def authorize_user\n # simple authorization: kick out anonymous users from backend actions\n=begin\n if !current_user\n redirect_back_or_default(home_page) and return if action_name =~ /index|edit|update|destroy/\n \n # skip checking permission if user is an admin\n elsif !current_user.has_role?('Admin')\n unless current_user.has_permission?(controller_name, action_name, params)\n flash[:warning] = 'Access Denied'\n redirect_back_or_default(home_page) and return\n end\n end\n=end\n end", "def access_denied\n end", "def action_allowed?\n if %w[edit update list_submissions].include? params[:action]\n current_user_has_admin_privileges? || current_user_teaching_staff_of_assignment?(params[:id])\n else\n current_user_has_ta_privileges?\n end\n end", "def check_permission\n unless @therapist.user_id == current_user.id\n redirect_back(fallback_location: root_path,\n alert: \"Error: Permission denied - Invalid User\")\n end\n end", "def access_denied\n\n end", "def user_is_allowed_to(action, resource)\n unless logged_in?\n redirect_to \"/login?return_url=\" + URI.encode(request.fullpath)\n return false\n end\n\n @user = logged_in_user\n unless @user.is_allowed(resource, action)\n @error = \"You don't have permission to #{action} #{resource}\"\n @return_url = request.fullpath\n render :template => \"caboose/extras/error\"\n return false\n end\n return true\n end", "def assert_user_cant_access(user, actions, params = {})\r\n assert_user_access_check(false, user, actions, params)\r\n end", "def unauthorized_user!\n if @user != current_user\n redirect_to root_path, status: :unauthorized, alert: 'You can only perform this action on your own user!'\n end\n end", "def authorize_unauthenticated_user\n target_action = params[:controller] + '#' + params[:action]\n unless User::DEFAULT_PERMISSIONS.include?(target_action)\n head :unauthorized and return\n end\n end", "def has_access?( action )\n unless( action_name == :show && @sir_item.sir_log.permitted_to_access?( current_user.id )) ||\n @sir_item.sir_log.permitted_to_update?( current_user.id )\n render_no_access \n return false\n end\n g = [ :new, :create ].include?( action_name ) ? @sir_item.resp_next_entry : @sir_entry.resp_this_entry\n unless current_user.permission_to_access( feature_identifier, action, g.id )\n render_no_permission \n return false\n end\n true\n end", "def self_edit_only\n #if current_user.id != Integer(params[:id]) && !current_user.is_admin\n if !can_edit\n redirect_to user_url, :notice => \"You don't have permission to do that.\"\n else\n end\n end", "def check_ownership \t\n \taccess_denied(:redirect => @check_ownership_of) unless current_user_owns?(@check_ownership_of)\n end", "def check_user_before_action\n @blog = Blog.find(params[:id])\n if (current_user != @blog.user) and (@blog.global == false)\n redirect_to({ action: \"index\" }, notice: \"You don't have sufficient permissions\")\n\n end\n end", "def allows_current_user_access_to?(perform, with_options = nil)\n super\n end", "def user_is_allowed(resource, action)\n if (!logged_in?)\n redirect_to \"/login?return_url=\" + URI.encode(request.fullpath)\n return\n end\n \n @user = logged_in_user\n if (!@user.is_allowed(resource, action))\n @error = \"You don't have permission to \" + action + \" \" + resource\n render :template => \"extras/error\"\n return false\n end\n \n return true \n end", "def tiene_permiso?\n if not protect?(action_name)\n return true\n end\n if @session['user'] and autorizado?(@session['user'], controller_name)\n return true\n end\n store_location\n access_denied\n return false\n end", "def validate_access\n if @user_logged_in != @answer.user\n render status: :forbidden\n end\n end", "def access_control(object = nil)\n if object.present? && @cur_user.present?\n author = author?\n end\n perm = Permission\n perm.getReq(params[:controller], params[:action], request.request_method)\n redirect t('redirect.denied') unless perm.grant?(user_perm, author)\n end", "def require_permission\n if Goal.find(params[:id]).user != current_user\n redirect_to goals_url, flash: { error: \"You do not have permission to do that.\"}\n end\n end", "def user_is_allowed(resource, action)\n if (!logged_in?)\n redirect_to \"/login?return_url=\" + URI.encode(request.fullpath)\n return false\n end\n \n @user = logged_in_user\n if (!@user.is_allowed(resource, action))\n @error = \"You don't have permission to \" + action + \" \" + resource\n @return_url = request.fullpath\n render :template => \"caboose/extras/error\"\n return false\n end\n \n return true \n end", "def has_access?( action )\n unless @sir_log.permitted_to_access?( current_user.id )\n render_no_access\n return false\n end\n return true if [ 'index', 'new', 'create', 'show_stats' ].include?( action_name )\n unless current_user.permission_to_access( feature_identifier, action, @sir_item.group_id )\n render_no_permission \n return false \n end\n return true\n end", "def not_authorised\n flash[:notice] = 'You are not authorized to perform this action!'\n redirect_back(fallback_location: root_path)\n end", "def check_can_access\n res = false\n read_actions = [ \"index\", \"list\", \"edit\" ]\n new_actions = [ \"new\", \"create\" ]\n edit_actions = [ \"edit\", \"update\", \"destroy\", \"update_logo\" ]\n\n res ||= (action_name == \"show_logo\")\n res ||= current_user.admin?\n\n if current_user.option_externalclients?\n res ||= (current_user.read_clients? and read_actions.include?(action_name))\n res ||= (current_user.edit_clients? and edit_actions.include?(action_name))\n res ||= (current_user.create_clients? and new_actions.include?(action_name))\n end\n\n if !res\n flash[\"notice\"] = _(\"Access denied\")\n redirect_from_last\n end\n end", "def authorization(action, object = \"default - missing something?\")\n if action == \"create\"\n not_authorised and return unless current_user.can_create?\n elsif action == \"update\"\n not_authorised and return unless current_user.can_update?(object)\n elsif action == \"destroy\"\n not_authorised and return unless current_user.can_destroy?(object)\n elsif action == \"owner\"\n not_authorised and return unless current_user.owner?(object)\n elsif action == \"admin\"\n not_authorised and return unless current_user.admin_only\n end\n end", "def require_owner\n @messsage = \"You don't have the permission to do this operation.\"\n render :file => \"shared/message\" unless @user.eql?(current_user)\n end", "def require_owner\n @messsage = \"You don't have the permission to do this operation.\"\n render :file => \"shared/message\" unless @user.eql?(current_user)\n end", "def login_required\nauthorized? || access_denied\nend", "def has_privilege?\n if (!logged_in?)\n redirect_to '/login' and return\n elsif (params[:user_id].to_i != current_user.id)\n redirect_to user_stories_path(current_user) and return\n end\n end", "def require_permission\n if current_user != Pilot.find(params[:id])\n redirect_to root_path\n #Or do something else here\n end\n end", "def define_eccept\n if current_user.info.id==@resource.id || can_manage_has_one(current_user.info, @resource, @model)\n return true\n else\n redirect_to root_path \n end\n end", "def try_as method, action, user\n log_in user\n self.send(method, action, permission_test_params)\n end", "def verify_access\n unless current_user.id == @worker.user_id\n flash[:warning] = \"You do not have authority to access that.\"\n redirect_to user_path(current_user.id)\n end\n end", "def owner_only\n unless current_user == @organism.owner\n flash[:alert] = \"Vous ne pouvez executer cette action car vous n'êtes pas le propriétaire de la base\"\n redirect_to admin_organisms_url\n end\n\n end", "def require_permission\n if Retirement.find(params[:id]).user != current_user\n redirect_to retirements_url, flash: { error: \"You do not have permission to do that.\"}\n end\n end", "def require_admin_or_correct_user\n @user = User.find(params[:id])\n flash[:error] = \"Access Denied\"\n redirect_to(root_url) unless (current_user.id == @user.id || is_admin?)\n end", "def authorise\n unless User.find_by_id(session[:user_id]) || (self.controller_name == 'users' && (self.action_name == 'new' || self.action_name == 'create'))\n session[:original_uri] = request.request_uri\n flash[:notice] = \"Please login!\"\n redirect_to login_url\n end\n end", "def admin_access_required\n access_denied unless admin?\n end", "def admin_access_required\n access_denied unless admin?\n end", "def admin_access_required\n access_denied unless admin?\n end", "def user_not_authorized\n \tflash[:alert] = \"You are not authorized to perform this action.\"\n \tredirect_to(request.referrer || root_path)\n end", "def facility_admin\n facility_controller_check\n unless current_user.role == \"site_admin\" || (@facility_role_access.present? && current_user.role == \"facility_admin\")\n flash[:error] = 'You are not authorized. Please request access from your manager'\n redirect_to root_url\n end\n end", "def help\r\n\r\n @user_actions = Access.where(:table_sid => \"users\", :action_sid => [\"index\", \"list\", \"new\", \"create\", \"show\", \"edit\", \"update\", \"destroy\", \"search\", \"download\", \"feed\", \"help\", \"login\", \"logout\", \"home\", \"access_graph\", \"field_access_graph\", \"change_password\"]).includes([:user_accesses, :profile_accesses]).reject{|a| @current_user.can_run?(a) }\r\n render(:layout => !request.xhr?)\r\n end", "def authorize\n unless User.find_by(id: session[:user_id])\n redirect_to tasks_index_path, notice: \"Please log in\"\n end\n end", "def login_required\n return true unless protect?(action_name)\n\n return true if user? && authorize?(session[:user])\n\n # store current location so that we can\n # come back after the user logged in\n store_location\n\n # call overwriteable reaction to unauthorized access\n access_denied\n false\n end", "def require_login\n !!current_user || access_denied\n end", "def check_permissions\n redirect_to index_path, alert: lack_permission_msg unless admin_or_organizer?\n end", "def permit_user\n if (!current_user.lunches_admin?) \n flash[:alert] = 'You not allowed to see all orders.'\n respond_to do |format| \n format.html {redirect_to(root_url)}\n end\n end\n end", "def no_current_user\n if @user = current_user\n logger.warn \"Restricting user #{@user.id} from calling create!\"\n head :method_not_allowed\n end\n end", "def perform_action(action_name, options)\n if action_allowed?(action_name, options[:current_user])\n return send(action_name, options)\n else\n return nil\n end\n end", "def ensure_no_user\n !current_user? || redirect_back_or_default\n end", "def owner_only\n unless current_user == @organism.owner\n flash[:alert] = \"Vous ne pouvez executer cette action car vous n'êtes pas le propriétaire de la base\"\n redirect_to admin_organisms_url\n end\n end", "def _can_do_action_without_object?(action, action_id)\n if _actions[action].nil?\n _invalid_general_action!(action)\n elsif unrestricted?\n true\n else\n accessly_query.can?(action_id, namespace)\n end\n end", "def authorize_user\n\t if !current_user.admin_user? then\n\t redirect_to '/', notice: 'You have attempted to access a function that is not available for basic users.'\n\t end\n\tend", "def authorized?\n %w(new create plans canceled thanks).include?(self.action_name) || \n ((self.action_name == 'dashboard') && current_user) ||\n admin?\n end", "def authorized?\n %w(new create plans canceled thanks).include?(self.action_name) || \n ((self.action_name == 'dashboard') && current_user) ||\n admin?\n end", "def authorized!\n redirect_to root_url, alert: \"You need to be set up for receiving whispers first\" and return unless current_user\n end", "def unauthorized\n end", "def check_user\n unless current_user.nil?\n return if current_user.admin?\n @activity = current_user.activities.find_by_id(params[:id])\n end\n if @activity.nil?\n flash[:error] = \"权限不足\"\n redirect_to Activity.find(params[:id])\n end\n end", "def check_access\n if current_user.nil? or !current_user.is_admin?\n flash[:error] = t('no_access')\n redirect_to :root\n return false\n end\n end", "def show\n return unless check_permission\n end", "def user_access\n @bot = current_user.admin? ? Bot.find(params[:id]) : current_user.bots.find(params[:id])\n\n check_user_access(@bot.account.user_id)\n\n rescue\n flash_access_denied\n end", "def protect?(action)\n true\n end", "def user_access_control_all\n @user = User.find(params[:user_id])\n\n unless !@user.admin? && current_user.admin? || current_user?(@user)\n response_access_denied\n end\n\n rescue\n response_access_denied\n end", "def check_access_control_all\n @user = User.find(params[:user_id])\n\n response_access_denied unless current_user.has_role?(:admin) || current_user.id == @user.id\n rescue\n response_access_denied\n end", "def authorized?(action, model_object = nil)\n Pundit.policy(@controller.current_user_for_pundit, model_object).public_send(action + '?') if action\n end", "def access_required_member\n\tlogger.debug session.to_yaml\n\t\tredirect_to '/access_denied.html' and return unless session[\"user_#{current_user.id}\"][:access_level] >= Role.access_level('Member')\n\tend", "def has_privilege?\n if (!logged_in?)\n redirect_to '/login' and return\n elsif (params[:user_id].to_i != current_user.id)\n redirect_to user_events_path(current_user) and return\n end\n end", "def check_manager_or_admin\n unless current_user && (current_user.privilege_manager? || current_user.privilege_admin?)\n flash[:danger] = \"You do not have permission to perform this operation\"\n redirect_to root_path\n end\n end", "def index\n\n #Make sure only logged in admins can manipulate users\n\n if @loggedinuser && @loggedinuser.authorizationlevel >= 4\n else \n redirect_to '/'\n end\n end", "def login_required\n authorized? || throw(:halt, :access_denied)\n end", "def filter_object\n # redirect_to(root_url, :notice => \"Do not have permission\") and return\n end" ]
[ "0.76345205", "0.7491912", "0.7108821", "0.7091189", "0.7089053", "0.7088044", "0.7067415", "0.69824374", "0.69402945", "0.69317067", "0.6927439", "0.6927417", "0.6918458", "0.6907153", "0.6905519", "0.6905519", "0.6904749", "0.68697476", "0.68641204", "0.6860207", "0.6856224", "0.6818753", "0.6799657", "0.6799657", "0.6775382", "0.6772228", "0.6760907", "0.6749381", "0.67486143", "0.6738657", "0.67306256", "0.67081887", "0.67047083", "0.66956186", "0.6694105", "0.66931564", "0.66926473", "0.66892236", "0.6686267", "0.66847336", "0.6680627", "0.66716075", "0.66691357", "0.6648115", "0.66347027", "0.66115224", "0.6609627", "0.6607886", "0.6605272", "0.65927386", "0.6588944", "0.65719545", "0.65627086", "0.65588033", "0.65569097", "0.65568405", "0.6554442", "0.6552372", "0.6550268", "0.6536664", "0.6536154", "0.6534486", "0.6524546", "0.6523883", "0.65134495", "0.6511473", "0.65095973", "0.65095973", "0.65095973", "0.6505989", "0.65059763", "0.6505872", "0.65048546", "0.65005773", "0.6500245", "0.6498617", "0.64963007", "0.6489318", "0.6488526", "0.64881814", "0.64863896", "0.64855546", "0.64795417", "0.64751565", "0.64751565", "0.6472962", "0.6472244", "0.64698255", "0.64635116", "0.6462918", "0.64612734", "0.6458266", "0.6458067", "0.6457223", "0.6455482", "0.6443753", "0.6443129", "0.6442425", "0.643686", "0.6436154", "0.64302087" ]
0.0
-1
Remove a listening channel, the LiveQuery will automatically remove itsself from the pool when there are no channels.
def remove_listener(collection, query) live_query = @volt_app.live_query_pool.lookup(collection, query) live_query.remove_channel(@channel) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_channel(channel_name)\r\n @channels.delete(channel_name.downcase)\r\n end", "def unsubscribe_from_channel; end", "def remove_channel( channel )\n @channel_map.delete channel.local_id\n end", "def unsubscribe_from_channel # :nodoc:\n run_callbacks :unsubscribe do\n unsubscribed\n end\n end", "def remove_channel(channel)\n @attributes[:channels].delete_if { |c| channel.resolve_id == c.resolve_id }\n end", "def close!\n live_queries = @volt_app.channel_live_queries[@channel]\n\n if live_queries\n live_queries.each do |live_query|\n live_query.remove_channel(@channel)\n end\n end\n\n @volt_app.channel_live_queries.delete(@channel)\n end", "def remove(channel_name, stream_name, connection)\n @mutex.synchronize do\n subscribers[channel_name][stream_name].delete(connection)\n subscribers[channel_name].delete(stream_name) if subscribers[channel_name][stream_name].empty?\n connection\n end\n end", "def unsubscribe\n check_subscribed!\n subscription.unsubscribe_from_channel\n end", "def cleanup_after_unsubscribe(channel)\n return if channel.listeners_count > 0\n logger.debug \"destroying channel #{channel.name}\"\n @channels.delete channel.name\n stat_channel_destroyed channel.name\n destroy if @channels.size == 0\n end", "def destroy_channel_request\n channel_request = ChannelRequest.where(:user_id => self.subscriber_id, :channel_id => self.channel_id).first\n channel_request.destroy unless channel_request.blank?\n end", "def unsubscribe( channel, callback )\n if @channels.include? channel\n @channels[channel].delete(callback)\n end\n if @channels[channel].empty?\n @client.unsubscribe channel\n @channels.delete(channel)\n end\n end", "def remove_channel_handler(channel, handler)\n handlers = @channels[channel]\n handlers.delete(handler) unless handlers.nil?\n end", "def unsubscribe(channel)\n @ws.send(get_unsubscribe_object(channel, increment_cnt).to_json)\n @channels.delete(channel)\n end", "def delete_channel(data)\n channel = Channel.new(data, self)\n server = channel.server\n\n # Handle normal and private channels separately\n if server\n @channels.delete(channel.id)\n server.channels.reject! { |c| c.id == channel.id }\n else\n @private_channels.delete(channel.id)\n end\n end", "def delete\n @channel_control.delete\n end", "def unsubscribed\n # Any cleanup needed when channel is unsubscribed\n stop_all_streams\n end", "def unsubscribed\n # Any cleanup needed when channel is unsubscribed\n stop_all_streams\n end", "def remove_game(channel)\n @games.delete(channel)\n end", "def delete_observers\n @sub_lock.synchronize { subscribers.delete channel }\n end", "def part(channel)\n if channel.is_a?(Channel)\n @channels.delete(channel)\n else\n @channels.delete(Channel.find(channel))\n end\n end", "def delete_channel(data)\n channel = Channel.new(data, self)\n server = channel.server\n\n # Handle normal and private channels separately\n if server\n @channels.delete(channel.id)\n server.delete_channel(channel.id)\n elsif channel.pm?\n @pm_channels.delete(channel.recipient.id)\n elsif channel.group?\n @channels.delete(channel.id)\n end\n end", "def open_channel\n @@game_channels.delete(@event.channel)\n nil\n end", "def cleanup\n @channel.close if @channel\n\n nil\n end", "def punsubscribe(*channels); end", "def unsubscribe(*channels); end", "def disconnect(channel)\r\n $LOG.info(\"Disconnecting from #{channel} channel.\")\r\n @pubNub.unsubscribe(\r\n :channel => @channel,\r\n :http_sync => true\r\n )\r\n end", "def unsubscribe_webhook\n if @redis\n @redis.pubsub.unsubscribe(subscribed_channel)\n @redis.close_connection\n end\n end", "def channel_ids_to_remove\n @channel_ids_to_remove ||= begin\n cids = []\n if self.respond_to?(:message)\n cids << self.try(:message).try(:channel).try(:id)\n Array(self.message&.channel&.sibling_channel_ids).each do |cid|\n cids << cid unless channel_ids_to_add.include?(cid)\n end\n end\n cids\n end\n end", "def unsubscribe(channel)\n send_action('unsubscribe', channel)\n end", "def remove_game(channel)\n if t = @games[channel].join_timer\n @bot.timer.remove(t)\n end\n @games.delete(channel)\n end", "def remove_game(channel)\n if t = @games[channel].join_timer\n @bot.timer.remove(t)\n end\n @games.delete(channel)\n end", "def unsubscribe\n @conn.send_data :opcode => UNSUBSCRIBE, :channel => @name\n end", "def remove_channel_open_handler( type, id )\n @channel_open_handlers[ type ][ id-1 ] = nil\n end", "def clear\n channels = @channels.dup\n @channels.clear\n channels\n end", "def destroy\n @channel = Channel.find(params[:channel_id])\n rescue ActiveRecord::RecordNotFound => e\n respond_to do |format|\n format.html { redirect_to :back, notice: I18n.t('general.failed_to_unsubscribe') }\n format.json { render json: e, status: :unprocessable_entity }\n end\n else\n current_user.channels.delete(@channel) if current_user.channels.include? @channel\n respond_to do |format|\n format.html { redirect_to @channel, notice: I18n.t('general.unsubscribed') }\n format.json { head :no_content }\n end\n end", "def unsubscribe(channels_string)\n channels = channels_string.split\n\n channels.each do |channel|\n queue_name = @subscriptions[channel]\n \n if queue_name\n queue = @session.queue(queue_name)\n if queue.exists?\n queue.unbind(@exchange, routing_key: \"#{channel}.*\")\n queue.unsubscribe\n @subscriptions.delete(channel)\n else\n puts \"The #{channel} channel does not exist.\"\n end\n end\n end\n end", "def delete(id)\n\t\t\tkparams = {}\n\t\t\t# Live channel id to delete\n\t\t\tclient.add_param(kparams, 'id', id);\n\t\t\tclient.queue_service_action_call('livechannel', 'delete', kparams);\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil;\n\t\t\tend\n\t\t\treturn client.do_queue();\n\t\tend", "def unsubscribe\n return if self.hub.nil?\n\n change_subscription(:unsubscribe)\n end", "def del\n channel = params['channel_id']\n existing = Board.find_by(:channel => channel)\n if existing then\n existing.destroy\n return render json: { :response_type => 'in_channel',\n :text => 'Removed the current game for the channel. It was between *' + existing.player1 + '* and *' + existing.player2 + '*' }\n end\n\n return render json: { :text => 'No ongoing game in the current channel' }\n end", "def delete_channel!(channel)\n sns.delete_topic(topic_arn: channel.arn)\n end", "def unsubscribed\n if current_user.is_a?(User)\n\n # if @userType == \"known\"\n ActionCable.server.broadcast \"AppearanceChannel\", { user: current_user.email, user_id: current_user.id, online: :off }\n # else\n # reject\n end\n # stop_all_streams\n # Any cleanup needed when channel is unsubscribed\n end", "def destroy\n \n @channel = @channel || ChannelClass.find(params[:id])\n @channel.destroy\n respond_to do |format|\n format.html { redirect_to channel_classes_url, notice: '频道删除成功.' }\n format.json { head :no_content }\n end\n \n end", "def remove_channel\n channel = Channel.find(params[:channel_id])\n @bss_title_id = BssTitleId.find(params[:id])\n \t@bss_title_id.channels.delete(channel)\n \trespond_to do |format|\n format.html {\n if params[:source] == 'episode_show'\n redirect_to episode_path(@bss_title_id.episode, show_details(:channel, params)), notice: 'Channel: ' + channel.name + ' removed'\n else\n redirect_to bss_title_id_path(@bss_title_id, show_details(:channel, params)), notice: 'Channel: ' + channel.name + ' removed'\n end\n }\n\t \tformat.json {render :show, status: :removed, location: @bss_title_id}\n \tend\n end", "def leave_channel(channel)\n channel = normalized_channel_name(channel)\n return unless channels.include? channel\n part channel\n end", "def disconnect\n @thread.exit\n @client.disconnect\n @channels.clear\n end", "def destroy\r\n @channel.destroy\r\n respond_to do |format|\r\n format.html { redirect_to user_channels_path(current_user)}\r\n end\r\n end", "def punsubscribe(*channels)\n raise NotImplementedError\n end", "def channel\n params.detect { |param| param.start_with?(\"#\") }&.delete(\"#\")\n end", "def unsubscribe(channel, connection)\n if sid = subscriptions.delete(channel => connection.signature)\n Channel[app_id => channel].unsubscribe(sid)\n end\n end", "def unsubscribe(topic, channel)\n name = \"#{topic}:#{channel}\"\n @subscriber_mutex.synchronize do\n subscriber = @subscribers[name]\n return unless subscriber\n subscriber.stop\n @subscribers.delete(name)\n end\n end", "def free_channels\n @channels.each_with_index do |channel, index|\n if channel\n unless SDL2::Mixer::Channels.play?(index)\n @channels[index] = false\n end\n end\n end\n end", "def release(channel)\n @channels.push(channel)\n @channels.sort!\n end", "def unsubscribe(endpoint, channel_name, subscription_id)\n channel = @channels[channel_name]\n if channel\n channel.unsubscribe(subscription_id)\n EM.next_tick { cleanup_after_unsubscribe channel }\n # Fire presence events if configured\n if @app_info['presence']\n EM.defer { fire_presence_close_events endpoint, channel }\n end\n\n else\n logger.debug \"Trying to unsubscribe for an inexistant channel #{channel_name}\"\n end\n end", "def unsubscribe_clients(channel)\n send_action('unsubscribe_clients', channel)\n end", "def unsubscribe\n redis.unsubscribe\n end", "def unsubscribe(client_id, channel, &callback)\n unless @subscriptions.containsEntry(client_id, channel)\n callback.call(true) if callback\n return\n end\n @subscriptions.remove(client_id, channel)\n @channels.remove(channel, client_id)\n @server.debug 'Unsubscribed client ? from channel ?', client_id, channel\n @server.trigger(:unsubscribe, client_id, channel)\n callback.call(true)\n end", "def unsubscribe(*channels)\n raise SubscriptionError, \"Can't unsubscribe if not subscribed.\" unless subscribed?\n\n @subscribed_node.unsubscribe(*channels)\n end", "def delete_facebook_channel(project_id, query_id)\n delete \"/projects/#{project_id}/facebookchannels/#{query_id}\"\n end", "def remove_observer (observer, channel=nil)\n\n channels = channel ? [ channel ] : @observers.keys\n\n channels.each { |c| do_remove_observer(observer, c) }\n end", "def remove_slack_integration_channel(account_name, channel_name, opts = {})\n remove_slack_integration_channel_with_http_info(account_name, channel_name, opts)\n nil\n end", "def unsubscribe(user)\n @clients.delete(user.signature)\n self.class.remove_channel(self) if empty?\n end", "def unsubscribe(*channels)\n _subscription(:unsubscribe, 0, channels, nil)\n end", "def exit_channel(channel_id, user_id)\n\t # clean up inuse channels\n\t if InuseChannel.find_by_name(channel_id) != nil\n\t inuse_channel = InuseChannel.find_by_name(channel_id)\n\t user1 = inuse_channel.user1\n\t user2 = inuse_channel.user2\n\t if user1 == user_id\n\t User.find_by_id(user1)\n\t else\n\t User.find_by_id(user2)\n\t end\n\t inuse_channel.destroy \n\t else\n\t free_channel = FreeChannel.find_by_id(free_channel_id)\n\t user = free_channel.user1\n\t User.find_by_name(user).destroy\n\t free_channel.destroy\n\t end\n\t \n\tend", "def delete(channels)\n\treturn if not channels.is_a? Array #meh\n\tcurChannels = readCurrentChannels()\n\tcurChannels.reject! { |e| channels.include? e.downcase }\n\twriteChannels(curChannels)\nend", "def destroy\n @channel = Channel.find(params[:id])\n @channel.destroy\n\n respond_with @channel\n end", "def delete(channel_id)\n\t\t\tkparams = {}\n\t\t\tclient.add_param(kparams, 'channelId', channel_id)\n\t\t\tclient.queue_service_action_call('channel', 'delete', 'bool', kparams)\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\treturn client.do_queue()\n\t\tend", "def unsubscribed\n # This will broadcast that user unsubscribed but the frontend will not receive the final broadcast\n p '**** ChatChannel unsubscribed'\n notification = {notification: 'User X has dropped off'}\n # ActionCable.server.broadcast(params[:room], notification)\n send_broadcast(params[:room], notification)\n end", "def close_channel\n return unless open?\n channel.close\n loop { !closed? }\n end", "def remove(push_channel_subscription)\n push_channel_subscription_object = PushChannelSubscription(push_channel_subscription)\n raise ArgumentError, \"Channel is required yet is empty\" if push_channel_subscription_object.channel.to_s.empty?\n if push_channel_subscription_object.client_id.to_s.empty? && push_channel_subscription_object.device_id.to_s.empty?\n raise ArgumentError, \"Either client_id or device_id must be present\"\n end\n\n client.delete(\"/push/channelSubscriptions\", push_channel_subscription_object.as_json)\n end", "def destroy\n @channel = Channel.find(params[:id])\n @channel.destroy\n\n respond_to do |format|\n format.html { redirect_to channels_url }\n format.json { head :ok }\n end\n end", "def remove_user(user)\n channels = Set.new\n\n @channels.each do |channel|\n if channel.remove_user(user)\n channels << channel\n end\n end\n\n channels\n end", "def allocate(channel=nil)\n raise \"No channels left to allocate\" if @channels.empty?\n return @channels.shift if channel.nil?\n raise \"Channel unavailable\" unless @channels.include?(channel)\n @channels.delete(channel)\n return channel\n end", "def destroy\n @channel = Channel.find(params[:id])\n @channel.destroy\n\n respond_to do |format|\n format.html { redirect_to(channels_url) }\n format.xml { head :ok }\n end\n end", "def remove_pending(*args)\n\n\t\t# Redirect to remove connection since it is an unbiased connection removed and would do this anyway\n\t\tself.send('remove_connection', *args)\n\tend", "def unsubscribe(opt_max=nil)\n @nc.send(:unsubscribe, self, opt_max)\n end", "def delete_listen(l)\n\t\treturn unless listen?\n\t\t\n\t\tbegin\n\t\t\tcase provider\n\t\t\twhen \"facebook\"\n\t\t\t\tdelete_listen_on_facebook(l)\n\t\t\tend\n\t\trescue Exception => e\n\t\t\tlogger.debug \"error deleting listen from service: #{provider}\"\n\t\t\tlogger.debug e.inspect\n\t\tend\n\tend", "def unsubscribe_plan\n proxies.delete(remote_plan)\n subscriptions.delete(remote_plan)\n if connected?\n call(:removed_sibling, @remote_plan, connection_space.plan.remote_id)\n end\n end", "def destroy\n @raw_channel = RawChannel.find(params[:id])\n @raw_channel.destroy\n\n respond_to do |format|\n format.html { redirect_to raw_channels_url }\n format.json { head :no_content }\n end\n end", "def unsubscribe(listener)\n listeners.delete(listener)\n end", "def destroy\n @channel = Channel.find(params[:id])\n @channel.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_channels_url }\n format.xml { head :ok }\n end\n end", "def channels \n debug [query[\"channels\"], \" are registered channels\"]\n @channels ||= query[\"channels\"].collect(&:strip).reject(&:empty?) \n @channels[0] ||= nil # Every user should have at last one channel\n @channels\n end", "def unsubscribe(cls)\n @subscribers.delete(name)\n end", "def destroy\n @universal_channel.destroy\n respond_to do |format|\n format.html { redirect_to universal_channels_url, notice: 'Universal channel was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @channel.destroy\n respond_to do |format|\n format.html { redirect_to channels_url }\n format.json { head :no_content }\n end\n end", "def stop_public_channel(channel_name) stop_channel(:public, channel_name) end", "def destroy\n @channel.destroy\n\n respond_to do |format|\n format.html { redirect_to(channels_url) }\n format.xml { head :ok }\n end\n end", "def remove_member(name, member)\n grpid = /(\\d+)/.match(name)[0]\n configure_interface(member, \"no channel-group #{grpid}\")\n end", "def unsubscribeack(channel, ack)\n @ws.send(get_unsubscribe_object(channel, increment_cnt).to_json)\n @channels.delete(channel)\n @acks[@cnt] = [channel, ack]\n end", "def deleteChannel(channelInfo)\r\n\t\tnum = 0\r\n\t\tchannel_id = 0\r\n\t\tchannelInfo.each_pair { | name, value |\r\n\t\t\tif(name == \"channel_id\")\r\n\t\t\t\tchannel_id = value\r\n\t\t\telse\r\n\t\t\t\tputs \"wrong parameter: #{name}\"\r\n\t\t\t\treturn \"wrong parameter: #{name}\"\r\n\t\t\tend\t\t\t\t\r\n\t\t}\r\n\r\n\t\tputs \"Connecting to database...\"\r\n\t\tbegin\r\n\t\t\t# connect to the MySQL server\r\n\t\t\tdbh = DBI.connect(\"DBI:Mysql:#{$db}:#{$db_ip}\",\"#{$user}\", \"#{$pass}\")\r\n\t\t\r\n\t\t\tnum = dbh.do(\"DELETE FROM spectrum WHERE id = '#{channel_id}'\")\r\n\t\t\tif (num == 1)\r\n\t\t\t\tputs \"Channel deleted...\"\r\n\t\t\t\treturn 0\r\n\t\t\tend\r\n\t\t\t\r\n\t\trescue DBI::DatabaseError => e\r\n\t\t\tputs \"An error occurred\"\r\n\t\t\tputs \"Error code: #{e.err}\"\r\n\t\t\tputs \"Error message: #{e.errstr}\"\r\n\t\tensure\r\n\t\t\t# disconnect from server\r\n\t\t\tdbh.disconnect if dbh\r\n\t\tend\r\n\t\t\t\r\n\t\treturn -1\r\n\tend", "def destroy\n @chatty_crow_channel.destroy\n flash[:notice] = l(:notice_successful_delete)\n redirect_to_plugin_settings\n end", "def part_all()\n @channels.clear()\n end", "def destroy\n @channel.destroy\n respond_to do |format|\n format.html { redirect_to channels_url, notice: 'Channel was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @channel.destroy\n respond_to do |format|\n format.html { redirect_to channels_url, notice: 'Channel was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_observer o\n @sub_lock.synchronize do\n subscribers.fetch(channel, {}).delete o\n end\n end", "def on_shutdown\n logger.debug \"Disconnecting user: #{@user} from channel: #{@channel}.\"\n @@connections[@channel].delete(@user)\n end", "def irc_quit_event(stem, sender, arguments) # :nodoc:\n @chan_mutex.synchronize do\n @channel_members.each { |chan, members| members.delete sender[:nick] }\n #TODO what should we do if we are in the middle of receiving NAMES replies?\n end\n end", "def pop\n connections.synchronize do\n evict\n _, connection = connections.pop\n connection\n end\n end", "def remove_listener(listener)\n listeners.delete(listener)\n end", "def unsubscribe()\n end", "def unsubscribed\n @room.remove_user(current_user)\n\n # Inform the other players that this player has left.\n broadcast_users_changed\n end" ]
[ "0.70596963", "0.68710816", "0.6856037", "0.67398417", "0.67341447", "0.6712721", "0.6665118", "0.65435237", "0.64570767", "0.6428591", "0.63431275", "0.6270383", "0.62609154", "0.62468237", "0.6215457", "0.62048614", "0.62048614", "0.6191188", "0.61433023", "0.6038613", "0.6031876", "0.6028366", "0.59762895", "0.5966818", "0.5948169", "0.59257776", "0.59255", "0.58813065", "0.5835368", "0.58319765", "0.58319765", "0.58097994", "0.5802867", "0.58018523", "0.5800575", "0.5797916", "0.57976425", "0.5762437", "0.57572424", "0.57318515", "0.5715423", "0.5703927", "0.56797534", "0.5668457", "0.56444424", "0.5643177", "0.5631302", "0.55993736", "0.5598481", "0.55656576", "0.5564539", "0.55567706", "0.55468845", "0.55307186", "0.5529406", "0.55204153", "0.5468399", "0.5466404", "0.54492444", "0.54485434", "0.544828", "0.5442157", "0.54236174", "0.54073495", "0.5400993", "0.5399824", "0.5396716", "0.537577", "0.53755295", "0.53548336", "0.53520375", "0.5339042", "0.5331946", "0.5317905", "0.5313587", "0.5308487", "0.53045654", "0.53044975", "0.5304196", "0.5302616", "0.52854747", "0.52818143", "0.52815205", "0.5279428", "0.5277581", "0.52747446", "0.52469325", "0.5234402", "0.5233222", "0.5226871", "0.52259207", "0.5217668", "0.5217668", "0.51828736", "0.5174147", "0.51660943", "0.5162292", "0.51577437", "0.5142295", "0.5125339" ]
0.70706624
0
Removes a channel from all associated live queries
def close! live_queries = @volt_app.channel_live_queries[@channel] if live_queries live_queries.each do |live_query| live_query.remove_channel(@channel) end end @volt_app.channel_live_queries.delete(@channel) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_channel( channel )\n @channel_map.delete channel.local_id\n end", "def delete_facebook_channel(project_id, query_id)\n delete \"/projects/#{project_id}/facebookchannels/#{query_id}\"\n end", "def remove_channel(channel_name)\r\n @channels.delete(channel_name.downcase)\r\n end", "def remove_game(channel)\n @games.delete(channel)\n end", "def remove_channel(channel)\n @attributes[:channels].delete_if { |c| channel.resolve_id == c.resolve_id }\n end", "def del\n channel = params['channel_id']\n existing = Board.find_by(:channel => channel)\n if existing then\n existing.destroy\n return render json: { :response_type => 'in_channel',\n :text => 'Removed the current game for the channel. It was between *' + existing.player1 + '* and *' + existing.player2 + '*' }\n end\n\n return render json: { :text => 'No ongoing game in the current channel' }\n end", "def remove_listener(collection, query)\n live_query = @volt_app.live_query_pool.lookup(collection, query)\n live_query.remove_channel(@channel)\n end", "def unsubscribe(channel)\n @ws.send(get_unsubscribe_object(channel, increment_cnt).to_json)\n @channels.delete(channel)\n end", "def remove_game(channel)\n if t = @games[channel].join_timer\n @bot.timer.remove(t)\n end\n @games.delete(channel)\n end", "def remove_game(channel)\n if t = @games[channel].join_timer\n @bot.timer.remove(t)\n end\n @games.delete(channel)\n end", "def part(channel)\n if channel.is_a?(Channel)\n @channels.delete(channel)\n else\n @channels.delete(Channel.find(channel))\n end\n end", "def unsubscribe_from_channel; end", "def channel_ids_to_remove\n @channel_ids_to_remove ||= begin\n cids = []\n if self.respond_to?(:message)\n cids << self.try(:message).try(:channel).try(:id)\n Array(self.message&.channel&.sibling_channel_ids).each do |cid|\n cids << cid unless channel_ids_to_add.include?(cid)\n end\n end\n cids\n end\n end", "def destroy_channel_request\n channel_request = ChannelRequest.where(:user_id => self.subscriber_id, :channel_id => self.channel_id).first\n channel_request.destroy unless channel_request.blank?\n end", "def part_all()\n @channels.clear()\n end", "def delete_channel(data)\n channel = Channel.new(data, self)\n server = channel.server\n\n # Handle normal and private channels separately\n if server\n @channels.delete(channel.id)\n server.channels.reject! { |c| c.id == channel.id }\n else\n @private_channels.delete(channel.id)\n end\n end", "def delete(channels)\n\treturn if not channels.is_a? Array #meh\n\tcurChannels = readCurrentChannels()\n\tcurChannels.reject! { |e| channels.include? e.downcase }\n\twriteChannels(curChannels)\nend", "def delete\n @channel_control.delete\n end", "def unsubscribe_clients(channel)\n send_action('unsubscribe_clients', channel)\n end", "def unsubscribe_from_channel # :nodoc:\n run_callbacks :unsubscribe do\n unsubscribed\n end\n end", "def clear\n channels = @channels.dup\n @channels.clear\n channels\n end", "def unsubscribe(*channels); end", "def delete_channel(data)\n channel = Channel.new(data, self)\n server = channel.server\n\n # Handle normal and private channels separately\n if server\n @channels.delete(channel.id)\n server.delete_channel(channel.id)\n elsif channel.pm?\n @pm_channels.delete(channel.recipient.id)\n elsif channel.group?\n @channels.delete(channel.id)\n end\n end", "def destroy\r\n @channel.destroy\r\n respond_to do |format|\r\n format.html { redirect_to user_channels_path(current_user)}\r\n end\r\n end", "def punsubscribe(*channels); end", "def unsubscribe\n check_subscribed!\n subscription.unsubscribe_from_channel\n end", "def unsubscribe(channel)\n send_action('unsubscribe', channel)\n end", "def remove_where(params)\n raise ArgumentError, \"params must be a Hash\" unless params.kind_of?(Hash)\n\n if (IdiomaticRubyWrapper(params).keys & [:channel, :client_id, :device_id]).length == 0\n raise ArgumentError, \"at least one channel, client_id or device_id filter param must be provided\"\n end\n\n params = params.clone\n\n client.delete(\"/push/channelSubscriptions\", IdiomaticRubyWrapper(params).as_json)\n end", "def cleanup_after_unsubscribe(channel)\n return if channel.listeners_count > 0\n logger.debug \"destroying channel #{channel.name}\"\n @channels.delete channel.name\n stat_channel_destroyed channel.name\n destroy if @channels.size == 0\n end", "def unsubscribe( channel, callback )\n if @channels.include? channel\n @channels[channel].delete(callback)\n end\n if @channels[channel].empty?\n @client.unsubscribe channel\n @channels.delete(channel)\n end\n end", "def unsubscribe(channels_string)\n channels = channels_string.split\n\n channels.each do |channel|\n queue_name = @subscriptions[channel]\n \n if queue_name\n queue = @session.queue(queue_name)\n if queue.exists?\n queue.unbind(@exchange, routing_key: \"#{channel}.*\")\n queue.unsubscribe\n @subscriptions.delete(channel)\n else\n puts \"The #{channel} channel does not exist.\"\n end\n end\n end\n end", "def remove(channel_name, stream_name, connection)\n @mutex.synchronize do\n subscribers[channel_name][stream_name].delete(connection)\n subscribers[channel_name].delete(stream_name) if subscribers[channel_name][stream_name].empty?\n connection\n end\n end", "def delete_observers\n @sub_lock.synchronize { subscribers.delete channel }\n end", "def destroy\n \n @channel = @channel || ChannelClass.find(params[:id])\n @channel.destroy\n respond_to do |format|\n format.html { redirect_to channel_classes_url, notice: '频道删除成功.' }\n format.json { head :no_content }\n end\n \n end", "def destroy\n @channel = Channel.find(params[:channel_id])\n rescue ActiveRecord::RecordNotFound => e\n respond_to do |format|\n format.html { redirect_to :back, notice: I18n.t('general.failed_to_unsubscribe') }\n format.json { render json: e, status: :unprocessable_entity }\n end\n else\n current_user.channels.delete(@channel) if current_user.channels.include? @channel\n respond_to do |format|\n format.html { redirect_to @channel, notice: I18n.t('general.unsubscribed') }\n format.json { head :no_content }\n end\n end", "def deleteChannel(channelInfo)\r\n\t\tnum = 0\r\n\t\tchannel_id = 0\r\n\t\tchannelInfo.each_pair { | name, value |\r\n\t\t\tif(name == \"channel_id\")\r\n\t\t\t\tchannel_id = value\r\n\t\t\telse\r\n\t\t\t\tputs \"wrong parameter: #{name}\"\r\n\t\t\t\treturn \"wrong parameter: #{name}\"\r\n\t\t\tend\t\t\t\t\r\n\t\t}\r\n\r\n\t\tputs \"Connecting to database...\"\r\n\t\tbegin\r\n\t\t\t# connect to the MySQL server\r\n\t\t\tdbh = DBI.connect(\"DBI:Mysql:#{$db}:#{$db_ip}\",\"#{$user}\", \"#{$pass}\")\r\n\t\t\r\n\t\t\tnum = dbh.do(\"DELETE FROM spectrum WHERE id = '#{channel_id}'\")\r\n\t\t\tif (num == 1)\r\n\t\t\t\tputs \"Channel deleted...\"\r\n\t\t\t\treturn 0\r\n\t\t\tend\r\n\t\t\t\r\n\t\trescue DBI::DatabaseError => e\r\n\t\t\tputs \"An error occurred\"\r\n\t\t\tputs \"Error code: #{e.err}\"\r\n\t\t\tputs \"Error message: #{e.errstr}\"\r\n\t\tensure\r\n\t\t\t# disconnect from server\r\n\t\t\tdbh.disconnect if dbh\r\n\t\tend\r\n\t\t\t\r\n\t\treturn -1\r\n\tend", "def unsubscribed\n # Any cleanup needed when channel is unsubscribed\n stop_all_streams\n end", "def unsubscribed\n # Any cleanup needed when channel is unsubscribed\n stop_all_streams\n end", "def disconnect(channel)\r\n $LOG.info(\"Disconnecting from #{channel} channel.\")\r\n @pubNub.unsubscribe(\r\n :channel => @channel,\r\n :http_sync => true\r\n )\r\n end", "def reset_all_channels\n @channels = {}\n end", "def destroy\n @chatty_crow_channel.destroy\n flash[:notice] = l(:notice_successful_delete)\n redirect_to_plugin_settings\n end", "def exit_channel(channel_id, user_id)\n\t # clean up inuse channels\n\t if InuseChannel.find_by_name(channel_id) != nil\n\t inuse_channel = InuseChannel.find_by_name(channel_id)\n\t user1 = inuse_channel.user1\n\t user2 = inuse_channel.user2\n\t if user1 == user_id\n\t User.find_by_id(user1)\n\t else\n\t User.find_by_id(user2)\n\t end\n\t inuse_channel.destroy \n\t else\n\t free_channel = FreeChannel.find_by_id(free_channel_id)\n\t user = free_channel.user1\n\t User.find_by_name(user).destroy\n\t free_channel.destroy\n\t end\n\t \n\tend", "def destroy\n @channel.destroy\n respond_to do |format|\n format.html { redirect_to user_path(current_user.id) }\n format.json { head :no_content }\n end\n end", "def delete_channel!(channel)\n sns.delete_topic(topic_arn: channel.arn)\n end", "def remove_user(user)\n channels = Set.new\n\n @channels.each do |channel|\n if channel.remove_user(user)\n channels << channel\n end\n end\n\n channels\n end", "def unsubscribe(channel, connection)\n if sid = subscriptions.delete(channel => connection.signature)\n Channel[app_id => channel].unsubscribe(sid)\n end\n end", "def destroy\n @channel.destroy\n respond_to do |format|\n format.html { redirect_to channels_url }\n format.json { head :no_content }\n end\n end", "def open_channel\n @@game_channels.delete(@event.channel)\n nil\n end", "def remove_channel\n channel = Channel.find(params[:channel_id])\n @bss_title_id = BssTitleId.find(params[:id])\n \t@bss_title_id.channels.delete(channel)\n \trespond_to do |format|\n format.html {\n if params[:source] == 'episode_show'\n redirect_to episode_path(@bss_title_id.episode, show_details(:channel, params)), notice: 'Channel: ' + channel.name + ' removed'\n else\n redirect_to bss_title_id_path(@bss_title_id, show_details(:channel, params)), notice: 'Channel: ' + channel.name + ' removed'\n end\n }\n\t \tformat.json {render :show, status: :removed, location: @bss_title_id}\n \tend\n end", "def destroy\n @channel = Channel.find(params[:id])\n @channel.destroy\n\n respond_to do |format|\n format.html { redirect_to channels_url }\n format.json { head :ok }\n end\n end", "def delete(id)\n\t\t\tkparams = {}\n\t\t\t# Live channel id to delete\n\t\t\tclient.add_param(kparams, 'id', id);\n\t\t\tclient.queue_service_action_call('livechannel', 'delete', kparams);\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil;\n\t\t\tend\n\t\t\treturn client.do_queue();\n\t\tend", "def destroy\n @universal_channel.destroy\n respond_to do |format|\n format.html { redirect_to universal_channels_url, notice: 'Universal channel was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @channel = Channel.find(params[:id])\n @channel.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_channels_url }\n format.xml { head :ok }\n end\n end", "def destroy\n @channel = Channel.find(params[:id])\n @channel.destroy\n\n respond_with @channel\n end", "def destroy\n @channel.destroy\n\n respond_to do |format|\n format.html { redirect_to(channels_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @channel = Channel.find(params[:id])\n @channel.destroy\n\n respond_to do |format|\n format.html { redirect_to(channels_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @raw_channel = RawChannel.find(params[:id])\n @raw_channel.destroy\n\n respond_to do |format|\n format.html { redirect_to raw_channels_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @channel.destroy\n respond_to do |format|\n format.html { redirect_to channels_url, notice: 'Channel was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @channel.destroy\n respond_to do |format|\n format.html { redirect_to channels_url, notice: 'Channel was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def unsubscribed\n if current_user.is_a?(User)\n\n # if @userType == \"known\"\n ActionCable.server.broadcast \"AppearanceChannel\", { user: current_user.email, user_id: current_user.id, online: :off }\n # else\n # reject\n end\n # stop_all_streams\n # Any cleanup needed when channel is unsubscribed\n end", "def remove_channel_handler(channel, handler)\n handlers = @channels[channel]\n handlers.delete(handler) unless handlers.nil?\n end", "def channels \n debug [query[\"channels\"], \" are registered channels\"]\n @channels ||= query[\"channels\"].collect(&:strip).reject(&:empty?) \n @channels[0] ||= nil # Every user should have at last one channel\n @channels\n end", "def track_channel_in_live_query(live_query)\n channel_live_queries = @volt_app.channel_live_queries\n channel_live_queries[@channel] ||= []\n channel_live_queries[@channel] << live_query\n end", "def channel\n params.detect { |param| param.start_with?(\"#\") }&.delete(\"#\")\n end", "def destroy_all\r\n Message.destroy_all(channel: @channel)\r\n respond_to do |format|\r\n format.html { redirect_to channel_messages_url(@channel), notice: 'Chat erfolgreich geleert.' }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @fav_channel = WatchChannel.find(params[:id])\n @fav_channel.delete\n flash.now[:notice] = \"#{@fav_channel.channel.channel_or_cug} #{@fav_channel.channel.name} has been removed from your favorite list\"\n end", "def unsubscribe_webhook\n if @redis\n @redis.pubsub.unsubscribe(subscribed_channel)\n @redis.close_connection\n end\n end", "def unsubscribe(*channels)\n _subscription(:unsubscribe, 0, channels, nil)\n end", "def destroy\n @channel_statistic.destroy\n respond_to do |format|\n format.html { redirect_to channel_statistics_url, notice: 'Channel statistic was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy_channels(client_id, channel_symbols, options = {})\n channel_symbols = [channel_symbols] unless channel_symbols.is_a? Array\n\n client_ids_to_be_unsubscribed = []\n channel_symbols.each do |channel_symbol|\n channel_symbol = channel_symbol.to_sym\n client_ids_to_be_unsubscribed << @channel_subscribers[channel_symbol] unless @channel_subscribers[channel_symbol].nil?\n end\n client_ids_to_be_unsubscribed = client_ids_to_be_unsubscribed.flatten.uniq\n\n client_ids_to_be_unsubscribed.each do |client_id|\n unsubscribe(client_id, channel_symbols)\n end\n\n channel_symbols.each do |channel_symbol|\n channel_symbol = channel_symbol.to_sym\n if INVALID_CHANNEL_NAMES_FOR_CREATION_AND_DESTRUCTION.include?(channel_symbol)\n notify(:type => :error, :code => 2051, :receivers => @qsif[:client_manager].web_socket(:client_id => client_id), :params => {:client_id => client_id, :channel_symbol => channel_symbol})\n next\n end\n if @channels[channel_symbol]\n subscriber = @channel_subscribers[channel_symbol]\n if subscriber\n @channel_subscriptions[subscriber].delete(channel_symbol) if @channel_subscriptions[subscriber]\n @channel_subscribers.delete(channel_symbol)\n end\n @channels.delete(channel_symbol)\n notify(:type => :debug, :code => 2050, :receivers => @qsif[:client_manager].web_socket(:client_id => client_id), :params => {:client_id => client_id, :channel_symbol => channel_symbol})\n else\n notify(:type => :error, :code => 2052, :receivers => @qsif[:client_manager].web_socket(:client_id => client_id), :params => {:client_id => client_id, :channel_symbol => channel_symbol})\n end\n end\n end", "def cleanup\n $redis.del key('chat')\n $redis.del key('messages')\n end", "def release(channel)\n @channels.push(channel)\n @channels.sort!\n end", "def clear_queues_cache\n channel.queues.clear\n end", "def unsubscribe\n redis.unsubscribe\n end", "def delete_free_iogroup_channels\n @iogroup = Iogroup.find(params[:iogroup_id])\n @iogroup.iogroupcomponents.each do |iogroupcomponent|\n iogroupcomponent.iochannels.each do |channel|\n channel.destroy!\n end\n end\n\n redirect_to iogroups_path, :notice => 'Freie Kanäle wurden gelöscht'\n end", "def destroy\n @channel_status = ChannelStatus.find(params[:id])\n @channel_status.destroy\n\n respond_to do |format|\n format.html { redirect_to channel_statuses_url }\n format.json { head :no_content }\n end\n end", "def purge!\n redis.keys(scope + \"*\").each do |key|\n redis.del key\n end\n end", "def unsubscribe(*channels)\n raise SubscriptionError, \"Can't unsubscribe if not subscribed.\" unless subscribed?\n\n @subscribed_node.unsubscribe(*channels)\n end", "def unsubscribed\n # This will broadcast that user unsubscribed but the frontend will not receive the final broadcast\n p '**** ChatChannel unsubscribed'\n notification = {notification: 'User X has dropped off'}\n # ActionCable.server.broadcast(params[:room], notification)\n send_broadcast(params[:room], notification)\n end", "def cleanup\n data_provider = Workflow::Invocation.lookup_data_provider(self.class.data_provider_name)\n channels = data_provider.data_provider_channels.all(:order => 'name')\n channels.each do |channel|\n dir = source_dir_for_channel(channel)\n # XXX ugly hack to get cleanup functional for initial release.\n # What should happen is a separate workflow should be instantiated\n # for every channel, like all other workflows work.\n @params[:channel] = channel\n cleanup_dir(dir, params)\n end\n end", "def clean_up\n Discussion.where(category_id: self.id).each do |d|\n Reply.where(discussion_id: d.id).destroy_all\n Revision.where(discussion_id: d.id).destroy_all\n d.destroy\n end\n end", "def delete(channel_id)\n\t\t\tkparams = {}\n\t\t\tclient.add_param(kparams, 'channelId', channel_id)\n\t\t\tclient.queue_service_action_call('channel', 'delete', 'bool', kparams)\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\treturn client.do_queue()\n\t\tend", "def remove(push_channel_subscription)\n push_channel_subscription_object = PushChannelSubscription(push_channel_subscription)\n raise ArgumentError, \"Channel is required yet is empty\" if push_channel_subscription_object.channel.to_s.empty?\n if push_channel_subscription_object.client_id.to_s.empty? && push_channel_subscription_object.device_id.to_s.empty?\n raise ArgumentError, \"Either client_id or device_id must be present\"\n end\n\n client.delete(\"/push/channelSubscriptions\", push_channel_subscription_object.as_json)\n end", "def destroy\n @activity = Activity.create(user_id: current_user.id, activity_type: 'Destroy', target_type: 'Channel', target_id: @channel.id)\n @channel.destroy\n respond_to do |format|\n format.html { redirect_to channels_url, notice: 'Channel was successfully destroyed.' }\n format.json { head :no_content }\n format.js\n end\n end", "def remove_course_forum\n @student_forums = ForumContributor.where(:user_id => self.pupil_id)\n @student_forums.each do |f|\n f.destroy\n end\n end", "def unsubscribe(user)\n @clients.delete(user.signature)\n self.class.remove_channel(self) if empty?\n end", "def unsubscribe\n @conn.send_data :opcode => UNSUBSCRIBE, :channel => @name\n end", "def unsubscribe\n @entry.subscribers.delete(current_user)\n end", "def punsubscribe(*channels)\n raise NotImplementedError\n end", "def free_channels\n @channels.each_with_index do |channel, index|\n if channel\n unless SDL2::Mixer::Channels.play?(index)\n @channels[index] = false\n end\n end\n end\n end", "def cleanup\n @channel.close if @channel\n\n nil\n end", "def destroy\n @tv_channel.destroy\n respond_to do |format|\n format.html { redirect_to tv_channels_url, notice: 'Tv channel was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy_collaborated_wikis_before_delete\n #1 fetch list of wiki_ids for that the user is a collaborator on\n wiki_ids = $redis.smembers(self.collaborated_wikis_hash_key)\n #2 iterate over those wiki ids and remove instances where that user/wiki relationship exists\n #not sure about the below\n wiki_ids.each do |wiki_id|\n $redis.srem(Wiki.wiki_collaborators_hash_key(wiki_id), self.id)\n end\n $redis.del(self.collaborated_wikis_hash_key)\n end", "def destroy\n @channel_type.destroy\n respond_to do |format|\n format.html { redirect_to channel_types_url, notice: 'Channel type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def close\n subscriptions.keys.each do |id| \n channel, sig = id.to_a.flatten\n Channel[app_id => channel].unsubscribe(subscriptions.delete(channel => sig))\n end\n end", "def remove_pending(*args)\n\n\t\t# Redirect to remove connection since it is an unbiased connection removed and would do this anyway\n\t\tself.send('remove_connection', *args)\n\tend", "def destroy\n @channel_info = ChannelInfo.find(params[:id])\n @channel_info.destroy\n\n respond_to do |format|\n format.html { redirect_to marketing_channel_infos_url }\n format.json { head :no_content }\n end\n end", "def unsubscribeack(channel, ack)\n @ws.send(get_unsubscribe_object(channel, increment_cnt).to_json)\n @channels.delete(channel)\n @acks[@cnt] = [channel, ack]\n end", "def unsubscribed\n User.find(current_user.id).update(online: false)\n ActionCable.server.broadcast(\n 'appearance_channel',\n user_id: current_user.id,\n is_online: false\n )\n end", "def unsubscribe(course)\n subscribeds.delete(course)\n end" ]
[ "0.69945365", "0.68250734", "0.6788795", "0.67515117", "0.6709242", "0.6559873", "0.6499193", "0.6446304", "0.6427382", "0.6427382", "0.6407356", "0.6380801", "0.6374218", "0.6371486", "0.6262556", "0.62399656", "0.62184054", "0.61931026", "0.6152476", "0.6128578", "0.6127365", "0.61094165", "0.6084874", "0.6042197", "0.60273564", "0.5976341", "0.5972687", "0.59625643", "0.5940244", "0.59184563", "0.5910971", "0.5908789", "0.5875806", "0.5869756", "0.58484745", "0.58447313", "0.5833135", "0.5833135", "0.5822618", "0.57916456", "0.5783683", "0.5780591", "0.5776842", "0.5768984", "0.575437", "0.5749522", "0.5749152", "0.57385343", "0.57364756", "0.573379", "0.5717125", "0.57066995", "0.5682286", "0.5660809", "0.5645693", "0.5633368", "0.5631552", "0.5619405", "0.5619405", "0.5618871", "0.5602933", "0.55956745", "0.558075", "0.5574937", "0.55511516", "0.55474657", "0.55393744", "0.5537416", "0.54752845", "0.54709387", "0.54627115", "0.54624784", "0.54527694", "0.5435517", "0.54254514", "0.5414796", "0.53693086", "0.53654885", "0.53631985", "0.5358517", "0.5357481", "0.535745", "0.5354774", "0.53541845", "0.53492004", "0.5336411", "0.5336033", "0.5328589", "0.5317114", "0.5311079", "0.5305679", "0.5297841", "0.5290555", "0.52784956", "0.52587223", "0.52363527", "0.5231116", "0.52290154", "0.52243865", "0.5219568" ]
0.7334368
0
Tracks that this channel will be notified from the live query.
def track_channel_in_live_query(live_query) channel_live_queries = @volt_app.channel_live_queries channel_live_queries[@channel] ||= [] channel_live_queries[@channel] << live_query end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def notify_observers(*args)\n return unless changed?\n\n unwrap(connection).exec \"NOTIFY #{channel}, #{args}\"\n\n changed false\n end", "def notify\n changed(true)\n notify_observers(self)\n end", "def notify_game_change\n connection.execute \"NOTIFY #{channel}, #{connection.quote self.to_s}\"\n end", "def subscribe_to_channel; end", "def subscribed\n stream_from channel_name\n end", "def subscribed; end", "def subscribed\n super\n increase_current_users\n stream_from channel\n end", "def subscribe\n self.subscribed = true\n end", "def on_track_change\n # XXXMLG implement\n end", "def notify\n @subscribers.each { |ident, (block,obj)| block.call(obj) }\n end", "def subscribed # :doc:\n # Override in subclasses\n end", "def _active_remote_track_changes?\n @_active_remote_track_changes != false\n end", "def notify\n {\n }\n end", "def notify\n {\n }\n end", "def before_query(query)\n if query.subscription? && !query.subscription_update?\n query.context.namespace(:subscriptions)[:events] = []\n end\n end", "def send_update\n changed\n notify_observers(self)\n end", "def notify\n return if destroy_if_old\n\n increase_busy_counter\n\n create_push\n end", "def on_connected\n end", "def notify\n end", "def detect_changed(skip_channel)\n not_added_or_removed = @previous_ids & @current_ids\n\n not_added_or_removed.each do |id|\n if @previous_results_hash[id] != (data = @results_hash[id])\n # Data hash changed\n @live_query.notify_changed(id, data, skip_channel)\n end\n end\n end", "def notify\n puts 'Subject: Notifying observers...'\n @observers.each { |observer| observer.update(self) }\n end", "def send_ready_notification\n\n end", "def subscribed\n \t#stream_from 'demo_chan'\n end", "def notify_subscribers\n NotificationSubscription.notify(self)\n end", "def on_open(event)\n logger.debug \"Connection openned as user: #{@user} on channel: #{@channel}.\"\n end", "def monitor_redis\n # redis.dup.subscribe(REDIS_CHANNEL) do |on|\n redis.subscribe(REDIS_CHANNEL) do |on|\n on.message do |_, message|\n l = REDIS_HEAD_FIELD_LENGTH\n channel = message[0, l].strip\n client_id = message[l, l].strip\n json = message[(l * 2)..-1]\n send_json_message(client_id: client_id, channel: channel, json: json)\n end\n end\n end", "def subscribe\n debug [self.name, \"incoming\"]\n subscribe_request\n end", "def track\n self.class.track(@tracking)\n end", "def observer\n Observer.for_db(self)\n end", "def notify\n {}\n end", "def notify\n {}\n end", "def notify\n {}\n end", "def notify_new_findings\n # TODO: make the method avoid the creation of a Notification record\n end", "def channel!\n return true unless query?\n\n raise 'This command may only be used in channels.'\n end", "def low_frequency\n log \"Updating event status\"\n M2mhub::Event.open_or_recently_closed.each(&:update_status!)\n log \"Finished\"\n true\n end", "def update\n Channel.channels_to_update\n end", "def channel?\n not query?\n end", "def broadcast_to_channel\n if Setting.first.reminders_enabled\n ActionCable.server.broadcast 'notification_channel', notification: self.to_serialize\n end\n end", "def subscribed\n id = params.fetch(:id)\n return unless execution = JobQueue.find_by_id(id)\n\n execution.viewers.push current_user\n\n Thread.new do\n ActiveRecord::Base.connection_pool.with_connection do\n builder = EventBuilder.new(execution.job)\n execution.output.each do |event, data|\n transmit event: event, data: builder.payload(event, data)\n end\n # TODO: disconnect all listeners so they close their sockets ?\n # then replace the reloaded/finished/waitUntilEnabled stuff with that\n end\n end\n end", "def notify_ready\n notify(\"READY=1\")\n end", "def show\n @notification.seen = true\n @notification.save\n end", "def pushed\n return false if deactivated?\n self.status = 'publishing'\n notify_observers :after_push if (suc = save)\n suc\n end", "def subscribe_notifications\n @subscribe_notifications ||= true\n end", "def track!\n tracker.track(params)\n end", "def track!\n tracker.track(params)\n end", "def onotify (channel, *args)\n\n do_notify(:all, channel, *args)\n do_notify(channel, channel, *args)\n end", "def connected\n\t\tdo_send('CN1')\t# Connection command - initiate comms\n\t\n\t\t@polling_timer = schedule.every('60s') do\n\t\t\tlogger.debug \"Polling JVC\"\n\t\t\tdo_send('CN1')\t# Connection command\n\t\tend\n\tend", "def coached_session_changed?\n coach_connections.any? && timeslot_changed?\n end", "def notify?\n true\n end", "def will_notify\n #Resque.safe_enqueue Notification, to_user_id, id, APP::NOTIFICATIONS::MESSAGE\n end", "def on_connected(&block)\n @on_connected_procs << block\n end", "def subscribe!\n # TODO: Implement\n end", "def observe_candidate\n observe { run_candidate }\n end", "def notify_new_finding\n # TODO: make the method avoid the creation of a Notification record\n end", "def cmd_notify_start\n\t\t\t\tprint_status \"Session activity will be sent to you via Slack Webhooks, channel: #{@channel}\"\n\t\t\t\tif read_settings()\n\t\t\t\t\tself.framework.events.add_session_subscriber(self)\n\t\t\t\t\tprint_good(\"Notify Plugin Started, Monitoring Sessions\")\n\t\t\t\telse\n\t\t\t\t\tprint_error(\"Could not set Slack Web API settings.\")\n\t\t\t\tend\n\t\t\tend", "def channel\r\n @record\r\n end", "def prePushListener\n end", "def seen\n if @ok\n @ok = @notification.has_been_seen\n end\n @new_notifications = current_user.number_notifications_not_seen\n end", "def broadcast_request_acceptance\n ActionCable.server.broadcast(\n \"notification_channel_#{@requestee_node.user_id}\",\n requesteeId: current_user.id,\n type: 'accept request'\n )\n end", "def on_appear\n @update = true\n unless @checkingCheckins\n update_checkins\n end\n unless @pinging\n location_ping\n end\n @frequency = 20\n end", "def notify?\n true\n end", "def add_tracked_subscriptions(channel_ids)\n channel_ids.each do |channel_id|\n ys = self.youtube_subscriptions.find_by(channel_id: channel_id)\n ys.update_attributes(tracked: true) if ys\n end\n end", "def notify_receiver\n conversation = ConversationBlueprint.render_as_json(self, view: :normal)\n ActionCable.server.broadcast \"user_#{ self.user_two_id }_notification_channel\", conversation\n end", "def listen\n @queue.subscribe(block: true) do |delivery_info, properties, body|\n puts(body)\n end\n end", "def trackable?\n true\n end", "def notify_change(method, *args)\n changed\n notify_observers(method, self, *args)\n end", "def broadcast_update\n broadcast broadcast_event_name(:updated), self, previous_changes\n end", "def on_subscribed(&block)\n return unless block\n\n call_now = false\n @lock.synchronize do\n if @subscribed\n call_now = true\n else\n @on_subscribed_handlers << block\n end\n end\n if call_now\n after(0, &block)\n end\n end", "def connected\n\t\t#\n\t\t# Get current state of the projector\n\t\t#\n\t\tdo_poll\n\t\t\n\t\t#\n\t\t# Get the state every 50 seconds :)\n\t\t#\n\t\t@polling_timer = schedule.every('50s') do\n\t\t\tdo_poll\n\t\tend\n\tend", "def notify\n return {}\n end", "def notify\n return {}\n end", "def notify\n return {}\n end", "def perform\n @logger.info({context: :monitor, action: :perfomed})\n @client.psubscribe(\"#{service}:*\") do |callback|\n callback.psubscribe(self.on_subscribed)\n callback.pmessage(self.on_message)\n callback.punsubscribe(self.on_unsubscribed)\n end\n end", "def notify_channel(connection, channel, payload)\n connection.execute(\"NOTIFY #{channel}, #{payload}\")\n end", "def notify\n raise NotImplementedError\n end", "def data_channel_open\n puts \"Data channel open!\"\n data_channel = $$.data_channel\n # send_message(\"ALIVE\")\nend", "def on_notification(&block)\n @callback = block\n end", "def on_connection_listener_fetch_loop_received(event)\n listener = event[:caller]\n time = event[:time]\n messages_count = event[:messages_buffer].size\n\n message = \"[#{listener.id}] Polled #{messages_count} messages in #{time}ms\"\n\n # We don't want the \"polled 0\" in dev as it would spam the log\n # Instead we publish only info when there was anything we could poll and fail over to the\n # zero notifications when in debug mode\n messages_count.zero? ? debug(message) : info(message)\n end", "def evented\n @evented = true\n end", "def fire_presence_open_events(endpoint, channel)\n channel_name = channel.name\n presence_info = endpoint.presence_info\n already_logged = channel.subscriptions_for(presence_info[:user_id]).length > 1\n invisible = presence_info[:invisible]\n # Send the connection open to other peers\n unless already_logged || invisible\n channel.publish presence_message_generate(channel_name, 'open', presence_info)\n end\n\n # And send to this peer other connections status\n channel.unique_subscriptors.each do |s|\n if (s[:user_id] != presence_info[:user_id] && !s[:invisible]) || already_logged\n endpoint.send_to_client presence_message_generate(channel_name, 'current', s)\n end\n end\n end", "def notify_subscribers\n NotifierJob.perform_later(self)\n end", "def notify?\n @notify == true\n end", "def after_query(query)\n events = query.context.namespace(:subscriptions)[:events]\n if events && events.any?\n @schema.subscriptions.write_subscription(query, events)\n end\n end", "def live\r\n channels = Channel.live\r\n render json: channels\r\n end", "def trackable?\n published?\n end", "def notify_pusher\n Pusher.trigger('location', 'new', self.trip.as_json)\n end", "def broadcast\n ActionCable.server.broadcast \"#{self.loggable_type}:#{self.loggable_id}\", self\n end", "def subscribe_to_channel(*)\n synchronize_entrypoint! { super }\n end", "def updated?\n self.connected && self.updated\n end", "def activate_observer(client = isimud_client)\n create_queue(client)\n isimud_send_action_message(:update)\n end", "def changed_and_notify(*args)\n changed\n notify_observers(*args)\n end", "def notifications\n end", "def email_changed?\n (self.channel_referent_id==0) && super\n end", "def notify(path, event_type = nil)\n changed(true)\n notify_observers(path, event_type)\n end", "def subscribe(data)\n # @channels (local tracker)\n # push channel name into subscribe list, if and only if not already in subscribe list\n end", "def inform_obeservers\n\t\t@observers.each { |observer| observer.update(self) }\n\tend", "def unsubscribed; end", "def listen\n # TODO\n self\n end", "def suscription_on?\n is_subscribed == true\n end", "def notification_query_options=(value)\n @notification_query_options = value\n end" ]
[ "0.6165639", "0.60553515", "0.6018944", "0.5887589", "0.584748", "0.583743", "0.5718442", "0.5641111", "0.56367415", "0.5604656", "0.5567094", "0.5544769", "0.554235", "0.554235", "0.55167496", "0.54863924", "0.5463499", "0.54607975", "0.54401386", "0.5414997", "0.538091", "0.5373552", "0.53644234", "0.5335433", "0.5331689", "0.532879", "0.5320217", "0.5300382", "0.5295735", "0.527714", "0.527714", "0.527714", "0.5267386", "0.5253398", "0.5246473", "0.5245212", "0.5237753", "0.523273", "0.5231333", "0.5223265", "0.52198815", "0.52143866", "0.52007365", "0.51998067", "0.51998067", "0.51942265", "0.51829404", "0.51725054", "0.5162132", "0.513316", "0.513042", "0.5114885", "0.5105529", "0.5099453", "0.50915945", "0.5084892", "0.50731313", "0.50711536", "0.5069342", "0.5063568", "0.5054383", "0.50531304", "0.5050982", "0.50466853", "0.50385725", "0.5038284", "0.5030698", "0.5020126", "0.50145364", "0.5008861", "0.5008861", "0.5008861", "0.5007294", "0.50055563", "0.500458", "0.5002594", "0.49967292", "0.499574", "0.49949598", "0.49900526", "0.49855372", "0.4984307", "0.49840298", "0.49756184", "0.49750316", "0.49702948", "0.49692687", "0.49541843", "0.49438906", "0.49416304", "0.49341458", "0.49333808", "0.49324235", "0.49315804", "0.4927144", "0.49247712", "0.49209607", "0.49199617", "0.49185517", "0.49161065" ]
0.7171607
0
Send the request to the URL and retrun raw data of the response
def raw_exchange_rates # BanqueMisr provide 18 currencies (17 Used and CYPRUS POUND) # But they have 2 <tr> for headers table_rows = Oga.parse_html(response.body).css('.exchangeRates tbody tr') fail ResponseError, 'Unknown HTML' unless table_rows&.size == 20 # remove the first 2 headers of the array and the last element # which is CYPRUS POUND which is not used anymore table_rows.lazy.drop(2).take(17).map(&:children).map do |cell| cell.map(&:text) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def do_request()\n uri = URI.parse(API_BASE_URL + build_request_path())\n response = Net::HTTP.get_response(uri)\n response.body\n end", "def raw_response\n Net::HTTP.get(endpoint)\n end", "def send_and_receive\n url = to_s\n raw_response = HTTPClient.new.get(url).body\n parsed_response = BEncode::Parser.new(StringIO.new(raw_response))\n parsed_response.parse!\n end", "def get\n @response = Net::HTTP.get_response(URI(@url))\n end", "def perform_http_request\n request_opts = { followlocation: true, ssl_verifypeer: false, timeout: 30 }\n @response = Typhoeus.get(@webpage_request.url, request_opts)\n @response && process_response_data\n @response\n end", "def retrieve_response\n session.post(url)\n end", "def request\n uri = URI(final_url)\n response = Net::HTTP.get(uri)\n ResponseAdapter.new(response: response)\n end", "def send_request(uri)\n resp = Net::HTTP.get_response(uri) \n data = JSON.parse(resp.body) # convert the JSON string to Ruby Hash\n return data\n end", "def request\n self.response = prepare_response(http_communication.content)\n end", "def go_get_raw(url)\n begin\n puts \"Connecting to URL: \" + url\n response = HTTParty.get(url, timeout: Rails.configuration.x.network_time_out)\n rescue Exception => e\n puts \"Connection ERROR: \" + e.message\n return nil\n end\n return response\n end", "def do_get url\n\t\turi = URI.parse(url)\n\t\tNet::HTTP.get_response(uri)\n\tend", "def send_get(url)\r\n result = @client.get(self.target_uri(url))\r\n raise \"Invalid status #{result.http_status} from server #{@host}:#{@port}\" if(result.http_status != '200')\r\n if block_given?\r\n yield(result.http_body)\r\n else\r\n result.http_body\r\n end\r\n end", "def perform_request url\n response = self.class.get(url)\n raise NotFound.new(\"404 Not Found\") if response.respond_to?(:code) && response.not_found?\n raise InvalidAPIResponse.new(response[\"status\"][\"message\"]) if response.is_a?(Hash) && response[\"status\"]\n\n response\n end", "def execute\n uri = request_uri\n http = Net::HTTP.new(uri.host, uri.port)\n request = Net::HTTP::Get.new(uri.request_uri)\n retries = Europeana.max_retries\n \n begin\n response = http.request(request)\n rescue Timeout::Error, Errno::ECONNREFUSED, EOFError\n retries -= 1\n raise unless retries > 0\n sleep Europeana.retry_delay\n retry\n end\n \n json = JSON.parse(response.body)\n raise Errors::RequestError, json['error'] unless json['success']\n json\n rescue JSON::ParserError\n raise Errors::ResponseError\n end", "def send_request\n @response = _send_request\n end", "def fetch()\n @result = open(@url,@headers)\n end", "def request(url)\n\n # For catch 4xx and 5xx HTTP errors\n has_errors = false\n\n # Send request to vendor API\n http = Curl.get(url) do |http|\n\n # On 4xx errors\n http.on_missing do\n has_errors = true\n end\n\n # On 5xx errors\n http.on_failure do\n has_errors = true\n end\n\n end\n\n raise \"Error from TRADO API - #{http.body_str}\" if has_errors\n\n JSON.parse(http.body_str)['data']\n\n end", "def request_data(request_url)\n\n uri = URI.parse(request_url)\n response = Net::HTTP.get_response(uri)\n data = JSON.parse(response.body)\n return data\n\nend", "def get_response(url)\n uri = URI(url)\n Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|\n request = Net::HTTP::Get.new uri\n return http.request(request).body\n end\nend", "def send_request(url, data)\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port)\n if uri.port == 443\n http.use_ssl\t= true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n response = http.post(uri.path, data)\n response.code == '200' ? response.body : response.error!\n end", "def response_from(request, url, options)\n begin\n response = HTTP.start url.host, url.port, options do |http|\n request.basic_auth OBIX.configuration.username, OBIX.configuration.password\n http.request request\n end\n\n unless response.code == \"200\"\n raise Error, \"The server responded with an unexpected status code #{response.code} for #{url}.\"\n end\n\n response.body\n rescue ::Timeout::Error\n raise Timeout, \"The remote server did not respond in a timely fashion\"\n end\n end", "def run_request(method, url, body, headers); end", "def send_request(url)\n verify_credentials!\n\n api_response = nil\n\n complete_url = Applitrack.api_base + url\n uri = URI(complete_url)\n\n Net::HTTP.start(uri.host, uri.port,\n use_ssl: uri.scheme == 'https') do |http|\n\n request = Net::HTTP::Get.new(uri.request_uri)\n request.basic_auth(Applitrack.username, Applitrack.password)\n\n api_response = http.request(request)\n if api_response.code != \"200\"\n raise api_error(api_response)\n end\n end\n\n api_response\n end", "def send_data(data, url)\n content_type = :xml\n response = Requester.request(url, data, content_type)\n response.body\n end", "def fetch_data\n res = Net::HTTP.start(DATA_URI.host, DATA_URI.port) do |http|\n http.get(DATA_URI.path, 'USER_AGENT' => 'Nordea::Bank gem')\n end\n\n if res.code =~ /2\\d\\d/\n res.body\n else\n fail ServerError, 'The server did not respond in the manner in which we are accustomed to.'\n end\n end", "def request\n self.http_response = http_client.get(url, request_options)\n self\n end", "def send\n uri = URI(@api_url)\n http = Net::HTTP.new(uri.host, uri.port)\n if uri.scheme == \"https\"\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n end\n http.read_timeout = GlobalConstant::CompanyApi.read_timeout\n http.open_timeout = GlobalConstant::CompanyApi.open_timeout\n req_obj = get_request_obj(uri.request_uri)\n\n http_response, e = nil, nil\n begin\n http_response = http.request(req_obj)\n set_api_response_cookie(http_response)\n parse_api_response(http_response)\n rescue Net::ReadTimeout, Net::OpenTimeout => e\n # Timeouts\n exception_with_internal_code(\n e,\n 'company_api_timeout',\n 'company api timeout',\n GlobalConstant::ErrorCode.internal_server_error,\n debug_data\n )\n rescue Exception => e\n # Exceptions\n exception_with_internal_code(e, 'company_api_exception', 'company api exception', GlobalConstant::ErrorCode.internal_server_error, debug_data)\n end\n\n end", "def upstream_response\n http = EM::HttpRequest.new(url).get\n logger.debug \"Received #{http.response_header.status} from NextBus\"\n http.response\n end", "def get url\n net_http_response = self.connection.get url\n [net_http_response.body, net_http_response.code.to_i, net_http_response.message]\n end", "def make_request\n response = @http.request(@request)\n end", "def do_request\n\t\t\tself.response = post_request(options)\n\t\tend", "def raw\n begin\n @raw ||= request_json(url)\n rescue OpenURI::HTTPError => e\n Rails.logger.error \"#{e.message}: #{url}\"\n raise\n end\n end", "def fetch\n response = HTTParty.get(@url)\n if response.success?\n @data = response.parsed_response\n end\n response.code\n end", "def request(url, body)\n #res = HTTParty.post(url, body: body, headers: {'Content-Type' => 'application/soap+xml; charset=\"utf-8\"'}, :verify => false)\n res = HTTParty.post(url, body: body, headers: {'Content-Type' => 'application/soap+xml; charset=\"utf-8\"'}, :verify => false)\n p \"response is: #{res}. response body is: #{res.body} for url: #{url}\"\n content = JSON.parse(res.body)\n end", "def call(request)\n\t\t\t\t\t\traise ::Protocol::HTTP2::Error, \"Connection closed!\" if self.closed?\n\t\t\t\t\t\t\n\t\t\t\t\t\t@count += 1\n\t\t\t\t\t\t\n\t\t\t\t\t\tresponse = create_response\n\t\t\t\t\t\tresponse.send_request(request)\n\t\t\t\t\t\tresponse.wait\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn response\n\t\t\t\t\tend", "def raw_response; end", "def submit\n http = Net::HTTP.new(URL.host, URL.port)\n http.use_ssl = true\n http.start { |send| send.request(self) }.body\n end", "def request(method, path, params)\n params ||= {}\n uri = full_url(path)\n\n Trubl.logger.info(\"Trubl::Client #{method}-ing #{uri} with params #{params.merge(headers: headers)}\")\n response = HTTMultiParty.send(method, uri, params.merge(headers: headers))\n\n if !response.code =~ /20[0-9]/\n Trubl.logger.fatal(\"Trubl::Client #{response.code} #{method}-ing #{uri.to_s} #{response.parsed_response}\")\n else\n Trubl.logger.debug(\"Trubl::Client #{uri} response: #{response.body}\")\n end\n response.body.force_encoding(\"utf-8\") if response.body and response.body.respond_to?(:force_encoding)\n response\n end", "def request\n http_segments = @segments.clone\n @params.each do |key,value|\n http_segments[key] = value\n end\n \n # avoid using URI.encode\n query = ''\n http_segments.each do |key, value|\n query += \"&#{key}=#{value}\"\n end\n query = query[1..-1]\n \n uri = URI::HTTP.build(\n :host => HOST,\n :path => @action_path,\n :query => query\n ).to_s\n result = JSON.parse(HTTParty.get(uri).parsed_response)\n Baidumap::Response.new(result,self)\n end", "def simple_request(method, url)\n uri = URI.parse(url)\n request = Net::HTTP::Get.new(uri)\n request.content_type = \"application/json\"\n request[\"Accept\"] = \"application/json\"\n request[\"App-Id\"] = ENV[\"salt_edge_app_id\"]\n request[\"Secret\"] = ENV[\"salt_edge_secret\"]\n\n req_options = {\n use_ssl: uri.scheme == \"https\",\n } \n\n response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|\n http.request(request)\n end\n\n #puts response.body\n return JSON.parse(response.body)\n end", "def send_request(url, data=nil)\n begin\n puts \"BigBlueButtonAPI: URL request = #{url}\" if @debug\n url_parsed = URI.parse(url)\n http = Net::HTTP.new(url_parsed.host, url_parsed.port)\n http.open_timeout = @timeout\n http.read_timeout = @timeout\n if data.nil?\n response = http.get(url_parsed.request_uri, @request_headers)\n else\n puts \"BigBlueButtonAPI: Sending as a POST request with data.size = #{data.size}\" if @debug\n opts = { 'Content-Type' => 'text/xml' }.merge @request_headers\n response = http.post(url_parsed.request_uri, data, opts)\n end\n puts \"BigBlueButtonAPI: URL response = #{response.body}\" if @debug\n\n rescue TimeoutError => error\n raise BigBlueButtonException.new(\"Timeout error. Your server is probably down: \\\"#{@url}\\\". Error: #{error}\")\n\n rescue Exception => error\n raise BigBlueButtonException.new(\"Connection error. Your URL is probably incorrect: \\\"#{@url}\\\". Error: #{error}\")\n end\n\n response\n end", "def response\n @response ||= Net::HTTP.new(uri.host).request(request)\n end", "def restRequest(url)\n printDebugMessage('restRequest', 'Begin', 11)\n printDebugMessage('restRequest', 'url: ' + url, 12)\n # Split URL into components\n uri = URI.parse(url)\n # Create a HTTP connection\n httpConn = Net::HTTP.new(uri.host, uri.port)\n # Get the resource\n if uri.query\n path = \"#{uri.path}?#{uri.query}\"\n else\n path = uri.path\n end\n resp, data = httpConn.get(path, {'User-agent' => getUserAgent()})\n case resp\n when Net::HTTPSuccess, Net::HTTPRedirection\n # OK\n else\n $stderr.puts data\n resp.error!\n end\n printDebugMessage('restRequest', 'data: ' + data, 21)\n printDebugMessage('restRequest', 'End', 11)\n return data\n end", "def send_request; end", "def get_http_content\n uri.query = URI.encode_www_form(params)\n res = Net::HTTP.get_response(uri)\n\n raise HTTPError.new(\"invalid #{res.code} response\") unless res.is_a?(Net::HTTPSuccess)\n\n puts res.code\n res.body\n end", "def get_content\n send_get_content(url)\n end", "def send\n sleep(delay_seconds) # Delay request if needed\n http = Net::HTTP.new(@uri.host, @uri.port)\n http.use_ssl = @config_use_ssl\n begin\n res = http.start { |http| @response = http.request(@request) }\n rescue Exception => e\n @failures << \"Exception raised while making request: #{e.message}\"\n end\n if @failures.size == 0\n @send_count += 1\n if @oks.include?(res.code)\n Log.response(@response)\n else\n Log.response(@response, false)\n @failures << \"Request returned #{res.code}\"\n end\n end\n end", "def dsi_send(request)\n socket = TCPSocket.new(URL, test? ? TEST_PORT : LIVE_PORT )\n\n ssl_context = OpenSSL::SSL::SSLContext.new\n ssl_context.verify_mode = OpenSSL::SSL::VERIFY_PEER\n\n ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)\n ssl_socket.sync_close = true\n ssl_socket.connect\n \n ssl_socket.puts(request)\n ssl_socket.flush\n \n response = \"\"\n \n while line = ssl_socket.gets\n response << line unless line.include? \"endofdata\"\n end\n \n ssl_socket.close\n return response\n end", "def request( params={} )\n if Biomart.proxy or ENV['http_proxy']\n proxy_uri = Biomart.proxy\n proxy_uri ||= ENV['http_proxy']\n proxy = URI.parse( proxy_uri )\n @@client = Net::HTTP::Proxy( proxy.host, proxy.port )\n end\n \n params[:url] = URI.escape(params[:url])\n \n if params[:method] === 'post'\n res = @@client.post_form( URI.parse(params[:url]), { \"query\" => params[:query] } )\n else\n res = @@client.get_response( URI.parse(params[:url]) )\n end\n \n # Process the response code/body to catch errors.\n if res.code != \"200\"\n raise HTTPError.new(res.code), \"HTTP error #{res.code}, please check your biomart server and URL settings.\"\n else\n if res.body =~ /ERROR/\n if res.body =~ /Filter (.+) NOT FOUND/\n raise FilterError.new(res.body), \"Biomart error. Filter #{$1} not found.\"\n elsif res.body =~ /Attribute (.+) NOT FOUND/\n raise AttributeError.new(res.body), \"Biomart error. Attribute #{$1} not found.\"\n elsif res.body =~ /Dataset (.+) NOT FOUND/\n raise DatasetError.new(res.body), \"Biomart error. Dataset #{$1} not found.\"\n else\n raise BiomartError.new(res.body), \"Biomart error.\"\n end\n end\n end\n \n return res.body\n end", "def send_request(method, url)\n @response = client.run_request(method, url, @body, headers) do |req|\n req.params = params\n end\n end", "def execute\n options = {\n method: :post,\n timeout: 6000,\n open_timeout: 6000,\n accept: :schema\n }\n options.merge!(url: @url, payload: @html)\n begin\n res = RestClient::Request.execute(options).to_str\n @response = JSON.parse(res)\n rescue => e\n puts \"some problems with #{@url}\"\n puts e\n nil\n end\n end", "def execute\n response = send_request\n response.body.to_s\n rescue HTTP::Redirector::TooManyRedirectsError\n raise ProxyFetcher::Exceptions::MaximumRedirectsReached\n end", "def get_response(uri)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = (uri.scheme == 'https')\n http.start do |http|\n resp, body = http.get([uri.path, uri.query].join('?'))\n end\n end", "def request(url, options)\n\t\tmy_url = URI.parse(URI.encode(url))\n\n\t\tbegin\n\t\t\tmy_url = URI.parse(url)\n\t\trescue URI::InvalidURIError\n\t\t\tmy_url = URI.parse(URI.encode(url))\n\t\tend\n\nstart_time = Time.now\n\t\tproxy_host = 'ubio.cnio.es'\n\t\tproxy_port = 3128\n\t\treq = Net::HTTP::Get.new(my_url.request_uri)\n#\t\tres = Net::HTTP.start(my_url.host, my_url.port, proxy_host, proxy_port) { |http|\n\t\tres = Net::HTTP.start(my_url.host, my_url.port) { |http|\n\t\t\thttp.request(req)\n\t\t}\n\n\n\n\t\t#http_session = proxy.new(my_url.host, my_url.port)\n\t\t#\n\t\t#res = nil\n\t\t#proxy.new(my_url.host, my_url.port).start { |http|\n\t\t#Net::HTTP::Proxy(proxy_host, proxy_port).start(my_url.host) { |http|\n\t\t#\treq = Net::HTTP::Get.new(my_url.request_uri)\n\t\t#\tres, data = http.request(req)\n\t\t#\n\t\t#\tputs \"shitting data: #{data}\\n\"\n\t\t#\tputs \"res.code: #{res.code}\\n\"\n\t\t#}\n\t\t#\n\t\t#\n\t\t#res = Net::HTTP.start(my_url.host, my_url.port) { |http|\n\t\t#\treq = Net::HTTP::Get.new(my_url.request_uri)\n\t\t#\thttp.request(req)\n\t\t#}\n\n\n#end_time = Time.now\n#elapsed_time = (end_time - start_time) * 1000\n#puts \"***=> Time elapsed for #{url}: #{elapsed_time} ms\\n\"\n#\n#puts \"response code: #{res ? res.code: 'res not available here'}\"\n\n\t\tres\n\tend", "def http_get(request)\n tries = 3\n begin\n curl = Curl::Easy.new request\n curl.useragent = USER_AGENT\n curl.perform\n begin\n JSON.parse curl.body_str\n rescue JSON::ParserError => err\n @log.warn \"Could not parse response for #{request} - this is probably not a json response: #{curl.body_str}\"\n return nil\n end\n rescue Curl::Err::ConnectionFailedError => err\n @log.error \"Connection failed: #{err}\"\n tries -= 1\n sleep 3\n if tries > 0\n retry\n else\n nil\n end\n rescue Curl::Err::RecvError => err\n @log.error \"Failure when receiving data from the peer: #{err}\"\n tries -= 1\n sleep 3\n if tries > 0\n retry\n else\n nil\n end\n rescue Curl::Err => err\n @log.error \"Failure in Curl call: #{err}\"\n tries -= 1\n sleep 3\n if tries > 0\n retry\n else\n nil\n end\n end\n end", "def fetch_from_url url\n require \"net/http\"\n\n uri = URI.parse(url)\n\n http = Net::HTTP.new(uri.host, uri.port)\n request = Net::HTTP::Get.new(uri.request_uri)\n\n request['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36 OPR/36.0.2130.46'\n \n response = http.request(request)\n \n return response.body # => The body (HTML, XML, blob, whatever)\n end", "def go_get(url)\n begin\n puts \"Connecting to URL: \" + url\n response = HTTParty.get(url, timeout: Rails.configuration.x.network_time_out)\n data = response.parsed_response\n rescue Exception => e\n puts \"Connection ERROR: \" + e.message\n return nil\n end\n return data\n end", "def make_http_request\n Net::HTTP.get_response('localhost', '/ping', 3000).body\nend", "def retrieve\n http_class = http_proxy @proxy[:host], @proxy\n\n @_req = http_class.new @uri.host, @uri.port\n\n @_req.read_timeout = @timeout if @timeout\n @_req.use_ssl = true if @uri.scheme =~ /^https$/\n\n elapsed_time = nil\n socket = nil\n socket_io = nil\n\n @_res = @_req.start do |http|\n socket = http.instance_variable_get \"@socket\"\n socket.debug_output = socket_io = StringIO.new\n\n start_time = Time.now\n res = http.request self.http_request, @body\n elapsed_time = Time.now - start_time\n\n res\n end\n\n Kronk.cookie_jar.set_cookies_from_headers @uri.to_s, @_res.to_hash if\n self.use_cookies\n\n @response = Response.new socket_io, @_res, self\n @response.time = elapsed_time\n\n @response\n end", "def request(url)\n raise TypeError, 'url must be a String or respond_to #to_s' unless url.is_a?(String) || url.respond_to?(:to_s)\n @parameters['url'] = url.to_s # The URL must contain the entire URL with the _escaped_fragment_ parsed out\n \n content_from_response(send_request)\n end", "def request\n url1 = url\n return false unless valid?\n http_response = HTTParty.post(url, :format => :plain,\n :query => @params.merge({ :cmd => @cmd }),\n :headers => {\n 'ZooZ-Unique-ID' => @unique_id,\n 'ZooZ-App-Key' => @app_key,\n 'ZooZ-Response-Type' => @response_type,\n }) if @response_type.eql?('NVP')\n\n\n\n http_response = HTTParty.post(url, :format => :json,\n :body => @params.merge({ :cmd => @cmd }),\n :headers => {\n 'ZooZDeveloperId' => @developer_id,\n 'ZooZServerAPIKey' => CGI::escape(@app_key)\n }) if @response_type.eql?('JSON')\n\n response = Response.new\n response.request = self\n response.http_response = http_response\n unless response.success?\n @errors = response.errors\n return false\n end\n response\n end", "def response\n connection.send(request_method) do |req|\n req.url path\n req.headers['LicenseID'] = client.license_id\n req.headers['Host'] = client.host\n req.headers['Connection'] = 'Keep-Alive'\n req.headers['Expect'] = '100-continue'\n req.headers['Content-Type'] = 'text/xml'\n req.body = body\n end\n end", "def get_response_body\n uri = URI.parse(@url)\n response = Net::HTTP.get_response(uri)\n response.body\n end", "def request(method, path, options, raw=false)\n response = connection(raw).send(method) do |request|\n case method\n when :get\n request.url(path, formatted_options(options))\n end\n end\n raw ? response : response.body\n end", "def run\n\n action Colors.grey(\"REQUEST \") + Colors.light_blue(\"#{options[:method].upcase} #{url}\")\n Console.instance.indent\n # run the request\n options[:ssl_verifypeer] = false\n options[:followlocation] = true\n\n Injector.decorate(options)\n\n # convert all headers keys to strings to avoid having symbols like :\"header\" when\n # declaring headers with colons instead of arrows\n if options.key?(:headers)\n new_opts = {}\n options[:headers].map do |k, v|\n new_opts[k.to_s] = v\n end\n options[:headers] = new_opts\n end\n\n if options.key?(:headers) and options[:headers].key?('Content-Type')\n ctype = options[:headers]['Content-Type']\n if ctype.include?('application/json')\n # automatically encode json content\n options[:body] = JSON.generate(options[:body], quirks_mode: true)\n end\n end\n\n\n\n self.response = Typhoeus::Request.new(url, options).run\n\n self.req_response = RequestResponse.new.tap { |r|\n r.raw_body = response.body\n r.headers = response.headers\n r.code = response.code\n r.total_time = response.total_time\n\n if !r.headers.nil? && r.headers.key?('Content-Type') && r.headers['Content-Type'].include?('application/json')\n r.body = JSON.parse(response.body)\n else\n r.body = response.body\n end\n }\n\n # reset assertion counter\n self.assert_no = 1\n\n # evaluate response against expectations\n begin\n instance_eval(&expectations)\n rescue AssertionException\n error error_msg + \" at #{expectations.source_location}\"\n raise RequestException\n rescue StandardError => e\n error 'Exception ' + e.message\n info e.backtrace.inspect\n _debug_info\n error error_msg\n raise RequestException\n ensure\n Console.instance.unindent\n end\n\n req_response\n\n end", "def send_request(request) # :nodoc:\n response = @http.request(request)\n validate_response(response)\n JSON.parse(response.body)\n end", "def fetch\n open(to_url) { |io| io.read }\n end", "def get\n if @data == nil\n url = make_url\n\n begin\n @data = Net::HTTP.get(URI.parse(url))\n rescue Exception => e\n @error = \"Unable to connect to #{url}\"\n end\n end\n\n return @data\n end", "def make_request(request, error)\n # URI request with timeouts\n uri = URI.parse(\"https://derpiboo.ru/#{request}\")\n http = Net::HTTP.new(uri.host, uri.port)\n http.open_timeout = 10\n http.read_timeout = 20\n http.use_ssl = true\n attempts = 1\n # Limit attempts so we dont annoy Derpibooru too badly\n response = nil\n while (attempts < 4) && response.nil?\n begin\n response = http.request_get(uri.request_uri)\n rescue\n sleep(attempts * 2)\n attempts += 1\n end\n end\n\n if response\n return JSON.parse(response.body)\n else\n error = \"Could not get a response from Derpibooru. Wait a few minutes and try again.\"\n return nil\n end\n end", "def send\n http = Net::HTTP.new(@uri.host, @uri.port)\n http.read_timeout = @http_timeout\n\n # Output request XML if debug flag is set\n if debug == true\n logger.info \"Request URL: #{@uri.to_s}\"\n logger.info \"Request Timeout: #{@http_timeout}\"\n logger.info \"Request headers: #{headers}\"\n logger.info \"Request body: #{body}\"\n end\n\n if @uri.port == 443\n http.use_ssl = true\n http.ssl_timeout = @http_timeout\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n\n post = Net::HTTP::Post.new(@uri.path, headers)\n post.body = body\n post.content_type = 'text/xml'\n\n response = http.start { |http| http.request(post) }\n\n if debug == true\n logger.info \"Response: #{response}\"\n end\n\n if response.is_a? Net::HTTPInternalServerError\n logger.info \"#{response.class.to_s}: #{response.message}\"\n return Hashie::Mash.new({})\n end\n\n @response = Hashie::Mash.new(Response.new(self, response))\n end", "def call\n conn = http_setup\n res = set_up_response(method.to_sym, uri, conn, headers ,body)\n\n response = HttpResponse.new(res)\n response.uri = uri\n raise response.error if !response.success? && !@has_retry_filter\n response\n end", "def do_request url\n Nokogiri::HTML(HTTParty.get(url))\nend", "def http_response \n url = @options['url'] || @options[:url]\n\n uri = URI.parse(url)\n\n response = nil\n retry_url_trailing_slash = true\n retry_url_execution_expired = true\n begin\n Net::HTTP.start(uri.host) {|http|\n http.open_timeout = TIMEOUT_LENGTH\n req = Net::HTTP::Get.new((uri.path != '' ? uri.path : '/' ) + (uri.query ? ('?' + uri.query) : ''))\n if uri.user && uri.password\n req.basic_auth uri.user, uri.password\n end\n response = http.request(req)\n }\n rescue Exception => e\n # forgot the trailing slash...add and retry\n if e.message == \"HTTP request path is empty\" and retry_url_trailing_slash\n url += '/'\n uri = URI.parse(url)\n h = Net::HTTP.new(uri.host)\n retry_url_trailing_slash = false\n retry\n elsif e.message =~ /execution expired/ and retry_url_execution_expired\n retry_url_execution_expired = false\n retry\n else\n response = e.to_s\n end\n end\n \n return response\n end", "def send_request(type,params)\n request_url = prepare_url(type,params)\n log \"Request URL: #{request_url}\"\n res = nil\n RemoteUtil.do_with_retry(exceptions: [TimeoutError, InternalServerError]) do |except|\n begin\n if not except.nil?\n puts \"Error calling BestBuy API, will retry: \" + except.to_s\n end\n res = Net::HTTP.get_response(URI::parse(request_url))\n rescue Timeout::Error\n raise BestBuyApi::TimeoutError, \"Timeout calling #{request_url}\"\n end\n if res.kind_of? Net::HTTPSuccess\n # Successful HTTP result.\n elsif res.kind_of? Net::HTTPInternalServerError\n raise BestBuyApi::InternalServerError, \"HTTP Response: #{res.code} #{res.message} for #{request_url}\"\n else\n raise BestBuyApi::RequestError, \"HTTP Response: #{res.code} #{res.message} for #{request_url}\"\n end\n end\n begin\n JSON.parse(res.body)\n rescue JSON::ParserError\n raise BestBuyApi::RequestError, \"Bad Response: JSON Parser Error for #{request_url}\"\n end\n \n end", "def http_send url, form_data, headers, &block\n if form_data['action'] == 'query'\n log.debug(\"GET: #{form_data.inspect}, #{@cookies.inspect}\")\n headers[:params] = form_data\n RestClient.get url, headers, &block\n else\n log.debug(\"POST: #{form_data.inspect}, #{@cookies.inspect}\")\n RestClient.post url, form_data, headers, &block\n end\n end", "def request(method, path, options, raw = false)\n response = connection(raw).send(method) do |request|\n case method\n when :get\n request.url(formatted_path(path), options)\n end\n end\n raw ? response : response.body\n end", "def send_raw_data request, response, data, mime, status_code = 200, headers = {}\n\t\t\t\theaders.each {|k, v| response[k] = v}\n\t\t\t\tresponse.status = status_code if response.status == 200 # avoid resetting a manually set status \n\t\t\t\tresponse['content-type'.freeze] = mime\n\t\t\t\tresponse['cache-control'.freeze] ||= 'public, max-age=86400'.freeze\t\t\t\t\n\t\t\t\tresponse.body = data\n\t\t\t\t# response['content-length'] = data.bytesize #this one is automated by the server and should be avoided to support Range requests.\n\t\t\t\ttrue\n\t\t\tend", "def get_url(url)\n myurl = URI.parse(url)\n req = Net::HTTP::Get.new(url)\n res = Net::HTTP.start(myurl.host, myurl.port) { |http|\n http.request(req)\n }\n \n res.body # return\n end", "def execute_http_request (method, url, args)\n @http_request = method, url.clone, args.clone\n self.http_response = HTTParty.send method, url, args\n Log.debug \"#{@http_response.request.http_method.to_s.split('::').last.upcase} - URL: #{@http_response.request.last_uri}\"\n Log.debug 'HEADER:'\n Log.debug http_response.request.options[:headers]\n # Log.debug @http_response.request.options[:body] if @http_response.request.options[:body]\n Log.debug 'BODY:' if http_response\n Log.debug http_response if http_response\n http_response\n end", "def read_http(url)\n uri = URI(url)\n Net::HTTP.get_response(uri)\nend", "def read_http(url)\n uri = URI(url)\n Net::HTTP.get_response(uri)\nend", "def send\n http = EM::HttpRequest.new(@uri).post(@request_options)\n\n http.callback do\n process(http.response)\n end\n\n http.errback do\n fail(http.error)\n end\n end", "def fetch\n url = URI.parse(self.class.url)\n req = Net::HTTP::Post.new(url.path)\n req.body = query_builder\n req.content_type = 'application/x-www-form-urlencoded'\n Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }.body\n end", "def get_response!\n HTTParty.send(self.https_method, *self.http_parse_args)\n end", "def request(method, path, body = nil)\n\t #Puppet.debug(\"REAQUEST URL #{method} #{@url} #{path} #{@connect_timeout} #{body}\")\n response = Excon.send(method, @url, :path => path, :headers => web_proxy_headers, :body => body, :connect_timeout => @connect_timeout)\n end", "def restRequest(url)\n printDebugMessage('restRequest', 'Begin', 11)\n printDebugMessage('restRequest', 'url: ' + url, 12)\n # Split URL into components\n uri = URI.parse(url)\n # Get the resource\n userAgent = getUserAgent()\n data = uri.read('User-agent' => userAgent)\n printDebugMessage('restRequest', 'data: ' + data, 21)\n printDebugMessage('restRequest', 'End', 11)\n return data\n end", "def request(kind, url, data, options)\n # options passed as optional parameter show up as an array\n options = options.first if options.kind_of? Array\n query_options = self.class.package_query_params(options)\n full_url = URI.parse(\"#{self.url}#{url}#{query_options}\")\n \n # create an object of the class required to process this method\n klass = Object.module_eval(\"::Net::HTTP::#{kind.to_s.capitalize}\", __FILE__, __LINE__)\n request = klass.new([full_url.path, full_url.query].compact.join('?'))\n request = apply_headers(request)\n # take passed data and encode it\n request.body = self.class.body_encoder(data) if data\n \n http = Net::HTTP.new(full_url.host, full_url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n http.read_timeout = 500\n response = http.start do |web|\n web.request(request)\n end\n return self.class.parse_response(response.code, response.body)\n end", "def raw_data\n @raw_data ||= api_url.open.read\n end", "def do_request(request, response)\n body = make_request(request)\n\n # Always 200. A simplification, but fine for user\n # error messages.\n response.status = 200\n response['Content-Type'] = 'text/html' \n response.body = body\n end", "def call\n request = http_request_class.new(uri.request_uri, headers)\n request.body = body if body\n http = http_setup\n # http.set_debug_output($stdout)\n response = wait_for_completion(HttpResponse.new(http.request(request)))\n Nokogiri::XML response.body unless response.nil?\n end", "def make_request_get_response_trend_availible\n @path_trend_availible = '/1.1/trends/available.json'\n @address_trend_availible = URI(\"#{@baseurl}#{@path_trend_availible}\")\n # Set up HTTP. Need ssL to make the connection\n @request_trend_availible = Net::HTTP::Get.new @address_trend_availible.request_uri\n @http = Net::HTTP.new @address_trend_availible.host, @address_trend_availible.port\n @http.use_ssl = true\n @http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n # Issue the request.\n @request_trend_availible.oauth! @http, @consumer_key_country, @access_token_country\n @http.start\n @response_trend_availible = @http.request @request_trend_availible\n @response_trend_availible\n end", "def make_request(request)\n raw_response = Net::HTTP.start(endpoint_uri.host, endpoint_uri.port) do |http|\n http.request_post(endpoint_uri.path, request.content, request.headers)\n end\n\n response = client.response(request, raw_response.body)\n\n # Sometimes Chrome sends a 500 with a valid SOAP fault in it, sometimes we see a 503 with a html\n # message in the body. In the first case, the above line will raise a LOLSoapFault. If we get\n # here, there was some other HTTP error, so raise that.\n raw_response.value # raises HTTP exception if not a 2xx response\n\n response\n end", "def make_request(url)\n res = Typhoeus::Request.new(\n url,\n method: :get,\n headers: {\n \"Accept-Charset\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"Accept-Language\" => \"en-US,en;q=0.9,pt;q=0.8\",\n \"X-Riot-Token\" => @api_key.to_s,\n \"User-Agent\": \"https://github.com/drish/rioter\"\n }\n ).run\n parse!(res)\n end", "def do_get\n Net::HTTP.get(URI.parse(api_url))\n end", "def raw_response\n @raw_response\n end", "def get_response_from(uri)\n http = Net::HTTP.new(uri.host, uri.port)\n http.read_timeout = http.open_timeout = SimpliTest.config[:settings][\"HTTP_TIMEOUT\"] || 3\n request = Net::HTTP::Get.new(uri.request_uri)\n if uri.scheme == 'https'\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n http.request(request)\n end", "def get_response url, format\r\n begin\r\n response = Net::HTTP.get_response(URI.parse(url))\r\n if format.to_sym == :json\r\n res = JSON.parse response.body\r\n else\r\n res = response.body\r\n end\r\n rescue Exception => e\r\n res = \"ERROR: There is a problem while fetching data, please check whether OpenTSDB is running or not.\"\r\n end\r\n res\r\n end", "def do_request(request, want_reply, data); end", "def get()\n return @http.request(@req)\n end", "def make_request(url,headers,query)\n c = HTTPClient.new\n c.get_content(url,query,headers)\nend", "def proxy\n uri = URI.parse(params[:url])\n open(uri.to_s) do |f|\n # TODO: instead of using f.read below, perhaps read it a bit at a time and\n # stream it a bit at a time. Look into response chunking for Rails.\n data = f.read\n # disposition: :inline means not an attachment -- render right to browser\n send_data data, type: f.content_type, disposition: :inline\n end\n end" ]
[ "0.727657", "0.7268351", "0.72491515", "0.7040075", "0.6970304", "0.6948901", "0.69078064", "0.68542325", "0.68305176", "0.68120384", "0.67594266", "0.6684522", "0.664027", "0.6539485", "0.6530578", "0.651048", "0.6477634", "0.64664763", "0.64615965", "0.645067", "0.643878", "0.64313483", "0.6428939", "0.6409277", "0.63999945", "0.6393074", "0.6380305", "0.63487715", "0.6343853", "0.6343484", "0.63195616", "0.63188785", "0.63088363", "0.6299863", "0.628983", "0.62851036", "0.62643886", "0.6257491", "0.62557274", "0.62538", "0.62447304", "0.624141", "0.62279946", "0.6216089", "0.6211276", "0.62050676", "0.61948764", "0.61933017", "0.6190778", "0.61852384", "0.61834097", "0.61766386", "0.6173528", "0.617219", "0.6164245", "0.6162912", "0.6154101", "0.6153554", "0.61488295", "0.6148506", "0.6146328", "0.6140723", "0.6134444", "0.6122603", "0.6119842", "0.6108502", "0.6105924", "0.61010575", "0.6099318", "0.6093731", "0.609141", "0.608362", "0.6073041", "0.6065814", "0.6062949", "0.60595053", "0.60579586", "0.60514206", "0.6046373", "0.6044944", "0.6044944", "0.60434306", "0.60430974", "0.6035423", "0.6035368", "0.6035033", "0.60348123", "0.602787", "0.6021424", "0.6018879", "0.6015053", "0.60116535", "0.5998691", "0.59965163", "0.59935904", "0.59928113", "0.5987082", "0.5987043", "0.5981855", "0.59775966", "0.59774053" ]
0.0
-1
Convert currency string to ISO symbol
def currency_symbol(currency) case currency when /UAE DIRHAM/ then :AED when /AUSTRALIA/ then :AUD when /BAHRAIN/ then :BHD when /CANADA/ then :CAD when /SWISS/ then :CHF when /DENMARK/ then :DKK when /EURO/ then :EUR when /GB POUND/ then :GBP when /JORDANIAN/ then :JOD when /JAPAN/ then :JPY when /KUWAIT/ then :KWD when /NORWAY/ then :NOK when /OMAN/ then :OMR when /QATARI/ then :QAR when /SAUDI/ then :SAR when /SWEDISH/ then :SEK when /US DOLLAR/ then :USD else fail ResponseError, "Unknown currency #{currency}" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_currency_symbol\n \"€\"\n end", "def currency_as_string; end", "def currency_symbol\n Currency.new(currency).symbol\n end", "def currency_as_string=(val); end", "def currency()\n return \" ש\\\"ח\"\n end", "def currency_as_string\n currency.to_s\n end", "def currency_as_string\n currency.to_s\n end", "def currency_code_to_sign (currency_code)\n if currency_code == :USD\n return \"$\"\n elsif currency_code == :EUR\n return \"€\"\n end\n end", "def currency_symbol\n if self.yard.present?\n self.yard.facility.address.country.currency rescue \"\"\n elsif self.facility.present?\n self.facility.address.country.currency rescue \"\"\n else\n \"\"\n end\n end", "def get_currency_symbol\n self.le_currency.nil? ? \"\" : self.le_currency.display_symbol\n end", "def get_currency_symbol\n self.le_currency.nil? ? \"\" : self.le_currency.display_symbol\n end", "def currency_denoted\n '&#36;'\n end", "def get_currency_name\n \"euro\"\n end", "def currency_as_string=(val)\n @currency = Currency.wrap(val)\n end", "def currency_as_string=(val)\n @currency = Currency.wrap(val)\n end", "def currency_as_string=(val)\n @currency = Currency.wrap(val)\n end", "def currency_as_string=(val)\n @currency = Currency.wrap(val)\n end", "def currency\n 'INR'\n end", "def currency_as_string\n self.currency.to_s\n end", "def currency_as_string\n self.currency.to_s\n end", "def currency_symbol(currency_or_holder)\n currency = currency_or_holder\n if (!currency_or_holder.is_a?(String) &&\n currency_or_holder.respond_to?(:currency))\n currency = currency_or_holder.currency\n end\n case currency\n when 'GBP' then '£'\n when 'EUR' then '€'\n else '$'\n end\n end", "def as_ca_dollar\n exchange_to(\"CAD\")\n end", "def as_ca_dollar\n exchange_to(\"CAD\")\n end", "def as_ca_dollar\n exchange_to(\"CAD\")\n end", "def as_ca_dollar\n exchange_to(\"CAD\")\n end", "def currency\n 'INR'\n end", "def currency_format string\n while string.sub!(/(\\d+)(\\d\\d\\d)/,'\\1,\\2'); end\n string\n end", "def as_euro; end", "def currency\n \"EUR\"\n end", "def to_currency\n reverse.scan(/(?:\\d*\\.)?\\d{1,3}-?/).join(',').reverse\n end", "def currency\n\t\t\"USD\"\n\tend", "def currency\n \"USD\"\n end", "def to_str_currency(amount)\n\n amount_fix = amount * 100\n\n return Money.new(amount_fix, \"CAD\").format\n\n end", "def as_ca_euro\n exchange_to(\"EUR\")\n end", "def replace_invalid_chars(price)\n decimalised = price[/[.]/] ? price : \"0.\" + price \n decimalised.gsub(/[£p]/, '').to_f\nend", "def as_euro\n exchange_to(\"EUR\")\n end", "def as_euro\n exchange_to(\"EUR\")\n end", "def as_euro\n exchange_to(\"EUR\")\n end", "def format_price(price)\n price.gsub!(\"€\",\"\")\n price.gsub!(\".\",\"\")\n price.gsub!(\",\",\".\").to_f\n end", "def symbol currency\n definitions[currency][:symbol]\n end", "def currency_converter amount, location\n case location\n when 'US' then \"$%.2f\" % amount\n when 'Japan' then \"$%.0f\" % amount\n when 'UK' then (\"$%.2f\" % amount).gsub('.', ',')\n end\nend", "def ost_currency_symbol\n if(GlobalConstant::Base.main_sub_environment?)\n \"OST\"\n else\n \"OST-Test\"\n end\n end", "def to_currency_z(val, currency=:usd)\n if currency == :usd\n ApplicationController.helpers.number_with_precision(val,\n precision: 2, separator: '.')\n else\n val\n end\n end", "def to_symbol(string)\n string.gsub(/[\\-_]/, '').to_sym\n end", "def currency\n 'usd'\n end", "def price_symbol\n price ? price.symbol : MoneyRails.default_currency.symbol\n end", "def currency\n return nil unless (extended_currency = read_attribute(:currency))\n encrypt_remove_pre_and_postfix(extended_currency, 'currency', 10)\n end", "def currency\n return nil unless (extended_currency = read_attribute(:currency))\n encrypt_remove_pre_and_postfix(extended_currency, 'currency', 10)\n end", "def itu2iso(number)\n name = country_for(number)\n\n if name.is_a?(String)\n Helpers.country_code_lookup(name)\n elsif name.is_a?(Array)\n name.map do |s|\n Helpers.country_code_lookup(s)\n end\n end\n end", "def to_currency(num)\n format(\"$%.2f\",num)\nend", "def allow_currency_symbols(*args)\n # Obviously US-centric, I need to make it international or customizable.\n # Some international symbols '¢£¥€ƒ$,'\n add_equal_method CURRENCY_CHARS, args \n end", "def çς\n \"±Magnitude\"\n end", "def currency_code\n data.currency_code\n end", "def to_symbol from_string\n return from_string.strip.gsub(\".\", \"_\").to_sym\n end", "def get_USD (num_string)\n if num_string == nil || num_string.to_i == 0\n return num_string\n end\n\n num_string = num_string.to_s.split(\"\")\n\n usd = [\"$\"]\n\n num_string.each_with_index do |num, index|\n if index == ((num_string.length) -1)\n usd << \"#{num}.00\"\n elsif index != 0 && index % 3 == 0\n usd << \",#{num}\"\n else\n usd << num.to_s\n end\n end\n return usd.join(\"\")\n end", "def price_as_string\n price_in_String = \"$\"\n price_in_String += (@price * 100).round.to_s\n price_in_String.insert(-3,\".\")\n return price_in_String\n end", "def formatted_currency(currency)\n format('%<value>.2f', value: currency)\n end", "def iso_code; end", "def iso_code; end", "def ot_currency_code\n end", "def currency_code\n h.e_system_currency\n end", "def to_s\n if SUIT_UNICODE_OK \n return self.unicode\n else\n return self.symbol\n end \n end", "def to_symbol(str)\n case str\n when /'/\n \":'\" + str.to_s.gsub(\"'\"){ \"\\\\'\" } + \"'\"\n else\n ':' + str.to_s\n end\n end", "def number_to_currency(amount)\n super(amount, unit: \"₹\")\n end", "def getAsCurrency(amount, symbol = '£', delimiter = ',')\n amount = amount.to_f\n returnHash = {}\n\n # Set index '1' to color\n if amount < 0\n returnHash[1] = @red\n else\n returnHash[1] = @green\n end\n\n # Set index '0' to formatted amount\n minus = (amount < 0) ? '-' : ''\n amount = '%.2f' % amount.abs\n amount = amount.to_s.reverse.gsub(%r{([0-9]{3}(?=([0-9])))}, \"\\\\1#{delimiter}\").reverse\n returnHash[0] = \"#{minus}#{symbol}#{amount}\"\n returnHash\n end", "def as_us_dollar\n exchange_to(\"USD\")\n end", "def as_us_dollar\n exchange_to(\"USD\")\n end", "def as_us_dollar\n exchange_to(\"USD\")\n end", "def as_us_dollar\n exchange_to(\"USD\")\n end", "def price_as_string\n return sprintf('$%.2f', @price)\n end", "def set_ConvertToCurrency(value)\n set_input(\"ConvertToCurrency\", value)\n end", "def turn_symbol_into_string(symbol)\n symbol.to_s\nend", "def format_money(money)\n money_with_dots = money.reverse.scan(/.{3}|.+/).join(\".\").reverse\n \"$#{money_with_dots}\" \n end", "def standardize_currency(input)\n plurals = @currency_set.keys.map{|key| key.pluralize}\n\n plurals.each do |word|\n input.gsub!(/#{word}/,word.singularize)\n end #standardize to singular word for lookup\n\n input.gsub!(/\\s/,\"\") #standardizes spacing\n input.split(\",\")\n end", "def as_ca_dollar; end", "def price_as_string\n sprintf(\"$%2.2f\", @price)\n end", "def display_currency(amount)\n '$' + ('%.2f' % amount).chomp('.00')\n end", "def parse_currency(currency)\n BigDecimal.new(currency.gsub(/[^0-9.-]/, ''))\n end", "def currency_code\n @currency_code\n end", "def price_as_string()\n @price = '%.2f' % (@price)\n return \"$\"+@price.to_s \n end", "def currency\n params['X-CURRENCY']\n end", "def price_as_string\n \"$\"+format(\"%0.2f\",@price)\n end", "def çς\n \"Magnitude\"\n end", "def pretty_currency_formatted(options={})\n if self == 0.00\n \"free\"\n else\n if options[:no_dollar_sign]\n \"#{self.currency_formatted}\"\n else\n \"$#{self.currency_formatted}\"\n end\n end \n end", "def turn_symbol_into_string(symbol)\n symbol.to_s\nend", "def turn_symbol_into_string(symbol)\n symbol.to_s\nend", "def turn_symbol_into_string(symbol)\n symbol.to_s\nend", "def price_as_string\n\t sprintf(\"$%.2f\",price)\n\n end", "def price_as_string()\n return \"$%0.2f\" %[@price]\n end", "def price_as_string\n sprintf(\"$%.2f\", @price)\n end", "def format_symbol\n\t\t:format\n\tend", "def currency_amount\n # define this elsewhere\n currencymark = '$'\n if self.credit?\n sprintf(\"%s%0.2f\",currencymark,self.amount)\n else\n # put minus sign before dollar\n sprintf(\"-%s%0.2f\", currencymark, self.amount.abs)\n end\n end", "def price_as_string\n return \"$\" + '%.2f' % @price\n end", "def price_as_string \n price_format = 0.0\n price_format = \"$%.2f\" % @price #formatstring\n price_format\n end", "def money_convert(money)\n if money != 0 \n print_mon = money.to_s\n print_mon = \"$#{print_mon.insert -3, \".\"}\"\n else\n print_mon = 0\n end\n end", "def format_country(country)\n return country if country == '' || country == 'Global'\n\n begin\n IsoCountryCodes.find(country).name\n rescue\n # Fallback to raw value\n country\n end\n end", "def price_as_string\n return \"$\"+format(\"%.2f\", @price)\n end", "def price_as_string\n return \"$%0.2f\" % [@price]\n end", "def price_as_string\n output = '%.2f' % price\n \"$\"+output.to_s\nend", "def format\n \"#{amount} #{currency}\"\n end" ]
[ "0.74886477", "0.7350946", "0.70146245", "0.6815757", "0.6814545", "0.67513037", "0.67513037", "0.6680303", "0.65636426", "0.65365803", "0.65365803", "0.64891684", "0.63780355", "0.6372301", "0.6372301", "0.6372301", "0.6372301", "0.63666016", "0.6266222", "0.6266222", "0.6255959", "0.625448", "0.625448", "0.625448", "0.625448", "0.6216613", "0.61779004", "0.61624265", "0.61567", "0.61396056", "0.6097054", "0.6080856", "0.60586995", "0.6047198", "0.6015658", "0.6011166", "0.6011166", "0.6011166", "0.5989113", "0.5985497", "0.5923566", "0.590883", "0.58854616", "0.58605266", "0.5854058", "0.5833136", "0.5798882", "0.5798882", "0.5792657", "0.57820266", "0.5769959", "0.5763814", "0.57542753", "0.57485956", "0.57472795", "0.5728786", "0.57272774", "0.57172614", "0.57172614", "0.5716237", "0.5696036", "0.56924814", "0.5676009", "0.56733084", "0.5643662", "0.5642331", "0.5642331", "0.5642331", "0.5642331", "0.5619368", "0.55830973", "0.55671227", "0.556162", "0.55612445", "0.5553576", "0.55523014", "0.55448693", "0.551492", "0.55129826", "0.5499209", "0.5497744", "0.5494895", "0.5486199", "0.5477156", "0.54757375", "0.54757375", "0.54757375", "0.5463713", "0.54609704", "0.54602075", "0.5447775", "0.54377073", "0.5431583", "0.5423389", "0.54038554", "0.54027563", "0.53922635", "0.53871655", "0.53799427", "0.53777033" ]
0.68355113
3
Validate if the session is active, the user is correct, and that they have permission to stream the derivative based on the session_id and the path to the stream. The values should be put into a POST. The method will reject a GET request for security reasons
def authorize resp = { authorized: StreamToken.validate_token(params[:token]) } if params[:name] and not resp[:authorized].any? { |valid| params[:name].index(valid).present? } return head :forbidden end respond_to do |format| format.urlencoded do resp[:authorized] = resp[:authorized].join(';') render plain: resp.to_query, content_type: :urlencoded, status: :accepted end format.text do render plain: resp[:authorized].join("\n"), status: :accepted end format.xml do render xml: resp, root: :response, status: :accepted end format.json do render json: resp, status: :accepted end end rescue StreamToken::Unauthorized return head :forbidden end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def rc_facebook_check_params_session\n return if rc_facebook.authorized? || !params[:session]\n\n rc_facebook.parse_json!(params[:session])\n logger.debug(\"DEBUG: Facebook: detected session, parsed:\" \\\n \" #{rc_facebook.data.inspect}\")\n\n if rc_facebook.authorized?\n rc_facebook_write_rg_fbs\n else\n logger.warn(\"WARN: Facebook: bad session: #{params[:session]}\")\n end\n end", "def valid?\n utils = Amazon::FPS::SignatureUtilsForOutbound.new(@access_key, @secret_key);\n utils.validate_request(:parameters => @params, :url_end_point => @url_end_point, :http_method => \"GET\")\n end", "def viewer\n authorize @session\n end", "def show\n authorize @video_call\n end", "def user_session_request?(env)\n env.url.to_s.include?('users/v2/session?processRules=true')\n end", "def permitAccess\n\tif session[:id] == nil\n\t\treturn false\n\telse\n\t\treturn true\n\tend\nend", "def restrict_access\n if session[:user_id]\n if !conversation_params.nil?\n conversation_params[:user_id] = session[:user_id]\n end\n else\n authenticate_or_request_with_http_token do |token, options|\n @user = User.where(:auth_token => token).first()\n if (@user)\n if !conversation_params.nil?\n conversation_params[:user_id] = @user.id\n end\n return true\n end\n false\n end\n end\n end", "def valid_session\r\n {}\r\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end", "def valid_session\n {}\n end" ]
[ "0.5843818", "0.5541384", "0.5517537", "0.5426414", "0.54233617", "0.538619", "0.53434867", "0.52863324", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924", "0.52765924" ]
0.0
-1
POST /company_businesses POST /company_businesses.json
def create respond_to do |format| if @company_business.save format.html { redirect_to @company_business, notice: 'Company business was successfully created.' } format.json { render json: @company_business, status: :created, location: @company_business } else format.html { render action: "new" } format.json { render json: @company_business.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_businesses()\n @good_business_records.each do |rec|\n existing_business = @businesses[rec.fields[\"name\"]]\n ## If the business doesn't exist then create it.\n if (existing_business.nil?)\n\tnew_business = Business.new\n\tnew_business.create(rec)\n\t@businesses[new_business.name] = new_business\n ## The business exists so update the updateable fields (arrays)\n else\n\texisting_business.update(rec)\n end\n end\n end", "def create\n @business = @user.businesses.build(business_params)\n\n respond_to do |format|\n if @business.save\n format.html { redirect_to root_path(@user), notice: 'Business was successfully created.' }\n format.json { render :show, status: :created, location: @business }\n else\n format.html { render :new }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @business = current_user.owned_businesses.new(business_params)\n\n respond_to do |format|\n if @business.save\n format.html { redirect_to business_path(@business), notice: 'Business was successfully created.' }\n format.json { render json: @business, status: :created, location: @business }\n else\n format.html { render action: \"new\" }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @businesstype = Businesstype.new(businesstype_params)\n\n respond_to do |format|\n if @businesstype.save\n format.html { redirect_to @businesstype, notice: 'Businesstype was successfully created.' }\n format.json { render :show, status: :created, location: @businesstype }\n else\n format.html { render :new }\n format.json { render json: @businesstype.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @businesses = Business.all\n end", "def index\n @businesses = Business.all\n end", "def index\n @businesses = Business.all\n end", "def submit_business_api_call(date, begin_time, budget, location, itinerary)\n preferences_request_biz = current_user.supplemental_preferences\n designated_preference_biz = preferences_request_biz.sample\n category_request_biz = designated_preference_biz.business_categories.sample\n business_search_term = designated_preference_biz.keywords.sample\n open_date_time = user_input_to_unix(date, begin_time)\n user_budget = convert_to_yelp_budget(budget)\n y = YelpResponse.new\n response = y.get_businesses_response({term: business_search_term, categories: category_request_biz, location: location, price: user_budget, open_at: open_date_time, limit: 20})\n response_container = []\n response_container << response[\"businesses\"].sample\n response_convert_hash = {}\n response_convert_hash[\"businesses\"] = response_container\n handle_businesses_response(response_convert_hash, y, itinerary)\n end", "def create\n @business = Business.new(business_params)\n respond_to do |format|\n if @business.save\n format.html { redirect_to businesses_path, notice: I18n.t('commons.successfully_created') }\n format.json { render json: @business, status: :created, location: @business }\n else\n format.html { render action: \"new\" }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n\t\t@businesses = Business.all\n\tend", "def create\n render json: Company.create(params[\"company\"])\n end", "def index\n @businesses = Business.all.offset(offset).limit(limit)\n render json: @businesses\n end", "def business_json\n @businesses.as_json(only: [:name, :id], include: { industry: { only: [:id, :name] }})\n end", "def create\n @company = Company.new(company_params[:company])\n @companyAuthority = @company.company_authority.new(company_params[:company_authority])\n\n if (!company_params[:lobs].blank?)\n company_params[:lobs].each do |lob|\n @companyAuthority.lob.new(lob)\n end\n end\n\n if @company.save\n render json: @company, status: :created, location: @company\n else\n render json: ErrorSerializer.serialize(@company.errors), status: :unprocessable_entity\n end\n end", "def index\n @user_businesses = Business.where({user_id: current_user.id})\n render json: JSONAPI::Serializer.serialize(@user_businesses, is_collection: true)\n end", "def index\n @businesses = @user.businesses.all\n end", "def create\n @company_branch = CompanyBranch.new(company_branch_params)\n\n respond_to do |format|\n if @company_branch.save\n format.html { redirect_to admin_company_branches_path, notice: 'Company branch was successfully created.' }\n format.json { render :show, status: :created, location: @company_branch }\n else\n format.html { render :new }\n format.json { render json: @company_branch.errors, status: :unprocessable_entity }\n end\n end\n end", "def format_businesses_response(json_data, pagination_data)\n data_hash = JSON.parse(json_data) \n new_hash = { \"businesses\" => data_hash, \"pagination\" => pagination_data }\n new_hash.to_json\n end", "def create\n # business = Business.create(business_params)\n # current_user.businesss << business\n # business = current_user.businesses.create(business_params)\n # redirect_to business_path(business)\n \n business = current_user.businesses.new(business_params)\n if business.save\n flash[:notice] = \"Successfully created business.\"\n redirect_to business_path(business)\n else\n flash[:error] = business.errors.full_messages.join(\", \")\n redirect_to new_business_path\n end\n end", "def create\n @schedule = Schedule.new(params[:schedule])\n @client_branches = ClientBranch.where(:client_id => @schedule.client_id)\n respond_to do |format|\n if @schedule.save\n @schedule.update_attributes(:branch_id => @schedule.client_branch.branch_id, :company_id => @schedule.client_branch.company_id)\n format.html { redirect_to @schedule, notice: 'Schedule was successfully created.' }\n format.json { render json: @schedule, status: :created, location: @schedule }\n else\n format.html { render action: \"new\" }\n format.json { render json: @schedule.errors, status: :unprocessable_entity }\n end\n end\n end", "def post(cnpj, branch, contractId, body)\n self.class.post(\"/aldebaran-carriers/carriers/#{cnpj}/contracts/#{branch}/#{contractId}/regions\", :basic_auth => @auth, :body => body.to_json)\n end", "def create\n @biz_company = BizCompany.new(params[:biz_company])\n\n respond_to do |format|\n if @biz_company.save\n format.html { redirect_to @biz_company, notice: '商业品牌创建成功。' }\n format.json { render json: @biz_company, status: :created, location: @biz_company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @biz_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n u=[session[:customer_id],DateTime.now]\n ud=u.join(\"/\")\n @m=Shop.near(business_params[:address],50,:order=>:distance)\n for n in @m do\n @business = Business.new(business_params)\n @business.status=\"pending\"\n @business.customer_id=session[:customer_id]\n @business.shop_id=n.id\n @business.unique_id=ud\n #respond_to do |format|\n if @business.save\n #redirect_to '/upload'\n #format.html { redirect_to @business, notice: 'Business was successfully created.' }\n #format.json { render :show, status: :created, location: @business }\n else\n #format.html { render :new }\n #format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n redirect_to businesses_url\n end", "def putBusiness( name, building_number, branch_name, address1, address2, address3, district, town, county, province, postcode, country, latitude, longitude, timezone, telephone_number, additional_telephone_number, email, website, category_id, category_type, do_not_display, referrer_url, referrer_name, destructive, delete_mode, master_entity_id)\n params = Hash.new\n params['name'] = name\n params['building_number'] = building_number\n params['branch_name'] = branch_name\n params['address1'] = address1\n params['address2'] = address2\n params['address3'] = address3\n params['district'] = district\n params['town'] = town\n params['county'] = county\n params['province'] = province\n params['postcode'] = postcode\n params['country'] = country\n params['latitude'] = latitude\n params['longitude'] = longitude\n params['timezone'] = timezone\n params['telephone_number'] = telephone_number\n params['additional_telephone_number'] = additional_telephone_number\n params['email'] = email\n params['website'] = website\n params['category_id'] = category_id\n params['category_type'] = category_type\n params['do_not_display'] = do_not_display\n params['referrer_url'] = referrer_url\n params['referrer_name'] = referrer_name\n params['destructive'] = destructive\n params['delete_mode'] = delete_mode\n params['master_entity_id'] = master_entity_id\n return doCurl(\"put\",\"/business\",params)\n end", "def companies\n render \"company/companies.json.jbuilder\", status: :ok\n end", "def create\n @bond = Bond.new(bond_params)\n\n respond_to do |format|\n if @bond.save\n format.html { redirect_to bonds_path, notice: I18n.t('messages.created_with', item: @bond.company) }\n format.json { render :show, status: :created, location: @bond }\n else\n format.html { render :new }\n format.json { render json: @bond.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @business = Business.new(params[:business])\n\n respond_to do |format|\n if @business.save\n format.html { redirect_to action: \"index\"}\n format.json { render json: @business, status: :created, location: @business }\n else\n format.html { render action: \"new\" }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @business = Business.new(business_params)\n @num = 1\n while Business.where([\"business_id = ?\", @num]).size > 0\n @num = @num + 1\n end\n @business.business_id = @num\n @business.user_email = current_user.email\n respond_to do |format|\n if @business.save\n format.html { redirect_to @business, notice: 'Business was successfully created.' }\n format.json { render :show, status: :created, location: @business }\n else\n format.html { render :new }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n if @company = Company.find(entity_id_from_params(:company))\n respond_to do |format|\n current_user.account.companies << @company\n format.html { redirect_to root_path, notice: 'Company was successfully created.' }\n format.json\n end\n end\n end", "def create\n @business = Business.new(business_params)\n respond_to do |format|\n if @business.save\n format.html { redirect_to root_path, notice: 'Business was successfully created.' }\n format.json { render :show, status: :created, location: @business }\n else\n format.html { render :new }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @business = Business.new(business_params)\n\n respond_to do |format|\n if @business.save\n format.html { redirect_to @business, notice: 'Business was successfully created.' }\n format.json { render :show, status: :created, location: @business }\n else\n format.html { render :new }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @businessbook = Businessbook.new(params[:businessbook])\n\n respond_to do |format|\n if @businessbook.save\n format.html { redirect_to @businessbook, :notice => 'Businessbook was successfully created.' }\n format.json { render :json => @businessbook, :status => :created, :location => @businessbook }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @businessbook.errors, :status => :unprocessable_entity }\n end\n end\n end", "def post_businesses_lookup(opts = {})\n data, _status_code, _headers = post_businesses_lookup_with_http_info(opts)\n data\n end", "def create\n begin\n \n detail = @@data_util.hash_data_to_upper_case( params[:company], ['description'])\n\n detail[:mypclient_id] = session[:client_id]\n detail[:createdby] = session[:username]\n detail[:isactive] = 1\n\n @company = Company.new(detail)\n if @company.save\n @@request_result[:success] = true\n @@request_result[:notice] = 'New company successfully created.'\n else\n @@request_result[:errormsg] = @company.errors.full_messages[0]\n end\n rescue Exception => e\n @@request_result[:errormsg] = e.message\n end\n render json: @@request_result\n end", "def index\n @businesses = Business.all\n render :index\n end", "def create\n\n @company = Company.find(1)\n\n @cout = Cout.new(cout_params)\n\n\n @cout[:code] = @cout.generate_cout_number\n @puntos = @company.get_puntos()\n @employees = @company.get_employees2() \n @trucks = @company.get_trucks\n\n respond_to do |format|\n if @cout.save\n format.html { redirect_to @cout, notice: 'Cout was successfully created.' }\n format.json { render :show, status: :created, location: @cout }\n else\n format.html { render :new }\n format.json { render json: @cout.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(params[:company])\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, :notice => 'Company was successfully created.' }\n format.json { render :json => @company, :status => :created, :location => @company }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @company.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @boat = Boat.new(boat_params)\n\n if @boat.save\n render json: @boat, status: :created, location: @boat\n else\n render json: @boat.errors, status: :unprocessable_entity\n end\n end", "def create\n @company = Company.new(params[:company])\n\n respond_to do |format|\n if @company.save\n format.html {\n redirect_to @company, notice: 'Company was successfully created.'\n }\n format.json {\n render json: @company, status: :created, location: @company\n }\n else\n format.html { render action: \"new\" }\n format.json {\n render json: @company.errors, status: :unprocessable_entity\n }\n end\n end\n end", "def create\n\t\t@company = Company.new(params[:company].merge({:by_user_id => current_user.id}))\n\t\tmake_breadcrumbs\n\n\t\trespond_to do |format|\n\t\t\tif @company.save\n\t\t\t\tformat.html { redirect_to @company, notice: t('app.companies.created') }\n\t\t\t\tformat.json { render json: @company, status: :created, location: @company }\n\t\t\telse\n\t\t\t\tformat.html { render action: \"new\" }\n\t\t\t\tformat.json { render json: @company.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def create\n @company = Company.new(params[:company])\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render json: @company, status: :created, location: @company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(params[:company])\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render json: @company, status: :created, location: @company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(params[:company])\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render json: @company, status: :created, location: @company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(params[:company])\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render json: @company, status: :created, location: @company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(params[:company])\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render json: @company, status: :created, location: @company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_new_companies\n params[:new_companies].each do |name|\n c = Company.new\n c.name = CGI.unescape(name)\n c.save\n @movie.production_companies << ProductionCompany.new( :company => c )\n end\n end", "def create\n company = Company.create(company_params)\n if company\n render json:{\n status: :created,\n company: company\n }\n else\n render json: { status: 500 }\n end\n\n \n \n end", "def create\n @rail_company = RailCompany.new(rail_company_params)\n\n respond_to do |format|\n if @rail_company.save\n format.html { redirect_to @rail_company, notice: 'Rail company was successfully created.' }\n format.json { render action: 'show', status: :created, location: @rail_company }\n else\n format.html { render action: 'new' }\n format.json { render json: @rail_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\t\t@business = business.new(business_params)\n\t\trespond_to do |format|\n\t\t\tif @business.save\n\t\t\t\tformat.html { redirect_to @business, notice: 'Business Line was successfully created.' }\n\t\t\t\tformat.json { render action: 'show', status: :created, location @business }\n\t\t\telse\n\t\t\t\tformat.html { render action: \"new\" }\n\t\t\t\tformat.json { render json: @business.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def create\n @company = Company.new(company_params)\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render :show, status: :created, location: @company }\n else\n format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(company_params)\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'company was successfully created.' }\n format.json { render :show, status: :created, location: @company }\n else\n format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(company_params)\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render :show, status: :created, location: @company }\n else\n format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(company_params)\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render :show, status: :created, location: @company }\n else\n format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(company_params)\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render :show, status: :created, location: @company }\n else\n format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(company_params)\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render :show, status: :created, location: @company }\n else\n format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(company_params)\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render :show, status: :created, location: @company }\n else\n format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @industry_branch = IndustryBranch.new(industry_branch_params)\n\n respond_to do |format|\n if @industry_branch.save\n format.html { redirect_to @industry_branch, notice: 'Industry branch was successfully created.' }\n format.json { render :show, status: :created, location: @industry_branch }\n else\n format.html { render :new }\n format.json { render json: @industry_branch.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(params[:company])\n\n if @company.save\n respond_with @company, status: :created, location: @company\n else\n respond_with @company, status: :unprocessable_entity\n end\n end", "def create\n @company = Company.new(company_params)\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render json: @company, status: :created, location: @company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(company_params)\n @data = return_all_details(company_params[:places_id])\n respond_to do |format|\n if @company.save\n @company.update(rating: @data[\"result\"][\"rating\"])\n @company.update(phone_number: @data[\"result\"][\"formatted_phone_number\"])\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render :show, status: :created, location: @company }\n else\n format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @branch = Branch.new branch_params.except(*[:lat, :lng]).merge(coordinates: [branch_params[:lng], branch_params[:lat]])\n @branch.bussiness_id = current_user.bussiness.id\n if @branch.save\n render 'show.json.jbuilder', status: :created\n else\n render json: @branch.errors, status: :bad_request\n end\n end", "def create\n @buisiness = Buisiness.new(buisiness_params)\n\n respond_to do |format|\n if @buisiness.save\n format.html { redirect_to @buisiness, notice: 'Buisiness was successfully created.' }\n format.json { render :show, status: :created, location: @buisiness }\n else\n format.html { render :new }\n format.json { render json: @buisiness.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(company_params)\n respond_to do |format|\n if @company.save\n #format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render :show, status: :created, location: @company }\n else\n #format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\r\n @company = Company.new(params[:company])\r\n respond_to do |format|\r\n if @company.save\r\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\r\n format.json { render json: @company, status: :created, location: @company }\r\n else\r\n format.html { render action: \"new\" }\r\n format.json { render json: @company.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @company_type = CompanyType.new(company_type_params)\n\n if @company_type.save\n render json: @company_type, status: :created, location: @company_type\n else\n render json: @company_type.errors, status: :unprocessable_entity\n end\n end", "def create\n @global_company = GlobalCompany.new(params[:global_company])\n\n respond_to do |format|\n if @global_company.save\n format.html { redirect_to @global_company, notice: 'Global company was successfully created.' }\n format.json { render json: @global_company, status: :created, location: @global_company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @global_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @customerbranch = Customerbranch.new(customerbranch_params.map{|k,v| {k.to_sym => v.class == ActionController::Parameters ? [v.to_hash] : v.to_s}}.reduce({}, :merge))\n\n respond_to do |format|\n if @customerbranch.save\n format.html { redirect_to @customerbranch, notice: 'Customerbranch was successfully created.' }\n format.json { render :show, status: :created, location: @customerbranch }\n else\n format.html { render :new }\n format.json { render json: @customerbranch.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @biz_company = BizCompany.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @biz_company }\n end\n end", "def create\n \n @company = Company.new(params[:company])\n \n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Empresa foi criada com sucesso.' }\n format.json { render json: @company, status: :created, location: @company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @shipping_company = ShippingCompany.new(shipping_company_params)\n\n respond_to do |format|\n if @shipping_company.save\n format.html { redirect_to @shipping_company, notice: 'Shipping company was successfully created.' }\n format.json { render :show, status: :created, location: @shipping_company }\n else\n format.html { render :new }\n format.json { render json: @shipping_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n company = Company.find_by_id(params[:company_id])\n company_logo = company.image_logo\n company_name = company.name \n\n \n @company_order = CompanyOrder.new(company_order_params)\n\n if @company_order.save\n render json: @company_order, status: :created, location: @company_order\n else\n render json: @company_order.errors, status: :unprocessable_entity\n end\n end", "def create\n @business = Business.new(params[:business])\n\n @business.user_id = current_user.id\n @business.label_id = current_label.id\n @business.subscription = sub \n \n if @business.save \n sub.transaction_event.setup_business(@business) \n\n respond_to do |format| \n format.json { render :json => @business.id } \n end \n #redirect_to congratulations_path\n else \n STDERR.puts @business.errors.inspect\n respond_to do |format| \n format.html { render \"new\" } \n format.json { render :json => @business, :status => 400 } \n end \n end \n end", "def index\n @school_businesses = SchoolBusiness.all\n end", "def create\n @company = Company.new(company_params)\n\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render action: 'show', status: :created, location: @company }\n else\n format.html { render action: 'new' }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @busca = Busca.new(busca_params)\n\n respond_to do |format|\n if @busca.save\n format.html { redirect_to @busca, notice: 'Busca was successfully created.' }\n format.json { render :show, status: :created, location: @busca }\n else\n format.html { render :new }\n format.json { render json: @busca.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ins_company = InsCompany.new(params[:ins_company])\n\n respond_to do |format|\n if @ins_company.save\n format.html { redirect_to @ins_company, notice: 'Ins company was successfully created.' }\n format.json { render json: @ins_company, status: :created, location: @ins_company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ins_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def business_params\n params.require(:business).permit(:name, :address, :city)\n end", "def create\n @business_owner = BusinessOwner.new(business_owner_params)\n\n respond_to do |format|\n if @business_owner.save\n format.html { redirect_to @business_owner, notice: 'Business owner was successfully created.' }\n format.json { render :show, status: :created, location: @business_owner }\n else\n format.html { render :new }\n format.json { render json: @business_owner.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_region\n @region = @company.companyregions.new(region_params)\n if @region.save\n render json: @region.as_json, status: :ok\n else\n render json: {region: @region.errors, status: :no_content}\n end\n end", "def create\n @boats_arr = Boat.all\n @new_job = Job.create(\n name: params[:job][:name],\n description: params[:job][:description],\n origin: params[:job][:origin],\n destination: params[:job][:destination],\n cost: params[:job][:cost],\n containers_needed: params[:job][:containers_needed]\n )\n# params for checkbox when creating new job\n params[:boat][:boat_ids].each do |boat_id|\n @id = boat_id.to_i\n @new_job.boats << Boat.find(@id)\n end\n\n\n if @new_job\n redirect_to url_for(:controller => :jobs, :action => :index)\n else\n redirect_to url_for(:controller => :jobs, :action => :new)\n end\n\n\n end", "def create\n @company = Company.new(params[:company])\n #@battalion = Battalion.find(params[:battalion_id])\n respond_to do |format|\n if @company.save\n flash[:notice] = 'Company was successfully created.'\n format.html { redirect_to :back }\n format.xml { render :xml => @company, :status => :created, :location => @company }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @company.errors, :status => :unprocessable_entity }\n end\n end\n end", "def business_params\n params.require(:business).permit(:name, :user_id, :password, :password_confirmation,\n user_businesses_attributes:[ :user_id, :business_id])\n end", "def create\n @business_area = BusinessArea.new(params[:business_area].permit(:name, :director))\n\n respond_to do |format|\n if @business_area.save\n format.html { redirect_to @business_area, notice: 'Business Area was successfully created.' }\n format.json { render :show, status: :created, location: @business_area }\n else\n format.html { render :new }\n format.json { render json: @business_area.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\t\tboat = Boat.new(boat_params)\n \tif boat.save\n \t\trender json: boat, status: 201\n \tend\n\tend", "def create\n @company = Company.new(company_params)\n respond_to do |format|\n if @company.save\n @company.visit.each do |visit|\n @visit = Visit.new(visit.attributes)\n @visit.companyId=@company.id\n daysFromNow = Frecuency.find(visit.frecuencyTypeId).days\n nextVisitDate = visit.visitDate + daysFromNow.day\n while nextVisitDate < (Date.today + 365.day)\n @nextVisit = Visit.new(visit.attributes)\n @nextVisit.visitDate = nextVisitDate\n @nextVisit.id = nil\n @nextVisit.companyId=@company.id\n @nextVisit.save\n nextVisitDate = nextVisitDate + daysFromNow.day\n end\n end\n if @company.save\n @company.expiration.each do |expiration|\n @expiration = Expiration.new(expiration.attributes)\n @expiration.companyId=@company.id\n end\n end\n format.html { redirect_to @company, notice: 'Cliente creado con exito' }\n format.json { render :show, status: :created, location: @company }\n else\n format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @account_company = Account::Company.new(account_company_params)\n\n respond_to do |format|\n if @account_company.save\n format.html { redirect_to @account_company, notice: 'Company was successfully created.' }\n format.json { render :show, status: :created, location: @account_company }\n else\n format.html { render :new }\n format.json { render json: @account_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(nested_params)\n respond_to do |format|\n if @company.save\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render :show, status: :created, location: @company }\n else\n format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @branch = Branch.create(branch_params)\n if @branch.valid?\n render json: @branch, status: :accepted\n else\n render json: {errors: @branch.errors.full_messages}, status: :unprocessable_entity \n end\n end", "def create\n @business_sector = BusinessSector.new(params[:business_sector])\n\n respond_to do |format|\n if @business_sector.save\n format.html { redirect_to @business_sector, notice: 'Business sector was successfully created.' }\n format.json { render json: @business_sector, status: :created, location: @business_sector }\n else\n format.html { render action: \"new\" }\n format.json { render json: @business_sector.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n event = Event.find(params[:event_id])\n @bus = event.buses.build(bus_params)\n respond_to do |format|\n if @bus.save\n format.html { redirect_to event_path(@bus.event), notice: 'Bus was successfully created.' }\n format.json { render :show, status: :created, location: @bus }\n else\n format.html { render :new }\n format.json { render json: @bus.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stationary_batteries_battery_bank = StationaryBatteriesBatteryBank.new(stationary_batteries_battery_bank_params)\n\n respond_to do |format|\n if @stationary_batteries_battery_bank.save\n format.html { redirect_to @stationary_batteries_battery_bank, notice: 'Stationary batteries battery bank was successfully created.' }\n format.json { render :show, status: :created, location: @stationary_batteries_battery_bank }\n else\n format.html { render :new }\n format.json { render json: @stationary_batteries_battery_bank.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @production_company = ProductionCompany.new(production_company_params)\n\n respond_to do |format|\n if @production_company.save\n format.html { redirect_to @production_company, notice: 'Production company was successfully created.' }\n format.json { render :show, status: :created, location: @production_company }\n else\n format.html { render :new }\n format.json { render json: @production_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @boc = Boc.new(boc_params)\n\n respond_to do |format|\n if @boc.save\n format.html { redirect_to new_boc_path, notice: 'Boc was successfully created.' }\n format.json { render :show, status: :created, location: @boc }\n else\n format.html { render :new }\n format.json { render json: @boc.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n begin\n @busgroup = Busgroup.new\n @busgroup.mypclient_id = session[:client_id]\n @busgroup.busgroupcode = params[:group_code].strip.upcase\n @busgroup.description = params[:description].strip\n @busgroup.isactive = 1\n @busgroup.createdby = session[:username]\n\n if @busgroup.save \n @@request_result[:success] = true\n @@request_result[:notice] = 'Business Group successfully created.'\n else\n @@request_result[:errormsg] = @busgroup.errors.full_messages[0]\n end\n rescue Exception => e\n @@request_result[:errormsg] = e.message\n end\n render json: @@request_result\n end", "def create\n @businessline = Businessline.new(businessline_params)\n\n respond_to do |format|\n if @businessline.save\n format.html { redirect_to @businessline, notice: 'Businessline was successfully created.' }\n format.json { render :show, status: :created, location: @businessline }\n else\n format.html { render :new }\n format.json { render json: @businessline.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @company = companies_scope.new\n @company.build_location\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @company }\n end\n end", "def create\n params[:company][:founded_on] = params[:company][:founded_on].blank? ? Date.today : params[:company][:founded_on].to_date\n @company = Company.new(company_params)\n\n respond_to do |format|\n if @company.save\n response_hash = @company.get_company_detail\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json {render json: {message: response_hash}, status: 200}\n else\n format.html { render :new }\n error = @company.errors.keys[0].to_s.capitalize+\" \"+@company.errors.values[0][0].to_s\n format.json { render json: {message: error}, status: 400 }\n end\n end\n end", "def create\n #@news_company = NewsCompany.new(params[:news_company])\n @news_companies = params[:news_companies].values.collect { |news_company| NewsCompany.new(news_company) }\n\n @news_companies.each do |news_company|\n if news_company.company_id!=0\n news_company.save!\n end\n end\n\n\n respond_to do |format|\n if @news_companies.all?(&:valid?)\n format.html { redirect_to news_path(News.find(@news_companies[0].news_id)), notice: 'News company was successfully created.' }\n format.json { render json: @news_company, status: :created, location: @news_company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @news_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def business_params\n params.require(:business).permit(:name, :business_id, :address, :city, :state, :postal_code, :phone_number)\n end", "def create\n business_category_params[\"business_centerable_type\"] = business_category_params[\"business_centerable_id\"].split(';').first\n business_category_params[\"business_centerable_id\"] = business_category_params[\"business_centerable_id\"].split(';').last\n @business_category = BusinessCategory.new(business_category_params)\n\n respond_to do |format|\n if @business_category.save\n format.html { redirect_to @business_category, notice: 'Business category was successfully created.' }\n format.json { render :show, status: :created, location: @business_category }\n else\n format.html { render :new }\n format.json { render json: @business_category.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.68930036", "0.65929097", "0.6588629", "0.62476134", "0.6207495", "0.6207495", "0.6207495", "0.61460567", "0.61074334", "0.60978484", "0.6089459", "0.6083822", "0.6080458", "0.6065163", "0.60603803", "0.6004575", "0.5987673", "0.59868383", "0.59698814", "0.59531635", "0.58861035", "0.5885822", "0.5882972", "0.5872517", "0.58701265", "0.5860515", "0.58171254", "0.5800008", "0.5774703", "0.57473767", "0.57472146", "0.57424647", "0.57362634", "0.57333964", "0.5732418", "0.57320666", "0.5717141", "0.56994915", "0.56972855", "0.5690872", "0.5689415", "0.56892234", "0.56892234", "0.56892234", "0.56892234", "0.56884396", "0.56834865", "0.5680292", "0.5672903", "0.5650456", "0.564921", "0.56490016", "0.56490016", "0.56490016", "0.56490016", "0.56490016", "0.5646202", "0.56369466", "0.56362045", "0.5607477", "0.56015766", "0.55985373", "0.5596538", "0.5593258", "0.55929756", "0.55899835", "0.5587918", "0.55814767", "0.55792", "0.55790645", "0.5574045", "0.5568639", "0.5564649", "0.5563869", "0.55550486", "0.55499214", "0.55472344", "0.5542332", "0.551252", "0.5511167", "0.55108577", "0.5509933", "0.5499942", "0.5493013", "0.54929495", "0.5491001", "0.5480865", "0.5477657", "0.54701436", "0.5467361", "0.54621464", "0.54609877", "0.54581326", "0.5448548", "0.5441001", "0.5433618", "0.54297453", "0.5428218", "0.54274946", "0.54270154" ]
0.62538105
3
PUT /company_businesses/1 PUT /company_businesses/1.json
def update respond_to do |format| if @company_business.update_attributes(params[:company_business]) format.html { redirect_to @company_business, notice: 'Company business was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @company_business.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n render json: Company.update(params[\"id\"], params[\"company\"])\n end", "def putBusiness( name, building_number, branch_name, address1, address2, address3, district, town, county, province, postcode, country, latitude, longitude, timezone, telephone_number, additional_telephone_number, email, website, category_id, category_type, do_not_display, referrer_url, referrer_name, destructive, delete_mode, master_entity_id)\n params = Hash.new\n params['name'] = name\n params['building_number'] = building_number\n params['branch_name'] = branch_name\n params['address1'] = address1\n params['address2'] = address2\n params['address3'] = address3\n params['district'] = district\n params['town'] = town\n params['county'] = county\n params['province'] = province\n params['postcode'] = postcode\n params['country'] = country\n params['latitude'] = latitude\n params['longitude'] = longitude\n params['timezone'] = timezone\n params['telephone_number'] = telephone_number\n params['additional_telephone_number'] = additional_telephone_number\n params['email'] = email\n params['website'] = website\n params['category_id'] = category_id\n params['category_type'] = category_type\n params['do_not_display'] = do_not_display\n params['referrer_url'] = referrer_url\n params['referrer_name'] = referrer_name\n params['destructive'] = destructive\n params['delete_mode'] = delete_mode\n params['master_entity_id'] = master_entity_id\n return doCurl(\"put\",\"/business\",params)\n end", "def update\n @business = @user.businesses.find(params[:id])\n respond_to do |format|\n if @business.update(business_params)\n format.html { redirect_to edit_user_business_path(@user, @business), notice: 'Business was successfully updated.' }\n format.json { render :show, status: :ok, location: @business }\n else\n format.html { render :edit }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @company = Company.find(company_params[:id])\n\n if @company.update(company_params)\n head :no_content\n else\n render json: @company.errors, status: :unprocessable_entity\n end\n end", "def update_companies\n current_companies = @movie.companies.collect { |c| c.id.to_s }\n\n delete_production_companies( current_companies )\n add_production_companies( current_companies ) unless params[:companies].nil?\n create_new_companies unless params[:new_companies].nil?\n end", "def set_business_company\n @business_company = Business::Company.find(params[:id])\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.json { render :show, status: :ok, location: @company }\n else\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @businesstype = Businesstype.find(params[:id])\n\n respond_to do |format|\n if @businesstype.update_attributes(params[:businesstype])\n format.html { redirect_to @businesstype, notice: 'Businesstype was successfully updated.' }\n format.json { render :show, status: :ok, location: @businesstype }\n else\n format.html { render :edit }\n format.json { render json: @businesstype.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @biz_company = BizCompany.find(params[:id])\n\n respond_to do |format|\n if @biz_company.update_attributes(params[:biz_company])\n format.html { redirect_to @biz_company, notice: '商业品牌更新成功。' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @biz_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @schedule = Schedule.new(params[:schedule])\n @client_branches = ClientBranch.where(:client_id => @schedule.client_id)\n respond_to do |format|\n if @schedule.save\n @schedule.update_attributes(:branch_id => @schedule.client_branch.branch_id, :company_id => @schedule.client_branch.company_id)\n format.html { redirect_to @schedule, notice: 'Schedule was successfully created.' }\n format.json { render json: @schedule, status: :created, location: @schedule }\n else\n format.html { render action: \"new\" }\n format.json { render json: @schedule.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @company = Company.find(params[:id])\n\n if @company.update_attributes(params[:company])\n respond_with @company\n else\n respond_with @company, status: :unprocessable_entity\n end\n end", "def update\n @target_company.update(target_company_params)\n @target_company = TargetCompany.new\n @target_companies = TargetCompany.all\n\n end", "def update\n @company = Company.find(params[:id])\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to companies_path, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def create\n @company = Company.new(company_params)\n @data = return_all_details(company_params[:places_id])\n respond_to do |format|\n if @company.save\n @company.update(rating: @data[\"result\"][\"rating\"])\n @company.update(phone_number: @data[\"result\"][\"formatted_phone_number\"])\n format.html { redirect_to @company, notice: 'Company was successfully created.' }\n format.json { render :show, status: :created, location: @company }\n else\n format.html { render :new }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @bond.update(bond_params)\n format.html { redirect_to bonds_path, notice: I18n.t('messages.updated_with', item: @bond.company) }\n format.json { render :show, status: :ok, location: @bond }\n else\n format.html { render :edit }\n format.json { render json: @bond.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @company = Company.find(params[:id])\n Rails.logger.info \"******\\n\\n\\nCompany: #{params[:company]}***********\\n\\n\\n\"\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @companies = Company.all\n respond_to do |format|\n if @house.update(house_params)\n format.html { redirect_to @house, notice: 'House was successfully updated.' }\n format.json { render :show, status: :ok, location: @house }\n else\n format.html { render :edit }\n format.json { render json: @house.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_businesses()\n @good_business_records.each do |rec|\n existing_business = @businesses[rec.fields[\"name\"]]\n ## If the business doesn't exist then create it.\n if (existing_business.nil?)\n\tnew_business = Business.new\n\tnew_business.create(rec)\n\t@businesses[new_business.name] = new_business\n ## The business exists so update the updateable fields (arrays)\n else\n\texisting_business.update(rec)\n end\n end\n end", "def update\n @data = return_all_details(company_params[:places_id])\n respond_to do |format|\n if @company.update(company_params)\n @company.update(rating: @data[\"result\"][\"rating\"])\n @company.update(phone_number: @data[\"result\"][\"formatted_phone_number\"])\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n begin\n @company = Company.find(params[:id])\n detail = @@data_util.hash_data_to_upper_case(params[:company], ['description'])\n detail[:lastupdateby] = session[:username]\n\n @@request_result[:data] = detail \n @@request_result[:type] = params[:company].class \n if @company.update_attributes(detail)\n @@request_result[:success] = true\n @@request_result[:notice] = 'Company successfully updated.'\n else\n @@request_result[:errormsg] = @company.errors.full_messages[0]\n end\n rescue Exception => e\n @@request_result[:errormsg] = e.message\n end\n render json: @@request_result\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n #format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n #format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\t\t@company = Company.find(params[:id])\n\t\tmake_breadcrumbs\n\n\t\trespond_to do |format|\n\t\t\tif @company.update_attributes(params[:company])\n\t\t\t\tformat.html { redirect_to @company, notice: t('app.companies.updated') }\n\t\t\t\tformat.json { head :ok }\n\t\t\telse\n\t\t\t\tformat.html { render action: \"edit\" }\n\t\t\t\tformat.json { render json: @company.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def update\n @company = Company.find(params[:id])\n\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html {\n redirect_to @company, notice: 'Company was successfully updated.'\n }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json {\n render json: @company.errors, status: :unprocessable_entity\n }\n end\n end\n end", "def update\n @company = Company.find(params[:id])\n\n @company.infos.each do |i|\n\t i.value = params[i.key]\n\t i.save\n end\n\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html { redirect_to @company, notice: 'Company successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html { redirect_to companies_url, notice: @company.name + ' was successfully created.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @company = Company.update(company_params)\n # $redis.publish('companies.update', @company.to_json)\n # render :action => 'show'\n end", "def set_api_v1_company\n @api_v1_company = Api::V1::Company.find(params[:id])\n end", "def test_update_company()\n # Parameters for the API call\n\n campaign_model = CampaignModel.new()\n campaign_model.utm_source = \"Adwords\"\n campaign_model.utm_medium = \"Twitter\"\n\n company_model = CompanyModel.new()\n company_model.modified_time = Time.now.utc.iso8601\n company_model.company_id = \"12345\"\n company_model.campaign = campaign_model\n\n # Perform the API call through the SDK function\n self.class.controller.update_company(company_model)\n\n # Test response code\n assert_equal(@response_catcher.response.status_code, 201)\n end", "def update\n @company = Company.find(params[:id])\n\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @company = Company.find(params[:id])\n\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @company = Company.find(params[:id])\n\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @company = Company.find(params[:id])\n\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @company = Company.find(params[:id])\n\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @company = Company.find(params[:id])\n\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @company = Company.find(params[:id])\n\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html { redirect_to @company, :notice => 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @company.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n @company = Company.find(1)\n @puntos = @company.get_puntos()\n @employees = @company.get_employees2() \n@trucks = @company.get_trucks\n\n respond_to do |format|\n if @cout.update(cout_params)\n format.html { redirect_to @cout, notice: 'Cout was successfully updated.' }\n format.json { render :show, status: :ok, location: @cout }\n else\n format.html { render :edit }\n format.json { render json: @cout.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @client_company.update(company_params)\n format.html {redirect_to @client_company, notice: 'Company was successfully updated.'}\n format.json {render :show, status: :ok, location: @client_company}\n else\n format.html {render :edit}\n format.json {render json: @client_company.errors, status: :unprocessable_entity}\n end\n end\n end", "def update\n respond_to do |format|\n if @company_branch.update(company_branch_params)\n format.html { redirect_to admin_company_branches_path, notice: 'Company branch was successfully updated.' }\n format.json { render :show, status: :ok, location: @company_branch }\n else\n format.html { render :edit }\n format.json { render json: @company_branch.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @company = Company.new(company_params[:company])\n @companyAuthority = @company.company_authority.new(company_params[:company_authority])\n\n if (!company_params[:lobs].blank?)\n company_params[:lobs].each do |lob|\n @companyAuthority.lob.new(lob)\n end\n end\n\n if @company.save\n render json: @company, status: :created, location: @company\n else\n render json: ErrorSerializer.serialize(@company.errors), status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render action: 'show', status: :ok, location: @company }\n else\n format.html { render action: 'edit' }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_company\n @client_company = ClientCompany.find(params[:id])\n end", "def update\n @business = Business.find(params[:id])\n\n respond_to do |format|\n if @business.update_attributes(business_params)\n format.html { redirect_to businesses_path, notice: I18n.t('commons.successfully_updated') }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n @company = Company.find(params[:id])\r\n \r\n respond_to do |format|\r\n if @company.update_attributes(params[:company])\r\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\r\n format.json { head :no_content }\r\n else\r\n format.html { render action: \"edit\" }\r\n format.json { render json: @company.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n @company = Company.find(id_from_params)\n\n respond_to do |format|\n if @company.accounts.exists? current_user.account.id\n @company.accounts.delete(current_user.account)\n @company.accounts << current_user.account\n\n format.html { redirect_to root_path, notice: 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n @company.accounts << current_user.account\n format.html { redirect_to root_path, notice: 'Company was successfully updated.' }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_company_branch\n @company_branch = CompanyBranch.find(params[:id])\n end", "def update\n respond_to do |format|\n if @hiring_company.update(hiring_company_params)\n format.html { redirect_to @hiring_company, notice: 'Hiring company was successfully updated.' }\n format.json { render :show, status: :ok, location: @hiring_company }\n else\n format.html { render :edit }\n format.json { render json: @hiring_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @company = Company.find(COMPANY_ID)\n\n respond_to do |format|\n if @company.update_attributes(params[:company])\n format.html { redirect_to administration_company_path(@company), notice: 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def put_businesses_token_with_http_info(token, body, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: BusinessesApi.put_businesses_token ...'\n end\n # verify the required parameter 'token' is set\n if @api_client.config.client_side_validation && token.nil?\n fail ArgumentError, \"Missing the required parameter 'token' when calling BusinessesApi.put_businesses_token\"\n end\n # verify the required parameter 'body' is set\n if @api_client.config.client_side_validation && body.nil?\n fail ArgumentError, \"Missing the required parameter 'body' when calling BusinessesApi.put_businesses_token\"\n end\n # resource path\n local_var_path = '/businesses/{token}'.sub('{' + 'token' + '}', CGI.escape(token.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body] || @api_client.object_to_http_body(body)\n\n # return_type\n return_type = opts[:debug_return_type] || 'BusinessCardholder'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || []\n\n new_options = opts.merge(\n :operation => :\"BusinessesApi.put_businesses_token\",\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:PUT, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: BusinessesApi#put_businesses_token\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def update\n @company_type = CompanyType.find(params[:id])\n\n if @company_type.update(company_type_params)\n head :no_content\n else\n render json: @company_type.errors, status: :unprocessable_entity\n end\n end", "def update\n @ins_company = InsCompany.find(params[:id])\n\n respond_to do |format|\n if @ins_company.update_attributes(params[:ins_company])\n format.html { redirect_to @ins_company, notice: 'Ins company was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ins_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @business.update(business_params)\n format.html { redirect_to businesses_path, notice: 'Business was successfully updated.' }\n format.json { render :index, status: :ok }\n else\n format.html { render :edit }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end", "def companies\n render \"company/companies.json.jbuilder\", status: :ok\n end", "def update\n @global_company = GlobalCompany.find(params[:id])\n\n respond_to do |format|\n if @global_company.update_attributes(params[:global_company])\n format.html { redirect_to @global_company, notice: 'Global company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @global_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @bus.update(bus_params)\n format.html { redirect_to bus_owners_bus_path(@bus), notice: 'Bus was successfully updated.' }\n format.json { render :show, status: :ok, location: @bus }\n else\n format.html { render :edit }\n format.json { render json: @bus.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n render json: Company.create(params[\"company\"])\n end", "def update\n @company = Company.friendly.find(params[:id])\n\n @company.companytype_id = params[:companytype_id]\n\n\n\n respond_to do |format|\n\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: t(\"updated\") }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_company\n id = params[:company_id] ? params[:company_id] : params[:id]\n @company = Company.find(id)\n end", "def set_company\n if /^0*[1-9]\\d*$/.match(params[:id])\n find_company\n else\n render json: { description: \"Invalid ID supplied\", code: 400 }\n end\n end", "def create\n if @company = Company.find(entity_id_from_params(:company))\n respond_to do |format|\n current_user.account.companies << @company\n format.html { redirect_to root_path, notice: 'Company was successfully created.' }\n format.json\n end\n end\n end", "def update\n @company = Company.find(params[:id])\n @battalion = Battalion.find(params[:battalion_id])\n respond_to do |format|\n if @company.update_attributes(params[:company])\n flash[:notice] = 'Company was successfully updated.'\n format.html { redirect_to battalion_company_path(@battalion, @company) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @company.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @business = current_user.owned_businesses.new(business_params)\n\n respond_to do |format|\n if @business.save\n format.html { redirect_to business_path(@business), notice: 'Business was successfully created.' }\n format.json { render json: @business, status: :created, location: @business }\n else\n format.html { render action: \"new\" }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end", "def putBusinessJson( json, country, timezone, master_entity_id, queue_priority)\n params = Hash.new\n params['json'] = json\n params['country'] = country\n params['timezone'] = timezone\n params['master_entity_id'] = master_entity_id\n params['queue_priority'] = queue_priority\n return doCurl(\"put\",\"/business/json\",params)\n end", "def update\n respond_to do |format|\n if @shipping_company.update(shipping_company_params)\n format.html { redirect_to @shipping_company, notice: 'Shipping company was successfully updated.' }\n format.json { render :show, status: :ok, location: @shipping_company }\n else\n format.html { render :edit }\n format.json { render json: @shipping_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @crunch_company = CrunchCompany.find(params[:id])\n @fetch_crunch = Crunchbase::Company.get(@crunch_company.company_name)\n @fetch_crunch_posts = @fetch_crunch.ipo\n\n respond_to do |format|\n if @crunch_company.update_attributes(params[:crunch_company])\n @crunch_company.update_attribute(:posts, @fetch_crunch_posts)\n format.html { redirect_to @crunch_company, notice: 'Crunch company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @crunch_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html {redirect_to @company, notice: 'Company was successfully updated.'}\n format.json {render :show, status: :ok, location: @company}\n else\n format.html {render :edit}\n format.json {render json: @company.errors, status: :unprocessable_entity}\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html {redirect_to action: :index, notice: 'Company was successfully updated.'}\n format.json {render :show, status: :ok, location: @company}\n else\n format.html {render :edit}\n format.json {render json: @company.errors, status: :unprocessable_entity}\n end\n end\n end", "def destroy\n @company_business.destroy\n\n respond_to do |format|\n format.html { redirect_to company_businesses_url }\n format.json { head :no_content }\n end\n end", "def update\n @events_company = EventsCompany.find(params[:id])\n\n respond_to do |format|\n if @events_company.update_attributes(params[:events_company])\n format.html { redirect_to @events_company, :notice => 'Events company was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @events_company.errors, :event => :unprocessable_entity }\n end\n end\n end", "def crunch\n @crunch_company = CrunchCompany.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @crunch_company }\n end\n @fetch_crunch = Crunchbase::Company.get(@crunch_company.company_name)\n # @fetch_crunch_posts_call = Crunchbase::Posts.get(@crunch_company.company_name)\n # @fetch_crunch_posts = @fetch_crunch[\"num_posts\"]\n @fetch_crunch_ipo_year = @fetch_crunch.ipo[\"pub_year\"]\n @fetch_crunch_ipo_valuation = @fetch_crunch.ipo[\"valuation_amount\"]\n @fetch_crunch_ipo_ticker = @fetch_crunch.ipo[\"stock_symbol\"]\n\n respond_to do |format|\n if @crunch_company.save\n @crunch_company.update_attribute(:ipo_year, @fetch_crunch_ipo_year)\n @crunch_company.update_attribute(:ipo_valuation, @fetch_crunch_ipo_valuation)\n @crunch_company.update_attribute(:ipo_ticker, @fetch_crunch_ipo_ticker)\n @crunch_company.update_attribute(:posts, @fetch_crunch_posts)\n format.html { redirect_to @crunch_company, notice: 'Crunch company was successfully created.' }\n format.json { render json: @crunch_company, status: :created, location: @crunch_company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @crunch_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @companies = Array.new\n Company.all.each do |comp|\n @companies << [comp.name, comp.id]\n end\n @project.name = @project.name.upcase\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Proyecto actualizado exitosamente.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Configurações da empresa alteradas com sucesso!' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company_vacancy.update(company_vacancy_params)\n format.html { redirect_to @company_vacancy, notice: 'Company vacancy was successfully updated.' }\n format.json { render :show, status: :ok, location: @company_vacancy }\n else\n format.html { render :edit }\n format.json { render json: @company_vacancy.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_company\n @company = Company.find(params[:company])\n end", "def create\n\n respond_to do |format|\n if @company_business.save\n format.html { redirect_to @company_business, notice: 'Company business was successfully created.' }\n format.json { render json: @company_business, status: :created, location: @company_business }\n else\n format.html { render action: \"new\" }\n format.json { render json: @company_business.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @biz_company = BizCompany.new(params[:biz_company])\n\n respond_to do |format|\n if @biz_company.save\n format.html { redirect_to @biz_company, notice: '商业品牌创建成功。' }\n format.json { render json: @biz_company, status: :created, location: @biz_company }\n else\n format.html { render action: \"new\" }\n format.json { render json: @biz_company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\t\trespond_to do |format|\n\t\t\tif @business.update(business_params)\n\t\t\t\tformat.html { redirect_to @business, notice: 'Business Line was successfully updated.' }\n\t\t\t\tformat.json { render json: @business.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def update\n @company = Company.find(params[:id])\n respond_to do |format|\n if @company.update!(nested_params)\n format.html { redirect_to @company, notice: \"#{@company.name} Company has been updated.\" }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to companies_path, notice: 'Общая информация о компании успешно отредактирована' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Bar atualizado com sucesso.' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\t\t@company = Company.find(params[:id])\n\t\t@company.update(company_params)\n\t\tredirect_to company_path(@company)\n\tend", "def update\n respond_to do |format|\n if @company.update(company_params)\n format.html { redirect_to @company, notice: 'Cliente actualizado con exito' }\n format.json { render :show, status: :ok, location: @company }\n else\n format.html { render :edit }\n format.json { render json: @company.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @company.update(company_params)\n redirect_to @company, notice: \"Company was successfully updated.\"\n else\n render :edit, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @visit_company.update(visit_company_params)\n format.html { redirect_to @visit_company, notice: 'Visit company was successfully updated.' }\n format.json { render :show, status: :ok, location: @visit_company }\n else\n format.html { render :edit }\n format.json { render json: @visit_company.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.6704675", "0.6606723", "0.6140297", "0.61236435", "0.6117336", "0.6115292", "0.6087208", "0.6046817", "0.60376763", "0.6005924", "0.6003887", "0.5985254", "0.59735674", "0.5939711", "0.5933765", "0.5911271", "0.58980525", "0.5846838", "0.5843454", "0.583731", "0.5835817", "0.5813439", "0.581299", "0.58117145", "0.58097035", "0.58062476", "0.58062476", "0.58062476", "0.58062476", "0.58062476", "0.58062476", "0.58062476", "0.58062476", "0.58062476", "0.58062476", "0.58062476", "0.58062476", "0.5802723", "0.580008", "0.5799321", "0.5797158", "0.5792739", "0.5792739", "0.5792739", "0.5792739", "0.5792739", "0.5792739", "0.57865804", "0.57728946", "0.5772531", "0.57662535", "0.5760291", "0.57587034", "0.5755509", "0.57393676", "0.57372564", "0.5726471", "0.5716582", "0.5708224", "0.57053065", "0.5699698", "0.5696801", "0.5695066", "0.56926537", "0.569192", "0.5688135", "0.5680612", "0.56744653", "0.5669543", "0.566797", "0.56601566", "0.5655474", "0.56508875", "0.5649014", "0.5640939", "0.5639405", "0.5639405", "0.5639181", "0.5635692", "0.56310004", "0.5624537", "0.5616722", "0.5609505", "0.56084293", "0.56008106", "0.56003547", "0.55999744", "0.5598742", "0.55976444", "0.55938107", "0.5590455", "0.5574936", "0.55630976", "0.55629754", "0.55604315", "0.5559067", "0.5548581", "0.55471116", "0.5544835", "0.5541588" ]
0.6234021
2
DELETE /company_businesses/1 DELETE /company_businesses/1.json
def destroy @company_business.destroy respond_to do |format| format.html { redirect_to company_businesses_url } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def delete\n render json: Company.delete(params[\"id\"])\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @biz_company = BizCompany.find(params[:id])\n @biz_company.destroy\n\n respond_to do |format|\n format.html { redirect_to biz_companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @business_company.destroy\n respond_to do |format|\n format.html { redirect_to business_companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @crunch_company = CrunchCompany.find(params[:id])\n @crunch_company.destroy\n\n respond_to do |format|\n format.html { redirect_to crunch_companies_url }\n format.json { head :no_content }\n end\n end", "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def destroy\n @rail_company.destroy\n respond_to do |format|\n format.html { redirect_to rail_companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @business = Business.find(params[:id])\n @business.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_businesses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @business = @user.businesses.find(params[:id])\n \n @business.destroy\n respond_to do |format|\n format.html { redirect_to root_path(@user), notice: 'Business was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @business = current_user.owned_businesses.find(params[:id])\n @business.destroy\n\n respond_to do |format|\n format.html { redirect_to businesses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @business = Business.find(params[:id])\n @business.destroy\n\n respond_to do |format|\n format.html { redirect_to businesses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @global_company = GlobalCompany.find(params[:id])\n @global_company.destroy\n\n respond_to do |format|\n format.html { redirect_to global_companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @company = Company.find(params[:id])\r\n @company.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to companies_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n #@company = Company.find_by_slug(params[:id])\n @company.destroy\n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ins_company = InsCompany.find(params[:id])\n @ins_company.destroy\n\n respond_to do |format|\n format.html { redirect_to ins_companies_url }\n format.json { head :ok }\n end\n end", "def destroy\n @guarantee_company.destroy\n respond_to do |format|\n format.html { redirect_to guarantee_companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @visit_company.destroy\n respond_to do |format|\n format.html { redirect_to visit_companies_url, notice: 'Visit company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company_branch.destroy\n respond_to do |format|\n format.html { redirect_to admin_company_branches_url, notice: 'Company branch was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_company_detail = Admin::CompanyDetail.find(params[:id])\n @admin_company_detail.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_company_details_url }\n format.json { head :ok }\n end\n end", "def destroy\n Company.transaction do\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end\n end", "def destroy\n @company = set_company\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_path, notice: \"#{@company.name} has been deleted.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @bond.destroy\n respond_to do |format|\n format.html { redirect_to bonds_url, notice: I18n.t('messages.destroyed_with', item: @bond.company) }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_path, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @businessline.destroy\n respond_to do |format|\n format.html { redirect_to businesslines_url, notice: 'Businessline was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n\n head :no_content\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Cliente eliminado con exito' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n #format.html { redirect_to companys_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: t(\"company_destroyed\") }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @bacon.destroy\n respond_to do |format|\n format.html { redirect_to bacons_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(id_from_params)\n @company.accounts.delete(current_user.account)\n #current_user.companies.delete(@company)\n #@company.destroy\n\n respond_to do |format|\n format.html { redirect_to root_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @companium.destroy\n respond_to do |format|\n format.html { redirect_to compania_url, notice: 'Companium was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @businesstype.destroy\n respond_to do |format|\n format.html { redirect_to businesstypes_url, notice: 'Businesstype was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n @companies = Company.all\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }\n format.json {render json: {message: @companies}, status: 200}\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html { redirect_to companies_url, notice: 'Bar Deletado.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company_vacancy.destroy\n respond_to do |format|\n format.html { redirect_to company_vacancies_url, notice: 'Company vacancy was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @business.destroy\n respond_to do |format|\n format.html { redirect_to businesses_url, notice: 'Business was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @business.destroy\n respond_to do |format|\n format.html { redirect_to businesses_url, notice: 'Business was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @business.destroy\n respond_to do |format|\n format.html { redirect_to businesses_url, notice: 'Business was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @business.destroy\n respond_to do |format|\n format.html { redirect_to businesses_url, notice: 'Business was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @business.destroy\n respond_to do |format|\n format.html { redirect_to businesses_url, notice: 'Business was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @business.destroy\n respond_to do |format|\n format.html { redirect_to businesses_url, notice: 'Business was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @business.destroy\n respond_to do |format|\n format.html { redirect_to businesses_url, notice: 'Business was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @new_company.destroy\n respond_to do |format|\n format.html { redirect_to new_companies_url, notice: 'New company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company_client.destroy\n respond_to do |format|\n format.html { redirect_to company_clients_url, notice: 'Клиент был успешно удален' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html {redirect_to companies_url, notice: 'Company was successfully destroyed.'}\n format.json {head :no_content}\n end\n end", "def destroy\n @company.destroy\n respond_to do |format|\n format.html {redirect_to companies_url, notice: 'Company was successfully destroyed.'}\n format.json {head :no_content}\n end\n end", "def destroy\n @events_company = EventsCompany.find(params[:id])\n @events_company.destroy\n\n respond_to do |format|\n format.html { redirect_to events_companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @hiring_company.destroy\n respond_to do |format|\n format.html { redirect_to hiring_companies_url, notice: 'Hiring company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @customer_company.destroy\n respond_to do |format|\n format.html { redirect_to customer_companies_url, notice: t(\"controllers.destroy_success\") }\n format.json { head :no_content }\n end\n end", "def destroy\n @bussiness.destroy\n respond_to do |format|\n format.html { redirect_to bussinesses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @shipping_company.destroy\n respond_to do |format|\n format.html { redirect_to shipping_companies_url, notice: 'Shipping company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @matched_business.destroy\n respond_to do |format|\n format.html { redirect_to matched_businesses_url, notice: 'Matched business was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company_royalty_detail.destroy\n respond_to do |format|\n format.html { redirect_to company_royalty_details_url, notice: 'Company royalty detail was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @mybusiness.destroy\n respond_to do |format|\n format.html { redirect_to mybusinesses_url, notice: 'Mybusiness was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company = Company.find(params[:id])\n @company.destroy\n\n flash[:notice] = \"company deleted\" \n\n respond_to do |format|\n format.html { redirect_to companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @production_company.destroy\n respond_to do |format|\n format.html { redirect_to production_companies_url, notice: 'Production company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @companyreg.destroy\n respond_to do |format|\n format.html { redirect_to companyregs_url, notice: 'Companyreg was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n if @company.destroy()\n render json: { :message => \"Success!\" }\n else\n render json: { :message => \"La zona no pudo ser eliminada\" }\n end\n end", "def destroy\n @company_owner.destroy\n respond_to do |format|\n format.html { redirect_to company_owners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @businessbook = Businessbook.find(params[:id])\n @businessbook.destroy\n\n respond_to do |format|\n format.html { redirect_to businessbooks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @trein_consul_comercial.destroy\n respond_to do |format|\n format.html { redirect_to trein_consul_comercials_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @part_company = PartCompany.find(params[:id])\n @part_company.destroy\n\n respond_to do |format|\n format.html { redirect_to part_companies_url }\n format.json { head :ok }\n end\n end", "def destroy\n @gas_company.destroy\n respond_to do |format|\n format.html { redirect_to admins_gas_companies_url, notice: 'Gas company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @tyc_company.destroy\n respond_to do |format|\n format.html { redirect_to tyc_companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @contact_company.destroy\n respond_to do |format|\n format.html { redirect_to contact_companies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sp_company_info = SpCompanyInfo.find(params[:id])\n @sp_company_info.destroy\n\n respond_to do |format|\n format.html { redirect_to sp_company_infos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @account_company.destroy\n respond_to do |format|\n format.html { redirect_to account_companies_url, notice: 'Company was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company_account = CompanyAccount.find(params[:id])\n @company_account.destroy\n\n respond_to do |format|\n format.html { redirect_to company_accounts_url }\n format.json { head :ok }\n end\n end", "def destroy\n @company_dashboard = CompanyDashboard.find(params[:id])\n @company_dashboard.destroy\n\n respond_to do |format|\n format.html { redirect_to(company_dashboards_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @credit_company.destroy\n respond_to do |format|\n format.html { redirect_to credit_companies_url, notice: t('credit_company.destroyed') }\n format.json { head :no_content }\n end\n end", "def destroy\n @company_lease_information.destroy\n respond_to do |format|\n format.html { redirect_to company_lease_informations_url, notice: 'Company lease information was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @company_investor.destroy\n respond_to do |format|\n format.html { redirect_to company_investors_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @business = Business.find(params[:id])\n @business.destroy\n\n respond_to do |format|\n format.html { redirect_to businesses_url, notice: I18n.t('commons.successfully_deleted') }\n format.js#\n format.json { head :no_content }\n end\n end" ]
[ "0.7447605", "0.7153824", "0.7148692", "0.69967127", "0.6976809", "0.696085", "0.695971", "0.69507307", "0.69425535", "0.6911259", "0.69102603", "0.6869113", "0.6869113", "0.6869113", "0.6851295", "0.6851295", "0.6851295", "0.6851295", "0.6851295", "0.6851295", "0.6851295", "0.6851295", "0.6851295", "0.6851295", "0.6809166", "0.6784131", "0.6781356", "0.678014", "0.67538404", "0.67420566", "0.6737914", "0.6731953", "0.6730262", "0.6729723", "0.67044127", "0.6704349", "0.6699243", "0.66893077", "0.6687468", "0.6677598", "0.6661683", "0.66517556", "0.66517556", "0.66517556", "0.66517556", "0.66517556", "0.66517556", "0.66517556", "0.66517556", "0.66517556", "0.66517556", "0.66517556", "0.66517556", "0.66517556", "0.66511106", "0.66509634", "0.6621847", "0.6615358", "0.6613615", "0.6611297", "0.6601572", "0.65982366", "0.65888184", "0.65888184", "0.65888184", "0.65888184", "0.65888184", "0.65888184", "0.65888184", "0.6584523", "0.6583666", "0.6582256", "0.6582053", "0.6574707", "0.6565746", "0.6563795", "0.6559469", "0.6548963", "0.654158", "0.65067077", "0.65009975", "0.6499741", "0.6490346", "0.6477179", "0.6473491", "0.6470755", "0.6469999", "0.6469626", "0.6466528", "0.6463708", "0.64617103", "0.6453713", "0.64505184", "0.64478195", "0.6443696", "0.6435338", "0.64201546", "0.6417998", "0.64122045", "0.6412131" ]
0.7238638
1
Grabs all of the yaml files found in /pages, and loads them as Page objects.
def find_all Dir["#{pages_dir}**/*.yml"].map {|f| new f } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pages\n plantuml_files.map { |static_file| page_from_static_file(static_file) }\n end", "def retrieve_pages(dir, dot_pages)\n site.pages.concat(PageReader.new(site, dir).read(dot_pages))\n end", "def retrieve_pages(dir, dot_pages); end", "def retrieve_pages(dir, entries_pages)\n entries_pages.each do |page_path|\n site.collections.pages.read_resource(site.in_source_dir(dir, page_path))\n end\n end", "def all\n Dir.chdir(content_dir) do\n files = Dir.glob(File.join(\"**\", \"*#{SOURCE_FILE_EXT}\")).delete_if {|p| p =~ Regexp.new(\"\\\\.[0-9]+\\\\#{SOURCE_FILE_EXT}$\")}\n files.collect {|f| Page.new(uri_from_path(f), File.open(f, 'r') {|b| b.read})}\n end\n end", "def generate_pages\n Dir.foreach(@site_path) do |file|\n if file =~ /(\\w+)\\.page/\n path = File.join(@site_path, file)\n\n File.open(File.join(@site_path, \"#{$1}.html\"), 'w') do |f|\n f << generate_page(parse_page(path))\n end\n\n @log.debug(\" generated a page from #{path}\")\n end\n end\n end", "def make_pages\n Dir.glob(concepts_glob).each do |concept_file_path|\n Jekyll.logger.debug(\"Geolexica:\",\n \"processing concept data #{concept_file_path}\")\n concept_hash = read_concept_file(concept_file_path)\n preprocess_concept_hash(concept_hash)\n add_page ConceptPage::HTML.new(site, concept_hash)\n add_page ConceptPage::JSON.new(site, concept_hash)\n add_page ConceptPage::JSONLD.new(site, concept_hash)\n add_page ConceptPage::Turtle.new(site, concept_hash)\n end\n end", "def pages\n @pages ||= source.map {|path| Page.new(self, path) }\n end", "def pages\n @pages ||= get_pages\n end", "def pages\n @pages ||= Transit::Page.roots.order('name ASC').all\n end", "def load_page_types\n logger.info ' - Loading page types'\n # Add all the load paths before loading the ruby files in case one page type needs to refer to another\n page_type_paths.each do |path|\n add_load_paths_for_page_types_in_dir(path)\n end\n # Then load up the ruby files, they woudl auto load but we need to know which page type classes get defined\n page_type_paths.each do |path|\n load_page_type_classes_in_dir(path)\n end\n self.page_type_classes = Page.send(:subclasses)\n logger.info \"Loaded the following page type classes: #{self.page_type_classes.map(&:to_s).join(', ')}\"\n end", "def fetch\n self.get(:pages).each do |attributes|\n page = self.add(attributes['fullpath'], attributes)\n\n self.mounting_point.locales[1..-1].each do |locale|\n # if not translated, no need to make an api call for that locale\n next unless page.translated_in?(locale)\n\n Locomotive::Mounter.with_locale(locale) do\n localized_attributes = self.get(\"pages/#{page._id}\", locale)\n\n # remove useless non localized attributes\n localized_attributes.delete('target_klass_slug')\n\n # isolate the editable elements\n editable_elements = self.filter_editable_elements(localized_attributes.delete('editable_elements'))\n\n page.attributes = localized_attributes\n\n page.set_editable_elements(editable_elements)\n end\n end\n end\n end", "def fetch\n position, last_dirname = nil, nil\n\n Dir.glob(File.join(self.root_dir, '**/*')).sort.each do |filepath|\n next unless File.directory?(filepath) || filepath =~ /\\.(#{Locomotive::Mounter::TEMPLATE_EXTENSIONS.join('|')})$/\n\n if last_dirname != File.dirname(filepath)\n position, last_dirname = 100, File.dirname(filepath)\n end\n\n page = self.add(filepath, position: position)\n\n next if File.directory?(filepath) || page.nil?\n\n if locale = self.filepath_locale(filepath)\n Locomotive::Mounter.with_locale(locale) do\n self.set_attributes_from_header(page, filepath)\n end\n else\n Locomotive::Mounter.logger.warn \"Unknown locale in the '#{File.basename(filepath)}' file.\"\n end\n\n position += 1\n end\n end", "def walk_pages (page)\n\n # extract page content\n if page[:Type] == :Pages\n callback(:begin_page_container, [page])\n res = @xref.object(page[:Resources])\n resources.push res if res\n @xref.object(page[:Kids]).each {|child| walk_pages(@xref.object(child))}\n resources.pop if res\n callback(:end_page_container)\n elsif page[:Type] == :Page\n callback(:begin_page, [page])\n res = @xref.object(page[:Resources])\n resources.push res if res\n walk_resources(current_resources)\n\n if @xref.object(page[:Contents]).kind_of?(Array)\n contents = @xref.object(page[:Contents])\n else\n contents = [page[:Contents]]\n end\n\n fonts = font_hash_from_resources(current_resources)\n\n if page.has_key?(:Contents) and page[:Contents]\n contents.each do |content|\n obj = @xref.object(content)\n content_stream(obj, fonts)\n end \n end\n\n resources.pop if res\n callback(:end_page)\n end\n end", "def page_files\n @page_files ||= (Dir.glob (Pathname.pwd.join(\"pages\", \"*.md\"))).sort\n end", "def transform_pages(dir = '')\n base = File.join(self.source, dir)\n entries = Dir.entries(base)\n entries = entries.reject { |e| e[-1..-1] == '~' }\n entries = entries.reject do |e|\n (e != '_posts') and ['.', '_'].include?(e[0..0])\n end\n\n # we need to make sure to process _posts *first* otherwise they \n # might not be available yet to other templates as {{ site.posts }}\n if entries.include?('_posts')\n entries.delete('_posts')\n read_posts(dir)\n end\n\n entries.each do |f|\n if File.directory?(File.join(base, f))\n next if self.dest.sub(/\\/$/, '') == File.join(base, f)\n transform_pages(File.join(dir, f))\n else\n first3 = File.open(File.join(self.source, dir, f)) { |fd| fd.read(3) }\n\n if first3 == \"---\"\n # file appears to have a YAML header so process it as a page\n page = Page.new(self.source, dir, f)\n page.render(self.layouts, site_payload)\n page.write(self.dest)\n else\n # otherwise copy the file without transforming it\n FileUtils.mkdir_p(File.join(self.dest, dir))\n FileUtils.cp(File.join(self.source, dir, f), File.join(self.dest, dir, f))\n end\n end\n end\n end", "def collect_pages\n #find page terminator\n start_line = 0\n current_line = 0\n @lines.each_with_index do |line, i|\n current_line = i\n if end_of_page?(line, i)\n @pages << Page.new(start_line, i) # every page in raw document\n start_line = i + 1 \n end \n end #end of line.each\n \n if current_line > start_line\n page = Page.new(start_line, current_line)\n @pages << page\n end\n #puts \" collect_pages found #{@pages.length} pages\"\n @pages \n end", "def children\n # Check to see whether dir exists.\n Slimdown::Folder.new(@absolute_path.chomp('.md')).pages\n end", "def build_pages( page_name )\n vars = {}\n paths = page_name.split( '/' )\n loop do\n try_page = paths.join( '_' ).gsub('-','_')\n if respond_to? \"skel_#{ try_page }\"\n section_path = File.dirname( page_name )\n path_storage = storage.path_storage( section_path )\n method( \"skel_#{ try_page }\" ).call( path_storage, section_path ) do |vars|\n vars[:weblog] = self\n raise TypeError, \"No `page' variable returned from skel_#{ try_page }.\" unless vars[:page]\n yield vars\n end\n return\n end\n break unless paths.slice!( -2 ) ## go up a directory\n end\n vars[:weblog] = self\n vars[:page] = Page.new( page_name )\n vars[:page].timestamp = Time.now\n yield vars\n end", "def transform_pages(dir = '')\n base = File.join(self.source, dir)\n entries = Dir.entries(base)\n entries = entries.reject { |e| ['.', '_'].include?(e[0..0]) }\n\n entries.each do |f|\n if File.directory?(File.join(base, f))\n next if self.dest.sub(/\\/$/, '') == File.join(base, f)\n transform_pages(File.join(dir, f))\n else\n first3 = File.open(File.join(self.source, dir, f)) { |fd| fd.read(3) }\n \n # if the file appears to have a YAML header then process it as a page\n if first3 == \"---\"\n page = Page.new(self.source, dir, f)\n page.add_layout(self.layouts, site_payload)\n page.write(self.dest)\n # otherwise copy the file without transforming it\n else\n FileUtils.mkdir_p(File.join(self.dest, dir))\n FileUtils.cp(File.join(self.source, dir, f), File.join(self.dest, dir, f))\n end\n end\n end\n end", "def transform_pages(dir = '')\n base = File.join(self.source, dir)\n entries = filter_entries(Dir.entries(base))\n directories = entries.select { |e| File.directory?(File.join(base, e)) }\n files = entries.reject { |e| File.directory?(File.join(base, e)) }\n\n # we need to make sure to process _posts *first* otherwise they\n # might not be available yet to other templates as {{ site.posts }}\n if directories.include?('_posts')\n directories.delete('_posts')\n render_posts(dir)\n end\n [directories, files].each do |entries|\n entries.each do |f|\n if File.directory?(File.join(base, f))\n next if self.dest.sub(/\\/$/, '') == File.join(base, f)\n transform_pages(File.join(dir, f))\n else\n first3 = File.open(File.join(self.source, dir, f)) { |fd| fd.read(3) }\n\n if first3 == \"---\"\n # file appears to have a YAML header so process it as a page\n page = Page.new(self.source, dir, f)\n\n section = zone_section(dir)\n payload = site_payload.deep_merge({\"zonal\" => section[\"zonal\"]})\n\n page.render(self.layouts, payload)\n page.write(self.dest)\n else\n # otherwise copy the file without transforming it\n FileUtils.mkdir_p(File.join(self.dest, dir))\n FileUtils.cp(File.join(self.source, dir, f), File.join(self.dest, dir, f))\n end\n end\n end\n end\n end", "def transform_pages(dir = '', source = self.source)\n base = File.join(source, dir)\n entries = filter_entries(Dir.entries(base))\n directories = entries.select { |e| File.directory?(File.join(base, e)) }\n files = entries.reject { |e| File.directory?(File.join(base, e)) }\n\n [directories, files].each do |entries|\n # we need to make sure to process _posts *first* otherwise they \n # might not be available yet to other templates as {{ site.posts }}\n if entries.include?('_posts')\n entries.delete('_posts')\n read_posts(dir)\n end\n entries.each do |f|\n if File.symlink?(File.join(base, f))\n # preserve symlinks\n FileUtils.mkdir_p(File.join(self.dest, dir))\n File.symlink(File.readlink(File.join(base, f)),\n File.join(self.dest, dir, f))\n elsif File.directory?(File.join(base, f))\n next if self.dest.sub(/\\/$/, '') == File.join(base, f)\n transform_pages(File.join(dir, f), source)\n else\n first3 = File.open(File.join(source, dir, f)) { |fd| fd.read(3) }\n \n # if the file appears to have a YAML header then process it as a page\n if first3 == \"---\"\n # file appears to have a YAML header so process it as a page\n page = Page.new(source, dir, f)\n page.add_layout(self.layouts, site_payload)\n page.write(self.dest)\n else\n # otherwise copy the file without transforming it\n FileUtils.mkdir_p(File.join(self.dest, dir))\n FileUtils.cp(File.join(source, dir, f), File.join(self.dest, dir, f))\n end\n end\n end\n end\n end", "def get_pages(options = nil)\n @client.raw('get', '/content/pages', options)\n end", "def load_yaml_files\n @room_list = YAML.load_file(__dir__ + '/rooms.yml')\n @weapon_list = YAML.load_file(__dir__ + '/weapons.yml')\n @enemy_list = YAML.load_file(__dir__ + '/enemy.yml')\n @high_score_list = YAML.load_file(__dir__ + '/high_score.yml')\n end", "def pages(treeish = nil)\n tree_list(treeish || 'master')\n end", "def load_pages_json(pages_json_path)\n basename = File.basename pages_json_path\n rel_dir = File.dirname pages_json_path\n rel_dir = rel_dir[self.source.size..rel_dir.size]\n page = ::JekyllPagesApi::PageWithoutAFile.new(\n self, self.source, rel_dir, basename)\n page.output = File.read(pages_json_path)\n self.pages << page\n end", "def pages\n @pages ||= []\n end", "def public_pages\n\n pages = {}\n\n # Add page contents\n ContentManagerSystem::Content.all(:type => {:id => 'page'}).map do |content| \n pages.store(content.title, content.alias)\n end \n\n # Add views\n ContentManagerSystem::View.all(:block => false).map do |view|\n pages.store(view.title, view.url)\n end\n\n return pages\n\n end", "def process_pages\n bindings = {\n :name => @definition.get_name,\n :version => @definition.get_version\n }\n\n page = Calamum::DocGenerator.new(:view)\n @definition.resources.each do |methods|\n methods[1].each do |resource|\n bindings.merge!(:resource => resource)\n filename = \"#{resource.slug}.html\"\n page.save_template(filename, bindings)\n end\n end\n end", "def read_posts\n base = File.join(self.source, \"_posts\")\n entries = Dir.entries(base)\n entries = entries.reject { |e| File.directory?(e) }\n \n entries.each do |f|\n self.posts << Post.new(base, f) if Post.valid?(f)\n end\n \n self.posts.sort!\n rescue Errno::ENOENT => e\n # ignore missing layout dir\n end", "def index\n @root_pages = Page.root_pages\n @uncategorized_pages = Page.uncategorized\n end", "def pages_slim\n Dir[src_path.join('pages', '**', '*.slim').to_s]\n end", "def load_all\n load_cache\n\n module_names.each do |module_name|\n mod = find_class_or_module(module_name) || load_class(module_name)\n\n # load method documentation since the loaded class/module does not have\n # it\n loaded_methods = mod.method_list.map do |method|\n load_method module_name, method.full_name\n end\n\n mod.method_list.replace loaded_methods\n\n loaded_attributes = mod.attributes.map do |attribute|\n load_method module_name, attribute.full_name\n end\n\n mod.attributes.replace loaded_attributes\n end\n\n all_classes_and_modules.each do |mod|\n descendent_re = /^#{mod.full_name}::[^:]+$/\n\n module_names.each do |name|\n next unless name =~ descendent_re\n\n descendent = find_class_or_module name\n\n case descendent\n when RDoc::NormalClass then\n mod.classes_hash[name] = descendent\n when RDoc::NormalModule then\n mod.modules_hash[name] = descendent\n end\n end\n end\n\n @cache[:pages].each do |page_name|\n page = load_page page_name\n @files_hash[page_name] = page\n @text_files_hash[page_name] = page if page.text?\n end\n end", "def list_pages(pages)\n pages.inject(''.html_safe) do |html, page|\n html << render(\n partial: page_partial(page),\n locals: {\n page: page,\n children: sitemap_children_for(page),\n }\n )\n end\n end", "def page_paths\n @pages_paths ||= Dir[File.join(Serious.pages, '*')].sort\n end", "def write_pages\n pages = Dir[\"#{source_path}/*.html\"].each do |p_name|\n page = Page.new(source_path, File.basename(p_name))\n # TODO allow user to specify which layouts a page should use \n page.render(site_payload, layouts.select{|x| x.name == \"application.html\"})\n page.write(destination_path)\n end\n end", "def add_pages\n exhibit.feature_pages.published.find_each do |p|\n sitemap.add sitemap.exhibit_feature_page_path(exhibit, p), priority: 0.8, lastmod: p.updated_at\n end\n\n exhibit.about_pages.published.find_each do |p|\n sitemap.add sitemap.exhibit_about_page_path(exhibit, p), priority: 0.5, lastmod: p.updated_at\n end\n end", "def read(files)\n files.map do |page|\n @unfiltered_content << Page.new(@site, @site.source, @dir, page)\n end\n @unfiltered_content.select { |page| site.publisher.publish?(page) }\n end", "def prepare()\n @pages = {}\n @files = {}\n @layouts = {}\n\n @commit = @version == :working ? @wiki.repo.head.commit : @wiki.repo.commit(@version)\n items = self.ls(@version)\n\n items.each do |item|\n filename = ::File.basename(item.path)\n dirname = ::File.dirname(item.path)\n if filename =~ /^_Layout.html/\n # layout\n @layouts[item.path] = ::Liquid::Template.parse(item.data)\n elsif @wiki.page_class.valid_page_name?(filename)\n # page\n page = @wiki.page_class.new(@wiki)\n blob = OpenStruct.new(:name => filename, :data => item.data)\n page.populate(blob, dirname)\n page.version = @commit\n\n if @preserve_tree\n key = [::File.dirname(item.path).gsub(/^\\./, \"\").gsub(/\\//, ' '), page.name].join(\" \").strip.downcase\n else\n key = page.name.downcase\n end\n @pages[key] = page\n else\n # file\n @files[item.path] = item.data\n end\n end\n end", "def read\n @site.layouts = LayoutReader.new(site).read\n read_directories\n read_included_excludes\n sort_files!\n CollectionReader.new(site).read\n ThemeAssetsReader.new(site).read\n read_data\n end", "def each_page\n page_obj = load_page(1)\n loop do\n yield page_obj\n break unless page_obj.has_next?\n page_obj = load_page(page_obj.next_page)\n end\n end", "def get_pages\n @pages << base_gallery_url\n (@doc/\"a\").select{|a| a[\"href\"] =~ /ndxpage/}.each do |e|\n @pages << base_gallery_url_prefix + e[\"href\"]\n end\n puts \"got pages!\"\n puts @pages.inspect\n puts \"---\"\n end", "def parse_page_file\n raise \"File not found: #{@pointer['realpath']}\" unless File.exist?(@pointer['realpath'])\n\n page = File.open(@pointer['realpath'], 'r:UTF-8') {|f| f.read }\n\n begin\n front_matter = page.match(FMregex)\n rescue => e\n raise \"Error trying to read meta-data from #{@pointer['realpath']}.\" +\n \" Check your folder configuration. Error details: #{e}\"\n end\n \n data = front_matter ?\n (YAML.load(front_matter[0].gsub(/---\\n/, \"\")) || {}) :\n {}\n\n result = {\n \"data\" => data,\n \"content\" => page.gsub(FMregex, '')\n }\n\n # variable cache\n @data = data\n @content = result['content']\n\n result\n rescue Psych::SyntaxError => e\n Ruhoh.log.error(\"Psych::SyntaxError while parsing top YAML Metadata in #{ @pointer['realpath'] }\\n\" +\n \"#{ e.message }\\n\" +\n \"Try validating the YAML metadata using http://yamllint.com\"\n )\n nil\n end", "def site_pages \n Rails.application.reload_routes!\n page_routes = Rails.application.routes.routes.select do |route|\n route.verb == \"GET\" && !route.name.blank? && !route.name.match(/^edit/) && !route.name.match(\"translat\") && !route.name.match(\"external_author\")\n end\n\n @paths = []\n @errors = []\n @errors << \"Skipping translation and external author pages because these areas are in-progress.\"\n\n page_routes.each do |r|\n path = r.path.split('(').first\n while (path.match(/:([^\\/]+)_id\\//)) do\n id = get_id(path, current_user, $1.singularize)\n if id\n path.gsub!(\":#{$1}_id\", \"#{id}\") if id\n @last_id = id\n else\n @errors << \"Couldn't find object for #{path}, #{$1}\"\n break\n end\n end\n\n if (path.match(/\\/([^\\/]+)\\/:id/))\n id = get_id(path, current_user, $1.singularize)\n if id\n path.gsub!(\":id\", \"#{id}\")\n @last_id = id\n else\n @errors << \"Couldn't find object for #{path}, id\"\n end\n end\n\n @paths << [path, r.name]\n end\n \n render :action => \"site_pages\", :layout => \"application\"\n end", "def read(files)\n files.each do |page|\n @unfiltered_content << Page.new(@site, @site.source, @dir, page)\n end\n @unfiltered_content.select { |page| site.publisher.publish?(page) }\n end", "def find\n list = Dir.glob(File.join(@pages_folder, '**/*'))\n list.map! { |name| name.gsub(@pages_folder + '/', '')}\n list.map { |name| name.force_html_extension }\n end", "def read\n self.fetch\n\n index, not_found = self.pages['index'], self.pages['404']\n\n # localize the fullpath for the 2 core pages: index and 404\n [index, not_found].each { |p| p.localize_fullpath(self.locales) }\n\n self.build_relationships(index, self.pages_to_list)\n\n # Locomotive::Mounter.with_locale(:en) { self.to_s } # DEBUG\n\n # Locomotive::Mounter.with_locale(:fr) { self.to_s } # DEBUG\n\n self.pages\n end", "def load_all\n html_path = self.most_recent_project_html\n html_resource = html_path.gsub(self.source_dir,\"\")\n self.file_mapper.add_file(html_resource, \"#{self.index_file}.html\")\n load_resources(html_path)\n end", "def ingest_pages\n @table_of_contents.unique_pages.each_with_index do |entry, index|\n label = entry ? Utils.xml_escape(entry.title) : \"Page #{index + 1}\"\n @component_objects.push ingest_page(entry.image_filename, label, index + 1)\n end\n\n if @manifest.embargo\n @component_objects.each do |pid|\n @drupal_db.add_embargo pid, @manifest.embargo['rangeName'], @manifest.embargo['endDate']\n end\n end\n end", "def run(pages)\n clean\n\n prototype_fetcher.fetch_pages(pages.map {|p| p[:prototype]})\n app_fetcher.fetch_pages\n\n normalised_html_files = pages.map do |i|\n {\n prototype_file: prototype_fetcher.get_normalised_filename(i[:prototype]),\n app_file: app_fetcher.get_normalised_filename(i[:app])\n }\n end\n\n diff_files = normalised_html_files.map do |i|\n generate_diff(i)\n end\n\n output_report diff_files\n end", "def transform_pages(dir = '')\n base = File.join(self.source, dir)\n entries = Dir.entries(base)\n entries = entries.reject { |e| ['.', '_'].include?(e[0..0]) }\n \n entries.each do |f|\n if File.directory?(File.join(base, f))\n transform_pages(File.join(dir, f))\n else\n first3 = File.open(File.join(self.source, dir, f)) { |fd| fd.read(3) }\n \n if first3 == \"---\"\n page = Page.new(self.source, dir, f)\n page.add_layout(self.layouts, site_payload)\n page.write(self.dest)\n else\n FileUtils.mkdir_p(File.join(self.dest, dir))\n FileUtils.cp(File.join(self.source, dir, f), File.join(self.dest, dir, f))\n end\n end\n end\n end", "def get_pages\n sitemap.resources.select { |resource| resource.data.type == 'page' }\n .sort_by { |r| get_page_priority(r.data) }\n end", "def yaml(*files, **options, &block) = read(*files, parse: :yaml, ext: ['.yml', '.yaml'], **options, &block)", "def parse_page_file(file_path)\n \n result = {}\n metadata = []\n remaining = ''\n \n File.open(file_path) do |file|\n \n while (not file.eof?)\n line = file.readline \n if match = line.match(/\\w*:\\s[\\w|\\s]*/)\n metadata.push(line)\n else\n remaining << line if not line.match(/^\\n|\\n\\r$/)\n break\n end\n end \n \n remaining << file.read # Reads the rest of the document\n\n result = {}\n \n if metadata and metadata.length > 0 \n result = YAML::load(metadata.join)\n end\n \n result.store(:body, remaining) if remaining\n \n end \n \n return result \n \n end", "def pages_data\n\n config_data = get_config_data\n\n all_data_files = Dir.glob(\"../#{ROOT_DIR}/lib/views/source/#{config_data[\"templates_page\"]}/**/*.json\")\n\n pageData_files = []\n\n all_data_files.map { |data| \n\n data_name = data.split(\"/\")[-1]\n pageData_files.push(\n {\n \"file_name\": data_name,\n \"link_name\": data_name.sub(\"~\", \"__\").chomp(\".json\"),\n \"label\": data_name.sub(\"~\", \" \").chomp(\".json\")\n }\n )\n }\n\n return pageData_files\n end", "def read\n filtered_entries.each do |file_path|\n full_path = collection_dir(file_path)\n next if File.directory?(full_path)\n\n if Utils.has_yaml_header? full_path\n read_document(full_path)\n else\n read_static_file(file_path, full_path)\n end\n end\n site.static_files.concat(files) unless files.empty?\n sort_docs!\n end", "def read_posts(dir)\n base = File.join(self.source, dir, '_posts')\n \n entries = []\n Dir.chdir(base) { entries = Dir['**/*'] }\n entries = entries.reject { |e| e[-1..-1] == '~' }\n entries = entries.reject { |e| File.directory?(File.join(base, e)) }\n\n # first pass processes, but does not yet render post content\n entries.each do |f|\n if Post.valid?(f)\n post = Post.new(self.source, dir, f)\n self.posts << post\n end\n end\n \n # second pass renders each post now that full site payload is available\n self.posts.each do |post|\n post.render(self.layouts, site_payload)\n end\n \n self.posts.sort!\n rescue Errno::ENOENT => e\n # ignore missing layout dir\n end", "def find_pages_for_menu\n if (@menu_pages = Rails.cache.read(cache_key = \"#{Refinery.base_cache_key}_menu_pages\")).nil?\n @menu_pages = Page.top_level(include_children = true)\n Rails.cache.write(cache_key, @menu_pages) if @menu_pages.present?\n end\n end", "def pages(name, opts = {}, *args, &block)\n instance_handler(name, Page, opts, *args, block)\n end", "def pages\n get(\"v1/event/#{@id}/pages\")\n end", "def pages(catalogs = nil)\n page_list = []\n catalogs ||= get_existing_catalogs\n\n if catalogs.is_a?(Array)\n catalogs.each { |c| page_list.concat pages(c) unless c.nil? }\n elsif catalogs.is_a?(Hash)\n if catalogs[:is_reference_only]\n if catalogs[:referenced_object]\n page_list.concat pages(catalogs[:referenced_object])\n else\n warn \"couldn't follow reference!!! #{catalogs} not found!\"\n end\n else\n case catalogs[:Type]\n when :Page\n page_list << catalogs\n when :Pages\n page_list.concat pages(catalogs[:Kids]) unless catalogs[:Kids].nil?\n when :Catalog\n page_list.concat pages(catalogs[:Pages]) unless catalogs[:Pages].nil?\n end\n end\n end\n page_list\n end", "def fetch_page_nodes\n (1..12).each do |file_name|\n body = File.open(\"#{Rails.root}/lib/wayfair_batch/#{file_name}.html\")\n @page_nodes.push(Nokogiri::HTML(body))\n end\n end", "def read_directories(dir = \"\")\n base = site.in_source_dir(dir)\n\n return unless File.directory?(base)\n\n dot_dirs = []\n dot_pages = []\n dot_static_files = []\n\n dot = Dir.chdir(base) { filter_entries(Dir.entries(\".\"), base) }\n dot.each do |entry|\n file_path = @site.in_source_dir(base, entry)\n if File.directory?(file_path)\n dot_dirs << entry\n elsif Utils.has_yaml_header?(file_path)\n dot_pages << entry\n else\n dot_static_files << entry\n end\n end\n\n retrieve_posts(dir)\n retrieve_dirs(base, dir, dot_dirs)\n retrieve_pages(dir, dot_pages)\n retrieve_static_files(dir, dot_static_files)\n end", "def crawlAllPages\n page = 1\n loop do\n puts \"Path: #{@basePath}#{page.to_s}\"\n path \"#{@basePath}#{page.to_s}\"\n\n response = crawl\n @dbm.insertCrawlerBlob response[\"beers\"]\n\n break if response[\"more\"].nil?\n page += 1\n end\n end", "def ingest_pages\n if @has_mets\n # This is basically equivalent to the BookPackage processing.\n sequence = 0\n @table_of_contents.unique_pages.each do |entry|\n sequence += 1\n label = entry.title ? Utils.xml_escape(entry.title) : \"Page #{sequence}\"\n @component_objects.push ingest_page(entry.image_filename, label, sequence)\n end\n else\n # NewspaperIssue packages don't necessarily have to have a METS file, so we do the best we can do.\n sequence = 0\n @page_filenames.each do |image_filename|\n sequence += 1\n @component_objects.push ingest_page(image_filename, \"Page #{sequence}\", sequence)\n end\n end\n\n if @manifest.embargo\n @component_objects.each do |pid|\n @drupal_db.add_embargo pid, @manifest.embargo['rangeName'], @manifest.embargo['endDate']\n end\n end\n end", "def load\n @all = [] #contains all template objects\n\n template_dir = Gem.datadir('moo') + '/templates/'\n\n template_files = Dir.entries(template_dir).reject do |t|\n t == '.' || t == '..'\n end\n\n template_files.each do |f|\n path = template_dir + f\n @all << Template.new(path)\n end\n end", "def process(pages)\n robot = Robots.new USER_AGENT\n until pages.nil? or pages.empty? \n newfound_pages = []\n pages.each { |page|\n begin\n if add_to_index?(page) then \n uri = URI.parse(page)\n host = \"#{uri.scheme}://#{uri.host}\"\n open(page, \"User-Agent\" => USER_AGENT) { |s|\n (Hpricot(s)/\"a\").each { |a| \n url = scrub(a.attributes['href'], host)\n newfound_pages << url unless url.nil? or !robot.allowed? url or newfound_pages.include? url\n }\n } \n end\n rescue => e \n print \"\\n** Error encountered crawling - #{page} - #{e.to_s}\"\n rescue Timeout::Error => e\n print \"\\n** Timeout encountered - #{page} - #{e.to_s}\"\n end\n }\n pages = newfound_pages\n File.open(LAST_CRAWLED_PAGES, 'w') { |out| YAML.dump(newfound_pages, out) }\n end \n end", "def links\n\t\t\tlinks = {}\n\t\t\tself.page_files(true).each do |p|\n\t\t\t\tpage = Page.new(p)\n\t\t\t\tlinks[page.base_dir] = page.url\n\t\t\tend\n\t\t\tlinks\n\t\tend", "def process_pages()\n unless Dir.exist?(node_files_path)\n raise \"Path to downloaded pages '#{node_files_path}' does not exist\"\n end\n\n Dir.glob(File.join(node_files_path, '*')) do |file_name|\n puts \"Processing: #{file_name}\"\n\n document = File.open(file_name) { |f| Nokogiri::HTML(f) }\n elements = document.xpath(\"//div[@class = 'debug-data-item']\")\n node_data = Hash.new\n\n elements.each do |e|\n name = e['data-name']\n value = e['data-value']\n node_data[name] = value\n end\n\n @nodes << node_data\n serialise(node_data)\n end\n end", "def setup\n @page = pages(:homepage)\n end", "def pages\n end", "def render_pages(static_path)\n puts \" Rendering pages\"\n Page.all.each do |p|\n if p.published? && (body = p.render)\n dir, filename = p.url, \"index.html\"\n dir, filename = p.parent.url, p.slug if p.slug =~ /\\.[^.]+$/i # File with extension (e.g. styles.css)\n FileUtils.mkdir_p(File.join(static_path, dir))\n File.open(File.join(static_path, dir, filename), 'w') { |io| io.print(body) }\n else\n puts \" ! Not rendering #{p.id} - #{p.status.name} - #{p.url}\"\n end\n end\nend", "def discover_paginate_templates(site_pages)\r\n candidates = []\r\n site_pages.select do |page|\r\n # If the page has the enabled config set, supports any type of file name html or md\r\n if page.data['pagination'].is_a?(Hash) && page.data['pagination']['enabled']\r\n candidates << page\r\n end\r\n end\r\n return candidates\r\n end", "def retrieve_posts(dir)\n return if outside_configured_directory?(dir)\n\n site.posts.docs.concat(post_reader.read_posts(dir))\n site.posts.docs.concat(post_reader.read_drafts(dir)) if site.show_drafts\n end", "def pages; end", "def index\n @cms_pages = Cms::Page.all\n end", "def read_posts(dir)\n base = File.join(self.source, dir, '_posts')\n entries = []\n Dir.chdir(base) { entries = filter_entries(Dir['**/*']) }\n\n # first pass processes, but does not yet render post content\n entries.each do |f|\n if Post.valid?(f)\n post = Post.new(self.source, dir, f)\n\n if post.published\n self.posts << post\n post.categories.each { |c| self.categories[c] << post }\n end\n end\n end\n\n self.posts.sort!\n \n # second pass renders each post now that full site payload is available\n self.posts.each_with_index do |post, idx|\n post.numericid = idx+1\n\tpost.previous = posts[idx - 1] unless idx - 1 < 0\n post.next = posts[idx + 1] unless idx + 1 >= posts.size\n post.render(self.layouts, site_payload)\n end\n \n self.categories.values.map { |cats| cats.sort! { |a, b| b <=> a} }\n rescue Errno::ENOENT => e\n # ignore missing layout dir\n end", "def render_all\n @data_loader.pages.each { |p| render_page p }\n @data_loader.multi_pages.each { |m| render_multi m }\n end", "def pages(treeish = nil)\n tree_list(treeish || @ref, true, false)\n end", "def index\n @pages = Page.all\n end", "def read\n site.defaults_reader.read\n site.data = site.collections.data.read.merge_data_resources\n read_layouts\n read_directories\n read_includes\n sort_files!\n read_collections\n site.config.source_manifests.select(&:content).each do |manifest|\n PluginContentReader.new(site, manifest).read\n end\n end", "def load_page page_name\n file = page_file page_name\n\n File.open file, 'rb' do |io|\n obj = Marshal.load io.read\n obj.store = self\n obj\n end\n rescue Errno::ENOENT => e\n error = MissingFileError.new(self, file, page_name)\n error.set_backtrace e.backtrace\n raise error\n end", "def load_yaml_files(path)\n each_data_file(path).map { |file| YAML.load_file(file) }\n end", "def read_posts(dir); end", "def extract_pages_list\n if @page\n if @page.wikitopdf_toc_page && @page.wikitopdf_toc_page.istoc\n [ url_by_page(@page) ] + pages_from_toc(@page)\n else\n [ url_by_page(@page) ] + pdf_page_hierarchy(@page.id)\n end\n else\n pdf_page_hierarchy(nil)\n end\n end", "def read_yaml(base, name)\n begin\n text = File.read(File.join(base, name))\n data = {'layout'=>'default'}\n\n if page_yaml = transfiguration['page_yaml']\n data.merge!(page_yaml)\n end\n\n # commented metadata\n if text =~ /<!--\\s+---\\s*(.*?)-->\\s*$\\n?/m\n text.delete($0)\n data.merge!(YAML.safe_load($1))\n end\n\n self.content = text\n self.data = data\n rescue SyntaxError => e\n puts \"YAML Exception reading #{File.join(base, name)}: #{e.message}\"\n rescue Exception => e\n puts \"Error reading file #{File.join(base, name)}: #{e.message}\"\n end\n\n unless self.data['layout']\n self.data['layout'] = 'page'\n end\n\n return self.data\n end", "def index\n @page_pages = PagePage.all\n end", "def load_font_bitmaps\n for page in @pages\n @page_bitmaps[page.id] = RPG::Cache.picture(page.file)\n end\n end", "def load\n @models = []\n\n # \n files = \n if File.directory?(config_path) \n files_in_dir = []\n Dir[config_path + \"/*.yml\"].each do |file|\n files_in_dir << file\n end\n files_in_dir\n elsif File.file?(config_path)\n [config_path]\n else\n nil\n end\n\n return nil if files.nil?\n\n # \n @models = files.inject(@models) do |models, file|\n begin\n yaml = YAML.load_file(file)\n rescue => ex\n logger.debug \"failed in reading yaml (#{file})\"\n next\n end\n if yaml.nil?\n logger.debug \"failed in reading yaml (#{file})\"\n next\n end\n models + yaml2models(yaml)\n end.extend(ArrayMethods)\n end", "def parse_html_files\n Find.find(Dir.getwd) do |file|\n if !File.directory? file and File.extname(file) == '.html'\n # exclude and skip if in a bad directory\n # we may be on an html file, but some we just do not want\n current = File.new(file).path\n\n # skip these folders entirely\n if current.match(/(blog|old|draft|archive|font)/i)\n next\n end\n\n # open file, pluck content out by its element(s)\n page = Nokogiri::HTML(open(file));\n\n # grab title\n title = page.css('title').text.to_s;\n title = strip_bad_chars(title)\n\n # for page title, destroy any pipes and MS pipes and return the first match\n title.sub!('Velir | ', '')\n\n # Grab hero title and tagline\n hero = page.css('article.type-centered h2').text\n hero_tagline = page.css('article.type-centered .type-hero').text\n\n # grab the body content\n body = page.css('.outer-wrapper .row .columns').to_html\n body = clean_body(body)\n\n # clean the file path\n path = File.new(file).path\n path.gsub! $base_path, \"/\"\n\n # if we have content, add this as a page to our page array\n if (body.length > 0)\n $count += 1\n puts \"Processing \" + title\n\n # insert into array\n data = {\n 'title' => title,\n 'path' => path,\n 'hero' => hero,\n 'hero_tagline' => hero_tagline,\n 'body' => body,\n }\n\n $pages.push data\n end\n end\n end\n\n write_csv($pages)\n report($count)\nend", "def index\n @page_hierarchies = PageHierarchy.all\n end", "def process_pages(dir, parent_section)\n\t\t\n\t\t# each page is a descendant of a section and contains one or more markdown subpages\n\t\tsubdirs_of(dir) do |page|\n\t\t\t\n\t\t\tpage_path = File.basename(page) # only the directory name\n\t\t\tpage_info = split_info(page_path) # array of position and page name\n\n\t\t\t# if this directory name is parsable\n\t\t\tif page_info\n\t\t\t\t# create the page\n\t\t\t\t# db_page = parent_section.pages.create(:title => page_info[2], :position => page_info[1], :path => page_path)\n\t\t\t\t\n\t\t\t\tdb_page = parent_section.pages.find_by_path(page_path) || parent_section.pages.new(path: page_path)\n\t\t\t\tdb_page.title = upcase_first_if_all_downcase(page_info[2])\n\t\t\t\tdb_page.position = page_info[1]\n\t\t\t\tdb_page.save\n\n\t\t\t\t# load submit.yml config file which contains items to submit\n\t\t\t\tsubmit_config = read_config(files(page, \"submit.yml\"))\n\n\t\t\t\t# add pset to database\n\t\t\t\tif submit_config\n\t\t\t\t\t\n\t\t\t\t\tdb_pset = nil\n\t\t\t\t\t\n\t\t\t\t\tif submit_config['name']\n\t\t\t\t\t\t# checks if pset already exists under name\n\t\t\t\t\t\tdb_pset = Pset.where(:name => submit_config['name']).first_or_initialize\n\t\t\t\t\t\tdb_pset.description = page_info[2]\n\t\t\t\t\t\tdb_pset.message = submit_config['message'] if submit_config['message']\n\t\t\t\t\t\tdb_pset.form = !!submit_config['form']\n\t\t\t\t\t\tdb_pset.url = !!submit_config['url']\n\t\t\t\t\t\tdb_pset.page = db_page # restore link to owning page!\n\t\t\t\t\t\tif submit_config['files']\n\t\t\t\t\t\t\tdb_pset.files = submit_config['files']\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdb_pset.files = nil\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\tdb_pset.config = submit_config\n\n\t\t\t\t\t\tdb_pset.automatic = !!db_pset.config && db_pset.config[\"automatic\"].present?\n\t\t\t\t\t\tdb_pset.save\n\t\t\t\t\t\t\n\t\t\t\t\t\tPset.where(\"id != ?\", db_pset).where(page_id: db_page).update_all(page_id: nil)\n\n\t\t\t\t\t\t# remove previous files\n\t\t\t\t\t\t# db_pset.pset_files.delete_all\n\n\t\t\t\t\t\t# always recreate so it's possible to remove files from submit\n\t\t\t\t\t\t# ['required', 'optional'].each do |modus|\n\t\t\t\t\t\t# \tif submit_config[modus]\n\t\t\t\t\t\t# \t\tsubmit_config[modus].each do |file|\n\t\t\t\t\t\t# \t\t\tdb_pset.pset_files.create(:filename => file, :required => modus == 'required')\n\t\t\t\t\t\t# \t\tend\n\t\t\t\t\t\t# \tend\n\t\t\t\t\t\t# end\n\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\tif submit_config['dependent_grades']\n\t\t\t\t\t\tsubmit_config['dependent_grades'].each do |grade|\n\t\t\t\t\t\t\tpset = Pset.where(:name => grade).first_or_create\n\t\t\t\t\t\t\tpset.update_attribute(:page_id, db_page.id)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\tPset.where(page_id: db_page).update_all(page_id: nil)\n\t\t\t\tend\n\t\t\t\tprocess_subpages(page, db_page)\n\t\t\tend\n\t\n\t\tend\n\tend", "def generate_all_pages_html(params={})\n @errors = []\n @been_cached = []\n Comatose.mount_points.each do |root_info|\n ComatosePage.active_mount_info = root_info\n generate_page_html(ComatosePage.find_by_path( root_info[:index] ), root_info, params)\n end\n @errors\n end", "def assign_pages!; end", "def generate()\n prepare\n ::Dir.mkdir(@output_path) unless ::File.exists? @output_path\n\n @pages.each do |name, page|\n SiteLog.debug(\"Starting page generation - #{name}\")\n page.generate(@output_path, @version, @preserve_tree)\n SiteLog.debug(\"Finished page generation - #{name}\")\n end\n\n @files.each do |path, data|\n path = ::File.join(@output_path, path)\n ::FileUtils.mkdir_p(::File.dirname(path))\n ::File.open(path, \"w\") do |f|\n f.write(data)\n end\n end\n end", "def wiki_pages(project, on_page = nil)\n opts = {}\n opts[:page] = on_page if on_page\n fetch_all(\"projects/#{project}/features/wiki/pages\", 'pages', opts)\n end", "def sitemap\n @pages = Page.sitemap\n end", "def index\n @pages = Page.includes(:user)\n end", "def index\n @pages = Page.all\n end", "def index\n @pages = Page.all\n end" ]
[ "0.7043972", "0.6895947", "0.68627375", "0.67453283", "0.6696323", "0.6664716", "0.66500103", "0.66384196", "0.65258586", "0.6386816", "0.6380106", "0.6305485", "0.63036996", "0.6290372", "0.6273399", "0.62681454", "0.626001", "0.6256252", "0.62232804", "0.6206196", "0.6182985", "0.61499983", "0.61400044", "0.61399835", "0.6130505", "0.6119312", "0.6090192", "0.60605085", "0.6023235", "0.6004968", "0.5997502", "0.5971969", "0.5970129", "0.59391844", "0.5931863", "0.5931492", "0.592269", "0.59210265", "0.5919402", "0.59093505", "0.5908312", "0.58951145", "0.5881504", "0.5875897", "0.58746487", "0.5874136", "0.5869106", "0.5853887", "0.5845648", "0.5844604", "0.5835008", "0.58320904", "0.5809955", "0.5806918", "0.5799426", "0.5798892", "0.5796451", "0.57926434", "0.57757735", "0.57756686", "0.5771813", "0.5760873", "0.5748042", "0.5745767", "0.5743892", "0.5741756", "0.5740715", "0.5732052", "0.57257336", "0.5710701", "0.57072026", "0.5703806", "0.5697639", "0.56876874", "0.5680152", "0.56770927", "0.56684893", "0.5665764", "0.5660803", "0.56523025", "0.5645288", "0.56313115", "0.56216705", "0.56157964", "0.5594252", "0.55895877", "0.5587633", "0.5563761", "0.55612385", "0.5558976", "0.5550466", "0.55445665", "0.5542057", "0.55359876", "0.55284345", "0.5514267", "0.5504646", "0.55034006", "0.5500122", "0.5500122" ]
0.7678771
0
A requriement of the Templette::DataAccessors interface. Returns self.
def page; self end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def data\n DataProxy.new(self)\n end", "def d(name)\n DataAccessor.new(name)\n end", "def data_accessor_for(clazz) #:nodoc:\n (@data_accessors ||= {})[clazz.name.to_sym] ||=\n Adapters::DataAccessor.create(clazz)\n end", "def data() @data ||= Data.new( self ); end", "def roller\n rv = super\n class << rv\n def to_dataset; riven end\n end\n rv\n end", "def dataset\n self\n end", "def dataset\n self\n end", "def dataset\n self\n end", "def data\n raise NotImplementedError\n end", "def define_accessor\n klass.class_eval <<-ACCESSOR\n def #{@relation}\n #self.dataset.left_outer_join(#{@relation}, :id => :#{klass.primary_key_string}).limit(1)\n puts #{relation_class}\n end\n \n def #{@relation}=(value)\n end\n ACCESSOR\n end", "def dataset\n @dataset_class.new(self)\n end", "def data\n self[:data]\n end", "def data\n self.reload if @should_reload\n return @data\n end", "def method_missing(method, *args, &block)\n @dataset = @dataset.send(method, *args, &block)\n raise(Sequel::Error, \"method #{method.inspect} did not return a dataset\") unless @dataset.is_a?(Dataset)\n self\n end", "def dataset\n @dataset ||= data_maker.dataset\n end", "def data\n @data || set_collection_data\n end", "def initialize\n @data = Data.instance\n end", "def data\n @data ||= @_data.respond_to?(:call) ? @_data.call() : @_data\n end", "def dataset\n @@dataset\n end", "def _update_dataset\n this\n end", "def _update_dataset\n this\n end", "def dataset_method\n :\"#{self[:name]}_dataset\"\n end", "def method_missing(name, *args, &block)\n return super unless @table.accessors?\n\n name =~ /^(\\w+)(=)?$/\n name_mod, assign = $1, $2\n index = @table.index_for_accessor(name_mod)\n arg_count = assign ? 1 : 0\n\n return super unless index\n\n raise ArgumentError, \"Wrong number of arguments (#{args.size} for #{arg_count})\" if args.size > arg_count\n\n if assign then\n raise \"Coercions not yet implemented\" # todo, coerce data when set\n @data[index] = args.first\n else\n @data[index]\n end\n end", "def this\n @this ||= dataset.filter(pk_hash).limit(1).naked\n end", "def data\n @data\n end", "def data\n @data\n end", "def data\n @data\n end", "def accessors\n self.class.accessors\n end", "def set_accessor\n @accessor = Accessor.find(params[:id])\n end", "def set_accessor\n @accessor = Accessor.find(params[:id])\n end", "def md_accessor(*accessors)\n md_reader(*accessors)\n md_writer(*accessors)\n end", "def accessor\n @@accessor ||= nil\n @@accessor\n end", "def _dataset_method\n :\"_#{self[:name]}_dataset\"\n end", "def dataset\n @dataset ||= generate_dataset\n end", "def this\n return @this if @this\n raise Error, \"No dataset for model #{model}\" unless ds = model.instance_dataset\n @this = use_server(ds.where(pk_hash))\n end", "def data\n @data\n end", "def get_data\n response = proxy.get_data(handle)\n self.update_properties(response)\n self.partial = false\n self.persisted = true\n end", "def dataset\n ds = Sequel::Dataset.new(self)\n end", "def dataset\n ds = Sequel::Dataset.new(self)\n end", "def dataset_method\n :\"#{self[:name]}_dataset\"\n end", "def hydrate(data)\n data.each do |k,v|\n getter = \"#{underscore_case(k)}\".to_sym\n setter = \"#{underscore_case(k)}=\".to_sym\n if self.respond_to? getter\n if v.kind_of? Hash\n object = self.send(getter)\n if (object.kind_of? SimpleObject)\n object.hydrate(v)\n elsif object.nil?\n puts \"don't know what to do with #{k}\"\n end\n else\n self.send(setter, v)\n end\n else\n puts \"Unknown attribute #{k} in hydrate\"\n end\n end\n self\n end", "def data\n @data_t\n end", "def create_accessors(name, meth, options = {})\n field = fields[name]\n create_field_getter(name, meth, field)\n create_field_setter(name, meth, field)\n end", "def data\n @data\n end", "def data\n self[:data].with_indifferent_access\n end", "def _metadata_dataset\n super.\n with_identifier_input_method(identifier_input_method_default).\n with_identifier_output_method(identifier_output_method_default)\n end", "def getters; end", "def data\n retrieve_data\n end", "def get(id)\n new(dataset.get(id))\n end", "def data_maker\n @data_maker ||= ::EdnaConsole::DataMaker.new(self.questions)\n end", "def data\n @data ||= aggregate\n end", "def data\n @data\n end", "def data\n @data\n end", "def data\n @data\n end", "def data\r\n @data\r\n end", "def data\n update_data\n @data\n end", "def flatten!\n self.class.attributes.keys.select { |k| k.end_with?('_data') }.each do |data_attr|\n reference_attr = data_attr[/(.+?)_data$/, 1]\n value = send(data_attr)\n next if value.nil?\n\n send(\"#{data_attr}=\", value)\n send(\"#{reference_attr})\", nil)\n end\n\n self\n end", "def this\n return @this if @this\n raise Error, \"No dataset for model #{model}\" unless ds = model.instance_dataset\n\n cond = if ds.joined_dataset?\n # SEQUEL5: Remove as joined model datasets are now allowed\n qualified_pk_hash\n else\n pk_hash\n end\n\n @this = use_server(ds.where(cond))\n end", "def data\n @datas\n end", "def create_setters\n schema_fields.keys.each do |key|\n self.class.send(:define_method, \"#{key.to_s}=\".to_sym) do |value| \n @data[key] = value #get_value key, value\n end\n end\n end", "def data_delegator(key)\n define_method(key.to_sym) { @obj.data[key] }\n end", "def call\n data\n end", "def create_accessors!\n instance.each do |key,val|\n create_accessor_for(key)\n end\n end", "def method_missing(sym, *args, &block)\n if self.data.respond_to?(sym)\n return self.data.send(sym, *args, &block)\n end\n\n super\n end", "def dataset_reader(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(attr_name)\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}\n dataset_get(:#{attr_name})\n end\n RUBY\n end\n end", "def _associated_dataset\n associated_class.dataset.clone\n end", "def method_missing(meth, *args, &block)\n if data.respond_to?(meth)\n return data.send(meth, *args, &block)\n else\n super\n end\n end", "def method_missing(method, *args, &block)\n data.send(method, *args, &block)\n end", "def initialize_accessor\n if @key_map\n self.define_singleton_method(:[], method(:get_row_by_map))\n self.define_singleton_method(:[]=, method(:set_row_by_map))\n else\n self.define_singleton_method(:[], method(:get_row_by_idx))\n self.define_singleton_method(:[]=, method(:set_row_by_idx))\n end\n end", "def data\n attributes.fetch(:data)\n end", "def data\n attributes.fetch(:data)\n end", "def data\n Facebooker::Data.new(self)\n end", "def get_data(columns=nil)\n @data\n end", "def get\n self\n end", "def data_attributes\n end", "def create_accessors(name, meth, options = {})\n field = fields[name]\n generated_field_methods.module_eval do\n if field.cast_on_read?\n define_method(meth) do\n field.get(read_attribute(name))\n end\n else\n define_method(meth) do\n read_attribute(name)\n end\n end\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n define_method(\"#{meth}?\") do\n attr = read_attribute(name)\n (options[:type] == Boolean) ? attr == true : attr.present?\n end\n end\n end", "def create_accessors!\n self.each do |key,val|\n create_accessor_for(key)\n end\n end", "def data\n self.load if @data.nil?\n @data\n end", "def get_data\n raise \"overwrite it\"\n end", "def create_getter\n @model.class_eval <<-EOS, __FILE__, __LINE__\n #{reader_visibility}\n def #{@getter}\n self[#{name.inspect}]\n end\n EOS\n end", "def data\n @data ||= aggregate(:single)\n end", "def access(value = nil)\n if value.nil?\n first.access\n else # set access\n each { |b| b.set_access(value) }\n self\n end\n end", "def set_private(data)\n res = super(self,data)\n return res\n end", "def valGetter\n \"#{DataMetaDom.getterName(@fld)}()\" + ( isMapping ? '.getKey()' : '')\n end", "def dalli\n @data\n end", "def clone\n\t\t\tCData.new self\n\t\tend", "def define_accessors\n self.metadata.properties_and_identity.each do |name, _|\n self.model.send :attr_accessor, name.downcase\n end\n end", "def values\n raise NotImplementedError, \"#{__method__} has not been implemented for this #{name} index\"\n end", "def read\n value = record.send(\"#{name}_data\")\n value unless value.nil? || value.empty?\n end", "def get_fields\n DatasetService.get_fields self.dataset_id, self.api_table_name\n end", "def create_getter!\n @target.class_eval <<-EOS\n #{reader_visibility.to_s}\n def #{name}\n attribute_get(#{name.inspect})\n end\n EOS\n \n if type == TrueClass\n @target.class_eval <<-EOS\n #{reader_visibility.to_s}\n def #{name.to_s.ensure_ends_with('?')}\n attribute_get(#{name.inspect})\n end\n EOS\n end\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def initialize data\n @data = data\n end", "def get\n Ata.get self\n end", "def data(_value=nil, _repair=false)\n raise NotImplementedError.new\n end", "def new_input_set()\n return GetReferenceDataInputSet.new()\n end", "def [](p1)\n #This is a stub, used for indexing\n end", "def method_missing(method, *args)\n return super if args.length > 1 or block_given?\n if args.length == 0\n return super unless data.has_key?(method)\n get method\n else\n set method, args[0]\n end\n end", "def cdr\n @value2\n end", "def field_accessors(name)\n field_reader(name)\n attr_writer(name)\n end", "def data= data \n end", "def data_policy_operations()\n return MicrosoftGraph::DataPolicyOperations::DataPolicyOperationsRequestBuilder.new(@path_parameters, @request_adapter)\n end" ]
[ "0.67281437", "0.64211106", "0.6259309", "0.60524756", "0.6001653", "0.597192", "0.597192", "0.597192", "0.58240175", "0.575634", "0.56876516", "0.5637037", "0.56338525", "0.56282914", "0.56139356", "0.561037", "0.56041664", "0.5582524", "0.55754375", "0.5575363", "0.5575363", "0.5510725", "0.5507717", "0.54956853", "0.54912674", "0.54912674", "0.54912674", "0.5489696", "0.5485503", "0.5485503", "0.5479749", "0.54789364", "0.5463009", "0.54275167", "0.5427481", "0.54233074", "0.5408442", "0.5402861", "0.5402861", "0.5402646", "0.53882957", "0.5378367", "0.5365828", "0.53619725", "0.5345211", "0.534078", "0.53379244", "0.5307142", "0.53067845", "0.5303532", "0.52973163", "0.5294113", "0.5294113", "0.5294113", "0.52839285", "0.5278308", "0.52532196", "0.5249364", "0.52483124", "0.5246481", "0.5231301", "0.521377", "0.52124906", "0.520748", "0.5195289", "0.51799846", "0.5169709", "0.5159914", "0.5136365", "0.51239103", "0.51239103", "0.51157343", "0.51013666", "0.50995064", "0.508646", "0.5085557", "0.50474817", "0.50438225", "0.5042538", "0.50340074", "0.5030866", "0.5029346", "0.50292957", "0.50287855", "0.5021124", "0.5019808", "0.5018582", "0.5015267", "0.49873728", "0.49849996", "0.4964904", "0.49584976", "0.49536338", "0.49461186", "0.49451166", "0.4936624", "0.49310312", "0.49302617", "0.49274302", "0.49271837", "0.49146843" ]
0.0
-1
declare a function with parameter "r"
def circleArea(r) # return PI * r^2 PI * r ** 2 # set end of circleArea function end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def r; end", "def r; end", "def setR(r)\r\n @r = r\r\n end", "def setR(method, *args)\n @r_interop = R::Support.exec_function_i(method, @r_interop, *args)\n self\n end", "def make_function(exp, register = true)\n name = map_name exp.shift\n args = exp.shift\n ruby_args = args.deep_clone\n ruby_args.shift # :args\n\n @method_name = name\n @c_method_name = \"rrc_c#{@c_klass_name}_#{normal_to_C name}\"\n\n @env.scope do\n c_args = check_args args, register # registered methods get self\n @methods[name] = ruby_args if register\n\n body = process exp.shift\n\n if name == :initialize then\n body[-1] = \"return self;\\n}\"\n end\n\n return \"static VALUE\\n#{@c_method_name}#{c_args} #{body}\"\n end\n end", "def _(*args)\n name = \"`%#{args.shift.to_s}%`\"\n args.unshift(@r_interop)\n R::Support.exec_function_name(name, *args)\n end", "def call_f(r)\n @f.arity > 1 ? @f.call(r, @attrs) : @f.call(r)\n end", "def arel_fn(name, *args)\n Arel::Nodes::NamedFunction.new(name, args)\n end", "def lr_function\n f = :pan\n case @modifiers\n when CONSTRAIN_MODIFIER_MASK\n f = :truck\n when COPY_MODIFIER_MASK\n f = :pan\n end\n f\nend", "def mrf; xparam(5); end", "def rec; sparam(2); end", "def fdr; sparam(8); end", "def circumference(r) #the scope of variable r only applies to the method circumference(r) this r is only passed to line 34\n 2 * pi * r\nend", "def f() 1 end", "def rut; end", "def use_function(name)\n call \"_#{name}\"\n end", "def fn\n Fn\n end", "def mrg; xparam(8); end", "def rra\n end", "def integrate(r,n,m = 'simpson')\n return nil unless self.ok?\n block = self.to_block(1)\n unless block == nil\n m = (m - '\"').downcase\n case m\n when \"trapezes\"\n return eval(\"Integrators.trapezi(r.sx,r.dx,n)#{block}\")\n when \"midpoint\"\n return eval(\"Integrators.simpson(r.sx,r.dx,n)#{block}\")\n when \"simpson\"\n return eval(\"Integrators.simpson(r.sx,r.dx,n)#{block}\")\n when \"rectl\"\n return eval(\"Integrators.rettsx(r.sx,r.dx,n)#{block}\")\n when \"rectr\"\n return eval(\"Integrators.rettdx(r.sx,r.dx,n)#{block}\")\n when \"boole\"\n return eval(\"Integrators.boole(r.sx,r.dx,n)#{block}\")\n else\n puts \"Argument Error: Invalid integration method\";\n return nil\n end\n end\n puts \"Argument Error: bad function for integration\";\n return nil\n end", "def foo(arg); end", "def initialize(rname)\n super\n @rname = rname\n end", "def f\n end", "def trg; xparam(9); end", "def PRF01=(arg)", "def _roda_run_main_route(r)\n _roda_main_route(r)\n end", "def my_method_param(name) #Define method \"my_method_param\"\n print \"Hello #{name}!\"\nend", "def module_function(sym, *rest) end", "def rrca\n end", "def FunctionCall(rest, parsed); end", "def PRF04=(arg)", "def tcr; sparam(5); end", "def mdr; sparam(7); end", "def create_function(function_name, returning, definition, options = {})\n\n end", "def x() @x end", "def init_r(str=nil)\n return true unless str\n begin\n r.eval_R(str)\n rescue Exception => e\n @error = e\n return false\n end\n end", "def my955; end", "def method_missing(func, *params)\n @reagent.send(func, *params) \n end", "def rla\n end", "def process_defn(exp)\n make_function exp\n end", "def returns=(_arg0); end", "def arg; end", "def x=(_arg0); end", "def x=(_arg0); end", "def x=(_arg0); end", "def run_function(name, params)\n payload = Payload.new\n payload.function_name = name\n payload.params = params\n call_route(:function, name, payload)\n end", "def foo (x)\nend", "def PRF02=(arg)", "def initialize(fun_name, args)\n @fun_name = fun_name\n @args = args\n @fun = Function.by_name_argnum fun_name, args.count\n end", "def call(*) end", "def call(*) end", "def _r_\n @r\n end", "def a(b)\nend", "def define; end", "def method_missing(meth, *args, &block)\n\t\t@r.send(meth, *args, &block)\n\tend", "def qrgen\n end", "def pdr; sparam(6); end", "def fstype=(_arg0); end", "def PRF03=(arg)", "def function(*args)\n Function.new(self, *args)\n end", "def function(*args)\n Function.new(self, *args)\n end", "def rn_custom; @rn_custom; end", "def x\n end", "def t_r(r,size)\n r * Math::sqrt(((size)-2).to_f / (1 - r**2))\n end", "def define\n end", "def define\n end", "def hrg; xparam(7); end", "def render r\n end", "def ri arg\n puts `ri #{arg}`\nend", "def rad _args\n \"rad _args;\" \n end", "def f1(x, x); end", "def /(arg0)\n end", "def /(arg0)\n end", "def f\n 1\n end", "def return_value=(_arg0); end", "def x; end", "def x; end", "def x; end", "def x; end", "def x; end", "def roar\n puts \"rooooar\"\nend", "def function!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 18 )\n\n\n\n type = FUNCTION\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n\n\n # - - - - main rule block - - - -\n # at line 39:11: 'receta'\n match( \"receta\" )\n\n\n\n @state.type = type\n @state.channel = channel\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 18 )\n\n\n end", "def x\n end", "def x\n end", "def declaration=(_arg0); end", "def r\n @r ||= RSRuby.instance\n end", "def dispatch(args = {})\n rjr_method = args[:rjr_method]\n\n # *note* not using concurrent access protection,\n # assumes all handlers/enviroments are registered\n # before first dispatch occurs\n handler = handler_for(rjr_method)\n environment = env_for(rjr_method)\n\n return Result.method_not_found(rjr_method) if handler.nil?\n\n request = Request.new args.merge(:rjr_handler => handler)\n\n # set request environment\n request.set_env(environment) unless environment.nil?\n\n begin\n retval = request.handle\n request.result = Result.new(:result => retval)\n\n rescue Exception => e\n warning = \"Exception Raised in #{rjr_method} handler #{e}\"\n RJR::Logger.warn [warning] + e.backtrace\n\n request.result = Result.new(:error_code => -32000,\n :error_msg => e.to_s,\n :error_class => e.class)\n end\n\n store_request request\n return request.result\n end", "def a \n return 1\nend", "def method_missing(name, *args)\n raise \"MethodMissing loop when searching for #{name} with #{args.inspect}\" if searching_for_method?\n @searching_for_method = true\n return create_resource(name, args[0], args[1]) if valid_type?(name)\n\n name = map_function(name)\n\n return call_function(name, args) if Puppet::Parser::Functions.function(name)\n\n super\n ensure\n @searching_for_method = false\n end", "def r(filename)\n require \"./#{filename}\"\nend", "def exr; sparam(9); end", "def jr_method(*args)\n @jr_method_args ||= []\n @jr_method_args << args\n end", "def method_name=(_arg0); end", "def method_name=(_arg0); end", "def mev; xparam(4); end", "def LCR\n attr_reader :value\n def initialize(?) # Indique los argumentos\n# Su c ́odigo aqu ́ı end\n def each(p)\n# Su c ́odigo aqu ́ı\n end\n def solve\n# Su c ́odigo aqu ́ı\n end\n end\n\n ##################################################### L C R\n\n end", "def method a = 3\r\nend", "def my_func(f)\n\t(f - 32) * 5/9\nend", "def computeArea(r) #Call to create function computeArea with parameter r\n PI * r ** 2 #Calculates the area using parameter r and constant pi\nend", "def m\nend", "def m\nend" ]
[ "0.6568186", "0.6568186", "0.6134554", "0.5840588", "0.58327186", "0.57965195", "0.55696076", "0.554189", "0.5514058", "0.54656667", "0.53988093", "0.5373943", "0.5366967", "0.5266914", "0.5261096", "0.52348727", "0.52191013", "0.52098393", "0.5208977", "0.5196114", "0.5173059", "0.5169601", "0.51599634", "0.5143445", "0.51289594", "0.5127168", "0.51257503", "0.5123789", "0.50992936", "0.5094436", "0.5089618", "0.50764203", "0.50696385", "0.5055494", "0.5044974", "0.503968", "0.5036632", "0.5003011", "0.49997526", "0.49973828", "0.49946767", "0.49812007", "0.49756122", "0.49756122", "0.49756122", "0.4975604", "0.49729508", "0.49492985", "0.4942593", "0.49367192", "0.49367192", "0.49272043", "0.49261817", "0.49009004", "0.48983765", "0.4894034", "0.48898882", "0.48771602", "0.48710373", "0.48701313", "0.48701313", "0.48681298", "0.4867482", "0.48633918", "0.48585626", "0.48585626", "0.48584592", "0.4858303", "0.48566908", "0.48512146", "0.48467007", "0.48460755", "0.48460755", "0.48433226", "0.48395604", "0.48395026", "0.48395026", "0.48395026", "0.48395026", "0.48395026", "0.48283333", "0.482694", "0.48255762", "0.48255762", "0.48167786", "0.48149106", "0.47996935", "0.47971871", "0.47959438", "0.47950754", "0.47946152", "0.47910458", "0.4789302", "0.4789302", "0.47838658", "0.47793815", "0.4779291", "0.47792238", "0.4777452", "0.47752732", "0.47752732" ]
0.0
-1
kind: 'preflop', 'flop', 'turn', 'river', 'showdown', 'exchange'
def initialize(attributes) @kind = attributes[:kind].to_s @players_count = (attributes[:players_count] || 0) @previous_pot = (attributes[:previous_pot] || 0) @cards = Utils::Cards.parse(attributes[:cards]) @board = attributes[:board] || [] @events = [] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show_flop\r\n show_hand\r\n end", "def normal_interactions\n [ Question, Fine, Woah ]\n end", "def kind; end", "def kind; end", "def kind; end", "def kind; end", "def kind; end", "def kind; end", "def kase_kinds\n [:idea, :question, :problem, :praise]\n end", "def chord_types; end", "def kind!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 24 )\n\n type = KIND\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 158:8: 'kind'\n match( \"kind\" )\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 24 )\n\n end", "def potion; end", "def stadium; end", "def kind\n if @side_a == @side_b && @side_a == @side_c\n :equilateral\n elsif @side_a == @side_b || @side_b == @side_c || @side_c == @side_a\n :isosceles\n else\n :scalene\n end\n end", "def food_and_drink; end", "def dish; end", "def two_player_mode\nend", "def game_mode; end", "def spouse; end", "def exchange\n :rock\n end", "def witcher; end", "def ai_one_logic(player)\n type = player.ai\n if self.round == 0\n if self.high_bet < 5\n return 'call', 0\n else\n return 'fold', 0\n end\n else\n if self.high_bet == 0\n return 'bet', 2\n elsif self.high_bet < 4\n return 'raise', 4\n elsif self.high_bet >= 16\n return 'fold', 0\n else\n return 'call', 0\n end\n end\n end", "def who_we_are\r\n end", "def battle_mode args\r\n\t#Selects a specific screen output function\r\n\tcase args.state.screen_select\r\n\t\twhen 2.1\r\n\t\t\tSS2_1 args\r\n\t\twhen 2.2\r\n\t\t\tSS2_2 args\r\n\t\twhen 2.3\r\n\t\t\tSS2_3 args\r\n\t\twhen 2.4\r\n\t\t\tSS2_4 args\r\n\t\twhen 2.5\r\n\t\t\tSS2_5 args\r\n\t\twhen 2.6\r\n\t\t\tSS2_6 args\r\n\tend\r\nend", "def chord; end", "def nature; end", "def modes; end", "def alternatives; end", "def skier_quest; end", "def variety; end", "def variety; end", "def set_kind(kind)\n\t\tend", "def kind\n @pokers.size > 3 ? 4 : @pokers.size\n end", "def factions\n \n end", "def mode_desc\n case mode\n when 'single' then 'each'\n when 'bracketed' then \"for #{volume} or more\"\n when 'boxed' then \"for every #{volume}\"\n end\n end", "def decide(hand)\n value(hand) >= 17 && :stand || :hit\nend", "def outcome\n if (pl_high? || session[:dealer].bust?) && !session[:player].bust?\n outcome = :player\n elsif session[:player].blackjack? && !session[:dealer].blackjack?\n outcome = :blackjack\n session[:player].qualities << \"lucky\"\n elsif push?\n outcome = :push\n else\n outcome = :dealer\n end\n outcome\n end", "def declare_signals\n self.signal_connect(:clicked){|choiced|\n click_used = false\n if choiced.label_widget.markup == $glob.null_markup\n if $player.act_p.human?\n $last_btn = choiced\n $glob.num_moves += 1\n choiced.label_widget.set_markup($player.act_p.mark_markup)\n $player.switch_player\n click_used = true\n check_victory\n end\n if !$player.act_p.human? and click_used and $glob.num_moves < 8\n choiced = $player.act_p.turn\n $last_btn = choiced\n choiced.label_widget.set_markup($player.act_p.mark_markup)\n $player.switch_player\n check_victory\n end\n end\n } \n end", "def get_kind\n\t\tend", "def quest; end", "def kind\n [:default, :bar, :baz][ self[:kind] ]\n end", "def trader; end", "def musician; end", "def musician; end", "def kind_enum\n\t\t['讲座沙龙','校园文化','竞赛创新','实践公益','其他']\n\tend", "def kind\n # returns nil, overridden and returning :question, :problem, etc. in sublcass\n end", "def kind\n :piggy_bank\n end", "def draw_tactic_overview\n end", "def play\n $game.surface.+$game.white.get('Ant')\n $game.surface.+$game.black.get('Beetle')\n $game.surface.+($game.white.get('Ant'), $game.surface.bug(Hive::Color[:white], Bug::Type[:ant1]), Side::Face[:bottom_left])\n #$game.surface.+($game.black.get('Grasshopper'), $game.surface.bug(Hive::Color[:black], Bug::Type[:beetle1]), Side::Face[:bottom_left])\n $game.surface.+($game.black.get('Grasshopper'), $game.surface.bug(Hive::Color[:black], Bug::Type[:beetle1]), Side::Face[:top_right])\n $game.surface.+($game.white.get('Ant'), $game.surface.bug(Hive::Color[:white], Bug::Type[:ant2]), Side::Face[:bottom_right])\n $game.surface.+($game.black.get('Queen'), $game.surface.bug(Hive::Color[:black], Bug::Type[:grasshopper1]), Side::Face[:top_right])\n $game.surface.+($game.white.get('Queen'), $game.surface.bug(Hive::Color[:white], Bug::Type[:ant3]), Side::Face[:bottom_right])\n $game.surface.+($game.black.get('Grasshopper'), $game.surface.bug(Hive::Color[:black], Bug::Type[:queen1]), Side::Face[:top_right])\n $game.surface.+($game.white.get('Spider'), $game.surface.bug(Hive::Color[:white], Bug::Type[:queen1]), Side::Face[:bottom_center])\n $game.surface.bug(Hive::Color[:black], Bug::Type[:grasshopper2]).move(Hive::Color[:black], Bug::Type[:beetle1], Side::Face[:bottom_left])\n $game.surface.bug(Hive::Color[:white], Bug::Type[:ant2]).move(Hive::Color[:black], Bug::Type[:queen1], Side::Face[:bottom_center])\n $game.surface.+($game.black.get('Grasshopper'), $game.surface.bug(Hive::Color[:black], Bug::Type[:beetle1]), Side::Face[:top_center])\n \n # Try putting a $game.list_moves after any move directive\n\n puts \"\\n\\n=====PROOF SECTION=======================\"\n $game.surface.bug(Hive::Color[:black], Bug::Type[:beetle1]).describe\n $game.surface.bug(Hive::Color[:black], Bug::Type[:grasshopper1]).describe\n $game.surface.bug(Hive::Color[:black], Bug::Type[:grasshopper2]).describe\n $game.surface.bug(Hive::Color[:black], Bug::Type[:grasshopper3]).describe\n $game.surface.bug(Hive::Color[:black], Bug::Type[:queen1]).describe\n \n $game.surface.bug(Hive::Color[:white], Bug::Type[:ant1]).describe\n $game.surface.bug(Hive::Color[:white], Bug::Type[:ant2]).describe\n $game.surface.bug(Hive::Color[:white], Bug::Type[:ant3]).describe\n $game.surface.bug(Hive::Color[:white], Bug::Type[:queen1]).describe\n $game.surface.bug(Hive::Color[:white], Bug::Type[:spider1]).describe\n end", "def choose\n self.move = %w(spock lizard).sample\n end", "def mode; end", "def mode; end", "def mode; end", "def mode; end", "def kind\n :activity\n end", "def drive(where)\n case where\n when :forward,:forwards\n @backwards_pin.set(0)\n @forwards_pin.set(1)\n when :backwards,:backward\n @forwards_pin.set(0)\n @backwards_pin.set(1)\n else\n @forwards_pin.set(0)\n @backwards_pin.set(0)\n end\n end", "def ingverb; end", "def action(type, amount, player)\n @player = Player.find(player.to_i)\n amount = amount.to_i\n case type\n when 'fold'\n @player.in_hand = false\n when 'bet'\n if amount > @player.money\n amount = @player.money\n end\n if amount + @player.in_pot_current < self.high_bet\n p 'invalid bet'\n else\n put_money(amount, @player)\n end\n when 'raise'\n # If player doesn't have enough money or trying to not raise enough and can't bet enough\n if amount > @player.money || (amount + @player.in_pot_current < 2*self.high_bet && 2*self.high_bet - @player.in_pot_current > @player.money)\n amount = @player.money\n elsif amount + @player.in_pot_current < self.high_bet\n amount = 2*self.high_bet - @player.in_pot_current\n else\n amount = amount + self.high_bet - @player.in_pot_current\n end\n put_money(amount, @player)\n when 'check'\n # do nothing; high better already set to be player after dealer inside of deal()\n when 'call'\n amount = self.high_bet - @player.in_pot_current\n put_money(amount, @player)\n else\n p 'invalid action'\n end\n self.current_player = self.get_next_player(@player.location) # Set next player to current\n\n @player.save\n self.save\n if self.high_better == self.current_player #progress round if you've gone back around to the high better\n # unless no one raises and it's back to big blind, bb should be able to go\n if self.high_bet <= self.big_blind && self.round == 0 && self.high_better == get_next_player(get_next_player(self.dealer))\n self.high_better = get_next_player(get_next_player(get_next_player(self.dealer)))\n else\n set_round((self.round + 1))\n deal(self.round)\n end\n end\n if self.players.where(:in_hand => true).length <= 1\n set_round(4)\n end\n\n @player.save\n self.save\n end", "def specie; end", "def specie; end", "def specie; end", "def specie; end", "def direction; end", "def direction; end", "def available_pitches(event)\n\t\tchord_choices = @score_book[event][0]\n\t\treturn chord_choices\n\tend", "def computer_choose_aggressive(board)\n choose_field_next_to_two(MARK_O, board)\nend", "def choose\n \n end", "def wagner; end", "def choose_winner; end", "def flow\n end", "def starship; end", "def channel_did_gain_property(stem, channel, property, argument, bestower)\n end", "def pile_cards\n if type == :basic\n basic_pile\n elsif type == :war\n war_pile\n elsif type == :mutally_assured_destruction\n destruction_pile\n end\n end", "def on_hand\n variant.on_hand\n end", "def move_diffs\n\t\tcase type\n\t\twhen :man\n\t\t\t[[forward, 1], [forward, -1]]\n\t\twhen :king\n\t\t\t[-1, 1].product([-1, 1])\n\t\tend\n\tend", "def whiny; end", "def type\n\n if @player_1.deck.cards[0].rank != @player_2.deck.cards[0].rank\n return :basic\n elsif @player_1.deck.cards[2].rank == @player_2.deck.cards[2].rank\n return :mutually_assured_destruction\n else\n return :war\n end\n end", "def board_mode args\r\n\t#Selects a specific screen output function\r\n\tcase args.state.screen_select\r\n\t\twhen 1.1\r\n\t\t\tSS1_1 args\r\n\t\twhen 1.2\r\n\t\t\tSS1_2 args\r\n\t\twhen 1.3\r\n\t\t\t#Resets randomNumber\r\n\t\t\targs.state.randomNumber = 0\r\n\t\t\targs.state.spaces_moved = 0\r\n\t\t\tSS1_3 args\r\n\t\twhen 1.4\r\n\t\t\tSS1_4 args\r\n\tend\r\nend", "def computer_choose_defensive(board)\n choose_field_next_to_two(MARK_X, board)\nend", "def bike_type(type)\n if type == 1\n @discipline = \"mountain\"\n @frame = \"mountain\"\n elsif type == 2\n @discipline = \"road\"\n @frame = \"road\"\n else\n @discipline = \"cyclo-cross\"\n @frame = \"cyclo-cross\"\n end\n @discipline\n @frame\n end", "def says (opinion)\n puts \"#{name} says #{opinion}\"\n end", "def coin_option ( opponent_flip )\n @coin_option = (opponent_flip == \"HEADS\") ? \"TAILS\" : \"HEADS\"\n end", "def current_opponent_effect_descriptors\n []\n end", "def setup_flip\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n if @acts[1] == :toggle\n @flip = !@flip \n elsif @acts[1] == :ori\n @flip = default_flip\n else\n @flip = @acts[1]\n end\n end", "def dismissal_methods_for(delivery)\n return '' unless delivery.key?('wicket')\n dismissals_for(delivery).map { |dismissal| dismissal['kind'] }.join(', ')\nend", "def flamegraph_mode; end", "def verb; end", "def verb; end", "def verb; end", "def verb; end", "def verb; end", "def strikes\r\n @pitches.select{|pitch| pitch.outcome == 'S'}\r\n end", "def kind\n type.to_s.underscore[5..-1]\n end", "def play\r\n display_welcome_message\r\n human_choose_move\r\n computer_choose_move\r\n display_winner\r\n display_goodbye_message\r\nend", "def flipFlop(cost, color)\n\tcase color.downcase \n\twhen \"yellow\" \n\t\tputs \"Order the AK-47 flip flop for $#{cost}\"\n\twhen \"red\" \n\t\tputs \"Order the Tuck Tuck flip flop for $#{cost}\"\n\twhen \"blue\" \n\t\tputs \"Order the Posidon flip flop for $#{cost}\"\n\twhen \"black\" \n\t\tputs \"Order the Bombshell Dark flip flop for $#{cost}\"\n\telse\n\t\tputs \"As of 22MAR14 they didn't have #{color}. Check their site for updates.\"\n\tend\nend", "def switch(name,aliases,desc,long_desc,negatable)\n abstract!\n end", "def check_win_or_lose\n # returns one of the symbols :win, :lose, or :play depending on the current game state\n \n end", "def solo; end", "def pound_sterling(pence); end", "def display_choices(monster) \n monster.display_moves << \"or type (Q)uit to give up.\"\n end", "def prapor_quest; end" ]
[ "0.5995832", "0.59265536", "0.5804005", "0.5804005", "0.5804005", "0.5804005", "0.5804005", "0.5804005", "0.57620907", "0.5714421", "0.56148887", "0.55120504", "0.5486864", "0.5480728", "0.5459612", "0.5457901", "0.5457008", "0.5439573", "0.5426686", "0.54238695", "0.5393056", "0.5387901", "0.5368686", "0.5354169", "0.5353232", "0.5342509", "0.5329537", "0.52941626", "0.529271", "0.5285634", "0.5285634", "0.525465", "0.52451706", "0.52450013", "0.5242249", "0.5236438", "0.5232222", "0.523181", "0.52238154", "0.5211141", "0.51908576", "0.5189897", "0.5188784", "0.5188784", "0.5183149", "0.51745284", "0.51704204", "0.5165834", "0.5161998", "0.5151667", "0.5137671", "0.5137671", "0.5137671", "0.5137671", "0.513683", "0.51329195", "0.5131879", "0.5121925", "0.5121733", "0.5121733", "0.5121733", "0.5121733", "0.5119968", "0.5119968", "0.5118008", "0.51086897", "0.51030606", "0.5101669", "0.50974107", "0.5095962", "0.5095431", "0.5089452", "0.50790226", "0.50773233", "0.50671434", "0.5061392", "0.50564325", "0.50548726", "0.5051149", "0.5049656", "0.5047413", "0.50399745", "0.5028979", "0.50274086", "0.5021891", "0.5017243", "0.5016017", "0.5016017", "0.5016017", "0.5016017", "0.5016017", "0.5015117", "0.50128716", "0.50125223", "0.50045276", "0.500427", "0.50022346", "0.5001451", "0.5000028", "0.49994037", "0.49972817" ]
0.0
-1
sets appriate fields to nil on artist and returns a new rejection object
def switch_thing(thing, act) if thing == ARTICLE_TITLE || thing == SUMMARY data = self.article_title self.summary = nil self.article_title = nil self.rejections() << Rejection.new_from_rejecting(Artist::ARTICLE_TITLE, data) if act == Artist::REJECT elsif thing == SAMPLE_TRACK_URL data = sample_track_url self.sample_track_url = nil self.rejections() << Rejection.new_from_rejecting(thing, data) if act == Artist::REJECT elsif thing == WEBSITE data = website self.website = nil self.rejections() << Rejection.new_from_rejecting(thing, data) if act == Artist::REJECT elsif thing == MYSPACE_URL data = myspace_url self.myspace_url = nil self.rejections() << Rejection.new_from_rejecting(thing, data) if act == Artist::REJECT end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reject\n self['reject']||{}\n end", "def artist\n art = super\n if art.nil?\n art = Artist.new\n art.title = \"Unknown Artist\"\n end\n art\n end", "def new_artist_or_nah(request_artist)\n artist = Artist.find_by name: request_artist\n if artist == nil\n Artist.create(name: request_artist)\n else\n artist\n end \n end", "def reject\n fog_model.reject\n end", "def reject\n self[:status] = \"Reject\"\n save\n end", "def create\n @artist.skip_unapproval = true\n if params[:artist][:approved]\n @artist.approver_id = current_user.id\n end\n @artist.initial_brand = website.brand\n @artist.skip_confirmation!\n @artist_brand = ArtistBrand.new(params.require(:artist_brand).permit(:artist_id, :brand_id, :intro))\n respond_to do |format|\n if @artist.save\n @artist_brand.artist_id = @artist.id\n @artist_brand.brand_id = website.brand_id\n @artist_brand.save\n format.html { redirect_to([:admin, @artist], notice: 'Artist was successfully created.') }\n format.xml { render xml: @artist, status: :created, location: @artist }\n website.add_log(user: current_user, action: \"Created artist #{@artist.name}\")\n else\n format.html { render action: \"new\" }\n format.xml { render xml: @artist.errors, status: :unprocessable_entity }\n end\n end\n end", "def infer_album_artist_from_track_data\n if track_artists().length == 1\n self.artist = track_artists()[0]\n \n @tracks.each do |track|\n track.artist = nil\n end\n else\n raise \"No album artist could be inferred.\"\n end\n end", "def create\n @artwork = Artwork.unpublished.new(new_artwork_params)\n @artwork.artist = Artist.find_or_initialize_by name: artist_params[:artist_name]\n\n #add transaction if needed\n respond_to do |format|\n if @artwork.save\n format.html { redirect_to @artwork, notice: 'Artwork was successfully created.' }\n format.json { render :show, status: :created, location: @artwork }\n else\n format.html { render :new }\n format.json { render json: @artwork.errors, status: :unprocessable_entity }\n end\n end\n end", "def artist_name\n if self.artist == nil \n nil \n else self.artist.name \n end \nend", "def reject!\n super { |r| yield(r) && orphan_resource(r) }\n end", "def create\n @product = Product.new(params[:product])\n authorize! :create, @product\n\n @product.artist = Artist.find_or_initialize_by_name(params[:artist][:name]) \n\n respond_to do |format|\n if @product.save\n format.html { redirect_to @product, notice: 'Product was successfully created.' }\n format.json { render json: @product, status: :created, location: @product }\n else\n format.html { render action: \"new\" }\n format.json { render json: @product.errors, status: :unprocessable_entity }\n end\n end\n end", "def rejected_exception\n @rejected_exception&.object\n end", "def reject!(user_id)\n if self.rejected_at.nil?\n self.update_attributes(rejected_at: Time.now, approved_at: nil, user: user_id)\n end\n self\n end", "def to_message\n ArtistMessage.new(\n id: id,\n name: name,\n bio: bio,\n genre: genre\n )\n end", "def reject(*)\n super.tap do\n __debug_sim('USER must make change(s) to complete the submission.')\n end\n end", "def update\n super\n if resource.errors.empty?\n save_creator_genre(resource)\n end\n end", "def artist_name\n self.try(:artist).try(:name)\n end", "def artist_name\n self.try(:artist).try(:name)\n end", "def artist_name\n self.try(:artist).try(:name)\n end", "def reject!(response_data={})\n @client.post(\"#{path}/reject\", response_data)\n end", "def reject\n self.update_attributes(:status => REJECTED)\n end", "def initialize(name, artist = nil, genre = nil)\n @name = name\n self.artist = artist if artist #Set (self) or song.artist to artist if artist !nil \n self.genre = genre if genre #Set (self) or song.genre to genre if genre !nil\n save \n end", "def create\n @params = format_params(artist_params)\n @artist = Artist.new(@params)\n @result = ArtistCommander.process_new_artist(@artist)\n if @result[:type] == \"error\"\n flash[:error] = @result[:value]\n redirect_to '/artists/new'\n else\n @artist.save\n associate_artist_albums\n respond_to do |format|\n @artist.save\n format.html { redirect_to @artist, notice: \"Artist was successfully created.\" }\n format.json { render :show, status: :created, location: @artist }\n end\n end\n end", "def to_message\n ArtistMessage.new(\n :id => self.id,\n :name => self.name,\n :bio => self.bio,\n :genre => self.genre\n )\n end", "def set_artist\n\n\tartist = Artist.find_by_artist_name(self.artist_name)\n\t if artist != nil \n\t\t self.artist_name = artist\n\t\t return true\n\t else\n\t\terrors.add_to_base(\"combination of: 'artist_name' is invalid- it must be unique\")\n\t\t return false\n\tend\nend", "def reject\n copy self.class.reject(@id)\n true\n end", "def reject\n copy self.class.reject(@id)\n true\n end", "def resolve(**args)\n product = Product.create(title: args[:title], description: args[:description])\n {\n product: product,\n result: product.errors.blank?\n }\n end", "def artist=(v)\n if @artist != v\n @needs_commit = true\n @artist = v\n end\n end", "def reject(id)\n end", "def create\n @artist = Artist.new(artist_params)\n\t@artist.total_donation = 0\n\tif @artist.photo.empty? || @artist.photo.nil?\n\t\t@artist.photo = \"no_image.png\"\n\tend\n\t\n respond_to do |format|\n if @artist.save\n format.html { redirect_to @artist, notice: 'Artist was successfully created.' }\n format.json { render :show, status: :created, location: @artist }\n else\n format.html { render :new }\n format.json { render json: @artist.errors, status: :unprocessable_entity }\n end\n end\n end", "def reject\n email = Email.find(params[:id])\n email.state = \"Rejected\"\n email.reject_reason = params[:reject_reason]\n if email.save!\n head :no_content\n else\n respond_with email, status: :unprocessable_entity\n end\n end", "def create\n @profil_artiste = ProfilArtiste.new(profil_artiste_params)\n @profil_artiste.artiste_id = current_artiste.id\n respond_to do |format|\n if @profil_artiste.save\n format.html { redirect_to @profil_artiste, notice: 'Profil artiste was successfully created.' }\n format.json { render :show, status: :created, location: @profil_artiste }\n else\n format.html { render :new }\n format.json { render json: @profil_artiste.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # Hack? How to do this better...\n params[:song][:genre] = Genre.find(params[:song][:genre_id])\n params[:song].delete(:genre_id)\n params[:song][:artist] = @artist\n @song = Song.new(params[:song])\n\n respond_to do |format|\n if @song.save\n format.html { redirect_to [@artist, @song], notice: 'Song was successfully created.' }\n format.json { render json: @song, status: :created, location: @song }\n else\n format.html { render action: \"new\" }\n format.json { render json: @song.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @absent = Absent.new\n @absent.reason = \"\"\n end", "def rejection(recipient, listing_title, listing_id)\n subject \"Your listing \\'#{listing_title}\\' has been reject. Please edit and resubmitted.\"\n recipients recipient\n from 'Project Bordeaux No-Reply <no-reply@appfactory.us>'\n sent_on Time.now\n body :url => FB_APP_HOME_URL, :listing_title => listing_title, :listing_id => listing_id\n end", "def artist\n if artists.nil?\n Artist.new :name => super\n elsif artists.size > 1\n artists\n else\n artists.first\n end\n end", "def reject\n throw :reject\n end", "def set_artist\n @artist = Artist.resolve(params[:id])\n end", "def new \n @artist = Artist.new\n end", "def reject\n transition_to :rejected\n end", "def miss_reason; end", "def create\n @artist = Artist.find_or_create_by(artist_name: artist_params[:artist_name])\n @artist.update(artist_params)\n gon.artist = @artist\n end", "def error(on_rejected)\n self.then(nil, on_rejected)\n end", "def new\n if !@artist\n @artist = current_user.artists.find(params[:id])\n end\n @album = Album.new\n end", "def initialize\n self.qual = false\n end", "def reject!\n raise RejectMessage\n end", "def initialize(name, artist = nil, genre = nil)\n @name = name\n #invokes #artist= (not setting @artist instance variable) to ensure that associations are created upon initialization\n self.artist=(artist) if artist != nil\n self.genre=(genre) if genre != nil\n end", "def reject\n @locale_entry.approved = false\n @locale_entry.reviewer = current_user\n @locale_entry.save!\n\n respond_with @source_entry, @locale_entry, location: glossary_source_locales_url\n end", "def reject(&blk); end", "def initialize(name, artist = nil, genre = nil)\n @name = name\n self.artist = artist if artist\n self.genre = genre if genre\n end", "def artist_name\n nil\n end", "def new\n @artist = Artist.new\n end", "def not_author_response\n if author_respondent?\n errors[:author] << 'cannot answer their own poll'\n end\n end", "def reject\n @company = Company.find(params[:id])\n if @company.reject!\n respond_with @company\n else\n respond_with @company, status: :unprocessable_entity\n end\n end", "def reject(&block); end", "def artist\n super\n end", "def reject!(user = nil)\n run_callbacks :rejection do\n self.rejected_at = Time.now\n self.rejecter = user if user\n self.status = 'rejected'\n self.save!\n self.order_items.each(&:reject!)\n deliver_rejected_order_email\n end\n end", "def create\n @Qualification = Qualification.new(parse_qualification_params)\n\n unless @qualification.save\n @qualification.errors.full_messages.each do |msg|\n add_request_error(title: msg)\n end\n render status: :unprocessable_entity\n end\n end", "def create\n redirect_to new_album_path, alert: \"You have to select at least one artist.\" and return if params[:album][:album_artists].size == 1 && params[:album][:album_artists][0].empty? # TODO: Find a better way to do this, it does not play nicely with json and xml\n @album = Album.new(album_params)\n album_artists\n album_cover if params[:search_online]\n\n respond_to do |format|\n if @album.save\n format.html { redirect_to @album, notice: 'Album was successfully created.' }\n format.json { render :show, status: :created, location: @album }\n format.xml { render xml: @album, status: :created }\n else\n format.html { render :new }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n format.xml { render xml: @album.errors, status: :unprocessable_entity }\n end\n end\n end", "def parse_qualification_params\n create_params = params\n .require(:qualification)\n .permit(:qualification_id, :qualified, :comment)\n\n unless (qualification = Qualification.where(id: create_params[:qualification_id]).first)\n add_request_error(title: I18n.t('api.request.errors.qualification_not_found'))\n end\n\n {\n user: 1,\n qualification: qualification,\n qualified: create_params[:qualified],\n comment: create_params[:comment]\n }.keep_if { |_, v| v.present? }\n end", "def artist_name\n if self.artist == nil\n nil\n else\n self.artist.name\n end\n end", "def artist_params\n params.require(:artist).permit(:name, :description)\n end", "def should_reject(attributes)\n\t\tif attributes[:id].present?\n\t\t\treturn false\n\t\telsif attributes[:image].blank?\n\t\t\treturn true\n\t\telse\n\t\t\treturn false\n\t\tend\n\tend", "def create_artist(node)\n if node.attributes['id'] and @artists[node.attributes['id']]\n artist = @artists[node.attributes['id']]\n else\n artist = @factory.new_artist\n @artists[node.attributes['id']] = artist\n end\n \n # Read all defined data fields\n artist.id = node.attributes['id']\n if node.attributes['type']\n artist.type = Utils.add_namespace(node.attributes['type'])\n end\n \n artist.name = node.elements['name'].text if node.elements['name']\n artist.sort_name = node.elements['sort-name'].text if node.elements['sort-name']\n artist.disambiguation = node.elements['disambiguation'].text if node.elements['disambiguation']\n \n if life_span = node.elements['life-span']\n artist.begin_date = read_date_attribute(life_span, 'begin')\n artist.end_date = read_date_attribute(life_span, 'end')\n end\n \n # Read the alias list\n read_alias_list(node.elements['alias-list'], artist.aliases)\n \n # Read the release list\n read_release_list(node.elements['release-list'], artist.releases) {|release|\n release.artist = artist unless release.artist\n }\n \n # Read the relation list\n if node.elements['relation-list']\n node.elements.each('relation-list') {|relation_node|\n read_relation_list(relation_node) {|relation|\n artist.add_relation relation\n }\n }\n end\n \n # Read the tag list\n read_tag_list(node.elements['tag-list'], artist.tags)\n \n return artist\n end", "def artist_params\n params.require(:artwork).permit(:artist_name)\n end", "def reject(&block)\n @reject = block if block\n @reject\n end", "def artist_name\n if self.name \n self.name\n else \n nil\n end \n end", "def artist\n\t\tartists == nil ? nil : artists.first\n\tend", "def create\n @user_artist = UserArtist.new\n\t@artist = Artist.find params[:artist_id]\n\t@user_artist.user_id = @current_user.id\n\t@user_artist.artist_id = @artist.id\n\t\n respond_to do |format|\n if @user_artist.save\n format.html { redirect_to @artist, notice: 'User artist was successfully created.' }\n format.json { render :show, status: :created, location: @user_artist }\n else\n format.html { render :new }\n format.json { render json: @user_artist.errors, status: :unprocessable_entity }\n end\n end\n end", "def artist_params\n params.require(:artist).permit(:name, :image_link, :biography)\n end", "def artist_name\n if self.artist\n self.artist.name\n else\n nil\n end\n end", "def reject_answer(attributes)\n exists = attributes[:id].present?\n if exists and attributes[:content].blank?\n attributes.merge!({ :_destroy => 1 })\n end\n\n return (!exists and attributes[:content].blank?)\n end", "def reject(reason: nil, **keyword_args)\n append(Reject.new(reason: reason, **keyword_args))\n end", "def artist_params\n params.require(:artist).permit(:artist_name, :artist_same, :artist_score)\n end", "def artist_params\n params.fetch(:artist, {})\n end", "def drake_made_this\n drake = Artist.find_or_create_by(name: \"Drake\")\n self.artist = drake\n end", "def reject\n\t\t@article = Article.find(params[:id])\n\n\t\tif @article.state == 1\n\t if params[:article][:message]\n\t @article.state = 2\n\t @article.message = params[:article][:message] \n\t @article.freezebody = @article.title + \"\\n\\n\" + @article.teaser + \"\\n\\n\" + @article.body + \"\\n\\n\" + @article.version + \"\\n\\n\" + @article.changelog\n\t \n\t if @article.save\n\t flash[:notice] = \"The artile was rejected.\"\n\t redirect_to :action => 'articles', :state => 1\n\t else\n\t render :action => \"editreject\"\n\t end \n\t else\n\t flash[:notice] = \"No reject without reject message.\"\n\t redirect_to :action => 'articles', :state => 1\n\t end\n\t else\n\t flash[:notice] = \"Only submitted articles can be rejected.\"\n\t redirect_to :action => 'articles', :state => 1\n\t end \n\tend", "def artist_params\n params.require(:artist).permit(:artist_name)\n end", "def decline\n request = ErrandRequest.find params[:id]\n if not request.nil? and request.errand.user_id == env['warden'].user.id\n request.declined = true\n request.save!\n render json: {ok: true}\n else\n render json: \"\", status: 404\n end\n end", "def artist_params\n params.require(:artist).permit(:name)\n end", "def initialize(song_name, song_artist = nil, song_genre = nil)\n @name = song_name\n song_artist != nil ? self.artist=(song_artist) : return\n song_genre != nil ? self.genre=(song_genre) : return\n end", "def artist=(artist)\n @artist = artist\n end", "def update\n # render text: params[:artist].to_yaml\n params[:artist][:skip_unapproval] = true\n if !!(params[:artist][:approved].to_i > 0)\n params[:artist][:approver_id] = current_user.id\n else\n params[:artist][:approver_id] = nil\n end\n @artist_brand = ArtistBrand.where(artist_id: @artist.id, brand_id: website.brand_id).first_or_create\n respond_to do |format|\n if @artist.update(artist_params)\n @artist_brand.update(params.require(:artist_brand).permit(:artist_id, :brand_id, :intro))\n format.html { redirect_to([:admin, @artist], notice: 'Artist was successfully updated.') }\n format.xml { head :ok }\n website.add_log(user: current_user, action: \"Updated artist: #{@artist.name}\")\n else\n format.html { render action: \"edit\" }\n format.xml { render xml: @artist.errors, status: :unprocessable_entity }\n end\n end\n end", "def artists(artist)\n if song.artist = nil || !Artist.find_by_name(name)\n song.artist = artist \n Artist.all << artist \n end \n end", "def deny!(kind, name, attributes = {})\n deny(kind, name, attributes).save\n end", "def reject(&block)\n new_instance_with_inherited_permitted_status(@parameters.reject(&block))\n end", "def attributes\n sanitized_values = self.to_h.dup\n sanitized_values[:access_token] = 'REDACTED'\n sanitized_values[:issuer] = self.issuer\n sanitized_values\n end", "def create\n @artist = Artist.new(artist_params)\n @artist.organization_id = params[:organization_id]\n\n respond_to do |format|\n if @artist.save\n format.html { redirect_to organization_artist_url(organization_id: @organization.id, id: @artist.id), notice: 'Artist was successfully created.' }\n format.json { render action: 'show', status: :created, location: @artist }\n else\n format.html { render action: 'new' }\n format.json { render json: @artist.errors, status: :unprocessable_entity }\n end\n end\n end", "def initialize(name, artist=nil, genre=nil)\n @name = name\n self.artist = artist if(artist!=nil)\n self.genre = genre if(genre!=nil)\n #@artist = artist\n end", "def initialize(name)\n @name = name\n @songs = [ ]\n #peter.song = (\"pit\") How to attribute song to the artist after the artist is create.\n end", "def reject!(person, reason)\n if (in_dispute_period? || contested?) && person_can_respond?(person) && response_for(person) != false\n self.class.transaction do\n BountyClaimEvent::BackerDisputed.create!(\n bounty_claim: self,\n person: person,\n description: reason\n )\n BountyClaimResponse.find_or_create_by_claim_and_person(self, person, false, reason) and reload\n end\n end\n end", "def invalid_data\n {\n :title => \"\",\n :description => nil,\n :parent_id => \"ss\"\n } \n end", "def reject( & block )\n\n load_parent_state\n \n return super\n\n end", "def keep_sponsor_name_error\n keep_interesting_errors(\n [I18n.t('errors.format_blank', attribute: I18n.t('activerecord.attributes.sponsor_covenant.sponsor_name'))]\n )\n end", "def reject\n\tRelationship.where(:accessed_id => params[:id], :accessor_id => params[:request_id]).first.destroy\n\tredirect_to(requests_user_path(current_user))\n end", "def artist=(artist)\n @artist = artist\n end", "def artist=(artist)\n @artist = artist\n end", "def artist=(artist)\n @artist = artist\n end", "def artist=(artist)\n @artist = artist\n end" ]
[ "0.58507925", "0.56096077", "0.5585204", "0.5334831", "0.5233449", "0.5122796", "0.5113652", "0.50821024", "0.50710475", "0.50166625", "0.49891585", "0.49865782", "0.49436396", "0.4939488", "0.49385795", "0.4926694", "0.49212027", "0.49212027", "0.49212027", "0.49086744", "0.48683858", "0.48505393", "0.48466292", "0.483007", "0.48155943", "0.48081753", "0.48081753", "0.48019466", "0.47935602", "0.47743672", "0.47649038", "0.47620156", "0.47517005", "0.47428527", "0.47403687", "0.47345144", "0.47314554", "0.47257158", "0.4705243", "0.4703228", "0.46918422", "0.46908727", "0.46820658", "0.46662542", "0.46656576", "0.466501", "0.46587768", "0.46586707", "0.46580306", "0.4655064", "0.46534735", "0.4643423", "0.46219075", "0.46213078", "0.46212223", "0.46208245", "0.4611335", "0.4607638", "0.46074772", "0.46073478", "0.46056274", "0.4603928", "0.4598992", "0.45956936", "0.45948446", "0.45943996", "0.45894426", "0.45879117", "0.45850605", "0.45819527", "0.45812505", "0.45796636", "0.45792645", "0.45707056", "0.45666796", "0.4564449", "0.4560961", "0.4557708", "0.45575616", "0.45528546", "0.4551106", "0.45407906", "0.45374462", "0.45334038", "0.45313382", "0.45307153", "0.45286956", "0.45276123", "0.45270658", "0.45223057", "0.45208132", "0.45189017", "0.4513942", "0.4510284", "0.45092288", "0.45060706", "0.45057037", "0.45057037", "0.45057037", "0.45057037" ]
0.47195303
38
`scope_name` is set as :current_user by default in the controller. If the instance does not have a method named `scope_name`, it defines the method so that it calls the +scope+.
def initialize(object, options = {}) self.object = object self.instance_options = options self.root = instance_options[:root] self.scope = instance_options[:scope] return if !(scope_name = instance_options[:scope_name]) || respond_to?(scope_name) define_singleton_method scope_name, -> { scope } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def scope_name; end", "def scope\n @scope ||= Array(@root_scope) + [Inflector.underscore(name)]\n end", "def current_user_scope\n current_user\n end", "def current_scope\n params[:scope].try(:to_sym) || railgun_resource.default_scope.try(:key)\n end", "def scope(scope_name)\n Scope.new(@backend, @name, scope_name)\n end", "def current_scope\n @scope\n end", "def method_missing(name, *args)\n if scopes[name].nil?\n super\n else\n execute_scope(name, *args)\n end\n end", "def custom_scope_get scope_name\n\t\t\tThread.current[SESSION].custom_scope_get scope_name\n\t\tend", "def execute_scope(name, *args)\n procedure = scopes[name]\n instance_exec(*args, &procedure)\n self\n end", "def scope_name name\n name.to_s.pluralize.to_sym\n end", "def scopeName _args\n \"scopeName _args;\" \n end", "def scope\n finder_or_run(:scope)\n end", "def scoped_by(name, options = {})\n options[:scope] ||= :reference\n if scope_class = self.class.scope_types[options[:scope]]\n @scopes[name] = scope_class.new(@model, name, options)\n end\n end", "def scope\n @scope\n end", "def scope\n @scope\n end", "def define_scope_method(name)\n singleton_class.class_eval do\n ruby2_keywords(\n define_method(name) do |*args|\n scoping = _declared_scopes[name]\n scope = instance_exec(*args, &scoping[:scope])\n extension = scoping[:extension]\n to_merge = scope || queryable\n criteria = to_merge.empty_and_chainable? ? to_merge : with_default_scope.merge(to_merge)\n criteria.extend(extension)\n criteria\n end\n )\n end\n end", "def read_scope(user)\n self\n end", "def scope\n read_attr :scope, :to_sym\n end", "def scope\n parameter[:scope]\n end", "def apply_to_scope(scope)\n scope\n end", "def controller_scope_name\n @controller_scope_name ||= 'admin.' + self.class.name.sub(/Controller$/, '').underscore.tr('/', '_')\n end", "def scope(scope_name, &block)\n scope_obj = LocatorScope.new(self)\n scope_obj.scoped_locator = send \"#{scope_name}_locator\"\n scope_obj.run(&block)\n end", "def selected_scope\n (params[:scope] || :default).to_sym\n end", "def find_scope(filter_name)\n @model_decorator.filters[filter_name].try(:[], :scope) || filter_name\n end", "def scope_name scope\n\t\traise \"No data-source set\" unless data_source\n\t\tdata_source.scopes.get(scope).human_name\n\tend", "def scope\n @scope ||= {}\n end", "def scope\n @scope ||= {}\n end", "def current_user\n scope == object\n end", "def scope=(value)\n @scope = value\n end", "def scope=(value)\n @scope = value\n end", "def scope=(value)\n @scope = value\n end", "def scope=(value)\n @scope = value\n end", "def scope=(value)\n @scope = value\n end", "def scope=(value)\n @scope = value\n end", "def scope(name, scope=nil, &block)\n raise ArgumentError, \"Dangerous scope name: a :#{name} method is already defined. Please, use another one.\" \\\n if respond_to?(name)\n proc = case\n when block_given?\n block\n when scope.is_a?(Flex::Scope)\n lambda {scope}\n when scope.is_a?(Proc)\n scope\n else\n raise ArgumentError, \"Scope object or Proc expected (got #{scope.inspect})\"\n end\n metaclass = class << self; self end\n metaclass.send(:define_method, name) do |*args|\n scope = proc.call(*args)\n raise Scope::Error, \"The scope :#{name} does not return a Flex::Scope object (got #{scope.inspect})\" \\\n unless scope.is_a?(Flex::Scope)\n scope\n end\n scope_methods << name\n end", "def scope\n @options[:scope]\n end", "def authenticate_scope!\r\n send(:\"authenticate_#{resource_name}!\")\r\n self.resource = resource_class.find(send(:\"current_#{resource_name}\").id)\r\n end", "def scope scope = nil, &proc\n @scope = (proc || scope) if (scope || proc) && configurable?\n @setup[:scope] ||= @scope ||\n (@controller.ctrl.slice.view.scope if @controller)\n end", "def current_scope\n Thread.current[:webspicy_scope] || default_scope\n end", "def scope(name = nil)\n raise 'Must specify name if no children have been defined yet' unless name || last_child\n name ||= last_child.name\n @outgoing_scopes[name]\n end", "def named_scope_method\n # Can't use respond_to because both AR 2 and 3\n # respond to both +scope+ and +named_scope+.\n ActiveRecord::VERSION::MAJOR == 2 ? :named_scope : :scope\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\")\n self.resource = resource_class.find(send(:\"current_#{resource_name}\").id)\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\")\n self.resource = resource_class.find(send(:\"current_#{resource_name}\").id)\n end", "def set_scope\n if (scope = params[:scope])\n if @resource.respond_to?(scope)\n @resource = @resource.send(scope)\n else\n not_allowed\n end\n end\n end", "def scope\n @scope ||= \"study.#{app_name}\"\n end", "def authenticate_scope!\r\n send(:\"authenticate_user!\", :force => true)\r\n self.resource = send(:\"current_user\")\r\n end", "def method_missing(method_name, *args, &block)\r\n if model\r\n scopes = ActiveRecord::Base.scopes.merge(model.scopes).keys\r\n\r\n if scopes.include? method_name\r\n return Restful::Resource::Scope.new self, method_name, model, args,\r\n block\r\n elsif method_name.to_s =~ /^(?:find(?:_all)?|first|last)_by_/\r\n finder method_name\r\n return send method_name, *args, &block\r\n end\r\n end\r\n\r\n super\r\n end", "def create_with_scope(name); end", "def apply_scopes(*)\n relation = super\n relation = relation.accessible_by(current_ability) if scope_accessible?\n relation\n end", "def apply_scope(target, type:, name: :default, scope_options: nil)\n raise ActionPolicy::UnknownScopeType.new(self.class, type) unless\n self.class.scoping_handlers.key?(type)\n\n raise ActionPolicy::UnknownNamedScope.new(self.class, type, name) unless\n self.class.scoping_handlers[type].key?(name)\n\n mid = :\"__scoping__#{type}__#{name}\"\n scope_options ? send(mid, target, **scope_options) : send(mid, target)\n end", "def update_scope\n @scope = params[:scope] || params[:q] || {}\n end", "def scope\n return @scope\n end", "def scope\n return @scope\n end", "def scope\n return @scope\n end", "def scope\n return @scope\n end", "def scope\n return @scope\n end", "def scope\n return @scope\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\", force: true)\n self.resource = send(:\"current_#{resource_name}\")\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\", force: true)\n self.resource = send(:\"current_#{resource_name}\")\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\", force: true)\n self.resource = send(:\"current_#{resource_name}\")\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\", force: true)\n self.resource = send(:\"current_#{resource_name}\")\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\", force: true)\n self.resource = send(:\"current_#{resource_name}\")\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\", force: true)\n self.resource = send(:\"current_#{resource_name}\")\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\", force: true)\n self.resource = send(:\"current_#{resource_name}\")\n end", "def devise_scope(scope); end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\", :force => true)\n self.resource = send(:\"current_#{resource_name}\")\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\", :force => true)\n self.resource = send(:\"current_#{resource_name}\")\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\", :force => true)\n self.resource = send(:\"current_#{resource_name}\")\n end", "def authenticate_scope!\n send(:\"authenticate_#{resource_name}!\", :force => true)\n self.resource = send(:\"current_#{resource_name}\")\n end", "def filtered_by(filter_name)\n valid_filter_name =\n FilterUtils.filter_name_by(filter_name, @model_decorator.filters)\n scope = find_scope(valid_filter_name)\n if scope.blank? then unscoped\n elsif scope.is_a?(Proc) then @model_class.instance_exec(&scope)\n elsif @model_class.respond_to?(scope)\n @model_class.public_send(scope)\n else unscoped\n end\n end", "def stradivari_scope(name, *args, &block)\n callable, options = stradivari_scope_options(*args, &block)\n\n scope(name, callable)\n options[:type] ||= :string\n stradivari_scopes.store(name.to_sym, options)\n end", "def pundit_scope\n base_scope = object ? object.send(parent_association_name) : self.class.model_klass\n\n # Enforce Pundit control if the gem is present\n # This current user must be injected in context inside the GraphqlController.\n if defined?(Pundit)\n self.class.pundit_scope_klass.new(current_user, base_scope.graphql_scope).resolve\n else\n base_scope.graphql_scope\n end\n end", "def pundit_scope(*scope)\n @pundit_api_scope ||= scope\n end", "def context_scope\n defined?(@_scope) ? @_scope : nil\n end", "def valid_scope_name?(name)\n if scopes[name] || respond_to?(name, true)\n if Mongoid.scope_overwrite_exception\n raise Errors::ScopeOverwrite.new(self.name,name)\n else\n if Mongoid.logger\n Mongoid.logger.warn(\n \"Creating scope :#{name}. \" +\n \"Overwriting existing method #{self.name}.#{name}.\"\n )\n end\n end\n end\n end", "def scope; end", "def scope; end", "def scope; end", "def scope; end", "def scope; end", "def scope; end", "def scope; end", "def scope; end", "def scope; end", "def scope; end", "def scope\n @scope.dup\n end", "def custom_filters(scope)\n scope\n end", "def scoped(scope = {}, &block)\n ActiveRecord::NamedScope::Scope.new(self, scope, &block)\n end", "def regulate_scope(name, &block)\n name, block = __synchromesh_parse_regulator_params(name, block)\n singleton_class.send(:define_method, :\"__secure_remote_access_to_#{name}\") do |this, acting_user, *args|\n r = this.send(name, *args)\n r = ReactiveRecordPsuedoRelationArray.new(r) if r.is_a? Array\n __set_synchromesh_permission_granted(this, r, r, acting_user, args, &block)\n end\n end", "def set_current_scope(scope)\n Thread.current[:webspicy_scope] = scope\n end", "def scope_options; end", "def scope_options; end", "def protected_scope(*args)\n self.scope_without_resource_definition_addition(*args)\n end", "def get_scope(cur_scope = nil)\n # base default scope is set up here so that deactivated module can update this\n cur_scope = AssemblyComponent.scoped if (cur_scope.nil?)\n return (defined?(super)) ? super(cur_scope) : cur_scope\n end", "def scope_level; end", "def scope(*)\n self['scope'] || self['current_account'].travel_plans\n end", "def try_to_set_scope\n #this is a commodity method\n if self.featurable.is_a?(Account)\n self.scope = \"AccountPlan\"\n end\n end", "def has_named_scope?(name)\n scope_proxy.has_named_scope?(name)\n end", "def authenticate_scope!\n \n \n do_before_request \n\n end", "def default_scope; end", "def scope\n @attributes[:scope]\n end" ]
[ "0.71355224", "0.70047474", "0.69022596", "0.6802003", "0.67924047", "0.6745818", "0.6744598", "0.67323834", "0.67269176", "0.6723036", "0.6610529", "0.6594619", "0.6586762", "0.65806764", "0.65806764", "0.65772337", "0.65422356", "0.6514057", "0.6400125", "0.6322532", "0.6308249", "0.63068825", "0.6303052", "0.63010234", "0.6285963", "0.62484044", "0.62484044", "0.6247447", "0.62295276", "0.62295276", "0.62295276", "0.62295276", "0.62295276", "0.62295276", "0.62273806", "0.6221335", "0.618803", "0.61787003", "0.6162818", "0.6146188", "0.6123175", "0.6114563", "0.6114563", "0.61135703", "0.6104328", "0.609453", "0.6092412", "0.6081441", "0.60785496", "0.60624146", "0.6053392", "0.60423595", "0.60423595", "0.60423595", "0.60423595", "0.60423595", "0.60423595", "0.60352206", "0.60352206", "0.60352206", "0.60352206", "0.60352206", "0.60352206", "0.60352206", "0.60296017", "0.60294306", "0.60294306", "0.60294306", "0.60294306", "0.6022644", "0.59927136", "0.59822935", "0.5951924", "0.5948381", "0.59474754", "0.5935154", "0.5935154", "0.5935154", "0.5935154", "0.5935154", "0.5935154", "0.5935154", "0.5935154", "0.5935154", "0.5935154", "0.5914455", "0.59066015", "0.5893381", "0.58887535", "0.58887035", "0.58841765", "0.58841765", "0.5884092", "0.5880036", "0.5876974", "0.58574", "0.58548003", "0.58455837", "0.5836024", "0.58127", "0.5804058" ]
0.0
-1
Used by adapter as resource root.
def json_key root || _type || object.class.model_name.to_s.underscore end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def root; resource :path => '/'; end", "def root \n context.metadata.root\n end", "def resource; end", "def resource\n (@nested_resource || @root_resource)\n end", "def resources; end", "def resources; end", "def resource_base_uri\n @resource ||= \"#{Hyperloop::Resource::ClientDrivers.opts[:resource_api_base_path]}/#{self.to_s.underscore.pluralize}\"\n end", "def resources()\n end", "def root_resource_name\n components.keys.first.to_s\n end", "def root\n @attributes[:root]\n end", "def resource_root\n FilePath.new(build_module.root, name + \".resources\").canonicalize\n end", "def root\n self\n end", "def root\n self\n end", "def root_object\n self\n end", "def root\n instance.options[:root]\n end", "def root\n instance.options[:root]\n end", "def root_collection\n return @root_collection ||= file_by_id(\"root\")\n end", "def resource_base_name\n 'JSON'\n end", "def resources_root()\n \"#{project_root}/Resources\"\n end", "def resource_root(project_id)\n \"/projects/#{project_id}/#{self.class.name.demodulize.tableize}\"\n end", "def resource\n\n end", "def load_current_resource; end", "def root\n @root\n end", "def resource\n self\n end", "def root(name)\n self._root = name\n end", "def root(key: nil, const: nil)\n add(Namespace::ROOT_PATH, key: key, const: const)\n end", "def root\n r = self.clone\n r.path = @root\n r.permissions = self.permissions\n r\n end", "def root_path; end", "def root_path; end", "def root_path; end", "def filesystem\n\t\tRush::Entry.factory('/', self)\n\tend", "def set_default_path\n unless @resource_config[:path]\n suffix = self.to_s.split('::').last\n @resource_config[:path] = Utility.underscore(suffix)\n end\n end", "def root_file_path; end", "def resource_base_name\n 'XML'\n end", "def resource\n self.class.resource\n end", "def contents_root\n config[:root]\n end", "def root_path \n @root_path\n end", "def root; end", "def root; end", "def root; end", "def root; end", "def root; end", "def root; end", "def root; end", "def root; end", "def root; end", "def root; end", "def root; end", "def root; end", "def root; end", "def root; end", "def root; end", "def get_resource_tree\n {\n method: \"Page.getResourceTree\"\n }\n end", "def root\n get '/'\n end", "def name\n @root\n end", "def folder\n @root_folder\n end", "def resources\n @resources ||= {}\n end", "def root\n @parent.root\n end", "def get_root()\n \n end", "def application_root; end", "def base_resource\n\t\t\t Subresource.new persisted? ? self.class.identify(self) : self.class.base_resource\n\t\t\tend", "def root hash = {}\n root_path hash\n end", "def root_uri\n attributes.fetch(:rootUri)\n end", "def path\n adapter.path\n end", "def root\n @elements[@root_name]\n end", "def root\n self.home\n self\n end", "def root\n JenkinsApi::Client::Root.new(self)\n end", "def root_folder\n connect\n\n @vm_folder\n end", "def root_storage\n @attributes[:root_storage]\n end", "def after_resource_to_hash_hook(res_hash, res)\n res_hash[:resources] = absolute_path(\"/slices/#{res.uuid}/resources\")\n res_hash\n end", "def root\n get \"/\"\n end", "def root\n get \"/\"\n end", "def root_path\n attributes.fetch(:rootPath)\n end", "def inherited(resource)\r\n resource.class_eval do\r\n self.versions ||= {}\r\n self.helper_object = Object.new\r\n\r\n begin\r\n plural = name.demodulize.tableize\r\n self.path = lambda { |format|\r\n begin\r\n new.polymorphic_path [:resources, plural], :format => format\r\n rescue => e\r\n nil\r\n end\r\n }\r\n self.query_template = DEFAULT_COLLECTION_QUERY_TEMPLATE.dup\r\n self.model = name.sub(/^Restful\\b/, '').constantize\r\n finder :find, :all, :first, :last\r\n helper ApplicationHelper\r\n rescue ArgumentError, NameError => e\r\n nil\r\n end\r\n\r\n Restful::Resource.classes << self\r\n end\r\n end", "def root_path=(_arg0); end", "def root_path=(_arg0); end", "def root_path=(_arg0); end", "def resource(set_name, path, &block)\n self.class.resource(set_name, path, &block)\n end", "def setup(resources) ; end", "def resource_url; nil end", "def initialize_root\n Utils.create_directory(@cache_root)\n Utils.clear_directory(@cache_root)\n end", "def root\n @group.root\n end", "def set_root() = self.destination_root = name", "def data_root\n \"/c\"\n end", "def root\n blk = self.class.has_widgets_blocks or raise \"Please setup a widget tree using has_widgets()\"\n @root ||= Apotomo::Widget.new(parent_controller, \"root\").tap do |root|\n self.instance_exec(root, &blk)\n end\n end", "def root_node; end", "def root\n return @root\n end", "def root\n return @root\n end", "def root_folder\n load unless loaded?\n @root_folder\n end", "def resources_path_names; end", "def app_root; end", "def current_resource\n @current_resource ||= @item\n end", "def bare_resource(resource)\n inner_name = \"bare_#{resource.name}\"\n inner_path = bare_d.join(\"#{resource.name}.conf\").to_s\n return inner_name, inner_path\n end", "def resource\n\t\t@album\n\tend", "def root\n fail \"The #{self.class} driver does not support the root method!\"\n end", "def root_to reference\n Router.set_root_to reference\n context = Context.collection[reference]\n context.routes[:root]= Route.new('/', context,{ context: reference})\n end", "def root\n 'public'\n end", "def root; get(\"\"); end", "def configure_base_resource\n Harvest.site = Resource.site = \"http#{'s' if @ssl}://#{@subdomain}.#{Harvest.api_domain}\"\n Harvest.subdomain = @subdomain\n Harvest.email = Resource.user = @email\n Harvest.password = Resource.password = @password\n load_resources\n end", "def resource\n @resource\n end", "def resource\n @resource\n end" ]
[ "0.69672817", "0.6171338", "0.6076182", "0.60425866", "0.6013549", "0.6013549", "0.5998068", "0.59105426", "0.58628017", "0.577526", "0.57501394", "0.57086957", "0.57086957", "0.57071584", "0.57018405", "0.57018405", "0.5647029", "0.5645331", "0.5636747", "0.56353456", "0.56348544", "0.5630563", "0.5623361", "0.55821717", "0.5580404", "0.55644464", "0.5553543", "0.5548099", "0.5548099", "0.5548099", "0.5533429", "0.5523728", "0.5521951", "0.5481471", "0.5448258", "0.54482174", "0.54441696", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.54437506", "0.5443008", "0.54294413", "0.5429274", "0.5418583", "0.5406244", "0.5390605", "0.5351446", "0.5346525", "0.53297025", "0.5324639", "0.53243494", "0.5323411", "0.53169817", "0.53118765", "0.53057325", "0.5303833", "0.5296714", "0.5290541", "0.5289445", "0.5289445", "0.52875024", "0.528466", "0.5283992", "0.5283992", "0.5283992", "0.5277415", "0.5274847", "0.5272712", "0.5264884", "0.52645147", "0.5264118", "0.5263273", "0.52618366", "0.52570087", "0.5255422", "0.5255422", "0.52553415", "0.52521795", "0.5243805", "0.52372026", "0.5236245", "0.5235461", "0.52335846", "0.52231157", "0.5221967", "0.52213365", "0.5218824", "0.5217696", "0.5217696" ]
0.0
-1
ax^2 + bx + c = 0
def quadra (a, b, c) if a == 0 puts "Решение не возможно!" return end d = (b**2)-(4*a*c) puts "Дискриминант равен #{d}" if d < 0 puts "d < 0 - Корней нет, а значит нет решения" elsif d == 0 m1 = -b - Math.sqrt(d) m2 = 2*a x = m1 / m2 #x = -b - Math.sqrt(d)/2*a - Этот вариант записи уравнения не работает почему-то. puts "В уравнении только один корень x = #{x}" elsif d > 0 v1 = -b + Math.sqrt(d) puts v1 v2 = -b - Math.sqrt(d) puts v2 v3 = 2*a puts v3 x1 = v1/v3 x2 = v2/v3 puts "В уравнении два корня: x1 = #{x1} и x2 = #{x2}" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def transmogrifier (a,b,c)\n (a*b)^c\n end", "def x\n @x ||= X.new( c*r, a, (-1*c*(b - c*n)), (r*r*a - (b - c*n)*(b - c*n)) )\n end", "def x\n @x ||= X.new( c*r, a, (-1*c*(b - c*n)), (r*r*a - (b - c*n)*(b - c*n)) )\n end", "def cac2\n 0\n end", "def c\n @c ||= self.p1.x * self.p2.y - self.p1.y * self.p2.x\n end", "def y()\n val = @b;\n @n.times {|i|\n val += @wn[i] * @xn[i];\n }\n return val;\n end", "def cramers_rule(ax,ay,az,a)\n # ax = array for all coefficients of x\n # ay = array for all coefficients of y\n # az = array for all coefficients of z\n # a = array for all constants\n x = Matrix[a,ay,az].determinant/Matrix[ax,ay,az].determinant.to_f\n y = Matrix[ax,a,az].determinant/Matrix[ax,ay,az].determinant.to_f\n z = Matrix[ax,ay,a].determinant/Matrix[ax,ay,az].determinant.to_f\n p x\n p y \n p z\n end", "def solve(a, b, c)\n par = (b * b - 4 * a * c).sqrt\n [(-b + par) / (2 * a), (-b - par) / (2 * a)]\n end", "def transmogrifier(a, b, c)\n # (a * b).pow(c)\n (a * b) ** c\nend", "def solve(a, b, c)\n v = b ** 2 - 4 * a * c\n if v < 0: raise RangeError end\n s0 = ((-1)*b - Math.sqrt(v))/(2*a)\n s1 = ((-1)*b + Math.sqrt(v))/(2*a)\n return s0, s1\nend", "def f2c_x(x)\n (x - x_orig) * zoom\n end", "def xor_c\n end", "def linear_congruence(a, b, m)\n inverse = self.inverse_of_congruene(m, a)\n n = Array.new\n for k in -5..5\n #x = invers*b + m*k. We know this from Theorom 4 section 3.4 of Rosen.\n n.push((inverse * b) + (m * k))\n end\n return n\n end", "def cosine\n\tcosine of 120 degrees is -.5\n\ta2 = c2 + b2 - 2bc cos A, (this is important to use)\n\tis it a triange? (a+b > c && a+c > b && b+c > a)\nend", "def f2c(temp_f)\n (temp_f - 32) * 5 / 9\nend", "def c0= c; @c0 = (c == 1) ? 1 : 0; end", "def euc_2d(c1, c2)\n Math.sqrt((c1[0] - c2[0])**2.0 + (c1[1] - c2[1])**2.0).round\nend", "def mathoper4argum(n, y, a, b)\n\n\tn + y - a / b\n\nend", "def erlang_c(m, u)\n d = power_fact(m, u)\n s = 1.0\n (1..(m - 1)).each do |k|\n s += power_fact(k, u)\n end\n d / (d + (1 - u / m) * s)\n end", "def x(y)\n return 1.0/2.0 * (y - 1.0)\n end", "def x(y)\n return 1.0/2.0 * (y - 1.0)\n end", "def x(y)\n return 1.0/2.0 * (y - 1.0)\n end", "def m1(a,b,c,d)\n (((a+(M-b)+(M-c))%M)^(d%M))%M # mix/power mod\n end", "def r\n return (x**2.0 + y**2.0 + z**2.0)**0.5\n end", "def normal(a, b)\n [a[1]*b[2]-a[2]*b[1],\n a[2]*b[0]-a[0]*b[2],\n a[0]*b[1]-a[1]*b[0]]\nend", "def cnd(x)\r\n l = x.abs\r\n k = 1.0 / (1.0 + 0.2316419 * l)\r\n w = 1.0 - 1.0 / Math.sqrt(2 * Math::PI) * Math.exp(-l * l / 2.0) *\r\n ( 0.31938153 * k +\r\n -0.356563782 * (k ** 2) +\r\n 1.781477937 * (k ** 3) +\r\n -1.821255978 * (k ** 4) +\r\n 1.330274429 * (k ** 5))\r\n w = 1.0 - w if x < 0\r\n end", "def sum_of_cubes(a, b)\n (a..b).inject(0) { |acc, iter| acc + iter**3 }\nend", "def m1(a,b,c,d)\n return (((a+(M-b)+(M-c))%M)^(d%M))%M # mix/power mod\n end", "def ctof temp2\n (temp2*1.8) + 32\nend", "def value(x, y)\r\n return 1 if x == 1 || y == 1\r\n value(x - 1, y) + value(x, y - 1)\r\nend", "def euc_2d(c1, c2)\n Math.sqrt((c1[0] - c2[0])**2.0 + (c1[1] - c2[1])**2.0).round\n end", "def e2w(n, m)\n# n = (n+0.938272)*(n+0.938272) - n*n\n n+m\nend", "def sum_of_cubes(a, b)\n (a..b).inject(0) { |sum, element| sum + element**3 }\nend", "def quadratic_equation(a, b, c)\n first_part = -b / (2 * a)\n second_part = (((b**2) - (4 * a * c))**(0.5)) / (2 * a)\n first_answer = first_part + second_part\n second_answer = first_part - second_part\n puts \"#{first_answer} or #{second_answer}.\"\nend", "def clk\n case [@c2, @c1, @c0]\n when [0,0,0] then do_nothing;\n when [0,0,1] then x_add_y\n when [0,1,0] then rotate_x\n when [0,1,1] then x_and_y\n when [1,0,0] then x_or_y\n when [1,0,1] then x_xor_y\n when [1,1,0] then not_x\n when [1,1,1] then x_equal_y\n else raise RuntimeError.new \"wrong alu operation: #{ [@c2, @c1, @c0] }\"\n end\n @z\n end", "def smc(a, b)\n a_i = a.map { |i| i > 0 ? 1 : 0 }\n b_i = b.map { |i| i > 0 ? 1 : 0 }\n m00 = (0 .. (a.size - 1)).map { |i| a_i[i] == 0 && b_i[i] == 0 ? 1 : 0 }\n m11 = (0 .. (a.size - 1)).map { |i| a_i[i] == 1 && b_i[i] == 1 ? 1 : 0 }\n return (m00 + m11).to_f / a.size\n end", "def calc_parab_y(x_in, fp_in)\r\n # - - - - - - - - - - - - - - - -\r\n lcy = (x_in * x_in) / (fp_in * 4.0)\r\n lcy\r\n end", "def cdf(x, a, b)\n return 0.0 if x <= 0.0\n return 1.0 if x >= 1.0\n Math::IncompleteBeta.axpy(1.0, 0.0, a, b, x)\n end", "def tx__x(n, x); 2.0 - tdist(n, x) * 2.0; end", "def f2c(t)\n\treturn (t - 32) * 5.fdiv(9)\nend", "def transmogrifier (a, b, c)\n ((a * b) ** c)\nend", "def CalculatePentagonal (input)\n\treturn (input * (3*input - 1) / 2)\nend", "def sum_of_cubes(a, b)\n=begin \n sum = 0\n (a..b).each do |n|\n sum += n*n*n\n end\n sum\n=end \n (a..b).reduce(0) { |a, b| a + b ** 3 }\nend", "def bs(a, b)\n if (b - a) == 1\n if a == 0\n pab = 1\n qab = 1\n else\n pab = ((6 * a)-5) * ((2 * a)-1) * ((6 * a)-1)\n qab = (a * a) * (a * $c3)\n end\n\n tab = pab * (13591409 + (545140134 * a))\n\n if a & 1 == 1\n tab = -tab\n end\n else\n m = 0\n m = ((a + b) / 2).round(0)\n\n pam, qam, tam = bs(a, m)\n pmb, qmb, tmb = bs(m, b)\n\n pab = pam * pmb\n qab = qam * qmb\n tab = qmb * tam + pam * tmb\n end\n return pab, qab, tab\nend", "def sum_of_cubes(a, b)\n (a..b).inject(0) { |sum, x| sum += (x*x*x) }\nend", "def sum_of_cubes(a, b)\n (a..b).inject(0) { |sum, x| sum += (x*x*x) }\nend", "def sum_of_cubes(a, b)\n (a..b).inject(0) { |sum, x| sum += (x*x*x) }\nend", "def arccot(x, unity)\n xpow = unity / x\n n = 1\n sign = 1\n sum = 0\n loop do\n term = xpow / n\n break if term == 0\n sum += sign * (xpow/n)\n xpow /= x*x\n n += 2\n sign = -sign\n end\n sum\n end", "def quad(a, b, c)\n\tif a != 0\n\t\targ = (b**2) - (4 * a * c)\n\t\tif arg > -1\n\t\t\t[(-b + Math.sqrt(arg))/(2*a), (-b -Math.sqrt(arg))/(2*a), true, 0]\n\t\telse \n\t\t\t[0, 0, false, 1]\n\t\tend\n\telse \n\t\t[0, 0, false, 2]\n\tend\nend", "def quadraticRoots(a, b, c)\n if a != 0 then\n arg = b ** 2 - 4 * a * c\n if arg >= 0 then\n [1,\n (((b * -1) + Math.sqrt(arg)) / (2*a)),\n (((b * -1) - Math.sqrt(arg)) / (2*a))]\n else\n print \"\\n*** quadraticRoots(): b^2 -4ac is negative!\\n\"\n [0,0,0]\n end\n else\n print \"\\n*** quadraticRoots(): a is zero!\\n\"\n [0,0,0]\n end \nend", "def c2= c; @c2 = (c == 1) ? 1 : 0; end", "def transmogrifier(a, b, c)\n p (a * b) ** c\nend", "def bitodec(bi)\n\tbistring = bi.to_s\n\tturnbi = bistring.chars.reverse.map{|i| i.to_i}\n\tfor index in (0...turnbi.length)\n\t\tturnbi[index] = turnbi[index]*(2**index)\n\tend\n\tdec = turnbi.sum\n\treturn dec\nend", "def f2c(f)\n\tc = (5.0/9.0)*(f-32.0)\n\treturn c\nend", "def stat_com(q, i, j, b)\n z = zz = 1\n k = i\n while(k <= j)\n zz = zz * q * k / (k - b)\n z = z + zz\n k += 2\n end\n z\n end", "def GF_product_t_i(a, b)\n t = GF_tables()\n t[:exponential][(t[:logarithmic][a] + t[:logarithmic][b]) % 255]\nend", "def exponenciacion_rapida(a, b, m)\n\t\t_x = 1\n\t\t_y = a%m\n\t\twhile ((b > 0)&&(_y > 1))\n\t\t\tif (b%2 != 0)\n\t\t\t\t_x = (_x*_y)%m\n\t\t\t\tb = b-1\n\t\t\telse\n\t\t\t\t_y = (_y*_y)%m\n\t\t\t\tb = b/2\n\t\t\tend\n\t\tend\n\t\treturn _x\n\tend", "def d(x)\n 2 * ( l(x) + h(x) ) - 1\n end", "def inverse_formula (a, b)\n return 2 * (a + 5 * b)\nend", "def sum_of_cubes(a, b)\n total = 0\n (a..b).each{ |x| total += x**3 } \n \n return total \nend", "def sum_of_cubes(a, b)\n (a..b).inject(0) {|sum, x| sum + x*x*x}\nend", "def p1(x, y, z)\n # x or y\n xor(x, y)\nend", "def syyx\n @syy-@syx*@sxx.inverse*@sxy\n end", "def escape c\n z = Complex(0, 0)\n for it in 1 .. @cap\n z = z ** 2 + c\n break if z.abs2 > 4.0 # 2.0 * 2.0\n end\n (it == @cap) ? 0 : it\n end", "def xor_b\n end", "def equation\n if p1.x == p2.x\n return \"x - #{p1.x}\"\n elsif p1.y == p2.y\n return \"#{p2.y} - p1.y\"\n end\n\n \"#{a}*x + #{b}*y + #{c} = 0\"\n end", "def cadera\n\t\t(@cadera[0] + @cadera[1])/2\n\tend", "def MUX2X1(x,y) XOR(x,y); end", "def sum_of_cubes(min, max)\n lower = min - 1\n (((max * (max + 1))/2) ** 2) - (((lower * (lower + 1))/2) ** 2)\nend", "def extended_euclid(a, b)\n if a < b\n swap_values = true\n end\n\n if swap_values\n a, b = b, a\n end\n\n remainders = []\n quotients = []\n a_tmp, b_tmp = a, b\n while a_tmp % b_tmp > 0\n remainders.push(a_tmp % b_tmp)\n quotients.push(a_tmp / b_tmp)\n\n a_tmp, b_tmp = b_tmp, a_tmp % b_tmp\n end\n\n x_tmp, y_tmp = 1, -quotients[-1]\n quotients.take(quotients.size - 1).reverse.each do |quotient|\n x_tmp, y_tmp = y_tmp, x_tmp - y_tmp * quotient\n end\n\n unless x_tmp*a + y_tmp*b == remainders[-1]\n raise 'Failed to compute Bezout coefficients'\n end\n\n if swap_values\n x_tmp, y_tmp = y_tmp, x_tmp\n end\n\n return x_tmp, y_tmp\nend", "def _anc\n @_p_nz = @_a &= @data\n @_p_c = @_p_nz >> 7\n end", "def min_x\n c2f_x(0)\n end", "def xor(x, y)\n\nend", "def at n\n @coeffs.each_with_index.map{ |c,i| c * (n**i) }.inject(&:+)\n end", "def ^(p0) end", "def ^(p0) end", "def ^(p0) end", "def ^(p0) end", "def ^(p0) end", "def sum_of_2int a, b\n (b == 0) ? a : (sum_of_2int (a^b),((a&b)<< 1))\nend", "def gcd2 a,b\n if a<b\n d,s,r = gcd2 b,a\n [d,r,s]\n elsif b==0\n [a,1,0]\n else\n x=a/b\n y=a%b\n d,r,s = gcd2 b,y\n # here we know that d = r*b+s*y, and a=x*b+y, so y=a-x*b\n # thus d=r*b+s*(a-x*b) = (r-s*x)*b + s*a\n # so we return [d,s,r-s*x]\n # uncomment the following three lines to see this work out\n # puts \"#{a}=#{x}*#{b}+#{y}\"\n # puts \"#{d}=#{s}*#{a} + #{(r-s*x)}*#{b}\"\n [d,s,(r-s*x)]\n end\nend", "def c2f_x(x)\n x / zoom + x_orig\n end", "def cross (a, b, c)\n return (b[0]-a[0])*(c[1]-a[1]) - (c[0]-a[0])*(b[1]-a[1])\nend", "def roots (a, b, c)\n array = Array.new(3)\n if a != 0\n arg = b*b - 4 * a * c\n if arg >= 0\n array[0] = true\n array[1] = (-b + Math.sqrt(arg))/(2*a)\n array[2] = (-b - Math.sqrt(arg))/(2*a)\n else\n print \" roots(): b^2 - 4ac is negative!\"\n array[0] = false\n array[1] = array[2] = 0.0 \n end\n else\n print \" roots(): a is zero!\"\n array[0] = false\n array[1] = array[2] = 0.0\n end\n array\nend", "def oval(x, a, b, h, k)\n k + -b * Math.sqrt(1 - ((x-h)/a) ** 2)\n end", "def c2f(c)\n c * 9.0 / 5 + 32\nend", "def v(r,c) (f(r)/f(c)/f(r-c)).to_s end", "def pow(base, y)\n result = 1\n for i in 0..(y - 1)\n result = result * base\n end\n puts \"\\n#{base}^(#{y}) = #{result}\\n\"\n end", "def quad(a,b,c)\n bsquaredminusfourac = b**2 - (4 * a * c)\n negb = b * -1\n twoa = 2 *a\n ans1 = negb + Math.sqrt(bsquaredminusfourac)\n ans2 = negb - Math.sqrt(bsquaredminusfourac)\n return (ans1 / twoa), (ans2 / twoa)\nend", "def f(a)\n return lsin(a) + calcpi() / 2\nend", "def sigma(inta, intx, intb, pw)\n ttl = 0\n for i in 1..intx\n ttl += (inta*intx+intb)\n end\n if(pw == 1)\n return ttl\n end\n if(pw > 1)\n ttl=ui_pow(ttl, pw)\n return ttl\n end\n if(pw == 0)\n return 1\n end\nend", "def coef\n(@sign+@coef.to_s).to_i\nend", "def pow(a, b, c)\n return false if c.negative?\n multi = 1\n (0...b).each do |i|\n multi = multi * a\n end\n result = multi % c\n result\nend", "def normal_towards(a, b, c)\n ac = a.dot(c)\n bc = b.dot(c)\n\n x = b.x * ac - a.x * bc\n y = b.y * ac - a.y * bc\n\n V.new(x, y)\n end", "def latbc(phi)\n=begin\n # not so good\n pi2 = Math::PI/2\n eps = 0.1\n xs = phi[0..1].val \n xe = phi[-2..-1].val\n if (pi2-xs[0].abs) / (xs[0]-xs[1]).abs < eps and\n (pi2-xe[-1].abs) / (xe[-1]-xe[-2]).abs < eps \n GPhys::Derivative::MIRROR_B\n else\n GPhys::Derivative::LINEAR_EXT\n end\n=end\n GPhys::Derivative::LINEAR_EXT\n end", "def cal()\n @v = 0.0;\n @n.times {|i|\n @v += @wn[i] * @xn[i];\n }\n nil;\n end", "def x(y)\n return @coefficients[0] / y\n end", "def ctof(c)\n f = c * 9.0/5.0 + 32.0\nend", "def equationValue(a, b, c, d, x)\n\t\tf = ((a+x)/(b+x))**(b + x)\n\t\tf = f - (c/d)\n\t\treturn f\n\tend", "def y(from = 0)\n self[1,2].to_i - 1 + from\n end" ]
[ "0.63203514", "0.60915214", "0.60915214", "0.60713476", "0.6071139", "0.59412324", "0.5905334", "0.57929564", "0.5734745", "0.57135224", "0.57093173", "0.5709317", "0.5665201", "0.56453323", "0.56384766", "0.56364495", "0.5633788", "0.5632742", "0.5585169", "0.5512094", "0.5512094", "0.5512094", "0.54846716", "0.54824126", "0.54806924", "0.5475007", "0.54667395", "0.54596967", "0.54481214", "0.5445681", "0.54433167", "0.5438564", "0.54371524", "0.5430238", "0.5422987", "0.54221994", "0.54195243", "0.54066443", "0.54059505", "0.53676796", "0.53652877", "0.535259", "0.5352408", "0.5349341", "0.53442764", "0.53442764", "0.53442764", "0.53409064", "0.53299946", "0.5329541", "0.5325615", "0.53216314", "0.53092104", "0.5307361", "0.53020185", "0.5295791", "0.5295206", "0.5286046", "0.52828944", "0.52817434", "0.5275121", "0.5273692", "0.52695245", "0.52670836", "0.5262827", "0.52574605", "0.52438074", "0.5242718", "0.52288", "0.52189684", "0.5205902", "0.5205857", "0.520355", "0.5199637", "0.5199369", "0.5199369", "0.5199369", "0.5199369", "0.5199369", "0.51914966", "0.5187755", "0.5179748", "0.51766783", "0.5175982", "0.51653636", "0.51567554", "0.51567185", "0.5155796", "0.5155163", "0.51503265", "0.51493376", "0.51479244", "0.5147834", "0.51442695", "0.5139284", "0.513153", "0.512882", "0.51190037", "0.5116075", "0.51130205" ]
0.53070533
54
After it is determined that a user is on a Newsfeed or Timeline feed, determine if that feed should get the new post
def validate_post_for_user_location(post, user, action) # First verify that the person on a Newsfeed is the current user, or # if the current user is on a user's Timeline, the current user # is allowed to see posts on that Timeline (depending on the user's # privacy setting) unless (( action == 'newsfeed' && access_level?(user, :self) ) || ( action == 'timeline' && access_level?(user, :public) )) return false end receiver = post.receiver creator = post.creator # Now check if the Newsfeed or Timeline of the user should receive # the new post. Newsfeeds get posts created for or by the owner, # or friends of the owner, of the Newsfeed; Timelines only get # posts created for or by the owner of the Timeline. ( action == 'newsfeed' && (access_level?(receiver, :friend) || access_level?(creator, :friend)) ) || ( action == 'timeline' && (receiver == user || creator == user) ) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fetch_from_news_feed\n unless self.facebook_omniauth.blank?\n fb_user = self.facebook_client_user\n unless fb_user.blank?\n posts = fb_user.home # fetch posts\n Movie.name_is_not_blank.name_without_dictionary_word.this_year.each do |movie|\n posts.each do |post|\n FacebookFeed.create_facebook_post(post, movie, post.from)\n User.pull_comments(post, movie) #check for comments is present\n end # each post end\n end # movie end\n end\n end\n end", "def is_syndicated_blog_post?\n feed.feed_type.name == \"Blog\"\n end", "def has_feed?\n !feed.nil?\n end", "def is_displayed_on_site?\n feed.feed_type.name == \"Article\"\n end", "def ensure_feed_creation\n with_feed(initiator) unless no_default_feed || joinable.membership_for?(user) || joinable.membership_request_for?(user)\n end", "def has_new_activity?(user)\n found_notification?(user) || found_comment_notifications?(user)\n end", "def can_add_feeds?\n false\n end", "def any_new?\n return true if articles.length == 0\n from_feed = feed.entries.first.published\n from_db = articles.last.published\n return true if from_feed > from_db\n false\n end", "def following?(post)\n posts.include?(post)\n end", "def update_found(feed, latest_db_post)\n if latest_db_post.nil?\n Log.log.debug \"Latest Post date is nil, table is empty. Performing initial update\"\n return true\n end\n last_blog_update = feed.updated.content\n Log.log.debug \"last_blog_update: #{last_blog_update}\"\n Log.log.debug \"latest_db_post: #{latest_db_post}\" \n if last_blog_update > latest_db_post\n Log.log.debug \"Updates Detected\"\n return true\n else\n Log.log.debug \"No updates found\"\n return false\n end\nend", "def has_liked_userpost(feed_item)\n @like = Like.where(user_id: current_user.id, userpost_id: feed_item.id).first\n !@like.nil?\n end", "def update_from_feed(feed_url)\n\t\tputs \"pulling feeds\"\n\t\tfeed = Feedzirra::Feed.fetch_and_parse(feed_url)\n\t\t# feed.last_modified - if it's been modified since last time\n\t\tfeed.entries.each do |entry|\n\t\t\t# if the post occured after it was last checked\n\t\t\tfind_keywords(entry.url)\n\t\t\tputs entry.url\n\t\t\t# call the keyword check and save on the actual post url\t\n\t\tend\nend", "def is_post_already_posted item\n\n\tpost= Posted.where(:link => item[\"link\"] ).first\n\t\t if !post.nil? \n\t\t return false \n\t\t else \n\n\t\t return true\n\n\t\t end \nend", "def is_post?\n is_entry? && params[:_entry_type_] == 'post'\n end", "def valid_feed_url?\n true if find_feed_locally(@url) || fetch_feed\n rescue StandardError\n false\n end", "def any_unread? usr\n @conv.posts.each do |post| \n if post.unread?(usr) && post.recipient_id == usr.id\n return true\n end\n end\n return false\n end", "def show\n if @user != current_user\n redirect_to :action => 'feed', :id => @user.id\n end\n end", "def replied_conv? usr\n if @conv.posts.count > 1 && @conv.posts.last.user_id != usr.id\n @conv.posts.each do |post|\n return true if post.user_id == usr.id\n end\n end\n false\n end", "def retweet?\n feedable_type == RETWEET_CLASS\n end", "def is_share_point_newsfeed_enabled\n return @is_share_point_newsfeed_enabled\n end", "def index\n people_in_feed = current_user.feed_list\n @posts = Post.where(user: people_in_feed)\n end", "def isAnnouncementPost\r\n\t\t\t\t\treturn @isAnnouncementPost\r\n\t\t\t\tend", "def is_a_post?\n self.object_type == :post\n end", "def posting_freights?\n current_user.full?(&:posting_type) == 'Freight'\n end", "def blog_feed\n Blogpost.from_users_followed_by(self)\n end", "def update_external_blogs\n users = User.find(:all, :conditions=>'blog_feed is not null')\n users.each do |user| \n if user.blog_feed.length > 0\n BlogPost.update_from_feed(user.blog_feed, user.id)\n end\n end\n end", "def rss\n\n # Get the specified user, making sure that it exists\n if !@user = User.find_by_login(params[:user_login])\n raise ActiveRecord::RecordNotFound\n end\n\n # If the everybody flag is set, respond with feed items about everybody\n # on Blavel\n # Otherwise, respond with feed items only about the people that the\n # current user is following\n @everybody = params[:everybody]\n if @everybody\n @feed_items = gather_feed_items\n else\n @feed_items = gather_feed_items(current_user)\n end\n\n rescue ActiveRecord::RecordNotFound => error\n logger.info error\n flash[:notice] = 'The user you requested does not exist.'\n redirect_to '/'\n end", "def share_to_fb_timeline?\n self.fb_action_id == FBSharing::Underway\n end", "def valid_feed?(item)\n !item['url'].to_s.strip.empty?\n end", "def getFeed\n\t\t\tresponse = HTTP.get(\"https://graph.facebook.com/v2.12/#{self.page_resource}/feed?access_token=#{ENV['FB_ACCESS_TOKEN']}\")\n\t\t\tfeedHash = JSON.parse(response.body)\n\t\t\tposts = feedHash[\"data\"].collect do |feed|\n\t\t\t\t\tfb_created = Date.parse(feed[\"created_time\"])\n\t\t\t\t\tcontent = feed[\"message\"]\n\t\t\t\t\tstory = feed[\"story\"]\n\t\t\t\t\tfb_id = feed[\"id\"]\n\t\t\t\t\toldPost = self.posts.where(fb_id: fb_id)\n\t\t\t\t\t\n\t\t\t\t\tif oldPost.empty? && !content.nil?\n\t\t\t\t\t\tself.posts.create(fb_id: fb_id, content: content, fb_created: fb_created.strftime('%m/%d/%Y'), story: story)\n\t\t\t\t\tend\n\t\t\tend \t\n\tend", "def is_approved?\n (self.approved_feeds.count > 0) && ((self.pending_feeds.count + self.denied_feeds.count) == 0)\n end", "def create\n url = params[:feed][:url]\n @feed = Feed.find_by_url(url) || Feed.new(url: url)\n @feed.fetch\n\n respond_to do |format|\n if @feed.save\n current_user.feeds << @feed unless current_user.feeds.include? @feed\n format.html { redirect_to @feed, notice: 'Feed was successfully added.' }\n format.json { render action: 'show', status: :created, location: @feed }\n else\n format.html { render action: 'new' }\n format.json { render json: @feed.errors, status: :unprocessable_entity }\n end\n end\n end", "def can_request?(post)\n post[:post_id] != posts\n end", "def posted?\n post.present?\n end", "def already_submitted?\n user_id = session[:drupal_user_id]\n campaign = get_campaign\n\n if user_id.nil? || campaign.nil?\n return false\n end\n\n posts = Rails.cache.fetch user_id.to_s + '-posted-on-' + campaign.id.to_s do\n Post.where(uid: user_id, campaign_id: campaign.id)\n end\n\n !posts.nil? && posts.count > 0\n end", "def is_blog_post?\n self.type == 'Blog'\n end", "def is_blog_post?\n self.type == 'Blog'\n end", "def newsfeed\n Post.newsfeed_for(self)\n end", "def is_my_post?(userid)\n #if someone is logged in\n if @current_user\n #if the user id of the post is the user id of the person logged in => it is my post\n if @current_user.id == userid\n return true\n # it isn't my post\n else\n return false\n end\n #It isn't my post because I'm not logged in\n else\n return false\n end\n end", "def feed\n Post.from_users_followed_by(self)\n end", "def feed\n Post.from_users_followed_by(self)\n end", "def is_a_feed?(url)\n it = begin\n open(url) \n rescue OpenURI::HTTPError\n return false\n end\n\n return false if !valid_content_type?(it.content_type)\n return false unless it.read =~ /<channel|feed[^>]*?>/ # Why yes, this is a hack. Why do you ask?\n\n true\n end", "def feed\n\n # If the user is not logged in, render the non-member home action\n if !current_user\n render :template => 'promo/home', :layout => 'empty'\n else\n @everybody = params[:everybody]\n\n # If the everybody flag is set, respond with feed items about everybody\n # on Blavel\n # Otherwise, respond with feed items only about the people that the\n # current user is following\n if @everybody\n @feed_items = gather_feed_items\n else\n @feed_items = gather_feed_items(current_user)\n end\n\n # Pass through the first 5 followers and the first 5 followees, all\n # randomised\n @followers = current_user.followers.sort_by { rand }.first(6)\n @followees = current_user.followees.sort_by { rand }.first(6)\n\n # Respond with html or javascript, depending on whether it is requested\n # via ajax or not\n respond_to do |format|\n format.html\n format.js { render :template => 'feeds/feed.js.erb', :layout => false }\n end\n end\n end", "def create\n @resource = Post.find_by(user_id: current_user.id, url: params[\"post\"][\"url\"])\n if @resource.present?\n # refer article recentry or not\n @refer_recently = @resource.created_at > DateTime.now - 7.days\n else\n @resource = Post.create!(user_id: current_user.id, url: params[\"post\"][\"url\"], title: params[\"post\"][\"title\"])\n UsersPost.create! user_id: current_user.id, post_id: @resource.id\n @refer_recently = false\n end\n end", "def feed\n # This is preliminary. See \"Following users\" for the full implementation.\n Micropost.where(\"story_id = ?\", id)\n end", "def feed\n Post.where(\"user_id IN (?) OR user_id = ?\", friend_ids, id).feed\n end", "def handle_news\n @feeder.send_feed(message.chat.id)\n end", "def is_pending?\n (self.pending_feeds.count > 0)\n end", "def feed\n\t\t\tpart_of_feed = \"relationships.follower_id = :id or microposts.user_id = :id\"\n\t\t\tMicropost.joins(user: :followers).where(part_of_feed, { id: id })\n\t\tend", "def feed\n\t\t# This is preliminary. See \"Following users\" for the full implementation.\n\t\t#Micropost.where(\"user_id = ?\", id) # \"?\" ensures variable 'id' is properly escaped\n\t\t\t\t\t\t\t# before being used in SQL query\n\t\t\t\t\t\t\t# same as 'microposts' - which references all microposts of the user\n\t\t\t\t\t\t\t# But eventually want not just this user's microposts -- but the\n\t\t\t\t\t\t\t# microposts of the folks he's following\n\t\t\t\t\t\t\t# Otherwise user.microposts would've been fine, rather we want user.feed\n\t\t# rather than show posts by user, show posts by users the user follows\n\t\tMicropost.from_users_followed_by(self) \n\tend", "def feed_target\n User.find_by(id: feed_id)\n end", "def valid_post?\n @post.blog == @blog\n end", "def insert_news_if_necessary(url)\n latest_date = latest_news_date(Feed.id_from_url(url))\n latest_date = Setting.keep_news_time if latest_date.zero?\n\n channel = Arss::FeedParser.parse_uri(url).feed['channel']\n return unless channel.has_key? 'items'\n\n channel['items'].each do |item|\n if Setting.get_delete_after_days.nonzero?\n next if (item['pubDate'] <= latest_date or item['pubDate'] < Setting.keep_news_time)\n end\n\n create(:user_id => User.current_user_id, :feed_id => Feed.id_from_url(url),\n :title => item['title'], :description => item['description'],\n :url => item['link'], :read => 0, :date => item['pubDate'])\n end\n end", "def is_first \n\t\treturn self == self.get_debate.posts.first\n\tend", "def get_first_entry\n wait_for_css(input_elements[:entries_list])\n entries = get_entries\n entries.each do |entry|\n unless entry.has_css?(input_elements[:tag_link_on_stream])\n @stream_post = entry\n @stream_post_id = @stream_post[\"data-mention-id\"]\n return true\n end\n end\n #fail(ArgumentError.new(\"All stream posts have tags\"))\n end", "def show\n redirect_to feeds_url\n # @feed = Feed.find(params[:id])\n # @user_feed = current_user.user_feeds.find_by_feed_id(@feed.id)\n end", "def is_feedable(well)\n tnow = Time.now.to_f\n tthen = well.get(:last_electroporated) || 0\n return tnow - tthen > 24 * 60 * 60\n end", "def share_to_tumblr?\n self.tumblr_post_id == TumblrSharing::Underway\n end", "def publish_newsfeed\n if avatar_file_name_changed?\n _content = contents.create!(privacy_level: is_anonymity? ? 'only_me' : 'only_friends', content_type: 'image', description: \"#{full_name(false)} updated #{the_sex_prefix} profile picture\", content_images_attributes: [{image: avatar}], skip_repeat_validation: true)\n user_photos.create(url: avatar.url, content_id: _content.id)\n end\n\n if cover_file_name_changed?\n _content = contents.create!(privacy_level: is_anonymity? ? 'only_me' : 'only_friends', content_type: 'image', description: \"#{full_name(false)} updated #{the_sex_prefix} cover photo\", content_images_attributes: [{image: cover}], skip_repeat_validation: true)\n user_photos.create(url: cover.url, content_id: _content.id)\n end\n end", "def poll!\n # Never poll for hosted users.\n unless hosted?\n posts_url = URI.join(url, '/posts.json')\n posts_json = HTTParty.get(posts_url, query: { updated_since: last_polled_at.try(:to_i) })\n\n # upsert posts in the database\n posts = posts_json.reverse.map do |json|\n # Sanity checks\n if json['domain'] != domain\n raise \"#{posts_url} contained an invalid domain.\"\n end\n\n # upsert post in local database\n Post.from_json!(json)\n end\n\n # add posts to local followers' timelines\n followings.includes(:user).each do |friendship|\n posts.each do |post|\n if friendship.created_at <= post.edited_at\n friendship.user.add_to_timeline(post)\n end\n end\n end\n\n posts\n end\n ensure\n touch(:last_polled_at)\n end", "def feed\n\t\tfollowing_ids = \"SELECT followed_id FROM relationships\n\t\tWHERE follower_id = :user_id\"\n\t\tPost.where(\"user_id IN (#{following_ids})\n\t\t\tOR user_id = :user_id\", user_id: id)\n\tend", "def has_new?\n return true if @last_post_time.nil?\n \n Net::HTTP.start @thread_url.host, 80 do |http|\n response = http.head(@thread_url.path)\n raise Thread404dError if response.code.to_i == 404 # .to_i because net/http is retarded.\n Time.parse(response['Last-Modified']) > @last_post_time\n end\n end", "def show\n @post = current_user.posts.build\n @user = User.find(params[:id])\n if current_user == @user\n @posts = current_user.feed.paginate(page: params[:page]) \n else\n @posts = @user.posts.paginate(page: params[:page])\n end\n end", "def feed_after(latest_update) \n\tif latest_update.present? \n\t\tself.feed.where(\"microposts.updated_at > ?\", latest_update)\n\tend\n end", "def send_news\n feed = RSS::Parser.parse open(KAGDEV_RSS).read\n last_post_title = feed.channel.item.title\n\n # Check, whether the latest title of the post at KAG development\n # blog is still the same, as it was, when the fetcher checked it last\n # time.\n return if unchanged?(last_post_title)\n\n item = feed.channel.item\n\n last_post_date = item.pubDate\n last_post_author = item.dc_creator\n last_post_link = item.link\n\n News.create(\n :title => last_post_title,\n :date => last_post_date,\n :author => last_post_author,\n :link => last_post_link\n )\n\n real_author = reveal_author(last_post_author)\n short_link = open(\"http://clck.ru/--?url=#{last_post_link}\").read\n\n Bot::CHANNELS.each do |chan|\n Channel(chan).send I18n.news_fetcher.news(real_author, last_post_title, short_link)\n end\n rescue SocketError\n nil\n end", "def feed\n @posts = Post.feed_of(params[:id])\n end", "def turn_to_status_post\n fail_with! 'Post already is StatusPost' if @post.status?\n\n if @post.uploads.count.zero?\n @post.type = 'StatusPost'\n @post.title = nil\n @post.save or fail_with! @post.errors\n\n FeedEventsManager.new(user: user, target: @post).turn_to_status_event\n\n @post.elastic_index_document\n @post\n end\n end", "def seller_post? listing, user, ptype\n !user.is_support? && ptype.blank? && listing.new_record?\n end", "def load_remote_feed!\n @live = true\n if self.http_headers.nil? && !(self.cache_object.nil?) &&\n !(self.cache_object.http_headers.nil?)\n @http_headers = YAML.load(self.cache_object.http_headers)\n end\n \n if (self.href =~ /^feed:/) == 0\n # Woah, Nelly, how'd that happen? You should've already been\n # corrected. So let's fix that url. And please,\n # just use less crappy browsers instead of badly defined\n # pseudo-protocol hacks.\n self.href = FeedTools::UriHelper.normalize_url(self.href)\n end\n \n # Find out what method we're going to be using to obtain this feed.\n begin\n uri = URI.parse(self.href)\n rescue URI::InvalidURIError\n raise FeedAccessError,\n \"Cannot retrieve feed using invalid URL: \" + self.href.to_s\n end\n retrieval_method = \"http\"\n case uri.scheme\n when \"http\"\n retrieval_method = \"http\"\n when \"ftp\"\n retrieval_method = \"ftp\"\n when \"file\"\n retrieval_method = \"file\"\n when nil\n raise FeedAccessError,\n \"No protocol was specified in the url.\"\n else\n raise FeedAccessError,\n \"Cannot retrieve feed using unrecognized protocol: \" + uri.scheme\n end\n \n # No need for http headers unless we're actually doing http\n if retrieval_method == \"http\"\n begin\n @http_response = (FeedTools::RetrievalHelper.http_get(\n self.href, :feed_object => self) do |url, response|\n # Find out if we've already seen the url we've been\n # redirected to.\n follow_redirect = true\n\n begin\n cached_feed = FeedTools::Feed.open(url,\n :disable_update_from_remote => true)\n if cached_feed.cache_object != nil &&\n cached_feed.cache_object.new_record? != true\n if !cached_feed.expired? &&\n !cached_feed.http_headers.blank?\n # Copy the cached state\n self.href = cached_feed.href\n \n @feed_data = cached_feed.feed_data\n @feed_data_type = cached_feed.feed_data_type\n \n if @feed_data.blank?\n raise \"Invalid cache data.\"\n end\n \n @title = nil; self.title\n self.href\n @link = nil; self.link\n \n self.last_retrieved = cached_feed.last_retrieved\n self.http_headers = cached_feed.http_headers\n self.cache_object = cached_feed.cache_object\n @live = false\n follow_redirect = false\n end\n end\n rescue\n # If anything goes wrong, ignore it.\n end\n follow_redirect\n end)\n case @http_response\n when Net::HTTPSuccess\n @feed_data = self.http_response.body\n @http_headers = {}\n self.http_response.each_header do |key, value|\n self.http_headers[key.downcase] = value\n end\n self.last_retrieved = Time.now.gmtime\n @live = true\n when Net::HTTPNotModified\n @http_headers = {}\n self.http_response.each_header do |key, value|\n self.http_headers[key.downcase] = value\n end\n self.last_retrieved = Time.now.gmtime\n @live = false\n else\n @live = false\n end\n rescue Exception => error\n @live = false\n if self.feed_data.nil?\n raise error\n end\n end\n elsif retrieval_method == \"https\"\n # Not supported... yet\n elsif retrieval_method == \"ftp\"\n # Not supported... yet\n # Technically, CDF feeds are supposed to be able to be accessed\n # directly from an ftp server. This is silly, but we'll humor\n # Microsoft.\n #\n # Eventually. If they're lucky. And someone demands it.\n elsif retrieval_method == \"file\"\n # Now that we've gone to all that trouble to ensure the url begins\n # with 'file://', strip the 'file://' off the front of the url.\n file_name = self.href.gsub(/^file:\\/\\//, \"\")\n if RUBY_PLATFORM =~ /mswin/\n file_name = file_name[1..-1] if file_name[0..0] == \"/\"\n end\n begin\n open(file_name) do |file|\n @http_response = nil\n @http_headers = {}\n @feed_data = file.read\n @feed_data_type = :xml\n self.last_retrieved = Time.now.gmtime\n end\n rescue\n @live = false\n # In this case, pulling from the cache is probably not going\n # to help at all, and the use should probably be immediately\n # appraised of the problem. Raise the exception.\n raise\n end\n end\n unless self.cache_object.nil?\n begin\n self.save\n rescue\n end\n end\n end", "def default_facebook\n post.new_record?\n end", "def sender_can_bill?\n !posts.detect { |post| post.can_bill? user }.nil?\n end", "def create_feed\n end", "def create_feed\n end", "def create_feed\n end", "def create_feed\n end", "def new_submission?(item)\n !existing_entry?(item)\n end", "def poll\n current = WebClient.new(api_key: @api_key).get(@feed.api_id)\n if Utils.diff(@feed.latest, current)\n Entry.new(feed_id: @feed.id, content: current).save!\n end\n\n @feed.latest\n end", "def gather_feed_items(user = nil)\n if user\n # Notes left on your posts and pictures\n notes_on_your_posts = []\n\n user.posts.each do |post|\n notes_on_your_posts = smush(notes_on_your_posts, post.notes)\n post.pictures.each do |picture|\n notes_on_your_posts = smush(notes_on_your_posts, picture.notes)\n end\n end\n\n # Notes left by people the current user is following\n notes_left_by_followees = []\n\n # Notes left on posts owned by people the current user is following\n notes_left_on_followees_posts = []\n\n # Notes left on pictures owned by people the current user is following\n notes_left_on_followees_pictures = []\n\n # Posts created by people the current user is following\n posts_by_followees = []\n\n # Followings of people the current user is following\n following_followees = []\n\n # People the current user is following, following other people\n followees_following = []\n\n user.followees.each do |followee|\n posts_by_followees = smush(posts_by_followees, followee.posts)\n notes_left_by_followees = smush(notes_left_by_followees, followee.notes)\n\n followee.posts.each do |post|\n notes_left_on_followees_posts = smush(notes_left_on_followees_posts, post.notes)\n post.pictures.each do |picture|\n notes_left_on_followees_pictures = smush(notes_left_on_followees_pictures, picture.notes)\n end\n end\n\n following_followees = smush(following_followees, Follow.find_all_by_followee_id(followee.id, :conditions => \"follower_id <> #{user.id}\"))\n followees_following = smush(followees_following, Follow.find_all_by_follower_id(followee.id, :conditions => \"follower_id <> #{user.id}\"))\n end\n\n # Remove totally blank posts from feed\n posts_by_followees.each do |post|\n if post.title.blank? and post.content.blank? and post.pictures.length == 0\n posts_by_followees.delete(post)\n end\n end\n blavel_posts = User.find_by_login('blavel') ? User.find_by_login('blavel').posts : nil\n posts = smush(posts_by_followees, blavel_posts)\n if posts\n posts = posts.uniq\n end\n\n # Remove notes left by logged in user\n notes = smush(notes_on_your_posts, notes_left_by_followees, notes_left_on_followees_posts, notes_left_on_followees_pictures)\n notes.each do |note|\n if note.user == user\n notes.delete(note)\n end\n end\n notes = notes.uniq\n\n # Add together follows\n following_you = Follow.find_all_by_followee_id(user.id)\n follows = smush(following_you, following_followees, followees_following)\n follows = follows.uniq\n else\n # If no user is specified, return all feed items\n notes = Note.find(:all)\n posts = Post.find(:all)\n follows = Follow.find(:all)\n\n # Remove totally blank posts from feed\n posts.each do |post|\n if post.title.blank? and post.content.blank? and post.pictures.length == 0\n posts.delete(post)\n end\n end\n end\n\n feed_items = smush(notes, posts, follows)\n feed_items.sort! { |x,y| y.created_at <=> x.created_at }\n feed_items = feed_items[0..19]\n\n return feed_items\n end", "def blogrss_check\n begin\n unless blogrss.blank?\n RestClient.get blogrss\n end\n rescue\n errors.add :base, \"Invalid Blog URL\"\n end\n end", "def check_last_public_story\n return unless (user.last_public_story_id == id && !allowed_in_public_feed?) ||\n (user.last_public_story_id != id && allowed_in_public_feed?)\n\n # Get the next most recent public story that's allowed in the public feed, if there is one\n stories = NonFriendStoriesList.new(id: user.id).paginate_messages(limit: 20)\n story = stories.reverse.detect{ |story| story.allowed_in_public_feed? }\n user.update_last_public_story(story, true)\n end", "def add_feed_url\n return false if parse_feed_url.nil?\n update_attribute(:feed_url, parse_feed_url)\n end", "def activity_feed_message(activity)\r\n user = activity.user\r\n case activity.item_type\r\n when \"Friendship\"\r\n friendship = activity.item\r\n %(#{user_link(user)} became friends with #{link_to friendship.friend.name, '/users/' + friendship.friend.id.to_s} <span class=\"activity_date\">#{friendship.updated_at.to_s(:event_list)}</span>) \r\n when \"Event\"\r\n event = activity.item\r\n %(#{user_link(user)} added a new event - #{link_to event.name, '/events/'+event.id.to_s} #{activity_date(event)})\r\n when \"User\"\r\n if user\r\n %(#{user_link(user)} joined. #{activity_date(user)})\r\n else\r\n %(A former user joined. #{activity_date(activity)}) \r\n end\r\n when \"Photo\"\r\n if activity.action == 'destroy'\r\n %(<span class=\"activity_text\"><span class=\"activity_user_link\">#{user_link(user)}</span> deleted a photo.</span>#{activity_date(activity)})\r\n else\r\n if activity.item\r\n photo = Photo.find(activity.item.id, :select=>\"id, user_id, filename, parent_id, created_at\")\r\n %(<span class=\"activity_text\"><span class=\"activity_user_link\">#{user_link(user)}</span> uploaded a photo - <a href=\"/photos/#{photo.id}\">#{image_tag(photo.public_filename(:small))}</a>.</span>#{activity_date(photo)})\r\n else\r\n # photo no longer exists, but still need to display upload event for history\r\n %(<span class=\"activity_text\"><span class=\"activity_user_link\">#{user_link(user)}</span> uploaded a photo.</span>#{activity_date(activity)})\r\n end\r\n end \r\n when \"Group\"\r\n group = activity.item\r\n if group\r\n %(A new group was created, #{link_to(group.name, group_url(group))} #{activity_date(group)})\r\n else\r\n %(A new group was created, group no longer exists)\r\n end\r\n when \"BlogPost\"\r\n blog_post = activity.item\r\n if blog_post\r\n %(#{user_link(user)} posted a new blog entry, <a href=\"/blog_posts/#{blog_post.id}\">#{blog_post.title}</a>. #{activity_date(blog_post)})\r\n else\r\n %(#{user_link(user)} posted a new blog entry.) \r\n end\r\n when \"Attendance\"\r\n if activity.item\r\n attendance = activity.item\r\n %(#{user_link(user)} is attending the event, #{link_to attendance.event.name, 'events/' + attendance.event.id.to_s}. #{activity_date(attendance)})\r\n else\r\n # attendance no longer exists, user has canceled\r\n %(#{image_tag(user.profile_photo.public_filename(:small))}#{user_link(user)} signed up for an event, but has since revoked that decision.)\r\n end\r\n when \"Membership\"\r\n membership = activity.item\r\n %(<span class=\"activity_text\"><span class=\"activity_user_link\">#{user_link(user)}</span> joined the group, <a href=\"/groups/#{membership.group.id}\">#{membership.group.name}</a>. </span>#{activity_date(membership)})\r\n when \"ForumPost\"\r\n forum_post = activity.item\r\n %(#{user_link(user)} posted a new message to the forum, <a href=\"/forum_posts/#{forum_post.id}\">#{forum_post.title}</a>. #{activity_date(forum_post)})\r\n when \"JobPost\"\r\n job_post = activity.item\r\n if job_post\r\n %(A new job was posted - #{link_to(job_post.job_title, job_posts_url)}. #{activity_date(job_post)})\r\n else\r\n # the job post has been deleted\r\n %(A new job was posted. #{activity_date(activity)})\r\n end\r\n when \"BookReview\"\r\n book_review = activity.item\r\n %(#{user.name} posted a new review for #{book_review.name}. #{activity_date(book_review)}) \r\n when \"StatusPost\"\r\n status_post = activity.item\r\n %(<span class=\"activity_text\"><span class=\"activity_user_link\">#{user_link(user)}</span> #{EngineyUtil.linkify(status_post.body)}</span>#{activity_date(status_post)})\r\n when \"Link\"\r\n link = activity.item\r\n if link\r\n %(#{user_link(user)} posted a new link #{link_to link.url, link.url} #{activity_date(link)})\r\n else\r\n # the link was deleted\r\n %(#{user_link(user)} posted a new link)\r\n end\r\n when \"Project\"\r\n project = activity.item\r\n if project\r\n %(#{user_link(user)} added a new project #{link_to project.name, project.url} #{activity_date(project)})\r\n else \r\n # the project was deleted\r\n %(#{user_link(user)} added a new project #{activity_date(activity)})\r\n end\r\n when \"Announcement\"\r\n announcement = activity.item\r\n if announcement\r\n %(#{user_link(user)} posted a new announcement, <b>#{announcement.title}</b> #{activity_date(announcement)})\r\n else\r\n %(#{user_link(user)} posted a new announcement #{activity_date(activity)})\r\n end\r\n when \"Classified\"\r\n classified = activity.item\r\n %(#{user_link(user)} posted a new classified, #{link_to classified.title, classified_url(classified)})\r\n else\r\n %(Invalid activity type - #{activity.item_type})\r\n end\r\n end", "def posts_feed\n\n init_posts_feed\n\n end", "def index\n @user = User.find(params[:user_id])\n @posts = Post.feed_items(@user)\n @post = Post.new\n end", "def ready_to_post?\n self.state == 'ready_to_post'\n end", "def fetch!\n parsed_feed = FeedNormalizer::FeedNormalizer.parse open(self.feed_url)\n \n self.update_attributes( :title => parsed_feed.title,\n :url => parsed_feed.url\n #:etag => parsed_feed.etag\n #:last_modified => parsed_feed.last_modified\n )\n \n parsed_feed.entries.each do |entry|\n self.entries.create(:url => entry.url,\n :title => entry.title,\n :author => entry.author,\n #:summary => entry.summary,\n :content => entry.content\n #:published => entry.published\n #:categories => entry.categories\n ) if !Entry.find_by_url(entry.url)\n end\n end", "def create_feed!\n feed = find_feed_locally(@url)\n\n # If we already have this feed, then just return it.\n return feed if feed\n\n # Fetch the feed from remote and try to parse it using the defined parsers.\n parser = fetch_feed\n\n # Again, check the localDB for a feed matching the final url in case of redirection\n # For example: if the url: https://www.7iber.com/feed\n # it will be redirected to to https://www.7iber.com/feed/\n feed = find_feed_locally(remote_response.uri.to_s)\n return feed if feed\n\n create_feed_from_parser(parser)\n end", "def feed\n # defer to Micropost.from_users_followed_by\n Micropost.from_users_followed_by(self)\n end", "def should_fetch?\n last_fetched_at.nil? or !fetched_directly? or facebook_api_error.present?\n end", "def add_feed name, url, type\n if Feed.find_by_name(name).nil?\n Feed.create(name: name, url: url, feed_type: type, updated_date: Date.yesterday)\n end\nend", "def push_post_through_topic(post, push_topic, single_user=nil, backlog=false)\n return unless post\n\n neo4j_topic_ids = Neo4j.pulled_from_ids(push_topic.neo4j_id)\n topics = Topic.where(:_id => {\"$in\" => [push_topic.id] + neo4j_topic_ids.map{|t| t}})\n\n # make the root post\n root_post = RootPost.new\n root_post.post = post\n\n topics.each do |topic|\n # the potential users this post can be pushed to\n if single_user\n user_feed_users = [single_user]\n else\n user_feed_users = User.only(:id, :following_topics).where(:following_topics => topic.id)\n end\n\n user_feed_users.each do |u|\n next if post.get_share(u.id) # don't distribute posters own posts based on the topics they're following\n\n item = FeedUserItem.where(:user_id => u.id, :post_id => post.id).first\n\n unless item\n post.pushed_users_count += 1\n item = FeedUserItem.new(:user_id => u.id, :post_id => post.id)\n item.created_at = backlog ? post.created_at : Time.now\n item.post_type = post._type\n end\n\n # add following topic reason\n if push_topic.id == topic.id && u.following_topics && u.following_topics.include?(topic.id)\n item.add_reason('ft', topic)\n elsif u.following_topics.include?(topic.id) # following topic related to another topic you're following\n item.add_reason('frt', topic, push_topic)\n end\n\n if item.reasons.length > 0\n item.save\n\n root_post.push_item = item\n\n # if it's a new feed post, push it to the users feed\n unless backlog\n Pusher[\"#{u.username}_realtime\"].trigger('new_post', root_post.as_json(:properties => :short))\n end\n end\n end\n end\n\n post.save\n end", "def check_for_posts\n if self.posts.any?\n errors[:base] << \"cannot delete Topic tag when posts are using it!\"\n return false\n else\n return true\n end\n end", "def is_blog_article?\n !current_article.nil?\n end", "def is_denied?\n (self.denied_feeds.count > 0)\n end", "def can_bill? usr\n !posts.detect { |post| post.can_bill? usr }.nil?\n end", "def edit\n\n # Show CET/CEST time to the user starting from the UTC time in the Database\n # TODO: have a better solution (see create action)\n @feed.date = @feed.date + 2.hour \n\n if @feed.user_id != current_user.id\n err_mex \n elsif @feed.has_been_published == true\n flash[:notice] = \"Non puoi modificare feed gia' pubblicati\"\n render \"show\"\n end\n\n end", "def show\n @post = Post.new\n @posts = @event.posts\n @is_member = @event.try(:members).exists?(:user_id => current_user.id)\n end", "def is_post_exist?\n @post = current_user.posts.where(:id => params[:id]).first\n unless @post.present?\n redirect_to user_posts_path, notice: 'You dont have access to requested post'\n end\n end", "def feed\n\t\tMicropost.where(\"user_id IN (?) OR user_id = ?\", following_ids, id)\n \n\tend", "def pending_repost?\n self.review_status_id == ReviewStatus.find(:first,\n :conditions => \"name='Pending Repost'\").id\n end" ]
[ "0.70568943", "0.6994355", "0.6989487", "0.66720164", "0.6630223", "0.64489996", "0.64114517", "0.632869", "0.6325523", "0.632544", "0.6248006", "0.6207678", "0.61979693", "0.61706525", "0.6158824", "0.61478025", "0.61162364", "0.6111978", "0.60858166", "0.60746443", "0.606473", "0.6054588", "0.6044898", "0.604357", "0.6040592", "0.6027946", "0.60123575", "0.60082823", "0.5998008", "0.5990688", "0.5987347", "0.5977515", "0.59627795", "0.59543914", "0.5941912", "0.5938495", "0.5938495", "0.59355086", "0.59081876", "0.5901492", "0.5901492", "0.5898998", "0.58977544", "0.5880335", "0.58737904", "0.5870549", "0.5869142", "0.58688563", "0.58612734", "0.5843261", "0.58341235", "0.5828571", "0.5819114", "0.57898545", "0.57826704", "0.5760142", "0.57501036", "0.57394403", "0.5730323", "0.57075185", "0.57054806", "0.5702593", "0.5697962", "0.56965786", "0.5684635", "0.56806505", "0.5679347", "0.5656448", "0.5654929", "0.56489164", "0.5648298", "0.56410056", "0.56410056", "0.56410056", "0.56410056", "0.56366247", "0.56355923", "0.56348616", "0.56321764", "0.5628309", "0.5625485", "0.56190014", "0.56150216", "0.56124365", "0.56085193", "0.55931413", "0.55906546", "0.5588536", "0.55877364", "0.55827016", "0.5581288", "0.5578257", "0.55733615", "0.55727094", "0.55668896", "0.55627483", "0.556199", "0.5560093", "0.55559933", "0.555446" ]
0.682481
3
Returns a collection that represents the instances belonging to this Auto Scaling group. You can use this collection to further refine the instances you are interested in: group.ec2_instances.filter('availabilityzone', 'useast1a').each do |i| puts instance.id end
def ec2_instances instances = EC2::InstanceCollection.new(:config => config) instances.tagged('aws:autoscaling:groupName').tagged_values(name) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_instances(incl_stopped=false)\n \n instances = @ec2.describe_instances\n instances = instances.select { |x| x[:aws_groups].include? @group_name }\n \n if(instances.length == 0)\n raise CaTPAWS::EC2::Error::InstanceRetrieval, \"No instances found in this group\"\n end \n \n unless (incl_stopped)\n instances = instances.select {|x| x[:aws_state_code].to_i <= 16}\n end\n @instances = instances\n end", "def instances\n @instances ||= aws_client.instances(filters: instance_filters).map do |instance|\n OpenStruct.new(\n with_tags(instance, private_ip: instance.private_ip_address,\n public_ip: instance.public_ip_address,\n instance: instance.instance_id)\n )\n end\n end", "def instance_ids\n @instance_ids ||= groups.map { |gr| gr.instances.map { |i| i.instance_id } }.flatten\n end", "def get_instances\n all_instances = Array.new()\n @groups.values.each do |instances|\n instances.each do |instance|\n all_instances << instance\n end\n end\n all_instances\n end", "def autoscaling_instances\n autoscaling_group.auto_scaling_instances\n end", "def autoscaling_instances\n autoscaling_group.auto_scaling_instances\n end", "def list_instances_detail()\n response = dbreq(\"GET\", dbmgmthost, \"#{dbmgmtpath}/instances/detail\", dbmgmtport, dbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end", "def id( )\n return @instances.map{ |i| i[:aws_instance_id] }\n end", "def instances\n IbmCloudRest.get \"#{@uri}/instances\"\n end", "def list_instances()\n response = dbreq(\"GET\", dbmgmthost, \"#{dbmgmtpath}/instances\", dbmgmtport, dbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end", "def instances\n Egi::Fedcloud::Vmhound::Log.info \"[#{self.class}] Retrieving active instances\"\n fetch_instances\n end", "def list_asgs\n # collect the list of running instances in this zone\n ec2 = AWS::EC2.new\n region = ec2.regions[AMI_REGION]\n instances = region.instances.select { |i| i.tags.to_h[\"server\"] == APP_NAME }\n\n # now find the list of running asgs\n format = \"%-32s %s\"\n puts\n puts format % [\"Instance Groups\", \"Tags\"]\n puts format % [\"-\" * 32, \"-\" * 60]\n auto_scaling = new_auto_scaling\n count = 0\n auto_scaling.groups.each do |group|\n count = count + 1\n puts format % [group.name, tag_value(group.tags, \"env\")]\n\n instances.each do |i|\n if i.tags.to_h[\"env\"] == tag_value(group.tags, \"env\")\n puts \"\\t%s %-13s %s\" % [i.id, i.status, i.dns_name]\n end\n end\n puts\n end\n puts format % [\"-\" * 32, \"-\" * 60]\n puts \"Found #{count} ASGs\"\n puts\nend", "def get_instances(group)\n raise \"unknown group: #{group}\" if !@groups.key? group\n @groups[group].dup\n end", "def instances\n instances = []\n JSON.parse(resource['/instances'].get)[\"instances\"].each do |i|\n instances << Instance.new(i)\n end\n return instances\n end", "def instances()\n return @instances\n end", "def instances_list\n return [] unless configured?\n\n @service.fetch_all do |token|\n @service.list_instances(@gcp_config['project'], @gcp_config['zone'], page_token: token)\n end.map(&:name)\n end", "def id_instances\n @id_instances ||= Hash[instances.map { |i| [i.instance_id, i] }]\n end", "def active_instances\n Egi::Fedcloud::Vmhound::Log.info \"[#{self.class}] Retrieving running instances\"\n fetch_instances ['ACTIVE']\n end", "def get_instances_description\n instances\n end", "def describe_instances( options = {} )\n options = { :instance_id => [] }.merge(options)\n params = pathlist(\"InstanceId\", options[:instance_id])\n return response_generator(:action => \"DescribeInstances\", :params => params)\n end", "def list_instances()\n response = dbreq(\"GET\",lbmgmthost,\"#{lbmgmtpath}/instances\",lbmgmtport,lbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end", "def instances_for_filter(filter_name, filter_value, state = \"running\")\n ec2.describe_instances(\n filters: [\n { name: filter_name, values: [filter_value] },\n { name: \"tag:environment\", values: [name] },\n { name: \"instance-state-name\", values: [state] }\n ])[:reservations]\n end", "def init_instances\n instances = []\n next_token = nil\n all_records_retrieved = false\n\n until all_records_retrieved\n response = @@client.describe_instances({\n next_token: next_token\n })\n next_token = response.next_token\n all_records_retrieved = next_token.nil? || next_token.empty?\n instances << response.reservations.map { |r| r.instances }\n end\n\n instances.flatten\n end", "def get_running_instances(group)\n get_instances(group).select{ |instance| instance.ready? }\n end", "def get_instances\n instances = [ ]\n get_clouds.each do |cloud|\n instances += cloud.instances.index(:filter => [], :view => 'tiny')\n end\n instances\n end", "def aws_instance_get(opts)\n AWS::EC2.new.instances[opts[:instance_id]]\n end", "def stop_instances_by_group_id(group_id)\n instances = @os_aws.describe_running_instances(group_id)\n ids = instances.map { |k, _| k[:instance_id] }\n\n puts \"Stoping the following instances #{ids}\"\n resp = []\n resp = @os_aws.stop_instances(ids).to_hash unless ids.empty?\n resp\n end", "def right_aws\n cloud_provider.ec2.describe_instances instance_id\n end", "def ec2_instance_data\n # Support for looking up security group id and subnet id using tags.\n vpc_id = nil\n client = ::Aws::EC2::Client.new(region: config[:region])\n if config[:subnet_id].nil? && config[:subnet_filter]\n filters = [config[:subnet_filter]].flatten\n\n r = { filters: [] }\n filters.each do |subnet_filter|\n r[:filters] <<\n {\n name: \"tag:#{subnet_filter[:tag]}\",\n values: [subnet_filter[:value]],\n }\n end\n\n subnets = client.describe_subnets(r).subnets\n raise \"Subnets with tags '#{filters}' not found during security group creation\" if subnets.empty?\n\n # => Select the least-populated subnet if we have multiple matches\n subnet = subnets.max_by { |s| s[:available_ip_address_count] }\n vpc_id = subnet.vpc_id\n config[:subnet_id] = subnet.subnet_id\n end\n\n if config[:security_group_ids].nil? && config[:security_group_filter]\n # => Grab the VPC in the case a Subnet ID rather than Filter was set\n vpc_id ||= client.describe_subnets(subnet_ids: [config[:subnet_id]]).subnets[0].vpc_id\n security_groups = []\n filters = [config[:security_group_filter]].flatten\n filters.each do |sg_filter|\n r = {}\n if sg_filter[:name]\n r[:filters] = [\n {\n name: \"group-name\",\n values: [sg_filter[:name]],\n },\n {\n name: \"vpc-id\",\n values: [vpc_id],\n },\n ]\n end\n\n if sg_filter[:tag]\n r[:filters] = [\n {\n name: \"tag:#{sg_filter[:tag]}\",\n values: [sg_filter[:value]],\n },\n {\n name: \"vpc-id\",\n values: [vpc_id],\n },\n ]\n end\n\n security_group = client.describe_security_groups(r).security_groups\n\n if security_group.any?\n security_group.each { |sg| security_groups.push(sg.group_id) }\n else\n raise \"A Security Group matching the following filter could not be found:\\n#{sg_filter}\"\n end\n end\n config[:security_group_ids] = security_groups\n end\n\n i = {\n instance_type: config[:instance_type],\n ebs_optimized: config[:ebs_optimized],\n image_id: config[:image_id],\n key_name: config[:aws_ssh_key_id],\n subnet_id: config[:subnet_id],\n private_ip_address: config[:private_ip_address],\n min_count: 1,\n max_count: 1,\n }\n\n if config[:tags] && !config[:tags].empty?\n tags = config[:tags].map do |k, v|\n # we convert the value to a string because\n # nils should be passed as an empty String\n # and Integers need to be represented as Strings\n { key: k, value: v.to_s }\n end\n instance_tag_spec = { resource_type: \"instance\", tags: tags }\n volume_tag_spec = { resource_type: \"volume\", tags: tags }\n i[:tag_specifications] = [instance_tag_spec, volume_tag_spec]\n end\n\n availability_zone = config[:availability_zone]\n if availability_zone\n if /^[a-z]$/i.match?(availability_zone)\n availability_zone = \"#{config[:region]}#{availability_zone}\"\n end\n i[:placement] = { availability_zone: availability_zone.downcase }\n end\n tenancy = config[:tenancy]\n if tenancy\n if i.key?(:placement)\n i[:placement][:tenancy] = tenancy\n else\n i[:placement] = { tenancy: tenancy }\n end\n end\n unless config[:block_device_mappings].nil? || config[:block_device_mappings].empty?\n i[:block_device_mappings] = config[:block_device_mappings]\n end\n i[:security_group_ids] = Array(config[:security_group_ids]) if config[:security_group_ids]\n i[:metadata_options] = config[:metadata_options] if config[:metadata_options]\n i[:user_data] = prepared_user_data if prepared_user_data\n if config[:iam_profile_name]\n i[:iam_instance_profile] = { name: config[:iam_profile_name] }\n end\n unless config.fetch(:associate_public_ip, nil).nil?\n i[:network_interfaces] =\n [{\n device_index: 0,\n associate_public_ip_address: config[:associate_public_ip],\n delete_on_termination: true,\n }]\n # If specifying `:network_interfaces` in the request, you must specify\n # network specific configs in the network_interfaces block and not at\n # the top level\n if config[:subnet_id]\n i[:network_interfaces][0][:subnet_id] = i.delete(:subnet_id)\n end\n if config[:private_ip_address]\n i[:network_interfaces][0][:private_ip_address] = i.delete(:private_ip_address)\n end\n if config[:security_group_ids]\n i[:network_interfaces][0][:groups] = i.delete(:security_group_ids)\n end\n end\n availability_zone = config[:availability_zone]\n if availability_zone\n if /^[a-z]$/i.match?(availability_zone)\n availability_zone = \"#{config[:region]}#{availability_zone}\"\n end\n i[:placement] = { availability_zone: availability_zone.downcase }\n end\n tenancy = config[:tenancy]\n if tenancy\n if i.key?(:placement)\n i[:placement][:tenancy] = tenancy\n else\n i[:placement] = { tenancy: tenancy }\n end\n end\n unless config[:instance_initiated_shutdown_behavior].nil? ||\n config[:instance_initiated_shutdown_behavior].empty?\n i[:instance_initiated_shutdown_behavior] = config[:instance_initiated_shutdown_behavior]\n end\n i\n end", "def get_instance_reservations(filters = {})\n AWS.memoize do\n @ec2.regions['us-west-1'].reserved_instances.select do |ins|\n filters.reduce(true) do |memo, filter_kvp|\n memo && ins.send(filter_kvp[0]) == filter_kvp[1]\n end\n end\n end\n end", "def db_instances(region)\n logger.info(\"fetching db instances of region #{region}\")\n rds_client = get_rds_client(region)\n next_token = nil\n rds_instances = []\n\n loop do\n options = { marker: next_token }\n resp = rds_client.describe_db_instances(options)\n rds_instances += resp.db_instances\n next_token = resp.marker\n break unless next_token\n end\n rds_instances\n end", "def fetch_instance(shortname = :all, options = {})\n return instances if instances && !options[:force]\n\n fetch_stack\n unless instance_list\n self.instance_list = self.instances =\n aws_client.describe_instances(stack_id: stack[:stack_id])[:instances]\n end\n\n if shortname != :all\n fetch_layer(shortname, force: true)\n self.instances = []\n\n layers.each do |layer|\n instance = aws_client.describe_instances(\n layer_id: layer[:layer_id])\n self.instances << instance[:instances]\n end\n\n self.instances.flatten!\n end\n end", "def instance_list(next_token=nil)\n self.ec2_client.describe_instances(\n {\n filters: [\n {\n name: \"tag:Branch\",\n values: [\"*\"],\n },\n {\n name: \"instance-state-name\",\n values: [\"running\"],\n }\n ],\n next_token: next_token\n })\n end", "def instance\n node = 'AWS_EC2_INSTANCE'\n q = []\n\n # instance node\n q.push(_upsert({ node: node, id: @name }))\n\n # vpc node and relationship\n if @data.vpc_id\n opts = {\n parent_node: node,\n parent_name: @name,\n child_node: 'AWS_VPC',\n child_name: @data.vpc_id,\n relationship: 'MEMBER_OF_VPC'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n # network_interfaces and relationship\n @data.network_interfaces.each do |ni|\n opts = {\n parent_node: node,\n parent_name: @name,\n child_node: 'AWS_NETWORK_INTERFACE',\n child_name: ni.network_interface_id,\n relationship: 'ATTACHED_TO_INSTANCE'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n # security_groups and relationship\n @data.security_groups.each do |sg|\n opts = {\n child_node: 'AWS_SECURITY_GROUP',\n child_name: sg.group_id,\n parent_node: node,\n parent_name: @name,\n relationship: 'IN_SECURITY_GROUP'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n # subnet and relationship\n if @data.subnet_id\n opts = {\n parent_node: node,\n parent_name: @name,\n child_node: 'AWS_SUBNET',\n # child_name: \"arn:aws:ec2:#{@region}:#{@account}:subnet/#{@data.subnet_id}\",\n child_name: @data.subnet_id,\n relationship: 'IN_SUBNET'\n }\n\n q.push(_upsert_and_link(opts))\n end\n\n if @data.iam_instance_profile\n opts = {\n node: 'AWS_EC2_IAM_PROFILE',\n id: @data.iam_instance_profile.arn\n }\n\n q.push(_merge(opts))\n\n opts = {\n from_node: node,\n from_name: @name,\n to_node: 'AWS_EC2_IAM_PROFILE',\n to_name: @data.iam_instance_profile.arn,\n relationship: 'HAS_IAM_PROFILE'\n }\n\n q.push(_link(opts))\n end\n\n if @data.metadata_options\n metadata_options = \"#{@name}-metadata-options\"\n\n opts = {\n node: 'AWS_EC2_INSTANCE_METADATA_OPTIONS',\n id: metadata_options\n }\n\n q.push(_merge(opts))\n\n opts = {\n from_node: node,\n from_name: @name,\n to_node: 'AWS_EC2_INSTANCE_METADATA_OPTIONS',\n to_name: metadata_options,\n relationship: 'HAS_METADATA_OPTIONS',\n relationship_attributes: @data.metadata_options.to_h\n }\n\n q.push(_link(opts))\n end\n\n q\n end", "def instances\n @instances ||= []\n end", "def describe_all_instances\n @os_aws.describe_all_instances\n end", "def instances_action(action)\n opts = {}\n opts[:group] = @option.group if @option.group\n opts[:id] = @argv.instid if @argv.instid\n opts[:id] &&= [opts[:id]].flatten\n \n instances = Rudy::AWS::EC2::Instances.list_group(opts[:group], :running, opts[:id])\n raise \"No matching instances running\" if instances.nil?\n \n inst_names = instances.collect { |inst| inst.dns_public || inst.awsid }\n inst_ids = instances.collect { |inst| inst.awsid }\n \n instance_count = (instances.size == 1) ? '1 instance' : \"#{instances.size} instances\"\n \n print \"#{action.to_s.capitalize} #{instance_count} (#{inst_names.join(', ')}) \"\n print \"in #{opts[:group]}\" if opts[:group]\n li\n execute_check(:medium)\n \n execute_action(\"#{action.to_s.capitalize} Failed\") { \n Rudy::AWS::EC2::Instances.send(action, inst_ids)\n }\n status\n end", "def container_instances\n instances = []\n @client.describe_tasks(cluster: @cluster, tasks: tasks)[0].each do |e|\n instances << e[:container_instance_arn]\n end\n instances\n end", "def describe_container_instances(params={})\n if instances = params.delete('containerInstances')\n params.merge!(Fog::AWS.indexed_param('containerInstances.member', [*instances]))\n end\n\n request({\n 'Action' => 'DescribeContainerInstances',\n :parser => Fog::Parsers::AWS::ECS::DescribeContainerInstances.new\n }.merge(params))\n end", "def running_hosts_in_asg(asg_name)\n return nil unless asg_name\n asg = @auto_scaling.groups[asg_name]\n return nil unless asg\n # return a lost of maps having the list of running instances\n asg.auto_scaling_instances.collect { |i|\n if i.health_status != 'Healthly'\n ec2instance = i.ec2_instance.dns_name\n {\n :instance_id => ec2instance.id,\n :health_status => i.health_status,\n :public_dns => ec2instance.dns_name,\n :ip => ec2instance.ip_address\n }\n else\n nil\n end }.compact!.sort { |x,y| x.instance_id <=> y.instance_id }\n end", "def stop\n puts \"Stoping any instance with group ID: #{@os_aws.group_uuid}\"\n\n stop_instances_by_group_id(@os_aws.group_uuid)\n end", "def instances\n @instances ||= init_instances.reject(&:terminated?)\n end", "def availability_zones\n @group.availability_zones\n end", "def get_instances_description\n @cached_descriptions ||= EC2ResponseObject.get_descriptions(ec2.describe_instances).sort_by {|a| a[:launching_time]}\n end", "def ec2_security_groups\n data.ec2_security_groups\n end", "def describe_instances\n return { reservations: [] } unless configured?\n\n @client.describe_instances.to_h\n end", "def create_ec2_instances(ec2_instance_collection)\n ec2_instance_collection.reject! { |e| e.count.zero? } # filter out empty collections\n\n ec2_instance_collection.each do |collection|\n collection.each do |instance|\n _create_entity 'AwsEC2Instance', {\n 'name' => instance.public_dns_name.empty? ? instance.private_dns_name : instance.public_dns_name,\n 'region' => instance.placement.availability_zone.chop,\n 'availability_zone' => instance.placement.availability_zone,\n 'public_ip_address' => instance.public_ip_address,\n 'private_dns_name' => instance.private_dns_name,\n 'private_ip_address' => instance.private_ip_address,\n 'public_dns_name' => instance.public_dns_name\n }\n end\n end\n end", "def aws_import_instances\n\n instances = []\n\n aws_regions.each do |region|\n ec2 = AWS::EC2.new.regions[ region ]\n\n found = ec2.instances.map do |inst|\n next unless [ :running, :pending ].include?( inst.status )\n aws_instance_to_props( region, inst )\n end\n\n instances += found.compact\n end\n\n @aws_instances = instances\n end", "def instances\n @instances ||= begin\n instances_channel = channel(\n Admin::V2::BigtableInstanceAdminClient::SERVICE_ADDRESS\n )\n Admin::V2::BigtableInstanceAdminClient.new(\n credentials: instances_channel,\n timeout: timeout,\n client_config: client_config,\n lib_name: \"gccl\",\n lib_version: Google::Cloud::Bigtable::VERSION\n )\n end\n end", "def list_ids(mixins = nil)\n id_list = []\n\n Backends::Ec2::Helpers::AwsConnectHelper.rescue_aws_service(@logger) do\n instance_statuses = @ec2_client.describe_instance_status(include_all_instances: true).instance_statuses\n instance_statuses.each { |istatus| id_list << istatus[:instance_id] } if instance_statuses\n end\n\n id_list\n end", "def get_instances_by_role(group, role)\n get_instances(group).select do |instance|\n if not instance.tags['role'].nil? and instance.ready?\n instance.tags.fetch('role', '').split(',').include? role\n end\n end\n end", "def security_groups\n @resource.security_groups.map { |sg| SecurityGroup.new(id: sg.group_id, ec2_resource: @ec2_resource) }\n end", "def get_pvm_instances\n pvm_instances = get(\"cloud-instances/#{guid}/pvm-instances\")[\"pvmInstances\"] || []\n\n pvm_instances.map do |pvm_instance|\n get_pvm_instance(pvm_instance[\"pvmInstanceID\"])\n end\n end", "def all_instances\n Puppet.debug(\"all_instances - cached instances is: #{cached_instances}\")\n Puppet.debug(\"all_instances - cached instances object id: #{cached_instances.object_id}\")\n # return cache if it has been created, this means that this function will only need\n # to be loaded once, returning all instances that exist of this resource in vsphere\n # then, we can lookup our version by name/id/whatever. This saves a TON of processing\n return cached_instances unless cached_instances.nil?\n\n # Fetch the current status of the portgroup\n cmd = <<-EOF\n $portgroup_hash = @{}\n $hosts = #{powercli_get_online_hosts}\n foreach($h in $hosts) {\n # We silently continue on errors otherwise PowerCLI creates an error if the\n # portgroup does not exist on the host which pollutes our $portgroup_hash return object\n $pg = Get-VirtualSwitch -Host $h -Standard -Name #{resource[:vswitch_name]} | Get-VirtualPortGroup -Name #{resource[:portgroup]} -ErrorAction SilentlyContinue\n if ($pg) {\n $obj_hash = @{}\n $obj_hash.Add('portgroup', $pg.Name)\n $obj_hash.Add('vlan', $pg.VLanId)\n $obj_hash.Add('vswitch_name', $pg.VirtualSwitchName)\n $portgroup_hash[$h.Name] = @($obj_hash)\n } else {\n # create empty hashtable\n $obj_hash = @{}\n $portgroup_hash[$h.Name] = @($obj_hash)\n }\n }\n $portgroup_hash | ConvertTo-Json\n EOF\n\n portgroups_stdout = powercli_connect_exec(cmd)[:stdout]\n\n unless portgroups_stdout.empty?\n portgroups_hash = JSON.parse(portgroups_stdout)\n cached_instances_set({})\n portgroups_hash.each do |esx_host, pg_array|\n # Extracting hash from array object\n pg_hash = pg_array[0]\n cached_instances[esx_host] = {\n ensure: :present,\n esx_host: esx_host,\n vswitch_name: pg_hash['vswitch_name'],\n vlan: pg_hash['vlan'],\n portgroup: pg_hash['portgroup'],\n }\n end\n end\n Puppet.debug(\"all_instances - cached instances is at end: #{cached_instances}\")\n Puppet.debug(\"all_instances - cached instances object_id at end: #{cached_instances.object_id}\")\n cached_instances\n end", "def terminate_instances_by_group_id(group_id)\n raise 'Group ID not defined' unless group_id\n\n instances = @os_aws.describe_running_instances(group_id)\n logger.info instances\n ids = instances.map { |k, _| k[:instance_id] }\n\n logger.info \"Terminating the following instances #{ids}\"\n resp = []\n resp = @os_aws.terminate_instances(ids).to_hash unless ids.empty?\n\n resp[:terminating_instances].first[:current_state][:name] == 'shutting-down'\n end", "def index\n\n credentials = Aws::Credentials.new('AKIAJ2JD2EKKFVDSR37A', 'cnZUnzuyYPqUevEPb045VJUnW55VR+rUCQrplzd/')\n ec2 = Aws::EC2::Client.new(\n region: \"us-east-1\",\n credentials: credentials\n )\n #i = ec2.instances.create(:image_id => \"ami-e3106686\")\n resp = ec2.run_instances({\n dry_run: true,\n image_id: \"ami-e3106686\", # required\n min_count: 1, # required\n max_count: 1, # required\n instance_type: \"t1.micro\", # accepts t1.micro, m1.small, m1.medium, m1.large, m1.xlarge, m3.medium, m3.large, m3.xlarge, m3.2xlarge, m4.large, m4.xlarge, m4.2xlarge, m4.4xlarge, m4.10xlarge, t2.micro, t2.small, t2.medium, t2.large, m2.xlarge, m2.2xlarge, m2.4xlarge, cr1.8xlarge, i2.xlarge, i2.2xlarge, i2.4xlarge, i2.8xlarge, hi1.4xlarge, hs1.8xlarge, c1.medium, c1.xlarge, c3.large, c3.xlarge, c3.2xlarge, c3.4xlarge, c3.8xlarge, c4.large, c4.xlarge, c4.2xlarge, c4.4xlarge, c4.8xlarge, cc1.4xlarge, cc2.8xlarge, g2.2xlarge, cg1.4xlarge, r3.large, r3.xlarge, r3.2xlarge, r3.4xlarge, r3.8xlarge, d2.xlarge, d2.2xlarge, d2.4xlarge, d2.8xlarge\n placement: {\n tenancy: \"default\", # accepts default, dedicated\n },\n\n block_device_mappings: [\n {\n virtual_name: \"String\",\n device_name: \"String\",\n ebs: {\n snapshot_id: \"String\",\n volume_size: 1,\n delete_on_termination: true,\n volume_type: \"standard\", # accepts standard, io1, gp2\n iops: 1,\n encrypted: true,\n },\n\n },\n ],\n monitoring: {\n enabled: true, # required\n },\n disable_api_termination: true,\n instance_initiated_shutdown_behavior: \"stop\", # accepts stop, terminate\n network_interfaces: [\n {\n delete_on_termination: true,\n private_ip_addresses: [\n {\n private_ip_address: \"172.31.2.177\", # required\n primary: true,\n },\n ],\n secondary_private_ip_address_count: 1,\n associate_public_ip_address: true,\n },\n ],\n ebs_optimized: true,\n })\n @ec2_instances = Ec2Instance.all\n end", "def vpc_security_groups\n vsgs = []\n @dbi.vpc_security_groups.each do |vsg|\n vsgs << vsg.vpc_security_group_id if vsg.status == 'active'\n end\n vsgs\n end", "def vpc_security_groups\n vsgs = []\n @dbi.vpc_security_groups.each do |vsg|\n vsgs << vsg.vpc_security_group_id if vsg.status == 'active'\n end\n vsgs\n end", "def print_instances_details(only_running=true)\n @groups.values.each_with_index do |instances, i|\n instances.each do |instance|\n if only_running and (not instance.ready?)\n next\n end\n puts sprintf \"%02d: %-20s %-20s %-20s %-20s %-25s %-20s (%s) (%s) (%s)\",\n i, (instance.tags[\"Name\"] || \"\").green,instance.private_dns_name ,instance.id.red, instance.flavor_id.cyan,\n instance.dns_name.blue, instance.availability_zone.magenta, (instance.tags[\"role\"] || \"\").yellow,\n (instance.tags[\"group\"] || \"\").yellow, (instance.tags[\"app\"] || \"\").green\n end\n end\n end", "def instances_names_list\n return [] unless configured?\n\n aws_instances_ids = instances_list || []\n aws_instances_ids.map { |instance| instance[:node_name] }\n end", "def available_instances\n @available_instances ||= {}\n end", "def instances\n end", "def monitor_instances( options = {} )\n options = { :instance_id => [] }.merge(options)\n raise ArgumentError, \"No :instance_id provided\" if options[:instance_id].nil? || options[:instance_id].empty?\n params = pathlist(\"InstanceId\", options[:instance_id])\n return response_generator(:action => \"MonitorInstances\", :params => params)\n end", "def describe_addresses_for_instance(ec2_client, instance_id)\n response = ec2_client.describe_addresses(\n filters: [\n {\n name: \"instance-id\",\n values: [instance_id]\n }\n ]\n )\n addresses = response.addresses\n if addresses.count.zero?\n puts \"No addresses.\"\n else\n addresses.each do |address|\n puts \"-\" * 20\n puts \"Public IP: #{address.public_ip}\"\n puts \"Private IP: #{address.private_ip_address}\"\n end\n end\nrescue StandardError => e\n puts \"Error getting address information for instance: #{e.message}\"\nend", "def group_ebs_volumes_aws\n @group_ebs_volumes_aws ||= Hash[ebs_groups.map do |group_name|\n vols = ebs_volumes.select { |vol| vol.group == group_name}\n [group_name, vols]\n end]\n end", "def get_instances(role: nil, username: nil, bastion: nil)\n puts \"Getting instances for role: #{role}\"\n servers = []\n instances_for_role(role).each do |res|\n res[:instances].each do |inst|\n servers << \"#{username}@#{inst[:private_ip_address]}\"\n end\n end\n\n puts \" - #{servers.join(', ')}\"\n servers\n end", "def instance_ips(instance_id)\n # If we get an Unauthorized error, it could mean that the OpenStack auth token has expired, so we are\n # going renew the fog connection one time to make sure that we get a new non-expired token.\n retried = false\n begin\n instance = openstack.servers.find { |s| s.name == instance_id }\n rescue Excon::Errors::Unauthorized => e\n unless retried\n retried = true\n @openstack = nil\n retry\n end\n raise ConnectionError, \"Unable to connect to OpenStack API: #{e.message}\"\n end\n raise InstanceNotFound, \"Instance '#{instance_id}' not found\" unless instance\n return instance.ip_addresses\n end", "def terminate\n logger.info \"Terminating any instance with GroupUUID: #{@os_aws.group_uuid}\"\n\n terminate_instances_by_group_id(@os_aws.group_uuid)\n end", "def get_ec2_list_info(name_regex)\n ec2 = Aws::EC2::Client.new()\n\n # Load VPCs\n vpcs={}\n ec2.describe_vpcs( {filters:[AVAILABLE_STATE_FILTER]} ).vpcs.each do |vpc|\n vpcs[ vpc.vpc_id ] = { name: getName(vpc.tags), cidr: vpc.cidr_block, subnets: {} }\n end\n\n # Load subnets\n ec2.describe_subnets( {filters:[AVAILABLE_STATE_FILTER]} ).subnets.each do |sn|\n vpc = vpcs[ sn.vpc_id ]\n vpc[:subnets][ sn.subnet_id ] = { name: getName(sn.tags), zone: sn.availability_zone, cidr: sn.cidr_block, instances: [] }\n end\n\n ec2_classic = []\n\n # Load instances\n instances = ec2.describe_instances().reservations.map { |r| r.instances } .flatten\n instances.each do |i|\n next if name_regex and not name_regex =~ getName(i.tags)\n instance = make_instance( i )\n if i.vpc_id\n vpc = vpcs[ i.vpc_id ]\n sn = vpc[:subnets][ i.subnet_id ]\n sn[:instances] << instance\n else\n ec2_classic << instance\n end\n end\n\n [vpcs, ec2_classic]\nend", "def public_groups\n Group.find_public self.id\n end", "def existing_instances(filter=\"\")\r\n instances_raw = `ps xao pid,pgid,command | grep '#{process_name} #{name_grep_string} #{filter}' | grep -iv #{Process.pid} | awk '{print $1 \"\\t\" $2 \"\\t\" $3}'`\r\n instances_raw.split(\"\\n\").map do |row|\r\n pid, group, command = row.split(\"\\t\")\r\n ProcessInfo.new(pid.to_i, group.to_i, command)\r\n end\r\n end", "def list(mixins = nil)\n computes = ::Occi::Core::Resources.new\n\n Backends::Ec2::Helpers::AwsConnectHelper.rescue_aws_service(@logger) do\n rsrvts = @ec2_client.describe_instances.reservations\n rsrvts.each do |reservation|\n next unless reservation && reservation.instances\n reservation.instances.each { |instance| computes << parse_backend_obj(instance, reservation[:reservation_id]) }\n end if rsrvts\n end\n\n computes\n end", "def active_instances; end", "def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end", "def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end", "def instanceinfo(compute,name)\n\t\tresp = compute.describe_instances\t\n\t\tif (resp.status == 200)\n\t\t\t# check through the instances looking for one with a matching Name tag\n\t\t\tresp.body['reservationSet'].each { |x|\n\t\t\t\tx['instancesSet'].each { |y| \n\t\t\t\t\tif ( y['tagSet']['Name'] == name)\n\t\t\t\t\t\treturn y\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\traise \"ebsvol[aws]->instanceinfo: I couldn't list the instances\"\n\t\tend\n\t\tnil\n\tend", "def list_instance_ip(compartment_id, instance_id)\n vcnapi = OracleBMC::Core::VirtualNetworkClient.new\n opts = { instance_id: instance_id }\n api = OracleBMC::Core::ComputeClient.new\n vnics = api.list_vnic_attachments(compartment_id, opts)\n network = vcnapi.get_vnic(vnics.data[0].vnic_id)\n return network.data.private_ip, network.data.public_ip\n end", "def status_of(instance)\n description.instances.select{ |e| e.instance_id == instance}\n end", "def list_instances(request_id)\n instances = []\n JSON.parse(resource[\"/requests/#{request_id}\"].get)[\"instances\"].each do |i|\n instances << Instance.new(i)\n end\n end", "def autoscale(instance_id)\n metadata = @ec2.describe_instances(instance_ids: [\"#{instance_id}\"])\n tags = metadata.reservations.first.instances.first\n # covert to hash to make this easier\n tags = tags.to_h\n tags = tags[:tags]\n # quick check to avoid having to iterate through all the tags to see if the one we need is there.\n temp_tags = tags.to_s\n if temp_tags.include?(\"aws:autoscaling:groupName\")\n tags.each do |curtag|\n if curtag[:key] == \"aws:autoscaling:groupName\"\n @autoscaling = curtag[:value]\n end\n end\n else\n @autoscaling = \"false\"\n end\n end", "def ec2_attributes\n to_hash.slice(\n :id, :status, :key_name, :security_groups, :availability_zone,\n :instance_type, :public_ip, :private_ip, :created_at, :image_id\n )\n end", "def list_instances token: nil\n instances.list_instances parent: project_path, page_token: token\n end", "def list\n attrcheck = { 'compartment' => @options[:compartment] }\n @validate.validate(@options, attrcheck)\n opts = {}\n opts[:availability_domain] = @options[:availability_domain] if @options[:availability_domain]\n opts[:display_name] = @options[:display_name] if @options[:display_name]\n BmcAuthenticate.new(@options)\n request = OracleBMC::Core::ComputeClient.new\n request = request.list_instances(@options[:compartment], opts)\n request.data\n end", "def remove_instance(params)\n Fog::Logger.deprecation(\n \"#{self.class}.#{__method__} is deprecated, use Fog::Compute::Google::InstanceGroup.#{__method__} instead [light_black](#{caller(0..0)})[/]\"\n )\n params[:instance] = [params[:instance]] unless params[:instance] == Array\n service.remove_instance_group_instances(params[:group], params[:zone], params[:instance])\n end", "def grab_scannable_instances(address_blob, active_addresses)\n # list to hold all addresses of a region\n ec2_addresses_list = []\n address_blob.each do |address|\n # gathers all ip addresses for a region and pushes all of them to ec2_addresses_list\n # if they are still active in the account\n ec2_addresses_list.push(address['public_ip_address']) if active_addresses.include?(address['public_ip_address'])\n end\n ec2_addresses_list\nend", "def event_instances(calendar_id, event_id)\n end", "def get_cloud_instances(cloud_id)\n http_get_request(Scalarium.clouds_url+\"/#{cloud_id}/instances\") \n end", "def get_ec2_details(instance_id)\n ec2 = Aws::EC2::Client.new()\n begin\n res = ec2.describe_instances({instance_ids:[instance_id]})\n rescue\n puts \"Can't found an EC2 instance with given ID: #{instance_id}\"\n exit\n end\n i = res.reservations[0].instances[0]\n instance = make_instance( i )\n\n begin\n res = ec2.describe_image_attribute({image_id: i.image_id, attribute: \"description\"})\n instance[:ami_desc] = res.description.value\n rescue\n instance[:ami_desc] = '-- unavailable as of now --'\n end\n\n if i.vpc_id\n instance[:vpc] = getName( ec2.describe_vpcs({vpc_ids:[i.vpc_id]}).vpcs[0].tags )\n instance[:subnet] = getName( ec2.describe_subnets({subnet_ids:[i.subnet_id]}).subnets[0].tags )\n end\n\n instance\nend", "def describe_auto_scaling_groups(options = {})\n if auto_scaling_group_names = options.delete('AutoScalingGroupNames')\n options.merge!(AWS.indexed_param('AutoScalingGroupNames.member.%d', [*auto_scaling_group_names]))\n end\n request({\n 'Action' => 'DescribeAutoScalingGroups',\n :parser => Fog::Parsers::AWS::AutoScaling::DescribeAutoScalingGroups.new\n }.merge!(options))\n end", "def instances(type)\n @instances[type]\n end", "def get_images\n images = get(\"cloud-instances/#{guid}/images\")[\"images\"] || []\n\n images.map do |image|\n get_image(image[\"imageID\"])\n end.compact\n end", "def ebs_groups\n @ebs_groups ||= ebs_volumes.map(&:group).reject(&:nil?).uniq\n end", "def get_docker_instance_list(options)\n message = \"Information:\\tListing docker images\"\n command = \"docker ps\"\n output = execute_command(options,message,command)\n instances = output.split(/\\n/)\n return instances\nend", "def index\n @instances = Instance.all\n end", "def index\n @instances = Instance.all\n end", "def describe_db_instances( options = {} )\n params = {}\n params['DBInstanceIdentifier'] = options[:db_instance_identifier] if options.has?(:db_instance_identifier)\n params['MaxRecords'] = options[:max_records].to_s if options.has?(:max_records)\n params['Marker'] = options[:marker] if options.has?(:marker)\n\n return response_generator(:action => \"DescribeDBInstances\", :params => params)\n end", "def add_instance(params)\n Fog::Logger.deprecation(\n \"#{self.class}.#{__method__} is deprecated, use Fog::Compute::Google::InstanceGroup.#{__method__} instead [light_black](#{caller(0..0)})[/]\"\n )\n params[:instance] = [params[:instance]] unless params[:instance] == Array\n service.add_instance_group_instances(params[:group], params[:zone], params[:instance])\n end", "def call_describe_instances\n\t`ec2-describe-instances >> #{EC2_DESCRIBE_INSTANCES_OUTPUT}`\nend", "def instances_status\n @instances.each do |i_id, meta|\n status = AWS::CLI_Interface.ec2_instance_status(i_id)\n output = \"#{meta['name']} (#{i_id})\".colorize(color: :white, background: :blue) +\n \" : \".colorize(:yellow) +\n \"#{status[:label]}\".colorize(color: :white, background: status[:color])\n\n if meta.has_key? 'timeout'\n output += \" : \".colorize(:yellow)\n output += \"Timeout: #{meta['timeout']}\".colorize(color: :black, background: :light_yellow)\n end\n\n Logging.log output\n end\n end", "def aws_dump_instances( fout = $stdout )\n fout.puts '['\n rows = @aws_instances.sort { |p,n| p[:name] <=> n[:name] }\n rows.each_with_index do |row, i|\n fout.puts( \" \" + JSON.generate( row, :space => ' ', :object_nl => ' ' ) +\n ( ( i == ( rows.length - 1 ) ) ? '' : ',' ) )\n end\n fout.puts ']'\n end" ]
[ "0.7120154", "0.700922", "0.69817704", "0.6866905", "0.6765711", "0.6765711", "0.6621574", "0.65516955", "0.65302515", "0.6495344", "0.6442376", "0.6400759", "0.63791084", "0.6370542", "0.6361791", "0.63461304", "0.6186976", "0.61823565", "0.61771417", "0.6108272", "0.60905635", "0.605728", "0.60458165", "0.6021569", "0.59825414", "0.5970237", "0.5957002", "0.59104365", "0.5881316", "0.58736646", "0.58586735", "0.58546275", "0.58358353", "0.5830775", "0.58197784", "0.5818439", "0.5802281", "0.579856", "0.57835865", "0.57800347", "0.5767788", "0.5766855", "0.5747477", "0.5740634", "0.5726125", "0.56608415", "0.5654603", "0.56544286", "0.56040275", "0.5586499", "0.5569305", "0.55285156", "0.5521763", "0.55064285", "0.55057186", "0.5478553", "0.5475163", "0.5475163", "0.5474636", "0.54622", "0.54528207", "0.5433143", "0.5413927", "0.5364508", "0.53506213", "0.53492236", "0.5341839", "0.5341594", "0.5339944", "0.5334929", "0.5332595", "0.5327836", "0.5321165", "0.53052425", "0.53052425", "0.53040904", "0.5302034", "0.52930015", "0.5289912", "0.52834827", "0.5278702", "0.52731836", "0.52729", "0.5271687", "0.52683645", "0.5264184", "0.52641463", "0.5261958", "0.5254785", "0.5249126", "0.5242519", "0.5239058", "0.52291197", "0.5218538", "0.5218538", "0.5217383", "0.5213251", "0.52085894", "0.5208419", "0.5204242" ]
0.723362
0
Adjusts the desired size of the Auto Scaling group by initiating scaling activities. When reducing the size of the group, it is not possible to define which Amazon EC2 instances will be terminated. This applies to any Auto Scaling decisions that might result in terminating instances.
def set_desired_capacity capacity, options = {} client_opts = {} client_opts[:auto_scaling_group_name] = name client_opts[:desired_capacity] = capacity client_opts[:honor_cooldown] = options[:honor_cooldown] == true client.set_desired_capacity(client_opts) nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def scale(max_size, desired_capacity)\n client.update_auto_scaling_group(auto_scaling_group_name: asg_name, max_size: max_size, desired_capacity: desired_capacity)\n end", "def update_auto_scaling_group(auto_scaling_group_name, options = {})\n if availability_zones = options.delete('AvailabilityZones')\n options.merge!(AWS.indexed_param('AvailabilityZones.member.%d', [*availability_zones]))\n end\n request({\n 'Action' => 'UpdateAutoScalingGroup',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(options))\n end", "def terminate_instance_in_auto_scaling_group(instance_id, should_decrement_desired_capacity)\n request({\n 'Action' => 'TerminateInstanceInAutoScalingGroup',\n 'InstanceId' => instance_id,\n 'ShouldDecrementDesiredCapacity' => should_decrement_desired_capacity.to_s,\n :parser => Fog::Parsers::AWS::AutoScaling::TerminateInstanceInAutoScalingGroup.new\n })\n end", "def shrink!\n params = instance.cfn_parameters( name, \"AsgMaxSize\" => min_instances.to_s)\n template_body = instance.template_body\n cfn_client.update_stack(\n stack_name: stack_name,\n template_body: template_body,\n parameters: params,\n capabilities: [\"CAPABILITY_IAM\"],\n )\n cfn_client.wait_until(\n :stack_update_complete, \n stack_name: stack_name\n )\n rescue Aws::Waiters::Errors::WaiterFailed => e\n puts e\n end", "def pause_scaling_events\n client.suspend_processes(auto_scaling_group_name: asg_name,\n scaling_processes:\n %w[ReplaceUnhealthy AlarmNotification ScheduledActions AZRebalance])\n end", "def scale_to(new_size)\n scale_to(new_size, background:nil)\n end", "def auto_scaling_group(group_name)\n AutoScalingGroup.new(group_name)\n end", "def update options = {}\n\n group_opts = group_options(options) \n\n # tags must be updated using a separate request from the\n # other attributes, *sigh*\n if tags = group_opts.delete(:tags)\n tags.map(&:to_hash).each do |tag|\n tag[:resource_type] = 'auto-scaling-group'\n tag[:resource_id] = name\n end\n client.create_or_update_tags(:tags => tags)\n end\n\n unless group_opts.empty?\n client_opts = group_opts.merge(:auto_scaling_group_name => name)\n client.update_auto_scaling_group(client_opts)\n end\n\n nil\n\n end", "def dynamic_resize_to_fit(size)\n resize_to_fit *(model.class::IMAGE_CONFIG[size])\n end", "def autoscale(instance_id)\n metadata = @ec2.describe_instances(instance_ids: [\"#{instance_id}\"])\n tags = metadata.reservations.first.instances.first\n # covert to hash to make this easier\n tags = tags.to_h\n tags = tags[:tags]\n # quick check to avoid having to iterate through all the tags to see if the one we need is there.\n temp_tags = tags.to_s\n if temp_tags.include?(\"aws:autoscaling:groupName\")\n tags.each do |curtag|\n if curtag[:key] == \"aws:autoscaling:groupName\"\n @autoscaling = curtag[:value]\n end\n end\n else\n @autoscaling = \"false\"\n end\n end", "def resize_node_group request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n verb, uri, query_string_params, body = ServiceStub.transcode_resize_node_group_request request_pb\n query_string_params = if query_string_params.any?\n query_string_params.to_h { |p| p.split \"=\", 2 }\n else\n {}\n end\n\n response = @client_stub.make_http_request(\n verb,\n uri: uri,\n body: body || \"\",\n params: query_string_params,\n options: options\n )\n operation = ::Gapic::Rest::TransportOperation.new response\n result = ::Google::Longrunning::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end", "def remove_auto_scaling_group_properties\n properties = []\n properties << :AvailabilityZones\n properties << :HealthCheckGracePeriod\n properties << :HealthCheckType\n add_patch Patches::RemoveProperty.new 'AWS::AutoScaling::AutoScalingGroup', properties\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n #else\n #@task.debug { \"Scaling group #{@name} already suspended\" }\n #end\n end", "def scale_down\n \n num_stopped = 0\n # lets figure out what we can shut down.\n logger.info \"Looking for unused instances to scale down...\"\n EventLog.info \"Looking for unused instances to scale down...\"\n instances.each do |i|\n #this is actually pretty complicated. we have to figure out the exact range for each instance, based on the instance launch time\n lt = i.launch_time\n lt_diff = 60 - lt.min\n lower_range = HOUR_MOD - lt_diff #careful, it could be negative!\n lower_range = lower_range + 60 if lower_range < 0 # adjust for negative!\n\n upper_range = lower_range + (60 - HOUR_MOD) #upper range for mins, could be > 59!\n upper_range = upper_range - 60 if upper_range > 59 #correct for over 59\n\n now_min = DateTime.now.min\n \n ### DEBUG shutdown logic\n # puts \"Instance: #{i.aws_instance_id}\"\n # puts \"Now: #{now_min}\"\n # puts \"Upper: #{upper_range}\"\n # puts \"Lower: #{lower_range}\"\n\n if (now_min > lower_range && now_min < upper_range) || ((upper_range < lower_range) && (now_min < upper_range || now_min > lower_range))\n #so lets shutdown, but only if it won't bring us below the min_running threshold\n\n #first find out how many instances are running of this type\n total_running = (instances.select{ |j| j.running? }).size\n unless ((total_running - 1) < min || (! i.available? && ! i.error? ) || (farm_type.eql?('admin')))\n # for now we shutdown via aws but this will change as we figure out a better way\n logger.info \"Shutting down #{i.farm.ami_id} -- #{i.instance_id} due to IDLE timeout.\"\n EventLog.info \"Shutting down #{i.farm.ami_id} -- #{i.instance_id} due to IDLE timeout.\"\n i.terminate\n num_stopped += 1\n end\n end\n end\n\n return num_stopped\n\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n @task.debug { \"Scaling group #{@name} already running\" }\n else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n end\n end\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n \n suspended = load_from_s3(@task.bucket)\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n #@task.debug { \"Scaling group #{@name} already running\" }\n #else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n autoscaling_group.suspend_processes suspended.keys\n end\n #end\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n else\n @task.debug { \"Scaling group #{@name} already suspended\" }\n end\n end", "def scale_cloud!\n add_instance_if_load_is_high\n terminate_instance_if_load_is_low\n end", "def scale_to_fit(new_width, new_height, &block)\n squish(*scale_dimensions_to_fit(new_width, new_height), &block)\n end", "def scaleup(now, priority)\n if now == false \n # Job will be examined and run by scheduler later\n jid = $jobManager.register(-1, @envid, \"SCALEUP\", @name, \"READY\", priority)\n # Make a request to the global scheduler for capacity\n if $useGlobalScheduler == true\n template=ENVIRONMENT[@name][:slave_template]\n if template == nil\n $Logger.error \"scaleup: unable to find slave template for env #{@name} envid #{@envid}\"\n return\n end\n # Put a cap on number of requests sent to global scheduler\n # NOTE: For time based policy the throttling is done in \n # elastic_maanger/evaltimepolicy()\n if ENVIRONMENT[@name][:elasticity_policy] != nil &&\n ENVIRONMENT[@name][:elasticity_policy][:max] != nil \n maxVMs = ENVIRONMENT[@name][:elasticity_policy][:max] \n else\n maxVMs=16\n end\n if @vms.size + @gsOutStandingReqs > maxVMs\n $Logger.info \"scaleup: Too many outstanding requests to global schduler #{@name} envid #{@envid} outstanding #{@gsOutStandingReqs}\"\n return \"Too many scale up requests outstanding\"\n end\n \n vcpus = TEMPLATE[template][:cpu]\n mem = TEMPLATE[template][:memory]\n $gsProxy.request(@envid, @name, vcpus, mem, ENVIRONMENT[@name][:endpoint])\n @gsOutStandingReqs += 1\n end\n return jid\n end\n paramfile = $WORKDIR + \"/envconfig.\" + @name\n execString = $SVCBIN + \" -c \" + paramfile + \" -u \" + @envid\n childpid=Kernel.fork\n if childpid == nil\n Helper.closeFds()\n $stdout.reopen($ENVLOGFILE + \".#{@envid}\",'a+')\n $stderr.reopen($ENVLOGFILE + \".#{@envid}\",'a+')\n exec(execString)\n end\n jid = $jobManager.register(childpid, @envid, \"SCALEUP\", @name, \"RUNNING\", priority)\n return jid \n end", "def scale_appservers_within_nodes\n if @creds[\"autoscale\"].downcase == \"true\"\n perform_scaling_for_appservers()\n end\n end", "def scale_to_fill(new_size)\n scale_to_fill(new_size, position: :center)\n end", "def resize(new_size, options={})\n param = {\n :uniq_id => @uniq_id,\n :new_size => new_size\n }.merge options\n options[:skip_fs_resize] = options[:skip_fs_resize] ? 1 : 0\n data = Storm::Base::SODServer.remote_call '/Server/resize', param\n self.from_hash data\n end", "def scale_within(new_size)\n target_size = SugarCube::CoreGraphics::Size(new_size)\n image_size = self.size\n\n if CGSizeEqualToSize(target_size, self.size)\n return self\n end\n\n width = image_size.width\n height = image_size.height\n\n target_width = target_size.width\n target_height = target_size.height\n\n width_factor = target_width / width\n height_factor = target_height / height\n\n if width_factor < height_factor\n scale_factor = width_factor\n else\n scale_factor = height_factor\n end\n\n if scale_factor == 1\n return self\n end\n\n scaled_size = CGSize.new(width * scale_factor, height * scale_factor)\n return scale_to(scaled_size)\n end", "def large_process\n case [model.attachable_type, model.image_type]\n when ['User', 'avatar'] then\n resize_to_fill 1024, 683 # 3x2\n when ['User', 'inspiration'] then\n resize_to_fit 1024, 9999 # fixed width\n when ['Message', 'avatar'] then\n resize_to_fit 1024, 9999 # fixed width\n when ['Message', 'alternate'] then\n resize_to_fit 1024, 9999 # fixed width\n when ['Alternative', 'avatar'] then\n resize_to_fill 1024, 683 # 3x2\n else\n resize_to_fit 1024, 9999 # fixed width\n end\n # TODO: Test and implement this.\n # fix_exif_rotation\n quality 70\n end", "def autoscaling_instances\n autoscaling_group.auto_scaling_instances\n end", "def autoscaling_instances\n autoscaling_group.auto_scaling_instances\n end", "def autoscale_params\n params.require(:auto_scale).permit(:grow_cpu_thresh, :shrink_cpu_thresh, :grow_ratio_thresh, :shrink_ratio_thresh, :enabled, :max_instances, :cooldown_period_in_seconds)\n end", "def destroy(options = { :force => false })\n requires :id\n\n opts = {}\n opts.merge!({'ForceDelete' => true}) if options[:force]\n\n service.delete_auto_scaling_group(id, opts)\n end", "def scale!(type, size)\n @transforms << \"#{SCALE_TYPES[type]}#{size}\"\n self\n end", "def resize\n @event.endtime = make_time_from_minute_and_day_delta(@event.endtime)\n if @event.save\n render nothing: true\n else\n render json: { message: 'This service could not be resized' }\n end\n end", "def resize_to_fit(new_width, new_height)\n manipulate! do |image|\n resize_image(image,new_width,new_height)\n end\n end", "def resize_to_fit(new_width, new_height)\n manipulate! do |image|\n resize_image(image,new_width,new_height)\n end\n end", "def setScaleInProtection(need_instances = @config['min_size'])\n live_instances = []\n begin\n desc = MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).describe_auto_scaling_groups(auto_scaling_group_names: [@mu_name]).auto_scaling_groups.first\n\n live_instances = desc.instances.map { |i| i.instance_id }\n already_set = 0\n desc.instances.each { |i|\n already_set += 1 if i.protected_from_scale_in\n }\n if live_instances.size < need_instances\n sleep 5\n elsif already_set > need_instances\n unset_me = live_instances.sample(already_set - need_instances)\n MU.log \"Disabling scale-in protection for #{unset_me.size.to_s} instances in #{@mu_name}\", MU::NOTICE, details: unset_me\n MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).set_instance_protection(\n auto_scaling_group_name: @mu_name,\n instance_ids: unset_me,\n protected_from_scale_in: false\n )\n elsif already_set < need_instances\n live_instances = live_instances.sample(need_instances)\n MU.log \"Enabling scale-in protection for #{@config['scale_in_protection']} instances in #{@mu_name}\", details: live_instances\n begin\n MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).set_instance_protection(\n auto_scaling_group_name: @mu_name,\n instance_ids: live_instances,\n protected_from_scale_in: true\n )\n rescue Aws::AutoScaling::Errors::ValidationError => e\n if e.message.match(/not in InService/i)\n sleep 5\n retry\n else\n raise e\n end\n end\n end\n end while live_instances.size < need_instances\n end", "def min_size\n @group.min_size\n end", "def put_scaling_policy(adjustment_type, auto_scaling_group_name, policy_name, scaling_adjustment, options = {})\n request({\n 'Action' => 'PutScalingPolicy',\n 'AdjustmentType' => adjustment_type,\n 'AutoScalingGroupName' => auto_scaling_group_name,\n 'PolicyName' => policy_name,\n 'ScalingAdjustment' => scaling_adjustment,\n :parser => Fog::Parsers::AWS::AutoScaling::PutScalingPolicy.new\n }.merge!(options))\n end", "def scale_to_fill(new_size, scale: scale)\n scale_to_fill(new_size, position: :center, scale: scale)\n end", "def resize_to_limit(new_width, new_height)\n manipulate! do |image|\n image = resize_image(image,new_width,new_height) if new_width < image.width || new_height < image.height\n image\n end\n end", "def shrink_to_fit(new_width, new_height, &block)\n new_width, new_height = scale_dimensions_to_fit(new_width, new_height)\n return block.call(self) if new_width >= width && new_height >= height\n squish(new_width, new_height, &block)\n end", "def suspend_processes(auto_scaling_group_name, options = {})\n if scaling_processes = options.delete('ScalingProcesses')\n options.merge!(AWS.indexed_param('ScalingProcesses.member.%d', [*scaling_processes]))\n end\n request({\n 'Action' => 'SuspendProcesses',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(options))\n end", "def scale_to_length(new_length)\n self.scale(new_length / length)\n end", "def max_size\n @group.max_size\n end", "def adjust(total_excess, total_adjustable_weighting)\n if @adjustable\n if total_adjustable_weighting == 0\n @size = MemorySize::ZERO\n else\n @size = default_size - (total_excess - excess) * @weighting / total_adjustable_weighting\n end\n end\n end", "def update\n @size_group = SizeGroup.find(params[:id])\n result = @size_group.update_attributes(params[:size_group])\n if result\n for size in params[:size]\n new_size = Size.new(size)\n new_size.save\n @size_group.sizes << new_size\n end\n for id,size in params[:existing_size]\n if size.has_key? :delete\n Size.delete(id)\n else\n this_size = Size.find(id)\n this_size.update_attributes(size)\n end\n end if params[:existing_size]\n end\n \n respond_to do |format|\n if result\n flash[:notice] = 'SizeGroup was successfully updated.'\n format.html { redirect_to([:admin, @size_group]) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @size_group.errors, :status => :unprocessable_entity }\n end\n end\n end", "def small\n @request[:size] = 'small'\n self\n end", "def medium\n @request[:size] = 'medium'\n self\n end", "def scale(app_env)\n name, env = app_env.split(SEPARATOR)\n scaling = self.settings['scale'] || {}\n all = scaling['all'] || {}\n\n app_scaling = (scaling[name] && scaling[name].reject { |k,v| v.class == Hash }) || {}\n # overwrite app scaling with the environment specific ones\n merged_environment_scaling = app_scaling.merge((scaling[name] && scaling[name][env]) || {})\n\n # overwrite all scaling with the environment specific ones\n all.merge(merged_environment_scaling)\n end", "def resize_to_limit(new_width, new_height)\n manipulate! do |image|\n image = resize_image(image,new_width,new_height) if new_width < image.x_size || new_height < image.y_size\n image\n end\n end", "def resize_to_limit(width, height)\n width = dimension_from width\n height = dimension_from height\n manipulate! do |img|\n geometry = Magick::Geometry.new(width, height, 0, 0, Magick::GreaterGeometry)\n new_img = img.change_geometry(geometry) do |new_width, new_height|\n img.resize(new_width, new_height)\n end\n destroy_image(img)\n new_img = yield(new_img) if block_given?\n new_img\n end\n end", "def expand_to_fit(new_width, new_height, &block)\n new_width, new_height = scale_dimensions_to_fit(new_width, new_height)\n return block.call(self) if new_width <= width && new_height <= height\n squish(new_width, new_height, &block)\n end", "def resize(count)\n @client.call('queue.resize', @name, count)\n end", "def delete options = {}\n client_opts = {}\n client_opts[:force_delete] = options[:force] == true\n client_opts[:auto_scaling_group_name] = name\n client.delete_auto_scaling_group(client_opts)\n nil\n end", "def update!(**args)\n @instance_size = args[:instance_size] if args.key?(:instance_size)\n end", "def scale_to(pool_name, target_num_servers)\n current_server_count = current_pool_size(pool_name)\n if target_num_servers > current_server_count\n remove_servers(pool(pool_name)[target_num_servers..-1])\n else\n add_additional_servers(pool_name, target_num_servers - current_server_count)\n end\n end", "def resize(typemap)\n typemap = typemap.map_key do |type, size|\n validate_type_argument(type)\n end\n each_type_topological do |t|\n min_size = t.apply_resize(typemap)\n explicit_size = typemap[t]\n if min_size && explicit_size && explicit_size < min_size\n raise InvalidSizeSpecifiedError, \"#{explicit_size} specified as new size for #{t}, but this type has to be at least of size #{min_size}\"\n end\n if explicit_size\n t.size = explicit_size\n elsif min_size\n t.size = min_size\n end\n typemap[t] = t.size\n end\n end", "def init_groups\n @@client.describe_auto_scaling_groups.auto_scaling_groups\n end", "def auto_scaling_group_name\n data.auto_scaling_group_name\n end", "def scale(*amount)\n self.dup.scale! *amount\n end", "def scale\n release = options[:version]\n changes = {}\n args.each do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)([=+-]\\d+)$/\n changes[$1] = $2\n end\n end\n\n if changes.empty?\n error(\"Usage: heroku ps:scale PROCESS1=AMOUNT1 [PROCESS2=AMOUNT2 ...]\\nMust specify PROCESS and AMOUNT to scale.\")\n end\n\n changes.keys.sort.each do |process|\n amount = changes[process]\n action(\"Scaling #{process} processes\") do\n amount.gsub!(\"=\", \"\")\n new_qty = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/apps/#{app}/ps/scale\",\n :query => {\n 'type' => process,\n 'qty' => amount,\n 'release' => release\n }\n ).body\n status(\"now running #{new_qty}\")\n end\n end\n end", "def set_size!(size) \n @transforms << SIZES[size]\n self \n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def resize_type(type, to_size)\n resize(type => to_size)\n end", "def scale\n raise NotImplementedError, \"Subclass responsibility\"\n end", "def size=(size)\n @size = size\n resize\n end", "def delete_old_asg config, launch_config_name\n auto_scaling = new_auto_scaling\n auto_scaling.groups.each do |group|\n server = tag_value(group.tags, \"server\")\n if server != config[\"server\"]\n next \n end\n\n env = tag_value(group.tags, \"env\")\n if env != config[\"env\"]\n next \n end\n\n if group.name != launch_config_name.name\n puts \"deleting instance group, #{group.name} => #{launch_config_name.name}\"\n delete_asg group.name\n end\n end\nend", "def get_app_scaling_limits\n web_cart = get_framework_cartridge\n component_instance = self.component_instances.find_by(cartridge_name: web_cart.name)\n group_instance = group_instances_with_scale.select{ |go| go.all_component_instances.include? component_instance }[0]\n [group_instance.min, group_instance.max]\n end", "def size= (x)\n change_options({\"size\" => x})\n end", "def scale(force_instances=nil)\n if self.cluster.nil?\n Onering::Logger.error(\"Task #{self.id} is missing the cluster attribute\")\n return false\n end\n\n self.instances = self.instance_count(force_instances)\n\n\n # persist the target instances count\n # --------------------------------------------------------------------------\n if self.save()\n Onering::Logger.debug(\"Task #{self.id} target instances set to #{self.instances}\")\n\n marathon_node = nil\n cluster_node_apps = nil\n\n # verify connectivity to the compute cluster\n # ------------------------------------------------------------------------\n Asset.urlquery(\"mesos.masters.options.cluster/#{self.cluster}\").each do |node|\n url = \"http://#{node.get(:fqdn)}:8080/v1/apps\"\n response = HTTParty.get(url)\n\n if response.code == 200\n cluster_node_apps = MultiJson.load(response.body)\n marathon_node = node\n break\n else\n Onering::Logger.warn(\"Unable to communicate with Marathon on node #{node.id} via #{url}\")\n next\n end\n end\n\n if marathon_node.nil?\n Onering::Logger.error(\"Cannot contact any Marathon nodes\")\n return false\n end\n\n # build the request\n # ------------------------------------------------------------------------\n marathon_task_name = \"harbormaster-#{self.id}\"\n cluster_app = cluster_node_apps.select{|i| i.get(:id) == marathon_task_name }.first\n\n body = {\n :id => marathon_task_name,\n :instances => self.instances,\n :mem => self.resources.get(:memory),\n :cpus => self.resources.get(:cpu),\n :cmd => self.task.get(:name),\n :env => self.resources.get(:environment,{})\n }\n\n # send request (with retries!)\n # ------------------------------------------------------------------------\n scale_success = false\n\n 3.times.each do\n break if scale_success === true\n\n catch(:retry) do\n response = nil\n url = nil\n\n # task not found in cluster, start it\n if cluster_app.nil?\n if self.enabled === true\n url = \"http://#{marathon_node.get(:fqdn)}:8080/v1/apps/start\"\n response = HTTParty.post(url, {\n :headers => {\n 'Content-type' => 'application/json'\n },\n :body => MultiJson.dump(body)\n })\n else\n Onering::Logger.debug(\"Task #{self.id} is disabled and absent from Marathon, skipping...\")\n return true\n end\n\n # task IS found in cluster\n else\n payload = MultiJson.dump(Hash[body.select{|k,v|\n [:id, :instances].include?(k.to_sym)\n }])\n\n # if these properties are changing, stop the existing service first\n if cluster_app['cmd'] != body[:cmd] or\n cluster_app['mem'].to_f != body[:mem].to_f or\n cluster_app['cpus'].to_f != body[:cpus].to_f\n then\n Onering::Logger.info(\"Launch parameters have changed for task #{self.id} (Marathon task #{marathon_task_name}), relaunching...\")\n\n response = HTTParty.post(\"http://#{marathon_node.get(:fqdn)}:8080/v1/apps/stop\", {\n :headers => {\n 'Content-type' => 'application/json'\n },\n :body => payload\n })\n\n if response.code >= 300\n Onering::Logger.warn(\"Received HTTP #{response.code} while stopping task #{self.id} (Marathon task #{marathon_task_name})\")\n end\n\n cluster_app = nil\n throw :retry\n end\n\n # stop it if we're not enabled\n if self.enabled == false\n Onering::Logger.debug(\"Sending stop command to #{marathon_node.get(:fqdn)} for task #{marathon_task_name}\")\n\n url = \"http://#{marathon_node.get(:fqdn)}:8080/v1/apps/stop\"\n response = HTTParty.post(url, {\n :headers => {\n 'Content-type' => 'application/json'\n },\n :body => payload\n })\n\n # scale it to n instances otherwise\n else\n Onering::Logger.debug(\"Sending scale command to #{marathon_node.get(:fqdn)} for task #{marathon_task_name}\")\n\n url = \"http://#{marathon_node.get(:fqdn)}:8080/v1/apps/scale\"\n response = HTTParty.post(url, {\n :headers => {\n 'Content-type' => 'application/json'\n },\n :body => payload\n })\n end\n end\n\n if response.code < 300\n scale_success = true\n next\n end\n\n Onering::Logger.warn(\"Received response HTTP #{response.code} from #{url}\")\n end\n end\n\n if scale_success === true\n # save the last scaled time\n # ----------------------------------------------------------------------\n self.last_scaled_at = Time.now\n self.save()\n\n return self\n else\n Onering::Logger.error(\"Attempt to scale task #{self.id} (Marathon task #{marathon_task_name}) failed\")\n return false\n end\n\n else\n return false\n end\n end", "def scale_to_fill(new_size, position:position)\n scale_to_fill(new_size, position: position, scale: self.scale)\n end", "def save\n requires :id\n requires :adjustment_type\n requires :auto_scaling_group_name\n requires :scaling_adjustment\n\n options = Hash[self.class.aliases.map { |key, value| [key, send(value)] }]\n options.delete_if { |key, value| value.nil? }\n\n service.put_scaling_policy(adjustment_type, auto_scaling_group_name, id, scaling_adjustment, options)\n reload\n end", "def reduce_max_size\n @max_size /= 2\n end", "def k_resize!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 48 )\n\n\n\n type = K_RESIZE\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n\n\n # - - - - main rule block - - - -\n # at line 445:3: 'resize'\n match( \"resize\" )\n\n\n\n @state.type = type\n @state.channel = channel\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 48 )\n\n\n end", "def scale\n requires_preauth\n\n changes = args.map do |arg|\n if change = arg.scan(/^([a-zA-Z0-9_]+)([=+-]\\d+)(?::([\\w-]+))?$/).first\n formation, quantity, size = change\n quantity = quantity[1..-1].to_i if quantity[0] == \"=\"\n { \"type\" => formation, \"quantity\" => quantity, \"size\" => size}\n end\n end.compact\n\n if changes.empty?\n display_dyno_formation(get_formation)\n else\n action(\"Scaling dynos\") do\n new_scales = scale_dynos(get_formation, changes)\n .map {|p| \"#{p[\"type\"]} at #{p[\"quantity\"]}:#{p[\"size\"]}\" }\n status(\"now running \" + new_scales.join(\", \") + \".\")\n end\n end\n end", "def scale_to_fit(width, height)\n @image = @image.scale_to_fit(width, height)\n self\n end", "def size=(other)\n @size = other\n\n if @workers.size > @size\n (@workers.size - @size).times { @workers.shift[:run] = false }\n else\n (@size - @workers.size).times { @workers << spawn }\n end\n end", "def terminate\n logger.info \"Terminating any instance with GroupUUID: #{@os_aws.group_uuid}\"\n\n terminate_instances_by_group_id(@os_aws.group_uuid)\n end", "def resize_to_fit width, height\n process :resize_to_fit => [width, height]\n end", "def scale_image(preferred_width, preferred_height)\n # Retrieve the current height and width\n image_data = ActiveStorage::Analyzer::ImageAnalyzer.new(image).metadata\n new_width = image_data[:width]\n new_height = image_data[:height]\n\n # Adjust the width\n if new_width > preferred_width\n new_width = preferred_width\n new_height = (new_height * new_width) / image_data[:width]\n end\n\n # Adjust the height\n if new_height > preferred_height\n old_height = new_height\n new_height = preferred_height\n new_width = (new_width * new_height) / old_height\n end\n\n # Return the resized image\n image.variant(resize_to_limit: [new_width, new_height])\n end", "def setSize(szX,szY,scale,centerp=FALSE)\n @device.setSize(szX,szY,scale,centerp) ;\n end", "def resize_to_limit!(image, width, height)\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resize \"#{width}x#{height}>\"\n end\n end\n end", "def adjust_groups(response)\n Group.destroy_all\n delete_matches(response)\n create_groups(response)\n redirect_to root_path\n end", "def after_enqueue_scale_workers_up(*args)\n if HerokuScaler.heroku?\n scaler = HerokuScaler.new(@queue)\n scaler.workers = 1 if job_count > 0\n end\n end", "def scaleimage **opts\n Vips::Image.scale self, **opts\n end", "def update\n if ((params.has_key?(:group_size)) && (not params[:group_size].empty?))\n update_max_group_size(params[:group_size])\n end\n if ((params.has_key?(:group_reader)) && (not params[:group_reader].empty?))\n update_group_readers(params[:group_reader])\n end\n redirect_to admin_path\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n save_to_s3(@task.bucket)\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def resize!\n end", "def scale\n app = extract_app\n current_process = nil\n changes = args.inject({}) do |hash, process_amount|\n if process_amount =~ /^([a-zA-Z0-9_]+)([=+-]\\d+)$/\n hash[$1] = $2\n end\n hash\n end\n\n error \"Usage: heroku ps:scale web=2 worker+1\" if changes.empty?\n\n changes.each do |process, amount|\n display \"Scaling #{process} processes... \", false\n amount.gsub!(\"=\", \"\")\n new_qty = heroku.ps_scale(app, :type => process, :qty => amount)\n display \"done, now running #{new_qty}\"\n end\n end", "def add_to_size_group(group, size_groups, max_samples)\n added = false\n size_groups.each do |size_group|\n total_size = size_group.map(&:length).inject(0, :+)\n next if total_size + group.length > max_samples\n size_group.push(group)\n added = true\n end\n size_groups.push([group]) unless added\n end", "def create_new_asg config\n delete_launch_configs\n\n auto_scaling = new_auto_scaling\n\n #\n # 1. create the launh configuration\n #\n options = {\n :security_groups => [AMI_SECURITY_GROUP],\n :key_pair => AMI_KEY_PAIR,\n :user_data => user_data\n }\n\n launch_config = auto_scaling.launch_configurations.create(\n launch_config_name, \n config[\"ami\"],\n AMI_INSTANCE_TYPE,\n options\n )\n\n #\n # now create the asg\n #\n\n tags = [\n {:key => \"server\", :value => APP_NAME},\n {:key => \"build\", :value => VERSION},\n {:key => \"env\", :value => APP_ENV}\n ]\n\n options = {\n :load_balancers => [AMI_ELB],\n :launch_configuration => launch_config,\n :availability_zones => [AMI_AZ],\n :min_size => 1,\n :max_size => 1,\n :tags => tags\n }\n\n puts \"creating asg\"\n puts \"\\toptions => #{options}\"\n puts \"\\ttags => #{tags}\"\n auto_scaling.groups.create(launch_config_name, options)\nend", "def shutdown(group)\n cfmshutdown = AWS::CloudFormation.new\n ec2shutdown = AWS::EC2.new\n puts \"XXXXXXXXXX DAILY CHECKING HERE SHUT DOWN XXXXXXXXXXXX\"\n puts group.name\n puts \"Shut down Job is working now\"\n puts group.users.length\n puts \"-------------\"\n if group.users.length > 0\n allinstanceids = []\n group.users.each do |user|\n if user.stacks.length > 0\n user.stacks.each do |stack|\n if stack.ec2instance_ids.length > 0 \n allinstanceids.concat stack.ec2instance_ids\n end\n end\n end\n end\n puts \"BUBBBUBUBBBB\"\n puts allinstanceids.class\n allinstanceids = allinstanceids.uniq\n puts allinstanceids.class\n puts \"BUBBBUBUBBBB\"\n if allinstanceids.length > 0\n $ec2_resource.instances({instance_ids: allinstanceids}).batch_stop # To job stop\n end\n end \n puts \"YYYYYYYYYYYYYYYYYYYYYYYY\"\n end", "def widths_reset\n @width = GroupLayout::DEFAULT_SIZE\n @max = GroupLayout::DEFAULT_SIZE\n end", "def update\n\t\t@auto_scaling_trigger = AutoScalingTrigger.find(params[:id], :include => [ :auto_scaling_group ])\n\t\t@auto_scaling_group = @auto_scaling_trigger.auto_scaling_group\n\t\tast_params = params[:auto_scaling_trigger]\n\t\t\n\t\tunless ast_params.nil?\n\t\t\tast_params.each do |k,v|\n\t\t\t\tast_params[k] = v.chomp\n\t\t\tend\n\t\tend\n\t\t\n\t\trespond_to do |format|\n\t\t\tif @auto_scaling_trigger.update_attributes(ast_params)\n\t\t\t\tp = @auto_scaling_group\n\t\t\t\to = @auto_scaling_trigger\n\t\t\t\tAuditLog.create_for_parent(\n\t\t\t\t\t:parent => p,\n\t\t\t\t\t:auditable_id => o.id,\n\t\t\t\t\t:auditable_type => o.class.to_s,\n\t\t\t\t\t:auditable_name => o.name,\n\t\t\t\t\t:author_login => current_user.login,\n\t\t\t\t\t:author_id => current_user.id,\n\t\t\t\t\t:summary => \"updated '#{o.name}'\",\n\t\t\t\t\t:changes => o.tracked_changes,\n\t\t\t\t\t:force => false\n\t\t\t\t)\n\t\t\telse\n\t\t\t\t@error_messages = @auto_scaling_trigger.errors.collect{ |attr,msg| \"#{attr.humanize} - #{msg}\" }\n\t\t\t\tflash[:error] = @error_messages.join('<br/>')\n\t\t\tend\n\t\t\tformat.json { render :json => @auto_scaling_trigger }\n\t\tend\n\tend", "def update options = {}\n\n client_opts = options.dup\n client_opts[:scheduled_action_name] = name\n client_opts[:auto_scaling_group_name] = auto_scaling_group_name\n\n # convert these options to timestamps \n [:start_time, :end_time].each do |opt|\n if client_opts[opt].is_a?(Time)\n client_opts[opt] = client_opts[opt].iso8601\n end\n end\n\n client.put_scheduled_update_group_action(client_opts)\n\n nil\n\n end", "def update\n\n if @size_group.update_attributes(params[:size_group])\n flash[:notice] = 'SizeGroup was successfully updated.'\n render :partial => 'show', :object => @size_group\n else\n render :partial => 'edit', :object => @size_group, :status => 409\n end\n end", "def resize(size)\n @size = size\n new_slots = Array.new(@size).map { 0 }\n new_slots.each_with_index do |slot, i|\n new_slots[i] = @slots[i]\n end\n @slots = new_slots\n end", "def set_custom_size(pagefile, min, max)\n unset_automatic_managed\n converge_by(\"set #{pagefile} to InitialSize=#{min} & MaximumSize=#{max}\") do\n logger.trace(\"Set-CimInstance -Property @{InitialSize = #{min} MaximumSize = #{max}\")\n powershell_exec! <<~EOD\n $page_file = \"#{pagefile}\"\n $driveLetter = $page_file.split(':')[0]\n Get-CimInstance -ClassName Win32_PageFileSetting -Filter \"SettingID='pagefile.sys @ $($driveLetter):'\" -ErrorAction Stop | Set-CimInstance -Property @{InitialSize = #{min}; MaximumSize = #{max};}\n EOD\n end\n end", "def adapt_design_size \n hits = 0\n while space_factor < Constants::Min_allowed_factor and hits < 3\n if @vertical \n @height /= Constants::Shrink_factor\n @height += @height%20 == 0 ? 0 : 20-@height%20\n elsif not @vertical\n @width /= Constants::Shrink_factor\n @width += @width%20 == 0 ? 0 : 20-@width%20\n end\n composite_main_image_position\n generate_white_spaces\n white_space_area = white_space_w * white_space_h\n hits +=1\n end\n end", "def scale_up(scale)\n self.side_length *= scale\n end", "def scale(sx,sy)\n set RGhost::Scale.new(sx,sy)\n \n end" ]
[ "0.75889874", "0.64803857", "0.639634", "0.5995356", "0.5989149", "0.5931947", "0.58502275", "0.5831773", "0.580236", "0.57989293", "0.57058764", "0.5676442", "0.5649288", "0.5638111", "0.5621373", "0.5608299", "0.5593765", "0.5592327", "0.5578411", "0.5553519", "0.5514979", "0.5420462", "0.54078597", "0.5401193", "0.5357302", "0.5341815", "0.5341815", "0.53400534", "0.53278226", "0.5286078", "0.52460057", "0.522304", "0.522304", "0.52191854", "0.5212838", "0.521029", "0.52098167", "0.52051514", "0.5204589", "0.5197544", "0.51948166", "0.5140065", "0.5138912", "0.5135286", "0.5132169", "0.5120985", "0.51208174", "0.51177984", "0.5097601", "0.5096388", "0.5089885", "0.5077349", "0.5073034", "0.5065016", "0.50555027", "0.50508934", "0.5048515", "0.5045417", "0.5038555", "0.503096", "0.5018627", "0.5018627", "0.5009349", "0.49968004", "0.49942484", "0.4985941", "0.4976675", "0.49703833", "0.4963186", "0.49588507", "0.4947729", "0.4939756", "0.49347994", "0.49273124", "0.49178264", "0.49158716", "0.491113", "0.49105158", "0.49086428", "0.48911792", "0.4888091", "0.48873955", "0.488426", "0.4875492", "0.4873606", "0.48731944", "0.48722938", "0.4861705", "0.48586282", "0.48585123", "0.48574424", "0.48546538", "0.4846635", "0.4844791", "0.48440358", "0.48402295", "0.48267433", "0.48267028", "0.4823163", "0.48225874" ]
0.5212971
34
Suspends processes for this Auto Scaling group. suspend two processes by name auto_scaling_group.suspend_processes 'Launch', 'AZRebalance'
def suspend_processes *processes client_opts = {} client_opts[:auto_scaling_group_name] = name client_opts[:scaling_processes] = processes.flatten client.suspend_processes(client_opts) nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def suspend_processes(auto_scaling_group_name, options = {})\n if scaling_processes = options.delete('ScalingProcesses')\n options.merge!(AWS.indexed_param('ScalingProcesses.member.%d', [*scaling_processes]))\n end\n request({\n 'Action' => 'SuspendProcesses',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(options))\n end", "def pause_scaling_events\n client.suspend_processes(auto_scaling_group_name: asg_name,\n scaling_processes:\n %w[ReplaceUnhealthy AlarmNotification ScheduledActions AZRebalance])\n end", "def suspend_all_processes\n suspend_processes\n end", "def suspend_all_processes\n groups.each do |group|\n group.suspend_processes\n end\n end", "def resume_processes *processes\n client_opts = {}\n client_opts[:auto_scaling_group_name] = name\n client_opts[:scaling_processes] = processes.flatten\n client.resume_processes(client_opts)\n nil\n end", "def suspend\n execute_prlctl('suspend', @uuid)\n end", "def resume_all_processes\n groups.each do |group|\n group.resume_processes\n end\n end", "def resume_all_processes\n resume_processes\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n save_to_s3(@task.bucket)\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def suspend\n process_status = status\n if process_status != 'terminated' && process_status != 'stopped'\n return status if Process.kill('STOP', @proc_attrs[:pid].to_i)\n end\n process_status\n rescue Errno::EPERM\n return 'non-privilaged operation'\n end", "def suspend_campaigns(params)\n perform_request(self, @token, 'campaigns', 'suspend', params)\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def suspend\n Fission::Action::VM::Suspender.new(self).suspend\n end", "def suspend\n param 'state' => Patriot::JobStore::JobState::SUSPEND\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def suspend\n action('suspend')\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n else\n @task.debug { \"Scaling group #{@name} already suspended\" }\n end\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n \n suspended = load_from_s3(@task.bucket)\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n #@task.debug { \"Scaling group #{@name} already running\" }\n #else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n autoscaling_group.suspend_processes suspended.keys\n end\n #end\n end", "def cmd_suspend(*args)\n # give'em help if they want it, or seem confused\n if args.length == 0 or (args.include? \"-h\")\n cmd_suspend_help\n return true\n end\n\n continue = args.delete(\"-c\") || false\n resume = args.delete(\"-r\") || false\n\n # validate all the proposed pids first so we can bail if one is bogus\n valid_pids = validate_pids(args)\n args.uniq!\n diff = args - valid_pids.map {|e| e.to_s}\n if not diff.empty? # then we had an invalid pid\n print_error(\"The following pids are not valid:\t#{diff.join(\", \").to_s}.\")\n if continue\n print_status(\"Continuing. Invalid args have been removed from the list.\")\n else\n print_error(\"Quitting.\tUse -c to continue using only the valid pids.\")\n return false\n end\n end\n\n targetprocess = nil\n if resume\n print_status(\"Resuming: #{valid_pids.join(\", \").to_s}\")\n else\n print_status(\"Suspending: #{valid_pids.join(\", \").to_s}\")\n end\n begin\n valid_pids.each do |pid|\n print_status(\"Targeting process with PID #{pid}...\")\n targetprocess = client.sys.process.open(pid, PROCESS_ALL_ACCESS)\n targetprocess.thread.each_thread do |x|\n if resume\n targetprocess.thread.open(x).resume\n else\n targetprocess.thread.open(x).suspend\n end\n end\n end\n rescue ::Rex::Post::Meterpreter::RequestError => e\n print_error \"Error acting on the process: #{e.to_s}.\"\n print_error \"Try migrating to a process with the same owner as the target process.\"\n print_error \"Also consider running the win_privs post module and confirm SeDebug priv.\"\n return false unless continue\n ensure\n targetprocess.close if targetprocess\n end\n return true\n end", "def suspend\n requires :id\n begin\n response = service.post_suspend_vapp(id)\n rescue Fog::VcloudDirector::Compute::BadRequest => ex\n Fog::Logger.debug(ex.message)\n return false\n end\n service.process_task(response.body)\n end", "def suspend\n execute(\"controlvm\", @uuid, \"savestate\")\n end", "def suspend_job(id)\n @drmaa_session.suspend(id)\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n @task.debug { \"Scaling group #{@name} already running\" }\n else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n end\n end\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n #else\n #@task.debug { \"Scaling group #{@name} already suspended\" }\n #end\n end", "def suspend\n raise Suspended\n end", "def suspend\n @active = false\n while creeps.any?{|creep| creep.busy? }\n sleep 1\n end\n while @colony_processor_busy\n sleep 1\n end\n end", "def suspend\n data = JSON.generate(:suspend => nil)\n response = @compute.connection.csreq(\"POST\",@svrmgmthost,\"#{@svrmgmtpath}/servers/#{URI.encode(self.id.to_s)}/action\",@svrmgmtport,@svrmgmtscheme,{'content-type' => 'application/json'},data)\n OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)\n true\n end", "def suspend\n\t\t@state = STATE_SUSPENDED\n\tend", "def suspend\n @suspended = true\n end", "def suspend(job = ALL_JOBS)\n DRMAA.control(job, DRMAA::ACTION_SUSPEND)\n end", "def suspend!\n return if suspended?\n self.status = \"suspended\"\n self.stop = Time.now.to_s\n end", "def suspend_all; threads.each {|x| suspend(x)}; end", "def suspend(job = ALL_JOBS)\n DRMAA.control(job, DRMAA::ACTION_SUSPEND)\n end", "def asg_suspend_termination\n @asg_suspend_termination = true\n end", "def suspend\n end", "def pause_process (wfid)\n\n get_expression_pool.pause_process(wfid)\n end", "def suspend_proc_gevents(str=\"\")\r\n @suspend_queue_proc = true\r\n @num_of_suspend += 1\r\n @log.debug(\"suspend_proc_gevents (#{str}) add lock #{@num_of_suspend}\")\r\n end", "def kill_processes(pid_array)\n command = 'taskkill '\n pid_array.each do |pid|\n command = command + \"/pid #{pid} \"\n end\n `#{command}`\n end", "def sleep(duration)\n if sleep_procs.any?\n sleep_procs.each { |_name, a_proc| instance_exec(duration, &a_proc) }\n else\n Kernel.sleep(duration)\n end\n end", "def suspend\n self.suspended = true\n save(:validate => false)\n end", "def suspend!\n self.update_attribute(:status, SUSPENDED)\n self.registration.update_attribute(:status, SUSPENDED) if self.registration\n end", "def scale\n release = options[:version]\n changes = {}\n args.each do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)([=+-]\\d+)$/\n changes[$1] = $2\n end\n end\n\n if changes.empty?\n error(\"Usage: heroku ps:scale PROCESS1=AMOUNT1 [PROCESS2=AMOUNT2 ...]\\nMust specify PROCESS and AMOUNT to scale.\")\n end\n\n changes.keys.sort.each do |process|\n amount = changes[process]\n action(\"Scaling #{process} processes\") do\n amount.gsub!(\"=\", \"\")\n new_qty = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/apps/#{app}/ps/scale\",\n :query => {\n 'type' => process,\n 'qty' => amount,\n 'release' => release\n }\n ).body\n status(\"now running #{new_qty}\")\n end\n end\n end", "def suspend_cluster_restore_suspend(opts = {})\n data, _status_code, _headers = suspend_cluster_restore_suspend_with_http_info(opts)\n return data\n end", "def suspend_vapp(vAppId)\n power_action(vAppId, 'suspend')\n end", "def suspended!\n self.update_attribute(:status, SUSPEND)\n end", "def kill_and_reap(pids)\n puts \"Sending signals...\"\n sig = :KILL\n pids.each do |pid|\n puts \"== kill #{pid} with #{sig}\"\n Process.kill(sig, -1 * pid.to_i)\n end\n\n pids.each do |pid|\n puts \"=== Waiting for: #{pid} #{Process.waitpid2(pid)}\"\n end\nend", "def suspend\n unless exists?\n return Response.new :code => 1, :message => 'VM does not exist'\n end\n\n running_response = running?\n return running_response unless running_response.successful?\n\n unless running_response.data\n return Response.new :code => 1, :message => 'VM is not running'\n end\n\n conf_file_response = conf_file\n return conf_file_response unless conf_file_response.successful?\n\n command = \"#{vmrun_cmd} suspend \"\n command << \"#{conf_file_response.data} 2>&1\"\n\n Response.from_command(`#{command}`)\n end", "def power_off\n requires :id\n begin\n response = service.post_power_off_vapp(id)\n rescue Fog::VcloudDirector::Compute::BadRequest => ex\n Fog::Logger.debug(ex.message)\n return false\n end\n service.process_task(response.body)\n end", "def suspend_admin\r\n Admin.suspend params[:id]\r\n redirect_to :action => 'show_admins' \r\n end", "def suspend_proc_gevents(str=\"\")\n @log.debug(\"Suspend handling events #{str}\")\n @net_controller.suspend_srv_msg_handler\n @num_of_suspend += 1\n @log.debug(\"suspend_proc_gevents add lock #{@num_of_suspend}\")\n end", "def suspend(options={})\n # either monitorIds or tag is required\n # if options is a hash, then treat it as options\n # otherwise, treat it as a monitor id or an array of them\n if options.class == Hash\n result = post('suspendExternalMonitor', options)\n elsif options.class == Array\n result = post('suspendExternalMonitor', monitorIds: options.join(','))\n else\n result = post('suspendExternalMonitor', monitorIds: options)\n end\n result\n end", "def reaper\n pstate = wait(0.5)\n do_kill(\"KILL\") unless pstate\n end", "def reap_children\n @child_list.each do |pid|\n Process.kill('SIGKILL', pid)\n\t Process.wait pid\n end\n end", "def cmd_suspend_help\n print_line(\"Usage: suspend [options] pid1 pid2 pid3 ...\")\n print_line(\"Suspend one or more processes.\")\n print @@suspend_opts.usage\n end", "def suspend_agent\r\n Admin.suspend params[:id]\r\n redirect_to :action => 'show_agents' \r\n end", "def kill_procs(options={})\n # Give it a good try to delete all processes.\n # This abuse is necessary to release locks on polyinstantiated\n # directories by pam_namespace.\n\n procfilter=\"-u #{uid}\"\n if options[:init_owned]\n procfilter << \" -P 1\"\n end\n\n # If the terminate delay is specified, try to terminate processes nicely\n # first and wait for them to die.\n if options[:term_delay]\n ::OpenShift::Runtime::Utils::oo_spawn(\"/usr/bin/pkill #{procfilter}\")\n etime = Time.now + options[:term_delay].to_i\n while (Time.now <= etime)\n out,err,rc = ::OpenShift::Runtime::Utils::oo_spawn(\"/usr/bin/pgrep #{procfilter}\")\n break unless rc == 0\n sleep 0.5\n end\n end\n\n oldproclist=\"\"\n stuckcount=0\n while stuckcount <= 10\n out,err,rc = ::OpenShift::Runtime::Utils::oo_spawn(\"/usr/bin/pkill -9 #{procfilter}\")\n break unless rc == 0\n\n sleep 0.5\n\n out,err,rc = ::OpenShift::Runtime::Utils::oo_spawn(\"/usr/bin/pgrep #{procfilter}\")\n if oldproclist == out\n stuckcount += 1\n else\n oldproclist = out\n stuckcount = 0\n end\n end\n\n out,err,rc = ::OpenShift::Runtime::Utils::oo_spawn(\"/usr/bin/pgrep #{procfilter}\")\n if rc == 0\n procset = out.split.join(' ')\n logger.error \"ERROR: failed to kill all processes for #{uid}: PIDs #{procset}\"\n end\n end", "def scale\n app = extract_app\n current_process = nil\n changes = args.inject({}) do |hash, process_amount|\n if process_amount =~ /^([a-zA-Z0-9_]+)([=+-]\\d+)$/\n hash[$1] = $2\n end\n hash\n end\n\n error \"Usage: heroku ps:scale web=2 worker+1\" if changes.empty?\n\n changes.each do |process, amount|\n display \"Scaling #{process} processes... \", false\n amount.gsub!(\"=\", \"\")\n new_qty = heroku.ps_scale(app, :type => process, :qty => amount)\n display \"done, now running #{new_qty}\"\n end\n end", "def suspend_job\n # get items\n query = AnalysisJobsItem.queued_for_analysis_job(id)\n\n # batch update\n query.find_in_batches(batch_size: AnalysisJob.batch_size) do |items|\n items.each(&:cancel!)\n end\n end", "def unpause\n data = JSON.generate(:unpause => nil)\n response = @compute.connection.csreq(\"POST\",@svrmgmthost,\"#{@svrmgmtpath}/servers/#{URI.encode(self.id.to_s)}/action\",@svrmgmtport,@svrmgmtscheme,{'content-type' => 'application/json'},data)\n OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)\n true\n end", "def suspend\n _suspend(false) do\n system(\"tput cup 26 0\")\n system(\"tput ed\")\n system(\"echo Enter C-d to return to application\")\n system (ENV['PS1']='\\s-\\v\\$ ') if ENV['SHELL']== '/bin/bash'\n system(ENV['SHELL']);\n end\n end", "def _suspend\n\t\t# Ask the user if they would like to background the session\n\t\tif (prompt_yesno(\"Background session #{name}?\") == true)\n\t\t\tself.interacting = false\n\t\tend\n\tend", "def end_process id\n taskswap 0 if @cur_proc_id == id\n @processes -= [id]\n @queue[0] -= [id]\n @queue[1] -= [id]\n end", "def stop(wait = true)\n request('stopProcessGroup', @name, wait)\n end", "def suspend\n FFI::Libvirt.virDomainSuspend(self) == 0\n end", "def suspend\n FFI::Libvirt.virDomainSuspend(self) == 0\n end", "def stop\n if @pid\n Process.kill('KILL', @pid)\n Process.wait @pid\n end\n @pid = nil\n if @pgid\n Process.kill('KILL', -(@pgid))\n end\n @pgid = nil\n end", "def pause_processing\n @processing = false\n end", "def after_suspend(user, transition)\n UserMailer.deliver_suspension_notice(user)\n end", "def reset!\n @suspend_new = false\n stop_all!\n end", "def force_stop\n @state.value = ApplicationState::State::STOPPED\n UnixUser.kill_procs(@user.uid)\n end", "def suspend_vapp(vAppId)\n params = {\n 'method' => :post,\n 'command' => \"/vApp/vapp-#{vAppId}/power/action/suspend\"\n }\n\n response, headers = send_request(params)\n task_id = headers[:location].gsub(\"#{@api_url}/task/\", \"\")\n task_id\n end", "def power_down\n send_to_vm('system_powerdown')\n end", "def stop_maintenance\n return true unless maint_mode?\n\n Instance.running_for_profile(self).map {|i| i.stop}\n maint_mode = false\n self.save!\n end", "def soft_stop_worker(sm_uuid)\n limit_worker_simulations(sm_uuid, 1)\n end", "def stop\n app = extract_app\n opt =\n if (args.first =~ /.+\\..+/)\n ps = args.first\n display \"Stopping #{ps} process... \", false\n {:ps => ps}\n elsif args.first\n type = args.first\n display \"Stopping #{type} processes... \", false\n {:type => type}\n else\n error \"Usage: heroku ps:stop PROCESS\"\n end\n\n heroku.ps_stop(app, opt)\n display \"done\"\n end", "def unpause_processing_with_pause_key\n unpause_processing_without_pause_key\n Resque.redis.del(pause_key)\n end", "def restart\n app = extract_app\n\n opts = case args.first\n when NilClass then\n display \"Restarting processes... \", false\n {}\n when /.+\\..+/\n ps = args.first\n display \"Restarting #{ps} process... \", false\n { :ps => ps }\n else\n type = args.first\n display \"Restarting #{type} processes... \", false\n { :type => type }\n end\n heroku.ps_restart(app, opts)\n display \"done\"\n end", "def reboot(hard = false)\n return if @cloud_id.nil?\n\n if hard\n groupname = nil\n if !@config['basis'].nil?\n resp = MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).describe_auto_scaling_instances(\n instance_ids: [@cloud_id]\n )\n groupname = resp.auto_scaling_instances.first.auto_scaling_group_name\n MU.log \"Pausing Autoscale processes in #{groupname}\", MU::NOTICE\n MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).suspend_processes(\n auto_scaling_group_name: groupname,\n scaling_processes: [\n \"Terminate\",\n ], \n )\n end\n begin\n MU.log \"Stopping #{@mu_name} (#{@cloud_id})\", MU::NOTICE\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).stop_instances(\n instance_ids: [@cloud_id]\n )\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).wait_until(:instance_stopped, instance_ids: [@cloud_id]) do |waiter|\n waiter.before_attempt do\n MU.log \"Waiting for #{@mu_name} to stop for hard reboot\"\n end\n end\n MU.log \"Starting #{@mu_name} (#{@cloud_id})\"\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).start_instances(\n instance_ids: [@cloud_id]\n )\n ensure\n if !groupname.nil?\n MU.log \"Resuming Autoscale processes in #{groupname}\", MU::NOTICE\n MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).resume_processes(\n auto_scaling_group_name: groupname,\n scaling_processes: [\n \"Terminate\",\n ],\n )\n end\n end\n else\n MU.log \"Rebooting #{@mu_name} (#{@cloud_id})\"\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).reboot_instances(\n instance_ids: [@cloud_id]\n )\n end\n end", "def stop\n puts \"Stoping any instance with group ID: #{@os_aws.group_uuid}\"\n\n stop_instances_by_group_id(@os_aws.group_uuid)\n end", "def scale_down\n \n num_stopped = 0\n # lets figure out what we can shut down.\n logger.info \"Looking for unused instances to scale down...\"\n EventLog.info \"Looking for unused instances to scale down...\"\n instances.each do |i|\n #this is actually pretty complicated. we have to figure out the exact range for each instance, based on the instance launch time\n lt = i.launch_time\n lt_diff = 60 - lt.min\n lower_range = HOUR_MOD - lt_diff #careful, it could be negative!\n lower_range = lower_range + 60 if lower_range < 0 # adjust for negative!\n\n upper_range = lower_range + (60 - HOUR_MOD) #upper range for mins, could be > 59!\n upper_range = upper_range - 60 if upper_range > 59 #correct for over 59\n\n now_min = DateTime.now.min\n \n ### DEBUG shutdown logic\n # puts \"Instance: #{i.aws_instance_id}\"\n # puts \"Now: #{now_min}\"\n # puts \"Upper: #{upper_range}\"\n # puts \"Lower: #{lower_range}\"\n\n if (now_min > lower_range && now_min < upper_range) || ((upper_range < lower_range) && (now_min < upper_range || now_min > lower_range))\n #so lets shutdown, but only if it won't bring us below the min_running threshold\n\n #first find out how many instances are running of this type\n total_running = (instances.select{ |j| j.running? }).size\n unless ((total_running - 1) < min || (! i.available? && ! i.error? ) || (farm_type.eql?('admin')))\n # for now we shutdown via aws but this will change as we figure out a better way\n logger.info \"Shutting down #{i.farm.ami_id} -- #{i.instance_id} due to IDLE timeout.\"\n EventLog.info \"Shutting down #{i.farm.ami_id} -- #{i.instance_id} due to IDLE timeout.\"\n i.terminate\n num_stopped += 1\n end\n end\n end\n\n return num_stopped\n\n end", "def suspend(node)\n Result.new(call(CMD_SUSPEND % node))\n end", "def reboot(hard = false)\n return if @cloud_id.nil?\n\n if hard\n groupname = nil\n if !@config['basis'].nil?\n resp = MU::Cloud::AWS.autoscale(region: @config['region'], credentials: @config['credentials']).describe_auto_scaling_instances(\n instance_ids: [@cloud_id]\n )\n groupname = resp.auto_scaling_instances.first.auto_scaling_group_name\n MU.log \"Pausing Autoscale processes in #{groupname}\", MU::NOTICE\n MU::Cloud::AWS.autoscale(region: @config['region'], credentials: @config['credentials']).suspend_processes(\n auto_scaling_group_name: groupname\n )\n end\n begin\n MU.log \"Stopping #{@mu_name} (#{@cloud_id})\", MU::NOTICE\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).stop_instances(\n instance_ids: [@cloud_id]\n )\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).wait_until(:instance_stopped, instance_ids: [@cloud_id]) do |waiter|\n waiter.before_attempt do |attempts|\n MU.log \"Waiting for #{@mu_name} to stop for hard reboot\"\n end\n end\n MU.log \"Starting #{@mu_name} (#{@cloud_id})\"\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).start_instances(\n instance_ids: [@cloud_id]\n )\n ensure\n if !groupname.nil?\n MU.log \"Resuming Autoscale processes in #{groupname}\", MU::NOTICE\n MU::Cloud::AWS.autoscale(region: @config['region'], credentials: @config['credentials']).resume_processes(\n auto_scaling_group_name: groupname\n )\n end\n end\n else\n MU.log \"Rebooting #{@mu_name} (#{@cloud_id})\"\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).reboot_instances(\n instance_ids: [@cloud_id]\n )\n end\n end", "def suspend_partner\n wait_until { change_status_link.visible? }\n change_status_link.click\n # wait for edit view\n wait_until { change_status_select.visible? }\n change_status_select.select('Suspended')\n submit_change_status_btn.click\n wait_until{ change_status_link.visible? }\n end", "def resume_process (wfid)\n\n get_expression_pool.resume_process(wfid)\n end", "def halt\n execute(\"controlvm\", @uuid, \"poweroff\")\n end", "def suspend &block\n if block_given? then\n @mutex.synchronize {\n begin\n @suspended = true\n block.call(self)\n ensure\n @suspended = false\n end\n }\n end\n end", "def stop_sleep_process(targets, accept_no_pid_found = false)\n targets = [targets].flatten\n\n targets.each do |target|\n case target['platform']\n when /osx/\n command = \"ps -e -o pid,comm | grep sleep | sed 's/^[^0-9]*//g' | cut -d\\\\ -f1\"\n when /win/\n command = \"ps -efW | grep PING | sed 's/^[^0-9]*[0-9]*[^0-9]*//g' | cut -d ' ' -f1\"\n else\n command = \"ps -ef | grep 'bin/sleep ' | grep -v 'grep' | grep -v 'true' | sed 's/^[^0-9]*//g' | cut -d\\\\ -f1\"\n end\n\n # A failed test may leave an orphaned sleep process, handle multiple matches.\n pids = nil\n on(target, command) do |output|\n pids = output.stdout.chomp.split\n if pids.empty? && !accept_no_pid_found\n raise(\"Did not find a pid for a sleep process on #{target}\")\n end\n end\n\n pids.each do |pid|\n target['platform'] =~ /win/ ?\n on(target, \"taskkill /F /pid #{pid}\") :\n on(target, \"kill -s TERM #{pid}\")\n end\n end\nend", "def scaleup(now, priority)\n if now == false \n # Job will be examined and run by scheduler later\n jid = $jobManager.register(-1, @envid, \"SCALEUP\", @name, \"READY\", priority)\n # Make a request to the global scheduler for capacity\n if $useGlobalScheduler == true\n template=ENVIRONMENT[@name][:slave_template]\n if template == nil\n $Logger.error \"scaleup: unable to find slave template for env #{@name} envid #{@envid}\"\n return\n end\n # Put a cap on number of requests sent to global scheduler\n # NOTE: For time based policy the throttling is done in \n # elastic_maanger/evaltimepolicy()\n if ENVIRONMENT[@name][:elasticity_policy] != nil &&\n ENVIRONMENT[@name][:elasticity_policy][:max] != nil \n maxVMs = ENVIRONMENT[@name][:elasticity_policy][:max] \n else\n maxVMs=16\n end\n if @vms.size + @gsOutStandingReqs > maxVMs\n $Logger.info \"scaleup: Too many outstanding requests to global schduler #{@name} envid #{@envid} outstanding #{@gsOutStandingReqs}\"\n return \"Too many scale up requests outstanding\"\n end\n \n vcpus = TEMPLATE[template][:cpu]\n mem = TEMPLATE[template][:memory]\n $gsProxy.request(@envid, @name, vcpus, mem, ENVIRONMENT[@name][:endpoint])\n @gsOutStandingReqs += 1\n end\n return jid\n end\n paramfile = $WORKDIR + \"/envconfig.\" + @name\n execString = $SVCBIN + \" -c \" + paramfile + \" -u \" + @envid\n childpid=Kernel.fork\n if childpid == nil\n Helper.closeFds()\n $stdout.reopen($ENVLOGFILE + \".#{@envid}\",'a+')\n $stderr.reopen($ENVLOGFILE + \".#{@envid}\",'a+')\n exec(execString)\n end\n jid = $jobManager.register(childpid, @envid, \"SCALEUP\", @name, \"RUNNING\", priority)\n return jid \n end", "def push_request_suspend(request_id, expiry)\n sleep 1\n puts '******* request_push_suspended'\n sleep 3\n puts \"******* pushed_suspended #{request_id}, #{expiry}\"\n end", "def shutdown(group)\n cfmshutdown = AWS::CloudFormation.new\n ec2shutdown = AWS::EC2.new\n puts \"XXXXXXXXXX DAILY CHECKING HERE SHUT DOWN XXXXXXXXXXXX\"\n puts group.name\n puts \"Shut down Job is working now\"\n puts group.users.length\n puts \"-------------\"\n if group.users.length > 0\n allinstanceids = []\n group.users.each do |user|\n if user.stacks.length > 0\n user.stacks.each do |stack|\n if stack.ec2instance_ids.length > 0 \n allinstanceids.concat stack.ec2instance_ids\n end\n end\n end\n end\n puts \"BUBBBUBUBBBB\"\n puts allinstanceids.class\n allinstanceids = allinstanceids.uniq\n puts allinstanceids.class\n puts \"BUBBBUBUBBBB\"\n if allinstanceids.length > 0\n $ec2_resource.instances({instance_ids: allinstanceids}).batch_stop # To job stop\n end\n end \n puts \"YYYYYYYYYYYYYYYYYYYYYYYY\"\n end", "def suspend!\n self.update_attribute(:activated_at, nil)\n end", "def terminate_instances_by_group_id(group_id)\n raise 'Group ID not defined' unless group_id\n\n instances = @os_aws.describe_running_instances(group_id)\n logger.info instances\n ids = instances.map { |k, _| k[:instance_id] }\n\n logger.info \"Terminating the following instances #{ids}\"\n resp = []\n resp = @os_aws.terminate_instances(ids).to_hash unless ids.empty?\n\n resp[:terminating_instances].first[:current_state][:name] == 'shutting-down'\n end", "def resume\n process_status = status\n if process_status == 'stopped'\n return status if Process.kill('CONT', @proc_attrs[:pid].to_i)\n end\n process_status\n rescue Errno::EPERM\n return 'non-privilaged operation'\n end", "def power_off\n target = entity_xml\n class_name = self.class.name.split(\"::\").last\n Config.logger.debug \"#{class_name} status: #{target[:status]}\"\n if is_status?(target, :SUSPENDED)\n error_msg = \"#{class_name} #{target.name} suspended, discard state before powering off.\"\n fail class_name == \"VApp\" ? VappSuspendedError : VmSuspendedError,\n error_msg\n end\n if is_status?(target, :POWERED_OFF)\n Config.logger.info \"#{class_name} #{target.name} is already powered off.\"\n return\n end\n\n power_off_link = target.power_off_link\n unless power_off_link\n fail CloudError, \"#{class_name} #{target.name} is not in a state that could be powered off.\"\n end\n\n task = connection.post(power_off_link, nil)\n monitor_task task, @session.time_limit[:power_off]\n Config.logger.info \"#{class_name} #{target.name} is powered off.\"\n\n undeploy(target, class_name)\n end", "def unpause_processing\n log \"CONT received; resuming job processing\"\n @paused = false\n redis.del(pause_key)\n end", "def suspend_patron\r\n Admin.suspend params[:id]\r\n redirect_to :action => 'show_patrons' \r\n end", "def suspend(c, ci, de, cr, cv)\n if state(COMMITMENT, c, ci, de, cr) and active(c, ci, cv)\n apply([[PENDING, c, ci, cv]], [])\n end\nend", "def suspend_new!\n @suspend_new = true\n end", "def test_more_than_one_pause_when_stopping\n stqe = @session.jobs['stqe']\n mail = @session.jobs['misc. email']\n\n stqe_start = @now\n start(stqe)\n assert_states([stqe], [])\n assert_new_record 1, stqe, stqe_start\n mail_start = @now\n start(mail)\n assert_states([mail], [stqe])\n assert_new_record 2, mail, mail_start\n pause\n assert_states([], [mail, stqe])\n stop(stqe)\n assert_states([], [mail])\n assert_stopped_with(1, 1.minute)\n stop(mail)\n assert_states([], [])\n assert_stopped_with(2, 1.minute)\n end" ]
[ "0.87122166", "0.75313544", "0.7240648", "0.7142046", "0.6909668", "0.6502795", "0.6167026", "0.61294985", "0.6110244", "0.6031816", "0.6025132", "0.5929465", "0.5771859", "0.5760472", "0.5751843", "0.5751843", "0.57494515", "0.57237697", "0.566512", "0.56474036", "0.5591733", "0.5587647", "0.55851877", "0.5579462", "0.55786043", "0.54659015", "0.545367", "0.5449493", "0.54154927", "0.54080814", "0.53336", "0.5328549", "0.53037506", "0.5258023", "0.52550936", "0.52375317", "0.51818097", "0.51700944", "0.51494145", "0.5091407", "0.50445724", "0.50357664", "0.5010144", "0.5004253", "0.5003815", "0.49881178", "0.49748847", "0.49729195", "0.4959194", "0.49537405", "0.49510887", "0.49407753", "0.49317816", "0.48729795", "0.48640865", "0.48626015", "0.48406938", "0.48272943", "0.48262605", "0.48212168", "0.48066005", "0.48000276", "0.47981888", "0.47432816", "0.47258732", "0.47258732", "0.47235695", "0.4697872", "0.46932125", "0.46847558", "0.46782774", "0.4670405", "0.4659893", "0.4646656", "0.46463433", "0.46427813", "0.4634375", "0.46323287", "0.46295166", "0.46280745", "0.46146175", "0.46010903", "0.45882806", "0.45881224", "0.45863593", "0.4580322", "0.45715186", "0.4569854", "0.45526963", "0.4552589", "0.4545296", "0.4543716", "0.45434082", "0.45431325", "0.45253706", "0.44927856", "0.4490788", "0.44840056", "0.44834313", "0.4476955" ]
0.82164705
1
Suspends all processes for this Auto Scaling group.
def suspend_all_processes suspend_processes end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def suspend_processes(auto_scaling_group_name, options = {})\n if scaling_processes = options.delete('ScalingProcesses')\n options.merge!(AWS.indexed_param('ScalingProcesses.member.%d', [*scaling_processes]))\n end\n request({\n 'Action' => 'SuspendProcesses',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(options))\n end", "def pause_scaling_events\n client.suspend_processes(auto_scaling_group_name: asg_name,\n scaling_processes:\n %w[ReplaceUnhealthy AlarmNotification ScheduledActions AZRebalance])\n end", "def suspend_all_processes\n groups.each do |group|\n group.suspend_processes\n end\n end", "def suspend_processes *processes\n client_opts = {}\n client_opts[:auto_scaling_group_name] = name\n client_opts[:scaling_processes] = processes.flatten\n client.suspend_processes(client_opts)\n nil\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n save_to_s3(@task.bucket)\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def resume_all_processes\n groups.each do |group|\n group.resume_processes\n end\n end", "def resume_all_processes\n resume_processes\n end", "def killall\n scheduler_enabled = scheduler.enabled?\n\n plan.permanent_tasks.clear\n plan.permanent_events.clear\n plan.missions.clear\n plan.transactions.each do |trsc|\n trsc.discard_transaction!\n end\n\n scheduler.enabled = false\n quit\n join\n\n if @application_exceptions\n process_pending_application_exceptions\n end\n\n start_new_cycle\n process_events\n cycle_end(Hash.new)\n\n ensure\n scheduler.enabled = scheduler_enabled\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n else\n @task.debug { \"Scaling group #{@name} already suspended\" }\n end\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n #else\n #@task.debug { \"Scaling group #{@name} already suspended\" }\n #end\n end", "def resume_processes *processes\n client_opts = {}\n client_opts[:auto_scaling_group_name] = name\n client_opts[:scaling_processes] = processes.flatten\n client.resume_processes(client_opts)\n nil\n end", "def stop\n puts \"Stoping any instance with group ID: #{@os_aws.group_uuid}\"\n\n stop_instances_by_group_id(@os_aws.group_uuid)\n end", "def terminate\n logger.info \"Terminating any instance with GroupUUID: #{@os_aws.group_uuid}\"\n\n terminate_instances_by_group_id(@os_aws.group_uuid)\n end", "def suspend\n execute_prlctl('suspend', @uuid)\n end", "def suspend_campaigns(params)\n perform_request(self, @token, 'campaigns', 'suspend', params)\n end", "def suspend\n @active = false\n while creeps.any?{|creep| creep.busy? }\n sleep 1\n end\n while @colony_processor_busy\n sleep 1\n end\n end", "def suspend\n Fission::Action::VM::Suspender.new(self).suspend\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n \n suspended = load_from_s3(@task.bucket)\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n #@task.debug { \"Scaling group #{@name} already running\" }\n #else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n autoscaling_group.suspend_processes suspended.keys\n end\n #end\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n @task.debug { \"Scaling group #{@name} already running\" }\n else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n end\n end\n end", "def reap_children\n @child_list.each do |pid|\n Process.kill('SIGKILL', pid)\n\t Process.wait pid\n end\n end", "def suspend_all; threads.each {|x| suspend(x)}; end", "def terminate_instances_by_group_id(group_id)\n raise 'Group ID not defined' unless group_id\n\n instances = @os_aws.describe_running_instances(group_id)\n logger.info instances\n ids = instances.map { |k, _| k[:instance_id] }\n\n logger.info \"Terminating the following instances #{ids}\"\n resp = []\n resp = @os_aws.terminate_instances(ids).to_hash unless ids.empty?\n\n resp[:terminating_instances].first[:current_state][:name] == 'shutting-down'\n end", "def drain_pool\n @pool.each { |worker| worker.kill }\n @pool.clear\n end", "def shutdown()\n \n #shutdown all the instances we have.\n ids = id()\n \n @ec2.terminate_instances(ids)\n \n # wait for them to shut down for a couple of minutes\n attempts = 0\n stats = state_code()\n while (stats.any? {|s| s<=16 }) do\n if attempts > 6 \n raise CaTPAWS::EC2::Error::InstanceShutdown, \"Instances still running after a long wait. Check your EC2 account manually?\"\n end\n puts \"Terminating instances, please wait...\"\n sleep(10)\n attempts+=1\n get_instances(true)\n stats = state_code()\n end\n \n #and delete the associated security group\n @ec2.delete_security_group(@group_name)\n \n end", "def cleanup\n @omicli_pgids.each do |pgid|\n `pkill -KILL -g #{pgid}`\n end\n @omicli_pgids.clear\n end", "def suspend_job\n # get items\n query = AnalysisJobsItem.queued_for_analysis_job(id)\n\n # batch update\n query.find_in_batches(batch_size: AnalysisJob.batch_size) do |items|\n items.each(&:cancel!)\n end\n end", "def remove_all\n @jobs.each do |job|\n job.unschedule\n end\n @@instances.delete self\n end", "def kill_procs(options={})\n # Give it a good try to delete all processes.\n # This abuse is necessary to release locks on polyinstantiated\n # directories by pam_namespace.\n\n procfilter=\"-u #{uid}\"\n if options[:init_owned]\n procfilter << \" -P 1\"\n end\n\n # If the terminate delay is specified, try to terminate processes nicely\n # first and wait for them to die.\n if options[:term_delay]\n ::OpenShift::Runtime::Utils::oo_spawn(\"/usr/bin/pkill #{procfilter}\")\n etime = Time.now + options[:term_delay].to_i\n while (Time.now <= etime)\n out,err,rc = ::OpenShift::Runtime::Utils::oo_spawn(\"/usr/bin/pgrep #{procfilter}\")\n break unless rc == 0\n sleep 0.5\n end\n end\n\n oldproclist=\"\"\n stuckcount=0\n while stuckcount <= 10\n out,err,rc = ::OpenShift::Runtime::Utils::oo_spawn(\"/usr/bin/pkill -9 #{procfilter}\")\n break unless rc == 0\n\n sleep 0.5\n\n out,err,rc = ::OpenShift::Runtime::Utils::oo_spawn(\"/usr/bin/pgrep #{procfilter}\")\n if oldproclist == out\n stuckcount += 1\n else\n oldproclist = out\n stuckcount = 0\n end\n end\n\n out,err,rc = ::OpenShift::Runtime::Utils::oo_spawn(\"/usr/bin/pgrep #{procfilter}\")\n if rc == 0\n procset = out.split.join(' ')\n logger.error \"ERROR: failed to kill all processes for #{uid}: PIDs #{procset}\"\n end\n end", "def stop_all\n checklist = registry.checked_workers( policy )\n checklist.live.each { |key| reap(key) }\n checklist.late.each { |key| reap(key) }\n checklist.hung.each { |key| reap(key) }\n checklist.dead.each { |key| reap(key) }\n end", "def suspend\n end", "def wakeup()\n @tasks.each_value { |t| t.wakeup() }\n end", "def suspend\n @suspended = true\n end", "def stop\n if @pid\n Process.kill('KILL', @pid)\n Process.wait @pid\n end\n @pid = nil\n if @pgid\n Process.kill('KILL', -(@pgid))\n end\n @pgid = nil\n end", "def reset!\n @suspend_new = false\n stop_all!\n end", "def suspend_job(id)\n @drmaa_session.suspend(id)\n end", "def suspend\n param 'state' => Patriot::JobStore::JobState::SUSPEND\n end", "def reaper\n pstate = wait(0.5)\n do_kill(\"KILL\") unless pstate\n end", "def suspend\n raise Suspended\n end", "def suspend\n action('suspend')\n end", "def shutdown(group)\n cfmshutdown = AWS::CloudFormation.new\n ec2shutdown = AWS::EC2.new\n puts \"XXXXXXXXXX DAILY CHECKING HERE SHUT DOWN XXXXXXXXXXXX\"\n puts group.name\n puts \"Shut down Job is working now\"\n puts group.users.length\n puts \"-------------\"\n if group.users.length > 0\n allinstanceids = []\n group.users.each do |user|\n if user.stacks.length > 0\n user.stacks.each do |stack|\n if stack.ec2instance_ids.length > 0 \n allinstanceids.concat stack.ec2instance_ids\n end\n end\n end\n end\n puts \"BUBBBUBUBBBB\"\n puts allinstanceids.class\n allinstanceids = allinstanceids.uniq\n puts allinstanceids.class\n puts \"BUBBBUBUBBBB\"\n if allinstanceids.length > 0\n $ec2_resource.instances({instance_ids: allinstanceids}).batch_stop # To job stop\n end\n end \n puts \"YYYYYYYYYYYYYYYYYYYYYYYY\"\n end", "def force_stop\n @state.value = ApplicationState::State::STOPPED\n UnixUser.kill_procs(@user.uid)\n end", "def scale_dynos_down(dyno_name, count, current_count)\n dynos_for_type(dyno_name).sort_by { |d| d['elapsed'] }.reverse.take(current_count - count).each do |dyno|\n run_heroku_api_command(:post_ps_stop, app, { 'ps' => dyno['process'] })\n end\n end", "def asg_suspend_termination\n @asg_suspend_termination = true\n end", "def pause_process (wfid)\n\n get_expression_pool.pause_process(wfid)\n end", "def reap_workers\n workers.each do |pid, _|\n terminate(pid)\n end\n\n begin\n # waits for every children to terminate\n loop { Process.wait }\n rescue Errno::ECHILD\n # if there are no more children, continue\n end\n\n # clean up the PID data structure for the worker processes\n workers.clear\n end", "def stopApplications()\n debug(\"Stop all applications\")\n @applications.each_key { |name|\n stopApplication(name)\n }\n end", "def shutdown\n @size.times do\n schedule { throw :exit }\n end\n\n @pool.map(&:join)\n end", "def shutdown!\n @pool.each(&:shutdown!)\n end", "def stop(graceful = true)\n self.listeners = []\n limit = Time.now + timeout\n until WORKERS.empty? || Time.now > limit\n if graceful\n soft_kill_each_worker(:QUIT)\n else\n kill_each_worker(:TERM)\n end\n sleep(0.1)\n reap_all_workers\n end\n kill_each_worker(:KILL)\n end", "def scale_down\n \n num_stopped = 0\n # lets figure out what we can shut down.\n logger.info \"Looking for unused instances to scale down...\"\n EventLog.info \"Looking for unused instances to scale down...\"\n instances.each do |i|\n #this is actually pretty complicated. we have to figure out the exact range for each instance, based on the instance launch time\n lt = i.launch_time\n lt_diff = 60 - lt.min\n lower_range = HOUR_MOD - lt_diff #careful, it could be negative!\n lower_range = lower_range + 60 if lower_range < 0 # adjust for negative!\n\n upper_range = lower_range + (60 - HOUR_MOD) #upper range for mins, could be > 59!\n upper_range = upper_range - 60 if upper_range > 59 #correct for over 59\n\n now_min = DateTime.now.min\n \n ### DEBUG shutdown logic\n # puts \"Instance: #{i.aws_instance_id}\"\n # puts \"Now: #{now_min}\"\n # puts \"Upper: #{upper_range}\"\n # puts \"Lower: #{lower_range}\"\n\n if (now_min > lower_range && now_min < upper_range) || ((upper_range < lower_range) && (now_min < upper_range || now_min > lower_range))\n #so lets shutdown, but only if it won't bring us below the min_running threshold\n\n #first find out how many instances are running of this type\n total_running = (instances.select{ |j| j.running? }).size\n unless ((total_running - 1) < min || (! i.available? && ! i.error? ) || (farm_type.eql?('admin')))\n # for now we shutdown via aws but this will change as we figure out a better way\n logger.info \"Shutting down #{i.farm.ami_id} -- #{i.instance_id} due to IDLE timeout.\"\n EventLog.info \"Shutting down #{i.farm.ami_id} -- #{i.instance_id} due to IDLE timeout.\"\n i.terminate\n num_stopped += 1\n end\n end\n end\n\n return num_stopped\n\n end", "def kill\n signal(\"KILL\", scope: :all)\n cleanup\n end", "def unlock_all\n Delayed::Job.transaction do\n Delayed::Job.where(:locked_by => hostname).update_all(:locked_by => nil, :locked_at => nil)\n end\n end", "def end_process id\n taskswap 0 if @cur_proc_id == id\n @processes -= [id]\n @queue[0] -= [id]\n @queue[1] -= [id]\n end", "def suspend(job = ALL_JOBS)\n DRMAA.control(job, DRMAA::ACTION_SUSPEND)\n end", "def suspend(job = ALL_JOBS)\n DRMAA.control(job, DRMAA::ACTION_SUSPEND)\n end", "def suspend\n requires :id\n begin\n response = service.post_suspend_vapp(id)\n rescue Fog::VcloudDirector::Compute::BadRequest => ex\n Fog::Logger.debug(ex.message)\n return false\n end\n service.process_task(response.body)\n end", "def stop\n Teamwork.logger.info \"stop task #{@producers.map { |x| x[0] }}\"\n @rufus_task&.shutdown(:wait)\n end", "def kill_and_reap(pids)\n puts \"Sending signals...\"\n sig = :KILL\n pids.each do |pid|\n puts \"== kill #{pid} with #{sig}\"\n Process.kill(sig, -1 * pid.to_i)\n end\n\n pids.each do |pid|\n puts \"=== Waiting for: #{pid} #{Process.waitpid2(pid)}\"\n end\nend", "def shutdown\n @size.times do\n schedule { throw :exit }\n end\n @pool.map(&:join)\n end", "def stop_all_instances\n Spinup.logger.info('Attempting to stop all running instances')\n running_instances = ec2.instances\n\n Spinup.logger.info(\" Found #{running_instances.count} running instances\")\n\n running_instances.each do |running_instance|\n instance_stopped?(running_instance)\n end\n end", "def stop(graceful = true)\n before_stop.call(self, graceful) if before_stop\n limit = Time.now + patience\n until CAPTAINS.empty? || (n = Time.now) > limit\n kill_each_captain(graceful ? :QUIT : :TERM)\n sleep(0.1)\n reap_all_captains\n end\n if n and n > limit\n logger.debug \"admiral patience exceeded by #{n - limit} seconds (limit #{patience} seconds)\" if $DEBUG\n end\n kill_each_captain(:KILL)\n after_stop.call(self, graceful) if after_stop\n end", "def suspend\n self.suspended = true\n save(:validate => false)\n end", "def graceful\n\t\treturn nil unless self.running?\n\t\tProcess.kill 'SIGUSR1', @pid\n\tend", "def suspend()\n #This is a stub, used for indexing\n end", "def reap_all_workers\n begin\n wpid, status = Process.waitpid2(-1, Process::WNOHANG)\n wpid or return\n if reexec_pid == wpid\n logger.error \"reaped #{status.inspect} exec()-ed\"\n self.reexec_pid = 0\n self.pid = pid.chomp('.oldbin') if pid\n proc_name 'master'\n else\n worker = WORKERS.delete(wpid) and worker.close rescue nil\n m = \"reaped #{status.inspect} worker=#{worker.number rescue 'unknown'}\"\n status.success? ? logger.info(m) : logger.error(m)\n end\n rescue Errno::ECHILD\n break\n end while true\n end", "def purge_expired_workers\n @services.purge_expired_workers\n end", "def stop\n ck_valid\n Process.kill 15, @pid if running?\n\n invalidate\n end", "def reap_all_workers\n begin\n wpid, status = Process.waitpid2(-1, Process::WNOHANG)\n wpid or return\n if reexec_pid == wpid\n logger.error \"reaped #{status.inspect} exec()-ed\"\n self.reexec_pid = 0\n self.pid = pid.chomp('.oldbin') if pid\n proc_name 'master'\n else\n worker = WORKERS.delete(wpid) and worker.close rescue nil\n m = \"reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}\"\n status.success? ? logger.info(m) : logger.error(m)\n end\n rescue Errno::ECHILD\n break\n end while true\n end", "def reap_workers\n loop do \n begin\n worker_pid, status = Process.waitpid2(-1, Process::WNOHANG) \n rescue Exception => e \n return\n end\n return unless worker_pid\n reap_worker(worker_pid) \n end\n end", "def suspend!\n return if suspended?\n self.status = \"suspended\"\n self.stop = Time.now.to_s\n end", "def sleep(duration)\n if sleep_procs.any?\n sleep_procs.each { |_name, a_proc| instance_exec(duration, &a_proc) }\n else\n Kernel.sleep(duration)\n end\n end", "def stop\n log(:debug) { 'Graceful shutdown requested.' }\n\n @running = false\n idle.each { |worker| worker.terminate }\n idle.clear\n\n if busy.any?\n log(:debug) { \"Wait for #{busy.size} workers to terminate.\" }\n\n wait :shutdown\n end\n\n log(:debug) { 'Graceful shutdown done.' }\n end", "def stop()\n @tasks.each_value { |task| task.stop() }\n end", "def stop_instances_by_group_id(group_id)\n instances = @os_aws.describe_running_instances(group_id)\n ids = instances.map { |k, _| k[:instance_id] }\n\n puts \"Stoping the following instances #{ids}\"\n resp = []\n resp = @os_aws.stop_instances(ids).to_hash unless ids.empty?\n resp\n end", "def shutdown_all\n # TODO: implement\n shutdown\n end", "def shutdown\n logger.info \"Shutting down ScoutApm\"\n return if !context.started?\n context.shutting_down!\n ::ScoutApm::Agent.instance.stop_background_worker\n end", "def stop_all\n @resources.each { |name,object| stop name unless object.done? } unless @all_stopped\n end", "def kill_instruments(_=nil)\n instruments_pids.each do |pid|\n terminator = RunLoop::ProcessTerminator.new(pid, \"QUIT\", \"instruments\")\n unless terminator.kill_process\n terminator = RunLoop::ProcessTerminator.new(pid, \"KILL\", \"instruments\")\n terminator.kill_process\n end\n end\n end", "def stop(graceful = true)\n limit = Time.now + timeout\n until WORKERS.empty? || Time.now > limit\n kill_each_worker(graceful ? :QUIT : :TERM)\n sleep(0.1)\n reap_all_workers\n end\n kill_each_worker(:KILL)\n end", "def resend_shutdown_signal\n @shutdown_signal_sent_at = Time.now\n output \"Resending #{@shutdown_signal.inspect} to process group pgid=#@pgid\"\n signal_process_group @shutdown_signal\n end", "def stop\n Process.kill \"KILL\", @sipp_pid if @sipp_pid\n end", "def shutdown\n @workers.each { |pid| Process.waitpid(pid) }\n DRb.stop_service\n end", "def shutdown\n @size.times do\n schedule { throw :exit }\n end\n\n @pool.map(&:join)\n\n true\n end", "def wakeup()\n @flows.each_value { |f| f.wakeup() }\n end", "def reap_all_captains\n begin\n cpid, status = Process.waitpid2(-1, Process::WNOHANG)\n cpid or return\n if reexec_pid == cpid\n logger.error \"reaped #{status.inspect} exec()-ed\"\n self.reexec_pid = 0\n self.pid = pid.chomp('.oldbin') if pid\n proc_name \"admiral\"\n else\n captain = CAPTAINS.delete(cpid) rescue nil\n m = \"reaped #{status.inspect} captain=#{captain.label rescue 'unknown'}\"\n status.success? ? logger.info(m) : logger.error(m)\n end\n rescue Errno::ECHILD\n break\n end while true\n end", "def stop_all(force = false)\n @monitor.stop if @monitor\n \n failed_to_kill = false\n debug = options[:debug]\n wait = options[:force_kill_wait].to_i\n pids = unix_pids\n if wait > 0 && pids.size > 0\n puts \"[daemons_ext]: Killing #{app_name} with force after #{wait} secs.\"\n STDOUT.flush\n\n # Send term first, don't delete PID files.\n pids.each {|pid| Process.kill('TERM', pid) rescue Errno::ESRCH}\n\n begin\n Timeout::timeout(wait) {block_on_pids(wait, debug, options[:sleepy_time] || 1)}\n rescue Timeout::Error\n puts \"[daemons_ext]: Time is up! Forcefully killing #{unix_pids.size} #{app_name}(s)...\"\n STDOUT.flush\n unix_pids.each {|pid| `kill -9 #{pid}`}\n begin\n # Give it an extra 30 seconds to kill -9\n Timeout::timeout(30) {block_on_pids(wait, debug, options[:sleepy_time] || 1)}\n rescue Timeout::Error\n failed_to_kill = true\n puts \"[daemons_ext]: #{unix_pids} #{app_name}(s) won't die! Giving up.\"\n STDOUT.flush\n end\n ensure\n # Delete Pidfiles\n @applications.each {|a| a.zap!}\n end\n\n puts \"[daemons_ext]: All #{app_name}s dead.\" unless failed_to_kill\n STDOUT.flush\n else\n @applications.each {|a| \n if force\n begin; a.stop; rescue ::Exception; end\n else\n a.stop\n end\n }\n end\n end", "def stop_all(wait=true)\n if script_to_run?('terminate')\n options = { \"DB_TERMINATE_SAFETY\" => \"text:off\" }\n run_script_on_set('terminate', @servers.select { |s| s.state != 'stopped' }, wait, options)\n # @servers.each { |s|run_script('terminate', s, options) unless s.state == 'stopped' }\n else\n @servers.each { |s| obj_behavior(s, :stop) }\n end\n \n wait_for_all(\"stopped\") if wait\n # unset dns in our local cached copy..\n @servers.each { |s| s.params['dns-name'] = nil } \n end", "def remove_all_spies\n @registry.remove_all.each(&:stop)\n end", "def stop()\n @running = false # to avoid error message from termination\n # the \"minus\" terminates all processes with the group ID @pid\n # this ensures the child and all of its grandchildren are terminated\n # PROBLEM: the children are not terminated when the parent exits\n Process.kill(\"-TERM\", @pid)\n Timer.cancel(@name)\n @@inst[self.class].delete(@name)\n end", "def reap_workers\n # Don't try to find more dead workers than the process count\n @workers.length.times do\n # We use +waitpid+ to find any child process which has exited. It\n # immediately returns when there aren't any dead processes.\n if pid = Process.waitpid(-1, Process::WNOHANG)\n despawn_worker(pid)\n else\n return # Stop when we don't find any\n end\n end\n end", "def stop_all!\n @devices.each(&:stop!)\n end", "def stop\n managers.each { |manager| manager << :terminate! } if managers\n @managers = nil\n\n nil\n end", "def terminate_instance_in_auto_scaling_group(instance_id, should_decrement_desired_capacity)\n request({\n 'Action' => 'TerminateInstanceInAutoScalingGroup',\n 'InstanceId' => instance_id,\n 'ShouldDecrementDesiredCapacity' => should_decrement_desired_capacity.to_s,\n :parser => Fog::Parsers::AWS::AutoScaling::TerminateInstanceInAutoScalingGroup.new\n })\n end", "def pause\n with_queue_control do |control|\n control.pause\n end\n end", "def power_off\n requires :id\n begin\n response = service.post_power_off_vapp(id)\n rescue Fog::VcloudDirector::Compute::BadRequest => ex\n Fog::Logger.debug(ex.message)\n return false\n end\n service.process_task(response.body)\n end", "def finalize()\n # below function is not yet fully functional\n unlock_all_instances()\n end", "def shutdown!\n shutdown\n kill_jobs\n end" ]
[ "0.7878253", "0.73964447", "0.73952764", "0.6985465", "0.67330927", "0.6577605", "0.65640837", "0.65640837", "0.655745", "0.6305511", "0.6054132", "0.6017615", "0.5987914", "0.5923863", "0.588988", "0.58294874", "0.57266843", "0.56494606", "0.56315875", "0.5628368", "0.55936426", "0.555184", "0.5551453", "0.55504", "0.5444814", "0.5423758", "0.5423525", "0.5417201", "0.5390985", "0.53837466", "0.53792363", "0.53568727", "0.5354416", "0.53416175", "0.5329639", "0.53211087", "0.52678293", "0.5243123", "0.52363133", "0.5231489", "0.5202146", "0.5187991", "0.5179253", "0.51755345", "0.5170754", "0.5113877", "0.51121104", "0.5106125", "0.5077172", "0.50757205", "0.5064685", "0.5044194", "0.50420326", "0.5036618", "0.5030433", "0.5023644", "0.501304", "0.49906483", "0.4987932", "0.49812335", "0.49807298", "0.49774817", "0.49755833", "0.4973438", "0.4964505", "0.49562564", "0.4952258", "0.49496293", "0.49461597", "0.49391392", "0.4938152", "0.4929741", "0.49265137", "0.49241778", "0.49162292", "0.4915467", "0.49055952", "0.49049565", "0.49047318", "0.49018872", "0.4891632", "0.48865154", "0.48862234", "0.48852846", "0.4875076", "0.4874903", "0.48721433", "0.48692736", "0.48686287", "0.484026", "0.48397514", "0.48364425", "0.48322156", "0.4827394", "0.48176122", "0.48155117", "0.48153874", "0.48140144", "0.48091638", "0.4807988" ]
0.73492324
3
Resumes processes for this Auto Scaling group. resume two processes by name auto_scaling_group.suspend_processes 'Launch', 'AZRebalance'
def resume_processes *processes client_opts = {} client_opts[:auto_scaling_group_name] = name client_opts[:scaling_processes] = processes.flatten client.resume_processes(client_opts) nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def suspend_processes(auto_scaling_group_name, options = {})\n if scaling_processes = options.delete('ScalingProcesses')\n options.merge!(AWS.indexed_param('ScalingProcesses.member.%d', [*scaling_processes]))\n end\n request({\n 'Action' => 'SuspendProcesses',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(options))\n end", "def resume_all_processes\n resume_processes\n end", "def suspend_processes *processes\n client_opts = {}\n client_opts[:auto_scaling_group_name] = name\n client_opts[:scaling_processes] = processes.flatten\n client.suspend_processes(client_opts)\n nil\n end", "def resume_all_processes\n groups.each do |group|\n group.resume_processes\n end\n end", "def pause_scaling_events\n client.suspend_processes(auto_scaling_group_name: asg_name,\n scaling_processes:\n %w[ReplaceUnhealthy AlarmNotification ScheduledActions AZRebalance])\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n \n suspended = load_from_s3(@task.bucket)\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n #@task.debug { \"Scaling group #{@name} already running\" }\n #else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n autoscaling_group.suspend_processes suspended.keys\n end\n #end\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n @task.debug { \"Scaling group #{@name} already running\" }\n else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n end\n end\n end", "def resume\n execute_prlctl('resume', @uuid)\n end", "def suspend_all_processes\n suspend_processes\n end", "def resume\n process_status = status\n if process_status == 'stopped'\n return status if Process.kill('CONT', @proc_attrs[:pid].to_i)\n end\n process_status\n rescue Errno::EPERM\n return 'non-privilaged operation'\n end", "def suspend_all_processes\n groups.each do |group|\n group.suspend_processes\n end\n end", "def resume\n @suspended = false\n end", "def resume(&block)\n @pauses_manager.resume(&block)\n end", "def resume_process (wfid)\n\n get_expression_pool.resume_process(wfid)\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n save_to_s3(@task.bucket)\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def resume\n execute(:resume_vm, VmId: vm_id)\n end", "def resume(job = ALL_JOBS)\n DRMAA.control(job, DRMAA::ACTION_RESUME)\n end", "def suspend\n execute_prlctl('suspend', @uuid)\n end", "def resume(job = ALL_JOBS)\n DRMAA.control(job, DRMAA::ACTION_RESUME)\n end", "def resume\n @pauses.each do |topic, partitions|\n partitions.each do |partition, pause|\n next unless pause.paused?\n next unless pause.expired?\n\n pause.resume\n\n yield(topic, partition)\n end\n end\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def resume_all; threads.each {|x| resume(x)}; end", "def resume_campaigns(params)\n perform_request(self, @token, 'campaigns', 'resume', params)\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n else\n @task.debug { \"Scaling group #{@name} already suspended\" }\n end\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def resume\n @vm.resume\n end", "def resume\n # Ensure already inactive\n unless self.active\n # Set active true\n update(active: true)\n # 2. StandingEvent for resume\n StandingEvent.create(change: 0,\n standing: self,\n type: :resume)\n return true\n end\n false\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n #else\n #@task.debug { \"Scaling group #{@name} already suspended\" }\n #end\n end", "def resume\n with_queue_control do |control|\n control.resume\n end\n end", "def cmd_suspend(*args)\n # give'em help if they want it, or seem confused\n if args.length == 0 or (args.include? \"-h\")\n cmd_suspend_help\n return true\n end\n\n continue = args.delete(\"-c\") || false\n resume = args.delete(\"-r\") || false\n\n # validate all the proposed pids first so we can bail if one is bogus\n valid_pids = validate_pids(args)\n args.uniq!\n diff = args - valid_pids.map {|e| e.to_s}\n if not diff.empty? # then we had an invalid pid\n print_error(\"The following pids are not valid:\t#{diff.join(\", \").to_s}.\")\n if continue\n print_status(\"Continuing. Invalid args have been removed from the list.\")\n else\n print_error(\"Quitting.\tUse -c to continue using only the valid pids.\")\n return false\n end\n end\n\n targetprocess = nil\n if resume\n print_status(\"Resuming: #{valid_pids.join(\", \").to_s}\")\n else\n print_status(\"Suspending: #{valid_pids.join(\", \").to_s}\")\n end\n begin\n valid_pids.each do |pid|\n print_status(\"Targeting process with PID #{pid}...\")\n targetprocess = client.sys.process.open(pid, PROCESS_ALL_ACCESS)\n targetprocess.thread.each_thread do |x|\n if resume\n targetprocess.thread.open(x).resume\n else\n targetprocess.thread.open(x).suspend\n end\n end\n end\n rescue ::Rex::Post::Meterpreter::RequestError => e\n print_error \"Error acting on the process: #{e.to_s}.\"\n print_error \"Try migrating to a process with the same owner as the target process.\"\n print_error \"Also consider running the win_privs post module and confirm SeDebug priv.\"\n return false unless continue\n ensure\n targetprocess.close if targetprocess\n end\n return true\n end", "def suspend\n process_status = status\n if process_status != 'terminated' && process_status != 'stopped'\n return status if Process.kill('STOP', @proc_attrs[:pid].to_i)\n end\n process_status\n rescue Errno::EPERM\n return 'non-privilaged operation'\n end", "def resume()\n @ole.Resume()\n end", "def resume\n action('resume')\n end", "def resume_job\n # get items\n query = AnalysisJobsItem.cancelled_for_analysis_job(id)\n\n # batch update\n query.find_in_batches(batch_size: AnalysisJob.batch_size) do |items|\n items.each(&:retry!)\n end\n end", "def resume_action\n Resume.new :component_id => component_id, :call_id => call_id\n end", "def resume\n\n end", "def resume\n end", "def resume\n end", "def resume\n data = JSON.generate(:resume => nil)\n response = @compute.connection.csreq(\"POST\",@svrmgmthost,\"#{@svrmgmtpath}/servers/#{URI.encode(self.id.to_s)}/action\",@svrmgmtport,@svrmgmtscheme,{'content-type' => 'application/json'},data)\n OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)\n true\n end", "def suspend\n execute(\"controlvm\", @uuid, \"savestate\")\n end", "def resume_action\n Resume.new :component_id => component_id, :call_id => call_id\n end", "def resume()\n\t\t\tkparams = {}\n\t\t\tclient.queue_service_action_call('household', 'resume', 'bool', kparams)\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\treturn client.do_queue()\n\t\tend", "def resume\n send_resume(@token, @session.session_id, @session.sequence)\n end", "def resume\n\tend", "def suspend_campaigns(params)\n perform_request(self, @token, 'campaigns', 'suspend', params)\n end", "def resume_process (wfid)\n\n wfid = extract_wfid wfid\n\n root_expression = fetch_root(wfid)\n\n #\n # remove 'paused' flag\n\n @paused_instances.delete(wfid)\n root_expression.unset_variable(OpenWFE::VAR_PAUSED)\n\n #\n # notify ...\n\n onotify(:resume, root_expression.fei)\n\n #\n # replay\n #\n # select PausedError instances in separate list\n\n errors = get_error_journal.get_error_log wfid\n error_class = OpenWFE::PausedError.name\n paused_errors = errors.select { |e| e.error_class == error_class }\n\n return if paused_errors.size < 1\n\n # replay select PausedError instances\n\n paused_errors.each { |e| get_error_journal.replay_at_error e }\n end", "def resume_action\n Resume.new :component_id => component_id, :target_call_id => target_call_id\n end", "def suspend\n requires :id\n begin\n response = service.post_suspend_vapp(id)\n rescue Fog::VcloudDirector::Compute::BadRequest => ex\n Fog::Logger.debug(ex.message)\n return false\n end\n service.process_task(response.body)\n end", "def do_resume(msg)\n\n return unless h.state == 'paused' || h.state == 'awaiting'\n\n h.state = nil\n\n m = h.delete('paused_apply')\n return do_apply(m) if m\n # if it's a paused apply, pipe it directly to #do_apply\n\n replies = h.delete('paused_replies') || []\n\n do_persist || return\n\n h.children.each { |i| @context.storage.put_msg('resume', 'fei' => i) }\n # resume children\n\n replies.each { |m| @context.storage.put_msg(m.delete('action'), m) }\n # trigger replies\n end", "def suspend\n Fission::Action::VM::Suspender.new(self).suspend\n end", "def suspend_job(id)\n @drmaa_session.suspend(id)\n end", "def resume(vid)\n perform_request(action: 'vserver-unsuspend', vserverid: vid)\n end", "def suspend\n param 'state' => Patriot::JobStore::JobState::SUSPEND\n end", "def suspend\n\t\t@state = STATE_SUSPENDED\n\tend", "def reboot(hard = false)\n return if @cloud_id.nil?\n\n if hard\n groupname = nil\n if !@config['basis'].nil?\n resp = MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).describe_auto_scaling_instances(\n instance_ids: [@cloud_id]\n )\n groupname = resp.auto_scaling_instances.first.auto_scaling_group_name\n MU.log \"Pausing Autoscale processes in #{groupname}\", MU::NOTICE\n MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).suspend_processes(\n auto_scaling_group_name: groupname,\n scaling_processes: [\n \"Terminate\",\n ], \n )\n end\n begin\n MU.log \"Stopping #{@mu_name} (#{@cloud_id})\", MU::NOTICE\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).stop_instances(\n instance_ids: [@cloud_id]\n )\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).wait_until(:instance_stopped, instance_ids: [@cloud_id]) do |waiter|\n waiter.before_attempt do\n MU.log \"Waiting for #{@mu_name} to stop for hard reboot\"\n end\n end\n MU.log \"Starting #{@mu_name} (#{@cloud_id})\"\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).start_instances(\n instance_ids: [@cloud_id]\n )\n ensure\n if !groupname.nil?\n MU.log \"Resuming Autoscale processes in #{groupname}\", MU::NOTICE\n MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).resume_processes(\n auto_scaling_group_name: groupname,\n scaling_processes: [\n \"Terminate\",\n ],\n )\n end\n end\n else\n MU.log \"Rebooting #{@mu_name} (#{@cloud_id})\"\n MU::Cloud::AWS.ec2(region: @region, credentials: @credentials).reboot_instances(\n instance_ids: [@cloud_id]\n )\n end\n end", "def reboot(hard = false)\n return if @cloud_id.nil?\n\n if hard\n groupname = nil\n if !@config['basis'].nil?\n resp = MU::Cloud::AWS.autoscale(region: @config['region'], credentials: @config['credentials']).describe_auto_scaling_instances(\n instance_ids: [@cloud_id]\n )\n groupname = resp.auto_scaling_instances.first.auto_scaling_group_name\n MU.log \"Pausing Autoscale processes in #{groupname}\", MU::NOTICE\n MU::Cloud::AWS.autoscale(region: @config['region'], credentials: @config['credentials']).suspend_processes(\n auto_scaling_group_name: groupname\n )\n end\n begin\n MU.log \"Stopping #{@mu_name} (#{@cloud_id})\", MU::NOTICE\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).stop_instances(\n instance_ids: [@cloud_id]\n )\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).wait_until(:instance_stopped, instance_ids: [@cloud_id]) do |waiter|\n waiter.before_attempt do |attempts|\n MU.log \"Waiting for #{@mu_name} to stop for hard reboot\"\n end\n end\n MU.log \"Starting #{@mu_name} (#{@cloud_id})\"\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).start_instances(\n instance_ids: [@cloud_id]\n )\n ensure\n if !groupname.nil?\n MU.log \"Resuming Autoscale processes in #{groupname}\", MU::NOTICE\n MU::Cloud::AWS.autoscale(region: @config['region'], credentials: @config['credentials']).resume_processes(\n auto_scaling_group_name: groupname\n )\n end\n end\n else\n MU.log \"Rebooting #{@mu_name} (#{@cloud_id})\"\n MU::Cloud::AWS.ec2(region: @config['region'], credentials: @config['credentials']).reboot_instances(\n instance_ids: [@cloud_id]\n )\n end\n end", "def resume(*args)\n @fiber.resume(*args)\n end", "def restart\n app = extract_app\n\n opts = case args.first\n when NilClass then\n display \"Restarting processes... \", false\n {}\n when /.+\\..+/\n ps = args.first\n display \"Restarting #{ps} process... \", false\n { :ps => ps }\n else\n type = args.first\n display \"Restarting #{type} processes... \", false\n { :type => type }\n end\n heroku.ps_restart(app, opts)\n display \"done\"\n end", "def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end", "def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end", "def resume\n return true if active?\n FFI::Libvirt.virDomainResume(self) == 0\n end", "def resume\n return true if active?\n FFI::Libvirt.virDomainResume(self) == 0\n end", "def resumed_background(job_fullname)\n \"Resuming the background job '#{job_fullname}'.\"\n end", "def resume!\n should_flush = @paused_mutex.synchronize do\n @paused -= 1 if @paused > 0\n @paused == 0\n end\n flush! if should_flush\n self\n end", "def resume!\n self.class.current(self.user).close! if self.class.current(self.user)\n self.work_times << TaskTime.create(start: DateTime.now, user: self.user)\n\n self\n end", "def resume; end", "def resume; end", "def _suspend\n\t\t# Ask the user if they would like to background the session\n\t\tif (prompt_yesno(\"Background session #{name}?\") == true)\n\t\t\tself.interacting = false\n\t\tend\n\tend", "def suspend_cluster_restore_suspend(opts = {})\n data, _status_code, _headers = suspend_cluster_restore_suspend_with_http_info(opts)\n return data\n end", "def reset!\n @suspend_new = false\n stop_all!\n end", "def resume_session\n session_tracker.resume_session\n end", "def restart\n process = shift_argument\n validate_arguments!\n release = options[:version]\n\n message, options = case process\n when NilClass\n [\"Restarting processes\", { }]\n when /.+\\..+/\n ps = args.first\n [\"Restarting #{ps} process\", { :ps => ps }]\n else\n type = args.first\n [\"Restarting #{type} processes\", { :type => type }]\n end\n\n action(message) do\n api.post_ps_restart(app, options.merge(:release => release))\n end\n end", "def suspend\n @suspended = true\n end", "def launch_minimum_number_of_instances \n if can_start_a_new_instance? && !minimum_number_of_instances_are_running? \n list_of_pending_instances.size == 0 ? request_launch_one_instance_at_a_time : wait(\"5.seconds\")\n reset!\n launch_minimum_number_of_instances\n provision_slaves_from_n(minimum_instances.to_i)\n after_launched\n end\n end", "def suspend\n raise Suspended\n end", "def resume\n FMOD.invoke(:ChannelGroup_SetPaused, self, 0)\n self\n end", "def suspend\n action('suspend')\n end", "def asg_suspend_termination\n @asg_suspend_termination = true\n end", "def cmd_resume argv\n setup argv\n uuid = @hash['uuid']\n response = @api.resume(uuid)\n msg response\n return response\n end", "def resume\n\t\t@state = STATE_ONLINE\n\tend", "def startup(group)\n cfmstartup = AWS::CloudFormation.new # call cloudformation\n ec2startup = AWS::EC2.new # call ec2\n # long running method\n puts \"XXXXXXXXXX DAILY CHECKING HERE STARUP XXXXXXXXXXXX\"\n puts group.name\n puts \"Start up Job is working now\"\n if group.users.length > 0\n allinstanceids = []\n group.users.each do |user|\n if user.stacks.length > 0\n user.stacks.each do |stack|\n if stack.ec2instance_ids.length > 0 \n allinstanceids.concat stack.ec2instance_ids # concatinate all instance ids with ec2 instance ids of stack\n end\n end\n end\n end\n p allinstanceids = allinstanceids.uniq\n if allinstanceids.length > 0\n $ec2_resource.instances({instance_ids: allinstanceids}).batch_start # start the jobs\n end\n end \n puts \"XXXXXXXXXXXXXXXXXXXXXX\"\n end", "def unpause_processing\n log \"CONT received; resuming job processing\"\n @paused = false\n redis.del(pause_key)\n end", "def suspend!\n return if suspended?\n self.status = \"suspended\"\n self.stop = Time.now.to_s\n end", "def suspend(job = ALL_JOBS)\n DRMAA.control(job, DRMAA::ACTION_SUSPEND)\n end", "def resume(node)\n Result.new(call(CMD_RESUME % node))\n end", "def restart(name)\n if proc = @processes[name]\n proc.on(:exit) do\n start(name)\n end\n proc.stop\n elsif @commands_by_name[name]\n start(name)\n else\n raise \"no process for #{name}\"\n end\n end", "def resume\n super\n each_slave { |instance, iter| instance.framework.resume{ iter.next } }\n true\n end", "def resume(seq, token, session_id)\n data = {\n op: Opcodes::RESUME,\n d: {\n seq: seq,\n token: token,\n session_id: session_id\n }\n }\n\n @ws.send(data.to_json)\n end", "def resume\n @halt = false\n end", "def suspend(job = ALL_JOBS)\n DRMAA.control(job, DRMAA::ACTION_SUSPEND)\n end", "def resume!\n raise InvalidActionError, \"Cannot resume a Output that is not paused.\" unless paused?\n resume_action.tap do |action|\n result = write_action action\n resumed! if result\n end\n end", "def resume\n if !block_given?\n @j_del.java_method(:resume, []).call()\n return self\n end\n raise ArgumentError, \"Invalid arguments when calling resume()\"\n end", "def resume_task\n background = params[:sync] != '1'\n\n if background\n SyncTaskWorker.perform_async('token' => session[:facebook].access_token, 'task' => @task.id)\n else\n task_class = \"Tasks::\" << \"#{@task.type}_task\".camelize\n klass = task_class.constantize.new(task: @task, send_mail: false)\n klass.run\n end\n \n flash[:notice] << 'This task is now resumed.'\n redirect_to tasks_path and return\n end", "def continue_process_events(str=\"\")\r\n @num_of_suspend -= 1\r\n if @num_of_suspend <= 0\r\n @num_of_suspend = 0\r\n @suspend_queue_proc = false\r\n @log.debug(\"Continue to process core events (locks: #{@num_of_suspend}) (#{str})\")\r\n process_next_gevent\r\n else\r\n @log.debug(\"Suspend yet locked #{@num_of_suspend} (#{str})\")\r\n end\r\n end", "def strict_resume_state\n super\n end", "def reboot_instances(*instances)\n instances = instances.flatten\n link = generate_request(\"RebootInstances\", amazonize_list('InstanceId', instances))\n request_info(link, RightBoolResponseParser.new(:logger => @logger))\n rescue Exception\n on_exception\n end", "def resume(fiber, *arguments); end", "def pause_processing\n @processing = false\n end", "def resume!\n raise InvalidActionError, \"Cannot resume a Output that is not paused.\" unless paused?\n resume_action.tap do |action|\n result = write_action action\n resumed! if result\n end\n end" ]
[ "0.7782267", "0.72685194", "0.7184569", "0.7073122", "0.6832541", "0.6691391", "0.6535876", "0.6292499", "0.610317", "0.60867125", "0.59854287", "0.5759839", "0.57172036", "0.5659814", "0.55444354", "0.5537938", "0.552023", "0.54997283", "0.5472325", "0.5393976", "0.5385579", "0.5385419", "0.53717154", "0.5317632", "0.5300939", "0.5300939", "0.5295943", "0.52936804", "0.52260935", "0.5219636", "0.52146024", "0.51998067", "0.5167008", "0.51375", "0.51181287", "0.506372", "0.5061813", "0.5046748", "0.5046748", "0.50302285", "0.5019673", "0.5015508", "0.501495", "0.5013217", "0.50044024", "0.4996182", "0.4938023", "0.49369094", "0.49099627", "0.4895544", "0.48927122", "0.48763144", "0.4873067", "0.48356307", "0.4820537", "0.47936004", "0.47898", "0.4776016", "0.4775008", "0.4752498", "0.4752498", "0.47357878", "0.47357878", "0.47356567", "0.47326958", "0.4725671", "0.47147012", "0.47147012", "0.47120643", "0.47017926", "0.46883395", "0.4674173", "0.4664833", "0.4653646", "0.46524075", "0.46506277", "0.46474805", "0.46419385", "0.46272665", "0.46027726", "0.46022654", "0.46012953", "0.45830762", "0.4573007", "0.45682752", "0.45601904", "0.45432636", "0.4541215", "0.4527311", "0.45272103", "0.45132357", "0.4511309", "0.45048058", "0.4499978", "0.4496769", "0.44886807", "0.44878834", "0.44873855", "0.44873163", "0.44798204" ]
0.8200772
0
Resumes all processes for this Auto Scaling group.
def resume_all_processes resume_processes end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def resume_processes *processes\n client_opts = {}\n client_opts[:auto_scaling_group_name] = name\n client_opts[:scaling_processes] = processes.flatten\n client.resume_processes(client_opts)\n nil\n end", "def resume_all_processes\n groups.each do |group|\n group.resume_processes\n end\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n \n suspended = load_from_s3(@task.bucket)\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n #@task.debug { \"Scaling group #{@name} already running\" }\n #else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n autoscaling_group.suspend_processes suspended.keys\n end\n #end\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n @task.debug { \"Scaling group #{@name} already running\" }\n else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n end\n end\n end", "def suspend_processes(auto_scaling_group_name, options = {})\n if scaling_processes = options.delete('ScalingProcesses')\n options.merge!(AWS.indexed_param('ScalingProcesses.member.%d', [*scaling_processes]))\n end\n request({\n 'Action' => 'SuspendProcesses',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(options))\n end", "def pause_scaling_events\n client.suspend_processes(auto_scaling_group_name: asg_name,\n scaling_processes:\n %w[ReplaceUnhealthy AlarmNotification ScheduledActions AZRebalance])\n end", "def resume\n execute_prlctl('resume', @uuid)\n end", "def resume\n @suspended = false\n end", "def resume_all; threads.each {|x| resume(x)}; end", "def resume(job = ALL_JOBS)\n DRMAA.control(job, DRMAA::ACTION_RESUME)\n end", "def resume(job = ALL_JOBS)\n DRMAA.control(job, DRMAA::ACTION_RESUME)\n end", "def resume_campaigns(params)\n perform_request(self, @token, 'campaigns', 'resume', params)\n end", "def resume\n @pauses.each do |topic, partitions|\n partitions.each do |partition, pause|\n next unless pause.paused?\n next unless pause.expired?\n\n pause.resume\n\n yield(topic, partition)\n end\n end\n end", "def resume\n with_queue_control do |control|\n control.resume\n end\n end", "def resume(&block)\n @pauses_manager.resume(&block)\n end", "def suspend_all_processes\n groups.each do |group|\n group.suspend_processes\n end\n end", "def suspend_processes *processes\n client_opts = {}\n client_opts[:auto_scaling_group_name] = name\n client_opts[:scaling_processes] = processes.flatten\n client.suspend_processes(client_opts)\n nil\n end", "def resume\n process_status = status\n if process_status == 'stopped'\n return status if Process.kill('CONT', @proc_attrs[:pid].to_i)\n end\n process_status\n rescue Errno::EPERM\n return 'non-privilaged operation'\n end", "def suspend_all_processes\n suspend_processes\n end", "def resume\n @vm.resume\n end", "def resume_process (wfid)\n\n get_expression_pool.resume_process(wfid)\n end", "def resume!\n should_flush = @paused_mutex.synchronize do\n @paused -= 1 if @paused > 0\n @paused == 0\n end\n flush! if should_flush\n self\n end", "def resume_job\n # get items\n query = AnalysisJobsItem.cancelled_for_analysis_job(id)\n\n # batch update\n query.find_in_batches(batch_size: AnalysisJob.batch_size) do |items|\n items.each(&:retry!)\n end\n end", "def resume\n execute(:resume_vm, VmId: vm_id)\n end", "def resume\n FMOD.invoke(:ChannelGroup_SetPaused, self, 0)\n self\n end", "def resume()\n @ole.Resume()\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n save_to_s3(@task.bucket)\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def resume\n # Ensure already inactive\n unless self.active\n # Set active true\n update(active: true)\n # 2. StandingEvent for resume\n StandingEvent.create(change: 0,\n standing: self,\n type: :resume)\n return true\n end\n false\n end", "def resume\n action('resume')\n end", "def resume_all\n @condition_variable.broadcast\n end", "def resume\n end", "def resume\n end", "def resume\n if(@paused)\n @paused = false\n reset\n end\n current_self\n end", "def resume\n\tend", "def resume\n\n end", "def do_resume(msg)\n\n return unless h.state == 'paused' || h.state == 'awaiting'\n\n h.state = nil\n\n m = h.delete('paused_apply')\n return do_apply(m) if m\n # if it's a paused apply, pipe it directly to #do_apply\n\n replies = h.delete('paused_replies') || []\n\n do_persist || return\n\n h.children.each { |i| @context.storage.put_msg('resume', 'fei' => i) }\n # resume children\n\n replies.each { |m| @context.storage.put_msg(m.delete('action'), m) }\n # trigger replies\n end", "def resume(*args)\n @fiber.resume(*args)\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def resume\n send_resume(@token, @session.session_id, @session.sequence)\n end", "def resume\n super\n each_slave { |instance, iter| instance.framework.resume{ iter.next } }\n true\n end", "def resume\n return true if active?\n FFI::Libvirt.virDomainResume(self) == 0\n end", "def resume\n return true if active?\n FFI::Libvirt.virDomainResume(self) == 0\n end", "def resume()\n\t\t\tkparams = {}\n\t\t\tclient.queue_service_action_call('household', 'resume', 'bool', kparams)\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\treturn client.do_queue()\n\t\tend", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def resume_session\n session_tracker.resume_session\n end", "def resume_action\n Resume.new :component_id => component_id, :call_id => call_id\n end", "def resume()\n #This is a stub, used for indexing\n end", "def resume!\n self.class.current(self.user).close! if self.class.current(self.user)\n self.work_times << TaskTime.create(start: DateTime.now, user: self.user)\n\n self\n end", "def resume_process (wfid)\n\n wfid = extract_wfid wfid\n\n root_expression = fetch_root(wfid)\n\n #\n # remove 'paused' flag\n\n @paused_instances.delete(wfid)\n root_expression.unset_variable(OpenWFE::VAR_PAUSED)\n\n #\n # notify ...\n\n onotify(:resume, root_expression.fei)\n\n #\n # replay\n #\n # select PausedError instances in separate list\n\n errors = get_error_journal.get_error_log wfid\n error_class = OpenWFE::PausedError.name\n paused_errors = errors.select { |e| e.error_class == error_class }\n\n return if paused_errors.size < 1\n\n # replay select PausedError instances\n\n paused_errors.each { |e| get_error_journal.replay_at_error e }\n end", "def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end", "def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end", "def resume_processing\n puts \"\\nDeferredActionChain.resume_processing: Resuming processing of DeferredActionChain[#{self.id}] of Rule #{self.rule_id}\\n\"\n rule.process_rule(event, self)\n end", "def resume_action\n Resume.new :component_id => component_id, :call_id => call_id\n end", "def resume; end", "def resume; end", "def restart!\n stop!\n start!\n end", "def resume\n @halt = false\n end", "def resume\n if !block_given?\n @j_del.java_method(:resume, []).call()\n return self\n end\n raise ArgumentError, \"Invalid arguments when calling resume()\"\n end", "def resume_action\n Resume.new :component_id => component_id, :target_call_id => target_call_id\n end", "def restart\n self.stop\n self.start\n end", "def reset!\n @suspend_new = false\n stop_all!\n end", "def resume(*args)\n #TODO should only allow if @status is :run, which really means\n # blocked by a call to Yield\n fiber.resume(*args)\n end", "def strict_resume_state\n super\n end", "def resume!\n raise InvalidActionError, \"Cannot resume a Output that is not paused.\" unless paused?\n resume_action.tap do |action|\n result = write_action action\n resumed! if result\n end\n end", "def resume\n @bars.each(&:resume)\n end", "def resume_listening(*queues)\n queues = determine_queue_names(queues)\n subscriber.resume_listening(queues)\n end", "def resume\n @mutex.synchronize do\n if @state == :complete\n false\n else\n @sleeper.wake\n true\n end\n end\n end", "def resume!\n raise InvalidActionError, \"Cannot resume a Output that is not paused.\" unless paused?\n resume_action.tap do |action|\n result = write_action action\n resumed! if result\n end\n end", "def autoscaling_instances\n autoscaling_group.auto_scaling_instances\n end", "def autoscaling_instances\n autoscaling_group.auto_scaling_instances\n end", "def restart\n stop\n start\n end", "def restart\n stop\n start\n end", "def restart\n stop; start\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n else\n @task.debug { \"Scaling group #{@name} already suspended\" }\n end\n end", "def startup(group)\n cfmstartup = AWS::CloudFormation.new # call cloudformation\n ec2startup = AWS::EC2.new # call ec2\n # long running method\n puts \"XXXXXXXXXX DAILY CHECKING HERE STARUP XXXXXXXXXXXX\"\n puts group.name\n puts \"Start up Job is working now\"\n if group.users.length > 0\n allinstanceids = []\n group.users.each do |user|\n if user.stacks.length > 0\n user.stacks.each do |stack|\n if stack.ec2instance_ids.length > 0 \n allinstanceids.concat stack.ec2instance_ids # concatinate all instance ids with ec2 instance ids of stack\n end\n end\n end\n end\n p allinstanceids = allinstanceids.uniq\n if allinstanceids.length > 0\n $ec2_resource.instances({instance_ids: allinstanceids}).batch_start # start the jobs\n end\n end \n puts \"XXXXXXXXXXXXXXXXXXXXXX\"\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n #else\n #@task.debug { \"Scaling group #{@name} already suspended\" }\n #end\n end", "def startApplications()\n debug(\"Start all applications\")\n @applications.each_key { |name|\n startApplication(name)\n }\n end", "def restart\n stop\n start\n end", "def restart\n stop\n start\n end", "def restart\n stop\n start\n end", "def resume\n\t\t@state = STATE_ONLINE\n\tend", "def restart\n stop if is_running?\n start\n \n is_running?\n end", "def resume(id)\n _params = {:id => id}\n return @master.call 'subaccounts/resume', _params\n end", "def resume(fiber, *arguments); end", "def resume_assignment(class_assignment)\n start_assignment(class_assignment)\n ActiveRecord::Base.transaction do\n begin_sequence(@class_assignment.sequence)\n end\n end", "def replace_instances\n log_options\n\n unless stack_exists?(name)\n raise StackDoesNotExistError, \"Stack #{name} does not exist.\"\n end\n\n stack = cfn.stacks[name]\n unless stack_was_just_updated?(stack)\n logger.info \"stack was not updated recently, not replacing instances.\"\n return\n end\n\n ex = WaitTimedOutError.new \"Timed out waiting to replace instances.\"\n wait_until(ex) do\n ok_to_replace_instances?(stack.status, stack.last_updated_time)\n end\n\n logger.info \"replacing all auto-scaling instances in #{name}\"\n\n if stack_asg.nil?\n raise MissingAutoScalingGroupError, \"No ASG found for stack #{name}\"\n end\n\n stack_asg.ec2_instances.each do |i|\n if i.status == :running\n logger.info \"terminating instance #{i.id}\"\n i.terminate\n else\n logger.info \"Not terminating #{i.id} due to status: #{i.status}\"\n end\n end\n end", "def restart!\n JobRestarter.restart(self)\n end", "def resume(value = nil)\n @fiber.resume value\n nil\n rescue FiberError\n raise DeadTaskError, \"cannot resume a dead task\"\n rescue RuntimeError => ex\n # These occur spuriously on 1.9.3 if we shut down an actor with running tasks\n return if ex.message == \"\"\n raise\n end", "def resumed_background(job_fullname)\n \"Resuming the background job '#{job_fullname}'.\"\n end", "def resume\n data = JSON.generate(:resume => nil)\n response = @compute.connection.csreq(\"POST\",@svrmgmthost,\"#{@svrmgmtpath}/servers/#{URI.encode(self.id.to_s)}/action\",@svrmgmtport,@svrmgmtscheme,{'content-type' => 'application/json'},data)\n OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)\n true\n end", "def resume(topic, partition)\n pause_for(topic, partition).resume!\n\n # During re-balancing we might have lost the paused partition. Check if partition is still in group before seek.\n seek_to_next(topic, partition) if @group.assigned_to?(topic, partition)\n end", "def restart\n stop if is_running?\n start\n\n is_running?\n end", "def restart\n stop\n start\n end", "def resume!\n raise InvalidActionError, \"Cannot resume a Say that is not paused.\" unless paused?\n resume_action.tap do |action|\n result = write_action action\n resumed! if result\n end\n end", "def restart\n stop\n sleep(1)\n start\n end", "def restart\n stop\n sleep(1)\n start\n end", "def resume_status\n Cproton.pn_ssl_resume_status(@impl)\n end", "def resume_task\n background = params[:sync] != '1'\n\n if background\n SyncTaskWorker.perform_async('token' => session[:facebook].access_token, 'task' => @task.id)\n else\n task_class = \"Tasks::\" << \"#{@task.type}_task\".camelize\n klass = task_class.constantize.new(task: @task, send_mail: false)\n klass.run\n end\n \n flash[:notice] << 'This task is now resumed.'\n redirect_to tasks_path and return\n end", "def update_resume\n\n end" ]
[ "0.76529264", "0.7550506", "0.69527906", "0.6786772", "0.65701437", "0.6296431", "0.6282769", "0.6035294", "0.6005665", "0.5958181", "0.59269327", "0.59145147", "0.5896866", "0.58966523", "0.5895775", "0.56975245", "0.56890625", "0.5688524", "0.56334895", "0.5604643", "0.5592404", "0.557932", "0.5564963", "0.5511447", "0.5391936", "0.5357746", "0.5344158", "0.53398085", "0.5328145", "0.5309449", "0.52956074", "0.52956074", "0.5265385", "0.524519", "0.5232999", "0.5205938", "0.52028185", "0.51751935", "0.51516384", "0.5145228", "0.5131381", "0.5131381", "0.512782", "0.51020586", "0.51020586", "0.5048034", "0.50147414", "0.5009388", "0.5005209", "0.49980834", "0.49645048", "0.49645048", "0.4952032", "0.4938523", "0.49191013", "0.49191013", "0.48537466", "0.4839019", "0.4821228", "0.48040992", "0.4800763", "0.4799023", "0.47959876", "0.4790671", "0.4790392", "0.47873697", "0.47742414", "0.4755813", "0.4745946", "0.47349316", "0.47349316", "0.4731445", "0.4731445", "0.47243813", "0.47242886", "0.4704752", "0.4704385", "0.46788216", "0.466167", "0.466167", "0.466167", "0.46525916", "0.46412632", "0.46391258", "0.46163675", "0.4610224", "0.4595833", "0.45866844", "0.45851386", "0.45771492", "0.4565942", "0.45621908", "0.45594728", "0.4543065", "0.45410314", "0.45400104", "0.45400104", "0.45298237", "0.45188236", "0.45177" ]
0.75933415
1
Enables all metrics collection for the Auto Scaling group.
def enable_all_metrics_collection enable_metrics_collection end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def autoscaling_instances\n autoscaling_group.auto_scaling_instances\n end", "def autoscaling_instances\n autoscaling_group.auto_scaling_instances\n end", "def disable_all_metrics_collection\n disable_metrics_collection\n end", "def init_groups\n @@client.describe_auto_scaling_groups.auto_scaling_groups\n end", "def enabled_metrics\n @group.enabled_metrics\n end", "def auto_scaling_group(group_name)\n AutoScalingGroup.new(group_name)\n end", "def update_auto_scaling_group(auto_scaling_group_name, options = {})\n if availability_zones = options.delete('AvailabilityZones')\n options.merge!(AWS.indexed_param('AvailabilityZones.member.%d', [*availability_zones]))\n end\n request({\n 'Action' => 'UpdateAutoScalingGroup',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(options))\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n @task.debug { \"Scaling group #{@name} already running\" }\n else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n end\n end\n end", "def describe_auto_scaling_groups(options = {})\n if auto_scaling_group_names = options.delete('AutoScalingGroupNames')\n options.merge!(AWS.indexed_param('AutoScalingGroupNames.member.%d', [*auto_scaling_group_names]))\n end\n request({\n 'Action' => 'DescribeAutoScalingGroups',\n :parser => Fog::Parsers::AWS::AutoScaling::DescribeAutoScalingGroups.new\n }.merge!(options))\n end", "def update_averages_for_metrics!\n Metric.all.each do |metric|\n update_averages_for_metric!(metric)\n end\n end", "def start\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n \n suspended = load_from_s3(@task.bucket)\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n #@task.debug { \"Scaling group #{@name} already running\" }\n #else\n start_instances\n\n @task.unsafe(\"Resuming #{@name} processes\") do\n autoscaling_group.resume_all_processes\n autoscaling_group.suspend_processes suspended.keys\n end\n #end\n end", "def monitor\n loop do\n sleep opts[:period]\n group.engine.logger.info \"#{group.banner}Monitoring group elasticity rule...\"\n # this is blocking because we don't want the rule to be triggered\n # too many times.\n if scale_up?\n group.engine.logger.info \"#{group.banner}Scaling up!\"\n manage(scale(:up))\n elsif scale_down?\n group.engine.logger.info \"#{group.banner}Scaling down!\"\n manage(scale(:down))\n else\n group.engine.logger.info \"#{group.banner}...\"\n end\n end\n end", "def remove_auto_scaling_group_properties\n properties = []\n properties << :AvailabilityZones\n properties << :HealthCheckGracePeriod\n properties << :HealthCheckType\n add_patch Patches::RemoveProperty.new 'AWS::AutoScaling::AutoScalingGroup', properties\n end", "def enable_all_alerts\n self.service_subscriptions.each do |subscription|\n subscription.update_attribute :sms_enabled, true\n subscription.update_attribute :email_enabled, true\n end\n end", "def enable()\n fail \"#{self} already enabled\" if @enabled\n @klasses.each_pair do |k,methods|\n methods.each_pair do |method_sym, (orig,blk)|\n new_meth = instrument_method(k,method_sym,orig,blk)\n k.class_eval do\n define_method method_sym, &new_meth\n end\n end\n end\n @enabled = true\n end", "def enable\n {\n method: \"Performance.enable\"\n }\n end", "def setup_metrics\n end", "def setup_metrics\n end", "def setup_metrics\n end", "def enable\n\t\t# if already enabled, nothing to do\n\t\tif @enabled == true\n\t\t\treturn false\n\t\tend\n\n\t\t# for each aspect, install in the class\n\t\t@aspects.each do |_aspect, arr|\n\t\t\tarr.each do |_class|\n\t\t\t\t_aspect.install(_class)\n\t\t\tend\n\t\tend\n\t\t@enabled = true\n\n\t\treturn true\n\tend", "def getAsgs()\n options = Hash.new\n asgs = []\n next_token = 0\n while next_token != nil\n options[:next_token] = next_token unless next_token == 0\n resp = @asg.describe_auto_scaling_groups(options)\n asgs.concat(resp.data[:auto_scaling_groups])\n next_token = resp.data[:next_token]\n end\n asgs\n end", "def set_metrics\n if rails?\n @metrics = MetricFu::AVAILABLE_METRICS + [:stats, :rails_best_practices]\n else\n @metrics = MetricFu::AVAILABLE_METRICS\n end\n end", "def collect_metrics(*)\n raise NotImplementedError, 'Must implement collect_metrics'\n end", "def each(&block)\n # delegate to the @metrics hash until we need something fancier\n @metrics_lock.synchronize do\n @metrics.each(&block)\n end\n end", "def set_metrics(metrics, batch)\n _this_ts, label, latency, error, threads, http_code = metrics\n ['ALL', label].each do |key|\n # load test worker threads are recorded at the start of the interval\n batch[key]['threads'] = threads unless batch[key]['threads']\n batch[key]['requests'] += 1\n batch[key]['errors'] += error\n batch[key]['http_code_distribution'][http_code] += 1\n # latency samples are not counted for failed requests\n unless error == 1\n batch[key]['latency_distribution'][latency] += 1\n batch[key]['latency_sum'] += latency\n end\n end\n end", "def enable!\n @mutex.synchronize do\n @advised.each { | x | x.enable! }\n end\n self\n end", "def update_metrics!(*args)\n self.class.metrics.each do |metric, options|\n send(metric, *args)\n end\n end", "def setup\n SidekiqPrometheus::Metrics.register_sidekiq_job_metrics\n SidekiqPrometheus::Metrics.register_sidekiq_gc_metric if gc_metrics_enabled?\n SidekiqPrometheus::Metrics.register_sidekiq_worker_gc_metrics if gc_metrics_enabled? && periodic_metrics_enabled?\n SidekiqPrometheus::Metrics.register_sidekiq_global_metrics if global_metrics_enabled? && periodic_metrics_enabled?\n sidekiq_setup\n end", "def metrics\n manager_instance(MetricManager)\n end", "def cpu_metrics\n super\n end", "def auto_scaling_group_name\n data.auto_scaling_group_name\n end", "def register_metrics!\n return if @registered\n @registered = true\n with_instance do |t|\n # Worker related\n t.add_gauge :dynflow_active_workers, 'The number of currently busy workers',\n [:queue, :world]\n t.add_counter :dynflow_worker_events, 'The number of processed events',\n [:queue, :world, :worker]\n\n # Execution plan related\n t.add_gauge :dynflow_active_execution_plans, 'The number of active execution plans',\n [:action, :world, :state]\n t.add_gauge :dynflow_queue_size, 'Number of items in queue',\n [:queue, :world]\n t.add_counter :dynflow_finished_execution_plans, 'The number of execution plans',\n [:action, :world, :result]\n\n # Step related\n # TODO: Configure buckets in a sane manner\n t.add_histogram :dynflow_step_real_time, 'The time between the start end end of the step',\n [:action, :phase]\n t.add_histogram :dynflow_step_execution_time, 'The time spent executing a step',\n [:action, :phase]\n\n # Connector related\n t.add_counter :dynflow_connector_envelopes, 'The number of envelopes handled by a connector',\n [:world, :direction]\n\n # Persistence related\n t.add_histogram :dynflow_persistence, 'The time spent communicating with the database',\n [:world, :method]\n end\n end", "def metrics=(array=[])\n @metrics = array.map { |m| m.is_a?(Metric) ? m : Metric.by_key(m) }.compact\n end", "def record_customer_metrics\n return unless enabled?\n return unless NewRelic::Agent.config[METRICS_ENABLED_KEY]\n\n @counter_lock.synchronize do\n return unless @seen > 0\n\n NewRelic::Agent.increment_metric(LINES, @seen)\n @seen_by_severity.each do |(severity, count)|\n NewRelic::Agent.increment_metric(line_metric_name_by_severity(severity), count)\n end\n\n @seen = 0\n @seen_by_severity.clear\n end\n end", "def collect(metrics)\n metrics\n end", "def metrics\n @metrics ||= collect_metrics\n end", "def enable_group(group)\n @event_groups[group] = true\n end", "def enqueue_metrics_update\n User::MetricsJob.perform_async(self.id) if self.need_to_update_metrics?\n end", "def all\n @@all_metrics ||= self.from_file(\n File.join(Rails.root, 'config', 'metrics.yml')\n )\n end", "def update options = {}\n\n group_opts = group_options(options) \n\n # tags must be updated using a separate request from the\n # other attributes, *sigh*\n if tags = group_opts.delete(:tags)\n tags.map(&:to_hash).each do |tag|\n tag[:resource_type] = 'auto-scaling-group'\n tag[:resource_id] = name\n end\n client.create_or_update_tags(:tags => tags)\n end\n\n unless group_opts.empty?\n client_opts = group_opts.merge(:auto_scaling_group_name => name)\n client.update_auto_scaling_group(client_opts)\n end\n\n nil\n\n end", "def scale(max_size, desired_capacity)\n client.update_auto_scaling_group(auto_scaling_group_name: asg_name, max_size: max_size, desired_capacity: desired_capacity)\n end", "def set_groups_metrics_dashboard\n @groups_metrics_dashboard = GroupsMetricsDashboard.find(params[:id])\n end", "def enable!\n tracers.each(&:enable!)\n end", "def aws_security_group_enable_inbound(opts)\n opts[:security_group].authorize_ingress(:tcp, 20..8080)\n end", "def associate_records_to_groups\n put_isos_into_iso_group\n put_agents_into_iso_group\n put_merchants_into_iso_group\n end", "def perform_reload\n api.group_reload(self)\n end", "def pause_scaling_events\n client.suspend_processes(auto_scaling_group_name: asg_name,\n scaling_processes:\n %w[ReplaceUnhealthy AlarmNotification ScheduledActions AZRebalance])\n end", "def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end", "def start_instances\n started = 0\n autoscaling_instances.each do |instance|\n ec2_instance = instance.ec2_instance\n next if !ec2_instance.exists?\n\n if ec2_instance.status == :stopped\n @task.unsafe(\"Starting instance #{instance.instance_id}\") do\n ec2_instance.start\n load_balancers.each do |elb|\n elb.instances.register(instance.instance_id)\n end\n started += 1\n end\n else\n @task.debug { \"Instance #{instance.instance_id} already running\" }\n end\n end\n\n # FIXME\n # This is to give instances a little more time to start up and become\n # healthy before restarting autoscaling processes.\n # If an instance isn't started and healthy in time, the autoscale will kill\n # it for being unhealthy.\n #\n # The \"right\" way to do it would be to actually poll the instances until\n # they are healthy (or a timeout is reached). With the current task model,\n # other actions are blocked while this is waiting, so I can't afford to\n # wait too long.\n sleep(@grace_period) if started > 0\n end", "def get_all_metrics()\n return nil unless Config.metrics\n f = Fiber.current\n resp = metrics.find().defer_as_a\n resp.callback do |doc|\n f.resume doc\n end\n resp.errback do |err|\n raise *err\n end\n docs = Fiber.yield\n # convert ids to int\n docs.collect{|doc| doc['_id'] = doc['_id'].to_i ; doc }\n end", "def all(options = {})\n data = service.list_metric_descriptors(options).body['metrics'] || []\n load(data)\n end", "def persist_metrics\n self.metrics.each(&:save)\n end", "def perform_scaling_for_appservers()\n APPS_LOCK.synchronize {\n @apps_loaded.each { |app_name|\n\n next if app_name == \"none\" \n initialize_scaling_info_for_app(app_name)\n\n # Always get scaling info, as that will send this info to the\n # AppDashboard for users to view.\n case get_scaling_info_for_app(app_name)\n when :scale_up\n Djinn.log_debug(\"Considering scaling up app #{app_name}.\")\n try_to_scale_up(app_name)\n when :scale_down\n Djinn.log_debug(\"Considering scaling down app #{app_name}.\")\n try_to_scale_down(app_name)\n else\n Djinn.log_debug(\"Not scaling app #{app_name} up or down right now.\")\n end\n }\n }\n end", "def scaling_policies\n @aws.describe_policies(\n auto_scaling_group_name: @group_name\n ).scaling_policies\n end", "def activate\n @libraries.each {|library| require(library) }\n self.activated = true\n rescue LoadError => e\n mf_log \"#{name} metric not activated, #{e.message}\"\n end", "def start\n perform do\n metrics = load_redis_metrics\n log_info metrics.to_s if metrics.names.any?\n\n submit_librato metrics\n end\n end", "def autoscale(instance_id)\n metadata = @ec2.describe_instances(instance_ids: [\"#{instance_id}\"])\n tags = metadata.reservations.first.instances.first\n # covert to hash to make this easier\n tags = tags.to_h\n tags = tags[:tags]\n # quick check to avoid having to iterate through all the tags to see if the one we need is there.\n temp_tags = tags.to_s\n if temp_tags.include?(\"aws:autoscaling:groupName\")\n tags.each do |curtag|\n if curtag[:key] == \"aws:autoscaling:groupName\"\n @autoscaling = curtag[:value]\n end\n end\n else\n @autoscaling = \"false\"\n end\n end", "def enable_aggregation! &block\n cpc = 'org.apache.hadoop.hbase.coprocessor.AggregateImplementation'\n add_coprocessor! cpc, &block unless has_coprocessor?(cpc)\n end", "def scale_appservers_within_nodes\n if @creds[\"autoscale\"].downcase == \"true\"\n perform_scaling_for_appservers()\n end\n end", "def ensure_all\n sync do\n devices.each { |dev| ct.group.devices.provide(dev) }\n end\n end", "def reset_metrics\n flush_cache\n self\n end", "def enable(*opts)\n opts.each { |key| set(key, true) }\n end", "def sidekiq_setup\n Sidekiq.configure_server do |config|\n config.server_middleware do |chain|\n chain.add SidekiqPrometheus::JobMetrics\n end\n\n if periodic_metrics_enabled?\n config.on(:startup) { SidekiqPrometheus::PeriodicMetrics.reporter.start }\n config.on(:shutdown) { SidekiqPrometheus::PeriodicMetrics.reporter.stop }\n end\n\n config.on(:startup) { SidekiqPrometheus.metrics_server }\n config.on(:shutdown) { SidekiqPrometheus.metrics_server.kill }\n end\n end", "def enable(*opts)\n opts.each { |key| set(key, true) }\n end", "def enable\n debug \"Call 'enable' for Pacemaker service '#{name}' on node '#{hostname}'\"\n manage_primitive name\n end", "def enable *opts\n opts.each { |key| set(key, true) }\n end", "def aggregations(boolean)\n @aggregations = boolean\n @loaded = false\n self\n end", "def gc_metrics_enabled?\n gc_metrics_enabled\n end", "def enable!\n \n @enabled = true\n \n @gems_or_gemsets.each do |this_gem_or_gemset, true_value|\n this_gem_or_gemset.enable!\n end\n \n return self\n \n end", "def enable!\n self.enabled = true\n end", "def arn\n cloud_desc.auto_scaling_group_arn\n end", "def setup\n @groups =\n Etsource::Fever.groups.map do |conf|\n Group.new(conf.name, self)\n end\n end", "def configure!\n raise(AlreadyConfiguredError, @configured_by) if already_configured?\n\n debug! if config.debug?\n\n configurators.each do |(group, block)|\n group group\n class_eval(&block)\n group nil\n end\n\n # Register metrics in adapters after evaluating all configuration blocks\n # to ensure that all global settings (like default tags) will be applied.\n adapters.each_value do |adapter|\n metrics.each_value do |metric|\n adapter.register!(metric)\n end\n end\n\n @configured_by = caller_locations(1, 1)[0].to_s\n end", "def autoscaling_group_exists?\n Tapjoy::AutoscalingBootstrap::AWS::Autoscaling::Group.describe.nil? ? false : true\n end", "def setScaleInProtection(need_instances = @config['min_size'])\n live_instances = []\n begin\n desc = MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).describe_auto_scaling_groups(auto_scaling_group_names: [@mu_name]).auto_scaling_groups.first\n\n live_instances = desc.instances.map { |i| i.instance_id }\n already_set = 0\n desc.instances.each { |i|\n already_set += 1 if i.protected_from_scale_in\n }\n if live_instances.size < need_instances\n sleep 5\n elsif already_set > need_instances\n unset_me = live_instances.sample(already_set - need_instances)\n MU.log \"Disabling scale-in protection for #{unset_me.size.to_s} instances in #{@mu_name}\", MU::NOTICE, details: unset_me\n MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).set_instance_protection(\n auto_scaling_group_name: @mu_name,\n instance_ids: unset_me,\n protected_from_scale_in: false\n )\n elsif already_set < need_instances\n live_instances = live_instances.sample(need_instances)\n MU.log \"Enabling scale-in protection for #{@config['scale_in_protection']} instances in #{@mu_name}\", details: live_instances\n begin\n MU::Cloud::AWS.autoscale(region: @region, credentials: @credentials).set_instance_protection(\n auto_scaling_group_name: @mu_name,\n instance_ids: live_instances,\n protected_from_scale_in: true\n )\n rescue Aws::AutoScaling::Errors::ValidationError => e\n if e.message.match(/not in InService/i)\n sleep 5\n retry\n else\n raise e\n end\n end\n end\n end while live_instances.size < need_instances\n end", "def collect_solr_core_jmx_metrics(metric_type_to_solr_core_mbean_attr_map)\n collections, collection_to_core_name_map = execute_solr_jmx_list_request()\n if @metric_level == \"CollectionLevel\"\n # If the metric level is equal to 'CollectionLevel' then aggregating the metrics of all cores for each collection on a node.\n collections.each do |collection_name|\n updated_metric_type_to_solr_core_mbean_attr_map = construct_jmx_metrics_with_core_name_as_id(metric_type_to_solr_core_mbean_attr_map, collection_name, collection_to_core_name_map)\n solr_core_mbean_bulk_request, metric_type_to_mbean_type_obj = create_solr_core_mbean_bulkrequest_and_mbeantype_list(updated_metric_type_to_solr_core_mbean_attr_map, collection_name)\n execute_solr_core_jmx_read_request(solr_core_mbean_bulk_request, metric_type_to_mbean_type_obj, collection_name)\n end\n else\n # If the metric level is not equal to 'CollectionLevel' then the other option 'ClusterLevel' was choosen.\n # Hence, aggregating the metrics at cluster level. i.e, For all cores on a node.\n solr_core_mbean_bulk_request, metric_type_to_mbean_type_obj = create_solr_core_mbean_bulkrequest_and_mbeantype_list(metric_type_to_solr_core_mbean_attr_map, nil)\n execute_solr_core_jmx_read_request(solr_core_mbean_bulk_request, metric_type_to_mbean_type_obj, nil)\n end\n end", "def setup_metrics\n require 'fog'\n @options = NewRelic::Plugin::Config.config.newrelic\n log.debug 'Establishing connection to New Relic'\n end", "def initialize(...)\n @metrics = {}\n register(...)\n end", "def destroy\n info(\"Disabling Metricbeat module\")\n metricbeat(['modules','disable',@resource[:name]])\n end", "def index\n @admin_sub_metrics = Admin::SubMetric.all\n end", "def metrics\n @metrics ||= []\n end", "def new_auto_scaling \n AWS::AutoScaling.new(:auto_scaling_endpoint => \"autoscaling.#{AMI_REGION}.amazonaws.com\")\nend", "def enable\n @enabled = true\n end", "def index\n @metrics = Metric.all\n end", "def enable_group(*groups, except: nil)\n set_service_groups_status(true, *groups, except: except)\n end", "def autoscale_params\n params.require(:auto_scale).permit(:grow_cpu_thresh, :shrink_cpu_thresh, :grow_ratio_thresh, :shrink_ratio_thresh, :enabled, :max_instances, :cooldown_period_in_seconds)\n end", "def metric_devices=(value)\n @metric_devices = value\n end", "def all_example_groups\n strategy.example_groups\n end", "def start_monitoring\n @scheduler.start()\n end", "def patch!\n # rubocop:disable Metrics/BlockLength\n ::SuckerPunch::Job::ClassMethods.class_eval do\n alias_method :__run_perform_without_datadog, :__run_perform\n def __run_perform(*args)\n Datadog::Tracing.send(:tracer).provider.context = Datadog::Tracing::Context.new\n\n __with_instrumentation(Ext::SPAN_PERFORM) do |span|\n span.resource = \"PROCESS #{self}\"\n\n span.set_tag(Tracing::Metadata::Ext::TAG_OPERATION, Ext::TAG_OPERATION_PERFORM)\n\n # Set analytics sample rate\n if Datadog::Tracing::Contrib::Analytics.enabled?(datadog_configuration[:analytics_enabled])\n Datadog::Tracing::Contrib::Analytics.set_sample_rate(\n span,\n datadog_configuration[:analytics_sample_rate]\n )\n end\n\n # Measure service stats\n Datadog::Tracing::Contrib::Analytics.set_measured(span)\n\n __run_perform_without_datadog(*args)\n end\n rescue => e\n ::SuckerPunch.__exception_handler.call(e, self, args)\n end\n ruby2_keywords :__run_perform if respond_to?(:ruby2_keywords, true)\n\n alias_method :__perform_async, :perform_async\n def perform_async(*args)\n __with_instrumentation(Ext::SPAN_PERFORM_ASYNC) do |span|\n span.resource = \"ENQUEUE #{self}\"\n\n span.set_tag(Datadog::Tracing::Metadata::Ext::TAG_OPERATION, Ext::TAG_OPERATION_PERFORM_ASYNC)\n\n # Measure service stats\n Datadog::Tracing::Contrib::Analytics.set_measured(span)\n\n __perform_async(*args)\n end\n end\n ruby2_keywords :perform_async if respond_to?(:ruby2_keywords, true)\n\n alias_method :__perform_in, :perform_in\n def perform_in(interval, *args)\n __with_instrumentation(Ext::SPAN_PERFORM_IN) do |span|\n span.resource = \"ENQUEUE #{self}\"\n\n span.set_tag(Datadog::Tracing::Metadata::Ext::TAG_OPERATION, Ext::TAG_OPERATION_PERFORM_IN)\n\n span.set_tag(Ext::TAG_PERFORM_IN, interval)\n\n # Measure service stats\n Datadog::Tracing::Contrib::Analytics.set_measured(span)\n\n __perform_in(interval, *args)\n end\n end\n ruby2_keywords :perform_in if respond_to?(:ruby2_keywords, true)\n\n private\n\n def datadog_configuration\n Datadog.configuration.tracing[:sucker_punch]\n end\n\n def __with_instrumentation(name)\n Datadog::Tracing.trace(name, service: datadog_configuration[:service_name]) do |span|\n span.span_type = Datadog::Tracing::Metadata::Ext::AppTypes::TYPE_WORKER\n span.set_tag(Datadog::Tracing::Metadata::Ext::TAG_COMPONENT, Ext::TAG_COMPONENT)\n span.set_tag(Ext::TAG_QUEUE, to_s)\n yield span\n end\n end\n end\n # rubocop:enable Metrics/BlockLength\n end", "def start\n run_all if options[:all_on_start]\n end", "def start_exporter(collect_interval: COLLECT_INTERVAL)\n Thread.new do\n Logging.instance.debug(\"initilize collectors harvest\")\n loop do\n Logging.instance.debug(\"start collectors harvest\")\n Yabeda.collectors.each(&:call)\n Logging.instance.debug(\"end collectors harvest\")\n sleep(collect_interval)\n end\n end\n end", "def index_email_distribution_groups\n engines_api_system.index_email_distribution_groups\n end", "def scale_cloud!\n add_instance_if_load_is_high\n terminate_instance_if_load_is_low\n end", "def metrics_enabled?\n if !block_given?\n return @j_del.java_method(:isMetricsEnabled, []).call()\n end\n raise ArgumentError, \"Invalid arguments when calling metrics_enabled?()\"\n end", "def metrics_enabled?\n if !block_given?\n return @j_del.java_method(:isMetricsEnabled, []).call()\n end\n raise ArgumentError, \"Invalid arguments when calling metrics_enabled?()\"\n end", "def metrics_enabled?\n if !block_given?\n return @j_del.java_method(:isMetricsEnabled, []).call()\n end\n raise ArgumentError, \"Invalid arguments when calling metrics_enabled?()\"\n end", "def ListView_SetGroupMetrics(hwnd, pGroupMetrics)\n send_listview_message(hwnd, :SETGROUPMETRICS, lparam: pGroupMetrics)\n end", "def start\n run_all if @options[:all_on_start]\n end", "def metrics(*args)\n @metrics = args.map { |id| @playground.metric(id) } unless args.empty?\n @metrics\n end" ]
[ "0.63155496", "0.63155496", "0.63154894", "0.6124643", "0.58603215", "0.58343536", "0.58028674", "0.54997826", "0.53667444", "0.5340069", "0.5304826", "0.529975", "0.5293918", "0.52245384", "0.5170505", "0.51577646", "0.5143741", "0.5143741", "0.5143741", "0.513776", "0.50459623", "0.5018695", "0.49829185", "0.4966753", "0.49267522", "0.4926059", "0.4890973", "0.488706", "0.48796022", "0.48760444", "0.4861915", "0.4860195", "0.4847792", "0.4825242", "0.48025703", "0.48013207", "0.48008728", "0.47859868", "0.47329846", "0.47157127", "0.4705266", "0.47048184", "0.46954042", "0.46852696", "0.46851537", "0.46775416", "0.46720448", "0.46602237", "0.46602237", "0.4648552", "0.46447235", "0.4643967", "0.4636466", "0.46219873", "0.461923", "0.4601624", "0.45957693", "0.4588359", "0.45883262", "0.45475757", "0.45472774", "0.4543852", "0.45419535", "0.4540537", "0.453871", "0.45259526", "0.4521738", "0.45161963", "0.44921592", "0.4484844", "0.44788948", "0.44735944", "0.44670945", "0.44525263", "0.4436401", "0.44277638", "0.44176346", "0.44155663", "0.44097054", "0.4403371", "0.43973875", "0.43687373", "0.43673992", "0.4322341", "0.43070936", "0.43020117", "0.42999047", "0.42987445", "0.429047", "0.42607537", "0.42592418", "0.42353848", "0.42340392", "0.4232881", "0.4229215", "0.4229215", "0.4229215", "0.4228254", "0.42273057", "0.42196184" ]
0.8177668
0
Disables all metrics collection for the Auto Scaling group.
def disable_all_metrics_collection disable_metrics_collection end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def enable_all_metrics_collection\n enable_metrics_collection\n end", "def destroy\n info(\"Disabling Metricbeat module\")\n metricbeat(['modules','disable',@resource[:name]])\n end", "def remove_auto_scaling_group_properties\n properties = []\n properties << :AvailabilityZones\n properties << :HealthCheckGracePeriod\n properties << :HealthCheckType\n add_patch Patches::RemoveProperty.new 'AWS::AutoScaling::AutoScalingGroup', properties\n end", "def disable!\n @mutex.synchronize do\n @advised.each { | x | x.disable! }\n end\n self\n end", "def disable\n {\n method: \"Performance.disable\"\n }\n end", "def reset_metrics\n flush_cache\n self\n end", "def uncan_all()\n self.brk_excluded = :all\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def disable_rate_limits!\n @rate_limits_disabled = true\n end", "def autoscaling_instances\n autoscaling_group.auto_scaling_instances\n end", "def autoscaling_instances\n autoscaling_group.auto_scaling_instances\n end", "def reset!\n default_tags.clear\n adapters.clear\n groups.each_key { |group| singleton_class.send(:remove_method, group) if group && respond_to?(group) }\n @groups = nil\n metrics.each_key { |metric| singleton_class.send(:remove_method, metric) if respond_to?(metric) }\n @metrics = nil\n collectors.clear\n configurators.clear\n instance_variable_set(:@configured_by, nil)\n instance_variable_set(:@debug_was_enabled_by, nil)\n end", "def disable_all_alerts\n self.service_subscriptions.each do |subscription|\n subscription.update_attribute :sms_enabled, false\n subscription.update_attribute :email_enabled, false\n end\n end", "def delete_all_metrics\n connection = Librato::Metrics.client.connection\n Librato::Metrics.list.each do |metric|\n #puts \"deleting #{metric['name']}...\"\n # expects 204\n connection.delete(\"metrics/#{metric['name']}\")\n end\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n save_to_s3(@task.bucket)\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def disable_alerting\n start = Time.now\n debug \"Checking disable_alerting setting for device group: \\\"#{resource[:full_path]}\\\"\"\n connection = self.class.get_connection(resource[:account])\n device_group = get_device_group(connection, resource[:full_path],'disableAlerting')\n debug \"Finished in #{(Time.now-start)*1000.0} ms\"\n device_group['disableAlerting'].to_s\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n #else\n #@task.debug { \"Scaling group #{@name} already suspended\" }\n #end\n end", "def clear_device_metrics_override\n {\n method: \"Emulation.clearDeviceMetricsOverride\"\n }\n end", "def reset_metrics_buffer\n @@metrics_buffer = []\n end", "def aws_security_group_disable_outbound(opts)\n opts[:security_group].revoke_egress('0.0.0.0/0')\n end", "def pause_scaling_events\n client.suspend_processes(auto_scaling_group_name: asg_name,\n scaling_processes:\n %w[ReplaceUnhealthy AlarmNotification ScheduledActions AZRebalance])\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n else\n @task.debug { \"Scaling group #{@name} already suspended\" }\n end\n end", "def redis_rate_limiting_cleanup!\n Gitlab::Redis::RateLimiting.with(&:flushdb)\n end", "def clear\n @adapter.clear.map { |impression| impression.update(ip: @config.machine_ip) }\n end", "def disable\n\t\t# if already disabled, nothing to do\n\t\tif @enabled == false\n\t\t\treturn false\n\t\tend\n\n\t\t# for each aspect, uninstall in the class\n\t\t@aspects.each do |_aspect, arr|\n\t\t\tarr.each do |_class|\n\t\t\t\t_aspect.uninstall(_class)\n\t\t\tend\n\t\tend\n\t\t@enabled = false\n\n\t\treturn true\n\tend", "def enabled_metrics\n @group.enabled_metrics\n end", "def disable()\n fail \"#{self} already disabled\" unless @enabled\n @klasses.each_pair do |k,methods|\n methods.each_pair do |method_sym, (old,blk)|\n bound = old.bind(k)\n k.class_eval {define_method method_sym, &bound.to_proc}\n end\n end\n @enabled = false\n end", "def disable\n debug \"Call 'disable' for Pacemaker service '#{name}' on node '#{hostname}'\"\n unmanage_primitive name\n end", "def disable_aggregation\n cpc = 'org.apache.hadoop.hbase.coprocessor.AggregateImplementation'\n remove_coprocessor cpc if has_coprocessor?(cpc)\n end", "def disable!\n tracers.each(&:disable!)\n end", "def disable!\n self.enabled = false\n end", "def reset_abilities\n @capabilities.each do |cap|\n cant_do cap\n end\n end", "def clear_device_metrics_override\n {\n method: \"Page.clearDeviceMetricsOverride\"\n }\n end", "def disable\n @enabled = false\n end", "def remove_all\n @jobs.each do |job|\n job.unschedule\n end\n @@instances.delete self\n end", "def init_groups\n @@client.describe_auto_scaling_groups.auto_scaling_groups\n end", "def disable!\n\n @enabled = false\n \n @gems_or_gemsets.each do |this_gem_or_gemset, true_value|\n this_gem_or_gemset.disable!\n end\n \n return self\n \n end", "def reset_policy_groups!\n @labels = nil\n end", "def remove_all_dismantle_masks\n groups = [$data_items, $data_armors, $data_weapons]\n for group in groups\n for obj in group\n next if obj.nil?\n obj.set_dismantle_mask_flags(true)\n end # for\n end # for\n end", "def disable!\n @enabled = false\n end", "def disable!\n @enabled = false\n end", "def undefine_batch_throttle(method_name)\n rocket_job_batch_throttles.delete_if { |throttle| throttle.method_name == method_name }\n end", "def clear_all!\n ::Instana.processor.clear!\n ::Instana.tracer.clear!\n $redis.flushall if $redis\n nil\nend", "def disable_aggregation! &block\n cpc = 'org.apache.hadoop.hbase.coprocessor.AggregateImplementation'\n remove_coprocessor! cpc, &block if has_coprocessor?(cpc)\n end", "def disable\n self.cards.update_all(:enabled => false)\n self.update_attribute(:enabled, false)\n self\n end", "def stop\n puts \"Stoping any instance with group ID: #{@os_aws.group_uuid}\"\n\n stop_instances_by_group_id(@os_aws.group_uuid)\n end", "def unregister_all\n registry.clear.default = nil\n end", "def disable\n redis.set(flag_key, 0)\n end", "def invalidate!\n free_resources\n @display_list.rebuild!\n end", "def suspend_all_processes\n groups.each do |group|\n group.suspend_processes\n end\n end", "def auto_scaling_group(group_name)\n AutoScalingGroup.new(group_name)\n end", "def disable_group(group)\n @event_groups[group] = false\n end", "def suspend_processes(auto_scaling_group_name, options = {})\n if scaling_processes = options.delete('ScalingProcesses')\n options.merge!(AWS.indexed_param('ScalingProcesses.member.%d', [*scaling_processes]))\n end\n request({\n 'Action' => 'SuspendProcesses',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(options))\n end", "def clear\n Thread.current[AGGREGATES_KEY] = nil\n end", "def clear\n Thread.current[AGGREGATES_KEY] = nil\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def disable\n disable_features :all\n end", "def reset_all_statistics\n super\n end", "def stop(*args, close_metrics: true)\n self.enabled = false\n result = super(*args)\n @metrics.close if close_metrics\n result\n end", "def remove_all_spies\n @registry.remove_all.each(&:stop)\n end", "def stop_all!\n @devices.each(&:stop!)\n end", "def delete_launch_configs\n auto_scaling = new_auto_scaling\n groups = auto_scaling.groups\n auto_scaling.launch_configurations.each do |config|\n if groups[config.name].nil?\n puts \"deleting asg launch configuration, #{config.name}\"\n config.delete()\n end\n end\nend", "def purge_instances!\n @@instances = [] and true\n end", "def disable!\n @cache_enabled = false\n end", "def disable!\n @cache_enabled = false\n end", "def reset\n [topics, queues, subscriptions].each do |resource|\n resource.values.each(&:delete)\n resource.clear\n end\n end", "def disable *opts\n opts.each { |key| set(key, false) }\n end", "def clear!\n BULK_APIS.keys\n .each { |key| redis.del(redis_key(key)) }\n end", "def disable\n end", "def delete_all\n super\n Rails.cache.delete_matched(/#{self.configure.cache.namespace}/)\n end", "def disable(*opts)\n opts.each { |key| set(key, false) }\n end", "def disable_all\n # rules_to_disable = @rules.select {|key, value| value!=:hidden} \n # rules_to_disable.each_key { |key| @rules[key] = :disabled }\n @default_state = :disabled\n end", "def expire_all\n do_with_logging(:expire_all, nil) do\n retryable do\n self.adapter.expire_all\n nil\n end\n end\n end", "def disown_all!\n self.groups.each do |group|\n self.disown!(group)\n end\n end", "def delete options = {}\n client_opts = {}\n client_opts[:force_delete] = options[:force] == true\n client_opts[:auto_scaling_group_name] = name\n client.delete_auto_scaling_group(client_opts)\n nil\n end", "def disable(*opts)\n opts.each { |key| set(key, false) }\n end", "def terminate_instance_in_auto_scaling_group(instance_id, should_decrement_desired_capacity)\n request({\n 'Action' => 'TerminateInstanceInAutoScalingGroup',\n 'InstanceId' => instance_id,\n 'ShouldDecrementDesiredCapacity' => should_decrement_desired_capacity.to_s,\n :parser => Fog::Parsers::AWS::AutoScaling::TerminateInstanceInAutoScalingGroup.new\n })\n end", "def clear_heartbeats\n Record.with(collection: \"#{self.class.name.demodulize.downcase}_heartbeat\") do |m|\n m.where(proprietor: { \"#{self.class.name.demodulize.downcase}_id\".to_sym => id }).delete\n end\n end", "def stop_throttling\n @timer.cancel\n @timer = nil\n end", "def remove_from_all_groups\n self.group_memberships.each {|m| m.destroy}\n end", "def disable\n\n @enabled = false\n\n return self\n\n end", "def delete_all_cluster_ips\n super\n end", "def killall\n scheduler_enabled = scheduler.enabled?\n\n plan.permanent_tasks.clear\n plan.permanent_events.clear\n plan.missions.clear\n plan.transactions.each do |trsc|\n trsc.discard_transaction!\n end\n\n scheduler.enabled = false\n quit\n join\n\n if @application_exceptions\n process_pending_application_exceptions\n end\n\n start_new_cycle\n process_events\n cycle_end(Hash.new)\n\n ensure\n scheduler.enabled = scheduler_enabled\n end", "def disable\n redis.hset(FeatureGuard.flags_hkey, feature_name, 0)\n end", "def disable_keys\n connection.execute(\"ALTER TABLE #{quoted_table_name} DISABLE KEYS\")\n end", "def queue_clear_grouped_controller\n if Volt.in_browser?\n # In the browser, we want to keep a grouped controller around during a single run\n # of the event loop. To make that happen, we clear it on the next tick.\n `setImmediate(function() {`\n clear_grouped_controller\n `});`\n else\n # For the backend, clear it immediately\n clear_grouped_controller\n end\n end", "def update_auto_scaling_group(auto_scaling_group_name, options = {})\n if availability_zones = options.delete('AvailabilityZones')\n options.merge!(AWS.indexed_param('AvailabilityZones.member.%d', [*availability_zones]))\n end\n request({\n 'Action' => 'UpdateAutoScalingGroup',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(options))\n end", "def clear\n if warning?\n warn(\"This operation can run for a very long time if the namespace contains lots of keys! \" +\n \"It should be used in tests, or when the namespace is small enough \" +\n \"and you are sure you know what you are doing.\")\n end\n\n batch_size = 1000\n\n if supports_scan?\n cursor = \"0\"\n begin\n cursor, keys = scan(cursor, count: batch_size)\n del(*keys) unless keys.empty?\n end until cursor == \"0\"\n else\n all_keys = keys(\"*\")\n all_keys.each_slice(batch_size) do |keys|\n del(*keys)\n end\n end\n end", "def disable_keys\n connection.execute(\"ALTER TABLE #{quoted_table_name} DISABLE KEYS\")\n end", "def disable\n @queue << \"disable\"\n end", "def stop\n @enabled = false\n end", "def stop_all\n @targets.each do |target_ip, _|\n deactivate target_ip\n end\n end", "def delete_asg name\n auto_scaling = new_auto_scaling\n groups = auto_scaling.groups\n raise \"unable to delete asg, #{name}. asg not found!\" if groups[name].nil? \n\n asg = groups[name]\n\n puts \"deleting asg, #{asg.name}\"\n asg.delete({:force => true})\n delete_launch_configs\nend", "def disable\n self.stop if self.status == :running\n output = supervisorctl(:remove, @resource[:name])\n rescue Puppet::ExecutionFailure\n raise Puppet::Error, \"Could not disable #{self.name}: #{output}\"\n end", "def stop_all\n checklist = registry.checked_workers( policy )\n checklist.live.each { |key| reap(key) }\n checklist.late.each { |key| reap(key) }\n checklist.hung.each { |key| reap(key) }\n checklist.dead.each { |key| reap(key) }\n end", "def without_auditing\n auditing_was_enabled = class_auditing_enabled\n disable_auditing\n yield\n ensure\n enable_auditing if auditing_was_enabled\n end", "def recording_off()\n update({:recording_enabled => false})\n reload()\n end", "def delete_all_responders\n super\n end", "def remove(name)\n metric = @metrics.delete(name)\n metric != nil\n end" ]
[ "0.695738", "0.63754964", "0.61624557", "0.5633099", "0.5563048", "0.55241174", "0.5523639", "0.5467503", "0.5460256", "0.544506", "0.544506", "0.5440977", "0.54260665", "0.54249275", "0.5412217", "0.53986275", "0.5384166", "0.53650624", "0.5345516", "0.53441924", "0.5320656", "0.530765", "0.52920175", "0.529041", "0.5280768", "0.52725375", "0.524947", "0.5245609", "0.5196476", "0.5195513", "0.51942945", "0.5184592", "0.51818", "0.51494503", "0.51404047", "0.5127133", "0.51073784", "0.5104084", "0.51012206", "0.5060963", "0.50566953", "0.5050983", "0.5040644", "0.5036912", "0.50273764", "0.5026283", "0.50191283", "0.501298", "0.49962124", "0.49950954", "0.4992573", "0.49837437", "0.49780455", "0.49702117", "0.49702117", "0.49513766", "0.49513766", "0.4943627", "0.49384975", "0.4935073", "0.4929832", "0.49037704", "0.48944107", "0.48907763", "0.4875414", "0.4875414", "0.48715252", "0.48631725", "0.48524588", "0.48498443", "0.4844982", "0.4838304", "0.48381242", "0.4830182", "0.48231325", "0.4820821", "0.4819796", "0.4817584", "0.48168743", "0.4813525", "0.48103487", "0.47845942", "0.47815466", "0.47813717", "0.47776288", "0.47761506", "0.47724232", "0.4767732", "0.47671148", "0.47659963", "0.4762311", "0.47603062", "0.4757631", "0.47554013", "0.47370142", "0.4734597", "0.47323295", "0.4730179", "0.47251162", "0.47180918" ]
0.80768263
0
Update one or more attributes on the Auto Scaling group.
def update options = {} group_opts = group_options(options) # tags must be updated using a separate request from the # other attributes, *sigh* if tags = group_opts.delete(:tags) tags.map(&:to_hash).each do |tag| tag[:resource_type] = 'auto-scaling-group' tag[:resource_id] = name end client.create_or_update_tags(:tags => tags) end unless group_opts.empty? client_opts = group_opts.merge(:auto_scaling_group_name => name) client.update_auto_scaling_group(client_opts) end nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_auto_scaling_group(auto_scaling_group_name, options = {})\n if availability_zones = options.delete('AvailabilityZones')\n options.merge!(AWS.indexed_param('AvailabilityZones.member.%d', [*availability_zones]))\n end\n request({\n 'Action' => 'UpdateAutoScalingGroup',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(options))\n end", "def update_group(group, attributes)\n group.update(attributes)\n end", "def update!(document, attributes)\n method = klass.ancestors.include?(ActAsGroup::Resource) && klass.group_update_method ||\n ActAsGroup.configuration.update_resource.to_sym\n\n document.send(method, attributes)\n end", "def update!(**args)\n @autoscaling_metric_specs = args[:autoscaling_metric_specs] if args.key?(:autoscaling_metric_specs)\n @machine_spec = args[:machine_spec] if args.key?(:machine_spec)\n @max_replica_count = args[:max_replica_count] if args.key?(:max_replica_count)\n @min_replica_count = args[:min_replica_count] if args.key?(:min_replica_count)\n end", "def update_group(group_or_id, attributes)\n instantize_group(group_or_id).update(attributes)\n end", "def update!(**args)\n @attribute_checker_group_type = args[:attribute_checker_group_type] if args.key?(:attribute_checker_group_type)\n @group_name = args[:group_name] if args.key?(:group_name)\n @group_read_time_usec = args[:group_read_time_usec] if args.key?(:group_read_time_usec)\n @inline_threading_enabled = args[:inline_threading_enabled] if args.key?(:inline_threading_enabled)\n end", "def update\n @attribute_group = AttributeGroup.find(params[:id])\n\n respond_to do |format|\n if @attribute_group.update_attributes(params[:attribute_group])\n format.html { redirect_to(@attribute_group, :notice => 'Attribute group was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @attribute_group.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @ad_group = args[:ad_group] if args.key?(:ad_group)\n @label = args[:label] if args.key?(:label)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n end", "def update!(**args)\n @max_group_count = args[:max_group_count] if args.key?(:max_group_count)\n @start_group = args[:start_group] if args.key?(:start_group)\n @metrics = args[:metrics] if args.key?(:metrics)\n @dimensions = args[:dimensions] if args.key?(:dimensions)\n @dimension_filter_clauses = args[:dimension_filter_clauses] if args.key?(:dimension_filter_clauses)\n end", "def update!(**args)\n @ad_group_ad = args[:ad_group_ad] if args.key?(:ad_group_ad)\n @label = args[:label] if args.key?(:label)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n end", "def update\n\t\t@auto_scaling_trigger = AutoScalingTrigger.find(params[:id], :include => [ :auto_scaling_group ])\n\t\t@auto_scaling_group = @auto_scaling_trigger.auto_scaling_group\n\t\tast_params = params[:auto_scaling_trigger]\n\t\t\n\t\tunless ast_params.nil?\n\t\t\tast_params.each do |k,v|\n\t\t\t\tast_params[k] = v.chomp\n\t\t\tend\n\t\tend\n\t\t\n\t\trespond_to do |format|\n\t\t\tif @auto_scaling_trigger.update_attributes(ast_params)\n\t\t\t\tp = @auto_scaling_group\n\t\t\t\to = @auto_scaling_trigger\n\t\t\t\tAuditLog.create_for_parent(\n\t\t\t\t\t:parent => p,\n\t\t\t\t\t:auditable_id => o.id,\n\t\t\t\t\t:auditable_type => o.class.to_s,\n\t\t\t\t\t:auditable_name => o.name,\n\t\t\t\t\t:author_login => current_user.login,\n\t\t\t\t\t:author_id => current_user.id,\n\t\t\t\t\t:summary => \"updated '#{o.name}'\",\n\t\t\t\t\t:changes => o.tracked_changes,\n\t\t\t\t\t:force => false\n\t\t\t\t)\n\t\t\telse\n\t\t\t\t@error_messages = @auto_scaling_trigger.errors.collect{ |attr,msg| \"#{attr.humanize} - #{msg}\" }\n\t\t\t\tflash[:error] = @error_messages.join('<br/>')\n\t\t\tend\n\t\t\tformat.json { render :json => @auto_scaling_trigger }\n\t\tend\n\tend", "def update!(**args)\n @attribute_id = args[:attribute_id] if args.key?(:attribute_id)\n @display_name = args[:display_name] if args.key?(:display_name)\n @group_display_name = args[:group_display_name] if args.key?(:group_display_name)\n @is_deprecated = args[:is_deprecated] if args.key?(:is_deprecated)\n @is_repeatable = args[:is_repeatable] if args.key?(:is_repeatable)\n @value_metadata = args[:value_metadata] if args.key?(:value_metadata)\n @value_type = args[:value_type] if args.key?(:value_type)\n end", "def update!(**args)\n @attribute_id = args[:attribute_id] if args.key?(:attribute_id)\n @display_name = args[:display_name] if args.key?(:display_name)\n @group_display_name = args[:group_display_name] if args.key?(:group_display_name)\n @is_deprecated = args[:is_deprecated] if args.key?(:is_deprecated)\n @is_repeatable = args[:is_repeatable] if args.key?(:is_repeatable)\n @value_metadata = args[:value_metadata] if args.key?(:value_metadata)\n @value_type = args[:value_type] if args.key?(:value_type)\n end", "def update!(**args)\n @ad_group = args[:ad_group] if args.key?(:ad_group)\n @asset_set = args[:asset_set] if args.key?(:asset_set)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n @status = args[:status] if args.key?(:status)\n end", "def UpdateGroup params = {}\n \n APICall(path: 'groups.json',method: 'PUT',payload: params.to_json)\n \n end", "def update!(**args)\n @all = args[:all] if args.key?(:all)\n @group_labels = args[:group_labels] if args.key?(:group_labels)\n @instance_name_prefixes = args[:instance_name_prefixes] if args.key?(:instance_name_prefixes)\n @instances = args[:instances] if args.key?(:instances)\n @zones = args[:zones] if args.key?(:zones)\n end", "def update_group(group_id, attributes)\n put(\"/v1/groups/#{group_id}\", attributes)\n end", "def update options = {}\n\n client_opts = options.dup\n client_opts[:scheduled_action_name] = name\n client_opts[:auto_scaling_group_name] = auto_scaling_group_name\n\n # convert these options to timestamps \n [:start_time, :end_time].each do |opt|\n if client_opts[opt].is_a?(Time)\n client_opts[opt] = client_opts[opt].iso8601\n end\n end\n\n client.put_scheduled_update_group_action(client_opts)\n\n nil\n\n end", "def update_attribute(attr_name, attr_value)\n update_attributes(attr_name => attr_value)\n end", "def update!(**args)\n @id = args[:id] if args.key?(:id)\n @name = args[:name] if args.key?(:name)\n @scaled_shape = args[:scaled_shape] if args.key?(:scaled_shape)\n @scaling_function = args[:scaling_function] if args.key?(:scaling_function)\n end", "def update_group(group_name, options = {})\n request({\n 'Action' => 'UpdateGroup',\n 'GroupName' => group_name,\n :parser => Fog::Parsers::AWS::IAM::UpdateGroup.new\n }.merge!(options))\n end", "def modify_target_group_attributes(tg_id, attributes)\n params = {}\n params.merge!(Fog::AWS.indexed_param('Attributes.member', attributes))\n request({\n 'Action' => 'ModifyTargetGroupAttributes',\n 'TargetGroupArn' => tg_id,\n :parser => Fog::Parsers::AWS::ELBV2::ModifyTargetGroupAttributes.new\n }.merge(params))\n end", "def update!(**args)\n @ad_group_criterion = args[:ad_group_criterion] if args.key?(:ad_group_criterion)\n @label = args[:label] if args.key?(:label)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n end", "def update_attributes(atts)\n atts.each { |att, val| send(:\"#{att}=\", val) }\n end", "def update!(**args)\n @ad_group_criterion = args[:ad_group_criterion] if args.key?(:ad_group_criterion)\n @info = args[:info] if args.key?(:info)\n end", "def update!(**args)\n @ad_group = args[:ad_group] if args.key?(:ad_group)\n @asset = args[:asset] if args.key?(:asset)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n @status = args[:status] if args.key?(:status)\n end", "def update!(**args)\n @group_name = args[:group_name] if args.key?(:group_name)\n end", "def update!(**args)\n @group_name = args[:group_name] if args.key?(:group_name)\n end", "def update!(**args)\n @group_name = args[:group_name] if args.key?(:group_name)\n end", "def update!(**args)\n @group_name = args[:group_name] if args.key?(:group_name)\n end", "def update!(**args)\n @group_id = args[:group_id] if args.key?(:group_id)\n @owner_gaia_id = args[:owner_gaia_id] if args.key?(:owner_gaia_id)\n @required_consistency_timestamp_usec = args[:required_consistency_timestamp_usec] if args.key?(:required_consistency_timestamp_usec)\n end", "def update!(**args)\n @group_id = args[:group_id] if args.key?(:group_id)\n @owner_gaia_id = args[:owner_gaia_id] if args.key?(:owner_gaia_id)\n @required_consistency_timestamp_usec = args[:required_consistency_timestamp_usec] if args.key?(:required_consistency_timestamp_usec)\n end", "def update!(**args)\n @scale = args[:scale] if args.key?(:scale)\n @status = args[:status] if args.key?(:status)\n end", "def update!(**args)\n @capacity = args[:capacity] if args.key?(:capacity)\n @count = args[:count] if args.key?(:count)\n @scale = args[:scale] if args.key?(:scale)\n end", "def update!(**args)\n @attributes = args[:attributes] if args.key?(:attributes)\n @usage_info = args[:usage_info] if args.key?(:usage_info)\n end", "def update!(**args)\n @mean_attributions = args[:mean_attributions] if args.key?(:mean_attributions)\n end", "def update!(**args)\n @attribute_name = args[:attribute_name] if args.key?(:attribute_name)\n @attribute_value = args[:attribute_value] if args.key?(:attribute_value)\n @section_name = args[:section_name] if args.key?(:section_name)\n end", "def remove_auto_scaling_group_properties\n properties = []\n properties << :AvailabilityZones\n properties << :HealthCheckGracePeriod\n properties << :HealthCheckType\n add_patch Patches::RemoveProperty.new 'AWS::AutoScaling::AutoScalingGroup', properties\n end", "def update!(**args)\n @autoscaling_spec = args[:autoscaling_spec] if args.key?(:autoscaling_spec)\n @disk_spec = args[:disk_spec] if args.key?(:disk_spec)\n @id = args[:id] if args.key?(:id)\n @machine_spec = args[:machine_spec] if args.key?(:machine_spec)\n @replica_count = args[:replica_count] if args.key?(:replica_count)\n @used_replica_count = args[:used_replica_count] if args.key?(:used_replica_count)\n end", "def update!(**args)\n @instances = args[:instances] if args.key?(:instances)\n @labels = args[:labels] if args.key?(:labels)\n @location = args[:location] if args.key?(:location)\n @network = args[:network] if args.key?(:network)\n @placement = args[:placement] if args.key?(:placement)\n @service_account = args[:service_account] if args.key?(:service_account)\n end", "def scale(max_size, desired_capacity)\n client.update_auto_scaling_group(auto_scaling_group_name: asg_name, max_size: max_size, desired_capacity: desired_capacity)\n end", "def update(attrs)\n super(attrs)\n end", "def update(attrs)\n super(attrs)\n end", "def update(attrs)\n super(attrs)\n end", "def update(attrs)\n super(attrs)\n end", "def update!(**args)\n @attribute_count = args[:attribute_count] if args.key?(:attribute_count)\n @class_count = args[:class_count] if args.key?(:class_count)\n @create_time = args[:create_time] if args.key?(:create_time)\n @description = args[:description] if args.key?(:description)\n @display_name = args[:display_name] if args.key?(:display_name)\n @etag = args[:etag] if args.key?(:etag)\n @labels = args[:labels] if args.key?(:labels)\n @name = args[:name] if args.key?(:name)\n @uid = args[:uid] if args.key?(:uid)\n @update_time = args[:update_time] if args.key?(:update_time)\n end", "def update!(**args)\n @attribute_id = args[:attribute_id] if args.key?(:attribute_id)\n @score = args[:score] if args.key?(:score)\n end", "def update(attrs)\n attrs.each_pair do |key, value|\n send(\"#{key}=\", value) if respond_to?(\"#{key}=\")\n # attributes[key] = value <- lets make use of virtual attributes too\n end\n end", "def update_attributes(args = {})\n assign_attributes(args)\n save\n end", "def update!(**args)\n @attribute_resources = args[:attribute_resources] if args.key?(:attribute_resources)\n @category = args[:category] if args.key?(:category)\n @data_type = args[:data_type] if args.key?(:data_type)\n @enum_values = args[:enum_values] if args.key?(:enum_values)\n @filterable = args[:filterable] if args.key?(:filterable)\n @is_repeated = args[:is_repeated] if args.key?(:is_repeated)\n @metrics = args[:metrics] if args.key?(:metrics)\n @name = args[:name] if args.key?(:name)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n @segments = args[:segments] if args.key?(:segments)\n @selectable = args[:selectable] if args.key?(:selectable)\n @selectable_with = args[:selectable_with] if args.key?(:selectable_with)\n @sortable = args[:sortable] if args.key?(:sortable)\n @type_url = args[:type_url] if args.key?(:type_url)\n end", "def update!(**args)\n @attribute_id = args[:attribute_id] if args.key?(:attribute_id)\n @value_type = args[:value_type] if args.key?(:value_type)\n @display_name = args[:display_name] if args.key?(:display_name)\n @group_display_name = args[:group_display_name] if args.key?(:group_display_name)\n @is_repeatable = args[:is_repeatable] if args.key?(:is_repeatable)\n @value_metadata = args[:value_metadata] if args.key?(:value_metadata)\n end", "def update_attributes!(args = {})\n assign_attributes(args)\n save!\n end", "def update attributes\n attributes.each do |name, value|\n send \"#{name}=\", value if respond_to? \"#{name}=\"\n end\n save\n end", "def update!(**args)\n @attribute_map = args[:attribute_map] if args.key?(:attribute_map)\n @dropped_attributes_count = args[:dropped_attributes_count] if args.key?(:dropped_attributes_count)\n end", "def update(attrs)\n @attrs ||= {}\n @attrs.update(attrs)\n self\n end", "def update_attributes(attribs = {})\n attribs.each { |name, value| write_attribute(name, value) }\n end", "def update(attrs)\n @attrs.update(attrs)\n self\n end", "def update!(**args)\n @group_id = args[:group_id] if args.key?(:group_id)\n end", "def update!(**args)\n @group_id = args[:group_id] if args.key?(:group_id)\n end", "def update!(**args)\n @attributes = args[:attributes] if args.key?(:attributes)\n end", "def update!(**args)\n @ad_group = args[:ad_group] if args.key?(:ad_group)\n @ad_group_ad = args[:ad_group_ad] if args.key?(:ad_group_ad)\n @ad_group_ad_label = args[:ad_group_ad_label] if args.key?(:ad_group_ad_label)\n @ad_group_asset = args[:ad_group_asset] if args.key?(:ad_group_asset)\n @ad_group_asset_set = args[:ad_group_asset_set] if args.key?(:ad_group_asset_set)\n @ad_group_audience_view = args[:ad_group_audience_view] if args.key?(:ad_group_audience_view)\n @ad_group_bid_modifier = args[:ad_group_bid_modifier] if args.key?(:ad_group_bid_modifier)\n @ad_group_criterion = args[:ad_group_criterion] if args.key?(:ad_group_criterion)\n @ad_group_criterion_label = args[:ad_group_criterion_label] if args.key?(:ad_group_criterion_label)\n @ad_group_label = args[:ad_group_label] if args.key?(:ad_group_label)\n @age_range_view = args[:age_range_view] if args.key?(:age_range_view)\n @asset = args[:asset] if args.key?(:asset)\n @asset_set = args[:asset_set] if args.key?(:asset_set)\n @asset_set_asset = args[:asset_set_asset] if args.key?(:asset_set_asset)\n @bidding_strategy = args[:bidding_strategy] if args.key?(:bidding_strategy)\n @campaign = args[:campaign] if args.key?(:campaign)\n @campaign_asset = args[:campaign_asset] if args.key?(:campaign_asset)\n @campaign_asset_set = args[:campaign_asset_set] if args.key?(:campaign_asset_set)\n @campaign_audience_view = args[:campaign_audience_view] if args.key?(:campaign_audience_view)\n @campaign_budget = args[:campaign_budget] if args.key?(:campaign_budget)\n @campaign_criterion = args[:campaign_criterion] if args.key?(:campaign_criterion)\n @campaign_label = args[:campaign_label] if args.key?(:campaign_label)\n @conversion_action = args[:conversion_action] if args.key?(:conversion_action)\n @custom_columns = args[:custom_columns] if args.key?(:custom_columns)\n @customer = args[:customer] if args.key?(:customer)\n @customer_asset = args[:customer_asset] if args.key?(:customer_asset)\n @customer_asset_set = args[:customer_asset_set] if args.key?(:customer_asset_set)\n @customer_client = args[:customer_client] if args.key?(:customer_client)\n @customer_manager_link = args[:customer_manager_link] if args.key?(:customer_manager_link)\n @dynamic_search_ads_search_term_view = args[:dynamic_search_ads_search_term_view] if args.key?(:dynamic_search_ads_search_term_view)\n @gender_view = args[:gender_view] if args.key?(:gender_view)\n @geo_target_constant = args[:geo_target_constant] if args.key?(:geo_target_constant)\n @keyword_view = args[:keyword_view] if args.key?(:keyword_view)\n @label = args[:label] if args.key?(:label)\n @location_view = args[:location_view] if args.key?(:location_view)\n @metrics = args[:metrics] if args.key?(:metrics)\n @product_group_view = args[:product_group_view] if args.key?(:product_group_view)\n @segments = args[:segments] if args.key?(:segments)\n @user_list = args[:user_list] if args.key?(:user_list)\n @webpage_view = args[:webpage_view] if args.key?(:webpage_view)\n end", "def update_attributes(attributes = {})\n raise ArgumentError.new(\"Cannot set attributes on new record\") if @label.to_s.empty?\n \n attributes.each do |k,v|\n if [\"status\", \"sync_period\", \"service_level\", \"password\", \"provider_token\", \"provider_token_secret\", \"provider_consumer_key\"].include? k\n send(\"#{k}=\", v)\n end\n end\n update_record\n end", "def update!(**args)\n @fixed_node_count = args[:fixed_node_count] if args.key?(:fixed_node_count)\n @scaling = args[:scaling] if args.key?(:scaling)\n end", "def update!(**args)\n @attribute_count = args[:attribute_count] if args.key?(:attribute_count)\n @create_time = args[:create_time] if args.key?(:create_time)\n @data_access_spec = args[:data_access_spec] if args.key?(:data_access_spec)\n @description = args[:description] if args.key?(:description)\n @display_name = args[:display_name] if args.key?(:display_name)\n @etag = args[:etag] if args.key?(:etag)\n @labels = args[:labels] if args.key?(:labels)\n @name = args[:name] if args.key?(:name)\n @parent_id = args[:parent_id] if args.key?(:parent_id)\n @resource_access_spec = args[:resource_access_spec] if args.key?(:resource_access_spec)\n @uid = args[:uid] if args.key?(:uid)\n @update_time = args[:update_time] if args.key?(:update_time)\n end", "def update\n @ail_group = AilGroup.find(params[:id])\n\n respond_to do |format|\n if @ail_group.update_attributes(params[:ail_group])\n flash[:notice] = 'AilGroup was successfully updated.'\n format.html { redirect_to(@ail_group) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @ail_group.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @boot_disk_size_gb = args[:boot_disk_size_gb] if args.key?(:boot_disk_size_gb)\n @cpus = args[:cpus] if args.key?(:cpus)\n @enable_load_balancer = args[:enable_load_balancer] if args.key?(:enable_load_balancer)\n @image = args[:image] if args.key?(:image)\n @image_type = args[:image_type] if args.key?(:image_type)\n @labels = args[:labels] if args.key?(:labels)\n @memory_mb = args[:memory_mb] if args.key?(:memory_mb)\n @replicas = args[:replicas] if args.key?(:replicas)\n @taints = args[:taints] if args.key?(:taints)\n @vsphere_config = args[:vsphere_config] if args.key?(:vsphere_config)\n end", "def update_attribute(key, value)\n self.update_attributes(key => value)\n end", "def update attributes, collection #:nodoc:\n 0\n end", "def update!(**args)\n @attribute_key = args[:attribute_key] if args.key?(:attribute_key)\n @attribute_value = args[:attribute_value] if args.key?(:attribute_value)\n end", "def update!(**args)\n @active_assets = args[:active_assets] if args.key?(:active_assets)\n @security_policy_applying_assets = args[:security_policy_applying_assets] if args.key?(:security_policy_applying_assets)\n @update_time = args[:update_time] if args.key?(:update_time)\n end", "def update!(**args)\n @attr_value = args[:attr_value] if args.key?(:attr_value)\n end", "def update!(**args)\n @group_columns = args[:group_columns] if args.key?(:group_columns)\n @group_temporal_total_weight = args[:group_temporal_total_weight] if args.key?(:group_temporal_total_weight)\n @group_total_weight = args[:group_total_weight] if args.key?(:group_total_weight)\n @temporal_total_weight = args[:temporal_total_weight] if args.key?(:temporal_total_weight)\n end", "def update_attributes(atts)\n atts.delete('_type')\n atts.each { |att, val| send(:\"#{att}=\", val) }\n end", "def update!(**args)\n @duration_ms = args[:duration_ms] if args.key?(:duration_ms)\n @instances = args[:instances] if args.key?(:instances)\n @uploader_name = args[:uploader_name] if args.key?(:uploader_name)\n end", "def update!(**args)\n @resource_group = args[:resource_group] if args.key?(:resource_group)\n @resource_kind = args[:resource_kind] if args.key?(:resource_kind)\n end", "def auto_scaling_group(group_name)\n AutoScalingGroup.new(group_name)\n end", "def update!(**args)\n @batch = args[:batch] if args.key?(:batch)\n @container_image = args[:container_image] if args.key?(:container_image)\n @vpc_network = args[:vpc_network] if args.key?(:vpc_network)\n end", "def update!(**args)\n @accelerators = args[:accelerators] if args.key?(:accelerators)\n @boot_disk_size_gb = args[:boot_disk_size_gb] if args.key?(:boot_disk_size_gb)\n @confidential_instance_config = args[:confidential_instance_config] if args.key?(:confidential_instance_config)\n @disable_public_ip_addresses = args[:disable_public_ip_addresses] if args.key?(:disable_public_ip_addresses)\n @enable_nested_virtualization = args[:enable_nested_virtualization] if args.key?(:enable_nested_virtualization)\n @machine_type = args[:machine_type] if args.key?(:machine_type)\n @pool_size = args[:pool_size] if args.key?(:pool_size)\n @pooled_instances = args[:pooled_instances] if args.key?(:pooled_instances)\n @service_account = args[:service_account] if args.key?(:service_account)\n @shielded_instance_config = args[:shielded_instance_config] if args.key?(:shielded_instance_config)\n @tags = args[:tags] if args.key?(:tags)\n end", "def update_kapp_attribute_definition(kapp_slug, name, body, headers=default_headers)\n @logger.info(\"Updating the \\\"#{name}\\\" Kapp attribute definition in the \\\"#{kapp_slug}\\\" kapp.\")\n put(\"#{@api_url}/kapps/#{kapp_slug}/kappAttributeDefinitions/#{encode(name)}\",body, headers)\n end", "def update_harman_employee_pricing\n authorize! :update, :harman_employee_pricing\n params[:product_attr].to_a.each do |key, attr|\n product = Product.find(key)\n product.update_attributes(attr)\n end\n redirect_to(harman_employee_pricing_admin_products_path, notice: \"Pricing updated successfully.\")\n end", "def update(attributes={})\n attributes.each do |attribute, value|\n public_send(\"#{attribute}=\", value)\n end\n end", "def update_attributes(attr = {})\n attr.each_pair do |k, v|\n if v.is_a?(Array) || v.is_a?(Hash)\n send(\"#{k}=\", v.dup)\n else\n send(\"#{k}=\", v)\n end\n end\n end", "def update!(**args)\n @instances = args[:instances] if args.key?(:instances)\n @parameters = args[:parameters] if args.key?(:parameters)\n end", "def update_attributes(attrs)\n self.attributes = attrs\n save\n end", "def update(attrs, opts={})\n update_attributes(attrs)\n save(opts)\n end", "def update_attr_with_ial(attr, ial); end", "def update_attributes attributes\n @attributes.merge! attributes\n end", "def update!(**args)\n @csai_classification = args[:csai_classification] if args.key?(:csai_classification)\n @csai_regexp_high_confidence_classification = args[:csai_regexp_high_confidence_classification] if args.key?(:csai_regexp_high_confidence_classification)\n @debug = args[:debug] if args.key?(:debug)\n @is_positive = args[:is_positive] if args.key?(:is_positive)\n @score = args[:score] if args.key?(:score)\n end", "def update_all(attributes = {})\n klass.collection.update(\n selector,\n { \"$set\" => attributes },\n :multi => true,\n :safe => Mongoid.persist_in_safe_mode\n )\n end", "def update!(**args)\n @metric_requests = args[:metric_requests] if args.key?(:metric_requests)\n @time_range = args[:time_range] if args.key?(:time_range)\n end", "def update!(**args)\n @metric_requests = args[:metric_requests] if args.key?(:metric_requests)\n @time_range = args[:time_range] if args.key?(:time_range)\n end", "def update_attributes(attrs)\n if id = attrs.delete(:id)\n @id = id\n end\n attrs.each do |key, value|\n setter = :\"#{key}=\"\n send(setter, value) if respond_to?(setter)\n end\n end", "def update\n @record_group = RecordGroup.find(params[:id])\n @record_group.accessible = :all if admin?\n respond_to do |format|\n if @record_group.update_attributes(params[:record_group])\n flash[:notice] = 'RecordGroup was successfully updated.'\n format.html { redirect_to(@record_group) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @record_group.errors, :status => :unprocessable_entity }\n end\n end\n end", "def save\n requires :id\n requires :adjustment_type\n requires :auto_scaling_group_name\n requires :scaling_adjustment\n\n options = Hash[self.class.aliases.map { |key, value| [key, send(value)] }]\n options.delete_if { |key, value| value.nil? }\n\n service.put_scaling_policy(adjustment_type, auto_scaling_group_name, id, scaling_adjustment, options)\n reload\n end", "def update_resource object, attributes\n object.update attributes\n end", "def update!(**args)\n @allow_no_resource_group_match = args[:allow_no_resource_group_match] if args.key?(:allow_no_resource_group_match)\n @description = args[:description] if args.key?(:description)\n @fingerprint = args[:fingerprint] if args.key?(:fingerprint)\n @id = args[:id] if args.key?(:id)\n @mode = args[:mode] if args.key?(:mode)\n @resource_groups = args[:resource_groups] if args.key?(:resource_groups)\n end", "def update\n\t\tparams[:group][:member_ids] = (params[:group][:member_ids] << @group.member_ids).flatten\n\t\t#special method update_attribute only updates explicitly stated attribute\n\t\tif @group.update_attributes(params[:group])\n\t\t\tredirect_to @group\n\t\t\tflash[:success] = \"group updated\"\n\t\tend\n\tend", "def update_harman_employee_pricing\n authorize! :update, :harman_employee_pricing\n Array(params[:product_attr].to_unsafe_h).each do |key, attr|\n product = Product.find(key)\n product.update(attr)\n end\n redirect_to(harman_employee_pricing_admin_products_path, notice: \"Pricing updated successfully.\")\n end", "def update!(**args)\n @instances = args[:instances] if args.key?(:instances)\n end", "def update_attrs(parameters, date, picture)\r\n self.update_attributes(parameters)\r\n self.actual_accommodation.update_attributes(date) if date\r\n if picture\r\n picture[:id] = self.id\r\n if picture[:file] != \"\"\r\n picture[:upload_status] = self.save_picture(picture)\r\n end\r\n end\r\n return true\r\n end" ]
[ "0.74691784", "0.7061314", "0.63325363", "0.63305366", "0.62738395", "0.62424904", "0.6221506", "0.62184185", "0.6218149", "0.614807", "0.61462647", "0.6125194", "0.61241025", "0.6101883", "0.6095457", "0.6094295", "0.60861397", "0.6073944", "0.60582435", "0.6037467", "0.6036121", "0.60286075", "0.60233575", "0.59973323", "0.5988949", "0.5979122", "0.59363973", "0.59363973", "0.59363973", "0.59363973", "0.5922786", "0.5922786", "0.5913309", "0.5864723", "0.583503", "0.5834863", "0.58264416", "0.581741", "0.58125037", "0.58085567", "0.5783493", "0.5775423", "0.5775423", "0.5775423", "0.5775423", "0.57697487", "0.57661116", "0.5759582", "0.57491356", "0.5745741", "0.57439", "0.5735324", "0.57320714", "0.5729756", "0.57191193", "0.57172644", "0.571566", "0.57083076", "0.57083076", "0.56988895", "0.56868607", "0.5683694", "0.5662281", "0.5659821", "0.5653782", "0.5631446", "0.56238025", "0.56190383", "0.561592", "0.56114596", "0.56113034", "0.56106126", "0.5608668", "0.56078655", "0.5606245", "0.5605679", "0.5605469", "0.5599324", "0.5591841", "0.55903685", "0.55796295", "0.55680376", "0.556119", "0.5553461", "0.55481803", "0.55397207", "0.55388975", "0.5538377", "0.5537834", "0.5536788", "0.5536788", "0.5535804", "0.5533899", "0.55322653", "0.5526584", "0.55239", "0.5522492", "0.55149686", "0.551186", "0.55117637" ]
0.7522412
0
Removes all tags from this Auto Scaling group.
def delete_all_tags delete_tags(self.tags) nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reset\n @tags.clear\n end", "def delete_tags\n @tags.delete_tags(@filename) unless @tags.nil?\n end", "def delete\n resource.delete_tags([self])\n nil\n end", "def destroy\n tag_ids.clone.each { |tag_id| destroy_tag(tag_id) }\n super\n end", "def purge_unused_tags!\n unused_tags.each do |tag|\n logger.info(\"Purging tag '#{tag}'\")\n entries_with(label: tag).each do |entry|\n payload = Protocol::Device::SetTagLabels.new(tags: id_to_tags_field(entry.tag_id), label: '')\n context.send_message(target: Target.new(site_id: entry.site_id),\n payload: payload,\n acknowledge: true)\n end\n end\n Timeout.timeout(5) do\n while !unused_tags.empty?\n sleep 0.1\n end\n end\n end", "def remove_all_asset_group_tags(id, opts = {})\n data, _status_code, _headers = remove_all_asset_group_tags_with_http_info(id, opts)\n data\n end", "def unset_all_tags\n @deployment.servers_no_reload.each do |s|\n # can't unset ALL tags, so we must set a bogus one\n s.tags = [{\"name\"=>\"removeme:now=1\"}]\n s.save\n end\n end", "def delete_tags\n tags = self.tags\n tags.each do |tag|\n tag.destroy if tag.posts.count == 1\n end\n end", "def clear_all_tags()\n puts \"Deleting Tags...\"\n Tag.delete_all()\n puts \"Finished deleting all tags.\"\nend", "def delete_image tags\n all_images_by_tags( tags ).each { | image | image.deregister } \n end", "def delete_tags(name); end", "def destroy_tags\n self.meme_tags.each{|mt| mt.destroy}\n end", "def remove_tags!(tenant_id,tags)\n @instance.remove_tags!(tenant_id,tags)\n end", "def destroy_taggings\n Tagging.where(:tag_id => self.id).each do |tagging|\n tagging.not_orphans = true\n tagging.destroy\n end\n end", "def destroy_all\n if resource.tags&.any?\n deleted_tags = resource.tags\n resource.tags = []\n resource.save!\n end\n\n render json: { tags: resource.tags, deleted_tags: deleted_tags || [] }\n end", "def unset_all_tags\n @servers.each do |s|\n # can't unset ALL tags, so we must set a bogus one\n s.tags = [{\"name\"=>\"removeme:now=1\"}]\n obj_behavior(s, :save)\n end\n end", "def clean_all_tags\n self.tags.destroy_all\n self.countries.destroy_all\n self.requirements.destroy_all\n self.places.destroy_all\n end", "def destroy_interview_taggings\n manager_interview_taggings.each do |tagging|\n tagging.destroy\n end\n end", "def clear\n @hash_tags.clear\n end", "def delete_tags(filename=@filename)\n Mutagen::AIFF::delete_chunk filename\n clear\n end", "def bulk_purge_tag(opts = {})\n data, _status_code, _headers = bulk_purge_tag_with_http_info(opts)\n data\n end", "def remove_from_all_groups\n self.group_memberships.each {|m| m.destroy}\n end", "def destroy\n current_user.tasks.all.each do |c|\n c.update({tag_ids: []})\n c.destroy\n end\n current_user.tags.all.each do |g|\n g.destroy\n end\n current_user.categories.all.each do |t|\n t.destroy\n end\n super\n end", "def remove_tags(tag_list, reload_tags = true)\n tags_to_delete = Tag.parse_to_tags(tag_list)\n TxactionTagging.transaction do\n destroy_taggings(tags_to_delete)\n end if tags_to_delete.any?\n self.taggings(reload_tags)\n current_tags = self.tags(reload_tags)\n update_attribute(:tagged, false) if current_tags.empty?\n end", "def untag(*tags)\n tags.each do |tag|\n run_context.node.tags.delete(tag)\n end\n end", "def untag(*tags)\n tags.each do |tag|\n run_context.node.tags.delete(tag)\n end\n end", "def destroy_tag(*tags)\n tags.each do |tag|\n gsub! Regexp.new(\"<\\s*#{tag}[^>]*>.*?<\\s*\\/#{tag}\\s*>\", Regexp::IGNORECASE + Regexp:: MULTILINE), ''\n end\n end", "def remove_preexisting_tagging\n user.taggings.find(:all, \n :conditions => { :tag_id => tag.id, :feed_item_id => feed_item.id, :classifier_tagging => classifier_tagging? }\n ).each(&:destroy)\n end", "def tags_to_remove\n aws_tags.reject { |t, v| local_tags.include?(t) and local_tags[t] == v }\n end", "def remove_tags(tag_id)\n self.tags.destroy(tag_id)\n end", "def unregister name\n @tags.delete(name)\n end", "def unregister name\n @tags.delete(name)\n end", "def remove_all\n @jobs.each do |job|\n job.unschedule\n end\n @@instances.delete self\n end", "def clear_tag(tag)\n metafeta_store.delete(tag)\n end", "def update_tags\n @updated = Tag.refresh_counts\n @deleted = []\n Tag.unused.order(:title).all.each do |tag|\n @deleted << tag.destroy\n end\n end", "def clear\n raise TypeError, \"Must set agent= before using tag manager\" unless @agent\n @agent.update_tags([], tags)\n true\n end", "def remove_tagging_by_each(model_type, model_id, tag_name)\n tag = Tag.get(tag_name)\n tagging = Tagging.where(:model_type => model_type, :model_id => model_id, :tag_id => tag.id).first\n tagging.destroy if !tagging.blank?\n end", "def refresh_tags\n taggings.delete_all\n metadata['tags'].each do |tag|\n new_tag = Tag.find_or_create_by(name: tag.parameterize)\n tags << new_tag\n validation = new_tag.find_similar\n spin_log(validation) unless validation.nil?\n end\n end", "def tags!\n @tags = nil\n tags\n end", "def destroy\n resources = find_resources_by_tag\n\n destroy_instance(resources)\n destroy_security_group(resources)\n destroy_subnet(resources)\n destroy_route_table(resources)\n\n nil\n end", "def clear_tag(key)\n meta.delete(key)\n end", "def expire_tags(*params)\n taggable.get(*params).each do |m|\n self.delete(m)\n end\n end", "def clean_up_tags\n self.tags.each do |tag|\n if tag.todos.count == 1\n tag.destroy\n end\n end\n end", "def remove_tags(tags)\n\t\t\t@metadata.attributes.update do |u|\n\t\t\t\tu.delete(:tags => tags)\n\t\t\t\tu.add(:idenity => 1)\n\t\t\tend\n\t\t\treturn nil\n\t\tend", "def destroy\n @tag.destroy\n end", "def destroy\n @tag.destroy\n end", "def tag_clean_up\n all_tags = Tag.all\n all_modules = UniModule.all\n\n all_tags.each do |tag|\n is_used_somewhere = false\n all_modules.each do |uni_module|\n if uni_module.tags.include?(tag)\n is_used_somewhere = true\n end\n end\n if !is_used_somewhere\n logs = TagLog.all.where(:tag_id => tag.id)\n if logs.size >0\n logs.each do |log|\n log.destroy\n end\n end\n tag.destroy\n end\n end\n end", "def destroy(options = { :force => false })\n requires :id\n\n opts = {}\n opts.merge!({'ForceDelete' => true}) if options[:force]\n\n service.delete_auto_scaling_group(id, opts)\n end", "def tags_to_remove=(value)\n @tags_to_remove = value\n end", "def remove_tags(*old_tags)\n raise TypeError, \"Must set agent= before using tag manager\" unless @agent\n @agent.update_tags([], old_tags)\n true\n end", "def tags_to_remove\n linked_tags - current_tags\n end", "def terminate\n logger.info \"Terminating any instance with GroupUUID: #{@os_aws.group_uuid}\"\n\n terminate_instances_by_group_id(@os_aws.group_uuid)\n end", "def purge (group)\n ensure_group(group).purge\n end", "def deactivate(*tags)\n tags.each { |t| TagList.delete(t) }\n end", "def deactivate(*tags)\n tags.each { |t| TagList.delete(t) }\n end", "def tags_to_remove\n return @tags_to_remove\n end", "def remove_tag(tag)\r\n self.tags.all(:name => tag.name).destroy\r\n end", "def remove_all_images\n self.cover_image.purge if self.cover_image.attached?\n self.images.each {|image| image.purge} if self.images.attached?\n end", "def delete()\n\n client.delete(\"/tags/#{gid}\") && true\n end", "def remove_auto_scaling_group_properties\n properties = []\n properties << :AvailabilityZones\n properties << :HealthCheckGracePeriod\n properties << :HealthCheckType\n add_patch Patches::RemoveProperty.new 'AWS::AutoScaling::AutoScalingGroup', properties\n end", "def reset\n [topics, queues, subscriptions].each do |resource|\n resource.values.each(&:delete)\n resource.clear\n end\n end", "def cleanup\n self.objectives.destroy_all\n end", "def purge_tag(opts = {})\n data, _status_code, _headers = purge_tag_with_http_info(opts)\n data\n end", "def refreshtags\n\t\tif Tag.all != nil\n\t\t\t@badtags = Tag.all.select {\n\t\t\t\t|tag|\n\t\t\t\t@usedresources = Resource.all.select {\n\t\t\t\t\t|resource|\n\t\t\t\t\tresource.tags.include? tag\n\t\t\t\t}\n\t\t\t\t@usedresources.empty?\n\t\t\t}\n\t\t\t@badtags.each {\n\t\t\t\t|tag|\n\t\t\t\ttag.destroy\n\t\t\t}\n\t\tend\n\tend", "def destroy_all\n all.each(&:destroy)\n end", "def remove\n remove_checkpoints\n remove_config\n remove_hiera_template\n end", "def destroy\n super\n\n @children.each do |_child_name, child_group|\n child_group.each(&:destroy)\n end\n\n @children = {}\n end", "def clear\n update_tags([], tags) { |raw_response| yield raw_response }\n end", "def delete_all_vlan_groups\n super\n end", "def stop\n puts \"Stoping any instance with group ID: #{@os_aws.group_uuid}\"\n\n stop_instances_by_group_id(@os_aws.group_uuid)\n end", "def destroy_all\n all.each(&:destroy)\n end", "def remove_all()\n @items.clear()\n end", "def empty_group\n self.group_memberships.each {|m| m.destroy}\n end", "def destroy_all\n each(&:destroy_all)\n end", "def delete_unused_tags\n ActiveRecord::Base.connection.execute(\n \"delete from tags where id in(\n select t.id from tags as t left join posts_tags as pt on pt.tag_id = t.id where pt.tag_id is null\n )\"\n )\n end", "def unassign_tags(tag_titles)\n update_counters_before\n tags = tag_titles.split(\",\").strip\n self.term_relationships.where({term_taxonomy_id: self.post_type.post_tags.where(name: tags).pluck(:id)}).destroy_all\n update_counters(\"tags\")\n end", "def clear_tags\n keys_to_remove = extra_config_keys\n\n spec_hash =\n keys_to_remove.map {|key| { :key => key, :value => '' } }\n\n spec = RbVmomi::VIM.VirtualMachineConfigSpec(\n :extraConfig => spec_hash\n )\n @item.ReconfigVM_Task(:spec => spec).wait_for_completion\n end", "def remove_request_tags(tags=[])\n if tags.any?\n tags.collect! { |tag|\n tag.slice!(0) if tag.first == '-' \n Tag.find_by_title(Rack::Utils::unescape(tag)) \n }\n self.requested_tags = (self.requested_tags - tags.compact).uniq\n end\n end", "def remove(tags)\n Array(tags).each { |t| @message.remove_label(t) }\n return @message.labels\n end", "def delete(*names)\n names.each { |name| @meta_tags.delete(name) }\n end", "def empty_group(group, opts)\n # unlink all resources from this group\n group.empty_group\n end", "def delete_all_node_groups\n delete_node_group_descendents(get_node_group(Rootuuid))\n end", "def destroy_all\n all.each do |n|\n n.destroy\n end\n end", "def remove_tags(*old_tags)\n update_tags([], old_tags) { |raw_response| yield raw_response if block_given? }\n end", "def remove_all\n @sequence.remove_all\n end", "def delete(tag)\n update_tag_file do |tag_array|\n tag_array.delete(tag)\n end\n end", "def reset_policy_groups!\n @labels = nil\n end", "def delete_old_asg config, launch_config_name\n auto_scaling = new_auto_scaling\n auto_scaling.groups.each do |group|\n server = tag_value(group.tags, \"server\")\n if server != config[\"server\"]\n next \n end\n\n env = tag_value(group.tags, \"env\")\n if env != config[\"env\"]\n next \n end\n\n if group.name != launch_config_name.name\n puts \"deleting instance group, #{group.name} => #{launch_config_name.name}\"\n delete_asg group.name\n end\n end\nend", "def unkeyword!(keyword_ids:)\n taggings.where(tag_id: keyword_ids).each(&:destroy)\n end", "def remove_all_asset_group_tags_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: AssetGroupApi.remove_all_asset_group_tags ...'\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling AssetGroupApi.remove_all_asset_group_tags\"\n end\n # resource path\n local_var_path = '/api/3/asset_groups/{id}/tags'.sub('{' + 'id' + '}', id.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json;charset=UTF-8'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = []\n data, status_code, headers = @api_client.call_api(:DELETE, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Links')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: AssetGroupApi#remove_all_asset_group_tags\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def pop_tags(quantity=1)\n tags.pop(quantity)\n end", "def delete\n validate_presence_of :name\n wrapper.delete_tag(@name) || raise(OperationFailed)\n end", "def after_destroy\n tag.destroy_without_callbacks if tag and tag.taggings.count == 0\n end", "def cleanup_image_tags\n self.tags = self.tags.strip\n unless self.tags.empty?\n tags = self.tags.split(\",\")\n tags_new = []\n tags.each do |item|\n tags_new.push(item.strip)\n end\n self.tags = tags_new.join(\",\")\n end\n end", "def delete_asg name\n auto_scaling = new_auto_scaling\n groups = auto_scaling.groups\n raise \"unable to delete asg, #{name}. asg not found!\" if groups[name].nil? \n\n asg = groups[name]\n\n puts \"deleting asg, #{asg.name}\"\n asg.delete({:force => true})\n delete_launch_configs\nend", "def degroup!\n self.explicit_boundaries = []\n self\n end", "def destroy(tag:)\n ActiveRecord::Base.transaction do\n old_label = TagLabel.find_by!(tag:)\n AdministrativeTag.find_by!(druid: identifier, tag_label: old_label).destroy!\n old_label.destroy! if old_label.administrative_tags.count.zero?\n end\n end", "def delete_tag tag\n delete \"tag/#{tag}\"\n end", "def destroy\n @taggable = current_user.taggables.find(params[:id])\n\n #destroy each tag in the taggable\n @taggable.tags.each do |tag|\n tag.destroy\n end\n\n @taggable.destroy\n\n respond_to do |format|\n format.html { redirect_to taggables_url }\n format.json { head :no_content }\n end\n end", "def remove_tags_to_image(image, tags)\n image = image.resolve_id if image.respond_to?(:resolve_id)\n tags = tags.map { |t| t.name if t.is_a(Tag) }\n WeebImage.new(API::Toph.remove_tags_to_image(self, image, tags), self)\n end" ]
[ "0.6701327", "0.6678438", "0.6633569", "0.6585839", "0.6535254", "0.65154374", "0.63734984", "0.6359661", "0.63518476", "0.63514024", "0.62728924", "0.62476224", "0.62399614", "0.6209171", "0.6176984", "0.61742646", "0.60872024", "0.60832626", "0.60548097", "0.59624183", "0.59594417", "0.5930628", "0.59300756", "0.591471", "0.5909691", "0.5909691", "0.5893507", "0.5868846", "0.58482724", "0.58412474", "0.58361894", "0.58361894", "0.58193743", "0.5789796", "0.5761103", "0.57367986", "0.5730259", "0.5718695", "0.568632", "0.56635696", "0.56490654", "0.5643521", "0.56392175", "0.5637673", "0.56370157", "0.56370157", "0.5631473", "0.56266946", "0.5626381", "0.5619281", "0.5602463", "0.55625594", "0.55528665", "0.55381644", "0.55381644", "0.5534938", "0.5524934", "0.5524564", "0.5521655", "0.5505832", "0.5497074", "0.5497033", "0.54922354", "0.5489277", "0.5479428", "0.5468338", "0.54631203", "0.54600096", "0.5451576", "0.5426275", "0.5407798", "0.53861785", "0.5376617", "0.5374156", "0.53677076", "0.5356971", "0.53568774", "0.5350651", "0.5346088", "0.5343985", "0.53372574", "0.53183246", "0.5318221", "0.5307811", "0.52948236", "0.5288565", "0.5288177", "0.5287742", "0.52873576", "0.52855444", "0.5284783", "0.52825546", "0.5272866", "0.52431977", "0.52426285", "0.5240499", "0.52391946", "0.52310157", "0.5230607", "0.5223318" ]
0.7555071
0
Deletes the Auto Scaling group. If you pass +:force+ as true then all the instances associated with this group will also be terminated.
def delete options = {} client_opts = {} client_opts[:force_delete] = options[:force] == true client_opts[:auto_scaling_group_name] = name client.delete_auto_scaling_group(client_opts) nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy(options = { :force => false })\n requires :id\n\n opts = {}\n opts.merge!({'ForceDelete' => true}) if options[:force]\n\n service.delete_auto_scaling_group(id, opts)\n end", "def delete_asg name\n auto_scaling = new_auto_scaling\n groups = auto_scaling.groups\n raise \"unable to delete asg, #{name}. asg not found!\" if groups[name].nil? \n\n asg = groups[name]\n\n puts \"deleting asg, #{asg.name}\"\n asg.delete({:force => true})\n delete_launch_configs\nend", "def perform_destroy\n api.group_destroy(self)\n end", "def destroy\n Group.delete_groups_and_acls([id])\n end", "def delete_resource_group(group_name)\n cmdline = Schott::AzureCLI::Commandlines.delete_resource_group(group_name)\n sh(cmdline)\n end", "def destroy_google_group\n result = Gandalf::GoogleApiClient.delete_google_group(self.apps_id)\n result.data\n end", "def destroy\n @group.destroy\n msg = [\"Destroyed group.\", rebuild_configs].join(\" \")\n redirect_to groups_url, notice: msg\n end", "def destroy\n @client.resource_groups.delete(@resource_group)\n end", "def delete_app_group(group,app)\n\t\t\tresults = submit_cmd('delete app group',:db,\" -env #{self.env} -domain #{self.domain} -plant #{self.plant} -group #{group} -app_instance #{app}\")\n\t\t\tputs results\n\tend", "def purge (group)\n ensure_group(group).purge\n end", "def destroy\n start = Time.now\n debug(\"Deleting device group: \\\"#{resource[:full_path]}\\\"\")\n connection = self.class.get_connection(resource[:account])\n device_group = get_device_group(connection, resource[:full_path], 'id')\n if device_group\n delete_device_group = rest(connection,\n Puppet::Provider::Logicmonitor::DEVICE_GROUP_ENDPOINT % device_group['id'],\n Puppet::Provider::Logicmonitor::HTTP_DELETE)\n valid_api_response?(delete_device_group) ? nil : alert(delete_device_group)\n end\n debug \"Finished in #{(Time.now-start)*1000.0} ms\"\n end", "def destroy(name, &each_group)\n list(name, &each_group) if each_group\n ret = @@ec2.delete_security_group(:group_name => name)\n (ret && ret['return'] == 'true')\n end", "def terminate_instance_in_auto_scaling_group(instance_id, should_decrement_desired_capacity)\n request({\n 'Action' => 'TerminateInstanceInAutoScalingGroup',\n 'InstanceId' => instance_id,\n 'ShouldDecrementDesiredCapacity' => should_decrement_desired_capacity.to_s,\n :parser => Fog::Parsers::AWS::AutoScaling::TerminateInstanceInAutoScalingGroup.new\n })\n end", "def delete(name)\n return unless resource_group?(name)\n\n info \"deleting the resource group: #{name}\"\n @client.resource_groups.delete(name, name)\n end", "def delete_group(group)\n\t\t\tend", "def delete_group(group)\n\t\t\tend", "def delete_group(uuid)\n Uploadcare::Group.delete(uuid)\n end", "def destroy #:nodoc:\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to groups_url }\n # format.xml { head :ok }\n end\n end", "def remove_group(group)\n self.groups.destroy group \n end", "def destroy\n @group.destroy\n\n head :no_content\n end", "def terminate\n logger.info \"Terminating any instance with GroupUUID: #{@os_aws.group_uuid}\"\n\n terminate_instances_by_group_id(@os_aws.group_uuid)\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n redirect_to groups_path\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n redirect_to groups_path\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n head :no_content\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_groups_url) }\n format.xml { head :ok }\n end\n end", "def delete_old_asg config, launch_config_name\n auto_scaling = new_auto_scaling\n auto_scaling.groups.each do |group|\n server = tag_value(group.tags, \"server\")\n if server != config[\"server\"]\n next \n end\n\n env = tag_value(group.tags, \"env\")\n if env != config[\"env\"]\n next \n end\n\n if group.name != launch_config_name.name\n puts \"deleting instance group, #{group.name} => #{launch_config_name.name}\"\n delete_asg group.name\n end\n end\nend", "def deletesecuritygroup\n if not checkRequirements([\"thezone\",\"thefirewall\"])\n return false\n end\n checkToken(@thezone)\n submit = queryGCE(:path => '/compute/v1beta15/projects/#{@thezone.name}/global/firewalls/#{@thefirewall.serial}', :method => 'delete', :options => '', :acces_token => @thezone.token )\n checkQuery(:type => 'global', :token => @thezone.token, :projectname => @thezone.name, :operationname => submit[\"name\"])\n end", "def destroy\n @group.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @group = GROUP.first_or_get(params[:id])\n @group.current_user = current_user\n @group.destroy if @group\n\n respond_to do |format|\n flash[:notice] = 'Group was successfully deleted.'\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def group_destroy(group)\n if(group.persisted?)\n request(\n :path => \"/groups/#{group.id}\",\n :method => :delete,\n :expects => 204\n )\n true\n else\n false\n end\n end", "def destroy\n\n\t\t@group = Group.find(params[:id])\n\t\t@group.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(groups_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend", "def destroy_group(name)\n response = Curl.delete(azure_face_uri << name) do |http|\n http.headers[\"Ocp-Apim-Subscription-Key\"] = key\n end\n response.body_str\n end", "def delete_group\r\n if request.post?\r\n @group=Group.find_by_id(params[:id], :conditions=>['account_id = ?',session[:account_id]])\r\n if @group.nil?\r\n flash[:error] = \"Invalid action.\"\r\n else\r\n flash[:success]= \"Group \" + @group.name + \" was deleted successfully \"\r\n @group.destroy\r\n @group_devices = Device.find(:all, :conditions=>['group_id=?',@group.id])\r\n for device in @group_devices\r\n device.icon_id =\"1\"\r\n device.group_id = nil\r\n device.save\r\n end\r\n end\r\n end\r\n redirect_to :action=>\"groups\"\r\n end", "def destroy \n ec2 = self.class.new_ec2(@resource.value(:user), @resource.value(:password))\n ec2.terminate_instances({:instance_id => @property_hash[:instance_id]})\n ec2.delete_security_group({:group_name => @resource.value(:name)})\n end", "def destroy\n return access_denied unless is_admin?(current_user)\n\n @group = Group.find(params[:id])\n @group.destroy\n redirect_to(groups_url)\n end", "def DeleteGroup id\n \n APICall(path: \"groups/#{id}.json\",method: 'DELETE')\n \n end", "def destroy\n Group.rebuild! if nil.|Group.find(:first).rgt\n\t @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def delete_group(id)\n delete(\"groups/#{id}\")\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n \n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @attribute_group = AttributeGroup.find(params[:id])\n @attribute_group.destroy\n\n respond_to do |format|\n format.html { redirect_to(attribute_groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group.destroy\n redirect_to groups_url, notice: \"Group was successfully destroyed.\" \n end", "def destroy\n @auth_ip_address_group.destroy\n head :no_content\n end", "def delete_security_group( options = {} )\n options = { :group_name => \"\" }.merge(options)\n raise ArgumentError, \"No :group_name provided\" if options[:group_name].nil? || options[:group_name].empty?\n params = { \"GroupName\" => options[:group_name] }\n return response_generator(:action => \"DeleteSecurityGroup\", :params => params)\n end", "def destroy\n\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = Group.find_by_param(params[:id])\n @group.tuners.clear\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy!(document)\n method = klass.ancestors.include?(ActAsGroup::Resource) && klass.group_destroy_method ||\n ActAsGroup.configuration.destroy_resource.to_sym\n document.send(method)\n end", "def destroy\n\t\t@auto_scaling_trigger = AutoScalingTrigger.find(params[:id], :include => [ :auto_scaling_group ])\n\t\t@auto_scaling_group = @auto_scaling_trigger.auto_scaling_group\n\t\tredirect_url = provider_account_path(@auto_scaling_group.provider_account_id, :anchor => :auto_scaling)\n\n\t\t@error_messages = []\n @auto_scaling_trigger.destroy\n\t\t@error_messages += @auto_scaling_trigger.errors.collect{ |attr,msg| \"#{attr.humanize} - #{msg}\" }\n\n respond_to do |format|\n\t\t\tif @error_messages.empty?\n\t\t\t\tp = @auto_scaling_group\n\t\t\t\to = @auto_scaling_trigger\n\t\t\t\tAuditLog.create_for_parent(\n\t\t\t\t\t:parent => p,\n\t\t\t\t\t:auditable_id => nil,\n\t\t\t\t\t:auditable_type => o.class.to_s,\n\t\t\t\t\t:auditable_name => o.name,\n\t\t\t\t\t:author_login => current_user.login,\n\t\t\t\t\t:author_id => current_user.id,\n\t\t\t\t\t:summary => \"deleted '#{o.name}'\",\n\t\t\t\t\t:changes => o.tracked_changes,\n\t\t\t\t\t:force => true\n\t\t\t\t)\n\t\t\telse\n\t\t\t\tflash[:error] = @error_messages.join('<br/>')\n\t\t\tend\n format.html { redirect_to redirect_url }\n format.xml { head :ok }\n format.js\n end\n end", "def delete_group \n Group.destroy(params[:id])\n\n respond_to do |format|\n format.html {redirect_to dashboard_path}\n end\n end", "def remove_auto_scaling_group_properties\n properties = []\n properties << :AvailabilityZones\n properties << :HealthCheckGracePeriod\n properties << :HealthCheckType\n add_patch Patches::RemoveProperty.new 'AWS::AutoScaling::AutoScalingGroup', properties\n end", "def delete_group(group)\n\t\t\t\tgroupname = nil\n\t\t\t\tif(group.respond_to(:groupname))\n\t\t\t\t\tgroupname = group.groupname\n\t\t\t\telse\n\t\t\t\t\tgroupname = group\n\t\t\t\tend\n\n\t\t\t\t`pw groupdel #{groupname}`\n\t\t\tend", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def delete!\n delete(:force => true)\n nil\n end", "def delete_group(group_id)\n current_path = \"/api/v1/groups/#{group_id}\"\n @conn.delete(current_path)\n end", "def destroy\n Log.create! description: \"<b>#{current_user.email} </b> deleted group <b>#{@group.name} </b> at #{Time.zone.now.strftime '%d-%m-%Y %H:%M:%S'}\", role_id: current_user.roles.ids.first\n @group.destroy\n respond_to do |format|\n format.html { redirect_to groups_url, notice: 'Group was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @alien_group.destroy\n respond_to do |format|\n format.html { redirect_to alien_groups_url, notice: 'Alien group was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy_group_with_extension\n # INFO: currently only a superuser can destroy a group. See CartoDB/cartodb-postgresql#114\n organization.owner.in_database(as: :superuser) do |conn|\n Carto::Group.destroy_group_extension_query(conn, name)\n end\n end", "def destroy\n group = Group.find(params[:id])\n group.destroy\n render json: {}\n end", "def destroy\n @ail_group = AilGroup.find(params[:id])\n @ail_group.destroy\n\n respond_to do |format|\n format.html { redirect_to(ail_groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to groups_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to groups_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to groups_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to groups_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to groups_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to groups_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exam_group = ExamGroup.shod(params[:id])\n authorize! :delete, @exam_group\n batch = @exam_group.batch\n @exam_group.destroy\n flash[:notice] = 'Exam Group deleted successfully!'\n redirect_to exam_group_path(batch)\n end", "def destroy\n @group = Group.find_by_slug_or_id(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.json { head :ok }\n end\n end", "def destroy\n @current_user.quit_group(@group)\n respond_to do |format|\n format.html { redirect_to groups_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @resource_group.destroy\n respond_to do |format|\n format.html { redirect_to resource_groups_url, notice: 'Resource group was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @group.destroy\n audit(@group, \"destroy\", @group.name )\n respond_to do |format|\n format.html { redirect_to groups_path, notice: 'Group was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @group.destroy\n respond_to do |format|\n format.html { redirect_to admin_groups_url, notice: t('activerecord.models.group') +'删除成功!' }\n format.json { head :no_content }\n end\n end", "def destroy\n Group.destroy(params[:id])\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to groups_url }\n format.json { head :ok }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to groups_url }\n format.json { head :ok }\n end\n end", "def delete_group(group_id)\n @api.delete(\"#{@api.path}/List/#{@id}/Group/#{group_id}\")\n end", "def delete_db_parameter_group(group_name)\n request({\n 'Action' => 'DeleteDBParameterGroup',\n 'DBParameterGroupName' => group_name,\n\n :parser => Fog::Parsers::AWS::RDS::DeleteDbParameterGroup.new\n })\n end", "def delete force: false\n clear! if force\n\n ensure_service!\n service.delete_zone id\n true\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to groups_url }\n format.json { head :ok }\n format.xml { head :ok }\n end\n end", "def delete(group)\n url = build_url(group)\n response = rest_delete(url)\n response.return!\n end", "def delete\n client_opts = {}\n client_opts[:scheduled_action_name] = name\n client_opts[:auto_scaling_group_name] = auto_scaling_group_name\n client.delete_scheduled_action(client_opts)\n nil\n end", "def destroy\n @meta_data_group = MetaDataGroup.find(params[:id])\n @meta_data_group.destroy\n\n respond_to do |format|\n format.html { redirect_to meta_data_groups_url }\n format.json { head :no_content }\n end\n end", "def destroy\n begin\n @user_group.destroy!\n rescue => e\n flash['error'] = \"#{e}\"\n else\n toast!(title: \"User group deleted\",\n message: \"The user group \\\"#{@user_group.name}\\\" has been deleted.\")\n ensure\n redirect_to user_groups_path\n end\n end", "def delete(key)\n key = to_key key\n @group.delete key if @group.key? key\n end", "def delete_group(group_id)\n\t\tself.group_list.delete(group_id)\n\t\tself.update_attribute(:group_list, self.group_list)\n\tend", "def destroy\n qg_id = params[:id]\n question_group = QuestionGroup.find(qg_id)\n qg_parent_id = question_group.parent_id\n # prevent deletion of root question group or parent-less group\n if qg_id != 1 and !qg_parent_id.nil? and question_group.destroy\n orphan_questions = Question.where('question_group_id = ?', qg_id)\n orphan_questions.update_all(question_group_id: qg_parent_id)\n render status: 200, json: {}\n else\n render status: 400, json: {}\n end\n end", "def delete_db_parameter_group( options = {} )\n raise ArgumentError, \"No :db_parameter_group_name provided\" if options.does_not_have?(:db_parameter_group_name)\n\n params = {}\n params['DBParameterGroupName'] = options[:db_parameter_group_name]\n\n return response_generator(:action => \"DeleteDBParameterGroup\", :params => params)\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n flash[:success] = \"Группа успешно удалена.\"\n format.html { redirect_to groups_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @group.destroy unless @group.default\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = @course.groups.find(params[:id])\n @group.destroy\n respond_to do |format|\n format.html { redirect_to groups_url, notice: 'Group was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete()\n\n client.delete(\"/tags/#{gid}\") && true\n end", "def empty_group(group, opts)\n # unlink all resources from this group\n group.empty_group\n end", "def delete_security_group(group_id)\n return if group_id.nil? || !configured?\n\n @client.delete_security_group(group_id: group_id)\n end", "def destroy\n begin\n group = Group.find(params[:id])\n group.destroy\n render json: { \"notice\"=>\"group deleted successfully\" }\n rescue ActiveRecord::RecordNotFound\n render json: { \"alert\"=>\"did not specify a valid id. no record deleted.\" }\n end\n end" ]
[ "0.832787", "0.6831928", "0.6784633", "0.6649838", "0.6626339", "0.6558953", "0.6490728", "0.63120383", "0.63002646", "0.6284608", "0.62440556", "0.62024176", "0.6190439", "0.6184121", "0.617778", "0.617778", "0.6126916", "0.6113461", "0.6077973", "0.6064484", "0.60430795", "0.60409075", "0.60409075", "0.60281104", "0.59918773", "0.5984195", "0.5956436", "0.5955417", "0.59510386", "0.5950425", "0.59380585", "0.59354544", "0.59178466", "0.5911586", "0.59053004", "0.58980477", "0.5895813", "0.5880292", "0.5866502", "0.5856448", "0.5849581", "0.58361226", "0.5825833", "0.5821422", "0.5821422", "0.5820125", "0.5796176", "0.5787804", "0.57849693", "0.5776784", "0.57709694", "0.5762508", "0.5762508", "0.5762508", "0.5762508", "0.5762508", "0.5762508", "0.5762508", "0.5762508", "0.5756144", "0.5748562", "0.5743809", "0.5743054", "0.5737188", "0.5733403", "0.57317215", "0.57313", "0.57313", "0.57313", "0.57313", "0.57313", "0.57313", "0.5725937", "0.5711934", "0.5706225", "0.57045233", "0.570311", "0.5701898", "0.5697508", "0.56936294", "0.56936294", "0.56799716", "0.5678982", "0.56789196", "0.5670479", "0.56690633", "0.56658155", "0.5661057", "0.5653508", "0.56522936", "0.56413037", "0.5633351", "0.5633213", "0.56298256", "0.56272805", "0.56226385", "0.56022173", "0.5600757", "0.55978215", "0.559264" ]
0.81559837
1
Deletes the Auto Scaling group along with all instances associated with the group, without waiting for all instances to be terminated.
def delete! delete(:force => true) nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy(options = { :force => false })\n requires :id\n\n opts = {}\n opts.merge!({'ForceDelete' => true}) if options[:force]\n\n service.delete_auto_scaling_group(id, opts)\n end", "def terminate\n logger.info \"Terminating any instance with GroupUUID: #{@os_aws.group_uuid}\"\n\n terminate_instances_by_group_id(@os_aws.group_uuid)\n end", "def perform_destroy\n api.group_destroy(self)\n end", "def delete options = {}\n client_opts = {}\n client_opts[:force_delete] = options[:force] == true\n client_opts[:auto_scaling_group_name] = name\n client.delete_auto_scaling_group(client_opts)\n nil\n end", "def destroy\n start = Time.now\n debug(\"Deleting device group: \\\"#{resource[:full_path]}\\\"\")\n connection = self.class.get_connection(resource[:account])\n device_group = get_device_group(connection, resource[:full_path], 'id')\n if device_group\n delete_device_group = rest(connection,\n Puppet::Provider::Logicmonitor::DEVICE_GROUP_ENDPOINT % device_group['id'],\n Puppet::Provider::Logicmonitor::HTTP_DELETE)\n valid_api_response?(delete_device_group) ? nil : alert(delete_device_group)\n end\n debug \"Finished in #{(Time.now-start)*1000.0} ms\"\n end", "def purge (group)\n ensure_group(group).purge\n end", "def destroy\n Group.delete_groups_and_acls([id])\n end", "def stop\n puts \"Stoping any instance with group ID: #{@os_aws.group_uuid}\"\n\n stop_instances_by_group_id(@os_aws.group_uuid)\n end", "def delete_resource_group(group_name)\n cmdline = Schott::AzureCLI::Commandlines.delete_resource_group(group_name)\n sh(cmdline)\n end", "def delete_asg name\n auto_scaling = new_auto_scaling\n groups = auto_scaling.groups\n raise \"unable to delete asg, #{name}. asg not found!\" if groups[name].nil? \n\n asg = groups[name]\n\n puts \"deleting asg, #{asg.name}\"\n asg.delete({:force => true})\n delete_launch_configs\nend", "def terminate_instance_in_auto_scaling_group(instance_id, should_decrement_desired_capacity)\n request({\n 'Action' => 'TerminateInstanceInAutoScalingGroup',\n 'InstanceId' => instance_id,\n 'ShouldDecrementDesiredCapacity' => should_decrement_desired_capacity.to_s,\n :parser => Fog::Parsers::AWS::AutoScaling::TerminateInstanceInAutoScalingGroup.new\n })\n end", "def destroy\n @group.destroy\n msg = [\"Destroyed group.\", rebuild_configs].join(\" \")\n redirect_to groups_url, notice: msg\n end", "def destroy\n @client.resource_groups.delete(@resource_group)\n end", "def destroy_google_group\n result = Gandalf::GoogleApiClient.delete_google_group(self.apps_id)\n result.data\n end", "def delete_group(uuid)\n Uploadcare::Group.delete(uuid)\n end", "def destroy \n ec2 = self.class.new_ec2(@resource.value(:user), @resource.value(:password))\n ec2.terminate_instances({:instance_id => @property_hash[:instance_id]})\n ec2.delete_security_group({:group_name => @resource.value(:name)})\n end", "def terminate_instances_by_group_id(group_id)\n raise 'Group ID not defined' unless group_id\n\n instances = @os_aws.describe_running_instances(group_id)\n logger.info instances\n ids = instances.map { |k, _| k[:instance_id] }\n\n logger.info \"Terminating the following instances #{ids}\"\n resp = []\n resp = @os_aws.terminate_instances(ids).to_hash unless ids.empty?\n\n resp[:terminating_instances].first[:current_state][:name] == 'shutting-down'\n end", "def destroy(name, &each_group)\n list(name, &each_group) if each_group\n ret = @@ec2.delete_security_group(:group_name => name)\n (ret && ret['return'] == 'true')\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def terminate_instances\n @task.unsafe(\"Stopping #{@name} Launch process\") do\n autoscaling_group.suspend_processes('Launch')\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Terminating instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.terminate\n end\n end\n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n # FIXME: This won't work if we reinstate suspended processes...\n #if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n #else\n #@task.debug { \"Scaling group #{@name} already suspended\" }\n #end\n end", "def remove_group(group)\n self.groups.destroy group \n end", "def stop(action)\n if !autoscaling_group.exists?\n @task.warn { \"Autoscaling group #{@name} doesn't exist\" }\n return\n end\n\n if autoscaling_group.suspended_processes.empty?\n case action\n when :default, :terminate\n terminate_instances\n when :stop\n stop_instances\n else\n raise Cloud::Cycler::TaskFailure.new(\"Unrecognised autoscaling action #{action}\")\n end\n else\n @task.debug { \"Scaling group #{@name} already suspended\" }\n end\n end", "def delete(name)\n return unless resource_group?(name)\n\n info \"deleting the resource group: #{name}\"\n @client.resource_groups.delete(name, name)\n end", "def empty_group(group, opts)\n # unlink all resources from this group\n group.empty_group\n end", "def delete_old_asg config, launch_config_name\n auto_scaling = new_auto_scaling\n auto_scaling.groups.each do |group|\n server = tag_value(group.tags, \"server\")\n if server != config[\"server\"]\n next \n end\n\n env = tag_value(group.tags, \"env\")\n if env != config[\"env\"]\n next \n end\n\n if group.name != launch_config_name.name\n puts \"deleting instance group, #{group.name} => #{launch_config_name.name}\"\n delete_asg group.name\n end\n end\nend", "def delete_group(group)\n\t\t\tend", "def delete_group(group)\n\t\t\tend", "def delete_app_group(group,app)\n\t\t\tresults = submit_cmd('delete app group',:db,\" -env #{self.env} -domain #{self.domain} -plant #{self.plant} -group #{group} -app_instance #{app}\")\n\t\t\tputs results\n\tend", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n redirect_to groups_path\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n redirect_to groups_path\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def destroy\n @auth_ip_address_group.destroy\n head :no_content\n end", "def destroy\n @exam_group = ExamGroup.shod(params[:id])\n authorize! :delete, @exam_group\n batch = @exam_group.batch\n @exam_group.destroy\n flash[:notice] = 'Exam Group deleted successfully!'\n redirect_to exam_group_path(batch)\n end", "def delete_group\r\n if request.post?\r\n @group=Group.find_by_id(params[:id], :conditions=>['account_id = ?',session[:account_id]])\r\n if @group.nil?\r\n flash[:error] = \"Invalid action.\"\r\n else\r\n flash[:success]= \"Group \" + @group.name + \" was deleted successfully \"\r\n @group.destroy\r\n @group_devices = Device.find(:all, :conditions=>['group_id=?',@group.id])\r\n for device in @group_devices\r\n device.icon_id =\"1\"\r\n device.group_id = nil\r\n device.save\r\n end\r\n end\r\n end\r\n redirect_to :action=>\"groups\"\r\n end", "def destroy #:nodoc:\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to groups_url }\n # format.xml { head :ok }\n end\n end", "def stop_instances\n @task.unsafe(\"Stopping #{@name} processes\") do\n save_to_s3(@task.bucket)\n autoscaling_group.suspend_all_processes\n end\n autoscaling_instances.each do |instance|\n @task.unsafe(\"Stopping instance #{instance.instance_id}\") do\n load_balancers.each do |elb|\n elb.instances.deregister(instance.instance_id)\n end\n instance.ec2_instance.stop\n end\n end\n end", "def group_destroy(group)\n if(group.persisted?)\n request(\n :path => \"/groups/#{group.id}\",\n :method => :delete,\n :expects => 204\n )\n true\n else\n false\n end\n end", "def empty_group\n self.group_memberships.each {|m| m.destroy}\n end", "def destroy\n @group.destroy\n\n head :no_content\n end", "def delete_group(id)\n delete(\"groups/#{id}\")\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n head :no_content\n end", "def dissolve_groups\n groups.destroy_all\n end", "def destroy\n Log.create! description: \"<b>#{current_user.email} </b> deleted group <b>#{@group.name} </b> at #{Time.zone.now.strftime '%d-%m-%Y %H:%M:%S'}\", role_id: current_user.roles.ids.first\n @group.destroy\n respond_to do |format|\n format.html { redirect_to groups_url, notice: 'Group was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n stop\n [ @resource['instances_dir'] + \"/\" + @resource[:name],\n @resource['instances_dir'] + \"/\" + \"_\" + @resource[:name]\n ].each do |dir|\n FileUtils.rm_rf(dir) if File.directory?(dir)\n end\n end", "def remove_from_group(group)\n self.memberships.find_by(group_id: group.id).destroy!\n end", "def remove_instance(params)\n Fog::Logger.deprecation(\n \"#{self.class}.#{__method__} is deprecated, use Fog::Compute::Google::InstanceGroup.#{__method__} instead [light_black](#{caller(0..0)})[/]\"\n )\n params[:instance] = [params[:instance]] unless params[:instance] == Array\n service.remove_instance_group_instances(params[:group], params[:zone], params[:instance])\n end", "def destroy\n Group.rebuild! if nil.|Group.find(:first).rgt\n\t @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n return access_denied unless is_admin?(current_user)\n\n @group = Group.find(params[:id])\n @group.destroy\n redirect_to(groups_url)\n end", "def destroy\n @group.destroy\n redirect_to groups_url, notice: \"Group was successfully destroyed.\" \n end", "def destroy\n\t\t@auto_scaling_trigger = AutoScalingTrigger.find(params[:id], :include => [ :auto_scaling_group ])\n\t\t@auto_scaling_group = @auto_scaling_trigger.auto_scaling_group\n\t\tredirect_url = provider_account_path(@auto_scaling_group.provider_account_id, :anchor => :auto_scaling)\n\n\t\t@error_messages = []\n @auto_scaling_trigger.destroy\n\t\t@error_messages += @auto_scaling_trigger.errors.collect{ |attr,msg| \"#{attr.humanize} - #{msg}\" }\n\n respond_to do |format|\n\t\t\tif @error_messages.empty?\n\t\t\t\tp = @auto_scaling_group\n\t\t\t\to = @auto_scaling_trigger\n\t\t\t\tAuditLog.create_for_parent(\n\t\t\t\t\t:parent => p,\n\t\t\t\t\t:auditable_id => nil,\n\t\t\t\t\t:auditable_type => o.class.to_s,\n\t\t\t\t\t:auditable_name => o.name,\n\t\t\t\t\t:author_login => current_user.login,\n\t\t\t\t\t:author_id => current_user.id,\n\t\t\t\t\t:summary => \"deleted '#{o.name}'\",\n\t\t\t\t\t:changes => o.tracked_changes,\n\t\t\t\t\t:force => true\n\t\t\t\t)\n\t\t\telse\n\t\t\t\tflash[:error] = @error_messages.join('<br/>')\n\t\t\tend\n format.html { redirect_to redirect_url }\n format.xml { head :ok }\n format.js\n end\n end", "def destroy\n @group = Group.find_by_param(params[:id])\n @group.tuners.clear\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy_group(name)\n response = Curl.delete(azure_face_uri << name) do |http|\n http.headers[\"Ocp-Apim-Subscription-Key\"] = key\n end\n response.body_str\n end", "def DeleteGroup id\n \n APICall(path: \"groups/#{id}.json\",method: 'DELETE')\n \n end", "def delete_group(group_id)\n current_path = \"/api/v1/groups/#{group_id}\"\n @conn.delete(current_path)\n end", "def remove_group\n create_group.tap do |r|\n r.action(:remove)\n end\n end", "def delete_group(group_id)\n\t\tself.group_list.delete(group_id)\n\t\tself.update_attribute(:group_list, self.group_list)\n\tend", "def delete(group)\n @queue[group.depth].delete(group)\n end", "def destroy\n @group.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def delete_instances(count)\n instances_to_delete = current_instances.last(count) \n parent.terminate_instances(Group.instance_ids(instances_to_delete))\n # remaining_instances under alive\n Output.new(current_instances.first(current_instances.size - count), instances_to_delete)\n end", "def destroy\n\n\t\t@group = Group.find(params[:id])\n\t\t@group.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(groups_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend", "def destroy\n @group.destroy\n audit(@group, \"destroy\", @group.name )\n respond_to do |format|\n format.html { redirect_to groups_path, notice: 'Group was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_groups_url) }\n format.xml { head :ok }\n end\n end", "def remove_from_all_groups\n self.group_memberships.each {|m| m.destroy}\n end", "def destroy\n @attribute_group = AttributeGroup.find(params[:id])\n @attribute_group.destroy\n\n respond_to do |format|\n format.html { redirect_to(attribute_groups_url) }\n format.xml { head :ok }\n end\n end", "def delete_group(group)\n\t\t\t\tgroupname = nil\n\t\t\t\tif(group.respond_to(:groupname))\n\t\t\t\t\tgroupname = group.groupname\n\t\t\t\telse\n\t\t\t\t\tgroupname = group\n\t\t\t\tend\n\n\t\t\t\t`pw groupdel #{groupname}`\n\t\t\tend", "def destroy\n begin\n @user_group.destroy!\n rescue => e\n flash['error'] = \"#{e}\"\n else\n toast!(title: \"User group deleted\",\n message: \"The user group \\\"#{@user_group.name}\\\" has been deleted.\")\n ensure\n redirect_to user_groups_path\n end\n end", "def destroy\n qg_id = params[:id]\n question_group = QuestionGroup.find(qg_id)\n qg_parent_id = question_group.parent_id\n # prevent deletion of root question group or parent-less group\n if qg_id != 1 and !qg_parent_id.nil? and question_group.destroy\n orphan_questions = Question.where('question_group_id = ?', qg_id)\n orphan_questions.update_all(question_group_id: qg_parent_id)\n render status: 200, json: {}\n else\n render status: 400, json: {}\n end\n end", "def shutdown()\n \n #shutdown all the instances we have.\n ids = id()\n \n @ec2.terminate_instances(ids)\n \n # wait for them to shut down for a couple of minutes\n attempts = 0\n stats = state_code()\n while (stats.any? {|s| s<=16 }) do\n if attempts > 6 \n raise CaTPAWS::EC2::Error::InstanceShutdown, \"Instances still running after a long wait. Check your EC2 account manually?\"\n end\n puts \"Terminating instances, please wait...\"\n sleep(10)\n attempts+=1\n get_instances(true)\n stats = state_code()\n end\n \n #and delete the associated security group\n @ec2.delete_security_group(@group_name)\n \n end", "def delete(key)\n key = to_key key\n @group.delete key if @group.key? key\n end", "def remove_auto_scaling_group_properties\n properties = []\n properties << :AvailabilityZones\n properties << :HealthCheckGracePeriod\n properties << :HealthCheckType\n add_patch Patches::RemoveProperty.new 'AWS::AutoScaling::AutoScalingGroup', properties\n end", "def remove_all\n @jobs.each do |job|\n job.unschedule\n end\n @@instances.delete self\n end", "def delete_group(group_id)\n @api.delete(\"#{@api.path}/List/#{@id}/Group/#{group_id}\")\n end", "def delete_db_parameter_group(group_name)\n request({\n 'Action' => 'DeleteDBParameterGroup',\n 'DBParameterGroupName' => group_name,\n\n :parser => Fog::Parsers::AWS::RDS::DeleteDbParameterGroup.new\n })\n end", "def stop_instances_by_group_id(group_id)\n instances = @os_aws.describe_running_instances(group_id)\n ids = instances.map { |k, _| k[:instance_id] }\n\n puts \"Stoping the following instances #{ids}\"\n resp = []\n resp = @os_aws.stop_instances(ids).to_hash unless ids.empty?\n resp\n end", "def destroy\n @group = Group.find(params[:id])\n @group.destroy\n \n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @group = GROUP.first_or_get(params[:id])\n @group.current_user = current_user\n @group.destroy if @group\n\n respond_to do |format|\n flash[:notice] = 'Group was successfully deleted.'\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @ail_group = AilGroup.find(params[:id])\n @ail_group.destroy\n\n respond_to do |format|\n format.html { redirect_to(ail_groups_url) }\n format.xml { head :ok }\n end\n end", "def auto_scaling_group(group_name)\n AutoScalingGroup.new(group_name)\n end", "def delete(group)\n url = build_url(group)\n response = rest_delete(url)\n response.return!\n end", "def cleanup()\n attempts = @options[:timeout].to_i / SLEEPWAIT\n start = Time.now\n\n @gce_helper.delete_firewall(@firewall, start, attempts)\n\n @hosts.each do |host|\n @gce_helper.delete_instance(host['vmhostname'], start, attempts)\n @logger.debug(\"Deleted Google Compute instance #{host['vmhostname']} for #{host.name}\")\n @gce_helper.delete_disk(host['diskname'], start, attempts)\n @logger.debug(\"Deleted Google Compute disk #{host['diskname']} for #{host.name}\")\n end\n\n end", "def destroy\n @current_user.quit_group(@group)\n respond_to do |format|\n format.html { redirect_to groups_path }\n format.json { head :no_content }\n end\n end", "def deletesecuritygroup\n if not checkRequirements([\"thezone\",\"thefirewall\"])\n return false\n end\n checkToken(@thezone)\n submit = queryGCE(:path => '/compute/v1beta15/projects/#{@thezone.name}/global/firewalls/#{@thefirewall.serial}', :method => 'delete', :options => '', :acces_token => @thezone.token )\n checkQuery(:type => 'global', :token => @thezone.token, :projectname => @thezone.name, :operationname => submit[\"name\"])\n end", "def destroy_deploy_groups_stages\n DeployGroupsStage.where(stage_id: id).delete_all\n end", "def leave(group)\n group_membership_ids.include? group.id\n groups.destroy(group)\n end", "def remove_group\n group = current_account.groups.of_devices.find(params[:group_id])\n\n group.devices.delete(current_account.devices.find(params[:apply_ids].split(\",\")))\n\n redirect_to devices_path\n end", "def delete_launch_configs\n auto_scaling = new_auto_scaling\n groups = auto_scaling.groups\n auto_scaling.launch_configurations.each do |config|\n if groups[config.name].nil?\n puts \"deleting asg launch configuration, #{config.name}\"\n config.delete()\n end\n end\nend", "def destroy\n group = Group.find(params[:id])\n group.destroy\n render json: {}\n end", "def destroy\n\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n\n @group = Group.find(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @aws_security_group_egress.destroy\n respond_to do |format|\n format.html { redirect_to aws_security_group_egresses_url, notice: 'Aws security group egress was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(group_id)\n if expired?(@begin_time)\n @auth = get_auth(@api_key)\n end\n Log.debug(\"#{@base_url}#{@get_post_delete_url}#{group_id}\")\n user_group = RestClient.delete \"#{@base_url}#{@get_post_delete_url}#{group_id}\", header\n end", "def delete_security_group( options = {} )\n options = { :group_name => \"\" }.merge(options)\n raise ArgumentError, \"No :group_name provided\" if options[:group_name].nil? || options[:group_name].empty?\n params = { \"GroupName\" => options[:group_name] }\n return response_generator(:action => \"DeleteSecurityGroup\", :params => params)\n end", "def delete_group \n Group.destroy(params[:id])\n\n respond_to do |format|\n format.html {redirect_to dashboard_path}\n end\n end", "def delete_all_node_groups\n delete_node_group_descendents(get_node_group(Rootuuid))\n end", "def delete_security_group(group_id)\n return if group_id.nil? || !configured?\n\n @client.delete_security_group(group_id: group_id)\n end", "def destroy\n @tasks_group.remove\n respond_to do |format|\n format.html { redirect_to tasks_groups_url, notice: 'Tasks group was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @group = Group.find_by_slug_or_id(params[:id])\n @group.destroy\n\n respond_to do |format|\n format.html { redirect_to(groups_url) }\n format.json { head :ok }\n end\n end", "def destroy\n if !self.insurance_sessions.blank?\n #check insurance session. If there is an insurance billng, then there must be a session.\n errors.add :base, \"The Group is associated to a session and/or claim. Group cannot be deleted\"\n else\n run_callbacks :destroy do\n self.update_column(:deleted, true)\n end\n end\n end", "def destroy_group_with_extension\n # INFO: currently only a superuser can destroy a group. See CartoDB/cartodb-postgresql#114\n organization.owner.in_database(as: :superuser) do |conn|\n Carto::Group.destroy_group_extension_query(conn, name)\n end\n end", "def delete\n client_opts = {}\n client_opts[:scheduled_action_name] = name\n client_opts[:auto_scaling_group_name] = auto_scaling_group_name\n client.delete_scheduled_action(client_opts)\n nil\n end" ]
[ "0.75265706", "0.7299891", "0.7165831", "0.7107583", "0.69403", "0.6890642", "0.6865347", "0.6856157", "0.6821598", "0.6815385", "0.67711204", "0.67091054", "0.6669437", "0.66642505", "0.6640211", "0.6591473", "0.6535158", "0.65344995", "0.65167373", "0.65167373", "0.6505168", "0.64388657", "0.6432007", "0.6338215", "0.6334158", "0.62845016", "0.6284443", "0.6284443", "0.62712294", "0.6213203", "0.6213203", "0.61551327", "0.6153158", "0.61305416", "0.61189264", "0.6109881", "0.6107085", "0.61058474", "0.61024857", "0.6096447", "0.6057844", "0.60472333", "0.6036634", "0.60316217", "0.602571", "0.6012509", "0.6006618", "0.5988155", "0.59865457", "0.5976104", "0.597445", "0.5971698", "0.5970181", "0.596729", "0.5966933", "0.5964661", "0.5957642", "0.5955874", "0.5955722", "0.5955154", "0.5949744", "0.59440273", "0.59389573", "0.589186", "0.58859485", "0.5883572", "0.586764", "0.5865477", "0.5861027", "0.5859235", "0.5856384", "0.5846678", "0.5845849", "0.5837631", "0.5833744", "0.58323425", "0.58211094", "0.580827", "0.58071506", "0.5802137", "0.5794187", "0.5794184", "0.5791533", "0.57905716", "0.5783929", "0.5779029", "0.5776091", "0.5774316", "0.57661146", "0.57661146", "0.5763867", "0.5762509", "0.5760503", "0.57553625", "0.5740618", "0.573684", "0.5729287", "0.5725611", "0.5720477", "0.5719439", "0.5714765" ]
0.0
-1
GET /course_proposal_questions GET /course_proposal_questions.json
def index @course_proposal_questions = CourseProposalQuestion.all end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def questions\n self.class.get(\"/2.2/questions\", @options)\n end", "def index\n params.require(:course)\n @questions = Course.find(params[:course]).questions.select {|q| q.answered == false}\n\n render json: @questions\n end", "def index\n @questions = @course.questions.all\n end", "def index\n @questions = @course.questions.all\n end", "def set_course_proposal_question\n @course_proposal_question = CourseProposalQuestion.find(params[:id])\n end", "def course_proposal_question_params\n params.require(:course_proposal_question).permit(:question, :help_text)\n end", "def index\n @proposals = Proposal.all\n\n render json: @proposals\n end", "def destroy\n @course_proposal_question.destroy\n respond_to do |format|\n format.html { redirect_to course_proposal_questions_url, notice: 'Course proposal question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def create\n @course_proposal_question = CourseProposalQuestion.new(course_proposal_question_params)\n\n respond_to do |format|\n if @course_proposal_question.save\n format.html { redirect_to @course_proposal_question, notice: 'Course proposal question was successfully created.' }\n format.json { render :show, status: :created, location: @course_proposal_question }\n else\n format.html { render :new }\n format.json { render json: @course_proposal_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @questions = @questionable.questions\n end", "def index\n @questions = @subsection.questions.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @questions }\n end\n end", "def get_questions\n result = QuizQuestion.includes(:quiz_answers).where(quiz_id: params[:id])\n\n @questions = result.map { |question| QuestionPresenter.new(question) }\n end", "def questions\n # Get a list of questionnaires that belong to instances of the current race\n if @course\n questionnaire_ids = @course.questionnaire_ids\n elsif @instance\n questionnaire_ids = @instance.questionnaire_ids\n else\n questionnaire_ids = []\n end\n\n # Collect question_ids that are used in those questionnaires\n question_ids = Set.new\n Questionnaire.where(:id => questionnaire_ids).find_each do |questionnaire|\n question_ids.merge(questionnaire.question_ids)\n end\n\n @questions = Question.find(question_ids.to_a)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @questions.to_json }\n end\n end", "def responses\n @proposal = current_user.proposals.find(params[:id])\n @responses = @proposal.responses\n\n respond_to do |format|\n format.html # responses.html.erb\n format.xml { render :xml => @responses }\n end\n end", "def list_questions_in_quiz(course_id,quiz_id,opts={})\n query_param_keys = [\n \n ]\n\n form_param_keys = [\n \n ]\n\n # verify existence of params\n raise \"course_id is required\" if course_id.nil?\n raise \"quiz_id is required\" if quiz_id.nil?\n # set default values and merge with input\n options = underscored_merge_opts(opts,\n :course_id => course_id,\n :quiz_id => quiz_id\n )\n\n # resource path\n path = path_replace(\"/v1/courses/{course_id}/quizzes/{quiz_id}/questions\",\n :course_id => course_id,\n :quiz_id => quiz_id)\n headers = nil\n form_params = select_params(options, form_param_keys)\n query_params = select_params(options, query_param_keys)\n if opts[:next_page]\n pagination_params = page_params_load(:get, path)\n query_params.merge! pagination_params if pagination_params\n end\n response = mixed_request(:get, path, query_params, form_params, headers)\n page_params_store(:get, path)\n response.map {|response|QuizQuestion.new(response)}\n end", "def questions\n return @questions\n end", "def get_forms\n @course = Course.find(params[:course_id])\n @forms = @course.professor_forms\n render json: @forms\n end", "def check_questions\n response = Request.get_request(URL_QUESTION)\n questions = []\n if response.success?\n data = Request.manage_response(response)\n end\n data.each do |question|\n questions << Question.new(question)\n end\n questions\nend", "def index\n @questions = Question.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @questions }\n end\n end", "def index\n @questions = Question.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @questions }\n end\n end", "def get_exam_section_questions(user_id, course_id, exam_id, section_id)\r\n relative_url = Path::USERS_COURSES_EXAMS_SECTIONS_QUESTIONS % [user_id,\r\n course_id, exam_id, section_id]\r\n response = get(relative_url)\r\n if !response.error?\r\n json_obj = JSON::parse(response.content)\r\n questions = json_obj['questions'] || []\r\n section_questions = []\r\n questions.each do |question|\r\n question_type = question['type']\r\n question_id = question['id']\r\n question_response = get_exam_section_question(user_id, course_id,\r\n exam_id, section_id,\r\n question_type, question_id)\r\n return question_response if question_response.error?\r\n\r\n section_question = JSON.parse(question_response.content)\r\n\t\t section_question['id'] = question_id\r\n section_question['type'] = question_type\t\t \r\n\t\t section_question['pointsPossible'] = question['pointsPossible']\r\n section_questions << section_question\r\n end\r\n\r\n response.content = { 'questions' => section_questions }.to_json\r\n end\r\n\r\n response\r\n end", "def quiz_questions\n @questions = set_quiz.questions\n end", "def index\n @course = Course.find(params[:course_id])\n @questions = @course.questions.current.due + @course.questions.current.pending.find(:all, :order => :next_datetime, :limit => 200)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @questions }\n end\n end", "def show\n @question_category = QuestionCategory.with_questions(question_category_id: params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @question_category }\n end\n end", "def index\n @question_categories = QuestionCategory.with_questions()\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @question_categories }\n end\n end", "def index\n @proposals = current_user.proposals\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @proposals }\n end\n end", "def get_question_list\n json= RestClient.get(\"http://localhost:3000/questions\")\n JSON.parse(json)\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @proposal }\n end\n end", "def show\n @proposal = Proposal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @proposal }\n end\n end", "def show\n @proposal = Proposal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @proposal }\n end\n end", "def questions\n @root.questions\n end", "def show\n @questions = Question.all\n end", "def index\n render status: :ok, json: @simple_question_alternatives\n end", "def index\n @proposals = Proposal.all()\n end", "def questions\n @pages.collect { |p| p.questions }.flatten\n end", "def show\n @questions = Question.find(params[:id])\n end", "def questions\n return Question.none unless committee && user\n Question.joins(:quiz_questions).\n where { |r| r.quiz_questions.quiz_id.in( \n committee.requestable_positions.\n with_statuses_mask( user.statuses_mask ).\n select { quiz_id } ) }.\n order { [ quiz_questions.quiz_id, quiz_questions.position ] }\n end", "def show\n @critical_question = CriticalQuestion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @critical_question }\n end\n end", "def questions\r\n return @questions \r\nend", "def index\n @survey_questions = get_survey_questions\n end", "def index\n @survey_questions = get_survey_questions\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def prebooking_questions\n\n # this is a patch\n if @url.blank? or @token.blank?\n return []\n end\n\n [\n {\n question: \"How many guests will be riding with you?\", \n choices: [0,1,2,3], \n code: \"guests\"\n },\n {\n question: \"How many attendants will be riding with you?\", \n choices: [0,1,2,3], \n code: \"attendants\"\n },\n {\n question: \"How many mobility devices will you be bringing?\", \n choices: [0,1,2,3], \n code: \"mobility_devices\"\n },\n {\n question: \"What is your trip purpose?\", \n choices: (trip_purposes[\"trip_purposes\"] || \n Config.ride_pilot_purposes.try(:map) {|k,v| {\"name\" => k, \"code\" => v}} || \n []).map{|p| [p[\"name\"], p[\"code\"]]}, \n code: \"purpose\"\n }\n ]\n end", "def show\n @questions_option = QuestionsOption.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @questions_option }\n end\n end", "def index\n @parts_for_proposal = PartsForProposal.all\n end", "def get_questions\n items = get_items\n make_response(HttpStatus::OK, make_result_list(items))\nend", "def index\n #@courses = @curriculum.courses\n\n @courses = ScopedCourse.where(:curriculum_id => @curriculum.id)\n .joins(:course_descriptions)\n .where([\"course_descriptions.locale = ?\", I18n.locale]).includes(:strict_prereqs)\n# .joins(<<-SQL\n# INNER JOIN course_descriptions\n# ON competence_nodes.abstract_course_id = course_descriptions.abstract_course_id\n# SQL\n# )\n\n respond_to do |format|\n #format.html # index.html.erb\n format.json do\n render :json => @courses.select(<<-SQL\n competence_nodes.id,\n competence_nodes.course_code,\n course_descriptions.name AS translated_name\n SQL\n ).to_json(:methods => :strict_prereq_ids, :root => true)\n end\n end\n end", "def index\n render json: @test_module.test_questions, status: :ok\n end", "def courses\n @courses = Course.where(faculty_id: params[:faculty_id]).order(:name)\n respond_to do |format|\n format.json { render json: @courses }\n end\n end", "def index\n @attempt_questions = AttemptQuestion.all\n end", "def index\n @survey_results = SurveyResult.all\n @course = Course.find(params[:course_id])\n\n @questions = [\n [\"classtime\",\"Class time is used productively.\"],\n [\"homework\",\"Homework assignments are conducive to relevant learning.\"],\n [\"midterm\",\"The midterm focused on relevant class material.\"],\n [\"workload\",\"The weekly workload is acceptable\"],\n [\"material\",\"The class material (lectures, books, etc.) is useful and easily available.\"],\n [\"pace\",\"The course pace is too fast\"],\n [\"passion\",\"The instructor is passionate about teaching the course.\"]\n ]\n end", "def new\n @knowledge_points = KnowledgePoint.all\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @question }\n end\n end", "def show\n @questions = @exam.questions\n @question = Question.new\n end", "def questions\n @_questions ||= fetch_questions\n end", "def index\n @parent_questions = ParentQuestion.all\n end", "def questions\n \n end", "def update\n respond_to do |format|\n if @course_proposal_question.update(course_proposal_question_params)\n format.html { redirect_to @course_proposal_question, notice: 'Course proposal question was successfully updated.' }\n format.json { render :show, status: :ok, location: @course_proposal_question }\n else\n format.html { render :edit }\n format.json { render json: @course_proposal_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @community_questions = CommunityQuestion.all\n end", "def index\n @proposals = listing.proposals\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @proposals }\n end\n end", "def show\n @question = Question.find(params[:id])\n @course = @question.course\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @question }\n end\n end", "def show\n @classroom = Classroom.find(params[:id])\n gon.questions = @classroom.questions.order(:time).map { |q| [q.time, 1 + q.reputation_for(:votes).to_i + q.answers.count*0.5] }\n totalArr = Array.new\n gon.questions.each do |q|\n index = q[0].to_i / 10\n totalArr[index] = totalArr[index].blank? ? 1 : totalArr[index] + 1;\n end\n\n gon.qpm = totalArr.each_with_index.map { |total,i| [i*10, total.to_i] }\n\n # get the 'hottest questions'\n if current_user_is_teacher\n @questions = @classroom.questions.find_with_reputation(:votes, :all, order: 'votes desc')\n else\n @questions = @classroom.questions.order('updated_at DESC').all\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @classroom }\n end\n end", "def list\n @questions = Question.paginate(page: params[:page], per_page: 10)\n end", "def index\n url = @httpIp + '/pet.com/api/question/getAllQuestions'\n uri = URI(url)\n response = Net::HTTP.get(uri)\n # @questions = JSON.parse(response, object_class: OpenStruct)\n @questions = Kaminari.paginate_array(JSON.parse(response, object_class: OpenStruct)).page(params[:page]).per(7)\n end", "def index\n @api_v1_questions = Api::V1::Question.all\n end", "def index\n @poll_questions = PollQuestion.all\n end", "def index\n @questions = @quiz.questions.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @questions }\n end\n end", "def index\n @template_questions = TemplateQuestion.all\n @checkin_questions = TemplateQuestion.checkin\n @review_questions = TemplateQuestion.review\n end", "def index\n find_questions\n end", "def index\n\t\t@questions = Question.includes(:course)\n\t if params[:id] && params['id']!=\"\"\n \t @questions = @questions.where('id = ?', params[:id])\n \tend\n\t if params[:course_id] && params['course_id']!=\"\"\n \t @questions = @questions.where('course_id = ?', params[:course_id])\n \tend\n\t if params[:content] && params['content']!=\"\"\n \t @questions = @questions.where('content LIKE ?', \"%#{params[:content]}%\")\n \tend\n\t\t\n\t\t@questions = @questions.paginate(page: params[:page], per_page: 20).order('created_at DESC')\n\n\n\t respond_to do |format|\n\t format.html # index.html.erb\n\t format.xml { render :xml => @questions }\n\t end\n\tend", "def questions_url\n view_context.questions_url\n end", "def questions=(value)\n @questions = value\n end", "def index\n @test_questions = TestQuestion.all\n end", "def index\n @test_questions = TestQuestion.all\n end", "def questions\n extracted_questions = []\n\n unless self.qp_questions.nil?\n self.qp_questions.each do |question| \n extracted_questions.push(Question.new(question))\n end \n end\n\n return extracted_questions\t\t\t\n\t\tend", "def index\n render_json(current_user.created_questions)\n end", "def index\n @proposals = current_user.proposals\n end", "def list_course_prereqs\n ScopedCourse.find_each do |scoped_course|\n puts \"Scoped: #{scoped_course.localized_description.name}\"\n if scoped_course.abstract_course\n puts \"Abstract: #{scoped_course.abstract_course.code}\"\n else\n puts \"Abstract: NULL\"\n end\n if scoped_course.prereqs.size > 0\n puts \"Prereqs:\"\n scoped_course.prereqs.each do |prereq_course|\n puts \" - #{prereq_course.localized_description.name}\"\n end\n else\n puts \"Prereqs: NONE\"\n end\n puts \"\\n\\n\"\n end\n end", "def get_questions(number)\n @questions_array = get_from_url(@questions_conn, QUESTIONS_OBTAINTION_KEY, {size: number})\n end", "def qa_page\n find_by(url: '/questions_and_tags')\n end", "def show\n @questions = @category.questions.includes(user: :questions).paginate(page: params[:page], per_page: 10)\n end", "def index\n @questions = Question.accessible_by(current_ability)\n\n respond_with @questions\n end", "def index\n @my_questions = MyQuestion.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @my_questions }\n end\n end" ]
[ "0.71004456", "0.673227", "0.6493525", "0.6493525", "0.63337207", "0.6300776", "0.62354195", "0.62217057", "0.6143496", "0.61383724", "0.6121525", "0.6104301", "0.60591197", "0.60242075", "0.6000374", "0.5961999", "0.59573615", "0.59563017", "0.5940224", "0.59039485", "0.5895032", "0.58934367", "0.5882213", "0.58712375", "0.586814", "0.58618087", "0.58612657", "0.5841774", "0.5838294", "0.5838294", "0.58373445", "0.5835435", "0.5833402", "0.58306926", "0.5827829", "0.58263975", "0.58123493", "0.5797324", "0.5790761", "0.577778", "0.577778", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57657975", "0.57641095", "0.5762392", "0.57559454", "0.574485", "0.57339215", "0.5726997", "0.57120204", "0.5697571", "0.5694834", "0.56933016", "0.5692257", "0.5690408", "0.56737137", "0.56733984", "0.56651086", "0.5659721", "0.56580395", "0.5644877", "0.5635969", "0.56321365", "0.56154853", "0.56086856", "0.5599238", "0.559494", "0.55885667", "0.5583963", "0.5573058", "0.556141", "0.55570227", "0.5556228", "0.5556228", "0.5539791", "0.5539698", "0.5538096", "0.5532521", "0.55322564", "0.5514713", "0.5514591", "0.5513458", "0.55102783" ]
0.76668197
0
GET /course_proposal_questions/1 GET /course_proposal_questions/1.json
def show end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @course_proposal_questions = CourseProposalQuestion.all\n end", "def questions\n self.class.get(\"/2.2/questions\", @options)\n end", "def index\n params.require(:course)\n @questions = Course.find(params[:course]).questions.select {|q| q.answered == false}\n\n render json: @questions\n end", "def set_course_proposal_question\n @course_proposal_question = CourseProposalQuestion.find(params[:id])\n end", "def show\n @critical_question = CriticalQuestion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @critical_question }\n end\n end", "def index\n @questions = @course.questions.all\n end", "def index\n @questions = @course.questions.all\n end", "def index\n @proposals = Proposal.all\n\n render json: @proposals\n end", "def show\n @proposal = Proposal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @proposal }\n end\n end", "def show\n @proposal = Proposal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @proposal }\n end\n end", "def create\n @course_proposal_question = CourseProposalQuestion.new(course_proposal_question_params)\n\n respond_to do |format|\n if @course_proposal_question.save\n format.html { redirect_to @course_proposal_question, notice: 'Course proposal question was successfully created.' }\n format.json { render :show, status: :created, location: @course_proposal_question }\n else\n format.html { render :new }\n format.json { render json: @course_proposal_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @question_category = QuestionCategory.with_questions(question_category_id: params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @question_category }\n end\n end", "def show\n @questions_option = QuestionsOption.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @questions_option }\n end\n end", "def destroy\n @course_proposal_question.destroy\n respond_to do |format|\n format.html { redirect_to course_proposal_questions_url, notice: 'Course proposal question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def index\n @questions = @subsection.questions.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @questions }\n end\n end", "def new\n @knowledge_points = KnowledgePoint.all\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @question }\n end\n end", "def index\n @questions = @questionable.questions\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @proposal }\n end\n end", "def index\n render status: :ok, json: @simple_question_alternatives\n end", "def responses\n @proposal = current_user.proposals.find(params[:id])\n @responses = @proposal.responses\n\n respond_to do |format|\n format.html # responses.html.erb\n format.xml { render :xml => @responses }\n end\n end", "def course_proposal_question_params\n params.require(:course_proposal_question).permit(:question, :help_text)\n end", "def show\n @questions = Question.find(params[:id])\n end", "def show\n if @v1_question\n render json: @v1_question\n else\n render json: get_errors, status: :unprocessable_entity\n end\n end", "def index\n @questions = Question.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @questions }\n end\n end", "def show\n @questionnaire = Questionnaire.find(params[:id])\n\n respond_to do |format|\n format.html\n format.json { render json: @questionnaire }\n end\n end", "def index\n @questions = Question.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @questions }\n end\n end", "def show\n @intake_question = IntakeQuestion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @intake_question }\n end\n end", "def questions\n # Get a list of questionnaires that belong to instances of the current race\n if @course\n questionnaire_ids = @course.questionnaire_ids\n elsif @instance\n questionnaire_ids = @instance.questionnaire_ids\n else\n questionnaire_ids = []\n end\n\n # Collect question_ids that are used in those questionnaires\n question_ids = Set.new\n Questionnaire.where(:id => questionnaire_ids).find_each do |questionnaire|\n question_ids.merge(questionnaire.question_ids)\n end\n\n @questions = Question.find(question_ids.to_a)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @questions.to_json }\n end\n end", "def show\n @test_question = TestQuestion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @test_question }\n end\n end", "def get_forms\n @course = Course.find(params[:course_id])\n @forms = @course.professor_forms\n render json: @forms\n end", "def show\n @poll_question = PollQuestion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @poll_question }\n end\n end", "def show\n @course_prerequisite = CoursePrerequisite.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @course_prerequisite }\n end\n end", "def get_question_list\n json= RestClient.get(\"http://localhost:3000/questions\")\n JSON.parse(json)\n end", "def get_one\n question_data = Question.new.get_one( params[:id] )\n return render json: question_data\n end", "def show\n @questionnaire = Questionnaire.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @questionnaire }\n end\n end", "def show\n @questionnaire = Questionnaire.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @questionnaire }\n end\n end", "def index\n @proposals = current_user.proposals\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @proposals }\n end\n end", "def choose_question\n if params.dig(:assessment, :type).present? && params.dig(:assessment, :type_id).present?\n type = params[:assessment][:type].camelize.constantize.where(id: params[:assessment][:type_id]).first rescue ''\n if type.present?\n all_questions = fetch_all_questions(type)\n if all_questions.count > 0\n assessment_questions = Assessment.fetch_assessment_questions(all_questions.ids, current_user.id)\n render json: calculate_remaining_qusts(all_questions, assessment_questions).order(\"RANDOM()\").limit(2).select(:id, :content, :options)\n else\n render json: {'type': 'No data found for selected type'}\n end\n else\n render json: {'type': 'Invalid selected type or type id'}\n end\n else\n render json: {'Input': 'Invalid inputs'}\n end\n end", "def show\n #@lecture = Lecture.find(params[:id])\n #@course = Course.find(params[:course_id])\n \n @lecture=Lecture.where(:id => params[:id], :course_id => params[:course_id])\n @course = Course.find(params[:course_id])\n \n if @lecture.empty?\n redirect_to course_lectures_path(params[:course_id]), :alert=> \"No such lecture\"\n else\n \n @lecture=@lecture.first\n \n \n @quizzes= OnlineQuiz.where(:lecture_id => params[:id])\n @url= get_answers_course_lecture_path(params[:course_id], params[:id])\n @s=params[:s] if params[:s]\n logger.debug(\"s issssss #{@s}\")\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lecture }\n end\n end\n end", "def update\n respond_to do |format|\n if @course_proposal_question.update(course_proposal_question_params)\n format.html { redirect_to @course_proposal_question, notice: 'Course proposal question was successfully updated.' }\n format.json { render :show, status: :ok, location: @course_proposal_question }\n else\n format.html { render :edit }\n format.json { render json: @course_proposal_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @category_question = CategoryQuestion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @category_question }\n end\n end", "def check_questions\n response = Request.get_request(URL_QUESTION)\n questions = []\n if response.success?\n data = Request.manage_response(response)\n end\n data.each do |question|\n questions << Question.new(question)\n end\n questions\nend", "def new\n @critical_question = CriticalQuestion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @critical_question }\n end\n end", "def index\n @question_categories = QuestionCategory.with_questions()\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @question_categories }\n end\n end", "def index\n @api_v1_questions = Api::V1::Question.all\n end", "def show\n authorize! :answer, @questionnaire\n\n respond_to do |format|\n format.html {\n @answer_set = AnswerSet.new()\n @answer_set.questionnaire_id = @questionnaire.id\n @answer_set.init_questionnaire(@questionnaire)\n }\n format.json { render :json => @questionnaire.questions.to_json }\n end\n end", "def index\n render json: @test_module.test_questions, status: :ok\n end", "def question\n Question.find_by_id(questions_id)\n end", "def show\n @question = Question.find(params[:id])\n @course = @question.course\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @question }\n end\n end", "def show\n @completed_quest = CompletedQuest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @completed_quest }\n end\n end", "def new\n @question = current_user.questions.new\n\t2.times do\n\t @question.choices.build\n\tend\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @question }\n end\n end", "def show\n @questions = @exam.questions\n @question = Question.new\n end", "def show\n @question = Question.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @question }\n end\n end", "def show\n @question = Question.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @question }\n end\n end", "def show\n @question = Question.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @question }\n end\n end", "def show\n @question = Question.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @question }\n end\n end", "def new\n @questions_option = QuestionsOption.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @questions_option }\n end\n end", "def show\n @question = Question.find(params[:id])\n\t@choice0 = @question.choices[0]\n\t@choice1 = @question.choices[1]\n#\t@comment0 = @choice0.comments.build(:choice_id => @choice0.id, :user_id => current_user.id)\n#\t@comment1 = @choice1.comments.build(:choice_id => @choice1.id, :user_id => current_user.id)\n#\t@comment0 = @choice0.comments.build()\n#\t@comment1 = @choice1.comments.build()\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @question }\n end\n end", "def index\n @course = Course.find(params[:course_id])\n @questions = @course.questions.current.due + @course.questions.current.pending.find(:all, :order => :next_datetime, :limit => 200)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @questions }\n end\n end", "def new\n @proposal = Proposal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @proposal }\n end\n end", "def new\n @proposal = Proposal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @proposal }\n end\n end", "def new\n @proposal = Proposal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @proposal }\n end\n end", "def show\n @questions = Question.all\n end", "def show\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @question }\n end\n end", "def show\n @question = Question.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @question }\n end\n end", "def show\n @question = Question.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @question }\n end\n end", "def show\n @my_question = MyQuestion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @my_question }\n end\n end", "def new\n @question = @subsection.questions.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @question }\n end\n end", "def show\n @competency_pertenece_evaluation = CompetencyPerteneceEvaluation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @competency_pertenece_evaluation }\n end\n end", "def show\n @cards_question = Cards::Question.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cards_question }\n end\n end", "def index\n @proposals = listing.proposals\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @proposals }\n end\n end", "def show\n @classroom = Classroom.find(params[:id])\n gon.questions = @classroom.questions.order(:time).map { |q| [q.time, 1 + q.reputation_for(:votes).to_i + q.answers.count*0.5] }\n totalArr = Array.new\n gon.questions.each do |q|\n index = q[0].to_i / 10\n totalArr[index] = totalArr[index].blank? ? 1 : totalArr[index] + 1;\n end\n\n gon.qpm = totalArr.each_with_index.map { |total,i| [i*10, total.to_i] }\n\n # get the 'hottest questions'\n if current_user_is_teacher\n @questions = @classroom.questions.find_with_reputation(:votes, :all, order: 'votes desc')\n else\n @questions = @classroom.questions.order('updated_at DESC').all\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @classroom }\n end\n end", "def index\n @attempt_questions = AttemptQuestion.all\n end", "def index\n @survey_questions = get_survey_questions\n end", "def index\n @survey_questions = get_survey_questions\n end", "def show\n @course_programme = CourseProgramme.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @course_programme }\n end\n end", "def show\n @assessment_course = AssessmentCourse.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @assessment_course }\n end\n end", "def view_reviews\n @submission = Submission.find(params[:id])\n @questions = @submission.assignment.questions.sort_by {|obj| obj.created_at }\n evaluation = @evaluations.where(:user_id => current_user.id)[0]\n @responses = @evaluations[0].responses.sort_by {|obj| obj.created_at }\n\n respond_to do |format|\n format.html { render view, :layout => 'no_sidebar' } # show.html.erb\n format.json { render json: @submission }\n end\n end", "def show\n @course_request = CourseRequest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @course_request }\n end\n end", "def index\n @proposals = Proposal.all()\n end", "def get_exam_section_questions(user_id, course_id, exam_id, section_id)\r\n relative_url = Path::USERS_COURSES_EXAMS_SECTIONS_QUESTIONS % [user_id,\r\n course_id, exam_id, section_id]\r\n response = get(relative_url)\r\n if !response.error?\r\n json_obj = JSON::parse(response.content)\r\n questions = json_obj['questions'] || []\r\n section_questions = []\r\n questions.each do |question|\r\n question_type = question['type']\r\n question_id = question['id']\r\n question_response = get_exam_section_question(user_id, course_id,\r\n exam_id, section_id,\r\n question_type, question_id)\r\n return question_response if question_response.error?\r\n\r\n section_question = JSON.parse(question_response.content)\r\n\t\t section_question['id'] = question_id\r\n section_question['type'] = question_type\t\t \r\n\t\t section_question['pointsPossible'] = question['pointsPossible']\r\n section_questions << section_question\r\n end\r\n\r\n response.content = { 'questions' => section_questions }.to_json\r\n end\r\n\r\n response\r\n end", "def show\n \t\tquestion = Question.find(params[:id])\n \t\tputs \"QUESTION: #{question.name}\"\n \t\trender json: question\n \tend", "def show\n @qc_evaluation = QcEvaluation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @qc_evaluation }\n end\n end", "def questions\r\n return @questions \r\nend", "def responses\n question=Question.find(params[:questionId])\n render :json=> question.response\n end", "def index\n @my_questions = MyQuestion.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @my_questions }\n end\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end", "def index\n @questions = Question.all\n end" ]
[ "0.7434157", "0.692222", "0.65849966", "0.6531316", "0.6327199", "0.6303049", "0.6303049", "0.62917584", "0.62825185", "0.62825185", "0.62761074", "0.6248612", "0.6221303", "0.61932045", "0.6179994", "0.6175323", "0.6148899", "0.6145449", "0.6125792", "0.6117495", "0.6097998", "0.6070635", "0.60646695", "0.6056607", "0.6029248", "0.6018168", "0.6014085", "0.6011272", "0.60084146", "0.6007693", "0.5984938", "0.59666044", "0.5959772", "0.5935013", "0.59313947", "0.59313947", "0.5927066", "0.5924709", "0.59169054", "0.5905974", "0.59055084", "0.59052885", "0.5905111", "0.5899535", "0.58988374", "0.5898632", "0.58973527", "0.5895203", "0.5881798", "0.58811307", "0.5871778", "0.5870353", "0.5863782", "0.5862584", "0.5862584", "0.5862584", "0.58537644", "0.58510184", "0.58483857", "0.5848002", "0.5848002", "0.5848002", "0.5845439", "0.58335906", "0.5826132", "0.5826132", "0.5825603", "0.58164656", "0.58134234", "0.5812575", "0.5801799", "0.5796131", "0.57925403", "0.5792346", "0.5792346", "0.57915807", "0.5781422", "0.57767767", "0.577287", "0.5771844", "0.57686436", "0.57620674", "0.5759544", "0.57541305", "0.57503617", "0.5750129", "0.57495385", "0.57495385", "0.57495385", "0.57495385", "0.57495385", "0.57495385", "0.57495385", "0.57495385", "0.57495385", "0.57495385", "0.57495385", "0.57495385", "0.57495385", "0.57495385", "0.57495385" ]
0.0
-1
POST /course_proposal_questions POST /course_proposal_questions.json
def create @course_proposal_question = CourseProposalQuestion.new(course_proposal_question_params) respond_to do |format| if @course_proposal_question.save format.html { redirect_to @course_proposal_question, notice: 'Course proposal question was successfully created.' } format.json { render :show, status: :created, location: @course_proposal_question } else format.html { render :new } format.json { render json: @course_proposal_question.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def course_proposal_question_params\n params.require(:course_proposal_question).permit(:question, :help_text)\n end", "def index\n @course_proposal_questions = CourseProposalQuestion.all\n end", "def create\n @course = Course.find(params[:course_id])\n @question = @course.questions.build(params[:question])\n @question.save\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @course, notice: 'Question was successfully created.' }\n format.json { render json: @course, status: :created, location: @question }\n else\n format.html { render action: \"new\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = @course.questions.new(question_params)\n @question.user = current_user\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to user_course_question_path(@course, @question), notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @course_proposal_question.destroy\n respond_to do |format|\n format.html { redirect_to course_proposal_questions_url, notice: 'Course proposal question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def set_course_proposal_question\n @course_proposal_question = CourseProposalQuestion.find(params[:id])\n end", "def questions_quiz_params\n if params[:questions_quiz] and params[:questions_quiz][:proposals_attributes]\n params[:questions_quiz][:proposals_attributes].each do |idx, attrs|\n attrs.merge!({\n question_id: @questions_quiz.question.id,\n questions_quiz_id: @questions_quiz.id\n })\n end\n end\n\n params.require(:questions_quiz).permit(proposals_attributes: [:answer_id, :question_id, :questions_quiz_id])\n end", "def create\n @question = Question.new(question_params)\n @courses = Course.all\n @users = User.all\n respond_to do |format|\n if @question.save\n format.html { redirect_to course_path(Course.find(@question.course_id))}\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\t\tif params[:question]==nil\n\t\t\tcid = params[:course_id]\n\t\t\ttit = params[:title]\n\t\t\tbod = params[:body]\n\t\t\t@question = Question.new(:course_id => cid, :title => tit, :body => bod)\n\t\telse\n\t @question = Question.new(params[:question])\n\t\t\t@course = course_init\n\t\t\t@question.course_id = @course.id\n\t\tend\n\t\t\n respond_to do |format|\n if @question.save\n format.html { redirect_to(@question, :notice => 'Question was successfully created.') }\n format.xml { render :xml => @question, :status => :created, :location => @question }\n format.json { render :json => @question, :status => :created, :location => @question }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @question.errors, :status => :unprocessable_entity }\n format.json { render :json => @question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def question_params\n params.require(:question).permit(:course_id, :title, :user_id, :content, :votes)\n end", "def add_question\n\t\t\tif(current_instructor.quizzes.exists?(:id => params[:quiz_id]))\n\t\t\t\tquiz = current_instructor.quizzes.find(params[:quiz_id])\n\t\t\t\tno = quiz.no_of_MCQ + quiz.no_of_rearrangeQ\t\n\t\t\t\tno.times do |n|\n\t\t\t\t\tquestion = Question.create((params[\"_json\"][n]).permit([:text, :mark, :right_answer, :choices => []]))\n\t\t\t\t\tquiz.questions << question\n\t\t\t\tend\n\t\t\t\trender json: { info: \"created\"}, status: 201\n\t\t\telse\n\t\t\t\trender json: { error:\"Quiz is not found\" }, status: 422\n\t\t\tend\n\t\tend", "def question_params\n params.require(:question).permit(:text, :option_a, :option_b, :option_c, :option_d, :started, :finished, :answer, :poll_centre_id)\n end", "def question_params\n params.require(:question).permit(:course_name, :description, :question, :answer)\n end", "def question_params\n params.require(:question).permit(:body, :slide, :presentation_id, :choices => [])\n end", "def add_new_questions\n questionnaire_id = params[:id]\n # If the questionnaire is being used in the active period of an assignment, delete existing responses before adding new questions\n if AnswerHelper.check_and_delete_responses(questionnaire_id)\n flash[:success] = 'You have successfully added a new question. Any existing reviews for the questionnaire have been deleted!'\n else\n flash[:success] = 'You have successfully added a new question.'\n end\n\n questionnaire = Questionnaire.find(questionnaire_id)\n current_num_of_questions = questionnaire.questions.size\n max_seq = 0\n Questionnaire.find(questionnaire_id).questions.each do |question|\n if !question.seq.nil? && question.seq > max_seq\n max_seq = question.seq\n end\n end\n ((current_num_of_questions + 1)..(current_num_of_questions + params[:question][:total_num].to_i)).each do\n max_seq += 1\n # Create question object based on type using question_factory\n question = question_factory(params[:question][:type], questionnaire_id, max_seq)\n if question.is_a? ScoredQuestion\n question.weight = params[:question][:weight]\n question.max_label = Question::MAX_LABEL\n question.min_label = Question::MIN_LABEL\n end\n\n if Question::SIZES.key?(question.class.name)\n question.size = Question::SIZES[question.class.name]\n end\n if Question::ALTERNATIVES.key?(question.class.name)\n question.alternatives = Question::ALTERNATIVES[question.class.name]\n end\n\n begin\n question.save\n rescue StandardError => e\n flash[:error] = e.message\n end\n end\n redirect_to edit_questionnaire_path(questionnaire_id.to_sym)\n end", "def create\n @apt_question = AptQuestion.new(apt_question_params)\n\n respond_to do |format|\n if @apt_question.save\n format.html { redirect_to @apt_question, notice: 'Apt question was successfully created.' }\n format.json { render :show, status: :created, location: @apt_question }\n else\n format.html { render :new }\n format.json { render json: @apt_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @test_question = TestQuestion.new(test_question_params)\n\n respond_to do |format|\n if @test_question.save\n format.html { redirect_to @test_question, notice: 'Test question was successfully created.' }\n format.json { render :show, status: :created, location: @test_question }\n else\n format.html { render :new }\n format.json { render json: @test_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @test_question = TestQuestion.new(test_question_params)\n\n respond_to do |format|\n if @test_question.save\n format.html { redirect_to @test_question, notice: 'Test question was successfully created.' }\n format.json { render :show, status: :created, location: @test_question }\n else\n format.html { render :new }\n format.json { render json: @test_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @proposal = Proposal.new(proposal_params)\n\n respond_to do |format|\n if @proposal.save\n format.html { redirect_to @proposal, notice: 'Proposal was successfully created.' }\n format.json { render :show, status: :created, location: @proposal }\n else\n format.html { render :new }\n format.json { render json: @proposal.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # puts params\n questions = JSON.parse(params[:questions])\n q_hash = questions[\"questions\"]\n @assignment = Assignment.new\n @assignment.course_id = params[:course_id]\n @assignment.type = \"Homework\"\n @assignment.start_date = params[:start_date]\n @assignment.end_date = params[:end_date]\n @assignment.name = params[:name]\n # Following is the question hash\n q_hash.each do |key, value|\n a_hash = key[\"answers\"]\n question = key[\"question\"]\n puts question\n new_question = Question.new\n new_question.description = question\n new_question.type = \"MultipleChoice\"\n # Answer hash\n a_hash.each do |k,v|\n puts k[\"is_correct\"]\n puts k[\"description\"]\n new_answer = Answer.new\n new_answer.description = k[\"description\"]\n new_answer.is_correct = k[\"is_correct\"]\n new_question.association(:answers).add_to_target(new_answer)\n end\n @assignment.association(:questions).add_to_target(new_question)\n end\n \n if @assignment.save\n render :show, status: :created, location: @assignment\n else\n render json: @assignment.errors, status: :unprocessable_entity\n end\n end", "def create\n @question = SurveyQuestion.new(question_params)\n if @question.save\n render json: @question\n else\n render json: @question.errors.full_messages.join(\", \"), status: :unprocessable_entity\n end\n end", "def create\n if @test.done.blank?\n redirect_to root_path, warning: \"This test have not finished yet\"\n return\n end\n params[:submission] = {}\n params[:submission][:user_id] = current_user.id\n @submission = @test.submissions.create(submission_params)\n respond_to do |format|\n if @submission.save\n @test.questions.each do |question|\n question.answers.each do |answer|\n answer.answers_of_questions.create({choice: false, question_id: question.id, submission_id: @submission.id})\n end\n end\n format.html { redirect_to edit_test_submission_path(@test, @submission) }\n else\n format.html { render :new }\n end\n end\n end", "def create\n @proposal = Proposal.new(params[:proposal])\n\n respond_to do |format|\n if @proposal.save\n format.html { redirect_to @proposal, notice: 'Proposal was successfully created.' }\n format.json { render json: @proposal, status: :created, location: @proposal }\n else\n format.html { render action: \"new\" }\n format.json { render json: @proposal.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_single_quiz_question(course_id,quiz_id,question__question_name__,question__question_text__,question__question_type__,opts={})\n query_param_keys = [\n \n ]\n\n form_param_keys = [\n :question__question_name__,\n :question__question_text__,\n :question__quiz_group_id__,\n :question__question_type__,\n :question__position__,\n :question__points_possible__,\n :question__correct_comments__,\n :question__incorrect_comments__,\n :question__neutral_comments__,\n :question__text_after_answers__,\n :question__answers__,\n \n ]\n\n # verify existence of params\n raise \"course_id is required\" if course_id.nil?\n raise \"quiz_id is required\" if quiz_id.nil?\n raise \"question__question_name__ is required\" if question__question_name__.nil?\n raise \"question__question_text__ is required\" if question__question_text__.nil?\n raise \"question__question_type__ is required\" if question__question_type__.nil?\n # set default values and merge with input\n options = underscored_merge_opts(opts,\n :course_id => course_id,\n :quiz_id => quiz_id,\n :question__question_name__ => question__question_name__,\n :question__question_text__ => question__question_text__,\n :question__question_type__ => question__question_type__\n )\n\n # resource path\n path = path_replace(\"/v1/courses/{course_id}/quizzes/{quiz_id}/questions\",\n :course_id => course_id,\n :quiz_id => quiz_id)\n headers = nil\n form_params = select_params(options, form_param_keys)\n query_params = select_params(options, query_param_keys)\n if opts[:next_page]\n pagination_params = page_params_load(:post, path)\n query_params.merge! pagination_params if pagination_params\n end\n response = mixed_request(:post, path, query_params, form_params, headers)\n page_params_store(:post, path)\n QuizQuestion.new(response)\n end", "def question_params\n params.permit(:lecture_id, :content, :correct_answer, :question_at)\n end", "def question_params\n params.require(:question).permit(:exam_id, :question, :correct_answer, :answer_1, :answer_2, :answer_3, :description)\n end", "def create\n @test_question = TestQuestion.new(params[:test_question])\n\n respond_to do |format|\n if @test_question.save\n format.html { redirect_to @test_question, :notice => 'Test question was successfully created.' }\n format.json { render :json => @test_question, :status => :created, :location => @test_question }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @test_question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n if @question.save\n render json: @question\n else\n render status: 400, nothing: true\n end\n end", "def create\n @quiz = Quiz.new(quiz_params)\n questions_arr.each do |i|\n question = Question.new(question_params(i))\n choices_arr(i).each do |j|\n choice = Choice.new(choice_params(j))\n choice.save\n question.choices << choice\n end\n @quiz.questions << question\n end\n\n if @quiz.save\n User.find(params[:user_id]).quizzes << @quiz\n render json: @quiz, status: :created, location: @quiz\n else\n render json: @quiz.errors, status: :unprocessable_entity\n end\n end", "def create\n @quiz = current_user.quizzes.build(quiz_params)\n\n @quiz.questions.each do |q|\n if q.question_type == \"free_answer\"\n q.answers = []\n end\n end\n\n puts @quiz.questions\n\n respond_to do |format|\n if @quiz.save\n format.html { redirect_to current_user, notice: 'Quiz was successfully created.' }\n format.json { render :show, status: :created, location: @quiz }\n else\n format.html { render :new }\n format.json { render json: @quiz.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @question = current_user.questions.new\n\t2.times do\n\t @question.choices.build\n\tend\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @question }\n end\n end", "def question_params\n params.require(:question).permit(:title, :body)\n #require returns question array\n #of everything being posted, work with the questions part, and allow these two things to be submitted\n end", "def prebooking_questions\n\n # this is a patch\n if @url.blank? or @token.blank?\n return []\n end\n\n [\n {\n question: \"How many guests will be riding with you?\", \n choices: [0,1,2,3], \n code: \"guests\"\n },\n {\n question: \"How many attendants will be riding with you?\", \n choices: [0,1,2,3], \n code: \"attendants\"\n },\n {\n question: \"How many mobility devices will you be bringing?\", \n choices: [0,1,2,3], \n code: \"mobility_devices\"\n },\n {\n question: \"What is your trip purpose?\", \n choices: (trip_purposes[\"trip_purposes\"] || \n Config.ride_pilot_purposes.try(:map) {|k,v| {\"name\" => k, \"code\" => v}} || \n []).map{|p| [p[\"name\"], p[\"code\"]]}, \n code: \"purpose\"\n }\n ]\n end", "def question_params\n params.require(:question).permit(:content, :response_type_id, :parent_id, :category_id, :groups,\n :version_independent_id, :description, :other_allowed, :subcategory_id,\n concepts_attributes: [:id, :value, :display_name, :code_system],\n data_collection_methods: [])\n end", "def create\n respond_to do |format|\n if @question.save\n @question_link = QuizQuestion.create!(:qtype => params[:qtype], :qid => @question.id, :quizid => params[:quizid], :points => params[:points])\n @question_link.save\n @question.update(:questionid => @question_link.id)\n @quiz = Quiz.find_by_id(params[:quizid])\n format.html { redirect_to admin_quiz_path(@quiz), notice: 'Quiz multiple choice question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to questions_path, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def question_params\n params.require(:question).permit(:user_id, :question, :yeah_count, :course_id, :answered)\n end", "def create\n @critical_question = CriticalQuestion.new(params[:critical_question])\n\n respond_to do |format|\n if @critical_question.save\n format.html { redirect_to @critical_question, notice: 'Critical question was successfully created.' }\n format.json { render json: @critical_question, status: :created, location: @critical_question }\n else\n format.html { render action: \"new\" }\n format.json { render json: @critical_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @parent_question = ParentQuestion.new(parent_question_params)\n\n respond_to do |format|\n if @parent_question.save\n format.html { redirect_to @parent_question, notice: 'Parent question was successfully created.' }\n format.json { render action: 'show', status: :created, location: @parent_question }\n else\n format.html { render action: 'new' }\n format.json { render json: @parent_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(params[:question])\n params[:knowledge_point_ids].each do |knowledge_point_id|\n @knowledge_point = KnowledgePoint.find_by_id(knowledge_point_id)\n @question.knowledge_points << @knowledge_point\n end\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, :notice => 'Question was successfully created.' }\n format.json { render :json => @question, :status => :created, :location => @question }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @community_question = CommunityQuestion.new(community_question_params)\n\n respond_to do |format|\n if @community_question.save\n format.html { redirect_to @community_question, notice: 'Community question was successfully created.' }\n format.json { render :show, status: :created, location: @community_question }\n else\n format.html { render :new }\n format.json { render json: @community_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @admin_academy_question = Academy::Question.new(admin_academy_question_params)\n\n respond_to do |format|\n if @admin_academy_question.save\n format.html { redirect_to @admin_academy_question, notice: 'Question was successfully created.' }\n format.json { render action: 'show', status: :created, location: @admin_academy_question }\n else\n format.html { render action: 'new' }\n format.json { render json: @admin_academy_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n section = Section.includes(:questions, phase: :template).find(params[:section_id])\n nbr = section.questions.maximum(:number)\n question_format = QuestionFormat.find_by(title: 'Text area')\n question = Question.new(section_id: section.id,\n question_format: question_format,\n number: nbr.present? ? nbr + 1 : 1)\n question_formats = allowed_question_formats\n authorize question\n render json: { html: render_to_string(partial: 'form', locals: {\n template: section.phase.template,\n section: section,\n question: question,\n method: 'post',\n url: org_admin_template_phase_section_questions_path(\n template_id: section.phase.template.id,\n phase_id: section.phase.id,\n id: section.id\n ),\n question_formats: question_formats\n }) }\n end", "def question_params\n params.require(:question).permit(:title, topic_ids: [], answers_attributes: [:id, :content, :is_correct])\n end", "def proposal_params\n params.require(:proposal).permit(:title, :description, :user_id, :hackathon_id)\n end", "def update\n respond_to do |format|\n if @course_proposal_question.update(course_proposal_question_params)\n format.html { redirect_to @course_proposal_question, notice: 'Course proposal question was successfully updated.' }\n format.json { render :show, status: :ok, location: @course_proposal_question }\n else\n format.html { render :edit }\n format.json { render json: @course_proposal_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n course = Course.includes(:professors).new(course_params)\n course.professor_ids=(params[:professors])\n\n if course.save\n render json: course.to_json(include: :professors)\n else\n render :json => { :errors => course.errors }, :status => 422\n end\n end", "def proposal_params\n params.require(:proposal).permit(:multi_app_identifier, :proposal_status_id, :category, :creator_id, \n :name, :given_names, :pesel, :citizenship_code, :birth_date, :birth_place, :family_name, :phone, :email,\n :lives_in_poland, :address_combine_id, :province_code, :province_name, :district_code, :district_name,\n :commune_code, :commune_name, :city_code, :city_name, :city_parent_code, :city_parent_name, :street_code, :street_name, :street_attribute,\n :c_address_house, :c_address_number, :c_address_postal_code,\n :esod_category, :exam_id, :exam_fullname, :exam_date_exam, :exam_online, :division_id, :division_fullname, :division_short_name, :division_min_years_old, \n :exam_fee_id, :exam_fee_price, :face_image_blob_path, :bank_pdf_blob_path, :consent_pdf_blob_path )\n end", "def question_params\n # params.require(:tst).permit(:name, :description, :status, :contributors)\n params.require(:question).permit(:name, :description, :status, :hint, :image_url, :explanation, :kind, :correct_response, :pause_at)\n end", "def create\n json = params[:survey]\n json[:questions] = JSON.parse(json[:questions])\n json[:questions].each_with_index do |question, idx|\n json[:questions][idx]['id'] = idx + 1\n end\n @survey = Survey.new(json)\n respond_to do |format|\n if @survey.save\n format.html { redirect_to @survey, notice: 'Survey was successfully created.' }\n format.json { render json: @survey, status: :created, location: @survey }\n else\n format.html { render action: \"new\" }\n format.json { render json: @survey.errors, status: :unprocessable_entity }\n end\n end\n end", "def questionnaire_params\n params.require(:questionnaire).permit(\n :title,\n :description,\n options: {},\n questions_attributes:\n [:id,\n :question_text,\n :correct_answer,\n :_destroy,\n question_answers_attributes:\n [:id,\n :is_correct_flag,\n :answer_text,\n :_destroy\n ]\n ])\n end", "def create\n @question = Question.new(params[:question])\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to api_v1_question_path(@question), notice: 'Question was successfully created.' }\n format.json { render json: @question, status: :created, location: @question }\n else\n format.html { render action: \"new\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Quizzes::Question.new(quizzes_question_params)\n\n respond_to do |format|\n if @question.save\n if params[:commit] =~ /add/i\n format.html { redirect_to edit_quiz_question_path(@question.quiz, @question) }\n else\n format.html { redirect_to quiz_questions_path(@question.quiz), notice: 'Question was successfully created.' }\n format.json { render :show, status: :created, location: @question }\n end\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def exam_params\r\n params.require(:exam).permit(\r\n :title, :time, :category_id,\r\n questions_attributes: [\r\n :id, :title, :score, :_destroy,\r\n options_attributes: [:id, :content, :is_correct, :_destroy]\r\n ])\r\n #params.require(:exam).permit(:title, :time, :category_id)\r\n end", "def create\n @question = @quiz.questions.new(params[:question])\n\n respond_to do |format|\n @question.save\n if @question.errors.blank?\n flash[:notice] = 'Question was successfully created.'\n format.html { redirect_to(quiz_questions_path(@quiz)) }\n format.xml { render :xml => @question, :status => :created, :location => @question }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def exam_question_params\n params.require(:exam_question).permit(:title, :question_text, :explanation_text)\n end", "def questions=(value)\n @questions = value\n end", "def create\n @question = current_user.questions.new(params[:question])\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: params.inspect}#'Question was successfully created.' }\n format.json { render json: @question, status: :created, location: @question }\n else\n format.html { render action: \"new\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def proposal_params\n params.require(:proposal).permit(:title, :content, :deadline, :price, :proposal_type, :company_id, :user_id)\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n QuestionMailer.trial_email(@question).deliver_now\n format.html { redirect_to root_path, notice: 'Your submission was successfully submitted.' }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def proposal_params\n params.require(:proposal).permit(:title, :content, :deadline, :price, :accepted, :company_id, :proposal_type, :completed, :completed_on, :paid, :charge_id, :bts, :focus_points, :time_of_day, :location_id, :background, :model_release)\n end", "def create\n puts evaluation_params\n @evaluation = Evaluation.new(evaluation_params)\n #De aca en adelante es para lograr insertar datos en la tabla intermedia \n #La Tabla intermedia se la evaluation_question\n respond_to do |format|\n puts \"Entre al respond\"\n if @evaluation.save\n puts \"Pude guardarlo\"\n evaluation = Evaluation.last\n evaluation.update(course_id: params[:course_id])\n evaluation_id = evaluation.id\n question_ids = params[:questions]\n question_ids.each do |question_id|\n EvaluationQuestion.create(question_id: question_id, evaluation_id: evaluation_id)\n end\n format.html { redirect_to @evaluation, notice: 'La evaluación fue creada con éxito' }\n format.json { render :show, status: :created, location: @evaluation }\n else\n @question = Question.all\n @courses = Course.all\n format.html { render :new }\n format.json { render json: @evaluation.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: \"Question was successfully created.\" }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def quiz_params\n params.require(:quiz).permit(:name, :description, :course_id, :due_date, :randomize_questions, :randomize_answers, :show_all_questions, question_attributes: [:id, :body, :_destroy, choice_attributes: [:id, :choice_body, :correct, :_destroy]])\n end", "def create\n @add_question = AddQuestion.new(add_question_params)\n\n respond_to do |format|\n if @add_question.save\n format.json { head :no_content }\n else\n format.html { render :new }\n format.json { render json: @add_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @proposal = Proposal.new(params[:proposal])\n @proposal.user = current_user\n respond_to do |format|\n if @proposal.save\n format.html { redirect_to @proposal, notice: 'Proposal was successfully created.' }\n format.json { render json: @proposal, status: :created, location: @proposal }\n else\n format.html { render action: \"new\" }\n format.json { render json: @proposal.errors, status: :unprocessable_entity }\n end\n end\n end", "def question_params\n params.require(:question).permit(:question_title, :quiz_id, choices_attributes: [])\n end", "def new\n @knowledge_points = KnowledgePoint.all\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @question }\n end\n end", "def question_params\n params.require(:question).permit(:trivia_id, :quiz_id, :response, :is_correct)\n end", "def create\n @cards_question = Cards::Question.new(params[:cards_question])\n\n respond_to do |format|\n if @cards_question.save\n format.html { redirect_to @cards_question, notice: 'Question was successfully created.' }\n format.json { render json: @cards_question, status: :created, location: @cards_question }\n else\n format.html { render action: \"new\" }\n format.json { render json: @cards_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @examquestion = Examquestion.new(examquestion_params)\n\n respond_to do |format|\n if @examquestion.save\n format.html { redirect_to @examquestion, notice: 'Examquestion was successfully created.' }\n format.json { render action: 'show', status: :created, location: @examquestion }\n else\n format.html { render action: 'new' }\n format.json { render json: @examquestion.errors, status: :unprocessable_entity }\n end\n end\n end", "def proposal_params\n params.require(:proposal).permit(:admin_id, :homework_id, :cost, :notes, :status, :deadline)\n end", "def new\n @project = Project.find(params[:project_id])\n @questionnaire = Questionnaire.new\n question = @questionnaire.qquestions.build\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @questionnaire }\n end\n end", "def new\n @question = @subsection.questions.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @question }\n end\n end", "def create\n question = @current_user.question.create!(question_params)\n render json: { question: question }\n end", "def proposal_params\n params.require(:proposal).permit(:esod_category, :customer_id, :category, :note, :user_id)\n end", "def create_question\n question_hash = Adapter.quiz_api(difficulty) #use adapter method, with difficulty passes into the url as a variable, to gnerate a new list of questions.\n new_question = Question.new #make a new question instance\n new_question.save #save now so we can store the question's id in the answer by calling self.id\n new_question.content = question_hash['question'] #adding all necessary column data to this question object/row\n new_question.create_answers(question_hash)\n new_question.quiz_id = self.id\n new_question.save #send the newly created question to the database\n end", "def quizzes_question_params\n params.require(:quizzes_question).permit(:quiz_id, :topic, :ordinal, :question, :open_ended, :answer, :answer_option_id, :answer_format, :answer_template, options_attributes: [:id, :label, :grade, :_destroy])\n end", "def create\n @question = Question.new(question_params)\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to @question, notice: NoticeMessages::SUCCESS_CREATE_QUESTION }\n format.json { render :show, status: :created, location: @question }\n else\n format.html { render :new }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def question_params\n params.require(:question).permit(:question, topic_ids: [])\n end", "def question_params\n params.require(:question).permit(:title, :answer1, :answer2, :answer3, :answer4, :answer5, :right_answer, :proof_id)\n end", "def proposal_params\n params.require(:proposal).permit(:subject, :body)\n end", "def create\n params[:questions_option][:correct].to_i\n @questions_option = QuestionsOption.new(questions_option_params)\n\n respond_to do |format|\n if @questions_option.save\n format.html { redirect_to :back, notice: 'Questions option was successfully created.' }\n format.json { render json: :back, status: :created, location: @questions_option }\n else\n format.html { render action: \"new\" }\n format.json { render json: :back.errors, status: :unprocessable_entity }\n end\n end\n end", "def question_params\n params.require(:question).permit(:question)\n end", "def create\n respond_to do |format|\n if @proposal.save\n format.html { redirect_to @proposal.enrolment, notice: 'Proposal was successfully created.' }\n format.json { render json: @proposal, status: :created, location: @proposal }\n else\n format.html { render action: \"new\" }\n format.json { render json: @proposal.errors, status: :unprocessable_entity }\n end\n end\n end", "def question_params\n params.require(:question).permit(:title, :content)\n end", "def question_params\n params.require(:question).permit(:title, :content)\n end", "def question_params\n params.require(:question).permit(:title, :content)\n end" ]
[ "0.71165013", "0.6742254", "0.6596467", "0.6493522", "0.63982767", "0.63767076", "0.6351012", "0.6346057", "0.63372546", "0.62813663", "0.62396675", "0.6190765", "0.6181965", "0.6173738", "0.6158913", "0.6128002", "0.611729", "0.611729", "0.6087749", "0.608717", "0.60533935", "0.60467654", "0.6041669", "0.6034528", "0.60192895", "0.6007975", "0.6006295", "0.60021806", "0.5990546", "0.59863573", "0.5984273", "0.5979979", "0.59788936", "0.59772336", "0.59577787", "0.5954315", "0.5950848", "0.5939884", "0.59241444", "0.5923448", "0.5921037", "0.591871", "0.5916412", "0.59116924", "0.5909823", "0.58959866", "0.58845633", "0.5875115", "0.5872416", "0.5867761", "0.5866043", "0.5864367", "0.5859576", "0.5859576", "0.5859576", "0.5859576", "0.5859576", "0.5859576", "0.5859576", "0.5859576", "0.5859576", "0.5859576", "0.58584034", "0.585363", "0.585188", "0.5850259", "0.5849057", "0.584619", "0.58450234", "0.5841482", "0.58407605", "0.5833477", "0.58334756", "0.58330834", "0.5829627", "0.58295107", "0.5828633", "0.58258003", "0.58236194", "0.58093005", "0.5807432", "0.5805813", "0.58040005", "0.58036214", "0.5802251", "0.58005965", "0.57963014", "0.5795723", "0.57876056", "0.5785013", "0.57844794", "0.5779994", "0.5777678", "0.577484", "0.57721233", "0.5760475", "0.5757773", "0.5756905", "0.5756905", "0.5756905" ]
0.7436503
0
PATCH/PUT /course_proposal_questions/1 PATCH/PUT /course_proposal_questions/1.json
def update respond_to do |format| if @course_proposal_question.update(course_proposal_question_params) format.html { redirect_to @course_proposal_question, notice: 'Course proposal question was successfully updated.' } format.json { render :show, status: :ok, location: @course_proposal_question } else format.html { render :edit } format.json { render json: @course_proposal_question.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to @question.course, notice: 'Question was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to api_v1_question_path(@question), notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to quiz_path(@question.subsection_id), notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @questions_option = QuestionsOption.find(params[:id])\n\n respond_to do |format|\n if @questions_option.update_attributes(params[:questions_option])\n format.html { redirect_to @questions_option, notice: 'Questions option was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @questions_option.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @test_question = TestQuestion.find(params[:id])\n\n respond_to do |format|\n if @test_question.update_attributes(params[:test_question])\n format.html { redirect_to @test_question, :notice => 'Test question was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @test_question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def set_course_proposal_question\n @course_proposal_question = CourseProposalQuestion.find(params[:id])\n end", "def update\n respond_to do |format|\n if @apt_question.update(apt_question_params)\n format.html { redirect_to @apt_question, notice: 'Apt question was successfully updated.' }\n format.json { render :show, status: :ok, location: @apt_question }\n else\n format.html { render :edit }\n format.json { render json: @apt_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_question.update(api_v1_question_params)\n format.html { redirect_to @api_v1_question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_question }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @critical_question = CriticalQuestion.find(params[:id])\n\n respond_to do |format|\n if @critical_question.update_attributes(params[:critical_question])\n format.html { redirect_to @critical_question, notice: 'Critical question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @critical_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to new_question_path, notice: 'questions was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @v1_question.update(v1_question_params)\n render json: @v1_question, status: :ok\n else\n render json: get_errors, status: :unprocessable_entity\n end\n end", "def edit_question\n\t\t\tquizzes = current_instructor.quizzes\n\t\t\t@found = 0\n\t\t\tquizzes.each do |quiz|\n\t\t\t\tif(quiz.questions.exists?(:id => params[:question_id]))\n\t\t\t\t\t@found = @found + 1\n\t\t\t\tend \n\t\t\tend\n\t\t\tif (@found > 0)\n\t\t\t\tquestion = Question.find(params[:question_id])\n\t\t\t\tif (question.update(question_params))\n\t\t\t\t\trender json: { success: true, data: { :question => question }, info:{} }, status: 200\n\t\t\t\telse\n\t\t\t\t\trender json: { error: question.errors }, status: 422 \n\t\t\t\tend\t\n\t\t\telse\n\t\t\t\trender json: { error:\"Question is not found\" }, status: 422\n\t\t\tend\n\t\tend", "def update\n question = Question.find(params[:id_question])\n if question.update(params_question)\n render json: question, status: 200\n else\n render json: question.errors, status: 422\n end\n\n end", "def update\n respond_to do |format|\n if @test_question.update(test_question_params)\n format.html { redirect_to @test_question, notice: 'Test question was successfully updated.' }\n format.json { render :show, status: :ok, location: @test_question }\n else\n format.html { render :edit }\n format.json { render json: @test_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @parent_question.update(parent_question_params)\n format.html { redirect_to @parent_question, notice: 'Parent question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @parent_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_existing_quiz_question(course_id,quiz_id,id,question__question_name__,question__question_text__,question__question_type__,opts={})\n query_param_keys = [\n \n ]\n\n form_param_keys = [\n :question__question_name__,\n :question__question_text__,\n :question__quiz_group_id__,\n :question__question_type__,\n :question__position__,\n :question__points_possible__,\n :question__correct_comments__,\n :question__incorrect_comments__,\n :question__neutral_comments__,\n :question__text_after_answers__,\n :question__answers__,\n \n ]\n\n # verify existence of params\n raise \"course_id is required\" if course_id.nil?\n raise \"quiz_id is required\" if quiz_id.nil?\n raise \"id is required\" if id.nil?\n raise \"question__question_name__ is required\" if question__question_name__.nil?\n raise \"question__question_text__ is required\" if question__question_text__.nil?\n raise \"question__question_type__ is required\" if question__question_type__.nil?\n # set default values and merge with input\n options = underscored_merge_opts(opts,\n :course_id => course_id,\n :quiz_id => quiz_id,\n :id => id,\n :question__question_name__ => question__question_name__,\n :question__question_text__ => question__question_text__,\n :question__question_type__ => question__question_type__\n )\n\n # resource path\n path = path_replace(\"/v1/courses/{course_id}/quizzes/{quiz_id}/questions/{id}\",\n :course_id => course_id,\n :quiz_id => quiz_id,\n :id => id)\n headers = nil\n form_params = select_params(options, form_param_keys)\n query_params = select_params(options, query_param_keys)\n if opts[:next_page]\n pagination_params = page_params_load(:put, path)\n query_params.merge! pagination_params if pagination_params\n end\n response = mixed_request(:put, path, query_params, form_params, headers)\n page_params_store(:put, path)\n QuizQuestion.new(response)\n end", "def update_correct_answer\n question_params = params.permit(:question_id, :question_type_id, :option_id)\n \n render json: Question.update_correct_option(question_params)\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to @question, :notice => 'Question was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to edit_question_path(@question), notice: 'Question was successfully updated.' }\n format.json\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_question\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to :planner, notice: 'Question was successfully updated.' }\n format.json { respond_with_bip(@question) }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n qp = question_params\n if qp[:question_type] == \"vignette\" or qp[:question_type] == \"nonchoice\"\n qp[:answer] = \"\"\n end\n\n respond_to do |format|\n if @question.update(qp)\n format.html { redirect_to paper_questions_path(question_params[:paper_id],question_params[:id]), notice: '題目已被成功編輯' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { redirect_to edit_paper_question_path, notice: '上傳檔案大小不可超過500KB' }\n format.json { render json: paper_questions_path.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @proposal = Proposal.find(params[:id])\n\n respond_to do |format|\n if @proposal.update_attributes(params[:proposal])\n format.html { redirect_to @proposal, notice: 'Proposal was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @proposal.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @cards_question = Cards::Question.find(params[:id])\n\n respond_to do |format|\n if @cards_question.update_attributes(params[:cards_question])\n format.html { redirect_to @cards_question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @cards_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @poll_question = PollQuestion.find(params[:id])\n\n respond_to do |format|\n if @poll_question.update_attributes(params[:poll_question])\n format.html { redirect_to @poll_question, notice: 'Poll question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @poll_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n #@question = Question.find(params[:id])\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to @question, notice: t('alert.question.update_success', default: 'Question was successfully updated.') }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @intake_question = IntakeQuestion.find(params[:id])\n\n respond_to do |format|\n if @intake_question.update_attributes(params[:intake_question])\n format.html { redirect_to @intake_question, notice: 'Intake question was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @intake_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @survey = Survey.find(params[:id])\n json = params[:survey]\n json[:questions] = JSON.parse(json[:questions])\n json[:questions].each_with_index do |question, idx|\n json[:questions][idx]['id'] = idx + 1\n end\n\n respond_to do |format|\n if @survey.update_attributes(json)\n format.html { redirect_to @survey, notice: 'Survey was successfully updated.' }\n format.json { render json: @survey }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @survey.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize @question\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n # @question.question_type_id = params[:question][:question_type_id]\n # @question.question_category_id = @question.question_type.question_category_id\n\n # authorize! :update, @question\n # @question.question_type_id = params[:question][:question_type_id]\n # @question.question_category_id = @question.question_type.question_category_id\n\n \n # # get fields from the form to update the question's section\n # @question.book = params[:question][:book]\n # @question.chapter = params[:question][:chapter]\n # @question.verse = params[:question][:verse]\n # @question.section_id = @question.set_section\n #---------------------------------------------------------\n \n # # if the the question has been approved, set the approver and the date approved\n # unless params[:question][:approval_level] == nil\n # @question.approved_by = current_user.id\n # @question.approved_on = DateTime.now\n # end\n\t\n @question.update_attributes(params[:question])\n unless @question.approval_level == -1\n respond_with @question\n\tend\n\t\n\t# set the section for this question\n\t#@question.section_id = @question.set_section\n \n # the quesiton is marked as refused, drop from database\n if @question.approval_level == -1\n \t@question.destroy\n destroyed = 1\n redirect_to approve_path, :notice => \"Successfully deleted question\"\n return\n end\n # if @question.update_attributes(params[:question])\n # # determine user and send them to appropriate page\n # if current_user.is_writer?\n # redirect_to write_path, :notice => \"Successfully updated question.\"\n # elsif current_user.is_approver?\n # redirect_to approve_path, :notice => \"Successfully updated question.\"\n # else\n # redirect_to @question, :notice => \"Successfully updated question.\"\n # end\n # else\n # render :action => 'edit'\n # end\n end", "def update\n respond_to do |format|\n if @proposal.update_attributes(params[:proposal])\n format.html { redirect_to @proposal, notice: 'Proposal was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @proposal.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n @question_link = QuizQuestion.find_by_id(@question.questionid)\n @question_link.update(:points => params[:points])\n @quiz = Quiz.find_by_id(@question_link.quizid)\n format.html { redirect_to admin_quiz_path(@quiz), notice: 'Quiz multiple choice question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, :notice =>'Question was successfully updated.' }\n format.json { render :show, :status => :ok, :location => @question }\n else\n format.html { render :edit }\n format.json { render :json => @question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @proposal = Proposal.find(params[:id])\n\n respond_to do |format|\n if @proposal.update_attributes(update_params)\n format.html { redirect_to @proposal, notice: 'Proposal was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @proposal.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @examquestion.update(examquestion_params)\n format.html { redirect_to @examquestion, notice: 'Examquestion was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @examquestion.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @questions = Question.all\n @categories = [\"Learning from Labs\", \"Lab Instructor\", \"Lab Space and Equipment\", \"Time Required to Complete Labs\", \"Lecture Section Instructor\"]\n respond_to do |format|\n if @survey.update(survey_params)\n format.html { redirect_to @survey, notice: 'Survey was successfully submitted.' }\n format.json { render :show, status: :ok, location: @survey }\n\n # Update 'completed' attribute to true\n submission = Survey.find_by(survey_ID: @survey.survey_ID)\n submission.update(status: true)\n\n # Increment 'completed' attribute for section\n @section = Section.find_by(class_num: @survey.class_num)\n @section.update(completed: @section.completed + 1)\n\n\n else\n format.html { render :edit }\n format.json { render json: @survey.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @multiple_choice_question = MultipleChoiceQuestion.find(params[:id])\n\n respond_to do |format|\n if @multiple_choice_question.update_attributes(params[:multiple_choice_question])\n format.html { redirect_to @multiple_choice_question, notice: 'Multiple choice question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @multiple_choice_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: \"Question was successfully updated.\" }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.json { render :json => 'Question updated OK' }\n format.xml { head :ok }\n else\n format.json { render :json => @question.errors }\n format.xml { render :xml => @question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to [@category, @question], notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n p = trial_params.clone\n if p[\"question_ids\"].nil?\n p[\"question_ids\"] = []\n end\n\n respond_to do |format|\n if @trial.update(p)\n format.html { redirect_to @trial, notice: 'Trial was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @trial.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = @quiz.questions.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n flash[:notice] = 'Question was successfully updated.'\n format.html { redirect_to(quiz_questions_path(@quiz)) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @admin_academy_question.update(admin_academy_question_params)\n format.html { redirect_to @admin_academy_question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @admin_academy_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @quizzes_question.update(quizzes_question_params)\n if params[:commit] =~ /add/i\n format.html { redirect_to edit_quiz_question_path(@question.quiz, @question) }\n else\n format.html { redirect_to quiz_questions_path(@question.quiz), notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @quizzes_question }\n end\n else\n format.html { render :edit }\n format.json { render json: @quizzes_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @my_question = MyQuestion.find(params[:id])\n\n respond_to do |format|\n if @my_question.update_attributes(params[:my_question])\n format.html { redirect_to @my_question, notice: 'My question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @my_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @template_question.update(template_question_params)\n format.html { redirect_to @template_question, notice: 'Template question was successfully updated.' }\n format.json { render :show, status: :ok, location: @template_question }\n else\n format.html { render :edit }\n format.json { render json: @template_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n params[:poll_question][:active] = params[:poll_question][:active].present?\n params[:poll_question][:existing_poll_option_attributes] ||= {}\n\n @poll_question.attributes = params[:poll_question]\n\n respond_to do |format|\n if @commit_type == 'preview' && @poll_question.valid?\n format.html { render template: 'admin/shared/update_preview', locals: { record: @poll_question }, layout: 'admin/admin_preview' }\n format.xml { render xml: @poll_question, status: :created, location: @poll_question }\n elsif @commit_type == 'save' && @poll_question.save(user: current_user)\n format.html do\n @refresh = true\n render 'admin/shared/update'\n end\n format.xml { head :ok }\n else\n format.html { render action: :edit }\n format.xml { render xml: @poll_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n if (@question.question_type.short_text? || @question.question_type.open_ended_text?)\n path = survey_path(params[:survey_id])\n else\n path = survey_question_path(params[:survey_id],@question.id)\n end\n format.html { redirect_to path, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @question_option.update(question_option_params)\n format.html { redirect_to @question_option, notice: 'Question option was successfully updated.' }\n format.json { render :show, status: :ok, location: @question_option }\n else\n format.html { render :edit }\n format.json { render json: @question_option.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @proposal = listing.proposals.find(params[:id])\n\n respond_to do |format|\n if @proposal.update_attributes(params[:proposal])\n format.html { redirect_to @proposal, notice: 'Proposal was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @proposal.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.update(params[:id], { \n :body => params[:body], \n :answer_type => params[:answer_type] }, \n params[:answers].values\n )\n\n respond_to do |format|\n format.json { render :json => @question.as_json({:include => :answers}) }\n\n # if @question.update_attributes(params[:question])\n # format.html { redirect_to @question, :notice => 'Question was successfully updated.' }\n # format.json { head :no_content }\n # else\n # format.html { render :action => \"edit\" }\n # format.json { render :json => @question.errors, :status => :unprocessable_entity }\n # end\n end\n end", "def update\n respond_to do |format|\n if @practice.update(practice_params)\n format.html { redirect_to new_question_path(practice_id: @practice.id), notice: 'Practice was successfully updated.' }\n format.json { render :show, status: :ok, location: @practice }\n else\n format.html { render :edit }\n format.json { render json: @practice.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @subtopics_question.update(subtopics_question_params)\n format.html { redirect_to @subtopics_question, notice: 'Subtopics question was successfully updated.' }\n format.json { render :show, status: :ok, location: @subtopics_question }\n else\n format.html { render :edit }\n format.json { render json: @subtopics_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @proposal.update(proposal_params)\n format.html { redirect_to @proposal, notice: 'Proposal was successfully updated.' }\n format.json { render :show, status: :ok, location: @proposal }\n else\n format.html { render :edit }\n format.json { render json: @proposal.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize_action_for @question\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_mod\n if params[:title] != nil && params[:content] != nil\n @question.title = params[:title]\n @question.content = params[:content]\n\n question_json = @question.to_h.to_json\n\n url = @httpIp+'/pet.com/api/question/updateQuestion'\n uri = URI(url)\n res = Net::HTTP.post(uri, question_json, \"Content-Type\" => \"application/json\")\n puts res.body\n flash[:notice] = \"successfully updated\"\n redirect_to questions_path\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'La pregunta fue modificada correctamente.' }\n format.json { render :show, status: :ok, location: @question }\n else\n format.html { render :edit }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @questions_quiz.update(questions_quiz_params)\n format.html { redirect_to @questions_quiz, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n format.js { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @questions_quiz.errors, status: :unprocessable_entity }\n format.js { head :unprocessable_entity }\n end\n end\n end", "def course_proposal_question_params\n params.require(:course_proposal_question).permit(:question, :help_text)\n end", "def update\n course = Course.includes(:professors).find(params[:id])\n course.update!(course_params)\n \n course.professor_ids=(params[:professors])\n\n render json: course.to_json(include: :professors)\n end", "def update\n @question = Question.find(params[:id])\n @question.update_attributes(params[:question])\n render :json => @question.id if @question.save\n # respond_to do |format|\n # if @question.update_attributes(params[:question])\n # format.html { redirect_to(@question, :notice => 'Question was successfully updated.') }\n # format.xml { head :ok }\n # else\n # format.html { render :action => \"edit\" }\n # format.xml { render :xml => @question.errors, :status => :unprocessable_entity }\n # end\n # end\n end", "def update\n respond_to do |format|\n if @poll_question.update(poll_question_params)\n format.html { redirect_to @poll_question, notice: 'Poll question was successfully updated.' }\n format.json { render :show, status: :ok, location: @poll_question }\n else\n @polls = Poll.all\n format.html { render :edit }\n format.json { render json: @poll_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.update_attributes(params[:question])\n format.html { redirect_to(@question, :notice => 'Question was successfully updated.') }\n format.xml { head :ok }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @question.errors, :status => :unprocessable_entity }\n\t\t\t\tformat.json { render :json => @question.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @survey = Survey.find_by_id( params[:survey_id] )\n @question = Question.find_by_id( params[:id] )\n\n if @question.update( question_params )\n if params[:commit] == \"Continue to the Next Step\"\n params[:option_num].to_i.times do\n @question.options.create # TODO: cleanup, could create empty options in db\n end\n\n redirect_to edit_survey_question_path(@survey, @question)\n else\n flash.now[:success] = \"Question Added!\"\n\n # Create new empty question for render\n @question = @survey.questions.build\n\n render :new\n end\n else\n flash.now[:error] = \"Sorry, we couldn't add that question due to errors.\"\n render :new\n end\n end", "def update\n respond_to do |format|\n if @community_question.update(community_question_params)\n format.html { redirect_to @community_question, notice: 'Community question was successfully updated.' }\n format.json { render :show, status: :ok, location: @community_question }\n else\n format.html { render :edit }\n format.json { render json: @community_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @question.status == 'published' || @question.version_independent_id != question_params[:version_independent_id]\n render json: @question.errors, status: :unprocessable_entity\n else\n update_response_sets(params)\n @question.update_concepts('Question')\n @question.updated_by = current_user\n if @question.update(question_params)\n @question.groups.each do |group|\n @question.add_to_group(group.id)\n end\n render :show, status: :ok, location: @question\n else\n @categories = Category.all\n render json: @question.errors, status: :unprocessable_entity\n end\n end\n end", "def update\n if @simple_question_alternative.update(simple_question_alternative_params)\n render status: :ok, json: @simple_question_alternative\n else\n self.send(:edit)\n end\n end", "def update\n @survey_question = SurveyQuestion.find(params[:id])\n\n respond_to do |format|\n if @survey_question.update_attributes(params[:survey_question])\n format.html { redirect_to survey_questions_path(@survey_question.survey_id),\n notice: 'Survey question was successfully updated.' }\n #format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n #format.json { render json: @survey_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @add_question.update(add_question_params)\n format.html { redirect_to @add_question, notice: 'Add question was successfully updated.' }\n format.json { render :show, status: :ok, location: @add_question }\n else\n format.html { render :edit }\n format.json { render json: @add_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @category_question = CategoryQuestion.find(params[:id])\n\n respond_to do |format|\n if @category_question.update_attributes(params[:category_question])\n format.html { redirect_to @category_question, notice: 'Category question was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category_question.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n question = Question.find(params[:id])\n authorize question\n\n new_version = question.template.generate_version?\n\n old_question_ids = {}\n if new_version\n # get a map from option number to id\n old_number_to_id = {}\n question.question_options.each do |opt|\n old_number_to_id[opt.number] = opt.id\n end\n\n # get a map from question versionable id to old id\n question.template.questions.each do |q|\n old_question_ids[q.versionable_id] = q.id\n end\n end\n\n question = get_modifiable(question)\n\n question_id_map = {}\n if new_version\n # params now out of sync (after versioning) with the question_options\n # so when we do the question.update it'll mess up\n # need to remap params to keep them consistent\n old_to_new_opts = {}\n question.question_options.each do |opt|\n old_id = old_number_to_id[opt.number]\n old_to_new_opts[old_id.to_s] = opt.id.to_s\n end\n\n question.template.questions.each do |q|\n question_id_map[old_question_ids[q.versionable_id].to_s] = q.id.to_s\n end\n end\n\n # rewrite the question_option ids so they match the new\n # version of the question\n # and also rewrite the remove_data question ids\n attrs = question_params\n attrs = update_option_ids(attrs, old_to_new_opts) if new_version && !attrs['question_options_attributes'].nil?\n\n # Need to reattach the incoming annotation's and question_options to the\n # modifiable (versioned) question\n attrs = transfer_associations(attrs, question) if new_version\n\n # If the user unchecked all of the themes set the association to an empty array\n # add check for number present to ensure this is not just an annotation\n attrs[:theme_ids] = [] if attrs[:theme_ids].blank? && attrs[:number].present?\n if question.update(attrs)\n if question.update_conditions(sanitize_hash(params['conditions']),\n old_to_new_opts, question_id_map)\n flash.now[:notice] = success_message(question, _('updated'))\n end\n else\n flash.now[:alert] = flash.now[:alert] = failure_message(question, _('update'))\n end\n if question.section.phase.template.customization_of.present?\n redirect_to org_admin_template_phase_path(\n template_id: question.section.phase.template.id,\n id: question.section.phase.id,\n section: question.section.id\n )\n else\n redirect_to edit_org_admin_template_phase_path(\n template_id: question.section.phase.template.id,\n id: question.section.phase.id,\n section: question.section.id\n )\n end\n end", "def update\n respond_to do |format|\n if @question.update(question_params)\n format.html { redirect_to @question, notice: 'Question was successfully updated.' }\n format.json { head :no_content }\n format.js { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @question.errors, status: :unprocessable_entity }\n format.js { head :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @proposal.accepted == true\n format.html { redirect_to @proposal, notice: 'The Proposal Can Not Be Changed After It Has Been Assigned' }\n end\n unless params[:proposal][:bts].nil? || params[:proposal][:bts].count == 0\n @proposal.bts.clear\n params[:proposal][:bts].each do |bt|\n @proposal.bts << bt\n end\n end\n unless params[:proposal][:focus_points].nil? || params[:proposal][:focus_points].count == 0\n @proposal.focus_points.clear\n params[:proposal][:focus_points].each do |fp|\n @proposal.focus_points << fp\n end\n end\n if @proposal.update(proposal_params)\n format.html { redirect_to @proposal, notice: 'Proposal was successfully updated.' }\n format.json { render :show, status: :ok, location: @proposal }\n else\n format.html { render :edit }\n format.json { render json: @proposal.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.687026", "0.6672324", "0.6656856", "0.6604427", "0.65882283", "0.65583193", "0.65362805", "0.65351844", "0.6527841", "0.6519026", "0.6497865", "0.6496542", "0.6494913", "0.6458557", "0.64584494", "0.6455926", "0.6454532", "0.64542645", "0.64514244", "0.6447249", "0.6436651", "0.6430294", "0.6430294", "0.6430294", "0.6430294", "0.6430294", "0.6418862", "0.64112395", "0.64110684", "0.6404424", "0.6402499", "0.63991237", "0.6397247", "0.639228", "0.63811696", "0.63811696", "0.63811696", "0.6356796", "0.63544214", "0.6352809", "0.63523144", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6347937", "0.6344981", "0.6337243", "0.63327956", "0.6327584", "0.6318822", "0.6318367", "0.63007694", "0.62992877", "0.6297972", "0.6287494", "0.62870705", "0.62743765", "0.62630266", "0.6259133", "0.6255223", "0.624028", "0.62336165", "0.62274134", "0.62227577", "0.62157047", "0.6204047", "0.62012565", "0.62011415", "0.62010944", "0.6197877", "0.6197442", "0.6189945", "0.6187539", "0.6184967", "0.6183682", "0.6180026", "0.6175216", "0.6157459", "0.6154762", "0.6143708", "0.6143508", "0.6142089", "0.6137251", "0.6135907", "0.6135847", "0.61335" ]
0.7374703
0
DELETE /course_proposal_questions/1 DELETE /course_proposal_questions/1.json
def destroy @course_proposal_question.destroy respond_to do |format| format.html { redirect_to course_proposal_questions_url, notice: 'Course proposal question was successfully destroyed.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @examquestion.destroy\n respond_to do |format|\n format.html { redirect_to examquestions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @test_question = TestQuestion.find(params[:id])\n @test_question.destroy\n\n respond_to do |format|\n format.html { redirect_to test_questions_url }\n format.json { head :ok }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to api_v1_questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @critical_question = CriticalQuestion.find(params[:id])\n @critical_question.destroy\n\n respond_to do |format|\n format.html { redirect_to critical_questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n if @v1_question.destroy\n render json: {'message': 'Deleted question successfully'}, status: :ok\n else\n render json: get_errors, status: :unprocessable_entity\n end\n\n end", "def destroy\n @questionnaire.destroy\n respond_to do |format|\n format.html { redirect_to questionnaires_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @attempt_question.destroy\n respond_to do |format|\n format.html { redirect_to attempt_questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @proposal = Proposal.find(params[:id])\n @proposal.destroy\n\n respond_to do |format|\n format.html { redirect_to root_path, notice: 'Proposal was successfully deleted.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to quiz_path(@question.subsection_id) }\n format.json { head :no_content }\n end\n end", "def destroy\n @apt_question.destroy\n respond_to do |format|\n format.html { redirect_to apt_questions_url, notice: 'Apt question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_v1_question.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n #@question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @questions_option = QuestionsOption.find(params[:id])\n @questions_option.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_options_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :ok }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :ok }\n end\n end", "def destroy\n @parent_question.destroy\n respond_to do |format|\n format.html { redirect_to parent_questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @proposal = Proposal.find(params[:id])\n @proposal.destroy\n\n respond_to do |format|\n format.html { redirect_to proposals_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @proposal = Proposal.find(params[:id])\n @proposal.destroy\n\n respond_to do |format|\n format.html { redirect_to proposals_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @questionable = @question.questionable\n @question.destroy\n respond_to do |format|\n format.html\n format.json { head :no_content }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n\n respond_to do |format|\n if @question.destroy\n format.html { redirect_to @question.course, notice: 'Question was successfully deleted.' }\n format.json { head :ok }\n else\n format.html { redirect_to @question.course, notice: 'Question was not deleted.' }\n format.json { render json: @question.errors, status: :unprocessable_destroy }\n end\n end\n end", "def destroy\n @tutorial_quest = Tutorial::Quest.find(params[:id])\n @tutorial_quest.destroy\n\n respond_to do |format|\n format.html { redirect_to tutorial_quests_url }\n format.json { head :ok }\n end\n end", "def destroy\n @b_question.destroy\n respond_to do |format|\n format.html { redirect_to questions_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to admin_questions_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @questionnaire = Questionnaire.find(params[:id])\n @questionnaire.destroy\n\n respond_to do |format|\n format.html { redirect_to questionnaires_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @questionnaire = Questionnaire.find(params[:id])\n @questionnaire.destroy\n\n respond_to do |format|\n format.html { redirect_to questionnaires_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @intake_question = IntakeQuestion.find(params[:id])\n @intake_question.destroy\n\n respond_to do |format|\n format.html { redirect_to intake_questions_url }\n format.json { head :ok }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url }\n format.json { head :no_content }\n end\n\tend", "def destroy\n @test_question.destroy\n respond_to do |format|\n format.html { redirect_to test_questions_url, notice: 'Test question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @test_question.destroy\n respond_to do |format|\n format.html { redirect_to test_questions_url, notice: 'Test question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question_learned.destroy\n respond_to do |format|\n format.html { redirect_to question_question_learneds_path(@question) }\n format.json { head :no_content }\n end\n end", "def destroy\n @question = Question.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to survey_url(params[:survey_id]) }\n format.json { head :no_content }\n end\n end", "def destroy\n @multiple_choice_question = MultipleChoiceQuestion.find(params[:id])\n @multiple_choice_question.destroy\n\n respond_to do |format|\n format.html { redirect_to multiple_choice_questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exam.destroy\n respond_to do |format|\n format.html { redirect_to course_exams_url(@exam.course_id) }\n format.json { head :no_content }\n end\n end", "def destroy\n @cards_question = Cards::Question.find(params[:id])\n @cards_question.destroy\n\n respond_to do |format|\n format.html { redirect_to cards_questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n course = Course.includes(:professors).find(params[:id])\n course.destroy\n \n render :json => course\n end", "def destroy\n @proposal.destroy\n respond_to do |format|\n format.html { redirect_to proposals_url, notice: 'Proposal was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @proposal.destroy\n respond_to do |format|\n format.html { redirect_to proposals_url, notice: 'Proposal was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @proposal.destroy\n respond_to do |format|\n format.html { redirect_to proposals_url, notice: 'Proposal was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_question\n question_params = params.permit(:id, :form_id, :question_type_id)\n\n render json: Question.delete_question(question_params)\n end", "def destroy\n @proposal.destroy\n\n respond_to do |format|\n format.html { redirect_to :back }\n format.json { head :no_content }\n end\n end", "def destroy\n @question_requirement = QuestionRequirement.find(params[:id])\n @question_requirement.destroy\n\n respond_to do |format|\n format.html { redirect_to(question_requirements_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to category_questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n #make sure we only let admins delete questions, or the current user delete their own questions\n if (@current_user.id == @question.user_id) || user_is_admin?\n @course = Course.find(@question.course_id)\n Answer.destroy_all(question_id: @question.id)\n @question.destroy\n respond_to do |format|\n format.html { redirect_to course_path(@course)}\n format.json { head :no_content }\n end\n else\n redirect_to courses_url\n end\n end", "def destroy\n @question.active = !@question.active\n\n questions_json = @question.to_h.to_json\n\n url = @httpIp+'/pet.com/api/question/updateQuestion'\n uri = URI(url)\n res = Net::HTTP.post(uri, questions_json, \"Content-Type\" => \"application/json\")\n puts res.body\n flash[:notice] = \"successfully deleted\"\n redirect_to questions_path\n end", "def destroy\n @poll_question = PollQuestion.find(params[:id])\n @poll_question.destroy\n\n respond_to do |format|\n format.html { redirect_to poll_questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to paper_questions_path, notice: '題目已被成功刪除' }\n format.json { head :no_content }\n end\n end", "def delete\n question = QuestionTest.where(test_id: params[:test_id], question_id: params[:id])\n if question.delete_all\n return render json: {message: 'Question was removed succesfully.', error: false}\n else\n return render json: {message: 'Error: Something went wrong. Question was not removed.', error: true}\n end\n end", "def destroy\n @oncourse_exercise.destroy\n respond_to do |format|\n format.html { redirect_to oncourse_exercises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @survey_question.destroy\n @survey_questions = SurveyQuestion.all\n # @survey_question.destroy\n # respond_to do |format|\n # format.html { redirect_to survey_questions_url, notice: 'Survey question was successfully destroyed.' }\n # format.json { head :no_content }\n # end\n end", "def destroy\n @survey_question = SurveyQuestion.find(params[:id])\n @survey_question.destroy\n\n respond_to do |format|\n format.html { redirect_to survey_questions_url }\n # format.json { head :no_content }\n end\n end", "def destroy\n @question = @quiz.questions.find(params[:id])\n @question.destroy\n\n respond_to do |format|\n format.html { redirect_to(quiz_questions_url(@quiz)) }\n format.xml { head :ok }\n end\n end", "def destroy\n @quiz.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @question_link = QuizQuestion.find_by_id(@question.questionid)\n @quiz = Quiz.find_by_id(@question_link.quizid)\n @question_link.destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to admin_quiz_path(@quiz), notice: 'Quiz multiple choice question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @community_question.destroy\n respond_to do |format|\n format.html { redirect_to community_questions_url, notice: 'Community question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = @key_questions_project.project\n @key_questions_project.destroy\n respond_to do |format|\n format.html do\n redirect_to edit_project_path(@project, page: 'key_questions'),\n notice: t('removed')\n end\n format.json { head :no_content }\n end\n end", "def destroy\n @completed_quest = CompletedQuest.find(params[:id])\n @completed_quest.destroy\n\n respond_to do |format|\n format.html { redirect_to completed_quests_url }\n format.json { head :ok }\n end\n end", "def destroy\n @question.destroy\n\n respond_to do |format|\n if @question.save\n format.html { redirect_to admin_course_path(@course), notice: 'Question was successfully deleted.' }\n else\n format.html { redirect_to admin_course_path(@course), notice: 'Question was not be deleted. Please try again later.' }\n end\n end\n end", "def destroy\n @proposal = Proposal.find(params[:id])\n committee = @proposal.committee\n @proposal.destroy\n\n respond_to do |format|\n format.html { redirect_to committee_path(committee) }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @question.destroy\n respond_to do |format|\n format.html { redirect_to questions_url, notice: \"Question was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @my_question = MyQuestion.find(params[:id])\n @my_question.destroy\n\n respond_to do |format|\n format.html { redirect_to my_questions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n curr_id = @parts_for_proposal.proposal_id\n @parts_for_proposal.destroy\n respond_to do |format|\n format.html { redirect_to proposal_url(:id => curr_id), notice: 'Part configuration was successfully removed.' }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @intern_question = InternQuestion.find(params[:id])\r\n @intern_question.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to intern_questions_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @questionnaire.destroy\n respond_to do |format|\n format.html { redirect_to questionnaires_url, notice: 'Questionnaire was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @questionnaire.destroy\n respond_to do |format|\n format.html { redirect_to questionnaires_url, notice: \"Questionnaire was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end" ]
[ "0.74135524", "0.7341972", "0.7326205", "0.73218465", "0.72966427", "0.72838473", "0.72794825", "0.7266921", "0.7263273", "0.7254235", "0.7248843", "0.7248843", "0.7248843", "0.7248843", "0.7248843", "0.7248843", "0.72465396", "0.72347593", "0.7213497", "0.7212765", "0.72127455", "0.72127455", "0.72127455", "0.72127455", "0.72127455", "0.72127455", "0.72123945", "0.7209989", "0.7209989", "0.7208955", "0.7205816", "0.7205816", "0.71990055", "0.71797246", "0.7177318", "0.7177089", "0.7171046", "0.71635497", "0.71635497", "0.7163119", "0.71600235", "0.71586996", "0.71586996", "0.7158066", "0.71575963", "0.7143536", "0.71196747", "0.71068895", "0.7087612", "0.708524", "0.708524", "0.708524", "0.70797473", "0.70796", "0.7078716", "0.70694655", "0.7064908", "0.7061736", "0.7051733", "0.70486706", "0.7044535", "0.704105", "0.70400673", "0.7034759", "0.7026007", "0.70195735", "0.70069164", "0.70012355", "0.7001077", "0.69967747", "0.6993682", "0.69922036", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69890743", "0.69876873", "0.6985648", "0.69845164", "0.69814825", "0.6980297", "0.69770527" ]
0.80670506
0
Use callbacks to share common setup or constraints between actions.
def set_course_proposal_question @course_proposal_question = CourseProposalQuestion.find(params[:id]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_required_actions\n # TODO: check what fields change to asign required fields\n end", "def action_hook; end", "def run_actions; end", "def define_action_hook; end", "def actions; end", "def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end", "def add_actions; end", "def callbacks; end", "def callbacks; end", "def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end", "def define_action_helpers; end", "def post_setup\n end", "def action_methods; end", "def action_methods; end", "def action_methods; end", "def before_setup; end", "def action_run\n end", "def execute(setup)\n @action.call(setup)\n end", "def define_action_helpers?; end", "def set_actions\n actions :all\n end", "def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end", "def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end", "def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end", "def setup_handler\n end", "def before_actions(*logic)\n self.before_actions = logic\n end", "def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end", "def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end", "def action; end", "def action; end", "def action; end", "def action; end", "def action; end", "def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end", "def workflow\n end", "def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end", "def before(action)\n invoke_callbacks *self.class.send(action).before\n end", "def process_action(...)\n send_action(...)\n end", "def before_dispatch(env); end", "def setup\n # override and do something appropriate\n end", "def after_actions(*logic)\n self.after_actions = logic\n end", "def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end", "def setup(_context)\n end", "def setup(resources) ; end", "def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end", "def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end", "def determine_valid_action\n\n end", "def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end", "def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end", "def startcompany(action)\n @done = true\n action.setup\n end", "def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end", "def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end", "def define_tasks\n define_weave_task\n connect_common_tasks\n end", "def setup(&block)\n define_method(:setup, &block)\n end", "def setup\n transition_to(:setup)\n end", "def setup\n transition_to(:setup)\n end", "def action\n end", "def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend", "def config(action, *args); end", "def setup\n @setup_proc.call(self) if @setup_proc\n end", "def before_action \n end", "def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end", "def action\n end", "def matt_custom_action_begin(label); end", "def setup\n # override this if needed\n end", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end", "def after(action)\n invoke_callbacks *options_for(action).after\n end", "def pre_task\n end", "def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end", "def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end", "def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end", "def setup_signals; end", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end", "def initialize(*args)\n super\n @action = :set\nend", "def setup\n #implement in subclass;\n end", "def after_set_callback; end", "def lookup_action; end", "def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end", "def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end", "def release_actions; end", "def setup(easy)\n super\n easy.customrequest = @verb\n end", "def around_hooks; end", "def save_action; end", "def action_target()\n \n end", "def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end", "def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end", "def before_setup\n # do nothing by default\n end", "def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end", "def default_action; end", "def setup(&blk)\n @setup_block = blk\n end", "def callback_phase\n super\n end", "def advice\n end", "def _handle_action_missing(*args); end", "def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end", "def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend", "def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end", "def duas1(action)\n action.call\n action.call\nend" ]
[ "0.6165152", "0.60463154", "0.59467196", "0.5917112", "0.5890387", "0.58345735", "0.57773316", "0.56991524", "0.56991524", "0.565454", "0.5622282", "0.54232633", "0.54119074", "0.54119074", "0.54119074", "0.53937256", "0.53801376", "0.5358599", "0.53412294", "0.5340814", "0.53314966", "0.53114754", "0.52984965", "0.52977055", "0.5296272", "0.5260649", "0.5245076", "0.52388334", "0.52388334", "0.52388334", "0.52388334", "0.52388334", "0.5235081", "0.52321917", "0.5228592", "0.5220735", "0.52198535", "0.52139324", "0.5208539", "0.5206585", "0.5178542", "0.5175199", "0.5173538", "0.5167041", "0.51614195", "0.51577675", "0.5153909", "0.51528823", "0.5152225", "0.51429904", "0.5141399", "0.51345575", "0.51145", "0.5114052", "0.5114052", "0.5110216", "0.5108656", "0.50935394", "0.5089196", "0.5081936", "0.5079627", "0.50675833", "0.5056105", "0.5053687", "0.5050475", "0.5050475", "0.503471", "0.5028311", "0.501982", "0.50157547", "0.5013552", "0.50014806", "0.50011593", "0.49976763", "0.4990292", "0.4990292", "0.49882022", "0.4981269", "0.49792367", "0.49766538", "0.4967978", "0.49667212", "0.4958987", "0.49572337", "0.49550423", "0.4954479", "0.4952353", "0.494726", "0.4944055", "0.4935437", "0.4931248", "0.49283475", "0.49281213", "0.49268973", "0.4921738", "0.49204507", "0.4918924", "0.49182287", "0.4916538", "0.49158585", "0.49156788" ]
0.0
-1
Never trust parameters from the scary internet, only allow the white list through.
def course_proposal_question_params params.require(:course_proposal_question).permit(:question, :help_text) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def strong_params\n params.require(:user).permit(param_whitelist)\n end", "def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end", "def allow_params_authentication!; end", "def allowed_params\n ALLOWED_PARAMS\n end", "def default_param_whitelist\n [\"mode\"]\n end", "def param_whitelist\n [:role, :title]\n end", "def expected_permitted_parameter_names; end", "def safe_params\n params.except(:host, :port, :protocol).permit!\n end", "def strong_params\n params.require(:team_member).permit(param_whitelist)\n end", "def permitir_parametros\n \t\tparams.permit!\n \tend", "def strong_params\n params.require(:community).permit(param_whitelist)\n end", "def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end", "def strong_params\n params.require(:education).permit(param_whitelist)\n end", "def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end", "def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end", "def param_whitelist\n [:rating, :review]\n end", "def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end", "def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end", "def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end", "def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end", "def valid_params_request?; end", "def strong_params\n params.require(:experience).permit(param_whitelist)\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end", "def allowed_params\n params.require(:allowed).permit(:email)\n end", "def permitted_params\n []\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end", "def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend", "def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end", "def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end", "def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end", "def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end", "def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end", "def safe_params\n params.require(:user).permit(:name)\n end", "def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend", "def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end", "def check_params; true; end", "def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end", "def quote_params\n params.permit!\n end", "def valid_params?; end", "def paramunold_params\n params.require(:paramunold).permit!\n end", "def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend", "def filtered_parameters; end", "def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end", "def filtering_params\n params.permit(:email, :name)\n end", "def check_params\n true\n end", "def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend", "def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend", "def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end", "def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end", "def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end", "def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend", "def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end", "def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end", "def active_code_params\n params[:active_code].permit\n end", "def filtering_params\n params.permit(:email)\n end", "def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end", "def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end", "def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end", "def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end", "def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end", "def list_params\n params.permit(:name)\n end", "def filter_parameters; end", "def filter_parameters; end", "def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end", "def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end", "def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end", "def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end", "def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end", "def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end", "def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end", "def url_whitelist; end", "def admin_social_network_params\n params.require(:social_network).permit!\n end", "def filter_params\n params.require(:filters).permit(:letters)\n end", "def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end", "def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end", "def sensitive_params=(params)\n @sensitive_params = params\n end", "def permit_request_params\n params.permit(:address)\n end", "def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end", "def secure_params\n params.require(:location).permit(:name)\n end", "def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end", "def question_params\n params.require(:survey_question).permit(question_whitelist)\n end", "def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end", "def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end", "def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end", "def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end", "def url_params\n params[:url].permit(:full)\n end", "def backend_user_params\n params.permit!\n end", "def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend", "def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end", "def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end", "def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end", "def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end", "def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end", "def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end", "def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end", "def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end" ]
[ "0.69792545", "0.6781151", "0.67419964", "0.674013", "0.6734356", "0.6591046", "0.6502396", "0.6496313", "0.6480641", "0.6477825", "0.64565", "0.6438387", "0.63791263", "0.63740575", "0.6364131", "0.63192815", "0.62991166", "0.62978333", "0.6292148", "0.6290449", "0.6290076", "0.62894756", "0.6283177", "0.6242471", "0.62382483", "0.6217549", "0.6214457", "0.6209053", "0.6193042", "0.6177802", "0.6174604", "0.61714715", "0.6161512", "0.6151757", "0.6150663", "0.61461", "0.61213595", "0.611406", "0.6106206", "0.6105114", "0.6089039", "0.6081015", "0.6071004", "0.60620916", "0.6019971", "0.601788", "0.6011056", "0.6010898", "0.6005122", "0.6005122", "0.6001556", "0.6001049", "0.59943926", "0.5992201", "0.59909594", "0.5990628", "0.5980841", "0.59669393", "0.59589154", "0.5958826", "0.5957911", "0.5957385", "0.5953072", "0.59526145", "0.5943361", "0.59386164", "0.59375334", "0.59375334", "0.5933856", "0.59292704", "0.59254247", "0.5924164", "0.59167904", "0.59088355", "0.5907542", "0.59064597", "0.5906243", "0.5898226", "0.589687", "0.5896091", "0.5894501", "0.5894289", "0.5891739", "0.58860534", "0.5882406", "0.587974", "0.58738774", "0.5869024", "0.58679986", "0.5867561", "0.5865932", "0.5864461", "0.58639693", "0.58617616", "0.5861436", "0.5860451", "0.58602303", "0.5854586", "0.58537364", "0.5850427", "0.5850199" ]
0.0
-1
If real_move is false, the move will be undone regardless of legality. Either way, move_to! will return true if the move is fully legal, and false otherwise.
def move_to!(new_x, new_y, real_move = true) return false unless game.current_player == color return false unless valid_move?(new_x, new_y) if (destination_piece = game.piece_at(new_x, new_y)) return capture_piece!(new_x, new_y, destination_piece, real_move) end update_piece_attributes(new_x, new_y, real_move) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def legal_move?(move)\n captured_piece = @board.data[move[0]][move[1]]\n move_current_piece(move)\n king = @king_location || move\n result = safe_king?(king)\n @board.data[move[0]][move[1]] = captured_piece\n result\n end", "def legal_move?(move)\n captured_piece = @board.data[move[0]][move[1]]\n move_current_piece(move)\n king = @king_location || move\n result = safe_king?(king)\n @board.data[move[0]][move[1]] = captured_piece\n result\n end", "def move_to!(new_x, new_y, real_move = true)\n return false unless valid_move?(new_x, new_y)\n castling = (x_coord - new_x).abs == 2\n\n # Call the move_to! method within the Piece model and move the king.\n return false unless super\n\n # If all of the requirements are met for valid_move? AND the intention is to castle;\n # place the rook in its appropriate position to complete the castling move.\n if castling\n rook_origin_file = (new_x == 3) ? 1 : 8\n rook_destination_file = (new_x == 3) ? 4 : 6\n castled_rook = game.piece_at(rook_origin_file, new_y)\n castled_rook.update_attributes(x_coord: rook_destination_file,\n y_coord: new_y,\n moved: true)\n end\n true\n end", "def move(to,board)\n if self.legal?(to,board)\n @coords = to\n @moved = true\n else\n return false\n end\n end", "def move_to!(new_x, new_y, real_move = true)\n # Make note of a pawn captured en passant. Don't destroy it until after\n # the call to super, which ensures that the move is valid.\n en_passant_victim = en_passant_capturee(new_x, new_y)\n\n # If the pawn is advancing two squares, it may be captured en passant on\n # the next move.\n en_passant_file = (new_y - y_coord).abs == 2 ? x_coord : nil\n\n # Call the Piece class's move_to! method. If it returns false, that means\n # it's rejecting the move. Make sure execution stops here in that case.\n return false unless super\n\n # Wait until after super has been called to update this. Otherwise, an en\n # passant capture would be rejected by super's call to valid_move?, which\n # would return false because en_passant_file has been updated to nil.\n game.update_attribute(:en_passant_file, en_passant_file)\n\n # Now, destroy a pawn captured en passant.\n en_passant_victim && en_passant_victim.destroy\n\n # TODO: Implement the promote! method.\n # promote! if y_coord == nth_rank(8)\n\n true\n end", "def valid_move?(x, y)\n return false if is_obstructed?(x, y)\n diagonal_move_left?(x, y) || diagonal_move_right?(x,y)\n \n end", "def legal_move?(board,from,to)\n\t\treturn false unless super(board,to)\n\t\tfrom_y = from[1]\n\t\tfrom_x = from[0]\n\t\tto_y = to[1]\n\t\tto_x = to[0]\n\t\t#when trying to move diagonally\n\t\tif from_x != to_x\n\t\t\t#checks colour of pawn\n\t\t\tif colour == \"white\"\n\t\t\t\t#checks only 1 vertical move away\n\t\t\t\tif (from_y-to_y) == 1\n\t\t\t\t\treturn true\n\t\t\t\telse\n\t\t\t\t\tputs \"No enemy pawn there\"\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tif (to_y-from_y) == 1\n\t\t\t\t\treturn true\n\t\t\t\telse\n\t\t\t\t\tputs \"No enemy pawn there\"\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t#when trying to move straight\n\t\tif colour == \"white\"\n\t\t\tif from_y == 6\n\t\t\t\tif (from_y-to_y) <= 2 && board.get_piece(to) == \"_\"\n\t\t\t\t\treturn true\n\t\t\t\telse\n\t\t\t\t\tputs \"Can only move 1 or 2 spaces from here and or another piece already there\"\n\t\t\t\t\treturn false\n\t\t\t\tend\t\t\t\t\t\n\t\t\telse\n\t\t\t\tif (from_y-to_y) == 1 && board.get_piece(to) == \"_\"\n\t\t\t\t\treturn true\n\t\t\t\telse\n\t\t\t\t\tputs \"Can only move 1 space from here and or another piece already there\"\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\tif from_y == 1\n\t\t\t\tif (to_y-from_y) <= 2 && board.get_piece(to) == \"_\"\n\t\t\t\t\treturn true\n\t\t\t\telse\n\t\t\t\t\tputs \"Can only move 1 or 2 spaces from here and or another piece already there\"\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tif (to_y-from_y) == 1 && board.get_piece(to) == \"_\"\n\t\t\t\t\treturn true\n\t\t\t\telse\n\t\t\t\t\tputs \"Can only move 1 space from here and or another piece already there\"\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_move?(destination)\n occupant = @board[destination]\n result = false\n if occupant.nil? || (enemy? occupant)\n result = movement_rule(destination)\n end\n\n result\n end", "def valid_move?(move)\n\t\tif in_bounds?(move) && empty_space?(move) && any_converted_pieces?(move)\n\t\t\treturn true\n\t\telse \n\t\t\treturn false\n\t\tend \n\tend", "def move(move = {})\n begin\n move!(move)\n rescue => e\n errors.add :base, e.message\n return false\n end\n end", "def is_legal?(game_state, move)\n move_list = legal_moves(game_state)\n \n move_list.each do |m|\n return true if move == m\n end\n \n false\n end", "def move?\n return @moving\n end", "def valid_move?(move)\n new_position = @current_player.position_after_move(move)\n\n if(@players.available_moves(@current_player).include? move)\n if(@mine.mineable?(new_position) && @current_player.tunneler != move)\n @current_player.damage(5, \"bumping into the wall\")\n return false\n elsif(@rubies.ruby_at_position(new_position))\n puts \"Found a ruby! Take it home!\"\n @current_player.load_up(@rubies.ruby_at_position(new_position))\n elsif(@current_player.home?(new_position))\n @current_player.unload_ruby\n end\n return true\n end\n\n false\n end", "def valid_move?(from, to, player)\n if piece = player_piece?(from, player)\n unless player_piece?(to, player)\n return piece.valid_dest?(to, @board)\n end\n end\n false\n end", "def move_possible?(target)\n self != target && # Can't target self\n same_scope?(target) && # can't be in different scopes\n # !(left..right).include?(target.left..target.right) # this needs tested more\n # detect impossible move\n !((left <= target.left && right >= target.left) or (left <= target.right && right >= target.right))\n end", "def safe_move?( team, from_row, from_col, to_row, to_col)\n backup_board = Marshal.load(Marshal.dump(board))\n\n # try the move\n board.move_piece(from_row,from_col,to_row,to_col)\n piece_sensing\n\n if game_state == \"check_#{team}\".to_sym\n result = false\n else\n result = true\n end\n\n # reverse move and switch back to the backup board\n board.move_piece(to_row,to_col,from_row,from_col)\n self.board = backup_board\n piece_sensing\n\n # Return the result of this check\n result\n end", "def move!(move = {})\n raise GameNotStarted, 'this game is not running' unless started?\n\n raise InvalidPlayerMove, 'this player is not authorized for this move' unless move_valid_for?(current_mover.id)\n\n if board.move!(move.fetch(:y_axis).to_i, move.fetch(:x_axis).to_i, current_mover.id)\n move.merge!(player_id: current_mover.id)\n self.board.moves.create!(move)\n\n update_columns({last_player_id: current_mover.id})\n else\n return false\n end\n\n # checking out for possible result!\n game_over?\n\n true\n end", "def move?\n @moving\n end", "def legal_move? piece, square\n if square.piece.nil? || square.piece.color != piece.color\n case piece.symbol\n\n when \"♟︎\", \"♙\"\n # Return true if square is adjacent and in the correct direction for pawn of that color\n pawn_move?(piece, square)\n when \"♞\", \"♘\"\n # Return true if move is an 'L' shape\n knight_move?(piece.square, square)\n when \"♝\", \"♗\"\n # Return true if move is diagonal and the path is not blocked by a piece\n if bishop_move?(piece.square, square) && clear_path?(piece.square, square)\n true\n else \n false\n end\n when \"♜\", \"♖\"\n # Return true if move is vertical/horizontal and path not blocked by a piece\n if rook_move?(piece.square, square) && clear_path?(piece.square, square)\n true\n else \n false\n end\n when \"♛\", \"♕\"\n # Return true if move is a straight line and path is not blocked by a piece\n if queen_move?(piece.square, square) && clear_path?(piece.square, square)\n true\n else \n false\n end\n when \"♚\", \"♔\"\n # Return true if move is in any direction but only to an adjacent square, and the square is not under attack from a piece\n king_move?(piece, square)\n else\n false\n end\n else\n false\n end\n end", "def legal_move?(new_x, new_y)\n return false unless actual_move?(new_x, new_y)\n return_val = false\n piece_moved_start_x = x_position\n piece_moved_start_y = y_position\n piece_captured = nil\n piece_captured_x = nil\n piece_captured_y = nil\n # check if you are moving pawn in en passant capture of enemy pawn\n if type == PAWN && !square_occupied?(new_x, new_y)\n if (new_x - piece_moved_start_x).abs == 1 && (new_y - piece_moved_start_y).abs == 1\n piece_captured = game.get_piece_at_coor(new_x, piece_moved_start_y)\n piece_captured_x = new_x\n piece_captured_y = piece_moved_start_y\n end\n end\n # return false if move is invalid for this piece for any of the reasons checked in piece #valid_move?\n return false unless valid_move?(new_x, new_y)\n # If square is occupied, respond according to whether piece is occupied by friend or foe\n if square_occupied?(new_x, new_y)\n occupying_piece = game.get_piece_at_coor(new_x, new_y)\n return false if (occupying_piece.is_white && is_white?) || (!occupying_piece.is_white && !is_white?)\n # since player is trying to capture a friendly piece\n piece_captured = occupying_piece\n piece_captured_x = occupying_piece.x_position\n piece_captured_y = occupying_piece.y_position\n capture_piece(occupying_piece)\n end\n # only here do we update coordinates of piece moved, once we have saved all starting coordinates of piece moved and any piece it captured\n update(x_position: new_x, y_position: new_y)\n increment_move\n return_val = true unless game.check?(is_white)\n update(x_position: piece_moved_start_x, y_position: piece_moved_start_y)\n piece_captured.update(x_position: piece_captured_x, y_position: piece_captured_y) unless piece_captured.nil?\n decrement_move\n return_val\n end", "def valid_move?(move)\n move.to_i.between?(1,9) && !taken?(move)\n end", "def normal_move?(to_x, to_y)\n return true if (to_y - y_position).abs == 1 && to_x == x_position\n false\n end", "def valid_move?(board, position)\n position = position.to_i\n return false if !valid_position?(position)\n return false if position_taken?(board, position)\n return true\nend", "def is_move_allowed(to_x,to_y) #Checks to see if the move is allowed based on the pieces 'rule'\n allowed=false\n \n x_diff=(to_x-@x).abs\n y_diff=(to_y-@y).abs\n \n if x_diff <=1 && y_diff <=1\n allowed= true\n end\n if x==to_x && y==to_y\n allowed = false\n end\n\n return allowed\n end", "def valid?(move)\n @board.valid_move?(move)\n end", "def could_be_valid_move?\n return @board_gfx.is_draggingpiece_valid?\n end", "def valid_move?(new_x, new_y)\n true\n end", "def moving?\n !@start_move\n end", "def validMove(piece, newLocation)\n # piece can move to any empty adjacent space.\n # might need to account for placing pieces. can be counted as a fly move i guess \n\n if newLocation == nil || piece == nil\n return false\n end\n\n # check if its a fly move. \n if @player1.isActive\n if @player1.numPlayedPieces <= 3\n fly = true \n else\n fly = false\n end\n else\n if @player2.numPlayedPieces <= 3\n fly = true \n else\n fly = false\n end\n end\n\n\n #checks if space is empty:\n if newLocation.isEmpty()\n # check if its a fly move\n if fly\n # if its a fly and the target location is empty its allowed. \n return true\n elsif piece.location == nil\n return true\n else\n # should return true if the move is valid.\n return @board.isAdjacent(piece,newLocation)\n end\n else\n # should the space is not empty, the move is invalid\n return false\n end\n\n end", "def is_move_valid(move)\n @moves.include? move\n end", "def valid_move?(board, ix)\n if position_taken?(board, ix) == false && move_val?(ix) == true\n return true\n else\n false\n end\nend", "def check_valid_move to_move\r\n\t\t\r\n\t\tif to_move == 0\r\n\t\t\tif driver.location.west_road == nil\r\n\t\t\t\treturn false\r\n\t\t\telse\r\n\t\t\t\treturn true\r\n\t\t\tend\r\n\t\t\r\n\t\telsif to_move == 1\r\n\t\t\tif driver.location.north_road == nil\r\n\t\t\t\treturn false\r\n\t\t\telse\r\n\t\t\t\treturn true\r\n\t\t\tend\r\n\t\t\r\n\t\telsif to_move == 2\r\n\t\t\tif driver.location.east_road == nil\r\n\t\t\t\treturn false\r\n\t\t\telse\r\n\t\t\t\treturn true\r\n\t\t\tend\r\n\t\t\r\n\t\telsif to_move == 3\r\n\t\t\tif driver.location.south_road == nil\r\n\t\t\t\treturn false\r\n\t\t\telse\r\n\t\t\t\treturn true\r\n\t\t\tend\r\n\t\telse\r\n\t\t\traise \"The location does not exist. Error\"\r\n\t\t\r\n\t\tend\r\n\t\treturn false\r\n\tend", "def valid_move?(move)\n # Array of all posiible moves , check the board and map out the possible moves from there.\n end", "def valid_move?(move)\n move = move.to_i if move.is_a? String\n return false unless move.is_a? Integer\n move.between?(1, 9) && !position_taken?(move-1) \n end", "def valid_move?(destination)\n possible_moves.select do |move|\n on_board?(move) && open?(move)\n end\n\n possible_moves.include?(destination)\n end", "def valid_move?(x_des, y_des)\n ( no_x_move?(x_des) && standard_move?(x_des, y_des) ) ||\n ( promotion_move?(x_des, y_des) || pawn_capture_move?(x_des, y_des) )\n end", "def is_move_available?\n self.robot.world.is_move_available?(self.x, self.y)\n end", "def try_move(move)\n\t\tsetup if !ready?\n\n\t\t# gen all possible moves\n\t\tmoves = generate_moves(self.pieces, self.turn)\n\t\treturn nil if moves.length == 0\n\t\tvalid_move = moves.find { | m | m.from == move.from && m.to == move.to }\n\t\treturn nil if valid_move.nil?\n\n\t\t# filter out moves that would leave us in check\n\t\tmoves = filter_for_self_check(self.pieces, moves, self.turn)\n\t\treturn nil if moves.length == 0\n\t\tvalid_move = moves.find { | m | m.from == move.from && m.to == move.to }\n\t\treturn nil if valid_move.nil?\n\n\t\t# perform the move\n\t\tvalid_move = perform_move(valid_move)\n\t\tif valid_move.promoted.nil?\n\t\t\tvalid_move = update_after_move(valid_move)\n\t\tend\n \n\t\t# create a new board and set it equal to this one, then save it\n\t\tnext_board = Board.new\n\t\tnext_board.game = self.game\n\t\tnext_board.set(self.fen)\n\t\tif !next_board.save!\n\t\t\treturn nil\n\t\tend\n\n\t\t# finally return our move to the game model\n\t\treturn valid_move\n\tend", "def valid_move?(to_row, to_col, board, color)\r\n return false if super == false\r\n return legal_move?(to_row, to_col, board) && move_not_in_check?(@row, @col, to_row, to_col, board)\r\n\tend", "def standard_move?(x_des, y_des)\n y_chg = (y_des.to_i - y_position).abs\n x_chg = (x_des.to_i - x_position).abs\n x_chg == 0 && ( y_chg == 1 ||\n ( first_move_pawn? && move_forward_two?(x_des, y_des) ) )\n end", "def valid_move?(board, index)\n if board[index].nil? || position_taken?(board, index) || board[index] == \"X\" || board[index] == \"O\"\n false\n else\n true\n end\nend", "def valid_move?(piece, location)\n\t\tif valid?(piece, location) == false\n\t\t\treturn false\n\t\tend\n\t\t\n\t\tif location_at_offset?(piece, location, 1, 1)\n\t\t\treturn true\n\t\tend\n\t\t\n\t\tif location_at_offset?(piece, location, -1, 1)\n\t\t\treturn true\n\t\tend\n\t\t\n\t\tif location_at_offset?(piece, location, 1, -1)\n\t\t\treturn true\n\t\tend\n\t\t\n\t\tif location_at_offset?(piece, location, -1, -1)\n\t\t\treturn true\n\t\tend\n\t\t\n\t\tif valid_jump?(piece, location) == nil\n\t\t\treturn false\n\t\telse\n\t\t\treturn true\n\t\tend\n\tend", "def valid_move?(piece, location)\n\t\tif valid?(piece, location) == false\n\t\t\treturn false\n\t\tend\n\t\t\n\t\tif location_at_offset?(piece, location, 1, 1)\n\t\t\treturn true\n\t\tend\n\t\t\n\t\tif location_at_offset?(piece, location, -1, 1)\n\t\t\treturn true\n\t\tend\n\t\t\n\t\tif location_at_offset?(piece, location, 1, -1)\n\t\t\treturn true\n\t\tend\n\t\t\n\t\tif location_at_offset?(piece, location, -1, -1)\n\t\t\treturn true\n\t\tend\n\t\t\n\t\tif valid_jump?(piece, location) == nil\n\t\t\treturn false\n\t\telse\n\t\t\treturn true\n\t\tend\n\tend", "def valid_move?(from_row, from_column, to_row, to_column)\n piece = @state[from_row][from_column]\n return false if piece == nil\n\n new_location = [to_row, to_column]\n return false unless piece.moves.include? new_location\n\n return pawn_valid_move?(piece, new_location, to_column, from_column) if\n piece.class == Pawn\n\n return false unless empty_location?([to_row, to_column]) || \n enemy_piece_at_location?(piece.color, new_location)\n\n unless piece.class == Knight || piece.class == King\n return no_pieces_in_between?(from_row, from_column, to_row, to_column)\n end\n\n true\n end", "def can_move?(end_pos)\n return false if end_pos == self.pos\n return false unless on_board?(end_pos)\n return false unless self.pos.vertical_to?(end_pos) || self.pos.horizontal_to?(end_pos)\n return false if own_piece?(@board[end_pos])\n all_moves = self.pos.to(end_pos)\n return false if all_moves.empty?\n return false unless not_blocked?(all_moves)\n return false unless (self.pos - end_pos) != nil && (self.pos - end_pos).two_norm_square == 2\n return false if is_square_in_check?(end_pos, @@opponent_color[self.color])\n return true\n end", "def possible_move?(origin_piece, test_row, test_col)\n if !board.piece_exists?(test_row,test_col) ||\n board.piece_team(test_row,test_col) != board.piece_team(origin_piece.row,origin_piece.col)\n if origin_piece.class == Pawn\n pawn_possible_move?(origin_piece, test_row, test_col)\n else\n true\n end\n else\n false\n end\n end", "def valid_move?(position)\n position.between?(0,8) && !position_taken?(position)\n end", "def commit_move?(piece, desired_space)\n get_travel_path(piece, desired_space)\n valid_move?(piece, desired_space)\n end", "def valid_move?(location)\n location.to_i.between?(1,9) && !position_taken?(location.to_i-1)\n end", "def update_force?\r\n # If move route is forced\r\n if @move_route_forcing\r\n # Custom move\r\n move_type_custom\r\n return true\r\n end\r\n return false\r\n end", "def is_legit_move?(move)\n return all_points[move].nil?\n end", "def allowed_move?(vector, starting_rank=nil)\n self.class.allowed_move?(vector, starting_rank)\n end", "def position_taken?(board, position)\n return false if valid_move?(board, position)\n return true unless valid_move?(board, position)\nend", "def legal_move?(x_destination, y_destination)\n x_movement_difference = (x_destination - self.x_pos).abs\n y_movement_difference = (y_destination - self.y_pos).abs\n\n x_movement_difference.between?(0, 1) && y_movement_difference.between?(0, 1)\n end", "def valid_move?(from, to, pieces)\n # check if move is forward for plain piece (not king)\n row = Game.index_to_row(from)\n if Game.is_king?(pieces[from-1]) # kings can go in both direction\n return false if (row + 1 != Game.index_to_row(to)) and (row - 1 != Game.index_to_row(to)) \n elsif Game.is_red?(pieces[from-1])\n return false if row + 1 != Game.index_to_row(to)\n elsif Game.is_white?(pieces[from-1]) and !Game.is_king?(pieces[from-1]) # kings can go in both direction\n return false if row - 1 != Game.index_to_row(to)\n end\n map = get_possible_moves_map\n map[from].include? to\n end", "def valid_move?\n\t\t# Now let's make sure all of the moves are valid.\n\t\t# I'll do this by seeing if the sorted version of each\n\t\t# column equals the @board version.\n\t\ttemp_board = Marshal.load(Marshal.dump(@board))\n\t\ttemp = temp_board[@move_from].shift\n\t\ttemp_board[@move_to].unshift(temp)\n\n\t\ttemp_board.each do |column|\n\t\t\tif column.sort != column\n\t\t\t\treturn false\n\t\t\tend\n\t\tend\n\t\t# If they all pass, we're good!\n\t\treturn true\n\tend", "def valid_move?(move_index)\r\n #valid if position is NOT taken\r\n valid = !self.position_taken?(move_index)\r\n if valid == true\r\n if move_index.between?(0,8)\r\n valid = true\r\n else\r\n valid = false\r\n end\r\n end\r\n valid\r\n end", "def is_acceptable(move)\n\t\t@@ACCEPTABLE_MOVES.include?(move)\n\tend", "def taken?(move)\n \t# Subtract 1 from move to correctly correspond with index\n if @board[move - 1] == \"X\" || @board[move - 1] == \"O\"\n return true\n end\n return false\n end", "def valid_move?(position)\n if !position.is_a?(Integer)\n position = position.to_i\n end\n if(position>=1 && position<=@board.length && !position_taken?(position))\n return true\n end\n return false\n end", "def possible_move?(coords)\n if @board.exists_at?(coords)\n piece = @board.at(coords)\n return (piece.nil? || piece.color != @current_color)\n end\n return false\n end", "def valid_move?(position)\n if is_number?(position)\n if position.to_i.between?(0, 10)\n if position_taken?(position.to_i-1)\n false\n else\n true\n end\n else \n false\n end\n else\n false\n end\n end", "def no_player_can_move?\n !valid_move?(:black) && !valid_move?(:red)\n end", "def check_if_moveisvalid(move)\n @all_available_moves.each do |avail_move|\n return true if move.is_equal_to?(avail_move)\n end\n return false\n end", "def check_move? piece, origin, dest\n real_nodes = stub_nodes\n\n apply_move(piece, origin, dest)\n dest_node = node_at(dest)\n check = king_in_check?(piece.color)\n @nodes = real_nodes\n return check\n end", "def valid_move?(position)\n !taken?(position) && position.to_i >0 && position.to_i <=9\n end", "def valid_move?(position)\n index=position.to_i - 1\n index.between?(0, 8) && !(position_taken?(index))\n end", "def valid_move?(position)\n if !position_taken?(position) && position.between?(0,8)\n true\n else\n false\n end\n end", "def valid_move?(position)\r\n @index = position.to_i-1\r\n if @index.between?(0,8) && !position_taken?(@index)\r\n return true\r\n else\r\n return false\r\n end\r\n end", "def valid_move?(move, redisplay = false, must_be_jump = false, color, king)\n return false if move.nil? || (move.any? {|pos| pos.nil?})\n raise OutOfBoard unless in_bounds?(move)\n source, dest = move.from, move.to\n if source && self[source] && self[source].moves.include?(dest)\n piece_color = self[source].color\n king = king || Piece.would_kingify?(piece_color, dest)\n return true, piece_color, king\n elsif must_be_jump\n unless Piece.jumps(color, self, source, king).include?(dest)\n raise MustChainOnlyJumps\n end\n else\n raise InvalidMove\n end\n king ||= Piece.would_kingify?(piece_color, dest)\n return true, color, king\n rescue CheckersException => e\n display(e) if redisplay\n return false\n end", "def valid_move?\n\t\t@table.stays_on_table?(@robot_direction, @x, @y)\n\tend", "def move\n return false unless on_the_table?\n\n next_x, next_y = facing.next_move_position(x, y)\n unless falls_off?(next_x, next_y)\n self.x = next_x\n self.y = next_y\n true\n else\n false\n end\n end", "def valid_move?(board, position)\n position = position.to_i\n if (position.between?(1,9)) && !(board[position.to_i - 1] == \"X\" || board[position.to_i - 1] == \"O\")\n return true\n else\n return false\n end\nend", "def valid_move?(board, position)\n position_taken?(board, position) == false && position.between?(0, 8) ? true : false\nend", "def move\n return false if @position.nil?\n \n movements = { north: { x: 0, y: 1 }, east: { x: 1, y: 0 }, south: { x: 0, y: -1 }, west: { x: -1, y: 0 } }\n position, movement = @position, movements[@direction]\n\n return false unless valid_position?(position[:x] + movement[:x], position[:y] + movement[:y])\n \n @position = { x: position[:x] + movement[:x], y: position[:y] + movement[:y] }\n true\n end", "def valid_move?(board, position)\n position = position.to_i - 1\n if position_taken?(board, position)\n return false\n else\n if position.between?(0,8) && (board[position] != \"X\" || board[position] != \"O\")\n return true\n else\n return false \n end\n end\nend", "def valid_move?(board,pos)\n if !position_taken?(board,pos.to_i-1) && pos.to_i.between?(1,9)\n return true\n elsif position_taken?(board,pos.to_i-1) && pos.to_i.between?(1,9)\n return false\n end\nend", "def validate_move?(move)\n return true if open_spots.include?(move)\n false\n end", "def check_move(direction)\n\n if direction == 0 #up\n if @y < 1\n \n return false\n end\n elsif direction == 1 #down\n if @y > @boundry\n \n return false\n end\n elsif direction == 2 #left\n if @x < 1\n \n return false\n end\n else #right\n\n if @x > @boundry\n \n return false\n end\n\n end\n\n return true\n end", "def puts_into_check?(move)\n # make move\n board[move] = self\n board[current_pos] = NullPiece.instance\n # see if in check\n check = board.in_check?(side)\n # unmake move\n board[current_pos] = self\n board[move] = NullPiece.instance\n\n check\n end", "def standard_move?(x,y)\n return (x_diff(x) == 0) && (y_diff(y) == 1)\n end", "def valid_move?\n\t\tvalid_1 = (0..2).include? (@take_from)\n\t\tvalid_2 = (0..2).include? (@move_to)\n\t\tif valid_1 == false || valid_2 == false\n\t\t\tputs \"I'm sorry, please input your move in a 'x,y' format, ensuring that you are selecting numbers between 1 and 3!\"\n\t\t\tmove_input\n\t\telsif @pegs[@take_from][0] == nil\n\t\t\tputs \"I'm sorry, I'm not in the mood for a philosophical debate so let's just agree that you cannot move nothing and you can try again.\"\n\t\t\tmove_input\n\t\tend\n\tend", "def can_use_move?\n moves = @moveset\n # TODO : Implement all the move conditions\n return moves.any? { |move| move.pp > 0 }\n end", "def valid_move?(board,position)\n valid = nil\n if position >= 0 && position <=8\n case position_taken?(board,position)\n when true\n valid = false\n when false\n valid = true\n end\n end\n\n return valid\nend", "def valid_move?(board, position)\n if !(position_taken?(board, position)) && position.between?(0, 8)\n return true\n else\n return false\n end\nend", "def pawn_move? piece, square\n if piece.moved == false && two_squares_vertical?(piece.square, square) && square.piece.nil?\n true\n elsif (diagonal?(piece.square, square) && adjacent?(piece.square, square)) && square.piece != nil\n true\n elsif vertical?(piece.square, square) && adjacent?(piece.square, square)\n pawn_direction?(piece, square)\n else\n false\n end\n end", "def check_valid(move)\n\n\t\tif @board[move[0]][move[1]] != \"-\"\n\t\t\treturn false\n\t\telse\n\t\t\treturn true\n\t\tend\n\n\tend", "def pawn_valid_move?(pawn, new_location, to_column, from_column)\n if to_column == from_column\n if (new_location[0] - pawn.location[0]).abs == 2\n return false if pawn.moved == true\n end\n empty_location?(new_location)\n else\n if enemy_piece_at_location?(pawn.color, new_location)\n true\n else\n valid_en_passant_move?(pawn.color, pawn.location[0], to_column)\n end\n end\n end", "def move_is_decisive?(move)\n begin\n make_move(move)\n if is_game_over?\n return @winner\n else\n return double_threat_analysis\n end\n ensure\n undo_move\n end\n return nil\n end", "def valid_move?(move)\n valid_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n if valid_numbers.include?(move)\n return true\n end\n return false\n end", "def check_move?(new_position)\n if new_position[0].between?(0,7) &&\n new_position[1].between?(0,7) &&\n !space_full?(new_position)\n return true\n end\n false\n end", "def moved?\n @moved\n end", "def opposite_move?(move, robot, direction)\n return false if move[:robot] != robot\n case move[:direction]\n when :up\n return direction == :down\n when :down\n return direction == :up\n when :left\n return direction == :right\n else\n return direction == :left\n end\n end", "def valid_move?(board, position)\n if position.to_i>=1 && position.to_i<=9 && !position_taken?(board, position.to_i-1)\n return true\n else\n return false\n end\nend", "def valid_move_seq?(move_seq)\n test_board = @board.dup_board\n # debugger\n if test_board[@position].perform_moves!(move_seq)\n return true\n else\n raise InvalidMoveError\n end\n end", "def valid_move?(cur_pos, next_pos)\n return false if @all_positions[next_pos] # no need to add already seen pos \n cur_col, cur_row = cur_pos\n next_col, next_row = next_pos\n bool_1 = (next_col - cur_col).abs == 2 && (next_row - cur_row).abs == 1\n bool_2 = (next_row - cur_row).abs == 2 && (next_col - cur_col).abs == 1\n bool_1 || bool_2\n end", "def valid_move?(board, position)\n position = position.to_i\n \n if !(position_taken?(board, position-1)) && position.between?(1,9)\n return true\n else\n return false\n end\nend", "def valid_move?(input_position)\n num = self.convert_to_i(input_position)\n num.between?(1, 9) && !self.taken?(num)\n end", "def valid_move? (board, position)\n position = position.to_i - 1\n (position.between?(0,8)) && (position_taken?(board, position) == false)\nend", "def valid_move?(board, position)\n position.between?(0, 8) && !position_taken?(board, position)\nend" ]
[ "0.76601964", "0.76601964", "0.74794567", "0.7450275", "0.74079376", "0.72268975", "0.71966887", "0.7151723", "0.71151793", "0.7111376", "0.702171", "0.70205534", "0.7016901", "0.70104545", "0.70008636", "0.6998319", "0.6976874", "0.6951291", "0.6893735", "0.68809867", "0.6878438", "0.6873777", "0.6856285", "0.68318856", "0.6803014", "0.67976826", "0.6796625", "0.6795087", "0.6794932", "0.67753625", "0.67430407", "0.6735569", "0.6724097", "0.6720019", "0.6710834", "0.6703704", "0.668979", "0.66860867", "0.6677775", "0.6677581", "0.6676448", "0.6672075", "0.6672075", "0.66701007", "0.6662103", "0.66465235", "0.6641317", "0.6629954", "0.66226184", "0.6614742", "0.6606049", "0.66058576", "0.6598247", "0.6597826", "0.65923405", "0.6588549", "0.6588353", "0.6586952", "0.6586855", "0.6586591", "0.6586068", "0.65852475", "0.65803003", "0.65800637", "0.65691346", "0.6569103", "0.6565585", "0.6565237", "0.6563508", "0.65537924", "0.6539698", "0.65396345", "0.65242106", "0.65233976", "0.65188396", "0.65136343", "0.6507823", "0.65050584", "0.6498197", "0.64952105", "0.6485781", "0.64809614", "0.6477731", "0.6477281", "0.6473426", "0.6472929", "0.6466451", "0.6462043", "0.6460778", "0.6455413", "0.6454349", "0.64487696", "0.6447404", "0.64430547", "0.6438975", "0.6438267", "0.64305735", "0.6426383", "0.6411395", "0.64060926" ]
0.66846263
38
Set a default Chef environment name for our chef_search calls.
def chef_env(env) chef_scope :chef_environment, env end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def default_environment=(env); end", "def test_chef_environment\n # If no environment is specified chef needs to use \"_default\" and attribute from cookbook\n actual = cook_environment(run_list: [\"recipe[environment_cookbook]\"])\n assert_equal \"_default/untouched\", actual\n\n # If one is specified chef needs to pick it up and get override attibute\n actual = cook_environment(run_list: [\"recipe[environment_cookbook]\"], environment: 'test_environment')\n assert_equal \"test_environment/test_env_was_here\", actual\n end", "def environment_name=(str)\n @environment_name = str\n end", "def default_environment_name\n return nil unless config?\n config.default_environment\n end", "def default_puppet_env_name\n ENV['PUPPET_ENV'] || Puppet[:environment]\n end", "def default_puppet_env_name\n ENV['PUPPET_ENV'] || Puppet[:environment]\n end", "def default_environment\n return nil unless default_environment_name\n environment(default_environment_name)\n end", "def default_environment; end", "def default_orgname\n ENV['ECM_DEFAULT_ORGNAME']\n end", "def prepare_environment(environment)\n environment.nil? ? DEFAULT_ENV_NAME : environment.to_s\n end", "def node_key\n @_cookbook_name_override || cookbook_name\n end", "def default_envs\n {\n \"PATH\" => \"\"\n }\n end", "def set_env_defaults\n ENV['KAIKI_NETID'] = \"kfs-test-sec1\" if ENV['KAIKI_NETID'].nil?\n ENV['KAIKI_ENV'] = \"dev\" if ENV['KAIKI_ENV'].nil?\nend", "def set_env_defaults\n ENV['KAIKI_NETID'] = \"kfs-test-sec1\" if ENV['KAIKI_NETID'].nil?\n ENV['KAIKI_ENV'] = \"dev\" if ENV['KAIKI_ENV'].nil?\nend", "def determine_chef_server(request)\n \n # Return specified Chef server, if given and match found\n if request.params[\"chef-server\"]\n EdmundsChefRailsProxy::Application.config.chef_servers.each do |chef_server|\n if chef_server[:url] =~ /#{request.params[\"chef-server\"]}/\n return chef_server\n end\n end\n end\n \n # Return matching Chef server if environment is specified\n if request.params[\"chef-environment\"] || request.fullpath =~ /\\/environments\\/.*/\n chef_environment = request.params[\"chef-environment\"] || request.fullpath[/\\/environments\\/([a-zA-Z0-9-]*).*/, 1]\n logger.debug \" determine_chef_server: chef_environment = #{chef_environment}\"\n EdmundsChefRailsProxy::Application.config.chef_servers.each do |chef_server|\n logger.debug chef_server\n chef_server[:envs].each do |chef_server_env|\n if chef_environment =~ /#{chef_server_env}/\n return chef_server\n end\n end\n end\n end\n\n # At this point, return default Chef server\n return EdmundsChefRailsProxy::Application.config.chef_servers[0]\n\nend", "def default_environment\n nil\n end", "def __default_cluster_name\n \"elasticsearch-test-#{Socket.gethostname.downcase}\"\n end", "def env_name(key); end", "def temporary=(name)\n envs = find(name)\n if envs.size == 0\n puts \"Sorry no environments were found matching '#{name}'!\"\n puts 'Here are the available options:'\n find('').sort.each do |file|\n puts File.basename(file)\n end\n exit 1\n elsif envs.size > 1\n puts 'Please try again with one of the following environments:'\n envs.sort.each do |file|\n puts File.basename(file)\n end\n exit 1\n else\n self.file = envs[0]\n end\n end", "def set_default_name \n self.name ||= \"Itinerary\" \n end", "def set_name\n @appname = \"Bike London\"\n end", "def setup!(requesting_actor_id, options=Hash.new)\n create_database!\n\n policy = OrgAuthPolicy.new(self, requesting_actor_id, options)\n policy.apply!\n\n # Environments are in erchef / SQL. Make an HTTP request to create the default environment\n headers = {:headers => {'x-ops-request-source' => 'web'}}\n rest = Chef::REST.new(Chef::Config[:chef_server_host_uri],\n Chef::Config[:web_ui_proxy_user],\n Chef::Config[:web_ui_private_key], headers)\n rest.post_rest(\"organizations/#{name}/environments\",\n {\n 'name' => '_default',\n 'description' => 'The default Chef environment'\n })\n end", "def nodes_for_environment(name)\n ridley.partial_search(:node, \"chef_environment:#{name}\", [\"fqdn\", \"cloud.public_hostname\", \"name\", \"os\"])\n end", "def option_from_env(name)\n ViteRuby.env[\"#{ ViteRuby::ENV_PREFIX }_#{ name.upcase }\"]\n end", "def environment(override = nil)\n override || @environment || autodetect_environment\n end", "def reset_env\n clear_env\n set_env self.env_defaults\n end", "def environment_name\n return @environment_name if @environment_name.is_a? String\n if ENV['EY_ENVIRONMENT_NAME']\n @environment_name = ENV['EY_ENVIRONMENT_NAME']\n elsif engine_yard_cloud_api.possible_to_detect_environment_from_git_config?\n @environment_name = engine_yard_cloud_api.environment_name\n end\n raise RuntimeError, \"[engineyard-metadata gem] You need to run this from the application repo, set EY.metadata.environment_name= or set ENV['EY_ENVIRONMENT_NAME']\" unless @environment_name.to_s.strip.length > 0\n @environment_name\n end", "def configure\n @environment = facts.fetch(\"chef_environment\"){\"development\"}.downcase\n @fqdn = facts.fetch(\"fqdn\"){\"\"}\n @app_names = facts.fetch(\"trebuchet\"){[]}\n end", "def environment_filter\n if self.environment == 'default'\n nil\n else\n self.environment\n end\n end", "def environment_filter\n if self.environment == 'default'\n nil\n else\n self.environment\n end\n end", "def modify_env(resource_name)\n ChefSpec::Matchers::ResourceMatcher.new(:env, :modify, resource_name)\n end", "def check_chef_env(chef_env_name)\n\n if chef_env_name\n begin\n chef_env = Chef::Environment.load(chef_env_name)\n rescue Net::HTTPServerException => e\n raise unless e.to_s =~ /^404/\n ui.info \"Creating chef environment \" + chef_env_name\n chef_env = Chef::Environment.new()\n chef_env.name(chef_env_name)\n chef_env.create\n end\n end\n\n chef_env\n end", "def define_suits\n [{ 'name' => 'default',\n 'run_list' => [\"recipe[#{@cookbook}::default]\"],\n 'attributes' => 'nil' }]\n end", "def environment(name = nil)\n name = default_environment_name unless name\n known_environments.find { |env| env.match_name?(name) }\n end", "def override_environment_setting(node, name, value)\n node.override_environment_setting(name, value)\n @dirty_environment_settings = true\n end", "def set_application_name(name)\n __remote_control_command(\"setScApplicationName\", [name,])\n end", "def default_app_name\n if is_workspace\n return default_build_settings(key: \"PRODUCT_NAME\")\n else\n return app_name\n end\n end", "def crowd_app_name(name=nil)\r\n rw_config(:crowd_app_name, name, nil)\r\n end", "def default_name\n @default_name ||= \"__#{name}_default__\"\n end", "def from_env\r\n return if not @name\r\n @owner = true\r\n replace( ENV[@name] )\r\n end", "def test_override\n write_var(:gear, 'DEFAULT_LABEL', 'bogus')\n\n OpenShift::Runtime::Utils::Environ.for_gear(File.join('/tmp', @uuid)).tap do |env|\n assert_equal 'bogus', env['DEFAULT_LABEL']\n end\n\n write_var(:cart, 'DEFAULT_LABEL', 'VIP')\n\n OpenShift::Runtime::Utils::Environ.for_gear(File.join('/tmp', @uuid)).tap do |env|\n assert_equal 'VIP', env['DEFAULT_LABEL']\n end\n end", "def default_environment_variables\n environment_variables.select &:default\n end", "def program_name(override=nil)\n if override\n @@program_name = override\n end\n @@program_name\n end", "def _env(e_name)\n __t_stringish(e_name)\n _jinja.env[__attribute_key(e_name)]\n end", "def default_environment\n { 'PATH' => '/srv/kafka/current/bin:/usr/bin:/bin' }\n end", "def default_environment\n { 'PATH' => '/srv/kafka/current/bin:/usr/bin:/bin' }\n end", "def chef_name\n \"#{name}_#{id}\"\n end", "def change_chef_vars(instances, &block)\n instances.each { |inst|\n query = \"name:#{inst['server_name']}\"\n query_nodes = Chef::Search::Query.new\n query_nodes.search('node', query) do |node_item|\n yield node_item\n end\n }\n end", "def test_single_environment_set_env_no_name\n cfg = DBGeni::Config.new\n cfg.load(\"environment('foo') { } \\n\")\n cfg.set_env\n assert_equal('foo', cfg.current_environment)\n end", "def suite_config\n {\n 'name' => 'default',\n 'run_list' => (File.exist?(File.join(base, 'test', 'cookbook')) || File.exist?(File.join(base, 'test', 'cookbooks'))) ? [\"#{cookbook_name}_test\"] : [cookbook_name],\n }\n end", "def environment=(env)\n self.config[:environment] = env.to_sym\n end", "def create_env(resource_name)\n ChefSpec::Matchers::ResourceMatcher.new(:env, :create, resource_name)\n end", "def test_name(name, environment)\n return name unless environment\n\n \"#{environment}: #{name}\"\n end", "def find_chef_env\n require 'json'\n require 'rubygems'\n require 'ohai'\n require 'mixlib/shellout'\n o = Ohai::System.new\n o.all_plugins\n\n env_command =\n Mixlib::ShellOut.new('sudo', 'knife',\n 'node', 'show',\n o[:fqdn] || o[:hostname], '-E',\n '-F', 'json')\n\n env_command.run_command\n\n env_command.invalid! 'Could not retrieve Chef environment!' \\\n unless env_command.status.success?\n\n JSON.parse(env_command.stdout)['chef_environment']\nend", "def use!(name)\n @parent.gemset_use(name, :replace_env => true)\n end", "def setEnvironment(e=:qa, url=nil)\n env={\n :qa => { :name => 'QA', :description => 'QA Env', :url => 'https://www.qa.com' },\n :qa2 => { :name => 'QA2', :description => 'QA2 Env', :url => 'https://www.qa2.com' },\n :prod => { :name => 'PROD', :description => 'CERT', :url => 'https://www.prod.com' }\n }\n\n\n if url.nil?\n @environment_under_test=env[e]\n else\n @environment_under_test={ :name => 'custom', :url => url.to_s }\n end\n\n\n end", "def validation_client_name; @validation_client_name || \"chef-validator\"; end", "def validation_client_name; @validation_client_name || \"chef-validator\"; end", "def consume_chef_environment(attrs)\n attrs = attrs ? attrs.dup : {}\n if env = attrs.delete(\"chef_environment\")\n chef_environment(env)\n end\n attrs\n end", "def name\n c.environment\n end", "def kernel_aki\n kernel = @kernel_override # allow user to override\n kernel ||= ENV['EC2_KERNEL_ID'] # use same kernel as VM is running\n end", "def default_external_name\n @default_external_name || DEFAULT_EXTERNAL_NAME\n end", "def initialize(chef_server_rest: nil)\n @name = \"\"\n @description = \"\"\n @default_attributes = Mash.new\n @override_attributes = Mash.new\n @env_run_lists = { \"_default\" => Chef::RunList.new }\n @chef_server_rest = chef_server_rest\n end", "def default_population\n self.name = self.name.downcase\n self.deployment ||= Deployment.system\n end", "def set_or_init(i,val)\n \n env = ENV[i.upcase]\n \n if env.nil?\n \n instance_variable_set(\"@\" + i, val)\n \n else\n \n instance_variable_set(\"@\" + i, env)\n \n end\n \n end", "def set_env(papers, site_host, site_name, nwo)\n ENV['REVIEW_REPOSITORY'] = nwo\n ENV['DOI_PREFIX'] = \"10.21105\"\n ENV['PAPER_REPOSITORY'] = papers\n ENV['JOURNAL_URL'] = site_host\n ENV['JOURNAL_NAME'] = site_name\n end", "def get_env_variable(name, default_value) \n var_name = name.upcase\n var_value = ENV[var_name]\n\n if var_value.to_s.empty? \n return default_value\n end\n\n return var_value\n end", "def env(key)\n if key.nil?\n nil\n elsif override_env.present?\n override_env[key]\n else\n ENV[key]\n end\n end", "def environment_names\n @environment_names ||= [nil] + env.tags.collect {|name, tag| tag['environment']}.compact\n end", "def default_fauxture_name\n :default\n end", "def env=(environment); end", "def env=(environment); end", "def chef_solo\n fetch(:chef_solo).to_s || 'chef-solo'\n end", "def option_name(key)\n case key\n when Symbol ; \"#{RACK_ENV_NS}.#{key}\"\n when String ; key\n else raise ArgumentError\n end\n end", "def environment_name(url = nil)\n url ||= self.url\n uri = URI(url)\n\n if (uri.host == 'localhost')\n if uri.port.nil?\n uri.host;\n else\n \"#{uri.host}:#{uri.port}\"\n end\n else\n name = case uri.host\n when /(?:origin-)?www\\d?(?:\\.pos)?(?:\\.siteb)?\\.([^\\.]+)(?:\\.fds)?\\.com/,\n /(?:m|m2qa1|mdev1|mockmacys|local)\\.([^\\.]+)(?:\\.fds)?\\.com/, # mobile env\n /([^\\.]+)\\.\\w+\\.\\w+\\.griddynamics\\.net/, # partial env\n /([^\\.]+)\\.stage2\\.cistages\\.fds/, # stage 2 env\n /([^\\-]+)-staging.bloomingdales\\.com/, #BCOM Heroku Staging Env\n /([^\\.]+).bloomingdales\\.com/, #BCOM Heroku Production Env\n /([^\\.]+)\\.cistages\\.fds/,\n /([^\\.]+)\\.macysbackstage\\.com/,\n /([^\\.]+)\\.herokuapp\\.com/,\n /([^\\.]+)\\.c4d\\.devops\\.fds\\.com/,\n /sstportal/\n Regexp.last_match.captures.first\n else\n raise URI::InvalidURIError, \"URI was not recognized: '#{url}'.\"\n end\n name\n end\n end", "def app_name=(value)\n @children['app-name'][:value] = value\n end", "def set_env(root, environment)\n self.root = root\n self.environment = environment\n config_file_paths << default_config_file_path\n end", "def around\n ClimateControl.modify(default_env_vars) do\n super\n end\n end", "def set_default_pool_name(opts)\n opts = check_params(opts,[:default_pools])\n super(opts)\n end", "def bootstrap_for_node\n bootstrap = Chef::Knife::Bootstrap.new\n bootstrap.name_args = [config[:fqdn]]\n bootstrap.config[:run_list] = get_config(:run_list).split(/[\\s,]+/)\n bootstrap.config[:secret_file] = get_config(:secret_file)\n bootstrap.config[:hint] = get_config(:hint)\n bootstrap.config[:ssh_user] = get_config(:ssh_user)\n bootstrap.config[:ssh_password] = get_config(:ssh_password)\n bootstrap.config[:ssh_port] = get_config(:ssh_port)\n bootstrap.config[:identity_file] = get_config(:identity_file)\n bootstrap.config[:chef_node_name] = get_config(:chef_node_name)\n bootstrap.config[:prerelease] = get_config(:prerelease)\n bootstrap.config[:bootstrap_version] = get_config(:bootstrap_version)\n bootstrap.config[:distro] = get_config(:distro)\n bootstrap.config[:use_sudo] = true unless get_config(:ssh_user) == 'root'\n bootstrap.config[:template_file] = get_config(:template_file)\n bootstrap.config[:environment] = get_config(:environment)\n bootstrap.config[:first_boot_attributes] = get_config(:first_boot_attributes)\n bootstrap.config[:log_level] = get_config(:log_level)\n # may be needed for vpc_mode\n bootstrap.config[:no_host_key_verify] = get_config(:no_host_key_verify)\n bootstrap\n end", "def handy_method()\n ENV[@sentinel_var] = \"foo\"\n new_env = { @sentinel_var => \"bar\" }\n\n Facter::Util::Resolution.with_env new_env do\n ENV[@sentinel_var].should == \"bar\"\n return\n end\n end", "def handy_method()\n ENV[@sentinel_var] = \"foo\"\n new_env = { @sentinel_var => \"bar\" }\n\n Facter::Util::Resolution.with_env new_env do\n ENV[@sentinel_var].should == \"bar\"\n return\n end\n end", "def chef_context\n @chef_context || ::Capistrano.env\n end", "def environment name, config=nil, &block\n environments[name] = klass.configure(config, &block)\n end", "def set_default(name, *args, &block)\n set(name, *args, &block) unless exists?(name)\nend", "def set_default(name, *args, &block)\n set(name, *args, &block) unless exists?(name)\nend", "def env(name, value)\n Stairs.configuration.env_adapter.set name, value\n end", "def launch_config_name \n \"#{APP_NAME}-build-#{VERSION}-#{APP_ENV}\"\nend", "def apply_system_defaults\n if @region.nil? && @zone.nil?\n @region, @zone = Rudy::DEFAULT_REGION, Rudy::DEFAULT_ZONE\n elsif @region.nil?\n @region = @zone.to_s.gsub(/[a-z]$/, '').to_sym\n elsif @zone.nil?\n @zone = \"#{@region}b\".to_sym\n end\n \n @environment ||= Rudy::DEFAULT_ENVIRONMENT\n @role ||= Rudy::DEFAULT_ROLE\n @localhost ||= Rudy.sysinfo.hostname || 'localhost'\n @auto = false if @auto.nil?\n end", "def test_Enviroment_007_SetEnv\r\n\r\n puts2(\"\")\r\n puts2(\"#######################\")\r\n puts2(\"Testcase: test_Enviroment_007_SetEnv\")\r\n puts2(\"#######################\")\r\n\r\n sEnvVarName = \"COMPUTERNAME\" # Is this one platform independent?\r\n sNewValue = \"MyNewName\"\r\n\r\n # Display the current value\r\n puts2(\"Current value of \" + sEnvVarName)\r\n printenv(sEnvVarName)\r\n\r\n puts2(\" Setting \" + sEnvVarName + \" to \" + sNewValue)\r\n\r\n # Set new value that will be in effect for duration of this Ruby session's test run\r\n setenv(sEnvVarName, sNewValue)\r\n\r\n # Display the current value\r\n puts2(\"Current value of \" + sEnvVarName)\r\n printenv(sEnvVarName)\r\n\r\n\r\n sNewEnvVarName = \"Ruby\"\r\n sNewSetting = \"Is Cool\"\r\n puts2(\" Setting a new Environment Variable \" + sNewEnvVarName + \" to a new setting \" + sNewSetting)\r\n\r\n # Set new value that will be in effect for duration of this Ruby session's test run\r\n setenv(sNewEnvVarName, sNewSetting)\r\n\r\n # Display the current value\r\n puts2(\"Current value of \" + sNewEnvVarName)\r\n printenv(sNewEnvVarName)\r\n\r\n end", "def initialize chef_recipe\n super(chef_recipe.cookbook_name, chef_recipe.recipe_name, chef_recipe.run_context)\n\n # TODO: Support other distributions besides 'linux'\n node.default[\"serf\"][\"binary_url\"] = File.join node[\"serf\"][\"base_binary_url\"], \"#{node[\"serf\"][\"version\"]}\", \"serf_#{node[\"serf\"][\"version\"]}_linux_#{node[\"serf\"][\"arch\"]}.zip\"\n\n current_version = get_serf_installed_version\n if current_version\n Chef::Log.info \"Current Serf Version : [#{current_version}]\"\n end\n end", "def set_default_cluster\n if study.default_options[:cluster].nil?\n cluster = study.cluster_groups.by_name(cluster_name_by_file_type)\n study.default_options[:cluster] = cluster.name if cluster.present?\n end\n end", "def determine_default_account_name\n Cadenero.default_account_name = options[\"default-account-name\"].presence ||\n ask(\"What will be the name for the default account? [Root Account]\").presence ||\n 'Root Account'\n end", "def default_service\n return @default_service if @default_service\n begin\n @default_service = File.basename($PROGRAM_NAME, '.*')\n rescue => e\n Datadog::Tracer.log.error(\"unable to guess default service: #{e}\")\n @default_service = 'ruby'.freeze\n end\n @default_service\n end", "def _env_change\n if @env_used\n @environments << @env\n @env = Bcpm::Tests::Environment.new\n @env_used = false\n end\n end", "def env_by_short_name(short_name)\n @env_map[short_name]\n end", "def setenv(n, v)\n debug \"Adding env: #{n}=#{v}\"\n debug \"prev value: #{@rye_getenv[n]}\"\n @rye_getenv[n] = v\n (@rye_current_environment_variables ||= {})[n] = v\n self\n end", "def environment=(env)\n @environment = env\n end", "def set_env()\n @triggers.each(&:set_env)\n end", "def default_provider\n return nil unless node && node['platform_family']\n Chef::Provider::Dropbox.const_get(node['platform_family'].split('_')\n .map(&:capitalize).join)\n end" ]
[ "0.64914715", "0.6276075", "0.62203985", "0.6024242", "0.60106164", "0.60106164", "0.58833575", "0.58743966", "0.57976645", "0.5753341", "0.5717913", "0.56838584", "0.5645325", "0.5645325", "0.55672544", "0.55611134", "0.5559538", "0.5537936", "0.5532204", "0.5529475", "0.55003417", "0.5490406", "0.54540616", "0.54379904", "0.54346335", "0.5426084", "0.53762966", "0.53190506", "0.5284735", "0.5284735", "0.5261922", "0.5249997", "0.5235518", "0.521767", "0.5207632", "0.5203007", "0.5147274", "0.5132594", "0.51106167", "0.5105936", "0.51046604", "0.5095269", "0.50815713", "0.506752", "0.50672483", "0.50672483", "0.506502", "0.5057383", "0.5048716", "0.5044035", "0.50330347", "0.50325197", "0.5030453", "0.50289524", "0.50285673", "0.50242114", "0.5018105", "0.5018105", "0.50140667", "0.49947762", "0.49838474", "0.49810743", "0.49624187", "0.49454644", "0.49340954", "0.4930601", "0.49288094", "0.49279281", "0.4926367", "0.49090534", "0.4902382", "0.4902382", "0.488379", "0.48753822", "0.487005", "0.4865631", "0.48569345", "0.4856832", "0.48547265", "0.4853052", "0.48480406", "0.48480406", "0.4842461", "0.4842284", "0.48406184", "0.48406184", "0.4839918", "0.48246408", "0.48179734", "0.48158193", "0.48136365", "0.48115906", "0.4802558", "0.47864982", "0.47839358", "0.47823277", "0.47819853", "0.47800368", "0.47774008", "0.47761786" ]
0.6390724
1
Set a term that is included for every chef_search call.
def chef_scope(field, term="*") scopes = fetch(:chef_scopes) || [] scopes.delete_if { |scope| scope =~ /chef_environment/ } set :chef_scopes, scopes << [field, term].join(":") end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def term=(value)\n self.content << (value.is_a?(XTF::Search::Element::Term) ? value : XTF::Search::Element::Term.new(value))\n end", "def search_terms=(value)\n @search_terms = value\n end", "def term=(term)\n @term = term\n @twitter_search = nil\n load_words\n end", "def search(term)\n raise \"Must be overridden\"\n end", "def term(string)\n @request.q = string\n end", "def set_search_terms\n if relevent_dish\n self.search_terms = self.name_translations.collect do |key,value|\n next value\n end.join(\" \")\n if self.restaurant\n self.restaurant_name = self.restaurant.name\n end\n if img = self.image.first\n self.top_image = img.img_url_medium\n end\n else\n self.search_terms = nil\n end\n save\n end", "def set_searchterm\n @searchterm = Searchterm.find(params[:id])\n end", "def set_common_term\n @common_term = CommonTerm.find(params[:id])\n end", "def add_search_term(term)\n @search_terms.push term\n end", "def add_terms(terms)\n\t\t\tif @search_string == nil\n\t\t\t\t@search_string = terms\n\t\t\telse\n\t\t\t\t@search_string << \"|\" + terms\n\t\t\tend\n\t\tend", "def set_term\n @term = Term.find(params[:id])\n end", "def set_term\n @term = Term.find(params[:id])\n end", "def before_GET(req)\n super\n @term = term(req)\n @title = \"Search for #{term(req)}\"\n end", "def <<(term)\n raise \"No document defined\" unless defined? @document\n unless @terms.include? term\n @terms[term] = @terms.length\n end\n i = @terms[term]\n @index[@document] ||= 0\n @index[@document] |= 1 << i\n end", "def track term\n @term = term\n if @term\n send_request @term\n end\n end", "def do_search(term = nil)\n @terms = term unless term.nil? #replace saved term with argument, if passed\n @attempts += 1\n @doc = Nokogiri::XML(open(build_call(@terms)))\n parse\n end", "def search_for_term(term)\n self.search_field = term\n self.search\n wait_for_ajax\n end", "def set_term\n @term = Term.find(params[:id])\n end", "def adv_search_set_text\n if @edit[@expkey].history.idx.zero? # Are we pointing at the first exp\n @edit[:adv_search_applied][:text] = if @edit[:new_search_name]\n _(\" - Filtered by \\\"%{text}\\\"\") % {:text => @edit[:new_search_name]}\n else\n _(\" - Filtered by \\\"%{text}\\\" report\") %\n {:text => @edit[:adv_search_report]}\n end\n else\n @edit[:custom_search] = true\n @edit[:adv_search_applied][:text] = _(\" - Filtered by custom search\")\n end\n end", "def each_search_term(starting_term = nil)\n alpha_terms(starting_term).each { |t| yield t if block_given? }\n end", "def set_tag_for_search(tag)\n @page.all(input_elements[:entries])\n @page.find(input_elements[:tag_filter_field]).set(tag)\n @page.find(input_elements[:tag_selected]).click\n @used_tag = tag\n end", "def set_term\n @term = UriService.client.find_term_by_internal_id(params[:id])\n raise ActionController::RoutingError, \"Could not find Term with internal_id: #{params[:id]}\" if @term.nil?\n end", "def get_term(term)\n term = term.gsub(Regex::ESCAPE) { |x| \"#{Regex::ESCAPECHAR}#{x}\" }\n tmp = SearchType::SEARCH_START\n search_type = SearchType::SEARCH_START | SearchType::SEARCH_END\n\n term = \"#{Regex::WILDCARD}#{term}\" if (search_type | tmp) == search_type\n tmp = SearchType::SEARCH_END\n term += Regex::WILDCARD.to_s if (search_type | tmp) == search_type\n term\n end", "def set_TextSearch(value)\n set_input(\"TextSearch\", value)\n end", "def set_TextSearch(value)\n set_input(\"TextSearch\", value)\n end", "def set_TextSearch(value)\n set_input(\"TextSearch\", value)\n end", "def term\r\n Riddle::Query.escape params[:term]\r\n end", "def term\r\n Riddle::Query.escape params[:term]\r\n end", "def set_Search(value)\n set_input(\"Search\", value)\n end", "def set_Search(value)\n set_input(\"Search\", value)\n end", "def set_Search(value)\n set_input(\"Search\", value)\n end", "def set_Search(value)\n set_input(\"Search\", value)\n end", "def set_Search(value)\n set_input(\"Search\", value)\n end", "def set_Search(value)\n set_input(\"Search\", value)\n end", "def set_Search(value)\n set_input(\"Search\", value)\n end", "def scoped(&block)\n raise UnsupportedSearchMethod unless @search_type == \"request\"\n @query[:searchTerms] << \"(\"\n yield self\n @query[:searchTerms] << \")\"\n return self\n end", "def set_term\n @term = Term.find(params[:id])\n raise ActiveRecord::RecordNotFound unless @term.user_id == session[:user_id]\n end", "def term; end", "def perform_search\n terms = { vehicle_year: 2006,\n vehicle_brand: \"Yamaha\",\n vehicle_model: \"Yz250\",\n vehicle_submodel: \"-- Base\",\n category_name: \"Complete Wheel Assembly\" }\n perform_search(terms)\n end", "def term\n @term\n end", "def set_search_text!\n self.text['a'] = extract_search_text :title, :meta_description\n self.text['b'] = extract_search_text :slug, :path\n self.text['c'] = extract_search_text *self.class.field_names(:textual)\n self.text['d'] = nil\n end", "def set_search\n @search = Recipe.ransack(params[:q])\n @search_recipes = @search.result.page(params[:page])\n @tag_search = Recipe.tagged_with(params[:search])\n end", "def set_ExpandTerms(value)\n set_input(\"ExpandTerms\", value)\n end", "def search_library_for=(text)\n self.text_field(:id=>\"mylibrary_livefilter\").set(\"#{text}\\n\")\n end", "def <<(string)\n self.term(string)\n\n self.results :print => true\n end", "def set_term_item_term\n @term_item_term = TermItemTerm.find(params[:id])\n end", "def set_SearchString(value)\n set_input(\"SearchString\", value)\n end", "def set_SearchString(value)\n set_input(\"SearchString\", value)\n end", "def search_crunchbase_sync term, opts={}, &callback\n crunchbase.new.search_sync term, opts, &callback\n end", "def search_library_for=(text)\n self.search_library=(\"#{text}\\n\")\n self.wait_for_ajax\n end", "def search(term)\n raise NoSearchTermException, \"No search term specified\" if term.nil?\n connection do\n client.search(term)\n end \n end", "def searchterm\r\n @@st.get_searchterm(referer)\r\n end", "def set_keyword\n journal = Journal.find(params[:journal_id])\n issue = journal.issues.find(params[:issue_id])\n article = issue.articles.find(params[:article_id])\n @keyword = article.keywords.find(params[:id])\n end", "def termdef(name)\n element(name, {:name => name, :class=>:term}, 'a')\n end", "def search\n super.merge(string: \"#{self.system_name}\")\n end", "def set_SearchExpression(value)\n set_input(\"SearchExpression\", value)\n end", "def search_for(search_term)\n type_into TestElements.search_box, search_term\n type_into TestElements.search_box, :return\n end", "def filter_single(param, field)\n {\n 'term': { \"#{field}.keyword\": param }\n }\n end", "def term(name)\n element(name, :class=>:term)\n end", "def set_people_term\n @people_term = PeopleTerm.find(params[:id])\n end", "def add_search_field(*) super end", "def terms\n\n end", "def terms\n\n end", "def term_name\n self.content\n end", "def search=(value)\n @search = value\n end", "def terms\n end", "def set_keywords\n\t\t\tself.keywords = [title, author, description].map(&:downcase).join(' ')\n\t\tend", "def term\n self.name\n end", "def autocomplete(term)\n get(\"/catalog/titles/autocomplete?term=#{term}\")\n end", "def related_to_keyword_search_parameter(&block)\n @search_parameters << RelatedToKeywordSearchParameter.new(&block)\n end", "def set_finder(search_param, set)\n render_output(set.grep(/#{search_param}/).to_a.sort) unless search_param.blank?\n end", "def set_keywords\n self._keywords = self.search_fields.map do |field|\n if field.is_a?(Hash)\n field.keys.map do |key|\n attribute = self.send(key)\n method = field[key]\n if attribute.is_a?(Array)\n if method.is_a?(Array)\n method.map {|m| attribute.map { |a| KeywordsExtractor.extract a.send(m) } }\n else\n attribute.map(&method).map { |t| KeywordsExtractor.extract t }\n end\n else\n KeywordsExtractor.extract(attribute.send(method))\n end\n end\n else\n KeywordsExtractor.extract(self.send(field))\n end\n end.flatten.compact.sort\n end", "def set_keywords\n self.search_fields.keys.each do |namespace| \n self._keywords[namespace] = self.search_fields[namespace].map do |field|\n if field.is_a?(Hash) \n field.keys.map do |key|\n attribute = self.send(key)\n method = field[key] \n attribute = [attribute] if !attribute.is_a?(Array) \n method = [method] if !method.is_a?(Array)\n method.map {|m| attribute.map { |a| Util.keywords a.send(m), stem_keywords[namespace], ignore_list[namespace] } }\n end\n else \n value = self[field]\n value = [value] if !value.is_a?(Array)\n value.map {|v| Util.keywords(v, stem_keywords[namespace], ignore_list[namespace]) if v}\n end\n end.flatten.map(&:to_s).select{|f| not f.empty? }.uniq.sort\n \n end\n end", "def do_search_for(key, value)\n search_term = self.send(\"filter_by_#{key}\", value)\n prepare_search_term_for(key, search_term)\n end", "def terms\n\tend", "def get_search_terms(array_of_terms)\n\t\treturn \"q=\"+array_of_terms.join(\"+\")\n\tend", "def search(text)\n normal\n type \"/#{text}<CR>\"\n end", "def search_series term, type\n\t\traw_output = @fred.series( 'search', \n\t\t\tsearch_text: term.to_s, \n\t\t\tsearch_type: type.to_s )\n\n\t\traw_output.seriess.series\n\t\t\n\tend", "def twitter_search(term)\n TwitterClient.new.search(term)\n end", "def set_term_search_instance_variables_from_options(options)\n @species_list = options[:species_list]\n @and_object = options[:object]\n @and_predicate = options[:predicate]\n # NOTE THAT YOU CANNOT HAVE TWO PREDICATES AND TWO OBJECTS!!!! (It's not\n # allowed in the UI, so I'm not accounting for it in the code)\n if @and_object.is_a?(Array)\n @term = TraitBank.term_as_hash(@and_object.first)\n @and_object = @and_object.size == 1 ? nil :\n TraitBank.term_as_hash(@and_object.last)\n\n @object = true\n elsif @and_predicate.is_a?(Array)\n @term = TraitBank.term_as_hash(@and_predicate.first)\n @and_predicate = @and_predicate.size == 1 ? nil :\n TraitBank.term_as_hash(@and_predicate.last)\n @object = false\n else\n # TODO: the whole \"object\" flag is LAME. Remove it entirely!\n @object = options[:object] && ! options[:predicate]\n if options[:predicate] && options[:predicate]\n @term = TraitBank.term_as_hash(options[:predicate])\n @and_predicate = nil\n @and_object = TraitBank.term_as_hash(options[:object])\n elsif options[:predicate]\n @term = TraitBank.term_as_hash(options[:predicate])\n @and_predicate = nil\n @and_object = nil\n else\n @term = TraitBank.term_as_hash(options[:object])\n @and_predicate = nil\n @and_object = nil\n end\n end\n @clade = options[:clade]\n end", "def set_admin_term\n @admin_term = Admin::Term.find(params[:id])\n end", "def search_people(searchterm,params={})\n @opensearch.search_people(searchterm,params) \n end", "def get_search_terms(string)\n\treturn \"q=\"+string.join(\"+\")\nend", "def kube_custom_search(context, term)\n cluster_id = node[cookbook_name]['cluster_id']\n ret_val = []\n filter = { 'name' => ['fqdn'], 'ip' => ['ipaddress'] }\n # puts \"search(#{context}, #{term}, filter_result: #{filter})\"\n search(context, term, filter_result: filter).each do |inst|\n raw = \"Raw search returns #{inst.inspect}\"\n # >[{\"name\"=>\"server-0\", \"ip\"=>\"ip-0\"}, {\"name\"=>\"server-1\", \"ip\"=>\"ip-1\"}]\n raise raw + \"\\n\" + err('no_master') if inst['name'].nil? && term == \"role:k8s_master_#{cluster_id}\"\n raise raw + \"\\n\" + err('no_minion') if inst['name'].nil? && term == \"role:k8s_minion_#{cluster_id}\"\n ret_val.push(name: inst['name'].downcase, ip: inst['ip'])\n end\n if ret_val.empty?\n abort(err('no_master')) if term == \"role:k8s_master_#{cluster_id}\"\n abort(err('no_minion')) if term == \"role:k8s_minion_#{cluster_id}\"\n end\n ret_val # >[{\"name\"=>\"server-0\", \"ip\"=>\"ip-0\"}, {\"name\"=>\"server-1\", \"ip\"=>\"ip-1\"}]\n end", "def add_term_filters\n body.filter(:term, posted: true)\n body.filter(:term, hidden_by_admin: false)\n body.filter(:term, restricted: false) unless include_restricted?\n body.filter(:term, unrevealed: false) unless include_unrevealed?\n body.filter(:term, anonymous: false) unless include_anon?\n body.filter(:term, chapter_count: 1) if options[:single_chapter]\n\n %i(complete language crossover).map do |field|\n value = options[field]\n body.filter(:term, field => value) unless value.nil?\n end\n add_tag_filters\n end", "def set_search_keyword\n @search_keyword = SearchKeyword.find(params[:id])\n end", "def update!(**args)\n @search_text = args[:search_text] if args.key?(:search_text)\n end", "def update!(**args)\n @search_text = args[:search_text] if args.key?(:search_text)\n end", "def term(req)\n CGI.escapeHTML(req.params['q'])\n end", "def set_searcher\n @searcher = Searcher.find(params[:id])\n end", "def search(word)\n \n end", "def set_SafeSearch(value)\n set_input(\"SafeSearch\", value)\n end", "def set_SafeSearch(value)\n set_input(\"SafeSearch\", value)\n end", "def search(word)\r\n \r\n end", "def term(**mapping)\n render(TERM, **mapping)\n end", "def search_builder(*args)\n super.tap do |builder|\n if @set\n builder.set = @set\n end\n end\n end", "def term(attributes = nil)\r\n body = { query: { term: attributes } }\r\n result = client.search index: index, type: type, body: body\r\n\r\n result_instance(result)\r\n end", "def termsig(*) end", "def set_keyword\n @keyword = Keyword.friendly.find(params[:id])\n end", "def ar_observe_field_query_terms destination\n observe_field 'query_terms', :frequency => 2,\n :update => \"auto_rest_index_table\",\n :before => \"Element.show('spinner')\",\n :success => \"Element.hide('spinner')\",\n :url => send(\"search_#{destination}_path\"), \n :method => :get,\n :with => \"query_terms\"\n end", "def set_SearchForUser(value)\n set_input(\"SearchForUser\", value)\n end" ]
[ "0.6918432", "0.66647184", "0.6598486", "0.64226973", "0.64085174", "0.64021266", "0.6303566", "0.6148493", "0.6143801", "0.6132444", "0.60770994", "0.60770994", "0.6069548", "0.59938836", "0.5972597", "0.59691733", "0.59419745", "0.5935316", "0.5909544", "0.5846233", "0.5807532", "0.5774404", "0.5683244", "0.5675383", "0.5675383", "0.5675383", "0.5674415", "0.5674415", "0.56724685", "0.56724685", "0.56724685", "0.56724685", "0.56724685", "0.56724685", "0.56724685", "0.56407434", "0.5634531", "0.563377", "0.56265205", "0.5621137", "0.5615895", "0.55550766", "0.549658", "0.54894125", "0.5486202", "0.54759324", "0.5457653", "0.5457562", "0.54220796", "0.54158586", "0.54031974", "0.5399859", "0.539776", "0.53874797", "0.53796655", "0.5378746", "0.53753775", "0.537499", "0.53745025", "0.53742856", "0.53714365", "0.5370641", "0.5370641", "0.53561914", "0.53558546", "0.5344694", "0.5340119", "0.53351194", "0.53237796", "0.5321437", "0.5313566", "0.528929", "0.528861", "0.5282019", "0.52765167", "0.52712184", "0.52676326", "0.526389", "0.5254888", "0.5247962", "0.5241388", "0.5241308", "0.52411884", "0.52401876", "0.52330065", "0.5232421", "0.5232164", "0.5232164", "0.52276415", "0.5227386", "0.5224801", "0.5216054", "0.5216054", "0.5199453", "0.519926", "0.5196671", "0.51933205", "0.5192839", "0.51912224", "0.51799726", "0.5175897" ]
0.0
-1
Set a Capistrano roles by searching a Chef Server for appropriate node data
def chef_role(names, query=nil, options={}, &block) user = options[:user] ||= fetch(:user) attribute = options.delete(:attribute) || :ipaddress index = options.delete(:index) || :node results_proc = block_given? ? block : chef_results_by(attribute) terms = [index, query].compact addresses = chef_search(*terms).flat_map(&results_proc) addresses.each do |address| server address, options.merge(roles: names) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def change_chef_vars(instances, &block)\n instances.each { |inst|\n query = \"name:#{inst['server_name']}\"\n query_nodes = Chef::Search::Query.new\n query_nodes.search('node', query) do |node_item|\n yield node_item\n end\n }\n end", "def serversForCapRoles(roles)\n find_servers(:roles => roles).collect { |x| x.host }\nend", "def roles(host)\n if $PROPERTIES.has_key?(host)\n #get the role assigned for the host\n roles=$PROPERTIES[host][:roles]\n #add the default roles to the host role array\n roles=roles + $PROPERTIES[\"default\"][:roles]\n else \n #assign default role for unassigned hosts\n roles=$PROPERTIES[\"default\"][:roles]\n end\n roles\nend", "def set_stage_roles(config)\n deployment.deploy_to_roles.each do |r|\n \n # create role attributes hash\n role_attr = r.role_attribute_hash\n \n if role_attr.blank?\n config.role r.name, r.hostname_and_port\n else\n config.role r.name, r.hostname_and_port, role_attr\n end\n end\n end", "def roles(host)\n roles = [ \"network\" ]\n case host\n when /^node/\n roles << \"compute\"\n when /^login/\n roles << \"login\"\n when /^master/\n roles << \"master\"\n when /^nfs/\n roles << \"nfsserver\"\n end\n roles\nend", "def load_roles\n top.roles.clear\n\n # define empty roles for all known ones so tasks don't fail if a role\n # doesn't exist due to a filter\n all_roles = rubber_instances.all_roles\n all_roles += rubber_cfg.environment.known_roles\n all_roles.uniq!\n all_roles.each {|name| top.roles[name.to_sym] = []}\n\n # define capistrano host => role mapping for all instances\n rubber_instances.filtered.each do |ic|\n ic.roles.each do |role|\n opts = Rubber::Util::symbolize_keys(role.options).merge(:platform => ic.platform, :provider => ic.provider)\n msg = \"Auto role: #{role.name.to_sym} => #{ic.full_name}\"\n msg << \", #{opts.inspect}\" if opts.inspect.size > 0\n logger.info msg\n top.role role.name.to_sym, ic.full_name, opts\n end\n end\n end", "def propagate_roles_needed(task_name) \n \n #All recipes besides server have the same name in their body; thus task_name usually is\n #Recipe.name. However, if you are executing a task that appears\n #as 'server_display' in the dropdown menu, it is actually named 'server' in the \n #recipes and in the database.\n if(task_name!=\"server_display\")\n recipe_to_run=Recipe.find_by_name(task_name) \n else \n recipe_to_run = Recipe.find_by_name(\"server\")\n if !recipe_to_run.role_needed then\n #Check if the recipe chosen to run on this deployment is a predefined recipe\n #that does not require a parameter, i.e. a specific ip_address list.\n #check to see that current_stage has all roles needed for the recipes it has,\n #otherwise propagate them.\n recipe_types = recipe_to_run.server_types #aggregating the server_types for all recipes in this stage\n recipe_types.each{|t| \n if !current_stage.roles.map{|r|r.name}.include?(t.name)then\n \n #propagate a role for every host that fits type t:\n t.hosts.each do |h|\n if(t.name==\"db\")\n @role = current_stage.roles.build({\"no_release\"=>\"0\", \"name\"=>t.name, \"primary\"=>\"1\", \"ssh_port\"=>\"\", \"no_symlink\"=>\"0\", \"host_id\"=>h.id})\n else\n @role = current_stage.roles.build({\"no_release\"=>\"0\", \"name\"=>t.name, \"primary\"=>\"0\", \"ssh_port\"=>\"\", \"no_symlink\"=>\"0\", \"host_id\"=>h.id})\n end\n if(!@role.save)\n RAILS_DEFAULT_LOGGER.error(\"could not save the given role #{t.name} on host #{h.name}\");\n end\n end\n \n end\n \n }\n end \n end\n end", "def cluster_assign_roles(environment, type, entry=nil)\n types = %w[basic hadoop kafka]\n unless types.include?(type.to_s.downcase)\n raise \"#{type} is not one of #{types.join(',')} !\"\n end\n\n #\n # We use system() instead of Mixlib::ShellOut specifically so that the\n # child process re-uses our STDOUT/STDERR.\n #\n # TODO: replace with IO::popen3\n #\n if entry.nil?\n system('sudo', './cluster-assign-roles.sh',\n environment, type.to_s.downcase.capitalize)\n else\n system('sudo', './cluster-assign-roles.sh',\n environment, type.to_s.downcase.capitalize, entry[:hostname])\n end\n\n # Why doesn't this raise an error?\n puts 'cluster-assign-roles.sh failed!' unless $CHILD_STATUS.success?\nend", "def start_new_roles_on_nodes_in_xen(ips_to_roles)\n Djinn.log_info(\"Starting new roles in virt with following info: \" +\n \"#{ips_to_roles.inspect}\")\n\n nodes_info = []\n keyname = @creds['keyname']\n ips_to_roles.each { |ip, roles|\n Djinn.log_info(\"Will add roles #{roles.join(', ')} to new \" +\n \"node at IP address #{ip}\")\n nodes_info << {\n \"public_ip\" => ip,\n \"private_ip\" => ip,\n \"jobs\" => roles,\n \"disk\" => nil\n }\n }\n\n add_nodes(nodes_info)\n update_hosts_info()\n\n if my_node.is_login?\n regenerate_nginx_config_files()\n end\n\n return nodes_info\n end", "def role_puppet_master\n $myxp.get_deployed_nodes('capi5k-init').first\nend", "def roles\n @run_list.select do |rl|\n rl.start_with?('r_', 'p_', 'base_', 'os_', 'os-')\n end\n end", "def create\n chef_server_rest.post(\"roles\", self)\n self\n end", "def start_new_roles_on_nodes_in_cloud(ips_to_roles)\n Djinn.log_info(\"Starting new roles in cloud with following info: \" +\n \"#{ips_to_roles.inspect}\")\n\n keyname = @creds['keyname']\n num_of_vms = ips_to_roles.keys.length\n roles = ips_to_roles.values\n disks = Array.new(size=num_of_vms, obj=nil) # no persistent disks\n Djinn.log_info(\"Need to spawn up #{num_of_vms} VMs\")\n imc = InfrastructureManagerClient.new(@@secret)\n\n begin\n new_nodes_info = imc.spawn_vms(num_of_vms, @creds, roles, disks)\n rescue AppScaleException => exception\n Djinn.log_error(\"Couldn't spawn #{num_of_vms} VMs with roles #{roles} \" +\n \"because: #{exception.message}\")\n return []\n end\n\n # initialize them and wait for them to start up\n Djinn.log_debug(\"info about new nodes is \" +\n \"[#{new_nodes_info.join(', ')}]\")\n\n add_nodes(new_nodes_info)\n update_hosts_info()\n\n if my_node.is_login?\n regenerate_nginx_config_files()\n end\n\n return new_nodes_info\n end", "def start_roles_on_nodes(ips_hash, secret)\n if !valid_secret?(secret)\n return BAD_SECRET_MSG\n end\n\n ips_hash = JSON.load(ips_hash)\n if ips_hash.class != Hash\n Djinn.log_warn(\"Was expecting ips_hash to be a Hash, not \" +\n \"a #{ips_hash.class}\")\n return BAD_INPUT_MSG\n end\n\n Djinn.log_info(\"Received a request to start additional roles on \" +\n \"new machines, with the following placement strategy: \" +\n \"#{ips_hash.inspect}\")\n\n # ips_hash maps roles to IPs, but the internal format here maps\n # IPs to roles, so convert to the right format\n ips_to_roles = {}\n ips_hash.each { |role, ip_or_ips|\n if ip_or_ips.class == String\n ips = [ip_or_ips] # just one IP\n else\n ips = ip_or_ips # a list of IPs\n end\n\n ips.each { |ip|\n if ips_to_roles[ip].nil?\n ips_to_roles[ip] = []\n end\n ips_to_roles[ip] << role\n }\n }\n\n Thread.new {\n if is_cloud?\n start_new_roles_on_nodes_in_cloud(ips_to_roles)\n else\n start_new_roles_on_nodes_in_xen(ips_to_roles)\n end\n }\n\n return ips_to_roles\n end", "def Chef_Solo_Nodes role_or_paths = '*'\n \n if role_or_paths.is_a?(Array)\n role = '*'\n files = role_or_paths.map { |path| File.expand_path(path) }\n else\n role = role_or_paths.to_s\n files = Dir.glob(\"nodes/*.json\")\n end\n \n files.map { |str| \n h = JSON(File.read(str))\n next if role != '*' && !(h['roles'] || []).include?(role)\n h['ipaddress'] ||= File.basename(str).sub(\".json\", \"\")\n h\n }.compact\n \nend", "def process_roles(items=node.run_list.run_list_items.dup)\n if entry = items.shift\n if entry.type == :role && role = inflate_role(entry.name)\n process_roles(role.run_list_for(@environment).run_list_items)\n node.default_attrs = Chef::Mixin::DeepMerge.merge(node.default_attrs, role.default_attributes)\n check_for_state_change \"deep merge of default attribute in role #{entry.name}\"\n node.override_attrs = Chef::Mixin::DeepMerge.merge(node.override_attrs, role.override_attributes)\n check_for_state_change \"deep merge of override attribute in role #{entry.name}\"\n end\n process_roles(items)\n end\n end", "def role(role, server)\n @roles[role] ||= []\n @roles[role] << server\n end", "def vm(config, name, *roles)\n roles << name\n config.vm.define name do |m|\n m.vm.host_name = name\n\n #m.vm.provision :shell, :inline => \"apt-get update\"\n #m.vm.provision :shell, :inline => \"apt-get upgrade -y\"\n m.vm.provision :puppet, :module_path => \"modules\" do |puppet|\n puppet.manifests_path = \"manifests\"\n puppet.manifest_file = \"site.pp\"\n\n puppet.facter = {}\n ENV.each do |key, value|\n next unless key =~ /^FACTER_/\n puppet.facter[key.gsub(/^FACTER_/, \"\")] = value\n end\n puppet.facter[\"roles\"] = roles.join(\",\")\n end\n end\nend", "def installRoles\n roledir = @ansible_path+\"/roles\"\n\n canon_links = {}\n\n repodirs = []\n\n # Make sure we search the global ansible_dir, if any is set\n if $MU_CFG and $MU_CFG['ansible_dir'] and !$MU_CFG['ansible_dir'].empty?\n if !Dir.exist?($MU_CFG['ansible_dir'])\n MU.log \"Config lists an Ansible directory at #{$MU_CFG['ansible_dir']}, but I see no such directory\", MU::WARN\n else\n repodirs << $MU_CFG['ansible_dir']\n end\n end\n\n # Hook up any Ansible roles listed in our platform repos\n if $MU_CFG and $MU_CFG['repos']\n $MU_CFG['repos'].each { |repo|\n repo.match(/\\/([^\\/]+?)(\\.git)?$/)\n shortname = Regexp.last_match(1)\n repodirs << MU.dataDir + \"/\" + shortname\n }\n end\n\n repodirs.each { |repodir|\n [\"roles\", \"ansible/roles\"].each { |subdir|\n next if !Dir.exist?(repodir+\"/\"+subdir)\n Dir.foreach(repodir+\"/\"+subdir) { |role|\n next if [\".\", \"..\"].include?(role)\n realpath = repodir+\"/\"+subdir+\"/\"+role\n link = roledir+\"/\"+role\n \n if isAnsibleRole?(realpath)\n if !File.exist?(link)\n File.symlink(realpath, link)\n canon_links[role] = realpath\n elsif File.symlink?(link)\n cur_target = File.readlink(link)\n if cur_target == realpath\n canon_links[role] = realpath\n elsif !canon_links[role]\n File.unlink(link)\n File.symlink(realpath, link)\n canon_links[role] = realpath\n end\n end\n end\n }\n }\n }\n\n # Now layer on everything bundled in the main Mu repo\n Dir.foreach(MU.myRoot+\"/ansible/roles\") { |role|\n next if [\".\", \"..\"].include?(role)\n next if File.exist?(roledir+\"/\"+role)\n File.symlink(MU.myRoot+\"/ansible/roles/\"+role, roledir+\"/\"+role)\n }\n\n coldir = \"#{Etc.getpwuid(Process.uid).dir}/.ansible/collections/ansible_collections\"\n [\"ansible.windows\", \"community.general.gem\"].each { |coll|\n %x{#{@ansible_execs}/ansible-galaxy collection list -p \"#{coldir}\"}\n if $? != 0\n system(%Q{#{@ansible_execs}/ansible-galaxy}, \"collection\", \"install\", coll, \"-p\", coldir)\n end\n } \n\n if @server.config['run_list']\n @server.config['run_list'].each { |role|\n found = false\n if !File.exist?(roledir+\"/\"+role)\n if role.match(/[^\\.]\\.[^\\.]/) and @server.config['groomer_autofetch']\n system(%Q{#{@ansible_execs}/ansible-galaxy}, \"--roles-path\", roledir, \"install\", role)\n found = true\n# XXX check return value\n else\n canon_links.keys.each { |longrole|\n if longrole.match(/\\.#{Regexp.quote(role)}$/)\n File.symlink(roledir+\"/\"+longrole, roledir+\"/\"+role)\n found = true\n break\n end\n }\n end\n else\n found = true\n end\n if !found\n raise MuError, \"Unable to locate Ansible role #{role}\"\n end\n }\n end\n\n end", "def eks_map(server_config_map)\n YAML.load(server_config_map.dig('data', 'mapRoles'))\n .select { |r| r.fetch('rolearn').include?('NodeInstanceRole') }\n end", "def customize_cloud_config(cloud_init_yaml, vm_i)\n case vm_i\n when 1 then cloud_init_yaml['coreos']['fleet']['metadata'] = 'role=head'\n when 2 then cloud_init_yaml['coreos']['fleet']['metadata'] = 'role=proxy'\n when 3 then cloud_init_yaml['coreos']['fleet']['metadata'] = 'role=web'\n when 4 then cloud_init_yaml['coreos']['fleet']['metadata'] = 'role=web'\n end\nend", "def set_roles(wanted_roles)\n current_roles = roles.map(&:name)\n\n remove = current_roles.reject { |r| wanted_roles.include?(r) }\n add = wanted_roles.reject { |r| current_roles.include?(r) }\n\n Ruolo.configuration.connection.transaction do\n remove.each do |role|\n remove_role(Ruolo::Models::Role.where(name: role).first)\n end\n\n add.each do |role|\n add_role(Ruolo::Models::Role.where(name: role).first)\n end\n end\n end", "def roles\n get_chef_files_absolute_paths roles_path\n end", "def roles(*select_roles, &block)\n if block_given?\n return yield(roles(*select_roles))\n end\n\n roles_set = Set.new select_roles.flatten.compact.map{|r| r.to_sym}\n if roles_set.empty? || roles_set.include?(:all)\n self\n else\n @cache[roles_set] ||= select { |server| server.matches_roles?(roles_set) }\n end\n end", "def roles(*select_roles, &block)\n if block_given?\n return yield(roles(*select_roles))\n end\n\n roles_set = Set.new select_roles.flatten.compact.map{|r| r.to_sym}\n if roles_set.empty? || roles_set.include?(:all)\n self\n else\n @cache[roles_set] ||= select { |server| server.matches_roles?(roles_set) }\n end\n end", "def deploy_to_roles(base_roles=self.roles)\n base_roles.dup.select { |role| not self.excluded_hosts.include?(role.host) }\n end", "def find_cloudera_role(type, environment = nil)\n\t \ttypes = {}\n\t \ttypes[:namenode] = { :recipe => \"c2c_cdh4::hadoop_namenode\", :port => node.hadoop.namenode_port }\n\t \ttypes[:jobtracker] = { :recipe => \"c2c_cdh4::hadoop_jobtracker\", :port => node.hadoop.jobtracker_port }\n\t \traise ArgumentError , \"I don't know about that kind of hadoop server\" unless types.has_key?(type)\n if node.run_list.expand(environment).recipes.include?(types[type][:recipe])\n node\n else\n search_string = %Q(recipes:\"#{types[type][:recipe]}\")\n search_string << %Q( AND chef_environment:#{environment}) if environment\n search(:node, search_string) do |matching_node|\n\n \tif is_remote_port_open? matching_node.ipaddress , types[type][:port]\n \t\treturn matching_node\n \tend\n end\n end\n end", "def resource_roles=(value)\n @resource_roles = value\n end", "def add_env_role_site(envs, roles, sites)\n { 'Environment' => envs, 'Role' => roles, 'Site' => sites }.each_pair do |kind, selection|\n select_item(kind, selection)\n end\n\n end", "def setup_role\n #get_statuses(@role)\n #set_default_status(@role)\n end", "def search_node_in_roles( roles )\n roles.each do |r|\n Chef::Log.info \"Searching for '#{self[:fqdn]}' in the '#{r}' role.\"\n if self.role?(r)\n # return true for the first match\n Chef::Log.info \"Whitelisting: Found node '#{self[:fqdn]}' via role '#{r}'.\"\n return true\n end\n end\n\n return false\n\n end", "def user_roles=(value)\n roles[:user_roles]=value\n end", "def set_roles_privilege\n @roles_privilege = RolesPrivilege.find(params[:id])\n end", "def roles= *new_roles\n roles.set_roles new_roles\n end", "def bootstrap_chef_script role, settings\n erubis_template(\n File.dirname(__FILE__)+\"/../config/user_data_script-#{role}.sh.erb\",\n :public_ip => settings[:elastic_ip],\n :hostname => settings[:user_data][:attributes][:node_name],\n :chef_server_fqdn => settings[:user_data][:chef_server].gsub(%r{http://(.*):\\d+},'\\1'),\n :ubuntu_version => 'lucid',\n :bootstrap_scripts_url_base => settings[:bootstrap_scripts_url_base],\n :chef_config => settings[:user_data]\n )\nend", "def register_tscm\n case node['platform']\n when 'redhat'\n client_id = shell_out('cat /opt/IBM/SCM/client/client.id').stdout\n\n if client_id.to_i == -1\n # registering the tscm client with server\n Chef::Log.info('Registering TSCM client........')\n\n # check for key required for server authentication\n verify_key\n\n # registering client using ssh command\n execute 'register-node' do\n command \"ssh -n -o StrictHostKeyChecking=no -i #{node['tscm']['key']} #{node['tscm']['proxy_user']}@#{node['tscm']['proxy_server']} powershell.exe -File 'C:/TSCM_Automation/TSCM_wrapper.ps1' #{node['tscm']['register_ot']} #{node['tscm']['node_name']} #{node['tscm']['OS_type']} #{node['tscm']['node_IP']}\"\n action :run\n timeout 1800\n end\n\n ruby_block 'sleep-after-register' do\n block do\n sleep(120)\n end\n action :run\n end\n \n else\n Chef::Log.error('TSCM Client: ' + (node['tscm']['node_name']).to_s + ' Already Registered with Object ID : ' + client_id.to_s + '.....................Nothing to do')\n node.default['tscm']['registration_status'] = 'success'\n end\n\n # registering on aix\n when 'aix'\n client_id = shell_out('cat /opt/IBM/SCM/client/client.id').stdout\n\n # check if the key is available; download in case it is not available\n verify_key\n \n Chef::Log.error(client_id.to_i)\n if client_id.to_i == -1\n Chef::Log.info('Registering the TSCM client.......')\n\n # registering the tscm client with server\n Chef::Log.info('Registering TSCM client........')\n\n execute 'register-tscm' do\n command \"ssh -n -o StrictHostKeyChecking=no -i #{node['tscm']['key']} #{node['tscm']['proxy_user']}@#{node['tscm']['proxy_server']} powershell.exe -File 'C:/TSCM_Automation/TSCM_wrapper.ps1' #{node['tscm']['register_ot']} #{node['tscm']['node_name']} #{node['tscm']['OS_type']} #{node['tscm']['node_IP']}\"\n action :run\n timeout 1800\n end\n\n ruby_block 'sleep-after-register' do\n block do\n sleep(120)\n end\n action :run\n end\n\n # checking log files for validating registration\n if ::File.exist?('/opt/IBM/SCM/client/client.log') && ::File.readlines('/opt/IBM/SCM/client/client.log').grep(/Storing obsfucated schedules/)\n Chef::Log.info('Registration Success...........')\n else\n Chef::Log.error('Registration Failed...........')\n end\n else\n Chef::Log.error('TSCM Client: ' + (node['tscm']['node_name']).to_s + ' Already Registered with Object ID : ' + client_id.to_s + '.....................Nothing to do')\n node.default['tscm']['registration_status'] = 'success'\n Chef::Log.error((node['tscm']['registration_status']).to_s)\n end\n end\nend", "def chef_role(name, query = \"*:*\", options = {})\n # TODO: This can only get a node's top-level attributes. Make it get nested\n # ones.\n attr = options.delete(:attribute) || :ipaddress\n nodes = Chef::Search::Query.new.search(:node, query)[0].map {|n| n[attr] }\n role name, *nodes, options\n nodes\n end", "def role(*args)\n cap_role(*args)\n puppet_role(*args)\n end", "def bootstrap\n unless @roles.nil? || @roles.empty? || platform == 'alpine'\n if platform =~ /(debian|ubuntu)/\n container.exec(['sh', '-c', 'apt-get-min update']) do |_, chunk|\n puts \"#{fqdn.purple}: #{chunk}\"\n end\n end\n system \"knife bootstrap #{@fqdn} -x kitchen -N #{@name} \" \\\n \"-r '#{@roles.join(', ')}' --sudo\"\n end\n self\n end", "def change_role(role)\n role_list.each do |old_role|\n remove_role old_role\n end\n puts role\n add_role role\n puts roles\n end", "def save\n begin\n chef_server_rest.put(\"roles/#{@name}\", self)\n rescue Net::HTTPClientException => e\n raise e unless e.response.code == \"404\"\n\n chef_server_rest.post(\"roles\", self)\n end\n self\n end", "def bootstrap_for_node(server, bootstrap_ip)\n bootstrap = Chef::Knife::Bootstrap.new\n Chef::Log.debug(\"Bootstrap name_args = [ #{bootstrap_ip} ]\")\n bootstrap.name_args = [ bootstrap_ip ]\n\n Chef::Log.debug(\"Bootstrap run_list = #{config[:run_list]}\")\n bootstrap.config[:run_list] = config[:run_list]\n\n Chef::Log.debug(\"Bootstrap ssh_user = #{config[:ssh_user]}\")\n bootstrap.config[:ssh_user] = config[:ssh_user]\n\n Chef::Log.debug(\"Bootstrap chef_node_name = #{config[:chef_node_name]}\")\n bootstrap.config[:chef_node_name] = config[:chef_node_name] || server.id\n\n Chef::Log.debug(\"Bootstrap prerelease = #{config[:prerelease]}\")\n bootstrap.config[:prerelease] = config[:prerelease]\n\n Chef::Log.debug(\"Bootstrap distro = #{config[:distro]}\")\n bootstrap.config[:distro] = config[:distro]\n\n if config[:ssh_user] == 'root'\n bootstrap.config[:use_sudo] = false\n else\n bootstrap.config[:use_sudo] = true\n end\n\n Chef::Log.debug(\"Bootstrap use_sudo = #{bootstrap.config[:use_sudo]}\")\n\n bootstrap.config[:environment] = config[:environment]\n Chef::Log.debug(\"Bootstrap environment = #{bootstrap.config[:environment]}\")\n\n bootstrap.config[:no_host_key_verify] = config[:no_host_key_verify]\n Chef::Log.debug(\"Bootstrap no_host_key_verify = #{bootstrap.config[:no_host_key_verify]}\")\n\n bootstrap.config[:identity_file] = config[:identity_file]\n Chef::Log.debug(\"Bootstrap identity_file = #{bootstrap.config[:identity_file]}\")\n\n bootstrap.config[:ssh_gateway] = determine_ssh_gateway(bootstrap_ip)\n Chef::Log.debug(\"Bootstrap ssh_gateway= #{bootstrap.config[:ssh_gateway]}\")\n\n bootstrap.config[:first_boot_attributes] = config[:json_attributes]\n Chef::Log.debug(\"Bootstrap json_attributes = #{bootstrap.config[:json_attributes]}\")\n\n bootstrap\n end", "def get_all_roles_nodes\n result = search(:node, \"chef_environment:#{node.chef_environment}\")\n if result.any? { |x| x['hostname'] == node['hostname'] }\n result.map! { |x| x['hostname'] == node['hostname'] ? node : x }\n else\n result.push(node)\n end\n return result.sort! { |a, b| a['hostname'] <=> b['hostname'] }\nend", "def role_dmtcpsnooze\n $myxp.get_deployed_nodes('capi5k-init')\nend", "def get_ansible_role(boxname)\n case boxname\n when \"centos/7\"\n \"centos7\"\n when \"ubuntu/xenial64\"\n \"xenial64\"\n when \"archlinux/archlinux\"\n \"arch\"\n end\nend", "def update_roles\r\n self.roles.create(:title => \"admin\")\r\n if self.name.eql? \"Grandor Eldoran\"\r\n self.roles.create(:title => \"admin\")\r\n elsif self.name.eql? \"Test2 Test2\"\r\n self.roles.create(:title => \"member\")\r\n end\r\n end", "def deploy_to_roles(base_roles=self.roles)\n base_roles.dup.delete_if{|role| self.excluded_hosts.include?(role.host) }\n end", "def deploy_to_roles(base_roles=self.roles)\n base_roles.dup.delete_if{|role| self.excluded_hosts.include?(role.host) }\n end", "def deploy_to_roles(base_roles=self.roles)\n base_roles.dup.delete_if{|role| self.excluded_hosts.include?(role.host) }\n end", "def setup_role\n if self.role_ids.empty?\n self.role_ids = self.roles.find_by_name(:registered).id\n end\n end", "def set_user_has_role_for_node\n @user_has_role_for_node = UserHasRoleForNode.find(params[:id])\n end", "def setup_role \n if self.role_ids.empty? \n self.role_ids = [2] \n end\n end", "def setup_role \n if self.role_ids.empty? \n self.role_ids = [2] \n end\n end", "def setup_role \n if self.role_ids.empty? \n self.role_ids = [2] \n end\n end", "def roles=(t)\n if t.kind_of?(String)\n t = t.downcase.split(\",\").join(\" \").split(\" \").uniq\n end\n self[:roles] = t\n end", "def register_node\n case node['platform']\n when 'windows'\n # Create temp directory where we copy/create source files to install tscm agent\n directory \"#{node['tscm']['temp']}\" do\n action :create\n not_if { ::File.directory?('C:\\\\tscm_temp')}\n end\n # copy tscm proxy key of tscm server on Node\n cookbook_file \"#{node['tscm']['temp']}\\\\#{node['tscm']['native_proxykey']}\" do\n source \"#{node['tscm']['native_proxykey']}\"\n action :create\n end\n # fix permissions of client side files keys\n powershell_script 'fix_keyfile_permission' do\n code <<-EOH\n cd 'C:/Program Files/OpenSSH-Win64/'\n Import-Module ./OpenSSHUtils.psd1 -Force \n Repair-UserKeyPermission -FilePath 'C:\\\\tscm_temp\\\\SCM_id_rsa' -Confirm:$false\n EOH\n end\n \n execute 'register-tscm' do\n command \"C:\\\\PROGRA~1\\\\OpenSSH-Win64\\\\ssh.exe -vvv -n -o StrictHostKeyChecking=no -vvv -i #{node['tscm']['temp']}\\\\SCM_id_rsa #{node['tscm']['TSCMProxy_user']}@#{node['tscm']['TSCMProxy_server']}\" + \" powershell.exe -File #{node['tscm']['tscmWrapper_path']} reg #{node['tscm']['hostname']} w2k12 #{node['tscm']['ipaddress']} > #{node['tscm']['register_log']} 2>&1\"\n action :run\n timeout 3600\n end\n ruby_block 'sleep-after-register' do\n block do\n sleep(120)\n end\n action :run\n end\n end\nend", "def setup_role \n if self.role_ids.empty? \n self.role_ids = [Role.find_by_name(\"User\").id] \n end\n end", "def camaleon_spree_user_roles_hook(args)\n args[:roles_list][:manager] << { key: 'spree_role', label: t('plugins.spree_cama.admin.roles.label', default: 'Spree Ecommerce'), description: t('plugins.spree_cama.admin.roles.descr', default: 'Manage all sections of Spree Ecommerce')}\n end", "def set_roles\n roles << Role.user unless has_role?(\"user\")\n as_seller! if @registration_as_seller.to_i == 1\n end", "def write_build_roles(path)\n docker_run_list.expanded_run_list_roles.each do |role|\n r = Chef::Resource::File.new(::File.join(path, \"#{role}.json\"), run_context)\n r.content(Chef::Role.load(role).to_json)\n r.run_action(:create)\n end\n end", "def start_new_roles_on_nodes(nodes_needed, instance_type, secret)\n if !valid_secret?(secret)\n return BAD_SECRET_MSG\n end\n\n if nodes_needed.class != Array\n Djinn.log_error(\"Was expecting nodes_needed to be an Array, not \" +\n \"a #{nodes_needed.class}\")\n return BAD_INPUT_MSG\n end\n\n Djinn.log_info(\"Received a request to acquire nodes with roles \" +\n \"#{nodes_needed.join(', ')}, with instance type #{instance_type} for \" +\n \"new nodes\")\n\n vms_to_use = []\n ZKInterface.lock_and_run {\n num_of_vms_needed = nodes_needed.length\n\n @nodes.each_with_index { |node, index|\n if node.is_open?\n Djinn.log_info(\"Will use node #{node} to run new roles\")\n node.jobs = nodes_needed[vms_to_use.length]\n vms_to_use << node\n\n if vms_to_use.length == nodes_needed.length\n Djinn.log_info(\"Only using open nodes to run new roles\")\n break\n end\n end\n }\n\n vms_to_spawn = nodes_needed.length - vms_to_use.length\n \n if vms_to_spawn > 0 and !is_cloud?\n Djinn.log_error(\"Still need #{vms_to_spawn} more nodes, but we \" +\n \"aren't in a cloud environment, so we can't acquire more nodes - \" +\n \"failing the caller's request.\")\n return NOT_ENOUGH_OPEN_NODES\n end\n\n if vms_to_spawn > 0\n Djinn.log_info(\"Need to spawn up #{vms_to_spawn} VMs\")\n # Make sure the user has said it is ok to add more VMs before doing so.\n allowed_vms = Integer(@creds['max_images']) - @nodes.length\n if allowed_vms < vms_to_spawn\n Djinn.log_info(\"Can't spawn up #{vms_to_spawn} VMs, because that \" +\n \"would put us over the user-specified limit of #{@creds['max']} \" +\n \"VMs. Instead, spawning up #{allowed_vms}.\")\n vms_to_spawn = allowed_vms\n if vms_to_spawn.zero?\n Djinn.log_error(\"Reached the maximum number of VMs that we \" +\n \"can use in this cloud deployment, so not spawning more nodes.\")\n return \"Reached maximum number of VMs we can use.\"\n end\n end\n\n disks = Array.new(size=vms_to_spawn, obj=nil) # no persistent disks\n\n # start up vms_to_spawn vms as open\n imc = InfrastructureManagerClient.new(@@secret)\n begin\n new_nodes_info = imc.spawn_vms(vms_to_spawn, @creds, \"open\", disks)\n rescue AppScaleException => exception\n Djinn.log_error(\"Couldn't spawn #{vms_to_spawn} VMs with roles \" +\n \"open because: #{exception.message}\")\n return exception.message\n end\n\n\n # initialize them and wait for them to start up\n Djinn.log_debug(\"info about new nodes is \" +\n \"[#{new_nodes_info.join(', ')}]\")\n add_nodes(new_nodes_info)\n\n # add information about the VMs we spawned to our list, which may\n # already have info about the open nodes we want to use\n new_nodes = Djinn.convert_location_array_to_class(new_nodes_info,\n @creds['keyname'])\n vms_to_use << new_nodes\n vms_to_use.flatten!\n end\n }\n\n wait_for_nodes_to_finish_loading(vms_to_use)\n \n nodes_needed.each_index { |i|\n Djinn.log_info(\"Adding roles #{nodes_needed[i].join(', ')} \" +\n \"to virtual machine #{vms_to_use[i]}\")\n ZKInterface.add_roles_to_node(nodes_needed[i], vms_to_use[i],\n @creds['keyname'])\n }\n\n wait_for_nodes_to_finish_loading(vms_to_use)\n\n return \"OK\"\n end", "def define_vm config, role, index, ip, memory = 512\n id = (index + 1).to_s.rjust(3, '0')\n config.vm.define \"#{role}_#{id}\" do |box|\n box.vm.customize [ \"modifyvm\", :id, \"--memory\", memory ]\n box.vm.box = \"centos_6_3\"\n box.vm.box_url = \"https://dl.dropbox.com/u/7225008/Vagrant/CentOS-6.3-x86_64-minimal.box\"\n box.vm.network :hostonly, \"192.168.34.#{ip}\", :netmask => \"255.255.255.0\"\n box.vm.host_name = \"#{role.downcase.gsub(/[^a-z0-9]+/, '-')}-#{id}.esi.dev\"\n #box.vm.provision :shell, :path => \"script/bootstrap-vm.sh\"\n box.vm.provision :puppet, :module_path => \"modules\" do |p|\n p.manifests_path = \"manifests\"\n p.manifest_file = \"site.pp\"\n end\n end\nend", "def expand!(data_source = \"server\")\n expansion = run_list.expand(chef_environment, data_source)\n raise Chef::Exceptions::MissingRole, expansion if expansion.errors?\n\n tags # make sure they're defined\n\n automatic_attrs[:recipes] = expansion.recipes.with_duplicate_names\n automatic_attrs[:expanded_run_list] = expansion.recipes.with_fully_qualified_names_and_version_constraints\n automatic_attrs[:roles] = expansion.roles\n\n apply_expansion_attributes(expansion)\n\n automatic_attrs[:chef_environment] = chef_environment\n expansion\n end", "def roles=(roles)\n roles = [*roles].map { |r| r.to_sym }\n self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)\n end", "def set_sys_role\n @sys_role = SysRole.find(params[:id])\n end", "def setup_role\n if self.role_ids.empty?\n self.role_ids = [2]\n end\n end", "def roles(klass)\n if @resource_config[:roles]\n raise DefinitionError, \"roles already declared in #{self}\"\n end\n @resource_config[:roles] = klass\n end", "def bootstrap_for_node(server, ssh_host)\n host = server[\"name\"]\n user = config[:ssh_user]\n password = server[\"password\"]\n Chef::Log.debug(\"Bootstrap host: #{host}\")\n Chef::Log.debug(\"Bootstrap user: #{user}\")\n Chef::Log.debug(\"Bootstrap pass: #{password}\")\n bootstrap = Chef::Knife::Bootstrap.new\n bootstrap.name_args = [ssh_host]\n bootstrap.config[:run_list] = config[:run_list]\n bootstrap.config[:ssh_user] = user\n bootstrap.config[:ssh_password] = password\n bootstrap.config[:ssh_gateway] = config[:ssh_gateway]\n bootstrap.config[:identity_file] = locate_config_value(:identity_file)\n bootstrap.config[:chef_node_name] = config[:server_display_name] if config[:server_display_name]\n bootstrap.config[:prerelease] = config[:prerelease]\n bootstrap.config[:bootstrap_version] = locate_config_value(:bootstrap_version)\n bootstrap.config[:distro] = locate_config_value(:distro)\n bootstrap.config[:use_sudo] = true\n bootstrap.config[:template_file] = locate_config_value(:template_file)\n bootstrap.config[:environment] = config[:environment]\n bootstrap.config[:secret_file] = locate_config_value(:secret_file)\n # may be needed for vpc_mode\n bootstrap.config[:no_host_key_verify] = config[:no_host_key_verify]\n begin\n bootstrap\n rescue\n sleep @initial_sleep_delay\n retry\n end\n end", "def roles=(roles)\n self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum\n end", "def roles=(roles)\n self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum\n end", "def setup_role\n \tif self.role_ids.empty?\n \t self.role_ids = [3]\n \tend\n end", "def bootstrap\n @inventory.add(@server.config['name'], @server.windows? ? @server.canonicalIP : @server.mu_name)\n play = {\n \"hosts\" => @server.config['name']\n }\n\n if !@server.windows? and @server.config['ssh_user'] != \"root\"\n play[\"become\"] = \"yes\"\n end\n\n if @server.windows?\n play[\"roles\"] = [\"mu-windows\"]\n else\n play[\"roles\"] = [\"mu-base\"]\n end\n if @server.config['run_list']\n play[\"roles\"].concat(@server.config['run_list'])\n end\n\n if @server.config['ansible_vars']\n play[\"vars\"] = @server.config['ansible_vars']\n end\n\n if @server.windows?\n play[\"vars\"] ||= {}\n play[\"vars\"][\"ansible_connection\"] = \"winrm\"\n play[\"vars\"]['ansible_python_interpreter'] = \"c:/bin/python/python310/python.exe\"\n play[\"vars\"][\"ansible_winrm_scheme\"] = \"https\"\n play[\"vars\"][\"ansible_winrm_transport\"] = \"ntlm\"\n play[\"vars\"][\"ansible_winrm_server_cert_validation\"] = \"ignore\" # XXX this sucks; use Mu_CA.pem if we can get it to work\n# play[\"vars\"][\"ansible_winrm_ca_trust_path\"] = \"#{MU.mySSLDir}/Mu_CA.pem\"\n play[\"vars\"][\"ansible_user\"] = @server.config['windows_admin_username']\n win_pw = @server.getWindowsAdminPassword\n\n pwfile = MU::Groomer::Ansible.vaultPasswordFile\n cmd = %Q{#{MU::Groomer::Ansible.ansibleExecDir}/ansible-vault}\n output = %x{#{cmd} encrypt_string '#{win_pw.gsub(/'/, \"\\\\\\\\'\")}' --vault-password-file #{pwfile}}\n\n play[\"vars\"][\"ansible_password\"] = output\n end\n\n File.open(@ansible_path+\"/\"+@server.config['name']+\".yml\", File::CREAT|File::RDWR|File::TRUNC, 0600) { |f|\n f.flock(File::LOCK_EX)\n f.puts [play].to_yaml.sub(/ansible_password: \\|-?[\\n\\s]+/, 'ansible_password: ') # Ansible doesn't like this (legal) YAML\n f.flock(File::LOCK_UN)\n }\n end", "def before_restart_role(cm, cl, hostname, role_type, role)\n CM.enter_maintenance_mode_role(cm, cl, role)\n\n case role_type\n when 'REGIONSERVER'\n empty_rs(cm, cl, hostname, @exp_file)\n when 'NAMENODE'\n nns = CM.nameservices_assigned_nn(cm, cl, role)\n nns.each { |nn| CM.failover_nn(cm, cl, role, nn) }\n end\n end", "def install_tscm\n case node['platform']\n when 'redhat'\n # Create dir to mount\n directory '/opt/IBM/SCM' do\n recursive true\n action :create\n end\n\n #Create SCM logical volume \n node['tscm']['logvols'].each do |logvol|\n lvm_logical_volume logvol['volname'] do\n group node['tscm']['volumegroup']\n size logvol['size']\n filesystem logvol['fstype']\n mount_point logvol['mountpoint']\n end\n end \n # verifying the tscm installation if already exists\n if ::File.exist?(\"#{node['tscm']['installed_dir']}jacclient\")\n install_status = shell_out(\"#{node['tscm']['installed_dir']}jacclient status\").stdout.chop\n if install_status.include?('The Tivoli Security Compliance Manager client is currently running')\n Chef::Log.error('TSCM client already installed on ' + (node['tscm']['node_name']).to_s + '........Nothing to do')\n end\n else\n Chef::Log.info('Installing TSCM ....')\n\n # creating a temporary directory for installinsg TSCM\n tempfolder = '/opt/IBM/tscm_temp'\n\n directory tempfolder.to_s do\n action :create\n end\n\n # get TSCM media to our temp dir\n media = tempfolder + '/' + node['tscm']['base_package'].to_s\n\n remote_file media.to_s do\n source node['tscm']['url'].to_s\n owner 'root'\n group 'root'\n mode '0755'\n action :create_if_missing\n end\n\n # Unpacking TSCM media\n execute 'unpack-media' do\n command 'cd ' + tempfolder.to_s + ' ; ' + ' tar -xf ' + media.to_s\n action :run\n not_if { ::File.exist?(\"#{media}/#{node['tscm']['base_package']}\") }\n end\n\n # run the installation script\n bash 'install-tscm' do\n code <<-EOH\n cd #{tempfolder}\n chmod 744 install_x64.sh\n ./install_x64.sh\n EOH\n end\n\n # copy the ssh key for TSCM to /opt/IBM/\n cookbook_file node['tscm']['key'].to_s do\n source node['tscm']['key_name'].to_s\n owner 'root'\n group 'root'\n mode '400'\n action :create_if_missing\n end\n\n # create temp directory to copy the auditing patching file\n directory node['tscm']['patch_dir'].to_s do\n recursive true\n owner 'root'\n group 'root'\n mode '0744'\n action :create\n end\n\n # copy the powershell script to node system\n cookbook_file node['tscm']['copy_script_path'].to_s do\n source 'copy_script.ps1'\n owner 'root'\n group 'root'\n mode '750'\n action :create\n end\n\n # copy the powershell script to TSCM Server\n bash 'copy-powershell-script-to-tscm-server' do\n code <<-EOH\n scp -C -o StrictHostKeyChecking=no -i #{node['tscm']['key']} #{node['tscm']['copy_script_path']} #{node['tscm']['proxy_user']}@#{node['tscm']['proxy_server']}:/c:/users/scm_auto_usr/\n\t EOH\n live_stream true\n action :run\n end\n\n # run the powershell scripts\n execute 'run-powershell-script' do\n command \"ssh -n -i #{node['tscm']['key']} #{node['tscm']['proxy_user']}@#{node['tscm']['proxy_server']} powershell -File 'C:/Users/scm_auto_usr/copy_script.ps1'\"\n live_stream true\n action :run\n end\n\n # copy the audit patching file\n execute 'download-audi-patching-file' do\n command \"scp -o StrictHostKeyChecking=no -i #{node['tscm']['key']} #{node['tscm']['proxy_user']}@#{node['tscm']['proxy_server']}:/C:/Users/scm_auto_usr/lssec_secfixdb_all.tar.gz /opt/IBM/SCM/client/software/completed/\"\n live_stream true\n action :run\n not_if { ::File.exist?(node['tscm']['audit_file'].to_s) }\n end\n\n client_pref = shell_out(\"grep 'debug=true' #{node['tscm']['client_pref']} \").stdout.chop\n\n if client_pref.include?('debug=true')\n Chef::Log.info('File Up to date..........Nothing to do')\n else\n # update the client.pref file to debug mode\n execute 'update-client.pref' do\n command \"sed -i -e 's/debug=false/debug=true/' #{node['tscm']['client_pref']}\"\n action :run\n end\n\n # restarting TSCM agent service for changes to take effect\n service node['tscm']['service_name'].to_s do\n action :stop\n end\n\n service node['tscm']['service_name'].to_s do\n action :start\n end\n end\n end\n\n # installing on aix\n when 'aix'\n Chef::Log.info('Installing TSCM on AIX platform...........')\n\n if ::File.exist?(\"#{node['tscm']['installed_dir']}jacclient\")\n install_status = shell_out(\"#{node['tscm']['installed_dir']}jacclient status\").stdout.chop\n if install_status.include?('HCVIN0033I The Tivoli Security Compliance Manager client is currently running')\n Chef::Log.error('TSCM client already installed on ' + (node['tscm']['node_name']).to_s + '........Nothing to do')\n end\n else\n Chef::Log.info('TSCM not installed ........Installing TSCM ')\n\n # creating temporary directory for copying tscm binaries\n tempfolder = '/opt/IBM/tscm_software'\n\n directory tempfolder.to_s do\n action :create\n not_if { ::File.exist?(tempfolder.to_s) }\n end\n\n media = tempfolder.to_s + '/' + (node['tscm']['base_package']).to_s\n node.default['tscm']['package_name'] = (node['tscm']['base_package']).to_s.chomp('.tar')\n\n # downloading binaries from the url\n remote_file media.to_s do\n source node['tscm']['url'].to_s\n owner 'root'\n mode '0755'\n action :create_if_missing\n end\n\n # creating prerequisite FS\n # create volume group ibmvg as mandatory requirement\n execute 'create-VG-ibmvg' do\n command 'mkvg -f -y ibmvg hdisk1'\n action :run\n returns [0, 1]\n not_if { shell_out('lsvg | grep ibmvg').stdout.chop != '' }\n end\n\n # required FS\n volumes = [\n { lvname: 'lv_scm', fstype: 'jfs2', vgname: 'ibmvg', size: 500, fsname: '/opt/IBM/SCM' },\n ]\n # Custom FS creation\n volumes.each do |data|\n ibm_tscm_makefs \"creation of #{data[:fsname]} file system\" do\n lvname data[:lvname]\n fsname data[:fsname]\n vgname data[:vgname]\n fstype data[:fstype]\n size data[:size]\n end\n end\n\n # Unpacking TSCM media\n execute 'unpack-media' do\n command 'cd ' + tempfolder.to_s + ' ; ' + ' tar -xf ' + media.to_s\n action :run\n not_if { ::File.exist?(media.to_s + node['tscm']['package_name'].to_s + 'install_aix6.sh') }\n end\n\n # run the installation script\n bash 'install-tscm' do\n code <<-EOH\n cd #{tempfolder}\n chmod +x install_aix6.sh\n ./install_aix6.sh \n EOH\n end\n\n # copy the ssh key for TSCM to /opt/IBM/ directory\n cookbook_file node['tscm']['key'].to_s do\n source node['tscm']['key_name'].to_s\n owner 'root'\n mode '400'\n action :create_if_missing\n end\n\n # create temp directory to copy the auditing patching file\n directory node['tscm']['patch_dir'].to_s do\n recursive true\n owner 'root'\n mode '0744'\n action :create\n end\n\n # copy the audit patching file\n execute 'download-audi-patching-file' do\n command \"scp -o StrictHostKeyChecking=no -i #{node['tscm']['key']} #{node['tscm']['proxy_user']}@#{node['tscm']['proxy_server']}:/C:/PROGRA~1/IBM/SCM/client/software/completed/lssec_secfixdb_all.tar.gz /opt/IBM/SCM/client/software/completed/\"\n action :run\n not_if { ::File.exist?(node['tscm']['audit_file'].to_s) }\n end\n\n # changing log-level to debug mode\n client_pref = shell_out(\"grep 'debug=true' #{node['tscm']['client_pref']} \").stdout.chop\n\n if client_pref.include?('debug=true')\n Chef::Log.info('File Up to date..........Nothing to do')\n else\n # update the client.pref file to debug mode\n execute 'update-client.pref' do\n command \"sed -e 's/debug=false/debug=true/g' #{node['tscm']['client_pref']}\"\n action :run\n end\n\n # restarting TSCM agent service for changes to take effect\n execute 'restart-tscm-service' do\n command '/opt/IBM/SCM/client/jacclient restart'\n action :run\n end\n end\n end\n end\nend", "def chef_context\n @chef_context || ::Capistrano.env\n end", "def app_roles=(value)\n @app_roles = value\n end", "def recipes\n ['runit', proc {\n begin\n if node['virtualization'] && %w{docker lxc}.include?(node['virtualization']['system'])\n resources('service[runsvdir-start]').action(:nothing)\n end\n rescue Chef::Exceptions::ResourceNotFound\n end\n }]\n end", "def ansible_roles\n roles = blueprint.resources.pluck(:type).map { |resource| resource.demodulize.underscore }\n roles.each_with_object({}) do |role, hash|\n hash[role] = [project_name]\n end\n end", "def roles=(roles)\n self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)\n end", "def roles=(roles)\n self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)\n end", "def set_roles *roles\n roles = roles.flatten\n raise ArgumentError, \"For a single role strategy you can only set one role, was: #{roles.flatten}\" if roles.empty? || (roles.size > 1)\n set_role roles.first\n end", "def settings_for_node\n cluster_name = self.parent.name.to_sym\n cluster_role = self.name.to_sym\n node_settings = {\n :user_data => { :attributes => { :run_list => [] } },\n :cluster_name => cluster_name,\n :cluster_role => cluster_role,\n }.deep_merge(Settings)\n node_settings.delete :pools\n raise \"Please define the '#{cluster_name}' cluster and the '#{cluster_role}' role in your ~/.chef/cluster_chef.yaml\" if (Settings[:pools][cluster_name].blank? || Settings[:pools][cluster_name][cluster_role].blank?)\n node_settings = node_settings.deep_merge(\n Settings[:pools][cluster_name][:common] ||{ }).deep_merge(\n Settings[:pools][cluster_name][cluster_role] ||{ })\n configure_aws_region node_settings\n node_settings\nend", "def set_system_role\n @role = System::Role.find(params[:id])\n end", "def web_servers; machines_by_role('web'); end", "def update_guild_role(data)\n role_data = data['role']\n server_id = data['guild_id'].to_i\n server = @servers[server_id]\n new_role = Role.new(role_data, self, server)\n role_id = role_data['id'].to_i\n old_role = server.roles.find { |r| r.id == role_id }\n old_role.update_from(new_role)\n end", "def update_guild_role(data)\n role_data = data['role']\n server_id = data['guild_id'].to_i\n server = @servers[server_id]\n new_role = Role.new(role_data, self, server)\n role_id = role_data['id'].to_i\n old_role = server.roles.find { |r| r.id == role_id }\n old_role.update_from(new_role)\n end", "def bootstrap_for_node\n bootstrap = Chef::Knife::Bootstrap.new\n bootstrap.name_args = [config[:fqdn]]\n bootstrap.config[:run_list] = get_config(:run_list).split(/[\\s,]+/)\n bootstrap.config[:secret_file] = get_config(:secret_file)\n bootstrap.config[:hint] = get_config(:hint)\n bootstrap.config[:ssh_user] = get_config(:ssh_user)\n bootstrap.config[:ssh_password] = get_config(:ssh_password)\n bootstrap.config[:ssh_port] = get_config(:ssh_port)\n bootstrap.config[:identity_file] = get_config(:identity_file)\n bootstrap.config[:chef_node_name] = get_config(:chef_node_name)\n bootstrap.config[:prerelease] = get_config(:prerelease)\n bootstrap.config[:bootstrap_version] = get_config(:bootstrap_version)\n bootstrap.config[:distro] = get_config(:distro)\n bootstrap.config[:use_sudo] = true unless get_config(:ssh_user) == 'root'\n bootstrap.config[:template_file] = get_config(:template_file)\n bootstrap.config[:environment] = get_config(:environment)\n bootstrap.config[:first_boot_attributes] = get_config(:first_boot_attributes)\n bootstrap.config[:log_level] = get_config(:log_level)\n # may be needed for vpc_mode\n bootstrap.config[:no_host_key_verify] = get_config(:no_host_key_verify)\n bootstrap\n end", "def is_hadoop_node settings\n has_role settings, \"hadoop\"\nend", "def set_up_server\n node = Chef::Node.new\n node.name 'nothing'\n node.automatic[:platform] = 'kitchen_metal'\n node.automatic[:platform_version] = 'kitchen_metal'\n Chef::Config.local_mode = true\n run_context = Chef::RunContext.new(node, {},\n Chef::EventDispatch::Dispatcher.new(Chef::Formatters::Doc.new(STDOUT,STDERR)))\n recipe_exec = Chef::Recipe.new('kitchen_vagrant_metal',\n 'kitchen_vagrant_metal', run_context)\n\n # We require a platform, but layout in driver is optional\n recipe_exec.instance_eval get_platform_recipe\n recipe = get_driver_recipe\n recipe_exec.instance_eval recipe if recipe\n return run_context\n end", "def after_restart_role(cm, cl, hostname, role_type, role)\n case role_type\n when 'REGIONSERVER'\n import_rs(cm, cl, hostname, @exp_file)\n when 'JOURNALNODE'\n CM.hdfs_role_edits(cm, cl, role)\n when *CHK_RTYPES\n CM.check_ha_status(cm, cl, role)\n end\n CM.exit_maintenance_mode_role(cm, cl, role)\n end", "def roles(roles) #:nodoc:\n @roles = roles\n end", "def on_app_master(&blk) on_roles(%w[solo app_master], &blk) end", "def app_servers\n return super unless CDO.chef_managed\n require 'aws-sdk'\n servers = Aws::EC2::Client.new.describe_instances(\n filters: [\n {name: 'tag:aws:cloudformation:stack-name', values: [CDO.stack_name]},\n {name: 'tag:aws:cloudformation:logical-id', values: ['Frontends']},\n {name: 'instance-state-name', values: ['running']}\n ]\n ).reservations.map(&:instances).flatten.map {|i| [\"fe-#{i.instance_id}\", i.private_dns_name]}.to_h\n servers.merge(super)\n end", "def install_dependent_roles\n ansible_directory = File.join(\"deployment\", \"ansible\")\n ansible_roles_txt = File.join(ansible_directory, \"roles.txt\")\n\n File.foreach(ansible_roles_txt) do |line|\n role_name, role_version = line.split(\",\")\n role_path = File.join(ansible_directory, \"roles\", role_name)\n galaxy_metadata = galaxy_install_info(role_name)\n\n if galaxy_metadata[\"version\"] != role_version.strip\n unless system(\"ansible-galaxy install -f -r #{ansible_roles_txt} -p #{File.dirname(role_path)}\")\n $stderr.puts \"\\nERROR: An attempt to install Ansible role dependencies failed.\"\n exit(1)\n end\n\n break\n end\n end\nend", "def find_multiple_nodes_by_role(role, stack, alternate=nil)\n if !node[:override_stacks].nil? && !node[:override_stacks][role].nil?\n stack = node[:override_stacks][role]\n puts \"stack override for #{role} found, using stack #{stack}\"\n end\n @nodes ||= find_stack(stack)\n matching_nodes = []\n @nodes.each { |stack_node|\n if stack_node[:roles] && stack_node[:roles].select{ |r| r[/#{role}/] }.size > 0\n matching_nodes << stack_node\n end\n }\n if matching_nodes.size == 0 && alternate\n Chef::Log.debug \"Unable to locate a #{role} machine in the '#{stack}' environment. Searching for alternate #{alternate} machine...\"\n @nodes.each { |stack_node|\n if stack_node[:roles] && stack_node[:roles].select{ |r| r[/#{alternate}/] }.size > 0\n matching_nodes << stack_node\n end\n }\n end\n # Fail if no node has been found in the stack\n raise \"The #{role} machine is either missing or corrupt in the #{stack} environment. This is okay, if the #{role} machine is not required.\" if matching_nodes.size == 0\n return matching_nodes\nend", "def roles=(roles)\n return self.roles_mask = (roles.map(&:to_sym) & ROLES).map { |r| 2**ROLES.index(r) }.sum\n end", "def roles\n self.dig_for_array(\"roles\")\n end", "def run # rubocop:disable Metrics/AbcSize, Metrics/PerceivedComplexity\n self.config = Chef::Config.merge!(config)\n\n # OPTIMIZE: Maybe instead of a flag, infer the graph format from fileext?\n\n # Parse the configuration options, provide defaults where needed\n output_format = if config[:graphformat]\n config[:graphformat].to_sym\n else\n :png\n end\n Chef::Log.debug(\"Output format is: #{output_format}\")\n\n # Determine of a filename has been passed\n filename = if @name_args.size >= 1\n @name_args[0]\n else\n \"role-spaghetti.#{output_format}\"\n end\n Chef::Log.debug(\"Output filename is: #{filename}\")\n\n loaded_roles = loader.find_all_objects(config[:role_path])\n\n # If we can't find any roles, it's pointless to continue.\n if loaded_roles.empty?\n ui.fatal(\"No roles were found in role_path: #{config[:role_path]}\")\n ui.fatal('Ensure that your knife.rb has the correct path.')\n exit 1\n end\n\n g = GraphViz.new(:RoleDependencies, type: :digraph,\n fontname: 'Verdana', fontsize: 20,\n label: \"\\n\\n\\nChef Role Dependencies\\n\",\n rankdir: 'LR',\n overlap: 'false',\n compound: 'true')\n\n loaded_roles.each do |role_file|\n # Create an absolute path, since some file references include relative paths\n abspath = File.absolute_path(File.join(config[:role_path], role_file))\n\n # The object_from_file method figures out the ruby/json logic\n role = loader.object_from_file(abspath)\n\n Chef::Log.debug(\"Loaded role is: #{role}\")\n\n # OPTIMIZE: Handle environment run_lists\n\n g.node[:shape] = 'box'\n g.node[:style] = 'rounded'\n g.node[:color] = 'red'\n role_node = g.add_nodes(\"#{role.name}_role\", label: role.name)\n\n # This logic is to ensure that an embedded role doesn't change color\n role.run_list.each do |rli|\n if rli.role?\n g.node[:shape] = 'box'\n g.node[:style] = 'rounded'\n g.node[:color] = 'red'\n rli_node = g.add_nodes(\"#{rli.name}_role\", label: rli.name)\n else\n g.node[:shape] = 'component'\n g.node[:color] = 'blue'\n rli_node = g.add_nodes(rli.name)\n end\n\n g.add_edges(role_node, rli_node)\n end\n end\n\n # Let's write out the graph to a file\n if config[:neatograph]\n g.output(output_format => filename.to_s, :use => 'neato')\n else\n # default to dot\n g.output(output_format => filename.to_s)\n end\n\n ui.msg(\"A Role dependency graph has been written to #{filename}\")\n end", "def roles\n\t\t\t\tProxy.new connection, 'role-strategy/strategy'\n\t\t\tend", "def ansible_roles\n roles = build.ansible_groups || []\n # roles = blueprint.resources.pluck(:type).map { |resource| resource.demodulize.underscore }\n roles.each_with_object({}) do |role, hash|\n # hash[role] = [project_name]\n hash[role] = ['default']\n end\n end" ]
[ "0.64230657", "0.6332273", "0.63054746", "0.62497824", "0.6248228", "0.6095409", "0.60914296", "0.60622865", "0.6020724", "0.5995489", "0.59676796", "0.5967544", "0.5930855", "0.5878182", "0.5830454", "0.58098686", "0.5804533", "0.5804311", "0.5793348", "0.5769174", "0.5759125", "0.5738702", "0.5719813", "0.5690622", "0.5690622", "0.5688671", "0.567663", "0.5669592", "0.5651951", "0.5613083", "0.56039214", "0.5586415", "0.5579602", "0.55710995", "0.5553064", "0.55518013", "0.5548708", "0.5532375", "0.5514632", "0.5512241", "0.54858243", "0.54784125", "0.5471674", "0.5458171", "0.5449831", "0.54431045", "0.54380566", "0.54380566", "0.54380566", "0.54349023", "0.5434873", "0.5414292", "0.5414292", "0.5414292", "0.540648", "0.53857404", "0.53789324", "0.53769994", "0.5368857", "0.535984", "0.5358643", "0.53506625", "0.53380466", "0.53336877", "0.53286564", "0.5327877", "0.5322464", "0.5302312", "0.5295318", "0.5295318", "0.529341", "0.5292672", "0.5260325", "0.52574885", "0.5256822", "0.52392507", "0.5236936", "0.5236559", "0.5232625", "0.5232625", "0.52286994", "0.5228125", "0.52239496", "0.5218592", "0.5218131", "0.5218131", "0.52175015", "0.5214938", "0.5202077", "0.51929647", "0.51909184", "0.51844436", "0.51769304", "0.5174035", "0.5167422", "0.5165597", "0.5160841", "0.515402", "0.51505667", "0.51483005" ]
0.61421573
5
Query a Chef Server to search for specific nodes
def chef_search(type, query="*:*") chef_scopes = fetch(:chef_scopes) || [] queries = [chef_scopes, query].flatten.join(" AND ") puts "Searching Chef types \"#{type}\" with \"#{queries}\"" if debug? results = chef_query_class.new.search(type, queries).first puts "Found #{results.count}" if debug? results end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def node_list\n list = {}\n search = Chef::Search::Query.new\n query = config[:query]\n\n ui.msg \"Search nodes '#{query}'\"\n search.search('node', query) do |node|\n if node['chef'] && node['chef']['client_version']\n version = node['chef']['client_version']\n\n list[version] ||= []\n list[version] << node\n end\n end\n ui.msg ''\n\n list\n end", "def discover_chef_nodes!\n chef_nodes.each do |chef_node|\n if chef_node[\"cluster_name\"] && chef_node[\"facet_name\"] && chef_node[\"facet_index\"]\n cluster_name = chef_node[\"cluster_name\"]\n facet_name = chef_node[\"facet_name\"]\n facet_index = chef_node[\"facet_index\"]\n elsif chef_node.name\n ( cluster_name, facet_name, facet_index ) = chef_node.name.split(/-/)\n else\n next\n end\n svr = Ironfan::Server.get(cluster_name, facet_name, facet_index)\n svr.chef_node = chef_node\n @aws_instance_hash[ chef_node.ec2.instance_id ] = svr if chef_node && chef_node[:ec2] && chef_node.ec2.instance_id\n end\n end", "def ceph_chef_mon_nodes\n results = nil\n if node['ceph']['search_by_environment']\n results = search(:node, ceph_chef_mon_env_search_string)\n else\n results = search(:node, \"tags:#{node['ceph']['mon']['tag']}\")\n if !results.include?(node) && node.run_list.roles.include?(node['ceph']['mon']['role'])\n results.push(node)\n end\n end\n\n results.map! { |x| x['hostname'] == node['hostname'] ? node : x }\n results.sort! { |a, b| a['hostname'] <=> b['hostname'] }\nend", "def auto_discover_nodes!\n @servers = execute(:all_nodes)\n end", "def query_by_nodename(nodename)\n query = {\"query\" => \"SELECT NodeName, NodeID FROM Orion.Nodes WHERE NodeName=@name\", \"parameters\" => {\"name\" => \"#{nodename}\"}}\n do_http_request(@querypath, query)\n end", "def change_chef_vars(instances, &block)\n instances.each { |inst|\n query = \"name:#{inst['server_name']}\"\n query_nodes = Chef::Search::Query.new\n query_nodes.search('node', query) do |node_item|\n yield node_item\n end\n }\n end", "def nodes\n request.get(path: node_index_path, auth_token: auth_token)\n end", "def get_nodes\n\tq = '[\"=\", [\"node\", \"active\"], true]'\n\n\tif ! q.is_a? String then\n\t\tq=JSON[q]\n\t\tend\n\tparams = {:query => q}\n\n response_nodelist = RestClient.get\"http://#{Tayu.puppetdb_server}:#{Tayu.puppetdb_port}/nodes\", { :accept => :json, :params => params }\n return JSON.parse(response_nodelist)\n end", "def find_nodes\n puts '1st pass: find nodes'\n find :nodes\n self\n end", "def query_couchbase_servers\n\n couchbase_servers = Hash.new\n \n r=rightscale_server_collection 'couchbase_cluster_nodes' do\n tags [\"couchbase:cluster_ip=#{cluster_ip}\"]\n secondary_tags [\"server:uuid=*\", \"couchbase:listen_ip=*\"]\n action :nothing\n end\n r.run_action(:load)\n \n node[:server_collection]['couchbase_cluster_nodes'].to_hash.values.each do |tags|\n uuid = RightScale::Utils::Helper.get_tag_value('server:uuid', tags)\n ip = RightScale::Utils::Helper.get_tag_value('couchbase:listen_ip', tags)\n couchbase_servers[uuid] = {}\n couchbase_servers[uuid][:ip] = ip\n end\n \n couchbase_servers\n \n end", "def query_by_nodeid(nodeid)\n query = {\"query\" => \"SELECT NodeName, NodeID FROM Orion.Nodes WHERE NodeID=@id\", \"parameters\" => {\"id\" => \"#{nodeid}\"}}\n do_http_request(@querypath, query)\n end", "def node_list\n Chef::Node.list.keys\n end", "def kube_custom_search(context, term)\n cluster_id = node[cookbook_name]['cluster_id']\n ret_val = []\n filter = { 'name' => ['fqdn'], 'ip' => ['ipaddress'] }\n # puts \"search(#{context}, #{term}, filter_result: #{filter})\"\n search(context, term, filter_result: filter).each do |inst|\n raw = \"Raw search returns #{inst.inspect}\"\n # >[{\"name\"=>\"server-0\", \"ip\"=>\"ip-0\"}, {\"name\"=>\"server-1\", \"ip\"=>\"ip-1\"}]\n raise raw + \"\\n\" + err('no_master') if inst['name'].nil? && term == \"role:k8s_master_#{cluster_id}\"\n raise raw + \"\\n\" + err('no_minion') if inst['name'].nil? && term == \"role:k8s_minion_#{cluster_id}\"\n ret_val.push(name: inst['name'].downcase, ip: inst['ip'])\n end\n if ret_val.empty?\n abort(err('no_master')) if term == \"role:k8s_master_#{cluster_id}\"\n abort(err('no_minion')) if term == \"role:k8s_minion_#{cluster_id}\"\n end\n ret_val # >[{\"name\"=>\"server-0\", \"ip\"=>\"ip-0\"}, {\"name\"=>\"server-1\", \"ip\"=>\"ip-1\"}]\n end", "def nodes_for_environment(name)\n ridley.partial_search(:node, \"chef_environment:#{name}\", [\"fqdn\", \"cloud.public_hostname\", \"name\", \"os\"])\n end", "def run( nodes )\n\t\t\tself.log.debug \"Got %d nodes to check with %p\" % [ nodes.length, self ]\n\t\t\tlookups = self.create_lookups( nodes )\n\t\t\treturn self.wait_for_responses( lookups, nodes )\n\t\tend", "def get_all_nodes(state)\n rc = []\n machines = state[:machines]\n chef_server = Cheffish::CheffishServerAPI.new(Cheffish.enclosing_chef_server)\n nodes = chef_server.get(\"/nodes\")\n nodes.each_key do |key|\n if (machines.include?(key))\n node_url = nodes[key]\n node = chef_server.get(node_url)\n rc.push(node)\n end\n end\n return rc\n end", "def nodes\n core_client.get_nodes\n end", "def listNodes\n nodes = []\n me = MU::Cloud::AWS::ServerPool.find(cloud_id: cloud_id).values.first\n if me and me.instances\n me.instances.each { |instance|\n found = MU::MommaCat.findStray(\"AWS\", \"server\", cloud_id: instance.instance_id, region: @region, dummy_ok: true)\n nodes.concat(found)\n }\n end\n nodes\n end", "def get_zk_nodes\n rl_results = search(:node, \"role:Kafka-Head-Zookeeper AND chef_environment:#{node.chef_environment}\")\n rl_results.map!{|x| x[:hostname] == node[:hostname] ? node : x}\n ro_results = search(:node, \"roles:Kafka-Head-Zookeeper AND chef_environment:#{node.chef_environment}\")\n ro_results.map!{|x| x[:hostname] == node[:hostname] ? node : x}\n results = rl_results.concat ro_results\n return results.uniq{|x| x[:hostname]}.sort\nend", "def discover_chef_clients!\n servers.each(&:chef_client)\n end", "def get_node_names\n Chef::Node.list.keys\n end", "def nodes(hsh={})\n results = describe_instances(:status=>'running').select_with_hash({:keypair_name => keypair.basename})\n results.select_with_hash(hsh)\n end", "def incoming(opts={})\n # Constrain results to this pool\n fq = \"format:Node\"\n # fq += \" AND pool:#{pool.id}\"\n http_response = Bindery.solr.select(params: {q:persistent_id, qf:\"bindery__associations_sim\", qt:'search', fq:fq})\n results = http_response[\"response\"][\"docs\"].map{|d| Node.find_by_persistent_id(d['id'])}\n end", "def getNodeList\n broker_url = APP_CONFIG['broker_ip'] + ':' + APP_CONFIG['broker_port'].to_s\n result = HTTParty.get(broker_url + \"/resources/nodes\", :verify => false)\n temp2 = JSON.parse(result.body)\n\n node_data = temp2[\"resource_response\"][\"resources\"]\n return node_data\n \n end", "def manage_cluster\n @nodes = Node.find(:all)\n end", "def nodelist\n runopts(:nodelist)\n end", "def get_nodes_by_recipe(recipe, includeme=true, options={})\n options = {\n :search_string => recipe,\n :include_me => includeme,\n :order => [:recipe],\n :safe_deref => nil,\n :current_node => nil,\n :one_or_all => :all\n }.merge(options)\n opsit_search(options)\n end", "def fakesearch_all_nodes(options = {})\n fakesearch_nodes(nil, options)\nend", "def get_all_roles_nodes\n result = search(:node, \"chef_environment:#{node.chef_environment}\")\n if result.any? { |x| x['hostname'] == node['hostname'] }\n result.map! { |x| x['hostname'] == node['hostname'] ? node : x }\n else\n result.push(node)\n end\n return result.sort! { |a, b| a['hostname'] <=> b['hostname'] }\nend", "def run( nodes )\n\t\t\tself.log.debug \"Got nodes to check with %p: %p\" % [ self, nodes ]\n\n\t\t\trecords = nodes.each_with_object( {} ) do |(identifier, node), hash|\n\t\t\t\tself.log.debug \"Looking up whois info for %p (%p)\" % [ identifier, node ]\n\t\t\t\thash[ identifier ] = self.client.lookup( node['name'] )\n\t\t\tend\n\n\t\t\treturn records.each_with_object( {} ) do |(identifier, record), hash|\n\t\t\t\tparser = record.parser\n\t\t\t\thash[ identifier ] = self.parse_record( parser, identifier )\n\t\t\tend\n\n\t\tend", "def services_for(node)\n # This info is taken from our JSON inventory file\n [JSON.parse(File.read(\"#{repository_path}/hosts.json\"))[\"#{node}.hpc_tutorial.org\"]]\n end", "def find\n log_output(\"Starting #{provider} find\", :info)\n validate_provision_fields\n connection = connect\n \n name = get_field('name')\n # select those servers matching name. Fail if servers don't have a name\n servers = connection.servers.select do |s|\n if s.respond_to?(:name)\n s.name =~ /#{name}/\n else\n raise PluginError, \"Provider #{provider} does not support finding servers by name\"\n end\n end\n\n save_server_ids_in_context(servers, true)\n save_server_in_context(servers, true)\n populate_meta(servers, 'find', true)\n\n msg = servers.empty? ? \"#{provider} found no servers\" : \"#{provider} found #{servers.size} servers: \"\n msg += servers.map{|s| s.respond_to?(:name) ? s.name : s.identity}.join(\",\")\n Maestro.log.debug msg\n write_output(\"#{msg}\\n\")\n end", "def getNodeStatus(node_id) \n cm_url = APP_CONFIG['cm_ip'] + ':' + APP_CONFIG['cm_port'].to_s\n res = HTTParty.get(cm_url+\"/resources/node/\"+ node_id)\n # puts \"status \"+node_id\n # puts res\n return res\n\n end", "def available_node_list\n all_nodes = Node.by_name\n return all_nodes.select {|node| node.status == \"RUNNING\"}\n end", "def help_node_names_data\n\t\t__elasticsearch__.client.cat.nodes(:format => 'json', :h => 'name')\n\tend", "def __get_nodes\n JSON.parse(Net::HTTP.get(URI(\"#{__cluster_url}/_nodes/process\")))\n end", "def get_node(state, name)\n machines = state[:machines]\n if (machines.include?(name))\n chef_server = Cheffish::CheffishServerAPI.new(Cheffish.enclosing_chef_server)\n nodes = chef_server.get(\"/nodes\")\n node_url = nodes[name]\n chef_server.get(node_url)\n else\n nil\n end\n end", "def find_nodes_with_http_info(term, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: QueriesApi.find_nodes ...\"\n end\n # verify the required parameter 'term' is set\n fail ArgumentError, \"Missing the required parameter 'term' when calling QueriesApi.find_nodes\" if term.nil?\n if !opts[:'skip_count'].nil? && opts[:'skip_count'] < 0.0\n fail ArgumentError, 'invalid value for \"opts[:\"skip_count\"]\" when calling QueriesApi.find_nodes, must be greater than or equal to 0.0.'\n end\n\n if !opts[:'max_items'].nil? && opts[:'max_items'] < 1.0\n fail ArgumentError, 'invalid value for \"opts[:\"max_items\"]\" when calling QueriesApi.find_nodes, must be greater than or equal to 1.0.'\n end\n\n # resource path\n local_var_path = \"/queries/nodes\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n query_params[:'term'] = term\n query_params[:'rootNodeId'] = opts[:'root_node_id'] if !opts[:'root_node_id'].nil?\n query_params[:'skipCount'] = opts[:'skip_count'] if !opts[:'skip_count'].nil?\n query_params[:'maxItems'] = opts[:'max_items'] if !opts[:'max_items'].nil?\n query_params[:'nodeType'] = opts[:'node_type'] if !opts[:'node_type'].nil?\n query_params[:'include'] = @api_client.build_collection_param(opts[:'include'], :csv) if !opts[:'include'].nil?\n query_params[:'orderBy'] = @api_client.build_collection_param(opts[:'order_by'], :csv) if !opts[:'order_by'].nil?\n query_params[:'fields'] = @api_client.build_collection_param(opts[:'fields'], :csv) if !opts[:'fields'].nil?\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n local_header_accept = ['application/json']\n local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result\n\n # HTTP header 'Content-Type'\n local_header_content_type = ['application/json']\n header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['basicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'NodePaging')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: QueriesApi#find_nodes\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def nodes\r\n params = {\r\n method: :get,\r\n url: '/project/nodes',\r\n params: { prjUUID: @uuid }\r\n }\r\n @session.request(**params).perform!['nodes']\r\n end", "def find_available_node\n node_name=nil\n nodes = JSON.parse http_get(@node_list_endpoint)\n nodes[\"computer\"].each do |i|\n if i[\"offline\"]\n node_name=i[\"displayName\"]\n break\n end\n end\n\n return node_name\nend", "def check_chef(hostname)\n knife = Chef::Knife.new\n knife.config[:config_file] = File.join(ENV['HOME'], '.chef', 'knife.rb')\n knife.configure_chef\n search_query = Chef::Search::Query.new\n result = search_query.search(:node, \"name:#{hostname}\")\n \n if result.last > 0\n puts msg = \"Chef already has node #{hostname} registered. Skipping\"\n @logger.warn(msg)\n return false\n end\n return true\nend", "def find_available_node\n node_name=nil\n nodes = JSON.parse http_get(@node_list_end_point)\n nodes[\"computer\"].each do |i|\n if i[\"offline\"]\n node_name=i[\"displayName\"]\n break\n end\n end\n\n return node_name\nend", "def index\n @node = Fedora.rest('rest/')\n end", "def search_for(host, options = T.unsafe(nil)); end", "def watch_nodes(opts = {})\n @conn.watch_nodes(opts)\n end", "def get_inflated_node_list\n Chef::Node.list(true)\n end", "def getmyhostname\n mydata = node['private-chef']['backends'].\n merge(node['private-chef']['frontends']).\n select { |k,v| k == node.name }.values.first\n mydata['hostname']\nend", "def find_by(type, filter, single = true, &block)\n nodes = []\n env = node.chef_environment\n if node.public_send(Inflections.pluralize(type.to_s)).include? filter\n nodes << node\n end\n if !single || nodes.empty?\n search(:node, \"#{type}:#{filter} AND chef_environment:#{env}\") do |n|\n nodes << n\n end\n end\n\n if block_given?\n nodes.each { |n| yield n }\n else\n single ? nodes.first : nodes\n end\n end", "def check_nodes(node)\n nodes = []\n all_nodes = get_consul_members\n if (node.downcase != \"all\")\n nodes << node if all_nodes.include? node\n else\n nodes = all_nodes\n end\n return nodes\n end", "def nodes\n get_chef_files_absolute_paths nodes_path\n end", "def nodes\n @conn.nodes\n end", "def chef_node\n return @chef_node unless @chef_node.nil?\n @chef_node = cluster.find_node(fullname) || false\n end", "def nodes_live?(host, port, ip_list, timeout_sec)\n params = {\n :action => \"CLUSTERSTATUS\"\n }\n sleep_time_sec = 10\n attempts = timeout_sec/sleep_time_sec\n all_nodes_live = false\n while attempts >= 0 do\n begin\n live_nodes = []\n Chef::Log.info(\"Getting live nodes. Remaining attempts : #{attempts}\")\n attempts = attempts - 1\n cluster_status_resp = solr_collection_api(host, port, params)\n cluster_live_nodes = cluster_status_resp[\"cluster\"][\"live_nodes\"]\n cluster_live_nodes.each do |live_node|\n ipaddress = live_node.split(\":\")[0]\n live_nodes.push ipaddress\n end\n Chef::Log.info(\"live_nodes = #{live_nodes}\")\n result = (ip_list-live_nodes)\n if result.empty?\n all_nodes_live = true\n break\n else\n Chef::Log.info(\"Nodes not live : #{result}\")\n end\n rescue => e\n Chef::Log.info(\"Error while getting live nodes : #{e.message}\")\n Chef::Log.info(\"Retry getting live nodes after #{sleep_time_sec} seconds\")\n sleep sleep_time_sec\n end\n end\n return all_nodes_live\n end", "def fetch_search_results(context)\n\n params = @params\n site_id = context['__site_id']\n\n matching_ids = Node.search_ids do\n\n # Site ID\n with :site_id, site_id\n\n # Node classification\n if params['classification']\n with :classification, params['classification']\n end\n\n # Parent\n if params['scope_to']\n parent_scope = context[params['scope_to']]\n with :parent_uri, parent_scope['uri']\n elsif params['parent_uri']\n with :parent_uri, params['parent_uri']\n end\n\n # Ordering\n order_by_fields = params['order_by'].blank? ? [] : params['order_by'].split(',')\n order_by_fields.each do |order_by_field|\n\n field_name, direction = order_by_field.gsub(/[\"']/, '').strip.split(' ', 2)\n direction = 'asc' if direction.blank?\n order_by field_name.to_sym, direction.to_sym\n\n end\n\n # Limit\n if params['limit']\n paginate :page => 1, :per_page => params['limit']\n end\n\n end\n\n results = []\n matching_ids.each do |id|\n\n node = Rails.cache.fetch \"node_id:#{site_id}:#{id}\" do\n Node.where(:site_id => site_id).find(id).to_liquid\n end\n results << node\n\n end\n\n results\n\n end", "def watch_nodes(opts = {})\n core_client.watch_nodes(opts)\n end", "def find_all_nodes(*args)\n raise NotImplementedError\n nodes = @database.all_nodes\n # TODO: design node finder syntax\n nodes\n end", "def scan_node(node, namespace, set_name, bin_names = nil, options = nil)\n scan_node_partitions(node, namespace, set_name, bin_names, options)\n end", "def find_all_nodes(*args)\n nodes = @nodes.find_all_nodes(*args)\n nodes.find_all { |n| context?(n) }\n end", "def nodes\n TestLab::Node.all\n end", "def nodes\n @cluster.nodes\n end", "def nodes()\n return SearchNodes.new(:node => self, :return_many => true)\n end", "def search_query(environment)\n items = [\"chef_environment:#{environment}\"]\n\n items += chef_attributes.collect do |key, value|\n key = key.gsub(/\\./, \"_\")\n \"#{attribute_escape(key)}:#{value}\"\n end\n\n items += roles.collect { |role| \"run_list:#{solr_escape('role['+role+']')}\" }\n items += recipes.collect { |recipe| \"run_list:#{solr_escape('recipe['+recipe+']')}\" }\n\n items.join(' AND ')\n end", "def search(node, qry)\n node.search(qry)\n end", "def search(params = {})\n http.get(\"/nfse\", params: filter(params)) do |response|\n respond_with_collection(response)\n end\n end", "def get_node( node_id, pages=1 )\n items = []\n 1.upto( pages ).each do |item_page|\n response = Amazon::Ecs.item_search( nil, :browse_node => node_id, :search_index => 'Books', \n :response_group => 'Large,Reviews,Similarities', :item_page => item_page, \n :power => 'binding:paperback or hardcover', :sort => 'reviewrank' ) # salesrank also possible\n response.items.each do |item|\n items << parse_item( item )\n end\n end\n return items\n end", "def list_ks_fusion_vms(options)\n options['search'] = \"rhel|centos|oel\"\n list_fusion_vms(search_string)\n return\nend", "def node(id, params = {})\n get \"nodes/#{id}\", {query: params}\n end", "def aws_discovery_bootstrap\n Chef::Log.info(\"etcd_service[#{ new_resource.name }] Setting node_name to #{ node['ec2']['instance_id'] }\")\n new_resource.node_name(node['ec2']['instance_id'])\n new_resource.client_host(node['ec2']['local_hostname'])\n new_resource.peer_host(node['ec2']['local_hostname'])\n\n ## Set our own tags _before_ waiting for peers.\n tag_resource = aws_resource_tag(node['ec2']['instance_id'])\n tag_resource.tags new_resource.aws_tags\n tag_resource.run_action(:update)\n tag_resource.action(:nothing)\n\n aws_wait_for_peers\n end", "def osops_search(\n search_string, # recipe or role name\n one_or_all=:one,# return first node found or a list of nodes?\n # if set to :all a list will be returned\n # even if only one node is found.\n include_me=true,# include self in results\n order=[:role, :recipe], # if only one item is to be returned and\n # there are results from both the role\n # search and the recipe search, pick the\n # first item from the list specified here.%\n # must be :recipe or :role\n safe_deref=nil, # if nil, return node(s), else return\n # rcb_safe_deref(node,safe_deref)\n current_node=nil,\n options = {}\n )\n\n # Next refactor, move options to first/only param\n # Passing options from other methods to override search params\n options = {\n :search_string => search_string,\n :one_or_all => one_or_all,\n :include_me => include_me,\n :order => order,\n :safe_deref => safe_deref,\n :current_node => current_node\n }.merge(options)\n\n search_string = options[:search_string]\n one_or_all = options[:one_or_all]\n include_me = options[:include_me]\n order = options[:order]\n safe_deref = options[:safe_deref]\n current_node = options[:current_node]\n\n debug(\"Osops_search: search_string:#{search_string}, one_or_all:#{one_or_all},\"\\\n + \"include_me:#{include_me}, order:#{order}, safe_deref:#{safe_deref}\")\n results = {\n :recipe => [],\n :role => [],\n :tag => []\n }\n\n current_node ||= node\n\n for query_type in order\n if include_me and current_node[\"#{query_type}s\"].include? search_string\n debug(\"node #{current_node} contains #{query_type} #{search_string}, so adding node to results\")\n results[query_type] << current_node\n break if one_or_all == :one # skip expensive searches if unnecessary\n end\n\n search_string.gsub!(/::/, \"\\\\:\\\\:\")\n query = \"#{query_type}s:#{search_string} AND chef_environment:#{current_node.chef_environment}\"\n debug(\"osops_search query: #{query}\")\n result, _, _ = Chef::Search::Query.new.search(:node, query)\n results[query_type].push(*result)\n break if one_or_all == :one and results.values.map(&:length).reduce(:+).nonzero?\n end #end for\n\n #combine results into prioritised list\n return_list = order.map { |search_type| results[search_type] }.reduce(:+)\n\n #remove duplicates\n return_list.uniq!(&:name)\n\n #remove self if returned by search but include_me is false\n return_list.delete_if { |e| e.name == current_node.name } if not include_me\n\n if not safe_deref.nil?\n # result should be dereferenced, do that then remove nils.\n debug(\"applying deref #{safe_deref}\")\n return_list.map! { |nodeish| rcb_safe_deref(nodeish, safe_deref) }\n return_list.delete_if { |item| item.nil? }\n end\n\n debug(\"ospos_search return_list: #{return_list}\")\n\n if one_or_all == :one\n #return first item\n return_list.first\n else\n #return list (even if it only contains one item)\n return_list\n end\n end", "def query_by_ipaddress(ipaddress)\n query = {\"query\" => \"SELECT NodeName, NodeID FROM Orion.Nodes WHERE IPAddress=@ipaddr\", \"parameters\" => {\"ipaddr\" => \"#{ipaddress}\"}}\n do_http_request(@querypath, query)\n end", "def searches\n wrapping!(\n search(\n root_uri,\n data_raw.to_s.gsub('=>', ':')\n )\n )\n end", "def node_election(role, tag, chef_environment = nil)\n chef_environment = chef_environment || node.chef_environment\n master = search(:node, \"run_list:role\\\\[#{role}\\\\] AND \\\n chef_environment:#{chef_environment} AND \\\n tags:#{tag}\") || []\n if master.empty?\n nodes = search(:node, \"run_list:role\\\\[#{role}\\\\] AND \\\n chef_environment:#{chef_environment}\") || []\n nodes = nodes.sort_by { |node| node.name } unless nodes.empty?\n if nodes.empty? or node.name.eql?(nodes.first.name)\n node.tags << tag unless node.tags.include?(tag)\n node.save\n end\n\n if nodes.empty?\n return node\n end\n\n return nodes.first\n else\n return master.first\n end\nend", "def get_registered_nodes\n update_nodes\n @registered_nodes\n end", "def discover_items(node=nil)\n iq = connection.iq_stanza({'to'=>jid.to_s}, x('query', 'xmlns' => Namespaces::DiscoverItems))\n send_iq_stanza_fibered iq\n end", "def dispatch\n @nodes.each do |node|\n conn = begin\n Train.create('ssh', host: node, port: 22, user: 'Administrator@cerny.cc', key_files: '/var/opt/delivery/workspace/.ssh/id_rsa').connection\n rescue\n Train.create('ssh', host: node, port: 22, user: 'root', key_files: '/var/opt/delivery/workspace/.ssh/id_rsa').connection\n end\n result = conn.run_command(@command)\n (result.exit_status.eql?(0) ? @results['succeeded'] << node : @results['failed'] << node)\n puts result.stdout\n puts result.stderr\n # @results.stdout << result.stdout\n # @results.stderr << result.stderr\n conn.close\n end\n end", "def fetch_nodes(nodes, dns_cache)\n ret = []\n nodes.each_with_index do |item, index|\n ip, port = item\n host = dns_cache.fetch(ip) {\n |missing_ip|\n host = Resolv.getname(missing_ip)\n dns_cache[ip] = host\n host\n }\n name = \"#{host}:#{port}\"\n role = index == 0 ? 'master' : 'slave'\n node = {\n :host => host, :port => port,\n :name => name, :ip => ip,\n :role => role\n }\n ret << node\n end\n ret\n end", "def find_nodes(term, opts = {})\n data, _status_code, _headers = find_nodes_with_http_info(term, opts)\n return data\n end", "def get_node_id_by_name(name, keyname, secret)\n\tget_node_cmd = \"#{node[:zendserver][:zsmanage]} cluster-list-servers -N #{keyname} -K #{secret} -U http://#{node[:hostname]}:10081/ZendServer/\"\n\tp = shell_out(get_node_cmd)\n\tp.stdout.split(/\\n/).grep(/#{name}/)[0].split(/\\t/)[0]\nend", "def where(query)\n components = query.match(NODE_QUERY_SYNTAX)\n\n raise BadReferenceError, \"for reference: #{query}\" unless components\n search_node_components(components)\n end", "def update_nodes\n mongo_driver = Kymera::MongoDriver.new(address, port, database, 'nodes')\n @registered_nodes = mongo_driver.get_collection('nodes')\n end", "def nodes\n # Find the nodes that were down but are ready to be refreshed, or those\n # with stale connection information.\n needs_refresh, available = seeds.partition do |node|\n refreshable?(node)\n end\n\n # Refresh those nodes.\n available.concat(refresh(needs_refresh))\n\n # Now return all the nodes that are available and participating in the\n # replica set.\n available.reject{ |node| node.down? }\n end", "def node\n @node ||=\n begin\n node = Chef::Node.new(chef_server_rest: client_rest)\n node.name(node_name)\n node.run_list(normalized_run_list)\n node.normal_attrs = first_boot_attributes if first_boot_attributes\n node.environment(environment) if environment\n node.policy_name = policy_name if policy_name\n node.policy_group = policy_group if policy_group\n (config[:tags] || []).each do |tag|\n node.tags << tag\n end\n node\n end\n end", "def physical_servers_inside_rack(rack)\n rack.nodeList.map { |node| node[\"itemInventory\"] }\n end", "def cluster() node[:cluster_name] ; end", "def search_node(ip)\n found = nil\n @known_nodes.each do |node|\n if node.is_you? ip\n found = node\n end\n end\n return found\n end", "def list_all_shards(args = {}) \n get(\"/shards.json/\", args)\nend", "def node\n Chef.run_context.node\n end", "def get_true_node_objects get_all_nodes=false\r\n nodes, all_nodes, names, iter_arr, file_cache_nodes, h = [],[],[],[],[],{}\r\n\r\n @config['chef_nodes'] = @config['ridley'].node.all\r\n\r\n @config['helper'].completion_rate? 0, __method__\r\n\r\n file_cache_nodes = @config['filesystem'].check_nodes_file_cache if @config['filesystem'].compare_file_node_cache_against_chef_nodes('equal')\r\n\r\n @config['chef_nodes'].each do |n|\r\n true_obj = if !file_cache_nodes.empty? && @config['parser'].array_of_nodes_contains_node_name?(file_cache_nodes, n.name)\r\n file_cache_nodes[@config['parser'].index_of_node_name_in_array_of_nodes(file_cache_nodes, n.name)]\r\n else\r\n @config['filesystem'].cleanup_file_caches('current-nodes')\r\n\r\n @config['ridley'].node.find(n.name)\r\n end\r\n\r\n iter_arr << n.name\r\n\r\n progress_value = (( iter_arr.length.to_f/@config['chef_nodes'].length.to_f )*100 ).floor\r\n\r\n @config['helper'].completion_rate? progress_value, __method__\r\n\r\n all_nodes << true_obj\r\n\r\n next if !get_all_nodes && true_obj.chef_environment != @options['env'] && true_obj.chef_environment != '_default'\r\n\r\n if get_all_nodes\r\n h[n.name] = true_obj\r\n names << n.name\r\n\r\n next\r\n end\r\n\r\n if @options['role'] == 'all'\r\n next if true_obj.chef_environment == '_default'\r\n\r\n h[n.name] = true_obj\r\n names << n.name\r\n\r\n next\r\n end\r\n\r\n if @options['node_name'] && true_obj.name == @options['node_name']\r\n h[n.name] = true_obj\r\n names << n.name\r\n\r\n next\r\n end\r\n\r\n if @options['address'] && true_obj.public_ipaddress == @options['address']\r\n h[n.name] = true_obj\r\n names << n.name\r\n\r\n next\r\n end\r\n\r\n unless ( @options['address'] || @options['node_name'] )\r\n if true_obj.run_list.include?(\"role[#{ @options['role'] }]\")\r\n h[n.name] = true_obj\r\n names << n.name\r\n\r\n next #not needed here but good to keep in mind\r\n end\r\n end\r\n end\r\n\r\n names.sort.each { |name| nodes << h[name] }\r\n\r\n @config['filesystem'].write_nodes_file_cache(all_nodes) unless @config['filesystem'].compare_file_node_cache_against_chef_nodes('equal')\r\n\r\n puts(\"\") unless @options['quiet']\r\n \r\n nodes\r\n end", "def find_available_hosts(folder, datastore)\n hosts = find_compute_resources(folder)\n hosts.select! { |host| host.datastore.include?(datastore) }\n hosts\nend", "def search_node_in_roles( roles )\n roles.each do |r|\n Chef::Log.info \"Searching for '#{self[:fqdn]}' in the '#{r}' role.\"\n if self.role?(r)\n # return true for the first match\n Chef::Log.info \"Whitelisting: Found node '#{self[:fqdn]}' via role '#{r}'.\"\n return true\n end\n end\n\n return false\n\n end", "def index\n Chef.all\n end", "def get_node_details(name_list)\n rpc_get_facts_direct(name_list)\n end", "def fetch_databag_tenants\n db_tenants = Array.new\n chef_api_connect.search.query(:foundation, '*:*', start: 0).rows.each do |tenant|\n db_tenants << tenant['raw_data']['id']\n end\n return db_tenants\nend", "def get_solrcloud_instances_by_action(node, action)\n if !node['workorder']['payLoad'].has_key?(\"SolrClouds\")\n puts \"***FAULT:FATAL=SolrClouds payload not found, you must pull the design.\"\n e = Exception.new(\"no backtrace\")\n e.set_backtrace(\"\")\n raise e \n end\n solr_clouds = node['workorder']['payLoad']['SolrClouds']\n Chef::Log.info(\"Total solrcloud instances in the payload : #{solr_clouds.size()}\")\n solr_clouds_actioned = solr_clouds.select { |solr_cloud| solr_cloud['rfcAction'] != nil && solr_cloud['rfcAction'].eql?(action) }\n Chef::Log.info(\"Total solrcloud instances with action #{action} in the deployment : #{solr_clouds_actioned.size()}\")\n return solr_clouds_actioned\n end", "def find_node(nd_name)\n chef_nodes.find{|nd| nd.name == nd_name }\n end", "def find_optional_node_by_criteria(stack, include_criteria=nil, exclude_criteria=nil)\n search_query = \"stack:#{stack}\"\n search_query = \"#{search_query} AND #{include_criteria}\" if include_criteria\n search_query = \"#{search_query} AND NOT name:#{node.name}\" unless exclude_criteria\n search_query = \"#{search_query} AND NOT (name:#{node.name} OR #{exclude_criteria})\" if exclude_criteria\n\n Chef::Log.debug \"find_optional_node_by_criteria(#{stack}, #{include_criteria}, #{exclude_criteria}) => search query: '#{search_query}'\"\n\n nodes = search(:node, \"#{search_query}\")\n nodes.flatten!\n\n # Warn if no node has been found in the stack\n Chef::Log.warn \"The search query '#{search_query}' returned 0 results.\" if nodes.size == 0\n # Fail if mutiple nodes have been found in the stack\n raise \"Multiple machines that match the search query '#{search_query}' were found in the #{stack} environment... This is not allowed. Cleanup of nodes may be necessary.\" if nodes.size > 1\n return nodes[0]\nend", "def get_node_info(treenodeid, _show_list = true)\n @nodetype, id = parse_nodetype_and_id(valid_active_node(treenodeid))\n # resetting action that was stored during edit to determine what is being edited\n @sb[:action] = nil\n\n # Reset session to same values as first time in\n session[:adv_search][\"Service\"] = session[:edit] = nil if session[:adv_search] && params[:action] != 'x_search_by_name'\n\n case TreeBuilder.get_model_for_prefix(@nodetype)\n when \"Service\"\n show_record(id)\n drop_breadcrumb(:name => _('Services'), :url => '/service/explorer') if @breadcrumbs.empty?\n @right_cell_text = _(\"Service \\\"%{name}\\\"\") % {:name => @record.name}\n @no_checkboxes = true\n @gtl_type = \"grid\"\n @items_per_page = ONE_MILLION\n @view, @pages = get_view(Vm, :parent => @record, :parent_method => :all_vms, :all_pages => true) # Get the records (into a view) and the paginator\n when \"Hash\"\n case id\n when 'asrv'\n process_show_list(:named_scope => [[:retired, false], :displayed])\n @right_cell_text = _(\"Active Services\")\n when 'rsrv'\n process_show_list(:named_scope => %i[retired displayed])\n @right_cell_text = _(\"Retired Services\")\n end\n when \"MiqSearch\", nil # nil if applying a filter from Advanced search - and @nodetype is root\n load_adv_search unless @nodetype == \"root\" # Select/load filter from Global/My Filters\n process_show_list\n @right_cell_text = _(\"All Services\")\n end\n @right_cell_text += _(\" (Names with \\\"%{search_text}\\\")\") % {:search_text => @search_text} if @search_text.present? && @nodetype != 's'\n @right_cell_text += @edit[:adv_search_applied][:text] if x_tree && @edit && @edit[:adv_search_applied]\n end", "def get_node( node_id, pages=2 )\n items = []\n 1.upto( pages ).each do |item_page|\n response = Amazon::Ecs.item_search( nil, :browse_node => node_id, :search_index => 'Books', \n :response_group => 'Large,Reviews,Similarities,AlternateVersions', :item_page => item_page, \n :power => 'binding:paperback or hardcover', :sort => 'salesrank' ) # salesrank also possible\n response.items.each do |item|\n items << Book.new( item )\n end\n end\n return items\n end", "def get_nodes_by_role(role, includeme=true, options={})\n options = {\n :search_string => role,\n :include_me => includeme,\n :order => [:role],\n :safe_deref => nil,\n :current_node => nil,\n :one_or_all => :all\n }.merge(options)\n opsit_search(options)\n end", "def get_node(node_name)\n Chef::Config.from_file(\"/etc/chef/client.rb\")\n Chef::Config[:client_key] = \"/etc/chef/client.pem\"\n Chef::Config[:http_retry_count] = 5\n node = Chef::Node.load(node_name)\n end" ]
[ "0.72092086", "0.6907744", "0.6647727", "0.65987945", "0.6517916", "0.64821213", "0.63215536", "0.6308564", "0.62858826", "0.6210898", "0.6196186", "0.6189882", "0.61747134", "0.6170602", "0.61280453", "0.60679644", "0.6048448", "0.60415477", "0.5994073", "0.59644383", "0.5953688", "0.59449816", "0.59326553", "0.5928031", "0.5894995", "0.58810145", "0.58795935", "0.5876981", "0.58566755", "0.5849483", "0.5837743", "0.58342016", "0.5828727", "0.5807053", "0.5794991", "0.57924414", "0.5787789", "0.57816356", "0.57417184", "0.5729195", "0.5720726", "0.57185227", "0.57175946", "0.5708411", "0.5654569", "0.5641671", "0.56405646", "0.56346524", "0.5620326", "0.55950475", "0.5587385", "0.558073", "0.5567018", "0.55583346", "0.55227184", "0.5506182", "0.5496508", "0.5486039", "0.54826736", "0.545804", "0.54380083", "0.54324496", "0.54323775", "0.5417128", "0.5381737", "0.53768575", "0.5372404", "0.53716975", "0.53658766", "0.5360352", "0.5356872", "0.53526074", "0.53472364", "0.5344009", "0.53420484", "0.5338013", "0.5337503", "0.5323412", "0.5311556", "0.5310829", "0.53097504", "0.5306144", "0.5303453", "0.5290164", "0.5281501", "0.5279815", "0.52792585", "0.527704", "0.5264858", "0.5243127", "0.5239024", "0.52288854", "0.5227781", "0.52215797", "0.5215176", "0.5209281", "0.5200312", "0.51993436", "0.51987904", "0.51920223" ]
0.5939358
22
Interface dependency using Chef for searching by default
def chef_query_class @chef_query_class ||= ::Chef::Search::Query end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def chef_api_client\n @chef_api_client ||= begin\n require \"chef/api_client\"\n Chef::ApiClient\n end\n end", "def load_cloudflare_cookbook_gems\n return if defined? @@cloudflare_cookbook_gems_loaded\n chef_gem 'cloudflare' do\n action :install\n version '2.0.1'\n end\n require 'resolv'\n require 'cloudflare'\n @@cloudflare_cookbook_gems_loaded = true\nend", "def dependencies; end", "def dependencies; end", "def dependencies; end", "def find_packages(name, constraint = nil)\n # implement inside child\n end", "def cask(name); dep name, :template => \"icelab:cask\"; end", "def chef_client(host, options = {})\n raise RuntimeError, \"abstract function: must be implemented on includer\"\n end", "def find(dependency)\n @dependencies[cookbook_name(dependency).to_s]\n end", "def ReadHelper\n ret = Pkg.TargetInit(\"/\", false)\n # Pkg::TargetInitialize (\"/\");\n Pkg.TargetLoad\n Pkg.SourceStartManager(true)\n Pkg.PkgSolve(false)\n\n @inst = Pkg.GetPackages(:installed, true)\n all_patterns = Pkg.ResolvableProperties(\"\", :pattern, \"\")\n @all_xpatterns = Pkg.ResolvableDependencies(\"\", :pattern, \"\")\n patterns = []\n visible_patterns = []\n\n patternsFullData = Builtins.filter(all_patterns) do |p|\n ret2 = false\n if Ops.get_symbol(p, \"status\", :none) == :installed &&\n !Builtins.contains(patterns, Ops.get_string(p, \"name\", \"no name\"))\n patterns = Builtins.add(\n patterns,\n Ops.get_string(p, \"name\", \"no name\")\n )\n ret2 = true\n if Ops.get_boolean(p, \"user_visible\", true) == true\n visible_patterns = Builtins.add(\n visible_patterns,\n Ops.get_string(p, \"name\", \"no name\")\n )\n end\n end\n ret2\n end\n Pkg.TargetFinish\n\n tmproot = AutoinstConfig.tmpDir\n SCR.Execute(path(\".target.mkdir\"), Ops.add(tmproot, \"/rootclone\"))\n Pkg.TargetInit(Ops.add(tmproot, \"/rootclone\"), true)\n Builtins.y2debug(\"SourceStartCache: %1\", Pkg.SourceStartCache(false))\n\n Pkg.SourceStartManager(true)\n\n userpackages = Pkg.FilterPackages(false, false, true, true)\n Pkg.TargetFinish\n # Remove kernel packages\n removepackages = []\n\n patternPackages = []\n new_p = []\n Builtins.foreach(patterns) do |tmp_pattern|\n xpattern = Builtins.filter(@all_xpatterns) do |p|\n Ops.get_string(p, \"name\", \"\") == tmp_pattern\n end\n found = Ops.get(xpattern, 0, {})\n req = false\n # kick out hollow patterns (always fullfilled patterns)\n Builtins.foreach(Ops.get_list(found, \"dependencies\", [])) do |d|\n if Ops.get_string(d, \"res_kind\", \"\") == \"package\" &&\n (Ops.get_string(d, \"dep_kind\", \"\") == \"requires\" ||\n Ops.get_string(d, \"dep_kind\", \"\") == \"recommends\")\n patternPackages = Builtins.add(\n patternPackages,\n Ops.get_string(d, \"name\", \"\")\n )\n req = true\n end\n end\n # workaround for our pattern design\n # a pattern with no requires at all is always fullfilled of course\n # you can fullfill the games pattern with no games installed at all\n new_p = Builtins.add(new_p, tmp_pattern) if req == true\n end\n patterns = deep_copy(new_p)\n\n patternPackagesTemp = deep_copy(patternPackages)\n run = false\n emergency_break = 0\n begin\n run = false\n emergency_break = Ops.add(emergency_break, 1)\n # remove all packages that are pulled in by the resolver anyway\n tmp = []\n patternPackagesTemp = Builtins.toset(patternPackagesTemp)\n Builtins.foreach(patternPackagesTemp) do |ppackage|\n Builtins.foreach(Pkg.ResolvableDependencies(ppackage, :package, \"\")) do |d|\n Builtins.foreach(Ops.get_list(d, \"dependencies\", [])) do |dd|\n if Ops.get_string(dd, \"res_kind\", \"\") == \"package\" &&\n (Ops.get_string(dd, \"dep_kind\", \"\") == \"requires\" ||\n Ops.get_string(dd, \"dep_kind\", \"\") == \"recommends\") &&\n !Builtins.contains(\n patternPackages,\n Ops.get_string(dd, \"name\", \"\")\n )\n patternPackages = Builtins.add(\n patternPackages,\n Ops.get_string(dd, \"name\", \"\")\n )\n tmp = Builtins.add(tmp, Ops.get_string(dd, \"name\", \"\"))\n run = true\n end\n end\n end\n end\n patternPackagesTemp = deep_copy(tmp)\n Builtins.y2milestone(\"temp package list = %1\", tmp)\n end while run == true && Ops.less_than(emergency_break, 20)\n\n software = {}\n if Ops.greater_than(Builtins.size(patterns), 0)\n Builtins.foreach(@inst) do |p|\n if !Builtins.contains(patternPackages, p)\n userpackages = Builtins.add(userpackages, p)\n end\n end\n Builtins.foreach(patternPackages) do |p|\n if !Builtins.contains(@inst, p)\n removepackages = Builtins.add(removepackages, p)\n end\n end\n end\n\n Ops.set(\n software,\n \"packages\",\n Builtins.sort(Builtins.filter(userpackages) do |pkg|\n !Builtins.regexpmatch(pkg, \"kernel-.*\") || pkg == \"kernel-uml\"\n end)\n )\n Ops.set(software, \"patterns\", Builtins.sort(visible_patterns))\n Ops.set(software, \"remove-packages\", Builtins.toset(removepackages))\n deep_copy(software)\n end", "def configure_ai_pkg_repo(options,read_only)\n service_base_name = get_ai_service_base_name(options)\n if options['host-os-name'].to_s.match(/SunOS/)\n smf_name = \"pkg/server:#{service_base_name}\"\n message = \"Information:\\tChecking if service \"+smf_name+\" exists\"\n if options['service'].to_s.match(/alt/)\n command = \"svcs -a |grep '#{smf_name}\"\n else\n command = \"svcs -a |grep '#{smf_name} |grep -v alt\"\n end\n output = execute_command(options,message,command)\n if not output.match(/#{smf_name}/)\n message = \"\"\n commands = []\n commands.push(\"svccfg -s pkg/server add #{options['service']}\")\n commands.push(\"svccfg -s #{smf_name} addpg pkg application\")\n commands.push(\"svccfg -s #{smf_name} setprop pkg/port=#{options['publisherport']}\")\n commands.push(\"svccfg -s #{smf_name} setprop pkg/inst_root=#{options['repodir']}\")\n commands.push(\"svccfg -s #{smf_name} addpg general framework\")\n commands.push(\"svccfg -s #{smf_name} addpropvalue general/complete astring: #{options['service']}\")\n commands.push(\"svccfg -s #{smf_name} setprop pkg/readonly=#{read_only}\")\n commands.push(\"svccfg -s #{smf_name} setprop pkg/proxy_base = astring: http://#{options['publisherhost']}/#{options['service']}\")\n commands.push(\"svccfg -s #{smf_name} addpropvalue general/enabled boolean: true\")\n commands.each do |temp_command|\n execute_command(options,message,temp_command)\n end\n refresh_smf_service(options,smf_name)\n add_apache_proxy(options,service_base_name)\n end\n end\n return\nend", "def install\n # Switch this to use Module#prepend at some point when I stop caring about Ruby 1.9.\n ::Berkshelf::Berksfile.class_exec do\n old_sources = instance_method(:sources)\n define_method(:sources) do\n original_sources = begin\n old_sources.bind(self).call\n rescue ::Berkshelf::NoAPISourcesDefined\n # We don't care, there will be a source\n []\n end\n # Make sure we never add two halite sources.\n original_sources.reject {|s| s.is_a?(::Halite::Berkshelf::Source) } + [::Halite::Berkshelf::Source.new(self)]\n end\n end\n\n # Inject support for the :halite location type\n ::Berkshelf::Downloader.class_exec do\n old_try_download = instance_method(:try_download)\n define_method(:try_download) do |source, name, version|\n remote_cookbook = source.cookbook(name, version)\n if remote_cookbook && remote_cookbook.location_type == :halite\n tmp_dir = Dir.mktmpdir\n Halite.convert(remote_cookbook.location_path, tmp_dir)\n tmp_dir\n else\n old_try_download.bind(self).call(source, name, version)\n end\n end\n end\n\n end", "def fetch_dependencies()\n\t\"berks vendor cookbooks #{(@debug ? '-v' : '-q')}\"\n end", "def install_repo!\n package 'apt-transport-https'\n include_recipe \"apt-chef::#{new_resource.channel}\"\n package 'chefdk' do\n version new_resource.version unless new_resource.version == 'latest'\n end\n end", "def install_dependencies\n recipe_eval do\n run_context.include_recipe 'chef-sugar::default'\n run_context.include_recipe 'build-essential::default'\n\n case node.platform_family\n when 'debian'\n package 'curl'\n package 'git-core'\n package 'libxml2-dev'\n package 'libxslt-dev'\n package 'zlib1g-dev'\n package 'ncurses-dev'\n package 'libssl-dev'\n when 'freebsd'\n package 'textproc/libxml2'\n package 'textproc/libxslt'\n package 'devel/ncurses'\n when 'mac_os_x'\n run_context.include_recipe 'homebrew::default'\n package 'libxml2'\n package 'libxslt'\n package 'openssl'\n when 'rhel'\n package 'curl'\n package 'bzip2'\n package 'file'\n package 'git'\n package 'libxml2-devel'\n package 'libxslt-devel'\n package 'ncurses-devel'\n package 'zlib-devel'\n package 'openssl-devel'\n end\n end\n end", "def direct_dependencies; end", "def lookup_executable(args)\n executable = args[:executable]\n matches = packages_providing(\"*#{executable}\").join(\"\\n\")\n puts \"packages which provide executable:\\n#{matches}\".bold.blue\nend", "def find_package(name, constraint)\n # implement inside child\n end", "def require_gems; end", "def cookbook\n require 'halite/gem'\n @cookbook ||= Halite::Gem.new(gemspec)\n end", "def load_interface(interface)\n # This require will only run once. If we repeat it, it is not\n # loaded again\n require \"virtualbox/com/interface/#{@__version}/#{interface}\"\n\n # Find the module based on the version and name and return it\n Object.module_eval(\"::VirtualBox::COM::Interface::#{version_const}::#{interface}\")\n end", "def initialize(name, run_context = nil)\n super\n @provider = Chef::Provider::Package::Rubygems\n end", "def expand_dependency(dependency, parent)\n\t\t\t\t# The job of this function is to take a dependency and turn it into 0 or more provisions. The dependency could be a normal fully-qualified name or a wildcard. It's not clear at which point pattern matching should affect dependency resolution, but it seems logical since it depends on the available provisions that it's done here.\n\t\t\t\t# Another benefit is that it introduces a fixed point of reference for expanding dependencies. When the resolver invokes this method, it can be assured that it will return the same result.\n\t\t\t\tif dependency.wildcard?\n\t\t\t\t\treturn expand_wildcard(dependency, parent)\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# Mostly, only one package will satisfy the dependency...\n\t\t\t\tviable_providers = @providers.select{|provider| provider.provides? dependency}\n\t\t\t\t\n\t\t\t\t# puts \"** Found #{viable_providers.collect(&:name).join(', ')} viable providers.\"\n\t\t\t\t\n\t\t\t\tif viable_providers.size == 1\n\t\t\t\t\tprovider = viable_providers.first\n\t\t\t\t\tprovision = provision_for(provider, dependency)\n\t\t\t\t\t\n\t\t\t\t\t# The best outcome, a specific provider was named:\n\t\t\t\t\treturn [provision]\n\t\t\t\telsif viable_providers.size > 1\n\t\t\t\t\t# ... however in some cases (typically where aliases are being used) an explicit selection must be made for the build to work correctly.\n\t\t\t\t\texplicit_providers = filter_by_selection(viable_providers)\n\t\t\t\t\t\n\t\t\t\t\t# puts \"** Filtering to #{explicit_providers.collect(&:name).join(', ')} explicit providers.\"\n\t\t\t\t\t\n\t\t\t\t\tif explicit_providers.size != 1\n\t\t\t\t\t\t# If we were unable to select a single package, we may use the priority to limit the number of possible options:\n\t\t\t\t\t\texplicit_providers = viable_providers if explicit_providers.empty?\n\t\t\t\t\t\t\n\t\t\t\t\t\texplicit_providers = filter_by_priority(explicit_providers)\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\tif explicit_providers.size == 0\n\t\t\t\t\t\t# No provider was explicitly specified, thus we require explicit conflict resolution:\n\t\t\t\t\t\t@conflicts[dependency] = viable_providers\n\t\t\t\t\telsif explicit_providers.size == 1\n\t\t\t\t\t\tprovider = explicit_providers.first\n\t\t\t\t\t\tprovision = provision_for(provider, dependency)\n\t\t\t\t\t\t\n\t\t\t\t\t\t# The best outcome, a specific provider was named:\n\t\t\t\t\t\treturn [provision]\n\t\t\t\t\telse\n\t\t\t\t\t\t# Multiple providers were explicitly mentioned that satisfy the dependency.\n\t\t\t\t\t\t@conflicts[dependency] = explicit_providers\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\treturn []\n\t\t\tend", "def included_interfaces; end", "def find_modules\n find_engine\n find_storage\n find_pod\n end", "def load_current_resource\n @current_resource = Chef::Resource::NexusCapability.new(new_resource.name)\n\n run_context.include_recipe \"nexus::cli\"\n Chef::Nexus.ensure_nexus_available(node)\n\n @current_resource\nend", "def depend(location, type, *args)\n if type == :gemfile\n registry = GemInstaller::Registry.new\n config_builder = registry.config_builder\n path = args.pop\n config_builder.config_file_paths = path\n config = config_builder.build_config\n gems = config.gems\n \n gems.each do |agem|\n # gem() function defined in Capistrano's RemoteDependency class\n options = pluck_accessor_hash(agem, [:platform, :install_options, :check_for_upgrade, :no_autogem, :fix_dependencies])\n depend_without_gemfile(location, :gem, agem.name, agem.version, options)\n end\n else\n depend_without_gemfile(location, type, *args)\n end\n end", "def discovery\n resource ''\n end", "def common_pods\n pod \"Regift\"\nend", "def install_dependencies\n raise 'Not implemented'\n end", "def enable_dependency_loading=(_arg0); end", "def enable_dependency_loading=(_arg0); end", "def franchise( name )\n require \"capistrano/fastfood/franchises/#{name}\"\n end", "def recipes\n ['runit', proc {\n begin\n if node['virtualization'] && %w{docker lxc}.include?(node['virtualization']['system'])\n resources('service[runsvdir-start]').action(:nothing)\n end\n rescue Chef::Exceptions::ResourceNotFound\n end\n }]\n end", "def get_helper(node)\n Chef::RemoteRecipe.factory(node)\n end", "def conscientious_require; end", "def discover_chef_clients!\n servers.each(&:chef_client)\n end", "def lookup_library(args)\n library = args[:library]\n paths = args.key?(:paths) ? sanitize_paths(args[:paths]) : []\n matches = packages_providing_library(library, *paths).join(\"\\n\")\n puts \"packages which provide library:\\n#{matches}\".bold.blue\nend", "def packages_providing(component)\n matches = []\n `yum provides #{component}`.each_line { |l|\n matches << $1 if l =~ /(.*)\\.fc.*/\n }\n matches\nend", "def service_provider\n base_class = if defined?(Chef::Provider::RunitService)\n Chef::Provider::RunitService\n elsif defined?(Chef::Provider::Service::Runit)\n Chef::Provider::Service::Runit\n else\n raise PoiseService::Error.new('Unable to find runit_service provider class.')\n end\n Class.new(base_class) do\n # Lie about the name.\n def self.name\n superclass.name\n end\n\n def inside_docker?\n # We account for docker already so just lock it to false.\n false\n end\n end\n end", "def service_require\n ruby_file_path @api, service_name_full\n end", "def pleaserun_setup\n chef_gem 'pleaserun' do\n compile_time true\n version '>= 0.0.30'\n end\n\n require 'pleaserun/namespace'\n require 'pleaserun/platform/base'\n\n target_platform = platform\n target_platform_version = platform_version || target_version\n\n if target_platform.nil? || target_platform.empty?\n require 'pleaserun/detector'\n if target_platform_version.nil?\n target_platform, target_platform_version = PleaseRun::Detector.detect\n else\n target_platform = PleaseRun::Detector.detect\n end\n Chef::Log.info \"[dropwizard_pleaserun] autodetected #{target_platform} \" \\\n \"/ #{target_platform_version}\"\n end\n\n Chef::Log.info \"[dropwizard_pleaserun] platform: #{target_platform} / \" \\\n \"version: #{target_platform_version}\"\n\n require \"pleaserun/platform/#{target_platform}\"\n platform_klass = load_platform(target_platform)\n\n pr = platform_klass.new(target_platform_version.to_s)\n pr.name = app_name\n pr.user = user unless user.nil?\n pr.group = group unless group.nil?\n pr.description = description unless description.nil?\n pr.umask = umask unless umask.nil?\n pr.runas = runas unless runas.nil?\n pr.chroot = chroot unless chroot.nil?\n pr.chdir = chdir unless chdir.nil?\n pr.nice = nice unless nice.nil?\n pr.prestart = prestart unless prestart.nil?\n pr.program = program\n pr.args = args unless args.empty?\n pr.log_directory = log_directory unless log_directory.nil?\n\n pr\nend", "def install_ruby_dependencies(rubie)\n pkgs = []\n case rubie\n when /^ruby-/, /^ree-/, /^rbx-/, /^kiji/\n case node['platform']\n when \"debian\",\"ubuntu\"\n pkgs = %w{ build-essential openssl libreadline6 libreadline6-dev\n zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev\n sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev\n ncurses-dev automake libtool bison ssl-cert }\n pkgs += %w{ subversion } if rubie =~ /^ruby-head$/\n when \"suse\"\n pkgs = %w{ gcc-c++ patch zlib zlib-devel libffi-devel\n sqlite3-devel libxml2-devel libxslt-devel }\n if node['platform_version'].to_f >= 11.0\n pkgs += %w{ libreadline5 readline-devel libopenssl-devel }\n else\n pkgs += %w{ readline readline-devel openssl-devel }\n end\n pkgs += %w{ git subversion autoconf } if rubie =~ /^ruby-head$/\n when \"centos\",\"redhat\",\"fedora\",\"scientific\",\"amazon\"\n pkgs = %w{ gcc-c++ patch readline readline-devel zlib zlib-devel\n libyaml-devel libffi-devel openssl-devel }\n pkgs += %w{ git subversion autoconf } if rubie =~ /^ruby-head$/\n end\n when /^jruby-/\n # TODO: need to figure out how to pull in java recipe only when needed. For\n # now, users of jruby will have to add the \"java\" recipe to their run_list.\n #include_recipe \"java\"\n case node['platform']\n when \"debian\",\"ubuntu\"\n pkgs += %w{ g++ ant }\n end\n end\n\n pkgs.each do |pkg|\n package pkg do\n action :nothing\n end.run_action(:install)\n end\nend", "def find(interface, rs_or_rq = RS)\r\n # if the interface is not specified, return false\r\n if !interface then\r\n return nil\r\n end\r\n # check the existence of the base_dir\r\n if !FileTest.directory?(base_dir) then\r\n return nil\r\n end\r\n # scan the response file in the directory\r\n dir_list = [base_dir]\r\n until dir_list.empty?\r\n # get the dir from the list\r\n current_dir = dir_list.shift\r\n current_dir << \"/\" unless current_dir[-1].chr == \"/\"\r\n # begin to traversa this dir, if find, reuslt will be the path, otherwise nil\r\n result = Dir.foreach(current_dir) do |child|\r\n # exclude the ., .., svn, web-inf\r\n next if child == \".\" || child == \"..\" || child.include?(\"\\.svn\") || child.include?(\"WEB-INF\")\r\n # form the path\r\n @status_bar.set_status_text(child_path = current_dir + child)\r\n \r\n if FileTest.directory?(child_path) then\r\n dir_list.push(child_path)\r\n next\r\n end\r\n \r\n if FileTest.file?(child_path) && child_path.downcase.include?(interface.downcase) && child_path.include?(rs_or_rq) then\r\n break child_path\r\n else\r next\r\n end\r\n end\r\n # if find break the loop\r\n break result if result\r\n end\r\n end", "def knife(sub_cmd)\n chef_exec(knife_cmd(sub_cmd))\nend", "def knife\n @knife ||= begin\n lf = create_log_file\n Chef::Knife::Bootstrap.load_deps\n kb = Chef::Knife::Bootstrap.new\n kb.ui = Chef::Knife::UI.new(lf, lf, lf, {verbosity: 2})\n kb\n end\n end", "def deployable_services\n # This info is taken by listing existing bash scripts\n Dir.glob(\"#{repository_path}/install-*.bash\").map { |file| File.basename(file).match(/install-(.*)\\.bash/)[1] }\n end", "def load_chef_fetcher\n Chef::Log.debug \"Load Chef Server fetcher from: #{cookbook_vendor_path}\"\n $LOAD_PATH.unshift(cookbook_vendor_path)\n require 'chef-server/fetcher'\n end", "def interface; end", "def interface; end", "def db_drivers_install\n include_recipe('python::pip')\n case db_uri.scheme\n when 'mysql'\n python_pip \"#{new_resource.name} :install mysql-python\" do\n package_name 'mysql-python'\n virtualenv \"#{home}/.venv\"\n action :install\n end\n end\n end", "def run\n\n # Grab all the config params from command line, knife.rb etc\n self.config = Chef::Config.merge!(config)\n\n # Check if we have a knife.rb\n puts \"Check location of knife.rb\"\n checkfiles(:config_file,\"The config file (knife.rb) should be stored in a .chef folder here or higher (towards root)\")\n if config[:config_file].nil?\n exit 1\n else\n # We shouldn't reach this point but lets make sure we die if we somehow do.\n unless ::File.exists?(File.expand_path(config[:config_file]))\n exit 1\n end\n end\n \n puts \"Check chef basics\"\n checkparm(:chef_server_url,'chef_server_url should be set to point to your chef server (https://<server.name>/organizations/<orgname>)')\n checkfiles(:cookbook_path,\"cookbook_path should point to a valid directory\")\n\n puts \"Check author and copyright info\"\n checkparm(:cookbook_copyright,\"cookbook_copyright should be set to your company name\")\n checkparm(:cookbook_email,\"cookbook_email should be set to your eMail address\")\n\n\n puts \"Check keys exist\"\n checkfiles(:client_key,\"This file is used for authenticating to Chef server and is normally saved in .chef as client.pem\")\n checkfiles(:validation_key,\"This file is used for bootstraping new nodes and is stored in .chef as validator.pem\")\n checkparm(:validation_client_name,\"validation_client_name is normally set to <orgname>-validator\")\n\n puts \"Check proxy configuration\"\n checkparm(:http_proxy,\"http_proxy should be set to a valid proxy like http://myproxy.ge.com:3128\")\n checkparm(:https_proxy,\"https_proxy should be set to a valid proxy like http://myproxy.ge.com:3128\")\n checkparm(:bootstrap_proxy,\"bootstrap_proxy should be set to a valid proxy like http://myproxy.ge.com:3128\")\n checkparm(:no_proxy,\"no_proxy should be set to exclude certain domains like *.ge.com from being proxied. Dont add wildcard subnets like 3.*\")\n\n puts \"Check GIT/Gerrit\"\n checkparm(:reviewhost,\"reviewhost should be set to the FQDN of your Gerrit server (leave out the http:// and the port number)\")\n\n # Check if GIT has a default username configured\n result=`git config --get user.name`.chomp\n if result.length < 1\n puts ui.color(\" the git user.name is not set. Add it using:-\", :red)\n puts ui.color(\" git config --global user.name <username>\", :magenta)\n else\n puts ui.color(\" the git user.name is set to #{result}\", :green)\n end\n\n # Check if GIT has a default email address configured\n result=`git config --get user.email`.chomp\n if result.length < 1\n puts ui.color(\" the git user.email is not set. Add it using:-\", :red)\n puts ui.color(\" git config --global user.email <email address>\", :magenta)\n else\n puts ui.color(\" the git user.email is set to #{result}\", :green)\n end\n\n # Check if the git core.autocrlf is set correctly (different on Windows and OSX... TODO: Check on Linux)\n result=`git config --get core.autocrlf`.chomp\n case result\n when 'input'\n if (RUBY_PLATFORM =~ /.*darwin.*/) or (RUBY_PLATFORM =~ /.*linux.*/)\n puts ui.color(\" the git core.autocrlf is set to 'input' which is correct for OSX or Linux systems\", :green)\n end\n if (RUBY_PLATFORM =~ /.*mingw.*/) or (RUBY_PLATFORM =~ /.*cygwin.*/)\n puts ui.color(\" the git core.autocrlf is set to 'input' but Windows/Linux should use 'true' to prevent line ending problems\", :red)\n end\n\n when 'true'\n if (RUBY_PLATFORM =~ /.*mingw.*/) or (RUBY_PLATFORM =~ /.*cygwin.*/)\n puts ui.color(\" the git core.autocrlf is set to 'true' which is correct for Windows/Cygwin\", :green)\n end\n if (RUBY_PLATFORM =~ /.*darwin.*/) or (RUBY_PLATFORM =~ /.*linux.*/)\n puts ui.color(\" the git core.autocrlf is set to 'true' but OSX/Linux should use 'input' to prevent line ending problems\", :red)\n end\n\n else\n puts ui.color(\" the git core.autocrlf is set to '#{result}'\", :red)\n puts ui.color(\" the git core.autocrlf should be set to 'input' (on OSX or Linux) or 'true' (on Windows) to prevent line ending problems\", :magenta)\n end\n\n # Check if we have a git remote called Gerrit.\n result=`git config --get remote.gerrit.url`.chomp\n if result.length < 1\n puts ui.color(\" we don't seem to have a git remote called gerrit.\", :red)\n puts ui.color(\" If we are in a project folder, check you have a valid .gitreview file and try running:-\", :red)\n puts ui.color(\" git review -s\", :magenta)\n else\n puts ui.color(\" the git remote for gerrit is set to #{result}\", :green)\n end\n\n # Check we have the settings to install Vagrant box templates and create Vagrant boxes\n # TODO: Add a check to make sure the box is installed and the URL is valid\n puts \"Check Vagrant\"\n checkparm(:vagrant_box,\"vagrant_box should be set to the name of your vagrant box\")\n checkparm(:vagrant_box_url,\"vagrant_box_url should point to a downloadable vagrant box\")\n\n puts \"Check berkshelf\"\n # Do we actually have a berks config\n berksConfigFile=File.expand_path(File.join('~','.berkshelf','config.json'))\n checkfile('Berkshelf Config',berksConfigFile,\"You dont have a Berkshelf config. Try running 'berks config'\")\n\n if ::File.exists?(berksConfigFile)\n berksConfigRaw=File.read(berksConfigFile)\n berksConfig=JSON.parse(berksConfigRaw)\n\n # Make sure that SSL verify is off\n if berksConfig['ssl']['verify'].to_s == 'false'\n puts ui.color(\" SSL verify is turned off\", :green)\n else\n puts ui.color(\" SSL verify is 'true'... you should set it to 'false' to allow connecting to Chef server\", :red)\n end\n \n # Check berks is using correct Chef server URL\n if berksConfig['chef']['chef_server_url'].to_s == config[:chef_server_url]\n puts ui.color(\" Berkshelf chef_server_url is '#{berksConfig['chef']['chef_server_url']}'\", :green)\n else\n puts ui.color(\" Berkshelf chef_server_url does not match knife.rb. It's set to '#{berksConfig['chef']['chef_server_url']}'\", :red)\n end\n\n # Check berks is using correct validator.pem\n if berksConfig['chef']['validation_key_path'].to_s == File.expand_path(config[:validation_key])\n puts ui.color(\" Berkshelf validation_key_path is '#{berksConfig['chef']['validation_key_path']}'\", :green)\n else\n puts ui.color(\" Berkshelf validation_key_path does not match knife.rb. It's set to '#{berksConfig['chef']['validation_key_path']}'\", :red)\n end\n\n # Check berks is using correct client.pem\n if berksConfig['chef']['client_key'].to_s == File.expand_path(config[:client_key])\n puts ui.color(\" Berkshelf client_key is '#{berksConfig['chef']['client_key']}'\", :green)\n else\n puts ui.color(\" Berkshelf client_key does not match knife.rb. It's set to '#{berksConfig['chef']['client_key']}'\", :red)\n end\n\n puts \"Done !!!\"\n\n end\n\n end", "def initialize(*args)\n super\n @action = :create\n @provider = Chef::Provider::LinodeDomainApi\nend", "def update_dependencies()\n\t\"berks vendor cookbooks #{(@debug ? '-d' : '-q')}\"\n end", "def prefer_indep_over_os_packages?; @prefer_indep_over_os_packages end", "def install_ark(resource_name)\n ChefSpec::Matchers::ResourceMatcher.new(:ark, :install, resource_name)\nend", "def resolve\n\n @perms = Constants::NOTFOUND\n @package = Constants::NOTFOUND\n @version = Constants::NOTFOUND\n @pie = Constants::NOTFOUND\n @stack = Constants::NOTFOUND\n\n # Get the file permissions\n permline = `#{Constants::LSPATH} -l #@path 2>/dev/null`\n if permline != ''\n @perms = permline[0,10]\n end\n\n # dpk and apt\n if Constants::PACKAGE == \"apt\"\n # Default: not found\n @package = Constants::NOTFOUND\n @version = Constants::NOTFOUND\n\n packageline = `#{Constants::DPKGPATH} --search #@path 2>/dev/null`\n if packageline =~ /([a-zA-Z0-9\\-\\.]*):.*/\n @package = $1\n versionline = `#{Constants::DPKGPATH} -p #@package 2>/dev/null`\n versionline.each_line do |line|\n if line =~ /Version:\\ *([a-zA-Z0-9\\-\\.:]*)/\n @version = $1\n end\n end\n end\n\n # rpm\n elsif Constants::PACKAGE == \"rpm\"\n packageline = `#{Constants::RPM} -qf #@path 2>/dev/null`\n if packageline.size < 1\n @package = Constants::NOTFOUND\n @version = Constants::NOTFOUND\n else\n @package = packageline.chomp\n versionline = `#{Constants::RPM} -qi #@package 2>/dev/null`\n @version = Constants::NOTFOUND\n end\n end\n\n # Get PIE and stack info\n elfLine = `#{Constants::READELFPATH} -hl #@path 2>/dev/null`\n @pie = Constants::NOTFOUND\n @stack = Constants::NOTFOUND\n elfLine.each_line do |line|\n if line =~ /Type:\\ *EXEC.*/\n @pie = \"FALSE\"\n elsif line =~ /Type:.*/\n @pie = \"TRUE\"\n elsif line =~ /GNU_STACK\\ *0x[0-9a-f]*\\ *0x[0-9a-f]*\\ *0x[0-9a-f]*\\ *0x[0-9a-f]*\\ *0x[0-9a-f]*\\ *([A-Z]*).*/\n @stack = $1\n end\n end\n end", "def search(gem_pattern, platform_only = T.unsafe(nil)); end", "def package_setup\n raise NotImplementedError\n end", "def installed_packages()\n\t\t\tend", "def resolve_with_librarian\n Kitchen.mutex.synchronize do\n Chef::Librarian.new(cheffile, tmpbooks_dir, logger: logger).resolve\n end\n end", "def install\n \n end", "def keyword_based_service?; end", "def auto_discover!(environment = nil)\n debug \"Starting cookbook auto-discovery\"\n unless discover\n raise \"Attempting to perform auto-discovery but auto-discovery is not enabled!\"\n end\n environment_items = Dir.glob(Utility.join_path(File.dirname(path), \"environments\", \"*.{json,rb}\")).map do |e_path|\n result = parse_environment(e_path)\n if result[:name] && result[:cookbooks]\n Smash.new(\n result[:name] => result[:cookbooks],\n )\n end\n end.compact.inject(Smash.new) { |m, n| m.merge(n) }\n environment_items.each do |e_name, items|\n next if environment && e_name != environment\n debug \"Discovery processing of environment: #{e_name}\"\n items.each do |ckbk_name, constraints|\n ckbk = cookbook.detect do |c|\n c.name == ckbk_name\n end\n if ckbk\n unless ckbk.constraint\n debug \"Skipping constraint merging due to lack of original constraints: #{ckbk.inspect}\"\n next\n end\n new_constraints = ckbk.constraint.dup\n new_constraints += constraints\n requirement = UnitRequirement.new(*new_constraints)\n new_constraints = flatten_constraints(requirement.requirements)\n debug \"Discovery merged constraints for #{ckbk.name}: #{new_constraints.inspect}\"\n ckbk.constraint.replace(new_constraints)\n else\n debug \"Discovery added cookbook #{ckbk_name}: #{constraints.inspect}\"\n cookbook.push(\n Cookbook.new(\n :name => ckbk_name,\n :constraint => constraints,\n )\n )\n end\n end\n end\n debug \"Completed cookbook auto-discovery\"\n true\n end", "def chef_solo_search_supported?(recipe_path)\n return false if recipe_path.nil? || ! File.exists?(recipe_path)\n cbk_tree_path = Pathname.new(File.join(recipe_path, '../../..'))\n search_libs = Dir[File.join(cbk_tree_path.realpath,\n '*/libraries/search.rb')]\n search_libs.any? do |lib|\n ! read_ast(lib).xpath(%q{//class[count(descendant::const[@value='Chef']\n ) = 1]/descendant::def/ident[@value='search']}).empty?\n end\n end", "def testLocateDep\n lLocatorCalled = false\n lCalled = false\n setupAppDir do\n setupRegressionUI('RDI::Test::Flows::UIFlows::RegressionUI', 'RDI::Test::Flows::UIFlows::RegressionUI::Directory') do\n # Tune the UI's behaviour\n @Installer.access_plugin('Views', 'RegressionUI') do |ioPlugin|\n ioPlugin.Locate = true\n end\n @Installer.access_plugin('LocationSelectors_RegressionUI', 'Directory') do |ioPlugin|\n ioPlugin.Directory = \"#{@RepositoryDir}/Binaries\"\n end\n # Call the installer expecting the GUI to appear\n lDesc = getSimpleDesc\n lError, lCMApplied, lIgnoredDeps, lUnresolvedDeps = @Installer.ensure_dependencies( [ lDesc ], {\n :preferred_views => [ 'RegressionUI' ]\n } )\n # Check results\n assert_equal(nil, lError)\n assert_equal( { 'DummyBinary' => [ [ 'SystemPath', \"#{@RepositoryDir}/Binaries\" ] ] }, lCMApplied )\n assert_equal( [], lIgnoredDeps )\n assert_equal( [], lUnresolvedDeps )\n # Get the plugins back\n @Installer.access_plugin('Views', 'RegressionUI') do |iPlugin|\n # Check that it was called correctly\n lCalled = iPlugin.Called\n end\n @Installer.access_plugin('LocationSelectors_RegressionUI', 'Directory') do |iPlugin|\n # Check that it was called correctly\n lLocatorCalled = iPlugin.Called\n end\n # Check that the dependency is resolved\n @Installer.access_plugin('Testers', 'Binaries') do |iPlugin|\n assert_equal(true, iPlugin.is_content_resolved?(['DummyBinary']))\n end\n end\n end\n assert_equal(true, lCalled)\n assert_equal(true, lLocatorCalled)\n end", "def infra_services_map\n {\n web: 'haproxy -- ./router.conf',\n yard: 'yard server --gems'\n }\n end", "def client\n return @client if @client\n\n @client = Chef::Client.new\n @client.ohai.data = Mash.from_hash(Fauxhai.mock(options).data)\n @client.load_node\n @client.build_node\n @client.save_updated_node\n @client\n end", "def dependencies=(_arg0); end", "def run_ohai\n @ohai.require_plugin(\"os\")\n end", "def run\n begin\n Kitchenplan::Log.info \"Kitchenplan run ready to begin.\"\n Kitchenplan::Log.debug \"Started with options: #{options.inspect}\"\n Kitchenplan::Log.info \"Validating dependencies for platform '#{self.platform.name}'...\"\n self.platform.prerequisites()\n if self.resolver.nil?\n\tKitchenplan::Log.info \"Checking for resolvers again now that dependencies are satisfied ... \"\n\tdetect_resolver(debug=@use_debug,config_dir=options[:config_dir])\n\tself.resolver.debug = @use_debug unless self.resolver.nil?\n\tKitchenplan::Log.warn \"Still couldn't find a resolver after installing prerequisites!\" if self.resolver.nil?\n end\n Kitchenplan::Log.info \"Generating Chef configs...\"\n generate_chef_config()\n Kitchenplan::Log.info \"Verifying cookbook dependencies using '#{self.resolver.name}'...\" unless self.resolver.nil?\n ping_google_analytics()\n update_cookbooks() unless self.resolver.nil?\n use_solo = options[:chef_mode].include?(\"solo\") ? true : false\n log_level = options[:log_level]\n log_file = options[:log_file]\n recipes = self.config['recipes']\n Kitchenplan::Log.debug \"self.resolver.config_dir = #{self.resolver.config_dir}\" unless self.resolver.nil?\n Kitchenplan::Log.debug \"self.config = #{self.config}, recipes = #{self.config['recipes']}\"\n self.platform.sudo(self.platform.run_chef(use_solo=use_solo,log_level=log_level,log_file=log_file,recipes=recipes))\n Kitchenplan::Log.info \"Chef run completed.\"\n self.exit!(\"Kitchenplan run complete. Exiting normally.\",0)\n rescue RuntimeError => e\n\tKitchenplan::Log.error \"An error was encountered shelling out and running a command to configure your system.\"\n\tKitchenplan::Log.error \"This could be due to a bug in Kitchenplan or an unexpected configuration on your system.\"\n\tKitchenplan::Log.error \"Failed command: #{e.message}\"\n\tKitchenplan::Log.error \"Stack trace:\"\n\te.backtrace.each { |l| Kitchenplan::Log.error \" #{l}\" }\n\tself.fatal!(\"Kitchenplan could not run successfully and is exiting with errors.\",-2)\n end\n end", "def search_for(dependency)\n @search[dependency] ||= begin\n additional_requirements = if locked_requirement = requirement_for_locked_pod_named(dependency.name)\n [locked_requirement]\n else\n Array(@podfile_requirements_by_root_name[dependency.root_name])\n end\n\n specifications_for_dependency(dependency, additional_requirements).freeze\n end\n end", "def upgrade_repo!\n package 'apt-transport-https'\n include_recipe \"apt-chef::#{new_resource.channel}\"\n package('chefdk') { action :upgrade }\n end", "def chef\n @chef ||= Appd::Server::Chef.new ssh\n end", "def getPackageDetails(cloud_name, cookbook_name, a_comp_mirrors, a_cloud_mirrors, src_mirror, node_platform, distributionurl)\n\n #Chef::Log.info(\"Getting mirror for app: #{cookbook_name} & cloud: #{cloud_name}\")\n base_url = ''\n base_url = distributionurl if (distributionurl != nil && !distributionurl.empty?)\n\n log \"getting_couchbase_pack\" do\n message \"Getting mirror for app: #{cookbook_name}, cloud: #{cloud_name} base url: #{base_url}\"\n level :info\n end\n\n # Search for component mirror\n comp_mirrors = JSON.parse(a_comp_mirrors) if base_url.empty?\n base_url = comp_mirrors[0] if (comp_mirrors != nil && comp_mirrors.size > 0)\n # Search for cloud mirror\n cloud_mirrors = JSON.parse(a_cloud_mirrors) if base_url.empty?\n base_url = cloud_mirrors[cookbook_name] if !cloud_mirrors.nil? && cloud_mirrors.has_key?(cookbook_name)\n # Search for cookbook default attribute mirror\n base_url = src_mirror if base_url.empty?\n\n case node_platform\n # Redhat based distros\n when 'redhat', 'centos', 'fedora'\n package_type = 'rpm'\n package_installer = 'rpm -i --nodeps'\n yum_package 'perl-Time-HiRes' do\n action :install\n end\n # Debian based ditros\n when 'ubuntu', 'debian'\n package_type = 'deb'\n package_installer = 'dpkg -i'\n else\n Chef::Application.fatal!(\"#{node_platform} platform is not supported for Couchbase.\")\n end\n #Chef::Log.info(\"Mirror base_url: #{base_url} & package_type: #{package_type}\")\n log \"result_couchbase_pack\" do\n message \"Mirror base_url: #{base_url} & package_type: #{package_type}\"\n level :info\n end\n return base_url, package_type, package_installer\nend", "def init\n clone_appd_cookbook\n chef_gem \"install berkshelf\"\n end", "def load_framework_interfaces\n interfaces = Array.new\n components_directory = \"#{File.dirname(__FILE__)}/../\"\n Dir.entries(components_directory).select {|entry| File.directory?(File.join(components_directory, entry)) && !(entry =='.' || entry == '..') }.each do |iface_dir|\n interfaces.push(extract_interface_info( components_directory, iface_dir)) if File.exist?(\"#{components_directory}#{iface_dir}/index.html\")\n end\n interfaces\nend", "def install_chef_gem(nr)\n # let chef_gem install the gem for us\n at_compile_time do\n chef_gem nr.gem_name do\n %w(options version source).each do |attr|\n value = new_resource.send(attr.to_sym)\n send(attr.to_sym, value) unless value.nil?\n end\n end\n end\n end", "def installed_versions(name, requirement)\n if gem_installed?(name, requirement)\n Chef::Log.info \"Gem #{name} (#{requirement}) found in OpsWorks user space.\"\n # from rubygems/specification.rb#find_all_by_name\n Gem::Dependency.new(name, requirement).matching_specs\n else\n Chef::Log.debug \"Gem #{name} (#{requirement}) not found in OpsWorks user space.\"\n []\n end\n end", "def chef_client\n return @chef_client unless @chef_client.nil?\n @chef_client = cluster.find_client(fullname) || false\n end", "def install!\n include_recipe 'zypper'\n super\n end", "def api_clients\n get_chef_files_absolute_paths api_clients_path\n end", "def installed_spec_directories; end", "def check_idl_dependencies\n recipes.each { |rcp| rcp.check_idl_dependencies }\n end", "def local_requires\n require \"talia_cl\"\nend", "def extended_interfaces; end", "def initialize(*args)\n super\n self[:notify] = [\n \"Service[splunk]\",\n \"Service[splunkd]\",\n ].select { |ref| catalog.resource(ref) } unless catalog.nil?\n\n end", "def find(path, type, setting); end", "def scan(name)\n raise NotImplementedError, \"Repositories must return an Array of matching packages.\"\n end", "def registry; end", "def registry; end", "def chef_init(file)\n self.file = file\n self.source = IO.read(File.expand_path(file))\n self.header = find_header_in(source)\n self.docstring = find_description_in(header)\n end", "def depends_all\n pkg_depends = self.class.depends_all\n if self.class.omnibus_package\n self.class.omnibus_recipes.each { |omni_recipe|\n recipe_file = File.expand_path(omni_recipe + '.rb', File.dirname(filename))\n\n Book.instance.load_recipe(recipe_file, config) do |recipe|\n pkg_depends << recipe.depends_all\n end\n }\n end\n\n pkg_depends.flatten.uniq\n end", "def depends_all\n pkg_depends = self.class.depends_all\n if self.class.omnibus_package\n self.class.omnibus_recipes.each { |omni_recipe|\n recipe_file = File.expand_path(omni_recipe + '.rb', File.dirname(filename))\n\n Book.instance.load_recipe(recipe_file, config) do |recipe|\n pkg_depends << recipe.depends_all\n end\n }\n end\n\n pkg_depends.flatten.uniq\n end", "def object_resources\n run_context.resource_collection.select do |resource|\n resource.is_a?(Chef::Resource::Icinga2Eventcommand)\n end\nend", "def enable_dependency_loading; end", "def enable_dependency_loading; end", "def chef_version(*version_args)\n @chef_versions << Gem::Dependency.new(\"chef\", *version_args) unless version_args.empty?\n @chef_versions\n end", "def create_client!\n Chef::ApiClient::Registration.new(node_name, client_path, http_api: rest).run\n end", "def toolbox(type)\n end", "def toolbox(type)\n end" ]
[ "0.58905697", "0.58658063", "0.58568287", "0.58568287", "0.58568287", "0.5838765", "0.5816879", "0.58113635", "0.5804071", "0.5735008", "0.5643202", "0.56092715", "0.5576077", "0.554456", "0.55291486", "0.5526053", "0.5515817", "0.5498583", "0.5494602", "0.5485111", "0.54770553", "0.5453621", "0.5451076", "0.54351455", "0.54302347", "0.5426136", "0.54004776", "0.53973", "0.5396661", "0.53893554", "0.5388685", "0.5388685", "0.53818965", "0.53436047", "0.53435075", "0.53372455", "0.53333443", "0.5322917", "0.532119", "0.5315341", "0.5312446", "0.53020525", "0.5300617", "0.5291907", "0.52788866", "0.52745616", "0.52691984", "0.5261988", "0.5260778", "0.5260778", "0.52555424", "0.52528846", "0.5251945", "0.52390534", "0.52315986", "0.52277774", "0.52264184", "0.5224754", "0.5212713", "0.5211464", "0.5205009", "0.52048796", "0.5202514", "0.52006525", "0.52000225", "0.5197065", "0.51954937", "0.51949435", "0.51940644", "0.5191969", "0.5182313", "0.5176433", "0.5170483", "0.5170323", "0.5162322", "0.5160696", "0.51484734", "0.51459074", "0.5143069", "0.5134793", "0.51318574", "0.51307285", "0.5130467", "0.51267743", "0.51215523", "0.5112551", "0.5111297", "0.5110166", "0.51078707", "0.5107704", "0.5107704", "0.51036435", "0.5083689", "0.5083689", "0.507646", "0.50732404", "0.50732404", "0.50657713", "0.50583124", "0.50562936", "0.50562936" ]
0.0
-1
Interface dependency of our Capistrano config context
def chef_context @chef_context || ::Capistrano.env end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def env_config; end", "def env_config; end", "def env_config; end", "def env_config; end", "def cap_config\n @cap_config ||= Sauce.instance.new_capistrano_config()\n end", "def create_config \n @config = ::Capistrano::Configuration.new\n if @cloud.debug || @cloud.verbose \n @config.logger.level = @cloud.debug ? ::Capistrano::Logger::MAX_LEVEL : ::Capistrano::Logger::INFO\n else\n @config.logger.level = ::Capistrano::Logger::IMPORTANT\n end\n \n capfile = returning Array.new do |arr|\n Dir[\"#{::File.dirname(__FILE__)}/recipies/*.rb\"].each {|a| arr << \"require '#{a}'\" }\n arr << \"ssh_options[:keys] = '#{@cloud.full_keypair_basename_path}'\"\n \n arr << set_poolparty_roles\n end.join(\"\\n\")\n \n @config.provisioner = self\n @config.cloud = @cloud\n \n @config.load(:string => capfile)\n \n @cloud.deploy_file ? @config.load(@cloud.deploy_file) : @config.set(:user, @cloud.user)\n end", "def base_recipe()\n warn \"#{self} hasn't been overridden to return a Proc!!\"\n lambda {\n # put your capistrano config and tasks in here\n }\n end", "def configuration_for(host, use_ssh_config); end", "def instantiate_configuration(options={}) #:nodoc:\n Capistrano::Configuration.new(options)\n end", "def config(mod, *accessors); end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def conf\n @c ||= JSON.load(File.read('/etc/knife-kvm/config.json'))\nend", "def capify_this_shit\n inject_into_file 'Capfile', after: '# Include tasks from other gems included in your Gemfile' do\n <<-RUBY\n\nrequire 'capistrano/rails'\nrequire 'capistrano/bundler'\nrequire 'capistrano/rails/migrations'\n\n RUBY\n end\n end", "def parametrize #alias\n self.configuration\n end", "def config\n\n end", "def actual_config\n Config.instance\n end", "def config\n @context.config\n end", "def new_capistrano_config(opts=@opts)\n c = Capistrano::Configuration.new(opts)\n # NOTE: Capistrano::Logger constant values are opposite of Logger ....goofy\n c.logger.level = opts[:log_level] || Capistrano::Logger::DEBUG\n @@load_paths.each {|d| c.load_paths << d }\n Array(opts[:load_paths]).flatten.each {|d| c.load_paths << d } if opts[:load_paths]\n return c\n end", "def setup_config\n # To be Extended\n end", "def check!\n Capistrano::Deploy::Dependencies.new(configuration) do |d|\n d.remote.file(Capistrano::Puppet::Service::Webrick::SERVICE_INIT).or(\"`#{Capistrano::Puppet::Service::Webrick::SERVICE_INIT}' does not exist. Please run `cap deploy:setup'.\")\n end\n end", "def reference\n :config\n end", "def reference\n :config\n end", "def instantiate_configuration(options={})\n config = Capistrano::Configuration.new(options)\n config.logger = logger\n config\n end", "def load_repo_config; end", "def config\n @config ||= YAML.load_file(BASE_PATH + '/local.config.yml')\nend", "def get_config\n\t\tend", "def initialize\n configure_via_yaml\n configure_via_env\n end", "def before_configuration_tasks \n end", "def config\n Config.new(@sources, @deployments)\n end", "def configuration; end", "def configuration; end", "def configuration; end", "def configuration; end", "def configuration; end", "def capistrano_application\n @@capistrano_application ||= load_capistrano_application\n end", "def config\n machined.config\n end", "def config_store; end", "def configurations; end", "def config(&blk)\n scope &blk\n self\n end", "def initialize(context)\n\tsuper\n\t\n\trequire_relative '../../lib/covered/config'\nend", "def config=(_arg0); end", "def config=(_arg0); end", "def config=(_arg0); end", "def config=(_arg0); end", "def config=(_arg0); end", "def config=(config); end", "def configure; end", "def install_configure_in(base)\n base.instance_eval <<-EOF\n # Configuration class for host module\n #\n #{base.name}::Configuration = Class.new(Configurations::Configuration)\n\n # The central configure method\n # @params [Proc] block the block to configure host module with\n # @raise [ArgumentError] error when not given a block\n # @example Configure a configuration\n # MyGem.configure do |c|\n # c.foo = :bar\n # end\n #\n def self.configure(&block)\n semaphore.synchronize do\n fail ArgumentError, \"configure needs a block\" unless block_given?\n include_configuration_type!(#{base.name}::Configuration)\n\n set_configuration!(&block)\n end\n end\n\n # A reader for Configuration\n #\n def configuration\n semaphore.synchronize do\n return @configuration if @configuration\n\n if @configuration_defaults\n include_configuration_type!(#{base.name}::Configuration)\n set_configuration! { }\n end\n end\n end\n\n\n private\n\n # Sets the configuration instance variable\n #\n def self.set_configuration!(&block)\n @configuration = #{base.name}::Configuration.__new__(\n configuration_options,\n &block\n )\n end\n\n @semaphore = Mutex.new\n def self.semaphore\n @semaphore\n end\n\n EOF\n end", "def config\n configuration\n end", "def config\n {\n :APP_NAME => APP_NAME,\n :APP_ENV => APP_ENV,\n :AWS_ACCESS_KEY_ID => AMI_ACCESS_KEY_ID,\n :AWS_SECRET_ACCESS_KEY => AMI_SECRET_ACCESS_KEY\n }\nend", "def inject_arkivo_config\n inject_into_file 'config/initializers/hyrax.rb', after: /^Hyrax\\.config do.*$/ do\n \"\\n # Hyrax can integrate with Zotero's Arkivo service for automatic deposit\\n\" \\\n \" # of Zotero-managed research items.\\n\" \\\n \" # Defaults to false. See README for more info\\n\" \\\n \" config.arkivo_api = true\\n\"\n end\n end", "def deploy?; run_options[:deploy]; end", "def config\n @config ||= compile\n end", "def initialize\n # These require statements are intentionally placed here to initialize\n # the gRPC module only when it's required.\n # See https://github.com/googleapis/toolkit/issues/446\n require \"gapic/grpc\"\n require \"google/cloud/deploy/v1/cloud_deploy_services_pb\"\n\n # Create the configuration object\n @config = Configuration.new Client.configure\n\n # Yield the configuration if needed\n yield @config if block_given?\n\n # Create credentials\n credentials = @config.credentials\n # Use self-signed JWT if the endpoint is unchanged from default,\n # but only if the default endpoint does not have a region prefix.\n enable_self_signed_jwt = @config.endpoint == Configuration::DEFAULT_ENDPOINT &&\n !@config.endpoint.split(\".\").first.include?(\"-\")\n credentials ||= Credentials.default scope: @config.scope,\n enable_self_signed_jwt: enable_self_signed_jwt\n if credentials.is_a?(::String) || credentials.is_a?(::Hash)\n credentials = Credentials.new credentials, scope: @config.scope\n end\n @quota_project_id = @config.quota_project\n @quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id\n\n @operations_client = Operations.new do |config|\n config.credentials = credentials\n config.quota_project = @quota_project_id\n config.endpoint = @config.endpoint\n end\n\n @location_client = Google::Cloud::Location::Locations::Client.new do |config|\n config.credentials = credentials\n config.quota_project = @quota_project_id\n config.endpoint = @config.endpoint\n end\n\n @iam_policy_client = Google::Iam::V1::IAMPolicy::Client.new do |config|\n config.credentials = credentials\n config.quota_project = @quota_project_id\n config.endpoint = @config.endpoint\n end\n\n @cloud_deploy_stub = ::Gapic::ServiceStub.new(\n ::Google::Cloud::Deploy::V1::CloudDeploy::Stub,\n credentials: credentials,\n endpoint: @config.endpoint,\n channel_args: @config.channel_args,\n interceptors: @config.interceptors\n )\n end", "def check!\n Capistrano::Deploy::Dependencies.new(configuration) do |d|\n # d.remote.directory(configuration[:releases_path]).or(\"`#{configuration[:releases_path]}' does not exist. Please run `cap deploy:setup'.\")\n # d.remote.writable(configuration[:deploy_to]).or(\"You do not have permissions to write to `#{configuration[:deploy_to]}'.\")\n # d.remote.writable(configuration[:releases_path]).or(\"You do not have permissions to write to `#{configuration[:releases_path]}'.\")\n end\n end", "def private_chef!(args = {})\n ChefBackup::Config.config = args\nend", "def cop_config; end", "def interface\n Context.interface\n end", "def install_configure_in(base)\n base.instance_eval <<-EOF\n # Configuration class for host module\n #\n #{base.name}::Configuration = Class.new(Configurations::Configuration)\n\n # The central configure method\n # @params [Proc] block the block to configure host module with\n # @raise [ArgumentError] error when not given a block\n # @example Configure a configuration\n # MyGem.configure do |c|\n # c.foo = :bar\n # end\n #\n def self.configure(&block)\n fail ArgumentError, \"configure needs a block\" unless block_given?\n include_configuration_type!(#{base.name}::Configuration)\n\n set_configuration!(&block)\n end\n\n # A reader for Configuration\n #\n def configuration\n return Thread.current[configuration_name] if Thread.current.key?(configuration_name)\n\n @configuration_defaults && configure {}\n end\n\n\n private\n\n # Sets the configuration instance variable\n #\n def self.set_configuration!(&block)\n Thread.current[configuration_name] = #{base.name}::Configuration.__new__(\n configuration_options,\n &block\n )\n end\n\n def self.configuration_name\n :\"#{underscore_camelized(base.name)}\"\n end\n\n EOF\n end", "def configuration_file_path; end", "def get_config(context)\n context.registers[:site].config\n end", "def plugin_conf\n inspec_config.fetch_plugin_config(\"inspec-chef\")\n end", "def create_monit_config\n # Scope closureeeeeee.\n _options = options\n _pid_file = pid_file\n _parent = service_resource.parent\n _script_path = script_path\n monit_config new_resource.service_name do\n if _options['monit_template']\n # If we have a template override, allow specifying a cookbook via\n # \"cookbook:template\".\n parts = _options['monit_template'].split(/:/, 2)\n if parts.length == 2\n source parts[1]\n cookbook parts[0]\n else\n source parts.first\n cookbook new_resource.cookbook_name.to_s\n end\n else\n source 'monit_service.conf.erb'\n cookbook 'poise-monit'\n end\n parent _parent\n variables service_resource: new_resource, options: _options, pid_file: _pid_file, script_path: _script_path\n # Don't trigger a restart if the template doesn't already exist, this\n # prevents restarting on the run that first creates the service.\n restart_on_update = _options.fetch('restart_on_update', new_resource.restart_on_update)\n if restart_on_update && ::File.exist?(path) # Path here is accessing MonitConfig::Resource#path.\n mode = restart_on_update.to_s == 'immediately' ? :immediately : :delayed\n notifies :restart, new_resource, mode\n end\n end\n end", "def vcap environment\n\nend", "def config\n yield self\n end", "def host; config[:host]; end", "def config_for(dest_path, sync_config_path = nil)\n require 'pdk/util'\n require 'pdk/analytics'\n\n module_root = PDK::Util.module_root\n sync_config_path ||= File.join(module_root, '.sync.yml') unless module_root.nil?\n config_path = File.join(@path, 'config_defaults.yml')\n\n if @config.nil?\n require 'deep_merge'\n conf_defaults = read_config(config_path)\n @sync_config = read_config(sync_config_path) unless sync_config_path.nil?\n @config = conf_defaults\n @config.deep_merge!(@sync_config, knockout_prefix: '---') unless @sync_config.nil?\n end\n file_config = @config.fetch(:global, {})\n file_config['module_metadata'] = @module_metadata\n file_config.merge!(@config.fetch(dest_path, {})) unless dest_path.nil?\n file_config.merge!(@config).tap do |c|\n if uri.default?\n file_value = if c['unmanaged']\n 'unmanaged'\n elsif c['delete']\n 'deleted'\n elsif @sync_config && @sync_config.key?(dest_path)\n 'customized'\n else\n 'default'\n end\n\n PDK.analytics.event('TemplateDir', 'file', label: dest_path, value: file_value)\n end\n end\n end", "def ignore_env_proxy; end", "def ignore_env_proxy; end", "def ignore_env_proxy; end", "def config\n @options[:config]\n end", "def c\n configuration\n end", "def config\n $VHOST.config\n end", "def initialize(context)\n @logger = LibertyBuildpack::Diagnostics::LoggerFactory.get_logger\n @app_dir = context[:app_dir]\n @java_home = context[:java_home]\n @java_opts = context[:java_opts]\n @lib_directory = context[:lib_directory]\n @common_paths = context[:common_paths] || CommonPaths.new\n @configuration = context[:configuration]\n @vcap_services = Heroku.heroku? ? Heroku.new.generate_vcap_services(ENV) : context[:vcap_services]\n @vcap_application = context[:vcap_application]\n @license_id = context[:license_ids]['IBM_LIBERTY_LICENSE']\n @environment = context[:environment]\n unpack_apps\n end", "def _shared_configuration #:nodoc:\n {:invocations => @_invocations}\n end", "def env_key; end", "def get_runtime_config(app)\n\t\texec_zi(app,self.zapp_instance)\n\tend", "def config\n<<-EOL\nManage the environment's config. Can use this to download the environment's config to jack/cfg folder or upload and apply config in jack/cfg folder to the environment.\n\nExample:\n\n$ jack config get hi-web-stag-1\n\nFor more info:\n\n$ jack help config\n\n$ jack config help upload\n\n$ jack config help download\nEOL\n end", "def configuration\n cfg = {:service => @service}\n cfg[:acl] = @acl.name if (@acl)\n cfg[:avpairs] = @avpairs if (@avpairs)\n cfg[:network_av] = @network_av.configuration if (@network_av)\n cfg[:shell_command_av] = @shell_command_av.configuration if (@shell_command_av)\n return(cfg)\n end", "def init\n create_file options[:inventory_config] do\n<<-YML\n# sources:\n# - \"https://supermarket.getchef.com\"\n# cookbooks:\n# cookbook-name:\n# versions:\n# - \"~> 4.0.2\"\n# - \"> 5.0.0\"\n# git:\n# location: url | path\n# branches:\n# - a_branch_name\n# refs:\n# - SHA\n\nYML\n end\n end", "def config\n self\n end", "def config\n @config_file\n end", "def remote_deployment_model\n site_url = self.endpoint_url\n username = self.username\n password = self.password\n cert_file = self.cert_file\n\n Class.new(RemoteDeployment) do\n self.site = site_url\n self.element_name = 'deployment'\n self.user = username\n self.password = password\n\n self.ssl_options = {\n verify_mode: OpenSSL::SSL::VERIFY_PEER,\n ca_file: cert_file\n } unless Rails.env.development?\n end\n end" ]
[ "0.6797451", "0.6797451", "0.6797451", "0.6797451", "0.6464963", "0.6284742", "0.60308534", "0.5903349", "0.5839589", "0.58211845", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.58043116", "0.5781243", "0.5777874", "0.57667774", "0.57218724", "0.5712056", "0.56957746", "0.56934756", "0.5676313", "0.5643738", "0.56430817", "0.56430817", "0.56337494", "0.5633203", "0.56308633", "0.56285185", "0.5606151", "0.56045246", "0.5600024", "0.55932546", "0.55932546", "0.55932546", "0.55932546", "0.55932546", "0.5569086", "0.5561337", "0.55322963", "0.5525455", "0.5510562", "0.5488328", "0.5483466", "0.5483466", "0.5483466", "0.5483466", "0.5483466", "0.547255", "0.5471403", "0.5468805", "0.5444296", "0.5435518", "0.5426069", "0.54156524", "0.5407296", "0.54065216", "0.53863513", "0.5381873", "0.5375069", "0.5368283", "0.5364689", "0.5360872", "0.5348732", "0.5347886", "0.5343847", "0.5324043", "0.5323166", "0.5321374", "0.5321292", "0.53205174", "0.53205174", "0.53205174", "0.53004307", "0.52987254", "0.52959704", "0.52700096", "0.52697784", "0.5268207", "0.52623373", "0.5261696", "0.52569914", "0.52553916", "0.5254584", "0.5254333", "0.5253388" ]
0.5893721
8
Query a Chef Server to search for specific nodes
def chef_results_by(attribute) case attribute when Symbol, String lambda { |node| node[attribute] } when Hash # not tested iface, family = attribute.keys.first.to_s, attribute.values.first.to_s lambda do |nodes| addresses = node["network"]["interfaces"][iface]["addresses"] addresses.select do |address, data| data["family"] == family end.to_a.first.first end else Proc.new {} # noop end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def node_list\n list = {}\n search = Chef::Search::Query.new\n query = config[:query]\n\n ui.msg \"Search nodes '#{query}'\"\n search.search('node', query) do |node|\n if node['chef'] && node['chef']['client_version']\n version = node['chef']['client_version']\n\n list[version] ||= []\n list[version] << node\n end\n end\n ui.msg ''\n\n list\n end", "def discover_chef_nodes!\n chef_nodes.each do |chef_node|\n if chef_node[\"cluster_name\"] && chef_node[\"facet_name\"] && chef_node[\"facet_index\"]\n cluster_name = chef_node[\"cluster_name\"]\n facet_name = chef_node[\"facet_name\"]\n facet_index = chef_node[\"facet_index\"]\n elsif chef_node.name\n ( cluster_name, facet_name, facet_index ) = chef_node.name.split(/-/)\n else\n next\n end\n svr = Ironfan::Server.get(cluster_name, facet_name, facet_index)\n svr.chef_node = chef_node\n @aws_instance_hash[ chef_node.ec2.instance_id ] = svr if chef_node && chef_node[:ec2] && chef_node.ec2.instance_id\n end\n end", "def ceph_chef_mon_nodes\n results = nil\n if node['ceph']['search_by_environment']\n results = search(:node, ceph_chef_mon_env_search_string)\n else\n results = search(:node, \"tags:#{node['ceph']['mon']['tag']}\")\n if !results.include?(node) && node.run_list.roles.include?(node['ceph']['mon']['role'])\n results.push(node)\n end\n end\n\n results.map! { |x| x['hostname'] == node['hostname'] ? node : x }\n results.sort! { |a, b| a['hostname'] <=> b['hostname'] }\nend", "def auto_discover_nodes!\n @servers = execute(:all_nodes)\n end", "def query_by_nodename(nodename)\n query = {\"query\" => \"SELECT NodeName, NodeID FROM Orion.Nodes WHERE NodeName=@name\", \"parameters\" => {\"name\" => \"#{nodename}\"}}\n do_http_request(@querypath, query)\n end", "def change_chef_vars(instances, &block)\n instances.each { |inst|\n query = \"name:#{inst['server_name']}\"\n query_nodes = Chef::Search::Query.new\n query_nodes.search('node', query) do |node_item|\n yield node_item\n end\n }\n end", "def nodes\n request.get(path: node_index_path, auth_token: auth_token)\n end", "def get_nodes\n\tq = '[\"=\", [\"node\", \"active\"], true]'\n\n\tif ! q.is_a? String then\n\t\tq=JSON[q]\n\t\tend\n\tparams = {:query => q}\n\n response_nodelist = RestClient.get\"http://#{Tayu.puppetdb_server}:#{Tayu.puppetdb_port}/nodes\", { :accept => :json, :params => params }\n return JSON.parse(response_nodelist)\n end", "def find_nodes\n puts '1st pass: find nodes'\n find :nodes\n self\n end", "def query_couchbase_servers\n\n couchbase_servers = Hash.new\n \n r=rightscale_server_collection 'couchbase_cluster_nodes' do\n tags [\"couchbase:cluster_ip=#{cluster_ip}\"]\n secondary_tags [\"server:uuid=*\", \"couchbase:listen_ip=*\"]\n action :nothing\n end\n r.run_action(:load)\n \n node[:server_collection]['couchbase_cluster_nodes'].to_hash.values.each do |tags|\n uuid = RightScale::Utils::Helper.get_tag_value('server:uuid', tags)\n ip = RightScale::Utils::Helper.get_tag_value('couchbase:listen_ip', tags)\n couchbase_servers[uuid] = {}\n couchbase_servers[uuid][:ip] = ip\n end\n \n couchbase_servers\n \n end", "def query_by_nodeid(nodeid)\n query = {\"query\" => \"SELECT NodeName, NodeID FROM Orion.Nodes WHERE NodeID=@id\", \"parameters\" => {\"id\" => \"#{nodeid}\"}}\n do_http_request(@querypath, query)\n end", "def node_list\n Chef::Node.list.keys\n end", "def kube_custom_search(context, term)\n cluster_id = node[cookbook_name]['cluster_id']\n ret_val = []\n filter = { 'name' => ['fqdn'], 'ip' => ['ipaddress'] }\n # puts \"search(#{context}, #{term}, filter_result: #{filter})\"\n search(context, term, filter_result: filter).each do |inst|\n raw = \"Raw search returns #{inst.inspect}\"\n # >[{\"name\"=>\"server-0\", \"ip\"=>\"ip-0\"}, {\"name\"=>\"server-1\", \"ip\"=>\"ip-1\"}]\n raise raw + \"\\n\" + err('no_master') if inst['name'].nil? && term == \"role:k8s_master_#{cluster_id}\"\n raise raw + \"\\n\" + err('no_minion') if inst['name'].nil? && term == \"role:k8s_minion_#{cluster_id}\"\n ret_val.push(name: inst['name'].downcase, ip: inst['ip'])\n end\n if ret_val.empty?\n abort(err('no_master')) if term == \"role:k8s_master_#{cluster_id}\"\n abort(err('no_minion')) if term == \"role:k8s_minion_#{cluster_id}\"\n end\n ret_val # >[{\"name\"=>\"server-0\", \"ip\"=>\"ip-0\"}, {\"name\"=>\"server-1\", \"ip\"=>\"ip-1\"}]\n end", "def nodes_for_environment(name)\n ridley.partial_search(:node, \"chef_environment:#{name}\", [\"fqdn\", \"cloud.public_hostname\", \"name\", \"os\"])\n end", "def run( nodes )\n\t\t\tself.log.debug \"Got %d nodes to check with %p\" % [ nodes.length, self ]\n\t\t\tlookups = self.create_lookups( nodes )\n\t\t\treturn self.wait_for_responses( lookups, nodes )\n\t\tend", "def get_all_nodes(state)\n rc = []\n machines = state[:machines]\n chef_server = Cheffish::CheffishServerAPI.new(Cheffish.enclosing_chef_server)\n nodes = chef_server.get(\"/nodes\")\n nodes.each_key do |key|\n if (machines.include?(key))\n node_url = nodes[key]\n node = chef_server.get(node_url)\n rc.push(node)\n end\n end\n return rc\n end", "def nodes\n core_client.get_nodes\n end", "def listNodes\n nodes = []\n me = MU::Cloud::AWS::ServerPool.find(cloud_id: cloud_id).values.first\n if me and me.instances\n me.instances.each { |instance|\n found = MU::MommaCat.findStray(\"AWS\", \"server\", cloud_id: instance.instance_id, region: @region, dummy_ok: true)\n nodes.concat(found)\n }\n end\n nodes\n end", "def get_zk_nodes\n rl_results = search(:node, \"role:Kafka-Head-Zookeeper AND chef_environment:#{node.chef_environment}\")\n rl_results.map!{|x| x[:hostname] == node[:hostname] ? node : x}\n ro_results = search(:node, \"roles:Kafka-Head-Zookeeper AND chef_environment:#{node.chef_environment}\")\n ro_results.map!{|x| x[:hostname] == node[:hostname] ? node : x}\n results = rl_results.concat ro_results\n return results.uniq{|x| x[:hostname]}.sort\nend", "def discover_chef_clients!\n servers.each(&:chef_client)\n end", "def get_node_names\n Chef::Node.list.keys\n end", "def nodes(hsh={})\n results = describe_instances(:status=>'running').select_with_hash({:keypair_name => keypair.basename})\n results.select_with_hash(hsh)\n end", "def chef_search(type, query=\"*:*\")\n chef_scopes = fetch(:chef_scopes) || []\n queries = [chef_scopes, query].flatten.join(\" AND \")\n puts \"Searching Chef types \\\"#{type}\\\" with \\\"#{queries}\\\"\" if debug?\n results = chef_query_class.new.search(type, queries).first\n puts \"Found #{results.count}\" if debug?\n results\n end", "def incoming(opts={})\n # Constrain results to this pool\n fq = \"format:Node\"\n # fq += \" AND pool:#{pool.id}\"\n http_response = Bindery.solr.select(params: {q:persistent_id, qf:\"bindery__associations_sim\", qt:'search', fq:fq})\n results = http_response[\"response\"][\"docs\"].map{|d| Node.find_by_persistent_id(d['id'])}\n end", "def getNodeList\n broker_url = APP_CONFIG['broker_ip'] + ':' + APP_CONFIG['broker_port'].to_s\n result = HTTParty.get(broker_url + \"/resources/nodes\", :verify => false)\n temp2 = JSON.parse(result.body)\n\n node_data = temp2[\"resource_response\"][\"resources\"]\n return node_data\n \n end", "def manage_cluster\n @nodes = Node.find(:all)\n end", "def nodelist\n runopts(:nodelist)\n end", "def get_nodes_by_recipe(recipe, includeme=true, options={})\n options = {\n :search_string => recipe,\n :include_me => includeme,\n :order => [:recipe],\n :safe_deref => nil,\n :current_node => nil,\n :one_or_all => :all\n }.merge(options)\n opsit_search(options)\n end", "def fakesearch_all_nodes(options = {})\n fakesearch_nodes(nil, options)\nend", "def get_all_roles_nodes\n result = search(:node, \"chef_environment:#{node.chef_environment}\")\n if result.any? { |x| x['hostname'] == node['hostname'] }\n result.map! { |x| x['hostname'] == node['hostname'] ? node : x }\n else\n result.push(node)\n end\n return result.sort! { |a, b| a['hostname'] <=> b['hostname'] }\nend", "def run( nodes )\n\t\t\tself.log.debug \"Got nodes to check with %p: %p\" % [ self, nodes ]\n\n\t\t\trecords = nodes.each_with_object( {} ) do |(identifier, node), hash|\n\t\t\t\tself.log.debug \"Looking up whois info for %p (%p)\" % [ identifier, node ]\n\t\t\t\thash[ identifier ] = self.client.lookup( node['name'] )\n\t\t\tend\n\n\t\t\treturn records.each_with_object( {} ) do |(identifier, record), hash|\n\t\t\t\tparser = record.parser\n\t\t\t\thash[ identifier ] = self.parse_record( parser, identifier )\n\t\t\tend\n\n\t\tend", "def services_for(node)\n # This info is taken from our JSON inventory file\n [JSON.parse(File.read(\"#{repository_path}/hosts.json\"))[\"#{node}.hpc_tutorial.org\"]]\n end", "def find\n log_output(\"Starting #{provider} find\", :info)\n validate_provision_fields\n connection = connect\n \n name = get_field('name')\n # select those servers matching name. Fail if servers don't have a name\n servers = connection.servers.select do |s|\n if s.respond_to?(:name)\n s.name =~ /#{name}/\n else\n raise PluginError, \"Provider #{provider} does not support finding servers by name\"\n end\n end\n\n save_server_ids_in_context(servers, true)\n save_server_in_context(servers, true)\n populate_meta(servers, 'find', true)\n\n msg = servers.empty? ? \"#{provider} found no servers\" : \"#{provider} found #{servers.size} servers: \"\n msg += servers.map{|s| s.respond_to?(:name) ? s.name : s.identity}.join(\",\")\n Maestro.log.debug msg\n write_output(\"#{msg}\\n\")\n end", "def getNodeStatus(node_id) \n cm_url = APP_CONFIG['cm_ip'] + ':' + APP_CONFIG['cm_port'].to_s\n res = HTTParty.get(cm_url+\"/resources/node/\"+ node_id)\n # puts \"status \"+node_id\n # puts res\n return res\n\n end", "def available_node_list\n all_nodes = Node.by_name\n return all_nodes.select {|node| node.status == \"RUNNING\"}\n end", "def help_node_names_data\n\t\t__elasticsearch__.client.cat.nodes(:format => 'json', :h => 'name')\n\tend", "def __get_nodes\n JSON.parse(Net::HTTP.get(URI(\"#{__cluster_url}/_nodes/process\")))\n end", "def get_node(state, name)\n machines = state[:machines]\n if (machines.include?(name))\n chef_server = Cheffish::CheffishServerAPI.new(Cheffish.enclosing_chef_server)\n nodes = chef_server.get(\"/nodes\")\n node_url = nodes[name]\n chef_server.get(node_url)\n else\n nil\n end\n end", "def find_nodes_with_http_info(term, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: QueriesApi.find_nodes ...\"\n end\n # verify the required parameter 'term' is set\n fail ArgumentError, \"Missing the required parameter 'term' when calling QueriesApi.find_nodes\" if term.nil?\n if !opts[:'skip_count'].nil? && opts[:'skip_count'] < 0.0\n fail ArgumentError, 'invalid value for \"opts[:\"skip_count\"]\" when calling QueriesApi.find_nodes, must be greater than or equal to 0.0.'\n end\n\n if !opts[:'max_items'].nil? && opts[:'max_items'] < 1.0\n fail ArgumentError, 'invalid value for \"opts[:\"max_items\"]\" when calling QueriesApi.find_nodes, must be greater than or equal to 1.0.'\n end\n\n # resource path\n local_var_path = \"/queries/nodes\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n query_params[:'term'] = term\n query_params[:'rootNodeId'] = opts[:'root_node_id'] if !opts[:'root_node_id'].nil?\n query_params[:'skipCount'] = opts[:'skip_count'] if !opts[:'skip_count'].nil?\n query_params[:'maxItems'] = opts[:'max_items'] if !opts[:'max_items'].nil?\n query_params[:'nodeType'] = opts[:'node_type'] if !opts[:'node_type'].nil?\n query_params[:'include'] = @api_client.build_collection_param(opts[:'include'], :csv) if !opts[:'include'].nil?\n query_params[:'orderBy'] = @api_client.build_collection_param(opts[:'order_by'], :csv) if !opts[:'order_by'].nil?\n query_params[:'fields'] = @api_client.build_collection_param(opts[:'fields'], :csv) if !opts[:'fields'].nil?\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n local_header_accept = ['application/json']\n local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result\n\n # HTTP header 'Content-Type'\n local_header_content_type = ['application/json']\n header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['basicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'NodePaging')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: QueriesApi#find_nodes\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def nodes\r\n params = {\r\n method: :get,\r\n url: '/project/nodes',\r\n params: { prjUUID: @uuid }\r\n }\r\n @session.request(**params).perform!['nodes']\r\n end", "def find_available_node\n node_name=nil\n nodes = JSON.parse http_get(@node_list_endpoint)\n nodes[\"computer\"].each do |i|\n if i[\"offline\"]\n node_name=i[\"displayName\"]\n break\n end\n end\n\n return node_name\nend", "def check_chef(hostname)\n knife = Chef::Knife.new\n knife.config[:config_file] = File.join(ENV['HOME'], '.chef', 'knife.rb')\n knife.configure_chef\n search_query = Chef::Search::Query.new\n result = search_query.search(:node, \"name:#{hostname}\")\n \n if result.last > 0\n puts msg = \"Chef already has node #{hostname} registered. Skipping\"\n @logger.warn(msg)\n return false\n end\n return true\nend", "def find_available_node\n node_name=nil\n nodes = JSON.parse http_get(@node_list_end_point)\n nodes[\"computer\"].each do |i|\n if i[\"offline\"]\n node_name=i[\"displayName\"]\n break\n end\n end\n\n return node_name\nend", "def index\n @node = Fedora.rest('rest/')\n end", "def search_for(host, options = T.unsafe(nil)); end", "def watch_nodes(opts = {})\n @conn.watch_nodes(opts)\n end", "def get_inflated_node_list\n Chef::Node.list(true)\n end", "def getmyhostname\n mydata = node['private-chef']['backends'].\n merge(node['private-chef']['frontends']).\n select { |k,v| k == node.name }.values.first\n mydata['hostname']\nend", "def find_by(type, filter, single = true, &block)\n nodes = []\n env = node.chef_environment\n if node.public_send(Inflections.pluralize(type.to_s)).include? filter\n nodes << node\n end\n if !single || nodes.empty?\n search(:node, \"#{type}:#{filter} AND chef_environment:#{env}\") do |n|\n nodes << n\n end\n end\n\n if block_given?\n nodes.each { |n| yield n }\n else\n single ? nodes.first : nodes\n end\n end", "def check_nodes(node)\n nodes = []\n all_nodes = get_consul_members\n if (node.downcase != \"all\")\n nodes << node if all_nodes.include? node\n else\n nodes = all_nodes\n end\n return nodes\n end", "def nodes\n get_chef_files_absolute_paths nodes_path\n end", "def nodes\n @conn.nodes\n end", "def chef_node\n return @chef_node unless @chef_node.nil?\n @chef_node = cluster.find_node(fullname) || false\n end", "def nodes_live?(host, port, ip_list, timeout_sec)\n params = {\n :action => \"CLUSTERSTATUS\"\n }\n sleep_time_sec = 10\n attempts = timeout_sec/sleep_time_sec\n all_nodes_live = false\n while attempts >= 0 do\n begin\n live_nodes = []\n Chef::Log.info(\"Getting live nodes. Remaining attempts : #{attempts}\")\n attempts = attempts - 1\n cluster_status_resp = solr_collection_api(host, port, params)\n cluster_live_nodes = cluster_status_resp[\"cluster\"][\"live_nodes\"]\n cluster_live_nodes.each do |live_node|\n ipaddress = live_node.split(\":\")[0]\n live_nodes.push ipaddress\n end\n Chef::Log.info(\"live_nodes = #{live_nodes}\")\n result = (ip_list-live_nodes)\n if result.empty?\n all_nodes_live = true\n break\n else\n Chef::Log.info(\"Nodes not live : #{result}\")\n end\n rescue => e\n Chef::Log.info(\"Error while getting live nodes : #{e.message}\")\n Chef::Log.info(\"Retry getting live nodes after #{sleep_time_sec} seconds\")\n sleep sleep_time_sec\n end\n end\n return all_nodes_live\n end", "def fetch_search_results(context)\n\n params = @params\n site_id = context['__site_id']\n\n matching_ids = Node.search_ids do\n\n # Site ID\n with :site_id, site_id\n\n # Node classification\n if params['classification']\n with :classification, params['classification']\n end\n\n # Parent\n if params['scope_to']\n parent_scope = context[params['scope_to']]\n with :parent_uri, parent_scope['uri']\n elsif params['parent_uri']\n with :parent_uri, params['parent_uri']\n end\n\n # Ordering\n order_by_fields = params['order_by'].blank? ? [] : params['order_by'].split(',')\n order_by_fields.each do |order_by_field|\n\n field_name, direction = order_by_field.gsub(/[\"']/, '').strip.split(' ', 2)\n direction = 'asc' if direction.blank?\n order_by field_name.to_sym, direction.to_sym\n\n end\n\n # Limit\n if params['limit']\n paginate :page => 1, :per_page => params['limit']\n end\n\n end\n\n results = []\n matching_ids.each do |id|\n\n node = Rails.cache.fetch \"node_id:#{site_id}:#{id}\" do\n Node.where(:site_id => site_id).find(id).to_liquid\n end\n results << node\n\n end\n\n results\n\n end", "def watch_nodes(opts = {})\n core_client.watch_nodes(opts)\n end", "def find_all_nodes(*args)\n raise NotImplementedError\n nodes = @database.all_nodes\n # TODO: design node finder syntax\n nodes\n end", "def scan_node(node, namespace, set_name, bin_names = nil, options = nil)\n scan_node_partitions(node, namespace, set_name, bin_names, options)\n end", "def find_all_nodes(*args)\n nodes = @nodes.find_all_nodes(*args)\n nodes.find_all { |n| context?(n) }\n end", "def nodes\n TestLab::Node.all\n end", "def nodes\n @cluster.nodes\n end", "def nodes()\n return SearchNodes.new(:node => self, :return_many => true)\n end", "def search_query(environment)\n items = [\"chef_environment:#{environment}\"]\n\n items += chef_attributes.collect do |key, value|\n key = key.gsub(/\\./, \"_\")\n \"#{attribute_escape(key)}:#{value}\"\n end\n\n items += roles.collect { |role| \"run_list:#{solr_escape('role['+role+']')}\" }\n items += recipes.collect { |recipe| \"run_list:#{solr_escape('recipe['+recipe+']')}\" }\n\n items.join(' AND ')\n end", "def search(node, qry)\n node.search(qry)\n end", "def search(params = {})\n http.get(\"/nfse\", params: filter(params)) do |response|\n respond_with_collection(response)\n end\n end", "def get_node( node_id, pages=1 )\n items = []\n 1.upto( pages ).each do |item_page|\n response = Amazon::Ecs.item_search( nil, :browse_node => node_id, :search_index => 'Books', \n :response_group => 'Large,Reviews,Similarities', :item_page => item_page, \n :power => 'binding:paperback or hardcover', :sort => 'reviewrank' ) # salesrank also possible\n response.items.each do |item|\n items << parse_item( item )\n end\n end\n return items\n end", "def list_ks_fusion_vms(options)\n options['search'] = \"rhel|centos|oel\"\n list_fusion_vms(search_string)\n return\nend", "def node(id, params = {})\n get \"nodes/#{id}\", {query: params}\n end", "def aws_discovery_bootstrap\n Chef::Log.info(\"etcd_service[#{ new_resource.name }] Setting node_name to #{ node['ec2']['instance_id'] }\")\n new_resource.node_name(node['ec2']['instance_id'])\n new_resource.client_host(node['ec2']['local_hostname'])\n new_resource.peer_host(node['ec2']['local_hostname'])\n\n ## Set our own tags _before_ waiting for peers.\n tag_resource = aws_resource_tag(node['ec2']['instance_id'])\n tag_resource.tags new_resource.aws_tags\n tag_resource.run_action(:update)\n tag_resource.action(:nothing)\n\n aws_wait_for_peers\n end", "def osops_search(\n search_string, # recipe or role name\n one_or_all=:one,# return first node found or a list of nodes?\n # if set to :all a list will be returned\n # even if only one node is found.\n include_me=true,# include self in results\n order=[:role, :recipe], # if only one item is to be returned and\n # there are results from both the role\n # search and the recipe search, pick the\n # first item from the list specified here.%\n # must be :recipe or :role\n safe_deref=nil, # if nil, return node(s), else return\n # rcb_safe_deref(node,safe_deref)\n current_node=nil,\n options = {}\n )\n\n # Next refactor, move options to first/only param\n # Passing options from other methods to override search params\n options = {\n :search_string => search_string,\n :one_or_all => one_or_all,\n :include_me => include_me,\n :order => order,\n :safe_deref => safe_deref,\n :current_node => current_node\n }.merge(options)\n\n search_string = options[:search_string]\n one_or_all = options[:one_or_all]\n include_me = options[:include_me]\n order = options[:order]\n safe_deref = options[:safe_deref]\n current_node = options[:current_node]\n\n debug(\"Osops_search: search_string:#{search_string}, one_or_all:#{one_or_all},\"\\\n + \"include_me:#{include_me}, order:#{order}, safe_deref:#{safe_deref}\")\n results = {\n :recipe => [],\n :role => [],\n :tag => []\n }\n\n current_node ||= node\n\n for query_type in order\n if include_me and current_node[\"#{query_type}s\"].include? search_string\n debug(\"node #{current_node} contains #{query_type} #{search_string}, so adding node to results\")\n results[query_type] << current_node\n break if one_or_all == :one # skip expensive searches if unnecessary\n end\n\n search_string.gsub!(/::/, \"\\\\:\\\\:\")\n query = \"#{query_type}s:#{search_string} AND chef_environment:#{current_node.chef_environment}\"\n debug(\"osops_search query: #{query}\")\n result, _, _ = Chef::Search::Query.new.search(:node, query)\n results[query_type].push(*result)\n break if one_or_all == :one and results.values.map(&:length).reduce(:+).nonzero?\n end #end for\n\n #combine results into prioritised list\n return_list = order.map { |search_type| results[search_type] }.reduce(:+)\n\n #remove duplicates\n return_list.uniq!(&:name)\n\n #remove self if returned by search but include_me is false\n return_list.delete_if { |e| e.name == current_node.name } if not include_me\n\n if not safe_deref.nil?\n # result should be dereferenced, do that then remove nils.\n debug(\"applying deref #{safe_deref}\")\n return_list.map! { |nodeish| rcb_safe_deref(nodeish, safe_deref) }\n return_list.delete_if { |item| item.nil? }\n end\n\n debug(\"ospos_search return_list: #{return_list}\")\n\n if one_or_all == :one\n #return first item\n return_list.first\n else\n #return list (even if it only contains one item)\n return_list\n end\n end", "def query_by_ipaddress(ipaddress)\n query = {\"query\" => \"SELECT NodeName, NodeID FROM Orion.Nodes WHERE IPAddress=@ipaddr\", \"parameters\" => {\"ipaddr\" => \"#{ipaddress}\"}}\n do_http_request(@querypath, query)\n end", "def searches\n wrapping!(\n search(\n root_uri,\n data_raw.to_s.gsub('=>', ':')\n )\n )\n end", "def node_election(role, tag, chef_environment = nil)\n chef_environment = chef_environment || node.chef_environment\n master = search(:node, \"run_list:role\\\\[#{role}\\\\] AND \\\n chef_environment:#{chef_environment} AND \\\n tags:#{tag}\") || []\n if master.empty?\n nodes = search(:node, \"run_list:role\\\\[#{role}\\\\] AND \\\n chef_environment:#{chef_environment}\") || []\n nodes = nodes.sort_by { |node| node.name } unless nodes.empty?\n if nodes.empty? or node.name.eql?(nodes.first.name)\n node.tags << tag unless node.tags.include?(tag)\n node.save\n end\n\n if nodes.empty?\n return node\n end\n\n return nodes.first\n else\n return master.first\n end\nend", "def get_registered_nodes\n update_nodes\n @registered_nodes\n end", "def discover_items(node=nil)\n iq = connection.iq_stanza({'to'=>jid.to_s}, x('query', 'xmlns' => Namespaces::DiscoverItems))\n send_iq_stanza_fibered iq\n end", "def dispatch\n @nodes.each do |node|\n conn = begin\n Train.create('ssh', host: node, port: 22, user: 'Administrator@cerny.cc', key_files: '/var/opt/delivery/workspace/.ssh/id_rsa').connection\n rescue\n Train.create('ssh', host: node, port: 22, user: 'root', key_files: '/var/opt/delivery/workspace/.ssh/id_rsa').connection\n end\n result = conn.run_command(@command)\n (result.exit_status.eql?(0) ? @results['succeeded'] << node : @results['failed'] << node)\n puts result.stdout\n puts result.stderr\n # @results.stdout << result.stdout\n # @results.stderr << result.stderr\n conn.close\n end\n end", "def fetch_nodes(nodes, dns_cache)\n ret = []\n nodes.each_with_index do |item, index|\n ip, port = item\n host = dns_cache.fetch(ip) {\n |missing_ip|\n host = Resolv.getname(missing_ip)\n dns_cache[ip] = host\n host\n }\n name = \"#{host}:#{port}\"\n role = index == 0 ? 'master' : 'slave'\n node = {\n :host => host, :port => port,\n :name => name, :ip => ip,\n :role => role\n }\n ret << node\n end\n ret\n end", "def find_nodes(term, opts = {})\n data, _status_code, _headers = find_nodes_with_http_info(term, opts)\n return data\n end", "def get_node_id_by_name(name, keyname, secret)\n\tget_node_cmd = \"#{node[:zendserver][:zsmanage]} cluster-list-servers -N #{keyname} -K #{secret} -U http://#{node[:hostname]}:10081/ZendServer/\"\n\tp = shell_out(get_node_cmd)\n\tp.stdout.split(/\\n/).grep(/#{name}/)[0].split(/\\t/)[0]\nend", "def where(query)\n components = query.match(NODE_QUERY_SYNTAX)\n\n raise BadReferenceError, \"for reference: #{query}\" unless components\n search_node_components(components)\n end", "def update_nodes\n mongo_driver = Kymera::MongoDriver.new(address, port, database, 'nodes')\n @registered_nodes = mongo_driver.get_collection('nodes')\n end", "def nodes\n # Find the nodes that were down but are ready to be refreshed, or those\n # with stale connection information.\n needs_refresh, available = seeds.partition do |node|\n refreshable?(node)\n end\n\n # Refresh those nodes.\n available.concat(refresh(needs_refresh))\n\n # Now return all the nodes that are available and participating in the\n # replica set.\n available.reject{ |node| node.down? }\n end", "def node\n @node ||=\n begin\n node = Chef::Node.new(chef_server_rest: client_rest)\n node.name(node_name)\n node.run_list(normalized_run_list)\n node.normal_attrs = first_boot_attributes if first_boot_attributes\n node.environment(environment) if environment\n node.policy_name = policy_name if policy_name\n node.policy_group = policy_group if policy_group\n (config[:tags] || []).each do |tag|\n node.tags << tag\n end\n node\n end\n end", "def physical_servers_inside_rack(rack)\n rack.nodeList.map { |node| node[\"itemInventory\"] }\n end", "def cluster() node[:cluster_name] ; end", "def search_node(ip)\n found = nil\n @known_nodes.each do |node|\n if node.is_you? ip\n found = node\n end\n end\n return found\n end", "def list_all_shards(args = {}) \n get(\"/shards.json/\", args)\nend", "def node\n Chef.run_context.node\n end", "def get_true_node_objects get_all_nodes=false\r\n nodes, all_nodes, names, iter_arr, file_cache_nodes, h = [],[],[],[],[],{}\r\n\r\n @config['chef_nodes'] = @config['ridley'].node.all\r\n\r\n @config['helper'].completion_rate? 0, __method__\r\n\r\n file_cache_nodes = @config['filesystem'].check_nodes_file_cache if @config['filesystem'].compare_file_node_cache_against_chef_nodes('equal')\r\n\r\n @config['chef_nodes'].each do |n|\r\n true_obj = if !file_cache_nodes.empty? && @config['parser'].array_of_nodes_contains_node_name?(file_cache_nodes, n.name)\r\n file_cache_nodes[@config['parser'].index_of_node_name_in_array_of_nodes(file_cache_nodes, n.name)]\r\n else\r\n @config['filesystem'].cleanup_file_caches('current-nodes')\r\n\r\n @config['ridley'].node.find(n.name)\r\n end\r\n\r\n iter_arr << n.name\r\n\r\n progress_value = (( iter_arr.length.to_f/@config['chef_nodes'].length.to_f )*100 ).floor\r\n\r\n @config['helper'].completion_rate? progress_value, __method__\r\n\r\n all_nodes << true_obj\r\n\r\n next if !get_all_nodes && true_obj.chef_environment != @options['env'] && true_obj.chef_environment != '_default'\r\n\r\n if get_all_nodes\r\n h[n.name] = true_obj\r\n names << n.name\r\n\r\n next\r\n end\r\n\r\n if @options['role'] == 'all'\r\n next if true_obj.chef_environment == '_default'\r\n\r\n h[n.name] = true_obj\r\n names << n.name\r\n\r\n next\r\n end\r\n\r\n if @options['node_name'] && true_obj.name == @options['node_name']\r\n h[n.name] = true_obj\r\n names << n.name\r\n\r\n next\r\n end\r\n\r\n if @options['address'] && true_obj.public_ipaddress == @options['address']\r\n h[n.name] = true_obj\r\n names << n.name\r\n\r\n next\r\n end\r\n\r\n unless ( @options['address'] || @options['node_name'] )\r\n if true_obj.run_list.include?(\"role[#{ @options['role'] }]\")\r\n h[n.name] = true_obj\r\n names << n.name\r\n\r\n next #not needed here but good to keep in mind\r\n end\r\n end\r\n end\r\n\r\n names.sort.each { |name| nodes << h[name] }\r\n\r\n @config['filesystem'].write_nodes_file_cache(all_nodes) unless @config['filesystem'].compare_file_node_cache_against_chef_nodes('equal')\r\n\r\n puts(\"\") unless @options['quiet']\r\n \r\n nodes\r\n end", "def find_available_hosts(folder, datastore)\n hosts = find_compute_resources(folder)\n hosts.select! { |host| host.datastore.include?(datastore) }\n hosts\nend", "def search_node_in_roles( roles )\n roles.each do |r|\n Chef::Log.info \"Searching for '#{self[:fqdn]}' in the '#{r}' role.\"\n if self.role?(r)\n # return true for the first match\n Chef::Log.info \"Whitelisting: Found node '#{self[:fqdn]}' via role '#{r}'.\"\n return true\n end\n end\n\n return false\n\n end", "def index\n Chef.all\n end", "def get_node_details(name_list)\n rpc_get_facts_direct(name_list)\n end", "def fetch_databag_tenants\n db_tenants = Array.new\n chef_api_connect.search.query(:foundation, '*:*', start: 0).rows.each do |tenant|\n db_tenants << tenant['raw_data']['id']\n end\n return db_tenants\nend", "def get_solrcloud_instances_by_action(node, action)\n if !node['workorder']['payLoad'].has_key?(\"SolrClouds\")\n puts \"***FAULT:FATAL=SolrClouds payload not found, you must pull the design.\"\n e = Exception.new(\"no backtrace\")\n e.set_backtrace(\"\")\n raise e \n end\n solr_clouds = node['workorder']['payLoad']['SolrClouds']\n Chef::Log.info(\"Total solrcloud instances in the payload : #{solr_clouds.size()}\")\n solr_clouds_actioned = solr_clouds.select { |solr_cloud| solr_cloud['rfcAction'] != nil && solr_cloud['rfcAction'].eql?(action) }\n Chef::Log.info(\"Total solrcloud instances with action #{action} in the deployment : #{solr_clouds_actioned.size()}\")\n return solr_clouds_actioned\n end", "def find_node(nd_name)\n chef_nodes.find{|nd| nd.name == nd_name }\n end", "def find_optional_node_by_criteria(stack, include_criteria=nil, exclude_criteria=nil)\n search_query = \"stack:#{stack}\"\n search_query = \"#{search_query} AND #{include_criteria}\" if include_criteria\n search_query = \"#{search_query} AND NOT name:#{node.name}\" unless exclude_criteria\n search_query = \"#{search_query} AND NOT (name:#{node.name} OR #{exclude_criteria})\" if exclude_criteria\n\n Chef::Log.debug \"find_optional_node_by_criteria(#{stack}, #{include_criteria}, #{exclude_criteria}) => search query: '#{search_query}'\"\n\n nodes = search(:node, \"#{search_query}\")\n nodes.flatten!\n\n # Warn if no node has been found in the stack\n Chef::Log.warn \"The search query '#{search_query}' returned 0 results.\" if nodes.size == 0\n # Fail if mutiple nodes have been found in the stack\n raise \"Multiple machines that match the search query '#{search_query}' were found in the #{stack} environment... This is not allowed. Cleanup of nodes may be necessary.\" if nodes.size > 1\n return nodes[0]\nend", "def get_node_info(treenodeid, _show_list = true)\n @nodetype, id = parse_nodetype_and_id(valid_active_node(treenodeid))\n # resetting action that was stored during edit to determine what is being edited\n @sb[:action] = nil\n\n # Reset session to same values as first time in\n session[:adv_search][\"Service\"] = session[:edit] = nil if session[:adv_search] && params[:action] != 'x_search_by_name'\n\n case TreeBuilder.get_model_for_prefix(@nodetype)\n when \"Service\"\n show_record(id)\n drop_breadcrumb(:name => _('Services'), :url => '/service/explorer') if @breadcrumbs.empty?\n @right_cell_text = _(\"Service \\\"%{name}\\\"\") % {:name => @record.name}\n @no_checkboxes = true\n @gtl_type = \"grid\"\n @items_per_page = ONE_MILLION\n @view, @pages = get_view(Vm, :parent => @record, :parent_method => :all_vms, :all_pages => true) # Get the records (into a view) and the paginator\n when \"Hash\"\n case id\n when 'asrv'\n process_show_list(:named_scope => [[:retired, false], :displayed])\n @right_cell_text = _(\"Active Services\")\n when 'rsrv'\n process_show_list(:named_scope => %i[retired displayed])\n @right_cell_text = _(\"Retired Services\")\n end\n when \"MiqSearch\", nil # nil if applying a filter from Advanced search - and @nodetype is root\n load_adv_search unless @nodetype == \"root\" # Select/load filter from Global/My Filters\n process_show_list\n @right_cell_text = _(\"All Services\")\n end\n @right_cell_text += _(\" (Names with \\\"%{search_text}\\\")\") % {:search_text => @search_text} if @search_text.present? && @nodetype != 's'\n @right_cell_text += @edit[:adv_search_applied][:text] if x_tree && @edit && @edit[:adv_search_applied]\n end", "def get_node( node_id, pages=2 )\n items = []\n 1.upto( pages ).each do |item_page|\n response = Amazon::Ecs.item_search( nil, :browse_node => node_id, :search_index => 'Books', \n :response_group => 'Large,Reviews,Similarities,AlternateVersions', :item_page => item_page, \n :power => 'binding:paperback or hardcover', :sort => 'salesrank' ) # salesrank also possible\n response.items.each do |item|\n items << Book.new( item )\n end\n end\n return items\n end", "def get_nodes_by_role(role, includeme=true, options={})\n options = {\n :search_string => role,\n :include_me => includeme,\n :order => [:role],\n :safe_deref => nil,\n :current_node => nil,\n :one_or_all => :all\n }.merge(options)\n opsit_search(options)\n end", "def get_node(node_name)\n Chef::Config.from_file(\"/etc/chef/client.rb\")\n Chef::Config[:client_key] = \"/etc/chef/client.pem\"\n Chef::Config[:http_retry_count] = 5\n node = Chef::Node.load(node_name)\n end" ]
[ "0.72092086", "0.6907744", "0.6647727", "0.65987945", "0.6517916", "0.64821213", "0.63215536", "0.6308564", "0.62858826", "0.6210898", "0.6196186", "0.6189882", "0.61747134", "0.6170602", "0.61280453", "0.60679644", "0.6048448", "0.60415477", "0.5994073", "0.59644383", "0.5953688", "0.59449816", "0.5939358", "0.59326553", "0.5928031", "0.5894995", "0.58810145", "0.58795935", "0.5876981", "0.58566755", "0.5849483", "0.5837743", "0.58342016", "0.5828727", "0.5807053", "0.5794991", "0.57924414", "0.5787789", "0.57816356", "0.57417184", "0.5729195", "0.5720726", "0.57185227", "0.57175946", "0.5708411", "0.5654569", "0.5641671", "0.56405646", "0.56346524", "0.5620326", "0.55950475", "0.5587385", "0.558073", "0.5567018", "0.55583346", "0.55227184", "0.5506182", "0.5496508", "0.5486039", "0.54826736", "0.545804", "0.54380083", "0.54324496", "0.54323775", "0.5417128", "0.5381737", "0.53768575", "0.5372404", "0.53716975", "0.53658766", "0.5360352", "0.5356872", "0.53526074", "0.53472364", "0.5344009", "0.53420484", "0.5338013", "0.5337503", "0.5323412", "0.5311556", "0.5310829", "0.53097504", "0.5306144", "0.5303453", "0.5290164", "0.5281501", "0.5279815", "0.52792585", "0.527704", "0.5264858", "0.5243127", "0.5239024", "0.52288854", "0.5227781", "0.52215797", "0.5215176", "0.5209281", "0.5200312", "0.51993436", "0.51987904", "0.51920223" ]
0.0
-1
Returns the first packet in +dump+
def packet dump Capp.offline(dump).loop.first end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_first\r\n if @head \r\n return @head.data\r\n else \r\n return nil\r\n end\r\n end", "def get_first\n return nil if !@head\n return @head.data\n end", "def get_first\n return nil if @head.nil?\n\n return @head.data\n end", "def get_first\n return nil if @head.nil?\n\n return @head.data\n end", "def get_first\r\n return @head ? @head.data : nil\r\n end", "def get_first\n return @head ? @head.data : nil\n end", "def get_first\n return head ? head.data : nil\n end", "def get_first\n return nil if @head.nil?\n return @head.data\n end", "def first_hop()\n @hops.find { |hop| !hop.ip.nil? && hop.ip != \"0.0.0.0\" }\n end", "def get_first\n if @head == nil\n return nil\n else\n return @head.data\n end\n end", "def get_first\n return nil if head.nil?\n return head.data\n end", "def get_first\n return @head.data if @head\n return @head\n end", "def get_first\n return @head if @head.nil?\n\n return @head.data\n end", "def get_first\n return @head.nil? ? nil : @head.data\n end", "def get_first\n return @head.nil? ? nil : @head.data\n end", "def get_first\n \n return nil if @head.nil?\n return @head.data\n \n end", "def get_first\n current = @head\n return nil if current.nil?\n \n return @head.data\n end", "def first\n\t\t@head.info if !@head.nil?\n\tend", "def get_first\n @head.nil? ? nil : @head.data\n end", "def first_line\n line_from_ip(0)\n end", "def get_first\n @head == nil ? nil : @head.data\n end", "def get_first\r\n @head&.data\r\n end", "def peek\n first.nil? ? nil : first.data\n end", "def peek\n @data[0]\n end", "def read_packet; end", "def first\n contents[0]\n end", "def poll_next_packet; end", "def first\n\n wi(fetch_all({}).first)\n end", "def get_packet\n\t\t\t\tfirst_number = read(1).unpack(\"C\")[0]\n\t\t\t\t# get the 'mask' property\n\t\t\t\tpacket_mask = first_number >> 6\n\t\t\t\t# get the 'frame1' property\n\t\t\t\tframe_number = first_number & 0x3F\n\t\t\t\tif frame_number == 0\n\t\t\t\t\t# if frame1 is equal to 0 then 'frame' is equal to 'frame2'\n\t\t\t\t\tframe_number = read(1).unpack(\"C\")[0]\n\t\t\t\telsif frame_number == 1\n\t\t\t\t\t# if frame1 is equal to 1 then 'frame' is equal to 'frame3'\n\t\t\t\t\tframe_number = read(2).unpack(\"n\")[0]\n\t\t\t\tend\n\t\t\t\t# init a 'frame stream' if it doesn't exist yet\n\t\t\t\tif ! @frames_in.has_key? frame_number\n\t\t\t\t\t@frames_in[frame_number] = Frame.new(0,0,0,0)\n\t\t\t\t\tif packet_mask != 0\n\t\t\t\t\t\traise StandardError, \"packet error\"\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\t# for logging purpose\n\t\t\t\t@bytes_in += 1\n\t\t\t\t\n\t\t\t\t# reads the 'time', 'datasize', 'rtmpdatatype' and 'streamid' properties from the socket\n\t\t\t\t# and put them into the 'frame stream' archive\n\t\t\t\t\n\t\t\t\tcase packet_mask\n\t\t\t\twhen 0\n\t\t\t\t\t@frames_in[frame_number].timer = getMediumInt()\n\t\t\t\t\t@frames_in[frame_number].size = getMediumInt()\n\t\t\t\t\t@frames_in[frame_number].data_type = read(1).unpack(\"C\")[0]\n\t\t\t\t\t@frames_in[frame_number].obj = read(4).unpack(\"N\")[0]\n\t\t\t\t\t@bytes_in += 11\n\t\t\t\twhen 1\n\t\t\t\t\t@frames_in[frame_number].timer = getMediumInt()\n\t\t\t\t\t@frames_in[frame_number].size = getMediumInt()\n\t\t\t\t\t@frames_in[frame_number].data_type = read(1).unpack(\"C\")[0]\n\t\t\t\t\t@bytes_in += 7\n\t\t\t\twhen 2\n\t\t\t\t\t@frames_in[frame_number].timer = getMediumInt()\n\t\t\t\t\t@bytes_in += 3\n\t\t\t\twhen 3\n\t\t\t\t\n\t\t\t\telse\n\t\t\t\t\n\t\t\t\tend\n\t\t\t\t# fix the CONNECTION_PACKET bug when its size is larger than 128 bytes (see caution 4.4.6)\n\t\t\t\tif ! @connected\n\t\t\t\t\tdata_length = @frames_in[frame_number].size\n\t\t\t\t\n\t\t\t\t\tif data_length < 129\n\t\t\t\t\t\tdata = read(data_length)\n\t\t\t\t\telsif data_length == 129\n\t\t\t\t\t\tdata = read(data_length+1)\n\t\t\t\t\t\tdata = data[0..-2]\n\t\t\t\t\telse data_length > 129\n\t\t\t\t\t\tdata = read(data_length+1)\n\t\t\t\t\t\tdata = data[0..127] << data[129..-1]\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\tdata = read(@frames_in[frame_number].size)\n\t\t\t\tend\n\t\t\t\t# for logging purpose\n\t\t\t\t@bytes_in += data.length\n\t\t\t\t@msg_in += 1\n\t\t\t\t# return a RTMP_PACKET with all its properties (implicit ones included)\n\t\t\t\treturn RTMPPacket.new(\tframe_number,\n\t\t\t\t\t\t\t@frames_in[frame_number].timer,\n\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\t@frames_in[frame_number].data_type,\n\t\t\t\t\t\t\t@frames_in[frame_number].obj)\n\t\tend", "def first\n\t\traise \"ContainerEmpty\" if @head.nil?\n\t\t@head\n\tend", "def getPacket(socket)\n\tpacket = Packet.new\n\tsize = 128\n\tbegin\n\t\tpacket = Packet.new(socket.recvfrom_nonblock(size)[0])\n\trescue Errno::EAGAIN\n\t\tIO.select([socket])\n\t\tretry\n\tend\n\treturn packet\nend", "def extract_opcode(dump)\n dump.each_line do |line|\n # If the line is a line of disassembled code...\n m = /\\A\\s+[0-9a-f]+:/i.match line\n\n # Extract the opcode field and remove any internal spaces\n return line.split(/\\t/)[1].split.join unless m.nil?\n end\nend", "def first\n @head\n end", "def next_message\n socket.get_packet\n end", "def get_first\r\n # if the list is empty, head is nil\r\n if @head.nil?\r\n return nil\r\n else \r\n value = @head.data\r\n return value\r\n end\r\n end", "def peek\n return nil if empty?\n _decode_message(self.first)\n end", "def packet(pkt)\n if ((pkt.ip_mf? or pkt.ip_off > 0 ))\n$stderr.puts \"*** Fragmented packet #{@event_collector.pkt_count}\"\n @event_collector.send(:ip_fragmented_packet) do\n { :src_ip => pkt.src, :dst_ip => pkt.dst, :ip_id => pkt.ip_id,\n :ip_proto => pkt.ip_proto, :ip_off => pkt.ip_off,\n :ip_body => pkt.ip_data\n }\n end\n end\n end", "def getPacket(socket)\n\tpacket = Packet.new\n\tsize = 2048 + 6\n\tbegin\n\t\tpacket = Packet.new(socket.recvfrom_nonblock(size)[0])\n\trescue Errno::EAGAIN\n\t\tIO.select([socket])\n\t\tretry\n\tend\n\n\treturn packet\nend", "def first\n @poss[0]\n end", "def first\n matches.first\n end", "def first\n header_data\n end", "def first\n self.take(1)[0]\n end", "def sms_deliver_first_octet\n octet = 0\n octet |= 0x04 unless @opts[:more_to_send]\n octet |= 0x80 if @opts[:has_udh]\n octet.chr\n end", "def getFirstRecordOffset(hdr)\n # Find the cursor record and get first rec from there.\n # hdr[:end_offset] should point to the offset of the EOF record. If the dirty flag\n # is set this is likely to have moved, but should be in front of it, so start the search there.\n pos = findCursorRecord(hdr[:end_offset])\n pos = findCursorRecord(0) if pos.nil?\n raise \"Win32 Eventlog cursor record not found.\" if pos.nil?\n\n EVENTLOGEOF.decode(read_buffer(pos - 4, EVENTLOGEOF.size))\n end", "def display_drb packet\n return unless @running\n return unless stream = packet_stream(packet)\n\n source = packet.source\n\n message = DRbDump::Message.from_stream self, packet, stream\n\n message.display\n\n stop if @statistics.drb_messages_sent >= @count\n\n @statistics.drb_packet_count += 1\n @drb_streams[source] = true\n @incomplete_timestamps.delete source\n rescue DRbDump::Loader::TooLarge\n display_drb_too_large packet\n rescue DRbDump::Loader::Premature, DRbDump::Loader::DataError\n @incomplete_streams[source] = stream.string\n @incomplete_timestamps[source] ||= packet.timestamp\n rescue DRbDump::Loader::Error\n @drb_streams[source] = false\n end", "def peek\n head.data if head\n end", "def peek\n @b.each_byte {|b| return b }\n end", "def packet_stream packet # :nodoc:\n payload = packet.payload\n\n return if payload.empty?\n\n source = packet.source\n\n if previous = @incomplete_streams.delete(source) then\n payload = previous << payload\n elsif /\\A....\\x04\\x08/m !~ payload then\n @drb_streams[source] = false\n return\n end\n\n stream = StringIO.new payload\n stream.set_encoding Encoding::BINARY, Encoding::BINARY\n stream\n end", "def xmos_extract_opcode(dump)\n dump.each_line do |line|\n # If the line is a line of dissassembled code\n m = /\\A\\s+0x[0-9a-f]+:/i.match line\n\n # Extract the opcode field and remove any internal spaces\n return line.split(/:/)[1].split.join unless m.nil?\n end\nend", "def packet_source_addr\n return nil if !@packet_source_addr_bin\n @packet_source_addr_bin.unpack('C4').join('.')\n end", "def peek\n raise IndexError.new if @data.size == 0\n return @data[0]\n end", "def first() end", "def parse_tcpdump(line)\n data = line.split(\" \")\n\n # Check input data validation, null -> skip\n if (line == nil) then\n return (nil)\n end\n if (data == []) then\n return (nil)\n end\n\n src = data[2]\n dst = data[4]\n size = data[-1] \n\n tmp1 = src.split(\".\")\n tmp2 = dst.split(\".\")\n if (tmp1.length == 5) then\n # IPv4\n src_ip = tmp1[0,4].join(\".\")\n src_port = tmp1[4]\n dst_ip = tmp2[0,4].join(\".\")\n dst_port = tmp2[4]\n else\n # IPv6\n src_ip = tmp1[0]\n src_port = tmp1[1]\n dst_ip = tmp2[0]\n dst_port = tmp2[1]\n end\n\n return ([src_ip, src_port, dst_ip, dst_port, size])\nend", "def list_first(list)\n list.head.data unless list.head.nil?\nend", "def peek\n @store[0]\n end", "def peek_first\n raise 'No such element' if @size == 0\n @head.value\n end", "def peek\n @store[0]\n end", "def printpacketdata\n puts \"@@packetdata =>\" + @@packetdata.bytes.to_s\nend", "def packet_item\n @packet_item\n end", "def peek\n @tape[-1]\n end", "def first(n=nil)\n to_recv = n || 1\n received = []\n each do |m|\n received << m\n break if received.size == to_recv\n end\n n ? received : received.first\n end", "def peek\n if empty?\n nil\n else\n @stack.first\n end\n end", "def sniff(iface)\n pp 'Sniffing...'\n cap = Capture.new(:iface => iface, :start => true, :filter => 'src 192.168.0.7')\n cap.stream.each do |p|\n pp 'Got one!'\n packet = Packet.parse p\n pp packet\n #$cmd = xor packet.payload\n pp packet.payload\n #value = `#{cmd}`\n\n pp packet.ip_dst_readable\n end\n\n\nend", "def first\n self.slice(0)\n end", "def first n\n @b.byteslice 0, n\n end", "def top_card\n return nil if @discard.empty?\n @discard.last.to_s\n end", "def read_packet\n length = @socket.read( 4 ).unpack( \"N\" ).first - 1\n type = @socket.read( 1 ).unpack( \"C\" ).first\n reader = @buffers.reader( @socket.read( length ) )\n return type, reader\n end", "def first\n @head.val\n end", "def message\n\t\t\t@packet.message\n\t\tend", "def packet(pkt)\n super(pkt)\n \n # Only process packets with length right now\n return nil unless pkt.udp_data.length > 0\n \n # Determine the packet's direction (up == src -> dst)\n dir = pkt.src.to_i < pkt.dst.to_i ? :up : :down\n\n # First, identify if this is a new stream or part of one on which we are\n # already keeping state.\n state = identify_state(pkt, :udp, false)\n state.udp_init(pkt, @event_collector) unless state.layer_4\n @protos.parse(pkt.udp_data, state, dir)\n end", "def peek()\n puts @head.data\n end", "def peek()\n puts @head.data\n end", "def head(bytes)\n read(bytes)\n end", "def first\n _id, entry = @redis.xrange(key, '-', '+', count: 1).first\n entry\n end", "def find_first(selector, data)\n data = @data unless data\n results = (data/selector)\n if results and results.first\n results.first.inner_html.strip\n else\n nil\n end\n end", "def first\n items.compact.first\n end", "def peek\n raise QueueUnderflow if empty?\n @info[0]\n end", "def first\n to_a.first\n end", "def peek\n @stack[0]\n end", "def get_entry(pEntry)\n return client.railgun.memread(pEntry,41).unpack('VVVVVVVVVvCCC')\n end", "def first\n self[0]\n end", "def first\n self[0]\n end", "def first\n @enumerable.first\n end", "def fetch_byte ( addr )\n\tif addr < @base || addr > @limit\n\t return nil\n\tend\n\tindex = addr - @base\n\tdata = @im[index].unpack \"C\"\n\treturn data[0]\n end", "def first\r\n self[0]\r\n end", "def decode_first_from_stream(stream, schema_name: nil, namespace: @namespace)\n data = decode_all_from_stream(stream, schema_name: schema_name, namespace: namespace)\n data.first\n end", "def read_first_line(file)\n `head -n 1 #{file}`.strip\nend", "def peekMin()\n @store[1]\n end", "def packets; end", "def top()\n return @pop_queue.first\n end", "def peek_first_item\n stack = []\n node, stack = *first_below(@root, stack)\n return nil unless node\n return node, stack\n end", "def first\n all[0]\n end", "def receive_packet\n\t\treturn parser.recv(self.sock)\n\tend", "def dissamble_packet(packet)\n packet_bytes = packet.bytes.to_a\n # debugger\n @thermo_address = packet_bytes[0] & 0b01111111\n @host_or_reply = packet_bytes[0][7]\n @message_type = packet_bytes[1] & 0b1111\n @data_length = (packet_bytes[1] & 0b11110000) / 0b10000\n @data = packet[2,@data_length]\n @checksum = packet[packet.length-1]\n @valid = validate_packet(packet)\n end", "def node_first\n @head\n end", "def first\n ptr = C.LLVMGetFirstInstruction(@block)\n LLVM::Instruction.from_ptr(ptr) unless ptr.null?\n end", "def head\n return nil if @head.nil?\n @head.data\n end", "def first! n\n slice = @b.byteslice 0, n\n @b = @b.byteslice n, -1\n slice\n end", "def type\n\t\t\t@packet.type\n\t\tend", "def unpack1 format\n unpack(format).first\n end" ]
[ "0.59918964", "0.5966294", "0.59548736", "0.59548736", "0.5946803", "0.5924725", "0.5924533", "0.59197056", "0.59157085", "0.5864313", "0.58566505", "0.5840855", "0.58146584", "0.5809229", "0.5809229", "0.579712", "0.57777494", "0.5727662", "0.5702424", "0.56881046", "0.5649787", "0.56011", "0.55721396", "0.5541515", "0.5528559", "0.5476947", "0.54705244", "0.54577893", "0.54506844", "0.54421055", "0.54222107", "0.5402866", "0.5375686", "0.5373266", "0.5351545", "0.5318163", "0.53070587", "0.53065467", "0.5292501", "0.5277438", "0.5265584", "0.5242935", "0.5242762", "0.5213512", "0.5203713", "0.5203048", "0.51489234", "0.51361144", "0.5124717", "0.51208574", "0.5119973", "0.5116178", "0.51104337", "0.5108973", "0.5108502", "0.51047534", "0.5097922", "0.50935614", "0.5082388", "0.5062417", "0.5060014", "0.505506", "0.5037146", "0.50341684", "0.5016807", "0.5002194", "0.4992395", "0.4987895", "0.49869573", "0.49867907", "0.49854052", "0.49854052", "0.4983738", "0.49825442", "0.49714813", "0.49667856", "0.49599847", "0.49546605", "0.4949382", "0.49442667", "0.49162358", "0.49162358", "0.4909403", "0.49074605", "0.48989263", "0.48981667", "0.48918", "0.48902282", "0.4888819", "0.48702666", "0.48611245", "0.48573726", "0.48539737", "0.48532593", "0.48498264", "0.48362783", "0.48224577", "0.4818865", "0.4815123", "0.48034805" ]
0.70979226
0
Reads /proc/mounts and returns partition name of the device mounted at /. It returns a String. But if the info isn't available or /proc/mounts is not readable, it will return an empty frozen String.
def root find_root[0].to_s end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def device_of_mount(m)\n unless Pathname.new(m).mountpoint?\n Chef::Log.warn(\n \"#{m} is not a mount point - I can't determine its device.\",\n )\n return nil\n end\n node['filesystem2']['by_pair'].to_hash.each do |pair, info|\n # we skip fake filesystems 'rootfs', etc.\n next unless pair.start_with?('/')\n # is this our FS?\n next unless pair.end_with?(\",#{m}\")\n # make sure this isn't some fake entry\n next unless info['kb_size']\n return info['device']\n end\n Chef::Log.warn(\n \"#{m} shows as valid mountpoint, but Ohai can't find it.\",\n )\n return nil\n end", "def device_of_mount(m)\n fs = self.filesystem_data\n unless Pathname.new(m).mountpoint?\n Chef::Log.warn(\n \"fb_helpers: #{m} is not a mount point - I can't determine its \" +\n 'device.',\n )\n return nil\n end\n unless fs && fs['by_pair']\n Chef::Log.warn(\n 'fb_helpers: no filesystem data so no node.device_of_mount',\n )\n return nil\n end\n fs['by_pair'].to_hash.each do |pair, info|\n # we skip fake filesystems 'rootfs', etc.\n next unless pair.start_with?('/')\n # is this our FS?\n next unless pair.end_with?(\",#{m}\")\n # make sure this isn't some fake entry\n next unless info['kb_size']\n\n return info['device']\n end\n Chef::Log.warn(\n \"fb_helpers: #{m} shows as valid mountpoint, but Ohai can't find it.\",\n )\n nil\n end", "def get_1st_partition(device)\n # Resolves the real device name (ex. /dev/sdg)\n Chef::Log.info(\"Getting 1st partition for device: #{device}\")\n fs_check = Mixlib::ShellOut.new(\"lsblk -ln -o Name #{device}|awk 'NR==2'\")\n fs_check.run_command\n partition = \"/dev/\" + fs_check.stdout.strip\n Chef::Log.info(\"1st partition for device: #{device} is: #{partition}\")\n partition\nend", "def verify_mounted(partition)\n\treturn `grep partition /proc/mounts | wc -l`.chomp\nend", "def get_device_mount_point( incoming_path )\n mount_lines = `mount`\n raise EBSRemoteExecException.new(nil,$?,mount_lines) if $? != 0\n path = File.ftype(incoming_path) != 'directory'? File.dirname(incoming_path) : incoming_path\n device=nil\n longest = \"\"\n mount_lines.each_line {|line|\n match = line =~ /(.+)\\son\\s(.+?)\\s.*/\n candidate = $2.strip\n candidate_device = $1.strip\n # Keep the longest prefix matching\n if match && path =~ /^#{candidate}/ && candidate.length > longest.length\n longest = candidate\n device = candidate_device\n end\n }\n unless device\n STDERR.puts \"Couldn't find the device for mount point #{path}\"\n Kernel.exit(-1)\n end\n device\n end", "def is_mounted?(device)\n system(\"grep -q '#{device}' /proc/mounts\")\nend", "def get_mount_path(filepath)\n cmd_exec(\"df \\\"#{filepath}\\\" | tail -1\").split(' ')[0]\n rescue\n raise \"Unable to get mount path of #{filepath}\"\n end", "def format_mount(partition, mount)\n\n # Partitions that we already have mounts set for.\n return nil if partition == '/dev/mapper/rootvg-slash'\n return nil if partition == '/dev/mapper/rootvg-var'\n return nil if partition == '/dev/mapper/rootvg-tmp'\n\n mount\nend", "def mountpoint\n 'dev/.osctl-mount-helper'\n end", "def list_partitions #by nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{print $1}'`.chomp.split\nend", "def mounts_info\n @mounts_info ||= vault_client.request(:get, \"/v1/sys/internal/ui/mounts\")\n rescue Vault::VaultError\n unable_to_determine_version\n raise\n end", "def mountpoints\n mtab = IO.readlines '/proc/mounts'\n mountpoints = mtab.map{ |line| line.split(/\\s+/)[1]}\n mountpoints.map!{ |mount| unescape(mount) }\n # Ignore common system mountpoints.\n mountpoints.reject!{ |mount| mount =~ /^\\/$/ }\n mountpoints.reject!{ |mount| mount =~ /^\\/(proc|sys|usr|boot|tmp|dev|var|bin|etc|lib).*/ }\n # Mount /run/media/* but ignore other /run/ mountpoints.\n mountpoints.reject!{ |mount| mount =~ /^\\/run.*/ unless mount =~ /^\\/run\\/(media.*)/ }\n\n # Add home dir.\n mountpoints << home\n end", "def get_partition_info\n # remove leading slash so it matches the packages.DU path\n remove_slash = true\n\n if !Stage.initial\n # read /proc/mounts as a list of maps\n # $[\"file\":\"/boot\", \"freq\":0, \"mntops\":\"rw\", \"passno\":0, \"spec\":\"/dev/sda1\", \"vfstype\":\"ext2\"]\n mounts = Convert.convert(\n SCR.Read(path(\".proc.mounts\")),\n :from => \"any\",\n :to => \"list <map <string, any>>\"\n )\n Builtins.y2milestone(\"mounts %1\", mounts)\n\n partitions = []\n Builtins.foreach(mounts) do |mpoint|\n name = Ops.get_string(mpoint, \"file\", \"\")\n if Builtins.substring(name, 0, 1) == \"/\" &&\n Builtins.substring(name, 0, 5) != \"/dev/\" && # filter out /dev/pts etc.\n Ops.get_string(mpoint, \"vfstype\", \"\") != \"rootfs\" # filter out duplicate \"/\" entry\n capacity = Pkg.TargetCapacity(name)\n if capacity != 0 # dont look at pseudo-devices (proc, shmfs, ...)\n used = Pkg.TargetUsed(name)\n partitions = Builtins.add(\n partitions,\n {\n \"name\" => name,\n \"free\" => Ops.subtract(capacity, used),\n \"used\" => used\n }\n )\n end\n end\n end\n Pkg.TargetInitDU(partitions)\n Builtins.y2milestone(\"get_partition_info: %1\", partitions)\n return deep_copy(partitions)\n end # !Stage::initial ()\n\n # remove the previous failures\n @failed_mounts = []\n\n # installation stage - Storage:: is definitely present\n # call Storage::GetTargetMap()\n targets = Convert.convert(\n WFM.call(\"wrapper_storage\", [\"GetTargetMap\"]),\n :from => \"any\",\n :to => \"map <string, map>\"\n )\n\n if targets == nil\n Builtins.y2error(\"Target map is nil, Storage:: is probably missing\")\n end\n\n if Mode.test\n targets = Convert.convert(\n SCR.Read(path(\".target.yast2\"), \"test_target_map.ycp\"),\n :from => \"any\",\n :to => \"map <string, map>\"\n )\n end\n\n target_partitions = []\n min_spare = 20 * 1024 * 1024 # minimum free space ( 20 MB )\n\n Builtins.foreach(targets) do |disk, diskinfo|\n part_info = Ops.get_list(diskinfo, \"partitions\", [])\n Builtins.foreach(part_info) do |part|\n Builtins.y2milestone(\"Adding partition: %1\", part)\n used_fs = Ops.get_symbol(part, \"used_fs\", :unknown)\n # ignore VFAT and NTFS partitions (bnc#)\n if used_fs == :vfat || used_fs == :ntfs\n Builtins.y2warning(\n \"Ignoring partition %1 with %2 filesystem\",\n Ops.get_string(part, \"device\", \"\"),\n used_fs\n )\n else\n free_size = 0\n\n if Ops.get(part, \"mount\") != nil &&\n Builtins.substring(Ops.get_string(part, \"mount\", \"\"), 0, 1) == \"/\"\n if Ops.get(part, \"create\") == true ||\n Ops.get(part, \"delete\") == false ||\n Ops.get(part, \"create\") == nil &&\n Ops.get(part, \"delete\") == nil\n Builtins.y2debug(\n \"get_partition_info: adding partition: %1\",\n part\n )\n\n # get free_size on partition in kBytes\n free_size = Ops.multiply(\n Ops.get_integer(part, \"size_k\", 0),\n 1024\n )\n free_size = Ops.subtract(free_size, min_spare)\n\n # free_size smaller than min_spare, fix negative value\n if Ops.less_than(free_size, 0)\n Builtins.y2milestone(\"Fixing free size: %1 to 0\", free_size)\n free_size = 0\n end\n\n used = 0\n if !(Ops.get_boolean(part, \"create\", false) ||\n Ops.get_boolean(part, \"format\", false))\n tmpdir = Convert.to_string(SCR.Read(path(\".target.tmpdir\")))\n tmpdir = Ops.add(tmpdir, \"/diskspace_mount\")\n SCR.Execute(\n path(\".target.bash\"),\n Builtins.sformat(\"test -d %1 || mkdir -p %1\", tmpdir)\n )\n\n # mount in read-only mode (safer)\n mount_options = [\"ro\"]\n\n # add \"nolock\" if it's a NFS share (bnc#433893)\n if used_fs == :nfs\n Builtins.y2milestone(\"Mounting NFS with 'nolock' option\")\n mount_options = Builtins.add(mount_options, \"nolock\")\n end\n\n # join the options\n mount_options_str = Builtins.mergestring(mount_options, \",\")\n\n mount_command = Builtins.sformat(\n \"/bin/mount -o %1 %2 %3\",\n mount_options_str,\n Ops.get_string(part, \"device\", \"\"),\n tmpdir\n )\n\n Builtins.y2milestone(\n \"Executing mount command: %1\",\n mount_command\n )\n\n result = Convert.to_integer(\n SCR.Execute(path(\".target.bash\"), mount_command)\n )\n Builtins.y2milestone(\"Mount result: %1\", result)\n\n if result == 0\n partition = Convert.convert(\n SCR.Read(path(\".run.df\")),\n :from => \"any\",\n :to => \"list <map <string, string>>\"\n )\n Builtins.foreach(partition) do |p|\n if Ops.get_string(p, \"name\", \"\") == tmpdir\n Builtins.y2internal(\"P: %1\", p)\n free_size = Ops.multiply(\n Builtins.tointeger(Ops.get_string(p, \"free\", \"0\")),\n 1024\n )\n used = Ops.multiply(\n Builtins.tointeger(Ops.get_string(p, \"used\", \"0\")),\n 1024\n )\n end\n end\n SCR.Execute(\n path(\".target.bash\"),\n Builtins.sformat(\"/bin/umount %1\", tmpdir)\n )\n else\n Builtins.y2error(\n \"Mount failed, ignoring partition %1\",\n Ops.get_string(part, \"device\", \"\")\n )\n @failed_mounts = Builtins.add(@failed_mounts, part)\n\n next\n end\n else\n # for formatted partitions estimate free system size\n # compute fs overhead\n used = EstimateFsOverhead(part)\n\n if Ops.greater_than(used, 0)\n Builtins.y2milestone(\n \"Partition %1: assuming fs overhead: %2kB\",\n Ops.get_string(part, \"device\", \"\"),\n Ops.divide(used, 1024)\n )\n end\n\n # journal size\n js = 0\n\n if ExtFs(used_fs)\n js = ExtJournalSize(part)\n reserved = ReservedSpace(part)\n\n if Ops.greater_than(reserved, 0)\n used = Ops.add(used, reserved)\n end\n elsif used_fs == :xfs\n js = XfsJournalSize(part)\n elsif used_fs == :reiser\n js = ReiserJournalSize(part)\n elsif used_fs == :jfs\n js = JfsJournalSize(part)\n else\n Builtins.y2warning(\n \"Unknown journal size for filesystem: %1\",\n used_fs\n )\n end\n\n if Ops.greater_than(js, 0)\n Builtins.y2milestone(\n \"Partition %1: assuming journal size: %2kB\",\n Ops.get_string(part, \"device\", \"\"),\n Ops.divide(js, 1024)\n )\n used = Ops.add(used, js)\n end\n\n # decrease free size\n free_size = Ops.subtract(free_size, used)\n\n # check for underflow\n if Ops.less_than(free_size, 0)\n Builtins.y2milestone(\"Fixing free size: %1 to 0\", free_size)\n free_size = 0\n end\n end\n\n # convert into kB for TargetInitDU\n free_size = Ops.divide(free_size, 1024)\n used = Ops.divide(used, 1024)\n\n Builtins.y2milestone(\n \"available partition: mount: %1, free: %2 KB, used: %3 KB\",\n Ops.get_string(part, \"mount\", \"\"),\n free_size,\n used\n )\n if !remove_slash\n target_partitions = Builtins.add(\n target_partitions,\n {\n \"name\" => Ops.get_string(part, \"mount\", \"\"),\n \"used\" => used,\n \"free\" => free_size\n }\n )\n else\n part_name = \"\"\n mount_name = Ops.get_string(part, \"mount\", \"\")\n\n if mount_name != \"/\"\n part_name = Builtins.substring(\n mount_name,\n 1,\n Builtins.size(mount_name)\n )\n else\n part_name = mount_name\n end\n\n target_partitions = Builtins.add(\n target_partitions,\n { \"name\" => part_name, \"used\" => used, \"free\" => free_size }\n )\n end\n end\n end\n end\n end # foreach (`part)\n end # foreach (`disk)\n\n # add estimated size occupied by non-package files\n target_partitions = EstimateTargetUsage(target_partitions)\n\n Builtins.y2milestone(\"get_partition_info: part %1\", target_partitions)\n Pkg.TargetInitDU(target_partitions)\n\n deep_copy(target_partitions)\n end", "def get_mounts\n mount_hash = {}\n mounts = File.open(\"/etc/mtab\", \"r\").read.split(\"\\n\").map{|l| l.split(/\\s+/)}\n mounts.each{|m| mount_hash[m[1]] = m[0] unless %w[devpts udev sysfs tmpfs none proc].include?(m[0])}\n mount_hash\nend", "def GetMountString(used_fs, defaultv)\n fsmap = GetFsMap(used_fs)\n ret = Ops.get_string(fsmap, :mount_string, defaultv)\n Builtins.y2milestone(\"GetMountString used_fs:%1 ret:%2\", used_fs, ret)\n ret\n end", "def getdiskusage\n content = \"\"\n begin\n content = `df -k`\n rescue\n warn \"Failed to run df command\"\n return nil\n end\n used_space = 0\n avail_space = 0\n content.split(\"\\n\").each do |line|\n if line =~ /\\s+\\d+\\s+(\\d+)\\s+(\\d+)\\s+\\d+%\\s+\\/($|home$)/\n used_space += $1.to_i\n avail_space += $2.to_i\n end\n end\n return {:avail_space => avail_space, :used_space => used_space}\n end", "def get_osx_disk_name(options)\n message = \"Information:\\tGetting root disk device ID\"\n command = \"df |grep '/$' |awk '{print \\\\$1}'\"\n output = execute_command(options,message,command)\n disk_id = output.chomp\n message = \"Information:\\tGetting volume name for \"+disk_id\n command = \"diskutil info #{disk_id} | grep 'Volume Name' |cut -f2 -d':'\"\n output = execute_command(options,message,command)\n volume = output.chomp.gsub(/^\\s+/,\"\")\n return volume\nend", "def get_current_devices(proc_partitions_output)\n lines = proc_partitions_output.split(\"\\n\")\n partitions = lines.drop(2).map do |line|\n line.chomp.split.last\n end.reject do |partition|\n partition =~ /^dm-\\d/\n end\n devices = partitions.select do |partition|\n partition =~ /[a-z]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n if devices.empty?\n devices = partitions.select do |partition|\n partition =~ /[0-9]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n end\n devices\n end", "def mounts\r\n @mounts.list\r\n end", "def mounted?(name)\n mount_loc = File.join(KVM_MOUNT_POINT, name)\n system(\"mount | grep #{mount_loc}\")\nend", "def determine_disk\n df_cmd = \"df 2>/dev/null|awk '$1 ~ /\\\\// {I=I+$3} END {print I}'\"\n disk = @shell.query('DISK_DF', df_cmd)\n\n # Result is expected to be in KiB. Convert to GB.\n @info[:disk] = disk.to_f / 1000 ** 2\n end", "def umount(partitions)\n partitions.each do |p|\n next unless p['mountpoint']\n\n return nil unless umount_dev(p['path'])\n end\n end", "def get_fs_type(device)\n fs_check = Mixlib::ShellOut.new(\"blkid -c /dev/null #{device}\")\n fs_check.run_command\n match = fs_check.stdout.match(/TYPE=\\\"(.*)\\\"/)\n match = '' if match.nil?\n\n match[1]\nend", "def get_fs_type(device)\n fs_check = Mixlib::ShellOut.new(\"blkid -c /dev/null #{device}\")\n fs_check.run_command\n match = fs_check.stdout.match(/\\sTYPE=\\\"(.*?)\\\"/)\n match = '' if match.nil?\n\n Chef::Log.info(\"File system type for device #{device}: #{match[1]}\")\n match[1]\nend", "def get_current_devices(output)\n lines = output.split(\"\\n\")\n partitions = lines.drop(2).map do |line|\n line.chomp.split.last\n end\n partitions.reject! do |partition|\n partition =~ /^dm-\\d/\n end\n devices = partitions.select do |partition|\n partition =~ /[a-z]$/\n end\n devices.sort!.map! {|device| \"/dev/#{device}\"}\n if devices.empty?\n devices = partitions.select do |partition|\n partition =~ /[0-9]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n end\n devices\n end", "def disk_space()\n\n instructions = 'df -h'\n r = @ssh ? @ssh.exec!(instructions) : `#{instructions}`\n\n @results[:disk_usage] = {}\n\n a = r.lines.grep(/\\/dev\\/root/)\n\n puts ('a: ' + a.inspect).debug if @debug\n\n if a.any? then\n size, used, avail = a[0].split(/ +/).values_at(1,2,3)\n\n @results[:disk_usage][:root] = {size: size, used: used, \n avail: avail}\n end\n\n a2 = r.lines.grep(/\\/dev\\/sda1/)\n\n puts ('a2: ' + a2.inspect).debug if @debug\n\n if a2.any? then\n size, used, avail = a2[0].split(/ +/).values_at(1,2,3)\n\n @results[:disk_usage][:sda1] = {size: size, used: used, \n avail: avail}\n end\n\n end", "def get_parent child_path\n parent_maj_min = nil\n if DEBUG_MODE or Platform.ubuntu? or Platform.fedora?\n command = \"udevadm\"\n params = \" info --query=property --name=#{child_path}\"\n end\n udevadm = CommandsExecutor.new command, params\n udevadm.execute false, false # None blocking and not debug mode\n raise \"Command execution error: #{udevadm.stderr.read}\" if not udevadm.success?\n udevadm.result.each_line do |line|\n line.squish!\n key = 'ID_PART_ENTRY_DISK'\n _key, value = line.split '='\n parent_maj_min = value and break if _key.eql? key\n end\n\n if DEBUG_MODE or Platform.ubuntu? or Platform.fedora?\n command = \"lsblk\"\n params = \" -b -P -o VENDOR,MODEL,TYPE,SIZE,KNAME,UUID,LABEL,MOUNTPOINT,FSTYPE,RM,MAJ:MIN\"\n end\n lsblk = CommandsExecutor.new command, params\n lsblk.execute\n raise \"Command execution error: #{lsblk.stderr.read}\" if not lsblk.success?\n lsblk.result.each_line do |line|\n data_hash = {}\n line.squish!\n line_data = line.gsub!(/\"(.*?)\"/, '\\1#').split \"#\"\n line_data.each do |data|\n data.strip!\n key, value = data.split \"=\"\n data_hash[key.downcase] = value\n return data_hash['kname'] if value == parent_maj_min\n end\n end\n raise \"Unable to find parent device for #{child_path}\"\n end", "def lvm_partition(dev)\n part = %x{sfdisk -l /dev/nbd0 2>/dev/null | grep 8e | cut -d ' ' -f 1}.strip\n part.empty? ? raise(\"Failed to locate LVM partition\") : part\nend", "def mountpoint?\n begin\n stat1 = expand_tilde.lstat\n stat2 = expand_tilde.parent.lstat\n stat1.dev == stat2.dev && stat1.ino == stat2.ino ||\n stat1.dev != stat2.dev\n rescue Errno::ENOENT\n false\n end\n end", "def mountpoint?\n begin\n stat1 = lstat\n stat2 = parent.lstat\n stat1.dev != stat2.dev or stat1.ino == stat2.ino\n rescue Errno::ENOENT\n false\n end\n end", "def list_nix_partitions # nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\" && $6==\"83\") print $1;else {if ($5==\"83\") print $1}}'`.chomp.split\nend", "def get_pt_type(device)\n fs_check = Mixlib::ShellOut.new(\"blkid -c /dev/null #{device}\")\n fs_check.run_command\n match = fs_check.stdout.match(/\\sPTTYPE=\\\"(.*?)\\\"/)\n match = '' if match.nil?\n\n Chef::Log.info(\"Partition type for device #{device}: #{match[1]}\")\n match[1]\nend", "def dev_stat\n begin\n @dev_stat ||= Sys::Filesystem.stat dev_path\n rescue SystemCallError\n @dev_stat = nil\n end\n end", "def list_size_swap_partitions # nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\" && $6==\"82\") print $5;else {if ($5==\"82\") print $4}}' | sed s/+//g`.chomp\nend", "def mount(name, root_dev)\n puts \"Mounting KVM device: #{root_dev}\"\n mount_loc = File.join(KVM_MOUNT_POINT, name)\n unless(system(\"mount | grep #{mount_loc}\"))\n FileUtils.mkdir_p(mount_loc)\n if(system(\"mount #{root_dev} #{mount_loc}\"))\n mount_loc\n else\n raise \"Failed to mount #{root_dev} to #{mount_loc}\"\n end\n else\n puts \"Device already mounted (#{mount_loc})\"\n mount_loc\n end\nend", "def nbd_device\n sys_parts = lsblk('')\n nbds = []\n\n sys_parts.each do |p|\n m = p['name'].match(/nbd(\\d+)/)\n next unless m\n\n nbds << m[1].to_i\n end\n\n nbds_max.times do |i| # if nbds_max returns 0 block is skipped\n return \"/dev/nbd#{i}\" unless nbds.include?(i)\n end\n\n OpenNebula.log_error(\"#{__method__}: Cannot find free nbd device\")\n\n ''\n end", "def name\n File.join(\"/dev/\",@device.gsub(/!/, \"/\"))\n end", "def get_disk_util\n used_info = query_data(params[:host], 'df.1kblocks.used', params[:from_ts], params[:to_ts])\n total_info = query_data(params[:host], 'df.1kblocks.total', params[:from_ts], params[:to_ts])\n\n used_info.delete_if { |k, v|\n k.index(\"fstype=tmpfs\")\n }\n total_info.delete_if { |k, v|\n k.index(\"fstype=tmpfs\")\n }\n \n results = {}\n used_info.each { |k, v|\n matcher = /mount=([\\/\\w]+) /.match(k)\n if matcher\n path = matcher[1]\n\n if total_info.has_key?(k)\n total_v = total_info[k]\n total_v_map = Hash[total_v]\n results[path] = v.collect { |point|\n ts = point[0]\n if (total_v_map.has_key?(ts))\n [ts, format(\"%.2f\", point[1] * 100.0 / total_v_map[ts]).to_f]\n end\n }.keep_if { |v| v }\n end\n end\n }\n\n render json: results\n end", "def guest_device(name, mount_point_obj)\n \"/dev/#{guest_vg_name(name, mount_point_obj)}/#{guest_lv_name(mount_point_obj)}\"\n end", "def MountUserDefinedVarPartition\n # function return value\n manual_mount_successful = false\n\n list_of_devices = []\n # $[ \"/dev/sda3\" : \"Label: My_Partition\" ]\n device_info = {}\n\n # Creating the list of known partitions\n Builtins.foreach(Storage.GetOndiskTarget) do |device, description|\n Builtins.foreach(Ops.get_list(description, \"partitions\", [])) do |partition|\n # Some partitions logically can't be used for /var\n next if Ops.get_symbol(partition, \"detected_fs\", :unknown) == :swap\n next if Ops.get_symbol(partition, \"type\", :unknown) == :extended\n next if !Builtins.haskey(partition, \"device\")\n list_of_devices = Builtins.add(\n list_of_devices,\n Ops.get_string(partition, \"device\", \"\")\n )\n Ops.set(\n device_info,\n Ops.get_string(partition, \"device\", \"\"),\n Builtins.sformat(\n # Informational text about selected partition, %x are replaced with values later\n _(\n \"<b>File system:</b> %1, <b>Type:</b> %2,<br>\\n\" +\n \"<b>Label:</b> %3, <b>Size:</b> %4,<br>\\n\" +\n \"<b>udev IDs:</b> %5,<br>\\n\" +\n \"<b>udev path:</b> %6\"\n ),\n # starts with >`<\n Builtins.substring(\n Builtins.tostring(\n Ops.get_symbol(partition, \"detected_fs\", :unknown)\n ),\n 1\n ),\n Ops.get_locale(partition, \"fstype\", _(\"Unknown\")),\n Ops.get_locale(partition, \"label\", _(\"None\")),\n String.FormatSize(\n Ops.multiply(Ops.get_integer(partition, \"size_k\", 0), 1024)\n ),\n Builtins.mergestring(Ops.get_list(partition, \"udev_id\", []), \", \"),\n Ops.get_locale(partition, \"udev_path\", _(\"Unknown\"))\n )\n )\n end\n end\n\n list_of_devices = Builtins.sort(list_of_devices)\n Builtins.y2milestone(\"Known devices: %1\", list_of_devices)\n\n while true\n UI.OpenDialog(\n VBox(\n MarginBox(\n 1,\n 0,\n VBox(\n # a popup caption\n Left(\n Heading(_(\"Unable to find the /var partition automatically\"))\n ),\n # a popup message\n Left(\n Label(\n _(\n \"Your system uses a separate /var partition which is required for the upgrade\\n\" +\n \"process to detect the disk-naming changes. Select the /var partition manually\\n\" +\n \"to continue the upgrade process.\"\n )\n )\n ),\n VSpacing(1),\n Left(\n ComboBox(\n Id(\"var_device\"),\n Opt(:notify),\n # a combo-box label\n _(\"&Select /var Partition Device\"),\n list_of_devices\n )\n ),\n VSpacing(0.5),\n # an informational rich-text widget label\n Left(Label(_(\"Device Info\"))),\n MinHeight(3, RichText(Id(\"device_info\"), \"\")),\n VSpacing(1)\n )\n ),\n MarginBox(\n 1,\n 0,\n ButtonBox(\n PushButton(Id(:ok), Opt(:okButton), Label.OKButton),\n PushButton(Id(:cancel), Opt(:cancelButton), Label.CancelButton)\n )\n )\n )\n )\n\n ret = nil\n\n # initial device\n var_device = Convert.to_string(UI.QueryWidget(Id(\"var_device\"), :Value))\n UI.ChangeWidget(\n Id(\"device_info\"),\n :Value,\n Ops.get(device_info, var_device, \"\")\n )\n\n # to handle switching the combo-box or [OK]/[Cancel]\n while true\n ret = UI.UserInput\n var_device = Convert.to_string(\n UI.QueryWidget(Id(\"var_device\"), :Value)\n )\n\n if ret == \"var_device\"\n UI.ChangeWidget(\n Id(\"device_info\"),\n :Value,\n Ops.get(device_info, var_device, \"\")\n )\n else\n break\n end\n end\n\n UI.CloseDialog\n\n # Trying user-selection\n if ret == :ok\n Builtins.y2milestone(\"Trying to mount %1 as /var\", var_device)\n mount_error = MountVarPartition(var_device)\n\n if mount_error != nil\n Report.Error(mount_error)\n next\n else\n Builtins.y2milestone(\"Manual mount (/var) successful\")\n manual_mount_successful = true\n break\n end \n # `cancel\n else\n Builtins.y2warning(\n \"User doesn't want to enter the /var partition device\"\n )\n break\n end\n end\n\n manual_mount_successful\n end", "def ip_by_mount(name)\n dev = available_dev unless mounted?(name)\n loc = mount(name, dev)\n addr = %x{cat #{File.join(loc, 'etc', 'network', 'interfaces')} | grep address}.split(' ').last.to_s.strip\n unmount_kvm_volume(name, dev) if dev\n addr\nend", "def dev_node\n disk_info = self.info\n return nil if disk_info.nil?\n return disk_info['system-entities'][0]['dev-entry']\n end", "def setup_device_for_mount\n # use ramdisk for creating a test device for mount.\n # This can cleaner if we have chef resource/provider for ramdisk.\n case ohai[:platform_family]\n when \"aix\"\n # On AIX, we can't create a ramdisk inside a WPAR, so we use\n # a \"namefs\" mount against / to test\n # https://www-304.ibm.com/support/knowledgecenter/ssw_aix_71/com.ibm.aix.performance/namefs_file_sys.htm\n device = \"/\"\n fstype = \"namefs\"\n when \"debian\", \"rhel\", \"amazon\"\n device = \"/dev/ram1\"\n unless File.exist?(device)\n shell_out(\"mknod -m 660 #{device} b 1 0\")\n shell_out(\"chown root:disk #{device}\")\n end\n shell_out(\"ls -1 /dev/ram*\").stdout.each_line do |d|\n if shell_out(\"mount | grep #{d}\").exitstatus == \"1\"\n # this device is not mounted, so use it.\n device = d\n break\n end\n end\n fstype = \"tmpfs\"\n shell_out!(\"mkfs -q #{device} 512\")\n when \"solaris2\"\n device = \"swap\"\n fstype = \"tmpfs\"\n else\n end\n [device, fstype]\n end", "def mount_list(www_root)\n arr = []\n %x{mount -t iso9660}.scan(/\\S+ on (\\S+)/) do |a|\n mountpoint = a[0]\n arr << mountpoint if mountpoint.match %r{#{www_root}}\n end\n arr\nend", "def pretty_info\n volinfo = self.info\n mountpoint = volinfo['MountPoint']\n mountpoint = 'Not mounted' if mountpoint.empty?\n rw = volinfo['WritableVolume'] ? 'writable' : 'read-only'\n ownership = self.ownership_enabled? ? 'ownership enabled' : 'no ownership'\n return volinfo['VolumeName'] + \" (#{self.dev_node}, #{mountpoint}, #{rw}, #{ownership})\\n\" \n end", "def tmpfs_mount_status(desired)\n # Start with checking if it was mounted the way we would mount it\n # this is ALMOST the same as the 'is it identical' check for non-tmpfs\n # filesystems except that with tmpfs we don't treat 'auto' as equivalent and\n # that we skip inode64 option on current mount status - because it's activated\n # by default on Linux kernel >= 5.9\n fs_data = node.filesystem_data\n key = \"#{desired['device']},#{desired['mount_point']}\"\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n if mounted['fs_type'] == 'tmpfs'\n Chef::Log.debug(\n \"fb_fstab: tmpfs #{desired['device']} on \" +\n \"#{desired['mount_point']} is currently mounted...\",\n )\n\n skipped_opts = []\n if _are_tmpfs_using_inode64?\n\n # inode64 is active by default on tmpfs for Linux kernel > 5.9\n skipped_opts.push('inode64')\n end\n\n if compare_opts(desired['opts'], mounted['mount_options'], skipped_opts)\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n end\n end\n # OK, if that's not the case, we don't have the same device, which\n # is OK. Find out if we have something mounted at the same spot, and\n # get its device name so we can find it's entry in node['filesystem']\n if fs_data['by_mountpoint'][desired['mount_point']]\n # If we are here the mountpoints are the same...\n mounted = fs_data['by_mountpoint'][desired['mount_point']].to_hash\n # OK, if it's tmpfs as well, we're diong good\n if mounted['fs_type'] == 'tmpfs'\n Chef::Log.warn(\n \"fb_fstab: Treating #{mounted['devices']} on \" +\n \"#{desired['mount_point']} the same as #{desired['device']} on \" +\n \"#{desired['mount_point']} because they are both tmpfs.\",\n )\n Chef::Log.debug(\n \"fb_fstab: tmpfs #{desired['device']} on \" +\n \"#{desired['mount_point']} is currently mounted...\",\n )\n Chef::Log.debug(\"fb_fstab: #{desired} vs #{mounted}\")\n if compare_opts(desired['opts'], mounted['mount_options'])\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n end\n Chef::Log.warn(\n \"fb_fstab: tmpfs is desired on #{desired['mount_point']}, but \" +\n \"non-tmpfs #{mounted['devices']} (#{mounted['fs_type']}) currently \" +\n 'mounted there.',\n )\n return :conflict\n end\n :missing\n end", "def mountpoint?\n begin\n stat1 = self.lstat\n stat2 = self.parent.lstat\n stat1.dev == stat2.dev && stat1.ino == stat2.ino ||\n stat1.dev != stat2.dev\n rescue Errno::ENOENT\n false\n end\n end", "def info\n Plist::parse_xml(diskutil 'info', '-plist', @dev_node)\n end", "def getFsPath(path)\n if path.kind_of? Array\n if path.length == 0\n localPath = @cwd.dup\n else\n localPath = normalizePath(path[0].dup)\n end\n else\n localPath = normalizePath(path.dup)\n end\n\n dl = localPath.slice!(0..1).upcase\n raise MiqException::MiqVmMountError, \"Unknown drive letter - #{dl}\" unless (fs = @driveToFS[dl])\n return fs, localPath\n end", "def mount_command(path)\n \"udisksctl mount --block-device #{path}\"\nend", "def MountPartition(mount_point, device, mount_type)\n if mount_type == \"\"\n # e.g. -> \"reiserfs\"\n mount_type = FileSystems.GetMountString(Storage.DetectFs(device), \"\")\n end\n\n # #223878, do not call modprobe with empty mount_type\n if mount_type == \"\"\n Builtins.y2warning(\"Unknown filesystem, skipping modprobe...\") \n # #211916, sysfs, proc are not modular\n elsif !Builtins.contains(@non_modular_fs, mount_type)\n # #167976, was broken with \"-t \", modprobe before adding it\n Builtins.y2milestone(\"Calling 'modprobe %1'\", mount_type)\n SCR.Execute(path(\".target.modprobe\"), mount_type, \"\")\n else\n Builtins.y2milestone(\n \"FS type %1 is not modular, skipping modprobe...\",\n mount_type\n )\n end\n\n error_message = nil\n if !(\n error_message_ref = arg_ref(error_message);\n _RunFSCKonJFS_result = RunFSCKonJFS(\n mount_type,\n device,\n error_message_ref\n );\n error_message = error_message_ref.value;\n _RunFSCKonJFS_result\n )\n return error_message\n end\n\n mount_type = Ops.add(\"-t \", mount_type) if mount_type != \"\"\n\n ret = Convert.to_boolean(\n SCR.Execute(\n path(\".target.mount\"),\n [\n device,\n Ops.add(Installation.destdir, mount_point),\n Installation.mountlog\n ],\n mount_type\n )\n )\n if ret\n return nil\n else\n return Convert.to_string(\n SCR.Read(path(\".target.string\"), Installation.mountlog)\n )\n end\n end", "def pretty_info\n s = ''\n dev = self.device\n return \"Disk image: #{self.image_path.basename} (na, detached, na)\\n\" if dev.nil?\n return dev.pretty_info\n end", "def mountpoint\n \"#{spec[:temp_dir]}\"\n end", "def FindPartitionInFstab(fstab, mountpoint)\n if Builtins.substring(\n mountpoint,\n Ops.subtract(Builtins.size(mountpoint), 1),\n 1\n ) == \"/\"\n mountpoint = Builtins.substring(\n mountpoint,\n 0,\n Ops.subtract(Builtins.size(mountpoint), 1)\n )\n end\n\n tmp = Builtins.filter(fstab.value) do |entry|\n Ops.get_string(entry, \"file\", \"\") == mountpoint ||\n Ops.get_string(entry, \"file\", \"\") == Ops.add(mountpoint, \"/\")\n end\n\n return nil if Builtins.size(tmp) == 0\n\n Ops.get_string(tmp, [0, \"spec\"], \"\")\n end", "def lsblk_path(p)\n return unless !p['path'] && p['name']\n\n if File.exist?(\"/dev/#{p['name']}\")\n p['path'] = \"/dev/#{p['name']}\"\n elsif File.exist?(\"/dev/mapper/#{p['name']}\")\n p['path'] = \"/dev/mapper/#{p['name']}\"\n end\n end", "def find_fstab(partitions, path)\n fstab = ''\n partitions.each do |p|\n OpenNebula.log(\"Looking for fstab on #{p['path']}\")\n\n rc = mount_dev(p['path'], path)\n next unless rc\n\n bin = COMMANDS[:catfstab]\n bin = COMMANDS[:cat] unless path.include?('containers/one-')\n\n cmd = \"#{bin} #{path}/etc/fstab\"\n\n _rc, fstab, _e = Command.execute(cmd, false)\n\n if fstab.empty?\n return false unless umount_dev(p['path'])\n\n next\n end\n\n OpenNebula.log(\"Found fstab on #{p['path']}\")\n break\n end\n\n return fstab unless fstab.empty?\n\n OpenNebula.log_error('No fstab file found')\n\n false\n end", "def filesystem_labels\n\n labels = {}\n\n mount = capture_command_output('mount')\n mount.each do |mount_line|\n\n mount_line.strip!\n device = mount_line.match(/^(.*?) on/)[1]\n\n if PlatformInfo.linux?\n\n # /dev/hda3 on / type ext4 (rw,errors=remount-ro)\n mount_point = mount_line.match(/^#{Regexp.quote(device)} on (.*?) type/)[1]\n fs_type = mount_line.match(/type (.*?) \\(/)[1]\n\n elsif PlatformInfo.osx?\n\n # /dev/disk0s2 on / (hfs, local, journaled)\n mount_point = mount_line.match(/^#{Regexp.quote(device)} on (.*?) \\(/)[1]\n fs_type = mount_line.match(/ \\((.*?), /)[1]\n \n else\n unsupported_platform\n end\n\n labels[device] = {\n :mount_point => mount_point,\n :file_system => fs_type\n }\n\n end\n\n labels\n\n end", "def MountPartitions(root_device_current)\n Builtins.y2milestone(\"mount partitions: %1\", root_device_current)\n\n return true if @did_try_mount_partitions\n\n @did_try_mount_partitions = true\n\n success = true\n\n # popup message, %1 will be replace with the name of the logfile\n message = Builtins.sformat(\n _(\n \"Partitions could not be mounted.\\n\" +\n \"\\n\" +\n \"Check the log file %1.\"\n ),\n Ops.add(Directory.logdir, \"/y2log\")\n )\n Builtins.y2milestone(\"selected partition: %1\", root_device_current)\n\n ret_bool = true\n\n fstab = []\n crtab = []\n\n # Mount selected root partition to Installation::destdir\n ret_bool = nil == FsckAndMount(\"/\", root_device_current, \"\") if !Mode.test\n\n if ret_bool\n # read the keyboard settings now, so that it used when\n # typing passwords for encrypted partitions\n # Calling a script because otherwise this module would depend on yast2-country\n if Stage.initial\n WFM.call(\n \"rootpart_check_keyboard\",\n [{ \"destdir\" => Installation.destdir }]\n )\n end\n\n fstab_ref = arg_ref(fstab)\n crtab_ref = arg_ref(crtab)\n read_fstab_and_cryptotab(fstab_ref, crtab_ref, root_device_current)\n fstab = fstab_ref.value\n crtab = crtab_ref.value\n Storage.ChangeDmNamesFromCrypttab(\n Ops.add(Installation.destdir, \"/etc/crypttab\")\n )\n Update.GetProductName\n\n if FstabUsesKernelDeviceNameForHarddisks(fstab)\n Builtins.y2warning(\n \"fstab on %1 uses kernel device name for hard disks\",\n root_device_current\n )\n warning = Builtins.sformat(\n _(\n \"Some partitions in the system on %1 are mounted by kernel-device name. This is\\n\" +\n \"not reliable for the update since kernel-device names are unfortunately not\\n\" +\n \"persistent. It is strongly recommended to start the old system and change the\\n\" +\n \"mount-by method to any other method for all partitions.\"\n ),\n root_device_current\n )\n if Mode.autoupgrade\n Popup.TimedWarning(warning, 10)\n else\n Popup.Warning(warning)\n end\n end\n\n if Builtins.size(fstab) == 0\n Builtins.y2error(\"no or empty fstab found!\")\n # error message\n message = _(\"No fstab found.\")\n success = false\n else\n tmp_msg = MountVarIfRequired(fstab, root_device_current, true)\n if tmp_msg != nil\n Builtins.y2error(\"failed to mount /var!\")\n message = tmp_msg\n success = false\n else\n tmp = \"\"\n\n if !(\n tmp_ref = arg_ref(tmp);\n check_root_device_result = check_root_device(\n root_device_current,\n fstab,\n tmp_ref\n );\n tmp = tmp_ref.value;\n check_root_device_result\n )\n Builtins.y2error(\"fstab has wrong root device!\")\n # message part 1\n message = Ops.add(\n Ops.add(\n _(\n \"The root partition in /etc/fstab has an invalid root device.\\n\"\n ),\n # message part 2\n Builtins.sformat(\n _(\"It is currently mounted as %1 but listed as %2.\\n\"),\n root_device_current,\n tmp\n )\n ),\n @sdb\n )\n success = false\n else\n Builtins.y2milestone(\"cryptotab %1\", crtab)\n\n fstab_ref = arg_ref(fstab)\n PrepareCryptoTab(crtab, fstab_ref)\n fstab = fstab_ref.value\n\n Builtins.y2milestone(\"fstab %1\", fstab)\n\n if !(\n message_ref = arg_ref(message);\n _MountFSTab_result = MountFSTab(fstab, message_ref);\n message = message_ref.value;\n _MountFSTab_result\n )\n success = false\n end\n end\n end\n end\n else\n Builtins.y2error(\n \"Could not mount root '%1' to '%2'\",\n root_device_current,\n Installation.destdir\n )\n success = false\n end\n\n Builtins.y2milestone(\n \"MountPartition (%1) = %2\",\n root_device_current,\n success\n )\n Builtins.y2milestone(\"activated %1\", @activated)\n\n if !success\n Popup.Message(message)\n\n # some mount failed, unmount all mounted fs\n UnmountPartitions(false)\n @did_try_mount_partitions = true\n else\n # enter the mount points of the newly mounted partitions\n # in the target map of the storage module\n AddToTargetMap()\n end\n\n success\n end", "def mount_point\n Pathname.new(self['MountPoint'])\n end", "def mountpoint\n self\n end", "def mountpoint\n self\n end", "def getmountedvolumes\n # only support Linux for now\n return {} unless Facter['kernel'] && Facter['kernel'].value == 'Linux'\n\n dir = \"/etc\"\n mounted = {}\n\n # AUTOFS - gather only files named auto[._]*\n Dir.glob(File.join(dir, \"*\")).each do |file|\n next if file !~ /^auto[._].*/\n\n # AUTOFS - match only lines that look like nfs syntax such as host:/path\n IO.foreach(file) do |line|\n if line =~ /\\w:\\S/ && line !~ /^\\s*#/\n # Parse it, Example : \" nventory_backup -noatime,intr irvnetappbk:/vol/nventory_backup \"\n if line =~ /^(\\w[\\w\\S]+)\\s+\\S+\\s+(\\w[\\w\\S]+):(\\S+)/\n mnt = $1\n host = $2\n vol = $3\n mounted[\"volumes[mounted][/mnt/#{mnt}][config]\"] = file\n mounted[\"volumes[mounted][/mnt/#{mnt}][volume_server]\"] = host\n mounted[\"volumes[mounted][/mnt/#{mnt}][volume]\"] = vol\n mounted[\"volumes[mounted][/mnt/#{mnt}][type]\"] = 'nfs'\n end\n end\n end # IO.foreach\n end # Dir.glob\n\n # FSTAB - has diff syntax than AUTOFS. Example: \"server:/usr/local/pub /pub nfs rsize=8192,wsize=8192,timeo=14,intr\"\n IO.foreach(\"/etc/fstab\") do |line|\n if line =~ /^(\\w[\\w\\S]+):(\\S+)\\s+(\\S+)\\s+nfs/\n host = $1\n vol = $2\n mnt = $3\n mounted[\"volumes[mounted][#{mnt}][config]\"] = \"/etc/fstab\"\n mounted[\"volumes[mounted][#{mnt}][volume_server]\"] = host\n mounted[\"volumes[mounted][#{mnt}][volume]\"] = vol\n mounted[\"volumes[mounted][#{mnt}][type]\"] = 'nfs'\n end\n end # IO.foreach\n return mounted\n end", "def tmpfs\n\t\t\t\tret = {}\n\t\t\t\tmounts.each { |x|\n\t\t\t\t\tret.merge!({x.split[1] => x}) if x.start_with?('tmpfs '.freeze)\n\t\t\t\t}\n\t\t\t\tret\n\t\t\tend", "def get_online_disk_command()\n if @os_info.major < 6; \"online noerr\" else; \"online disk noerr\" end\n end", "def mount_status(desired)\n # We treat tmpfs specially. While we don't want people to mount tmpfs with\n # a device of 'none' or 'tmpfs', we also don't want to make them remount\n # (and lose all their data) just to convert to fb_fstab. So we'll make\n # them use a new name in the config, but we will treat the pre-mounted\n # mounts as valid/the same. Besides, since the device is meaningless, we\n # can just ignore it for the purposes of this test anyway.\n if desired['type'] == 'tmpfs'\n return tmpfs_mount_status(desired)\n end\n\n key = \"#{desired['device']},#{desired['mount_point']}\"\n fs_data = node.filesystem_data\n mounted = nil\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n else\n key = \"#{desired['device']}/,#{desired['mount_point']}\"\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n end\n end\n\n if mounted\n Chef::Log.debug(\n \"fb_fstab: There is an entry in node['filesystem'] for #{key}\",\n )\n # If it's a virtual device, we require the fs type to be identical.\n # otherwise, we require them to be similar. This is because 'auto'\n # is meaningless without a physical device, so we don't want to allow\n # it to be the same.\n if compare_fstype(desired['type'], mounted['fs_type']) ||\n (desired['device'].start_with?('/') &&\n [desired['type'], mounted['fs_type']].include?('auto'))\n Chef::Log.debug(\n \"fb_fstab: FS #{desired['device']} on #{desired['mount_point']}\" +\n ' is currently mounted...',\n )\n if compare_opts(desired['opts'], mounted['mount_options'])\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n else\n Chef::Log.warn(\n \"fb_fstab: Device #{desired['device']} is mounted at \" +\n \"#{mounted['mount']} as desired, but with fstype \" +\n \"#{mounted['fs_type']} instead of #{desired['type']}\",\n )\n return :conflict\n end\n end\n\n # In this case we don't have the device we expect at the mountpoint we\n # expect. Assuming it's not NFS/Gluster which can be mounted in more than\n # once place, we look up this device and see if it moved or just isn't\n # mounted\n unless ['nfs', 'nfs4', 'glusterfs'].include?(desired['type'])\n device = fs_data['by_device'][desired['device']]\n # Here we are checking if the device we want\n # has already a mount defined\n # We want to return :moved if it does except\n # in the case when it's a btrfs\n # disk and our desired and current options\n # are trying to mount different subvolumes\n if device && device['mounts'] && !device['mounts'].empty? &&\n !(\n FB::Fstab.btrfs_subvol?(\n device['fs_type'],\n device['mount_options'].join(','),\n ) &&\n FB::Fstab.btrfs_subvol?(\n desired['type'],\n desired['opts'],\n ) &&\n !FB::Fstab.same_subvol?(\n device['mounts'][0],\n device['mount_options'].join(','),\n desired['opts'],\n )\n )\n\n Chef::Log.warn(\n \"fb_fstab: #{desired['device']} is at #{device['mounts']}, but\" +\n \" we want it at #{desired['mount_point']}\",\n )\n return :moved\n end\n end\n\n # Ok, this device isn't mounted, but before we return we need to check\n # if anything else is mounted where we want to be.\n if fs_data['by_mountpoint'][desired['mount_point']]\n devices = fs_data['by_mountpoint'][\n desired['mount_point']]['devices']\n Chef::Log.warn(\n \"fb_fstab: Device #{desired['device']} desired at \" +\n \"#{desired['mount_point']} but something #{devices} already \" +\n 'mounted there.',\n )\n return :conflict\n end\n :missing\n end", "def list_size_nix_partitions # nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\" && $6==\"83\") print $5;else {if ($5==\"83\") print $4}}' | sed s/+//g`.chomp.split\nend", "def other_mounts\n others = []\n fstab_lines.each do |line|\n localdevice, localmount, _fstype, _options, _freq, _pass = line.split(/\\s+/)\n others << line if localmount == mount && localdevice != device\n end\n others\n end", "def all_devices search = nil\n partitions = []\n devices = []\n device = nil\n has_extended = false\n if DEBUG_MODE or Platform.ubuntu? or Platform.fedora?\n command = \"lsblk\"\n params = \" #{search} -b -P -o VENDOR,MODEL,TYPE,SIZE,KNAME,UUID,LABEL,MOUNTPOINT,FSTYPE,RM\"\n end\n lsblk = CommandsExecutor.new command, params\n lsblk.execute\n raise \"Command execution error: #{lsblk.stderr.read}\" if not lsblk.success?\n\n lsblk.result.each_line do |line|\n data_hash = {}\n line.squish!\n line_data = line.gsub!(/\"(.*?)\"/, '\\1#').split \"#\"\n line_data.each do |data|\n data.strip!\n key, value = data.split \"=\"\n data_hash[key.downcase] = value\n end\n data_hash['rm'] = data_hash['rm'].to_i # rm = 1 if device is a removable/flash device, otherwise 0\n if data_hash['type'] == 'mpath'\n data_hash.except!('uuid', 'label', 'mountpoint', 'fstype')\n if device\n multipath_info = {'mkname' => data_hash['kname'], 'multipath' => true, 'size' => data_hash['size']}\n device.merge! multipath_info\n else\n data_hash['multipath'] = true\n device = data_hash\n devices.push device\n end\n next\n end\n if data_hash['type'] == 'disk'\n data_hash.except!('uuid', 'label', 'mountpoint', 'fstype')\n unless device.nil?\n device['partitions'] = partitions\n partitions = []\n devices.push device\n device = nil # cleanup the variable\n end\n device = data_hash\n next\n end\n if data_hash['type'] == 'part'\n data_hash.except!('model', 'vendor')\n data_hash.merge! self.usage data_hash['kname']\n\n partition_number = get_partition_number \"/dev/#{data_hash['kname']}\" # For reference: data_hash['kname'].match(/[0-9]*$/)[0].to_i\n extended_partition_types = ['0x05'.hex, '0x0F'.hex]\n if partition_type_hex(data_hash['kname']).in? extended_partition_types\n has_extended = true\n next\n end\n if has_extended and partition_number > 4\n data_hash['logical'] = true\n end\n # device['partitions'].nil? ? device['partitions'] = [data_hash] : device['partitions'].push(data_hash)\n partitions.push(data_hash)\n end\n end\n device['partitions'] = partitions if device\n devices.push device\n if search\n return devices.first || partitions.first\n else\n return devices\n end\n end", "def GetMountPoints\n mountPoints = {}\n swapPoints = []\n tg = GetTargetMap()\n Builtins.foreach(tg) do |targetdevice, target|\n partitions = Ops.get_list(target, \"partitions\", [])\n Builtins.foreach(partitions) do |partition|\n partitionName = Ops.get_string(partition, \"device\", \"\")\n mountPoint = Ops.get_string(partition, \"mount\", \"\")\n fsid = Ops.get_integer(partition, \"fsid\", 0)\n if mountPoint != \"\"\n raid_type = \"\"\n if Ops.get_symbol(partition, \"type\", :undefined) == :sw_raid\n raid_type = Ops.get_string(partition, \"raid_type\", \"\")\n end\n # partition has a mount point\n if mountPoint == \"swap\"\n swapPoints = Builtins.add(\n swapPoints,\n [partitionName, fsid, targetdevice, raid_type]\n )\n else\n mountPoints = Builtins.add(\n mountPoints,\n mountPoint,\n [partitionName, fsid, targetdevice, raid_type]\n )\n end\n end\n end\n end\n if Ops.greater_than(Builtins.size(swapPoints), 0)\n mountPoints = Builtins.add(mountPoints, \"swap\", swapPoints)\n end\n if !Stage.initial\n cm = Builtins.filter(Partitions.CurMounted) do |e|\n Builtins.search(Ops.get_string(e, \"spec\", \"\"), \"/dev/\") == 0\n end\n Builtins.foreach(cm) do |e|\n if !Builtins.haskey(mountPoints, Ops.get_string(e, \"file\", \"\"))\n p = GetPartition(tg, Ops.get_string(e, \"spec\", \"\"))\n if Ops.greater_than(Builtins.size(p), 0)\n raid_type = \"\"\n if Ops.get_symbol(p, \"type\", :undefined) == :sw_raid\n raid_type = Ops.get_string(p, \"raid_type\", \"\")\n end\n d = GetDiskPartition(Ops.get_string(e, \"spec\", \"\"))\n Ops.set(\n mountPoints,\n Ops.get_string(e, \"file\", \"\"),\n [\n Ops.get_string(p, \"device\", \"\"),\n Ops.get_integer(p, \"fsid\", 0),\n Ops.get_string(d, \"disk\", \"\"),\n raid_type\n ]\n )\n end\n end\n end\n end\n Builtins.y2milestone(\"ret %1\", mountPoints)\n deep_copy(mountPoints)\n end", "def list_swap_partitions_with_size # nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\" && $6==\"82\") print $1\":\"$5;else {if ($5==\"82\") print $1\":\"$4}}' | sed s/+//g`.chomp.split\nend", "def IsMounted(mountpoint)\n if Builtins.substring(\n mountpoint,\n Ops.subtract(Builtins.size(mountpoint), 1),\n 1\n ) == \"/\"\n mountpoint = Builtins.substring(\n mountpoint,\n 0,\n Ops.subtract(Builtins.size(mountpoint), 1)\n )\n end\n\n ret = true\n Builtins.foreach(@activated) do |e|\n if Ops.get_string(e, :type, \"\") == \"mount\" &&\n (Ops.get_string(e, :mntpt, \"\") == mountpoint ||\n Ops.get_string(e, :mntpt, \"\") == Ops.add(mountpoint, \"/\"))\n ret = true\n end\n end\n ret\n end", "def filesystem_file(host)\n case host['platform']\n when %r{aix}\n '/etc/filesystems'\n when %r{el-|centos|fedora|sles|debian|ubuntu}\n '/etc/fstab'\n else\n # TODO: Add Solaris and OSX support, as per PUP-5201 and PUP-4823\n fail_test(\"Unable to determine filesystem table file location for #{host['platform']}\")\n end\n end", "def get_drive\n begin\n q = @db_connection.query('SELECT @@tmpdir;')\n q.each { |x| @tmp=x[0]; }\n return @tmp[0]\n rescue Mysql::Error => e\n print_error(\"Problem getting drive from @@tmpdir!\")\n puts \"\\t=> \".white + \"#{e}\".light_red\n return nil\n end\n end", "def partition_used(partition)\n # Return magic number if in test_mode to prevent syscall\n return '128' if @test_mode\n b = ' ' * 128\n syscall(137, partition, b)\n a = b.unpack('QQQQQ')\n [a[2] * blocks_per_kilobyte, a[4] * blocks_per_kilobyte]\n end", "def display_host(hostname, partitions)\n volume_groups = {}\n lvm_members = []\n\n puts hostname\n partitions.keys.sort.each do |partition|\n if partitions[partition]['filesystem'] == 'LVM2_member'\n lvm_members << partition\n next\n end\n next if partition == '/dev/mapper/rootvg-swap'\n next if partition == '/dev/mapper/rootvg-afscache'\n next unless partition.match(/^\\/dev\\/mapper\\/(\\S+)-(\\S+)/)\n\n vg = $~[1]\n short_partition = $~[2]\n volume_groups[vg] = [] unless volume_groups.key?(vg)\n volume_groups[vg] << partition\n end\n\n puts \"LVM partitions: \" + lvm_members.sort.join(', ')\n puts 'lvm::volume_groups:'\n volume_groups.keys.sort.each do |vg|\n puts \" #{vg}:\"\n puts ' logical_volumes:'\n volume_groups[vg].sort.each do |partition|\n\n next unless partition.match(/^\\/dev\\/mapper\\/\\S+-(\\S+)/)\n short_partition = $~[1]\n\n # Skip the partition if it's an expected size.\n space = format_space(partition, partitions[partition]['size'].to_s)\n next if space.nil?\n\n # Find if this is a known volume and set the mount to nil then, so we\n # don't print in useless data.\n mount = format_mount(partition, partitions[partition]['mount'].to_s)\n\n puts ' ' + short_partition + ':'\n puts ' ' + 'size: ' + space\n puts ' ' + 'mountpath: ' + mount unless mount.nil?\n puts ' ' + 'fs_type: ' + partitions[partition]['filesystem'].to_s unless mount.nil?\n end\n end\n\n puts\nend", "def fetch_disk_size\n total_size = 0\n total_size = `lsblk -b --output SIZE -d -n | paste -s -d + - | bc`\n number_to_human_size total_size\n end", "def forks\n `vmstat -f`.split.first\n end", "def list_partitions_with_size_and_type # by nelsongs. => list: partition size type\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\") print $1\":\"$5\":\"$6;else print $1\":\"$4\":\"$5}' | sed s/+//g`.split\nend", "def root_device_name\n data[:root_device_name]\n end", "def unmount_command(path)\n \"udisksctl unmount --block-device #{path}\"\nend", "def parent_whole_disk\n Device.new('/dev/' + self['ParentWholeDisk'])\n end", "def mounted?\n '' != self['MountPoint']\n end", "def list_nix_partitions_with_size # nelsongs \n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\" && $6==\"83\") print $1\":\"$5;else {if ($5==\"83\") print $1\":\"$4}}' | sed s/+//g`.chomp.split\nend", "def list_swap_partitions_with_type_and_size # nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\" && $6==\"82\") print $1\":\"$5\":\"$6;else {if ($5==\"82\") print $1\":\"$4\":\"$5}}' | sed s/+//g`.chomp.split\nend", "def mounted?\n !!( attached? && mount_point && File.exists?(mount_point) && current[:mount] == mount_point )\n end", "def convert_from_mapper(name)\n if name.match(/\\/dev\\/mapper/)\n v=name.split(\"/\")\n c=v[3].split(\"-\")\n vg=c[0]\n lv=c[1]\n \"/dev/#{vg}/#{lv}\"\n else\n name\n end\n end", "def partition_device\n Souffle::Log.info \"#{@node.log_prefix} Partitioning the device...\"\n provider.partition(@node)\n end", "def filesystem\n platform_service(:filesystem)\n end", "def get_device_info()\n @errors = []\n info = {}\n return info unless @programmer_path\n\n response = IO.popen(\"#{@programmer_path} I\").readlines\n puts response if $debug\n response.each do |line|\n if line =~ /Error/i\n errors << line\n else\n parts = line.split(/:|\\.\\.\\./)\n info[parts[0].strip.split.join.to_sym] = parts[1].strip if parts.size == 2\n end\n end # each\n info\n end", "def disk(cfg)\n mountpoint = \"mountpoint=\\\"#{cfg['mount']}\\\"\"\n query = @client.percent_query_free(\n \"node_filesystem_size{#{mountpoint}}\",\n \"node_filesystem_avail{#{mountpoint}}\"\n )\n prepare_metrics('disk', @client.query(query))\n end", "def get_filesystem\n @@current_fake ? @@current_fake[:filesystem] : ''\n end", "def GetDiskPartition(device)\n Ops.get(GetDiskPartitionTg(device, GetTargetMap()), 0, {})\n end", "def getDiskInfo(device, disk)\n disk = deep_copy(disk)\n c = {}\n c = Builtins.find(@conts) { |p| Ops.get_string(p, \"device\", \"\") == device }\n if c == nil\n tmp = GetDiskPartition(device)\n Builtins.y2milestone(\"getDiskInfo map %1\", tmp)\n c = Builtins.find(@conts) do |p|\n Ops.get_string(p, \"device\", \"\") == Ops.get_string(tmp, \"disk\", \"\")\n end if Ops.get_string(\n tmp,\n \"disk\",\n \"\"\n ) != device\n end\n Builtins.y2milestone(\"getDiskInfo c:%1\", c)\n if c != nil\n disk = toDiskMap(disk, getContainerInfo(c))\n Builtins.y2milestone(\n \"getDiskInfo ret:%1\",\n Builtins.haskey(disk, \"partitions\") ?\n Builtins.remove(disk, \"partitions\") :\n disk\n )\n end\n deep_copy(disk)\n end", "def __nrpe_fstab\n\t\t\t\tdata = call_nrpe \"check_fstab\"\n\t\t\t\treturn false if data == false\n\t\t\t\tdisks = data.chomp.split(\"|\").map! {|x| x.strip }\n\t\t\t\tdisks.delete(\"$\") if disks.include?(\"$\")\n\t\t\t\treturn disks\n\t\tend", "def select_device_name(volume_attachments, first_device_name_letter)\n (first_device_name_letter..'z').each do |char|\n # Some kernels remap device names (from sd* to vd* or xvd*).\n device_names = [\"/dev/sd#{char}\", \"/dev/vd#{char}\", \"/dev/xvd#{char}\"]\n # Bosh Agent will lookup for the proper device name if we set it initially to sd*.\n return \"/dev/sd#{char}\" if volume_attachments.select { |v| device_names.include?(v['device']) }.empty?\n @logger.warn(\"`/dev/sd#{char}' is already taken\")\n end\n\n nil\n end", "def verify_mount_count\n @mounted_partitions.length\n end", "def get_uuid(device)\n Chef::Log.info(\"Getting uuid for device: #{device}\")\n fs_check = Mixlib::ShellOut.new(\"blkid -c /dev/null #{device}\")\n fs_check.run_command\n match = fs_check.stdout.match(/\\sUUID=\\\"(.*?)\\\"/)\n match = '' if match.nil?\n Chef::Log.info(\"uuid for device: #{device} is #{match[1]}\")\n match[1]\nend", "def lsblk(device)\n partitions = {}\n blocklist = ''\n\n cmd =\"#{COMMANDS[:lsblk]} -OJ #{device}\"\n\n 3.times do |t| # wait for device to be ready to be parsed\n rc, o, e = Command.execute(cmd, false)\n\n if rc != 0 || o.empty?\n OpenNebula.log_error(\"#{__method__}: #{rc}, #{o}, #{e}\") if t == 3\n sleep 1\n next\n end\n\n blocklist = o\n break\n end\n\n begin\n partitions = JSON.parse(blocklist)['blockdevices']\n\n if !device.empty?\n partitions = partitions[0]\n\n if partitions['children']\n partitions = partitions['children']\n else\n partitions = [partitions]\n end\n\n partitions.delete_if do |p|\n p['fstype'].casecmp('swap').zero? if p['fstype']\n end\n end\n rescue StandardError\n OpenNebula.log_error(\"lsblk: error parsing lsblk -OJ #{device}\")\n return {}\n end\n\n # Fix for lsblk paths for version < 2.33\n partitions.each do |p|\n lsblk_path(p)\n\n p['children'].each {|q| lsblk_path(q) } if p['children']\n end\n\n partitions\n end", "def ramdisk_id\n data[:ramdisk_id]\n end", "def test_mountstring\n mount = nil\n name = \"yaytest\"\n path = tmpdir\n assert_nothing_raised {\n mount = Puppet::Network::Handler.fileserver::Mount.new(name, path)\n }\n\n assert_equal(\"mount[#{name}]\", mount.to_s)\n end", "def root_fs\n\t\t\t\tfind_root[2].to_s\n\t\t\tend" ]
[ "0.6930065", "0.68186027", "0.67002195", "0.6683224", "0.66773266", "0.66220176", "0.6585295", "0.6462865", "0.63970613", "0.6382977", "0.63176656", "0.6284937", "0.62830704", "0.62827677", "0.6138401", "0.6130033", "0.6054028", "0.60255635", "0.59874845", "0.5978643", "0.59399945", "0.5937705", "0.59267443", "0.59181523", "0.58805954", "0.5849878", "0.5849579", "0.583016", "0.57529813", "0.5750911", "0.5720453", "0.5698271", "0.5693475", "0.56849504", "0.5642277", "0.56196815", "0.56107366", "0.55786407", "0.55683243", "0.55159086", "0.5500469", "0.54957384", "0.54878926", "0.5472303", "0.5455589", "0.5432086", "0.5429961", "0.54014856", "0.5393309", "0.5392248", "0.5389413", "0.5383205", "0.53713447", "0.53655267", "0.5349548", "0.53471565", "0.5341091", "0.5339179", "0.5318915", "0.5317055", "0.5317055", "0.52669245", "0.5256655", "0.524431", "0.524179", "0.52375233", "0.5234325", "0.5229098", "0.52237165", "0.5200693", "0.5193745", "0.5186901", "0.5184928", "0.5177866", "0.51706195", "0.5169833", "0.51431376", "0.5140195", "0.5139455", "0.51263255", "0.5119599", "0.5114287", "0.5113144", "0.5082458", "0.508101", "0.50753087", "0.50612146", "0.5061177", "0.5041951", "0.5033054", "0.5029713", "0.502725", "0.5027029", "0.50097734", "0.5003491", "0.49942723", "0.49940753", "0.4993819", "0.49889794", "0.49873123", "0.49717793" ]
0.0
-1
Reads /proc/mounts and returns the file system of the device mounted at /. It returns a String. But if the info isn't available or /proc/mounts is not readable, it will return an empty frozen String.
def root_fs find_root[2].to_s end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_mounted?(device)\n system(\"grep -q '#{device}' /proc/mounts\")\nend", "def device_of_mount(m)\n unless Pathname.new(m).mountpoint?\n Chef::Log.warn(\n \"#{m} is not a mount point - I can't determine its device.\",\n )\n return nil\n end\n node['filesystem2']['by_pair'].to_hash.each do |pair, info|\n # we skip fake filesystems 'rootfs', etc.\n next unless pair.start_with?('/')\n # is this our FS?\n next unless pair.end_with?(\",#{m}\")\n # make sure this isn't some fake entry\n next unless info['kb_size']\n return info['device']\n end\n Chef::Log.warn(\n \"#{m} shows as valid mountpoint, but Ohai can't find it.\",\n )\n return nil\n end", "def device_of_mount(m)\n fs = self.filesystem_data\n unless Pathname.new(m).mountpoint?\n Chef::Log.warn(\n \"fb_helpers: #{m} is not a mount point - I can't determine its \" +\n 'device.',\n )\n return nil\n end\n unless fs && fs['by_pair']\n Chef::Log.warn(\n 'fb_helpers: no filesystem data so no node.device_of_mount',\n )\n return nil\n end\n fs['by_pair'].to_hash.each do |pair, info|\n # we skip fake filesystems 'rootfs', etc.\n next unless pair.start_with?('/')\n # is this our FS?\n next unless pair.end_with?(\",#{m}\")\n # make sure this isn't some fake entry\n next unless info['kb_size']\n\n return info['device']\n end\n Chef::Log.warn(\n \"fb_helpers: #{m} shows as valid mountpoint, but Ohai can't find it.\",\n )\n nil\n end", "def get_mounts\n mount_hash = {}\n mounts = File.open(\"/etc/mtab\", \"r\").read.split(\"\\n\").map{|l| l.split(/\\s+/)}\n mounts.each{|m| mount_hash[m[1]] = m[0] unless %w[devpts udev sysfs tmpfs none proc].include?(m[0])}\n mount_hash\nend", "def mounts_info\n @mounts_info ||= vault_client.request(:get, \"/v1/sys/internal/ui/mounts\")\n rescue Vault::VaultError\n unable_to_determine_version\n raise\n end", "def get_mount_path(filepath)\n cmd_exec(\"df \\\"#{filepath}\\\" | tail -1\").split(' ')[0]\n rescue\n raise \"Unable to get mount path of #{filepath}\"\n end", "def dev_stat\n begin\n @dev_stat ||= Sys::Filesystem.stat dev_path\n rescue SystemCallError\n @dev_stat = nil\n end\n end", "def get_device_mount_point( incoming_path )\n mount_lines = `mount`\n raise EBSRemoteExecException.new(nil,$?,mount_lines) if $? != 0\n path = File.ftype(incoming_path) != 'directory'? File.dirname(incoming_path) : incoming_path\n device=nil\n longest = \"\"\n mount_lines.each_line {|line|\n match = line =~ /(.+)\\son\\s(.+?)\\s.*/\n candidate = $2.strip\n candidate_device = $1.strip\n # Keep the longest prefix matching\n if match && path =~ /^#{candidate}/ && candidate.length > longest.length\n longest = candidate\n device = candidate_device\n end\n }\n unless device\n STDERR.puts \"Couldn't find the device for mount point #{path}\"\n Kernel.exit(-1)\n end\n device\n end", "def get_fs_type(device)\n fs_check = Mixlib::ShellOut.new(\"blkid -c /dev/null #{device}\")\n fs_check.run_command\n match = fs_check.stdout.match(/\\sTYPE=\\\"(.*?)\\\"/)\n match = '' if match.nil?\n\n Chef::Log.info(\"File system type for device #{device}: #{match[1]}\")\n match[1]\nend", "def GetMountString(used_fs, defaultv)\n fsmap = GetFsMap(used_fs)\n ret = Ops.get_string(fsmap, :mount_string, defaultv)\n Builtins.y2milestone(\"GetMountString used_fs:%1 ret:%2\", used_fs, ret)\n ret\n end", "def mountpoint\n 'dev/.osctl-mount-helper'\n end", "def get_fs_type(device)\n fs_check = Mixlib::ShellOut.new(\"blkid -c /dev/null #{device}\")\n fs_check.run_command\n match = fs_check.stdout.match(/TYPE=\\\"(.*)\\\"/)\n match = '' if match.nil?\n\n match[1]\nend", "def mountpoints\n mtab = IO.readlines '/proc/mounts'\n mountpoints = mtab.map{ |line| line.split(/\\s+/)[1]}\n mountpoints.map!{ |mount| unescape(mount) }\n # Ignore common system mountpoints.\n mountpoints.reject!{ |mount| mount =~ /^\\/$/ }\n mountpoints.reject!{ |mount| mount =~ /^\\/(proc|sys|usr|boot|tmp|dev|var|bin|etc|lib).*/ }\n # Mount /run/media/* but ignore other /run/ mountpoints.\n mountpoints.reject!{ |mount| mount =~ /^\\/run.*/ unless mount =~ /^\\/run\\/(media.*)/ }\n\n # Add home dir.\n mountpoints << home\n end", "def mounts\r\n @mounts.list\r\n end", "def get_filesystem\n @@current_fake ? @@current_fake[:filesystem] : ''\n end", "def mounted?(name)\n mount_loc = File.join(KVM_MOUNT_POINT, name)\n system(\"mount | grep #{mount_loc}\")\nend", "def getdiskusage\n content = \"\"\n begin\n content = `df -k`\n rescue\n warn \"Failed to run df command\"\n return nil\n end\n used_space = 0\n avail_space = 0\n content.split(\"\\n\").each do |line|\n if line =~ /\\s+\\d+\\s+(\\d+)\\s+(\\d+)\\s+\\d+%\\s+\\/($|home$)/\n used_space += $1.to_i\n avail_space += $2.to_i\n end\n end\n return {:avail_space => avail_space, :used_space => used_space}\n end", "def verify_mounted(partition)\n\treturn `grep partition /proc/mounts | wc -l`.chomp\nend", "def filesystem\n platform_service(:filesystem)\n end", "def filesystem_file(host)\n case host['platform']\n when %r{aix}\n '/etc/filesystems'\n when %r{el-|centos|fedora|sles|debian|ubuntu}\n '/etc/fstab'\n else\n # TODO: Add Solaris and OSX support, as per PUP-5201 and PUP-4823\n fail_test(\"Unable to determine filesystem table file location for #{host['platform']}\")\n end\n end", "def disk_space()\n\n instructions = 'df -h'\n r = @ssh ? @ssh.exec!(instructions) : `#{instructions}`\n\n @results[:disk_usage] = {}\n\n a = r.lines.grep(/\\/dev\\/root/)\n\n puts ('a: ' + a.inspect).debug if @debug\n\n if a.any? then\n size, used, avail = a[0].split(/ +/).values_at(1,2,3)\n\n @results[:disk_usage][:root] = {size: size, used: used, \n avail: avail}\n end\n\n a2 = r.lines.grep(/\\/dev\\/sda1/)\n\n puts ('a2: ' + a2.inspect).debug if @debug\n\n if a2.any? then\n size, used, avail = a2[0].split(/ +/).values_at(1,2,3)\n\n @results[:disk_usage][:sda1] = {size: size, used: used, \n avail: avail}\n end\n\n end", "def tmpfs_mount_status(desired)\n # Start with checking if it was mounted the way we would mount it\n # this is ALMOST the same as the 'is it identical' check for non-tmpfs\n # filesystems except that with tmpfs we don't treat 'auto' as equivalent and\n # that we skip inode64 option on current mount status - because it's activated\n # by default on Linux kernel >= 5.9\n fs_data = node.filesystem_data\n key = \"#{desired['device']},#{desired['mount_point']}\"\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n if mounted['fs_type'] == 'tmpfs'\n Chef::Log.debug(\n \"fb_fstab: tmpfs #{desired['device']} on \" +\n \"#{desired['mount_point']} is currently mounted...\",\n )\n\n skipped_opts = []\n if _are_tmpfs_using_inode64?\n\n # inode64 is active by default on tmpfs for Linux kernel > 5.9\n skipped_opts.push('inode64')\n end\n\n if compare_opts(desired['opts'], mounted['mount_options'], skipped_opts)\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n end\n end\n # OK, if that's not the case, we don't have the same device, which\n # is OK. Find out if we have something mounted at the same spot, and\n # get its device name so we can find it's entry in node['filesystem']\n if fs_data['by_mountpoint'][desired['mount_point']]\n # If we are here the mountpoints are the same...\n mounted = fs_data['by_mountpoint'][desired['mount_point']].to_hash\n # OK, if it's tmpfs as well, we're diong good\n if mounted['fs_type'] == 'tmpfs'\n Chef::Log.warn(\n \"fb_fstab: Treating #{mounted['devices']} on \" +\n \"#{desired['mount_point']} the same as #{desired['device']} on \" +\n \"#{desired['mount_point']} because they are both tmpfs.\",\n )\n Chef::Log.debug(\n \"fb_fstab: tmpfs #{desired['device']} on \" +\n \"#{desired['mount_point']} is currently mounted...\",\n )\n Chef::Log.debug(\"fb_fstab: #{desired} vs #{mounted}\")\n if compare_opts(desired['opts'], mounted['mount_options'])\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n end\n Chef::Log.warn(\n \"fb_fstab: tmpfs is desired on #{desired['mount_point']}, but \" +\n \"non-tmpfs #{mounted['devices']} (#{mounted['fs_type']}) currently \" +\n 'mounted there.',\n )\n return :conflict\n end\n :missing\n end", "def filesystem_labels\n\n labels = {}\n\n mount = capture_command_output('mount')\n mount.each do |mount_line|\n\n mount_line.strip!\n device = mount_line.match(/^(.*?) on/)[1]\n\n if PlatformInfo.linux?\n\n # /dev/hda3 on / type ext4 (rw,errors=remount-ro)\n mount_point = mount_line.match(/^#{Regexp.quote(device)} on (.*?) type/)[1]\n fs_type = mount_line.match(/type (.*?) \\(/)[1]\n\n elsif PlatformInfo.osx?\n\n # /dev/disk0s2 on / (hfs, local, journaled)\n mount_point = mount_line.match(/^#{Regexp.quote(device)} on (.*?) \\(/)[1]\n fs_type = mount_line.match(/ \\((.*?), /)[1]\n \n else\n unsupported_platform\n end\n\n labels[device] = {\n :mount_point => mount_point,\n :file_system => fs_type\n }\n\n end\n\n labels\n\n end", "def get_disk_util\n used_info = query_data(params[:host], 'df.1kblocks.used', params[:from_ts], params[:to_ts])\n total_info = query_data(params[:host], 'df.1kblocks.total', params[:from_ts], params[:to_ts])\n\n used_info.delete_if { |k, v|\n k.index(\"fstype=tmpfs\")\n }\n total_info.delete_if { |k, v|\n k.index(\"fstype=tmpfs\")\n }\n \n results = {}\n used_info.each { |k, v|\n matcher = /mount=([\\/\\w]+) /.match(k)\n if matcher\n path = matcher[1]\n\n if total_info.has_key?(k)\n total_v = total_info[k]\n total_v_map = Hash[total_v]\n results[path] = v.collect { |point|\n ts = point[0]\n if (total_v_map.has_key?(ts))\n [ts, format(\"%.2f\", point[1] * 100.0 / total_v_map[ts]).to_f]\n end\n }.keep_if { |v| v }\n end\n end\n }\n\n render json: results\n end", "def get_current_devices(output)\n lines = output.split(\"\\n\")\n partitions = lines.drop(2).map do |line|\n line.chomp.split.last\n end\n partitions.reject! do |partition|\n partition =~ /^dm-\\d/\n end\n devices = partitions.select do |partition|\n partition =~ /[a-z]$/\n end\n devices.sort!.map! {|device| \"/dev/#{device}\"}\n if devices.empty?\n devices = partitions.select do |partition|\n partition =~ /[0-9]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n end\n devices\n end", "def get_osx_disk_name(options)\n message = \"Information:\\tGetting root disk device ID\"\n command = \"df |grep '/$' |awk '{print \\\\$1}'\"\n output = execute_command(options,message,command)\n disk_id = output.chomp\n message = \"Information:\\tGetting volume name for \"+disk_id\n command = \"diskutil info #{disk_id} | grep 'Volume Name' |cut -f2 -d':'\"\n output = execute_command(options,message,command)\n volume = output.chomp.gsub(/^\\s+/,\"\")\n return volume\nend", "def mountpoint?\n begin\n stat1 = expand_tilde.lstat\n stat2 = expand_tilde.parent.lstat\n stat1.dev == stat2.dev && stat1.ino == stat2.ino ||\n stat1.dev != stat2.dev\n rescue Errno::ENOENT\n false\n end\n end", "def mount_list(www_root)\n arr = []\n %x{mount -t iso9660}.scan(/\\S+ on (\\S+)/) do |a|\n mountpoint = a[0]\n arr << mountpoint if mountpoint.match %r{#{www_root}}\n end\n arr\nend", "def fstype\n return self['fstype'] if has_key?('fstype')\n Chef::Log.info([\n self['fstype'], current[:fstype],\n File.exists?(device) && `file -s '#{device}'`.chomp,\n self,\n ].inspect)\n return current[:fstype] if current[:fstype]\n return unless File.exists?(device)\n dev_type_str = `file -s '#{device}'`.chomp\n case\n when dev_type_str =~ /SGI XFS/ then self['fstype'] = 'xfs'\n when dev_type_str =~ /Linux.*(ext[2-4])/ then self['fstype'] = $1\n else\n raise \"Can't determine filesystem type of #{device} -- set it explicitly in node[:volumes]\"\n end\n self['fstype']\n end", "def getFsPath(path)\n if path.kind_of? Array\n if path.length == 0\n localPath = @cwd.dup\n else\n localPath = normalizePath(path[0].dup)\n end\n else\n localPath = normalizePath(path.dup)\n end\n\n dl = localPath.slice!(0..1).upcase\n raise MiqException::MiqVmMountError, \"Unknown drive letter - #{dl}\" unless (fs = @driveToFS[dl])\n return fs, localPath\n end", "def mountpoint?\n begin\n stat1 = lstat\n stat2 = parent.lstat\n stat1.dev != stat2.dev or stat1.ino == stat2.ino\n rescue Errno::ENOENT\n false\n end\n end", "def other_mounts\n others = []\n fstab_lines.each do |line|\n localdevice, localmount, _fstype, _options, _freq, _pass = line.split(/\\s+/)\n others << line if localmount == mount && localdevice != device\n end\n others\n end", "def tmpfs\n\t\t\t\tret = {}\n\t\t\t\tmounts.each { |x|\n\t\t\t\t\tret.merge!({x.split[1] => x}) if x.start_with?('tmpfs '.freeze)\n\t\t\t\t}\n\t\t\t\tret\n\t\t\tend", "def mount(name, root_dev)\n puts \"Mounting KVM device: #{root_dev}\"\n mount_loc = File.join(KVM_MOUNT_POINT, name)\n unless(system(\"mount | grep #{mount_loc}\"))\n FileUtils.mkdir_p(mount_loc)\n if(system(\"mount #{root_dev} #{mount_loc}\"))\n mount_loc\n else\n raise \"Failed to mount #{root_dev} to #{mount_loc}\"\n end\n else\n puts \"Device already mounted (#{mount_loc})\"\n mount_loc\n end\nend", "def lsof\n Dir.new(\"/proc/#{Process.pid}/fd/\").entries\n end", "def mount_command(path)\n \"udisksctl mount --block-device #{path}\"\nend", "def filesystem_data\n self['filesystem2'] || self['filesystem']\n end", "def get_current_devices(proc_partitions_output)\n lines = proc_partitions_output.split(\"\\n\")\n partitions = lines.drop(2).map do |line|\n line.chomp.split.last\n end.reject do |partition|\n partition =~ /^dm-\\d/\n end\n devices = partitions.select do |partition|\n partition =~ /[a-z]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n if devices.empty?\n devices = partitions.select do |partition|\n partition =~ /[0-9]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n end\n devices\n end", "def DetectFs(device)\n ret = :unknown\n Builtins.y2milestone(\"DetectFs:%1\", device)\n vinfo = ::Storage::VolumeInfo.new()\n r = @sint.getVolume(device, vinfo)\n if r != 0\n Builtins.y2error(\"DetectFs device:%1 not found (ret:%2)\", device, r)\n else\n curr = {}\n curr = volumeMap(vinfo, curr)\n ret = Ops.get_symbol(curr, \"detected_fs\", :unknown)\n end\n Builtins.y2milestone(\"DetectFs ret %1\", ret)\n ret\n end", "def format_mount(partition, mount)\n\n # Partitions that we already have mounts set for.\n return nil if partition == '/dev/mapper/rootvg-slash'\n return nil if partition == '/dev/mapper/rootvg-var'\n return nil if partition == '/dev/mapper/rootvg-tmp'\n\n mount\nend", "def mount_status(desired)\n # We treat tmpfs specially. While we don't want people to mount tmpfs with\n # a device of 'none' or 'tmpfs', we also don't want to make them remount\n # (and lose all their data) just to convert to fb_fstab. So we'll make\n # them use a new name in the config, but we will treat the pre-mounted\n # mounts as valid/the same. Besides, since the device is meaningless, we\n # can just ignore it for the purposes of this test anyway.\n if desired['type'] == 'tmpfs'\n return tmpfs_mount_status(desired)\n end\n\n key = \"#{desired['device']},#{desired['mount_point']}\"\n fs_data = node.filesystem_data\n mounted = nil\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n else\n key = \"#{desired['device']}/,#{desired['mount_point']}\"\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n end\n end\n\n if mounted\n Chef::Log.debug(\n \"fb_fstab: There is an entry in node['filesystem'] for #{key}\",\n )\n # If it's a virtual device, we require the fs type to be identical.\n # otherwise, we require them to be similar. This is because 'auto'\n # is meaningless without a physical device, so we don't want to allow\n # it to be the same.\n if compare_fstype(desired['type'], mounted['fs_type']) ||\n (desired['device'].start_with?('/') &&\n [desired['type'], mounted['fs_type']].include?('auto'))\n Chef::Log.debug(\n \"fb_fstab: FS #{desired['device']} on #{desired['mount_point']}\" +\n ' is currently mounted...',\n )\n if compare_opts(desired['opts'], mounted['mount_options'])\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n else\n Chef::Log.warn(\n \"fb_fstab: Device #{desired['device']} is mounted at \" +\n \"#{mounted['mount']} as desired, but with fstype \" +\n \"#{mounted['fs_type']} instead of #{desired['type']}\",\n )\n return :conflict\n end\n end\n\n # In this case we don't have the device we expect at the mountpoint we\n # expect. Assuming it's not NFS/Gluster which can be mounted in more than\n # once place, we look up this device and see if it moved or just isn't\n # mounted\n unless ['nfs', 'nfs4', 'glusterfs'].include?(desired['type'])\n device = fs_data['by_device'][desired['device']]\n # Here we are checking if the device we want\n # has already a mount defined\n # We want to return :moved if it does except\n # in the case when it's a btrfs\n # disk and our desired and current options\n # are trying to mount different subvolumes\n if device && device['mounts'] && !device['mounts'].empty? &&\n !(\n FB::Fstab.btrfs_subvol?(\n device['fs_type'],\n device['mount_options'].join(','),\n ) &&\n FB::Fstab.btrfs_subvol?(\n desired['type'],\n desired['opts'],\n ) &&\n !FB::Fstab.same_subvol?(\n device['mounts'][0],\n device['mount_options'].join(','),\n desired['opts'],\n )\n )\n\n Chef::Log.warn(\n \"fb_fstab: #{desired['device']} is at #{device['mounts']}, but\" +\n \" we want it at #{desired['mount_point']}\",\n )\n return :moved\n end\n end\n\n # Ok, this device isn't mounted, but before we return we need to check\n # if anything else is mounted where we want to be.\n if fs_data['by_mountpoint'][desired['mount_point']]\n devices = fs_data['by_mountpoint'][\n desired['mount_point']]['devices']\n Chef::Log.warn(\n \"fb_fstab: Device #{desired['device']} desired at \" +\n \"#{desired['mount_point']} but something #{devices} already \" +\n 'mounted there.',\n )\n return :conflict\n end\n :missing\n end", "def determine_disk\n df_cmd = \"df 2>/dev/null|awk '$1 ~ /\\\\// {I=I+$3} END {print I}'\"\n disk = @shell.query('DISK_DF', df_cmd)\n\n # Result is expected to be in KiB. Convert to GB.\n @info[:disk] = disk.to_f / 1000 ** 2\n end", "def filesystem_usage\n\n usage = {}\n\n df = capture_command_output('df', '-k')[1..-1] # Don't include the column headers.\n df.each do |df_line|\n\n df_line.strip!\n device = df_line.match(/^(.*?)\\s{2,}/)[1]\n tokens = df_line.gsub(/^#{Regexp.quote(device)}\\s+/, '').split(/\\s+/, 5)\n \n # Convert all KB values to bytes.\n size = tokens[0].to_i * 1024\n used = tokens[1].to_i * 1024\n available = tokens[2].to_i * 1024\n used_percentage = tokens[3].to_i\n\n usage[device] = {\n :size => size,\n :used => used,\n :used_percentage => used_percentage,\n :available => available\n }\n\n end\n\n usage\n\n end", "def get_partition_info\n # remove leading slash so it matches the packages.DU path\n remove_slash = true\n\n if !Stage.initial\n # read /proc/mounts as a list of maps\n # $[\"file\":\"/boot\", \"freq\":0, \"mntops\":\"rw\", \"passno\":0, \"spec\":\"/dev/sda1\", \"vfstype\":\"ext2\"]\n mounts = Convert.convert(\n SCR.Read(path(\".proc.mounts\")),\n :from => \"any\",\n :to => \"list <map <string, any>>\"\n )\n Builtins.y2milestone(\"mounts %1\", mounts)\n\n partitions = []\n Builtins.foreach(mounts) do |mpoint|\n name = Ops.get_string(mpoint, \"file\", \"\")\n if Builtins.substring(name, 0, 1) == \"/\" &&\n Builtins.substring(name, 0, 5) != \"/dev/\" && # filter out /dev/pts etc.\n Ops.get_string(mpoint, \"vfstype\", \"\") != \"rootfs\" # filter out duplicate \"/\" entry\n capacity = Pkg.TargetCapacity(name)\n if capacity != 0 # dont look at pseudo-devices (proc, shmfs, ...)\n used = Pkg.TargetUsed(name)\n partitions = Builtins.add(\n partitions,\n {\n \"name\" => name,\n \"free\" => Ops.subtract(capacity, used),\n \"used\" => used\n }\n )\n end\n end\n end\n Pkg.TargetInitDU(partitions)\n Builtins.y2milestone(\"get_partition_info: %1\", partitions)\n return deep_copy(partitions)\n end # !Stage::initial ()\n\n # remove the previous failures\n @failed_mounts = []\n\n # installation stage - Storage:: is definitely present\n # call Storage::GetTargetMap()\n targets = Convert.convert(\n WFM.call(\"wrapper_storage\", [\"GetTargetMap\"]),\n :from => \"any\",\n :to => \"map <string, map>\"\n )\n\n if targets == nil\n Builtins.y2error(\"Target map is nil, Storage:: is probably missing\")\n end\n\n if Mode.test\n targets = Convert.convert(\n SCR.Read(path(\".target.yast2\"), \"test_target_map.ycp\"),\n :from => \"any\",\n :to => \"map <string, map>\"\n )\n end\n\n target_partitions = []\n min_spare = 20 * 1024 * 1024 # minimum free space ( 20 MB )\n\n Builtins.foreach(targets) do |disk, diskinfo|\n part_info = Ops.get_list(diskinfo, \"partitions\", [])\n Builtins.foreach(part_info) do |part|\n Builtins.y2milestone(\"Adding partition: %1\", part)\n used_fs = Ops.get_symbol(part, \"used_fs\", :unknown)\n # ignore VFAT and NTFS partitions (bnc#)\n if used_fs == :vfat || used_fs == :ntfs\n Builtins.y2warning(\n \"Ignoring partition %1 with %2 filesystem\",\n Ops.get_string(part, \"device\", \"\"),\n used_fs\n )\n else\n free_size = 0\n\n if Ops.get(part, \"mount\") != nil &&\n Builtins.substring(Ops.get_string(part, \"mount\", \"\"), 0, 1) == \"/\"\n if Ops.get(part, \"create\") == true ||\n Ops.get(part, \"delete\") == false ||\n Ops.get(part, \"create\") == nil &&\n Ops.get(part, \"delete\") == nil\n Builtins.y2debug(\n \"get_partition_info: adding partition: %1\",\n part\n )\n\n # get free_size on partition in kBytes\n free_size = Ops.multiply(\n Ops.get_integer(part, \"size_k\", 0),\n 1024\n )\n free_size = Ops.subtract(free_size, min_spare)\n\n # free_size smaller than min_spare, fix negative value\n if Ops.less_than(free_size, 0)\n Builtins.y2milestone(\"Fixing free size: %1 to 0\", free_size)\n free_size = 0\n end\n\n used = 0\n if !(Ops.get_boolean(part, \"create\", false) ||\n Ops.get_boolean(part, \"format\", false))\n tmpdir = Convert.to_string(SCR.Read(path(\".target.tmpdir\")))\n tmpdir = Ops.add(tmpdir, \"/diskspace_mount\")\n SCR.Execute(\n path(\".target.bash\"),\n Builtins.sformat(\"test -d %1 || mkdir -p %1\", tmpdir)\n )\n\n # mount in read-only mode (safer)\n mount_options = [\"ro\"]\n\n # add \"nolock\" if it's a NFS share (bnc#433893)\n if used_fs == :nfs\n Builtins.y2milestone(\"Mounting NFS with 'nolock' option\")\n mount_options = Builtins.add(mount_options, \"nolock\")\n end\n\n # join the options\n mount_options_str = Builtins.mergestring(mount_options, \",\")\n\n mount_command = Builtins.sformat(\n \"/bin/mount -o %1 %2 %3\",\n mount_options_str,\n Ops.get_string(part, \"device\", \"\"),\n tmpdir\n )\n\n Builtins.y2milestone(\n \"Executing mount command: %1\",\n mount_command\n )\n\n result = Convert.to_integer(\n SCR.Execute(path(\".target.bash\"), mount_command)\n )\n Builtins.y2milestone(\"Mount result: %1\", result)\n\n if result == 0\n partition = Convert.convert(\n SCR.Read(path(\".run.df\")),\n :from => \"any\",\n :to => \"list <map <string, string>>\"\n )\n Builtins.foreach(partition) do |p|\n if Ops.get_string(p, \"name\", \"\") == tmpdir\n Builtins.y2internal(\"P: %1\", p)\n free_size = Ops.multiply(\n Builtins.tointeger(Ops.get_string(p, \"free\", \"0\")),\n 1024\n )\n used = Ops.multiply(\n Builtins.tointeger(Ops.get_string(p, \"used\", \"0\")),\n 1024\n )\n end\n end\n SCR.Execute(\n path(\".target.bash\"),\n Builtins.sformat(\"/bin/umount %1\", tmpdir)\n )\n else\n Builtins.y2error(\n \"Mount failed, ignoring partition %1\",\n Ops.get_string(part, \"device\", \"\")\n )\n @failed_mounts = Builtins.add(@failed_mounts, part)\n\n next\n end\n else\n # for formatted partitions estimate free system size\n # compute fs overhead\n used = EstimateFsOverhead(part)\n\n if Ops.greater_than(used, 0)\n Builtins.y2milestone(\n \"Partition %1: assuming fs overhead: %2kB\",\n Ops.get_string(part, \"device\", \"\"),\n Ops.divide(used, 1024)\n )\n end\n\n # journal size\n js = 0\n\n if ExtFs(used_fs)\n js = ExtJournalSize(part)\n reserved = ReservedSpace(part)\n\n if Ops.greater_than(reserved, 0)\n used = Ops.add(used, reserved)\n end\n elsif used_fs == :xfs\n js = XfsJournalSize(part)\n elsif used_fs == :reiser\n js = ReiserJournalSize(part)\n elsif used_fs == :jfs\n js = JfsJournalSize(part)\n else\n Builtins.y2warning(\n \"Unknown journal size for filesystem: %1\",\n used_fs\n )\n end\n\n if Ops.greater_than(js, 0)\n Builtins.y2milestone(\n \"Partition %1: assuming journal size: %2kB\",\n Ops.get_string(part, \"device\", \"\"),\n Ops.divide(js, 1024)\n )\n used = Ops.add(used, js)\n end\n\n # decrease free size\n free_size = Ops.subtract(free_size, used)\n\n # check for underflow\n if Ops.less_than(free_size, 0)\n Builtins.y2milestone(\"Fixing free size: %1 to 0\", free_size)\n free_size = 0\n end\n end\n\n # convert into kB for TargetInitDU\n free_size = Ops.divide(free_size, 1024)\n used = Ops.divide(used, 1024)\n\n Builtins.y2milestone(\n \"available partition: mount: %1, free: %2 KB, used: %3 KB\",\n Ops.get_string(part, \"mount\", \"\"),\n free_size,\n used\n )\n if !remove_slash\n target_partitions = Builtins.add(\n target_partitions,\n {\n \"name\" => Ops.get_string(part, \"mount\", \"\"),\n \"used\" => used,\n \"free\" => free_size\n }\n )\n else\n part_name = \"\"\n mount_name = Ops.get_string(part, \"mount\", \"\")\n\n if mount_name != \"/\"\n part_name = Builtins.substring(\n mount_name,\n 1,\n Builtins.size(mount_name)\n )\n else\n part_name = mount_name\n end\n\n target_partitions = Builtins.add(\n target_partitions,\n { \"name\" => part_name, \"used\" => used, \"free\" => free_size }\n )\n end\n end\n end\n end\n end # foreach (`part)\n end # foreach (`disk)\n\n # add estimated size occupied by non-package files\n target_partitions = EstimateTargetUsage(target_partitions)\n\n Builtins.y2milestone(\"get_partition_info: part %1\", target_partitions)\n Pkg.TargetInitDU(target_partitions)\n\n deep_copy(target_partitions)\n end", "def get_1st_partition(device)\n # Resolves the real device name (ex. /dev/sdg)\n Chef::Log.info(\"Getting 1st partition for device: #{device}\")\n fs_check = Mixlib::ShellOut.new(\"lsblk -ln -o Name #{device}|awk 'NR==2'\")\n fs_check.run_command\n partition = \"/dev/\" + fs_check.stdout.strip\n Chef::Log.info(\"1st partition for device: #{device} is: #{partition}\")\n partition\nend", "def format_filesystem(system_arch, device)\n fs_type = system_arch == \"x86_64\" ? \"XFS\" : \"ext4\"\n puts \"Formatting #{fs_type} filesystem on #{device} ...\"\n\n command = case system_arch\n when \"x86_64\" then \"/sbin/mkfs.xfs -f #{device}\"\n else \"/sbin/mkfs.ext4 -F #{device}\"\n end\n IO.popen(command) do |f|\n while ! f.eof\n puts f.gets\n end\n end\n end", "def forks\n `vmstat -f`.split.first\n end", "def do_ls()\n\t\tif @system_type == WINDOWS then \n\t\t\treturn %x(dir #{@path})\n\t\tend \n\t\tif @system_type == UNIX then \n\t\t\treturn %x(ls #{@path})\n\t\tend\n\tend", "def setup_device_for_mount\n # use ramdisk for creating a test device for mount.\n # This can cleaner if we have chef resource/provider for ramdisk.\n case ohai[:platform_family]\n when \"aix\"\n # On AIX, we can't create a ramdisk inside a WPAR, so we use\n # a \"namefs\" mount against / to test\n # https://www-304.ibm.com/support/knowledgecenter/ssw_aix_71/com.ibm.aix.performance/namefs_file_sys.htm\n device = \"/\"\n fstype = \"namefs\"\n when \"debian\", \"rhel\", \"amazon\"\n device = \"/dev/ram1\"\n unless File.exist?(device)\n shell_out(\"mknod -m 660 #{device} b 1 0\")\n shell_out(\"chown root:disk #{device}\")\n end\n shell_out(\"ls -1 /dev/ram*\").stdout.each_line do |d|\n if shell_out(\"mount | grep #{d}\").exitstatus == \"1\"\n # this device is not mounted, so use it.\n device = d\n break\n end\n end\n fstype = \"tmpfs\"\n shell_out!(\"mkfs -q #{device} 512\")\n when \"solaris2\"\n device = \"swap\"\n fstype = \"tmpfs\"\n else\n end\n [device, fstype]\n end", "def ip_by_mount(name)\n dev = available_dev unless mounted?(name)\n loc = mount(name, dev)\n addr = %x{cat #{File.join(loc, 'etc', 'network', 'interfaces')} | grep address}.split(' ').last.to_s.strip\n unmount_kvm_volume(name, dev) if dev\n addr\nend", "def read()\n File.open(\"/tmp/mount/y0\", \"r\").read.to_f\nend", "def pretty_info\n s = ''\n dev = self.device\n return \"Disk image: #{self.image_path.basename} (na, detached, na)\\n\" if dev.nil?\n return dev.pretty_info\n end", "def list_partitions #by nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{print $1}'`.chomp.split\nend", "def unmount\n if !is_mounted?\n warning('dev, sys, and proc are already unmounted')\n else\n announcing 'Unmounting dev, sys, and proc' do\n dirs = %w[ dev sys proc ]\n dirs.each{|dir| cmd(\"umount -l #{$chrootdir}/#{dir}\", exit=false) }\n end\n end\n end", "def mountpoint?\n begin\n stat1 = self.lstat\n stat2 = self.parent.lstat\n stat1.dev == stat2.dev && stat1.ino == stat2.ino ||\n stat1.dev != stat2.dev\n rescue Errno::ENOENT\n false\n end\n end", "def get_device_info()\n @errors = []\n info = {}\n return info unless @programmer_path\n\n response = IO.popen(\"#{@programmer_path} I\").readlines\n puts response if $debug\n response.each do |line|\n if line =~ /Error/i\n errors << line\n else\n parts = line.split(/:|\\.\\.\\./)\n info[parts[0].strip.split.join.to_sym] = parts[1].strip if parts.size == 2\n end\n end # each\n info\n end", "def fs_value(p, val)\n key = case val\n when 'size'\n 'kb_size'\n when 'used'\n 'kb_used'\n when 'available'\n 'kb_available'\n when 'percent'\n 'percent_used'\n else\n fail \"fb_helpers: Unknown FS val #{val} for node.fs_value\"\n end\n fs = self.filesystem_data\n # Some things like /dev/root and rootfs have same mount point...\n if fs && fs['by_mountpoint'] && fs['by_mountpoint'][p] &&\n fs['by_mountpoint'][p][key]\n return fs['by_mountpoint'][p][key].to_f\n end\n\n Chef::Log.warn(\n \"fb_helpers: Tried to get filesystem information for '#{p}', but it \" +\n 'is not a recognized filesystem, or does not have the requested info.',\n )\n nil\n end", "def umount(partitions)\n partitions.each do |p|\n next unless p['mountpoint']\n\n return nil unless umount_dev(p['path'])\n end\n end", "def name\n File.join(\"/dev/\",@device.gsub(/!/, \"/\"))\n end", "def getmountedvolumes\n # only support Linux for now\n return {} unless Facter['kernel'] && Facter['kernel'].value == 'Linux'\n\n dir = \"/etc\"\n mounted = {}\n\n # AUTOFS - gather only files named auto[._]*\n Dir.glob(File.join(dir, \"*\")).each do |file|\n next if file !~ /^auto[._].*/\n\n # AUTOFS - match only lines that look like nfs syntax such as host:/path\n IO.foreach(file) do |line|\n if line =~ /\\w:\\S/ && line !~ /^\\s*#/\n # Parse it, Example : \" nventory_backup -noatime,intr irvnetappbk:/vol/nventory_backup \"\n if line =~ /^(\\w[\\w\\S]+)\\s+\\S+\\s+(\\w[\\w\\S]+):(\\S+)/\n mnt = $1\n host = $2\n vol = $3\n mounted[\"volumes[mounted][/mnt/#{mnt}][config]\"] = file\n mounted[\"volumes[mounted][/mnt/#{mnt}][volume_server]\"] = host\n mounted[\"volumes[mounted][/mnt/#{mnt}][volume]\"] = vol\n mounted[\"volumes[mounted][/mnt/#{mnt}][type]\"] = 'nfs'\n end\n end\n end # IO.foreach\n end # Dir.glob\n\n # FSTAB - has diff syntax than AUTOFS. Example: \"server:/usr/local/pub /pub nfs rsize=8192,wsize=8192,timeo=14,intr\"\n IO.foreach(\"/etc/fstab\") do |line|\n if line =~ /^(\\w[\\w\\S]+):(\\S+)\\s+(\\S+)\\s+nfs/\n host = $1\n vol = $2\n mnt = $3\n mounted[\"volumes[mounted][#{mnt}][config]\"] = \"/etc/fstab\"\n mounted[\"volumes[mounted][#{mnt}][volume_server]\"] = host\n mounted[\"volumes[mounted][#{mnt}][volume]\"] = vol\n mounted[\"volumes[mounted][#{mnt}][type]\"] = 'nfs'\n end\n end # IO.foreach\n return mounted\n end", "def file_system(op, path)\n path = @mudlib_path + path\n if op == :ls\n return Dir.entries(path)\n elsif op == :cat\n if File.file?(path)\n\treturn File.read(path)\n else\n\treturn \"File not found\"\n end\n end\n end", "def unmount_command(path)\n \"udisksctl unmount --block-device #{path}\"\nend", "def sys\n return `uname -n`.chomp\n end", "def pretty_info\n volinfo = self.info\n mountpoint = volinfo['MountPoint']\n mountpoint = 'Not mounted' if mountpoint.empty?\n rw = volinfo['WritableVolume'] ? 'writable' : 'read-only'\n ownership = self.ownership_enabled? ? 'ownership enabled' : 'no ownership'\n return volinfo['VolumeName'] + \" (#{self.dev_node}, #{mountpoint}, #{rw}, #{ownership})\\n\" \n end", "def mounted?\n '' != self['MountPoint']\n end", "def mounted?\n !!( attached? && mount_point && File.exists?(mount_point) && current[:mount] == mount_point )\n end", "def guest_device(name, mount_point_obj)\n \"/dev/#{guest_vg_name(name, mount_point_obj)}/#{guest_lv_name(mount_point_obj)}\"\n end", "def mount_paths_listing\n Dir[\"#{mounts_path}/*\"]\n end", "def mountpoint\n \"#{spec[:temp_dir]}\"\n end", "def dev_node\n disk_info = self.info\n return nil if disk_info.nil?\n return disk_info['system-entities'][0]['dev-entry']\n end", "def mount_point\n Pathname.new(self['MountPoint'])\n end", "def nbd_device\n sys_parts = lsblk('')\n nbds = []\n\n sys_parts.each do |p|\n m = p['name'].match(/nbd(\\d+)/)\n next unless m\n\n nbds << m[1].to_i\n end\n\n nbds_max.times do |i| # if nbds_max returns 0 block is skipped\n return \"/dev/nbd#{i}\" unless nbds.include?(i)\n end\n\n OpenNebula.log_error(\"#{__method__}: Cannot find free nbd device\")\n\n ''\n end", "def get_parent child_path\n parent_maj_min = nil\n if DEBUG_MODE or Platform.ubuntu? or Platform.fedora?\n command = \"udevadm\"\n params = \" info --query=property --name=#{child_path}\"\n end\n udevadm = CommandsExecutor.new command, params\n udevadm.execute false, false # None blocking and not debug mode\n raise \"Command execution error: #{udevadm.stderr.read}\" if not udevadm.success?\n udevadm.result.each_line do |line|\n line.squish!\n key = 'ID_PART_ENTRY_DISK'\n _key, value = line.split '='\n parent_maj_min = value and break if _key.eql? key\n end\n\n if DEBUG_MODE or Platform.ubuntu? or Platform.fedora?\n command = \"lsblk\"\n params = \" -b -P -o VENDOR,MODEL,TYPE,SIZE,KNAME,UUID,LABEL,MOUNTPOINT,FSTYPE,RM,MAJ:MIN\"\n end\n lsblk = CommandsExecutor.new command, params\n lsblk.execute\n raise \"Command execution error: #{lsblk.stderr.read}\" if not lsblk.success?\n lsblk.result.each_line do |line|\n data_hash = {}\n line.squish!\n line_data = line.gsub!(/\"(.*?)\"/, '\\1#').split \"#\"\n line_data.each do |data|\n data.strip!\n key, value = data.split \"=\"\n data_hash[key.downcase] = value\n return data_hash['kname'] if value == parent_maj_min\n end\n end\n raise \"Unable to find parent device for #{child_path}\"\n end", "def get_cgroup_attribute_nocgget(attribute, username)\n begin\n value = nil\n File.open('/proc/mounts', File::RDONLY) do |mounts|\n mounts.each do |l|\n if l =~ /^\\S+\\s+(\\S+)\\s+cgroup\\s+/\n begin\n File.open(File.join($1, \"openshift\", username, attribute), File::RDONLY) do |cgfile|\n value = cgfile.read.strip\n end\n rescue\n end\n end\n end\n end\n rescue\n end\n if value.nil?\n $stderr.puts \"Could not find attribute #{attribute}\"\n exit 2\n end\n value\nend", "def stat_char(filename)\r\n return nil if !File.exists?(filename)\r\n\r\n return '/' if File.directory?(filename)\r\n return '%' if File.chardev?(filename)\r\n return '#' if File.blockdev?(filename)\r\n return '@' if File.symlink?(filename)\r\n return '=' if File.socket?(filename)\r\n return '|' if File.pipe?(filename)\r\n return '*' if File.executable?(filename)\r\n nil\r\n end", "def get_online_disk_command()\n if @os_info.major < 6; \"online noerr\" else; \"online disk noerr\" end\n end", "def info\n Plist::parse_xml(diskutil 'info', '-plist', @dev_node)\n end", "def mountpoint\n self\n end", "def mountpoint\n self\n end", "def kernel_name\n uname('-s')\n end", "def getClockId(path)\n return 0 unless path\n fd = IO.sysopen(path, Fcntl::O_RDWR)\n # From missing.h in linuxptp\n fd\n end", "def filesystem_type(host)\n case host['platform']\n when %r{aix}\n 'jfs2'\n when %r{el-|centos|fedora|sles|debian|ubuntu}\n 'ext3'\n else\n # TODO: Add Solaris and OSX support, as per PUP-5201 and PUP-4823\n fail_test(\"Unable to determine a standard filesystem table type for #{host['platform']}\")\n end\n end", "def current\n return {} unless device && node[:filesystem] && node[:filesystem][ device ]\n curr = Mash.new(node[:filesystem][ device ].to_hash)\n curr['fstype'] ||= curr['fs_type']\n curr\n end", "def mount options = {}\n opts = {\n :force_readonly => false\n }.merge!(options)\n args = []\n args << 'readOnly' if opts[:force_readonly]\n args << opts[:mountpoint] if opts.has_key?(:mountpoint)\n args << self.dev_node\n diskutil 'mount', *args\n end", "def pwd\r\n ndev.rpc.command(\"show cli directory\").text.strip\r\n end", "def test_mountstring\n mount = nil\n name = \"yaytest\"\n path = tmpdir\n assert_nothing_raised {\n mount = Puppet::Network::Handler.fileserver::Mount.new(name, path)\n }\n\n assert_equal(\"mount[#{name}]\", mount.to_s)\n end", "def get_unix_info()\n v = $VERBOSE\n $VERBOSE = nil\n sysname = `uname -s`\n $VERBOSE = v\n sysname = sysname.chomp\n\n if(sysname.include?(\"Linux\")) # for linux (rhel, suse, oel)\n # check if it is SUSE\n filepath = Pathname.new(\"/etc/SuSE-release\")\n if(filepath.exist?())\n release_file = '/etc/SuSE-release'\n else # for RHEL, OEL, etc.\n release_file = '/etc/issue'\n end\n\n $VERBOSE = nil\n flavor = `head -n 1 #{release_file}`\n $VERBOSE = v\n sysname = flavor.sub(/\\(\\w+\\)/, '').chomp\n sysname = sysname.sub(/\\s+\\Z/, \"\")\n\n else # for other unix platforms (solaris, aix, hpux)\n $VERBOSE = nil\n if(sysname.eql?(\"AIX\"))\n version = `oslevel`\n else\n version = `uname -r`\n end\n $VERBOSE = v\n sysname = sysname + \" \" + version.chomp\n end\n\n $VERBOSE = nil\n if(sysname.eql?(\"HP-UX\"))\n processor = `uname -m`\n else\n processor = `uname -p`\n end\n\n if(sysname.include?(\"SunOS\"))\n isainfo = `isainfo -b`\n isainfo = isainfo.chomp\n bitinfo = \" \" + isainfo + \"-bit\"\n else\n bitinfo = \"\"\n end\n $VERBOSE = v\n\n os_info = sysname + \" \" + processor.chomp + bitinfo\n os_info\nend", "def statfs(ctx,path)\n return wrap_context(ctx,__method__,path) if ctx\n block_size = 1024\n\n stats = @root.statistics(path)\n case stats\n when Array\n used_space, used_files, total_space, total_files = stats\n used_files ||= 0\n used_space ||= 0\n total_files ||= used_files\n total_space ||= used_space\n result = RFuse::StatVfs.new(\n \"bsize\" => block_size,\n \"frsize\" => block_size,\n \"blocks\" => total_space / block_size,\n \"bfree\" => (total_space - used_space)/block_size,\n \"bavail\" => (total_space - used_space)/block_size,\n \"files\" => total_files,\n \"ffree\" => (total_files - used_files)\n )\n return result\n else\n #expected to quack like rfuse:statvfs\n return stats\n end\n end", "def IsMounted(mountpoint)\n if Builtins.substring(\n mountpoint,\n Ops.subtract(Builtins.size(mountpoint), 1),\n 1\n ) == \"/\"\n mountpoint = Builtins.substring(\n mountpoint,\n 0,\n Ops.subtract(Builtins.size(mountpoint), 1)\n )\n end\n\n ret = true\n Builtins.foreach(@activated) do |e|\n if Ops.get_string(e, :type, \"\") == \"mount\" &&\n (Ops.get_string(e, :mntpt, \"\") == mountpoint ||\n Ops.get_string(e, :mntpt, \"\") == Ops.add(mountpoint, \"/\"))\n ret = true\n end\n end\n ret\n end", "def get_os\n line = Cocaine::CommandLine.new('uname')\n output = line.run\n\n output.chomp.downcase.intern\n end", "def kvm_type(name)\n base = File.join(KVM_HOME, name, 'rootfs', 'etc')\n if(File.exists?(lsb = File.join(base, 'lsb-release')))\n File.readlines(lsb).last.split('=').last.strip.gsub('\"', '')\n elsif(File.exists?(sys_rel = File.join(base, 'system-release')))\n File.readlines(sys_rel).first.strip\n elsif(File.exists?(deb_ver = File.join(base, 'debian_version')))\n \"Debain #{File.read(deb_ver).strip}\"\n else\n 'UNKNOWN'\n end\nend", "def fetch_disk_size\n total_size = 0\n total_size = `lsblk -b --output SIZE -d -n | paste -s -d + - | bc`\n number_to_human_size total_size\n end", "def path\n if location =~ /^\\/dev/\n \"dev:#{location}\"\n elsif location =~ /iso$/\n \"iso:#{location}\"\n elsif location.is_a?(Integer)\n \"disc:#{location}\"\n elsif location =~ /^disc/\n location\n else\n raise RuntimeError\n end\n end", "def path\n if location =~ /^\\/dev/\n \"dev:#{location}\"\n elsif location =~ /iso$/\n \"iso:#{location}\"\n elsif location.is_a?(Integer)\n \"disc:#{location}\"\n elsif location =~ /^disc/\n location\n else\n raise RuntimeError\n end\n end", "def get_drive\n begin\n q = @db_connection.query('SELECT @@tmpdir;')\n q.each { |x| @tmp=x[0]; }\n return @tmp[0]\n rescue Mysql::Error => e\n print_error(\"Problem getting drive from @@tmpdir!\")\n puts \"\\t=> \".white + \"#{e}\".light_red\n return nil\n end\n end", "def systemctl\n @systemctl ||= which(\"systemctl\")\n end", "def systemctl\n @systemctl ||= which(\"systemctl\")\n end", "def read_device_info (device, kind)\n kind = kind.to_sym\n kinds = [:ip, :udid, :serial]\n unless kinds.include?(kind)\n raise \"#{kind} must be one of '#{kinds}'\"\n end\n cmd = \"cat ~/.xamarin/devices/#{device}/#{kind} | tr -d '\\n'\"\n `#{cmd}`\nend", "def list_nix_partitions # nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\" && $6==\"83\") print $1;else {if ($5==\"83\") print $1}}'`.chomp.split\nend", "def sfdisk_get_size(dev_name)\n out = %x{sfdisk #{dev_name} -s}\n Chef::Log.info(\"updating geo using sfdisk: #{out}\")\n\n # sfdisk sees the world as 1k blocks\n @current.blocks(out.to_i)\nend" ]
[ "0.68751645", "0.6759435", "0.6738563", "0.6627858", "0.662304", "0.6616091", "0.65095633", "0.6439599", "0.64104897", "0.640019", "0.63009113", "0.6202191", "0.6198536", "0.61742616", "0.6166239", "0.6055224", "0.6003462", "0.6000581", "0.59881014", "0.57667184", "0.56954557", "0.56689245", "0.56431293", "0.56355685", "0.5631309", "0.56285834", "0.5627067", "0.56258744", "0.5601559", "0.5595638", "0.5589984", "0.55894476", "0.55826557", "0.5567696", "0.55503863", "0.5542799", "0.5537049", "0.5528042", "0.5501633", "0.54969853", "0.5483774", "0.5480622", "0.5428163", "0.5425577", "0.5392689", "0.53823876", "0.53800714", "0.53600365", "0.5343577", "0.5336491", "0.53349864", "0.5326663", "0.53100175", "0.529416", "0.52898645", "0.52724856", "0.52582294", "0.52407396", "0.5239994", "0.5228976", "0.52107257", "0.52064246", "0.5195239", "0.518238", "0.5180694", "0.5166188", "0.5163134", "0.5162933", "0.5148461", "0.5146664", "0.51329786", "0.5130944", "0.5120362", "0.5102393", "0.509429", "0.5082928", "0.5077388", "0.50562507", "0.50562507", "0.5036921", "0.49908885", "0.4980591", "0.49640405", "0.4960555", "0.49591", "0.49528402", "0.49456817", "0.4943813", "0.49396706", "0.4922847", "0.49127144", "0.49055597", "0.48995304", "0.48995304", "0.4894562", "0.48942104", "0.48942104", "0.4886821", "0.48865002", "0.48632875" ]
0.5600199
29
Reads /proc/mounts and returns the options used for mounting /. It returns a String. But if the info isn't available or /proc/mounts is not readable, it will return an empty frozen string.
def root_mount_options find_root[3].to_s end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mounts_info\n @mounts_info ||= vault_client.request(:get, \"/v1/sys/internal/ui/mounts\")\n rescue Vault::VaultError\n unable_to_determine_version\n raise\n end", "def get_mounts\n mount_hash = {}\n mounts = File.open(\"/etc/mtab\", \"r\").read.split(\"\\n\").map{|l| l.split(/\\s+/)}\n mounts.each{|m| mount_hash[m[1]] = m[0] unless %w[devpts udev sysfs tmpfs none proc].include?(m[0])}\n mount_hash\nend", "def is_mounted?(device)\n system(\"grep -q '#{device}' /proc/mounts\")\nend", "def mountpoints\n mtab = IO.readlines '/proc/mounts'\n mountpoints = mtab.map{ |line| line.split(/\\s+/)[1]}\n mountpoints.map!{ |mount| unescape(mount) }\n # Ignore common system mountpoints.\n mountpoints.reject!{ |mount| mount =~ /^\\/$/ }\n mountpoints.reject!{ |mount| mount =~ /^\\/(proc|sys|usr|boot|tmp|dev|var|bin|etc|lib).*/ }\n # Mount /run/media/* but ignore other /run/ mountpoints.\n mountpoints.reject!{ |mount| mount =~ /^\\/run.*/ unless mount =~ /^\\/run\\/(media.*)/ }\n\n # Add home dir.\n mountpoints << home\n end", "def device_of_mount(m)\n unless Pathname.new(m).mountpoint?\n Chef::Log.warn(\n \"#{m} is not a mount point - I can't determine its device.\",\n )\n return nil\n end\n node['filesystem2']['by_pair'].to_hash.each do |pair, info|\n # we skip fake filesystems 'rootfs', etc.\n next unless pair.start_with?('/')\n # is this our FS?\n next unless pair.end_with?(\",#{m}\")\n # make sure this isn't some fake entry\n next unless info['kb_size']\n return info['device']\n end\n Chef::Log.warn(\n \"#{m} shows as valid mountpoint, but Ohai can't find it.\",\n )\n return nil\n end", "def mounts\r\n @mounts.list\r\n end", "def dev_stat\n begin\n @dev_stat ||= Sys::Filesystem.stat dev_path\n rescue SystemCallError\n @dev_stat = nil\n end\n end", "def mountpoint\n 'dev/.osctl-mount-helper'\n end", "def device_of_mount(m)\n fs = self.filesystem_data\n unless Pathname.new(m).mountpoint?\n Chef::Log.warn(\n \"fb_helpers: #{m} is not a mount point - I can't determine its \" +\n 'device.',\n )\n return nil\n end\n unless fs && fs['by_pair']\n Chef::Log.warn(\n 'fb_helpers: no filesystem data so no node.device_of_mount',\n )\n return nil\n end\n fs['by_pair'].to_hash.each do |pair, info|\n # we skip fake filesystems 'rootfs', etc.\n next unless pair.start_with?('/')\n # is this our FS?\n next unless pair.end_with?(\",#{m}\")\n # make sure this isn't some fake entry\n next unless info['kb_size']\n\n return info['device']\n end\n Chef::Log.warn(\n \"fb_helpers: #{m} shows as valid mountpoint, but Ohai can't find it.\",\n )\n nil\n end", "def GetMountString(used_fs, defaultv)\n fsmap = GetFsMap(used_fs)\n ret = Ops.get_string(fsmap, :mount_string, defaultv)\n Builtins.y2milestone(\"GetMountString used_fs:%1 ret:%2\", used_fs, ret)\n ret\n end", "def get_mount_path(filepath)\n cmd_exec(\"df \\\"#{filepath}\\\" | tail -1\").split(' ')[0]\n rescue\n raise \"Unable to get mount path of #{filepath}\"\n end", "def mount options = {}\n opts = {\n :force_readonly => false\n }.merge!(options)\n args = []\n args << 'readOnly' if opts[:force_readonly]\n args << opts[:mountpoint] if opts.has_key?(:mountpoint)\n args << self.dev_node\n diskutil 'mount', *args\n end", "def getdiskusage\n content = \"\"\n begin\n content = `df -k`\n rescue\n warn \"Failed to run df command\"\n return nil\n end\n used_space = 0\n avail_space = 0\n content.split(\"\\n\").each do |line|\n if line =~ /\\s+\\d+\\s+(\\d+)\\s+(\\d+)\\s+\\d+%\\s+\\/($|home$)/\n used_space += $1.to_i\n avail_space += $2.to_i\n end\n end\n return {:avail_space => avail_space, :used_space => used_space}\n end", "def mounted?(name)\n mount_loc = File.join(KVM_MOUNT_POINT, name)\n system(\"mount | grep #{mount_loc}\")\nend", "def get_device_mount_point( incoming_path )\n mount_lines = `mount`\n raise EBSRemoteExecException.new(nil,$?,mount_lines) if $? != 0\n path = File.ftype(incoming_path) != 'directory'? File.dirname(incoming_path) : incoming_path\n device=nil\n longest = \"\"\n mount_lines.each_line {|line|\n match = line =~ /(.+)\\son\\s(.+?)\\s.*/\n candidate = $2.strip\n candidate_device = $1.strip\n # Keep the longest prefix matching\n if match && path =~ /^#{candidate}/ && candidate.length > longest.length\n longest = candidate\n device = candidate_device\n end\n }\n unless device\n STDERR.puts \"Couldn't find the device for mount point #{path}\"\n Kernel.exit(-1)\n end\n device\n end", "def other_mounts\n others = []\n fstab_lines.each do |line|\n localdevice, localmount, _fstype, _options, _freq, _pass = line.split(/\\s+/)\n others << line if localmount == mount && localdevice != device\n end\n others\n end", "def getmountedvolumes\n # only support Linux for now\n return {} unless Facter['kernel'] && Facter['kernel'].value == 'Linux'\n\n dir = \"/etc\"\n mounted = {}\n\n # AUTOFS - gather only files named auto[._]*\n Dir.glob(File.join(dir, \"*\")).each do |file|\n next if file !~ /^auto[._].*/\n\n # AUTOFS - match only lines that look like nfs syntax such as host:/path\n IO.foreach(file) do |line|\n if line =~ /\\w:\\S/ && line !~ /^\\s*#/\n # Parse it, Example : \" nventory_backup -noatime,intr irvnetappbk:/vol/nventory_backup \"\n if line =~ /^(\\w[\\w\\S]+)\\s+\\S+\\s+(\\w[\\w\\S]+):(\\S+)/\n mnt = $1\n host = $2\n vol = $3\n mounted[\"volumes[mounted][/mnt/#{mnt}][config]\"] = file\n mounted[\"volumes[mounted][/mnt/#{mnt}][volume_server]\"] = host\n mounted[\"volumes[mounted][/mnt/#{mnt}][volume]\"] = vol\n mounted[\"volumes[mounted][/mnt/#{mnt}][type]\"] = 'nfs'\n end\n end\n end # IO.foreach\n end # Dir.glob\n\n # FSTAB - has diff syntax than AUTOFS. Example: \"server:/usr/local/pub /pub nfs rsize=8192,wsize=8192,timeo=14,intr\"\n IO.foreach(\"/etc/fstab\") do |line|\n if line =~ /^(\\w[\\w\\S]+):(\\S+)\\s+(\\S+)\\s+nfs/\n host = $1\n vol = $2\n mnt = $3\n mounted[\"volumes[mounted][#{mnt}][config]\"] = \"/etc/fstab\"\n mounted[\"volumes[mounted][#{mnt}][volume_server]\"] = host\n mounted[\"volumes[mounted][#{mnt}][volume]\"] = vol\n mounted[\"volumes[mounted][#{mnt}][type]\"] = 'nfs'\n end\n end # IO.foreach\n return mounted\n end", "def mount_list(www_root)\n arr = []\n %x{mount -t iso9660}.scan(/\\S+ on (\\S+)/) do |a|\n mountpoint = a[0]\n arr << mountpoint if mountpoint.match %r{#{www_root}}\n end\n arr\nend", "def disk_space()\n\n instructions = 'df -h'\n r = @ssh ? @ssh.exec!(instructions) : `#{instructions}`\n\n @results[:disk_usage] = {}\n\n a = r.lines.grep(/\\/dev\\/root/)\n\n puts ('a: ' + a.inspect).debug if @debug\n\n if a.any? then\n size, used, avail = a[0].split(/ +/).values_at(1,2,3)\n\n @results[:disk_usage][:root] = {size: size, used: used, \n avail: avail}\n end\n\n a2 = r.lines.grep(/\\/dev\\/sda1/)\n\n puts ('a2: ' + a2.inspect).debug if @debug\n\n if a2.any? then\n size, used, avail = a2[0].split(/ +/).values_at(1,2,3)\n\n @results[:disk_usage][:sda1] = {size: size, used: used, \n avail: avail}\n end\n\n end", "def tmpfs_mount_status(desired)\n # Start with checking if it was mounted the way we would mount it\n # this is ALMOST the same as the 'is it identical' check for non-tmpfs\n # filesystems except that with tmpfs we don't treat 'auto' as equivalent and\n # that we skip inode64 option on current mount status - because it's activated\n # by default on Linux kernel >= 5.9\n fs_data = node.filesystem_data\n key = \"#{desired['device']},#{desired['mount_point']}\"\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n if mounted['fs_type'] == 'tmpfs'\n Chef::Log.debug(\n \"fb_fstab: tmpfs #{desired['device']} on \" +\n \"#{desired['mount_point']} is currently mounted...\",\n )\n\n skipped_opts = []\n if _are_tmpfs_using_inode64?\n\n # inode64 is active by default on tmpfs for Linux kernel > 5.9\n skipped_opts.push('inode64')\n end\n\n if compare_opts(desired['opts'], mounted['mount_options'], skipped_opts)\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n end\n end\n # OK, if that's not the case, we don't have the same device, which\n # is OK. Find out if we have something mounted at the same spot, and\n # get its device name so we can find it's entry in node['filesystem']\n if fs_data['by_mountpoint'][desired['mount_point']]\n # If we are here the mountpoints are the same...\n mounted = fs_data['by_mountpoint'][desired['mount_point']].to_hash\n # OK, if it's tmpfs as well, we're diong good\n if mounted['fs_type'] == 'tmpfs'\n Chef::Log.warn(\n \"fb_fstab: Treating #{mounted['devices']} on \" +\n \"#{desired['mount_point']} the same as #{desired['device']} on \" +\n \"#{desired['mount_point']} because they are both tmpfs.\",\n )\n Chef::Log.debug(\n \"fb_fstab: tmpfs #{desired['device']} on \" +\n \"#{desired['mount_point']} is currently mounted...\",\n )\n Chef::Log.debug(\"fb_fstab: #{desired} vs #{mounted}\")\n if compare_opts(desired['opts'], mounted['mount_options'])\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n end\n Chef::Log.warn(\n \"fb_fstab: tmpfs is desired on #{desired['mount_point']}, but \" +\n \"non-tmpfs #{mounted['devices']} (#{mounted['fs_type']}) currently \" +\n 'mounted there.',\n )\n return :conflict\n end\n :missing\n end", "def get_osx_disk_name(options)\n message = \"Information:\\tGetting root disk device ID\"\n command = \"df |grep '/$' |awk '{print \\\\$1}'\"\n output = execute_command(options,message,command)\n disk_id = output.chomp\n message = \"Information:\\tGetting volume name for \"+disk_id\n command = \"diskutil info #{disk_id} | grep 'Volume Name' |cut -f2 -d':'\"\n output = execute_command(options,message,command)\n volume = output.chomp.gsub(/^\\s+/,\"\")\n return volume\nend", "def ps_format\n return nil unless options.format\n\n \"table {{.ID}}\\t{{.Mounts}}\" if options.format.eql?('mounts')\n end", "def get_fs_type(device)\n fs_check = Mixlib::ShellOut.new(\"blkid -c /dev/null #{device}\")\n fs_check.run_command\n match = fs_check.stdout.match(/\\sTYPE=\\\"(.*?)\\\"/)\n match = '' if match.nil?\n\n Chef::Log.info(\"File system type for device #{device}: #{match[1]}\")\n match[1]\nend", "def verify_mounted(partition)\n\treturn `grep partition /proc/mounts | wc -l`.chomp\nend", "def filesystem_labels\n\n labels = {}\n\n mount = capture_command_output('mount')\n mount.each do |mount_line|\n\n mount_line.strip!\n device = mount_line.match(/^(.*?) on/)[1]\n\n if PlatformInfo.linux?\n\n # /dev/hda3 on / type ext4 (rw,errors=remount-ro)\n mount_point = mount_line.match(/^#{Regexp.quote(device)} on (.*?) type/)[1]\n fs_type = mount_line.match(/type (.*?) \\(/)[1]\n\n elsif PlatformInfo.osx?\n\n # /dev/disk0s2 on / (hfs, local, journaled)\n mount_point = mount_line.match(/^#{Regexp.quote(device)} on (.*?) \\(/)[1]\n fs_type = mount_line.match(/ \\((.*?), /)[1]\n \n else\n unsupported_platform\n end\n\n labels[device] = {\n :mount_point => mount_point,\n :file_system => fs_type\n }\n\n end\n\n labels\n\n end", "def mount_status(desired)\n # We treat tmpfs specially. While we don't want people to mount tmpfs with\n # a device of 'none' or 'tmpfs', we also don't want to make them remount\n # (and lose all their data) just to convert to fb_fstab. So we'll make\n # them use a new name in the config, but we will treat the pre-mounted\n # mounts as valid/the same. Besides, since the device is meaningless, we\n # can just ignore it for the purposes of this test anyway.\n if desired['type'] == 'tmpfs'\n return tmpfs_mount_status(desired)\n end\n\n key = \"#{desired['device']},#{desired['mount_point']}\"\n fs_data = node.filesystem_data\n mounted = nil\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n else\n key = \"#{desired['device']}/,#{desired['mount_point']}\"\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n end\n end\n\n if mounted\n Chef::Log.debug(\n \"fb_fstab: There is an entry in node['filesystem'] for #{key}\",\n )\n # If it's a virtual device, we require the fs type to be identical.\n # otherwise, we require them to be similar. This is because 'auto'\n # is meaningless without a physical device, so we don't want to allow\n # it to be the same.\n if compare_fstype(desired['type'], mounted['fs_type']) ||\n (desired['device'].start_with?('/') &&\n [desired['type'], mounted['fs_type']].include?('auto'))\n Chef::Log.debug(\n \"fb_fstab: FS #{desired['device']} on #{desired['mount_point']}\" +\n ' is currently mounted...',\n )\n if compare_opts(desired['opts'], mounted['mount_options'])\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n else\n Chef::Log.warn(\n \"fb_fstab: Device #{desired['device']} is mounted at \" +\n \"#{mounted['mount']} as desired, but with fstype \" +\n \"#{mounted['fs_type']} instead of #{desired['type']}\",\n )\n return :conflict\n end\n end\n\n # In this case we don't have the device we expect at the mountpoint we\n # expect. Assuming it's not NFS/Gluster which can be mounted in more than\n # once place, we look up this device and see if it moved or just isn't\n # mounted\n unless ['nfs', 'nfs4', 'glusterfs'].include?(desired['type'])\n device = fs_data['by_device'][desired['device']]\n # Here we are checking if the device we want\n # has already a mount defined\n # We want to return :moved if it does except\n # in the case when it's a btrfs\n # disk and our desired and current options\n # are trying to mount different subvolumes\n if device && device['mounts'] && !device['mounts'].empty? &&\n !(\n FB::Fstab.btrfs_subvol?(\n device['fs_type'],\n device['mount_options'].join(','),\n ) &&\n FB::Fstab.btrfs_subvol?(\n desired['type'],\n desired['opts'],\n ) &&\n !FB::Fstab.same_subvol?(\n device['mounts'][0],\n device['mount_options'].join(','),\n desired['opts'],\n )\n )\n\n Chef::Log.warn(\n \"fb_fstab: #{desired['device']} is at #{device['mounts']}, but\" +\n \" we want it at #{desired['mount_point']}\",\n )\n return :moved\n end\n end\n\n # Ok, this device isn't mounted, but before we return we need to check\n # if anything else is mounted where we want to be.\n if fs_data['by_mountpoint'][desired['mount_point']]\n devices = fs_data['by_mountpoint'][\n desired['mount_point']]['devices']\n Chef::Log.warn(\n \"fb_fstab: Device #{desired['device']} desired at \" +\n \"#{desired['mount_point']} but something #{devices} already \" +\n 'mounted there.',\n )\n return :conflict\n end\n :missing\n end", "def mountpoint?\n begin\n stat1 = expand_tilde.lstat\n stat2 = expand_tilde.parent.lstat\n stat1.dev == stat2.dev && stat1.ino == stat2.ino ||\n stat1.dev != stat2.dev\n rescue Errno::ENOENT\n false\n end\n end", "def mount_paths_listing\n Dir[\"#{mounts_path}/*\"]\n end", "def get_device_info()\n @errors = []\n info = {}\n return info unless @programmer_path\n\n response = IO.popen(\"#{@programmer_path} I\").readlines\n puts response if $debug\n response.each do |line|\n if line =~ /Error/i\n errors << line\n else\n parts = line.split(/:|\\.\\.\\./)\n info[parts[0].strip.split.join.to_sym] = parts[1].strip if parts.size == 2\n end\n end # each\n info\n end", "def pretty_info\n volinfo = self.info\n mountpoint = volinfo['MountPoint']\n mountpoint = 'Not mounted' if mountpoint.empty?\n rw = volinfo['WritableVolume'] ? 'writable' : 'read-only'\n ownership = self.ownership_enabled? ? 'ownership enabled' : 'no ownership'\n return volinfo['VolumeName'] + \" (#{self.dev_node}, #{mountpoint}, #{rw}, #{ownership})\\n\" \n end", "def get_disk_util\n used_info = query_data(params[:host], 'df.1kblocks.used', params[:from_ts], params[:to_ts])\n total_info = query_data(params[:host], 'df.1kblocks.total', params[:from_ts], params[:to_ts])\n\n used_info.delete_if { |k, v|\n k.index(\"fstype=tmpfs\")\n }\n total_info.delete_if { |k, v|\n k.index(\"fstype=tmpfs\")\n }\n \n results = {}\n used_info.each { |k, v|\n matcher = /mount=([\\/\\w]+) /.match(k)\n if matcher\n path = matcher[1]\n\n if total_info.has_key?(k)\n total_v = total_info[k]\n total_v_map = Hash[total_v]\n results[path] = v.collect { |point|\n ts = point[0]\n if (total_v_map.has_key?(ts))\n [ts, format(\"%.2f\", point[1] * 100.0 / total_v_map[ts]).to_f]\n end\n }.keep_if { |v| v }\n end\n end\n }\n\n render json: results\n end", "def tmpfs\n\t\t\t\tret = {}\n\t\t\t\tmounts.each { |x|\n\t\t\t\t\tret.merge!({x.split[1] => x}) if x.start_with?('tmpfs '.freeze)\n\t\t\t\t}\n\t\t\t\tret\n\t\t\tend", "def mount_command(path)\n \"udisksctl mount --block-device #{path}\"\nend", "def mounted?\n '' != self['MountPoint']\n end", "def mountpoint?\n begin\n stat1 = lstat\n stat2 = parent.lstat\n stat1.dev != stat2.dev or stat1.ino == stat2.ino\n rescue Errno::ENOENT\n false\n end\n end", "def get_fs_type(device)\n fs_check = Mixlib::ShellOut.new(\"blkid -c /dev/null #{device}\")\n fs_check.run_command\n match = fs_check.stdout.match(/TYPE=\\\"(.*)\\\"/)\n match = '' if match.nil?\n\n match[1]\nend", "def filesystem_usage\n\n usage = {}\n\n df = capture_command_output('df', '-k')[1..-1] # Don't include the column headers.\n df.each do |df_line|\n\n df_line.strip!\n device = df_line.match(/^(.*?)\\s{2,}/)[1]\n tokens = df_line.gsub(/^#{Regexp.quote(device)}\\s+/, '').split(/\\s+/, 5)\n \n # Convert all KB values to bytes.\n size = tokens[0].to_i * 1024\n used = tokens[1].to_i * 1024\n available = tokens[2].to_i * 1024\n used_percentage = tokens[3].to_i\n\n usage[device] = {\n :size => size,\n :used => used,\n :used_percentage => used_percentage,\n :available => available\n }\n\n end\n\n usage\n\n end", "def pretty_info\n s = ''\n dev = self.device\n return \"Disk image: #{self.image_path.basename} (na, detached, na)\\n\" if dev.nil?\n return dev.pretty_info\n end", "def format_mount(partition, mount)\n\n # Partitions that we already have mounts set for.\n return nil if partition == '/dev/mapper/rootvg-slash'\n return nil if partition == '/dev/mapper/rootvg-var'\n return nil if partition == '/dev/mapper/rootvg-tmp'\n\n mount\nend", "def info\n Plist::parse_xml(diskutil 'info', '-plist', @dev_node)\n end", "def get_partition_info\n # remove leading slash so it matches the packages.DU path\n remove_slash = true\n\n if !Stage.initial\n # read /proc/mounts as a list of maps\n # $[\"file\":\"/boot\", \"freq\":0, \"mntops\":\"rw\", \"passno\":0, \"spec\":\"/dev/sda1\", \"vfstype\":\"ext2\"]\n mounts = Convert.convert(\n SCR.Read(path(\".proc.mounts\")),\n :from => \"any\",\n :to => \"list <map <string, any>>\"\n )\n Builtins.y2milestone(\"mounts %1\", mounts)\n\n partitions = []\n Builtins.foreach(mounts) do |mpoint|\n name = Ops.get_string(mpoint, \"file\", \"\")\n if Builtins.substring(name, 0, 1) == \"/\" &&\n Builtins.substring(name, 0, 5) != \"/dev/\" && # filter out /dev/pts etc.\n Ops.get_string(mpoint, \"vfstype\", \"\") != \"rootfs\" # filter out duplicate \"/\" entry\n capacity = Pkg.TargetCapacity(name)\n if capacity != 0 # dont look at pseudo-devices (proc, shmfs, ...)\n used = Pkg.TargetUsed(name)\n partitions = Builtins.add(\n partitions,\n {\n \"name\" => name,\n \"free\" => Ops.subtract(capacity, used),\n \"used\" => used\n }\n )\n end\n end\n end\n Pkg.TargetInitDU(partitions)\n Builtins.y2milestone(\"get_partition_info: %1\", partitions)\n return deep_copy(partitions)\n end # !Stage::initial ()\n\n # remove the previous failures\n @failed_mounts = []\n\n # installation stage - Storage:: is definitely present\n # call Storage::GetTargetMap()\n targets = Convert.convert(\n WFM.call(\"wrapper_storage\", [\"GetTargetMap\"]),\n :from => \"any\",\n :to => \"map <string, map>\"\n )\n\n if targets == nil\n Builtins.y2error(\"Target map is nil, Storage:: is probably missing\")\n end\n\n if Mode.test\n targets = Convert.convert(\n SCR.Read(path(\".target.yast2\"), \"test_target_map.ycp\"),\n :from => \"any\",\n :to => \"map <string, map>\"\n )\n end\n\n target_partitions = []\n min_spare = 20 * 1024 * 1024 # minimum free space ( 20 MB )\n\n Builtins.foreach(targets) do |disk, diskinfo|\n part_info = Ops.get_list(diskinfo, \"partitions\", [])\n Builtins.foreach(part_info) do |part|\n Builtins.y2milestone(\"Adding partition: %1\", part)\n used_fs = Ops.get_symbol(part, \"used_fs\", :unknown)\n # ignore VFAT and NTFS partitions (bnc#)\n if used_fs == :vfat || used_fs == :ntfs\n Builtins.y2warning(\n \"Ignoring partition %1 with %2 filesystem\",\n Ops.get_string(part, \"device\", \"\"),\n used_fs\n )\n else\n free_size = 0\n\n if Ops.get(part, \"mount\") != nil &&\n Builtins.substring(Ops.get_string(part, \"mount\", \"\"), 0, 1) == \"/\"\n if Ops.get(part, \"create\") == true ||\n Ops.get(part, \"delete\") == false ||\n Ops.get(part, \"create\") == nil &&\n Ops.get(part, \"delete\") == nil\n Builtins.y2debug(\n \"get_partition_info: adding partition: %1\",\n part\n )\n\n # get free_size on partition in kBytes\n free_size = Ops.multiply(\n Ops.get_integer(part, \"size_k\", 0),\n 1024\n )\n free_size = Ops.subtract(free_size, min_spare)\n\n # free_size smaller than min_spare, fix negative value\n if Ops.less_than(free_size, 0)\n Builtins.y2milestone(\"Fixing free size: %1 to 0\", free_size)\n free_size = 0\n end\n\n used = 0\n if !(Ops.get_boolean(part, \"create\", false) ||\n Ops.get_boolean(part, \"format\", false))\n tmpdir = Convert.to_string(SCR.Read(path(\".target.tmpdir\")))\n tmpdir = Ops.add(tmpdir, \"/diskspace_mount\")\n SCR.Execute(\n path(\".target.bash\"),\n Builtins.sformat(\"test -d %1 || mkdir -p %1\", tmpdir)\n )\n\n # mount in read-only mode (safer)\n mount_options = [\"ro\"]\n\n # add \"nolock\" if it's a NFS share (bnc#433893)\n if used_fs == :nfs\n Builtins.y2milestone(\"Mounting NFS with 'nolock' option\")\n mount_options = Builtins.add(mount_options, \"nolock\")\n end\n\n # join the options\n mount_options_str = Builtins.mergestring(mount_options, \",\")\n\n mount_command = Builtins.sformat(\n \"/bin/mount -o %1 %2 %3\",\n mount_options_str,\n Ops.get_string(part, \"device\", \"\"),\n tmpdir\n )\n\n Builtins.y2milestone(\n \"Executing mount command: %1\",\n mount_command\n )\n\n result = Convert.to_integer(\n SCR.Execute(path(\".target.bash\"), mount_command)\n )\n Builtins.y2milestone(\"Mount result: %1\", result)\n\n if result == 0\n partition = Convert.convert(\n SCR.Read(path(\".run.df\")),\n :from => \"any\",\n :to => \"list <map <string, string>>\"\n )\n Builtins.foreach(partition) do |p|\n if Ops.get_string(p, \"name\", \"\") == tmpdir\n Builtins.y2internal(\"P: %1\", p)\n free_size = Ops.multiply(\n Builtins.tointeger(Ops.get_string(p, \"free\", \"0\")),\n 1024\n )\n used = Ops.multiply(\n Builtins.tointeger(Ops.get_string(p, \"used\", \"0\")),\n 1024\n )\n end\n end\n SCR.Execute(\n path(\".target.bash\"),\n Builtins.sformat(\"/bin/umount %1\", tmpdir)\n )\n else\n Builtins.y2error(\n \"Mount failed, ignoring partition %1\",\n Ops.get_string(part, \"device\", \"\")\n )\n @failed_mounts = Builtins.add(@failed_mounts, part)\n\n next\n end\n else\n # for formatted partitions estimate free system size\n # compute fs overhead\n used = EstimateFsOverhead(part)\n\n if Ops.greater_than(used, 0)\n Builtins.y2milestone(\n \"Partition %1: assuming fs overhead: %2kB\",\n Ops.get_string(part, \"device\", \"\"),\n Ops.divide(used, 1024)\n )\n end\n\n # journal size\n js = 0\n\n if ExtFs(used_fs)\n js = ExtJournalSize(part)\n reserved = ReservedSpace(part)\n\n if Ops.greater_than(reserved, 0)\n used = Ops.add(used, reserved)\n end\n elsif used_fs == :xfs\n js = XfsJournalSize(part)\n elsif used_fs == :reiser\n js = ReiserJournalSize(part)\n elsif used_fs == :jfs\n js = JfsJournalSize(part)\n else\n Builtins.y2warning(\n \"Unknown journal size for filesystem: %1\",\n used_fs\n )\n end\n\n if Ops.greater_than(js, 0)\n Builtins.y2milestone(\n \"Partition %1: assuming journal size: %2kB\",\n Ops.get_string(part, \"device\", \"\"),\n Ops.divide(js, 1024)\n )\n used = Ops.add(used, js)\n end\n\n # decrease free size\n free_size = Ops.subtract(free_size, used)\n\n # check for underflow\n if Ops.less_than(free_size, 0)\n Builtins.y2milestone(\"Fixing free size: %1 to 0\", free_size)\n free_size = 0\n end\n end\n\n # convert into kB for TargetInitDU\n free_size = Ops.divide(free_size, 1024)\n used = Ops.divide(used, 1024)\n\n Builtins.y2milestone(\n \"available partition: mount: %1, free: %2 KB, used: %3 KB\",\n Ops.get_string(part, \"mount\", \"\"),\n free_size,\n used\n )\n if !remove_slash\n target_partitions = Builtins.add(\n target_partitions,\n {\n \"name\" => Ops.get_string(part, \"mount\", \"\"),\n \"used\" => used,\n \"free\" => free_size\n }\n )\n else\n part_name = \"\"\n mount_name = Ops.get_string(part, \"mount\", \"\")\n\n if mount_name != \"/\"\n part_name = Builtins.substring(\n mount_name,\n 1,\n Builtins.size(mount_name)\n )\n else\n part_name = mount_name\n end\n\n target_partitions = Builtins.add(\n target_partitions,\n { \"name\" => part_name, \"used\" => used, \"free\" => free_size }\n )\n end\n end\n end\n end\n end # foreach (`part)\n end # foreach (`disk)\n\n # add estimated size occupied by non-package files\n target_partitions = EstimateTargetUsage(target_partitions)\n\n Builtins.y2milestone(\"get_partition_info: part %1\", target_partitions)\n Pkg.TargetInitDU(target_partitions)\n\n deep_copy(target_partitions)\n end", "def lsof\n Dir.new(\"/proc/#{Process.pid}/fd/\").entries\n end", "def list_partitions #by nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{print $1}'`.chomp.split\nend", "def get_current_devices(output)\n lines = output.split(\"\\n\")\n partitions = lines.drop(2).map do |line|\n line.chomp.split.last\n end\n partitions.reject! do |partition|\n partition =~ /^dm-\\d/\n end\n devices = partitions.select do |partition|\n partition =~ /[a-z]$/\n end\n devices.sort!.map! {|device| \"/dev/#{device}\"}\n if devices.empty?\n devices = partitions.select do |partition|\n partition =~ /[0-9]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n end\n devices\n end", "def determine_disk\n df_cmd = \"df 2>/dev/null|awk '$1 ~ /\\\\// {I=I+$3} END {print I}'\"\n disk = @shell.query('DISK_DF', df_cmd)\n\n # Result is expected to be in KiB. Convert to GB.\n @info[:disk] = disk.to_f / 1000 ** 2\n end", "def get_parallels_disk(options)\n message = \"Information:\\tDetermining directory for Parallels VM \"+options['name']\n command = \"prlctl list #{options['name']} --info |grep image |awk '{print $4}' |cut -f2 -d=\"\n vm_dir = execute_command(options,message,command)\n vm_dir = vm_dir.chomp.gsub(/'/,\"\")\n return vm_dir\nend", "def mountpoint?\n begin\n stat1 = self.lstat\n stat2 = self.parent.lstat\n stat1.dev == stat2.dev && stat1.ino == stat2.ino ||\n stat1.dev != stat2.dev\n rescue Errno::ENOENT\n false\n end\n end", "def mounted?\n !!( attached? && mount_point && File.exists?(mount_point) && current[:mount] == mount_point )\n end", "def mount_point\n @mount_point ||= options[:iso_mount_point]\n return @mount_point\n end", "def volume_ls\n help = [\n '',\n \"Use: #{me} volume ls\",\n '',\n 'Lists the names of all cyber-dojo volumes',\n '',\n minitab + '--quiet Only display volume names'\n ]\n\n if ['help','--help'].include? ARGV[2]\n show help\n exit failed\n end\n\n # There is currently no [--filter label=LABEL] option on [docker volume ls]\n # https://github.com/docker/docker/pull/21567\n # So I have to inspect all volumes. Could be slow if lots of volumes.\n\n names = run(\"docker volume ls --quiet\").split\n names = names.select{ |name| cyber_dojo_volume?(name) }\n\n if ARGV[2] == '--quiet'\n names.each { |name| puts name }\n else\n types = names.map { |name| cyber_dojo_type(name) }\n urls = names.map { |name| cyber_dojo_label(name) }\n\n headings = { :name => 'NAME', :type => 'TYPE', :url => 'SRC' }\n\n gap = 3\n max_name = ([headings[:name]] + names).max_by(&:length).length + gap\n max_type = ([headings[:type]] + types).max_by(&:length).length + gap\n max_url = ([headings[:url ]] + urls ).max_by(&:length).length + gap\n\n spaced = lambda { |max,s| s + (space * (max - s.length)) }\n\n name = spaced.call(max_name, headings[:name])\n type = spaced.call(max_type, headings[:type])\n url = spaced.call(max_url , headings[:url ])\n puts name + type + url\n names.length.times do |n|\n name = spaced.call(max_name, names[n])\n type = spaced.call(max_type, types[n])\n url = spaced.call(max_url , urls[n])\n puts name + type + url\n end\n end\nend", "def IsMounted(mountpoint)\n if Builtins.substring(\n mountpoint,\n Ops.subtract(Builtins.size(mountpoint), 1),\n 1\n ) == \"/\"\n mountpoint = Builtins.substring(\n mountpoint,\n 0,\n Ops.subtract(Builtins.size(mountpoint), 1)\n )\n end\n\n ret = true\n Builtins.foreach(@activated) do |e|\n if Ops.get_string(e, :type, \"\") == \"mount\" &&\n (Ops.get_string(e, :mntpt, \"\") == mountpoint ||\n Ops.get_string(e, :mntpt, \"\") == Ops.add(mountpoint, \"/\"))\n ret = true\n end\n end\n ret\n end", "def forks\n `vmstat -f`.split.first\n end", "def ip_by_mount(name)\n dev = available_dev unless mounted?(name)\n loc = mount(name, dev)\n addr = %x{cat #{File.join(loc, 'etc', 'network', 'interfaces')} | grep address}.split(' ').last.to_s.strip\n unmount_kvm_volume(name, dev) if dev\n addr\nend", "def mount_point\n Pathname.new(self['MountPoint'])\n end", "def get_cgroup_attribute_nocgget(attribute, username)\n begin\n value = nil\n File.open('/proc/mounts', File::RDONLY) do |mounts|\n mounts.each do |l|\n if l =~ /^\\S+\\s+(\\S+)\\s+cgroup\\s+/\n begin\n File.open(File.join($1, \"openshift\", username, attribute), File::RDONLY) do |cgfile|\n value = cgfile.read.strip\n end\n rescue\n end\n end\n end\n end\n rescue\n end\n if value.nil?\n $stderr.puts \"Could not find attribute #{attribute}\"\n exit 2\n end\n value\nend", "def setup_device_for_mount\n # use ramdisk for creating a test device for mount.\n # This can cleaner if we have chef resource/provider for ramdisk.\n case ohai[:platform_family]\n when \"aix\"\n # On AIX, we can't create a ramdisk inside a WPAR, so we use\n # a \"namefs\" mount against / to test\n # https://www-304.ibm.com/support/knowledgecenter/ssw_aix_71/com.ibm.aix.performance/namefs_file_sys.htm\n device = \"/\"\n fstype = \"namefs\"\n when \"debian\", \"rhel\", \"amazon\"\n device = \"/dev/ram1\"\n unless File.exist?(device)\n shell_out(\"mknod -m 660 #{device} b 1 0\")\n shell_out(\"chown root:disk #{device}\")\n end\n shell_out(\"ls -1 /dev/ram*\").stdout.each_line do |d|\n if shell_out(\"mount | grep #{d}\").exitstatus == \"1\"\n # this device is not mounted, so use it.\n device = d\n break\n end\n end\n fstype = \"tmpfs\"\n shell_out!(\"mkfs -q #{device} 512\")\n when \"solaris2\"\n device = \"swap\"\n fstype = \"tmpfs\"\n else\n end\n [device, fstype]\n end", "def get_verbose_disc_type(drive)\n if !disc_ready?(drive)\n return \"NOT READY\"\n end\n\n if disc_blank?(drive)\n return \"BLANK (unknown type)\"\n end\n\n fd = File.open(drive, File::NONBLOCK | File::RDONLY) \n rv = fd.ioctl($CDROM_DISC_STATUS, 0);\n fd.close\n\n # Possible race with above, so repeat a few cases.\n case rv \n when $CDS_NO_INFO\n return \"BLANK (unknown type)\"\n when $CDS_NO_DISC\n return \"NOT READY\"\n when $CDS_AUDIO\n return \"AUDIO (Red Book CD-DA)\"\n when $CDS_DATA_1\n return \"DATA (Yellow Book, Mode 1, Format 1)\"\n when $CDS_DATA_2\n return \"DATA (Yellow Book, Mode 1, Format 2)\"\n when $CDS_XA_2_1\n return \"DATA (Green Book, Mode 2, Format 1)\"\n when $CDS_XA_2_2\n return \"DATA (Green Book, Mode 2, Format 2)\"\n when $CDS_MIXED\n return \"MIXED (Vomit Book)\"\n else\n return \"FUCKED!\"\n end\n\nend", "def GetMountPoints\n mountPoints = {}\n swapPoints = []\n tg = GetTargetMap()\n Builtins.foreach(tg) do |targetdevice, target|\n partitions = Ops.get_list(target, \"partitions\", [])\n Builtins.foreach(partitions) do |partition|\n partitionName = Ops.get_string(partition, \"device\", \"\")\n mountPoint = Ops.get_string(partition, \"mount\", \"\")\n fsid = Ops.get_integer(partition, \"fsid\", 0)\n if mountPoint != \"\"\n raid_type = \"\"\n if Ops.get_symbol(partition, \"type\", :undefined) == :sw_raid\n raid_type = Ops.get_string(partition, \"raid_type\", \"\")\n end\n # partition has a mount point\n if mountPoint == \"swap\"\n swapPoints = Builtins.add(\n swapPoints,\n [partitionName, fsid, targetdevice, raid_type]\n )\n else\n mountPoints = Builtins.add(\n mountPoints,\n mountPoint,\n [partitionName, fsid, targetdevice, raid_type]\n )\n end\n end\n end\n end\n if Ops.greater_than(Builtins.size(swapPoints), 0)\n mountPoints = Builtins.add(mountPoints, \"swap\", swapPoints)\n end\n if !Stage.initial\n cm = Builtins.filter(Partitions.CurMounted) do |e|\n Builtins.search(Ops.get_string(e, \"spec\", \"\"), \"/dev/\") == 0\n end\n Builtins.foreach(cm) do |e|\n if !Builtins.haskey(mountPoints, Ops.get_string(e, \"file\", \"\"))\n p = GetPartition(tg, Ops.get_string(e, \"spec\", \"\"))\n if Ops.greater_than(Builtins.size(p), 0)\n raid_type = \"\"\n if Ops.get_symbol(p, \"type\", :undefined) == :sw_raid\n raid_type = Ops.get_string(p, \"raid_type\", \"\")\n end\n d = GetDiskPartition(Ops.get_string(e, \"spec\", \"\"))\n Ops.set(\n mountPoints,\n Ops.get_string(e, \"file\", \"\"),\n [\n Ops.get_string(p, \"device\", \"\"),\n Ops.get_integer(p, \"fsid\", 0),\n Ops.get_string(d, \"disk\", \"\"),\n raid_type\n ]\n )\n end\n end\n end\n end\n Builtins.y2milestone(\"ret %1\", mountPoints)\n deep_copy(mountPoints)\n end", "def filesystem_data\n self['filesystem2'] || self['filesystem']\n end", "def get_filesystem\n @@current_fake ? @@current_fake[:filesystem] : ''\n end", "def kernel_config\n return unless cmd_exec('test -r /boot/config-`uname -r` && echo true').include? 'true'\n\n output = cmd_exec(\"cat /boot/config-`uname -r`\").to_s.strip\n\n return if output.empty?\n\n config = output.split(\"\\n\").map(&:strip).reject(&:empty?).reject {|i| i.start_with? '#'}\n\n return if config.empty?\n\n config\n rescue\n raise 'Could not retrieve kernel config'\n end", "def mount(name, root_dev)\n puts \"Mounting KVM device: #{root_dev}\"\n mount_loc = File.join(KVM_MOUNT_POINT, name)\n unless(system(\"mount | grep #{mount_loc}\"))\n FileUtils.mkdir_p(mount_loc)\n if(system(\"mount #{root_dev} #{mount_loc}\"))\n mount_loc\n else\n raise \"Failed to mount #{root_dev} to #{mount_loc}\"\n end\n else\n puts \"Device already mounted (#{mount_loc})\"\n mount_loc\n end\nend", "def get_current_devices(proc_partitions_output)\n lines = proc_partitions_output.split(\"\\n\")\n partitions = lines.drop(2).map do |line|\n line.chomp.split.last\n end.reject do |partition|\n partition =~ /^dm-\\d/\n end\n devices = partitions.select do |partition|\n partition =~ /[a-z]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n if devices.empty?\n devices = partitions.select do |partition|\n partition =~ /[0-9]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n end\n devices\n end", "def fstype\n return self['fstype'] if has_key?('fstype')\n Chef::Log.info([\n self['fstype'], current[:fstype],\n File.exists?(device) && `file -s '#{device}'`.chomp,\n self,\n ].inspect)\n return current[:fstype] if current[:fstype]\n return unless File.exists?(device)\n dev_type_str = `file -s '#{device}'`.chomp\n case\n when dev_type_str =~ /SGI XFS/ then self['fstype'] = 'xfs'\n when dev_type_str =~ /Linux.*(ext[2-4])/ then self['fstype'] = $1\n else\n raise \"Can't determine filesystem type of #{device} -- set it explicitly in node[:volumes]\"\n end\n self['fstype']\n end", "def unmount\n if !is_mounted?\n warning('dev, sys, and proc are already unmounted')\n else\n announcing 'Unmounting dev, sys, and proc' do\n dirs = %w[ dev sys proc ]\n dirs.each{|dir| cmd(\"umount -l #{$chrootdir}/#{dir}\", exit=false) }\n end\n end\n end", "def do_ls()\n\t\tif @system_type == WINDOWS then \n\t\t\treturn %x(dir #{@path})\n\t\tend \n\t\tif @system_type == UNIX then \n\t\t\treturn %x(ls #{@path})\n\t\tend\n\tend", "def get_online_disk_command()\n if @os_info.major < 6; \"online noerr\" else; \"online disk noerr\" end\n end", "def get_dell_chassis_info\n ENV['PATH'] = \"#{ENV['PATH']}:/opt/dell/srvadmin/bin/\"\n chassis = {}\n result = nil\n begin\n #result = `omreport modularenclosure -fmt ssv`\n #result.split(\"\\n\").each do |line|\n # if line =~ /Service Tag/\n # chassis[:service_tag] = line.split(\";\")[1].strip\n # break\n # end\n #end\n timeout(5) do\n result = `omreport chassis info -fmt ssv`\n end\n result.split(\"\\n\").each do |line|\n if line =~ /Server Module Location;Slot (\\d+)/\n chassis[:slot_num] = $1.to_i\n elsif line =~ /Chassis Service Tag/\n chassis[:service_tag] = line.split(\";\")[1].strip\n end\n end\n # if no slot_number then the blade isn't really in a chassis/blade enclosure\n # such as the case with Dell PowerEdge 1950\n return {} if chassis[:slot_num].nil?\n rescue Timeout::Error\n warn \"Timed out when trying to run omreport\"\n rescue\n warn \"Failed to run/parse Dell's omreport command\"\n end\n return chassis\n end", "def list_size_swap_partitions # nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\" && $6==\"82\") print $5;else {if ($5==\"82\") print $4}}' | sed s/+//g`.chomp\nend", "def unmount_command(path)\n \"udisksctl unmount --block-device #{path}\"\nend", "def umount_and_detach_device(options={})\n detached_vol=nil\n device = get_device_mount_point(self.MountPoint)\n if(options[:device])\n STDERR.puts \"WARNING! the previously mounted device (#{device}) is different from the device we're asking to detach (#{options[:device]})\"\n device = options[:device]\n end\n begin\n umount_dir(self.MountPoint)\n rescue Exception => e\n STDERR.puts \"#{e}\\n ...continuing without unmounting\"\n end\n #detache the mounted volume\n STDERR.puts \"Detaching volume in device #{device}:\"\n begin\n detached_vol=detach_volume(device)\n\n raise EBSRemoteExecException.new(nil,$?,\"Timeout while waiting for the device to attach\") unless wait_for_detachment(device)\n rescue Exception => e\n display_exception(e, \"unmount_and_detach_device\")\n STDERR.puts \"...was the previously mounted DB directory not an EBS volume??\\n continuing without the detachment...\"\n end\n detached_vol\n end", "def docker_info()\n# changed cmd to use full path for security\n# cmd = 'docker info'\n cmd = which('docker') + \" info\"\n\tOpen3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|\n docker_info_stdout=stdout.read\n containers = docker_info_stdout.grep(/Containers/).to_s.split(':',2).last\n images = docker_info_stdout.grep(/Images/).to_s.split(':',2).last\n driver = docker_info_stdout.grep(/Driver/).to_s.split(':',2).last\n root_dir = docker_info_stdout.grep(/Root Dir/).to_s.split(':',2).last\n dirs = docker_info_stdout.grep(/Dirs/).to_s.split(':',2).last\n return \"Containers:#{containers.to_i} Images:#{images.to_i} Driver:#{driver.to_s.delete!(\"\\n\",\" \")} Root Dir:#{root_dir.to_s.delete!(\"\\n\")} Dirs:#{dirs.to_s.delete!(\"\\n\")}\"\nend\nend", "def pwd\r\n ndev.rpc.command(\"show cli directory\").text.strip\r\n end", "def stat_char(filename)\r\n return nil if !File.exists?(filename)\r\n\r\n return '/' if File.directory?(filename)\r\n return '%' if File.chardev?(filename)\r\n return '#' if File.blockdev?(filename)\r\n return '@' if File.symlink?(filename)\r\n return '=' if File.socket?(filename)\r\n return '|' if File.pipe?(filename)\r\n return '*' if File.executable?(filename)\r\n nil\r\n end", "def mountpoint\n \"#{spec[:temp_dir]}\"\n end", "def mountpoint\n self\n end", "def mountpoint\n self\n end", "def fetch_disk_size\n total_size = 0\n total_size = `lsblk -b --output SIZE -d -n | paste -s -d + - | bc`\n number_to_human_size total_size\n end", "def __nrpe_fstab\n\t\t\t\tdata = call_nrpe \"check_fstab\"\n\t\t\t\treturn false if data == false\n\t\t\t\tdisks = data.chomp.split(\"|\").map! {|x| x.strip }\n\t\t\t\tdisks.delete(\"$\") if disks.include?(\"$\")\n\t\t\t\treturn disks\n\t\tend", "def mounted?(force: false)\n if force || mounted.nil?\n self.mounted = dataset.mounted?(recursive: true)\n else\n mounted\n end\n end", "def filesystem\n platform_service(:filesystem)\n end", "def dockerized?\n File.read(\"/proc/1/cgroup\").include?(\"docker\")\nend", "def lsblk_path(p)\n return unless !p['path'] && p['name']\n\n if File.exist?(\"/dev/#{p['name']}\")\n p['path'] = \"/dev/#{p['name']}\"\n elsif File.exist?(\"/dev/mapper/#{p['name']}\")\n p['path'] = \"/dev/mapper/#{p['name']}\"\n end\n end", "def verify_mount_count\n @mounted_partitions.length\n end", "def df( opts = {} )\r\n \r\n outf = {:format => 'text' } if opts[:format] == :text\r\n args = { :detail => true } if opts[:size_div]\r\n \r\n got = @ndev.rpc.get_system_storage( args, outf )\r\n \r\n return got.text if opts[:format] == :text\r\n return got if opts[:format] == :xml\r\n \r\n df_h = {}\r\n ### need to turn this into a Hash\r\n got.xpath('filesystem').each do |fs|\r\n fs_name = fs.xpath('filesystem-name').text.strip\r\n fs_h = {}\r\n df_h[fs_name] = fs_h\r\n \r\n fs_h[:mounted_on] = fs.xpath('mounted-on').text.strip \r\n datum = fs.xpath('total-blocks')\r\n fs_h[:total_blocks] = datum.text.to_i\r\n fs_h[:total_size] = datum.attribute('format').value\r\n \r\n datum = fs.xpath('used-blocks')\r\n fs_h[:used_blocks] = datum.text.to_i\r\n fs_h[:used_size] = datum.attribute('format').value\r\n fs_h[:used_percent] = fs.xpath('used-percent').text.to_i\r\n \r\n datum = fs.xpath('available-blocks')\r\n fs_h[:avail_blocks] = datum.text.to_i\r\n fs_h[:avail_size] = datum.attribute('format').value\r\n if opts[:size_div]\r\n fs_h[:total_size] = fs_h[:total_size].to_i / opts[:size_div]\r\n fs_h[:used_size] = fs_h[:used_size].to_i / opts[:size_div]\r\n fs_h[:avail_size] = fs_h[:avail_size].to_i / opts[:size_div]\r\n end\r\n end\r\n df_h\r\n end", "def configure(conf)\n super\n # -P: use the POSIX output format\n @execute_command = \"df -P #{@option} #{@mounted_path} 2> /dev/null\"\n end", "def get_unix_info()\n v = $VERBOSE\n $VERBOSE = nil\n sysname = `uname -s`\n $VERBOSE = v\n sysname = sysname.chomp\n\n if(sysname.include?(\"Linux\")) # for linux (rhel, suse, oel)\n # check if it is SUSE\n filepath = Pathname.new(\"/etc/SuSE-release\")\n if(filepath.exist?())\n release_file = '/etc/SuSE-release'\n else # for RHEL, OEL, etc.\n release_file = '/etc/issue'\n end\n\n $VERBOSE = nil\n flavor = `head -n 1 #{release_file}`\n $VERBOSE = v\n sysname = flavor.sub(/\\(\\w+\\)/, '').chomp\n sysname = sysname.sub(/\\s+\\Z/, \"\")\n\n else # for other unix platforms (solaris, aix, hpux)\n $VERBOSE = nil\n if(sysname.eql?(\"AIX\"))\n version = `oslevel`\n else\n version = `uname -r`\n end\n $VERBOSE = v\n sysname = sysname + \" \" + version.chomp\n end\n\n $VERBOSE = nil\n if(sysname.eql?(\"HP-UX\"))\n processor = `uname -m`\n else\n processor = `uname -p`\n end\n\n if(sysname.include?(\"SunOS\"))\n isainfo = `isainfo -b`\n isainfo = isainfo.chomp\n bitinfo = \" \" + isainfo + \"-bit\"\n else\n bitinfo = \"\"\n end\n $VERBOSE = v\n\n os_info = sysname + \" \" + processor.chomp + bitinfo\n os_info\nend", "def stat(path = nil, mode = StatNormal)\n\n # Find entry, and return. Dead simple :-p.\n path = Path.new(path) unless path.kind_of?(Path)\n mmap, cmap = dir_walk(path, mode == StatStrict ? DW_Fail : DW_Nil)\n [mmap, cmap, path]\n\n end", "def meminfo\n File.read(\"/proc/meminfo\").split(\"\\n\").map{ |f| f.split(':') }\n .map{ |name, value| [name, value.to_i / 1024.0] }.to_h\nrescue\n {}\nend", "def read_device_info (device, kind)\n kind = kind.to_sym\n kinds = [:ip, :udid, :serial]\n unless kinds.include?(kind)\n raise \"#{kind} must be one of '#{kinds}'\"\n end\n cmd = \"cat ~/.xamarin/devices/#{device}/#{kind} | tr -d '\\n'\"\n `#{cmd}`\nend", "def all_devices search = nil\n partitions = []\n devices = []\n device = nil\n has_extended = false\n if DEBUG_MODE or Platform.ubuntu? or Platform.fedora?\n command = \"lsblk\"\n params = \" #{search} -b -P -o VENDOR,MODEL,TYPE,SIZE,KNAME,UUID,LABEL,MOUNTPOINT,FSTYPE,RM\"\n end\n lsblk = CommandsExecutor.new command, params\n lsblk.execute\n raise \"Command execution error: #{lsblk.stderr.read}\" if not lsblk.success?\n\n lsblk.result.each_line do |line|\n data_hash = {}\n line.squish!\n line_data = line.gsub!(/\"(.*?)\"/, '\\1#').split \"#\"\n line_data.each do |data|\n data.strip!\n key, value = data.split \"=\"\n data_hash[key.downcase] = value\n end\n data_hash['rm'] = data_hash['rm'].to_i # rm = 1 if device is a removable/flash device, otherwise 0\n if data_hash['type'] == 'mpath'\n data_hash.except!('uuid', 'label', 'mountpoint', 'fstype')\n if device\n multipath_info = {'mkname' => data_hash['kname'], 'multipath' => true, 'size' => data_hash['size']}\n device.merge! multipath_info\n else\n data_hash['multipath'] = true\n device = data_hash\n devices.push device\n end\n next\n end\n if data_hash['type'] == 'disk'\n data_hash.except!('uuid', 'label', 'mountpoint', 'fstype')\n unless device.nil?\n device['partitions'] = partitions\n partitions = []\n devices.push device\n device = nil # cleanup the variable\n end\n device = data_hash\n next\n end\n if data_hash['type'] == 'part'\n data_hash.except!('model', 'vendor')\n data_hash.merge! self.usage data_hash['kname']\n\n partition_number = get_partition_number \"/dev/#{data_hash['kname']}\" # For reference: data_hash['kname'].match(/[0-9]*$/)[0].to_i\n extended_partition_types = ['0x05'.hex, '0x0F'.hex]\n if partition_type_hex(data_hash['kname']).in? extended_partition_types\n has_extended = true\n next\n end\n if has_extended and partition_number > 4\n data_hash['logical'] = true\n end\n # device['partitions'].nil? ? device['partitions'] = [data_hash] : device['partitions'].push(data_hash)\n partitions.push(data_hash)\n end\n end\n device['partitions'] = partitions if device\n devices.push device\n if search\n return devices.first || partitions.first\n else\n return devices\n end\n end", "def from_stty\n return unless output.tty?\n size = run_command('stty', 'size').split.map(&:to_i)\n size if nonzero_column?(size[1])\n rescue Errno::ENOENT\n end", "def umount(partitions)\n partitions.each do |p|\n next unless p['mountpoint']\n\n return nil unless umount_dev(p['path'])\n end\n end", "def bindfs_fuse_loaded(machine)\n machine.guest.capability(:bindfs_fuse_installed)\n end", "def mount?\n return $game_player.system_tag == TMount\n end", "def get_available_fusion_vms(options)\n vm_list = []\n if File.directory?(options['fusiondir']) or File.symlink?(options['fusiondir'])\n vm_list = %x[find \"#{options['fusiondir']}/\" -name \"*.vmx'].split(\"\\n\")\n end\n return vm_list\nend", "def disk_statistics(flags=\"\")\n disk_stats = Vmstator::DiskStatistics.new\n output = `vmstat #{flags}`.split(\"\\n\")\n # remove first line of the output\n output.shift\n output.shift\n output.each do |line|\n name, total, merged, sectors, ms, total, merged, sectors, ms, cur, sec = line.split\n data = {:name => name, :totoal => total, :merged => merged, :sectors => sectors,\n :ms => ms, :cur => cur, :sec => sec }\n disk_stats.update(data)\n end\n disk_stats\n end", "def enum_recent_mounts(base_key)\n\trecent_mounts = []\n\tpartial_path = base_key + '\\Software\\\\Microsoft\\Windows\\CurrentVersion\\Explorer'\n\tfull_path = \"#{partial_path}\\\\Map Network Drive MRU\"\n\texplorer_keys = registry_enumkeys(partial_path)\n\tif explorer_keys.include?(\"Map Network Drive MRU\")\n\t\tregistry_enumvals(full_path).each do |k|\n\t\t\tif not k =~ /MRUList/\n\t\t\t\trecent_mounts << registry_getvaldata(full_path,k)\n\t\t\tend\n\t\tend\n\tend\n\treturn recent_mounts\nend", "def guest_device(name, mount_point_obj)\n \"/dev/#{guest_vg_name(name, mount_point_obj)}/#{guest_lv_name(mount_point_obj)}\"\n end", "def read_host_info\n json { execute_prlctl('server', 'info', '--json') }\n end" ]
[ "0.6927114", "0.6858722", "0.631671", "0.6203542", "0.6201873", "0.6196647", "0.60554075", "0.60455483", "0.60393727", "0.5905791", "0.59029275", "0.5758121", "0.57253873", "0.57090795", "0.5683376", "0.56236786", "0.5562347", "0.55541927", "0.55527204", "0.55078304", "0.54673046", "0.54519385", "0.544172", "0.5430317", "0.54187846", "0.5417214", "0.5404257", "0.5402652", "0.5380167", "0.53759414", "0.5365202", "0.5348262", "0.5328976", "0.53278184", "0.53169984", "0.5316247", "0.5316053", "0.5275307", "0.5257795", "0.5224116", "0.51569194", "0.51504123", "0.5118374", "0.50856453", "0.5076764", "0.5069075", "0.50678813", "0.5057726", "0.502588", "0.5003209", "0.5001801", "0.49926767", "0.4960279", "0.49594212", "0.4959064", "0.49533165", "0.49319363", "0.49205807", "0.4901154", "0.4878864", "0.48737353", "0.4869902", "0.4863281", "0.48627296", "0.4854934", "0.48516268", "0.48278338", "0.4816462", "0.4799689", "0.47872558", "0.47816142", "0.47528273", "0.47470048", "0.4746365", "0.47322056", "0.47233975", "0.47233975", "0.4718198", "0.46931666", "0.46857944", "0.4683449", "0.46829316", "0.46729958", "0.46673667", "0.46669915", "0.4653445", "0.46442991", "0.46385655", "0.46242443", "0.46229845", "0.46213442", "0.46127892", "0.45972937", "0.45936406", "0.45724875", "0.45626432", "0.45562896", "0.4547073", "0.45396537", "0.45288116" ]
0.59032905
10
Reads /proc/mounts and finds all tmpfs. It returns a Hash But if the info isn't available or /proc/mounts is not readable, it will return an empty Hash.
def tmpfs ret = {} mounts.each { |x| ret.merge!({x.split[1] => x}) if x.start_with?('tmpfs '.freeze) } ret end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_mounts\n mount_hash = {}\n mounts = File.open(\"/etc/mtab\", \"r\").read.split(\"\\n\").map{|l| l.split(/\\s+/)}\n mounts.each{|m| mount_hash[m[1]] = m[0] unless %w[devpts udev sysfs tmpfs none proc].include?(m[0])}\n mount_hash\nend", "def mountpoints\n mtab = IO.readlines '/proc/mounts'\n mountpoints = mtab.map{ |line| line.split(/\\s+/)[1]}\n mountpoints.map!{ |mount| unescape(mount) }\n # Ignore common system mountpoints.\n mountpoints.reject!{ |mount| mount =~ /^\\/$/ }\n mountpoints.reject!{ |mount| mount =~ /^\\/(proc|sys|usr|boot|tmp|dev|var|bin|etc|lib).*/ }\n # Mount /run/media/* but ignore other /run/ mountpoints.\n mountpoints.reject!{ |mount| mount =~ /^\\/run.*/ unless mount =~ /^\\/run\\/(media.*)/ }\n\n # Add home dir.\n mountpoints << home\n end", "def mounts_info\n @mounts_info ||= vault_client.request(:get, \"/v1/sys/internal/ui/mounts\")\n rescue Vault::VaultError\n unable_to_determine_version\n raise\n end", "def mounts\r\n @mounts.list\r\n end", "def disk_space()\n\n instructions = 'df -h'\n r = @ssh ? @ssh.exec!(instructions) : `#{instructions}`\n\n @results[:disk_usage] = {}\n\n a = r.lines.grep(/\\/dev\\/root/)\n\n puts ('a: ' + a.inspect).debug if @debug\n\n if a.any? then\n size, used, avail = a[0].split(/ +/).values_at(1,2,3)\n\n @results[:disk_usage][:root] = {size: size, used: used, \n avail: avail}\n end\n\n a2 = r.lines.grep(/\\/dev\\/sda1/)\n\n puts ('a2: ' + a2.inspect).debug if @debug\n\n if a2.any? then\n size, used, avail = a2[0].split(/ +/).values_at(1,2,3)\n\n @results[:disk_usage][:sda1] = {size: size, used: used, \n avail: avail}\n end\n\n end", "def other_mounts\n others = []\n fstab_lines.each do |line|\n localdevice, localmount, _fstype, _options, _freq, _pass = line.split(/\\s+/)\n others << line if localmount == mount && localdevice != device\n end\n others\n end", "def getmountedvolumes\n # only support Linux for now\n return {} unless Facter['kernel'] && Facter['kernel'].value == 'Linux'\n\n dir = \"/etc\"\n mounted = {}\n\n # AUTOFS - gather only files named auto[._]*\n Dir.glob(File.join(dir, \"*\")).each do |file|\n next if file !~ /^auto[._].*/\n\n # AUTOFS - match only lines that look like nfs syntax such as host:/path\n IO.foreach(file) do |line|\n if line =~ /\\w:\\S/ && line !~ /^\\s*#/\n # Parse it, Example : \" nventory_backup -noatime,intr irvnetappbk:/vol/nventory_backup \"\n if line =~ /^(\\w[\\w\\S]+)\\s+\\S+\\s+(\\w[\\w\\S]+):(\\S+)/\n mnt = $1\n host = $2\n vol = $3\n mounted[\"volumes[mounted][/mnt/#{mnt}][config]\"] = file\n mounted[\"volumes[mounted][/mnt/#{mnt}][volume_server]\"] = host\n mounted[\"volumes[mounted][/mnt/#{mnt}][volume]\"] = vol\n mounted[\"volumes[mounted][/mnt/#{mnt}][type]\"] = 'nfs'\n end\n end\n end # IO.foreach\n end # Dir.glob\n\n # FSTAB - has diff syntax than AUTOFS. Example: \"server:/usr/local/pub /pub nfs rsize=8192,wsize=8192,timeo=14,intr\"\n IO.foreach(\"/etc/fstab\") do |line|\n if line =~ /^(\\w[\\w\\S]+):(\\S+)\\s+(\\S+)\\s+nfs/\n host = $1\n vol = $2\n mnt = $3\n mounted[\"volumes[mounted][#{mnt}][config]\"] = \"/etc/fstab\"\n mounted[\"volumes[mounted][#{mnt}][volume_server]\"] = host\n mounted[\"volumes[mounted][#{mnt}][volume]\"] = vol\n mounted[\"volumes[mounted][#{mnt}][type]\"] = 'nfs'\n end\n end # IO.foreach\n return mounted\n end", "def get_disk_util\n used_info = query_data(params[:host], 'df.1kblocks.used', params[:from_ts], params[:to_ts])\n total_info = query_data(params[:host], 'df.1kblocks.total', params[:from_ts], params[:to_ts])\n\n used_info.delete_if { |k, v|\n k.index(\"fstype=tmpfs\")\n }\n total_info.delete_if { |k, v|\n k.index(\"fstype=tmpfs\")\n }\n \n results = {}\n used_info.each { |k, v|\n matcher = /mount=([\\/\\w]+) /.match(k)\n if matcher\n path = matcher[1]\n\n if total_info.has_key?(k)\n total_v = total_info[k]\n total_v_map = Hash[total_v]\n results[path] = v.collect { |point|\n ts = point[0]\n if (total_v_map.has_key?(ts))\n [ts, format(\"%.2f\", point[1] * 100.0 / total_v_map[ts]).to_f]\n end\n }.keep_if { |v| v }\n end\n end\n }\n\n render json: results\n end", "def mount_list(www_root)\n arr = []\n %x{mount -t iso9660}.scan(/\\S+ on (\\S+)/) do |a|\n mountpoint = a[0]\n arr << mountpoint if mountpoint.match %r{#{www_root}}\n end\n arr\nend", "def is_mounted?(device)\n system(\"grep -q '#{device}' /proc/mounts\")\nend", "def getdiskusage\n content = \"\"\n begin\n content = `df -k`\n rescue\n warn \"Failed to run df command\"\n return nil\n end\n used_space = 0\n avail_space = 0\n content.split(\"\\n\").each do |line|\n if line =~ /\\s+\\d+\\s+(\\d+)\\s+(\\d+)\\s+\\d+%\\s+\\/($|home$)/\n used_space += $1.to_i\n avail_space += $2.to_i\n end\n end\n return {:avail_space => avail_space, :used_space => used_space}\n end", "def filesystem_usage\n\n usage = {}\n\n df = capture_command_output('df', '-k')[1..-1] # Don't include the column headers.\n df.each do |df_line|\n\n df_line.strip!\n device = df_line.match(/^(.*?)\\s{2,}/)[1]\n tokens = df_line.gsub(/^#{Regexp.quote(device)}\\s+/, '').split(/\\s+/, 5)\n \n # Convert all KB values to bytes.\n size = tokens[0].to_i * 1024\n used = tokens[1].to_i * 1024\n available = tokens[2].to_i * 1024\n used_percentage = tokens[3].to_i\n\n usage[device] = {\n :size => size,\n :used => used,\n :used_percentage => used_percentage,\n :available => available\n }\n\n end\n\n usage\n\n end", "def mount_paths_listing\n Dir[\"#{mounts_path}/*\"]\n end", "def tmpfs_mount_status(desired)\n # Start with checking if it was mounted the way we would mount it\n # this is ALMOST the same as the 'is it identical' check for non-tmpfs\n # filesystems except that with tmpfs we don't treat 'auto' as equivalent and\n # that we skip inode64 option on current mount status - because it's activated\n # by default on Linux kernel >= 5.9\n fs_data = node.filesystem_data\n key = \"#{desired['device']},#{desired['mount_point']}\"\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n if mounted['fs_type'] == 'tmpfs'\n Chef::Log.debug(\n \"fb_fstab: tmpfs #{desired['device']} on \" +\n \"#{desired['mount_point']} is currently mounted...\",\n )\n\n skipped_opts = []\n if _are_tmpfs_using_inode64?\n\n # inode64 is active by default on tmpfs for Linux kernel > 5.9\n skipped_opts.push('inode64')\n end\n\n if compare_opts(desired['opts'], mounted['mount_options'], skipped_opts)\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n end\n end\n # OK, if that's not the case, we don't have the same device, which\n # is OK. Find out if we have something mounted at the same spot, and\n # get its device name so we can find it's entry in node['filesystem']\n if fs_data['by_mountpoint'][desired['mount_point']]\n # If we are here the mountpoints are the same...\n mounted = fs_data['by_mountpoint'][desired['mount_point']].to_hash\n # OK, if it's tmpfs as well, we're diong good\n if mounted['fs_type'] == 'tmpfs'\n Chef::Log.warn(\n \"fb_fstab: Treating #{mounted['devices']} on \" +\n \"#{desired['mount_point']} the same as #{desired['device']} on \" +\n \"#{desired['mount_point']} because they are both tmpfs.\",\n )\n Chef::Log.debug(\n \"fb_fstab: tmpfs #{desired['device']} on \" +\n \"#{desired['mount_point']} is currently mounted...\",\n )\n Chef::Log.debug(\"fb_fstab: #{desired} vs #{mounted}\")\n if compare_opts(desired['opts'], mounted['mount_options'])\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n end\n Chef::Log.warn(\n \"fb_fstab: tmpfs is desired on #{desired['mount_point']}, but \" +\n \"non-tmpfs #{mounted['devices']} (#{mounted['fs_type']}) currently \" +\n 'mounted there.',\n )\n return :conflict\n end\n :missing\n end", "def all_entries\n inclusively do\n [Mount::Entry.new(\n shared_dir.path,\n shared_dir.mountpoint,\n 'none',\n 'bind,create=dir,ro',\n true\n )] + entries.select { |m| m.in_config? || (m.automount? && !m.temp?) }\n end\n end", "def device_of_mount(m)\n unless Pathname.new(m).mountpoint?\n Chef::Log.warn(\n \"#{m} is not a mount point - I can't determine its device.\",\n )\n return nil\n end\n node['filesystem2']['by_pair'].to_hash.each do |pair, info|\n # we skip fake filesystems 'rootfs', etc.\n next unless pair.start_with?('/')\n # is this our FS?\n next unless pair.end_with?(\",#{m}\")\n # make sure this isn't some fake entry\n next unless info['kb_size']\n return info['device']\n end\n Chef::Log.warn(\n \"#{m} shows as valid mountpoint, but Ohai can't find it.\",\n )\n return nil\n end", "def device_of_mount(m)\n fs = self.filesystem_data\n unless Pathname.new(m).mountpoint?\n Chef::Log.warn(\n \"fb_helpers: #{m} is not a mount point - I can't determine its \" +\n 'device.',\n )\n return nil\n end\n unless fs && fs['by_pair']\n Chef::Log.warn(\n 'fb_helpers: no filesystem data so no node.device_of_mount',\n )\n return nil\n end\n fs['by_pair'].to_hash.each do |pair, info|\n # we skip fake filesystems 'rootfs', etc.\n next unless pair.start_with?('/')\n # is this our FS?\n next unless pair.end_with?(\",#{m}\")\n # make sure this isn't some fake entry\n next unless info['kb_size']\n\n return info['device']\n end\n Chef::Log.warn(\n \"fb_helpers: #{m} shows as valid mountpoint, but Ohai can't find it.\",\n )\n nil\n end", "def GetMountPoints\n mountPoints = {}\n swapPoints = []\n tg = GetTargetMap()\n Builtins.foreach(tg) do |targetdevice, target|\n partitions = Ops.get_list(target, \"partitions\", [])\n Builtins.foreach(partitions) do |partition|\n partitionName = Ops.get_string(partition, \"device\", \"\")\n mountPoint = Ops.get_string(partition, \"mount\", \"\")\n fsid = Ops.get_integer(partition, \"fsid\", 0)\n if mountPoint != \"\"\n raid_type = \"\"\n if Ops.get_symbol(partition, \"type\", :undefined) == :sw_raid\n raid_type = Ops.get_string(partition, \"raid_type\", \"\")\n end\n # partition has a mount point\n if mountPoint == \"swap\"\n swapPoints = Builtins.add(\n swapPoints,\n [partitionName, fsid, targetdevice, raid_type]\n )\n else\n mountPoints = Builtins.add(\n mountPoints,\n mountPoint,\n [partitionName, fsid, targetdevice, raid_type]\n )\n end\n end\n end\n end\n if Ops.greater_than(Builtins.size(swapPoints), 0)\n mountPoints = Builtins.add(mountPoints, \"swap\", swapPoints)\n end\n if !Stage.initial\n cm = Builtins.filter(Partitions.CurMounted) do |e|\n Builtins.search(Ops.get_string(e, \"spec\", \"\"), \"/dev/\") == 0\n end\n Builtins.foreach(cm) do |e|\n if !Builtins.haskey(mountPoints, Ops.get_string(e, \"file\", \"\"))\n p = GetPartition(tg, Ops.get_string(e, \"spec\", \"\"))\n if Ops.greater_than(Builtins.size(p), 0)\n raid_type = \"\"\n if Ops.get_symbol(p, \"type\", :undefined) == :sw_raid\n raid_type = Ops.get_string(p, \"raid_type\", \"\")\n end\n d = GetDiskPartition(Ops.get_string(e, \"spec\", \"\"))\n Ops.set(\n mountPoints,\n Ops.get_string(e, \"file\", \"\"),\n [\n Ops.get_string(p, \"device\", \"\"),\n Ops.get_integer(p, \"fsid\", 0),\n Ops.get_string(d, \"disk\", \"\"),\n raid_type\n ]\n )\n end\n end\n end\n end\n Builtins.y2milestone(\"ret %1\", mountPoints)\n deep_copy(mountPoints)\n end", "def mount_files\n Dir.glob('proc/*', base: mountpoint)\n end", "def all_devices search = nil\n partitions = []\n devices = []\n device = nil\n has_extended = false\n if DEBUG_MODE or Platform.ubuntu? or Platform.fedora?\n command = \"lsblk\"\n params = \" #{search} -b -P -o VENDOR,MODEL,TYPE,SIZE,KNAME,UUID,LABEL,MOUNTPOINT,FSTYPE,RM\"\n end\n lsblk = CommandsExecutor.new command, params\n lsblk.execute\n raise \"Command execution error: #{lsblk.stderr.read}\" if not lsblk.success?\n\n lsblk.result.each_line do |line|\n data_hash = {}\n line.squish!\n line_data = line.gsub!(/\"(.*?)\"/, '\\1#').split \"#\"\n line_data.each do |data|\n data.strip!\n key, value = data.split \"=\"\n data_hash[key.downcase] = value\n end\n data_hash['rm'] = data_hash['rm'].to_i # rm = 1 if device is a removable/flash device, otherwise 0\n if data_hash['type'] == 'mpath'\n data_hash.except!('uuid', 'label', 'mountpoint', 'fstype')\n if device\n multipath_info = {'mkname' => data_hash['kname'], 'multipath' => true, 'size' => data_hash['size']}\n device.merge! multipath_info\n else\n data_hash['multipath'] = true\n device = data_hash\n devices.push device\n end\n next\n end\n if data_hash['type'] == 'disk'\n data_hash.except!('uuid', 'label', 'mountpoint', 'fstype')\n unless device.nil?\n device['partitions'] = partitions\n partitions = []\n devices.push device\n device = nil # cleanup the variable\n end\n device = data_hash\n next\n end\n if data_hash['type'] == 'part'\n data_hash.except!('model', 'vendor')\n data_hash.merge! self.usage data_hash['kname']\n\n partition_number = get_partition_number \"/dev/#{data_hash['kname']}\" # For reference: data_hash['kname'].match(/[0-9]*$/)[0].to_i\n extended_partition_types = ['0x05'.hex, '0x0F'.hex]\n if partition_type_hex(data_hash['kname']).in? extended_partition_types\n has_extended = true\n next\n end\n if has_extended and partition_number > 4\n data_hash['logical'] = true\n end\n # device['partitions'].nil? ? device['partitions'] = [data_hash] : device['partitions'].push(data_hash)\n partitions.push(data_hash)\n end\n end\n device['partitions'] = partitions if device\n devices.push device\n if search\n return devices.first || partitions.first\n else\n return devices\n end\n end", "def mounted?(name)\n mount_loc = File.join(KVM_MOUNT_POINT, name)\n system(\"mount | grep #{mount_loc}\")\nend", "def dev_stat\n begin\n @dev_stat ||= Sys::Filesystem.stat dev_path\n rescue SystemCallError\n @dev_stat = nil\n end\n end", "def fetch_mounted_nfs_shares\n if resource[:nfs_hostname]\n # Get list of all mounted NFS datastores, and add it to mounted NFS shares\n Puppet.debug(\"Getting list of mounted NFS datastores...\")\n host.esxcli.storage.nfs.list.each do |nfs_store|\n if nfs_store[:Host] && nfs_store[:Share] && nfs_store[:Mounted]\n key = nfs_store[:Host] + \":\" + nfs_store[:Share]\n @mounted_nfs_shares[key] = { :volume_name => nfs_store[:VolumeName], :new_mount => false }\n Puppet.debug(\"Found existing NFS mount #{key} on the ESX host\")\n end\n end\n end\n end", "def lsof\n Dir.new(\"/proc/#{Process.pid}/fd/\").entries\n end", "def check_unwanted_filesystems\n # extra things to skip\n devs_to_skip = node['fb_fstab']['umount_ignores']['devices'].dup\n dev_prefixes_to_skip =\n node['fb_fstab']['umount_ignores']['device_prefixes'].dup\n mounts_to_skip =\n node['fb_fstab']['umount_ignores']['mount_points'].dup\n mount_prefixes_to_skip =\n node['fb_fstab']['umount_ignores']['mount_point_prefixes'].dup\n mount_regexes_to_skip =\n node['fb_fstab']['umount_ignores']['mount_point_regexes'].dup\n fstypes_to_skip = node['fb_fstab']['umount_ignores']['types'].dup\n\n base_mounts = get_unmasked_base_mounts(:hash)\n\n # we're going to iterate over specified mounts a lot, lets dump it\n desired_mounts = node['fb_fstab']['mounts'].to_hash\n\n fs_data = node.filesystem_data\n fs_data['by_pair'].to_hash.each_value do |mounted_data|\n # ohai uses many things to populate this structure, one of which\n # is 'blkid' which gives info on devices that are not currently\n # mounted. This skips those, plus swap, of course.\n unless mounted_data['mount']\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"- it isn't mounted.\",\n )\n next\n end\n # Work around chef 12 ohai bug\n if mounted_data.key?('inodes_used') && !mounted_data.key?('kb_used')\n Chef::Log.debug(\n 'fb_fstab: Skipping mal-formed Chef 12 \"df -i\" entry ' +\n mounted_data.to_s,\n )\n next\n end\n # skip anything seemingly magical\n if devs_to_skip.include?(mounted_data['device'])\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}): exempted device\",\n )\n next\n elsif mounts_to_skip.include?(mounted_data['mount'])\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}): exempted mountpoint\",\n )\n next\n elsif fstypes_to_skip.include?(mounted_data['fs_type'])\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}): exempted fstype\",\n )\n next\n elsif dev_prefixes_to_skip.any? do |i|\n mounted_data['device']&.start_with?(i)\n end\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}) - exempted device prefix\",\n )\n next\n elsif mount_prefixes_to_skip.any? do |i|\n mounted_data['mount']&.start_with?(i)\n end\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}) - exempted mount_point prefix\",\n )\n next\n elsif mount_regexes_to_skip.any? do |i|\n mounted_data['mount'] =~ /#{i}/\n end\n Chef::Log.debug(\n \"fb_fstab: Skipping umount check for #{mounted_data['device']} \" +\n \"(#{mounted_data['mount']}) - exempted mount_point regex\",\n )\n next\n end\n\n # Is this device in our list of desired mounts?\n next if should_keep(mounted_data, desired_mounts, base_mounts)\n\n if node['fb_fstab']['enable_unmount']\n converge_by \"unmount #{mounted_data['mount']}\" do\n umount(mounted_data['mount'], mounted_data['lock_file'], node['fb_fstab']['umount_delete_empty_mountdir'])\n end\n else\n Chef::Log.warn(\n \"fb_fstab: Would umount #{mounted_data['device']} from \" +\n \"#{mounted_data['mount']}, but \" +\n 'node[\"fb_fstab\"][\"enable_unmount\"] is false',\n )\n Chef::Log.debug(\"fb_fstab: #{mounted_data}\")\n end\n end\n end", "def get_partition_info\n # remove leading slash so it matches the packages.DU path\n remove_slash = true\n\n if !Stage.initial\n # read /proc/mounts as a list of maps\n # $[\"file\":\"/boot\", \"freq\":0, \"mntops\":\"rw\", \"passno\":0, \"spec\":\"/dev/sda1\", \"vfstype\":\"ext2\"]\n mounts = Convert.convert(\n SCR.Read(path(\".proc.mounts\")),\n :from => \"any\",\n :to => \"list <map <string, any>>\"\n )\n Builtins.y2milestone(\"mounts %1\", mounts)\n\n partitions = []\n Builtins.foreach(mounts) do |mpoint|\n name = Ops.get_string(mpoint, \"file\", \"\")\n if Builtins.substring(name, 0, 1) == \"/\" &&\n Builtins.substring(name, 0, 5) != \"/dev/\" && # filter out /dev/pts etc.\n Ops.get_string(mpoint, \"vfstype\", \"\") != \"rootfs\" # filter out duplicate \"/\" entry\n capacity = Pkg.TargetCapacity(name)\n if capacity != 0 # dont look at pseudo-devices (proc, shmfs, ...)\n used = Pkg.TargetUsed(name)\n partitions = Builtins.add(\n partitions,\n {\n \"name\" => name,\n \"free\" => Ops.subtract(capacity, used),\n \"used\" => used\n }\n )\n end\n end\n end\n Pkg.TargetInitDU(partitions)\n Builtins.y2milestone(\"get_partition_info: %1\", partitions)\n return deep_copy(partitions)\n end # !Stage::initial ()\n\n # remove the previous failures\n @failed_mounts = []\n\n # installation stage - Storage:: is definitely present\n # call Storage::GetTargetMap()\n targets = Convert.convert(\n WFM.call(\"wrapper_storage\", [\"GetTargetMap\"]),\n :from => \"any\",\n :to => \"map <string, map>\"\n )\n\n if targets == nil\n Builtins.y2error(\"Target map is nil, Storage:: is probably missing\")\n end\n\n if Mode.test\n targets = Convert.convert(\n SCR.Read(path(\".target.yast2\"), \"test_target_map.ycp\"),\n :from => \"any\",\n :to => \"map <string, map>\"\n )\n end\n\n target_partitions = []\n min_spare = 20 * 1024 * 1024 # minimum free space ( 20 MB )\n\n Builtins.foreach(targets) do |disk, diskinfo|\n part_info = Ops.get_list(diskinfo, \"partitions\", [])\n Builtins.foreach(part_info) do |part|\n Builtins.y2milestone(\"Adding partition: %1\", part)\n used_fs = Ops.get_symbol(part, \"used_fs\", :unknown)\n # ignore VFAT and NTFS partitions (bnc#)\n if used_fs == :vfat || used_fs == :ntfs\n Builtins.y2warning(\n \"Ignoring partition %1 with %2 filesystem\",\n Ops.get_string(part, \"device\", \"\"),\n used_fs\n )\n else\n free_size = 0\n\n if Ops.get(part, \"mount\") != nil &&\n Builtins.substring(Ops.get_string(part, \"mount\", \"\"), 0, 1) == \"/\"\n if Ops.get(part, \"create\") == true ||\n Ops.get(part, \"delete\") == false ||\n Ops.get(part, \"create\") == nil &&\n Ops.get(part, \"delete\") == nil\n Builtins.y2debug(\n \"get_partition_info: adding partition: %1\",\n part\n )\n\n # get free_size on partition in kBytes\n free_size = Ops.multiply(\n Ops.get_integer(part, \"size_k\", 0),\n 1024\n )\n free_size = Ops.subtract(free_size, min_spare)\n\n # free_size smaller than min_spare, fix negative value\n if Ops.less_than(free_size, 0)\n Builtins.y2milestone(\"Fixing free size: %1 to 0\", free_size)\n free_size = 0\n end\n\n used = 0\n if !(Ops.get_boolean(part, \"create\", false) ||\n Ops.get_boolean(part, \"format\", false))\n tmpdir = Convert.to_string(SCR.Read(path(\".target.tmpdir\")))\n tmpdir = Ops.add(tmpdir, \"/diskspace_mount\")\n SCR.Execute(\n path(\".target.bash\"),\n Builtins.sformat(\"test -d %1 || mkdir -p %1\", tmpdir)\n )\n\n # mount in read-only mode (safer)\n mount_options = [\"ro\"]\n\n # add \"nolock\" if it's a NFS share (bnc#433893)\n if used_fs == :nfs\n Builtins.y2milestone(\"Mounting NFS with 'nolock' option\")\n mount_options = Builtins.add(mount_options, \"nolock\")\n end\n\n # join the options\n mount_options_str = Builtins.mergestring(mount_options, \",\")\n\n mount_command = Builtins.sformat(\n \"/bin/mount -o %1 %2 %3\",\n mount_options_str,\n Ops.get_string(part, \"device\", \"\"),\n tmpdir\n )\n\n Builtins.y2milestone(\n \"Executing mount command: %1\",\n mount_command\n )\n\n result = Convert.to_integer(\n SCR.Execute(path(\".target.bash\"), mount_command)\n )\n Builtins.y2milestone(\"Mount result: %1\", result)\n\n if result == 0\n partition = Convert.convert(\n SCR.Read(path(\".run.df\")),\n :from => \"any\",\n :to => \"list <map <string, string>>\"\n )\n Builtins.foreach(partition) do |p|\n if Ops.get_string(p, \"name\", \"\") == tmpdir\n Builtins.y2internal(\"P: %1\", p)\n free_size = Ops.multiply(\n Builtins.tointeger(Ops.get_string(p, \"free\", \"0\")),\n 1024\n )\n used = Ops.multiply(\n Builtins.tointeger(Ops.get_string(p, \"used\", \"0\")),\n 1024\n )\n end\n end\n SCR.Execute(\n path(\".target.bash\"),\n Builtins.sformat(\"/bin/umount %1\", tmpdir)\n )\n else\n Builtins.y2error(\n \"Mount failed, ignoring partition %1\",\n Ops.get_string(part, \"device\", \"\")\n )\n @failed_mounts = Builtins.add(@failed_mounts, part)\n\n next\n end\n else\n # for formatted partitions estimate free system size\n # compute fs overhead\n used = EstimateFsOverhead(part)\n\n if Ops.greater_than(used, 0)\n Builtins.y2milestone(\n \"Partition %1: assuming fs overhead: %2kB\",\n Ops.get_string(part, \"device\", \"\"),\n Ops.divide(used, 1024)\n )\n end\n\n # journal size\n js = 0\n\n if ExtFs(used_fs)\n js = ExtJournalSize(part)\n reserved = ReservedSpace(part)\n\n if Ops.greater_than(reserved, 0)\n used = Ops.add(used, reserved)\n end\n elsif used_fs == :xfs\n js = XfsJournalSize(part)\n elsif used_fs == :reiser\n js = ReiserJournalSize(part)\n elsif used_fs == :jfs\n js = JfsJournalSize(part)\n else\n Builtins.y2warning(\n \"Unknown journal size for filesystem: %1\",\n used_fs\n )\n end\n\n if Ops.greater_than(js, 0)\n Builtins.y2milestone(\n \"Partition %1: assuming journal size: %2kB\",\n Ops.get_string(part, \"device\", \"\"),\n Ops.divide(js, 1024)\n )\n used = Ops.add(used, js)\n end\n\n # decrease free size\n free_size = Ops.subtract(free_size, used)\n\n # check for underflow\n if Ops.less_than(free_size, 0)\n Builtins.y2milestone(\"Fixing free size: %1 to 0\", free_size)\n free_size = 0\n end\n end\n\n # convert into kB for TargetInitDU\n free_size = Ops.divide(free_size, 1024)\n used = Ops.divide(used, 1024)\n\n Builtins.y2milestone(\n \"available partition: mount: %1, free: %2 KB, used: %3 KB\",\n Ops.get_string(part, \"mount\", \"\"),\n free_size,\n used\n )\n if !remove_slash\n target_partitions = Builtins.add(\n target_partitions,\n {\n \"name\" => Ops.get_string(part, \"mount\", \"\"),\n \"used\" => used,\n \"free\" => free_size\n }\n )\n else\n part_name = \"\"\n mount_name = Ops.get_string(part, \"mount\", \"\")\n\n if mount_name != \"/\"\n part_name = Builtins.substring(\n mount_name,\n 1,\n Builtins.size(mount_name)\n )\n else\n part_name = mount_name\n end\n\n target_partitions = Builtins.add(\n target_partitions,\n { \"name\" => part_name, \"used\" => used, \"free\" => free_size }\n )\n end\n end\n end\n end\n end # foreach (`part)\n end # foreach (`disk)\n\n # add estimated size occupied by non-package files\n target_partitions = EstimateTargetUsage(target_partitions)\n\n Builtins.y2milestone(\"get_partition_info: part %1\", target_partitions)\n Pkg.TargetInitDU(target_partitions)\n\n deep_copy(target_partitions)\n end", "def verify_mounted(partition)\n\treturn `grep partition /proc/mounts | wc -l`.chomp\nend", "def enum_recent_mounts(base_key)\n\trecent_mounts = []\n\tpartial_path = base_key + '\\Software\\\\Microsoft\\Windows\\CurrentVersion\\Explorer'\n\tfull_path = \"#{partial_path}\\\\Map Network Drive MRU\"\n\texplorer_keys = registry_enumkeys(partial_path)\n\tif explorer_keys.include?(\"Map Network Drive MRU\")\n\t\tregistry_enumvals(full_path).each do |k|\n\t\t\tif not k =~ /MRUList/\n\t\t\t\trecent_mounts << registry_getvaldata(full_path,k)\n\t\t\tend\n\t\tend\n\tend\n\treturn recent_mounts\nend", "def get_current_devices(proc_partitions_output)\n lines = proc_partitions_output.split(\"\\n\")\n partitions = lines.drop(2).map do |line|\n line.chomp.split.last\n end.reject do |partition|\n partition =~ /^dm-\\d/\n end\n devices = partitions.select do |partition|\n partition =~ /[a-z]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n if devices.empty?\n devices = partitions.select do |partition|\n partition =~ /[0-9]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n end\n devices\n end", "def filesystem_labels\n\n labels = {}\n\n mount = capture_command_output('mount')\n mount.each do |mount_line|\n\n mount_line.strip!\n device = mount_line.match(/^(.*?) on/)[1]\n\n if PlatformInfo.linux?\n\n # /dev/hda3 on / type ext4 (rw,errors=remount-ro)\n mount_point = mount_line.match(/^#{Regexp.quote(device)} on (.*?) type/)[1]\n fs_type = mount_line.match(/type (.*?) \\(/)[1]\n\n elsif PlatformInfo.osx?\n\n # /dev/disk0s2 on / (hfs, local, journaled)\n mount_point = mount_line.match(/^#{Regexp.quote(device)} on (.*?) \\(/)[1]\n fs_type = mount_line.match(/ \\((.*?), /)[1]\n \n else\n unsupported_platform\n end\n\n labels[device] = {\n :mount_point => mount_point,\n :file_system => fs_type\n }\n\n end\n\n labels\n\n end", "def setup_device_for_mount\n # use ramdisk for creating a test device for mount.\n # This can cleaner if we have chef resource/provider for ramdisk.\n case ohai[:platform_family]\n when \"aix\"\n # On AIX, we can't create a ramdisk inside a WPAR, so we use\n # a \"namefs\" mount against / to test\n # https://www-304.ibm.com/support/knowledgecenter/ssw_aix_71/com.ibm.aix.performance/namefs_file_sys.htm\n device = \"/\"\n fstype = \"namefs\"\n when \"debian\", \"rhel\", \"amazon\"\n device = \"/dev/ram1\"\n unless File.exist?(device)\n shell_out(\"mknod -m 660 #{device} b 1 0\")\n shell_out(\"chown root:disk #{device}\")\n end\n shell_out(\"ls -1 /dev/ram*\").stdout.each_line do |d|\n if shell_out(\"mount | grep #{d}\").exitstatus == \"1\"\n # this device is not mounted, so use it.\n device = d\n break\n end\n end\n fstype = \"tmpfs\"\n shell_out!(\"mkfs -q #{device} 512\")\n when \"solaris2\"\n device = \"swap\"\n fstype = \"tmpfs\"\n else\n end\n [device, fstype]\n end", "def forks\n `vmstat -f`.split.first\n end", "def list_partitions #by nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{print $1}'`.chomp.split\nend", "def mount_status(desired)\n # We treat tmpfs specially. While we don't want people to mount tmpfs with\n # a device of 'none' or 'tmpfs', we also don't want to make them remount\n # (and lose all their data) just to convert to fb_fstab. So we'll make\n # them use a new name in the config, but we will treat the pre-mounted\n # mounts as valid/the same. Besides, since the device is meaningless, we\n # can just ignore it for the purposes of this test anyway.\n if desired['type'] == 'tmpfs'\n return tmpfs_mount_status(desired)\n end\n\n key = \"#{desired['device']},#{desired['mount_point']}\"\n fs_data = node.filesystem_data\n mounted = nil\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n else\n key = \"#{desired['device']}/,#{desired['mount_point']}\"\n if fs_data['by_pair'][key]\n mounted = fs_data['by_pair'][key].to_hash\n end\n end\n\n if mounted\n Chef::Log.debug(\n \"fb_fstab: There is an entry in node['filesystem'] for #{key}\",\n )\n # If it's a virtual device, we require the fs type to be identical.\n # otherwise, we require them to be similar. This is because 'auto'\n # is meaningless without a physical device, so we don't want to allow\n # it to be the same.\n if compare_fstype(desired['type'], mounted['fs_type']) ||\n (desired['device'].start_with?('/') &&\n [desired['type'], mounted['fs_type']].include?('auto'))\n Chef::Log.debug(\n \"fb_fstab: FS #{desired['device']} on #{desired['mount_point']}\" +\n ' is currently mounted...',\n )\n if compare_opts(desired['opts'], mounted['mount_options'])\n Chef::Log.debug('fb_fstab: ... with identical options.')\n return :same\n else\n Chef::Log.debug(\n \"fb_fstab: ... with different options #{desired['opts']} vs \" +\n mounted['mount_options'].join(','),\n )\n Chef::Log.info(\n \"fb_fstab: #{desired['mount_point']} is mounted with options \" +\n \"#{canonicalize_opts(mounted['mount_options'])} instead of \" +\n canonicalize_opts(desired['opts']).to_s,\n )\n return :remount\n end\n else\n Chef::Log.warn(\n \"fb_fstab: Device #{desired['device']} is mounted at \" +\n \"#{mounted['mount']} as desired, but with fstype \" +\n \"#{mounted['fs_type']} instead of #{desired['type']}\",\n )\n return :conflict\n end\n end\n\n # In this case we don't have the device we expect at the mountpoint we\n # expect. Assuming it's not NFS/Gluster which can be mounted in more than\n # once place, we look up this device and see if it moved or just isn't\n # mounted\n unless ['nfs', 'nfs4', 'glusterfs'].include?(desired['type'])\n device = fs_data['by_device'][desired['device']]\n # Here we are checking if the device we want\n # has already a mount defined\n # We want to return :moved if it does except\n # in the case when it's a btrfs\n # disk and our desired and current options\n # are trying to mount different subvolumes\n if device && device['mounts'] && !device['mounts'].empty? &&\n !(\n FB::Fstab.btrfs_subvol?(\n device['fs_type'],\n device['mount_options'].join(','),\n ) &&\n FB::Fstab.btrfs_subvol?(\n desired['type'],\n desired['opts'],\n ) &&\n !FB::Fstab.same_subvol?(\n device['mounts'][0],\n device['mount_options'].join(','),\n desired['opts'],\n )\n )\n\n Chef::Log.warn(\n \"fb_fstab: #{desired['device']} is at #{device['mounts']}, but\" +\n \" we want it at #{desired['mount_point']}\",\n )\n return :moved\n end\n end\n\n # Ok, this device isn't mounted, but before we return we need to check\n # if anything else is mounted where we want to be.\n if fs_data['by_mountpoint'][desired['mount_point']]\n devices = fs_data['by_mountpoint'][\n desired['mount_point']]['devices']\n Chef::Log.warn(\n \"fb_fstab: Device #{desired['device']} desired at \" +\n \"#{desired['mount_point']} but something #{devices} already \" +\n 'mounted there.',\n )\n return :conflict\n end\n :missing\n end", "def get_current_devices(output)\n lines = output.split(\"\\n\")\n partitions = lines.drop(2).map do |line|\n line.chomp.split.last\n end\n partitions.reject! do |partition|\n partition =~ /^dm-\\d/\n end\n devices = partitions.select do |partition|\n partition =~ /[a-z]$/\n end\n devices.sort!.map! {|device| \"/dev/#{device}\"}\n if devices.empty?\n devices = partitions.select do |partition|\n partition =~ /[0-9]$/\n end.sort.map {|device| \"/dev/#{device}\"}\n end\n devices\n end", "def get_device_mount_point( incoming_path )\n mount_lines = `mount`\n raise EBSRemoteExecException.new(nil,$?,mount_lines) if $? != 0\n path = File.ftype(incoming_path) != 'directory'? File.dirname(incoming_path) : incoming_path\n device=nil\n longest = \"\"\n mount_lines.each_line {|line|\n match = line =~ /(.+)\\son\\s(.+?)\\s.*/\n candidate = $2.strip\n candidate_device = $1.strip\n # Keep the longest prefix matching\n if match && path =~ /^#{candidate}/ && candidate.length > longest.length\n longest = candidate\n device = candidate_device\n end\n }\n unless device\n STDERR.puts \"Couldn't find the device for mount point #{path}\"\n Kernel.exit(-1)\n end\n device\n end", "def get_local_storage\n storage = {:hostname => Socket.gethostname, :mounts => [], :vgs => []}\n\n LVM::LVM.new({:command => \"/usr/bin/sudo /sbin/lvm\"}) do |lvm|\n lvm.volume_groups.each do |vg|\n vg.logical_volumes.each do |lv|\n mnt = get_mount(lv.name)\n fs = {:mount => mnt.mount_point, :fs => mnt.name, :lv => lv.name, :vg => vg.name}\n storage[:mounts] << fs\n end\n\n volg = {:vg => vg.name, :pvs => []}\n vg.physical_volumes.each do |pv|\n volg[:pvs] << {:pv => pv.name}\n end\n storage[:vgs] << volg\n end\n end\n storage\n end", "def mountpoint?\n begin\n stat1 = expand_tilde.lstat\n stat2 = expand_tilde.parent.lstat\n stat1.dev == stat2.dev && stat1.ino == stat2.ino ||\n stat1.dev != stat2.dev\n rescue Errno::ENOENT\n false\n end\n end", "def linux_processes\n\t\tlist = []\n\t\t::Dir[\"/proc/*/stat\"].select { |file| file =~ /\\/proc\\/\\d+\\// }.each do |file|\n\t\t\tbegin\n\t\t\t\tlist << read_proc_file(file)\n\t\t\trescue\n\t\t\t\t# process died between the dir listing and accessing the file\n\t\t\tend\n\t\tend\n\t\tlist\n\tend", "def linux_processes\n\t\tlist = []\n\t\t::Dir[\"/proc/*/stat\"].select { |file| file =~ /\\/proc\\/\\d+\\// }.each do |file|\n\t\t\tbegin\n\t\t\t\tlist << read_proc_file(file)\n\t\t\trescue\n\t\t\t\t# process died between the dir listing and accessing the file\n\t\t\tend\n\t\tend\n\t\tlist\n\tend", "def mount(name, root_dev)\n puts \"Mounting KVM device: #{root_dev}\"\n mount_loc = File.join(KVM_MOUNT_POINT, name)\n unless(system(\"mount | grep #{mount_loc}\"))\n FileUtils.mkdir_p(mount_loc)\n if(system(\"mount #{root_dev} #{mount_loc}\"))\n mount_loc\n else\n raise \"Failed to mount #{root_dev} to #{mount_loc}\"\n end\n else\n puts \"Device already mounted (#{mount_loc})\"\n mount_loc\n end\nend", "def get_mount_path(filepath)\n cmd_exec(\"df \\\"#{filepath}\\\" | tail -1\").split(' ')[0]\n rescue\n raise \"Unable to get mount path of #{filepath}\"\n end", "def find_fstab(partitions, path)\n fstab = ''\n partitions.each do |p|\n OpenNebula.log(\"Looking for fstab on #{p['path']}\")\n\n rc = mount_dev(p['path'], path)\n next unless rc\n\n bin = COMMANDS[:catfstab]\n bin = COMMANDS[:cat] unless path.include?('containers/one-')\n\n cmd = \"#{bin} #{path}/etc/fstab\"\n\n _rc, fstab, _e = Command.execute(cmd, false)\n\n if fstab.empty?\n return false unless umount_dev(p['path'])\n\n next\n end\n\n OpenNebula.log(\"Found fstab on #{p['path']}\")\n break\n end\n\n return fstab unless fstab.empty?\n\n OpenNebula.log_error('No fstab file found')\n\n false\n end", "def umount(partitions)\n partitions.each do |p|\n next unless p['mountpoint']\n\n return nil unless umount_dev(p['path'])\n end\n end", "def initialize\n @mounts = {}\n end", "def getservedvolumes\n # only support Linux for now\n return {} unless Facter['kernel'] && Facter['kernel'].value == 'Linux'\n\n # Don't do anything if exports file is not there\n return {} if !File.exists?(\"/etc/exports\")\n\n served = {}\n\n IO.foreach(\"/etc/exports\") do |line|\n if line =~ /(\\S+)\\s+/\n vol = $1\n served[\"volumes[served][#{vol}][config]\"] = \"/etc/exports\"\n served[\"volumes[served][#{vol}][type]\"] = 'nfs'\n end\n end\n return served\n end", "def __nrpe_fstab\n\t\t\t\tdata = call_nrpe \"check_fstab\"\n\t\t\t\treturn false if data == false\n\t\t\t\tdisks = data.chomp.split(\"|\").map! {|x| x.strip }\n\t\t\t\tdisks.delete(\"$\") if disks.include?(\"$\")\n\t\t\t\treturn disks\n\t\tend", "def meminfo\n File.read(\"/proc/meminfo\").split(\"\\n\").map{ |f| f.split(':') }\n .map{ |name, value| [name, value.to_i / 1024.0] }.to_h\nrescue\n {}\nend", "def statfs(ctx,path)\n return wrap_context(ctx,__method__,path) if ctx\n block_size = 1024\n\n stats = @root.statistics(path)\n case stats\n when Array\n used_space, used_files, total_space, total_files = stats\n used_files ||= 0\n used_space ||= 0\n total_files ||= used_files\n total_space ||= used_space\n result = RFuse::StatVfs.new(\n \"bsize\" => block_size,\n \"frsize\" => block_size,\n \"blocks\" => total_space / block_size,\n \"bfree\" => (total_space - used_space)/block_size,\n \"bavail\" => (total_space - used_space)/block_size,\n \"files\" => total_files,\n \"ffree\" => (total_files - used_files)\n )\n return result\n else\n #expected to quack like rfuse:statvfs\n return stats\n end\n end", "def mountpoint?\n begin\n stat1 = lstat\n stat2 = parent.lstat\n stat1.dev != stat2.dev or stat1.ino == stat2.ino\n rescue Errno::ENOENT\n false\n end\n end", "def unmount\n if !is_mounted?\n warning('dev, sys, and proc are already unmounted')\n else\n announcing 'Unmounting dev, sys, and proc' do\n dirs = %w[ dev sys proc ]\n dirs.each{|dir| cmd(\"umount -l #{$chrootdir}/#{dir}\", exit=false) }\n end\n end\n end", "def autodiscover_devices\n logger.debug 'Discovering information about storage subsystem (HDD and MD devices)'\n @storage_information = HddAutodiscover.new(STORAGE_CONFIG[:volume_name])\n collected = @storage_information.collect()\n\n assert [:storage, :free_space, collected[:lvm][:free]]\n collected[:hdd].each do |hdd|\n assert [:hdd, hdd.device, :sn, hdd.sn]\n assert [:hdd, hdd.device, :temperature, hdd.temperature]\n assert [:hdd, hdd.device, :health, hdd.health]\n end\n end", "def stat(path = nil, mode = StatNormal)\n\n # Find entry, and return. Dead simple :-p.\n path = Path.new(path) unless path.kind_of?(Path)\n mmap, cmap = dir_walk(path, mode == StatStrict ? DW_Fail : DW_Nil)\n [mmap, cmap, path]\n\n end", "def disk_all(cfg)\n ignored = cfg['ignore_fs'] || 'tmpfs'\n ignore_fs = \"fstype!~\\\"#{ignored}\\\"\"\n query = @client.percent_query_free(\n \"node_filesystem_files{#{ignore_fs}}\",\n \"node_filesystem_files_free{#{ignore_fs}}\"\n )\n prepare_metrics('disk_all', @client.query(query))\n end", "def verify_mount_count\n @mounted_partitions.length\n end", "def disk_specs(path)\n specs = []\n unit = 0\n if resource[:virtual_disks]\n resource[:virtual_disks].each do |vd|\n size = vd[\"size\"].to_i * 1024 * 1024\n specs << disk_spec(path, size, unit)\n unit += 1\n end\n else\n specs << disk_spec(path, resource[:disk_size], unit)\n end\n\n specs\n end", "def snapshot_filesystem\n mtimes = {}\n\n files = @files.map { |file| Dir[file] }.flatten.uniq\n\n files.each do |file|\n if File.exists? file\n mtimes[file] = File.stat(file).mtime\n end\n end\n\n mtimes\n end", "def facts\n if ENV['MK_EXTERNAL_FACTS']\n begin\n Facter::Util::Config.ext_fact_loader = Facter::Util::DirectoryLoader.loader_for(ENV['MK_EXTERNAL_FACTS'])\n rescue Facter::Util::DirectoryLoader::NoSuchDirectoryError\n # An error here should go back to the server; though how ?\n # But carry on anyway\n end\n end\n Facter::to_hash\n end", "def lsblk(device)\n partitions = {}\n blocklist = ''\n\n cmd =\"#{COMMANDS[:lsblk]} -OJ #{device}\"\n\n 3.times do |t| # wait for device to be ready to be parsed\n rc, o, e = Command.execute(cmd, false)\n\n if rc != 0 || o.empty?\n OpenNebula.log_error(\"#{__method__}: #{rc}, #{o}, #{e}\") if t == 3\n sleep 1\n next\n end\n\n blocklist = o\n break\n end\n\n begin\n partitions = JSON.parse(blocklist)['blockdevices']\n\n if !device.empty?\n partitions = partitions[0]\n\n if partitions['children']\n partitions = partitions['children']\n else\n partitions = [partitions]\n end\n\n partitions.delete_if do |p|\n p['fstype'].casecmp('swap').zero? if p['fstype']\n end\n end\n rescue StandardError\n OpenNebula.log_error(\"lsblk: error parsing lsblk -OJ #{device}\")\n return {}\n end\n\n # Fix for lsblk paths for version < 2.33\n partitions.each do |p|\n lsblk_path(p)\n\n p['children'].each {|q| lsblk_path(q) } if p['children']\n end\n\n partitions\n end", "def _setup_tmpfs\n\t\treturn false if (!@config[\"ramdisk\"] || !@config[\"ramdisk\"][\"enabled\"])\n\t\treturn true if (command_send(\"mount | grep -E '/tmp/captain\\s' | awk '{print $1}'\").eql? \"tmpfs\")\n\t\t_nfs_server = command_send(\"sudo showmount -e localhost | grep /tmp/captain/nfs | awk '{print $2}'\")\n\t\t_nfs_client = command_send(\"sudo mount | grep -E '/tmp/captain/nfs\\s' | awk '{print $1}' | awk -F ':' '{print $1}'\")\n\t\t_size = [(@config[\"ramdisk\"][\"size\"] || 512), @capabilities[\"linux\"][\"ram\"][\"free\"]].min\n\t\tdestroy_nfs_server if _nfs_server.length>0\n\t\tdestroy_nfs_client if _nfs_client.length>0\n\t\tcommand_send(\"([ ! -d \\\"/tmp/captain\\\" ] || mv /tmp/captain /tmp/.captain) && mkdir /tmp/captain && sudo mount -t tmpfs -o size=#{_size}m tmpfs /tmp/captain && ([ ! -d \\\"/tmp/.captain\\\" ] || (shopt -s dotglob && mv /tmp/.captain/* /tmp/captain/ && shopt -u dotglob && sudo rm -rf /tmp/.captain))\")\n\t\t@tmpfs = true\n\t\tsetup_nfs_server(_nfs_server, true) if _nfs_server.length>0 && (command_send(\"ls -la /tmp/captain/nfs/.check 2>/dev/null | wc -l\").eql? \"1\")\n\t\tsetup_nfs_client(_nfs_client, true) if _nfs_client.length>0\n\t\treturn true\n\tend", "def get_device_info()\n @errors = []\n info = {}\n return info unless @programmer_path\n\n response = IO.popen(\"#{@programmer_path} I\").readlines\n puts response if $debug\n response.each do |line|\n if line =~ /Error/i\n errors << line\n else\n parts = line.split(/:|\\.\\.\\./)\n info[parts[0].strip.split.join.to_sym] = parts[1].strip if parts.size == 2\n end\n end # each\n info\n end", "def read\n\n\t\t\t# initialise an array with zeroes\n\n\t\t\tret =\n\t\t\t\t(0...(COLS.size)).map { 0 }\n\n\t\t\t# iterate lines from the diskstats file\n\n\t\t\tFile.new(\"/proc/diskstats\").each \\\n\t\t\t\tdo |line|\n\n\t\t\t\t\t# split columns\n\n\t\t\t\t\tcols =\n\t\t\t\t\t\tline.strip.split /\\s+/\n\n\t\t\t\t\t# ignore irrelevant lines\n\n\t\t\t\t\tnext \\\n\t\t\t\t\t\tunless @disk == \"all\" \\\n\t\t\t\t\t\t\t|| cols[2] == @disk\n\n\t\t\t\t\t# add this lines data to the totals\n\n\t\t\t\t\t(0...(COLS.size)).each do |i|\n\n\t\t\t\t\t\tret[i] +=\n\t\t\t\t\t\t\tcols[i + 3].to_i\n\n\t\t\t\t\tend\n\n\t\t\t\tend\n\n\t\t\t# and return\n\n\t\t\treturn ret\n\n\t\tend", "def info_disks\n @disks = {}\n\n keys = disk_keys\n vc_disks = vcenter_disks_get\n one_disks = one_disks_list\n\n one_disks.each do |one_disk|\n index = one_disk['DISK_ID']\n\n disk = query_disk(one_disk, keys, vc_disks)\n\n vc_dev = vc_disks.delete(disk) if disk\n\n if vc_dev\n @disks[index] = Disk.new(index.to_i, one_disk, vc_dev)\n else\n @disks[index] = Disk.one_disk(index.to_i, one_disk)\n end\n end\n\n vc_disks.each {|d| @disks[d[:path_wo_ds]] = Disk.vc_disk(d) }\n\n @disks\n end", "def mountpoint\n 'dev/.osctl-mount-helper'\n end", "def get_available_fusion_vms(options)\n vm_list = []\n if File.directory?(options['fusiondir']) or File.symlink?(options['fusiondir'])\n vm_list = %x[find \"#{options['fusiondir']}/\" -name \"*.vmx'].split(\"\\n\")\n end\n return vm_list\nend", "def GetFreeSpace(device, used_fs, verbose)\n resize_info = {}\n content_info = {}\n\n r = (\n resize_info_ref = arg_ref(resize_info);\n content_info_ref = arg_ref(content_info);\n _GetFreeInfo_result = GetFreeInfo(\n device,\n true,\n resize_info_ref,\n true,\n content_info_ref,\n used_fs == :ntfs\n );\n resize_info = resize_info_ref.value;\n content_info = content_info_ref.value;\n _GetFreeInfo_result\n )\n\n used = 1024*Ops.get_integer(resize_info, :used_k, 0)\n resize_free = 1024*Ops.get_integer(resize_info, :resize_free_k, 0)\n df_free = 1024*Ops.get_integer(resize_info, :df_free_k, 0)\n resize_ok = Ops.get_boolean(resize_info, :resize_ok, false)\n\n win_disk = Ops.get_boolean(content_info, :windows, false)\n efi = Ops.get_boolean(content_info, :efi, false)\n\n if used_fs == :ntfs && (!r || !resize_ok) && verbose\n cmd = Builtins.sformat(\"/usr/sbin/ntfsresize -f -i '%1'\", device)\n Builtins.y2milestone(\"GetFreeSpace Executing cmd:%1\", cmd)\n bcall = Convert.to_map(\n SCR.Execute(\n path(\".target.bash_output\"),\n cmd,\n { \"LC_MESSAGES\" => \"POSIX\" }\n )\n )\n Builtins.y2milestone(\"GetFreeSpace Executing ret:%1\", bcall)\n tmp = _(\"Resize Not Possible:\") + \"\\n\\n\"\n tmp = Ops.add(\n Ops.add(tmp, Ops.get_string(bcall, \"stdout\", \"\")),\n Ops.get_string(bcall, \"stderr\", \"\")\n )\n Popup.Error(tmp)\n return {}\n end\n\n linux_size = 0\n min_linux_size = 0\n add_free = Ops.subtract(df_free, resize_free)\n\n Builtins.y2milestone(\n \"GetFreeSpace resize_free %1 add_free %2\",\n resize_free,\n add_free\n )\n\n if Ops.less_than(resize_free, 300 * 1024 * 1024) || !r\n linux_size = 0\n min_linux_size = 0\n elsif Ops.less_than(resize_free, 600 * 1024 * 1024)\n linux_size = resize_free\n if Ops.less_than(add_free, 75 * 1024 * 1024)\n linux_size = Ops.add(\n Ops.subtract(linux_size, 75 * 1024 * 1024),\n add_free\n )\n end\n min_linux_size = linux_size\n elsif Ops.less_than(resize_free, 1024 * 1024 * 1024)\n linux_size = resize_free\n if Ops.less_than(add_free, 200 * 1024 * 1024)\n linux_size = Ops.add(\n Ops.subtract(linux_size, 200 * 1024 * 1024),\n add_free\n )\n end\n min_linux_size = 300 * 1024 * 1024\n elsif Ops.less_than(resize_free, 2 * 1024 * 1024 * 1024)\n linux_size = resize_free\n if Ops.less_than(add_free, 300 * 1024 * 1024)\n linux_size = Ops.add(\n Ops.subtract(linux_size, 300 * 1024 * 1024),\n add_free\n )\n end\n min_linux_size = 500 * 1024 * 1024\n elsif Ops.less_than(resize_free, 3 * 1024 * 1024 * 1024)\n linux_size = resize_free\n if Ops.less_than(add_free, 800 * 1024 * 1024)\n linux_size = Ops.add(\n Ops.subtract(linux_size, 800 * 1024 * 1024),\n add_free\n )\n end\n min_linux_size = 500 * 1024 * 1024\n else\n linux_size = resize_free\n if Ops.less_than(add_free, Ops.divide(resize_free, 3))\n linux_size = Ops.add(\n Ops.subtract(linux_size, Ops.divide(resize_free, 3)),\n add_free\n )\n end\n min_linux_size = 500 * 1024 * 1024\n end\n\n new_size = Ops.subtract(\n Ops.add(Ops.add(used, add_free), resize_free),\n linux_size\n )\n\n ret = {\n \"free\" => (resize_free>0) ? resize_free : 0,\n \"df_free\" => df_free,\n \"used\" => used,\n \"win_disk\" => win_disk,\n \"efi\" => efi,\n \"linux_size\" => linux_size,\n \"max_win_size\" => Ops.subtract(\n Ops.add(Ops.add(used, resize_free), add_free),\n min_linux_size\n ),\n \"ntfs\" => used_fs == :ntfs,\n \"new_size\" => new_size\n }\n Ops.set(ret, \"ok\", r)\n Builtins.y2milestone(\"GetFreeSpace %1 ret %2\", device, ret)\n ret\n end", "def find_caches\n Dir.glob(File.join(@root, '**/*.cache')).reduce([]) { |stats, filename|\n stat = safe_stat(filename)\n # stat maybe nil if file was removed between the time we called\n # dir.glob and the next stat\n stats << [filename, stat] if stat\n stats\n }.sort_by { |_, stat| stat.mtime.to_i }\n end", "def __nrpe_alldisks\n\t\t\t\tdata = call_nrpe \"check_alldisks\"\n\t\t\t\treturn false if data == false\n\t\t\t\tdisks = data.chomp.split(\"|\")[1].split.map! {|x| x = x.split(\"=\")[0] }\n\t\t\t\treturn disks\n\t\tend", "def unmount_mounted_nfs_shares\n @mounted_nfs_shares.each do |key, value|\n if value[:new_mount]\n if unmount_nfs_share(value[:volume_name])\n @mounted_nfs_shares.delete(key) # Remove from mount map as well\n end\n end\n end\n end", "def format_mount(partition, mount)\n\n # Partitions that we already have mounts set for.\n return nil if partition == '/dev/mapper/rootvg-slash'\n return nil if partition == '/dev/mapper/rootvg-var'\n return nil if partition == '/dev/mapper/rootvg-tmp'\n\n mount\nend", "def mountpoint?\n begin\n stat1 = self.lstat\n stat2 = self.parent.lstat\n stat1.dev == stat2.dev && stat1.ino == stat2.ino ||\n stat1.dev != stat2.dev\n rescue Errno::ENOENT\n false\n end\n end", "def get_dell_chassis_info\n ENV['PATH'] = \"#{ENV['PATH']}:/opt/dell/srvadmin/bin/\"\n chassis = {}\n result = nil\n begin\n #result = `omreport modularenclosure -fmt ssv`\n #result.split(\"\\n\").each do |line|\n # if line =~ /Service Tag/\n # chassis[:service_tag] = line.split(\";\")[1].strip\n # break\n # end\n #end\n timeout(5) do\n result = `omreport chassis info -fmt ssv`\n end\n result.split(\"\\n\").each do |line|\n if line =~ /Server Module Location;Slot (\\d+)/\n chassis[:slot_num] = $1.to_i\n elsif line =~ /Chassis Service Tag/\n chassis[:service_tag] = line.split(\";\")[1].strip\n end\n end\n # if no slot_number then the blade isn't really in a chassis/blade enclosure\n # such as the case with Dell PowerEdge 1950\n return {} if chassis[:slot_num].nil?\n rescue Timeout::Error\n warn \"Timed out when trying to run omreport\"\n rescue\n warn \"Failed to run/parse Dell's omreport command\"\n end\n return chassis\n end", "def mountpoint\n \"#{spec[:temp_dir]}\"\n end", "def info\n Plist::parse_xml(diskutil 'info', '-plist', @dev_node)\n end", "def IsMounted(mountpoint)\n if Builtins.substring(\n mountpoint,\n Ops.subtract(Builtins.size(mountpoint), 1),\n 1\n ) == \"/\"\n mountpoint = Builtins.substring(\n mountpoint,\n 0,\n Ops.subtract(Builtins.size(mountpoint), 1)\n )\n end\n\n ret = true\n Builtins.foreach(@activated) do |e|\n if Ops.get_string(e, :type, \"\") == \"mount\" &&\n (Ops.get_string(e, :mntpt, \"\") == mountpoint ||\n Ops.get_string(e, :mntpt, \"\") == Ops.add(mountpoint, \"/\"))\n ret = true\n end\n end\n ret\n end", "def list_nix_partitions # nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\" && $6==\"83\") print $1;else {if ($5==\"83\") print $1}}'`.chomp.split\nend", "def lsblk_path(p)\n return unless !p['path'] && p['name']\n\n if File.exist?(\"/dev/#{p['name']}\")\n p['path'] = \"/dev/#{p['name']}\"\n elsif File.exist?(\"/dev/mapper/#{p['name']}\")\n p['path'] = \"/dev/mapper/#{p['name']}\"\n end\n end", "def DetectFs(device)\n ret = :unknown\n Builtins.y2milestone(\"DetectFs:%1\", device)\n vinfo = ::Storage::VolumeInfo.new()\n r = @sint.getVolume(device, vinfo)\n if r != 0\n Builtins.y2error(\"DetectFs device:%1 not found (ret:%2)\", device, r)\n else\n curr = {}\n curr = volumeMap(vinfo, curr)\n ret = Ops.get_symbol(curr, \"detected_fs\", :unknown)\n end\n Builtins.y2milestone(\"DetectFs ret %1\", ret)\n ret\n end", "def mount options = {}\n opts = {\n :force_readonly => false\n }.merge!(options)\n args = []\n args << 'readOnly' if opts[:force_readonly]\n args << opts[:mountpoint] if opts.has_key?(:mountpoint)\n args << self.dev_node\n diskutil 'mount', *args\n end", "def disk_statistics(flags=\"\")\n disk_stats = Vmstator::DiskStatistics.new\n output = `vmstat #{flags}`.split(\"\\n\")\n # remove first line of the output\n output.shift\n output.shift\n output.each do |line|\n name, total, merged, sectors, ms, total, merged, sectors, ms, cur, sec = line.split\n data = {:name => name, :totoal => total, :merged => merged, :sectors => sectors,\n :ms => ms, :cur => cur, :sec => sec }\n disk_stats.update(data)\n end\n disk_stats\n end", "def ip_by_mount(name)\n dev = available_dev unless mounted?(name)\n loc = mount(name, dev)\n addr = %x{cat #{File.join(loc, 'etc', 'network', 'interfaces')} | grep address}.split(' ').last.to_s.strip\n unmount_kvm_volume(name, dev) if dev\n addr\nend", "def list_size_swap_partitions # nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\" && $6==\"82\") print $5;else {if ($5==\"82\") print $4}}' | sed s/+//g`.chomp\nend", "def FindRootPartitions\n return if @didSearchForRootPartitions\n\n ModuleLoading.Load(\n \"reiserfs\",\n \"\",\n \"Linux\",\n \"Reiser FS\",\n Linuxrc.manual,\n true\n )\n ModuleLoading.Load(\"jfs\", \"\", \"Linux\", \"JFS\", Linuxrc.manual, true)\n ModuleLoading.Load(\"xfs\", \"\", \"Linux\", \"XFS\", Linuxrc.manual, true)\n ModuleLoading.Load(\"ext3\", \"\", \"Linux\", \"Ext3\", Linuxrc.manual, true)\n ModuleLoading.Load(\"ext4\", \"\", \"Linux\", \"Ext4\", Linuxrc.manual, true)\n ModuleLoading.Load(\"btrfs\", \"\", \"Linux\", \"BtrFS\", Linuxrc.manual, true)\n ModuleLoading.Load(\"raid0\", \"\", \"Linux\", \"Raid 0\", Linuxrc.manual, true)\n ModuleLoading.Load(\"raid1\", \"\", \"Linux\", \"Raid 1\", Linuxrc.manual, true)\n ModuleLoading.Load(\"raid5\", \"\", \"Linux\", \"Raid 5\", Linuxrc.manual, true)\n ModuleLoading.Load(\"raid6\", \"\", \"Linux\", \"Raid 6\", Linuxrc.manual, true)\n ModuleLoading.Load(\"raid10\", \"\", \"Linux\", \"Raid 10\", Linuxrc.manual, true)\n ModuleLoading.Load(\n \"multipath\",\n \"\",\n \"Linux\",\n \"Multipath\",\n Linuxrc.manual,\n true\n )\n ModuleLoading.Load(\"dm-mod\", \"\", \"Linux\", \"DM\", Linuxrc.manual, true)\n SCR.Execute(path(\".target.bash\"), \"/sbin/devmap_mknod.sh\")\n ModuleLoading.Load(\"dm-snapshot\", \"\", \"Linux\", \"DM\", Linuxrc.manual, true)\n\n if Mode.test\n Storage.SetTargetMap(\n Convert.convert(\n SCR.Read(path(\".target.yast2\"), \"test_target_map.ycp\"),\n :from => \"any\",\n :to => \"map <string, map>\"\n )\n )\n end\n\n #\tStorage::ActivateEvms();\n target_map = Storage.GetOndiskTarget\n Builtins.y2milestone(\"target_map: %1\", target_map)\n\n # prepare progress-bar\n if UI.WidgetExists(Id(\"search_progress\"))\n UI.ReplaceWidget(\n Id(\"search_progress\"),\n ProgressBar(\n Id(\"search_pb\"),\n _(\"Evaluating root partition. One moment please...\"),\n 100,\n 0\n )\n )\n end\n\n @rootPartitions = {}\n @numberOfValidRootPartitions = 0\n\n # all partitions on all devices\n max_steps = 0\n Builtins.foreach(target_map) do |device, description|\n max_steps = Ops.add(\n max_steps,\n Builtins.size(Ops.get_list(description, \"partitions\", []))\n )\n end\n\n counter = 0\n Builtins.foreach(target_map) do |device, description|\n Builtins.foreach(Ops.get_list(description, \"partitions\", [])) do |partition|\n counter = Ops.add(counter, 1)\n if UI.WidgetExists(Id(\"search_progress\"))\n UI.ChangeWidget(\n Id(\"search_pb\"),\n :Value,\n Ops.divide(Ops.multiply(100, counter), max_steps)\n )\n end\n # some partitions don't make sense at all\n if Ops.get_symbol(partition, \"detected_fs\", :unknown) != :swap &&\n Ops.get_symbol(partition, \"type\", :primary) != :extended\n freshman = {}\n\n if Mode.test\n freshman = {\n :valid => true,\n :name => \"SuSE Linux 4.2\",\n :arch => \"i286\",\n :label => \"Label\"\n }\n else\n freshman = CheckPartition(partition)\n end\n\n @rootPartitions = Builtins.add(\n @rootPartitions,\n Ops.get_string(partition, \"device\", \"error\"),\n freshman\n )\n\n if Ops.get_boolean(freshman, :valid, false)\n @numberOfValidRootPartitions = Ops.add(\n @numberOfValidRootPartitions,\n 1\n )\n end\n end\n end\n end\n\n # 100%\n if UI.WidgetExists(Id(\"search_progress\"))\n UI.ChangeWidget(Id(\"search_pb\"), :Value, 100)\n end\n\n @didSearchForRootPartitions = true\n\n Builtins.y2milestone(\"rootPartitions: %1\", @rootPartitions)\n\n nil\n end", "def get_fs_type(device)\n fs_check = Mixlib::ShellOut.new(\"blkid -c /dev/null #{device}\")\n fs_check.run_command\n match = fs_check.stdout.match(/\\sTYPE=\\\"(.*?)\\\"/)\n match = '' if match.nil?\n\n Chef::Log.info(\"File system type for device #{device}: #{match[1]}\")\n match[1]\nend", "def disks\n return @disks unless @disks.empty?\n\n info_disks\n end", "def find_matching_udev_devices(&block)\n\n #Create a udev enumerator devices.\n context = RubDev::Context.new\n enumerator = RubDev::Enumerate.new(context)\n\n #Yield the given enumerator to the provided block,\n #allowing it to narrow our search.\n block[enumerator]\n\n #... scan for the relevant devices...\n enumerator.scan_devices\n paths = enumerator.to_list\n\n devices = []\n\n #... and build an array of relevant syspaths.\n until paths.name.nil?\n devices << RubDev::Device.from_syspath(context, paths.name)\n paths.next\n end\n \n devices\n\n end", "def cache_found\n found = true\n\n Open3.popen3('klist') do |stdin, stdout, stderr|\n found = false unless stderr.gets.nil?\n end\n\n found\n end", "def df( opts = {} )\r\n \r\n outf = {:format => 'text' } if opts[:format] == :text\r\n args = { :detail => true } if opts[:size_div]\r\n \r\n got = @ndev.rpc.get_system_storage( args, outf )\r\n \r\n return got.text if opts[:format] == :text\r\n return got if opts[:format] == :xml\r\n \r\n df_h = {}\r\n ### need to turn this into a Hash\r\n got.xpath('filesystem').each do |fs|\r\n fs_name = fs.xpath('filesystem-name').text.strip\r\n fs_h = {}\r\n df_h[fs_name] = fs_h\r\n \r\n fs_h[:mounted_on] = fs.xpath('mounted-on').text.strip \r\n datum = fs.xpath('total-blocks')\r\n fs_h[:total_blocks] = datum.text.to_i\r\n fs_h[:total_size] = datum.attribute('format').value\r\n \r\n datum = fs.xpath('used-blocks')\r\n fs_h[:used_blocks] = datum.text.to_i\r\n fs_h[:used_size] = datum.attribute('format').value\r\n fs_h[:used_percent] = fs.xpath('used-percent').text.to_i\r\n \r\n datum = fs.xpath('available-blocks')\r\n fs_h[:avail_blocks] = datum.text.to_i\r\n fs_h[:avail_size] = datum.attribute('format').value\r\n if opts[:size_div]\r\n fs_h[:total_size] = fs_h[:total_size].to_i / opts[:size_div]\r\n fs_h[:used_size] = fs_h[:used_size].to_i / opts[:size_div]\r\n fs_h[:avail_size] = fs_h[:avail_size].to_i / opts[:size_div]\r\n end\r\n end\r\n df_h\r\n end", "def get_sysinfo\n\t\tsystem_data = {}\n\t\tkernel_version = cmd_exec(\"uname -a\")\n\t\tversion = read_file(\"/etc/release\").split(\"\\n\")[0].strip\n\t\tsystem_data[:version] = version\n\t\tsystem_data[:kernel] = kernel_version\n\t\tsystem_data[:hostname] = kernel_version.split(\" \")[1]\n\t\treturn system_data\n\tend", "def find_storage_locations\n if setting_ok_storage_locations\n $config[\"settings\"][\"storage destinations\"][\"tv\"].each do |directory|\n files_secondary = find_files(true,directory) \n shows_on_storage_device(directory,files_secondary).keys.each do |show|\n $show_storage[show] = directory\n end\n end\n end\nend", "def detach_disks_specs\n detach_disk_array = []\n extra_config = []\n keys = disk_keys.invert\n\n ipool = VCenterDriver::VIHelper.one_pool(OpenNebula::ImagePool)\n disks_each(:detached?) do |d|\n key = d.key.to_s\n source = VCenterDriver::FileHelper.escape_path(d.path)\n persistent =\n VCenterDriver::VIHelper\n .find_persistent_image_by_source(\n source, ipool\n )\n\n op = { :operation => :remove, :device => d.device }\n if !persistent && d.type != 'CDROM'\n op[:fileOperation] = :destroy\n end\n detach_disk_array << op\n\n # Remove reference opennebula.disk if exist from vmx and cache\n extra_config << d.config(:delete) if keys[key]\n end\n\n [detach_disk_array, extra_config]\n end", "def get_fs_type(device)\n fs_check = Mixlib::ShellOut.new(\"blkid -c /dev/null #{device}\")\n fs_check.run_command\n match = fs_check.stdout.match(/TYPE=\\\"(.*)\\\"/)\n match = '' if match.nil?\n\n match[1]\nend", "def mount_ephemerals(attrs={})\n owner.volume(:ephemeral0, attrs){ device '/dev/sdb'; volume_id 'ephemeral0' ; mount_point '/mnt' ; tags( :bulk => true, :local => true, :fallback => true) } if flavor_info[:ephemeral_volumes] > 0\n owner.volume(:ephemeral1, attrs){ device '/dev/sdc'; volume_id 'ephemeral1' ; mount_point '/mnt2'; tags( :bulk => true, :local => true, :fallback => true) } if flavor_info[:ephemeral_volumes] > 1\n owner.volume(:ephemeral2, attrs){ device '/dev/sdd'; volume_id 'ephemeral2' ; mount_point '/mnt3'; tags( :bulk => true, :local => true, :fallback => true) } if flavor_info[:ephemeral_volumes] > 2\n owner.volume(:ephemeral3, attrs){ device '/dev/sde'; volume_id 'ephemeral3' ; mount_point '/mnt4'; tags( :bulk => true, :local => true, :fallback => true) } if flavor_info[:ephemeral_volumes] > 3\n end", "def list_swap_partitions_with_size # nelsongs\n\treturn `fdisk -l | grep /dev | grep -v Disk | awk '{if ($2==\"*\" && $6==\"82\") print $1\":\"$5;else {if ($5==\"82\") print $1\":\"$4}}' | sed s/+//g`.chomp.split\nend", "def attach_disks_specs\n attach_disk_array = []\n extraconfig = []\n attach_spod_array = []\n attach_spod_disk_info = {}\n\n pos = { :ide => 0, :scsi => 0 }\n disks_each(:no_exists?) do |disk|\n disk.one_item['TYPE'] == 'CDROM' ? k = :ide : k = :scsi\n\n if disk.storpod?\n spec = calculate_add_disk_spec(disk.one_item, pos[k])\n attach_spod_array << spec\n\n controller_key = spec[:device].controllerKey\n unit_number = spec[:device].unitNumber\n\n unit_ctrl = \"#{controller_key}-#{unit_number}\"\n attach_spod_disk_info[unit_ctrl] = disk.id\n else\n aspec = calculate_add_disk_spec(disk.one_item, pos[k])\n extra_key = \"opennebula.mdisk.#{disk.one_item['DISK_ID']}\"\n extra_value = aspec[:device].key.to_s\n\n attach_disk_array << aspec\n extraconfig << { :key => extra_key, :value => extra_value }\n end\n\n pos[k]+=1\n end\n\n { :disks => attach_disk_array,\n :spods => attach_spod_array,\n :spod_info => attach_spod_disk_info,\n :extraconfig => extraconfig }\n end", "def mounted?\n !!( attached? && mount_point && File.exists?(mount_point) && current[:mount] == mount_point )\n end", "def shared_folders\n {}.tap do |result|\n @env[:machine].config.vm.synced_folders.each do |id, data|\n # Ignore NFS shared folders\n next if !data[:type] == :nfs\n\n # This to prevent overwriting the actual shared folders data\n result[id] = data.dup\n end\n end\n end", "def file_get_initialization(structure = ENV[\"HOME\"]) # this is linux specific for now\n @file_information = {} # {\"/directory\"=>[\"file\"], \"/directory/directory\"=>[\"file\", \"file\"]\n files = [] \n directory = \"\"\n directories = [] \n things = structure.split('/')\n things.each do |thing|\n if thing == \"\"\n directories.push(\"/root\")\n else\n directory = \"#{directory}/#{thing}\" \n @current_directory = directory\n directories.push(\"#{directory}\") if File.directory?(\"#{directory}\")\n end\n end \n return directories\n end", "def mounted?\n '' != self['MountPoint']\n end", "def get_1st_partition(device)\n # Resolves the real device name (ex. /dev/sdg)\n Chef::Log.info(\"Getting 1st partition for device: #{device}\")\n fs_check = Mixlib::ShellOut.new(\"lsblk -ln -o Name #{device}|awk 'NR==2'\")\n fs_check.run_command\n partition = \"/dev/\" + fs_check.stdout.strip\n Chef::Log.info(\"1st partition for device: #{device} is: #{partition}\")\n partition\nend" ]
[ "0.7868856", "0.705546", "0.6727915", "0.66328394", "0.64825094", "0.6407223", "0.63958997", "0.635185", "0.6327745", "0.615456", "0.6116929", "0.6062659", "0.60454106", "0.5913282", "0.58284503", "0.5810452", "0.57494676", "0.5737623", "0.5724618", "0.5695389", "0.5632698", "0.56222004", "0.56219953", "0.5618356", "0.5616188", "0.55848587", "0.5566519", "0.55372965", "0.55359614", "0.5499482", "0.5476862", "0.5439451", "0.54310375", "0.5385655", "0.5331082", "0.5329789", "0.5288038", "0.52853364", "0.5221698", "0.5221698", "0.51948357", "0.51849085", "0.515209", "0.51456445", "0.51422113", "0.5128975", "0.5122821", "0.511715", "0.51142985", "0.5066907", "0.5060828", "0.5058891", "0.50351816", "0.5024747", "0.50164515", "0.50133103", "0.4984201", "0.49756664", "0.49726573", "0.49704787", "0.49697894", "0.4968092", "0.49343696", "0.4932051", "0.49196804", "0.49075234", "0.49040923", "0.48920175", "0.4889293", "0.48844746", "0.48815143", "0.48795903", "0.48741305", "0.48690304", "0.4821921", "0.48215067", "0.48147205", "0.47884166", "0.4764388", "0.47573474", "0.47463232", "0.47425014", "0.4738449", "0.47374937", "0.4735458", "0.47327363", "0.4719732", "0.47160783", "0.47055727", "0.4687832", "0.4673792", "0.46719387", "0.46655318", "0.46611756", "0.46607086", "0.46578985", "0.46439624", "0.46396053", "0.46393076", "0.46295536" ]
0.7696831
1
define the arguments that the user will input
def arguments(model) args = OpenStudio::Ruleset::OSArgumentVector.new return args end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def arguments; end", "def arguments; end", "def arguments; end", "def arguments\n \"\"\n end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def get_input \n puts \"to save this game, input 's,filename'\"\n puts \"to load a game, input 'l,filename'\"\n puts \"input a coordinate to access. prefix with r for reveal or f for flag\"\n puts \"example 'f,1,2' places a flag at 1,2\"\n input = gets.chomp\n \n args = input.split(',')\n end", "def args(*) end", "def arguments(required, *optional)\n puts \"required: #{required}\"\n puts \"optional: #{optional}\"\nend", "def args()\n #This is a stub, used for indexing\n end", "def arguments()\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n #make an argument for the variable name\n variable_name = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"variable_name\",true)\n variable_name.setDisplayName(\"Enter Variable Name.\")\n variable_name.setDescription(\"Valid values can be found in the eplusout.rdd file after a simulation is run.\")\n args << variable_name\n \n #make an argument for the electric tariff\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << \"Detailed\"\n reporting_frequency_chs << \"Timestep\"\n reporting_frequency_chs << \"Zone Timestep\"\n reporting_frequency_chs << \"Hourly\"\n reporting_frequency_chs << \"Daily\"\n reporting_frequency_chs << \"Monthly\"\n reporting_frequency_chs << \"Runperiod\"\n reporting_frequency = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName(\"Reporting Frequency.\")\n reporting_frequency.setDefaultValue(\"Hourly\")\n args << reporting_frequency\n\n #make an argument for the key_value\n key_value = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"key_value\",true)\n key_value.setDisplayName(\"Enter Key Name.\")\n key_value.setDescription(\"Enter * for all objects or the full name of a specific object to.\")\n key_value.setDefaultValue(\"*\")\n args << key_value\n \n env = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"env\", true)\n env.setDisplayName(\"availableEnvPeriods\")\n env.setDescription(\"availableEnvPeriods\")\n env.setDefaultValue(\"RUN PERIOD 1\")\n args << env\n \n return args\n end", "def set_arguments (args)\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # make an argument for the variable name\n variable_name = OpenStudio::Measure::OSArgument.makeStringArgument('variable_name', true)\n variable_name.setDisplayName('Enter Variable Name.')\n variable_name.setDescription('Valid values can be found in the eplusout.rdd file after a simulation is run.')\n args << variable_name\n\n # make an argument for the electric tariff\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << 'Detailed'\n reporting_frequency_chs << 'Timestep'\n reporting_frequency_chs << 'Zone Timestep'\n reporting_frequency_chs << 'Hourly'\n reporting_frequency_chs << 'Daily'\n reporting_frequency_chs << 'Monthly'\n reporting_frequency_chs << 'Runperiod'\n reporting_frequency = OpenStudio::Measure::OSArgument.makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency.')\n reporting_frequency.setDefaultValue('Hourly')\n args << reporting_frequency\n\n # make an argument for the key_value\n key_value = OpenStudio::Measure::OSArgument.makeStringArgument('key_value', true)\n key_value.setDisplayName('Enter Key Name.')\n key_value.setDescription('Enter * for all objects or the full name of a specific object to.')\n key_value.setDefaultValue('*')\n args << key_value\n\n env = OpenStudio::Measure::OSArgument.makeStringArgument('env', true)\n env.setDisplayName('availableEnvPeriods')\n env.setDescription('availableEnvPeriods')\n env.setDefaultValue('RUN PERIOD 1')\n args << env\n\n args\n end", "def handle_arguments(args)\n if input_file.nil?\n print_usage\n true\n else\n args.help || args.version\n end\n end", "def arguments=(_arg0); end", "def command_line\r\n ARGV.each do |arg|\r\n if arg == \"instructions\"\r\n instructions\r\n elsif arg == \"calculator\"\r\n ask_for_digits\r\n else\r\n \r\n end\r\n end\r\n \r\n end", "def prescreen_input(args)\n if ((args.nil?) || (args.empty?))\n ['-eq', Date.today.strftime('%Y-%m-%d')]\n elsif ((args.length == 1) && (args[0].is_date?))\n ['-eq', args[0]]\n else\n args\n end\nend", "def varios_args(*args)\n puts \"Tamanho de args: #{args.size}\"\n args.each { |x| p x}\n end", "def process_arguments\n @e_addr = @options.email\n @r_name = @options.run_names\n @m_name = @options.machine_names\n @action = @options.action\n @snfs = @options.snfs\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # url of the city database\n city_db_url = OpenStudio::Measure::OSArgument.makeStringArgument('city_db_url', true)\n city_db_url.setDisplayName('City Database Url')\n city_db_url.setDescription('Url of the City Database')\n city_db_url.setDefaultValue('')\n args << city_db_url\n\n # project id to update\n project_id = OpenStudio::Measure::OSArgument.makeStringArgument('project_id', true)\n project_id.setDisplayName('Project ID')\n project_id.setDescription('Project ID to generate reports for.')\n project_id.setDefaultValue('0')\n args << project_id\n\n # datapoint id to update\n datapoint_id = OpenStudio::Measure::OSArgument.makeStringArgument('datapoint_id', true)\n datapoint_id.setDisplayName('Datapoint ID')\n datapoint_id.setDescription('Datapoint ID to generate reports for.')\n datapoint_id.setDefaultValue('0')\n args << datapoint_id\n\n return args\n end", "def validate_args (args)\n\t# todo\nend", "def args() return @args end", "def input=(_arg0); end", "def process_inputs(args)\n @input = ((name = args[:in_file]) && (IO.read(name, mode: \"rb\"))) ||\n args[:in_str] ||\n fail(\"An input must be specified.\")\n\n @generator = args[:generator] ||\n ((key = args[:key]) && Generator.new(key)) ||\n fail(\"A key or generator must be specified.\")\n\n @window = args[:window] || 16\n\n #The filler value is for testing purposes only. It should\n #not be specified when secure operation is desired.\n @fill_value = args[:filler]\n end", "def parse_args\r\n if(cmd.args =~ /\\=/)\r\n self.names = InputFormatter.titlecase_arg(cmd.args.before(\"=\"))\r\n self.action_args = cmd.args.after(\"=\")\r\n elseif (cmd.args && one_word_command)\r\n self.names = InputFormatter.titlecase_arg(cmd.args)\r\n self.action_args = \"\"\r\n else\r\n self.names = enactor.name\r\n self.action_args = cmd.args\r\n end\r\n\r\n self.names = self.names ? self.names.split(/[ ,]/) : nil\r\n\r\n self.combat_command = cmd.switch ? cmd.switch.downcase : nil\r\n end", "def manage_args(*args)\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n #make an argument for your name\n user_name = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"user_name\",true)\n user_name.setDisplayName(\"What is your name?\")\n args << user_name\n\n #make an argument to add new space true/false\n add_space = OpenStudio::Ruleset::OSArgument::makeBoolArgument(\"add_space\",true)\n add_space.setDisplayName(\"Add a space to your model?\")\n add_space.setDefaultValue(true)\n args << add_space\n \n return args\n end", "def greeting\n puts \"Hello, MTA rider! How can we help?\"\n puts \"please enter one of the following commands:\"\n puts \"lines / stops the_line / calculate Departing_Line Departing_Stop Arriving_Line Arriving_Stop\"\n user_call, *user_args = gets.chomp\n user_args.to_s\n # user_args.split(\" \")\n # puts user_input\n\n if user_call == lines\n show_lines()\n elsif user_call == stops\n show_stops(user_args[0])\n elsif user_call == calculate\n if user_args.length < 4\n puts 'please enter \"Departing_Line Departing_Stop Arriving_Line Arriving_Stop\"'\n puts 'or enter \"exit\" to return to the home screen' \n user_input = gets.chomp\n if user_input == \"exit\"\n greeting()\n end \n user_input = user_input.split(\" \")\n calculate(user_input[0], user_input[1], user_input[2], user_input[3])\n else\n calculate(user_args[0], user_args[1], user_args[2], user_args[3])\n end\n else\n \n end\nend", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n\n\n # Make an argument for evap effectiveness\n input_csv_path = OpenStudio::Measure::OSArgument::makeStringArgument(\"input_csv_folder_path\",true)\n input_csv_path.setDisplayName(\"raw_data_input_folder_path\")\n input_csv_path.setDefaultValue(\"data_file\")\n args << input_csv_path\n\n test_numbers = OpenStudio::StringVector.new\n test_numbers << 'Test_3'\n test_numbers << 'Test_6'\n test_numbers << 'Test_8'\n \n test_names = OpenStudio::StringVector.new\n test_names << 'UA_test'\n test_names << 'Cooling_test'\n test_names << 'Plenum_test'\n\n test_selections = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('test_data',test_numbers,test_names,true)\n\n \n test_selections.setDisplayName(\"Experiment\")\n test_selections.setDefaultValue(\"Test_3\")\n args << test_selections\n\n \n return args\n end", "def arguments\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # URL of the DEnCity server that will be posted to\n hostname = OpenStudio::Ruleset::OSArgument::makeStringArgument('hostname', true)\n hostname.setDisplayName('URL of the DEnCity Server')\n hostname.setDefaultValue('http://www.dencity.org')\n args << hostname\n\n # DEnCity server user id at hostname\n user_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('user_id',true)\n user_id.setDisplayName('User ID for DEnCity Server')\n args << user_id\n\n # DEnCIty server user id's password\n auth_code = OpenStudio::Ruleset::OSArgument::makeStringArgument('auth_code', true)\n auth_code.setDisplayName('Authentication code for User ID on DEnCity server')\n args << auth_code\n\n # Building type for DEnCity's metadata\n building_type = OpenStudio::Ruleset::OSArgument::makeStringArgument('building_type', false)\n building_type.setDisplayName('Building type')\n args << building_type\n\n # HVAC system for DEnCity's metadata\n primary_hvac = OpenStudio::Ruleset::OSArgument::makeStringArgument('primary_hvac', false)\n primary_hvac.setDisplayName('Primary HVAC system in building')\n args << primary_hvac\n\n args\n\n end", "def arguments\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n #make choice argument for facade\r\n choices = OpenStudio::StringVector.new\r\n choices << \"MessagePack\"\r\n choices << \"CSV\"\r\n choices << \"Both\"\r\n output_format = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"output_format\", choices)\r\n output_format.setDisplayName(\"Output Format\")\r\n output_format.setDefaultValue(\"Both\")\r\n args << output_format\r\n\r\n args\r\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\t\n #make an argument for entering furnace installed afue\n afue = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"afue\",true)\n afue.setDisplayName(\"Installed AFUE\")\n afue.setUnits(\"Btu/Btu\")\n afue.setDescription(\"The installed Annual Fuel Utilization Efficiency (AFUE) of the furnace, which can be used to account for performance derating or degradation relative to the rated value.\")\n afue.setDefaultValue(1.0)\n args << afue\n\n #make an argument for entering furnace installed supply fan power\n fanpower = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"fan_power_installed\",true)\n fanpower.setDisplayName(\"Installed Supply Fan Power\")\n fanpower.setUnits(\"W/cfm\")\n fanpower.setDescription(\"Fan power (in W) per delivered airflow rate (in cfm) of the indoor fan for the maximum fan speed under actual operating conditions.\")\n fanpower.setDefaultValue(0.5)\n args << fanpower\t\n\t\n #make a string argument for furnace heating output capacity\n furnacecap = OpenStudio::Measure::OSArgument::makeStringArgument(\"capacity\", true)\n furnacecap.setDisplayName(\"Heating Capacity\")\n furnacecap.setDescription(\"The output heating capacity of the furnace. If using '#{Constants.SizingAuto}', the autosizing algorithm will use ACCA Manual S to set the capacity.\")\n furnacecap.setUnits(\"kBtu/hr\")\n furnacecap.setDefaultValue(Constants.SizingAuto)\n args << furnacecap\n \n return args\n end", "def greeting(args)\r\n greet = args[:greet] || \"Hi\"\r\n title = args[:title] || \"Citizen\"\r\n name = args[:name] \r\n puts \"#{greet} #{title} #{name}\"\r\nend", "def parse_args\n\t\t@args = @args_a.each_slice(2).to_a.inject({}) { |h, k| h[k[0]] = k[1]; h }\n\t\tkeys = @skeys + @lkeys\n\t\t@args.each do |k, v|\n\t\t\tif !keys.include?(k)\n\t\t\t\tputs \"Unknown option `#{k}'\"\n\t\t\t\texit\n\t\t\tend\n\n\t\t\tif keys.include?(v)\n\t\t\t\tputs \"Missing values for `#{k}' and `#{v}'\"\n\t\t\t\texit\n\t\t\tend\n\n\t\t\tif v != nil\n\t\t\t\tif v.start_with?('-')\n\t\t\t\t\tputs \"Warning: Value of `#{k}' appears to be a flag\"\n\t\t\t\tend\n\n\t\t\t\tif @static.has_key?(k)\n\t\t\t\t\tif !@static[k].include?(v)\n\t\t\t\t\t\tputs \"Unknown option `#{v}' for `#{k}'\"\n\t\t\t\t\t\texit\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\tif remove_keys(@no_vals).has_blank?\n\t\t\tputs \"Missing argument(s)\"\n\t\t\texit\n\t\tend\t\t\t\n\tend", "def command_line_arguments(array)\n array.size.times do\n if array.include?('-nc')\n colour_changer(:white)\n array.delete('-nc')\n elsif array.any? { |x| ['-d1', '-d2', '-d3', '-d4'].include? x }\n key = (array[0])[1, 2].to_sym\n @difficulty = DIFFICULTY[key]\n @promptarr = prompt_select(key)\n @intro = false\n end\n end\n end", "def arguments()\n args = OpenStudio::Measure::OSArgumentVector.new\n \n #make an argument for the frequency\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << \"Detailed\"\n reporting_frequency_chs << \"Timestep\"\n reporting_frequency_chs << \"Hourly\"\n reporting_frequency_chs << \"Daily\"\n reporting_frequency_chs << \"Monthly\"\n reporting_frequency_chs << \"Runperiod\"\n reporting_frequency = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName(\"Reporting Frequency\")\n reporting_frequency.setDefaultValue(\"Hourly\")\n args << reporting_frequency\n \n # TODO: argument for subset of output meters\n \n return args\n end", "def arguments()\n args = OpenStudio::Measure::OSArgumentVector.new\n\n #make an argument for the frequency\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << \"Timestep\"\n reporting_frequency_chs << \"Hourly\"\n reporting_frequency_chs << \"Daily\"\n reporting_frequency_chs << \"Monthly\"\n reporting_frequency_chs << \"RunPeriod\"\n arg = OpenStudio::Measure::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n arg.setDisplayName(\"Reporting Frequency\")\n arg.setDefaultValue(\"Hourly\")\n args << arg\n\n #make an argument for including optional output variables\n arg = OpenStudio::Measure::OSArgument::makeBoolArgument(\"inc_output_variables\", true)\n arg.setDisplayName(\"Include Output Variables\")\n arg.setDefaultValue(false)\n args << arg\n\n return args\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n #make an argument for entering furnace installed afue\n userdefined_eff = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"userdefinedeff\",true)\n userdefined_eff.setDisplayName(\"Efficiency\")\n\tuserdefined_eff.setUnits(\"Btu/Btu\")\n\tuserdefined_eff.setDescription(\"The efficiency of the electric baseboard.\")\n userdefined_eff.setDefaultValue(1.0)\n args << userdefined_eff\n\n #make a choice argument for furnace heating output capacity\n cap_display_names = OpenStudio::StringVector.new\n cap_display_names << Constants.SizingAuto\n (5..150).step(5) do |kbtu|\n cap_display_names << \"#{kbtu} kBtu/hr\"\n end\n\n #make a string argument for furnace heating output capacity\n selected_baseboardcap = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"selectedbaseboardcap\", cap_display_names, true)\n selected_baseboardcap.setDisplayName(\"Heating Output Capacity\")\n selected_baseboardcap.setDefaultValue(Constants.SizingAuto)\n args << selected_baseboardcap\n\t\n return args\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n #make an argument for entering baseboard efficiency\n baseboardeff = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"efficiency\",true)\n baseboardeff.setDisplayName(\"Efficiency\")\n baseboardeff.setUnits(\"Btu/Btu\")\n baseboardeff.setDescription(\"The efficiency of the electric baseboard.\")\n baseboardeff.setDefaultValue(1.0)\n args << baseboardeff\n\n #make a string argument for baseboard heating output capacity\n baseboardcap = OpenStudio::Measure::OSArgument::makeStringArgument(\"capacity\", true)\n baseboardcap.setDisplayName(\"Heating Capacity\")\n baseboardcap.setDescription(\"The output heating capacity of the electric baseboard. If using '#{Constants.SizingAuto}', the autosizing algorithm will use ACCA Manual S to set the capacity.\")\n baseboardcap.setUnits(\"kBtu/hr\")\n baseboardcap.setDefaultValue(Constants.SizingAuto)\n args << baseboardcap\n\t\n return args\n end", "def user_input_command_line_menu\n\tcommand_line_input = gets.strip.to_i\n\tcommand_line_input_logic(command_line_input)\nend", "def cmdarg; end", "def cmdarg; end", "def cmdarg; end", "def check_inputs_g(args)\n raise TypeError, Ajaila::Messager.warning(\"Nothing to generate...\") if args == []\n raise TypeError, Ajaila::Messager.warning(\"Only miners, selectors, presenters supported\\n(ex. miner SomeMiner, selector SomeSelector,\\n presenter SomePresenter, table SomeTable)\") if KNOWN_INSTANCES.include?(args[0]) == false\n raise TypeError, Ajaila::Messager.warning(\"Your #{args[0]} needs a name!\") if args[1] == nil\n raise TypeError, Ajaila::Messager.warning(\"Wrong format of the #{args[0]} name (use only A-Z and a-z symbols)\") if args[1][/^[A-Z]+$/i] == nil\n return 0\n end", "def arguments\n parser.arguments\n end", "def valid_args(type)\n case type\n when 'search' then %i[q format addressdetails extratags namedetails viewbox bounded exclude_place_ids limit accept-language email]\n when 'reverse' then %i[format lat lon zoom addressdetails extratags namedetails accept-language email]\n else []\n end\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n id = OpenStudio::Measure::OSArgument.makeStringArgument('feature_id', false)\n id.setDisplayName('Feature unique identifier')\n id.setDefaultValue('1')\n args << id\n\n name = OpenStudio::Measure::OSArgument.makeStringArgument('feature_name', false)\n name.setDisplayName('Feature scenario specific name')\n name.setDefaultValue('name')\n args << name\n\n feature_type = OpenStudio::Measure::OSArgument.makeStringArgument('feature_type', false)\n feature_type.setDisplayName('URBANopt Feature Type')\n feature_type.setDefaultValue('Building')\n args << feature_type\n\n feature_location = OpenStudio::Measure::OSArgument.makeStringArgument('feature_location', false)\n feature_location.setDisplayName('URBANopt Feature Location')\n feature_location.setDefaultValue('0')\n args << feature_location\n\n # make an argument for the frequency\n reporting_frequency_chs = OpenStudio::StringVector.new\n reporting_frequency_chs << 'Detailed'\n reporting_frequency_chs << 'Timestep'\n reporting_frequency_chs << 'Hourly'\n reporting_frequency_chs << 'Daily'\n # reporting_frequency_chs << 'Zone Timestep'\n reporting_frequency_chs << 'BillingPeriod' # match it to utility bill object\n ## Utility report here to report the start and end for each fueltype\n reporting_frequency_chs << 'Monthly'\n reporting_frequency_chs << 'Runperiod'\n\n reporting_frequency = OpenStudio::Measure::OSArgument.makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency')\n reporting_frequency.setDescription('The frequency at which to report timeseries output data.')\n reporting_frequency.setDefaultValue('Timestep')\n args << reporting_frequency\n\n return args\n end", "def madlib_inputs\n print \"Enter a noun: \" \n noun = gets.chomp\n print \"Enter a verb: \" \n verb = gets.chomp\n print \"Enter an adjective: \" \n adjective = gets.chomp\n print \"Enter an adverb: \" \n adverb = gets.chomp\n madlib_line(noun, verb, adjective, adverb)\nend", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n #make a start date argument\n start_date = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"start_date\",true)\n start_date.setDisplayName(\"Start date\")\n args << start_date\n \n #make an end date argument\n end_date = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"end_date\",true)\n end_date.setDisplayName(\"End date\")\n args << end_date\n \n return args\n end", "def check_arguments\n convert_boolean_strings\n check_output\n check_log_level\n check_input_entry\n check_input_types\n end", "def process_arguments\n # clean unsupport symbols, e.g. JieFang;\n # or error argument due to option typo, e.g. '-list' will put 'ist' into the array in this src.\n @support_newspapers = Array.new #TODO: move to elsewhere\n @support_newspapers << :XM\n @support_newspapers << :WHB\n @support_newspapers << :YZ\n # ATTENTION: command line input is an array of string, to be consistent, internally I use only symbol when using this symbol\n @options.newspapers = @options.newspapers.collect { | item | item.to_sym } & @support_newspapers\n \n if @options.newspapers.size == 0\n @support_newspapers.each do | sym |\n @options.newspapers << sym\n end\n end\n end", "def args\n raw_args\n end", "def argv; end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n #make an argument for your name\n code_choices = OpenStudio::StringVector.new \n code_choices << \"ASHRAE 90.1-2007\" \n code_choices << \"ASHRAE 90.1-2010\" \n energy_code = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('energy_code', code_choices, true)\n energy_code.setDisplayName(\"Code baseline\")\n energy_code.setDefaultValue(\"ASHRAE 90.1-2010\")\n args << energy_code\n \n #make an argument to add new space true/false\n leed_check = OpenStudio::Ruleset::OSArgument::makeBoolArgument(\"leed_check\",true)\n leed_check.setDisplayName(\"Perform typical LEED checks?\")\n leed_check.setDefaultValue(true)\n args << leed_check\n \n return args\n end", "def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \t\"os_object_type\"\t],\n [ \"weather_file_name\", \"STRING\", true, false, \"Weather File Name\", nil, nil, nil, nil, \t nil\t\t\t\t\t],\n #Default set for server weather folder.\n [ \"weather_directory\", \"STRING\", true, false, \"Weather Directory\", \"../../weather\", nil, nil, nil,\t nil\t\t\t\t\t]\n \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end", "def inflamed _args\n \"inflamed _args;\" \n end", "def more_options\n puts Rainbow(\"Specify your additional options for your search: 'release date', 'search history', or go back\").yellow.underline\n input = gets.chomp.downcase\n \n if input == \"release date\"\n option_release_date\n \n elsif input == \"search history\"\n game_history\n\n elsif input == \"go back\"\n continue_or_exit\n \n else \n puts \"Input not recognized please try again\"\n more_options\n end\n end", "def cmd(options={})\n arguments\n end", "def arguments()\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # this measure will require arguments, but at this time, they are not known\n geometry_profile = OpenStudio::Ruleset::OSArgument::makeStringArgument('geometry_profile', true)\n geometry_profile.setDefaultValue(\"{}\")\n os_model = OpenStudio::Ruleset::OSArgument::makeStringArgument('os_model', true)\n os_model.setDefaultValue('multi-model mode')\n user_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('user_id', true)\n user_id.setDefaultValue(\"00000000-0000-0000-0000-000000000000\")\n job_id = OpenStudio::Ruleset::OSArgument::makeStringArgument('job_id', true)\n #job_id.setDefaultValue(SecureRandom.uuid.to_s)\n ashrae_climate_zone = OpenStudio::Ruleset::OSArgument::makeStringArgument('ashrae_climate_zone', false)\n ashrae_climate_zone.setDefaultValue(\"-1\")\n building_type = OpenStudio::Ruleset::OSArgument::makeStringArgument('building_type', false)\n building_type.setDefaultValue(\"BadDefaultType\")\n\n args << geometry_profile\n args << os_model\n args << user_id\n args << job_id\n args << ashrae_climate_zone\n args << building_type\n\n return args\n end", "def user_input\n\tgets\nend", "def input\n @input ||= args.dig(:input)\n end", "def parse_args\n require 'optimist'\n opts = Optimist.options do\n opt :source, \"Inventory Source UID\", :type => :string, :required => ENV[\"SOURCE_UID\"].nil?, :default => ENV[\"SOURCE_UID\"]\n opt :ingress_api, \"Hostname of the ingress-api route\", :type => :string, :default => ENV[\"INGRESS_API\"] || \"http://localhost:9292\"\n opt :config, \"Configuration file name\", :type => :string, :default => ENV[\"CONFIG\"] || \"default\"\n opt :data, \"Amount & custom values of generated items\", :type => :string, :default => ENV[\"DATA\"] || \"default\"\n end\n\n opts\nend", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # lat arg\n lat = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"lat\", true)\n lat.setDisplayName(\"Latitude\")\n lat.setDefaultValue(39.7392000000)\n args << lat\n\n # long arg\n lon = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"lon\", true)\n lon.setDisplayName(\"Longitude\")\n lon.setDefaultValue(-104.9903000000)\n args << lon\n\n return args\n end", "def add args\n db = get_db\n if args.empty?\n print \"Enter a short summary: \"\n STDOUT.flush\n text = gets.chomp\n if text.empty?\n exit ERRCODE\n end\n else\n # if you add last arg as P1..P5, I'll update priority automatically\n if args.last =~ /P[1-5]/\n $default_priority = args.pop\n end\n text = args.join \" \"\n end\n # convert actual newline to C-a. slash n's are escapes so echo -e does not muck up.\n #atitle=$( echo \"$atitle\" | tr -cd '\\40-\\176' )\n text.tr! \"\\n\", '\u0001'\n title = text\n desc = nil\n if $prompt_desc\n # choice of vim or this XXX also how to store in case of error or abandon\n # and allow user to edit, so no retyping. This could be for mult fields\n message \"Enter a detailed description (. to exit): \"\n desc = Cmdapp.get_lines\n #message \"You entered #{desc}\"\n end\n type = $default_type || \"bug\"\n severity = $default_severity || \"normal\"\n status = $default_status || \"open\"\n priority = $default_priority || \"P3\"\n if $prompt_type\n type = Cmdapp._choice(\"Select type:\", %w[bug enhancement feature task] )\n #message \"You selected #{type}\"\n end\n if $prompt_priority\n #priority = Cmdapp._choice(\"Select priority:\", %w[normal critical moderate] )\n priority = ask_priority\n #message \"You selected #{severity}\"\n end\n if $prompt_severity\n severity = Cmdapp._choice(\"Select severity:\", %w[normal critical moderate] )\n #message \"You selected #{severity}\"\n end\n if $prompt_status\n status = Cmdapp._choice(\"Select status:\", %w[open started closed stopped canceled] )\n #message \"You selected #{status}\"\n end\n assigned_to = $default_assigned_to\n if $prompt_assigned_to\n message \"Assign to:\"\n #assigned_to = $stdin.gets.chomp\n assigned_to = Cmdapp._gets \"assigned_to\", \"assigned_to\", $default_assigned_to\n #message \"You selected #{assigned_to}\"\n end\n project = component = version = nil\n # project\n if $use_project\n project = Cmdapp.user_input('project', $prompt_project, nil, $valid_project, $default_project)\n end\n if $use_component\n component = Cmdapp.user_input('component', $prompt_component, nil, $valid_component, $default_component)\n end\n if $use_version\n version = Cmdapp.user_input('version', $prompt_version, nil, $valid_version, $default_version)\n end\n\n start_date = @now\n due_date = default_due_date\n comment_count = 0\n priority ||= \"P3\" \n description = desc\n fix = nil #\"Some long text\" \n #date_created = @now\n #date_modified = @now\n body = {}\n body[\"title\"]=title\n body[\"description\"]=description\n body[\"type\"]=type\n body[\"status\"]=status\n body[\"start_date\"]=start_date.to_s\n body[\"due_date\"]=due_date.to_s\n body[\"priority\"]=priority\n body[\"severity\"]=severity\n body[\"assigned_to\"]=assigned_to\n body[\"created_by\"] = $default_user\n # only insert if its wanted by user\n body[\"project\"]=project if $use_project\n body[\"component\"]=component if $use_component\n body[\"version\"]=version if $use_version\n\n rowid = db.table_insert_hash(\"bugs\", body)\n puts \"Issue #{rowid} created\"\n logid = db.sql_logs_insert rowid, \"create\", \"#{rowid} #{type}: #{title}\"\n body[\"id\"] = rowid\n mail_issue nil, body\n \n 0\n end", "def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \"os_object_type\"\t ],\n [ \"alternativeModel\", \"STRING\", true, false, \"Alternative Model\", 'FullServiceRestaurant.osm', nil, nil, nil, \t nil\t\t\t\t\t],\n [ \"osm_directory\", \"STRING\", true, false, \"OSM Directory\", \"../../lib/btap/resources/models/smart_archetypes\", nil, nil, nil,\t nil\t\t\t\t\t] \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end", "def arguments(model)\n #list of arguments as they will appear in the interface. They are available in the run command as\n @argument_array_of_arrays = [\n [ \"variable_name\", \"type\", \"required\", \"model_dependant\", \"display_name\", \"default_value\", \"min_value\", \"max_value\", \"string_choice_array\", \"os_object_type\"\t ],\n [ \"alternativeModel\", \"STRING\", true, false, \"Alternative Model\", 'FullServiceRestaurant.osm', nil, nil, nil, \t nil\t\t\t\t\t],\n [ \"osm_directory\", \"STRING\", true, false, \"OSM Directory\", \"../../lib/btap/resources/models/smart_archetypes\", nil, nil, nil,\t nil\t\t\t\t\t] \n ]\n #set up arguments. \n args = OpenStudio::Ruleset::OSArgumentVector.new\n self.argument_setter(args)\n return args\n end", "def arguments()\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n # the name of the sql file\r\n csv_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_name\", true)\r\n csv_name.setDisplayName(\"CSV file name\")\r\n csv_name.setDescription(\"CSV file name.\")\r\n csv_name.setDefaultValue(\"mtr.csv\")\r\n args << csv_name\r\n \r\n csv_time_header = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_time_header\", true)\r\n csv_time_header.setDisplayName(\"CSV Time Header\")\r\n csv_time_header.setDescription(\"CSV Time Header Value.\")\r\n csv_time_header.setDefaultValue(\"Date/Time\")\r\n args << csv_time_header\r\n \r\n csv_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var\", true)\r\n csv_var.setDisplayName(\"CSV variable name\")\r\n csv_var.setDescription(\"CSV variable name\")\r\n csv_var.setDefaultValue(\"Whole Building:Facility Total Electric Demand Power [W](TimeStep)\")\r\n args << csv_var\r\n \r\n csv_var_dn = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var_dn\", true)\r\n csv_var_dn.setDisplayName(\"CSV variable display name\")\r\n csv_var_dn.setDescription(\"CSV variable display name\")\r\n csv_var_dn.setDefaultValue(\"\")\r\n args << csv_var_dn\r\n \r\n years = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"year\", true)\r\n years.setDisplayName(\"Year in csv data\")\r\n years.setDescription(\"Year in csv data => mm:dd:yy or mm:dd\")\r\n years.setDefaultValue(true)\r\n args << years\r\n \r\n seconds = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"seconds\", true)\r\n seconds.setDisplayName(\"Seconds in csv data\")\r\n seconds.setDescription(\"Seconds in csv data => hh:mm:ss or hh:mm\")\r\n seconds.setDefaultValue(true)\r\n args << seconds\r\n \r\n sql_key = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_key\", true)\r\n sql_key.setDisplayName(\"SQL key\")\r\n sql_key.setDescription(\"SQL key\")\r\n sql_key.setDefaultValue(\"Whole Building\")\r\n args << sql_key \r\n\r\n sql_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_var\", true)\r\n sql_var.setDisplayName(\"SQL var\")\r\n sql_var.setDescription(\"SQL var\")\r\n sql_var.setDefaultValue(\"Facility Total Electric Demand Power\")\r\n args << sql_var \r\n \r\n norm = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"norm\", true)\r\n norm.setDisplayName(\"norm of the difference of csv and sql\")\r\n norm.setDescription(\"norm of the difference of csv and sql\")\r\n norm.setDefaultValue(1)\r\n args << norm \r\n\r\n find_avail = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"find_avail\", true)\r\n find_avail.setDisplayName(\"find_avail\")\r\n find_avail.setDescription(\"find_avail\")\r\n find_avail.setDefaultValue(true)\r\n args << find_avail \r\n\r\n compute_diff = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"compute_diff\", true)\r\n compute_diff.setDisplayName(\"compute_diff\")\r\n compute_diff.setDescription(\"compute_diff\")\r\n compute_diff.setDefaultValue(true)\r\n args << compute_diff\r\n \r\n verbose_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"verbose_messages\", true)\r\n verbose_messages.setDisplayName(\"verbose_messages\")\r\n verbose_messages.setDescription(\"verbose_messages\")\r\n verbose_messages.setDefaultValue(true)\r\n args << verbose_messages \r\n\r\n return args\r\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\t\t\n\n #Make a string argument for occupants (auto or number)\n num_occ = OpenStudio::Measure::OSArgument::makeStringArgument(\"num_occ\", false)\n num_occ.setDisplayName(\"Number of Occupants\")\n num_occ.setDescription(\"Specify the number of occupants. For a multifamily building, specify one value for all units or a comma-separated set of values (in the correct order) for each unit. A value of '#{Constants.Auto}' will calculate the average number of occupants from the number of bedrooms. Used to specify the internal gains from people only.\")\n num_occ.setDefaultValue(Constants.Auto)\n args << num_occ\n\n #Make a string argument for 24 weekday schedule values\n weekday_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"weekday_sch\", true)\n weekday_sch.setDisplayName(\"Weekday schedule\")\n weekday_sch.setDescription(\"Specify the 24-hour weekday schedule.\")\n weekday_sch.setDefaultValue(\"1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 0.88310, 0.40861, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.29498, 0.55310, 0.89693, 0.89693, 0.89693, 1.00000, 1.00000, 1.00000\")\n args << weekday_sch\n \n #Make a string argument for 24 weekend schedule values\n weekend_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"weekend_sch\", true)\n weekend_sch.setDisplayName(\"Weekend schedule\")\n weekend_sch.setDescription(\"Specify the 24-hour weekend schedule.\")\n weekend_sch.setDefaultValue(\"1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 0.88310, 0.40861, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.24189, 0.29498, 0.55310, 0.89693, 0.89693, 0.89693, 1.00000, 1.00000, 1.00000\")\n args << weekend_sch\n\n #Make a string argument for 12 monthly schedule values\n monthly_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"monthly_sch\", true)\n monthly_sch.setDisplayName(\"Month schedule\")\n monthly_sch.setDescription(\"Specify the 12-month schedule.\")\n monthly_sch.setDefaultValue(\"1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0\")\n args << monthly_sch\n\n return args\n end", "def validate_arguments()\n usage unless ARGV.count > 0\nend", "def input args\n if args.state.inputlist.length > 5\n args.state.inputlist.pop\n end\n\n should_process_special_move = (args.inputs.keyboard.key_down.j) ||\n (args.inputs.keyboard.key_down.k) ||\n (args.inputs.keyboard.key_down.a) ||\n (args.inputs.keyboard.key_down.d) ||\n (args.inputs.controller_one.key_down.y) ||\n (args.inputs.controller_one.key_down.x) ||\n (args.inputs.controller_one.key_down.left) ||\n (args.inputs.controller_one.key_down.right)\n\n if (should_process_special_move)\n if (args.inputs.keyboard.key_down.j && args.inputs.keyboard.key_down.k) ||\n (args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.y)\n args.state.inputlist.unshift(\"shield\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&\n (args.state.inputlist[0] == \"forward-attack\") && ((args.state.tick_count - args.state.lastpush) <= 15)\n args.state.inputlist.unshift(\"dash-attack\")\n args.state.player.dx = 20\n elsif (args.inputs.keyboard.key_down.j && args.inputs.keyboard.a) ||\n (args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.left)\n args.state.inputlist.unshift(\"back-attack\")\n elsif ( args.inputs.controller_one.key_down.x || args.inputs.keyboard.key_down.j)\n args.state.inputlist.unshift(\"forward-attack\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&\n (args.state.player.y > 128)\n args.state.inputlist.unshift(\"dair\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y)\n args.state.inputlist.unshift(\"up-attack\")\n elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a) &&\n (args.state.inputlist[0] == \"<\") &&\n ((args.state.tick_count - args.state.lastpush) <= 10)\n args.state.inputlist.unshift(\"<<\")\n args.state.player.dx = -15\n elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a)\n args.state.inputlist.unshift(\"<\")\n args.state.timeleft = args.state.tick_count\n elsif (args.inputs.controller_one.key_down.right || args.inputs.keyboard.key_down.d)\n args.state.inputlist.unshift(\">\")\n end\n\n args.state.lastpush = args.state.tick_count\n end\n\n if args.inputs.keyboard.space || args.inputs.controller_one.r2 # if the user presses the space bar\n args.state.player.jumped_at ||= args.state.tick_count # jumped_at is set to current frame\n\n # if the time that has passed since the jump is less than the player's jump duration and\n # the player is not falling\n if args.state.player.jumped_at.elapsed_time < args.state.player_jump_power_duration && !args.state.player.falling\n args.state.player.dy = args.state.player_jump_power # change in y is set to power of player's jump\n end\n end\n\n # if the space bar is in the \"up\" state (or not being pressed down)\n if args.inputs.keyboard.key_up.space || args.inputs.controller_one.key_up.r2\n args.state.player.jumped_at = nil # jumped_at is empty\n args.state.player.falling = true # the player is falling\n end\n\n if args.inputs.left # if left key is pressed\n if args.state.player.dx < -5\n args.state.player.dx = args.state.player.dx\n else\n args.state.player.dx = -5\n end\n\n elsif args.inputs.right # if right key is pressed\n if args.state.player.dx > 5\n args.state.player.dx = args.state.player.dx\n else\n args.state.player.dx = 5\n end\n else\n args.state.player.dx *= args.state.player_speed_slowdown_rate # dx is scaled down\n end\n\n if ((args.state.player.dx).abs > 5) #&& ((args.state.tick_count - args.state.lastpush) <= 10)\n args.state.player.dx *= 0.95\n end\nend", "def arguments(model = nil)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n chs = OpenStudio::StringVector.new\n chs << 'Last OSM'\n chs << 'Last IDF'\n file_source = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('file_source', chs, true)\n file_source.setDisplayName('Model Source')\n file_source.setDefaultValue('Last OSM')\n args << file_source\n\n chs = OpenStudio::StringVector.new\n chs << 'Timestep'\n chs << 'Hourly'\n reporting_frequency = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('reporting_frequency', chs, true)\n reporting_frequency.setDisplayName('Reporting Frequency')\n reporting_frequency.setDefaultValue('Hourly')\n args << reporting_frequency\n\n variable1_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable1_name', true)\n variable1_name.setDisplayName('Variable 1 Name')\n variable1_name.setDefaultValue('Surface Outside Face Temperature')\n args << variable1_name\n\n variable2_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable2_name', true)\n variable2_name.setDisplayName('Variable 2 Name')\n variable2_name.setDefaultValue('Surface Inside Face Temperature')\n args << variable2_name\n\n variable3_name = OpenStudio::Ruleset::OSArgument.makeStringArgument('variable3_name', true)\n variable3_name.setDisplayName('Variable 3 Name')\n variable3_name.setDefaultValue('Zone Mean Radiant Temperature')\n args << variable3_name\n\n return args\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # Create a list of the names and handles of space types\n # used in the building.\n used_space_type_handles = OpenStudio::StringVector.new\n used_space_type_names = OpenStudio::StringVector.new\n model.getSpaceTypes.sort.each do |space_type|\n if space_type.spaces.size > 0 # only show space types used in the building\n used_space_type_handles << space_type.handle.to_s\n used_space_type_names << space_type.name.to_s\n end\n end\n\t\n # Make an argument for plenum space type\n ceiling_return_plenum_space_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"ceiling_return_plenum_space_type\", used_space_type_handles, used_space_type_names,false)\n ceiling_return_plenum_space_type.setDisplayName(\"This space type should be part of a ceiling return air plenum.\")\n args << ceiling_return_plenum_space_type\n\t\n # Make a bool argument to edit/not edit each space type\n\t\tmodel.getSpaceTypes.sort.each do |space_type|\n\t\t\tif space_type.spaces.size > 0 # only show space types used in the building\n\t\t\t\tspace_type_to_edit = OpenStudio::Ruleset::OSArgument::makeBoolArgument(space_type.name.get.to_s,false)\n\t\t\t\t# Make a bool argument for this space type\n\t\t\t\tspace_type_to_edit.setDisplayName(\"Add #{space_type.name.get} space type to GSHP system?\")\n\t\t\t\tspace_type_to_edit.setDefaultValue(false)\t\t\n\t\t\t\targs << space_type_to_edit\n\t\t\tend\n\t\tend\n\t \n\t\t# Heating COP of GSHP\n\t\tgshp_htg_cop = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"gshp_htg_cop\",false)\n\t\tgshp_htg_cop.setDisplayName(\"GSHP DX Heating Coil Heating COP\")\n\t\tgshp_htg_cop.setDefaultValue(4.0)\n\t\targs << gshp_htg_cop\n\t\t\n\t\t# Cooling EER of GSHP\n\t\tgshp_clg_eer = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"gshp_clg_eer\",false)\n\t\tgshp_clg_eer.setDisplayName(\"GSHP DX Cooling Coil Cooling EER\")\n\t\tgshp_clg_eer.setDefaultValue(14)\n\t\targs << gshp_clg_eer\n\t\t\n\t\t# GSHP Fan Type PSC or ECM\n\t\tfan_choices = OpenStudio::StringVector.new\n\t\tfan_choices << \"PSC\"\n\t\tfan_choices << \"ECM\"\n\t\tgshp_fan_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"gshp_fan_type\",fan_choices,true) # note ECM fan type may correspond to different set of heat pump performance curves\n\t\tgshp_fan_type.setDisplayName(\"GSHP Fan Type: PSC or ECM?\")\n\t\tgshp_fan_type.setDefaultValue(\"PSC\")\n args << gshp_fan_type\n\t\t\n\t\t# Condenser Loop Cooling Temperature\n\t\t# condLoopCoolingTemp = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"condLoopCoolingTemp\",false)\n\t\t# condLoopCoolingTemp.setDisplayName(\"Condenser Loop Cooling Temperature (F)\")\n\t\t# condLoopCoolingTemp.setDefaultValue(90)\n\t\t# args << condLoopCoolingTemp\n\t\t\n\t\t# Condenser Loop Heating Temperature\n\t\t# condLoopHeatingTemp = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"condLoopHeatingTemp\",false)\n\t\t# condLoopHeatingTemp.setDisplayName(\"Condenser Loop Heating Temperature (F)\")\n\t\t# condLoopHeatingTemp.setDefaultValue(60)\t\n\t\t# args << condLoopHeatingTemp\n\t\t\n\t\t# Vertical Bore HX\n\t\tbuilding_area = model.getBuilding.floorArea \n\t\tbuilding_cool_ton = building_area*10.7639/500\t\t# 500sf/ton estimated\n\t\tbore_hole_no = OpenStudio::Ruleset::OSArgument::makeIntegerArgument(\"bore_hole_no\",false)\n\t\tbore_hole_no.setDisplayName(\"Number of Bore Holes\")\n\t\tbore_hole_no.setDefaultValue(building_cool_ton.to_i) \n\t\targs << bore_hole_no\n\n\t\t\n\t\tbore_hole_length = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"bore_hole_length\",false)\n\t\tbore_hole_length.setDisplayName(\"Bore Hole Length (ft)\")\n\t\tbore_hole_length.setDefaultValue(200)\n\t\targs << bore_hole_length\n\n\t\tbore_hole_radius = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"bore_hole_radius\",false)\n\t\tbore_hole_radius.setDisplayName(\"Bore Hole Radius (inch)\")\n\t\tbore_hole_radius.setDefaultValue(6.0)\n\t\targs << bore_hole_radius\n\t\t\n\t\tground_k_value = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"ground_k_value\",false)\n\t\tground_k_value.setDisplayName(\"Ground Conductivity (Btu/hr.F.R\")\n\t\tground_k_value.setDefaultValue(0.75)\n\t\targs << ground_k_value\n\t\t\n\t\tgrout_k_value = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"grout_k_value\",false)\n\t\tgrout_k_value.setDisplayName(\"Grout Conductivity (Btu/hr.F.R\")\n\t\tgrout_k_value.setDefaultValue(0.75)\n\t\targs << grout_k_value\n\t\t\n\t\tchs = OpenStudio::StringVector.new\n\t\tchs << \"Yes\"\n\t\tchs << \"No\"\n\t\tsupplemental_boiler = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"supplemental_boiler\",chs, true)\n\t\tsupplemental_boiler.setDisplayName(\"Supplemental Heating Boiler?\")\n\t\tsupplemental_boiler.setDefaultValue(\"No\")\n\t\targs << supplemental_boiler\n\t\t\n\t\t# Boiler Capacity\n\t\tboiler_cap = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"boiler_cap\",false)\n\t\tboiler_cap.setDisplayName(\"boiler normal capacity (MBtuh)\")\n\t\tboiler_cap.setDefaultValue(500.0)\n\t\targs << boiler_cap\n\t\t\t\t\n\t\t# Boiler Efficiency\n\t\tboiler_eff = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"boiler_eff\",false)\n\t\tboiler_eff.setDisplayName(\"Boiler Thermal Efficiency\")\n\t\tboiler_eff.setDefaultValue(0.9)\n\t\targs << boiler_eff\n\t\t\n\t\t# Boiler fuel Type\n\t\tfuel_choices = OpenStudio::StringVector.new\n\t\tfuel_choices << \"NaturalGas\"\n\t\tfuel_choices << \"PropaneGas\"\n\t\tfuel_choices << \"FuelOil#1\"\n\t\tfuel_choices << \"FuelOil#2\"\n\t\tfuel_choices << \"Electricity\"\n\t\tboiler_fuel_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"boiler_fuel_type\",fuel_choices,false) \n\t\tboiler_fuel_type.setDisplayName(\"Boiler Fuel Type\")\n\t\tboiler_fuel_type.setDefaultValue(\"NaturalGas\")\n\t\targs << boiler_fuel_type\n\t\t\n\t\t# boiler Hot water supply temperature\n\t\tboiler_hw_st = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"boiler_hw_st\",false)\n\t\tboiler_hw_st.setDisplayName(\"Boiler Design Heating Water Outlet Temperature (F)\")\n\t\tboiler_hw_st.setDefaultValue(120)\t\n\t\targs << boiler_hw_st\n\t\t\n\t\t# DOAS Fan Type\n\t\tdoas_fan_choices = OpenStudio::StringVector.new\n\t\tdoas_fan_choices << \"Constant\"\n\t\tdoas_fan_choices << \"Variable\"\n\t\tdoas_fan_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"doas_fan_type\",doas_fan_choices,true)\n\t\tdoas_fan_type.setDisplayName(\"DOAS Fan Flow Control - Variable means DCV controls\")\n\t\tdoas_fan_type.setDefaultValue(\"Variable\")\n\t\targs << doas_fan_type\n\t\t\n\t\t# DOAS Energy Recovery\n\t\terv_choices = OpenStudio::StringVector.new\n\t\terv_choices << \"plate w/o economizer lockout\"\n\t\terv_choices << \"plate w/ economizer lockout\"\n\t\terv_choices << \"rotary wheel w/o economizer lockout\"\n\t\terv_choices << \"rotary wheel w/ economizer lockout\"\n\t\terv_choices << \"none\"\n\t\tdoas_erv = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"doas_erv\",erv_choices,true)\n\t\tdoas_erv.setDisplayName(\"DOAS Energy Recovery?\")\n\t\tdoas_erv.setDefaultValue(\"none\")\n\t\targs << doas_erv\n\t\t\n\t\t# DOAS Evaporative Cooling\n\t\tevap_choices = OpenStudio::StringVector.new\n\t\tevap_choices << \"Direct Evaporative Cooler\"\n\t\tevap_choices << \"none\"\n\t\tdoas_evap = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"doas_evap\",evap_choices,true)\n\t\tdoas_evap.setDisplayName(\"DOAS Direct Evaporative Cooling?\")\n\t\tdoas_evap.setDefaultValue(\"none\")\n\t\targs << doas_evap\n\t\t\n\t\t# DOAS DX Cooling\n\t\tdoas_dx_eer = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"doas_dx_eer\",false)\n\t\tdoas_dx_eer.setDisplayName(\"DOAS DX Cooling EER\")\n\t\tdoas_dx_eer.setDefaultValue(10.0)\n\t\targs << doas_dx_eer\n\t\n # make an argument for material and installation cost\n # todo - I would like to split the costing out to the air loops weighted by area of building served vs. just sticking it on the building\n cost_total_hvac_system = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"cost_total_hvac_system\",true)\n cost_total_hvac_system.setDisplayName(\"Total Cost for HVAC System ($).\")\n cost_total_hvac_system.setDefaultValue(0.0)\n args << cost_total_hvac_system\n \n #make an argument to remove existing costs\n remake_schedules = OpenStudio::Ruleset::OSArgument::makeBoolArgument(\"remake_schedules\",true)\n remake_schedules.setDisplayName(\"Apply recommended availability and ventilation schedules for air handlers?\")\n remake_schedules.setDefaultValue(true)\n args << remake_schedules\n\n return args\n end", "def arguments()\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n # the name of the sql file\r\n csv_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_name\", true)\r\n csv_name.setDisplayName(\"CSV file name\")\r\n csv_name.setDescription(\"CSV file name.\")\r\n csv_name.setDefaultValue(\"mtr.csv\")\r\n args << csv_name\r\n \r\n csv_time_header = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_time_header\", true)\r\n csv_time_header.setDisplayName(\"CSV Time Header\")\r\n csv_time_header.setDescription(\"CSV Time Header Value.\")\r\n csv_time_header.setDefaultValue(\"Date/Time\")\r\n args << csv_time_header\r\n \r\n csv_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var\", true)\r\n csv_var.setDisplayName(\"CSV variable name\")\r\n csv_var.setDescription(\"CSV variable name\")\r\n csv_var.setDefaultValue(\"Whole Building:Facility Total Electric Demand Power [W](TimeStep)\")\r\n args << csv_var\r\n \r\n csv_var_dn = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"csv_var_dn\", true)\r\n csv_var_dn.setDisplayName(\"CSV variable display name\")\r\n csv_var_dn.setDescription(\"CSV variable display name\")\r\n csv_var_dn.setDefaultValue(\"\")\r\n args << csv_var_dn\r\n \r\n years = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"year\", true)\r\n years.setDisplayName(\"Year in csv data\")\r\n years.setDescription(\"Year in csv data => mm:dd:yy or mm:dd\")\r\n years.setDefaultValue(true)\r\n args << years\r\n \r\n seconds = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"seconds\", true)\r\n seconds.setDisplayName(\"Seconds in csv data\")\r\n seconds.setDescription(\"Seconds in csv data => hh:mm:ss or hh:mm\")\r\n seconds.setDefaultValue(true)\r\n args << seconds\r\n \r\n sql_key = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_key\", true)\r\n sql_key.setDisplayName(\"SQL key\")\r\n sql_key.setDescription(\"SQL key\")\r\n sql_key.setDefaultValue(\"\")\r\n args << sql_key \r\n\r\n sql_var = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"sql_var\", true)\r\n sql_var.setDisplayName(\"SQL var\")\r\n sql_var.setDescription(\"SQL var\")\r\n sql_var.setDefaultValue(\"Facility Total Electric Demand Power\")\r\n args << sql_var \r\n \r\n stp = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"stp\", true)\r\n stp.setDisplayName(\"Timeseries Timestep\")\r\n stp.setDescription(\"Timeseries Timestep\")\r\n stp.setDefaultValue(\"Zone Timestep\")\r\n args << stp\r\n \r\n env = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"env\", true)\r\n env.setDisplayName(\"availableEnvPeriods\")\r\n env.setDescription(\"availableEnvPeriods\")\r\n env.setDefaultValue(\"RUN PERIOD 1\")\r\n args << env\r\n \r\n norm = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"norm\", true)\r\n norm.setDisplayName(\"norm of the difference of csv and sql\")\r\n norm.setDescription(\"norm of the difference of csv and sql\")\r\n norm.setDefaultValue(1)\r\n args << norm \r\n\r\n scale = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"scale\", true)\r\n scale.setDisplayName(\"scale factor to apply to the difference\")\r\n scale.setDescription(\"scale factor to apply to the difference\")\r\n scale.setDefaultValue(1)\r\n args << scale \r\n\r\n find_avail = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"find_avail\", true)\r\n find_avail.setDisplayName(\"find_avail\")\r\n find_avail.setDescription(\"find_avail\")\r\n find_avail.setDefaultValue(true)\r\n args << find_avail \r\n\r\n compute_diff = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"compute_diff\", true)\r\n compute_diff.setDisplayName(\"compute_diff\")\r\n compute_diff.setDescription(\"compute_diff\")\r\n compute_diff.setDefaultValue(true)\r\n args << compute_diff\r\n \r\n verbose_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"verbose_messages\", true)\r\n verbose_messages.setDisplayName(\"verbose_messages\")\r\n verbose_messages.setDescription(\"verbose_messages\")\r\n verbose_messages.setDefaultValue(true)\r\n args << verbose_messages \r\n \r\n algorithm_download = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"algorithm_download\", true)\r\n algorithm_download.setDisplayName(\"algorithm_download\")\r\n algorithm_download.setDescription(\"algorithm_download\")\r\n algorithm_download.setDefaultValue(false)\r\n args << algorithm_download \r\n \r\n plot_flag = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"plot_flag\", true)\r\n plot_flag.setDisplayName(\"plot_flag timeseries data\")\r\n plot_flag.setDescription(\"plot_flag timeseries data\")\r\n plot_flag.setDefaultValue(true)\r\n args << plot_flag\r\n \r\n plot_name = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"plot_name\", true)\r\n plot_name.setDisplayName(\"Plot name\")\r\n plot_name.setDescription(\"Plot name\")\r\n plot_name.setDefaultValue(\"\")\r\n args << plot_name\r\n \r\n warning_messages = OpenStudio::Ruleset::OSArgument.makeBoolArgument(\"warning_messages\", true)\r\n warning_messages.setDisplayName(\"warning_messages\")\r\n warning_messages.setDescription(\"warning_messages\")\r\n warning_messages.setDefaultValue(false)\r\n args << warning_messages\r\n\r\n return args\r\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # the name of the space to add to the model\n setpoint = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"setpoint_temperature\", true)\n setpoint.setUnits(\"Degrees Celsius\")\n setpoint.setDisplayName(\"Ambient Loop Temperature\")\n setpoint.setDefaultValue(20)\n setpoint.setDescription(\"Temperature setpoint for the ambient loop\")\n args << setpoint\n\n delta = OpenStudio::Ruleset::OSArgument.makeDoubleArgument(\"design_delta\", true)\n delta.setUnits(\"Delta Temperature\")\n delta.setDefaultValue(5.55) # 10 Deg F default delta\n delta.setDisplayName(\"Delta Design Loop Temperature\")\n delta.setDescription(\"Delta design temperature for the ambient loop\")\n args << delta\n\n return args\n end", "def arguments\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n return args\n end", "def print_two_again(arg1, arg2) # Non-variable list of inputs it will accept\n puts \"arg1: #{arg1}, arg2: #{arg2}\"\nend", "def commander _args\n \"commander _args;\" \n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # make a string argument for furnace fuel type\n fuel_display_names = OpenStudio::StringVector.new\n fuel_display_names << Constants.FuelTypeGas\n fuel_display_names << Constants.FuelTypeOil\n fuel_display_names << Constants.FuelTypePropane\n fuel_display_names << Constants.FuelTypeElectric\n fuel_type = OpenStudio::Measure::OSArgument::makeChoiceArgument('fuel_type', fuel_display_names, true)\n fuel_type.setDisplayName('Fuel Type')\n fuel_type.setDescription('Type of fuel used for heating.')\n fuel_type.setDefaultValue(Constants.FuelTypeGas)\n args << fuel_type\n\n # make an argument for entering furnace installed afue\n afue = OpenStudio::Measure::OSArgument::makeDoubleArgument('afue', true)\n afue.setDisplayName('Installed AFUE')\n afue.setUnits('Btu/Btu')\n afue.setDescription('The installed Annual Fuel Utilization Efficiency (AFUE) of the furnace, which can be used to account for performance derating or degradation relative to the rated value.')\n afue.setDefaultValue(0.78)\n args << afue\n\n # make an argument for entering furnace installed supply fan power\n fan_power_installed = OpenStudio::Measure::OSArgument::makeDoubleArgument('fan_power_installed', true)\n fan_power_installed.setDisplayName('Installed Supply Fan Power')\n fan_power_installed.setUnits('W/cfm')\n fan_power_installed.setDescription('Fan power (in W) per delivered airflow rate (in cfm) of the indoor fan for the maximum fan speed under actual operating conditions.')\n fan_power_installed.setDefaultValue(0.5)\n args << fan_power_installed\n\n # make a string argument for furnace heating output capacity\n capacity = OpenStudio::Measure::OSArgument::makeStringArgument('capacity', true)\n capacity.setDisplayName('Heating Capacity')\n capacity.setDescription(\"The output heating capacity of the furnace. If using '#{Constants.SizingAuto}', the autosizing algorithm will use ACCA Manual S to set the capacity.\")\n capacity.setUnits('kBtu/hr')\n capacity.setDefaultValue(Constants.SizingAuto)\n args << capacity\n\n # make a string argument for distribution system efficiency\n dse = OpenStudio::Measure::OSArgument::makeStringArgument('dse', true)\n dse.setDisplayName('Distribution System Efficiency')\n dse.setDescription('Defines the energy losses associated with the delivery of energy from the equipment to the source of the load.')\n dse.setDefaultValue('NA')\n args << dse\n\n # make a bool argument for open hvac flue\n has_hvac_flue = OpenStudio::Measure::OSArgument::makeBoolArgument('has_hvac_flue', true)\n has_hvac_flue.setDisplayName('Air Leakage: Has Open HVAC Flue')\n has_hvac_flue.setDescription('Specifies whether the building has an open flue associated with the HVAC system.')\n has_hvac_flue.setDefaultValue(true)\n args << has_hvac_flue\n\n return args\n end", "def args\n @args\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n\n return args\n end", "def default_args(a,b,c=1)\n puts \"\\nValues of variables: \",a,b,c\nend", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n \n \t#Make a string argument for 24 weekday cooling set point values\n clg_wkdy = OpenStudio::Measure::OSArgument::makeStringArgument(\"clg_wkdy\", false)\n clg_wkdy.setDisplayName(\"Weekday Setpoint\")\n clg_wkdy.setDescription(\"Specify a single cooling setpoint or a 24-hour comma-separated cooling schedule for the weekdays.\")\n clg_wkdy.setUnits(\"degrees F\")\n clg_wkdy.setDefaultValue(\"76\")\n args << clg_wkdy \n \n \t#Make a string argument for 24 weekend cooling set point values\n clg_wked = OpenStudio::Measure::OSArgument::makeStringArgument(\"clg_wked\", false)\n clg_wked.setDisplayName(\"Weekend Setpoint\")\n clg_wked.setDescription(\"Specify a single cooling setpoint or a 24-hour comma-separated cooling schedule for the weekend.\")\n clg_wked.setUnits(\"degrees F\")\n clg_wked.setDefaultValue(\"76\")\n args << clg_wked\t\n\t\n return args\n end", "def arguments\n args = OpenStudio::Measure::OSArgumentVector.new\n # this measure does not require any user arguments, return an empty list\n return args\n end" ]
[ "0.73753476", "0.73753476", "0.73753476", "0.70890766", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.7008301", "0.68296087", "0.6826596", "0.67602986", "0.67480284", "0.6589929", "0.6581451", "0.6579882", "0.65468127", "0.6503042", "0.647451", "0.64706385", "0.64699155", "0.6469245", "0.64641875", "0.64103556", "0.6389132", "0.637863", "0.6374086", "0.6373223", "0.63639134", "0.6358853", "0.6347805", "0.63475585", "0.63470906", "0.6329135", "0.63280094", "0.62932867", "0.6289945", "0.6271416", "0.6257277", "0.6257238", "0.6239814", "0.6235555", "0.62354916", "0.6221531", "0.6221531", "0.6221531", "0.62026656", "0.61958784", "0.61795026", "0.61696565", "0.6168981", "0.6167551", "0.6165484", "0.6161183", "0.6146112", "0.6128867", "0.611614", "0.6099537", "0.609091", "0.608763", "0.6082464", "0.60754794", "0.6075173", "0.60703015", "0.6069249", "0.6053929", "0.60461015", "0.6037139", "0.6037139", "0.603555", "0.6028014", "0.60276234", "0.6026254", "0.6021278", "0.6006005", "0.60050625", "0.60002536", "0.5998068", "0.5990844", "0.5986098", "0.59826887", "0.59739846", "0.59692407", "0.59684443", "0.5966365", "0.59595567" ]
0.0
-1
end the arguments method define what happens when the measure is run
def run(model, runner, user_arguments) super(model, runner, user_arguments) #use the built-in error checking if not runner.validateUserArguments(arguments(model), user_arguments) return false end epw_file_path = File.join(File.dirname(__FILE__), "resources/srrl_2013_amy.epw") epw_file = OpenStudio::EpwFile.load(epw_file_path).get OpenStudio::Model::WeatherFile.setWeatherFile(model, epw_file) return true end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def measure=(_arg0); end", "def measure(*args, &b)\n end", "def measure; end", "def communicate_measure_result(_ = nil, _ = nil); end", "def communicate_measure_result(_ = nil, _ = nil); end", "def arguments; end", "def arguments; end", "def arguments; end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n\n percent_runtime_reduction = runner.getDoubleArgumentValue(\"percent_runtime_reduction\",user_arguments)\n\n \n \n # Check arguments for reasonableness\n if percent_runtime_reduction >= 100\n runner.registerError(\"Percent runtime reduction must be less than 100.\")\n return false\n end\n\n # Find all the original schedules (before occ sensors installed)\n original_lts_schedules = []\n model.getLightss.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end \n\n # Make copies of all the original lights schedules, reduced to include occ sensor impact\n original_schs_new_schs = {}\n original_lts_schedules.uniq.each do |orig_sch|\n # Copy the original schedule\n new_sch = orig_sch.clone.to_ScheduleRuleset.get\n new_sch.setName(\"#{new_sch.name.get} with occ sensor\")\n # Reduce each value in each profile (except the design days) by the specified amount\n runner.registerInfo(\"Reducing values in '#{orig_sch.name}' schedule by #{percent_runtime_reduction}% to represent occ sensor installation.\")\n day_profiles = []\n day_profiles << new_sch.defaultDaySchedule\n new_sch.scheduleRules.each do |rule|\n day_profiles << rule.daySchedule\n end\n multiplier = (100 - percent_runtime_reduction)/100\n day_profiles.each do |day_profile|\n #runner.registerInfo(\"#{day_profile.name}\")\n times_vals = day_profile.times.zip(day_profile.values)\n #runner.registerInfo(\"original time/values = #{times_vals}\")\n times_vals.each do |time,val|\n day_profile.addValue(time, val * multiplier)\n end\n #runner.registerInfo(\"new time/values = #{day_profile.times.zip(day_profile.values)}\")\n end \n #log the relationship between the old sch and the new, reduced sch\n original_schs_new_schs[orig_sch] = new_sch\n end\n \n # Replace the old schedules with the new, reduced schedules\n spaces_sensors_added_to = []\n model.getLightss.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end\n \n # Report if the measure is not applicable\n num_sensors_added = spaces_sensors_added_to.uniq.size\n if spaces_sensors_added_to.size == 0\n runner.registerAsNotApplicable(\"This measure is not applicable because there were no lights in the building.\")\n return true\n end \n \n # Report final condition\n runner.registerFinalCondition(\"Added occupancy sensors to #{num_sensors_added} spaces in the building.\")\n\n return true\n\n end", "def run(workspace, runner, user_arguments)\n super(workspace, runner, user_arguments)\n\n # use the built-in error checking \n if !runner.validateUserArguments(arguments(workspace), user_arguments)\n return false\n end\n \n # Report that this is an anti-measure\n runner.registerValue('anti_measure',true) \n \n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end\n \n\t# Initialize counter variables\n\tno_economizer = 0\n\tfixed_dry_bulb = 0\n\tdifferential_dry_bulb = 0\t\n\tfixed_enthalpy = 0\n\tdifferential_enthalpy = 0\n\tfixed_dew_point_and_dry_bulb = 0\n\telectronic_enthalpy = 0\n\tdifferential_dry_bulb_and_enthalpy = 0\n\t\n\t# Retrieve all Controller:Outdoor air objects in the idf \t\n\toa_controllers = workspace.getObjectsByType(\"Controller:OutdoorAir\".to_IddObjectType)\n\t\n\t# Get the names of each Controller:Outdoor Air object\n\toa_controllers.each do |oa_controller|\n\n\t\toa_controller_name = oa_controller.getString(0).to_s #(0) is field Name\n\t\toa_controller_economizer_control_type = oa_controller.getString(7).to_s #(7) is field Economizer Control Type\n\t\n\t\t# test for presence No economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"NoEconomizer\" # or empty\n\t\t\trunner.registerInfo(\"The Controller:Outdoor air object named #{oa_controller_name} has a disabled airside economizer. Economizer sensor faults will not be added.\")\n\t\t\tno_economizer = no_economizer + 1\n\t\tend\n\t\t\n\t\t# test for presence of differential dry bulb economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"DifferentialDryBulb\"\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir \n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\tdifferential_dry_bulb = differential_dry_bulb + 1\n\t\t\t# info message\n\t\t\trunner.registerInfo(\"To model dry bulb sensor drift, a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg F has been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\t\n\n\t\tend # OA Controller Type DifferentialDryBulb\n\n\t\t# test for presence of fixed dry bulb economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"FixedDryBulb\"\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\trunner.registerInfo(\"To model dry bulb sensor drift, a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg F has been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tfixed_dry_bulb = fixed_dry_bulb + 1\n\t\t\t\n\t\tend # OA Controller Type = FixedDryBulb \t\t\n\t\t\n\t\t# test for presence of fixed enthalpy economizer controller setting \t\t\t\t\n\t\tif oa_controller_economizer_control_type == \"FixedEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\twworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model enthalpy sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tfixed_enthalpy = fixed_enthalpy + 1\n\t\tend # OA Controller Type = FixedEnthalpy \n\t\t\n\t\t# test for presence of differential enthalpy economizer controller setting \t\t\n\t\tif oa_controller_economizer_control_type == \"DifferentialEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model enthalpy sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tdifferential_enthalpy = differential_enthalpy + 1\n\t\t\t\n\t\tend # OA Controller Type =\"Differential Enthalpy\"\t\t\n\t\t\n\t\n\t\t# test for presence of electronic enthalpy economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"ElectronicEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model enthalpy sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\telectronic_enthalpy = electronic_enthalpy + 1\n\n\t\tend # OA Controller Type = \"ElectronicEnthalpy\" \t\t\n\t\t\n\t\t# test for presence of fixed dew point and dry bulb economizer controller setting \n\t\tif oa_controller_economizer_control_type == \"FixedDewPointAndDryBulb\" \n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model both enthalpy and dry bulb sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb and a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tfixed_dew_point_and_dry_bulb = fixed_dew_point_and_dry_bulb + 1\n\n\t\tend # OA Controller Type = \"FixedDewPointAndDryBulb\" \n\t\n\t\t# test for presence of differential dry bulb and enthalpy economizer controller setting \t\t\n\t\tif oa_controller_economizer_control_type == \"DifferentialDryBulbAndEnthalpy\"\n\t\t\t# Initialze array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t5; \t\t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\n\t\t\t# Create IDF object text for FaultModel:EnthalpySensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:EnthalpySensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Enthalpy Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-5; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\n\t\t\t# Initialize array to hold new IDF objects\n\t\t\tstring_object = []\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:OutdoorAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:OutdoorAir,\n\t\t\t\t#{oa_controller_name}_Outdoor Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\t\t\t\t\t\t\n\t\t\t# Create IDF object text for FaultModel:TemperatureSensorOffset:ReturnAir\n\t\t\tstring_object = \"\n\t\t\t\tFaultModel:TemperatureSensorOffset:ReturnAir,\n\t\t\t\t#{oa_controller_name}_Return Air Temp Sensor Bias, !- Name\n\t\t\t\tAlways On Discrete, \t\t\t\t\t\t\t!- Availability Schedule Name\n\t\t\t\t, \t\t\t\t\t\t\t\t\t\t\t\t!- Severity Schedule Name\n\t\t\t\tController:OutdoorAir, \t\t\t\t\t\t\t!- Controller Object Type\n\t\t\t\t#{oa_controller_name}, \t\t\t\t\t\t\t!- Controller Object Name\n\t\t\t\t-1.11; \t\t\t\t\t\t\t\t\t\t\t!- Temperature Sensor Offset \n\t\t\t\t\"\n\t\t\t# Add string object to workspace to create idf object\n\t\t\tidfObject = OpenStudio::IdfObject::load(string_object)\n\t\t\tobject = idfObject.get\n\t\t\tworkspace.addObject(object)\n\n\t\t\trunner.registerInfo(\"To model both enthalpy and dry bulb sensor drift, a FaultModel:EnthalpySensorOffset:ReturnAir object with an offset of -2 Btu/lb and a FaultModel:EnthalpySensorOffset:OutdoorAir object with an offset of +2 Btu/lb and a FaultModel:TemperatureSensorOffset:ReturnAir object with an offset of -2 deg F and a FaultModel:TemperatureSensorOffset:OutdoorAir object with an offset of +2 deg have been added to the #{oa_controller_economizer_control_type} controlled airside economizer associated with the Controller:Outdoor air object named #{oa_controller_name}. The fault availability is scheduled using the 'Always On Discrete' schedule.\")\n\t\t\tdifferential_dry_bulb_and_enthalpy = differential_dry_bulb_and_enthalpy + 1\n\t\tend # OA Controller Type \"DifferentialDryBulbAndEnthalpy\"\n\t\t\n\t\t\t\t\n\tend # end loop through oa controller objects\n\n\t# reporting when N/A condition is appropriate\n\tif fixed_dry_bulb +\tdifferential_dry_bulb + fixed_enthalpy + differential_enthalpy + fixed_dew_point_and_dry_bulb +\telectronic_enthalpy + differential_dry_bulb_and_enthalpy == 0\n\t\trunner.registerAsNotApplicable(\"Measure not applicable because the model contains no OutdoorAir:Controller objects with operable economizers.\")\n\tend \n\t\n\ttotal = fixed_dry_bulb + differential_dry_bulb + fixed_enthalpy + differential_enthalpy + fixed_dew_point_and_dry_bulb + electronic_enthalpy + differential_dry_bulb_and_enthalpy\n\t\n\t# reporting initial condition of model\n\trunner.registerInitialCondition(\"The measure started with #{total} Outdoor Air Controllers configured for operational airside economizers. #{no_economizer} Outdoor Air Controller had the Economizer Contrrol Type set to 'NoEconomizer'.\")\n\t# reporting final condition of model\n\trunner.registerFinalCondition(\"The measure finished by adding outdoor and return air temperature and enthalpy sensor faults to #{total} economizer configurations.\")\n \n return true\n \n end", "def measure\n\t\t1\n\tend", "def run(runner, user_arguments)\n super(runner, user_arguments)\n\n # use the built-in error checking\n unless runner.validateUserArguments(arguments, user_arguments)\n return false\n end\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments, user_arguments)\n return false\n end\n\n feature_id = runner.getStringArgumentValue('feature_id', user_arguments)\n feature_name = runner.getStringArgumentValue('feature_name', user_arguments)\n feature_type = runner.getStringArgumentValue('feature_type', user_arguments)\n feature_location = runner.getStringArgumentValue('feature_location', user_arguments)\n\n # Assign the user inputs to variables\n reporting_frequency = runner.getStringArgumentValue('reporting_frequency', user_arguments)\n\n # BilingPeriod reporting frequency not implemented yet\n if reporting_frequency == 'BillingPeriod'\n @@logger.error('BillingPeriod frequency is not implemented yet')\n end\n\n # cache runner for this instance of the measure\n @runner = runner\n\n # get the WorkflowJSON object\n workflow = runner.workflow\n\n # get the last model and sql file\n model = runner.lastOpenStudioModel\n if model.empty?\n runner.registerError('Cannot find last model.')\n return false\n end\n model = model.get\n\n sql_file = runner.lastEnergyPlusSqlFile\n if sql_file.empty?\n runner.registerError('Cannot find last sql file.')\n return false\n end\n sql_file = sql_file.get\n model.setSqlFile(sql_file)\n\n # get building from model\n building = model.getBuilding\n\n # get surfaces from model\n surfaces = model.getSurfaces\n\n # get epw_file\n epw_file = runner.lastEpwFile\n if epw_file.empty?\n runner.registerError('Cannot find last epw file.')\n return false\n end\n epw_file = epw_file.get\n\n # create output feature_report report object\n feature_report = URBANopt::Reporting::DefaultReports::FeatureReport.new\n feature_report.id = feature_id\n feature_report.name = feature_name\n feature_report.feature_type = feature_type\n feature_report.directory_name = workflow.absoluteRunDir\n\n timesteps_per_hour = model.getTimestep.numberOfTimestepsPerHour\n feature_report.timesteps_per_hour = timesteps_per_hour\n\n feature_report.simulation_status = 'Complete'\n\n feature_report.reporting_periods << URBANopt::Reporting::DefaultReports::ReportingPeriod.new\n\n ###########################################################################\n ##\n # Get Location information and store in the feature_report\n ##\n\n if feature_location.include? '['\n # get longitude from feature_location\n longitude = (feature_location.split(',')[0].delete! '[]').to_f\n # get latitude from feature_location\n latitude = (feature_location.split(',')[1].delete! '[]').to_f\n # latitude\n feature_report.location.latitude_deg = latitude\n # longitude\n feature_report.location.longitude_deg = longitude\n end\n\n # surface_elevation\n elev = sql_query(runner, sql_file, 'InputVerificationandResultsSummary', \"TableName='General' AND RowName='Elevation' AND ColumnName='Value'\")\n feature_report.location.surface_elevation_ft = elev\n\n ##########################################################################\n ##\n\n # Get program information and store in the feature_report\n ##\n\n # floor_area\n floor_area = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='Building Area' AND RowName='Total Building Area' AND ColumnName='Area'\")\n feature_report.program.floor_area_sqft = convert_units(floor_area, 'm^2', 'ft^2')\n\n # conditioned_area\n conditioned_area = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='Building Area' AND RowName='Net Conditioned Building Area' AND ColumnName='Area'\")\n feature_report.program.conditioned_area_sqft = convert_units(conditioned_area, 'm^2', 'ft^2')\n\n # unconditioned_area\n unconditioned_area = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='Building Area' AND RowName='Unconditioned Building Area' AND ColumnName='Area'\")\n feature_report.program.unconditioned_area_sqft = convert_units(unconditioned_area, 'm^2', 'ft^2')\n if building.standardsBuildingType.is_initialized\n floor_area -= unconditioned_area if ['Residential'].include?(building.standardsBuildingType.get) # conditioned floor area only\n end\n\n # maximum_number_of_stories\n number_of_stories = building.standardsNumberOfStories.get if building.standardsNumberOfStories.is_initialized\n number_of_stories ||= 1\n feature_report.program.maximum_number_of_stories = number_of_stories\n\n # maximum_number_of_stories_above_ground\n number_of_stories_above_ground = building.standardsNumberOfAboveGroundStories.get if building.standardsNumberOfAboveGroundStories.is_initialized\n number_of_stories_above_ground ||= 1\n feature_report.program.maximum_number_of_stories_above_ground = number_of_stories_above_ground\n\n # maximum_roof_height\n floor_to_floor_height = building.nominalFloortoFloorHeight.get if building.nominalFloortoFloorHeight.is_initialized\n floor_to_floor_height ||= 8\n feature_report.program.maximum_roof_height_ft = feature_report.program.maximum_number_of_stories_above_ground * floor_to_floor_height\n\n # footprint_area\n if building.standardsBuildingType.is_initialized\n if not ['Residential'].include?(building.standardsBuildingType.get)\n feature_report.program.footprint_area_sqft = feature_report.program.floor_area_sqft / number_of_stories\n else\n feature_report.program.footprint_area_sqft = convert_units(floor_area, 'm^2', 'ft^2') / building.additionalProperties.getFeatureAsInteger('NumberOfConditionedStories').get\n end\n end\n\n # number_of_residential_units\n number_of_living_units = building.standardsNumberOfLivingUnits.get if building.standardsNumberOfLivingUnits.is_initialized\n number_of_living_units ||= 1\n feature_report.program.number_of_residential_units = number_of_living_units\n\n ## building_types\n\n # get an array of the model spaces\n spaces = model.getSpaces\n\n # get array of model space types\n space_types = model.getSpaceTypes\n\n # create a hash for space_type_areas (spcace types as keys and their areas as values)\n space_type_areas = {}\n model.getSpaceTypes.each do |space_type|\n building_type = space_type.standardsBuildingType\n if building_type.empty?\n building_type = 'unknown'\n else\n building_type = building_type.get\n end\n next if ['Residential'].include?(building_type) # space types with empty building type fields will inherit from the building object\n space_type_areas[building_type] = 0 if space_type_areas[building_type].nil?\n space_type_areas[building_type] += convert_units(space_type.floorArea, 'm^2', 'ft^2')\n end\n\n # create a hash for space_type_occupancy (spcace types as keys and their occupancy as values)\n space_type_occupancy = {}\n spaces.each do |space|\n if space.spaceType.empty?\n raise 'space.spaceType is empty. Make sure spaces have a space type'\n else\n building_type = space.spaceType.get.standardsBuildingType\n end\n if building_type.empty?\n building_type = 'unknown'\n else\n building_type = building_type.get\n end\n space_type_occupancy[building_type] = 0 if space_type_occupancy[building_type].nil?\n space_type_occupancy[building_type] += space.numberOfPeople\n end\n\n # combine all in a building_types array\n building_types = []\n for i in 0..(space_type_areas.size - 1)\n building_types << { building_type: space_type_areas.keys[i], floor_area: space_type_areas.values[i], maximum_occupancy: space_type_occupancy.values[i] }\n end\n # add results to the feature report JSON\n feature_report.program.building_types = building_types\n\n ## window_area\n # north_window_area\n north_window_area = sql_query(runner, sql_file, 'InputVerificationandResultsSummary', \"TableName='Window-Wall Ratio' AND RowName='Window Opening Area' AND ColumnName='North (315 to 45 deg)'\").to_f\n feature_report.program.window_area_sqft[:north_window_area_sqft] = convert_units(north_window_area, 'm^2', 'ft^2')\n # south_window_area\n south_window_area = sql_query(runner, sql_file, 'InputVerificationandResultsSummary', \"TableName='Window-Wall Ratio' AND RowName='Window Opening Area' AND ColumnName='South (135 to 225 deg)'\").to_f\n feature_report.program.window_area_sqft[:south_window_area_sqft] = convert_units(south_window_area, 'm^2', 'ft^2')\n # east_window_area\n east_window_area = sql_query(runner, sql_file, 'InputVerificationandResultsSummary', \"TableName='Window-Wall Ratio' AND RowName='Window Opening Area' AND ColumnName='East (45 to 135 deg)'\").to_f\n feature_report.program.window_area_sqft[:east_window_area_sqft] = convert_units(east_window_area, 'm^2', 'ft^2')\n # west_window_area\n west_window_area = sql_query(runner, sql_file, 'InputVerificationandResultsSummary', \"TableName='Window-Wall Ratio' AND RowName='Window Opening Area' AND ColumnName='West (225 to 315 deg)'\").to_f\n feature_report.program.window_area_sqft[:west_window_area_sqft] = convert_units(west_window_area, 'm^2', 'ft^2')\n # total_window_area\n total_window_area = north_window_area + south_window_area + east_window_area + west_window_area\n feature_report.program.window_area_sqft[:total_window_area_sqft] = convert_units(total_window_area, 'm^2', 'ft^2')\n\n ## wall_area\n # north_wall_area\n north_wall_area = sql_query(runner, sql_file, 'InputVerificationandResultsSummary', \"TableName='Window-Wall Ratio' AND RowName='Gross Wall Area' AND ColumnName='North (315 to 45 deg)'\").to_f\n feature_report.program.wall_area_sqft[:north_wall_area_sqft] = convert_units(north_wall_area, 'm^2', 'ft^2')\n # south_wall_area\n south_wall_area = sql_query(runner, sql_file, 'InputVerificationandResultsSummary', \"TableName='Window-Wall Ratio' AND RowName='Gross Wall Area' AND ColumnName='South (135 to 225 deg)'\").to_f\n feature_report.program.wall_area_sqft[:south_wall_area_sqft] = convert_units(south_wall_area, 'm^2', 'ft^2')\n # east_wall_area\n east_wall_area = sql_query(runner, sql_file, 'InputVerificationandResultsSummary', \"TableName='Window-Wall Ratio' AND RowName='Gross Wall Area' AND ColumnName='East (45 to 135 deg)'\").to_f\n feature_report.program.wall_area_sqft[:east_wall_area_sqft] = convert_units(east_wall_area, 'm^2', 'ft^2')\n # west_wall_area\n west_wall_area = sql_query(runner, sql_file, 'InputVerificationandResultsSummary', \"TableName='Window-Wall Ratio' AND RowName='Gross Wall Area' AND ColumnName='West (225 to 315 deg)'\").to_f\n feature_report.program.wall_area_sqft[:west_wall_area_sqft] = convert_units(west_wall_area, 'm^2', 'ft^2')\n # total_wall_area\n total_wall_area = north_wall_area + south_wall_area + east_wall_area + west_wall_area\n feature_report.program.wall_area_sqft[:total_wall_area_sqft] = convert_units(total_wall_area, 'm^2', 'ft^2')\n\n # total_roof_area\n total_roof_area = 0.0\n surfaces.each do |surface|\n if (surface.outsideBoundaryCondition == 'Outdoors') && (surface.surfaceType == 'RoofCeiling')\n total_roof_area += surface.netArea\n end\n end\n\n total_roof_area_sqft = convert_units(total_roof_area, 'm^2', 'ft^2')\n feature_report.program.roof_area_sqft[:total_roof_area_sqft] = total_roof_area_sqft\n\n # available_roof_area_sqft\n # RK: a more robust method should be implemented to find the available_roof_area\n # assign available roof area to be a percentage of the total roof area\n\n if building_types[0][:building_type].include? 'Single-Family Detached'\n feature_report.program.roof_area_sqft[:available_roof_area_sqft] = 0.45 * total_roof_area_sqft\n else\n feature_report.program.roof_area_sqft[:available_roof_area_sqft] = 0.75 * total_roof_area_sqft\n end\n\n # RK: Temporary solution: assign available roof area to be equal to total roof area\n # feature_report.program.roof_area_sqft[:available_roof_area_sqft] = total_roof_area_sqft\n\n # orientation\n # RK: a more robust method should be implemented to find orientation(finding main axis of the building using aspect ratio)\n building_rotation = model.getBuilding.northAxis\n feature_report.program.orientation_deg = building_rotation\n\n # aspect_ratio\n north_wall_area = sql_query(runner, sql_file, 'InputVerificationandResultsSummary', \"TableName='Window-Wall Ratio' AND RowName='Gross Wall Area' AND ColumnName='North (315 to 45 deg)'\")\n east_wall_area = sql_query(runner, sql_file, 'InputVerificationandResultsSummary', \"TableName='Window-Wall Ratio' AND RowName='Gross Wall Area' AND ColumnName='East (45 to 135 deg)'\")\n aspect_ratio = north_wall_area / east_wall_area if north_wall_area != 0 && east_wall_area != 0\n aspect_ratio ||= nil\n feature_report.program.aspect_ratio = aspect_ratio\n\n # total_construction_cost\n total_construction_cost = sql_query(runner, sql_file, 'Life-Cycle Cost Report', \"TableName='Present Value for Recurring, Nonrecurring and Energy Costs (Before Tax)' AND RowName='LCC_MAT - BUILDING - LIFE CYCLE COSTS' AND ColumnName='Cost'\")\n feature_report.program.total_construction_cost_dollar = total_construction_cost\n\n # packaged thermal storage capacities by cooling coil\n ptes_keys = sql_file.availableKeyValues('RUN Period 1', 'Zone Timestep', 'Cooling Coil Ice Thermal Storage End Fraction')\n if ptes_keys.empty?\n ptes_size = nil\n runner.registerWarning('Query failed for Packaged Ice Thermal Storage Capacity')\n else\n begin\n ptes_size = 0\n ptes_keys.each do |pk|\n ptes_size += sql_query(runner, sql_file, 'ComponentSizingSummary', \"TableName='Coil:Cooling:DX:SingleSpeed:ThermalStorage' AND RowName='#{pk}' AND ColumnName='Ice Storage Capacity'\").to_f\n end\n ptes_size = convert_units(ptes_size, 'GJ', 'kWh')\n rescue StandardError\n runner.registerWarning('Query ptes_size.get failed')\n end\n end\n feature_report.thermal_storage.ptes_size_kwh = ptes_size\n\n # get the central tank thermal storage capacity\n its_size = nil\n its_size_index = sql_file.execAndReturnFirstDouble(\"SELECT ReportVariableDataDictionaryIndex FROM ReportVariableDataDictionary WHERE VariableName='Ice Thermal Storage Capacity'\")\n if its_size_index.empty?\n runner.registerWarning('Query failed for Ice Thermal Storage Capacity')\n else\n begin\n its_size = sql_file.execAndReturnFirstDouble(\"SELECT VariableValue FROM ReportVariableData WHERE ReportVariableDataDictionaryIndex=#{its_size_index}\").get\n its_size = convert_units(its_size.to_f, 'GJ', 'kWh')\n rescue StandardError\n runner.registerWarning('Query its_size.get failed')\n end\n end\n feature_report.thermal_storage.its_size_kwh = its_size\n\n ############################################################################\n ##\n # Get Reporting Periods information and store in the feature_report\n ##\n\n # start_date\n # month\n begin_month = model.getRunPeriod.getBeginMonth\n feature_report.reporting_periods[0].start_date.month = begin_month\n # day_of_month\n begin_day_of_month = model.getRunPeriod.getBeginDayOfMonth\n feature_report.reporting_periods[0].start_date.day_of_month = begin_day_of_month\n # year\n begin_year = model.getYearDescription.calendarYear\n feature_report.reporting_periods[0].start_date.year = begin_year\n\n # end_date\n # month\n end_month = model.getRunPeriod.getEndMonth\n feature_report.reporting_periods[0].end_date.month = end_month\n # day_of_month\n end_day_of_month = model.getRunPeriod.getEndDayOfMonth\n feature_report.reporting_periods[0].end_date.day_of_month = end_day_of_month\n # year\n end_year = model.getYearDescription.calendarYear\n feature_report.reporting_periods[0].end_date.year = end_year\n\n # total_site_energy\n total_site_energy = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='Site and Source Energy' AND RowName='Total Site Energy' AND ColumnName='Total Energy'\")\n feature_report.reporting_periods[0].total_site_energy_kwh = convert_units(total_site_energy, 'GJ', 'kWh')\n\n # total_source_energy\n total_source_energy = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='Site and Source Energy' AND RowName='Total Source Energy' AND ColumnName='Total Energy'\")\n feature_report.reporting_periods[0].total_source_energy_kwh = convert_units(total_source_energy, 'GJ', 'kWh')\n\n # EUI is only valid with a full year of energy data\n if begin_month == 1 && begin_day_of_month == 1 && end_month == 12 && end_day_of_month == 31\n # calculate site EUI\n site_EUI_kwh_per_m2 = feature_report.reporting_periods[0].total_site_energy_kwh / floor_area\n site_EUI_kbtu_per_ft2 = convert_units(total_site_energy, 'GJ', 'kBtu') / convert_units(floor_area, 'm^2', 'ft^2')\n # add site EUI to feature report\n feature_report.reporting_periods[0].site_EUI_kwh_per_m2 = site_EUI_kwh_per_m2\n feature_report.reporting_periods[0].site_EUI_kbtu_per_ft2 = site_EUI_kbtu_per_ft2\n # calculate source EUI\n source_EUI_kwh_per_m2 = feature_report.reporting_periods[0].total_source_energy_kwh / floor_area\n source_EUI_kbtu_per_ft2 = convert_units(total_source_energy, 'GJ', 'kBtu') / convert_units(floor_area, 'm^2', 'ft^2')\n # add source EUI to feature report\n feature_report.reporting_periods[0].source_EUI_kwh_per_m2 = source_EUI_kwh_per_m2\n feature_report.reporting_periods[0].source_EUI_kbtu_per_ft2 = source_EUI_kbtu_per_ft2\n end\n\n # net_site_energy\n net_site_energy = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='Site and Source Energy' AND RowName='Net Site Energy' AND ColumnName='Total Energy'\")\n feature_report.reporting_periods[0].net_site_energy_kwh = convert_units(net_site_energy, 'GJ', 'kWh')\n\n # net_source_energy\n net_source_energy = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='Site and Source Energy' AND RowName='Net Source Energy' AND ColumnName='Total Energy'\")\n feature_report.reporting_periods[0].net_source_energy_kwh = convert_units(net_source_energy, 'GJ', 'kWh')\n\n # electricity\n electricity = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='Electricity'\")\n feature_report.reporting_periods[0].electricity_kwh = convert_units(electricity, 'GJ', 'kWh')\n\n # natural_gas\n natural_gas = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='Natural Gas'\")\n feature_report.reporting_periods[0].natural_gas_kwh = convert_units(natural_gas, 'GJ', 'kWh')\n\n # propane\n propane = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='Propane'\")\n feature_report.reporting_periods[0].propane_kwh = convert_units(propane, 'GJ', 'kWh')\n\n # fuel_oil\n fuel_oil = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='Fuel Oil No 2'\")\n feature_report.reporting_periods[0].fuel_oil_kwh = convert_units(fuel_oil, 'GJ', 'kWh')\n\n # other_fuels\n gasoline = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='Gasoline'\")\n diesel = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='Diesel'\")\n coal = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='Coal'\")\n fueloilno1 = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='Fuel Oil No 1'\")\n otherfuel1 = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='Other Fuel 1'\")\n steam = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='Steam'\")\n # ensure not nil\n feature_report.reporting_periods[0].other_fuels_kwh = 0.0\n feature_report.reporting_periods[0].other_fuels_kwh += convert_units(gasoline, 'GJ', 'kWh') unless gasoline.nil?\n feature_report.reporting_periods[0].other_fuels_kwh += convert_units(diesel, 'GJ', 'kWh') unless diesel.nil?\n feature_report.reporting_periods[0].other_fuels_kwh += convert_units(coal, 'GJ', 'kWh') unless coal.nil?\n feature_report.reporting_periods[0].other_fuels_kwh += convert_units(fueloilno1, 'GJ', 'kWh') unless fueloilno1.nil?\n feature_report.reporting_periods[0].other_fuels_kwh += convert_units(otherfuel1, 'GJ', 'kWh') unless otherfuel1.nil?\n feature_report.reporting_periods[0].other_fuels_kwh += convert_units(steam, 'GJ', 'kWh') unless steam.nil?\n\n # district_cooling\n district_cooling = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='District Cooling'\")\n feature_report.reporting_periods[0].district_cooling_kwh = convert_units(district_cooling, 'GJ', 'kWh')\n if building.standardsBuildingType.is_initialized\n feature_report.reporting_periods[0].district_cooling_kwh = 0.0 if ['Residential'].include?(building.standardsBuildingType.get)\n end\n\n # district_heating\n district_heating = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='District Heating'\")\n feature_report.reporting_periods[0].district_heating_kwh = convert_units(district_heating, 'GJ', 'kWh')\n if building.standardsBuildingType.is_initialized\n feature_report.reporting_periods[0].district_heating_kwh = 0.0 if ['Residential'].include?(building.standardsBuildingType.get)\n end\n\n # water\n water = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='Total End Uses' AND ColumnName='Water'\")\n feature_report.reporting_periods[0].water_qbft = water\n\n # electricity_produced\n electricity_produced = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='Electric Loads Satisfied' AND RowName='Total On-Site and Utility Electric Sources' AND ColumnName='Electricity'\")\n feature_report.reporting_periods[0].electricity_produced_kwh = convert_units(electricity_produced, 'GJ', 'kWh')\n\n ## end_uses\n\n # get fuel type as listed in the sql file\n fueltypes = fuel_types.values\n\n # get enduses as listed in the sql file\n enduses = end_uses.values\n enduses.delete('Facility')\n\n # loop through fuel types and enduses to fill in sql_query method\n fueltypes.each do |ft|\n enduses.each do |eu|\n sql_r = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='#{eu}' AND ColumnName='#{ft}'\")\n\n # report each query in its corresponding feature report obeject\n x = ft.tr(' ', '_').downcase\n if x.include? 'water'\n x_u = x + '_qbft'\n else \n x = x.gsub('_#2', '')\n x_u = x + '_kwh'\n end\n m = feature_report.reporting_periods[0].end_uses.send(x_u)\n\n y = eu.tr(' ', '_').downcase\n # ensure not nil so the equations below don't error out\n if sql_r.nil?\n sql_r = 0.0\n end\n sql_r = convert_units(sql_r, 'GJ', 'kWh')\n\n if building.standardsBuildingType.is_initialized\n sql_r = 0.0 if ['Residential'].include?(building.standardsBuildingType.get) && x_u.include?('district')\n end\n m.send(\"#{y}=\", sql_r)\n end\n end\n\n # other fuels\n m = feature_report.reporting_periods[0].end_uses.send('other_fuels_kwh')\n enduses.each do |eu|\n y = eu.tr(' ', '_').downcase\n sql_r = 0.0\n other_fuels.each do |ft|\n sql = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses' AND RowName='#{eu}' AND ColumnName='#{ft}'\")\n\n # ensure not nil so the equations below don't error out\n if not sql.nil?\n sql_r += convert_units(sql, 'GJ', 'kWh')\n end\n end\n m.send(\"#{y}=\", sql_r)\n end\n\n # add enduses subcategories\n electric_vehicles = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='End Uses By Subcategory' AND RowName='Exterior Equipment:Electric Vehicles' AND ColumnName='Electricity'\")\n feature_report.reporting_periods[0].end_uses.electricity_kwh.electric_vehicles = convert_units(electric_vehicles, 'GJ', 'kWh')\n\n ### energy_production\n ## electricity_produced\n # photovoltaic\n photovoltaic_power = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='Electric Loads Satisfied' AND RowName='Photovoltaic Power' AND ColumnName='Electricity'\")\n feature_report.reporting_periods[0].energy_production_kwh[:electricity_produced][:photovoltaic] = convert_units(photovoltaic_power, 'GJ', 'kWh')\n\n ## Total utility cost\n total_utility_cost = sql_query(runner, sql_file, 'Economics Results Summary Report', \"TableName='Annual Cost' AND RowName='Cost' AND ColumnName='Total'\")\n feature_report.reporting_periods[0].total_utility_cost_dollar = total_utility_cost\n\n ## Utility Costs\n # electricity utility cost\n elec_utility_cost = sql_query(runner, sql_file, 'Economics Results Summary Report', \"TableName='Annual Cost' AND RowName='Cost' AND ColumnName='Electric'\")\n feature_report.reporting_periods[0].utility_costs_dollar[0][:fuel_type] = 'Electricity'\n feature_report.reporting_periods[0].utility_costs_dollar[0][:total_cost] = elec_utility_cost\n # gas utility cost\n gas_utility_cost = sql_query(runner, sql_file, 'Economics Results Summary Report', \"TableName='Annual Cost' AND RowName='Cost' AND ColumnName='Natural Gas'\")\n feature_report.reporting_periods[0].utility_costs_dollar << { fuel_type: 'Natural Gas', total_cost: gas_utility_cost }\n\n ## comfort_result\n # time_setpoint_not_met_during_occupied_cooling\n time_setpoint_not_met_during_occupied_cooling = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='Comfort and Setpoint Not Met Summary' AND RowName='Time Setpoint Not Met During Occupied Cooling' AND ColumnName='Facility'\")\n feature_report.reporting_periods[0].comfort_result[:time_setpoint_not_met_during_occupied_cooling] = time_setpoint_not_met_during_occupied_cooling\n\n # time_setpoint_not_met_during_occupied_heating\n time_setpoint_not_met_during_occupied_heating = sql_query(runner, sql_file, 'AnnualBuildingUtilityPerformanceSummary', \"TableName='Comfort and Setpoint Not Met Summary' AND RowName='Time Setpoint Not Met During Occupied Heating' AND ColumnName='Facility'\")\n feature_report.reporting_periods[0].comfort_result[:time_setpoint_not_met_during_occupied_heating] = time_setpoint_not_met_during_occupied_heating\n\n # time_setpoint_not_met_during_occupied_hour\n time_setpoint_not_met_during_occupied_hours = time_setpoint_not_met_during_occupied_heating + time_setpoint_not_met_during_occupied_cooling\n feature_report.reporting_periods[0].comfort_result[:time_setpoint_not_met_during_occupied_hours] = time_setpoint_not_met_during_occupied_hours\n\n ######################################## Reporting TImeseries Results FOR CSV File ######################################\n\n # Get the weather file run period (as opposed to design day run period)\n ann_env_pd = nil\n sql_file.availableEnvPeriods.each do |env_pd|\n env_type = sql_file.environmentType(env_pd)\n if env_type.is_initialized\n if env_type.get == OpenStudio::EnvironmentType.new('WeatherRunPeriod')\n ann_env_pd = env_pd\n end\n end\n end\n\n if ann_env_pd == false\n runner.registerError(\"Can't find a weather runperiod, make sure you ran an annual simulation, not just the design days.\")\n return false\n end\n\n # timeseries we want to report\n requested_timeseries_names = [\n 'Electricity:Facility',\n 'ElectricityProduced:Facility',\n 'NaturalGas:Facility',\n 'Propane:Facility',\n 'FuelOilNo2:Facility',\n 'OtherFuels:Facility',\n 'Cooling:Electricity',\n 'Heating:Electricity',\n 'InteriorLights:Electricity',\n 'ExteriorLights:Electricity',\n 'InteriorEquipment:Electricity',\n 'ExteriorEquipment:Electricity',\n 'Fans:Electricity',\n 'Pumps:Electricity',\n 'WaterSystems:Electricity',\n 'HeatRejection:Electricity',\n 'HeatRejection:NaturalGas',\n 'Heating:NaturalGas',\n 'WaterSystems:NaturalGas',\n 'InteriorEquipment:NaturalGas',\n 'HeatRejection:Propane',\n 'Heating:Propane',\n 'WaterSystems:Propane',\n 'InteriorEquipment:Propane',\n 'HeatRejection:FuelOilNo2',\n 'Heating:FuelOilNo2',\n 'WaterSystems:FuelOilNo2',\n 'InteriorEquipment:FuelOilNo2',\n 'HeatRejection:OtherFuels',\n 'Heating:OtherFuels',\n 'WaterSystems:OtherFuels',\n 'InteriorEquipment:OtherFuels',\n 'DistrictCooling:Facility',\n 'DistrictHeating:Facility',\n 'District Cooling Chilled Water Rate',\n 'District Cooling Mass Flow Rate',\n 'District Cooling Inlet Temperature',\n 'District Cooling Outlet Temperature',\n 'District Heating Hot Water Rate',\n 'District Heating Mass Flow Rate',\n 'District Heating Inlet Temperature',\n 'District Heating Outlet Temperature',\n 'Cooling Coil Total Cooling Rate',\n 'Heating Coil Heating Rate'\n ]\n\n # add thermal comfort timeseries\n comfortTimeseries = ['Zone Thermal Comfort Fanger Model PMV', 'Zone Thermal Comfort Fanger Model PPD']\n requested_timeseries_names += comfortTimeseries\n\n # add additional power timeseries (for calculating transformer apparent power to compare to rating ) in VA\n powerTimeseries = ['Net Electric Energy', 'Electricity:Facility Power', 'ElectricityProduced:Facility Power', 'Electricity:Facility Apparent Power', 'ElectricityProduced:Facility Apparent Power', 'Net Power', 'Net Apparent Power']\n requested_timeseries_names += powerTimeseries\n\n # add additional thermal storage timeseries\n tesTimeseries = ['Ice Thermal Storage End Fraction', 'Cooling Coil Ice Thermal Storage End Fraction']\n requested_timeseries_names += tesTimeseries\n\n # register info all timeseries\n runner.registerInfo(\"All timeseries: #{requested_timeseries_names}\")\n\n # timeseries variables to keep to calculate power\n tsToKeep = ['Electricity:Facility', 'ElectricityProduced:Facility']\n tsToKeepIndexes = {}\n\n ### powerFactor ###\n # use power_factor default: 0.9\n # TODO: Set powerFactor default based on building type\n powerFactor = 0.9\n\n ### power_conversion ###\n # divide values by total_seconds to convert J to W (W = J/sec)\n # divide values by total_hours to convert kWh to kW (kW = kWh/hrs)\n total_seconds = (60 / timesteps_per_hour.to_f) * 60 # make sure timesteps_per_hour is a float in the division\n total_hours = 1 / timesteps_per_hour.to_f # make sure timesteps_per_hour is a float in the division\n # set power_conversion\n power_conversion = total_hours # we set the power conversio to total_hours since we want to convert lWh to kW\n puts \"Power Converion: to convert kWh to kW values will be divided by #{power_conversion}\"\n\n # number of values in each timeseries\n n = nil\n # all numeric timeseries values, transpose of CSV file (e.g. values[key_cnt] is column, values[key_cnt][i] is column and row)\n values = []\n tmpArray = []\n # since schedule value will have a bunch of key_values, we need to keep track of these as additional timeseries\n key_cnt = 0\n # this is recording the name of these final timeseries to write in the header of the CSV\n final_timeseries_names = []\n\n # loop over requested timeseries\n requested_timeseries_names.each_index do |i|\n timeseries_name = requested_timeseries_names[i]\n puts \" *********timeseries_name = #{timeseries_name}******************\"\n runner.registerInfo(\"TIMESERIES: #{timeseries_name}\")\n\n # get all the key values that this timeseries can be reported for (e.g. if PMV is requested for each zone)\n if timeseries_name.include?('OtherFuels')\n key_values = sql_file.availableKeyValues('RUN PERIOD 1', 'Zone Timestep', timeseries_name.upcase)\n else\n key_values = sql_file.availableKeyValues('RUN PERIOD 1', 'Zone Timestep', timeseries_name)\n end\n runner.registerInfo(\"KEY VALUES: #{key_values}\")\n if key_values.empty?\n key_values = ['']\n end\n\n # sort keys\n sorted_keys = key_values.sort\n requested_keys = requested_timeseries_names\n final_keys = []\n # make sure aggregated timeseries are listed in sorted order before all individual feature timeseries\n sorted_keys.each do |k|\n if requested_keys.include? k\n final_keys << k\n end\n end\n sorted_keys.each do |k|\n if !requested_keys.include? k\n final_keys << k\n end\n end\n\n # loop over final keys\n final_keys.each_with_index do |key_value, key_i|\n new_timeseries_name = ''\n\n runner.registerInfo(\"!! TIMESERIES NAME: #{timeseries_name} AND key_value: #{key_value}\")\n\n # check if we have to come up with a new name for the timeseries in our CSV header\n if key_values.size == 1\n # use timeseries name when only 1 keyvalue\n new_timeseries_name = timeseries_name\n else\n # use key_value name\n # special case for Zone Thermal Comfort: use both timeseries_name and key_value\n if timeseries_name.include? 'Zone Thermal Comfort'\n new_timeseries_name = timeseries_name + ' ' + key_value\n else\n new_timeseries_name = key_value\n end\n end\n # final_timeseries_names << new_timeseries_name\n\n # get the actual timeseries\n if timeseries_name.include?('OtherFuels')\n ts = sql_file.timeSeries(ann_env_pd.to_s, reporting_frequency.to_s, timeseries_name.upcase, key_value)\n else\n ts = sql_file.timeSeries(ann_env_pd.to_s, reporting_frequency.to_s, timeseries_name, key_value)\n end\n\n if n.nil?\n # first timeseries should always be set\n runner.registerInfo('First timeseries')\n values[key_cnt] = ts.get.values\n n = values[key_cnt].size\n elsif ts.is_initialized\n runner.registerInfo('Is Initialized')\n values[key_cnt] = ts.get.values\n else\n runner.registerInfo('Is NOT Initialized')\n values[key_cnt] = Array.new(n, 0)\n end\n\n # residential considerations\n if building.standardsBuildingType.is_initialized\n values[key_cnt] = Array.new(n, 0) if ['DistrictCooling:Facility', 'DistrictHeating:Facility'].include?(timeseries_name) && ['Residential'].include?(building.standardsBuildingType.get)\n end\n\n # unit conversion\n old_unit = ts.get.units if ts.is_initialized\n\n if timeseries_name.include?('NaturalGas') || timeseries_name.include?('Propane') || timeseries_name.include?('FuelOilNo2') || timeseries_name.include?('OtherFuels')\n new_unit = 'kBtu'\n else\n new_unit = case old_unit.to_s\n when 'J'\n 'kWh'\n when 'kBtu'\n 'kWh'\n when 'gal'\n 'm3'\n when 'W'\n 'W'\n end\n end\n\n # loop through each value and apply unit conversion\n os_vec = values[key_cnt]\n if !timeseries_name.include? 'Zone Thermal Comfort'\n for i in 0..os_vec.length - 1\n\n unless new_unit == old_unit || old_unit.nil? || new_unit.nil? || !ts.is_initialized\n os_vec[i] = OpenStudio.convert(os_vec[i], old_unit, new_unit).get\n end\n\n end\n end\n\n # keep certain timeseries to calculate power\n if tsToKeep.include? timeseries_name\n tsToKeepIndexes[timeseries_name] = key_cnt\n end\n\n # special processing: power\n if powerTimeseries.include? timeseries_name\n # special case: net series (subtract generation from load)\n if timeseries_name.include? 'Net'\n\n newVals = Array.new(n, 0)\n # Apparent power calculation\n\n if timeseries_name.include?('Apparent')\n (0..n - 1).each do |j|\n newVals[j] = (values[tsToKeepIndexes['Electricity:Facility']][j].to_f - values[tsToKeepIndexes['ElectricityProduced:Facility']][j].to_f) / power_conversion / powerFactor\n j += 1\n end\n new_unit = 'kVA'\n elsif timeseries_name.include? 'Net Electric Energy'\n (0..n - 1).each do |j|\n newVals[j] = (values[tsToKeepIndexes['Electricity:Facility']][j].to_f - values[tsToKeepIndexes['ElectricityProduced:Facility']][j].to_f)\n j += 1\n end\n new_unit = 'kWh'\n else\n runner.registerInfo('Power calc')\n # Power calculation\n (0..n - 1).each do |j|\n newVals[j] = (values[tsToKeepIndexes['Electricity:Facility']][j].to_f - values[tsToKeepIndexes['ElectricityProduced:Facility']][j].to_f) / power_conversion\n j += 1\n end\n new_unit = 'kW'\n end\n\n values[key_cnt] = newVals\n else\n tsToKeepIndexes.each do |key, indexValue|\n if timeseries_name.include? key\n runner.registerInfo(\"timeseries_name: #{timeseries_name}, key: #{key}\")\n # use this timeseries\n newVals = Array.new(n, 0)\n # Apparent power calculation\n if timeseries_name.include?('Apparent')\n (0..n - 1).each do |j|\n newVals[j] = values[indexValue][j].to_f / power_conversion / powerFactor\n j += 1\n end\n new_unit = 'kVA'\n else\n # Power calculation\n (0..n - 1).each do |j|\n newVals[j] = values[indexValue][j].to_f / power_conversion\n j += 1\n end\n new_unit = 'kW'\n end\n values[key_cnt] = newVals\n end\n end\n end\n end\n\n # append units to headers\n new_timeseries_name += \"(#{new_unit})\"\n final_timeseries_names << new_timeseries_name\n\n # TODO: DELETE PUTS\n # puts \" *********timeseries_name = #{timeseries_name}******************\"\n # if timeseries_name.include? 'Power'\n # puts \"values = #{values[key_cnt]}\"\n # puts \"units = #{new_unit}\"\n # end\n\n # thermal storage ice end fractions have multiple timeseries, aggregate into a single series with consistent name and use the average value at each timestep\n if tesTimeseries.include? timeseries_name\n\n # set up array if 1st key_value\n if key_i == 0\n runner.registerInfo(\"SETTING UP NEW ARRAY FOR: #{timeseries_name}\")\n tmpArray = Array.new(n, 1)\n end\n\n # add to array (keep min value at each timestep)\n (0..(n - 1)).each do |ind|\n tVal = values[key_cnt][ind].to_f\n tmpArray[ind] = [tVal, tmpArray[ind]].min\n end\n end\n\n # comfort results usually have multiple timeseries (per zone), aggregate into a single series with consistent name and use worst value at each timestep\n if comfortTimeseries.include? timeseries_name\n\n # set up array if 1st key_value\n if key_i == 0\n runner.registerInfo(\"SETTING UP NEW ARRAY FOR: #{timeseries_name}\")\n tmpArray = Array.new(n, 0)\n end\n\n # add to array (keep max value at each timestep)\n (0..(n - 1)).each do |ind|\n # process negative and positive values differently\n tVal = values[key_cnt][ind].to_f\n if tVal < 0\n tmpArray[ind] = [tVal, tmpArray[ind]].min\n else\n tmpArray[ind] = [tVal, tmpArray[ind]].max\n end\n end\n\n # aggregate and save when all keyvalues have been processed\n if key_i == final_keys.size - 1\n\n hrsOutOfBounds = 0\n if timeseries_name === 'Zone Thermal Comfort Fanger Model PMV'\n (0..(n - 1)).each do |ind|\n # -0.5 < x < 0.5 is within bounds\n if values[key_cnt][ind].to_f > 0.5 || values[key_cnt][ind].to_f < -0.5\n hrsOutOfBounds += 1\n end\n end\n hrsOutOfBounds = hrsOutOfBounds.to_f / timesteps_per_hour\n elsif timeseries_name === 'Zone Thermal Comfort Fanger Model PPD'\n (0..(n - 1)).each do |ind|\n # > 20 is outside bounds\n if values[key_cnt][ind].to_f > 20\n hrsOutOfBounds += 1\n end\n end\n hrsOutOfBounds = hrsOutOfBounds.to_f / timesteps_per_hour\n else\n # this one is already scaled by timestep, no need to divide total\n (0..(n - 1)).each do |ind|\n hrsOutOfBounds += values[key_cnt][ind].to_f if values[key_cnt][ind].to_f > 0\n end\n end\n\n # save variable to feature_reports hash\n runner.registerInfo(\"timeseries #{timeseries_name}: hours out of bounds: #{hrsOutOfBounds}\")\n if timeseries_name === 'Zone Thermal Comfort Fanger Model PMV'\n feature_report.reporting_periods[0].comfort_result[:hours_out_of_comfort_bounds_PMV] = hrsOutOfBounds\n elsif timeseries_name == 'Zone Thermal Comfort Fanger Model PPD'\n feature_report.reporting_periods[0].comfort_result[:hours_out_of_comfort_bounds_PPD] = hrsOutOfBounds\n end\n\n end\n\n end\n\n # increment key_cnt in new_keys loop\n key_cnt += 1\n end\n end\n\n # Add datime column\n datetimes = []\n # check what timeseries is available\n available_ts = sql_file.availableTimeSeries\n puts \"####### available_ts = #{available_ts}\"\n # get the timeseries for any of available timeseries\n # RK: code enhancement needed\n ts_d_e = sql_file.timeSeries(ann_env_pd.to_s, reporting_frequency.to_s, 'Electricity:Facility', '')\n ts_d_g = sql_file.timeSeries(ann_env_pd.to_s, reporting_frequency.to_s, 'NaturalGas:Facility', '')\n\n if ts_d_e.is_initialized\n timeseries_d = ts_d_e.get\n elsif ts_d_g.is_initialized\n timeseries_d = ts_d_g.get\n else\n raise 'ELECTRICITY and GAS results are not initiaized'\n end\n # get formated datetimes\n timeseries_d.dateTimes.each do |datetime|\n datetimes << format_datetime(datetime.to_s)\n end\n # insert datetimes to values\n values.insert(0, datetimes)\n # insert datetime header to names\n final_timeseries_names.insert(0, 'Datetime')\n\n runner.registerInfo(\"new final_timeseries_names size: #{final_timeseries_names.size}\")\n\n # Save the 'default_feature_reports.csv' file\n File.open('default_feature_reports.csv', 'w') do |file|\n file.puts(final_timeseries_names.join(','))\n (0...n).each do |l|\n line = []\n values.each_index do |j|\n line << values[j][l]\n end\n file.puts(line.join(','))\n end\n end\n\n # closing the sql file\n sql_file.close\n\n ############################# Adding timeseries_csv info to json report and saving CSV ################################\n # add csv info to feature_report\n feature_report.timeseries_csv.path = File.join(Dir.pwd, 'default_feature_reports.csv')\n feature_report.timeseries_csv.first_report_datetime = '0'\n feature_report.timeseries_csv.column_names = final_timeseries_names\n\n ##### Save the 'default_feature_reports.json' file\n\n feature_report_hash = feature_report.to_hash\n\n File.open('default_feature_reports.json', 'w') do |f|\n f.puts JSON.pretty_generate(feature_report_hash)\n # make sure data is written to the disk one way or the other\n begin\n f.fsync\n rescue StandardError\n f.flush\n end\n end\n\n # reporting final condition\n runner.registerFinalCondition('Default Feature Reports generated successfully.')\n\n true\n # end the run method\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n\n pct_red = runner.getDoubleArgumentValue(\"pct_red\",user_arguments)\n start_hr = runner.getDoubleArgumentValue(\"start_hr\",user_arguments)\n end_hr = runner.getDoubleArgumentValue(\"end_hr\",user_arguments)\n \n\n\n #check the fraction for reasonableness\n if not 0 <= pct_red and pct_red <= 100\n runner.registerError(\"Percent reduction value needs to be between 0 and 100.\")\n return false\n end\n\n #check start_hr for reasonableness and round to 15 minutes\n start_red_hr = nil\n start_red_min = nil\n if not 0 <= start_hr and start_hr <= 24\n runner.registerError(\"Time in hours needs to be between or equal to 0 and 24\")\n return false\n else\n rounded_start_hr = ((start_hr*4).round)/4.0\n if not start_hr == rounded_start_hr\n runner.registerInfo(\"Start time rounded to nearest 15 minutes: #{rounded_start_hr}\")\n end\n start_red_hr = rounded_start_hr.truncate\n start_red_min = (rounded_start_hr - start_red_hr)*60\n start_red_min = start_red_min.to_i\n end\n\n #check end_hr for reasonableness and round to 15 minutes\n end_red_hr = nil\n end_red_min = nil \n if not 0 <= end_hr and end_hr <= 24\n runner.registerError(\"Time in hours needs to be between or equal to 0 and 24.\")\n return false\n elsif end_hr > end_hr\n runner.registerError(\"Please enter an end time later in the day than end time.\")\n return false\n else\n rounded_end_hr = ((end_hr*4).round)/4.0\n if not end_hr == rounded_end_hr\n runner.registerInfo(\"End time rounded to nearest 15 minutes: #{rounded_end_hr}\")\n end\n end_red_hr = rounded_end_hr.truncate\n end_red_min = (rounded_end_hr - end_red_hr)*60\n end_red_min = end_red_min.to_i\n end\n\n # Translate the percent reduction into a multiplier\n red_mult = pct_red/100\n\n # Get schedules from all lights.\n original_lights_schs = []\n model.getLightss.each do |lights|\n if lights.schedule.is_initialized\n lights_sch = lights.schedule.get\n original_lights_schs << lights_sch\n end\n end\n\n # loop through the unique list of lights schedules, cloning\n # and reducing schedule fraction during the specified time range.\n original_lights_schs_new_schs = {}\n original_lights_schs.uniq.each do |lights_sch|\n if lights_sch.to_ScheduleRuleset.is_initialized\n new_lights_sch = lights_sch.clone(model).to_ScheduleRuleset.get\n new_lights_sch.setName(\"#{lights_sch.name} with Solar Cogeneration and Daylighting\")\n original_lights_schs_new_schs[lights_sch] = new_lights_sch\n new_lights_sch = new_lights_sch.to_ScheduleRuleset.get\n \n # method to adjust the values in a day schedule by a \n # specified percentage during a range of hours.\n def reduce_schedule(day_sch, red_mult, start_red_hr, start_red_min, end_red_hr, end_red_min)\n start_time = OpenStudio::Time.new(0, start_red_hr, start_red_min, 0)\n end_time = OpenStudio::Time.new(0, end_red_hr, end_red_min, 0)\n\n # Get the original values at the desired start and end times\n # and put points into the schedule at those times.\n day_sch.addValue(start_time, day_sch.getValue(start_time))\n day_sch.addValue(end_time, day_sch.getValue(end_time))\n \n # Store the original time/values then clear the schedule\n times = day_sch.times\n values = day_sch.values\n day_sch.clearValues\n\n # Modify the time/values and add back to the schedule\n for i in 0..(values.length - 1)\n if times[i] > start_time and times[i] <= end_time # Inside range\n day_sch.addValue(times[i], values[i] * red_mult)\n else\n day_sch.addValue(times[i], values[i])\n end\n end\n\n end #end reduce schedule\n\n # Reduce default day schedule\n if new_lights_sch.scheduleRules.size == 0\n runner.registerWarning(\"Schedule '#{new_lights_sch.name}' applies to all days. It has been treated as a Weekday schedule.\")\n end\n reduce_schedule(new_lights_sch.defaultDaySchedule, red_mult, start_red_hr, start_red_min, end_red_hr, end_red_min)\n \n # Reduce all other schedule rules\n new_lights_sch.scheduleRules.each do |sch_rule|\n reduce_schedule(sch_rule.daySchedule, red_mult, start_red_hr, start_red_min, end_red_hr, end_red_min)\n end\n \n end \n end #end of original_lights_schs.uniq.each do\n\n #loop through all lights instances, replacing old lights schedules with the reduced schedules\n model.getLightss.each do |lights|\n if lights.schedule.empty?\n runner.registerWarning(\"There was no schedule assigned for the lights object named '#{lights.name}. No schedule was added.'\")\n else\n old_lights_sch = lights.schedule.get\n lights.setSchedule(original_lights_schs_new_schs[old_lights_sch])\n runner.registerInfo(\"Schedule for the lights object named '#{lights.name}' was reduced to simulate the application of Solar Cogeneration and Daylighting.\")\n end\n end\n\n # NA if the model has no lights\n if model.getLightss.size == 0\n runner.registerNotAsApplicable(\"Not Applicable - There are no lights in the model.\")\n end\n\n # Reporting final condition of model\n runner.registerFinalCondition(\"#{original_lights_schs.uniq.size} schedule(s) were edited to reflect the addition of Solar Cogeneration and Daylighting to the building.\")\n \n return true\n\n end", "def communicate_measure_result(_ = nil, _ = nil)\r\n end", "def run(workspace, runner, user_arguments)\n super(workspace, runner, user_arguments)\n\n #use the built-in error checking \n if not runner.validateUserArguments(arguments(workspace), user_arguments)\n return false\n end\n \n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end\n \n require 'json'\n \n # Get the last openstudio model\n model = runner.lastOpenStudioModel\n if model.empty?\n runner.registerError(\"Could not load last OpenStudio model, cannot apply measure.\")\n return false\n end\n model = model.get\n \n results = {}\n \n #get all DX coils in model\n dx_single = workspace.getObjectsByType(\"Coil:Cooling:DX:SingleSpeed\".to_IddObjectType)\n dx_two = workspace.getObjectsByType(\"Coil:Cooling:DX:TwoSpeed\".to_IddObjectType)\n \n dx_single.each do |dx|\n dx_name = {}\n coil_name = dx.getString(0).get\n runner.registerInfo(\"DX coil: #{coil_name} Initial COP: #{dx.getDouble(4).get}\")\n dx.setDouble(4,7.62)\n runner.registerInfo(\"DX coil: #{coil_name} Final COP: #{dx.getDouble(4).get}\")\n dx_name[:dxname] = \"#{coil_name}\"\n results[\"#{coil_name}\"] = dx_name\n end\n\n dx_two.each do |dx|\n dx_name = {}\n coil_name = dx.getString(0).get\n runner.registerInfo(\"DX coil: #{coil_name} Initial High COP: #{dx.getDouble(4).get}, Initial Low COP: #{dx.getDouble(16).get}\")\n dx.setDouble(4,7.62)\n dx.setDouble(16,7.62)\n runner.registerInfo(\"DX coil: #{coil_name} Final High COP: #{dx.getDouble(4).get}, Final Low COP: #{dx.getDouble(16).get}\")\n dx_name[:dxname] = \"#{coil_name}\"\n results[\"#{coil_name}\"] = dx_name\n end\n \n if results.empty?\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\n end\n \n #save airloop parsing results to ems_results.json\n runner.registerInfo(\"Saving ems_results.json\")\n FileUtils.mkdir_p(File.dirname(\"ems_results.json\")) unless Dir.exist?(File.dirname(\"ems_results.json\"))\n File.open(\"ems_results.json\", 'w') {|f| f << JSON.pretty_generate(results)}\n \n if results.empty?\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\n #save blank ems_membrane_heat_pump_cooling_only.ems file so Eplus measure does not crash\n ems_string = \"\"\n runner.registerInfo(\"Saving blank ems_membrane_heat_pump_cooling_only file\")\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\n f.write(ems_string)\n end\n return true\n end\n \n timeStep = model.getTimestep.numberOfTimestepsPerHour\n \n runner.registerInfo(\"Making EMS string for Membrane Heat Pump Cooling Only\")\n #start making the EMS code\n ems_string = \"\" #clear out the ems_string\n ems_string << \"\\n\" \n ems_string << \"Output:Variable,*,Cooling Coil Sensible Cooling Energy,timestep; !- HVAC Sum [J]\" + \"\\n\"\n ems_string << \"\\n\" \n \n results.each_with_index do |(key, value), i| \n ems_string << \"EnergyManagementSystem:Sensor,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}SensibleClgJ,\" + \"\\n\"\n ems_string << \" #{value[:dxname]},\" + \"\\n\"\n ems_string << \" Cooling Coil Sensible Cooling Energy;\" + \"\\n\"\n ems_string << \"\\n\" \n ems_string << \"WaterUse:Equipment,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUse, !- Name\" + \"\\n\"\n ems_string << \" Membrane HP Cooling, !- End-Use Subcategory\" + \"\\n\"\n ems_string << \" 0.003155, !- Peak Flow Rate {m3/s} = 3000 gal/hr\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule; !- Flow Rate Fraction Schedule Name\" + \"\\n\"\n ems_string << \"\\n\" \n ems_string << \"Schedule:Constant,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule, !- Name\" + \"\\n\"\n ems_string << \" , !- Schedule Type Limits Name\" + \"\\n\"\n ems_string << \" 1; !- Hourly Value\" + \"\\n\"\n ems_string << \"\\n\" \n ems_string << \"EnergyManagementSystem:Actuator,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseCtrl,\" + \"\\n\"\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule,\" + \"\\n\"\n ems_string << \" Schedule:Constant,\" + \"\\n\"\n ems_string << \" Schedule Value;\" + \"\\n\"\n ems_string << \"\\n\" \n end\n ems_string << \"EnergyManagementSystem:ProgramCallingManager,\" + \"\\n\"\n ems_string << \" MembraneHPWaterUseProgramControl, !- Name\" + \"\\n\"\n ems_string << \" AfterPredictorBeforeHVACManagers, !- EnergyPlus Model Calling Point\" + \"\\n\"\n ems_string << \" MembraneHPWaterUseProgram; !- Program Name 1\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \"EnergyManagementSystem:Program,\" + \"\\n\"\n ems_string << \" MembraneHPWaterUseProgram, !- Name\" + \"\\n\"\n ems_string << \" SET TimeStepsPerHr = #{timeStep}\" + \"\\n\"\n results.each_with_index do |(key, value), i|\n ems_string << \" SET MembraneHP#{i+1}SensibleClgTonHr = MembraneHP#{i+1}SensibleClgJ * 0.0000007898,\" + \"\\n\"\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGal = MembraneHP#{i+1}SensibleClgTonHr * 3.0,\" + \"\\n\"\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGalPerHr = MembraneHP#{i+1}SensibleWtrGal * TimeStepsPerHr,\" + \"\\n\"\n ems_string << \" SET MembraneHP#{i+1}WaterUseCtrl = MembraneHP#{i+1}SensibleWtrGalPerHr / 3000.0,\" + \"\\n\"\n end \n ems_string << \" SET UnusedLine = 0;\" + \"\\n\"\n \n #save EMS snippet\n runner.registerInfo(\"Saving ems_membrane_heat_pump_cooling_only file\")\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\n f.write(ems_string)\n end\n \n #unique initial conditions based on\n runner.registerInitialCondition(\"The building has #{results.size} DX coils for which this measure is applicable.\")\n\n #reporting final condition of model\n runner.registerFinalCondition(\"The efficiency of the following coils was increased to SEER 26 to reflect the replacement of these coils with membrane heatpumps: #{results.keys}\")\n \n ems_path = '../MembraneHeatPumpCoolingOnly/ems_membrane_heat_pump_cooling_only.ems'\n json_path = '../MembraneHeatPumpCoolingOnly/ems_results.json'\n if File.exist? ems_path\n ems_string = File.read(ems_path)\n if File.exist? json_path\n json = JSON.parse(File.read(json_path))\n end\n else\n ems_path2 = Dir.glob('../../**/ems_membrane_heat_pump_cooling_only.ems')\n ems_path1 = ems_path2[0]\n json_path2 = Dir.glob('../../**/ems_results.json')\n json_path1 = json_path2[0]\n if ems_path2.size > 1\n runner.registerWarning(\"more than one ems_membrane_heat_pump_cooling_only.ems file found. Using first one found.\")\n end\n if !ems_path1.nil? \n if File.exist? ems_path1\n ems_string = File.read(ems_path1)\n if File.exist? json_path1\n json = JSON.parse(File.read(json_path1))\n else\n runner.registerError(\"ems_results.json file not located\") \n end \n else\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\")\n end \n else\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\") \n end\n end\n if json.nil?\n runner.registerError(\"ems_results.json file not located\")\n return false\n end\n \n if json.empty?\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\n return true\n end\n \n idf_file = OpenStudio::IdfFile::load(ems_string, 'EnergyPlus'.to_IddFileType).get\n runner.registerInfo(\"Adding EMS code to workspace\")\n workspace.addObjects(idf_file.objects)\n \n return true\n\n end", "def run(workspace, runner, user_arguments)\r\n super(workspace, runner, user_arguments)\r\n\r\n #use the built-in error checking \r\n if not runner.validateUserArguments(arguments(workspace), user_arguments)\r\n return false\r\n end\r\n \r\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\r\n if run_measure == 0\r\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\r\n return true \r\n end\r\n \r\n require 'json'\r\n \r\n # Get the last openstudio model\r\n model = runner.lastOpenStudioModel\r\n if model.empty?\r\n runner.registerError(\"Could not load last OpenStudio model, cannot apply measure.\")\r\n return false\r\n end\r\n model = model.get\r\n \r\n results = {}\r\n #get all DX coils in model\r\n dx_single = model.getCoilCoolingDXSingleSpeeds \r\n dx_two = model.getCoilCoolingDXTwoSpeeds\r\n \r\n if !dx_single.empty?\r\n dx_single.each do |dx|\r\n dx_name = {}\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial COP: #{dx.ratedCOP.get}\")\r\n dx.setRatedCOP(OpenStudio::OptionalDouble.new(7.62))\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final COP: #{dx.ratedCOP.get}\")\r\n dx_name[:dxname] = \"#{dx.name.get}\"\r\n results[\"#{dx.name.get}\"] = dx_name\r\n end\r\n end\r\n if !dx_two.empty?\r\n dx_two.each do |dx|\r\n dx_name = {}\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial High COP: #{dx.ratedHighSpeedCOP.get} Low COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx.setRatedHighSpeedCOP(7.62)\r\n dx.setRatedLowSpeedCOP(7.62)\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final High COP: #{dx.ratedHighSpeedCOP.get} Final COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx_name[:dxname] = \"#{dx.name.get}\"\r\n results[\"#{dx.name.get}\"] = dx_name\r\n end\r\n end\r\n \r\n if results.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\r\n end\r\n \r\n #save airloop parsing results to ems_results.json\r\n runner.registerInfo(\"Saving ems_results.json\")\r\n FileUtils.mkdir_p(File.dirname(\"ems_results.json\")) unless Dir.exist?(File.dirname(\"ems_results.json\"))\r\n File.open(\"ems_results.json\", 'w') {|f| f << JSON.pretty_generate(results)}\r\n \r\n if results.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\r\n #save blank ems_membrane_heat_pump_cooling_only.ems file so Eplus measure does not crash\r\n ems_string = \"\"\r\n runner.registerInfo(\"Saving blank ems_membrane_heat_pump_cooling_only file\")\r\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\r\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\r\n f.write(ems_string)\r\n end\r\n return true\r\n end\r\n \r\n timeStep = model.getTimestep.numberOfTimestepsPerHour\r\n \r\n runner.registerInfo(\"Making EMS string for Membrane Heat Pump Cooling Only\")\r\n #start making the EMS code\r\n ems_string = \"\" #clear out the ems_string\r\n ems_string << \"\\n\" \r\n ems_string << \"Output:Variable,*,Cooling Coil Sensible Cooling Energy,timestep; !- HVAC Sum [J]\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n \r\n results.each_with_index do |(key, value), i| \r\n ems_string << \"EnergyManagementSystem:Sensor,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}SensibleClgJ,\" + \"\\n\"\r\n ems_string << \" #{value[:dxname]},\" + \"\\n\"\r\n ems_string << \" Cooling Coil Sensible Cooling Energy;\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n ems_string << \"WaterUse:Equipment,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUse, !- Name\" + \"\\n\"\r\n ems_string << \" Membrane HP Cooling, !- End-Use Subcategory\" + \"\\n\"\r\n ems_string << \" 0.003155, !- Peak Flow Rate {m3/s} = 3000 gal/hr\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule; !- Flow Rate Fraction Schedule Name\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n ems_string << \"Schedule:Constant,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule, !- Name\" + \"\\n\"\r\n ems_string << \" , !- Schedule Type Limits Name\" + \"\\n\"\r\n ems_string << \" 1; !- Hourly Value\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n ems_string << \"EnergyManagementSystem:Actuator,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseCtrl,\" + \"\\n\"\r\n ems_string << \" MembraneHP#{i+1}WaterUseSchedule,\" + \"\\n\"\r\n ems_string << \" Schedule:Constant,\" + \"\\n\"\r\n ems_string << \" Schedule Value;\" + \"\\n\"\r\n ems_string << \"\\n\" \r\n end\r\n ems_string << \"EnergyManagementSystem:ProgramCallingManager,\" + \"\\n\"\r\n ems_string << \" MembraneHPWaterUseProgramControl, !- Name\" + \"\\n\"\r\n ems_string << \" AfterPredictorBeforeHVACManagers, !- EnergyPlus Model Calling Point\" + \"\\n\"\r\n ems_string << \" MembraneHPWaterUseProgram; !- Program Name 1\" + \"\\n\"\r\n ems_string << \"\\n\"\r\n ems_string << \"EnergyManagementSystem:Program,\" + \"\\n\"\r\n ems_string << \" MembraneHPWaterUseProgram, !- Name\" + \"\\n\"\r\n ems_string << \" SET TimeStepsPerHr = #{timeStep}\" + \"\\n\"\r\n results.each_with_index do |(key, value), i|\r\n ems_string << \" SET MembraneHP#{i+1}SensibleClgTonHr = MembraneHP#{i+1}SensibleClgJ * 0.0000007898,\" + \"\\n\"\r\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGal = MembraneHP#{i+1}SensibleClgTonHr * 3.0,\" + \"\\n\"\r\n ems_string << \" SET MembraneHP#{i+1}SensibleWtrGalPerHr = MembraneHP#{i+1}SensibleWtrGal * TimeStepsPerHr,\" + \"\\n\"\r\n ems_string << \" SET MembraneHP#{i+1}WaterUseCtrl = MembraneHP#{i+1}SensibleWtrGalPerHr / 3000.0,\" + \"\\n\"\r\n end \r\n ems_string << \" SET UnusedLine = 0;\" + \"\\n\"\r\n \r\n #save EMS snippet\r\n runner.registerInfo(\"Saving ems_membrane_heat_pump_cooling_only file\")\r\n FileUtils.mkdir_p(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\")) unless Dir.exist?(File.dirname(\"ems_membrane_heat_pump_cooling_only.ems\"))\r\n File.open(\"ems_membrane_heat_pump_cooling_only.ems\", \"w\") do |f|\r\n f.write(ems_string)\r\n end\r\n \r\n #unique initial conditions based on\r\n runner.registerInitialCondition(\"The building has #{results.size} DX coils for which this measure is applicable.\")\r\n\r\n #reporting final condition of model\r\n runner.registerFinalCondition(\"The efficiency of the following coils was increased to SEER 26 to reflect the replacement of these coils with membrane heatpumps: #{results.keys}\")\r\n \r\n ems_path = '../MembraneHeatPumpCoolingOnlyEms/ems_membrane_heat_pump_cooling_only.ems'\r\n json_path = '../MembraneHeatPumpCoolingOnlyEms/ems_results.json'\r\n if File.exist? ems_path\r\n ems_string = File.read(ems_path)\r\n if File.exist? json_path\r\n json = JSON.parse(File.read(json_path))\r\n end\r\n else\r\n ems_path2 = Dir.glob('../../**/ems_membrane_heat_pump_cooling_only.ems')\r\n ems_path1 = ems_path2[0]\r\n json_path2 = Dir.glob('../../**/ems_results.json')\r\n json_path1 = json_path2[0]\r\n if ems_path2.size > 1\r\n runner.registerWarning(\"more than one ems_membrane_heat_pump_cooling_only.ems file found. Using first one found.\")\r\n end\r\n if !ems_path1.nil? \r\n if File.exist? ems_path1\r\n ems_string = File.read(ems_path1)\r\n if File.exist? json_path1\r\n json = JSON.parse(File.read(json_path1))\r\n else\r\n runner.registerError(\"ems_results.json file not located\") \r\n end \r\n else\r\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\")\r\n end \r\n else\r\n runner.registerError(\"ems_membrane_heat_pump_cooling_only.ems file not located\") \r\n end\r\n end\r\n if json.nil?\r\n runner.registerError(\"ems_results.json file not located\")\r\n return false\r\n end\r\n \r\n if json.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n return true\r\n end\r\n \r\n idf_file = OpenStudio::IdfFile::load(ems_string, 'EnergyPlus'.to_IddFileType).get\r\n runner.registerInfo(\"Adding EMS code to workspace\")\r\n workspace.addObjects(idf_file.objects)\r\n \r\n return true\r\n\r\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n #use the built-in error checking\n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n #assume the occ sensors will last the full analysis\n expected_life = 25\n \n #assign the user inputs to variables\n space_type_object = runner.getOptionalWorkspaceObjectChoiceValue(\"space_type\",user_arguments,model)\n percent_runtime_reduction = runner.getDoubleArgumentValue(\"percent_runtime_reduction\",user_arguments)\n material_and_installation_cost_per_space = runner.getDoubleArgumentValue(\"material_and_installation_cost_per_space\",user_arguments)\n\n #check the space_type for reasonableness and see if measure should run on space type or on the entire building\n apply_to_building = false\n space_type = nil\n if space_type_object.empty?\n handle = runner.getStringArgumentValue(\"space_type\",user_arguments)\n if handle.empty?\n runner.registerError(\"No space type was chosen.\")\n else\n runner.registerError(\"The selected space type with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n end\n return false\n else\n if not space_type_object.get.to_SpaceType.empty?\n space_type = space_type_object.get.to_SpaceType.get\n elsif not space_type_object.get.to_Building.empty?\n apply_to_building = true\n else\n runner.registerError(\"Script Error - argument not showing up as space type or building.\")\n return false\n end\n end\n \n #check arguments for reasonableness\n if percent_runtime_reduction >= 100\n runner.registerError(\"Percent runtime reduction must be less than 100.\")\n return false\n end\n\n #find all the original schedules (before occ sensors installed)\n original_lts_schedules = []\n if apply_to_building #apply to the whole building\n \n model.getLightss.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end\n else #apply to the a specific space type\n #do the lights assigned to the space type itself\n space_type.lights.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end\n #do the lights in each space of the selected space type\n space_type.spaces.each do |space|\n space.lights.each do |light_fixture|\n if light_fixture.schedule.is_initialized\n original_lts_schedules << light_fixture.schedule.get\n end\n end \n end\n end\n \n #make copies of all the original lights schedules, reduced to include occ sensor impact\n original_schs_new_schs = {}\n original_lts_schedules.uniq.each do |orig_sch|\n #TODO skip non-schedule-ruleset schedules\n \n #copy the original schedule\n new_sch = orig_sch.clone.to_ScheduleRuleset.get\n #reduce each value in each profile (except the design days) by the specified amount\n runner.registerInfo(\"Reducing values in '#{orig_sch.name}' schedule by #{percent_runtime_reduction}% to represent occ sensor installation.\")\n day_profiles = []\n day_profiles << new_sch.defaultDaySchedule\n new_sch.scheduleRules.each do |rule|\n day_profiles << rule.daySchedule\n end\n multiplier = (100 - percent_runtime_reduction)/100\n day_profiles.each do |day_profile|\n #runner.registerInfo(\"#{day_profile.name}\")\n times_vals = day_profile.times.zip(day_profile.values)\n #runner.registerInfo(\"original time/values = #{times_vals}\")\n times_vals.each do |time,val|\n day_profile.addValue(time, val * multiplier)\n end\n #runner.registerInfo(\"new time/values = #{day_profile.times.zip(day_profile.values)}\")\n end \n #log the relationship between the old sch and the new, reduced sch\n original_schs_new_schs[orig_sch] = new_sch\n #runner.registerInfo(\"***\")\n end\n \n #replace the old schedules with the new schedules\n spaces_sensors_added_to = []\n if apply_to_building #apply to the whole building\n runner.registerInfo(\"Adding occupancy sensors to whole building\")\n model.getLightss.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end\n else #apply to the a specific space type\n #do the lights assigned to the space type itself\n runner.registerInfo(\"Adding occupancy sensors to space type '#{space_type.name}'\")\n space_type.lights.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end\n #do the lights in each space of the selected space type\n space_type.spaces.each do |space|\n runner.registerInfo(\"Adding occupancy sensors to space '#{space.name}\")\n space.lights.each do |light_fixture|\n next if light_fixture.schedule.empty?\n lights_sch = light_fixture.schedule.get\n new_sch = original_schs_new_schs[lights_sch]\n if new_sch\n runner.registerInfo(\"Added occupancy sensor for '#{light_fixture.name}'\")\n light_fixture.setSchedule(new_sch)\n spaces_sensors_added_to << light_fixture.space\n end\n end \n end\n end \n \n #report if the measure is not applicable\n num_sensors_added = spaces_sensors_added_to.uniq.size\n if spaces_sensors_added_to.size == 0\n runner.registerAsNotApplicable(\"This measure is not applicable because there were no lights in the specified areas of the building.\")\n return true\n end\n \n #report initial condition\n runner.registerInitialCondition(\"The building has several areas where occupancy sensors could be used to reduce lighting energy by turning off the lights while no occupants are present.\") \n \n #add cost of adding occ sensors\n if material_and_installation_cost_per_space != 0\n cost = OpenStudio::Model::LifeCycleCost.createLifeCycleCost(\"Add #{material_and_installation_cost_per_space} Occ Sensors to the Building\", model.getBuilding, material_and_installation_cost_per_space * num_sensors_added, \"CostPerEach\", \"Construction\", expected_life, 0)\n if cost.empty?\n runner.registerError(\"Failed to add costs.\")\n end\n end \n \n #report final condition\n if apply_to_building\n runner.registerFinalCondition(\"Add occupancy sensors to #{num_sensors_added} spaces in the building. The total cost to perform this is $#{material_and_installation_cost_per_space.round} per space, for a total cost of $#{(material_and_installation_cost_per_space * num_sensors_added).round}\")\n else\n runner.registerFinalCondition(\"Add occupancy sensors to #{num_sensors_added} #{space_type.name} spaces in the building. The total cost to perform this is $#{material_and_installation_cost_per_space.round} per space, for a total cost of $#{(material_and_installation_cost_per_space * num_sensors_added).round}\")\n end\n \n return true\n \n end", "def run(model, runner, user_arguments)\r\n super(model, runner, user_arguments)\r\n\r\n #use the built-in error checking \r\n if not runner.validateUserArguments(arguments(model), user_arguments)\r\n return false\r\n end\r\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\r\n if run_measure == 0\r\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\r\n return true \r\n end\r\n \r\n require 'json'\r\n \r\n results = {}\r\n dx_name = []\r\n #get all DX coils in model\r\n dx_single = model.getCoilCoolingDXSingleSpeeds \r\n dx_two = model.getCoilCoolingDXTwoSpeeds\r\n dx_heat = model.getCoilHeatingDXSingleSpeeds\r\n \r\n if !dx_single.empty?\r\n dx_single.each do |dx|\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial COP: #{dx.ratedCOP.get}\")\r\n dx.setRatedCOP(OpenStudio::OptionalDouble.new(6.0))\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final COP: #{dx.ratedCOP.get}\")\r\n dx_name << dx.name.get\r\n end\r\n end\r\n if !dx_two.empty?\r\n dx_two.each do |dx|\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial High COP: #{dx.ratedHighSpeedCOP.get} Low COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx.setRatedHighSpeedCOP(6.0)\r\n dx.setRatedLowSpeedCOP(6.0)\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final High COP: #{dx.ratedHighSpeedCOP.get} Final COP: #{dx.ratedLowSpeedCOP.get}\")\r\n dx_name << dx.name.get\r\n end\r\n end\r\n if !dx_heat.empty?\r\n dx_heat.each do |dx|\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Initial COP: #{dx.ratedCOP}\")\r\n dx.setRatedCOP(6.0)\r\n runner.registerInfo(\"DX coil: #{dx.name.get} Final COP: #{dx.ratedCOP}\")\r\n dx_name << dx.name.get\r\n end\r\n end\r\n \r\n if dx_name.empty?\r\n runner.registerWarning(\"No DX coils are appropriate for this measure\")\r\n runner.registerAsNotApplicable(\"No DX coils are appropriate for this measure\")\r\n end\r\n \r\n #unique initial conditions based on\r\n runner.registerInitialCondition(\"The building has #{dx_name.size} DX coils for which this measure is applicable.\")\r\n\r\n #reporting final condition of model\r\n runner.registerFinalCondition(\"The COP of the following coils was increased to 6: #{dx_name}\")\r\n return true\r\n\r\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # assign the user inputs to variables\n retrofit_month = runner.getStringArgumentValue('retrofit_month', user_arguments).to_i\n retrofit_day = runner.getStringArgumentValue('retrofit_day', user_arguments).to_i\n\n # report initial condition of model\n runner.registerInitialCondition(\"Measure started successfully.\")\n\n # TODO: check the month and day for reasonableness\n runner.registerInfo(\"User entered retrofit month: #{retrofit_month}\")\n runner.registerInfo(\"User entered retrofit day: #{retrofit_day}\")\n\n prog_calling_manager = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n prog_calling_manager.setCallingPoint('BeginTimestepBeforePredictor')\n\n # Remove old and add new equip with EMS by spaces\n hash_space_epd = Hash.new\n v_spaces = model.getSpaces\n v_spaces.each do |space|\n current_space_equip = space.electricEquipment[0]\n unless current_space_equip.nil?\n\n # Get equipment power density for each space type\n new_space_epd = runner.getOptionalDoubleArgumentValue(\"new_#{space.name.to_s}_epd\", user_arguments)\n if new_space_epd.is_initialized\n hash_space_epd[\"new_#{space.name.to_s}_epd\"] = new_space_epd\n runner.registerInfo(\"User entered new electric equipment power density for #{space.name.to_s} is #{new_space_epd} W/m2\")\n # Set ems\n current_space_equip_def = current_space_equip.electricEquipmentDefinition\n equip_sch_name = current_space_equip.schedule.get.nameString\n equip_sch_ems_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')\n equip_sch_ems_sensor.setKeyName(equip_sch_name)\n runner.registerInfo(\"Delete old equip object for #{space.name}\")\n current_space_equip.remove\n\n new_equip = add_equip_space(space, current_space_equip_def)\n equip_level_w = new_space_epd.to_f * space.floorArea.to_f\n ems_equip_program = add_equip_ems(model, new_equip, equip_level_w, equip_sch_ems_sensor, retrofit_month, retrofit_day)\n prog_calling_manager.addProgram(ems_equip_program)\n runner.registerInfo(\"Add ems equipment control for #{space.name} succeeded.\")\n else\n # Get equipment power ratio for each space type\n new_space_ratio = runner.getDoubleArgumentValue(\"new_#{space.name.to_s}_ratio\", user_arguments)\n\n old_equip_sch = current_space_equip.schedule.get\n ems_equip_program = add_equip_ems_w_occ_var(model, current_space_equip, old_equip_sch, new_space_ratio, retrofit_month, retrofit_day)\n prog_calling_manager.addProgram(ems_equip_program)\n runner.registerInfo(\"Add ems equipment control for #{space.name} succeeded.\")\n # runner.registerInfo(\"Delete old equip object for #{space.name}\")\n # current_space_equip.remove\n end\n\n end\n end\n\n # Remove old and add new equip with EMS by space types\n hash_space_type_epd = Hash.new\n v_space_types = model.getSpaceTypes\n v_space_types.each do |space_type|\n current_spaces = space_type.spaces\n current_space_type_equip = space_type.electricEquipment[0]\n unless current_space_type_equip.nil?\n # Get equipment power density for each space type\n current_space_type_epd = runner.getStringArgumentValue(\"new_#{space_type.name.to_s}_epd\", user_arguments)\n hash_space_type_epd[\"new_#{space_type.name.to_s}_epd\"] = current_space_type_epd\n runner.registerInfo(\"User entered new electric equipment power density for #{space_type.name.to_s} is #{current_space_type_epd} W/m2\")\n\n # Set ems\n current_space_type_equip_def = current_space_type_equip.electricEquipmentDefinition\n current_space_type_sch_set = space_type.defaultScheduleSet.get\n current_space_type_equip_sch_set = current_space_type_sch_set.electricEquipmentSchedule.get\n\n equip_sch_name = current_space_type_equip_sch_set.nameString\n equip_sch_ems_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')\n equip_sch_ems_sensor.setKeyName(equip_sch_name)\n\n puts \"Delete old equip object for #{space_type.name}\"\n current_space_type_equip.remove\n\n current_spaces.each do |space|\n # Calculate equipemtn electric power for each space\n new_equip = add_equip_space_type(model, space, space_type, current_space_type_equip_def)\n equip_level_w = current_space_type_epd.to_f * space.floorArea.to_f\n ems_equip_program = add_equip_ems(model, new_equip, equip_level_w, equip_sch_ems_sensor, retrofit_month, retrofit_day)\n prog_calling_manager.addProgram(ems_equip_program)\n runner.registerInfo(\"Add ems equipment control for #{space.name} succeeded.\")\n end\n end\n end\n\n # echo the model updates back to the user\n runner.registerInfo(\"The electric equipment retrofit measure is applied.\")\n\n # report final condition of model\n runner.registerFinalCondition(\"Measure ended successfully.\")\n\n return true\n end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def args; end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n # initialize variables\n affected_space_types = []\n affected_flag = false\n power_tot = 0\n power_tot_new = 0\n control_factor = 0.05 #90.1-2010 Table 9.6.2\n\n # standards space types\n affected_space_types << \"BreakRoom\"\n affected_space_types << \"Conference\"\n affected_space_types << \"Office\"\n affected_space_types << \"Restroom\"\n affected_space_types << \"Stair\"\n\n # get model objects\n space_types = model.getSpaceTypes\n\n # DO STUFF\n #TODO account for zone multipliers?\n space_types.each do |st|\n\n std_spc_typ = st.standardsSpaceType.to_s\n area = st.floorArea\n people = st.getNumberOfPeople(area)\n power = st.getLightingPower(area, people)\n power_tot += power\n\n #calcualte LPD\n lpd_area = power / area\n lpd_people = power / people\n\n affected_space_types.each do |ast|\n\n if ast == std_spc_typ\n\n #calculate adjustment and new power\n power_adj = power * control_factor\n power_new = power - power_adj\n\n lpd_area_new = power_new / area\n lpd_people_new = power_new / people\n\n #set new power\n if st.lightingPowerPerFloorArea.is_initialized\n\n runner.registerInfo(\"Adjusting interior lighting power for space type: #{st.name}\")\n st.setLightingPowerPerFloorArea(lpd_area_new)\n\n lpd_area_ip = OpenStudio.convert(lpd_area,\"ft^2\",\"m^2\").get\n lpd_area_new_ip = OpenStudio.convert(lpd_area_new,\"ft^2\",\"m^2\").get\n lpd_area_change = (1 - (lpd_area_new / lpd_area)) * 100\n\n runner.registerInfo(\"=> Initial interior lighting power = #{lpd_area_ip.round(2)} W/ft2\")\n runner.registerInfo(\"=> Final interior lighting power = #{lpd_area_new_ip.round(2)} W/ft2\")\n runner.registerInfo(\"=> Interior lighting power reduction = #{lpd_area_change.round(0)}%\")\n\n elsif st.lightingPowerPerPerson.is_initialized\n\n runner.registerInfo(\"Adjusting interior lighting power for space type: #{st.name}\")\n st.setLightingPowerPerPerson(lpd_people_new)\n\n lpd_people_change = (1 - (lpd_people_new / lpd_people)) * 100\n\n runner.registerInfo(\"=> Initial interior lighting power = #{lpd_people} W/person\")\n runner.registerInfo(\"=> Final interior lighting power = #{lpd_people_new} W/person\")\n runner.registerInfo(\"=> Interior lighting power reduction = #{lpd_people_change.round(0)}%\")\n\n else\n\n runner.registerWarning(\"Lighting power is specified using Lighting Level (W) for affected space type: #{st.name}\")\n\n end #set new power\n\n affected_flag = true\n\n end\n\n end #affected space types\n\n # calculate new total lighting power\n power = st.getLightingPower(area, people)\n power_tot_new += power\n\n end #space types\n\n # report not applicable\n if affected_flag == false\n runner.registerAsNotApplicable(\"No affected space types found\")\n end\n\n # report initial condition\n runner.registerInitialCondition(\"Total interior lighting power = #{power_tot.round(0)} W\")\n\n # report final condition\n runner.registerFinalCondition(\"Total interior lighting power = #{power_tot_new.round(0)} W\")\n\n return true\n\n end", "def end(arg0)\n end", "def update!(**args)\n @elapsed_duration = args[:elapsed_duration] if args.key?(:elapsed_duration)\n @metrics = args[:metrics] if args.key?(:metrics)\n @step_count = args[:step_count] if args.key?(:step_count)\n end", "def duration=(_arg0); end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # assign the user inputs to variables\n args = get_argument_values(runner, arguments(model), user_arguments)\n\n measures_dir = File.absolute_path(File.join(File.dirname(__FILE__), '../../resources/hpxml-measures'))\n arg_names = []\n { 'BuildResidentialHPXML' => Constants.build_residential_hpxml_excludes,\n 'BuildResidentialScheduleFile' => Constants.build_residential_schedule_file_excludes }.each do |measure_name, measure_excludes|\n full_measure_path = File.join(measures_dir, measure_name, 'measure.rb')\n measure = get_measure_instance(full_measure_path)\n\n measure.arguments(model).each do |arg|\n next if measure_excludes.include? arg.name\n\n arg_names << arg.name.to_sym\n end\n end\n\n args_to_delete = args.keys - arg_names # these are the extra ones added in the arguments section\n\n # Conditioned floor area\n if args[:geometry_unit_cfa] == Constants.Auto\n cfas = { ['0-499', HPXML::ResidentialTypeSFD] => 298, # AHS 2021, 1 detached and mobile home weighted average\n ['0-499', HPXML::ResidentialTypeSFA] => 273, # AHS 2021, 1 detached and mobile home weighted average\n ['0-499', HPXML::ResidentialTypeApartment] => 322, # AHS 2021, multi-family weighted average\n ['500-749', HPXML::ResidentialTypeSFD] => 634, # AHS 2021, 1 detached and mobile home weighted average\n ['500-749', HPXML::ResidentialTypeSFA] => 625, # AHS 2021, 1 attached\n ['500-749', HPXML::ResidentialTypeApartment] => 623, # AHS 2021, multi-family weighted average\n ['750-999', HPXML::ResidentialTypeSFD] => 881, # AHS 2021, 1 detached and mobile home weighted average\n ['750-999', HPXML::ResidentialTypeSFA] => 872, # AHS 2021, 1 attached\n ['750-999', HPXML::ResidentialTypeApartment] => 854, # AHS 2021, multi-family weighted average\n ['1000-1499', HPXML::ResidentialTypeSFD] => 1228, # AHS 2021, 1 detached and mobile home weighted average\n ['1000-1499', HPXML::ResidentialTypeSFA] => 1207, # AHS 2021, 1 attached\n ['1000-1499', HPXML::ResidentialTypeApartment] => 1138, # AHS 2021, multi-family weighted average\n ['1500-1999', HPXML::ResidentialTypeSFD] => 1698, # AHS 2021, 1 detached and mobile home weighted average\n ['1500-1999', HPXML::ResidentialTypeSFA] => 1678, # AHS 2021, 1 attached\n ['1500-1999', HPXML::ResidentialTypeApartment] => 1682, # AHS 2021, multi-family weighted average\n ['2000-2499', HPXML::ResidentialTypeSFD] => 2179, # AHS 2021, 1 detached and mobile home weighted average\n ['2000-2499', HPXML::ResidentialTypeSFA] => 2152, # AHS 2021, 1 attached\n ['2000-2499', HPXML::ResidentialTypeApartment] => 2115, # AHS 2021, multi-family weighted average\n ['2500-2999', HPXML::ResidentialTypeSFD] => 2678, # AHS 2021, 1 detached and mobile home weighted average\n ['2500-2999', HPXML::ResidentialTypeSFA] => 2663, # AHS 2021, 1 attached\n ['2500-2999', HPXML::ResidentialTypeApartment] => 2648, # AHS 2021, multi-family weighted average\n ['3000-3999', HPXML::ResidentialTypeSFD] => 3310, # AHS 2021, 1 detached and mobile home weighted average\n ['3000-3999', HPXML::ResidentialTypeSFA] => 3228, # AHS 2021, 1 attached\n ['3000-3999', HPXML::ResidentialTypeApartment] => 3171, # AHS 2021, multi-family weighted average\n ['4000+', HPXML::ResidentialTypeSFD] => 5587, # AHS 2021, 1 detached and mobile home weighted average\n ['4000+', HPXML::ResidentialTypeSFA] => 7414, # AHS 2019, 1 attached\n ['4000+', HPXML::ResidentialTypeApartment] => 6348 } # AHS 2021, 4,000 or more all unit average\n cfa = cfas[[args[:geometry_unit_cfa_bin], args[:geometry_unit_type]]]\n if cfa.nil?\n runner.registerError(\"ResStockArguments: Could not look up conditioned floor area for '#{args[:geometry_unit_cfa_bin]}' and '#{args[:geometry_unit_type]}'.\")\n return false\n end\n args[:geometry_unit_cfa] = Float(cfa)\n else\n args[:geometry_unit_cfa] = Float(args[:geometry_unit_cfa])\n end\n\n # Vintage\n if args[:vintage].is_initialized\n args[:year_built] = Integer(Float(args[:vintage].get.gsub(/[^0-9]/, ''))) # strip non-numeric\n end\n\n # Num Occupants\n if args[:geometry_unit_num_occupants].to_s == Constants.Auto\n args[:geometry_unit_num_occupants] = Geometry.get_occupancy_default_num(args[:geometry_unit_num_bedrooms])\n else\n args[:geometry_unit_num_occupants] = Integer(args[:geometry_unit_num_occupants].to_s)\n end\n\n # Plug Loads\n args[:misc_plug_loads_television_annual_kwh] = 0.0 # \"other\" now accounts for television\n args[:misc_plug_loads_television_usage_multiplier] = 0.0 # \"other\" now accounts for television\n args[:misc_plug_loads_other_usage_multiplier] = Float(args[:misc_plug_loads_other_usage_multiplier].to_s) * args[:misc_plug_loads_other_2_usage_multiplier]\n args[:misc_plug_loads_well_pump_usage_multiplier] = Float(args[:misc_plug_loads_well_pump_usage_multiplier].to_s) * args[:misc_plug_loads_well_pump_2_usage_multiplier]\n args[:misc_plug_loads_vehicle_usage_multiplier] = Float(args[:misc_plug_loads_vehicle_usage_multiplier].to_s) * args[:misc_plug_loads_vehicle_2_usage_multiplier]\n\n if args[:misc_plug_loads_other_annual_kwh].to_s == Constants.Auto\n if [HPXML::ResidentialTypeSFD].include?(args[:geometry_unit_type])\n args[:misc_plug_loads_other_annual_kwh] = 1146.95 + 296.94 * args[:geometry_unit_num_occupants] + 0.3 * args[:geometry_unit_cfa] # RECS 2015\n elsif [HPXML::ResidentialTypeSFA].include?(args[:geometry_unit_type])\n args[:misc_plug_loads_other_annual_kwh] = 1395.84 + 136.53 * args[:geometry_unit_num_occupants] + 0.16 * args[:geometry_unit_cfa] # RECS 2015\n elsif [HPXML::ResidentialTypeApartment].include?(args[:geometry_unit_type])\n args[:misc_plug_loads_other_annual_kwh] = 875.22 + 184.11 * args[:geometry_unit_num_occupants] + 0.38 * args[:geometry_unit_cfa] # RECS 2015\n end\n end\n\n # PV\n if args[:pv_system_module_type] != 'none'\n args[:pv_system_num_bedrooms_served] = Integer(args[:geometry_unit_num_bedrooms])\n else\n args[:pv_system_num_bedrooms_served] = 0\n end\n\n # Setpoints\n weekday_heating_setpoints = [args[:hvac_control_heating_weekday_setpoint_temp]] * 24\n weekend_heating_setpoints = [args[:hvac_control_heating_weekend_setpoint_temp]] * 24\n\n weekday_cooling_setpoints = [args[:hvac_control_cooling_weekday_setpoint_temp]] * 24\n weekend_cooling_setpoints = [args[:hvac_control_cooling_weekend_setpoint_temp]] * 24\n\n hvac_control_heating_weekday_setpoint_offset_magnitude = args[:hvac_control_heating_weekday_setpoint_offset_magnitude]\n hvac_control_heating_weekday_setpoint_schedule = args[:hvac_control_heating_weekday_setpoint_schedule].split(',').map { |i| Float(i) }\n weekday_heating_setpoints = modify_setpoint_schedule(weekday_heating_setpoints, hvac_control_heating_weekday_setpoint_offset_magnitude, hvac_control_heating_weekday_setpoint_schedule)\n\n hvac_control_heating_weekend_setpoint_offset_magnitude = args[:hvac_control_heating_weekend_setpoint_offset_magnitude]\n hvac_control_heating_weekend_setpoint_schedule = args[:hvac_control_heating_weekend_setpoint_schedule].split(',').map { |i| Float(i) }\n weekend_heating_setpoints = modify_setpoint_schedule(weekend_heating_setpoints, hvac_control_heating_weekend_setpoint_offset_magnitude, hvac_control_heating_weekend_setpoint_schedule)\n\n hvac_control_cooling_weekday_setpoint_offset_magnitude = args[:hvac_control_cooling_weekday_setpoint_offset_magnitude]\n hvac_control_cooling_weekday_setpoint_schedule = args[:hvac_control_cooling_weekday_setpoint_schedule].split(',').map { |i| Float(i) }\n weekday_cooling_setpoints = modify_setpoint_schedule(weekday_cooling_setpoints, hvac_control_cooling_weekday_setpoint_offset_magnitude, hvac_control_cooling_weekday_setpoint_schedule)\n\n hvac_control_cooling_weekend_setpoint_offset_magnitude = args[:hvac_control_cooling_weekend_setpoint_offset_magnitude]\n hvac_control_cooling_weekend_setpoint_schedule = args[:hvac_control_cooling_weekend_setpoint_schedule].split(',').map { |i| Float(i) }\n weekend_cooling_setpoints = modify_setpoint_schedule(weekend_cooling_setpoints, hvac_control_cooling_weekend_setpoint_offset_magnitude, hvac_control_cooling_weekend_setpoint_schedule)\n\n args[:hvac_control_heating_weekday_setpoint] = weekday_heating_setpoints.join(', ')\n args[:hvac_control_heating_weekend_setpoint] = weekend_heating_setpoints.join(', ')\n args[:hvac_control_cooling_weekday_setpoint] = weekday_cooling_setpoints.join(', ')\n args[:hvac_control_cooling_weekend_setpoint] = weekend_cooling_setpoints.join(', ')\n\n # Seasons\n if args[:use_auto_heating_season]\n args[:hvac_control_heating_season_period] = HPXML::BuildingAmerica\n end\n\n if args[:use_auto_cooling_season]\n args[:hvac_control_cooling_season_period] = HPXML::BuildingAmerica\n end\n\n # Flue or Chimney\n if (args[:heating_system_has_flue_or_chimney] == 'false') &&\n (args[:heating_system_2_has_flue_or_chimney] == 'false') &&\n (args[:water_heater_has_flue_or_chimney] == 'false')\n args[:air_leakage_has_flue_or_chimney_in_conditioned_space] = false\n elsif (args[:heating_system_type] != 'none' && args[:heating_system_has_flue_or_chimney] == 'true') ||\n (args[:heating_system_2_type] != 'none' && args[:heating_system_2_has_flue_or_chimney] == 'true') ||\n (args[:water_heater_type] != 'none' && args[:water_heater_has_flue_or_chimney] == 'true')\n args[:air_leakage_has_flue_or_chimney_in_conditioned_space] = true\n end\n\n # HVAC Secondary\n if args[:heating_system_2_type] != 'none'\n if args[:heating_system_type] != 'none'\n if ((args[:heating_system_fraction_heat_load_served] + args[:heating_system_2_fraction_heat_load_served]) > 1.0)\n info_msg = \"Adjusted fraction of heat load served by the primary heating system (#{args[:heating_system_fraction_heat_load_served]}\"\n args[:heating_system_fraction_heat_load_served] = 1.0 - args[:heating_system_2_fraction_heat_load_served]\n info_msg += \" to #{args[:heating_system_fraction_heat_load_served]}) to allow for a secondary heating system (#{args[:heating_system_2_fraction_heat_load_served]}).\"\n runner.registerInfo(info_msg)\n end\n elsif args[:heat_pump_type] != 'none'\n if ((args[:heat_pump_fraction_heat_load_served] + args[:heating_system_2_fraction_heat_load_served]) > 1.0)\n info_msg = \"Adjusted fraction of heat load served by the primary heating system (#{args[:heat_pump_fraction_heat_load_served]}\"\n args[:heat_pump_fraction_heat_load_served] = 1.0 - args[:heating_system_2_fraction_heat_load_served]\n info_msg += \" to #{args[:heat_pump_fraction_heat_load_served]}) to allow for a secondary heating system (#{args[:heating_system_2_fraction_heat_load_served]}).\"\n runner.registerInfo(info_msg)\n end\n end\n end\n\n # HVAC Faults\n if args[:heating_system_rated_cfm_per_ton].is_initialized && args[:heating_system_actual_cfm_per_ton].is_initialized\n args[:heating_system_airflow_defect_ratio] = (args[:heating_system_actual_cfm_per_ton].get - args[:heating_system_rated_cfm_per_ton].get) / args[:heating_system_rated_cfm_per_ton].get\n end\n\n if args[:cooling_system_rated_cfm_per_ton].is_initialized && args[:cooling_system_actual_cfm_per_ton].is_initialized\n args[:cooling_system_airflow_defect_ratio] = (args[:cooling_system_actual_cfm_per_ton].get - args[:cooling_system_rated_cfm_per_ton].get) / args[:cooling_system_rated_cfm_per_ton].get\n end\n\n if args[:cooling_system_frac_manufacturer_charge].is_initialized\n args[:cooling_system_charge_defect_ratio] = args[:cooling_system_frac_manufacturer_charge].get - 1.0\n end\n\n if args[:heat_pump_rated_cfm_per_ton].is_initialized && args[:heat_pump_actual_cfm_per_ton].is_initialized\n args[:heat_pump_airflow_defect_ratio] = (args[:heat_pump_actual_cfm_per_ton].get - args[:heat_pump_rated_cfm_per_ton].get) / args[:cooling_system_rated_cfm_per_ton].get\n end\n\n if args[:heat_pump_frac_manufacturer_charge].is_initialized\n args[:heat_pump_charge_defect_ratio] = args[:heat_pump_frac_manufacturer_charge].get - 1.0\n end\n\n # Error check geometry inputs\n corridor_width = args[:geometry_corridor_width]\n corridor_position = args[:geometry_corridor_position].to_s\n\n if (corridor_width == 0) && (corridor_position != 'None')\n corridor_position = 'None'\n end\n if corridor_position == 'None'\n corridor_width = 0\n end\n if corridor_width < 0\n runner.registerError('ResStockArguments: Invalid corridor width entered.')\n return false\n end\n\n # Adiabatic Walls\n args[:geometry_unit_left_wall_is_adiabatic] = false\n args[:geometry_unit_right_wall_is_adiabatic] = false\n args[:geometry_unit_front_wall_is_adiabatic] = false\n args[:geometry_unit_back_wall_is_adiabatic] = false\n\n # Map corridor arguments to adiabatic walls and shading\n n_floors = Float(args[:geometry_num_floors_above_grade].to_s)\n if [HPXML::ResidentialTypeApartment, HPXML::ResidentialTypeSFA].include? args[:geometry_unit_type]\n n_units = Float(args[:geometry_building_num_units].to_s)\n horiz_location = args[:geometry_unit_horizontal_location].to_s\n aspect_ratio = Float(args[:geometry_unit_aspect_ratio].to_s)\n\n if args[:geometry_unit_type] == HPXML::ResidentialTypeApartment\n n_units_per_floor = n_units / n_floors\n if n_units_per_floor >= 4 && (corridor_position == 'Double Exterior' || corridor_position == 'None')\n has_rear_units = true\n args[:geometry_unit_back_wall_is_adiabatic] = true\n elsif n_units_per_floor >= 4 && (corridor_position == 'Double-Loaded Interior')\n has_rear_units = true\n args[:geometry_unit_front_wall_is_adiabatic] = true\n elsif (n_units_per_floor == 2) && (horiz_location == 'None') && (corridor_position == 'Double Exterior' || corridor_position == 'None')\n has_rear_units = true\n args[:geometry_unit_back_wall_is_adiabatic] = true\n elsif (n_units_per_floor == 2) && (horiz_location == 'None') && (corridor_position == 'Double-Loaded Interior')\n has_rear_units = true\n args[:geometry_unit_front_wall_is_adiabatic] = true\n elsif corridor_position == 'Single Exterior (Front)'\n has_rear_units = false\n args[:geometry_unit_front_wall_is_adiabatic] = false\n else\n has_rear_units = false\n args[:geometry_unit_front_wall_is_adiabatic] = false\n end\n\n # Error check MF & SFA geometry\n if !has_rear_units && ((corridor_position == 'Double-Loaded Interior') || (corridor_position == 'Double Exterior'))\n corridor_position = 'Single Exterior (Front)'\n runner.registerWarning(\"Specified incompatible corridor; setting corridor position to '#{corridor_position}'.\")\n end\n\n # Model exterior corridors as overhangs\n if (corridor_position.include? 'Exterior') && corridor_width > 0\n args[:overhangs_front_depth] = corridor_width\n args[:overhangs_front_distance_to_top_of_window] = 1\n end\n\n elsif args[:geometry_unit_type] == HPXML::ResidentialTypeSFA\n n_floors = 1.0\n n_units_per_floor = n_units\n has_rear_units = false\n end\n\n if has_rear_units\n unit_width = n_units_per_floor / 2\n else\n unit_width = n_units_per_floor\n end\n if (unit_width <= 1) && (horiz_location != 'None')\n runner.registerWarning(\"No #{horiz_location} location exists, setting horizontal location to 'None'\")\n horiz_location = 'None'\n end\n if (unit_width > 1) && (horiz_location == 'None')\n runner.registerError('ResStockArguments: Specified incompatible horizontal location for the corridor and unit configuration.')\n return false\n end\n if (unit_width <= 2) && (horiz_location == 'Middle')\n runner.registerError('ResStockArguments: Invalid horizontal location entered, no middle location exists.')\n return false\n end\n\n # Infiltration adjustment for SFA/MF units\n # Calculate exposed wall area ratio for the unit (unit exposed wall area\n # divided by average unit exposed wall area)\n if (n_units_per_floor <= 2) || (n_units_per_floor == 4 && has_rear_units) # No middle unit(s)\n exposed_wall_area_ratio = 1.0 # all units have same exterior wall area\n else # Has middle unit(s)\n if has_rear_units\n n_end_units = 4 * n_floors\n n_mid_units = n_units - n_end_units\n n_bldg_fronts_backs = n_end_units + n_mid_units\n n_bldg_sides = n_end_units\n else\n n_end_units = 2 * n_floors\n n_mid_units = n_units - n_end_units\n n_bldg_fronts_backs = n_end_units * 2 + n_mid_units * 2\n n_bldg_sides = n_end_units\n end\n if has_rear_units\n n_unit_fronts_backs = 1\n else\n n_unit_fronts_backs = 2\n end\n if ['Middle'].include? horiz_location\n n_unit_sides = 0\n elsif ['Left', 'Right'].include? horiz_location\n n_unit_sides = 1\n end\n n_bldg_sides_equivalent = n_bldg_sides + n_bldg_fronts_backs * aspect_ratio\n n_unit_sides_equivalent = n_unit_sides + n_unit_fronts_backs * aspect_ratio\n exposed_wall_area_ratio = n_unit_sides_equivalent / (n_bldg_sides_equivalent / n_units)\n end\n\n # Apply adjustment to infiltration value\n args[:air_leakage_value] *= exposed_wall_area_ratio\n\n if horiz_location == 'Left'\n args[:geometry_unit_right_wall_is_adiabatic] = true\n elsif horiz_location == 'Middle'\n args[:geometry_unit_left_wall_is_adiabatic] = true\n args[:geometry_unit_right_wall_is_adiabatic] = true\n elsif horiz_location == 'Right'\n args[:geometry_unit_left_wall_is_adiabatic] = true\n end\n end\n\n # Infiltration Reduction\n if args[:air_leakage_percent_reduction].is_initialized\n args[:air_leakage_value] *= (1.0 - args[:air_leakage_percent_reduction].get / 100.0)\n end\n\n # Num Floors\n if args[:geometry_unit_type] == HPXML::ResidentialTypeApartment\n args[:geometry_unit_num_floors_above_grade] = 1\n else\n args[:geometry_unit_num_floors_above_grade] = Integer(args[:geometry_num_floors_above_grade])\n end\n\n # Adiabatic Floor/Ceiling\n if args[:geometry_unit_level].is_initialized\n if args[:geometry_unit_level].get == 'Bottom'\n if args[:geometry_num_floors_above_grade] > 1 # this could be \"bottom\" of a 1-story building\n args[:geometry_attic_type] = HPXML::AtticTypeBelowApartment\n end\n elsif args[:geometry_unit_level].get == 'Middle'\n args[:geometry_foundation_type] = HPXML::FoundationTypeAboveApartment\n args[:geometry_attic_type] = HPXML::AtticTypeBelowApartment\n elsif args[:geometry_unit_level].get == 'Top'\n args[:geometry_foundation_type] = HPXML::FoundationTypeAboveApartment\n end\n end\n\n # Wall Assembly R-Value\n args[:wall_assembly_r] += args[:exterior_finish_r]\n\n if args[:wall_continuous_exterior_r].is_initialized\n args[:wall_assembly_r] += args[:wall_continuous_exterior_r].get\n end\n\n # Rim Joist Assembly R-Value\n rim_joist_assembly_r = 0\n if Float(args[:geometry_rim_joist_height].to_s) > 0\n drywall_assembly_r = 0.9\n uninsulated_wall_assembly_r = 3.4\n\n assembly_exterior_r = args[:exterior_finish_r] + args[:rim_joist_continuous_exterior_r]\n\n if args[:rim_joist_continuous_interior_r] > 0 && args[:rim_joist_assembly_interior_r] > 0\n # rim joist assembly = siding + half continuous interior insulation + half rim joist assembly - drywall\n # (rim joist assembly = nominal cavity + 1/2 in sheathing + 1/2 in drywall)\n assembly_interior_r = (args[:rim_joist_continuous_interior_r] + uninsulated_wall_assembly_r - drywall_assembly_r) / 2.0 # parallel to floor joists\n assembly_interior_r += (args[:rim_joist_assembly_interior_r]) / 2.0 # derated\n elsif args[:rim_joist_continuous_interior_r] > 0 || args[:rim_joist_assembly_interior_r] > 0\n runner.registerError('ResStockArguments: For rim joist interior insulation, must provide both continuous and assembly R-values.')\n return false\n else # uninsulated interior\n # rim joist assembly = siding + continuous foundation insulation + uninsulated wall - drywall\n # (uninsulated wall is nominal cavity + 1/2 in sheathing + 1/2 in drywall)\n assembly_interior_r = uninsulated_wall_assembly_r - drywall_assembly_r\n end\n\n rim_joist_assembly_r = assembly_exterior_r + assembly_interior_r\n end\n args[:rim_joist_assembly_r] = rim_joist_assembly_r\n\n # Heat Pump Backup\n if args[:heat_pump_backup_use_existing_system].is_initialized\n args_to_delete.delete('heat_pump_backup_use_existing_system')\n end\n\n args.each do |arg_name, arg_value|\n begin\n if arg_value.is_initialized\n arg_value = arg_value.get\n else\n next\n end\n rescue\n end\n\n if args_to_delete.include?(arg_name) || (arg_value == Constants.Auto)\n arg_value = '' # don't assign these to BuildResidentialHPXML or BuildResidentialScheduleFile\n end\n\n register_value(runner, arg_name.to_s, arg_value)\n end\n\n return true\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n # Make integer arg to run measure [1 is run, 0 is no run]\n run_measure = OpenStudio::Ruleset::OSArgument::makeIntegerArgument(\"run_measure\",true)\n run_measure.setDisplayName(\"Run Measure\")\n run_measure.setDescription(\"integer argument to run measure [1 is run, 0 is no run]\")\n run_measure.setDefaultValue(1)\n args << run_measure\n\n # make an argument for fractional value during specified time\n pct_red = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"pct_red\",true)\n pct_red.setDisplayName(\"Percent Daytime Lighting Runtime Fraction Reduction\")\n pct_red.setDefaultValue(50.0)\n args << pct_red\n\n # start time\n start_hr = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"start_hr\",true)\n start_hr.setDisplayName(\"Time to start reduction\")\n start_hr.setUnits(\"24hr, use decimal for sub hour\")\n start_hr.setDefaultValue(9.0)\n args << start_hr\n\n # end time\n end_hr = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"end_hr\",true)\n end_hr.setDisplayName(\"Time to end reduction\")\n end_hr.setUnits(\"24hr, use decimal for sub hour\")\n end_hr.setDefaultValue(16.0)\n args << end_hr\n\n return args\n end", "def deco_args; end", "def calculated; end", "def finished=(_arg0); end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # define if the measure should run to a specific time period or whole day\n apply_to_time = true\n\n # assign the user inputs to variables\n object = runner.getOptionalWorkspaceObjectChoiceValue('space_type', user_arguments, model)\n single_space_type = runner.getDoubleArgumentValue('single_space_type', user_arguments)\n occupied_space_type = runner.getDoubleArgumentValue('occupied_space_type', user_arguments)\n unoccupied_space_type = runner.getDoubleArgumentValue('unoccupied_space_type', user_arguments)\n starttime_winter2 = runner.getStringArgumentValue('starttime_winter2', user_arguments)\n endtime_winter2 = runner.getStringArgumentValue('endtime_winter2', user_arguments)\n starttime_winter1 = runner.getStringArgumentValue('starttime_winter1', user_arguments)\n endtime_winter1 = runner.getStringArgumentValue('endtime_winter1', user_arguments)\n starttime_summer = runner.getStringArgumentValue('starttime_summer', user_arguments)\n endtime_summer = runner.getStringArgumentValue('endtime_summer', user_arguments)\n auto_date = runner.getBoolArgumentValue('auto_date', user_arguments)\n alt_periods = runner.getBoolArgumentValue('alt_periods', user_arguments)\n demo_cost_initial_const=false\n\n winter_start_month1 = 1\n winter_end_month1 = 5\n summer_start_month = 6\n summer_end_month = 9\n winter_start_month2 = 10\n winter_end_month2 = 12\n\n######### GET CLIMATE ZONES ################\n if auto_date\n ashraeClimateZone = ''\n #climateZoneNUmber = ''\n climateZones = model.getClimateZones\n climateZones.climateZones.each do |climateZone|\n if climateZone.institution == 'ASHRAE'\n ashraeClimateZone = climateZone.value\n runner.registerInfo(\"Using ASHRAE Climate zone #{ashraeClimateZone}.\")\n end\n end\n\n if ashraeClimateZone == '' # should this be not applicable or error?\n runner.registerError(\"Please assign an ASHRAE Climate Zone to your model using the site tab in the OpenStudio application. The measure can't make AEDG recommendations without this information.\")\n return false # note - for this to work need to check for false in measure.rb and add return false there as well.\n # else\n # climateZoneNumber = ashraeClimateZone.split(//).first\n end\n # #runner.registerInfo(\"CLIMATE ZONE #{ashraeClimateZone}. Right now does not do anything.\")\n # if !['1', '2', '3', '4', '5', '6', '7', '8'].include? climateZoneNumber\n # runner.registerError('ASHRAE climate zone number is not within expected range of 1 to 8.')\n # return false # note - for this to work need to check for false in measure.rb and add return false there as well.\n # end\n\n if alt_periods\n if ashraeClimateZone == '3A'\n starttime_summer = '18:01:00'\n endtime_summer = '21:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '4A'\n starttime_summer = '18:01:00'\n endtime_summer = '21:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5A'\n starttime_summer = '14:01:00'\n endtime_summer = '17:59:00'\n starttime_winter1 = '18:01:00'\n endtime_winter1 = '21:59:00'\n starttime_winter2 = '18:01:00'\n endtime_winter2 = '21:59:00'\n elsif ashraeClimateZone == '6A'\n starttime_summer = '13:01:00'\n endtime_summer = '16:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n end\n else\n if ashraeClimateZone == '2A'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '2B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '3A'\n starttime_summer = '19:01:00'\n endtime_summer = '22:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '3B'\n starttime_summer = '18:01:00'\n endtime_summer = '21:59:00'\n starttime_winter1 = '19:01:00'\n endtime_winter1 = '22:59:00'\n starttime_winter2 = '19:01:00'\n endtime_winter2 = '22:59:00'\n elsif ashraeClimateZone == '3C'\n starttime_summer = '19:01:00'\n endtime_summer = '22:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '4A'\n starttime_summer = '12:01:00'\n endtime_summer = '15:59:00'\n starttime_winter1 = '16:01:00'\n endtime_winter1 = '19:59:00'\n starttime_winter2 = '16:01:00'\n endtime_winter2 = '19:59:00'\n elsif ashraeClimateZone == '4B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '4C'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5A'\n starttime_summer = '20:01:00'\n endtime_summer = '23:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '5C'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '6A'\n starttime_summer = '16:01:00'\n endtime_summer = '19:59:00'\n starttime_winter1 = '18:01:00'\n endtime_winter1 = '21:59:00'\n starttime_winter2 = '18:01:00'\n endtime_winter2 = '21:59:00'\n elsif ashraeClimateZone == '6B'\n starttime_summer = '17:01:00'\n endtime_summer = '20:59:00'\n starttime_winter1 = '17:01:00'\n endtime_winter1 = '20:59:00'\n starttime_winter2 = '17:01:00'\n endtime_winter2 = '20:59:00'\n elsif ashraeClimateZone == '7A'\n starttime_summer = '16:01:00'\n endtime_summer = '19:59:00'\n starttime_winter1 = '18:01:00'\n endtime_winter1 = '21:59:00'\n starttime_winter2 = '18:01:00'\n endtime_winter2 = '21:59:00'\n end\n end\n end \n\n # check the lighting power reduction percentages and for reasonableness\n if occupied_space_type > 100\n runner.registerError('Please Enter a Value less than or equal to 100 for the Electric Equipment Power Reduction Percentage.')\n return false\n elsif occupied_space_type == 0\n runner.registerInfo('No Electric Equipment power adjustment requested, but some life cycle costs may still be affected.')\n elsif (occupied_space_type < 1) && (occupied_space_type > -1)\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{occupied_space_type} percent is abnormally low.\")\n elsif occupied_space_type > 90\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{occupied_space_type} percent is abnormally high.\")\n elsif occupied_space_type < 0\n runner.registerInfo('The requested value for Electric Equipment power reduction percentage was negative. This will result in an increase in Electric Equipment power.')\n end\n\n # check the equipment_power_reduction_percent and for reasonableness\n if unoccupied_space_type > 100\n runner.registerError('Please Enter a Value less than or equal to 100 for the Electric Equipment Power Reduction Percentage.')\n return false\n elsif unoccupied_space_type == 0\n runner.registerInfo('No Electric Equipment power adjustment requested, but some life cycle costs may still be affected.')\n elsif (unoccupied_space_type < 1) && (unoccupied_space_type > -1)\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{unoccupied_space_type} percent is abnormally low.\")\n elsif unoccupied_space_type > 90\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{unoccupied_space_type} percent is abnormally high.\")\n elsif unoccupied_space_type < 0\n runner.registerInfo('The requested value for Electric Equipment power reduction percentage was negative. This will result in an increase in Electric Equipment power.')\n end\n\n # check the equipment_power_reduction_percent and for reasonableness\n if single_space_type > 100\n runner.registerError('Please Enter a Value less than or equal to 100 for the Electric Equipment Power Reduction Percentage.')\n return false\n elsif single_space_type == 0\n runner.registerInfo('No Electric Equipment power adjustment requested, but some life cycle costs may still be affected.')\n elsif (single_space_type < 1) && (single_space_type > -1)\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{single_space_type} percent is abnormally low.\")\n elsif single_space_type > 90\n runner.registerWarning(\"A Electric Equipment Power Reduction Percentage of #{single_space_type} percent is abnormally high.\")\n elsif single_space_type < 0\n runner.registerInfo('The requested value for Electric Equipment power reduction percentage was negative. This will result in an increase in Electric Equipment power.')\n end\n\n # check the time periods for reasonableness\n if (starttime_winter1.to_f > endtime_winter1.to_f) && (starttime_winter2.to_f > endtime_winter2.to_f) && (starttime_summer.to_f > endtime_summer.to_f)\n runner.registerError('The end time should be larger than the start time.')\n return false\n end\n\n # check the space_type for reasonableness\n space_type = nil\n if object.empty?\n handle = runner.getStringArgumentValue('space_type', user_arguments)\n if handle.empty?\n runner.registerError('No space type was chosen.')\n else\n runner.registerError(\"The selected space type with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n end\n return false\n else\n if !object.get.to_SpaceType.empty?\n space_type = object.get.to_SpaceType.get\n elsif !object.get.to_Building.empty?\n apply_to_building = true\n else\n runner.registerError('Script Error - argument not showing up as space type or building.')\n return false\n end\n end\n\n\n ############################################\n\n # assign the time duration when DR strategy is applied, from shift_time1 to shift_time2, only applied when apply_to_time is ture\n shift_time1 = OpenStudio::Time.new(starttime_winter1)\n shift_time2 = OpenStudio::Time.new(endtime_winter1)\n shift_time3 = OpenStudio::Time.new(0, 24, 0, 0)\n shift_time4 = OpenStudio::Time.new(starttime_summer)\n shift_time5 = OpenStudio::Time.new(endtime_summer)\n shift_time6 = OpenStudio::Time.new(starttime_winter2)\n shift_time7 = OpenStudio::Time.new(endtime_winter2)\n \n \n # get space types in model\n if apply_to_building\n space_types = model.getSpaceTypes\n else\n space_types = []\n space_types << space_type # only run on a single space type\n end\n\n # make a hash of old defs and new equipments and luminaire defs\n cloned_equi_defs = {}\n # loop through space types\n space_types.each do |space_type|\n\n equi_set_schs = {}\n if apply_to_building # measure will be applied differently to space types, based on whether the space type is occupied\n if !space_type.people.empty?\n equipment_power_reduction_percent = 1 - (occupied_space_type/100)\n else\n equipment_power_reduction_percent = 1 - (unoccupied_space_type/100)\n end\n runner.registerInitialCondition(\"Equipment power will be reduced by #{occupied_space_type}% in occupied spaces, and reduced by #{unoccupied_space_type}% in unoccupied spaces\")\n\n else\n equipment_power_reduction_percent = 1 - (single_space_type/100) # measure will be applied evenly to all zones\n runner.registerInitialCondition(\"Equipment power will be reduced by #{single_space_type}% to '#{space_type.name}'.\")\n end\n\n space_type_equipments = space_type.electricEquipment\n space_type_equipments.each do |space_type_equipment|\n #clone of not already in hash\n equi_set_sch = space_type_equipment.schedule\n if !equi_set_sch.empty?\n # clone of not already in hash\n if equi_set_schs.key?(equi_set_sch.get.name.to_s)\n new_equi_set_sch = equi_set_schs[equi_set_sch.get.name.to_s]\n else\n new_equi_set_sch = equi_set_sch.get.clone(model)\n new_equi_set_sch = new_equi_set_sch.to_Schedule.get\n new_equi_set_sch_name = new_equi_set_sch.setName(\"#{new_equi_set_sch.name} adjusted #{equipment_power_reduction_percent}\")\n # add to the hash\n equi_set_schs[new_equi_set_sch.name.to_s] = new_equi_set_sch\n end\n # hook up clone to equipment\n \n if space_type_equipment.name.to_s != \"OfficeLarge Data Center Elec Equip\" && space_type_equipment.name.to_s != \"OfficeLarge Main Data Center Elec Equip\"\n space_type_equipment.setSchedule(new_equi_set_sch)\n runner.registerInfo(\"#{space_type_equipment.name} has a new electric equipment schedule\")\n end\n else\n runner.registerWarning(\"#{space_type.equipments.name} doesn't have a schedule.\")\n end\n end\n \n if apply_to_time\n runner.registerFinalCondition(\" equipment power is reduced from #{shift_time1} to #{shift_time2}.\")\n runner.registerFinalCondition(\" equipment power is reduced from #{shift_time4} to #{shift_time5} during special between month #{summer_start_month} and #{summer_end_month}\")\n else\n runner.registerFinalCondition(\" equipment power is reduced all day.\")\n end\n\n \n # make equipment schedule adjustments and rename.\n equi_set_schs.each do |k, v| # old name and new object for schedule\n if !v.to_ScheduleRuleset.empty?\n\n schedule = v.to_ScheduleRuleset.get\n default_rule = schedule.defaultDaySchedule\n rules = schedule.scheduleRules\n\n days_covered = Array.new(7, false)\n\n if rules.length > 0\n rules.each do |rule|\n summerStartMonth = OpenStudio::MonthOfYear.new(summer_start_month)\n summerEndMonth = OpenStudio::MonthOfYear.new(summer_end_month)\n summerStartDate = OpenStudio::Date.new(summerStartMonth, 1)\n summerEndDate = OpenStudio::Date.new(summerEndMonth, 30)\n \n summer_rule = rule.clone(model).to_ScheduleRule.get\n summer_rule.setStartDate(summerStartDate)\n summer_rule.setEndDate(summerEndDate)\n\n allDaysCovered(summer_rule, days_covered)\n\n cloned_day_summer = rule.daySchedule.clone(model)\n cloned_day_summer.setParent(summer_rule)\n\n summer_day = summer_rule.daySchedule\n day_time_vector = summer_day.times\n day_value_vector = summer_day.values\n summer_day.clearValues\n \n summer_day = createDaySchedule(summer_day, day_time_vector, day_value_vector, shift_time4, shift_time5, equipment_power_reduction_percent)\n \n ##############################################\n winterStartMonth1 = OpenStudio::MonthOfYear.new(winter_start_month1)\n winterEndMonth1 = OpenStudio::MonthOfYear.new(winter_end_month1)\n winterStartDate1 = OpenStudio::Date.new(winterStartMonth1, 1)\n winterEndDate1 = OpenStudio::Date.new(winterEndMonth1, 31)\n \n winter_rule1 = rule #rule.clone(model).to_ScheduleRule.get\n winter_rule1.setStartDate(winterStartDate1)\n winter_rule1.setEndDate(winterEndDate1)\n\n\n cloned_day_winter = rule.daySchedule.clone(model)\n cloned_day_winter.setParent(winter_rule1)\n\n winter_day1 = winter_rule1.daySchedule\n day_time_vector = winter_day1.times\n day_value_vector = winter_day1.values\n winter_day1.clearValues\n \n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time6, shift_time7, equipment_power_reduction_percent)\n if shift_time1 != shift_time6 \n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time1, shift_time2, equipment_power_reduction_percent)\n end\n ###################################################\n winterStartMonth2 = OpenStudio::MonthOfYear.new(winter_start_month2)\n winterEndMonth2 = OpenStudio::MonthOfYear.new(winter_end_month2)\n winterStartDate2 = OpenStudio::Date.new(winterStartMonth2, 1)\n winterEndDate2 = OpenStudio::Date.new(winterEndMonth2, 31)\n \n winter_rule2 = winter_rule1.clone(model).to_ScheduleRule.get\n winter_rule2.setStartDate(winterStartDate2)\n winter_rule2.setEndDate(winterEndDate2)\n \n cloned_day_winter2 = winter_day1.clone(model)\n cloned_day_winter2.setParent(winter_rule2)\n end\n end\n #runner.registerInfo(\"BEFORE #{days_covered}\")\n if days_covered.include?(false)\n summerStartMonth = OpenStudio::MonthOfYear.new(summer_start_month)\n summerEndMonth = OpenStudio::MonthOfYear.new(summer_end_month)\n summerStartDate = OpenStudio::Date.new(summerStartMonth, 1)\n summerEndDate = OpenStudio::Date.new(summerEndMonth, 30)\n \n summer_rule = OpenStudio::Model::ScheduleRule.new(schedule)\n summer_rule.setStartDate(summerStartDate)\n summer_rule.setEndDate(summerEndDate)\n coverSomeDays(summer_rule, days_covered)\n allDaysCovered(summer_rule, days_covered)\n\n cloned_day_summer = default_rule.clone(model)\n cloned_day_summer.setParent(summer_rule)\n\n summer_day = summer_rule.daySchedule\n day_time_vector = summer_day.times\n day_value_vector = summer_day.values\n summer_day.clearValues\n \n summer_day = createDaySchedule(summer_day, day_time_vector, day_value_vector, shift_time4, shift_time5, equipment_power_reduction_percent)\n \n ##############################################\n winterStartMonth1 = OpenStudio::MonthOfYear.new(winter_start_month1)\n winterEndMonth1 = OpenStudio::MonthOfYear.new(winter_end_month1)\n winterStartDate1 = OpenStudio::Date.new(winterStartMonth1, 1)\n winterEndDate1 = OpenStudio::Date.new(winterEndMonth1, 31)\n \n winter_rule1 = summer_rule.clone(model).to_ScheduleRule.get #OpenStudio::Model::ScheduleRule.new(schedule)\n winter_rule1.setStartDate(winterStartDate1)\n winter_rule1.setEndDate(winterEndDate1)\n\n #coverSomeDays(winter_rule1, days_covered)\n #allDaysCovered(summer_rule, days_covered)\n\n cloned_day_winter = default_rule.clone(model)\n cloned_day_winter.setParent(winter_rule1)\n\n winter_day1 = winter_rule1.daySchedule\n day_time_vector = winter_day1.times\n day_value_vector = winter_day1.values\n winter_day1.clearValues\n \n\n\n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time6, shift_time7, equipment_power_reduction_percent)\n if shift_time1 != shift_time6 \n winter_day1 = createDaySchedule(winter_day1, day_time_vector, day_value_vector, shift_time1, shift_time2, equipment_power_reduction_percent)\n end\n ###################################################\n winterStartMonth2 = OpenStudio::MonthOfYear.new(winter_start_month2)\n winterEndMonth2 = OpenStudio::MonthOfYear.new(winter_end_month2)\n winterStartDate2 = OpenStudio::Date.new(winterStartMonth2, 1)\n winterEndDate2 = OpenStudio::Date.new(winterEndMonth2, 31)\n \n winter_rule2 = winter_rule1.clone(model).to_ScheduleRule.get #OpenStudio::Model::ScheduleRule.new(schedule)\n winter_rule2.setStartDate(winterStartDate2)\n winter_rule2.setEndDate(winterEndDate2)\n \n cloned_day_winter2 = winter_day1.clone(model)\n cloned_day_winter2.setParent(winter_rule2)\n end\n #runner.registerInfo(\"AFTER Summer #{days_covered}\")\n else\n runner.registerWarning(\"Schedule '#{k}' isn't a ScheduleRuleset object and won't be altered by this measure.\")\n v.remove # remove un-used clone\n end\n end\n\n end\n return true\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n \n #use the built-in error checking \n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n #assume the aerator will last the full analysis\n expected_life = 25\n \n #assign the user inputs to variables\n water_fixture_def_object = runner.getOptionalWorkspaceObjectChoiceValue(\"water_fixture_def\",user_arguments,model)\n pct_flow_reduction = runner.getDoubleArgumentValue(\"pct_flow_reduction\",user_arguments)\n material_and_installation_cost_per_fixture = runner.getDoubleArgumentValue(\"material_and_installation_cost_per_fixture\",user_arguments)\n \n #check the water_fixture_def argument to make sure it still is in the model\n water_fixture_def = nil\n if water_fixture_def_object.empty?\n handle = runner.getStringArgumentValue(\"water_fixture_def\",user_arguments)\n if handle.empty?\n runner.registerError(\"No water fixture definition was chosen.\")\n else\n runner.registerError(\"The selected water fixture definition with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n end\n return false\n else\n if water_fixture_def_object.get.to_WaterUseEquipmentDefinition.is_initialized\n water_fixture_def = water_fixture_def_object.get.to_WaterUseEquipmentDefinition.get\n runner.registerInfo(\"Modifying the flow rate of #{water_fixture_def.name.get}.\")\n end\n end\n \n #count the number of these fixtures in the building\n num_fixtures_modified = water_fixture_def.instances.size\n original_name = water_fixture_def.name.get\n original_flow_rate_m3_per_sec = water_fixture_def.peakFlowRate\n original_flow_rate_gpm = OpenStudio::convert(original_flow_rate_m3_per_sec, \"m^3/s\",\"gal/min\").get\n runner.registerInitialCondition(\"This building has (#{num_fixtures_modified}) #{original_name}s. These fixtures have a flow rate of #{original_flow_rate_gpm}gpm, which is much higher than necessary for washing.\")\n\n #check to make sure the measure is applicable\n if num_fixtures_modified == 0\n runner.registerAsNotApplicable(\"This measure is not applicable. No #{original_name}s could be found in the building.\")\n return true\n end\n \n #find the fixture and reduce it's flow rate per the user input\n runner.registerInfo(\"pct_flow_reduction = #{pct_flow_reduction}\")\n pct_flow_reduction_multiplier = (100 - pct_flow_reduction)/100\n new_flow_rate_m3_per_sec = original_flow_rate_m3_per_sec * pct_flow_reduction_multiplier\n runner.registerInfo(\"original flow rate = #{original_flow_rate_m3_per_sec}m^3/s, multiplier = #{pct_flow_reduction_multiplier}, new flow rate = #{new_flow_rate_m3_per_sec}m^3/s\")\n water_fixture_def.setPeakFlowRate(new_flow_rate_m3_per_sec)\n new_flow_rate_gpm = OpenStudio::convert(new_flow_rate_m3_per_sec, \"m^3/s\",\"gal/min\").get\n water_fixture_def.setName(\"#{original_name} with Aerator\")\n runner.registerInfo(\"Reduced the peak flow rate of #{original_name} by #{pct_flow_reduction}%, from #{original_flow_rate_gpm}gpm to #{new_flow_rate_gpm}gpm.\")\n #add the cost per aerator * number of aerators to the building\n if material_and_installation_cost_per_fixture != 0\n cost = OpenStudio::Model::LifeCycleCost.createLifeCycleCost(\"Add Aerators to #{num_fixtures_modified} #{original_name}\", model.getBuilding, material_and_installation_cost_per_fixture * num_fixtures_modified, \"CostPerEach\", \"Construction\", expected_life, 0)\n if cost.empty?\n runner.registerError(\"Failed to add costs.\")\n end\n end \n \n #report the final condition\n runner.registerFinalCondition(\"Added aerators to (#{num_fixtures_modified}) #{original_name}s in the building, reducing their peak flow rate by #{pct_flow_reduction}%, from #{original_flow_rate_gpm}gpm down to #{new_flow_rate_gpm}gpm. This was accomplished at a cost of $#{material_and_installation_cost_per_fixture} per fixture, for a total cost of $#{(material_and_installation_cost_per_fixture * num_fixtures_modified).round}.\")\n \n return true\n \n end", "def parse_user_arguments(runner, user_arguments)\n apply_measure = runner.getStringArgumentValue(\"apply_measure\",user_arguments)\n # This measure is not applicable if apply_measure is false\n if apply_measure == \"FALSE\"\n runner.registerAsNotApplicable(\"Not Applicable - User chose not to apply this measure via the apply_measure argument.\")\n return true\n end\n \n @cooled_beam_type = runner.getStringArgumentValue(\"cooled_beam_type\", user_arguments)\n @existing_plant_loop_name = runner.getStringArgumentValue(\"existing_plant_loop_name\", user_arguments)\n @new_loop_pump_head = runner.getDoubleArgumentValue(\"new_loop_pump_head\", user_arguments)\n @air_loop_name = runner.getStringArgumentValue(\"air_loop_name\", user_arguments)\n @new_airloop_fan_pressure_rise = runner.getDoubleArgumentValue(\"new_airloop_fan_pressure_rise\", user_arguments)\n @supply_air_vol_flow_rate = runner.getDoubleArgumentValue(\"supply_air_vol_flow_rate\", user_arguments)\n @max_tot_chw_vol_flow_rate = runner.getDoubleArgumentValue(\"max_tot_chw_vol_flow_rate\", user_arguments)\n @number_of_beams = runner.getIntegerArgumentValue(\"number_of_beams\", user_arguments)\n @beam_length = runner.getDoubleArgumentValue(\"beam_length\", user_arguments)\n @design_inlet_water_temperature = runner.getDoubleArgumentValue(\"design_inlet_water_temperature\", user_arguments)\n @design_outlet_water_temperature = runner.getDoubleArgumentValue(\"design_outlet_water_temperature\", user_arguments)\n @coil_surface_area_per_coil_length = runner.getDoubleArgumentValue(\"coil_surface_area_per_coil_length\", user_arguments)\n @coefficient_alpha = runner.getDoubleArgumentValue(\"coefficient_alpha\", user_arguments)\n @coefficient_n1 = runner.getDoubleArgumentValue(\"coefficient_n1\", user_arguments)\n @coefficient_n2 = runner.getDoubleArgumentValue(\"coefficient_n2\", user_arguments)\n @coefficient_n3 = runner.getDoubleArgumentValue(\"coefficient_n3\", user_arguments)\n @coefficient_a0 = runner.getDoubleArgumentValue(\"coefficient_a0\", user_arguments)\n @coefficient_k1 = runner.getDoubleArgumentValue(\"coefficient_k1\", user_arguments)\n @coefficient_n = runner.getDoubleArgumentValue(\"coefficient_n\", user_arguments)\n @coefficient_kin = runner.getDoubleArgumentValue(\"coefficient_kin\", user_arguments)\n @leaving_pipe_inside_dia = runner.getStringArgumentValue(\"leaving_pipe_inside_dia\", user_arguments)\n end", "def end; end", "def end; end", "def end; end", "def passes; end", "def passes; end", "def run(runner, user_arguments)\n super(runner, user_arguments)\n\n # make the runner a class variable\n @runner = runner\n\n # if true errors on QAQC sections will show full backtrace. Use for diagnostics\n @error_backtrace = true\n\n # register initial condition\n runner.registerInitialCondition('Starting QAQC report generation')\n\n # get sql, model, and web assets\n setup = OsLib_Reporting.setup(runner)\n unless setup\n return false\n end\n @model = setup[:model]\n # workspace = setup[:workspace]\n @sql = setup[:sqlFile]\n web_asset_path = setup[:web_asset_path]\n\n # temp code to address climate zone problem mentioned in OpenStudio issue# 3148\n climateZones = @model.getClimateZones\n cz = climateZones.getClimateZones('ASHRAE').first.value\n climateZones.clear\n climateZones.setClimateZone('ASHRAE', cz)\n\n # assign the user inputs to variables\n args = OsLib_HelperMethods.createRunVariables(runner, @model, user_arguments, arguments)\n unless args\n return false\n end\n\n # vector to store the results and checks\n report_elems = OpenStudio::AttributeVector.new\n\n # used for edapt programs to populate xml file with extra data\n # report_elems << create_results\n\n # lookup and replace argument values from upstream measures\n if args['use_upstream_args'] == true\n args.each do |arg, value|\n next if arg == 'use_upstream_args' # this argument should not be changed\n value_from_osw = OsLib_HelperMethods.check_upstream_measure_for_arg(runner, arg)\n if !value_from_osw.empty?\n runner.registerInfo(\"Replacing argument named #{arg} from current measure with a value of #{value_from_osw[:value]} from #{value_from_osw[:measure_name]}.\")\n new_val = value_from_osw[:value]\n # TODO: - make code to handle non strings more robust. check_upstream_measure_for_arg coudl pass bakc the argument type\n if arg == 'total_bldg_floor_area'\n args[arg] = new_val.to_f\n elsif arg == 'num_stories_above_grade'\n args[arg] = new_val.to_f\n elsif arg == 'zipcode'\n args[arg] = new_val.to_i\n else\n args[arg] = new_val\n end\n end\n end\n end\n\n # utility name to to used by some qaqc checks\n @utility_name = nil # for utility QAQC string is passed in\n default_target_standard = args['template'] # for utility QAQC this is hard coded, for generic it is user argument\n\n # get building type, different standards path if multifamily\n building_type = ''\n if @model.getBuilding.standardsBuildingType.is_initialized\n building_type = @model.getBuilding.standardsBuildingType.get\n end\n\n # create an attribute vector to hold the checks\n check_elems = OpenStudio::AttributeVector.new\n\n # loop through QAQC categories where bool is true\n possible_check_categories.each do |hash|\n # skip if bool arg for this method is false\n next if args[hash[:method_name]] == false\n\n cat = hash[:cat]\n cat_input = \"\\'#{cat}\\'\"\n if hash[:standards]\n standards_input = \",\\'#{default_target_standard}\\'\"\n else\n standards_input = ''\n end\n if hash[:data].nil?\n data_input = ''\n else\n data_input = \",#{hash[:data]}\"\n end\n\n # get min tol\n if args.key?(\"#{hash[:method_name]}_tol\")\n # get tol value\n tol = args[\"#{hash[:method_name]}_tol\"]\n # set min inputs\n if tol.is_a? Float\n min_input = \",#{tol}\"\n else\n min_input = ''\n end\n else\n min_input = ''\n end\n\n # get max tol\n if args.key?(\"#{hash[:method_name]}_max_tol\")\n # get tol value\n max_tol = args[\"#{hash[:method_name]}_max_tol\"]\n # set max inputs\n if max_tol.is_a? Float\n max_input = \",#{max_tol}\"\n elsif (hash[:tol_max] == true) && hash[:tol_min].is_a?(Float)\n # if true then use double from min_tol\n max_input = \",#{args[\"#{hash[:method_name]}_tol\"]}\"\n else\n max_input = ''\n end\n else\n if (hash[:tol_max] == true) && hash[:tol_min].is_a?(Float)\n # if true then use double from min_tol\n max_input = \",#{args[\"#{hash[:method_name]}_tol\"]}\"\n else\n max_input = ''\n end\n end\n\n # run QAQC check\n eval(\"check_elems << #{hash[:method_name]}(#{cat_input}#{data_input}#{standards_input}#{min_input}#{max_input},false)\")\n end\n\n # add checks to report_elems\n report_elems << OpenStudio::Attribute.new('checks', check_elems)\n\n # create an extra layer of report. the first level gets thrown away.\n top_level_elems = OpenStudio::AttributeVector.new\n top_level_elems << OpenStudio::Attribute.new('report', report_elems)\n\n # create the report\n result = OpenStudio::Attribute.new('summary_report', top_level_elems)\n result.saveToXml(OpenStudio::Path.new('report.xml'))\n\n # closing the sql file\n @sql.close\n\n # reporting final condition\n runner.registerFinalCondition('Finished generating report.xml.')\n\n # populate sections using attributes\n sections = OsLib_Reporting.sections_from_check_attributes(check_elems, runner)\n\n # generate html output\n OsLib_Reporting.gen_html(\"#{File.dirname(__FILE__)}report.html.erb\", web_asset_path, sections, name)\n\n return true\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # assign the user inputs to variables\n verbose_info_statements = runner.getBoolArgumentValue(\"verbose_info_statements\",user_arguments)\n zones = runner.getOptionalWorkspaceObjectChoiceValue('zones', user_arguments, model) # model is passed in because of argument type\n cooling_mdot_per_ft2 = runner.getDoubleArgumentValue(\"cooling_mdot_per_ft2\",user_arguments)\n heating_mdot_per_ft2 = runner.getDoubleArgumentValue(\"heating_mdot_per_ft2\",user_arguments)\n cooling_LAT = runner.getDoubleArgumentValue(\"cooling_LAT\",user_arguments)\n heating_LAT = runner.getDoubleArgumentValue(\"heating_LAT\",user_arguments)\n cooling_HumRat = runner.getDoubleArgumentValue(\"cooling_HumRat\",user_arguments)\n heating_HumRat = runner.getDoubleArgumentValue(\"heating_HumRat\",user_arguments)\n internal_variable_availability_dictionary_reporting = runner.getStringArgumentValue('internal_variable_availability_dictionary_reporting', user_arguments)\n ems_runtime_language_debug_output_level = runner.getStringArgumentValue('ems_runtime_language_debug_output_level', user_arguments)\n actuator_availability_dictionary_reporting = runner.getStringArgumentValue('actuator_availability_dictionary_reporting', user_arguments)\n\n runner.registerInitialCondition(\"Measure began with #{model.getEnergyManagementSystemSensors.count} EMS sensors, #{model.getEnergyManagementSystemActuators.count} EMS Actuators, #{model.getEnergyManagementSystemPrograms.count} EMS Programs, #{model.getEnergyManagementSystemSubroutines.count} EMS Subroutines, #{model.getEnergyManagementSystemProgramCallingManagers.count} EMS Program Calling Manager objects\")\n \n # test user argument values for reasonableness\n if cooling_LAT > heating_LAT \n runner.registerError(\"Measure failed because the value of #{cooling_LAT} Deg F entered for the clg supply air temperature must be less then then value of #{heating_LAT} entered for the htg supply air temp.\") \n return false\n end\n \n if cooling_mdot_per_ft2 < 0.50 \n runner.registerError(\"Measure failed because the value of #{cooling_mdot_per_ft2} cfm/ft2 entered for the clg airflow per sqft must be greater then 0.50.\") \n return false\n end\n\n if heating_mdot_per_ft2 < 0.50 \n runner.registerError(\"Measure failed because the value of #{heating_mdot_per_ft2} cfm/ft2 entered for the htg airflow per sqft must be greater then 0.50.\") \n return false\n end\n \n # check the zone selection for existence in model\n apply_to_all_zones = false\n selected_zone = nil\n if zones.empty?\n handle = runner.getStringArgumentValue('zones', user_arguments)\n if handle.empty?\n runner.registerError('No thermal zone was chosen.')\n return false\n else\n runner.registerError(\"The selected thermal zone with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n return false\n end\n else\n if !zones.get.to_ThermalZone.empty?\n selected_zone = zones.get.to_ThermalZone.get\n elsif !zones.get.to_Building.empty?\n apply_to_all_zones = true\n else\n runner.registerError('Script Error - argument not showing up as thermal zone.')\n return false\n end\n end\n \n # define selected zone(s), depending on user input, add selected zones to an array\n selected_zones = []\n if apply_to_all_zones == true\n model.getThermalZones.each do |each_zone|\n if each_zone.thermostatSetpointDualSetpoint.is_initialized\n tstat = each_zone.thermostatSetpointDualSetpoint.get\n if tstat.heatingSetpointTemperatureSchedule.is_initialized || tstat.coolingSetpointTemperatureSchedule.is_initialized\n if each_zone.airLoopHVAC.empty?\n selected_zones << each_zone\n else\n if verbose_info_statements == true\n runner.registerInfo(\"HVAC System serving Thermal Zone named #{each_zone.name} is attached to air AirLoop, and will not be modified by this measure.\") \n end\n end\n else\n if verbose_info_statements == true\n runner.registerInfo(\"Thermal Zone named #{each_zone.name} is unconditioned, and will not be modified by this measure.\") \n end\n end\n end \n end \n else\n selected_zones << selected_zone\n end\n \n if selected_zones.length == 0\n runner.registerError(\"Model contains no 'qualified' Themal Zones for this measure to modelfy.\") \n return false\n end\n \n # Convert arguments to SI units\n cooling_LAT_SI = OpenStudio.convert(cooling_LAT,\"F\",\"C\")\n heating_LAT_SI = OpenStudio.convert(heating_LAT,\"F\",\"C\")\n\n # initialize counter variable and declare EMS variables for proper scope within loops\n ems_det_purchased_air_state_prg = nil\n ems_set_purchased_air_prg = nil\n ems_prgm_calling_mngr = nil\n counter = 0\n\n # Loop through selected conditioned zone(s), replace existing HVAC equipment with ZoneHVACIdealLoadsAirSystems objects\n selected_zones.each do |zone|\n \n counter += 1 \n cooling_mdot = zone.floorArea * cooling_mdot_per_ft2\n cooling_mdot_SI = OpenStudio.convert(cooling_mdot,\"cfm\",\"m^3/s\")\n \n heating_mdot = zone.floorArea * heating_mdot_per_ft2\n heating_mdot_SI = OpenStudio.convert(heating_mdot,\"cfm\",\"m^3/s\")\n \n zone.equipment.each do |zone_equipment|\n # remove zone equipment HVAC object attached to zone. NOTE: the .remove method also removes 'child' coils from their plant loops\n next if zone_equipment.to_FanZoneExhaust.is_initialized\n if verbose_info_statements == true\n runner.registerInfo(\"Removing ZoneHVAC Equipment named #{zone_equipment.name} currently serving Thermal Zone #{zone.name}.\")\n end\n zone_equipment.remove\n end \n \n # Remove existing outdoor VRF units (special type of ZoneHVAC Equip that is not in zone and not in AirLoops)\n if model.getAirConditionerVariableRefrigerantFlows.count != 0\n runner.registerAsNotApplicable(\"This model has one outdoor VRF unit named '#{getAirConditionerVariableRefrigerantFlows[0].name}'. This measure has not been written to identify whether or not to remove a VRF indoor unit from a thermal zone. The measure logic will not be executed.\")\n return true\n end\n \n # Remove plant loops that no longer have demand side components that are coils\n model.getPlantLoops.each do |plantloop|\n delete_loop = true\n plantloop.demandComponents.each do |comp| \n if comp.to_CoilCoolingLowTempRadiantConstFlow.is_initialized or\n comp.to_CoilCoolingLowTempRadiantVarFlow.is_initialized or\n comp.to_WaterUseConnections.is_initialized or\n comp.to_CoilWaterHeatingDesuperheater.is_initialized or\n comp.to_CoilCoolingWater.is_initialized or \n comp.to_CoilCoolingWaterToAirHeatPumpEquationFit.is_initialized or\n comp.to_CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFit.is_initialized or \n comp.to_CoilHeatingLowTempRadiantVarFlow.is_initialized or\n comp.to_CoilHeatingLowTempRadiantConstFlow.is_initialized or \n comp.to_CoilHeatingWater.is_initialized or\n comp.to_CoilHeatingWaterBaseboard.is_initialized or \n comp.to_CoilHeatingWaterBaseboardRadiant.is_initialized or\n comp.to_CoilHeatingWaterToAirHeatPumpEquationFit.is_initialized or \n comp.to_CoilHeatingWaterToAirHeatPumpVariableSpeedEquationFit.is_initialized or\n comp.to_CoilSystemCoolingWaterHeatExchangerAssisted.is_initialized or \n comp.to_CoilWaterHeatingAirToWaterHeatPump.is_initialized or\n comp.to_CoilWaterHeatingAirToWaterHeatPumpWrapped.is_initialized\n \n delete_loop = false\n end\n end \n if delete_loop == true\n if verbose_info_statements == true\n runner.registerInfo(\"Removing #{plantloop.sizingPlant.loopType} Plant Loop named '#{plantloop.name}' from the model as the measure previously removed all demand side coils from this loop.\")\n end\n plantloop.remove\n end\n end # end loop through plant loops\n \n # create ZoneHVACIdealLoadsAirSystem and assign to the thermal zone. \n ideal_loads_HVAC = OpenStudio::Model::ZoneHVACIdealLoadsAirSystem.new(model)\n ideal_loads_HVAC.setName(\"#{zone.name}#{counter}AIR\")\n ideal_loads_HVAC.addToThermalZone(zone)\n if verbose_info_statements == true\n runner.registerInfo(\"Replaced the existing Zone HVAC system(s) serving the thermal zone named '#{zone.name}' with a new ZoneHVACIdealLoadsAirSystem.\") \n end\n \n # First time (and only time) through the thermal zone loop, create new EnergyManagementSystem:Program, EnergyManagementSystem:ProgramCallingManager \n # and EnergyManagement:GlobalVariable objects and stub them out\n \n if counter == 1\n \n # Create new EnergyManagementSystem:Program object for determining purchased air \n ems_det_purchased_air_state_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)\n ems_det_purchased_air_state_prg.setName(\"Determine_Purch_Air_State\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Program object named '#{ems_det_purchased_air_state_prg.name}' added to determine zone purchased air status.\") \n end\n \n # Create new EnergyManagementSystem:Program object for setting purchased air \n ems_set_purchased_air_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)\n ems_set_purchased_air_prg.setName(\"Set_Purch_Air\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Program object named '#{ems_set_purchased_air_prg.name}' added to set zone purchased air status.\") \n end\n \n # create a new EnergyManagementSystem:ProgramCallingManager object configured to call the EMS programs\n ems_prgm_calling_mngr = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n ems_prgm_calling_mngr.setName(\"Constant Volume Purchased Air Example\")\n ems_prgm_calling_mngr.setCallingPoint(\"AfterPredictorAfterHVACManagers\")\n ems_prgm_calling_mngr.addProgram(ems_det_purchased_air_state_prg)\n ems_prgm_calling_mngr.addProgram(ems_set_purchased_air_prg)\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Program Calling Manager object named '#{ems_prgm_calling_mngr.name}' added to call #{ems_det_purchased_air_state_prg.name} and #{ems_set_purchased_air_prg.name} EMS programs.\") \n end\n \n end # end logic that only runs once\n \n # Create new EnergyManagementSystem:GlobalVariable object and configure to hold the current \"Zone State\"\n ems_zone_state_gv = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, \"#{zone.name}_State\".gsub(\" \",\"_\"))\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Global Variable object named '#{ems_zone_state_gv.name}' was added to hold the current 'Zone State' - heating, cooling or deadband.\") \n end\n \n # Create new EnergyManagementSystem:Sensor object representing the Zone Predicted Sensible Load to Setpoint Heat Transfer Rate\n ems_zone_pred_sens_load_to_Stpt_HTR_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, \"Zone Predicted Sensible Load to Setpoint Heat Transfer Rate\")\n ems_zone_pred_sens_load_to_Stpt_HTR_sensor.setName(\"Sensible_Load_Zone_#{counter}\")\n ems_zone_pred_sens_load_to_Stpt_HTR_sensor.setKeyName(\"#{zone.name}\") \n if verbose_info_statements == true\n runner.registerInfo(\"EMS Sensor object named '#{ems_zone_pred_sens_load_to_Stpt_HTR_sensor.name}' representing the Zone Predicted Sensible Load to Setpoint Heat Transfer Rate for the zone named #{zone.name} added to the model.\") \n end\n \n # Create EMS Actuator Objects representing Ideal Loads Air System Air Mass Flow Rate, Supply Air temp and Supply Air Humidity Ratio serving the thermal zone\n ems_ideal_air_loads_mdot_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(ideal_loads_HVAC,\"Ideal Loads Air System\",\"Air Mass Flow Rate\")\n ems_ideal_air_loads_mdot_actuator.setName(\"ZONE_#{counter}_AIR_Mdot\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Actuator object named '#{ems_ideal_air_loads_mdot_actuator.name}' representing the Ideal Air Loads System Mass Flow Rate for the Ideal Air Loads System named #{ideal_loads_HVAC.name} was added to the model.\") \n end\n \n ems_ideal_air_loads_supply_temp_sensor = OpenStudio::Model::EnergyManagementSystemActuator.new(ideal_loads_HVAC,\"Ideal Loads Air System\",\"Air Temperature\")\n ems_ideal_air_loads_supply_temp_sensor.setName(\"ZONE_#{counter}_AIR_SupplyT\") \n if verbose_info_statements == true\n runner.registerInfo(\"EMS Actuator object named '#{ems_ideal_air_loads_supply_temp_sensor.name}' representing the Ideal Air Loads System Supply Air Temperature for the Ideal Air Loads System named #{ideal_loads_HVAC.name} was added to the model.\") \n end\n \n ems_ideal_air_loads_supply_HumRat_sensor = OpenStudio::Model::EnergyManagementSystemActuator.new(ideal_loads_HVAC,\"Ideal Loads Air System\",\"Air Humidity Ratio\")\n ems_ideal_air_loads_supply_HumRat_sensor.setName(\"ZONE_#{counter}_AIR_SupplyHumRat\") \n if verbose_info_statements == true\n runner.registerInfo(\"EMS Actuator object named '#{ems_ideal_air_loads_supply_HumRat_sensor.name}' representing the Ideal Air Loads System Supply Air Humidity Ratio the Ideal Air Loads System named #{ideal_loads_HVAC.name} was added to the model.\") \n end\n \n # Add logic to the two EMS programs as we iterate through the selected zone loop\n # NOTE: State value of 1 means zone is heating, state value of 2 means zone is cooling, state value of 0 means zone in deadband\n ems_det_purchased_air_state_prg.addLine(\"IF (#{ems_zone_pred_sens_load_to_Stpt_HTR_sensor.name} <= 0.0)\")\n ems_det_purchased_air_state_prg.addLine(\"SET #{ems_zone_state_gv.name} = 2.0\")\n ems_det_purchased_air_state_prg.addLine(\"ELSEIF (#{ems_zone_pred_sens_load_to_Stpt_HTR_sensor.name} > 0.0)\")\n ems_det_purchased_air_state_prg.addLine(\"SET #{ems_zone_state_gv.name} = 1.0\")\n ems_det_purchased_air_state_prg.addLine(\"ENDIF\")\n \n ems_set_purchased_air_prg.addLine(\"IF (#{ems_zone_state_gv.name} == 2.0)\")\n ems_set_purchased_air_prg.addLine(\"SET #{ems_ideal_air_loads_mdot_actuator.name} = #{cooling_mdot_SI}\")\n ems_set_purchased_air_prg.addLine(\"SET #{ems_ideal_air_loads_supply_temp_sensor.name} = #{cooling_LAT_SI}\")\n ems_set_purchased_air_prg.addLine(\"SET #{ems_ideal_air_loads_supply_HumRat_sensor.name} = #{cooling_HumRat}\")\n ems_set_purchased_air_prg.addLine(\"ELSEIF (#{ems_zone_state_gv.name} == 1.0)\")\n ems_set_purchased_air_prg.addLine(\"SET #{ems_ideal_air_loads_mdot_actuator.name} = #{heating_mdot_SI}\")\n ems_set_purchased_air_prg.addLine(\"SET #{ems_ideal_air_loads_supply_temp_sensor.name} = #{heating_LAT_SI}\")\n ems_set_purchased_air_prg.addLine(\"SET #{ems_ideal_air_loads_supply_HumRat_sensor.name} = #{heating_HumRat}\")\n ems_set_purchased_air_prg.addLine(\"ENDIF\")\n \n end # end loop through qualified thermal zones\n\n # create OutputEnergyManagementSystem object (a 'unique' object) and configure to allow EMS reporting\n output_EMS = model.getOutputEnergyManagementSystem\n output_EMS.setInternalVariableAvailabilityDictionaryReporting('internal_variable_availability_dictionary_reporting')\n output_EMS.setEMSRuntimeLanguageDebugOutputLevel('ems_runtime_language_debug_output_level')\n output_EMS.setActuatorAvailabilityDictionaryReporting('actuator_availability_dictionary_reporting')\n\n runner.registerFinalCondition(\"Measure finished with #{model.getEnergyManagementSystemSensors.count} EMS sensors, #{model.getEnergyManagementSystemActuators.count} EMS Actuators, #{model.getEnergyManagementSystemPrograms.count} EMS Programs, #{model.getEnergyManagementSystemSubroutines.count} EMS Subroutines, #{model.getEnergyManagementSystemProgramCallingManagers.count} EMS Program Calling Manager objects\")\n\n end", "def end_point=(_arg0); end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # assign the user inputs to variables\n verbose_info_statements = runner.getBoolArgumentValue(\"verbose_info_statements\",user_arguments)\n coil_cooling_DX_single_speed_objects = runner.getOptionalWorkspaceObjectChoiceValue('coil_cooling_DX_single_speed_objects', user_arguments, model) # model is passed in because of argument type\n oa_db_curve_threshold_temp = runner.getDoubleArgumentValue(\"oa_db_curve_threshold_temp\",user_arguments)\n c2_a = runner.getDoubleArgumentValue(\"c2_a\",user_arguments)\n c2_b = runner.getDoubleArgumentValue(\"c2_b\",user_arguments)\n c2_c = runner.getDoubleArgumentValue(\"c2_c\",user_arguments)\n c2_d = runner.getDoubleArgumentValue(\"c2_d\",user_arguments)\n c2_e = runner.getDoubleArgumentValue(\"c2_e\",user_arguments)\n c2_f = runner.getDoubleArgumentValue(\"c2_f\",user_arguments)\n internal_variable_availability_dictionary_reporting = runner.getStringArgumentValue('internal_variable_availability_dictionary_reporting', user_arguments)\n ems_runtime_language_debug_output_level = runner.getStringArgumentValue('ems_runtime_language_debug_output_level', user_arguments)\n actuator_availability_dictionary_reporting = runner.getStringArgumentValue('actuator_availability_dictionary_reporting', user_arguments)\n\n runner.registerInitialCondition(\"Measure began with #{model.getEnergyManagementSystemSensors.count} EMS sensors, #{model.getEnergyManagementSystemActuators.count} EMS Actuators, #{model.getEnergyManagementSystemPrograms.count} EMS Programs, #{model.getEnergyManagementSystemSubroutines.count} EMS Subroutines, #{model.getEnergyManagementSystemProgramCallingManagers.count} EMS Program Calling Manager objects\")\n\n # convert threshold temperature to SI \n oa_db_curve_threshold_temp_SI = OpenStudio.convert(oa_db_curve_threshold_temp,\"F\",\"C\")\n\n # check the dx cooling coils for existence in model\n apply_to_all_dx_single_speed_coils = false\n selected_dx_clg_coils = nil\n \n if coil_cooling_DX_single_speed_objects.empty?\n handle = runner.getStringArgumentValue('coil_cooling_DX_single_speed_objects', user_arguments)\n if handle.empty?\n runner.registerError('No dx coil object was chosen.')\n return false\n else\n runner.registerError(\"The selected single speed dx cooling coil with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n return false\n end\n else\n if !coil_cooling_DX_single_speed_objects.get.to_CoilCoolingDXSingleSpeed.empty?\n selected_dx_clg_coils = coil_cooling_DX_single_speed_objects.get.to_CoilCoolingDXSingleSpeed.get\n elsif !coil_cooling_DX_single_speed_objects.get.to_Building.empty?\n apply_to_all_plantloops = true\n else\n runner.registerError('Script Error - argument not showing up as a dx cooling coil.')\n return false\n end\n end\n\n # define selected single speed dx cooling coils), depending on user input, add selected coil(s) to an array\n selected_dx_single_speed_clg_coils = []\n if apply_to_all_plantloops == true\n model.getCoilCoolingDXSingleSpeeds.each do |each_dx_coil|\n selected_dx_single_speed_clg_coils << each_dx_coil\n end\n else \n selected_dx_single_speed_clg_coils << selected_dx_clg_coils\n end\n if selected_dx_single_speed_clg_coils.length == 0\n runner.registerAsNotApplicable(\"Model contains no 'qualified' single speed dx cooling coils attached to PTHP Zone HVAC for this measure to modify.\") \n return true\n end\n \n # declare variables for proper scope\n counter = 0\n oa_db_EMS_sensor = nil\n ems_curve_overwrite_mngr_prgm = nil\n ems_prgm_calling_mngr = nil\n dx_coil_inlet_node = nil\n dx_coil_outlet_node = nil\n oa_mixer_inlet_node_name = nil\n pthp = nil\n \n # Create a 'stub' object for the EnergyManagementSystem:Program object for overriding DX Single Speed clg coil capacity curves \n ems_curve_overwrite_mngr_prgm = OpenStudio::Model::EnergyManagementSystemProgram.new(model)\n ems_curve_overwrite_mngr_prgm.setName(\"CurveOverwriteMGR\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Program object named '#{ems_curve_overwrite_mngr_prgm.name}' added to control when clg coil capacity curves will be overridden.\") \n end\n \n # Create a new EnergyManagementSystem:ProgramCallingManager object configured to call the EMS program\n ems_prgm_calling_mngr = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n ems_prgm_calling_mngr.setName(\"EMSBasedCurveManager\")\n ems_prgm_calling_mngr.setCallingPoint(\"AfterPredictorBeforeHVACManagers\")\n ems_prgm_calling_mngr.addProgram(ems_curve_overwrite_mngr_prgm) \n if verbose_info_statements == true\n runner.registerInfo(\"EMS Program Calling Manager object named '#{ems_prgm_calling_mngr.name}' added to call #{ems_curve_overwrite_mngr_prgm.name} EMS program.\") \n end\n \n # Loop through selected plantloops\n selected_dx_single_speed_clg_coils.each do |dx_clg_coil|\n \n counter += 1\n \n # get curve name for dx_clg_coil object\n cap_curve = dx_clg_coil.totalCoolingCapacityFunctionOfTemperatureCurve\n # Retrieve existing coefficients from curve\n \n if not cap_curve.to_CurveBiquadratic.empty?\n curve_obj = cap_curve.to_CurveBiquadratic.get\n c1_a = curve_obj.coefficient1Constant \n c1_b = curve_obj.coefficient2x\n c1_c = curve_obj.coefficient3xPOW2\n c1_d = curve_obj.coefficient4y\n c1_e = curve_obj.coefficient5yPOW2\n c1_f = curve_obj.coefficient6xTIMESY\n if verbose_info_statements == true\n runner.registerInfo(\"retrieve coefficient values of existing Biquadratic curve named #{cap_curve.name} associated with the DX Single Speed Cooling coil named #{dx_clg_coil.name}.\")\n end\n else\n runner.registerError(\"This measure requires the Total Cooling Capacity Function Of Temperature Curve named #{cap_curve.name} associated with the DX Single Speed Cooling coil named #{dx_clg_coil} to be a BiQuadratic Curve. Please correct and re-run.\")\n return false\n end \n \n # retrieve parent PTHP object for 'feedforward' node naming that occurs in osm->idf translator\n if not dx_clg_coil.containingZoneHVACComponent.empty?\n zone_HVAC_component = dx_clg_coil.containingZoneHVACComponent.get\n if not zone_HVAC_component.to_ZoneHVACPackagedTerminalHeatPump.empty?\n pthp = zone_HVAC_component.to_ZoneHVACPackagedTerminalHeatPump.get\n\n # get dx_clg_coil object inlet node\n # Use PTHP name pattern \"<PTHP_NAME> MIXED AIR NODE\" Per conversation with Kyle Benne on 4/11/2018,\n dx_coil_inlet_node = \"#{pthp.name} Mixed Air Node\" \n\n #get dx_clg_coil object outlet node\n # Use PTHP name pattern \"<PTHP_NAME> COOLING COIL OUTLET NODE\" Per conversation with Kyle Benne on 4/11/2018,\n dx_coil_outlet_node = \"#{pthp.name} Cooling Coil Outlet Node\" \n \n # get OA mixer object (outdoor air inlet temperature) and (outdoor air inlet pressure) nodes \n # Use PTHP name pattern \"<PTHP_NAME> OA NODE\" Per conversation with Kyle Benne on 4/11/2018,\n oa_mixer_inlet_node_name = \"#{pthp.name} OA Node\"\n\n end\n end \n \n # create a new EMS Actuator Object representing the cooling capacity as a function of temperature curve \n ems_clg_cap_func_temp_curve_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(cap_curve,\"Curve\",\"Curve Result\")\n ems_clg_cap_func_temp_curve_actuator.setName(\"CurveOverwrite#{counter}\".gsub(\"-\",\"_\"))\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Actuator object named '#{ems_clg_cap_func_temp_curve_actuator.name}' representing the 'clg curve as a function of temp' object associated with dx cooling coil object named #{dx_clg_coil.name}.\") \n end\n # create new EnergyManagementSystem:GlobalVariable object and configure to hold EMS program results before modifying the curve output\n ems_curve_input_gv = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, \"CurveInput2_#{counter}\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Global Variable object named '#{ems_curve_input_gv.name}' representing results of evaluating the new performance curve associated with #{dx_clg_coil.name} added to the model.\") \n end\n \n # create new EMS Sensor Object representing 'DX Coil capacity as function of temp' curve \n ems_actual_curve_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, \"Performance Curve Output Value\")\n ems_actual_curve_sensor.setName(\"ActualCurve#{counter}\")\n ems_actual_curve_sensor.setKeyName(\"#{cap_curve.name}\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Sensor object named #{ems_actual_curve_sensor.name} added to the model to represent the 'Clg Capacity as a Function of Temp' curve associated with the DX cooling coil object named #{dx_clg_coil.name}.\")\n end\n \n #Create new EMS Sensor Object representing OA Mixer inlet node pressure \n ems_oa_mixer_inlet_node_pressure_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, \"System Node Pressure\")\n ems_oa_mixer_inlet_node_pressure_sensor.setName(\"Pressure#{counter}\")\n ems_oa_mixer_inlet_node_pressure_sensor.setKeyName(\"#{oa_mixer_inlet_node_name}\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Sensor object named #{ems_oa_mixer_inlet_node_pressure_sensor.name} added to the model to represent the 'System Node Pressure' associated with the inlet node of the Outdoor Air Mixer object serving the PTHP object named #{dx_clg_coil.name}.\")\n end\n \n #Create new EMS Sensor Object representing dx coil inlet node dry bulb temperature \n ems_coil_inlet_dbt_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, \"System Node Temperature\")\n ems_coil_inlet_dbt_sensor.setName(\"CoilInletDBT#{counter}\")\n ems_coil_inlet_dbt_sensor.setKeyName(\"#{dx_coil_inlet_node}\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Sensor object named #{ems_coil_inlet_dbt_sensor.name} added to the model to represent the 'System Node Temperature' associated with the inlet node of the dx coil object named #{dx_clg_coil.name}.\")\n end\n \n #Create new EMS Sensor Object representing dx coil inlet node humidity ratio\n ems_coil_inlet_hum_rat_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, \"System Node Humidity Ratio\")\n ems_coil_inlet_hum_rat_sensor.setName(\"CoilInletW#{counter}\")\n ems_coil_inlet_hum_rat_sensor.setKeyName(\"#{dx_coil_inlet_node}\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Sensor object named #{ems_coil_inlet_hum_rat_sensor.name} added to the model to represent the 'System Node Humidity Ratio' associated with the inlet node of the dx coil object named #{dx_clg_coil.name}.\")\n end\n \n #Create new EMS Sensor Object representing OA Mixer inlet node dry bulb temp\n ems_oa_mixer_inlet_node_temp_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, \"System Node Temperature\")\n ems_oa_mixer_inlet_node_temp_sensor.setName(\"OAT#{counter}\")\n ems_oa_mixer_inlet_node_temp_sensor.setKeyName(\"#{oa_mixer_inlet_node_name}\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Sensor object named #{ems_oa_mixer_inlet_node_temp_sensor.name} added to the model to represent the 'System Node Temperature' associated with the inlet node of the Outdoor Air Mixer object serving the PTHP object named #{dx_clg_coil.name}.\")\n end\n \n # create new EnergyManagementSystem:OutputVariable object and configure it to hold the current curve value \n ems_erl_curve_value_ov = OpenStudio::Model::EnergyManagementSystemOutputVariable.new(model, ems_actual_curve_sensor)\n ems_erl_curve_value_ov.setName(\"ERLCurveValue#{counter}\") \n ems_erl_curve_value_ov.setEMSVariableName(\"#{ems_actual_curve_sensor.name}\")\n ems_erl_curve_value_ov.setTypeOfDataInVariable(\"Averaged\")\n\t ems_erl_curve_value_ov.setUpdateFrequency(\"ZoneTimeStep\") \n if verbose_info_statements == true\n runner.registerInfo(\"EMS Global Variable object named #{ems_erl_curve_value_ov.name} added to the model to represent the current performance curve value.\") \n end\n \n # create new EnergyManagementSystem:OutputVariable object and configure it to hold the old curve value \n ems_old_curve_value_gv = OpenStudio::Model::EnergyManagementSystemOutputVariable.new(model, ems_curve_input_gv)\n ems_old_curve_value_gv.setName(\"OldCurveValue#{counter}\") \n ems_old_curve_value_gv.setEMSVariableName(\"#{ems_curve_input_gv.name}\")\n ems_old_curve_value_gv.setTypeOfDataInVariable(\"Averaged\")\n\t ems_old_curve_value_gv.setUpdateFrequency(\"ZoneTimeStep\") \n if verbose_info_statements == true\n runner.registerInfo(\"EMS Global Variable object named #{ems_old_curve_value_gv.name} added to the model to represent the old performance curve value.\") \n end\n \n # create new EnergyManagementSystem:OutputVariable object and configure it to hold the new curve value \n ems_new_curve_value_gv = OpenStudio::Model::EnergyManagementSystemOutputVariable.new(model, ems_clg_cap_func_temp_curve_actuator)\n ems_new_curve_value_gv.setName(\"NewCurveValue#{counter}\") \n ems_new_curve_value_gv.setEMSVariableName(\"#{ems_clg_cap_func_temp_curve_actuator.name}\")\n ems_new_curve_value_gv.setTypeOfDataInVariable(\"Averaged\")\n\t ems_new_curve_value_gv.setUpdateFrequency(\"ZoneTimeStep\") \n if verbose_info_statements == true\n runner.registerInfo(\"EMS Global Variable object named #{ems_new_curve_value_gv.name} added to the model to represent the new performance curve value.\") \n end\n \n # Add logic to the EMS program as we iterate through the selected dx cooling coil objects\n ems_curve_overwrite_mngr_prgm.addLine(\"SET TTmp_#{counter} = #{ems_coil_inlet_dbt_sensor.name}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET WTmp_#{counter} = #{ems_coil_inlet_hum_rat_sensor.name}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET PTmp_#{counter} = #{ems_oa_mixer_inlet_node_pressure_sensor.name}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET MyWB_#{counter} = @TwbFnTdbWPb TTmp_#{counter} WTmp_#{counter} PTmp_#{counter}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET IVOnea_#{counter} = MyWB_#{counter}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET IVTwo_#{counter} = #{ems_oa_mixer_inlet_node_temp_sensor.name}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET IVThree_#{counter} = IVOnea_#{counter}*IVTwo_#{counter}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET C1_#{counter} = #{c1_a}\") \n ems_curve_overwrite_mngr_prgm.addLine(\"SET C2_#{counter} = #{c1_b}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET C3_#{counter} = #{c1_c}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET C4_#{counter} = #{c1_d}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET C5_#{counter} = #{c1_e}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET C6_#{counter} = #{c1_f}\")\n\n ems_curve_overwrite_mngr_prgm.addLine(\"SET C1_a#{counter} = #{c2_a}\") \n ems_curve_overwrite_mngr_prgm.addLine(\"SET C2_a#{counter} = #{c2_b}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET C3_a#{counter} = #{c2_c}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET C4_a#{counter} = #{c2_d}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET C5_a#{counter} = #{c2_e}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET C6_a#{counter} = #{c2_f}\")\n \n # break curve input into two seperate statments (left and right hand) as to not exceed EMS 100 character line limit.\n ems_curve_overwrite_mngr_prgm.addLine(\"SET LeftCurveInput_#{counter}=C1_#{counter}+(C2_#{counter}*IVOnea_#{counter})+(C3_#{counter}*IVOnea_#{counter}*IVonea_#{counter})\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET RightCurveInput_#{counter}=(C4_#{counter}*IVTwo_#{counter})+(C5_#{counter}*IVTwo_#{counter}*IVTwo_#{counter})+(C6_#{counter}*IVThree_#{counter})\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET CurveInput_#{counter} = LeftCurveInput_#{counter} + RightCurveInput_#{counter}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET ##{ems_curve_input_gv.name} = CurveInput_#{counter}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"IF #{ems_oa_mixer_inlet_node_temp_sensor.name}>#{oa_db_curve_threshold_temp_SI}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET LeftCurveInput_#{counter}=C1_a#{counter}+(C2_a#{counter}*IVOnea_#{counter})+(C3_a#{counter}*IVOnea_#{counter}*IVonea_#{counter})\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET RightCurveInput_#{counter}=(C4_a#{counter}*IVTwo_#{counter})+(C5_a#{counter}*IVTwo_#{counter}*IVTwo_#{counter})+(C6_a#{counter}*IVThree_#{counter})\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET CurveInput_#{counter}=LeftCurveInput_#{counter} + RightCurveInput_#{counter}\")\n ems_curve_overwrite_mngr_prgm.addLine(\"ENDIF\")\n ems_curve_overwrite_mngr_prgm.addLine(\"SET #{ems_clg_cap_func_temp_curve_actuator.name} = CurveInput_#{counter}\")\n \n # create new OutputVariable object describing info at the requested reporting frequency\n erl_curve_value_output_variable = OpenStudio::Model::OutputVariable.new(\"#{ems_erl_curve_value_ov.name}\",model)\n erl_curve_value_output_variable.setKeyValue(\"*\") \n erl_curve_value_output_variable.setReportingFrequency(\"Hourly\") \n if verbose_info_statements == true\n runner.registerInfo(\"EnergyPlus Output Variable object named #{ems_erl_curve_value_ov.name} added to the .rdd file for post-processing.\") \n end\n \n # create new OutputVariable object describing info at the requested reporting frequency\n erl_curve_value_output_variable = OpenStudio::Model::OutputVariable.new(\"#{ems_old_curve_value_gv.name}\",model)\n erl_curve_value_output_variable.setKeyValue(\"*\") \n erl_curve_value_output_variable.setReportingFrequency(\"Hourly\") \n if verbose_info_statements == true\n runner.registerInfo(\"EnergyPlus Output Variable object named #{ems_old_curve_value_gv.name} added to the .rdd file for post-processing.\") \n end\n \n # create new OutputVariable object describing info at the requested reporting frequency\n erl_curve_value_output_variable = OpenStudio::Model::OutputVariable.new(\"#{ems_new_curve_value_gv.name}\",model)\n erl_curve_value_output_variable.setKeyValue(\"*\") \n erl_curve_value_output_variable.setReportingFrequency(\"Hourly\") \n if verbose_info_statements == true\n runner.registerInfo(\"EnergyPlus Output Variable object named #{ems_new_curve_value_gv.name} added to the .rdd file for post-processing.\") \n end\n \n end # end loop through selected dx cooling coils \n\n # create new OutputVariable object describing info at the requested reporting frequency\n output_variable_oa_db = OpenStudio::Model::OutputVariable.new(\"Site Outdoor Air Drybulb Temperature\",model)\n output_variable_oa_db.setKeyValue(\"*\")\n output_variable_oa_db.setReportingFrequency(\"Hourly\") \n output_variable_oa_db.setVariableName(\"Site Outdoor Air Drybulb Temperature\")\n if verbose_info_statements == true\n runner.registerInfo(\"EnergyPlus Output Variable object named #{output_variable_oa_db.name} added to the .rdd file for post-processing.\") \n end\n \n # create OutputEnergyManagementSystem object (a 'unique' object) and configure to allow EMS reporting\n output_EMS = model.getOutputEnergyManagementSystem\n output_EMS.setInternalVariableAvailabilityDictionaryReporting(\"internal_variable_availability_dictionary_reporting\")\n output_EMS.setEMSRuntimeLanguageDebugOutputLevel(\"ems_runtime_language_debug_output_level\")\n output_EMS.setActuatorAvailabilityDictionaryReporting(\"actuator_availability_dictionary_reporting\")\n if verbose_info_statements == true\n runner.registerInfo(\"Output EMS Program Object settings configured for the model.\") \n end\n \n runner.registerFinalCondition(\"Measure finished with #{model.getEnergyManagementSystemSensors.count} EMS sensors, #{model.getEnergyManagementSystemActuators.count} EMS Actuators, #{model.getEnergyManagementSystemPrograms.count} EMS Programs, #{model.getEnergyManagementSystemSubroutines.count} EMS Subroutines, #{model.getEnergyManagementSystemProgramCallingManagers.count} EMS Program Calling Manager objects\")\n\n end", "def runs=(_arg0); end", "def after=(_arg0); end", "def total_time=(_arg0); end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n return false unless runner.validateUserArguments(arguments(model), user_arguments)\n\n # assign the user inputs to variables\n setpoint = runner.getDoubleArgumentValue(\"setpoint_temperature\", user_arguments)\n delta = runner.getDoubleArgumentValue(\"design_delta\", user_arguments)\n\n # This measure only works with the predifined loop name of `Ambient Loop`\n plant_loop = model.getPlantLoopByName('Ambient Loop').get\n\n # try and set the temperature of the ambient loop - this includes setting the\n # plant loop min/max temperatures, the sizing plant objects, and the schedules\n loop_sizing = plant_loop.sizingPlant\n loop_sizing.setDesignLoopExitTemperature(setpoint)\n loop_sizing.setLoopDesignTemperatureDifference(delta)\n\n plant_loop.supplyOutletNode.setpointManagers.each {|sm| sm.remove}\n\n amb_loop_schedule = OpenStudio::Model::ScheduleRuleset.new(model)\n amb_loop_schedule.setName(\"Ambient Loop Temperature Ruleset\")\n amb_loop_schedule.defaultDaySchedule.setName(\"Ambient Loop Temperature - Default\")\n amb_loop_schedule.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), setpoint)\n\n amb_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, amb_loop_schedule)\n amb_stpt_manager.setName('Ambient Loop Setpoint Manager - Scheduled')\n amb_stpt_manager.setControlVariable(\"Temperature\")\n amb_stpt_manager.addToNode(plant_loop.supplyOutletNode)\n\n # report final condition of model\n runner.registerFinalCondition(\"The final maximum loop temperature is: #{setpoint}\")\n\n return true\n end", "def runs; end", "def finish(options); end", "def args(*) end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end \n \n #initialize variables\n zone_hvac_count = 0\n pump_count = 0\n air_loop_count = 0\n \n #loop through each air loop in the model\n model.getAirLoopHVACs.sort.each do |air_loop|\n\n # call the method to generate a new occupancy schedule based on a 5% threshold\n occ_sch = air_loop.get_occupancy_schedule(0.15)\n old_sch = air_loop.availabilitySchedule\n next unless compare_eflh(runner, old_sch, occ_sch)\n # set the availability schedule of the airloop to the newly generated schedule\n air_loop.setAvailabilitySchedule(occ_sch)\n runner.registerInfo(\"The availability schedule named #{old_sch.name} for #{air_loop.name} was replaced with a new schedule named #{occ_sch.name} which tracks the occupancy profile of the thermal zones on this airloop.\")\n air_loop_count +=1\n \n end\n\n #loop through each thermal zone\n model.getThermalZones.sort.each do |thermal_zone|\n \n # zone equipments assigned to thermal zones\n thermal_zone_equipment = thermal_zone.equipment \n \n if thermal_zone_equipment.size >= 1\n # run schedule method to create a new schedule ruleset, routines \n occ_sch = thermal_zone.get_occupancy_schedule(0.15)\n \n #loop through Zone HVAC Equipment\n thermal_zone_equipment.each do |equip|\n \n # getting the fan exhaust object & getting relevant information for it. \n if equip.to_FanZoneExhaust.is_initialized\n zone_equip = equip.to_FanZoneExhaust.get\n old_schedule = zone_equip.availabilitySchedule.get\n next unless compare_eflh(runner, old_schedule, occ_sch)\n #assign the 'occ_sch' here as exhaust's availability schedule\n zone_equip.setAvailabilitySchedule(occ_sch)\n runner.registerInfo(\"The availability schedule named #{old_schedule.name} for the OS_Fan_ZoneExhaust named #{zone_equip.name} was replaced with a new schedule named #{occ_sch.name} representing the occupancy profile of the thermal zone named #{thermal_zone.name}.\")\n zone_hvac_count += 1 \t\n elsif equip.to_RefrigerationAirChiller.is_initialized\n zone_equip = equip.to_RefrigerationAirChiller.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_WaterHeaterHeatPump.is_initialized\n zone_equip = equip.to_WaterHeaterHeatPump.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardConvectiveElectric.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardConvectiveElectric.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardConvectiveWater.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardConvectiveWater.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardRadiantConvectiveElectric.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardRadiantConvectiveElectric.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACBaseboardRadiantConvectiveWater.is_initialized\n zone_equip = equip.to_ZoneHVACBaseboardRadiantConvectiveWater.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACDehumidifierDX.is_initialized\n zone_equip = equip.to_ZoneHVACDehumidifierDX.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACEnergyRecoveryVentilator.is_initialized\n zone_equip = equip.to_ZoneHVACEnergyRecoveryVentilator.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\n elsif equip.to_ZoneHVACFourPipeFanCoil.is_initialized\n zone_equip = equip.to_ZoneHVACFourPipeFanCoil.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneHVACHighTemperatureRadiant.is_initialized\n zone_equip = equip.to_ZoneHVACHighTemperatureRadiant.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\n elsif equip.to_ZoneHVACIdealLoadsAirSystem.is_initialized\n zone_equip = equip.to_ZoneHVACIdealLoadsAirSystem.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t \n elsif equip.to_ZoneHVACLowTemperatureRadiantElectric.is_initialized\n zone_equip = equip.to_ZoneHVACLowTemperatureRadiantElectric.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneHVACLowTempRadiantConstFlow.is_initialized\n zone_equip = equip.to_ZoneHVACLowTempRadiantConstFlow.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t \t\n elsif equip.to_ZoneHVACLowTempRadiantVarFlow.is_initialized\n zone_equip = equip.to_ZoneHVACLowTempRadiantVarFlow.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized\n zone_equip = equip.to_ZoneHVACPackagedTerminalAirConditioner.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACPackagedTerminalHeatPump.is_initialized\n zone_equip = equip.to_ZoneHVACPackagedTerminalHeatPump.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\n elsif equip.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.is_initialized\n next unless compare_eflh(runner, old_schedule, occ_sch) \n equip.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.get.setTerminalUnitAvailabilityschedule(occ_sch)\n runner.registerInfo(\"The availability schedule for the Zone HVAC Terminal Unit Variable Refrigerant Flow Object has been replaced with a new schedule named #{occ_sch.name} representing the occupancy profile of the thermal zone named #{thermal_zone.name}.\")\t\t\t\t\t\n zone_hvac_count += 1 \n elsif equip.to_ZoneHVACUnitHeater.is_initialized\n zone_equip = equip.to_ZoneHVACUnitHeater.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\n elsif equip.to_ZoneHVACUnitVentilator.is_initialized\n zone_equip = equip.to_ZoneHVACUnitVentilator.get\n zone_hvac_count += 1 if set_equip_availability_schedule(runner, thermal_zone, occ_sch, zone_equip)\t\t\t\t\t\n elsif equip.to_ZoneVentilationDesignFlowRate.is_initialized\n runner.registerInfo(\"Thermal Zone named #{thermal_zone.name} has a Zone Ventilation Design Flow Rate object attacjhed as a ZoneHVACEquipment object. No modification were made to this object.\")\t\t\n end \t\n \n end # end loop through Zone HVAC Equipment\n \n else\n runner.registerInfo(\"Thermal Zone named #{thermal_zone.name} has no Zone HVAC Equipment objects attached - therefore no schedule objects have been altered.\")\t\n end # end of if statement\n \n end # end loop through thermal zones\n\n # Change pump control status if any airloops or\n # zone equipment were changed.\n if air_loop_count > 0 || zone_hvac_count > 0\n model.getPlantLoops.each do |plantLoop|\n #Loop through each plant loop demand component\n plantLoop.demandComponents.each do |dc|\n if dc.to_PumpConstantSpeed.is_initialized\n cs_pump = dc.to_PumpConstantSpeed.get\n if cs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Demand side Constant Speed Pump object named #{cs_pump.name} on the plant loop named #{dc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Pump Control Type attribute of Demand side Constant Speed Pump object named #{cs_pump.name} on the plant loop named #{dc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end\n end\n \n if dc.to_PumpVariableSpeed.is_initialized\n vs_pump = dc.to_PumpVariableSpeed.get\n if vs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Demand side Variable Speed Pump named #{vs_pump.name} on the plant loop named #{dc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Demand side Pump Control Type attribute of Variable Speed Pump named #{vs_pump.name} on the plant loop named #{dc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end\n end\n end\n \n #Loop through each plant loop supply component\n plantLoop.supplyComponents.each do |sc|\n if sc.to_PumpConstantSpeed.is_initialized\n cs_pump = sc.to_PumpConstantSpeed.get\n if cs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Supply side Constant Speed Pump object named #{cs_pump.name} on the plant loop named #{sc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Supply Side Pump Control Type atteribute of Constant Speed Pump named #{cs_pump.name} on the plant loop named #{sc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end #end if statement\t\n end #end if statement for changing supply component constant speed pump objects\n \n if sc.to_PumpVariableSpeed.is_initialized\n vs_pump = sc.to_PumpVariableSpeed.get\n if vs_pump.pumpControlType == (\"Intermittent\")\n runner.registerInfo(\"Supply side Variable Speed Pump object named #{vs_pump.name} on the plant loop named #{sc.name} had a pump control type attribute already set to intermittent. No changes will be made to this object.\")\n else \n cs_pump.setPumpControlType(\"Intermittent\")\n runner.registerInfo(\"Pump Control Type attribute of Supply Side Variable Speed Pump named #{vs_pump.name} on the plant loop named #{sc.name} was changed from continuous to intermittent.\")\n pump_count +=1\n end #end if statement\t\n end #end if statement for changing supply component variable speed pump objects\n \n end # end loop throught plant loop supply side components\n \n end # end loop through plant loops\n end\n \n #Write N/A message\n if air_loop_count == 0 && zone_hvac_count == 0 && pump_count == 0 \n runner.registerAsNotApplicable(\"The model did not contain any Airloops, Thermal Zones having ZoneHVACEquipment objects or associated plant loop pump objects to act upon. The measure is not applicable.\")\n return true\n end\t\n \n #report initial condition of model\n runner.registerInitialCondition(\"The model started with #{air_loop_count} AirLoops, #{zone_hvac_count} Zone HVAC Equipment Object and #{pump_count} pump objects subject to modifications.\")\n \n # report final condition of model\n runner.registerFinalCondition(\"The measure modified the availability schedules of #{air_loop_count} AirLoops and #{zone_hvac_count} Zone HVAC Equipment objects. #{pump_count} pump objects had control settings modified.\")\n \n # Add ASHRAE Standard 55 warnings\n reporting_frequency = \"Timestep\"\n outputVariable = OpenStudio::Model::OutputVariable.new(\"Zone Thermal Comfort ASHRAE 55 Adaptive Model 90% Acceptability Status []\",model)\n outputVariable.setReportingFrequency(reporting_frequency)\n runner.registerInfo(\"Adding output variable for 'Zone Thermal Comfort ASHRAE 55 Adaptive Model 90% Acceptability Status' reporting at the model timestep.\")\n \n return true\n\t\n end", "def measure_code(model,runner)\n ################ Start Measure code here ################################\n # Argument will be passed as instance variable. So if your argument was height, your can access it using @height. \n\n # report initial condition\n site = model.getSite\n initial_design_days = model.getDesignDays\n if site.weatherFile.is_initialized\n weather = site.weatherFile.get\n runner.registerInitialCondition(\"The initial weather file path was '#{weather.path.get}' and the model had #{initial_design_days.size} design days.\")\n else\n runner.registerInitialCondition(\"The initial weather file has not been set and the model had #{initial_design_days.size} design days.\")\n end\n\n\n #Check form weather directory Weather File\n unless (Pathname.new @weather_directory).absolute?\n @weather_directory = File.expand_path(File.join(File.dirname(__FILE__), @weather_directory))\n end\n weather_file = File.join(@weather_directory, @weather_file_name)\n if File.exists?(weather_file) and @weather_file_name.downcase.include? \".epw\"\n BTAP::runner_register(\"Info\", \"The epw weather file #{weather_file} was found!\", runner)\n else\n BTAP::runner_register(\"Error\",\"'#{weather_file}' does not exist or is not an .epw file.\", runner)\n return false\n end\n\n begin\n weather = BTAP::Environment::WeatherFile.new(weather_file)\n #Set Weather file to model.\n weather.set_weather_file(model)\n #Store information about this run in the runner for output. This will be in the csv and R dumps.\n runner.registerValue( 'city',weather.city )\n runner.registerValue( 'state_province_region ',weather.state_province_region )\n runner.registerValue( 'country',weather.country )\n runner.registerValue( 'hdd18',weather.hdd18 )\n runner.registerValue( 'cdd18',weather.cdd18 )\n runner.registerValue( 'necb_climate_zone',BTAP::Compliance::NECB2011::get_climate_zone_name(weather.hdd18).to_s)\n runner.registerFinalCondition( \"Model ended with weatherfile of #{model.getSite.weatherFile.get.path.get}\" )\n rescue\n BTAP::runner_register(\"Error\",\"'#{weather_file}' could not be loaded into model.\", runner)\n\n return false\n end\n BTAP::runner_register(\"FinalCondition\",\"Weather file set to #{weather_file}\",runner)\n return true\n end", "def run(workspace, runner, user_arguments)\n super(workspace, runner, user_arguments)\n\n #use the built-in error checking \n if not runner.validateUserArguments(arguments(workspace), user_arguments)\n return false\n end\n \n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue(\"run_measure\",user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true \n end\n \n require 'json'\n \n # Get the last openstudio model\n model = runner.lastOpenStudioModel\n if model.empty?\n runner.registerError(\"Could not load last OpenStudio model, cannot apply measure.\")\n return false\n end\n model = model.get\n \n results = {}\n airloop_name = []\n # Loop over the airloops to find valid ones for this measure\n model.getAirLoopHVACs.each do |air_loop|\n found_coil = 0 #have not found any cooling coils\n found_hcoil = 0 #have not found any heating coils\n found_fan = 0 #have not found any fans \n temp = {}\n air_loop.supplyComponents.each do |component|\n # Get the unitary equipment\n if component.to_AirLoopHVACUnitaryHeatPumpAirToAir.is_initialized\n unitary = component.to_AirLoopHVACUnitaryHeatPumpAirToAir.get\n # Get the cooling coil from inside the unitary equipment\n if unitary.coolingCoil.to_CoilCoolingDXSingleSpeed.is_initialized\n clg_coil = unitary.coolingCoil.to_CoilCoolingDXSingleSpeed.get\n runner.registerInfo(\"Found #{clg_coil.name} on #{air_loop.name}\")\n found_coil += 1 #found necessary cooling coil DX singlespeed\n temp[:cool_coil] = \"#{clg_coil.name}\"\n end\n # get heating coil\n if unitary.heatingCoil.to_CoilHeatingDXSingleSpeed.is_initialized\n htg_coil = unitary.heatingCoil.to_CoilHeatingDXSingleSpeed.get\n runner.registerInfo(\"Found #{htg_coil.name} on #{air_loop.name}\")\n found_hcoil += 1 #found necessary cooling coil DX singlespeed\n temp[:heat_coil] = \"#{htg_coil.name}\"\n end\n # get the supply fan from inside the unitary equipment\n if unitary.supplyAirFan.to_FanConstantVolume.is_initialized\n supply_fan = unitary.supplyAirFan.to_FanConstantVolume.get\n runner.registerInfo(\"Found #{supply_fan.name} on #{air_loop.name}\")\n found_fan += 1 #found necessary Fan object\n temp[:fan] = \"#{supply_fan.name}\"\n elsif unitary.supplyAirFan.to_FanOnOff.is_initialized\n supply_fan = unitary.supplyAirFan.to_FanOnOff.get\n runner.registerInfo(\"Found #{supply_fan.name} on #{air_loop.name}\")\n found_fan += 1 #found necessary Fan object\n temp[:fan] = \"#{supply_fan.name}\"\n else\n runner.registerInfo(\"No OnOff or Constant Volume Fan in the Unitary system on #{air_loop.name}\") \n end\n end\n # Get the cooling coil directly from the airloop\n if component.to_CoilCoolingDXSingleSpeed.is_initialized\n clg_coil = component.to_CoilCoolingDXSingleSpeed.get\n runner.registerInfo(\"Found #{clg_coil.name} on #{air_loop.name}\")\n found_coil += 1 #found necessary cooling coil DX singlespeed\n temp[:cool_coil] = \"#{clg_coil.name}\"\n \n # Get the heating coil directly from the airloop\n elsif component.to_CoilHeatingDXSingleSpeed.is_initialized\n htg_coil = component.to_CoilHeatingDXSingleSpeed.get\n runner.registerInfo(\"Found #{htg_coil.name} on #{air_loop.name}\")\n found_hcoil += 1 #found necessary heating coil DX singlespeed\n temp[:heat_coil] = \"#{htg_coil.name}\"\n \n # Get the heating coil directly from the airloop\n elsif component.to_CoilHeatingGas.is_initialized\n htg_coil = component.to_CoilHeatingGas.get\n runner.registerInfo(\"Found #{htg_coil.name} on #{air_loop.name}\")\n found_hcoil += 1 #found necessary heating coil gas\n temp[:heat_coil] = \"#{htg_coil.name}\"\n \n # Get the heating coil directly from the airloop\n elsif component.to_CoilHeatingElectric.is_initialized\n htg_coil = component.to_CoilHeatingElectric.get\n runner.registerInfo(\"Found #{htg_coil.name} on #{air_loop.name}\")\n found_hcoil += 1 #found necessary heating coil gas\n temp[:heat_coil] = \"#{htg_coil.name}\"\n \n # get the supply fan directly from the airloop\n elsif component.to_FanConstantVolume.is_initialized\n supply_fan = component.to_FanConstantVolume.get\n runner.registerInfo(\"Found #{supply_fan.name} on #{air_loop.name}\")\n found_fan += 1 #found necessary Fan object\n temp[:fan] = \"#{supply_fan.name}\"\n \n elsif component.to_FanOnOff.is_initialized\n supply_fan = component.to_FanOnOff.get\n runner.registerInfo(\"Found #{supply_fan.name} on #{air_loop.name}\")\n found_fan += 1 #found necessary Fan object\n temp[:fan] = \"#{supply_fan.name}\"\n end\n end\n runner.registerInfo(\"airloop #{air_loop.name} found = #{(found_coil + found_fan)}\")\n found_oa = 0\n found_act = 0\n found_oasch = 0\n found_oafsch = 0\n #found too many objects on an airloop\n if (found_coil + found_hcoil + found_fan) > 3\n runner.registerInfo(\"Too many objects on airloop #{air_loop.name}. Airloop N/A\")\n #found a Fan and Cooling Coil DX Single Speed, get rest of info\n elsif (found_coil + found_hcoil + found_fan) < 3\n runner.registerInfo(\"Not enough objects on airloop #{air_loop.name}. Airloop N/A\")\n elsif (found_coil + found_hcoil + found_fan) == 3 \n # get outdoorair controller\n if air_loop.airLoopHVACOutdoorAirSystem.is_initialized\n controller_oa = air_loop.airLoopHVACOutdoorAirSystem.get.getControllerOutdoorAir\n runner.registerInfo(\"Found #{controller_oa.name} on #{air_loop.name}\")\n found_oa += 1 #found necessary OA controller\n temp[:controller_oa] = \"#{controller_oa.name}\"\n # get actuator node name\n actuatorNodeName = air_loop.airLoopHVACOutdoorAirSystem.get.outboardOANode.get.name.get\n runner.registerInfo(\"Found #{actuatorNodeName} on #{air_loop.name}\")\n found_act += 1 #found necessary actuator node\n temp[:actuatorNodeName] = \"#{actuatorNodeName}\"\n # get minimumFractionofOutdoorAirSchedule\n minimumFractionofOutdoorAirSchedule = controller_oa.minimumFractionofOutdoorAirSchedule\n # get minimumOutdoorAirSchedule\n minimumOutdoorAirSchedule = controller_oa.minimumOutdoorAirSchedule\n if minimumFractionofOutdoorAirSchedule.is_initialized && minimumOutdoorAirSchedule.is_initialized\n runner.registerWarning(\"Both minimumOutdoorAirSchedule and minimumFractionofOutdoorAirSchedule in Airloop #{air_loop.name} are missing.\")\n end\n if minimumFractionofOutdoorAirSchedule.is_initialized\n runner.registerInfo(\"Found #{minimumFractionofOutdoorAirSchedule.get.name} on #{air_loop.name}\")\n found_oafsch += 1 #found necessary fraction OA schedule\n temp[:minimumFractionofOutdoorAirSchedule] = \"#{minimumFractionofOutdoorAirSchedule.get.name}\"\n # else\n # always_on = model.alwaysOnDiscreteSchedule\n # controller_oa.setMinimumFractionofOutdoorAirSchedule(always_on)\n # runner.registerInfo(\"Added #{controller_oa.minimumFractionofOutdoorAirSchedule.get.name} on #{air_loop.name}\")\n # runner.registerWarning(\"Added #{controller_oa.minimumFractionofOutdoorAirSchedule.get.name} on #{air_loop.name}\")\n # found_oafsch += 1 #added necessary fraction OA schedule\n # temp[:minimumFractionofOutdoorAirSchedule] = \"#{controller_oa.minimumFractionofOutdoorAirSchedule.get.name}\"\n end\n if minimumOutdoorAirSchedule.is_initialized\n runner.registerInfo(\"Found #{minimumOutdoorAirSchedule.get.name} on #{air_loop.name}\")\n found_oasch += 1 #found necessary OA schedule\n temp[:minimumOutdoorAirSchedule] = \"#{minimumOutdoorAirSchedule.get.name}\"\n else\n # always_on = model.alwaysOnDiscreteSchedule\n # controller_oa.setMinimumOutdoorAirSchedule(always_on)\n always_on_eplus = \"Schedule:Constant,\n AlwaysOn, !- Name\n , !- Schedule Type Limits Name\n 1.0; !- Hourly Value\n \"\n idfObject = OpenStudio::IdfObject::load(always_on_eplus)\n #add to workspace\n always_on_eplus_object = workspace.addObject(idfObject.get).get\n outdoorAirControllerObjects = workspace.getObjectsByType(\"Controller:OutdoorAir\".to_IddObjectType)\n outdoorAirControllerObjects do |oa|\n if oa.name.to_s == controller_oa.name.to_s\n oa.setPointer(17, always_on_eplus_object.handle)\n end\n end \n runner.registerInfo(\"Added #{always_on_eplus_object.name.get} on #{air_loop.name}\")\n runner.registerWarning(\"Added #{always_on_eplus_object.name.get} on #{air_loop.name}\")\n found_oasch += 1 #added necessary OA schedule\n temp[:minimumOutdoorAirSchedule] = \"#{always_on_eplus_object.name.get}\"\n end\n end\n if (found_oasch + found_act + found_oa) == 3 #add valid air loop to results\n results[\"#{air_loop.name}\"] = temp\n airloop_name << \"#{air_loop.name}\"\n runner.registerInfo(\"Adding valid AirLoop #{air_loop.name} to results.\")\n end \n end\n end\n #save airloop parsing results to ems_results.json\n runner.registerInfo(\"Saving ems_results.json\")\n FileUtils.mkdir_p(File.dirname(\"ems_results.json\")) unless Dir.exist?(File.dirname(\"ems_results.json\"))\n File.open(\"ems_results.json\", 'w') {|f| f << JSON.pretty_generate(results)}\n \n if results.empty?\n runner.registerWarning(\"No Airloops are appropriate for this measure\")\n runner.registerAsNotApplicable(\"No Airloops are appropriate for this measure\")\n #save blank ems_advanced_rtu_controls.ems file so Eplus measure does not crash\n ems_string = \"\"\n runner.registerInfo(\"Saving blank ems_advanced_rtu_controls file\")\n FileUtils.mkdir_p(File.dirname(\"ems_advanced_rtu_controls.ems\")) unless Dir.exist?(File.dirname(\"ems_advanced_rtu_controls.ems\"))\n File.open(\"ems_advanced_rtu_controls.ems\", \"w\") do |f|\n f.write(ems_string)\n end\n return true\n end\n \n runner.registerInfo(\"Making EMS string for Advanced RTU Controls\")\n #start making the EMS code\n ems_string = \"\" #clear out the ems_string\n \n ems_string << \"EnergyManagementSystem:GlobalVariable,\" + \"\\n\"\n ems_string << \" FanPwrExp, ! Exponent used in fan power law\" + \"\\n\"\n ems_string << \" Stage1Speed, ! Fan speed in cooling mode\" + \"\\n\"\n ems_string << \" HeatSpeed, ! Fan speed in heating mode\" + \"\\n\"\n ems_string << \" VenSpeed, ! Fan speed in ventilation mode\" + \"\\n\"\n ems_string << \" EcoSpeed; ! Fan speed in economizer mode\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \"EnergyManagementSystem:Program,\" + \"\\n\"\n ems_string << \" Set_FanCtl_Par1,\" + \"\\n\"\n ems_string << \" SET FanPwrExp = 2.2,\" + \"\\n\"\n ems_string << \" SET HeatSpeed = 0.9,\" + \"\\n\"\n ems_string << \" SET VenSpeed = 0.4,\" + \"\\n\"\n ems_string << \" SET Stage1Speed = 0.9,\" + \"\\n\"\n ems_string << \" SET EcoSpeed = 0.75,\" + \"\\n\"\n results.each_with_index do |(key, value), i| \n if i < results.size - 1\n ems_string << \" SET PSZ#{i}_OADesignMass = PSZ#{i}_DesignOAFlowMass,\" + \"\\n\"\n else\n ems_string << \" SET PSZ#{i}_OADesignMass = PSZ#{i}_DesignOAFlowMass;\" + \"\\n\"\n end\n end\n\n ems_string << \"\\n\"\n ems_string << \"EnergyManagementSystem:ProgramCallingManager,\" + \"\\n\"\n ems_string << \" Fan_Parameter_manager, !- Name\" + \"\\n\"\n ems_string << \" BeginNewEnvironment, !- EnergyPlus Model Calling Point\" + \"\\n\"\n ems_string << \" Set_FanCtl_Par1; !- Program Name 1\" + \"\\n\"\n ems_string << \"\\n\"\n\n results.each_with_index do |(key, value), i|\n ems_string << \"EnergyManagementSystem:InternalVariable,\" + \"\\n\"\n ems_string << \" PSZ#{i}_DesignOAFlowMass, !- Name \" + \"\\n\"\n ems_string << \" #{value[:controller_oa]}, !- Internal Data Index Key Name\" + \"\\n\"\n ems_string << \" Outdoor Air Controller Minimum Mass Flow Rate; !- Internal Data Type\" + \"\\n\"\n ems_string << \"\\n\"\n end\n\n results.each_with_index do |(key, value), i|\n ems_string << \"EnergyManagementSystem:InternalVariable,\" + \"\\n\"\n ems_string << \" PSZ#{i}_FanDesignPressure, !- Name \" + \"\\n\"\n ems_string << \" #{value[:fan]}, !- Internal Data Index Key Name\" + \"\\n\"\n ems_string << \" Fan Nominal Pressure Rise; !- Internal Data Type\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \"EnergyManagementSystem:InternalVariable,\" + \"\\n\"\n ems_string << \" PSZ#{i}_DesignFlowMass, !- Name \" + \"\\n\"\n ems_string << \" #{value[:controller_oa]}, !- Internal Data Index Key Name\" + \"\\n\"\n ems_string << \" Outdoor Air Controller Maximum Mass Flow Rate; !- Internal Data Type\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \"EnergyManagementSystem:Sensor,\" + \"\\n\"\n ems_string << \" PSZ#{i}_OASch,\" + \"\\n\"\n ems_string << \" #{value[:minimumOutdoorAirSchedule]},\" + \"\\n\"\n ems_string << \" Schedule Value;\" + \"\\n\"\n ems_string << \"\\n\"\n if !value[:minimumFractionofOutdoorAirSchedule].nil?\n ems_string << \"EnergyManagementSystem:Sensor,\" + \"\\n\"\n ems_string << \" PSZ#{i}_OAFracSch,\" + \"\\n\"\n ems_string << \" #{value[:minimumFractionofOutdoorAirSchedule]},\" + \"\\n\"\n ems_string << \" Schedule Value;\" + \"\\n\"\n ems_string << \"\\n\"\n end\n ems_string << \"EnergyManagementSystem:Sensor,\" + \"\\n\"\n ems_string << \" PSZ#{i}_OAFlowMass,\" + \"\\n\"\n ems_string << \" #{value[:actuatorNodeName]},\" + \"\\n\"\n ems_string << \" System Node Mass Flow Rate;\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \"EnergyManagementSystem:Sensor,\" + \"\\n\"\n ems_string << \" PSZ#{i}_HtgRTF,\" + \"\\n\"\n ems_string << \" #{value[:heat_coil]},\" + \"\\n\"\n ems_string << \" Heating Coil Runtime Fraction;\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \"EnergyManagementSystem:Sensor,\" + \"\\n\"\n ems_string << \" PSZ#{i}_ClgRTF,\" + \"\\n\"\n ems_string << \" #{value[:cool_coil]},\" + \"\\n\"\n ems_string << \" Cooling Coil Runtime Fraction;\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \"EnergyManagementSystem:Actuator,\" + \"\\n\"\n ems_string << \" PSZ#{i}_FanPressure, ! Name \" + \"\\n\"\n ems_string << \" #{value[:fan]}, ! Actuated Component Unique Name\" + \"\\n\"\n ems_string << \" Fan, ! Actuated Component Type\" + \"\\n\"\n ems_string << \" Fan Pressure Rise; ! Actuated Component Control Type\" + \"\\n\"\n ems_string << \"\\n\"\n end\n\n results.each_with_index do |(key, value), i|\n ems_string << \"EnergyManagementSystem:Program,\" + \"\\n\"\n ems_string << \" PSZ#{i}_FanControl, !- Name\" + \"\\n\"\n ems_string << \" IF PSZ#{i}_HtgRTF > 0,\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Htg = PSZ#{i}_HtgRTF, ! Percent of time in heating mode\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Ven = 1 - PSZ#{i}_HtgRTF, ! Percent of time in ventilation mode\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Eco = 0, ! Percent of time in economizer mode\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Stage1 = 0, ! Percent of time in DX cooling\" + \"\\n\"\n ems_string << \" ELSE,\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Htg = 0,\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_MinOA1 = PSZ#{i}_OADesignMass * PSZ#{i}_OASch,\" + \"\\n\"\n if !value[:minimumFractionofOutdoorAirSchedule].nil?\n ems_string << \" SET PSZ#{i}_MinOA2 = PSZ#{i}_DesignFlowMass * PSZ#{i}_OAFracSch,\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_MinOA = @Max PSZ#{i}_MinOA1 PSZ#{i}_MinOA2, \" + \"\\n\"\n else\n ems_string << \" SET PSZ#{i}_MinOA = PSZ#{i}_MinOA1, \" + \"\\n\"\n end\n ems_string << \" IF PSZ#{i}_ClgRTF > 0, ! Mechanical cooling is on\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Stage1 = PSZ#{i}_ClgRTF,\" + \"\\n\"\n ems_string << \" IF PSZ#{i}_OAFlowMass > PSZ#{i}_MinOA, ! Integrated Economzing mode\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Eco = 1-PSZ#{i}_ClgRTF, \" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Ven = 0,\" + \"\\n\"\n ems_string << \" ELSE,\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Eco = 0,\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Ven = 1-PSZ#{i}_ClgRTF,\" + \"\\n\"\n ems_string << \" ENDIF,\" + \"\\n\"\n ems_string << \" ELSE, ! Mechanical cooling is off\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Stage1 = 0, \" + \"\\n\"\n ems_string << \" IF PSZ#{i}_OAFlowMass > PSZ#{i}_MinOA, ! Economizer mode\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Eco = 1.0,\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Ven = 0,\" + \"\\n\"\n ems_string << \" ELSE,\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Eco = 0,\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_Ven = 1.0,\" + \"\\n\"\n ems_string << \" ENDIF,\" + \"\\n\"\n ems_string << \" ENDIF,\" + \"\\n\"\n ems_string << \" ENDIF,\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \" ! For each mode, (percent time in mode) * (fanSpeed^PwrExp) is the contribution to weighted fan power over time step\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_FPR = PSZ#{i}_Ven * (VenSpeed ^ FanPwrExp),\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_FPR = PSZ#{i}_FPR + PSZ#{i}_Eco * (EcoSpeed ^ FanPwrExp),\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_FPR1 = PSZ#{i}_Stage1 * (Stage1Speed ^ FanPwrExp),\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_FPR = PSZ#{i}_FPR + PSZ#{i}_FPR1,\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_FPR3 = PSZ#{i}_Htg * (HeatSpeed ^ FanPwrExp),\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_FanPwrRatio = PSZ#{i}_FPR + PSZ#{i}_FPR3,\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \" ! System fan power is directly proportional to static pressure, so this change linearly adjusts fan energy for speed control\" + \"\\n\"\n ems_string << \" SET PSZ#{i}_FanPressure = PSZ#{i}_FanDesignPressure * PSZ#{i}_FanPwrRatio;\" + \"\\n\"\n ems_string << \"\\n\"\n ems_string << \"EnergyManagementSystem:ProgramCallingManager,\" + \"\\n\"\n ems_string << \" PSZ#{i}_Fan_Manager, !- Name\" + \"\\n\"\n ems_string << \" BeginTimestepBeforePredictor, !- EnergyPlus Model Calling Point\" + \"\\n\"\n ems_string << \" PSZ#{i}_FanControl; !- Program Name 1\" + \"\\n\"\n ems_string << \"\\n\"\n end\n \n #save EMS snippet\n runner.registerInfo(\"Saving ems_advanced_rtu_controls file\")\n FileUtils.mkdir_p(File.dirname(\"ems_advanced_rtu_controls.ems\")) unless Dir.exist?(File.dirname(\"ems_advanced_rtu_controls.ems\"))\n File.open(\"ems_advanced_rtu_controls.ems\", \"w\") do |f|\n f.write(ems_string)\n end\n \n #unique initial conditions based on\n runner.registerInitialCondition(\"The building has #{results.length} constant air volume units for which this measure is applicable.\")\n\n #reporting final condition of model\n runner.registerFinalCondition(\"VSDs and associated controls were applied to #{results.length} single-zone, constant air volume units in the model. Airloops affected were #{airloop_name}\")\n\n \n ems_path = '../AdvancedRTUControls/ems_advanced_rtu_controls.ems'\n json_path = '../AdvancedRTUControls/ems_results.json'\n if File.exist? ems_path\n ems_string = File.read(ems_path)\n if File.exist? json_path\n json = JSON.parse(File.read(json_path))\n end\n else\n ems_path2 = Dir.glob('../../**/ems_advanced_rtu_controls.ems')\n ems_path1 = ems_path2[0]\n json_path2 = Dir.glob('../../**/ems_results.json')\n json_path1 = json_path2[0]\n if ems_path2.size > 1\n runner.registerWarning(\"more than one ems_advanced_rtu_controls.ems file found. Using first one found.\")\n end\n if !ems_path1.nil? \n if File.exist? ems_path1\n ems_string = File.read(ems_path1)\n if File.exist? json_path1\n json = JSON.parse(File.read(json_path1))\n else\n runner.registerError(\"ems_results.json file not located\") \n end \n else\n runner.registerError(\"ems_advanced_rtu_controls.ems file not located\")\n end \n else\n runner.registerError(\"ems_advanced_rtu_controls.ems file not located\") \n end\n end\n if json.nil?\n runner.registerError(\"ems_results.json file not located\")\n return false\n end\n\n ##testing code\n # ems_string1 = \"EnergyManagementSystem:Actuator,\n # PSZ0_FanPressure, ! Name \n # Perimeter_ZN_4 ZN PSZ-AC Fan, ! Actuated Component Unique Name\n # Fan, ! Actuated Component Type\n # Fan Pressure Rise; ! Actuated Component Control Type\"\n \n # idf_file1 = OpenStudio::IdfFile::load(ems_string1, 'EnergyPlus'.to_IddFileType).get\n # runner.registerInfo(\"Adding test EMS code to workspace\")\n # workspace.addObjects(idf_file1.objects)\n \n if json.empty?\n runner.registerWarning(\"No Airloops are appropriate for this measure\")\n return true\n end\n \n #get all emsActuators in model to test if there is an EMS conflict\n emsActuator = workspace.getObjectsByType(\"EnergyManagementSystem:Actuator\".to_IddObjectType)\n\n if emsActuator.size == 0\n runner.registerInfo(\"The model does not contain any emsActuators, continuing\")\n else\n runner.registerInfo(\"The model contains #{emsActuator.size} emsActuators, checking if any are attached to Fans.\")\n emsActuator.each_with_index do |emsActuatorObject|\n emsActuatorObject_name = emsActuatorObject.getString(1).to_s # Name\n runner.registerInfo(\"EMS string: #{emsActuatorObject_name}\")\n json.each do |js|\n if (emsActuatorObject_name.eql? js[1][\"fan\"].to_s) && (emsActuatorObject.getString(2).to_s.eql? \"Fan\") && (emsActuatorObject.getString(3).to_s.eql? \"Fan Pressure Rise\")\n runner.registerInfo(\"Actuated Component Unique Name: #{emsActuatorObject.getString(1).to_s}\")\n runner.registerInfo(\"Actuated Component Type: #{emsActuatorObject.getString(2).to_s}\")\n runner.registerInfo(\"Actuated Component Control Type: #{emsActuatorObject.getString(3).to_s}\")\n runner.registerInfo(\"EMS control logic modifying fan pressure rise already exists in the model. EEM not applied\")\n runner.registerAsNotApplicable(\"EMS control logic modifying fan pressure rise already exists in the model. EEM not applied\")\n return true\n else\n runner.registerInfo(\"EMS string: #{js[1][\"fan\"].to_s} has no EMS conflict\")\n end\n end\n end\n end\n \n idf_file = OpenStudio::IdfFile::load(ems_string, 'EnergyPlus'.to_IddFileType).get\n runner.registerInfo(\"Adding EMS code to workspace\")\n workspace.addObjects(idf_file.objects)\n \n return true\n\n end", "def around_perform_stats(*args)\n start = Time.now\n yield\n time_taken = Time.now - start\n statsd.timing(\"duration:#{self}\", time_taken)\n statsd.increment(\"total_successful:#{self}\")\n statsd.increment(\"total_successful\")\n run_hooks(:duration, :duration, args) {|key| statsd.timing(key, time_taken)}\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n \n #use the built-in error checking \n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n \n finished_surfaces = []\n unfinished_surfaces = []\n model.getSpaces.each do |space|\n # Wall between finished space and outdoors\n if Geometry.space_is_finished(space) and Geometry.space_is_above_grade(space)\n space.surfaces.each do |surface|\n next if surface.surfaceType.downcase != \"wall\" or surface.outsideBoundaryCondition.downcase != \"outdoors\"\n finished_surfaces << surface\n end\n # Attic wall under an insulated roof\n elsif Geometry.is_unfinished_attic(space)\n attic_roof_r = Construction.get_space_r_value(runner, space, \"roofceiling\")\n next if attic_roof_r.nil? or attic_roof_r <= 5 # assume uninsulated if <= R-5 assembly\n space.surfaces.each do |surface|\n next if surface.surfaceType.downcase != \"wall\" or surface.outsideBoundaryCondition.downcase != \"outdoors\"\n unfinished_surfaces << surface\n end\n end\n end\n \n # Continue if no applicable surfaces\n if finished_surfaces.empty? and unfinished_surfaces.empty?\n runner.registerAsNotApplicable(\"Measure not applied because no applicable surfaces were found.\")\n return true\n end \n \n # Get inputs\n dsWallCavityInsRvalue = runner.getDoubleArgumentValue(\"cavity_r\",user_arguments)\n\tdsWallInstallGrade = {\"I\"=>1, \"II\"=>2, \"III\"=>3}[runner.getStringArgumentValue(\"install_grade\",user_arguments)]\n dsWallStudDepth = runner.getDoubleArgumentValue(\"stud_depth\",user_arguments)\n\tdsWallGapDepth = runner.getDoubleArgumentValue(\"gap_depth\",user_arguments)\n dsWallFramingFactor = runner.getDoubleArgumentValue(\"framing_factor\",user_arguments)\n dsWallStudSpacing = runner.getDoubleArgumentValue(\"framing_spacing\",user_arguments)\n dsWallIsStaggered = runner.getBoolArgumentValue(\"is_staggered\",user_arguments)\n \n # Validate inputs\n if dsWallCavityInsRvalue <= 0.0\n runner.registerError(\"Cavity Insulation Nominal R-value must be greater than 0.\")\n return false\n end\n if dsWallStudDepth <= 0.0\n runner.registerError(\"Stud Depth must be greater than 0.\")\n return false\n end\n if dsWallGapDepth < 0.0\n runner.registerError(\"Gap Depth must be greater than or equal to 0.\")\n return false\n end\n if dsWallFramingFactor < 0.0 or dsWallFramingFactor >= 1.0\n runner.registerError(\"Framing Factor must be greater than or equal to 0 and less than 1.\")\n return false\n end\n if dsWallStudSpacing <= 0.0\n runner.registerError(\"Framing Spacing must be greater than 0.\")\n return false\n end\n\n # Process the double wood stud walls\n \n # Define materials\n cavityDepth = 2.0 * dsWallStudDepth + dsWallGapDepth\n mat_ins_inner_outer = Material.new(name=nil, thick_in=dsWallStudDepth, mat_base=BaseMaterial.InsulationGenericDensepack, k_in=cavityDepth / dsWallCavityInsRvalue)\n mat_ins_middle = Material.new(name=nil, thick_in=dsWallGapDepth, mat_base=BaseMaterial.InsulationGenericDensepack, k_in=cavityDepth / dsWallCavityInsRvalue)\n mat_framing_inner_outer = Material.new(name=nil, thick_in=dsWallStudDepth, mat_base=BaseMaterial.Wood)\n mat_framing_middle = Material.new(name=nil, thick_in=dsWallGapDepth, mat_base=BaseMaterial.Wood)\n mat_stud = Material.new(name=nil, thick_in=dsWallStudDepth, mat_base=BaseMaterial.Wood)\n mat_gap_total = Material.AirCavityClosed(cavityDepth)\n mat_gap_inner_outer = Material.new(name=nil, thick_in=dsWallStudDepth, mat_base=nil, k_in=dsWallStudDepth / (mat_gap_total.rvalue * dsWallStudDepth / cavityDepth), rho=Gas.Air.rho, cp=Gas.Air.cp)\n mat_gap_middle = Material.new(name=nil, thick_in=dsWallGapDepth, mat_base=nil, k_in=dsWallGapDepth / (mat_gap_total.rvalue * dsWallGapDepth / cavityDepth), rho=Gas.Air.rho, cp=Gas.Air.cp)\n \n # Set paths\n stud_frac = 1.5 / dsWallStudSpacing\n dsWallMiscFramingFactor = dsWallFramingFactor - stud_frac\n if dsWallMiscFramingFactor < 0\n runner.registerError(\"Framing Factor (#{dsWallFramingFactor.to_s}) is less than the framing solely provided by the studs (#{stud_frac.to_s}).\")\n return false\n end\n dsGapFactor = Construction.get_wall_gap_factor(dsWallInstallGrade, dsWallFramingFactor, dsWallCavityInsRvalue)\n path_fracs = [dsWallMiscFramingFactor, stud_frac, stud_frac, dsGapFactor, (1.0 - (2 * stud_frac + dsWallMiscFramingFactor + dsGapFactor))] \n \n if not finished_surfaces.empty?\n # Define construction\n fin_double_stud_wall = Construction.new(path_fracs)\n fin_double_stud_wall.add_layer(Material.AirFilmVertical, false)\n fin_double_stud_wall.add_layer(Material.DefaultWallMass, false) # thermal mass added in separate measure\n fin_double_stud_wall.add_layer([mat_framing_inner_outer, mat_stud, mat_ins_inner_outer, mat_gap_inner_outer, mat_ins_inner_outer], true, \"StudandCavityInner\")\n if dsWallGapDepth > 0\n fin_double_stud_wall.add_layer([mat_framing_middle, mat_ins_middle, mat_ins_middle, mat_gap_middle, mat_ins_middle], true, \"Cavity\")\n end\n if dsWallIsStaggered\n fin_double_stud_wall.add_layer([mat_framing_inner_outer, mat_ins_inner_outer, mat_stud, mat_gap_inner_outer, mat_ins_inner_outer], true, \"StudandCavityOuter\")\n else\n fin_double_stud_wall.add_layer([mat_framing_inner_outer, mat_stud, mat_ins_inner_outer, mat_gap_inner_outer, mat_ins_inner_outer], true, \"StudandCavityOuter\")\n end\n fin_double_stud_wall.add_layer(Material.DefaultWallSheathing, false) # OSB added in separate measure\n fin_double_stud_wall.add_layer(Material.DefaultExteriorFinish, false) # exterior finish added in separate measure\n fin_double_stud_wall.add_layer(Material.AirFilmOutside, false)\n\n # Create and assign construction to surfaces\n if not fin_double_stud_wall.create_and_assign_constructions(finished_surfaces, runner, model, name=\"ExtInsFinWall\")\n return false\n end\n end\n \n if not unfinished_surfaces.empty?\n # Define construction\n unfin_double_stud_wall = Construction.new(path_fracs)\n unfin_double_stud_wall.add_layer(Material.AirFilmVertical, false)\n unfin_double_stud_wall.add_layer([mat_framing_inner_outer, mat_stud, mat_ins_inner_outer, mat_gap_inner_outer, mat_ins_inner_outer], true, \"StudandCavityInner\")\n if dsWallGapDepth > 0\n unfin_double_stud_wall.add_layer([mat_framing_middle, mat_ins_middle, mat_ins_middle, mat_gap_middle, mat_ins_middle], true, \"Cavity\")\n end\n if dsWallIsStaggered\n unfin_double_stud_wall.add_layer([mat_framing_inner_outer, mat_ins_inner_outer, mat_stud, mat_gap_inner_outer, mat_ins_inner_outer], true, \"StudandCavityOuter\")\n else\n unfin_double_stud_wall.add_layer([mat_framing_inner_outer, mat_stud, mat_ins_inner_outer, mat_gap_inner_outer, mat_ins_inner_outer], true, \"StudandCavityOuter\")\n end\n unfin_double_stud_wall.add_layer(Material.DefaultWallSheathing, false) # OSB added in separate measure\n unfin_double_stud_wall.add_layer(Material.DefaultExteriorFinish, false) # exterior finish added in separate measure\n unfin_double_stud_wall.add_layer(Material.AirFilmOutside, false)\n\n # Create and assign construction to surfaces\n if not unfin_double_stud_wall.create_and_assign_constructions(unfinished_surfaces, runner, model, name=\"ExtInsFinWall\")\n return false\n end\n end\n \n # Store info for HVAC Sizing measure\n units = Geometry.get_building_units(model, runner)\n if units.nil?\n return false\n end\n (finished_surfaces + unfinished_surfaces).each do |surface|\n units.each do |unit|\n next if not unit.spaces.include?(surface.space.get)\n unit.setFeature(Constants.SizingInfoWallType(surface), \"DoubleWoodStud\")\n end\n end\n\n # Remove any constructions/materials that aren't used\n HelperMethods.remove_unused_constructions_and_materials(model, runner)\n\n return true\n \n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n #use the built-in error checking\n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n #assign the user inputs to variables\n eff = runner.getDoubleArgumentValue(\"eff\",user_arguments)\n\n #check the user_name for reasonableness\n if eff <= 0\n runner.registerError(\"Please enter a positive value for Nominal Thermal Efficiency.\")\n return false\n end\n if eff > 1\n runner.registerWarning(\"The requested Nominal Thermal Efficiency must be <= 1\")\n end\n \n #change the efficiency of each boiler\n #loop through all the plant loops in the mode\n model.getPlantLoops.each do |plant_loop|\n #loop through all the supply components on this plant loop\n plant_loop.supplyComponents.each do |supply_component|\n #check if the supply component is a boiler\n if not supply_component.to_BoilerHotWater.empty?\n boiler = supply_component.to_BoilerHotWater.get\n #set the efficiency of the boiler\n boiler.setNominalThermalEfficiency(eff)\n runner.registerInfo(\"set boiler #{boiler.name} efficiency to #{eff}\")\n end\n end\n end\n \n \n=begin \n initial_effs = []\n missing_initial_effs = 0\n\n #find and loop through air loops\n air_loops = model.getAirLoopHVACs\n air_loops.each do |air_loop|\n supply_components = air_loop.supplyComponents\n\n #find two speed dx units on loop\n supply_components.each do |supply_component|\n dx_unit = supply_component.to_CoilCoolingDXTwoSpeed\n if not dx_unit.empty?\n dx_unit = dx_unit.get\n\n #change and report high speed cop\n initial_high_cop = dx_unit.ratedHighSpeedCOP\n if not initial_high_cop.empty?\n runner.registerInfo(\"Changing the Rated High Speed COP from #{initial_high_cop.get} to #{cop_high} for two speed dx unit '#{dx_unit.name}' on air loop '#{air_loop.name}'\")\n initial_high_cop_values << initial_high_cop.get\n dx_unit.setRatedHighSpeedCOP(cop_high)\n else\n runner.registerInfo(\"Setting the Rated High Speed COP to #{cop_high} for two speed dx unit '#{dx_unit.name}' on air loop '#{air_loop.name}. The original object did not have a Rated High Speed COP value'\")\n missing_initial_high_cop = missing_initial_high_cop + 1\n dx_unit.setRatedHighSpeedCOP(cop_high)\n end\n\n #change and report low speed cop\n initial_low_cop = dx_unit.ratedLowSpeedCOP\n if not initial_low_cop.empty?\n runner.registerInfo(\"Changing the Rated Low Speed COP from #{initial_low_cop.get} to #{cop_low} for two speed dx unit '#{dx_unit.name}' on air loop '#{air_loop.name}'\")\n initial_low_cop_values << initial_low_cop.get\n dx_unit.setRatedLowSpeedCOP(cop_low)\n else\n runner.registerInfo(\"Setting the Rated Low Speed COP to #{cop_low} for two speed dx unit '#{dx_unit.name}' on air loop '#{air_loop.name}. The original object did not have a Rated Low Speed COP COP value'\")\n missing_initial_low_cop = missing_initial_low_cop + 1\n dx_unit.setRatedLowSpeedCOP(cop_low)\n end\n\n end #end if not dx_unit.empty?\n\n end #end supply_components.each do\n\n end #end air_loops.each do\n\n #reporting initial condition of model\n runner.registerInitialCondition(\"The starting Rated High Speed COP values range from #{initial_high_cop_values.min} to #{initial_high_cop_values.max}. The starting Rated Low Speed COP values range from #{initial_low_cop_values.min} to #{initial_low_cop_values.max}.\")\n\n #warning if two counts of cop's are not the same\n if not initial_high_cop_values.size + missing_initial_high_cop == initial_low_cop_values.size + missing_initial_low_cop\n runner.registerWarning(\"Something went wrong with the measure, not clear on count of two speed dx objects\")\n end\n\n if initial_high_cop_values.size + missing_initial_high_cop == 0\n runner.registerAsNotApplicable(\"The model does not contain any two speed DX cooling units, the model will not be altered.\")\n return true\n end\n\n #reporting final condition of model\n runner.registerFinalCondition(\"#{initial_high_cop_values.size + missing_initial_high_cop} two speed dx units had their High and Low speed COP values set to #{cop_high} for high, and #{cop_low} for low.\")\n=end\n return true\n\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # make a double argument for central ac cooling rated seer\n seer = OpenStudio::Measure::OSArgument::makeDoubleArgument('seer', true)\n seer.setDisplayName('Rated SEER')\n seer.setUnits('Btu/W-h')\n seer.setDescription('Seasonal Energy Efficiency Ratio (SEER) is a measure of equipment energy efficiency over the cooling season.')\n seer.setDefaultValue(16.0)\n args << seer\n\n # make a double argument for central ac eer\n eer = OpenStudio::Measure::OSArgument::makeDoubleArgument('eer', true)\n eer.setDisplayName('EER')\n eer.setUnits('kBtu/kWh')\n eer.setDescription('EER (net) from the A test (95 ODB/80 EDB/67 EWB).')\n eer.setDefaultValue(13.5)\n args << eer\n\n # make a double argument for central ac eer 2\n eer2 = OpenStudio::Measure::OSArgument::makeDoubleArgument('eer2', true)\n eer2.setDisplayName('EER 2')\n eer2.setUnits('kBtu/kWh')\n eer2.setDescription('EER (net) from the A test (95 ODB/80 EDB/67 EWB) for the second speed.')\n eer2.setDefaultValue(12.4)\n args << eer2\n\n # make a double argument for central ac rated shr\n shr = OpenStudio::Measure::OSArgument::makeDoubleArgument('shr', true)\n shr.setDisplayName('Rated SHR')\n shr.setDescription('The sensible heat ratio (ratio of the sensible portion of the load to the total load) at the nominal rated capacity.')\n shr.setDefaultValue(0.71)\n args << shr\n\n # make a double argument for central ac rated shr 2\n shr2 = OpenStudio::Measure::OSArgument::makeDoubleArgument('shr2', true)\n shr2.setDisplayName('Rated SHR 2')\n shr2.setDescription('The sensible heat ratio (ratio of the sensible portion of the load to the total load) at the nominal rated capacity for the second speed.')\n shr2.setDefaultValue(0.73)\n args << shr2\n\n # make a double argument for central ac capacity ratio\n capacity_ratio = OpenStudio::Measure::OSArgument::makeDoubleArgument('capacity_ratio', true)\n capacity_ratio.setDisplayName('Capacity Ratio')\n capacity_ratio.setDescription('Capacity divided by rated capacity.')\n capacity_ratio.setDefaultValue(0.72)\n args << capacity_ratio\n\n # make a double argument for central ac capacity ratio 2\n capacity_ratio2 = OpenStudio::Measure::OSArgument::makeDoubleArgument('capacity_ratio2', true)\n capacity_ratio2.setDisplayName('Capacity Ratio 2')\n capacity_ratio2.setDescription('Capacity divided by rated capacity for the second speed.')\n capacity_ratio2.setDefaultValue(1.0)\n args << capacity_ratio2\n\n # make a double argument for central ac fan speed ratio\n fan_speed_ratio = OpenStudio::Measure::OSArgument::makeDoubleArgument('fan_speed_ratio', true)\n fan_speed_ratio.setDisplayName('Fan Speed Ratio')\n fan_speed_ratio.setDescription('Fan speed divided by fan speed at the compressor speed for which Capacity Ratio = 1.0.')\n fan_speed_ratio.setDefaultValue(0.86)\n args << fan_speed_ratio\n\n # make a double argument for central ac fan speed ratio 2\n fan_speed_ratio2 = OpenStudio::Measure::OSArgument::makeDoubleArgument('fan_speed_ratio2', true)\n fan_speed_ratio2.setDisplayName('Fan Speed Ratio 2')\n fan_speed_ratio2.setDescription('Fan speed divided by fan speed at the compressor speed for which Capacity Ratio = 1.0 for the second speed.')\n fan_speed_ratio2.setDefaultValue(1.0)\n args << fan_speed_ratio2\n\n # make a double argument for central ac rated supply fan power\n fan_power_rated = OpenStudio::Measure::OSArgument::makeDoubleArgument('fan_power_rated', true)\n fan_power_rated.setDisplayName('Rated Supply Fan Power')\n fan_power_rated.setUnits('W/cfm')\n fan_power_rated.setDescription('Fan power (in W) per delivered airflow rate (in cfm) of the outdoor fan under conditions prescribed by AHRI Standard 210/240 for SEER testing.')\n fan_power_rated.setDefaultValue(0.14)\n args << fan_power_rated\n\n # make a double argument for central ac installed supply fan power\n fan_power_installed = OpenStudio::Measure::OSArgument::makeDoubleArgument('fan_power_installed', true)\n fan_power_installed.setDisplayName('Installed Supply Fan Power')\n fan_power_installed.setUnits('W/cfm')\n fan_power_installed.setDescription('Fan power (in W) per delivered airflow rate (in cfm) of the outdoor fan for the maximum fan speed under actual operating conditions.')\n fan_power_installed.setDefaultValue(0.3)\n args << fan_power_installed\n\n # make a double argument for central ac crankcase\n crankcase_capacity = OpenStudio::Measure::OSArgument::makeDoubleArgument('crankcase_capacity', true)\n crankcase_capacity.setDisplayName('Crankcase')\n crankcase_capacity.setUnits('kW')\n crankcase_capacity.setDescription('Capacity of the crankcase heater for the compressor.')\n crankcase_capacity.setDefaultValue(0.0)\n args << crankcase_capacity\n\n # make a double argument for central ac crankcase max t\n crankcase_temp = OpenStudio::Measure::OSArgument::makeDoubleArgument('crankcase_temp', true)\n crankcase_temp.setDisplayName('Crankcase Max Temp')\n crankcase_temp.setUnits('degrees F')\n crankcase_temp.setDescription('Outdoor dry-bulb temperature above which compressor crankcase heating is disabled.')\n crankcase_temp.setDefaultValue(55.0)\n args << crankcase_temp\n\n # make a double argument for central ac 1.5 ton eer capacity derate\n eer_capacity_derate_1ton = OpenStudio::Measure::OSArgument::makeDoubleArgument('eer_capacity_derate_1ton', true)\n eer_capacity_derate_1ton.setDisplayName('1.5 Ton EER Capacity Derate')\n eer_capacity_derate_1ton.setDescription('EER multiplier for 1.5 ton air-conditioners.')\n eer_capacity_derate_1ton.setDefaultValue(1.0)\n args << eer_capacity_derate_1ton\n\n # make a double argument for central ac 2 ton eer capacity derate\n eer_capacity_derate_2ton = OpenStudio::Measure::OSArgument::makeDoubleArgument('eer_capacity_derate_2ton', true)\n eer_capacity_derate_2ton.setDisplayName('2 Ton EER Capacity Derate')\n eer_capacity_derate_2ton.setDescription('EER multiplier for 2 ton air-conditioners.')\n eer_capacity_derate_2ton.setDefaultValue(1.0)\n args << eer_capacity_derate_2ton\n\n # make a double argument for central ac 3 ton eer capacity derate\n eer_capacity_derate_3ton = OpenStudio::Measure::OSArgument::makeDoubleArgument('eer_capacity_derate_3ton', true)\n eer_capacity_derate_3ton.setDisplayName('3 Ton EER Capacity Derate')\n eer_capacity_derate_3ton.setDescription('EER multiplier for 3 ton air-conditioners.')\n eer_capacity_derate_3ton.setDefaultValue(1.0)\n args << eer_capacity_derate_3ton\n\n # make a double argument for central ac 4 ton eer capacity derate\n eer_capacity_derate_4ton = OpenStudio::Measure::OSArgument::makeDoubleArgument('eer_capacity_derate_4ton', true)\n eer_capacity_derate_4ton.setDisplayName('4 Ton EER Capacity Derate')\n eer_capacity_derate_4ton.setDescription('EER multiplier for 4 ton air-conditioners.')\n eer_capacity_derate_4ton.setDefaultValue(1.0)\n args << eer_capacity_derate_4ton\n\n # make a double argument for central ac 5 ton eer capacity derate\n eer_capacity_derate_5ton = OpenStudio::Measure::OSArgument::makeDoubleArgument('eer_capacity_derate_5ton', true)\n eer_capacity_derate_5ton.setDisplayName('5 Ton EER Capacity Derate')\n eer_capacity_derate_5ton.setDescription('EER multiplier for 5 ton air-conditioners.')\n eer_capacity_derate_5ton.setDefaultValue(1.0)\n args << eer_capacity_derate_5ton\n\n # make a string argument for central air cooling output capacity\n capacity = OpenStudio::Measure::OSArgument::makeStringArgument('capacity', true)\n capacity.setDisplayName('Cooling Capacity')\n capacity.setDescription(\"The output cooling capacity of the air conditioner. If using '#{Constants.SizingAuto}', the autosizing algorithm will use ACCA Manual S to set the capacity.\")\n capacity.setUnits('tons')\n capacity.setDefaultValue(Constants.SizingAuto)\n args << capacity\n\n # make a string argument for distribution system efficiency\n dse = OpenStudio::Measure::OSArgument::makeStringArgument('dse', true)\n dse.setDisplayName('Distribution System Efficiency')\n dse.setDescription('Defines the energy losses associated with the delivery of energy from the equipment to the source of the load.')\n dse.setDefaultValue('NA')\n args << dse\n\n return args\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n\t#make a double argument for solar absorptivity\n\tsolar_abs = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"solar_abs\", true)\n\tsolar_abs.setDisplayName(\"Solar Absorptivity\")\n\tsolar_abs.setDescription(\"Fraction of the incident radiation that is absorbed.\")\n\tsolar_abs.setDefaultValue(0.3)\n\targs << solar_abs\n\n\t#make a double argument for conductivity\n\tcond = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"conductivity\", true)\n\tcond.setDisplayName(\"Conductivity\")\n cond.setUnits(\"Btu-in/h-ft^2-R\")\n\tcond.setDescription(\"Conductivity of the exterior finish assembly.\")\n\tcond.setDefaultValue(0.62)\n\targs << cond\n\n\t#make a double argument for density\n\tdens = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"density\", true)\n\tdens.setDisplayName(\"Density\")\n dens.setUnits(\"lb/ft^3\")\n\tdens.setDescription(\"Density of the exterior finish assembly.\")\n\tdens.setDefaultValue(11.1)\n\targs << dens\n\n #make a double argument for specific heat\n\tspecheat = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"specific_heat\", true)\n\tspecheat.setDisplayName(\"Specific Heat\")\n specheat.setUnits(\"Btu/lb-R\")\n\tspecheat.setDescription(\"Specific heat of the exterior finish assembly.\")\n\tspecheat.setDefaultValue(0.25)\n\targs << specheat\n\n #make a double argument for thickness\n\tthick_in = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"thick_in\", true)\n\tthick_in.setDisplayName(\"Thickness\")\n thick_in.setUnits(\"in\")\n\tthick_in.setDescription(\"Thickness of the exterior finish assembly.\")\n\tthick_in.setDefaultValue(0.375)\n\targs << thick_in\n\n #make a double argument for emissivity\n\temiss = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"emissivity\", true)\n\temiss.setDisplayName(\"Emissivity\")\n\temiss.setDescription(\"Measure of the material's ability to emit infrared energy.\")\n\temiss.setDefaultValue(0.9)\n\targs << emiss\n \n return args\n end", "def run(runner, user_arguments)\n super(runner, user_arguments)\n\n # use the built-in error checking \n if !runner.validateUserArguments(arguments(), user_arguments)\n return false\n end\n\n # Assign the user inputs to variables\n reporting_frequency = runner.getStringArgumentValue(\"reporting_frequency\",user_arguments)\n inc_output_variables = runner.getBoolArgumentValue(\"inc_output_variables\",user_arguments)\n\n # Define run directory location\n run_dir_typical = File.absolute_path(File.join(Dir.pwd, 'run'))\n run_dir_comstock = File.absolute_path(File.join(Dir.pwd, '..'))\n if File.exist?(run_dir_typical)\n run_dir = run_dir_typical\n runner.registerInfo(\"run_dir = #{run_dir}\")\n elsif File.exist?(run_dir_comstock)\n run_dir = run_dir_comstock\n runner.registerInfo(\"run_dir = #{run_dir}\")\n else\n runner.registerError(\"Could not find directory with EnergyPlus output, cannont extract timeseries results\")\n return false\n end\n\n # Write the file that defines the unit conversions\n convert_txt_path = File.join(run_dir, 'convert.txt')\n File.open(convert_txt_path, 'w') do |f|\n # electricity\n f.puts('!Electricity')\n f.puts('conv,J,kWh,2.777778E-07,0')\n f.puts('wild,elec,J,kWh')\n # natural gas\n f.puts('!Natural Gas')\n f.puts('conv,J,kBtu,9.484517E-07,0')\n f.puts('wild,gas,J,kBtu')\n # water\n f.puts('!Water')\n f.puts('conv,m3,gal,2.641720E+02,0')\n end\n\n # Write the RVI file, which defines the CSV columns requested\n rvi_path = File.join(run_dir, 'var_request.rvi')\n enduse_timeseries_name = 'enduse_timeseries.csv'\n File.open(rvi_path,'w') do |f|\n f.puts('ip.eso') # convertESOMTR always uses this name\n f.puts(enduse_timeseries_name)\n\n # End Use/Fuel Type\n end_uses.each do |end_use|\n fuel_types.each do |fuel_type|\n variable_name = if end_use == 'Facility'\n \"#{fuel_type}:#{end_use}\"\n else\n \"#{end_use}:#{fuel_type}\"\n end\n f.puts(variable_name)\n end\n end\n\n # End Use Subcategories\n end_use_subcats.each do |subcat|\n f.puts(subcat)\n end\n\n # Optionally request timeseries\n if inc_output_variables\n output_vars.each do |output_var|\n f.puts(output_var)\n end\n end\n f.puts('0') # end-of-file marker\n end\n\n # Copy the necessary executables to the run directory\n start_time = Time.new\n resources_dir = File.absolute_path(File.join(__dir__, 'resources'))\n runner.registerInfo(\"resources_dir = #{resources_dir}\")\n\n # Copy convertESOMTR\n convert_eso_name = if os == :windows\n 'convertESOMTR.exe'\n elsif os == :linux\n 'convertESOMTR'\n elsif os == :macosx\n 'convertESOMTR.osx' # Made up extension to differentiate from linux\n end\n orig_convert_eso_path = File.join(resources_dir, convert_eso_name)\n convert_eso_path = File.join(run_dir, convert_eso_name)\n FileUtils.cp(orig_convert_eso_path, convert_eso_path)\n\n # Copy ReadVarsESO\n readvars_eso_name = if os == :windows\n 'ReadVarsESO.exe'\n elsif os == :linux\n 'ReadVarsESO'\n elsif os == :macosx\n 'ReadVarsESO.osx' # Made up extension to differentiate from linux\n end\n orig_readvars_eso_path = File.join(resources_dir, readvars_eso_name)\n readvars_eso_path = File.join(run_dir, readvars_eso_name)\n FileUtils.cp(orig_readvars_eso_path, readvars_eso_path) \n\n # Copy libraries (OSX only)\n if os == :macosx\n ['libgcc_s.1.dylib', 'libgfortran.5.dylib', 'libquadmath.0.dylib'].each do |dylib|\n FileUtils.cp(File.join(resources_dir, dylib), File.join(run_dir, dylib)) \n end\n end\n end_time = Time.new\n runner.registerInfo(\"Copying executables took #{end_time - start_time} seconds\")\n\n # Call convertESOMTR\n start_time = Time.new\n command = \"#{convert_eso_path}\"\n stdout_str, stderr_str, status = Open3.capture3(command, chdir: run_dir)\n if status.success?\n runner.registerInfo(\"Successfully ran convertESOMTR: #{command}\")\n else\n runner.registerError(\"Error running convertESOMTR: #{command}\")\n runner.registerError(\"stdout: #{stdout_str}\")\n runner.registerError(\"stderr: #{stderr_str}\")\n return false\n end\n end_time = Time.new\n runner.registerInfo(\"Running convertESOMTR took #{end_time - start_time} seconds\")\n\n # Call ReadVarsESO\n start_time = Time.new\n command = \"#{readvars_eso_path} #{File.basename(rvi_path)} #{reporting_frequency} Unlimited FixHeader\"\n stdout_str, stderr_str, status = Open3.capture3(command, chdir: run_dir)\n if status.success?\n runner.registerInfo(\"Successfully ran convertESOMTR: #{command}\")\n else\n runner.registerError(\"Error running convertESOMTR: #{command}\")\n runner.registerError(\"stdout: #{stdout_str}\")\n runner.registerError(\"stderr: #{stderr_str}\")\n return false\n end\n end_time = Time.new\n runner.registerInfo(\"Running ReadVarsESO took #{end_time - start_time} seconds\")\n\n return true\n end", "def modeler_description\n return 'Passes in all arguments from the options lookup, processes them, and then registers values to the runner to be used by other measures.'\n end", "def start_after=(_arg0); end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n \n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end \n \n curves = Curves.new\n supply = Supply.new\n \n miniSplitHPCoolingRatedSEER = runner.getDoubleArgumentValue(\"miniSplitHPCoolingRatedSEER\",user_arguments) \n miniSplitHPCoolingMinCapacity = runner.getDoubleArgumentValue(\"miniSplitHPCoolingMinCapacity\",user_arguments) \n miniSplitHPCoolingMaxCapacity = runner.getDoubleArgumentValue(\"miniSplitHPCoolingMaxCapacity\",user_arguments) \n miniSplitHPCoolingMinAirflow = runner.getDoubleArgumentValue(\"miniSplitHPCoolingMinAirflow\",user_arguments) \n miniSplitHPCoolingMaxAirflow = runner.getDoubleArgumentValue(\"miniSplitHPCoolingMaxAirflow\",user_arguments) \n miniSplitHPRatedSHR = runner.getDoubleArgumentValue(\"miniSplitHPRatedSHR\",user_arguments) \n miniSplitHPSupplyFanPower = runner.getDoubleArgumentValue(\"miniSplitHPSupplyFanPower\",user_arguments) \n miniSplitHPCoolingOversizeFactor = runner.getDoubleArgumentValue(\"miniSplitHPCoolingOversizeFactor\",user_arguments) \n miniSplitHPHeatingCapacityOffset = runner.getDoubleArgumentValue(\"miniSplitHPHeatingCapacityOffset\",user_arguments) \n miniSplitHPHeatingRatedHSPF = runner.getDoubleArgumentValue(\"miniSplitHPHeatingRatedHSPF\",user_arguments) \n miniSplitHPHeatingMinCapacity = runner.getDoubleArgumentValue(\"miniSplitHPHeatingMinCapacity\",user_arguments) \n miniSplitHPHeatingMaxCapacity = runner.getDoubleArgumentValue(\"miniSplitHPHeatingMaxCapacity\",user_arguments) \n miniSplitHPHeatingMinAirflow = runner.getDoubleArgumentValue(\"miniSplitHPHeatingMinAirflow\",user_arguments) \n miniSplitHPHeatingMaxAirflow = runner.getDoubleArgumentValue(\"miniSplitHPHeatingMaxAirflow\",user_arguments) \n miniSplitHPMinT = runner.getDoubleArgumentValue(\"miniSplitHPMinT\",user_arguments) \n miniSplitHPIsColdClimate = runner.getBoolArgumentValue(\"miniSplitHPIsColdClimate\",user_arguments) \n miniSplitCoolingOutputCapacity = runner.getStringArgumentValue(\"miniSplitCoolingOutputCapacity\",user_arguments)\n unless miniSplitCoolingOutputCapacity == Constants.SizingAuto\n miniSplitCoolingOutputCapacity = OpenStudio::convert(miniSplitCoolingOutputCapacity.split(\" \")[0].to_f,\"ton\",\"Btu/h\").get\n miniSplitHeatingOutputCapacity = miniSplitCoolingOutputCapacity + miniSplitHPHeatingCapacityOffset\n end\n miniSplitSupplementalHeatingOutputCapacity = runner.getStringArgumentValue(\"miniSplitSupplementalHeatingOutputCapacity\",user_arguments)\n if not miniSplitSupplementalHeatingOutputCapacity == Constants.SizingAuto and not miniSplitSupplementalHeatingOutputCapacity == \"NO SUPP HEAT\"\n miniSplitSupplementalHeatingOutputCapacity = OpenStudio::convert(miniSplitSupplementalHeatingOutputCapacity.split(\" \")[0].to_f,\"kBtu/h\",\"Btu/h\").get\n end\n \n # _processAirSystem \n \n has_cchp = miniSplitHPIsColdClimate\n \n curves.mshp_indices = [1,3,5,9]\n \n # Cooling Coil\n curves = HVAC.get_cooling_coefficients(runner, Constants.Num_Speeds_MSHP, false, true, curves)\n\n curves, supply = _processAirSystemMiniSplitCooling(runner, miniSplitHPCoolingRatedSEER, miniSplitHPCoolingMinCapacity, miniSplitHPCoolingMaxCapacity, miniSplitHPCoolingMinAirflow, miniSplitHPCoolingMaxAirflow, miniSplitHPRatedSHR, miniSplitHPSupplyFanPower, curves, supply)\n \n supply.HPCoolingOversizingFactor = miniSplitHPCoolingOversizeFactor\n \n # Heating Coil\n curves = HVAC.get_heating_coefficients(runner, Constants.Num_Speeds_MSHP, false, curves, miniSplitHPMinT)\n \n curves, supply = _processAirSystemMiniSplitHeating(runner, miniSplitHPHeatingRatedHSPF, miniSplitHPHeatingMinCapacity, miniSplitHPHeatingMaxCapacity, miniSplitHPHeatingMinAirflow, miniSplitHPHeatingMaxAirflow, miniSplitHPSupplyFanPower, miniSplitHPMinT, curves, supply) \n \n # _processCurvesSupplyFan\n \n const_biquadratic = OpenStudio::Model::CurveBiquadratic.new(model)\n const_biquadratic.setName(\"ConstantBiquadratic\")\n const_biquadratic.setCoefficient1Constant(1)\n const_biquadratic.setCoefficient2x(0)\n const_biquadratic.setCoefficient3xPOW2(0)\n const_biquadratic.setCoefficient4y(0)\n const_biquadratic.setCoefficient5yPOW2(0)\n const_biquadratic.setCoefficient6xTIMESY(0)\n const_biquadratic.setMinimumValueofx(-100)\n const_biquadratic.setMaximumValueofx(100)\n const_biquadratic.setMinimumValueofy(-100)\n const_biquadratic.setMaximumValueofy(100) \n \n # _processCurvesMiniSplitHP\n \n htg_coil_stage_data = []\n curves.mshp_indices.each do |i|\n # Heating Capacity f(T). These curves were designed for E+ and do not require unit conversion\n hp_heat_cap_ft = OpenStudio::Model::CurveBiquadratic.new(model)\n hp_heat_cap_ft.setName(\"HP_Heat-Cap-fT#{i+1}\")\n hp_heat_cap_ft.setCoefficient1Constant(curves.HEAT_CAP_FT_SPEC_coefficients[i][0])\n hp_heat_cap_ft.setCoefficient2x(curves.HEAT_CAP_FT_SPEC_coefficients[i][1])\n hp_heat_cap_ft.setCoefficient3xPOW2(curves.HEAT_CAP_FT_SPEC_coefficients[i][2])\n hp_heat_cap_ft.setCoefficient4y(curves.HEAT_CAP_FT_SPEC_coefficients[i][3])\n hp_heat_cap_ft.setCoefficient5yPOW2(curves.HEAT_CAP_FT_SPEC_coefficients[i][4])\n hp_heat_cap_ft.setCoefficient6xTIMESY(curves.HEAT_CAP_FT_SPEC_coefficients[i][5])\n hp_heat_cap_ft.setMinimumValueofx(-100)\n hp_heat_cap_ft.setMaximumValueofx(100)\n hp_heat_cap_ft.setMinimumValueofy(-100)\n hp_heat_cap_ft.setMaximumValueofy(100)\n \n # Heating EIR f(T). These curves were designed for E+ and do not require unit conversion\n hp_heat_eir_ft = OpenStudio::Model::CurveBiquadratic.new(model)\n hp_heat_eir_ft.setName(\"HP_Heat-EIR-fT#{i+1}\")\n hp_heat_eir_ft.setCoefficient1Constant(curves.HEAT_EIR_FT_SPEC_coefficients[i][0])\n hp_heat_eir_ft.setCoefficient2x(curves.HEAT_EIR_FT_SPEC_coefficients[i][1])\n hp_heat_eir_ft.setCoefficient3xPOW2(curves.HEAT_EIR_FT_SPEC_coefficients[i][2])\n hp_heat_eir_ft.setCoefficient4y(curves.HEAT_EIR_FT_SPEC_coefficients[i][3])\n hp_heat_eir_ft.setCoefficient5yPOW2(curves.HEAT_EIR_FT_SPEC_coefficients[i][4])\n hp_heat_eir_ft.setCoefficient6xTIMESY(curves.HEAT_EIR_FT_SPEC_coefficients[i][5])\n hp_heat_eir_ft.setMinimumValueofx(-100)\n hp_heat_eir_ft.setMaximumValueofx(100)\n hp_heat_eir_ft.setMinimumValueofy(-100)\n hp_heat_eir_ft.setMaximumValueofy(100)\n\n hp_heat_cap_fff = OpenStudio::Model::CurveQuadratic.new(model)\n hp_heat_cap_fff.setName(\"HP_Heat-Cap-fFF#{i+1}\")\n hp_heat_cap_fff.setCoefficient1Constant(curves.HEAT_CAP_FFLOW_SPEC_coefficients[i][0])\n hp_heat_cap_fff.setCoefficient2x(curves.HEAT_CAP_FFLOW_SPEC_coefficients[i][1])\n hp_heat_cap_fff.setCoefficient3xPOW2(curves.HEAT_CAP_FFLOW_SPEC_coefficients[i][2])\n hp_heat_cap_fff.setMinimumValueofx(0)\n hp_heat_cap_fff.setMaximumValueofx(2)\n hp_heat_cap_fff.setMinimumCurveOutput(0)\n hp_heat_cap_fff.setMaximumCurveOutput(2)\n\n hp_heat_eir_fff = OpenStudio::Model::CurveQuadratic.new(model)\n hp_heat_eir_fff.setName(\"HP_Heat-EIR-fFF#{i+1}\")\n hp_heat_eir_fff.setCoefficient1Constant(curves.HEAT_EIR_FFLOW_SPEC_coefficients[i][0])\n hp_heat_eir_fff.setCoefficient2x(curves.HEAT_EIR_FFLOW_SPEC_coefficients[i][1])\n hp_heat_eir_fff.setCoefficient3xPOW2(curves.HEAT_EIR_FFLOW_SPEC_coefficients[i][2])\n hp_heat_eir_fff.setMinimumValueofx(0)\n hp_heat_eir_fff.setMaximumValueofx(2)\n hp_heat_eir_fff.setMinimumCurveOutput(0)\n hp_heat_eir_fff.setMaximumCurveOutput(2)\n \n hp_heat_plf_fplr = OpenStudio::Model::CurveQuadratic.new(model)\n hp_heat_plf_fplr.setName(\"HP_Heat-PLF-fPLR#{i+1}\")\n hp_heat_plf_fplr.setCoefficient1Constant(curves.HEAT_CLOSS_FPLR_SPEC_coefficients[0])\n hp_heat_plf_fplr.setCoefficient2x(curves.HEAT_CLOSS_FPLR_SPEC_coefficients[1])\n hp_heat_plf_fplr.setCoefficient3xPOW2(curves.HEAT_CLOSS_FPLR_SPEC_coefficients[2])\n hp_heat_plf_fplr.setMinimumValueofx(0)\n hp_heat_plf_fplr.setMaximumValueofx(1)\n hp_heat_plf_fplr.setMinimumCurveOutput(0.7)\n hp_heat_plf_fplr.setMaximumCurveOutput(1) \n \n stage_data = OpenStudio::Model::CoilHeatingDXMultiSpeedStageData.new(model, hp_heat_cap_ft, hp_heat_cap_fff, hp_heat_eir_ft, hp_heat_eir_fff, hp_heat_plf_fplr, const_biquadratic)\n if miniSplitCoolingOutputCapacity != Constants.SizingAuto\n stage_data.setGrossRatedHeatingCapacity(OpenStudio::convert(miniSplitHeatingOutputCapacity,\"Btu/h\",\"W\").get * supply.Capacity_Ratio_Heating[i])\n stage_data.setRatedAirFlowRate(OpenStudio::convert(supply.HeatingCFMs[i] * OpenStudio::convert(miniSplitHeatingOutputCapacity,\"Btu/h\",\"ton\").get,\"cfm\",\"m^3/s\").get)\n end\n stage_data.setGrossRatedHeatingCOP(1.0 / supply.HeatingEIR[i])\n stage_data.setRatedWasteHeatFractionofPowerInput(0.2)\n htg_coil_stage_data[i] = stage_data\n end \n \n clg_coil_stage_data = []\n curves.mshp_indices.each do |i|\n # Cooling Capacity f(T). These curves were designed for E+ and do not require unit conversion\n cool_cap_ft = OpenStudio::Model::CurveBiquadratic.new(model)\n cool_cap_ft.setName(\"Cool-Cap-fT#{i+1}\")\n cool_cap_ft.setCoefficient1Constant(curves.COOL_CAP_FT_SPEC_coefficients[i][0])\n cool_cap_ft.setCoefficient2x(curves.COOL_CAP_FT_SPEC_coefficients[i][1])\n cool_cap_ft.setCoefficient3xPOW2(curves.COOL_CAP_FT_SPEC_coefficients[i][2])\n cool_cap_ft.setCoefficient4y(curves.COOL_CAP_FT_SPEC_coefficients[i][3])\n cool_cap_ft.setCoefficient5yPOW2(curves.COOL_CAP_FT_SPEC_coefficients[i][4])\n cool_cap_ft.setCoefficient6xTIMESY(curves.COOL_CAP_FT_SPEC_coefficients[i][5])\n cool_cap_ft.setMinimumValueofx(13.88)\n cool_cap_ft.setMaximumValueofx(23.88)\n cool_cap_ft.setMinimumValueofy(18.33)\n cool_cap_ft.setMaximumValueofy(51.66)\n\n # Cooling EIR f(T). These curves were designed for E+ and do not require unit conversion\n cool_eir_ft = OpenStudio::Model::CurveBiquadratic.new(model)\n cool_eir_ft.setName(\"Cool-EIR-fT#{i+1}\")\n cool_eir_ft.setCoefficient1Constant(curves.COOL_EIR_FT_SPEC_coefficients[i][0])\n cool_eir_ft.setCoefficient2x(curves.COOL_EIR_FT_SPEC_coefficients[i][1])\n cool_eir_ft.setCoefficient3xPOW2(curves.COOL_EIR_FT_SPEC_coefficients[i][2])\n cool_eir_ft.setCoefficient4y(curves.COOL_EIR_FT_SPEC_coefficients[i][3])\n cool_eir_ft.setCoefficient5yPOW2(curves.COOL_EIR_FT_SPEC_coefficients[i][4])\n cool_eir_ft.setCoefficient6xTIMESY(curves.COOL_EIR_FT_SPEC_coefficients[i][5])\n cool_eir_ft.setMinimumValueofx(13.88)\n cool_eir_ft.setMaximumValueofx(23.88)\n cool_eir_ft.setMinimumValueofy(18.33)\n cool_eir_ft.setMaximumValueofy(51.66) \n \n cool_cap_fff = OpenStudio::Model::CurveQuadratic.new(model)\n cool_cap_fff.setName(\"Cool-Cap-fFF#{i+1}\")\n cool_cap_fff.setCoefficient1Constant(curves.COOL_CAP_FFLOW_SPEC_coefficients[i][0])\n cool_cap_fff.setCoefficient2x(curves.COOL_CAP_FFLOW_SPEC_coefficients[i][1])\n cool_cap_fff.setCoefficient3xPOW2(curves.COOL_CAP_FFLOW_SPEC_coefficients[i][2])\n cool_cap_fff.setMinimumValueofx(0)\n cool_cap_fff.setMaximumValueofx(2)\n cool_cap_fff.setMinimumCurveOutput(0)\n cool_cap_fff.setMaximumCurveOutput(2) \n\n cool_eir_fff = OpenStudio::Model::CurveQuadratic.new(model)\n cool_eir_fff.setName(\"Cool-EIR-fFF#{i+1}\")\n cool_eir_fff.setCoefficient1Constant(curves.COOL_EIR_FFLOW_SPEC_coefficients[i][0])\n cool_eir_fff.setCoefficient2x(curves.COOL_EIR_FFLOW_SPEC_coefficients[i][1])\n cool_eir_fff.setCoefficient3xPOW2(curves.COOL_EIR_FFLOW_SPEC_coefficients[i][2])\n cool_eir_fff.setMinimumValueofx(0)\n cool_eir_fff.setMaximumValueofx(2)\n cool_eir_fff.setMinimumCurveOutput(0)\n cool_eir_fff.setMaximumCurveOutput(2) \n \n cool_plf_fplr = OpenStudio::Model::CurveQuadratic.new(model)\n cool_plf_fplr.setName(\"Cool-PLF-fPLR#{i+1}\")\n cool_plf_fplr.setCoefficient1Constant(curves.COOL_CLOSS_FPLR_SPEC_coefficients[0])\n cool_plf_fplr.setCoefficient2x(curves.COOL_CLOSS_FPLR_SPEC_coefficients[1])\n cool_plf_fplr.setCoefficient3xPOW2(curves.COOL_CLOSS_FPLR_SPEC_coefficients[2])\n cool_plf_fplr.setMinimumValueofx(0)\n cool_plf_fplr.setMaximumValueofx(1)\n cool_plf_fplr.setMinimumCurveOutput(0.7)\n cool_plf_fplr.setMaximumCurveOutput(1) \n \n stage_data = OpenStudio::Model::CoilCoolingDXMultiSpeedStageData.new(model, cool_cap_ft, cool_cap_fff, cool_eir_ft, cool_eir_fff, cool_plf_fplr, const_biquadratic)\n if miniSplitCoolingOutputCapacity != Constants.SizingAuto\n stage_data.setGrossRatedTotalCoolingCapacity(OpenStudio::convert(miniSplitCoolingOutputCapacity,\"Btu/h\",\"W\").get * supply.Capacity_Ratio_Cooling[i])\n stage_data.setRatedAirFlowRate(OpenStudio::convert(supply.CoolingCFMs[i] * OpenStudio::convert(miniSplitCoolingOutputCapacity,\"Btu/h\",\"ton\").get,\"cfm\",\"m^3/s\").get)\n stage_data.setGrossRatedSensibleHeatRatio(supply.SHR_Rated[i])\n end\n stage_data.setGrossRatedCoolingCOP(1.0 / supply.CoolingEIR[i])\n stage_data.setNominalTimeforCondensateRemovaltoBegin(1000)\n stage_data.setRatioofInitialMoistureEvaporationRateandSteadyStateLatentCapacity(1.5)\n stage_data.setMaximumCyclingRate(3)\n stage_data.setLatentCapacityTimeConstant(45)\n stage_data.setRatedWasteHeatFractionofPowerInput(0.2)\n clg_coil_stage_data[i] = stage_data \n end\n \n # Heating defrost curve for reverse cycle\n defrosteir = OpenStudio::Model::CurveBiquadratic.new(model)\n defrosteir.setName(\"DefrostEIR\")\n defrosteir.setCoefficient1Constant(0.1528)\n defrosteir.setCoefficient2x(0)\n defrosteir.setCoefficient3xPOW2(0)\n defrosteir.setCoefficient4y(0)\n defrosteir.setCoefficient5yPOW2(0)\n defrosteir.setCoefficient6xTIMESY(0)\n defrosteir.setMinimumValueofx(-100)\n defrosteir.setMaximumValueofx(100)\n defrosteir.setMinimumValueofy(-100)\n defrosteir.setMaximumValueofy(100)\n \n # Check if has equipment\n HelperMethods.remove_hot_water_loop(model, runner) \n \n num_units = Geometry.get_num_units(model, runner)\n if num_units.nil?\n return false\n end\n \n (0...num_units).to_a.each do |unit_num|\n _nbeds, _nbaths, unit_spaces = Geometry.get_unit_beds_baths_spaces(model, unit_num + 1, runner)\n thermal_zones = Geometry.get_thermal_zones_from_unit_spaces(unit_spaces)\n if thermal_zones.length > 1\n runner.registerInfo(\"Unit #{unit_num + 1} spans more than one thermal zone.\")\n end\n control_slave_zones_hash = Geometry.get_control_and_slave_zones(thermal_zones)\n control_slave_zones_hash.each do |control_zone, slave_zones|\n\n # Remove existing equipment\n HelperMethods.remove_existing_hvac_equipment(model, runner, \"Mini-Split Heat Pump\", control_zone)\n \n # _processSystemHeatingCoil\n \n htg_coil = OpenStudio::Model::CoilHeatingDXMultiSpeed.new(model)\n htg_coil.setName(\"DX Heating Coil\")\n htg_coil.setMinimumOutdoorDryBulbTemperatureforCompressorOperation(OpenStudio::convert(supply.min_hp_temp,\"F\",\"C\").get)\n htg_coil.setCrankcaseHeaterCapacity(0)\n htg_coil.setDefrostEnergyInputRatioFunctionofTemperatureCurve(defrosteir)\n htg_coil.setMaximumOutdoorDryBulbTemperatureforDefrostOperation(OpenStudio::convert(supply.max_defrost_temp,\"F\",\"C\").get)\n htg_coil.setDefrostStrategy(\"ReverseCycle\")\n htg_coil.setDefrostControl(\"OnDemand\")\n htg_coil.setApplyPartLoadFractiontoSpeedsGreaterthan1(false)\n htg_coil.setFuelType(\"Electricity\")\n \n heating_indices = curves.mshp_indices\n heating_indices.each do |i|\n htg_coil.addStage(htg_coil_stage_data[i])\n end\n \n supp_htg_coil = OpenStudio::Model::CoilHeatingElectric.new(model, model.alwaysOnDiscreteSchedule)\n supp_htg_coil.setName(\"HeatPump Supp Heater\")\n supp_htg_coil.setEfficiency(1)\n if miniSplitSupplementalHeatingOutputCapacity == \"NO SUPP HEAT\"\n supp_htg_coil.setNominalCapacity(0)\n elsif miniSplitSupplementalHeatingOutputCapacity != Constants.SizingAuto\n supp_htg_coil.setNominalCapacity(OpenStudio::convert(miniSplitSupplementalHeatingOutputCapacity,\"Btu/h\",\"W\").get)\n end\n \n # _processSystemCoolingCoil\n \n clg_coil = OpenStudio::Model::CoilCoolingDXMultiSpeed.new(model)\n clg_coil.setName(\"DX Cooling Coil\")\n clg_coil.setCondenserType(\"AirCooled\")\n clg_coil.setApplyPartLoadFractiontoSpeedsGreaterthan1(false)\n clg_coil.setApplyLatentDegradationtoSpeedsGreaterthan1(false)\n clg_coil.setCrankcaseHeaterCapacity(0)\n clg_coil.setFuelType(\"Electricity\")\n \n cooling_indices = curves.mshp_indices\n cooling_indices.each do |i|\n clg_coil.addStage(clg_coil_stage_data[i])\n end \n \n # _processSystemFan\n \n supply_fan_availability = OpenStudio::Model::ScheduleConstant.new(model)\n supply_fan_availability.setName(\"SupplyFanAvailability\")\n supply_fan_availability.setValue(1)\n\n fan = OpenStudio::Model::FanOnOff.new(model, supply_fan_availability)\n fan.setName(\"Supply Fan\")\n fan.setEndUseSubcategory(\"HVACFan\")\n fan.setFanEfficiency(supply.eff)\n fan.setPressureRise(supply.static)\n fan.setMotorEfficiency(1)\n fan.setMotorInAirstreamFraction(1)\n\n supply_fan_operation = OpenStudio::Model::ScheduleConstant.new(model)\n supply_fan_operation.setName(\"SupplyFanOperation\")\n supply_fan_operation.setValue(0) \n \n # _processSystemAir\n \n air_loop_unitary = OpenStudio::Model::AirLoopHVACUnitarySystem.new(model)\n air_loop_unitary.setName(\"Forced Air System\")\n air_loop_unitary.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)\n air_loop_unitary.setSupplyFan(fan)\n air_loop_unitary.setHeatingCoil(htg_coil)\n air_loop_unitary.setCoolingCoil(clg_coil)\n air_loop_unitary.setSupplementalHeatingCoil(supp_htg_coil)\n air_loop_unitary.setFanPlacement(\"BlowThrough\")\n air_loop_unitary.setSupplyAirFanOperatingModeSchedule(supply_fan_operation)\n air_loop_unitary.setMaximumSupplyAirTemperature(OpenStudio::convert(supply.supp_htg_max_supply_temp,\"F\",\"C\").get)\n air_loop_unitary.setMaximumOutdoorDryBulbTemperatureforSupplementalHeaterOperation(OpenStudio::convert(supply.supp_htg_max_outdoor_temp,\"F\",\"C\").get)\n air_loop_unitary.setSupplyAirFlowRateWhenNoCoolingorHeatingisRequired(0) \n \n air_loop = OpenStudio::Model::AirLoopHVAC.new(model)\n air_loop.setName(\"Central Air System\")\n air_supply_inlet_node = air_loop.supplyInletNode\n air_supply_outlet_node = air_loop.supplyOutletNode\n air_demand_inlet_node = air_loop.demandInletNode\n air_demand_outlet_node = air_loop.demandOutletNode \n \n air_loop_unitary.addToNode(air_supply_inlet_node)\n\n runner.registerInfo(\"Added on/off fan '#{fan.name}' to branch '#{air_loop_unitary.name}' of air loop '#{air_loop.name}'\")\n runner.registerInfo(\"Added DX cooling coil '#{clg_coil.name}' to branch '#{air_loop_unitary.name}' of air loop '#{air_loop.name}'\")\n runner.registerInfo(\"Added DX heating coil '#{htg_coil.name}' to branch '#{air_loop_unitary.name}' of air loop '#{air_loop.name}'\")\n runner.registerInfo(\"Added electric heating coil '#{supp_htg_coil.name}' to branch '#{air_loop_unitary.name}' of air loop '#{air_loop.name}'\")\n\n air_loop_unitary.setControllingZoneorThermostatLocation(control_zone) \n \n # _processSystemDemandSideAir\n # Demand Side\n\n # Supply Air\n zone_splitter = air_loop.zoneSplitter\n zone_splitter.setName(\"Zone Splitter\")\n\n diffuser_living = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)\n diffuser_living.setName(\"Living Zone Direct Air\")\n # diffuser_living.setMaximumAirFlowRate(OpenStudio::convert(supply.Living_AirFlowRate,\"cfm\",\"m^3/s\").get)\n air_loop.addBranchForZone(control_zone, diffuser_living.to_StraightComponent)\n\n air_loop.addBranchForZone(control_zone)\n runner.registerInfo(\"Added air loop '#{air_loop.name}' to thermal zone '#{control_zone.name}' of unit #{unit_num + 1}\")\n\n slave_zones.each do |slave_zone|\n\n HelperMethods.has_boiler(model, runner, slave_zone, true)\n HelperMethods.has_electric_baseboard(model, runner, slave_zone, true)\n \n diffuser_fbsmt = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)\n diffuser_fbsmt.setName(\"FBsmt Zone Direct Air\")\n # diffuser_fbsmt.setMaximumAirFlowRate(OpenStudio::convert(supply.Living_AirFlowRate,\"cfm\",\"m^3/s\").get)\n air_loop.addBranchForZone(slave_zone, diffuser_fbsmt.to_StraightComponent)\n\n air_loop.addBranchForZone(slave_zone)\n runner.registerInfo(\"Added air loop '#{air_loop.name}' to thermal zone '#{slave_zone.name}' of unit #{unit_num + 1}\")\n\n end \n \n end\n \n end\n \n return true\n\n end", "def end_options\n abstract!\n end", "def run(runner, user_arguments)\n super(runner, user_arguments)\n \n #use the built-in error checking on the arguments. In this case, there are no arguments\n if not runner.validateUserArguments(arguments(), user_arguments)\n return false\n end\n\n #load the last model and the sql file\n model = runner.lastOpenStudioModel\n if model.empty?\n runner.registerError(\"Cannot find last model.\")\n return false\n end\n model = model.get\n \n sql = runner.lastEnergyPlusSqlFile\n if sql.empty?\n runner.registerError(\"Cannot find last sql file.\")\n return false\n end\n sql = sql.get\n \n #make a vector of all end uses in OpenStudio\n end_use_cat_types = []\n OpenStudio::EndUseCategoryType::getValues.each do |end_use_val|\n end_use_cat_types << OpenStudio::EndUseCategoryType.new(end_use_val)\n end\n\n #make a vector of all fuel types in OpenStudio\n end_use_fuel_types = []\n OpenStudio::EndUseFuelType::getValues.each do |end_use_fuel_type_val|\n end_use_fuel_types << OpenStudio::EndUseFuelType.new(end_use_fuel_type_val)\n end \n\n #only attempt to get monthly data if enduses table is available from sql file\n if sql.endUses.is_initialized\n \n #the end uses table is available, so assign it to a variable\n end_uses_table = sql.endUses.get\n \n #loop through all the fuel types\n end_use_fuel_types.each do |end_use_fuel_type|\n #loop through all end uses categories in the fuel type\n end_use_cat_types.each do |end_use_cat_type|\n #get the energy consumption for this fuel type & end use combination\n energy_consumption = end_uses_table.getEndUse(end_use_fuel_type,end_use_cat_type)\n runner.registerInfo(\"energy consumption for #{end_use_fuel_type.valueName}:#{end_use_cat_type.valueName} = #{energy_consumption} GJ\")\n \n #NOTE there are some helper methods available so not everything has to be written as a new query\n #http://openstudio.nrel.gov/latest-c-sdk-documentation\n #click on Utilities>SqlFile\n #all the methods are listed there (usually the names are self-explanatory) \n \n #fake error check as an example\n if energy_consumption > 100 #100GJ\n runner.registerWarning(\"energy consumption for #{end_use_fuel_type.valueName}:#{end_use_cat_type.valueName} = #{energy_consumption} GJ; This seems too high (normal limit is 100GJ)\")\n end\n \n #append the info to a file here. Ruby can write to many different filetypes, googling should have examples\n #after running the file, look inside the directory for this measure and you should find \"report.csv\"\n #this filepath can be anywhere on your computer.\n #you could also make the user enter the filepath as a string argument if you wanted.\n File.open(\"report.csv\", 'w') do |file|\n file << \"#{end_use_fuel_type.valueName},#{end_use_cat_type.valueName},#{energy_consumption},GJ\"\n end\n \n end\n end\n \n else\n\n puts \"End-Use table not available in results file; could not retrieve monthly costs by end use\"\n #runner.registerError(\"End-Use table not available in results; could not retrieve monthly costs by end use\")\n\n end\n \n return true\n \n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # make a double argument for Integrated Modified Energy Factor\n imef = OpenStudio::Measure::OSArgument::makeDoubleArgument('imef', true)\n imef.setDisplayName('Integrated Modified Energy Factor')\n imef.setUnits('ft^3/kWh-cycle')\n imef.setDescription('The Integrated Modified Energy Factor (IMEF) is the capacity of the clothes container divided by the total clothes washer energy consumption per cycle, where the energy consumption is the sum of the machine electrical energy consumption, the hot water energy consumption, the energy required for removal of the remaining moisture in the wash load, standby energy, and off-mode energy consumption. If only a Modified Energy Factor (MEF) is available, convert using the equation: IMEF = (MEF - 0.503) / 0.95.')\n imef.setDefaultValue(0.95)\n args << imef\n\n # make a double argument for Rated Annual Consumption\n rated_annual_energy = OpenStudio::Measure::OSArgument::makeDoubleArgument('rated_annual_energy', true)\n rated_annual_energy.setDisplayName('Rated Annual Consumption')\n rated_annual_energy.setUnits('kWh')\n rated_annual_energy.setDescription('The annual energy consumed by the clothes washer, as rated, obtained from the EnergyGuide label. This includes both the appliance electricity consumption and the energy required for water heating.')\n rated_annual_energy.setDefaultValue(387.0)\n args << rated_annual_energy\n\n # make a double argument for Annual Cost With Gas DHW\n annual_cost = OpenStudio::Measure::OSArgument::makeDoubleArgument('annual_cost', true)\n annual_cost.setDisplayName('Annual Cost with Gas DHW')\n annual_cost.setUnits('$')\n annual_cost.setDescription('The annual cost of using the system under test conditions. Input is obtained from the EnergyGuide label.')\n annual_cost.setDefaultValue(24.0)\n args << annual_cost\n\n # make an integer argument for Test Date\n test_date = OpenStudio::Measure::OSArgument::makeIntegerArgument('test_date', true)\n test_date.setDisplayName('Test Date')\n test_date.setDefaultValue(2007)\n test_date.setDescription('Input obtained from EnergyGuide labels. The new E-guide labels state that the test was performed under the 2004 DOE procedure, otherwise use year < 2004.')\n args << test_date\n\n # make a double argument for Drum Volume\n drum_volume = OpenStudio::Measure::OSArgument::makeDoubleArgument('drum_volume', true)\n drum_volume.setDisplayName('Drum Volume')\n drum_volume.setUnits('ft^3')\n drum_volume.setDescription(\"Volume of the washer drum. Obtained from the EnergyStar website or the manufacturer's literature.\")\n drum_volume.setDefaultValue(3.5)\n args << drum_volume\n\n # make a boolean argument for Use Cold Cycle Only\n cold_cycle = OpenStudio::Measure::OSArgument::makeBoolArgument('cold_cycle', true)\n cold_cycle.setDisplayName('Use Cold Cycle Only')\n cold_cycle.setDescription('The washer is operated using only the cold cycle.')\n cold_cycle.setDefaultValue(false)\n args << cold_cycle\n\n # make a boolean argument for Thermostatic Control\n thermostatic_control = OpenStudio::Measure::OSArgument::makeBoolArgument('thermostatic_control', true)\n thermostatic_control.setDisplayName('Thermostatic Control')\n thermostatic_control.setDescription(\"The clothes washer uses hot and cold water inlet valves to control temperature (varies hot water volume to control wash temperature). Use this option for machines that use hot and cold inlet valves to control wash water temperature or machines that use both inlet valves AND internal electric heaters to control temperature of the wash water. Input obtained from the manufacturer's literature.\")\n thermostatic_control.setDefaultValue(true)\n args << thermostatic_control\n\n # make a boolean argument for Has Internal Heater Adjustment\n internal_heater = OpenStudio::Measure::OSArgument::makeBoolArgument('internal_heater', true)\n internal_heater.setDisplayName('Has Internal Heater Adjustment')\n internal_heater.setDescription(\"The washer uses an internal electric heater to adjust the temperature of wash water. Use this option for washers that have hot and cold water connections but use an internal electric heater to adjust the wash water temperature. Obtain the input from the manufacturer's literature.\")\n internal_heater.setDefaultValue(false)\n args << internal_heater\n\n # make a boolean argument for Has Water Level Fill Sensor\n fill_sensor = OpenStudio::Measure::OSArgument::makeBoolArgument('fill_sensor', true)\n fill_sensor.setDisplayName('Has Water Level Fill Sensor')\n fill_sensor.setDescription(\"The washer has a vertical axis and water level fill sensor. Input obtained from the manufacturer's literature.\")\n fill_sensor.setDefaultValue(false)\n args << fill_sensor\n\n # make a double argument for occupancy energy multiplier\n mult_e = OpenStudio::Measure::OSArgument::makeDoubleArgument('mult_e', true)\n mult_e.setDisplayName('Occupancy Energy Multiplier')\n mult_e.setDescription('Appliance energy use is multiplied by this factor to account for occupancy usage that differs from the national average.')\n mult_e.setDefaultValue(1)\n args << mult_e\n\n # make a double argument for occupancy water multiplier\n mult_hw = OpenStudio::Measure::OSArgument::makeDoubleArgument('mult_hw', true)\n mult_hw.setDisplayName('Occupancy Hot Water Multiplier')\n mult_hw.setDescription('Appliance hot water use is multiplied by this factor to account for occupancy usage that differs from the national average. This should generally be equal to the Occupancy Energy Multiplier.')\n mult_hw.setDefaultValue(1)\n args << mult_hw\n\n # make a choice argument for location\n location_args = OpenStudio::StringVector.new\n location_args << Constants.Auto\n Geometry.get_model_locations(model).each do |loc|\n location_args << loc\n end\n location = OpenStudio::Measure::OSArgument::makeChoiceArgument('location', location_args, true, true)\n location.setDisplayName('Location')\n location.setDescription(\"The space type for the location. '#{Constants.Auto}' will automatically choose a space type based on the space types found in the model.\")\n location.setDefaultValue(Constants.Auto)\n args << location\n\n # make a choice argument for plant loop\n plant_loops = model.getPlantLoops\n plant_loop_args = OpenStudio::StringVector.new\n plant_loop_args << Constants.Auto\n plant_loops.each do |plant_loop|\n plant_loop_args << plant_loop.name.to_s\n end\n plant_loop = OpenStudio::Measure::OSArgument::makeChoiceArgument('plant_loop', plant_loop_args, true, true)\n plant_loop.setDisplayName('Plant Loop')\n plant_loop.setDescription(\"Select the plant loop for the dishwasher. '#{Constants.Auto}' will try to choose the plant loop associated with the specified space. For multifamily buildings, '#{Constants.Auto}' will choose the plant loop for each unit of the building.\")\n plant_loop.setDefaultValue(Constants.Auto)\n args << plant_loop\n\n return args\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n #use the built-in error checking\n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n #assign the user inputs to variables\n setpoint = runner.getDoubleArgumentValue(\"setpoint\",user_arguments)\n control_type = runner.getStringArgumentValue(\"control_type\",user_arguments)\n min_power_fraction = runner.getDoubleArgumentValue(\"min_power_fraction\",user_arguments)\n min_light_fraction = runner.getDoubleArgumentValue(\"min_light_fraction\",user_arguments)\n height = runner.getDoubleArgumentValue(\"height\",user_arguments)\n\n\n #check the setpoint for reasonableness\n if setpoint < 0 or setpoint > 9999 #dfg need input on good value\n runner.registerError(\"A setpoint of #{setpoint} foot-candles is outside the measure limit.\")\n return false\n elsif setpoint > 999\n runner.registerWarning(\"A setpoint of #{setpoint} foot-candles is abnormally high.\") #dfg need input on good value\n end\n\n #check the min_power_fraction for reasonableness\n if min_power_fraction < 0.0 or min_power_fraction > 0.6\n runner.registerError(\"The requested minimum input power fraction of #{min_power_fraction} for continuous dimming control is outside the acceptable range of 0 to 0.6.\")\n return false\n end\n\n #check the min_light_fraction for reasonableness\n if min_light_fraction < 0.0 or min_light_fraction > 0.6\n runner.registerError(\"The requested minimum light output fraction of #{min_light_fraction} for continuous dimming control is outside the acceptable range of 0 to 0.6.\")\n return false\n end\n\n #check the height for reasonableness\n if height < -360 or height > 360 # neg ok because space origin may not be floor\n runner.registerError(\"A setpoint of #{height} inches is outside the measure limit.\")\n return false\n elsif height > 72\n runner.registerWarning(\"A setpoint of #{height} inches is abnormally high.\")\n elseif height < 0\n runner.registerWarning(\"Typically the sensor height should be a positive number, however if your space origin is above the floor then a negative sensor height may be approriate.\")\n end\n\n #unit conversion from IP units to SI units\n setpoint_si = OpenStudio.convert(setpoint,'fc','lux').get\n height_si = OpenStudio.convert(height,'in','m').get\n\n #variable to tally the area to which the overall measure is applied\n area = 0\n #variables to aggregate the number of sensors installed and the area affected\n sensor_count = 0\n sensor_area = 0\n #array with subset of spaces\n spaces_selected_without_sensors = []\n affected_zones = []\n affected_zone_names = []\n #hash to hold sensor objects\n new_sensor_objects = {}\n\n num_spaces_selected = 0\n spaces_selected = []\n model.getSpaces.each do |space|\n next if not runner.inSelection(space)\n spaces_selected << space \n end\n \n if spaces_selected.size == 0\n runner.registerAsNotApplicable(\"No spaces were selected. Please select spaces to add daylight sensors.\")\n end\n\n #reporting initial condition of model\n runner.registerInitialCondition(\"#{spaces_selected.size} spaces selected.\")\n\n #test that there is no sensor already in the space, and that zone object doesn't already have sensors assigned.\n \n \n spaces_selected.each do |space|\n if space.daylightingControls.length == 0\n space_zone = space.thermalZone\n if not space_zone.empty?\n space_zone = space_zone.get\n if space_zone.primaryDaylightingControl.empty? and space_zone.secondaryDaylightingControl.empty?\n spaces_selected_without_sensors << space\n elsif\n runner.registerWarning(\"Thermal zone '#{space_zone.name}' which includes space '#{space.name}' already had a daylighting sensor. No sensor was added to space '#{space.name}'.\")\n end\n else\n runner.registerWarning(\"Space '#{space.name}' is not associated with a thermal zone. It won't be part of the EnergyPlus simulation.\")\n end\n else\n runner.registerWarning(\"Space '#{space.name}' already has a daylighting sensor. No sensor was added.\")\n end\n end\n\n #loop through all spaces, and add a daylighting sensor with dimming to each\n space_count = 0\n spaces_selected_without_sensors.each do |space|\n space_count = space_count + 1\n area += space.floorArea\n\n # #eliminate spaces that don't have exterior natural lighting\n # has_ext_nat_light = false\n # space.surfaces.each do |surface|\n # next if not surface.outsideBoundaryCondition == \"Outdoors\"\n # surface.subSurfaces.each do |sub_surface|\n # next if sub_surface.subSurfaceType == \"Door\"\n # next if sub_surface.subSurfaceType == \"OverheadDoor\"\n # has_ext_nat_light = true\n # end\n # end\n # if has_ext_nat_light == false\n # runner.registerWarning(\"Space '#{space.name}' has no exterior natural lighting. No sensor will be added.\")\n # next\n # end\n\n #find floors\n floors = []\n space.surfaces.each do |surface|\n next if not surface.surfaceType == \"Floor\"\n floors << surface\n end\n\n #this method only works for flat (non-inclined) floors\n boundingBox = OpenStudio::BoundingBox.new\n floors.each do |floor|\n boundingBox.addPoints(floor.vertices)\n end\n xmin = boundingBox.minX.get\n ymin = boundingBox.minY.get\n zmin = boundingBox.minZ.get\n xmax = boundingBox.maxX.get\n ymax = boundingBox.maxY.get\n\n #create a new sensor and put at the center of the space\n sensor = OpenStudio::Model::DaylightingControl.new(model)\n sensor.setName(\"#{space.name} daylighting control\")\n x_pos = (xmin + xmax) / 2\n y_pos = (ymin + ymax) / 2\n z_pos = zmin + height_si #put it 1 meter above the floor\n new_point = OpenStudio::Point3d.new(x_pos, y_pos, z_pos)\n sensor.setPosition(new_point)\n sensor.setIlluminanceSetpoint(setpoint_si)\n sensor.setLightingControlType(control_type)\n sensor.setMinimumInputPowerFractionforContinuousDimmingControl(min_power_fraction)\n sensor.setMinimumLightOutputFractionforContinuousDimmingControl(min_light_fraction)\n sensor.setSpace(space)\n\n #push unique zones to array for use later in measure\n temp_zone = space.thermalZone.get\n if affected_zone_names.include?(temp_zone.name.to_s) == false\n affected_zones << temp_zone\n affected_zone_names << temp_zone.name.to_s\n end\n\n #push sensor object into hash with space name\n new_sensor_objects[space.name.to_s] = sensor\n\n #add floor area to the daylighting area tally\n sensor_area += space.floorArea\n\n #add to sensor count for reporting\n sensor_count += 1\n\n end #end spaces_selected_without_sensors.each do\n\n #loop through thermal Zones for spaces with daylighting controls added\n affected_zones.each do |zone|\n zone_spaces = zone.spaces\n zone_spaces_with_new_sensors = []\n zone_spaces.each do |zone_space|\n if not zone_space.daylightingControls.empty?\n zone_spaces_with_new_sensors << zone_space\n end\n end\n\n if not zone_spaces_with_new_sensors.empty?\n #need to identify the two largest spaces\n primary_area = 0\n secondary_area = 0\n primary_space = nil\n secondary_space = nil\n three_or_more_sensors = false\n\n # dfg temp - need to add another if statement so only get spaces with sensors\n zone_spaces_with_new_sensors.each do |zone_space|\n zone_space_area = zone_space.floorArea\n if zone_space_area > primary_area\n primary_area = zone_space_area\n primary_space = zone_space\n elsif zone_space_area > secondary_area\n secondary_area = zone_space_area\n secondary_space = zone_space\n else\n #setup flag to warn user that more than 2 sensors can't be added to a space\n three_or_more_sensors = true\n end\n\n end\n\n if primary_space\n #setup primary sensor\n sensor_primary = new_sensor_objects[primary_space.name.to_s]\n zone.setPrimaryDaylightingControl(sensor_primary)\n zone.setFractionofZoneControlledbyPrimaryDaylightingControl(primary_area/(primary_area + secondary_area))\n end\n\n if secondary_space\n #setup secondary sensor\n sensor_secondary = new_sensor_objects[secondary_space.name.to_s]\n zone.setSecondaryDaylightingControl(sensor_secondary)\n zone.setFractionofZoneControlledbySecondaryDaylightingControl(secondary_area/(primary_area + secondary_area))\n end\n\n #warn that additional sensors were not used\n if three_or_more_sensors == true\n runner.registerWarning(\"Thermal zone '#{zone.name}' had more than two spaces with sensors. Only two sensors were associated with the thermal zone.\")\n end\n\n end #end if not zone_spaces.empty?\n\n end #end affected_zones.each do\n\n #setup OpenStudio units that we will need\n unit_area_ip = OpenStudio::createUnit(\"ft^2\").get\n unit_area_si = OpenStudio::createUnit(\"m^2\").get\n\n #define starting units\n area_si = OpenStudio::Quantity.new(sensor_area, unit_area_si)\n\n #unit conversion from IP units to SI units\n area_ip = OpenStudio::convert(area_si, unit_area_ip).get\n\n #reporting final condition of model\n runner.registerFinalCondition(\"Added daylighting controls to #{sensor_count} spaces, covering #{area_ip}.\")\n\n return true\n\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n \n finished_surfaces = []\n unfinished_surfaces = []\n model.getSpaces.each do |space|\n # Wall between finished space and outdoors\n if Geometry.space_is_finished(space) and Geometry.space_is_above_grade(space)\n space.surfaces.each do |surface|\n next if surface.surfaceType.downcase != \"wall\" or surface.outsideBoundaryCondition.downcase != \"outdoors\"\n finished_surfaces << surface\n end\n # Attic wall under an insulated roof\n elsif Geometry.is_unfinished_attic(space)\n attic_roof_r = Construction.get_space_r_value(runner, space, \"roofceiling\")\n next if attic_roof_r.nil? or attic_roof_r <= 5 # assume uninsulated if <= R-5 assembly\n space.surfaces.each do |surface|\n next if surface.surfaceType.downcase != \"wall\" or surface.outsideBoundaryCondition.downcase != \"outdoors\"\n unfinished_surfaces << surface\n end\n end\n end\n \n # Continue if no applicable surfaces\n if finished_surfaces.empty? and unfinished_surfaces.empty?\n runner.registerAsNotApplicable(\"Measure not applied because no applicable surfaces were found.\")\n return true\n end \n \n # Get inputs\n cmuThickness = runner.getDoubleArgumentValue(\"thickness\",user_arguments)\n cmuConductivity = runner.getDoubleArgumentValue(\"conductivity\",user_arguments)\n cmuDensity = runner.getDoubleArgumentValue(\"density\",user_arguments)\n cmuFramingFactor = runner.getDoubleArgumentValue(\"framing_factor\",user_arguments)\n cmuFurringInsRvalue = runner.getDoubleArgumentValue(\"furring_r\",user_arguments)\n cmuFurringCavityDepth = runner.getDoubleArgumentValue(\"furring_cavity_depth\",user_arguments)\n cmuFurringStudSpacing = runner.getDoubleArgumentValue(\"furring_spacing\",user_arguments)\n\n # Validate inputs\n if cmuThickness <= 0.0\n runner.registerError(\"CMU Block Thickness must be greater than 0.\")\n return false\n end\n if cmuConductivity <= 0.0\n runner.registerError(\"CMU Conductivity must be greater than 0.\")\n return false\n end\n if cmuDensity <= 0.0\n runner.registerError(\"CMU Density must be greater than 0.\")\n return false\n end\n if cmuFramingFactor < 0.0 or cmuFramingFactor >= 1.0\n runner.registerError(\"Framing Factor must be greater than or equal to 0 and less than 1.\")\n return false\n end\n if cmuFurringInsRvalue < 0.0\n runner.registerError(\"Furring Insulation R-value must be greater than or equal to 0.\")\n return false\n end\n if cmuFurringCavityDepth < 0.0\n runner.registerError(\"Furring Cavity Depth must be greater than or equal to 0.\")\n return false\n end\n if cmuFurringStudSpacing < 0.0\n runner.registerError(\"Furring Stud Spacing must be greater than or equal to 0.\")\n return false\n end\n\n # Process the CMU walls\n \n # Define materials\n mat_cmu = Material.new(name=nil, thick_in=cmuThickness, mat_base=BaseMaterial.Concrete, k_in=cmuConductivity, rho=cmuDensity)\n mat_framing = Material.new(name=nil, thick_in=cmuThickness, mat_base=BaseMaterial.Wood)\n mat_furring = nil\n mat_furring_cavity = nil\n if cmuFurringCavityDepth != 0\n mat_furring = Material.new(name=nil, thick_in=cmuFurringCavityDepth, mat_base=BaseMaterial.Wood)\n if cmuFurringInsRvalue == 0\n mat_furring_cavity = Material.AirCavityClosed(cmuFurringCavityDepth)\n else\n mat_furring_cavity = Material.new(name=nil, thick_in=cmuFurringCavityDepth, mat_base=BaseMaterial.InsulationGenericDensepack, k_in=cmuFurringCavityDepth / cmuFurringInsRvalue)\n end\n end\n \n # Set paths\n if not mat_furring.nil?\n stud_frac = 1.5 / cmuFurringStudSpacing\n cavity_frac = 1.0 - (stud_frac + cmuFramingFactor)\n path_fracs = [cmuFramingFactor, stud_frac, cavity_frac]\n else # No furring:\n path_fracs = [cmuFramingFactor, 1.0 - cmuFramingFactor]\n end\n \n if not finished_surfaces.empty?\n # Define construction\n fin_cmu_wall = Construction.new(path_fracs)\n fin_cmu_wall.add_layer(Material.AirFilmVertical, false)\n fin_cmu_wall.add_layer(Material.DefaultWallMass, false) # thermal mass added in separate measure\n if not mat_furring.nil?\n fin_cmu_wall.add_layer([mat_furring, mat_furring, mat_furring_cavity], true, \"Furring\")\n fin_cmu_wall.add_layer([mat_framing, mat_cmu, mat_cmu], true, \"CMU\")\n else\n fin_cmu_wall.add_layer([mat_framing, mat_cmu], true, \"CMU\")\n end\n fin_cmu_wall.add_layer(Material.DefaultWallSheathing, false) # OSB added in separate measure\n fin_cmu_wall.add_layer(Material.DefaultExteriorFinish, false) # exterior finish added in separate measure\n fin_cmu_wall.add_layer(Material.AirFilmOutside, false)\n \n # Create and assign construction to surfaces\n if not fin_cmu_wall.create_and_assign_constructions(finished_surfaces, runner, model, name=\"ExtInsFinWall\")\n return false\n end\n end\n \n if not unfinished_surfaces.empty?\n # Define construction\n unfin_cmu_wall = Construction.new(path_fracs)\n unfin_cmu_wall.add_layer(Material.AirFilmVertical, false)\n if not mat_furring.nil?\n unfin_cmu_wall.add_layer([mat_furring, mat_furring, mat_furring_cavity], true, \"Furring\")\n unfin_cmu_wall.add_layer([mat_framing, mat_cmu, mat_cmu], true, \"CMU\")\n else\n unfin_cmu_wall.add_layer([mat_framing, mat_cmu], true, \"CMU\")\n end\n unfin_cmu_wall.add_layer(Material.DefaultWallSheathing, false) # OSB added in separate measure\n unfin_cmu_wall.add_layer(Material.DefaultExteriorFinish, false) # exterior finish added in separate measure\n unfin_cmu_wall.add_layer(Material.AirFilmOutside, false)\n \n # Create and assign construction to surfaces\n if not unfin_cmu_wall.create_and_assign_constructions(unfinished_surfaces, runner, model, name=\"ExtInsFinWall\")\n return false\n end\n end\n \n # Store info for HVAC Sizing measure\n units = Geometry.get_building_units(model, runner)\n if units.nil?\n return false\n end\n (finished_surfaces + unfinished_surfaces).each do |surface|\n units.each do |unit|\n next if not unit.spaces.include?(surface.space.get)\n unit.setFeature(Constants.SizingInfoWallType(surface), \"CMU\")\n unit.setFeature(Constants.SizingInfoCMUWallFurringInsRvalue(surface), cmuFurringInsRvalue)\n end\n end\n\n # Remove any constructions/materials that aren't used\n HelperMethods.remove_unused_constructions_and_materials(model, runner)\n \n return true\n\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # assign the user inputs to variables\n verbose_info_statements = runner.getBoolArgumentValue(\"verbose_info_statements\",user_arguments)\n fixed_window_subsurface = runner.getOptionalWorkspaceObjectChoiceValue('fixed_window_subsurface', user_arguments, model) # model is passed in because of argument type\n internal_variable_availability_dictionary_reporting = runner.getStringArgumentValue('internal_variable_availability_dictionary_reporting', user_arguments)\n ems_runtime_language_debug_output_level = runner.getStringArgumentValue('ems_runtime_language_debug_output_level', user_arguments) \n actuator_availability_dictionary_reporting = runner.getStringArgumentValue('actuator_availability_dictionary_reporting', user_arguments) \n \n runner.registerInitialCondition(\"Measure began with #{model.getEnergyManagementSystemSensors.count} EMS sensors, #{model.getEnergyManagementSystemActuators.count} EMS Actuators, #{model.getEnergyManagementSystemPrograms.count} EMS Programs, #{model.getEnergyManagementSystemSubroutines.count} EMS Subroutines, #{model.getEnergyManagementSystemProgramCallingManagers.count} EMS Program Calling Manager objects\")\n \n # declare arrys for scope\n array_of_21_sets = []\n material_property_glazing_spectral_data_vector = []\n standard_glazing_layer_array = []\n construction_array = []\n ems_window_construction_array = []\n \n # load idf into workspace\n workspace = OpenStudio::Workspace::load(OpenStudio::Path.new(\"#{File.dirname(__FILE__)}/resources/EMSThermochromicWindow.idf\")).get\n \n # get all MaterialPropertyGlazingSpectralData objects from within the idf\n # material_property_glazing_spectral_datas = source_idf.getObjectsByType(\"MaterialProperty:GlazingSpectralData\".to_IddObjectType)\n material_property_glazing_spectral_datas = workspace.getObjectsByType(\"MaterialProperty:GlazingSpectralData\".to_IddObjectType)\n if verbose_info_statements == true\n runner.registerInfo(\"The model has #{material_property_glazing_spectral_datas.size} material_property_glazing_spectral_datas objects.\")\n end\n \n material_property_glazing_spectral_datas.each do |material_property_glazing_spectral_data|\n \n spectral_data = {\"name\" => \"\",\"properties\" => []}\n spectral_data[\"name\"] = material_property_glazing_spectral_data.getString(0).to_s\n \n # Note: EnergyPlus file MaterialProperty:GlazingSpectralData objects have 1764 /4 = 441 sets of 4 values each \n n = material_property_glazing_spectral_data.numFields\n (1..n).each do |i| \n spectral_data[\"properties\"] << material_property_glazing_spectral_data.getString(i).to_s \n end\n array_of_21_sets << spectral_data\n end\n \n array_of_21_sets.each do |set|\n \n props = set[\"properties\"]\n material_property_glazing_spectral_data = OpenStudio::Model::MaterialPropertyGlazingSpectralData.new(model)\n material_property_glazing_spectral_data.setName(\"#{set[\"name\"]}\")\n \n k = (props.length / 4) - 1\n (0..k).each do |i| # note 440 uniques (a, b, c, d) pairs of attributes for each spectral data field object\n material_property_glazing_spectral_data.addSpectralDataField(props[(i*4)+0].to_f, props[(i*4)+1].to_f, props[(i*4)+2].to_f, props[(i*4)+3].to_f)\t\n end\n \n material_property_glazing_spectral_data_vector << material_property_glazing_spectral_data\n end \n \n # create (2) required new air gas materials to used by all EMS window constructions \n air_gas_3mm_material = OpenStudio::Model::Gas.new(model, \"Air\", 0.003) \n air_gas_3mm_material.setName(\"AIR 3MM\")\n \n air_gas_8mm_material = OpenStudio::Model::Gas.new(model, \"Air\", 0.008) \n air_gas_8mm_material.setName(\"AIR 8MM\")\n \n # loop through array of OS MaterialPropertyGlazingSpectralData objects and create 21 new Standard Glazing objects \n material_property_glazing_spectral_data_vector.each do |spec_data_obj|\n spec_data_obj_name = spec_data_obj.name\n layer_name = spec_data_obj_name.to_s.slice(\"sp\")\n if ((spec_data_obj_name == \"WO18RT25SP\") || (spec_data_obj_name == \"Clear3PPGSP\"))\n layer = OpenStudio::Model::StandardGlazing.new(model, 'Spectral', 0.0075)\n else\n layer = OpenStudio::Model::StandardGlazing.new(model, 'Spectral', 0.003276)\n end\n layer.setName(\"#{layer_name}\")\n layer.setWindowGlassSpectralDataSet(spec_data_obj)\n layer.setInfraredTransmittanceatNormalIncidence(0) # same for all 21 constructions\n layer.setFrontSideInfraredHemisphericalEmissivity(0.84) # same for all 21 constructions\n layer.setBackSideInfraredHemisphericalEmissivity(0.84) # same for all 21 constructions\n if ((spec_data_obj_name == \"WO18RT25SP\") || (spec_data_obj_name == \"Clear3PPGSP\"))\n layer.setConductivity(1.0) \n else\n layer.setConductivity(0.6) \n end\n layer.setDirtCorrectionFactorforSolarandVisibleTransmittance(1) # same for all 21 constructions\n layer.setSolarDiffusing(false)\n standard_glazing_layer_array << layer\n end\n\n # Create (2) unique standard glazing layers not used for Thermochromatic performance \n sb60_clear_3_ppg_layer = standard_glazing_layer_array[0]\n clear_3ppg_layer = standard_glazing_layer_array[1]\n remaining_standard_glazing_layer_array = standard_glazing_layer_array.drop(2)\n \n # create (19) new arrays of layered constructions representing thermochromatic layers\n remaining_standard_glazing_layer_array.each do |remaining_standard_glazing_layer|\n construction = [sb60_clear_3_ppg_layer, air_gas_3mm_material, remaining_standard_glazing_layer, air_gas_8mm_material, sb60_clear_3_ppg_layer]\n construction_array << construction\n end\n \n # create 19 new OS:Construction objects representing EMS thermochromatic windows\n name_index_array = [25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 50, 55, 60, 65, 70, 75, 80, 85]\n index = 0\n \n construction_array.each do |const|\n ems_window_construction = OpenStudio::Model::Construction.new(const)\n ems_window_construction.setName(\"TCwindow_#{name_index_array[index]}\")\n if verbose_info_statements == true\n runner.registerInfo(\"Created a new Construction named #{ems_window_construction.name} representing a thermochromatic window construction.\")\n end\n ems_window_construction_array << ems_window_construction\n index +=1\n end\n\n # check the user argument of the fixed window subsurface for reasonableness\n if fixed_window_subsurface.empty?\n handle = runner.getStringArgumentValue('fixed_window_subsurface', user_arguments)\n if handle.empty?\n runner.registerError('No fixed window subsurface was chosen.')\n else\n runner.registerError(\"The selected fixed window subsurface with handle '#{handle}' was not found in the model. It may have been removed by another measure.\")\n end\n return false\n else\n if !fixed_window_subsurface.get.to_SubSurface.empty?\n fixed_window_subsurface = fixed_window_subsurface.get.to_SubSurface.get\n else\n runner.registerError('Script Error - argument not showing up as construction.')\n return false\n end\n end\n \n # Create a new EnergyManagementSystem:Sensor object representing the Surface Outside Face temp of the EMS thermochromatic window subsurface\n ems_win_Tout_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, \"Surface Outside Face Temperature\")\n ems_win_Tout_sensor.setName(\"Win1_Tout\")\n ems_win_Tout_sensor.setKeyName(\"#{fixed_window_subsurface.name}\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS Sensor object named '#{ems_win_Tout_sensor.name}' representing the Surface Outside Face temp of the EMS thermochromatic window subsurface was added to the model.\") \n end\n \n # Create a new EMS Actuator Object representing the construction state of the EMS generated thermochromatic window \n ems_win_construct_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(fixed_window_subsurface, \"Surface\", \"Construction State\")\n ems_win_construct_actuator.setName(\"Win1_Construct\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS Actuator object named '#{ems_win_construct_actuator.name}' representing construction state of the EMS generated thermochromatic window was added to the model.\") \n end\n \n # Create 19 EnergyManagementSystem:ConstructionIndexVariable objects for each unique thermochromatic construction\n ems_window_construction_array.each do |ems_window_construction|\n ems_constr_index_var = OpenStudio::Model::EnergyManagementSystemConstructionIndexVariable.new(model, ems_window_construction ) \n ems_constr_index_var.setName(\"#{ems_window_construction.name}\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS SystemConstructionIndexVariable object named '#{ems_constr_index_var.name}' representing the the EMS construction state of the thermochromatic window was added to the model.\") \n end\n end\n \n # Create new EnergyManagementSystem:Program object for assigning different window constructions by dynamically evaluating the exterior surface temp of the fixed window subsurface \n ems_apply_thermochromatic_constructions_prgm = OpenStudio::Model::EnergyManagementSystemProgram.new(model)\n ems_apply_thermochromatic_constructions_prgm.setName(\"#{fixed_window_subsurface.name}_Control\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"IF #{ems_win_Tout_sensor.name} <= 26.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_25\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 28.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_27\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 30.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_29\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 32.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_31\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 34.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_33\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 36.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_35\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 38.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_37\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 40.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_39\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 42.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_41\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 44.0\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_43\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 47.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_45\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 52.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_50\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 57.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_55\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 62.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_60\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 67.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_65\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 72.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_70\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 77.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_75\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSEIF #{ems_win_Tout_sensor.name} <= 82.5\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_80\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ELSE\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"SET #{ems_win_construct_actuator.name} = TCwindow_85\")\n ems_apply_thermochromatic_constructions_prgm.addLine(\"ENDIF\")\n if verbose_info_statements == true\n runner.registerInfo(\"An EMS Program Object named '#{ems_apply_thermochromatic_constructions_prgm.name}' for dynamically assigning different window constructions based on the exterior surface temp was added to the model.\") \n end\n \n # Create a new EnergyManagementSystem:ProgramCallingManager object configured to call the EMS programs\n ems_prgm_calling_mngr = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n ems_prgm_calling_mngr.setName(\"My thermochromic window emulator\")\n ems_prgm_calling_mngr.setCallingPoint(\"BeginTimestepBeforePredictor\")\n ems_prgm_calling_mngr.addProgram(ems_apply_thermochromatic_constructions_prgm)\n if verbose_info_statements == true\n runner.registerInfo(\"EMS Program Calling Manager object named '#{ems_prgm_calling_mngr.name}' added to call EMS program for dynamically applying a thermochromatic window.\") \n end\n \n # create unique object for OutputEnergyManagementSystems and configure to allow EMS reporting\n outputEMS = model.getOutputEnergyManagementSystem\n outputEMS.setInternalVariableAvailabilityDictionaryReporting(\"internal_variable_availability_dictionary_reporting\")\n outputEMS.setEMSRuntimeLanguageDebugOutputLevel(\"ems_runtime_language_debug_output_level\")\n outputEMS.setActuatorAvailabilityDictionaryReporting(\"actuator_availability_dictionary_reporting\")\n if verbose_info_statements == true\n runner.registerInfo(\"EMS OutputEnergyManagementSystem object configured per user arguments.\") \n end\n \n runner.registerFinalCondition(\"Measure finished with #{model.getEnergyManagementSystemSensors.count} EMS sensors, #{model.getEnergyManagementSystemActuators.count} EMS Actuators, #{model.getEnergyManagementSystemPrograms.count} EMS Programs, #{model.getEnergyManagementSystemSubroutines.count} EMS Subroutines, #{model.getEnergyManagementSystemProgramCallingManagers.count} EMS Program Calling Manager objects\")\n\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n \n\t#TODO: New argument for demand response for pool heaters (alternate schedules if automatic DR control is specified)\n\t\n\t#make a double argument for Base Energy Use\n\tbase_energy = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"base_energy\")\n\tbase_energy.setDisplayName(\"Base Energy Use\")\n base_energy.setUnits(\"kWh/yr\")\n\tbase_energy.setDescription(\"The national average (Building America Benchmark) energy use.\")\n\tbase_energy.setDefaultValue(2300)\n\targs << base_energy\n\n\t#make a double argument for Energy Multiplier\n\tmult = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"mult\")\n\tmult.setDisplayName(\"Energy Multiplier\")\n\tmult.setDescription(\"Sets the annual energy use equal to the base energy use times this multiplier.\")\n\tmult.setDefaultValue(1)\n\targs << mult\n\t\n #make a boolean argument for Scale Energy Use\n\tscale_energy = OpenStudio::Measure::OSArgument::makeBoolArgument(\"scale_energy\",true)\n\tscale_energy.setDisplayName(\"Scale Energy Use\")\n\tscale_energy.setDescription(\"If true, scales the energy use relative to a 3-bedroom, 1920 sqft house using the following equation: Fscale = (0.5 + 0.25 x Nbr/3 + 0.25 x FFA/1920) where Nbr is the number of bedrooms and FFA is the finished floor area.\")\n\tscale_energy.setDefaultValue(true)\n\targs << scale_energy\n\n\t#Make a string argument for 24 weekday schedule values\n\tweekday_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"weekday_sch\")\n\tweekday_sch.setDisplayName(\"Weekday schedule\")\n\tweekday_sch.setDescription(\"Specify the 24-hour weekday schedule.\")\n\tweekday_sch.setDefaultValue(\"0.003, 0.003, 0.003, 0.004, 0.008, 0.015, 0.026, 0.044, 0.084, 0.121, 0.127, 0.121, 0.120, 0.090, 0.075, 0.061, 0.037, 0.023, 0.013, 0.008, 0.004, 0.003, 0.003, 0.003\")\n\targs << weekday_sch\n \n\t#Make a string argument for 24 weekend schedule values\n\tweekend_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"weekend_sch\")\n\tweekend_sch.setDisplayName(\"Weekend schedule\")\n\tweekend_sch.setDescription(\"Specify the 24-hour weekend schedule.\")\n\tweekend_sch.setDefaultValue(\"0.003, 0.003, 0.003, 0.004, 0.008, 0.015, 0.026, 0.044, 0.084, 0.121, 0.127, 0.121, 0.120, 0.090, 0.075, 0.061, 0.037, 0.023, 0.013, 0.008, 0.004, 0.003, 0.003, 0.003\")\n\targs << weekend_sch\n\n\t#Make a string argument for 12 monthly schedule values\n\tmonthly_sch = OpenStudio::Measure::OSArgument::makeStringArgument(\"monthly_sch\")\n\tmonthly_sch.setDisplayName(\"Month schedule\")\n\tmonthly_sch.setDescription(\"Specify the 12-month schedule.\")\n\tmonthly_sch.setDefaultValue(\"1.154, 1.161, 1.013, 1.010, 1.013, 0.888, 0.883, 0.883, 0.888, 0.978, 0.974, 1.154\")\n\targs << monthly_sch\n\n return args\n end", "def arguments(model)\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n #make integer arg to run measure [1 is run, 0 is no run]\r\n run_measure = OpenStudio::Ruleset::OSArgument::makeIntegerArgument(\"run_measure\",true)\r\n run_measure.setDisplayName(\"Run Measure\")\r\n run_measure.setDescription(\"integer argument to run measure [1 is run, 0 is no run]\")\r\n run_measure.setDefaultValue(1)\r\n args << run_measure\r\n return args\r\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n \n #use the built-in error checking \n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n #assign the user inputs to variables\n insul_tchkn = runner.getDoubleArgumentValue(\"insul_tchkn\",user_arguments)\n #add_space = runner.getBoolArgumentValue(\"add_space\",user_arguments)\n\n #check if insul_tchkn present\n if insul_tchkn == \"\"\n runner.registerError(\"No Insulation Thickness Was Entered\")\n return false\n end \n\t\n\t#ruby test to see if insul_tchkn is reasonable\n if insul_tchkn < 0 or insul_tchkn > 12 \n runner.registerWarning(\"Insulation thickness must be between 0 and 12 (in). You entered #{insul_tchkn}\") \n end\n \n\t# make a new material layer\n\toptions = {\n\t\t\"layerIndex\" => 0, # 0 will be outside. Measure writer should validate any non 0 layerIndex passed in.\n\t\t\"name\" => \"Exterior Wall and Finish System\",\n\t\t\"roughness\" => \"MediumRough\",\n\t\t\"thickness\" => insul_tchkn*0.0254, # meters,\n\t\t\"conductivity\" => 0.0360563953045152, # W/m*K\n\t\t\"density\" => 25.6295413983362,\n\t\t\"specificHeat\" => 1465.38,\n\t\t\"thermalAbsorptance\" => 0.9,\n\t\t\"solarAbsorptance\" => 0.7,\n\t\t\"visibleAbsorptance\" => 0.7,\n\t}\n\texposedMaterialNew = OpenStudio::Model::StandardOpaqueMaterial.new(model)\n\texposedMaterialNew.setName(options[\"name\"])\t\n\t# set requested material properties\n\tif not options[\"roughness\"].nil? then exposedMaterialNew.setRoughness(options[\"roughness\"]) end\n\tif not options[\"thickness\"].nil? then exposedMaterialNew.setThickness(options[\"thickness\"]) end\n\tif not options[\"conductivity\"].nil? then exposedMaterialNew.setConductivity( options[\"conductivity\"]) end\n\tif not options[\"density\"].nil? then exposedMaterialNew.setDensity(options[\"density\"])end\n\tif not options[\"specificHeat\"].nil? then exposedMaterialNew.setSpecificHeat(options[\"specificHeat\"]) end\n\tif not options[\"thermalAbsorptance\"].nil? then exposedMaterialNew.setThermalAbsorptance(options[\"thermalAbsorptance\"]) end\n\tif not options[\"solarAbsorptance\"].nil? then exposedMaterialNew.setSolarAbsorptance(options[\"solarAbsorptance\"]) end\n\tif not options[\"visibleAbsorptance\"].nil? then exposedMaterialNew.setVisibleAbsorptance(options[\"visibleAbsorptance\"]) end\n\t\n\t#create an array of exterior walls\n surfaces = model.getSurfaces\n exterior_surfaces = []\n exterior_surface_constructions = []\n exterior_surface_construction_names = []\n\texterior_surfaces_num_layers = []\n\t\n surfaces.each do |surface|\t\n if not surface.construction.empty? \t \n if surface.outsideBoundaryCondition == \"Outdoors\" and surface.surfaceType == \"Wall\"\n\t\t\texterior_surfaces << surface\n\t\t\text_wall_const = surface.construction.get\n\t\t\t#only add construction if it hasn't been added yet\n\t\t\tif not exterior_surface_construction_names.include?(ext_wall_const.name.to_s)\n\t\t\t exterior_surface_constructions << ext_wall_const.to_Construction.get\n\t\t\tend\n\t\t\texterior_surface_construction_names << ext_wall_const.name.to_s \n\t\tend #end of surface.outsideBoundaryCondition\t \n\t end # end of if not surface.construction.empty?\t \n end # end of surfaces.each do\n\t\n\t # nothing will be done if there are no exterior surfaces\n if exterior_surfaces.empty?\n runner.registerAsNotApplicable(\"Model does not have any exterior walls.\")\n return true\n end\t\n\n\t# for each exterior surface construction, add the new material layer to the construction\n\tnum_constructions_changed = 0\n\texterior_surface_constructions.each do |exterior_surface_construction|\n\t # add new material layer to construction \n\t exterior_surface_construction.insertLayer(options[\"layerIndex\"],exposedMaterialNew)\t\n\t runner.registerInfo(\"Added #{exposedMaterialNew.name.to_s} to construction #{exterior_surface_construction.name.to_s}.\")\n\t num_constructions_changed += 1\n\tend\n\t\t\n\t#returning the insulation thickness\n runner.registerInfo(\"Applied Insulation of Thickness #{insul_tchkn}(in) to #{num_constructions_changed} Building Constructions.\")\n\t\n return true\n \n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # Use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n # Return N/A if not selected to run\n run_measure = runner.getIntegerArgumentValue('run_measure', user_arguments)\n if run_measure == 0\n runner.registerAsNotApplicable(\"Run Measure set to #{run_measure}.\")\n return true\n end\n\n r_val_ip = runner.getDoubleArgumentValue('r_val_ip', user_arguments)\n\n # Check the r_val_ip for reasonableness\n if r_val_ip <= 0\n runner.registerError(\"R-value must be greater than 0. You entered #{r_val_ip}.\")\n return false\n end\n\n # Convert r_val_ip to si\n r_val_si = OpenStudio.convert(r_val_ip, 'ft^2*h*R/Btu', 'm^2*K/W').get\n\n # Create a material for Expanded Polystyrene - Molded Beads\n # https://bcl.nrel.gov/node/34582\n # Expanded Polystyrene - Molded Beads - 1 in., ! Name\n # VeryRough, ! Roughness\n # 0.0254, ! Thickness {m}\n # 0.0352, ! Conductivity {W/m-K}\n # 24, ! Density {kg/m3}\n # 1210, ! Specific Heat {J/kg-K}\n ins_layer = OpenStudio::Model::StandardOpaqueMaterial.new(model)\n ins_layer.setRoughness('VeryRough')\n ins_layer.setConductivity(0.0352)\n ins_layer.setDensity(24.0)\n ins_layer.setSpecificHeat(1210.0)\n\n # Calculate the thickness required to meet the desired R-Value\n reqd_thickness_si = r_val_si * ins_layer.thermalConductivity\n reqd_thickness_ip = OpenStudio.convert(reqd_thickness_si, 'm', 'in').get\n ins_layer.setThickness(reqd_thickness_si)\n ins_layer.setName(\"Expanded Polystyrene - Molded Beads - #{reqd_thickness_ip.round(1)} in.\")\n runner.registerInfo(\"To achieve an R-Value of #{r_val_ip.round(2)} you need #{ins_layer.name} insulation.\")\n\n # Find all exterior walls and get a list of their constructions\n wall_constructions = []\n model.getSurfaces.each do |surface|\n if surface.outsideBoundaryCondition == 'Outdoors' && surface.surfaceType == 'Wall'\n if surface.construction.is_initialized\n wall_constructions << surface.construction.get\n end\n end\n end\n\n # Make clones of all the wall constructions used and the add\n # insulation layer to these new constructions.\n old_to_new_construction_map = {}\n wall_constructions.uniq.each do |wall_construction|\n wall_construction_plus_ins = wall_construction.clone(model).to_Construction.get\n wall_construction_plus_ins.insertLayer(0, ins_layer)\n old_to_new_construction_map[wall_construction] = wall_construction_plus_ins\n end\n\n # Find all exterior walls and replace their old constructions with the\n # cloned constructions that include the insulation layer.\n area_of_insulation_added_si = 0\n model.getSurfaces.each do |surface|\n if surface.outsideBoundaryCondition == 'Outdoors' && surface.surfaceType == 'Wall'\n if surface.construction.is_initialized\n wall_construction = surface.construction.get\n wall_construction_plus_ins = old_to_new_construction_map[wall_construction]\n surface.setConstruction(wall_construction_plus_ins)\n area_of_insulation_added_si += surface.netArea\n end\n end\n end\n\n # This measure is not applicable if there are no exterior walls\n if area_of_insulation_added_si == 0\n runner.registerAsNotApplicable('Not Applicable - Model does not have any exterior walls to add EIFS insulation to.')\n return true\n end\n\n # Convert affected area to ft^2 for reporting\n area_of_insulation_added_ip = OpenStudio.convert(area_of_insulation_added_si, 'm^2', 'ft^2').get\n\n # Report the initial condition\n runner.registerInitialCondition(\"The building has #{area_of_insulation_added_ip.round(2)} ft2 of exterior walls.\")\n\n # Report the final condition\n runner.registerFinalCondition(\"#{ins_layer.name} insulation has been applied to #{area_of_insulation_added_ip.round} ft2 of exterior walls.\")\n runner.registerValue('env_wall_eifs_area_ft2', area_of_insulation_added_ip.round(2), 'ft2')\n return true\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # # Make integer arg to run measure [1 is run, 0 is no run]\n # run_measure = OpenStudio::Ruleset::OSArgument::makeIntegerArgument(\"run_measure\",true)\n # run_measure.setDisplayName(\"Run Measure\")\n # run_measure.setDescription(\"integer argument to run measure [1 is run, 0 is no run]\")\n # run_measure.setDefaultValue(1)\n # args << run_measure\n\n return args\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n depth = OpenStudio.convert(runner.getDoubleArgumentValue(\"depth\",user_arguments), \"ft\", \"m\").get\n offset = OpenStudio.convert(runner.getDoubleArgumentValue(\"offset\",user_arguments), \"ft\", \"m\").get\n # width_extension = OpenStudio.convert(runner.getDoubleArgumentValue(\"width_extension\",user_arguments), \"ft\", \"m\").get\n facade_bools = OpenStudio::StringVector.new\n facade_bools << \"#{Constants.FacadeFront} Facade\"\n facade_bools << \"#{Constants.FacadeBack} Facade\"\n facade_bools << \"#{Constants.FacadeLeft} Facade\" \n facade_bools << \"#{Constants.FacadeRight} Facade\"\n facade_bools_hash = Hash.new\n facade_bools.each do |facade_bool|\n facade_bools_hash[facade_bool] = runner.getBoolArgumentValue(facade_bool.downcase.gsub(\" \", \"_\"),user_arguments)\n end \n\n # error checking\n if depth < 0\n runner.registerError(\"Overhang depth must be greater than or equal to 0.\")\n return false\n end\n if offset < 0\n runner.registerError(\"Overhang offset must be greater than or equal to 0.\")\n return false\n end\n # if width_extension < 0 \n # runner.registerError(\"Overhang width extension must be greater than or equal to 0.\")\n # return false\n # end\n\n # Remove existing overhangs\n num_removed = 0 \n model.getShadingSurfaceGroups.each do |shading_surface_group|\n remove_group = false\n shading_surface_group.shadingSurfaces.each do |shading_surface|\n next unless shading_surface.name.to_s.downcase.include? \"overhang\"\n num_removed += 1\n remove_group = true\n end\n if remove_group\n shading_surface_group.remove\n end\n end\n if num_removed > 0\n runner.registerInfo(\"#{num_removed} overhang shading surfaces removed.\")\n end\n \n # No overhangs to add? Exit here.\n if depth == 0\n if num_removed == 0\n runner.registerAsNotApplicable(\"No overhangs were added or removed.\")\n end\n return true\n end\n \n windows_found = false\n \n subsurfaces = model.getSubSurfaces\n subsurfaces.each do |subsurface|\n \n next if not subsurface.subSurfaceType.downcase.include? \"window\"\n \n windows_found = true\n facade = Geometry.get_facade_for_surface(subsurface)\n next if facade.nil?\n next if !facade_bools_hash[\"#{facade} Facade\"]\n\n overhang = subsurface.addOverhang(depth, offset)\n overhang.get.setName(\"#{subsurface.name} - Overhang\")\n \n runner.registerInfo(\"#{overhang.get.name.to_s} added.\")\n\n end\n \n if not windows_found\n runner.registerAsNotApplicable(\"No windows found for adding overhangs.\")\n return true\n end\n \n return true\n \n end", "def run(runner, user_arguments)\r\n super(runner, user_arguments)\r\n\r\n #use the built-in error checking\r\n unless runner.validateUserArguments(arguments, user_arguments)\r\n return false\r\n end\r\n\r\n # require 'ruby-prof'\r\n\r\n begin\r\n # RubyProf.start\r\n\r\n output_format = runner.getStringArgumentValue(\"output_format\", user_arguments)\r\n os_version = OpenStudio::VersionString.new(OpenStudio::openStudioVersion())\r\n min_version_feature1 = OpenStudio::VersionString.new(\"1.2.3\")\r\n require \"time\"\r\n\r\n unless os_version >= min_version_feature1\r\n runner.registerError(\"Dencity Reports requires a version of OpenStudio greater than 1.2.3.\")\r\n return false\r\n end\r\n\r\n # determine how to format time series output\r\n msgpack_flag = FALSE\r\n csv_flag = FALSE\r\n if output_format == \"MessagePack\" || output_format == \"Both\"\r\n msgpack_flag = TRUE\r\n end\r\n if output_format == \"CSV\" || output_format == \"Both\"\r\n csv_flag = TRUE\r\n end\r\n\r\n # get the last model and sql file\r\n model = runner.lastOpenStudioModel\r\n if model.empty?\r\n runner.registerError(\"Cannot find last model.\")\r\n return false\r\n end\r\n model = model.get\r\n building = model.getBuilding\r\n\r\n runner.registerInfo(\"Model loaded\")\r\n\r\n sql_file = runner.lastEnergyPlusSqlFile\r\n if sql_file.empty?\r\n runner.registerError(\"Cannot find last sql file.\")\r\n return false\r\n end\r\n sql_file = sql_file.get\r\n model.setSqlFile(sql_file)\r\n\r\n runner.registerInfo(\"Sql loaded\")\r\n\r\n #Initalize array that will be used to construct the DEnCity metadata csv\r\n metadata = Array.new\r\n metadata[0] = [\"name\", \"display_name\", \"short_name\", \"description\", \"unit\", \"datatype\", \"user_defined\"]\r\n\r\n #get building footprint to use for calculating end use EUIs\r\n building_area = sql_query(runner, sql_file, \"AnnualBuildingUtilityPerformanceSummary\", \"TableName='Building Area' AND RowName='Total Building Area' AND ColumnName='Area'\")\r\n building_area ||= \"NIL\"\r\n runner.registerValue(\"building_area\", building_area, \"m2\")\r\n metadata[metadata.length] = [\"building_area\", \"Total Building Area\", \"Bldg Area\", \"Total building area as calculated by Energy Plus\", \"square_meter\", \"double\", \"FALSE\"]\r\n\r\n #get end use totals for fuels\r\n site_energy_use = 0.0\r\n OpenStudio::EndUseFuelType.getValues.each do |fuel_type|\r\n fuel_str = OpenStudio::EndUseFuelType.new(fuel_type).valueDescription\r\n fuel_type_aggregation = 0.0\r\n mult_factor = 1\r\n if fuel_str != \"Water\"\r\n runner_units_eui = \"MJ/m2\"\r\n metadata_units_eui = \"megajoules_per_square_meter\"\r\n mult_factor = 1000\r\n runner_units_agg = \"GJ\"\r\n metadata_units_agg = \"gigajoule\"\r\n else\r\n runner_units_eui = \"m\"\r\n metadata_units_eui = \"meter\"\r\n runner_units_agg = \"m3\"\r\n metadata_units_agg = \"cubic meter\"\r\n end\r\n OpenStudio::EndUseCategoryType.getValues.each do |category_type|\r\n category_str = OpenStudio::EndUseCategoryType.new(category_type).valueDescription\r\n temp_val = sql_query(runner, sql_file, \"AnnualBuildingUtilityPerformanceSummary\", \"TableName='End Uses' AND RowName='#{category_str}' AND ColumnName='#{fuel_str}'\")\r\n if temp_val\r\n eui_val = temp_val / building_area * mult_factor\r\n prefix_str = OpenStudio::toUnderscoreCase(\"#{fuel_str}_#{category_str}_eui\")\r\n runner.registerValue(\"#{prefix_str}\", eui_val, \"#{runner_units_eui}\")\r\n short_name = \"#{short_os_fuel(fuel_str)} #{short_os_cat(category_str)} EUI\"\r\n metadata[metadata.length] = [prefix_str, \"#{category_str} #{fuel_str} EUI\", short_name, \"Total #{fuel_str.downcase} used for #{category_str.downcase} per square foot\", metadata_units_eui, \"double\", \"FALSE\"]\r\n fuel_type_aggregation += temp_val\r\n end\r\n end\r\n if fuel_type_aggregation\r\n prefix_str = OpenStudio::toUnderscoreCase(\"total_#{fuel_str}_end_use\")\r\n runner.registerValue(prefix_str, fuel_type_aggregation, \"#{runner_units_agg}\")\r\n short_name = \"#{short_os_fuel(fuel_str)} Total\"\r\n metadata[metadata.length] = [prefix_str, \"Total #{fuel_str} End Use\", short_name, \"Total #{fuel_str.downcase} End Use\", metadata_units_agg, \"double\", \"FALSE\"]\r\n site_energy_use += fuel_type_aggregation if fuel_str != \"Water\"\r\n end\r\n end\r\n\r\n runner.registerValue(\"site_energy_use\", site_energy_use, \"GJ\")\r\n metadata[metadata.length] = [\"site_energy_use\", \"Total Site Energy Use\", \"Site Energy\", \"Total energy consumption for the site\", \"gigajoule\", \"double\", \"FALSE\"]\r\n\r\n #get monthly fuel aggregates\r\n #todo: get all monthly fuel type outputs, including non-present fuel types, mapping to 0\r\n OpenStudio::EndUseFuelType.getValues.each do |fuel_type|\r\n fuel_str = OpenStudio::EndUseFuelType.new(fuel_type).valueDescription\r\n mult_factor = 10**-6 / building_area\r\n runner_units = \"MJ/m2\"\r\n metadata_units = \"megajoules_per_square_meter\"\r\n if fuel_str == \"Water\"\r\n next\r\n end\r\n OpenStudio::MonthOfYear.getValues.each do |month|\r\n if month >= 1 and month <= 12\r\n fuel_and_month_aggregation = 0.0\r\n OpenStudio::EndUseCategoryType::getValues.each do |category_type|\r\n if sql_file.energyConsumptionByMonth(OpenStudio::EndUseFuelType.new(fuel_str), OpenStudio::EndUseCategoryType.new(category_type), OpenStudio::MonthOfYear.new(month)).is_initialized\r\n val_in_j = sql_file.energyConsumptionByMonth(OpenStudio::EndUseFuelType.new(fuel_str), OpenStudio::EndUseCategoryType.new(category_type), OpenStudio::MonthOfYear.new(month)).get\r\n fuel_and_month_aggregation += val_in_j\r\n end\r\n end\r\n fuel_and_month_aggregation *= mult_factor\r\n month_str = OpenStudio::MonthOfYear.new(month).valueDescription\r\n prefix_str = OpenStudio::toUnderscoreCase(\"#{month_str}_end_use_#{fuel_str}_eui\")\r\n runner.registerValue(\"#{prefix_str}\", fuel_and_month_aggregation, \"#{runner_units}\")\r\n short_name = \"#{month_str[0..2]} #{short_os_fuel(fuel_str)} EUI\"\r\n metadata[metadata.length] = [\"#{prefix_str}\", \"#{month_str} #{fuel_str} EUI\", short_name, \"Total #{fuel_str.downcase} end use energy use per square meter in #{month_str}\", metadata_units, \"double\", \"FALSE\"]\r\n end\r\n end\r\n end\r\n\r\n # queries that don't have API methods yet\r\n\r\n life_cycle_cost = sql_query(runner, sql_file, \"Life-Cycle Cost Report\", \"TableName='Present Value by Category' AND RowName='Grand Total' AND ColumnName='Present Value'\")\r\n runner.registerValue(\"life_cycle_cost\", life_cycle_cost, \"dollars\")\r\n metadata[metadata.length] = [\"life_cycle_cost\", \"Total Life Cycle Cost\", \"Life Cycle Cost\", \"Total calculated life cycle cost\", \"us_dollar\", \"double\", \"FALSE\"]\r\n\r\n conditioned_area = sql_query(runner, sql_file, \"AnnualBuildingUtilityPerformanceSummary\", \"TableName='Building Area' AND RowName='Net Conditioned Building Area' AND ColumnName='Area'\")\r\n runner.registerValue(\"conditioned_area\", conditioned_area, \"m2\")\r\n metadata[metadata.length] = [\"conditioned_area\", \"Total Conditioned Area\", \"Cond Bldg Area\", \"Total conditioned building area as calculated by Energy Plus\", \"square_meter\", \"double\", \"FALSE\"]\r\n\r\n unconditioned_area = sql_query(runner, sql_file, \"AnnualBuildingUtilityPerformanceSummary\", \"TableName='Building Area' AND RowName='Unconditioned Building Area' AND ColumnName='Area'\")\r\n runner.registerValue(\"unconditioned_area\", unconditioned_area, \"m2\")\r\n metadata[metadata.length] = [\"unconditioned_area\", \"Total Unconditioned Area\", \"Uncond Bldg Area\", \"Total unconditioned building area as calculated by EnergyPlus\", \"square_meter\", \"double\", \"FALSE\"]\r\n\r\n total_site_eui = sql_query(runner, sql_file, \"AnnualBuildingUtilityPerformanceSummary\", \"TableName='Site and Source Energy' AND RowName='Total Site Energy' AND ColumnName='Energy Per Conditioned Building Area'\")\r\n runner.registerValue(\"total_site_eui\", total_site_eui, \"MJ/m2\")\r\n metadata[metadata.length] = [\"total_site_eui\", \"Total Site Energy Use Intensity\", \"Site EUI\", \"Total site energy use intensity per conditioned building area as calculated by EnergyPlus\", \"megajoules_per_square_meter\", \"double\", \"FALSE\"]\r\n\r\n total_source_eui = sql_query(runner, sql_file, \"AnnualBuildingUtilityPerformanceSummary\", \"TableName='Site and Source Energy' AND RowName='Total Source Energy' AND ColumnName='Energy Per Conditioned Building Area'\")\r\n runner.registerValue(\"total_source_eui\", total_source_eui, \"MJ/m2\")\r\n metadata[metadata.length] = [\"total_source_eui\", \"Total Source Energy Use Intensity\", \"Source EUI\", \"Total source energy use intensity per conditioned building area as calculated by EnergyPlus\", \"megajoules_per_square_meter\", \"double\", \"FALSE\"]\r\n\r\n time_setpoint_not_met_during_occupied_heating = sql_query(runner, sql_file, \"AnnualBuildingUtilityPerformanceSummary\", \"TableName='Comfort and Setpoint Not Met Summary' AND RowName='Time Setpoint Not Met During Occupied Heating' AND ColumnName='Facility'\")\r\n runner.registerValue(\"time_setpoint_not_met_during_occupied_heating\", time_setpoint_not_met_during_occupied_heating, \"hr\")\r\n metadata[metadata.length] = [\"time_setpoint_not_met_during_occupied_heating\", \"Occupied Time During Which Heating Setpoint Not Met\", \"Setpoint Missed Heat\", \"Hours during which the building was occupied but the heating setpoint temperature was not met\", \"hour\", \"double\", \"FALSE\"]\r\n\r\n time_setpoint_not_met_during_occupied_cooling = sql_query(runner, sql_file, \"AnnualBuildingUtilityPerformanceSummary\", \"TableName='Comfort and Setpoint Not Met Summary' AND RowName='Time Setpoint Not Met During Occupied Cooling' AND ColumnName='Facility'\")\r\n runner.registerValue(\"time_setpoint_not_met_during_occupied_cooling\", time_setpoint_not_met_during_occupied_cooling, \"hr\")\r\n metadata[metadata.length] = [\"time_setpoint_not_met_during_occupied_cooling\", \"Occupied Time During Which Cooling Setpoint Not Met\", \"Setpoint Missed Cool\", \"Hours during which the building was occupied but the cooling setpoint temperature was not met\", \"hour\", \"double\", \"FALSE\"]\r\n\r\n time_setpoint_not_met_during_occupied_hours = time_setpoint_not_met_during_occupied_heating + time_setpoint_not_met_during_occupied_cooling\r\n runner.registerValue(\"time_setpoint_not_met_during_occupied_hours\", time_setpoint_not_met_during_occupied_hours, \"hr\")\r\n metadata[metadata.length] = [\"time_setpoint_not_met_during_occupied_hours\", \"Occupied Time During Which Temperature Setpoint Not Met\", \"Setpoint Missed Total\", \"Hours during which the building was occupied but the setpoint temperatures were not met\", \"hour\", \"double\", \"FALSE\"]\r\n\r\n window_to_wall_ratio_north = sql_query(runner, sql_file, \"InputVerificationandResultsSummary\", \"TableName='Window-Wall Ratio' AND RowName='Gross Window-Wall Ratio' AND ColumnName='North (315 to 45 deg)'\")\r\n runner.registerValue(\"window_to_wall_ratio_north\", window_to_wall_ratio_north, \"%\")\r\n metadata[metadata.length] = [\"window_to_wall_ratio_north\", \"North Window to Wall Ratio\", \"WWR North\", \"Window to wall ratio of wall objects facing between 315 and 45 degrees\", \"percent\", \"double\", \"FALSE\"]\r\n\r\n window_to_wall_ratio_south = sql_query(runner, sql_file, \"InputVerificationandResultsSummary\", \"TableName='Window-Wall Ratio' AND RowName='Gross Window-Wall Ratio' AND ColumnName='South (135 to 225 deg)'\")\r\n runner.registerValue(\"window_to_wall_ratio_south\", window_to_wall_ratio_south, \"%\")\r\n metadata[metadata.length] = [\"window_to_wall_ratio_south\", \"South Window to Wall Ratio\", \"WWR South\", \"Window to wall ratio of wall objects facing between 135 and 225 degrees\", \"percent\", \"double\", \"FALSE\"]\r\n\r\n window_to_wall_ratio_east = sql_query(runner, sql_file, \"InputVerificationandResultsSummary\", \"TableName='Window-Wall Ratio' AND RowName='Gross Window-Wall Ratio' AND ColumnName='East (45 to 135 deg)'\")\r\n runner.registerValue(\"window_to_wall_ratio_east\", window_to_wall_ratio_east, \"%\")\r\n metadata[metadata.length] = [\"window_to_wall_ratio_east\", \"East Window to Wall Ratio\", \"WWR East\", \"Window to wall ratio of wall objects facing between 45 and 135 degrees\", \"percent\", \"double\", \"FALSE\"]\r\n\r\n window_to_wall_ratio_west = sql_query(runner, sql_file, \"InputVerificationandResultsSummary\", \"TableName='Window-Wall Ratio' AND RowName='Gross Window-Wall Ratio' AND ColumnName='West (225 to 315 deg)'\")\r\n runner.registerValue(\"window_to_wall_ratio_west\", window_to_wall_ratio_west, \"%\")\r\n metadata[metadata.length] = [\"window_to_wall_ratio_west\", \"West Window to Wall Ratio\", \"WWR West\", \"Window to wall ratio of wall objects facing between 225 and 315 degrees\", \"percent\", \"double\", \"FALSE\"]\r\n\r\n lat = sql_query(runner, sql_file, \"InputVerificationandResultsSummary\", \"TableName='General' AND RowName='Latitude' AND ColumnName='Value'\")\r\n runner.registerValue(\"latitude\", lat, \"deg\")\r\n metadata[metadata.length] = [\"latitude\", \"Latitude\", \"Lat\", \"Building latitude based on weather file\", \"degrees_angular\", \"double\", \"FALSE\"]\r\n\r\n long = sql_query(runner, sql_file, \"InputVerificationandResultsSummary\", \"TableName='General' AND RowName='Longitude' AND ColumnName='Value'\")\r\n runner.registerValue(\"longitude\", long, \"deg\")\r\n metadata[metadata.length] = [\"longitude\", \"Longitude\", \"Long\", \"Building longitude based on weather file\", \"degrees_angular\", \"double\", \"FALSE\"]\r\n\r\n weather_file = sql_query(runner, sql_file, \"InputVerificationandResultsSummary\", \"TableName='General' AND RowName='Weather File' AND ColumnName='Value'\")\r\n runner.registerValue(\"weather_file\", weather_file, \"deg\")\r\n metadata[metadata.length] = [\"weather_file\", \"Weather File\", \"Weather File\", \"Name of weather file\", \"none\", \"string\", \"FALSE\"]\r\n\r\n # queries with one-line API methods\r\n building_rotation = building.northAxis\r\n runner.registerValue(\"orientation\", building_rotation, \"deg\")\r\n metadata[metadata.length] = [\"orientation\", \"Building Orientation\", \"Orientation\", \"Degrees of building north axis off of true north\", \"degrees_angular\", \"double\", \"FALSE\"]\r\n\r\n #floor_to_floor_height = building.nominalFloortoFloorHeight.get\r\n #runner.registerValue(\"floor_to_floor_height\", floor_to_floor_height, \"m\")\r\n #metadata[metadata.length] = [\"floor_to_floor_height\", \"Floor to Floor Height\", \"Flr-to-Flr Height\", \"Nominal floor to floor height of building\", \"meter\", \"double\", \"FALSE\"]\r\n\r\n #total_building_volume = building_area * floor_to_floor_height\r\n #runner.registerValue(\"total_building_volume\", total_building_volume, \"m3\")\r\n #metadata[metadata.length] = [\"total_building_volume\", \"Total Building Volume\", \"Volume\", \"Building volume calculated by multiplying floor to floor height and footprint\", \"cubic_meter\", \"double\", \"FALSE\"]\r\n\r\n total_occupancy = building.numberOfPeople\r\n runner.registerValue(\"total_occupancy\", total_occupancy, \"people\")\r\n metadata[metadata.length] = [\"total_occupancy\", \"Total Building Occupancy\", \"Bldg Occ\", \"Number of people in the building as calculated by EnergyPlus\", \"none\", \"double\", \"FALSE\"]\r\n\r\n occupancy_density = building.peoplePerFloorArea\r\n runner.registerValue(\"occupant_density\", occupancy_density, \"people/m2\")\r\n metadata[metadata.length] = [\"occupant_density\", \"Building Occupancy Density\", \"Occ Density\", \"Number of people per floor area as calculated by EnergyPlus\", \"none\", \"double\", \"FALSE\"]\r\n\r\n lighting_power = building.lightingPower\r\n runner.registerValue(\"lighting_power\", lighting_power, \"W\")\r\n metadata[metadata.length] = [\"lighting_power\", \"Lighting Power\", \"Lighting Pwr\", \"Total lighting power\", \"watt\", \"double\", \"FALSE\"]\r\n\r\n lighting_power_density = building.lightingPowerPerFloorArea\r\n runner.registerValue(\"lighting_power_density\", lighting_power_density, \"W/m2\")\r\n metadata[metadata.length] = [\"lighting_power_density\", \"Lighting Power Density\", \"LPD\", \"Total lighting power density\", \"watts_per_square_meter\", \"double\", \"FALSE\"]\r\n\r\n infiltration_rate = building.infiltrationDesignAirChangesPerHour\r\n runner.registerValue(\"infiltration_rate\", infiltration_rate, \"ACH\")\r\n metadata[metadata.length] = [\"infiltration_rate\", \"Infiltration Rate\", \"Infil Rate\", \"Infiltration rate of air into the building\", \"none\", \"double\", \"FALSE\"]\r\n\r\n number_of_floors = building.standardsNumberOfStories.get if building.standardsNumberOfStories.is_initialized\r\n number_of_floors ||= \"NIL\"\r\n runner.registerValue(\"number_of_floors\", number_of_floors, \"\")\r\n metadata[metadata.length] = [\"number_of_floors\", \"Number of Floors\", \"Number of Floors\", \"Total number of storeys in the building\", \"none\", \"double\", \"FALSE\"]\r\n\r\n building_type = building.standardsBuildingType if building.standardsBuildingType.is_initialized\r\n building_type ||= \"NIL\"\r\n runner.registerValue(\"building_type\", building_type, \"\")\r\n metadata[metadata.length] = [\"building_type\", \"Building Type\", \"Bldg Type\", \"Building type as defined by the modeler\", \"none\", \"string\", \"FALSE\"]\r\n\r\n #get exterior wall, exterior roof, and ground plate areas\r\n exterior_wall_area = 0.0\r\n exterior_roof_area = 0.0\r\n ground_contact_area = 0.0\r\n surfaces = model.getSurfaces\r\n surfaces.each do |surface|\r\n if surface.outsideBoundaryCondition == \"Outdoors\" and surface.surfaceType == \"Wall\"\r\n exterior_wall_area += surface.netArea\r\n end\r\n if surface.outsideBoundaryCondition == \"Outdoors\" and surface.surfaceType == \"RoofCeiling\"\r\n exterior_roof_area += surface.netArea\r\n end\r\n if surface.outsideBoundaryCondition == \"Ground\" and surface.surfaceType == \"Floor\"\r\n ground_contact_area += surface.netArea\r\n end\r\n end\r\n\r\n runner.registerValue(\"exterior_wall_area\", exterior_wall_area, \"m2\")\r\n metadata[metadata.length] = [\"exterior_wall_area\", \"Exterior Wall Area\", \"Ext Wall Area\", \"Total area of all surfaces with the conditions of 'Outdoors' and 'Wall'\", \"square_meter\", \"double\", \"FALSE\"]\r\n\r\n runner.registerValue(\"exterior_roof_area\", exterior_roof_area, \"m2\")\r\n metadata[metadata.length] = [\"exterior_roof_area\", \"Exterior Roof Area\", \"Ext Roof Area\", \"Total area of all surfaces with the conditions of 'Outdoors' and 'Roof'\", \"square_meter\", \"double\", \"FALSE\"]\r\n\r\n runner.registerValue(\"ground_contact_area\", ground_contact_area, \"m2\")\r\n metadata[metadata.length] = [\"ground_contact_area\", \"Ground Contact Area\", \"Gnd Area\", \"Total area of all surfaces with the conditions of 'Ground' and 'Floor'\", \"square_meter\", \"double\", \"FALSE\"]\r\n\r\n #get exterior fenestration area\r\n exterior_fenestration_area = 0.0\r\n subsurfaces = model.getSubSurfaces\r\n subsurfaces.each do |subsurface|\r\n if subsurface.outsideBoundaryCondition == \"Outdoors\"\r\n if subsurface.subSurfaceType == \"FixedWindow\" or subsurface.subSurfaceType == \"OperableWindow\"\r\n exterior_fenestration_area += subsurface.netArea\r\n end\r\n end\r\n end\r\n\r\n runner.registerValue(\"exterior_fenestration_area\", exterior_fenestration_area, \"m2\")\r\n metadata[metadata.length] = [\"exterior_fenestration_area\", \"Exterior Fenestration Area\", \"Window Area Total\", \"Total area of all surfaces with the conditions of 'Outdoors' and 'FixedWindow' or 'OperableWindow'\", \"square_meter\", \"double\", \"FALSE\"]\r\n\r\n #get density of economizers in airloops\r\n num_airloops = 0\r\n num_economizers = 0\r\n model.getAirLoopHVACs.each do |air_loop|\r\n num_airloops += 1\r\n if air_loop.airLoopHVACOutdoorAirSystem.is_initialized\r\n air_loop_oa = air_loop.airLoopHVACOutdoorAirSystem.get\r\n air_loop_oa_controller = air_loop_oa.getControllerOutdoorAir\r\n if air_loop_oa_controller.getEconomizerControlType != \"NoEconomizer\"\r\n num_economizers += 1\r\n end\r\n end\r\n end\r\n economizer_density = num_economizers / num_airloops if num_airloops != 0\r\n economizer_density ||= \"NIL\"\r\n\r\n runner.registerValue(\"economizer_density\", economizer_density, \"\")\r\n metadata[metadata.length] = [\"economizer_density\", \"Economizer Density\", \"Econ Density\", \"Proportion of air loops with economizers to air loops without\", \"percent\", \"double\", \"FALSE\"]\r\n\r\n #get aspect ratios\r\n north_wall_area = sql_query(runner, sql_file, \"InputVerificationandResultsSummary\", \"TableName='Window-Wall Ratio' AND RowName='Gross Wall Area' AND ColumnName='North (315 to 45 deg)'\")\r\n east_wall_area = sql_query(runner, sql_file, \"InputVerificationandResultsSummary\", \"TableName='Window-Wall Ratio' AND RowName='Gross Wall Area' AND ColumnName='East (45 to 135 deg)'\")\r\n aspect_ratio = north_wall_area / east_wall_area if north_wall_area != 0 && east_wall_area != 0\r\n aspect_ratio ||= \"NIL\"\r\n\r\n runner.registerValue(\"aspect_ratio\", aspect_ratio, \"\")\r\n metadata[metadata.length] = [\"aspect_ratio\", \"Aspect Ratio\", \"Aspect Ratio\", \"Proportion of north wall area to east wall area\", \"percent\", \"double\", \"FALSE\"]\r\n\r\n #write metadata CSV\r\n runner.registerInfo(\"Saving Dencity metadata csv file\")\r\n CSV.open(\"report_metadata.csv\", \"wb\") do |csv|\r\n metadata.each do |elem|\r\n csv << elem\r\n end\r\n end\r\n runner.registerInfo(\"Saved Dencity metadata as report_metadata.csv\")\r\n\r\n #get meter timeseries data and output as a msgpack or csv or both\r\n #todo: find a way for the sql call to not rely on RUN PERIOD 1\r\n timeseries_start = Time.now.to_i\r\n available_meters = sql_file.execAndReturnVectorOfString(\"SELECT VariableName FROM ReportMeterDataDictionary WHERE VariableType='Sum' AND ReportingFrequency='Hourly'\")\r\n get_timeseries_flag = TRUE\r\n if available_meters.empty?\r\n runner.registerWarning(\"No meters found with Hourly reporting frequency to extract timeseries data from\")\r\n else\r\n begin\r\n meter_strings = available_meters.get\r\n runner.registerInfo(\"The following meters were found: #{meter_strings}\")\r\n rescue\r\n runner.registerWarning(\"Unable to retrieve timeseries strings\")\r\n get_timeseries_flag = FALSE\r\n end\r\n meter_units = sql_file.execAndReturnVectorOfString(\"SELECT VariableUnits FROM ReportMeterDataDictionary WHERE VariableType='Sum' AND ReportingFrequency='Hourly'\")\r\n begin\r\n meter_units = meter_units.get\r\n runner.registerInfo(\"Units were found for all available meters\")\r\n rescue\r\n runner.registerWarning(\"Unable to retrieve timeseries unit strings\")\r\n get_timeseries_flag = FALSE\r\n end\r\n runner.registerInfo(\"The following meter units were found: #{meter_units}\")\r\n runner.registerError(\"Timeseries variable names and units of differing lengths. Exiting Dencity Reports.\") if meter_units.size != meter_strings.size\r\n get_timeseries_flag = FALSE if meter_units.size != meter_strings.size\r\n end\r\n\r\n runner.registerInfo(\"get_timeseries_flag is set to #{get_timeseries_flag}\")\r\n if get_timeseries_flag\r\n runner.registerInfo(\"Retrieving timeseries data\")\r\n if msgpack_flag and csv_flag\r\n require \"parallel\"\r\n require \"msgpack\"\r\n msgpack_array = []\r\n csv_array = []\r\n mark0 = Time.now.to_i\r\n Parallel.each_with_index(meter_strings, :in_threads => 4) do |meter_string, meter_index|\r\n if sql_file.timeSeries(\"RUN PERIOD 1\", \"Hourly\", meter_string, \"\").is_initialized\r\n sql_ts = sql_file.timeSeries(\"RUN PERIOD 1\", \"Hourly\", meter_string, \"\").get\r\n ts_values = sql_ts.values\r\n ts_times = sql_ts.dateTimes\r\n timeseries_out = {}\r\n initial_epoch_time = Time.parse(ts_times[0].toString).to_i*1000\r\n timestep_in_epoch = (Time.parse(ts_times[1].toString).to_i - Time.parse(ts_times[0].toString).to_i)*1000\r\n timeseries_out[initial_epoch_time] = ts_values[0]\r\n next_epoch_time = initial_epoch_time\r\n for i in 1..ts_times.size - 1\r\n next_epoch_time += timestep_in_epoch\r\n timeseries_out[next_epoch_time] = ts_values[i]\r\n end\r\n csv_array << ([\"epoch_time\"] + timeseries_out.to_a.transpose[0]) if meter_index == 0\r\n csv_array << ([meter_string.gsub(\":\", \"_\") + \" [\" + meter_units[meter_index] + \"]\"] + timeseries_out.to_a.transpose[1])\r\n meter_hash = {timeseries: {}}\r\n meter_hash[:timeseries][:fuel] = meter_string.gsub(\":\", \"_\")\r\n meter_hash[:timeseries][:interval] = Time.parse(ts_times[1].toString).to_i - Time.parse(ts_times[0].toString).to_i\r\n meter_hash[:timeseries][:interval_units] = \"seconds\"\r\n meter_hash[:timeseries][:data] = timeseries_out\r\n meter_hash[:timeseries][:units] = meter_units[meter_index]\r\n msgpack_array << meter_hash\r\n else\r\n runner.registerWarning(\"Timeseries #{meter_string} was empty.\")\r\n end\r\n end\r\n mark1 = Time.now.to_i\r\n runner.registerInfo(\"DeltaMake=#{mark1-mark0}s\")\r\n File.open(\"report_timeseries.msgpack\", \"w\") do |file|\r\n file << {data: msgpack_array}.to_msgpack\r\n end\r\n runner.registerInfo(\"Saved timeseries data as report_timeseries.msgpack\")\r\n csv_array = csv_array.transpose\r\n CSV.open(\"report_timeseries.csv\", \"w\") do |csv|\r\n csv_array.each do |elem|\r\n csv << elem\r\n end\r\n end\r\n runner.registerInfo(\"Saved timeseries data as report_timeseries.csv\")\r\n mark2 = Time.now.to_i\r\n runner.registerInfo(\"DeltaWrite=#{mark2-mark1}s\")\r\n\r\n elsif msgpack_flag\r\n require \"parallel\"\r\n require \"msgpack\"\r\n msgpack_array = []\r\n mark0 = Time.now.to_i\r\n meter_strings.each_with_index(meter_strings, :in_threads => 4) do |meter_string, meter_index|\r\n if sql_file.timeSeries(\"RUN PERIOD 1\", \"Hourly\", meter_string, \"\").is_initialized\r\n sql_ts = sql_file.timeSeries(\"RUN PERIOD 1\", \"Hourly\", meter_string, \"\").get\r\n ts_values = sql_ts.values\r\n ts_times = sql_ts.dateTimes\r\n timeseries_out = {}\r\n initial_epoch_time = Time.parse(ts_times[0].toString).to_i*1000\r\n timestep_in_epoch = (Time.parse(ts_times[1].toString).to_i - Time.parse(ts_times[0].toString).to_i)*1000\r\n timeseries_out[initial_epoch_time] = ts_values[0]\r\n next_epoch_time = initial_epoch_time\r\n for i in 1..ts_times.size - 1\r\n next_epoch_time += timestep_in_epoch\r\n timeseries_out[next_epoch_time] = ts_values[i]\r\n end\r\n meter_hash = {timeseries: {}}\r\n meter_hash[:timeseries][:fuel] = meter_string.gsub(\":\", \"_\")\r\n meter_hash[:timeseries][:interval] = Time.parse(ts_times[1].toString).to_i - Time.parse(ts_times[0].toString).to_i\r\n meter_hash[:timeseries][:interval_units] = \"seconds\"\r\n meter_hash[:timeseries][:data] = timeseries_out\r\n meter_hash[:timeseries][:units] = meter_units[meter_index]\r\n msgpack_array << meter_hash\r\n else\r\n runner.registerWarning(\"Timeseries #{meter_string} was empty.\")\r\n end\r\n end\r\n mark1 = Time.now.to_i\r\n runner.registerInfo(\"DeltaMake=#{mark1-mark0}s\")\r\n File.open(\"report_timeseries.msgpack\", \"w\") do |file|\r\n file << {data: msgpack_array}.to_msgpack\r\n runner.registerInfo(\"Saved timeseries data as report_timeseries.msgpack\")\r\n end\r\n mark2 = Time.now.to_i\r\n runner.registerInfo(\"DeltaWrite=#{mark2-mark1}s\")\r\n\r\n elsif csv_flag\r\n require \"parallel\"\r\n csv_array = []\r\n mark0 = Time.now.to_i\r\n Parallel.each_with_index(meter_strings, :in_threads => 4) do |meter_string, meter_index|\r\n if sql_file.timeSeries(\"RUN PERIOD 1\", \"Hourly\", meter_string, \"\").is_initialized\r\n sql_ts = sql_file.timeSeries(\"RUN PERIOD 1\", \"Hourly\", meter_string, \"\").get\r\n ts_values = sql_ts.values\r\n ts_times = sql_ts.dateTimes\r\n timeseries_out = {}\r\n initial_epoch_time = Time.parse(ts_times[0].toString).to_i*1000\r\n timestep_in_epoch = (Time.parse(ts_times[1].toString).to_i - Time.parse(ts_times[0].toString).to_i)*1000\r\n timeseries_out[initial_epoch_time] = ts_values[0]\r\n next_epoch_time = initial_epoch_time\r\n for i in 1..ts_times.size - 1\r\n next_epoch_time += timestep_in_epoch\r\n timeseries_out[next_epoch_time] = ts_values[i]\r\n end\r\n csv_array << ([\"epoch_time\"] + timeseries_out.to_a.transpose[0]) if meter_index == 0\r\n csv_array << ([meter_string.gsub(\":\", \"_\") + \" [\" + meter_units[meter_index] + \"]\"] + timeseries_out.to_a.transpose[1])\r\n else\r\n runner.registerWarning(\"Timeseries #{meter_string} was empty.\")\r\n end\r\n end\r\n mark1 = Time.now.to_i\r\n runner.registerInfo(\"DeltaMake=#{mark1-mark0}s\")\r\n csv_array = csv_array.transpose\r\n CSV.open(\"report_timeseries.csv\", \"w\") do |csv|\r\n csv_array.each do |elem|\r\n csv << elem\r\n end\r\n end\r\n runner.registerInfo(\"Saved timeseries data as report_timeseries.csv\")\r\n mark2 = Time.now.to_i\r\n runner.registerInfo(\"DeltaWrite=#{mark2-mark1}s\")\r\n end\r\n end\r\n timeseries_end = Time.now.to_i\r\n runner.registerInfo(\"Total Timeseries Time: #{timeseries_end-timeseries_start}\")\r\n\r\n #closing the sql file\r\n sql_file.close\r\n\r\n #reporting final condition\r\n runner.registerFinalCondition(\"DEnCity Report generated successfully.\")\r\n\r\n rescue => e\r\n fail \"Measure failed with #{e.message}:#{e.backtrace}\"\r\n ensure\r\n\r\n # profile_results = RubyProf.stop\r\n # FileUtils.mkdir_p 'results'\r\n # File.open(\"results/profile-graph.html\", 'w') { |f| RubyProf::GraphHtmlPrinter.new(profile_results).print(f) }\r\n # File.open(\"results/profile-flat.txt\", 'w') { |f| RubyProf::FlatPrinter.new(profile_results).print(f) }\r\n # File.open(\"results/profile-tree.prof\", 'w') { |f| RubyProf::CallTreePrinter.new(profile_results).print(f) }\r\n\r\n\r\n end\r\n\r\n true\r\n\r\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n # use the built-in error checking\n if !runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n runner.registerInfo(\"Start to create lighting measure from occupant schedule\")\n\n ### Get user selected lighting space assumptions for each space\n v_space_types = model.getSpaceTypes\n i = 1\n lght_space_type_arg_vals = {}\n # Loop through all space types, group spaces by their types\n v_space_types.each do |space_type|\n # Loop through all spaces of current space type\n v_current_spaces = space_type.spaces\n next if not v_current_spaces.size > 0\n v_current_spaces.each do |current_space|\n lght_space_type_val = runner.getStringArgumentValue(@@v_space_args[current_space.nameString], user_arguments)\n lght_space_type_arg_vals[current_space.nameString] = lght_space_type_val\n i += 1\n end\n end\n\n puts lght_space_type_arg_vals\n\n ### Start creating new lighting schedules based on occupancy schedule\n occ_schedule_dir = runner.getStringArgumentValue('occ_schedule_dir', user_arguments)\n model_temp_run_path = Dir.pwd + '/'\n measure_root_path = File.dirname(__FILE__)\n\n puts '=' * 80\n puts measure_root_path\n\n if File.file?(occ_schedule_dir)\n # Check if user provided a occupancy schedule CSV file\n csv_file = occ_schedule_dir\n puts 'Use user provided occupancy schedule file at: ' + csv_file.to_s\n runner.registerInitialCondition('Location check:' + File.expand_path(\"../..\", measure_root_path))\n # runner.registerInitialCondition('Use user provided occupancy schedule file at: ' + csv_file.to_s)\n else\n # Check if schedule file at several places\n # 1. Default fils path when run with OSW in CLI\n csv_path_lookup_1 = File.expand_path(\"../..\", measure_root_path) + \"/files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"First lookup location: \" + csv_path_lookup_1\n runner.registerInfo(\"First lookup location: \" + csv_path_lookup_1)\n # 2. Default path when run with OpenStudio CLI\n csv_path_lookup_2 = File.expand_path(\"../..\", model_temp_run_path) + \"/files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"Second lookup location: \" + csv_path_lookup_2\n runner.registerInfo(\"Second lookup location: \" + csv_path_lookup_2)\n # 3. Default path when run with OpenStudio GUI\n csv_path_lookup_3 = File.expand_path(\"../../..\", model_temp_run_path) + \"/resources/files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"Third lookup location: \" + csv_path_lookup_3\n runner.registerInfo(\"Third lookup location: \" + csv_path_lookup_3)\n # 4. Generated files folder when run with rspec\n csv_path_lookup_4 = File.expand_path(\"..\", model_temp_run_path) + \"/generated_files/#{@@default_occupant_schedule_filename}\"\n puts '#' * 80\n puts \"Forth lookup location: \" + csv_path_lookup_4\n runner.registerInfo(\"Forth lookup location: \" + csv_path_lookup_4)\n # 5. Generated files folder with OpenStudio V2.9.0+\n csv_path_lookup_5 = File.join(File.expand_path(\"../..\", model_temp_run_path), 'generated_files', @@default_occupant_schedule_filename)\n puts '#' * 80\n puts \"Fifth lookup location: \" + csv_path_lookup_5\n runner.registerInfo(\"Fifth lookup location: \" + csv_path_lookup_5)\n\n if File.file?(csv_path_lookup_1)\n csv_file = csv_path_lookup_1\n elsif File.file?(csv_path_lookup_2)\n csv_file = csv_path_lookup_2\n elsif File.file?(csv_path_lookup_3)\n csv_file = csv_path_lookup_3\n elsif File.file?(csv_path_lookup_4)\n csv_file = csv_path_lookup_4 \n elsif File.file?(csv_path_lookup_5)\n csv_file = csv_path_lookup_5\n else\n csv_file = ''\n end\n puts 'Use default occupancy schedule file at: ' + csv_file.to_s\n runner.registerInfo('Use default occupancy schedule file at: ' + csv_file.to_s)\n end\n\n # Get the spaces with occupancy count schedule available\n v_spaces_occ_sch = File.readlines(csv_file)[3].split(',') # Room ID is saved in 4th row of the occ_sch file\n v_headers = Array.new\n v_spaces_occ_sch.each do |space_occ_sch|\n if !['Room ID', 'Outdoor', 'Outside building'].include? space_occ_sch and !space_occ_sch.strip.empty?\n v_headers << space_occ_sch\n end\n end\n v_headers = [\"Time\"] + v_headers\n\n # report initial condition of model\n runner.registerInfo(\"The building has #{v_headers.length - 1} spaces with available occupant schedule file.\")\n\n # Read the occupant count schedule file and clean it\n clean_csv = File.readlines(csv_file).drop(6).join\n csv_table_sch = CSV.parse(clean_csv, headers: true)\n new_csv_table = csv_table_sch.by_col!.delete_if do |column_name, column_values|\n !v_headers.include? column_name\n end\n\n runner.registerInfo(\"Successfully read occupant count schedule from CSV file.\")\n runner.registerInfo(\"Creating new lighting schedules...\")\n\n # Create lighting schedule based on the occupant count schedule\n v_cols = Array.new\n v_ts = new_csv_table.by_col!['Time']\n v_headers.each do |header|\n if header != 'Time'\n space_name = header\n v_occ_n = new_csv_table.by_col![space_name]\n v_light = create_lighting_sch_from_occupancy_count(space_name, v_ts, v_occ_n, @@off_delay)\n v_cols << v_light\n end\n end\n\n runner.registerInfo(\"Writing new lighting schedules to CSV file.\")\n # Write new lighting schedule file to CSV\n file_name_light_sch = \"#{model_temp_run_path}/#{@@lighting_schedule_CSV_name}\"\n vcols_to_csv(v_cols, file_name_light_sch)\n\n # Add new lighting schedule from the CSV file created\n runner.registerInfo(\"Removing old OS:Lights and OS:Lights:Definition for office and conference rooms.\")\n # Remove old lights definition objects for office and conference rooms\n v_space_types.each do |space_type|\n space_type.spaces.each do |space|\n selected_space_type = lght_space_type_arg_vals[space.name.to_s]\n if (@@office_type_names.include? selected_space_type) || (@@conference_room_type_names.include? selected_space_type)\n space_type.lights.each do |lght|\n puts 'Remove old lights definition object: ' + lght.lightsDefinition.name.to_s\n lght.lightsDefinition.remove\n end\n end\n end\n end\n\n # Remove old lights objects for office and conference rooms\n # Caution: the order of deletion matters\n v_space_types.each do |space_type|\n space_type.spaces.each do |space|\n selected_space_type = lght_space_type_arg_vals[space.name.to_s]\n if (@@office_type_names.include? selected_space_type) || (@@conference_room_type_names.include? selected_space_type)\n space_type.lights.each do |lght|\n puts 'Remove old lights object: ' + lght.name.to_s\n lght.remove\n end\n end\n end\n end\n\n puts '---> Create new lighting schedules from CSV.'\n\n runner.registerInfo(\"Adding new OS:Schedule:File objects to the model....\")\n v_spaces = model.getSpaces\n v_spaces.each do |space|\n v_headers.each_with_index do |s_space_name, i|\n if s_space_name == space.name.to_s\n col = i\n temp_file_path = file_name_light_sch\n sch_file_name = space.name.to_s + ' lght sch'\n schedule_file = get_os_schedule_from_csv(model, temp_file_path, sch_file_name, col, skip_row = 1)\n schedule_file.setMinutesperItem(@@minute_per_item.to_s)\n model = add_light(model, space, schedule_file)\n end\n end\n end\n\n # report final condition of model\n runner.registerFinalCondition(\"Finished creating and adding new lighting schedules for #{v_headers.length - 1} spaces.\")\n\n return true\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n # Make an argument to apply/not apply this measure\n chs = OpenStudio::StringVector.new\n chs << \"TRUE\"\n chs << \"FALSE\"\n apply_measure = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('apply_measure', chs, true)\n apply_measure.setDisplayName(\"Apply Measure?\")\n apply_measure.setDefaultValue(\"TRUE\")\n args << apply_measure\n \n #Argument 1 Type of Chilled Beam System, required, choice, default Active\n beam_options = [\"Active\", \"Passive\"]\n cooled_beam_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"cooled_beam_type\", beam_options,true)\n cooled_beam_type.setDisplayName('Select the Type of Chilled Beam to be added and indicate the Thermal Zones that Chilled Beams will be added to. NOTE: Users should confirm subsequent chilled beam model parameters. Defaulted coefficient values may not be representative of actual chilled beam performance')\n cooled_beam_type.setDefaultValue(\"Active\")\n args << cooled_beam_type\n \n #Argument 3 Chilled Water Loop selection or creation \n existing_plant_loops = model.getPlantLoops\n existing_chilled_loops = existing_plant_loops.select{ |pl| pl.sizingPlant.loopType() == \"Cooling\"}\n existing_plant_names = existing_chilled_loops.select{ |pl| not pl.name.empty?}.collect{ |pl| pl.name.get }\n existing_plant_names << \"Create New\"\n existing_plant_loop_name = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"existing_plant_loop_name\", existing_plant_names, true)\n existing_plant_loop_name.setDisplayName('Chilled Water loop serving chilled beams. If \"Create New\" is selected a loop containing an air cooled chiller (COP=3.5) generating chilled water at 57 Deg F will be created. A constant speed pump (with user defined pressure rise) will be created.')\n existing_plant_loop_name.setDefaultValue (\"Create New\")\n args << existing_plant_loop_name\n \n #argument 4, new loop rated pump head type double, required, double, default 60 feet\n new_loop_rated_pump_head = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('new_loop_pump_head', true)\n new_loop_rated_pump_head.setDisplayName('The pump head (in feet of water) that will be assigned to the primary chilled water loop circulation pump. This argument will only be used if a new chilled water plant loop is created.')\n new_loop_rated_pump_head.setDefaultValue (60)\n args<< new_loop_rated_pump_head\n #must check interpretation of the 60 default value for pump head. meant to be 60 feet.\n \n #argument 5. air_loop_name, required, double, default Create New\n air_loops_list = model.getAirLoopHVACs.collect { |l| l.name.get }\n air_loops_list << \"Create New\"\n air_loop_name = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('air_loop_name', air_loops_list, true)\n air_loop_name.setDisplayName('Air loop to serve selected zones by chilled beam units. This should be an air loop configured as a DOAS. If \"Create New\" is selected, an air loop containing a Dual Wheel DOAS system with a chilled water coil served by the user selected chiller plant loop will be created. The DOAS will be configured to deliver a constant temperature of 65 Deg F to connected zones.')\n air_loop_name.setDefaultValue (\"Create New\")\n args << air_loop_name\n \n #argument 5.5 (mislabeled in spec) new airloop fan pressure rise, required, double, default none\n new_airloop_fan_pressure_rise = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('new_airloop_fan_pressure_rise',true)\n new_airloop_fan_pressure_rise.setDisplayName('The pressure rise (inches of water) that will be assigned to the constant speed fans of a new air loop. This pressure rise, which includes the pressure across an energy wheel, will be split evenly between the new supply and exhaust fans.')\n new_airloop_fan_pressure_rise.setDefaultValue(\"5.00\")\n args << new_airloop_fan_pressure_rise\n \n #argument 6 supply air vol flow rate, double, default to -1\n supply_air_vol_flow_rate = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('supply_air_vol_flow_rate',true)\n supply_air_vol_flow_rate.setDisplayName('The combined air flow rate (cfm) of the supply air serving all chilled beams in a zone. Enter -1 to autosize (based on the zone ventilation requirement). If a value is entered, and multiple thermal zones are selected, this value will be hard coded to all selected zones.')\n supply_air_vol_flow_rate.setDefaultValue(\"-1\")\n args << supply_air_vol_flow_rate\n \n #argument 7 max tot chw vol flow rate, required, double, default -1\n max_tot_chw_vol_flow_rate = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('max_tot_chw_vol_flow_rate',true)\n max_tot_chw_vol_flow_rate.setDisplayName('Combined maximum chilled water flow rate (gpm) of all chilled beam units serving a zone. Enter -1 to autosize based on the zone design load. If a value is entered, and multiple thermal zones are selected, this value will be hard coded to all selected zones.')\n max_tot_chw_vol_flow_rate.setDefaultValue(\"-1\")\n args << max_tot_chw_vol_flow_rate\n \n #arg 8 number of beams, required, double, default -1\n number_of_beams = OpenStudio::Ruleset::OSArgument::makeIntegerArgument('number_of_beams',true)\n number_of_beams.setDisplayName('The number of individual chilled beam units serving each zone. Enter -1 to autosize based on a value of 1.11 GPM per chilled beam unit.')\n number_of_beams.setDefaultValue(\"-1\")\n args << number_of_beams\n \n #arg9 beam_length, required, double, defailt -1\n beam_length = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('beam_length',true)\n beam_length.setDisplayName('The length (ft) of an individual beam. Enter -1 to autosize based upon the # of beam units and the zone design sensible cooling load.')\n beam_length.setDefaultValue(\"-1\")\n args << beam_length\n \n #arg10 design_inlet_water_temperature, requried, double, default 59\n design_inlet_water_temperature = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('design_inlet_water_temperature',true)\n design_inlet_water_temperature.setDisplayName('The design inlet water temperature (Deg F) of a beam unit.')\n design_inlet_water_temperature.setDefaultValue(\"59\")\n args << design_inlet_water_temperature\n \n #arg11 design_outlet_water_temperature, required, double, default 62.6\n design_outlet_water_temperature = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('design_outlet_water_temperature',true)\n design_outlet_water_temperature.setDisplayName('The design outlet water temperature )Deg F) of the beam units.')\n design_outlet_water_temperature.setDefaultValue(\"62.6\")\n args << design_outlet_water_temperature\n \n #arg12 coil_surface_area_per_coil_length, required, double, default 17.78\n coil_surface_area_per_coil_length = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coil_surface_area_per_coil_length',true)\n coil_surface_area_per_coil_length.setDisplayName('Surface area on the air side of the beam per unit beam length (ft^2/ft). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coil_surface_area_per_coil_length.setDefaultValue(\"17.78\")\n args << coil_surface_area_per_coil_length\n \n #arg13 coefficient_alpha required, double, default 15.3\n coefficient_alpha = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_alpha',true)\n coefficient_alpha.setDisplayName('Model parameter alpha (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_alpha.setDefaultValue(\"15.3\")\n args << coefficient_alpha\n \n #arg14 coefficient_n1, required, double, default 0\n coefficient_n1 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_n1',true)\n coefficient_n1.setDisplayName('Model parameter n1 (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_n1.setDefaultValue(\"0\")\n args << coefficient_n1\n \n #arg15 coefficient_n2,required, double, default .84)\n coefficient_n2 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_n2',true)\n coefficient_n2.setDisplayName('Model parameter n2 (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_n2.setDefaultValue(\"0.84\")\n args << coefficient_n2\n\n #arg16 coefficient_n3,required, double, default .84)\n coefficient_n3 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_n3',true)\n coefficient_n3.setDisplayName('Model parameter n3 (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_n3.setDefaultValue(\".12\")\n args << coefficient_n3\n \n #arg17 coefficient_a0,required, double, default .5610)\n coefficient_a0 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_a0',true)\n coefficient_a0.setDisplayName('Model parameter a0 (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_a0.setDefaultValue(\".5610\")\n args << coefficient_a0\n \n #arg18 coefficient_k1,required, double, default .00571)\n coefficient_k1 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_k1',true)\n coefficient_k1.setDisplayName('Model parameter k1 (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_k1.setDefaultValue(\".005710\")\n args << coefficient_k1\n \n #arg19 coefficient_n,required, double, default .40)\n coefficient_n = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_n',true)\n coefficient_n.setDisplayName('Model parameter n (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_n.setDefaultValue(\".400\")\n args << coefficient_n\n \n #arg20 coefficient_kin,required, double, default 2.0)\n coefficient_kin = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_kin',true)\n coefficient_kin.setDisplayName('Model parameter kin (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_kin.setDefaultValue(\"2.0\")\n args << coefficient_kin\n \n #argument 21 leaving_pipe_inside_dia, required, choice, default \"1/2 type K\"\n pipe_inside_dia_options = [\"1/2 Type K\", \"1/2 Type L\", \"3/4 Type K\", \"3/4 Type L\"]\n leaving_pipe_inside_dia = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"leaving_pipe_inside_dia\", pipe_inside_dia_options,true)\n leaving_pipe_inside_dia.setDisplayName('Diameter (inches) of the chilled beam unit water inlet and outlet pipe connections.')\n leaving_pipe_inside_dia.setDefaultValue(\"1/2 Type K\")\n args << leaving_pipe_inside_dia\n #note: [1/2 TypeK = .527 ] [1/2 Type L = .545] [3/4 type k = .745] [3/4 type l=.785]\n \n return args\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n\n #use the built-in error checking\n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\n #assign the user inputs to variables\n htg_setback_f = runner.getDoubleArgumentValue(\"htg_setback_f\",user_arguments)\n clg_setback_f = runner.getDoubleArgumentValue(\"clg_setback_f\",user_arguments)\n start_time = runner.getStringArgumentValue(\"start_time\",user_arguments)\n end_time = runner.getStringArgumentValue(\"end_time\",user_arguments)\n material_cost = runner.getDoubleArgumentValue(\"material_cost\",user_arguments)\n\n #split times into minutes and hours\n start_hr = start_time.split(\":\")[0].to_i\n start_min = start_time.split(\":\")[1].to_i\n end_hr = end_time.split(\":\")[0].to_i\n end_min = end_time.split(\":\")[1].to_i\n \n #show user inputs\n runner.registerInfo(\"Adding #{htg_setback_f}F heating and #{clg_setback_f}F cooling setback from #{start_hr}:#{start_min} to #{end_hr}:#{end_min}\")\n \n #arrays to store messages that occur inside reduce_schedule\n @infos = []\n \n #define a method to reduce schedule values\n #within a given timeframe\n def reduce_schedule(sch, start_hr, start_min, end_hr, end_min, setback_c)\n if sch.to_ScheduleRuleset.is_initialized\n sch = sch.to_ScheduleRuleset.get\n else\n return false\n end\n \n @infos << \"Modifying #{sch.name}\"\n \n start_time = OpenStudio::Time.new(0, start_hr, start_min, 0)\n end_time = OpenStudio::Time.new(0, end_hr, end_min, 0)\n crosses_midnight = false\n if start_time < end_time\n crosses_midnight = false\n elsif start_time > end_time\n crosses_midnight = true\n end\n \n @infos << \"crosses_midnight = #{crosses_midnight}\"\n \n day_profiles = []\n day_profiles << sch.defaultDaySchedule\n sch.scheduleRules.each do |rule|\n day_profiles << rule.daySchedule\n end\n \n day_profiles.each do |day_profile|\n\n #report out the original schedule\n @infos << \"Before setback:\"\n day_profile.times.zip(day_profile.values).each do |time,val|\n @infos << \"#{time} = #{val}\"\n end\n\n original_start_time_val = day_profile.getValue(start_time)\n original_end_time_val = day_profile.getValue(end_time)\n day_profile.addValue(start_time,original_start_time_val)\n day_profile.addValue(end_time,original_end_time_val)\n times_vals = day_profile.times.zip(day_profile.values)\n \n #report out the original schedule\n @infos << \"After adding breaks but before setback:\"\n day_profile.times.zip(day_profile.values).each do |time,val|\n @infos << \"#{time} = #{val}\"\n end\n \n #apply the setback\n times_vals.each do |time,val|\n if crosses_midnight == false\n if time > start_time and time <= end_time\n day_profile.addValue(time, val + setback_c)\n end\n elsif crosses_midnight == true\n if time <= end_time or time > start_time\n day_profile.addValue(time, val + setback_c)\n end\n end\n end #next time val pair in the schedule\n \n #report out the changed schedule\n @infos << \"After setback:\"\n day_profile.times.zip(day_profile.values).each do |time,val|\n @infos << \"#{time} = #{val}\"\n end\n \n end #next day profile\n \n return sch\n \n end #end reduce schedule method \n \n #log to make sure we don't setback to same schedule twice\n prev_setback_schs = []\n \n #get all the thermostats in the building\n model.getThermalZones.each do |zone|\n thermostat = zone.thermostatSetpointDualSetpoint\n if thermostat.is_initialized\n thermostat = thermostat.get\n htg_sch = thermostat.heatingSetpointTemperatureSchedule\n clg_sch = thermostat.coolingSetpointTemperatureSchedule\n \n #convert the setbacks to C (actually a delta C is a K\n #also, heating setback = lower heating setpoint, so make sign negative\n htg_setback_c = -1.0 * OpenStudio::convert(htg_setback_f,\"R\",\"K\").get\n clg_setback_c = OpenStudio::convert(clg_setback_f,\"R\",\"K\").get\n \n #add a heating setback\n if htg_sch.is_initialized\n htg_sch = htg_sch.get\n #skip already setback schedules\n if prev_setback_schs.include?(htg_sch)\n runner.registerInfo(\"The #{zone.name} htg sch: #{htg_sch.name} has already had setback applied.\")\n else\n prev_setback_schs << reduce_schedule(htg_sch, start_hr, start_min, end_hr, end_min, htg_setback_c)\n runner.registerInfo(\"Applied setback to #{zone.name} htg sch: #{htg_sch.name}\")\n end\n end\n \n #add a cooling setback\n if clg_sch.is_initialized\n clg_sch = clg_sch.get\n #skip already setback schedules\n if prev_setback_schs.include?(clg_sch)\n runner.registerInfo(\"The #{zone.name} clg sch: #{clg_sch.name} has already had setback applied.\")\n else\n prev_setback_schs << reduce_schedule(clg_sch, start_hr, start_min, end_hr, end_min, clg_setback_c)\n runner.registerInfo(\"Applied setback to #{zone.name} clg sch: #{clg_sch.name}\")\n end\n end\n\n end #if thermostat\n \n end #next zone\n\n #log all the messages from applying the messages\n @infos.each do |msg|\n runner.registerInfo(\"#{msg}\")\n end\n \n=begin \n #add lifeCycleCost objects if there is a non-zero value in one of the cost arguments\n building = model.getBuilding\n if costs_requested == true\n quantity = lights_def.quantity\n #adding new cost items\n lcc_mat = OpenStudio::Model::LifeCycleCost.createLifeCycleCost(\"LCC_Mat - #{lights_def.name} night reduction\", building, material_cost * quantity, \"CostPerEach\", \"Construction\", expected_life, years_until_costs_start)\n lcc_om = OpenStudio::Model::LifeCycleCost.createLifeCycleCost(\"LCC_OM - #{lights_def.name} night reduction\", building, om_cost * quantity, \"CostPerEach\", \"Maintenance\", om_frequency, 0)\n measure_cost = material_cost * quantity\n end #end of costs_requested == true\n\n\n #reporting final condition of model\n runner.registerFinalCondition(\"#{lights_sch_names.uniq.size} schedule(s) were edited. The cost for the measure is #{neat_numbers(measure_cost,0)}.\")\n=end\n return true\n\n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n \n # Add a check box for specifying verbose info statements\n\tverbose_info_statements = OpenStudio::Ruleset::OSArgument::makeBoolArgument(\"verbose_info_statements\", false)\n\tverbose_info_statements.setDisplayName(\"Check to allow measure to generate verbose runner.registerInfo statements.\")\n\tverbose_info_statements.setDefaultValue(false)\n\targs << verbose_info_statements\n \n # Note: There does not seem to be a way to retrieve the linkage between \n # existing ZoneHVACIdealLoadsAirSystemideal objects and their \n # attached Thermal Zones (via the API). Therefore this measure will \n # ask the user which existing conditioned thermal zones to \n # convert to be served by (autosized) ZoneHVACIdealLoadsAirSystems from a choice list. \n # initially, the choice list will only be populated by Thermal zones which are \n # (1) conditioned and (2) served only by ZoneHVAC Equipment objetcs, which this \n # measure will delete. \n \n # 1) make an argument for <conditioned> thermal zone(s) served only by ZoneHVAC equipment \n # to apply ZoneHVACIdealLoadsAirSystem assignments to \n tz_handles = OpenStudio::StringVector.new\n tz_display_names = OpenStudio::StringVector.new\n\n # put all thermal zone names into a hash\n tz_hash = {}\n model.getThermalZones.each do |tz|\n tz_hash[tz.name.to_s] = tz\n end\n\n # looping through a sorted hash of zones to place 'qualified' thermal zones within\n # must be conditioned and not attached to an airloop\n tz_hash.sort.map do |tz_name, tz|\n if tz.thermostatSetpointDualSetpoint.is_initialized\n tstat = tz.thermostatSetpointDualSetpoint.get\n if tstat.heatingSetpointTemperatureSchedule.is_initialized || tstat.coolingSetpointTemperatureSchedule.is_initialized\n if tz.airLoopHVAC.empty?\n tz_handles << tz.handle.to_s\n tz_display_names << tz_name\n end\n end\n end\n end\n\n # add building to string vector with zones\n building = model.getBuilding\n tz_handles << building.handle.to_s\n tz_display_names << '*All Cond. Zones not served by Air Loops*' \n \n zones = OpenStudio::Measure::OSArgument.makeChoiceArgument('zones', tz_handles, tz_display_names, true)\n zones.setDisplayName('Choose Conditioned Thermal Zone(s) to apply Ideal HVAC system changes to.')\n zones.setDefaultValue('*All Cond. Zones not served by Air Loops*') # if no zone is chosen this will run on all zones\n args << zones\n \n # Make a double precision argument for the Supply Mass Flow rate for Heating \n heating_mdot_per_ft2 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"heating_mdot_per_ft2\",true)\n heating_mdot_per_ft2.setDisplayName(\"Htg Supply Airflow\")\n heating_mdot_per_ft2.setDescription(\"Airflow of Zone Ideal HVAC system when in heating mode in cfm/ft^2.\")\n heating_mdot_per_ft2.setDefaultValue(1.0)\n heating_mdot_per_ft2.setMinValue(0.0)\n heating_mdot_per_ft2.setMaxValue(3.0)\n args << heating_mdot_per_ft2\n \n # Make a double precision argument for the Supply Mass Flow rate for Cooling\n cooling_mdot_per_ft2 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"cooling_mdot_per_ft2\",true)\n cooling_mdot_per_ft2.setDisplayName(\"Clg Supply Airflow\")\n cooling_mdot_per_ft2.setDescription(\"Airflow of Zone Ideal HVAC system when in cooling mode in cfm/ft^2.\")\n cooling_mdot_per_ft2.setDefaultValue(1.2)\n cooling_mdot_per_ft2.setMinValue(0.0)\n cooling_mdot_per_ft2.setMaxValue(3.0)\n args << cooling_mdot_per_ft2\n\n # Make a double precision argument for the Supply Air Dry Bulb Temperature for Heating \n heating_LAT = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"heating_LAT\",true)\n heating_LAT.setDisplayName(\"Htg LAT\")\n heating_LAT.setDescription(\"Supply Air Temp of Zone Ideal HVAC system when in heating mode, Deg F.\")\n heating_LAT.setDefaultValue(105)\n heating_LAT.setMinValue(90)\n heating_LAT.setMaxValue(120)\n args << heating_LAT\n\n # Make a double precision argument for the Supply Air Dry Bulb Temperature for Cooling\n cooling_LAT = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"cooling_LAT\",true)\n cooling_LAT.setDisplayName(\"Clg LAT\")\n cooling_LAT.setDescription(\"Supply Air Temp of Zone Ideal HVAC system when in cooling mode, Deg F.\")\n cooling_LAT.setDefaultValue(55)\n cooling_LAT.setMinValue(42)\n cooling_LAT.setMaxValue(65)\n args << cooling_LAT\n \n # Make a double precision argument for the Supply Air Humidity Ratio for Heating \n heating_HumRat = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"heating_HumRat\",true)\n heating_HumRat.setDisplayName(\"Htg HumRat\")\n heating_HumRat.setDescription(\"Supply Air Humidity Ratio of Zone Ideal HVAC system when in heating mode, (lb H2O/lb dry air).\")\n heating_HumRat.setDefaultValue(0.015)\n heating_HumRat.setMinValue(0.006)\n heating_HumRat.setMaxValue(0.017)\n args << heating_HumRat\n \n # Make a double precision argument for the Supply Air Humidity Ratio for Cooling\n cooling_HumRat = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"cooling_HumRat\",true)\n cooling_HumRat.setDisplayName(\"Clg HumRat\")\n cooling_HumRat.setDescription(\"Supply Air Humidity Ratio of Zone Ideal HVAC system when in cooling mode, (lb H2O/lb dry air).\")\n cooling_HumRat.setDefaultValue(0.009)\n cooling_HumRat.setMinValue(0.006)\n cooling_HumRat.setMaxValue(0.017)\n args << cooling_HumRat\n\n # make a choice argument for setting EMS InternalVariableAvailabilityDictionaryReporting value\n int_var_avail_dict_rep_chs = OpenStudio::StringVector.new\n int_var_avail_dict_rep_chs << 'None'\n int_var_avail_dict_rep_chs << 'NotByUniqueKeyNames'\n int_var_avail_dict_rep_chs << 'Verbose'\n \n internal_variable_availability_dictionary_reporting = OpenStudio::Measure::OSArgument.makeChoiceArgument('internal_variable_availability_dictionary_reporting', int_var_avail_dict_rep_chs, true)\n internal_variable_availability_dictionary_reporting.setDisplayName('Level of output reporting related to the EMS internal variables that are available.')\n internal_variable_availability_dictionary_reporting.setDefaultValue('None')\n args << internal_variable_availability_dictionary_reporting\n \n # make a choice argument for setting EMSRuntimeLanguageDebugOutputLevel value\n ems_runtime_language_debug_level_chs = OpenStudio::StringVector.new\n ems_runtime_language_debug_level_chs << 'None'\n ems_runtime_language_debug_level_chs << 'ErrorsOnly'\n ems_runtime_language_debug_level_chs << 'Verbose'\n \n ems_runtime_language_debug_output_level = OpenStudio::Measure::OSArgument.makeChoiceArgument('ems_runtime_language_debug_output_level', ems_runtime_language_debug_level_chs, true)\n ems_runtime_language_debug_output_level.setDisplayName('Level of output reporting related to the execution of EnergyPlus Runtime Language, written to .edd file.')\n ems_runtime_language_debug_output_level.setDefaultValue('None')\n args << ems_runtime_language_debug_output_level\n \n # make a choice argument for setting EMS ActuatorAvailabilityDictionaryReportingvalue\n actuator_avail_dict_rep_chs = OpenStudio::StringVector.new\n actuator_avail_dict_rep_chs << 'None'\n actuator_avail_dict_rep_chs << 'NotByUniqueKeyNames'\n actuator_avail_dict_rep_chs << 'Verbose'\n \n actuator_availability_dictionary_reporting = OpenStudio::Measure::OSArgument.makeChoiceArgument('actuator_availability_dictionary_reporting', actuator_avail_dict_rep_chs, true)\n actuator_availability_dictionary_reporting.setDisplayName('Level of output reporting related to the EMS actuators that are available.')\n actuator_availability_dictionary_reporting.setDefaultValue('None')\n args << actuator_availability_dictionary_reporting\n \n return args\n end", "def finalize\n super\n\n @short = Config.get_if_unset(@short, nil)\n @type = Config.get_if_unset(@type, ANY_ARGUMENT_TYPE)\n @operator = Util.ensure_instance(\n Config.get_if_unset(@operator, Cliqr::Command::ArgumentOperator.for_type(@type))\n )\n @default = Config.get_if_unset(@default, ARGUMENT_DEFAULTS[@type])\n @multi_valued = Config.get_if_unset(@multi_valued, false)\n\n self\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n \n #use the built-in error checking \n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\t\n\tfuel_type_array = ['NaturalGas','Electricity','PropaneGas','FuelOil#1','FuelOil#2',\\\n\t\t'Coal','Diesel','Gasoline','OtherFuel1','OtherFuel2','Steam','DistrictHeating']\n\t\n\thandle = runner.getStringArgumentValue(\"heater_fuel_type_widget\",user_arguments)\n\theater_fuel_type = handle.to_i\n\theater_fuel = fuel_type_array[heater_fuel_type]\n\n\theater_thermal_efficiency = runner.getDoubleArgumentValue(\"heater_thermal_efficiency\",user_arguments)\n\t\n\tif heater_thermal_efficiency <= 0 \n\t\trunner.registerError(\"Enter a value greater than zero for the 'Heater Thermal Efficiency'.\")\n\telsif heater_thermal_efficiency > 1.0 \n\t\trunner.registerError(\"Enter a value less than or equal to 1.0 for the 'HeaterThermal Efficiency'.\")\n\tend\n\t\n\ti_water_heater = 0\n\tmodel.getWaterHeaterMixeds.each do |water_heater|\n\t\ti_water_heater = i_water_heater + 1\n\t\t\n\t\t# check if AllAirloop is selected or not.\n\t\tunit = water_heater.to_WaterHeaterMixed.get\n\t\t\t\n\t\t#get the original value for reporting\n\t\theater_thermal_efficiency_old = unit.heaterThermalEfficiency\n\t\toncycle_loss_coeff_old = unit.onCycleLossCoefficienttoAmbientTemperature\n\t\toffcycle_loss_coeff_old = unit.offCycleLossCoefficienttoAmbientTemperature\n\t\tpeak_use_flow_old = unit.peakUseFlowRate\n\t\t\t\n\t\trunner.registerInfo(\"Initial: Heater Thermal Efficiency of '#{unit.name}' was #{heater_thermal_efficiency_old}.\")\n\t\trunner.registerInfo(\"Initial: On Cycle Loss Coefficient to Ambient Temperature of '#{unit.name}' was #{oncycle_loss_coeff_old}.\")\n\t\trunner.registerInfo(\"Initial: Off Cycle Loss Coefficient to Ambient Temperature'#{unit.name}' was #{offcycle_loss_coeff_old}.\")\n\t\tif peak_use_flow_old.is_a? Numeric\t\n\t\t\trunner.registerInfo(\"Initial: Peak Use Flow Rate of '#{unit.name}' was #{peak_use_flow_old}.\")\n\t\tend\n\t\t\t\t\t\n\t\t#now we have all user inputs, so set them to the new model\n\t\tunit.setHeaterFuelType(heater_fuel)\n\t\tunit.setHeaterThermalEfficiency(heater_thermal_efficiency)\n\t\t\t\n\t\trunner.registerInfo(\"Final: Heater Thermal Efficiency of '#{unit.name}' was set to be #{heater_thermal_efficiency}.\")\t\t\t\t\n\tend\n\n return true\n \n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n\n # make an argument for adjustment to cooling setpoint\n cooling_adjustment = OpenStudio::Measure::OSArgument.makeDoubleArgument('cooling_adjustment', true)\n cooling_adjustment.setDisplayName('Degrees Fahrenheit to Adjust Cooling Setpoint By')\n cooling_adjustment.setDefaultValue(1.0)\n args << cooling_adjustment\n\n # make an argument for adjustment to heating setpoint\n heating_adjustment = OpenStudio::Measure::OSArgument.makeDoubleArgument('heating_adjustment', true)\n heating_adjustment.setDisplayName('Degrees Fahrenheit to Adjust heating Setpoint By')\n heating_adjustment.setDefaultValue(-1.0)\n args << heating_adjustment\n\n # make arguments for DR start time\n start_hour = OpenStudio::Measure::OSArgument.makeIntegerArgument('start_hour', true)\n start_hour.setDisplayName('start_hour')\n start_hour.setDefaultValue(15)\n args << start_hour\n\n start_minute = OpenStudio::Measure::OSArgument.makeIntegerArgument('start_minute', true)\n start_minute.setDisplayName('start_minute')\n start_minute.setDefaultValue(0)\n args << start_minute\n\n # make arguments for DR end time\n end_hour = OpenStudio::Measure::OSArgument.makeIntegerArgument('end_hour', true)\n end_hour.setDisplayName('end_hour')\n end_hour.setDefaultValue(18)\n args << end_hour\n\n end_minute = OpenStudio::Measure::OSArgument.makeIntegerArgument('end_minute', true)\n end_minute.setDisplayName('end_minute')\n end_minute.setDefaultValue(0)\n args << end_minute\n\n # make an argument for adjustment to heating setpoint\n alter_design_days = OpenStudio::Measure::OSArgument.makeBoolArgument('alter_design_days', true)\n alter_design_days.setDisplayName('Alter Design Day Thermostats')\n alter_design_days.setDefaultValue(false)\n args << alter_design_days\n\n return args\n end", "def run(model, runner, user_arguments)\n super(model, runner, user_arguments)\n \n #use the built-in error checking \n if not runner.validateUserArguments(arguments(model), user_arguments)\n return false\n end\n\t \n acCoolingInstalledSEER = runner.getDoubleArgumentValue(\"acCoolingInstalledSEER\",user_arguments)\n acNumberSpeeds = runner.getDoubleArgumentValue(\"acNumberSpeeds\",user_arguments)\n acCoolingEER = runner.getStringArgumentValue(\"acCoolingEER\",user_arguments).split(\",\").map {|i| i.to_f}\n acSHRRated = runner.getStringArgumentValue(\"acSHRRated\",user_arguments).split(\",\").map {|i| i.to_f}\n acCapacityRatio = runner.getStringArgumentValue(\"acCapacityRatio\",user_arguments).split(\",\").map {|i| i.to_f}\n acRatedAirFlowRate = runner.getDoubleArgumentValue(\"acRatedAirFlowRate\",user_arguments)\n acFanspeedRatio = runner.getStringArgumentValue(\"acFanspeedRatio\",user_arguments).split(\",\").map {|i| i.to_f}\n acSupplyFanPowerRated = runner.getDoubleArgumentValue(\"acSupplyFanPowerRated\",user_arguments)\n acSupplyFanPowerInstalled = runner.getDoubleArgumentValue(\"acSupplyFanPowerInstalled\",user_arguments)\n acCondenserType = runner.getStringArgumentValue(\"acCondenserType\",user_arguments)\n acCrankcase = runner.getDoubleArgumentValue(\"acCrankcase\",user_arguments)\n acCrankcaseMaxT = runner.getDoubleArgumentValue(\"acCrankcaseMaxT\",user_arguments)\n acEERCapacityDerateFactor1ton = runner.getDoubleArgumentValue(\"acEERCapacityDerateFactor1ton\",user_arguments)\n acEERCapacityDerateFactor2ton = runner.getDoubleArgumentValue(\"acEERCapacityDerateFactor2ton\",user_arguments)\n acEERCapacityDerateFactor3ton = runner.getDoubleArgumentValue(\"acEERCapacityDerateFactor3ton\",user_arguments)\n acEERCapacityDerateFactor4ton = runner.getDoubleArgumentValue(\"acEERCapacityDerateFactor4ton\",user_arguments)\n acEERCapacityDerateFactor5ton = runner.getDoubleArgumentValue(\"acEERCapacityDerateFactor5ton\",user_arguments)\n acEERCapacityDerateFactor = [acEERCapacityDerateFactor1ton, acEERCapacityDerateFactor2ton, acEERCapacityDerateFactor3ton, acEERCapacityDerateFactor4ton, acEERCapacityDerateFactor5ton]\n acOutputCapacity = runner.getStringArgumentValue(\"acCoolingOutputCapacity\",user_arguments)\n unless acOutputCapacity == Constants.SizingAuto\n acOutputCapacity = OpenStudio::convert(acOutputCapacity.split(\" \")[0].to_f,\"ton\",\"Btu/h\").get\n end\n\n # error checking\n unless [1, 2, 4].include? acNumberSpeeds\n runner.registerError(\"Invalid number of compressor speeds entered.\")\n return false\n end\n unless ( acNumberSpeeds == acCoolingEER.length and acNumberSpeeds == acSHRRated.length and acNumberSpeeds == acCapacityRatio.length and acNumberSpeeds == acFanspeedRatio.length )\n runner.registerError(\"Entered wrong length for EER, Rated SHR, Capacity Ratio, or Fan Speed Ratio given the Number of Speeds.\")\n return false\n end \n \n # Create the material class instances\n air_conditioner = AirConditioner.new(acCoolingInstalledSEER, acNumberSpeeds, acRatedAirFlowRate, acFanspeedRatio, acCapacityRatio, acCoolingEER, acSupplyFanPowerInstalled, acSupplyFanPowerRated, acSHRRated, acCondenserType, acCrankcase, acCrankcaseMaxT, acEERCapacityDerateFactor)\n supply = Supply.new\n\n # _processAirSystem\n \n if air_conditioner.ACCoolingInstalledSEER == 999\n air_conditioner.hasIdealAC = true\n else\n air_conditioner.hasIdealAC = false\n end\n\n supply.static = UnitConversion.inH2O2Pa(0.5) # Pascal\n\n # Flow rate through AC units - hardcoded assumption of 400 cfm/ton\n supply.cfm_ton = 400 # cfm / ton\n\n supply.HPCoolingOversizingFactor = 1 # Default to a value of 1 (currently only used for MSHPs)\n supply.SpaceConditionedMult = 1 # Default used for central equipment \n \n # Cooling Coil\n if air_conditioner.hasIdealAC\n supply = HVAC.get_cooling_coefficients(runner, air_conditioner.ACNumberSpeeds, true, false, supply)\n else\n supply = HVAC.get_cooling_coefficients(runner, air_conditioner.ACNumberSpeeds, false, false, supply)\n end\n supply.CFM_TON_Rated = HVAC.calc_cfm_ton_rated(air_conditioner.ACRatedAirFlowRate, air_conditioner.ACFanspeedRatio, air_conditioner.ACCapacityRatio)\n supply = HVAC._processAirSystemCoolingCoil(runner, air_conditioner.ACNumberSpeeds, air_conditioner.ACCoolingEER, air_conditioner.ACCoolingInstalledSEER, air_conditioner.ACSupplyFanPowerInstalled, air_conditioner.ACSupplyFanPowerRated, air_conditioner.ACSHRRated, air_conditioner.ACCapacityRatio, air_conditioner.ACFanspeedRatio, air_conditioner.ACCondenserType, air_conditioner.ACCrankcase, air_conditioner.ACCrankcaseMaxT, air_conditioner.ACEERCapacityDerateFactor, air_conditioner, supply, false)\n \n # Determine if the compressor is multi-speed (in our case 2 speed).\n # If the minimum flow ratio is less than 1, then the fan and\n # compressors can operate at lower speeds.\n if supply.min_flow_ratio == 1.0\n supply.compressor_speeds = 1.0\n else\n supply.compressor_speeds = supply.Number_Speeds\n end\n \n num_units = Geometry.get_num_units(model, runner)\n if num_units.nil?\n return false\n end \n \n (0...num_units).to_a.each do |unit_num|\n _nbeds, _nbaths, unit_spaces = Geometry.get_unit_beds_baths_spaces(model, unit_num + 1, runner)\n thermal_zones = Geometry.get_thermal_zones_from_unit_spaces(unit_spaces)\n if thermal_zones.length > 1\n runner.registerInfo(\"Unit #{unit_num + 1} spans more than one thermal zone.\")\n end\n control_slave_zones_hash = Geometry.get_control_and_slave_zones(thermal_zones)\n control_slave_zones_hash.each do |control_zone, slave_zones|\n \n # Remove existing equipment\n htg_coil = HelperMethods.remove_existing_hvac_equipment(model, runner, \"Central Air Conditioner\", control_zone)\n \n # _processCurvesDXCooling\n \n clg_coil_stage_data = HVAC._processCurvesDXCooling(model, supply, acOutputCapacity)\n\n # _processSystemCoolingCoil\n \n if supply.compressor_speeds == 1.0\n\n clg_coil = OpenStudio::Model::CoilCoolingDXSingleSpeed.new(model, model.alwaysOnDiscreteSchedule, clg_coil_stage_data[0].totalCoolingCapacityFunctionofTemperatureCurve, clg_coil_stage_data[0].totalCoolingCapacityFunctionofFlowFractionCurve, clg_coil_stage_data[0].energyInputRatioFunctionofTemperatureCurve, clg_coil_stage_data[0].energyInputRatioFunctionofFlowFractionCurve, clg_coil_stage_data[0].partLoadFractionCorrelationCurve)\n clg_coil.setName(\"DX Cooling Coil\")\n if acOutputCapacity != Constants.SizingAuto\n clg_coil.setRatedTotalCoolingCapacity(OpenStudio::convert(acOutputCapacity,\"Btu/h\",\"W\").get)\n end\n if air_conditioner.hasIdealAC\n if acOutputCapacity != Constants.SizingAuto\n clg_coil.setRatedSensibleHeatRatio(0.8)\n clg_coil.setRatedAirFlowRate(supply.CFM_TON_Rated[0] * acOutputCapacity * OpenStudio::convert(1.0,\"Btu/h\",\"ton\").get * OpenStudio::convert(1.0,\"cfm\",\"m^3/s\").get)\n end\n clg_coil.setRatedCOP(OpenStudio::OptionalDouble.new(1.0))\n else\n if acOutputCapacity != Constants.SizingAuto\n clg_coil.setRatedSensibleHeatRatio(supply.SHR_Rated[0])\n clg_coil.setRatedAirFlowRate(supply.CFM_TON_Rated[0] * acOutputCapacity * OpenStudio::convert(1.0,\"Btu/h\",\"ton\").get * OpenStudio::convert(1.0,\"cfm\",\"m^3/s\").get)\n end\n clg_coil.setRatedCOP(OpenStudio::OptionalDouble.new(1.0 / supply.CoolingEIR[0]))\n end\n clg_coil.setRatedEvaporatorFanPowerPerVolumeFlowRate(OpenStudio::OptionalDouble.new(supply.fan_power_rated / OpenStudio::convert(1.0,\"cfm\",\"m^3/s\").get))\n\n if air_conditioner.hasIdealAC\n clg_coil.setNominalTimeForCondensateRemovalToBegin(OpenStudio::OptionalDouble.new(0))\n clg_coil.setRatioOfInitialMoistureEvaporationRateAndSteadyStateLatentCapacity(OpenStudio::OptionalDouble.new(0))\n clg_coil.setMaximumCyclingRate(OpenStudio::OptionalDouble.new(0))\n clg_coil.setLatentCapacityTimeConstant(OpenStudio::OptionalDouble.new(0))\n else\n clg_coil.setNominalTimeForCondensateRemovalToBegin(OpenStudio::OptionalDouble.new(1000.0))\n clg_coil.setRatioOfInitialMoistureEvaporationRateAndSteadyStateLatentCapacity(OpenStudio::OptionalDouble.new(1.5))\n clg_coil.setMaximumCyclingRate(OpenStudio::OptionalDouble.new(3.0))\n clg_coil.setLatentCapacityTimeConstant(OpenStudio::OptionalDouble.new(45.0))\n end\n\n if supply.CondenserType == Constants.CondenserTypeAir\n clg_coil.setCondenserType(\"AirCooled\")\n else\n clg_coil.setCondenserType(\"EvaporativelyCooled\")\n clg_coil.setEvaporativeCondenserEffectiveness(OpenStudio::OptionalDouble.new(1))\n clg_coil.setEvaporativeCondenserAirFlowRate(OpenStudio::OptionalDouble.new(OpenStudio::convert(850.0,\"cfm\",\"m^3/s\").get * acOutputCapacity))\n clg_coil.setEvaporativeCondenserPumpRatedPowerConsumption(OpenStudio::OptionalDouble.new(0))\n end\n\n clg_coil.setCrankcaseHeaterCapacity(OpenStudio::OptionalDouble.new(OpenStudio::convert(supply.Crankcase,\"kW\",\"W\").get))\n clg_coil.setMaximumOutdoorDryBulbTemperatureForCrankcaseHeaterOperation(OpenStudio::OptionalDouble.new(OpenStudio::convert(supply.Crankcase_MaxT,\"F\",\"C\").get))\n\n else\n\n clg_coil = OpenStudio::Model::CoilCoolingDXMultiSpeed.new(model)\n clg_coil.setName(\"DX Cooling Coil\")\n clg_coil.setCondenserType(supply.CondenserType)\n clg_coil.setApplyPartLoadFractiontoSpeedsGreaterthan1(false)\n clg_coil.setApplyLatentDegradationtoSpeedsGreaterthan1(false)\n clg_coil.setCrankcaseHeaterCapacity(OpenStudio::convert(supply.Crankcase,\"kW\",\"W\").get)\n clg_coil.setMaximumOutdoorDryBulbTemperatureforCrankcaseHeaterOperation(OpenStudio::convert(supply.Crankcase_MaxT,\"F\",\"C\").get)\n \n clg_coil.setFuelType(\"Electricity\")\n \n clg_coil_stage_data.each do |i|\n clg_coil.addStage(i)\n end \n\n end\n \n # _processSystemFan\n \n supply_fan_availability = OpenStudio::Model::ScheduleConstant.new(model)\n supply_fan_availability.setName(\"SupplyFanAvailability\")\n supply_fan_availability.setValue(1)\n\n fan = OpenStudio::Model::FanOnOff.new(model, supply_fan_availability)\n fan.setName(\"Supply Fan\")\n fan.setEndUseSubcategory(\"HVACFan\")\n fan.setFanEfficiency(supply.eff)\n fan.setPressureRise(supply.static)\n fan.setMotorEfficiency(1)\n fan.setMotorInAirstreamFraction(1)\n\n supply_fan_operation = OpenStudio::Model::ScheduleConstant.new(model)\n supply_fan_operation.setName(\"SupplyFanOperation\")\n supply_fan_operation.setValue(0) \n \n # _processSystemAir\n \n air_loop_unitary = OpenStudio::Model::AirLoopHVACUnitarySystem.new(model)\n air_loop_unitary.setName(\"Forced Air System\")\n air_loop_unitary.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)\n air_loop_unitary.setCoolingCoil(clg_coil) \n if not htg_coil.nil?\n # Add the existing furnace back in\n air_loop_unitary.setHeatingCoil(htg_coil)\n else\n air_loop_unitary.setSupplyAirFlowRateDuringHeatingOperation(0.0000001) # this is when there is no heating present\n end\n air_loop_unitary.setSupplyFan(fan)\n air_loop_unitary.setFanPlacement(\"BlowThrough\")\n air_loop_unitary.setSupplyAirFanOperatingModeSchedule(supply_fan_operation)\n air_loop_unitary.setMaximumSupplyAirTemperature(OpenStudio::convert(120.0,\"F\",\"C\").get)\n air_loop_unitary.setSupplyAirFlowRateWhenNoCoolingorHeatingisRequired(0) \n \n air_loop = OpenStudio::Model::AirLoopHVAC.new(model)\n air_loop.setName(\"Central Air System\")\n air_supply_inlet_node = air_loop.supplyInletNode\n air_supply_outlet_node = air_loop.supplyOutletNode\n air_demand_inlet_node = air_loop.demandInletNode\n air_demand_outlet_node = air_loop.demandOutletNode \n \n air_loop_unitary.addToNode(air_supply_inlet_node)\n \n runner.registerInfo(\"Added on/off fan '#{fan.name}' to branch '#{air_loop_unitary.name}' of air loop '#{air_loop.name}'\")\n runner.registerInfo(\"Added DX cooling coil '#{clg_coil.name}' to branch '#{air_loop_unitary.name}' of air loop '#{air_loop.name}'\")\n unless htg_coil.nil?\n runner.registerInfo(\"Added heating coil '#{htg_coil.name}' to branch '#{air_loop_unitary.name}' of air loop '#{air_loop.name}'\")\n end\n \n air_loop_unitary.setControllingZoneorThermostatLocation(control_zone)\n \n # _processSystemDemandSideAir\n # Demand Side\n\n # Supply Air\n zone_splitter = air_loop.zoneSplitter\n zone_splitter.setName(\"Zone Splitter\")\n\n diffuser_living = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)\n diffuser_living.setName(\"Living Zone Direct Air\")\n # diffuser_living.setMaximumAirFlowRate(OpenStudio::convert(supply.Living_AirFlowRate,\"cfm\",\"m^3/s\").get)\n air_loop.addBranchForZone(control_zone, diffuser_living.to_StraightComponent)\n\n air_loop.addBranchForZone(control_zone)\n runner.registerInfo(\"Added air loop '#{air_loop.name}' to thermal zone '#{control_zone.name}' of unit #{unit_num + 1}\")\n\n slave_zones.each do |slave_zone|\n\n diffuser_fbsmt = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)\n diffuser_fbsmt.setName(\"FBsmt Zone Direct Air\")\n # diffuser_fbsmt.setMaximumAirFlowRate(OpenStudio::convert(supply.Living_AirFlowRate,\"cfm\",\"m^3/s\").get)\n air_loop.addBranchForZone(slave_zone, diffuser_fbsmt.to_StraightComponent)\n\n air_loop.addBranchForZone(slave_zone)\n runner.registerInfo(\"Added air loop '#{air_loop.name}' to thermal zone '#{slave_zone.name}' of unit #{unit_num + 1}\")\n\n end \n \n end\n \n end\n\t\n return true\n \n end", "def arguments(model)\n args = OpenStudio::Measure::OSArgumentVector.new\n \n #make a double argument for thickness of the cmu block\n thickness = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"thickness\", true)\n thickness.setDisplayName(\"CMU Block Thickness\")\n thickness.setUnits(\"in\")\n thickness.setDescription(\"Thickness of the CMU portion of the wall.\")\n thickness.setDefaultValue(6.0)\n args << thickness\n \n #make a double argument for conductivity of the cmu block\n conductivity = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"conductivity\", true)\n conductivity.setDisplayName(\"CMU Conductivity\")\n conductivity.setUnits(\"Btu-in/hr-ft^2-R\")\n conductivity.setDescription(\"Overall conductivity of the finished CMU block.\")\n conductivity.setDefaultValue(5.33)\n args << conductivity \n \n #make a double argument for density of the cmu block\n density = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"density\", true)\n density.setDisplayName(\"CMU Density\")\n density.setUnits(\"lb/ft^3\")\n density.setDescription(\"The density of the finished CMU block.\")\n density.setDefaultValue(119.0)\n args << density \n \n #make a double argument for framing factor\n framing_factor = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"framing_factor\", true)\n framing_factor.setDisplayName(\"Framing Factor\")\n framing_factor.setUnits(\"frac\")\n framing_factor.setDescription(\"Total fraction of the wall that is framing for windows or doors.\")\n framing_factor.setDefaultValue(0.076)\n args << framing_factor\n \n #make a double argument for furring insulation R-value\n furring_r = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"furring_r\", true)\n furring_r.setDisplayName(\"Furring Insulation R-value\")\n furring_r.setUnits(\"hr-ft^2-R/Btu\")\n furring_r.setDescription(\"R-value of the insulation filling the furring cavity. Enter zero for no furring strips.\")\n furring_r.setDefaultValue(0.0)\n args << furring_r\n \n #make a double argument for furring cavity depth\n furring_cavity_depth = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"furring_cavity_depth\", true)\n furring_cavity_depth.setDisplayName(\"Furring Cavity Depth\")\n furring_cavity_depth.setUnits(\"in\")\n furring_cavity_depth.setDescription(\"The depth of the interior furring cavity. Enter zero for no furring strips.\")\n furring_cavity_depth.setDefaultValue(1.0)\n args << furring_cavity_depth \n \n #make a double argument for furring stud spacing\n furring_spacing = OpenStudio::Measure::OSArgument::makeDoubleArgument(\"furring_spacing\", true)\n furring_spacing.setDisplayName(\"Furring Stud Spacing\")\n furring_spacing.setUnits(\"in\")\n furring_spacing.setDescription(\"Spacing of studs in the furring. Enter zero for no furring strips.\")\n furring_spacing.setDefaultValue(24.0)\n args << furring_spacing \n \n return args\n end" ]
[ "0.7510201", "0.6948276", "0.69206923", "0.62894714", "0.62894714", "0.6225757", "0.6225757", "0.6225757", "0.6146954", "0.61146826", "0.6114524", "0.6041721", "0.5980296", "0.5975661", "0.59709084", "0.5965006", "0.5961643", "0.59559", "0.59477925", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.5908425", "0.58986664", "0.58985174", "0.5882732", "0.5864818", "0.5863785", "0.5831729", "0.5820031", "0.58175105", "0.58094317", "0.57942665", "0.5789224", "0.57787794", "0.5775385", "0.5775385", "0.5775385", "0.5752542", "0.5752542", "0.5750403", "0.5747432", "0.5722471", "0.5719637", "0.57102484", "0.570993", "0.5707515", "0.570369", "0.56924325", "0.5682169", "0.56664926", "0.5663144", "0.56559116", "0.5652274", "0.56520724", "0.5649097", "0.5645977", "0.56459194", "0.56310606", "0.5631058", "0.5624145", "0.56184506", "0.5611985", "0.5608362", "0.5595674", "0.55944383", "0.55879116", "0.5586779", "0.55850816", "0.55721945", "0.55665904", "0.5566056", "0.5563077", "0.55508393", "0.5548171", "0.5547922", "0.5532491", "0.55293345", "0.5528049", "0.55267286", "0.5524", "0.5523323", "0.5522255", "0.55174", "0.5516991" ]
0.0
-1
:callseq: scale_bilinear(width, height) Scales the image using the bilinear interpolation method. Bilinear interpolation calculates the color values in the resulting image by looking at the four nearest pixels for each pixel in the resulting image. This gives a more accurate representation than nearestneighbor interpolation, at the expense of slightly blurring the resulting image. == Example i = Axon::JPEG('test.jpg') i.scale_bilinear(50, 75) i.width => 50 i.height => 75
def scale_bilinear(*args) @source = BilinearScaler.new(@source, *args) self end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def scale(width: @image.width, height: @image.height,\n algorithm: 'bilineal') # bilinear, nearest_neighbor\n if algorithm == 'nearest_neighbor'\n Image.new(@image.resample_nearest_neighbor(width, height), path)\n else\n Image.new(@image.resample_bilinear(width, height), path)\n end\n end", "def scale(w, h, method = :bilinear)\n @image.send(\"resample_#{method}!\", w, h)\n self\n end", "def scaleimage **opts\n Vips::Image.scale self, **opts\n end", "def resample!(image, width, height)\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resample \"#{width}x#{height}\"\n end\n end\n end", "def resize(width,height)\n\t\t@buffer=@buffer.scale(width, height, :bilinear)\n\tend", "def resize(image, height:, width:)\n n_channels = image.shape[2]\n\n if n_channels.nil?\n bilinear_resize(image, height, width)\n else\n resized = image.class.zeros(height, width, n_channels)\n n_channels.times { |c| resized[true, true, c] = bilinear_resize(image[true, true, c], height, width) }\n resized\n end\n end", "def scale_to_fit(width, height)\n @image = @image.scale_to_fit(width, height)\n self\n end", "def resize_to_fit!(image, width, height)\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resize \"#{width}x#{height}\"\n end\n end\n end", "def scale\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.scale(1.5)\n img.write('public' + @photo.attachment_url)\n end", "def scale_nearest(*args)\n @source = NearestNeighborScaler.new(@source, *args)\n self\n end", "def scale(factor=0.75, quality: nil)\n \n read() do |img|\n \n img2 = img.scale(factor) \n write img2, quality\n \n end\n \n end", "def resize_to_limit!(image, width, height)\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resize \"#{width}x#{height}>\"\n end\n end\n end", "def resize_and_optimize(width, height)\n manipulate! do |img|\n img.format(\"jpg\") do |c|\n c.quality \"70\"\n c.resize \"#{width}x#{height}\"\n end\n\n img\n end\n end", "def get_scaled_size(image, width_bound, height_bound)\n width_multiplier = 1.0 * width_bound / image.columns\n height_multiplier = 1.0 * height_bound / image.rows\n\n if image.rows * width_multiplier <= height_bound\n width_multiplier\n else\n height_multiplier\n end\n end", "def scale_by(width_factor, height_factor, &block)\n squish(width*width_factor, height*height_factor, &block)\n end", "def scale_by_pixels(dimensions)\n out_pixels = sqrt(options[:width] * options[:height]).truncate\n src_pixels = sqrt(dimensions[0] * dimensions[1]).truncate\n out_pixels / src_pixels.to_f\n end", "def resize_to_fit width, height\n manipulate! do |image|\n cols = image.width\n rows = image.height\n\n if width != cols or height != rows\n scale = [width/cols.to_f, height/rows.to_f].min\n cols = (scale * (cols + 0.5)).round\n rows = (scale * (rows + 0.5)).round\n image.resize cols, rows do |img|\n yield(img) if block_given?\n img.save current_path\n end\n end\n end\n end", "def resample inimage, dpi, outimage=nil\n m_begin \"resample\"\n img = get_image(inimage)\n old_dpi = (image_dpi inimage)[0]\n if old_dpi != dpi then\n if false\n out = img.resample(dpi)\n elsif \n old_dpi = (image_dpi inimage)[0]\n ratio = dpi / old_dpi\n out = img.sample(ratio)\n out.density = \"#{dpi}x#{dpi}\"\n end\n else\n out = img\n end\n outimage = inimage if outimage.nil?\n put_image(outimage, out)\n m_end \"resample\"\n end", "def scale_to_fit(new_width, new_height, &block)\n squish(*scale_dimensions_to_fit(new_width, new_height), &block)\n end", "def resize!(w, h, resample = true)\n ptr = self.class.create_image_ptr(w, h, false)\n ::GD2::GD2FFI.send(resample ? :gdImageCopyResampled : :gdImageCopyResized,\n ptr, image_ptr, 0, 0, 0, 0, w.to_i, h.to_i, width.to_i, height.to_i)\n alpha_blending = alpha_blending?\n init_with_image(ptr)\n self.alpha_blending = alpha_blending\n self\n end", "def optimized_image(image,x,y)\n return image.variant(resize_to_fill: [x,y]).processed\n end", "def scale(x, xmin, xmax, ymin, ymax)\n xrange = xmax - xmin\n yrange = ymax - ymin\n ymin + (x - xmin) * (yrange.to_f / xrange) \n end", "def scale_image(preferred_width, preferred_height)\n # Retrieve the current height and width\n image_data = ActiveStorage::Analyzer::ImageAnalyzer.new(image).metadata\n new_width = image_data[:width]\n new_height = image_data[:height]\n\n # Adjust the width\n if new_width > preferred_width\n new_width = preferred_width\n new_height = (new_height * new_width) / image_data[:width]\n end\n\n # Adjust the height\n if new_height > preferred_height\n old_height = new_height\n new_height = preferred_height\n new_width = (new_width * new_height) / old_height\n end\n\n # Return the resized image\n image.variant(resize_to_limit: [new_width, new_height])\n end", "def scale\n scale_factor = 20 # template.png height divided by canvas height\n self.image_x *= scale_factor\n self.image_y *= scale_factor\n self.height *= scale_factor\n self.width *= scale_factor\n self.rotation *= 180 / Math::PI\n end", "def SetImageScale(scale)\n\t\t@img_scale = scale;\n\tend", "def scaled_using(source, destination)\n Scale.transform(self).using(source, destination)\n end", "def scale( scale_x, scale_y = scale_x )\n dup.scale!(scale_x, scale_y)\n end", "def tile_crop_resize(image, dpi)\n size = {\n 'x' => image.columns,\n 'y' => image.rows\n }\n\n resize = false\n\n ['x', 'y'].each do |a|\n if (@field['size' + a])\n size[a] = @field['size' + a]*dpi\n resize = true\n end\n end\n\n if (@field['tile'])\n image = tile_image(image, dpi) if @field['tile']\n elsif (resize)\n scaleX = size['x']/image.columns\n scaleY = size['y']/image.rows\n\n scale = scaleX\n scale = scaleY if scaleY > scaleX\n\n image.resize!(image.columns*scale, image.rows*scale, Magick::LanczosFilter, 0.7)\n end\n\n image.crop!(Magick::CenterGravity, size['x'], size['y']) if (@field['crop'])\n\n return image\n end", "def fit\n if self.needs_to_be_resized?\n rmagick_img.resize_to_fit!(@x, @y)\n else\n rmagick_img.resize_to_fit(@x, @y)\n end\n end", "def resize_to_limit(width, height)\n width = dimension_from width\n height = dimension_from height\n manipulate! do |img|\n geometry = Magick::Geometry.new(width, height, 0, 0, Magick::GreaterGeometry)\n new_img = img.change_geometry(geometry) do |new_width, new_height|\n img.resize(new_width, new_height)\n end\n destroy_image(img)\n new_img = yield(new_img) if block_given?\n new_img\n end\n end", "def resize_to_fill!(image, width, height, gravity: \"Center\")\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resize \"#{width}x#{height}^\"\n cmd.gravity gravity\n cmd.background \"rgba(255,255,255,0.0)\" # transparent\n cmd.extent \"#{width}x#{height}\"\n end\n end\n end", "def resize_retina_image(image_filename)\n \n image_name = File.basename(image_filename)\n \n image = Magick::Image.read(image_filename).first # Read the image\n new_image = image.scale(SCALE_BY)\n \n if new_image.write(image_filename) # Overwrite image file\n puts \"Resizing Image (#{SCALE_BY}): #{image_name}\"\n else\n puts \"Error: Couldn't resize image #{image_name}\"\n end\n \nend", "def resize_to_fit(new_width, new_height)\n manipulate! do |image|\n resize_image(image,new_width,new_height)\n end\n end", "def resize_to_fit(new_width, new_height)\n manipulate! do |image|\n resize_image(image,new_width,new_height)\n end\n end", "def resize_to_fit(width, height)\n width = dimension_from width\n height = dimension_from height\n manipulate! do |img|\n img.resize_to_fit!(width, height)\n img = yield(img) if block_given?\n img\n end\n end", "def resize_to_fit(new_width, new_height)\n width, height = FastImage.size(self.current_path)\n width_ratio = new_width.to_f / width.to_f\n height_when_width_used = height * width_ratio\n if height_when_width_used <= new_height\n new_height = height_when_width_used\n else\n height_ratio = new_height.to_f / height.to_f\n new_width = width * height_ratio\n end\n FastImage.resize(self.current_path, self.current_path, new_width, new_height)\n end", "def resize_to_fit(width, height)\n manipulate! do |img|\n img.resize \"#{width}x#{height}\"\n img = yield(img) if block_given?\n img\n end\n end", "def small(input) # Method that returns the image\n self.images[input].variant(resize: \"300x300\").processed # Resizing the image and return it\n end", "def binarize id\n m_begin \"binarize\"\n put_image(id, get_image(id).bilevel_channel(QuantumRange/2))\n# put_image(id, @var_table[id].quantize(2, GRAYColorspace, NoDitherMethod) )\n m_end \"binarize\"\n end", "def scale(value)\r\n value * @height/2 + @height/4\r\n end", "def scale(factor_x, factor_y, around_x, around_y, &rendering_code); end", "def resize_to_limit(new_width, new_height)\n manipulate! do |image|\n image = resize_image(image,new_width,new_height) if new_width < image.width || new_height < image.height\n image\n end\n end", "def resize_to_limit(new_width, new_height)\n manipulate! do |image|\n image = resize_image(image,new_width,new_height) if new_width < image.x_size || new_height < image.y_size\n image\n end\n end", "def upRes(file_path)\t\n\t\toriginal_image = Magick::Image.read(file_path) { self.density = \"300.0x300.0\" }\n\t\toriginal_image.each do |image|\n\t\t\t image = image.resample(300.0, 300.0)\n\t\t\t image.write(file_path) { self.quality = 100 }\n\t\tend\n\tend", "def scale_by_bounds(dimensions)\n x = options[:width] / dimensions[0].to_f\n y = options[:height] / dimensions[1].to_f\n x * dimensions[1] > options[:height] ? y : x\n end", "def resize_to_fit(width, height)\n manipulate! do |image|\n resize_image image, width, height\n end\n self\n end", "def scale(*args, &block); end", "def resize_to_fit(width, height)\n manipulate! do |img|\n img.manipulate!(:resize => \"#{width}x#{height}\")\n img = yield(img) if block_given?\n img\n end\n end", "def resizeImages\n # For each of the 9 images\n for counter in (1..9)\n pngName = \"./images/\" + counter.to_s() + \".png\"\n image = Magick::Image.read(pngName).first\n # Make the new image 25% larger\n thumb = image.scale(1.25)\n thumb.write(pngName)\n end\n end", "def to_image\n matrix_img = Vips::Image.new_from_array @matrix\n matrix_img.scaleimage\n end", "def resize_to_limit(width, height)\n manipulate! do |img|\n img.resize \"#{width}x#{height}>\"\n img = yield(img) if block_given?\n img\n end\n end", "def scale_within(new_size)\n target_size = SugarCube::CoreGraphics::Size(new_size)\n image_size = self.size\n\n if CGSizeEqualToSize(target_size, self.size)\n return self\n end\n\n width = image_size.width\n height = image_size.height\n\n target_width = target_size.width\n target_height = target_size.height\n\n width_factor = target_width / width\n height_factor = target_height / height\n\n if width_factor < height_factor\n scale_factor = width_factor\n else\n scale_factor = height_factor\n end\n\n if scale_factor == 1\n return self\n end\n\n scaled_size = CGSize.new(width * scale_factor, height * scale_factor)\n return scale_to(scaled_size)\n end", "def resample(pipeline, width, height)\n pipeline.resample!(\"#{width}x#{height}\")\n end", "def process_image(path)\n picture_name = File.basename(path)\n thumbnail_dir = File.join(File.dirname(path), \"thumbnails\")\n thumbnail_path = File.join(thumbnail_dir, \"#{File.basename(picture_name, File.extname(picture_name))}.jpg\")\n Dir.mkdir(thumbnail_dir) unless File.exist?(thumbnail_dir)\n\n image_optim = ImageOptim.new\n\n image = MiniMagick::Image.open(path)\n image_prop = {\n \"name\" => picture_name,\n \"thumb\" => \"thumbnails/#{picture_name}\",\n \"height\" => image.height,\n \"width\" => image.width\n }\n\n return image_prop if File.exist?(thumbnail_path)\n\n# -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB\n\n image.format \"jpeg\" unless File.extname(picture_name) == \"jpg\"\n image.combine_options do |b|\n b.resize \"#{MAX_DIMENSION}>\"\n b.sampling_factor \"4:2:0\"\n b.strip\n b.interlace \"JPEG\"\n b.colorspace \"RGB\"\n b.quality 85\n end\n image.write thumbnail_path\n\n image_optim.optimize_image!(path)\n image_optim.optimize_image!(thumbnail_path)\n\n image_prop\nend", "def scale(x, y)\n primitive 'scale ' + sprintf('%g,%g', x, y)\n end", "def resize_to_limit(width, height)\n manipulate! do |image|\n image = resize_image(image, width, height) if width < image.x_size || height < image.y_size\n image\n end\n self\n end", "def scale(factor_x, factor_y=factor_x, &rendering_code); end", "def scale(range)\n u = uninterpolate\n i = interpolate(range[0], range[1])\n\n lambda do |x|\n x = ([0.0, x, (wrong + right).to_f].sort[1]).to_f\n i.call(u.call(x))\n end\n end", "def scale_to(new_size, background:background)\n new_size = SugarCube::CoreGraphics::Size(new_size)\n\n image_size = self.size\n\n if CGSizeEqualToSize(image_size, new_size)\n return self\n end\n\n new_image = nil\n width = image_size.width\n height = image_size.height\n\n target_width = new_size.width\n target_height = new_size.height\n\n scale_factor = 0.0\n scaled_width = target_width\n scaled_height = target_height\n\n thumbnail_point = CGPoint.new(0.0, 0.0)\n width_factor = target_width / width\n height_factor = target_height / height\n\n if width_factor < height_factor\n scale_factor = width_factor\n else\n scale_factor = height_factor\n end\n\n scaled_width = width * scale_factor\n scaled_height = height * scale_factor\n\n # center the image\n\n if width_factor < height_factor\n thumbnail_point.y = (target_height - scaled_height) * 0.5\n elsif width_factor > height_factor\n thumbnail_point.x = (target_width - scaled_width) * 0.5\n end\n\n # this is actually the interesting part:\n\n UIGraphicsBeginImageContextWithOptions(new_size, false, self.scale)\n\n if background\n background = background.uicolor\n context = UIGraphicsGetCurrentContext()\n background.setFill\n CGContextAddRect(context, [[0, 0], new_size])\n CGContextDrawPath(context, KCGPathFill)\n end\n\n thumbnail_rect = CGRectZero\n thumbnail_rect.origin = thumbnail_point\n thumbnail_rect.size.width = scaled_width\n thumbnail_rect.size.height = scaled_height\n\n self.drawInRect(thumbnail_rect)\n\n new_image = UIGraphicsGetImageFromCurrentImageContext()\n UIGraphicsEndImageContext()\n\n raise \"could not scale image\" unless new_image\n\n return new_image\n end", "def scale(*args)\n r = Rect.new x, y, w, h\n r.resolution = r.resolution * Vector2[args.singularize]\n r\n end", "def resizeImage(imageName)\n image = MiniMagick::Image.open(imageName)\n height = image.height\n width = image.width\n\n if height > width\n ratio = 128.0 / height\n reHeight = (height * ratio).floor\n reWidth = (width * ratio).floor\n else\n ratio = 128.0 / width\n reHeight = (height * ratio).floor\n reWidth = (width * ratio).floor\n end\n\n image.resize(\"#{reHeight} x #{reWidth}\")\n image.write(\"resize.jpg\")\n end", "def resize_to_fit width, height\n process :resize_to_fit => [width, height]\n end", "def resize(path)\n gravity = @options.key?(:gravity) ? @options[:gravity] : 'Center'\n\n img = MiniMagick::Image.open(@file)\n cols, rows = img[:dimensions]\n\n img.combine_options do |cmd|\n if @width != cols || @height != rows\n scale_x = @width/cols.to_f\n scale_y = @height/rows.to_f\n\n if scale_x >= scale_y\n cols = (scale_x * (cols + 0.5)).round\n rows = (scale_x * (rows + 0.5)).round\n cmd.resize \"#{cols}\"\n else\n cols = (scale_y * (cols + 0.5)).round\n rows = (scale_y * (rows + 0.5)).round\n cmd.resize \"x#{rows}\"\n end\n end\n\n cmd.quality @options[:quality] if @options.key?(:quality)\n cmd.gravity gravity\n cmd.background 'rgba(255,255,255,0.0)'\n cmd.extent \"#{@width}x#{@height}\" if cols != @width || rows != @height\n end\n\n img.write(path)\n end", "def resize_to_fit\n image = ManagedImage.from_path(params[:image])\n width = params[:width].to_i\n height = params[:height].to_i\n render json: image.resize_to_fit(width, height)\n end", "def scale_to_cover(new_width, new_height, &block)\n raise ArgumentError, \"must supply the width and/or height\" if new_width.nil? && new_height.nil?\n if new_height.nil? || (!new_width.nil? && height*new_width > width*new_height)\n squish(new_width, height*new_width/width, &block)\n else\n squish(width*new_height/height, new_height, &block)\n end\n end", "def resize_photos_helper(photo)\n return nil if photo.blank?\n image = MiniMagick::Image.open(self.photo.url)\n [[:height,300], [:width, 600]].each do |param, num|\n if image.send(param) > num \n scaling_percent = (num / image.send(param).to_f)*100\n image.sample(scaling_percent.to_s + \"%\")\n end\n end\n return image\n end", "def scale_fixed old_min, old_max, new_min, new_max\n self.map do |elem|\n Rya::ExtendedClasses::MATH.scale elem, old_min, old_max, new_min, new_max\n end\n end", "def scales\n \n end", "def convert_image\n i = 0 \n main = [small\t=\t[\"jpg\",\"small\",240,160], \n\t medium\t=\t[\"jpg\",\"medium\",640,427], \n\t large\t=\t[\"jpg\",\"large\",1024,683]]\n while i < main.count\n # Runs the resize function with params to each size\n resize_image(main[i])\n i +=1\n end\n end", "def hscale(factor)\n @width *= factor\n @left *= factor\n self\n end", "def resize_resize_simple(width, height, image_file, opts = {})\n data, _status_code, _headers = resize_resize_simple_with_http_info(width, height, image_file, opts)\n data\n end", "def process_small_image\n small_image.encode!(:png).convert!('-resize 50x50 -gravity center -background none -extent 50x50')\n end", "def fit_within(max_w, max_h)\n w, h = width, height\n\n if w > max_w.to_i or h > max_h.to_i\n\n w_ratio = max_w.quo(w)\n h_ratio = max_h.quo(h)\n\n if (w_ratio < h_ratio)\n h = (h * w_ratio)\n w = (w * w_ratio)\n else\n h = (h * h_ratio)\n w = (w * h_ratio)\n end\n end\n\n if block_given?\n self.resize(w, h) do |image|\n yield image\n end\n else\n self.resize(w, h)\n end\n end", "def scaled_to(destination)\n Scale.transform(self).to(destination)\n end", "def resize_to_limit(width, height)\n manipulate! do |img|\n img.manipulate!(:resize => \"#{width}x#{height}>\")\n img = yield(img) if block_given?\n img\n end\n end", "def create_image(scale)\n # find the image size\n size = CGSizeMake(WIDTH * scale, HEIGHT * scale)\n # make the image bitmap and draw all of the parts\n image_bitmap(size, scale)\n end", "def process_image(src, dest, maxw, maxh)\n i = QuickMagick::Image.read(src).first\n # AMF - added quality setting to limit size of images (some sites had high quality jpeg, so files sizes were still big)\n i.quality = 75\n w, h = i.width, i.height\n extra = (w - h/(maxh.to_f/maxw.to_f)).to_i\n if extra > 0\n i.shave(\"#{extra>>1}x0\") if i.width > i.height\n w -= extra\n end\n if w > maxw or h > maxh\n i.resize(\"#{maxw}x#{maxh}\")\n end\n i.save(dest)\n end", "def resize_to_fill(width, height, gravity = 'Center')\n manipulate! do |img|\n cols, rows = img.dimensions[:x].to_i, img.dimensions[:y].to_i\n opt={}\n if width != cols || height != rows\n scale = [width/cols.to_f, height/rows.to_f].max\n cols = (scale * (cols + 0.5)).round\n rows = (scale * (rows + 0.5)).round\n opt[:resize] = \"#{cols}x#{rows}\"\n end\n opt[:gravity] = gravity\n opt[:background] = \"rgba(255,255,255,0.0)\"\n opt[:extent] = \"#{width}x#{height}\" if cols != width || rows != height\n img.manipulate!(opt)\n img = yield(img) if block_given?\n img\n end\n end", "def shrink_to_fit(new_width, new_height, &block)\n new_width, new_height = scale_dimensions_to_fit(new_width, new_height)\n return block.call(self) if new_width >= width && new_height >= height\n squish(new_width, new_height, &block)\n end", "def scale_aspect_to_fill_size(aSize)\n if aSize.width/aSize.height > size.width/size.height\n croppedImg = image_by_cropping_to_center_size(CGSize.new(size.width, (size.width/aSize.width * aSize.height).to_i))\n else\n croppedImg = image_by_cropping_to_center_size(CGSize.new((size.height/aSize.height * aSize.width).to_i, size.height))\n end\n\n croppedImg.scale_to_size(aSize)\n end", "def mul( val )\n @x.scale( val )\n @y.scale( val )\n self\n end", "def scaled_from(source)\n Scale.transform(self).from(source)\n end", "def resize_to_fill\n image = ManagedImage.from_path(params[:image])\n width = params[:width].to_i\n height = params[:height].to_i\n render json: image.resize_to_fill(width, height)\n end", "def create_resized_image\n create_image do |xfrm|\n if size\n MiniMagick::Tool::Convert.new do |cmd|\n cmd << xfrm.path # input\n cmd.flatten\n cmd.resize(size)\n cmd << xfrm.path # output\n end\n end\n end\n end", "def resizeImage(width,height)\n if @image != nil\n @image.resize(width,height)\n @image.applyOn(@imageBox)\n end\n end", "def draw_image_stretch(image, x1, y1, x2, y2, x3, y3, x4, y4, color)\n end", "def scale(xscale, yscale = xscale)\n current_transformation.scale(xscale, yscale)\n self[\"transform\"] = current_transformation.to_s\n end", "def image_background(scale, image_path)\n image = Magick::Image.read(image_path)\n if scale != 1.0\n image[0].resize!(scale) # TODO: Resize with new scale (crop if necessary for wide graph)\n end\n image[0]\n end", "def scale(scale_x, scale_y, center_x = nil, center_y = nil)\n args = [scale_x, scale_y, center_x, center_y].compact\n @canvas << js_method('scale', *args)\n return self\n end", "def resize_to_fill(new_width, new_height)\n manipulate! do |image|\n\n image = resize_image image, new_width, new_height, :max\n\n if image.width > new_width\n top = 0\n left = (image.width - new_width) / 2\n elsif image.height > new_height\n left = 0\n top = (image.height - new_height) / 2\n else\n left = 0\n top = 0\n end\n\n # Floating point errors can sometimes chop off an extra pixel\n # TODO: fix all the universe so that floating point errors never happen again\n new_height = image.height if image.height < new_height\n new_width = image.width if image.width < new_width\n\n image.extract_area(left, top, new_width, new_height)\n\n end\n end", "def scale!(alpha, incx=1, n=nil)\n #FIXME\n # raise(DataTypeError, \"Incompatible data type for the scaling factor\") unless\n # NMatrix::upcast(self.dtype, NMatrix::min_dtype(alpha)) == self.dtype\n raise(DataTypeError, \"Incompatible data type for the scaling factor\") if\n self.dtype == :int8\n @s.mapMultiplyToSelf(alpha)\n return self\n end", "def scale_to(new_size)\n scale_to(new_size, background:nil)\n end", "def img_resize( dat, w, h, options = {} )\n quality = options[:quality]\n format = options[:format]\n\n begin\n img = GD2::Image.load(dat)\n if h == 0\n h = ( w / img.aspect ).to_i\n end\n\n puts \"resizing image… width: #{w}, height: #{h}, quality: #{quality}\" if $debug\n\n # make sure it doesn't upscale image\n res = img.size\n\n if res[0] < w and res[1] < h\n w = res[0]\n h = res[1]\n elsif res[0] < w\n w = res[0]\n h = (w / img.aspect).to_i\n elsif res[1] < h\n h = res[1]\n w = (h / img.aspect).to_i\n end\n\n nimg = img.resize( w, h )\n\n if img_type(dat) == :jpeg and quality\n nimg.jpeg( quality.to_i )\n else\n case img_type(dat)\n when :png\n nimg.png\n when :jpeg\n nimg.jpeg\n when :gif\n nimg.gif\n else\n raise 'img_resize(), unknown output format'\n end\n end\n rescue => errmsg\n puts \"error: resize failed. #{w} #{h} #{quality}\"\n p errmsg\n return nil\n end\nend", "def scale(f)\n @x *= f\n @y *= f\n self\n end", "def resize_all(size_constraint)\n require 'rmagick'\n\n Dir.new('.').each do |f|\n if f.match(/jpg/)\n if (i = Magick::Image.read(f).first)\n i.resize_to_fit!(size_constraint)\n i.write(f)\n end\n end\n end\nend", "def resize_to_limit(new_width, new_height)\n width, height = FastImage.size(self.current_path)\n if width > new_width || height > new_height\n resize_to_fit(new_width, new_height)\n end\n end", "def expand_to_fit(new_width, new_height, &block)\n new_width, new_height = scale_dimensions_to_fit(new_width, new_height)\n return block.call(self) if new_width <= width && new_height <= height\n squish(new_width, new_height, &block)\n end", "def create_resized_image\n create_image do |xfrm|\n if size\n xfrm.flatten\n xfrm.resize(size)\n end\n end\n end", "def process(transform)\n raise \"Don't know how to do the #{transform} transformation\" unless geometry = StandardImageGeometry[transform.to_sym]\n change_image do |img|\n img.change_geometry(geometry) { |cols, rows, image| image.resize!(cols, rows) }\n end\n @aspect = transform.to_s\n self\n end", "def resize_post_with_http_info(max_width, max_height, image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ResizeApi.resize_post ...'\n end\n # verify the required parameter 'max_width' is set\n if @api_client.config.client_side_validation && max_width.nil?\n fail ArgumentError, \"Missing the required parameter 'max_width' when calling ResizeApi.resize_post\"\n end\n # verify the required parameter 'max_height' is set\n if @api_client.config.client_side_validation && max_height.nil?\n fail ArgumentError, \"Missing the required parameter 'max_height' when calling ResizeApi.resize_post\"\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ResizeApi.resize_post\"\n end\n # resource path\n local_var_path = '/image/resize/preserveAspectRatio/{maxWidth}/{maxHeight}'.sub('{' + 'maxWidth' + '}', max_width.to_s).sub('{' + 'maxHeight' + '}', max_height.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/octet-stream'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ResizeApi#resize_post\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end" ]
[ "0.74876934", "0.6929598", "0.62904245", "0.62255514", "0.6087487", "0.58767915", "0.58165014", "0.5636177", "0.5613749", "0.56060153", "0.5601863", "0.5581311", "0.5555667", "0.5544393", "0.55158347", "0.5513507", "0.5510966", "0.54933", "0.54405916", "0.54188484", "0.535726", "0.53488755", "0.53214526", "0.5266102", "0.5181276", "0.51682407", "0.51298666", "0.5096579", "0.50855964", "0.5082029", "0.50735074", "0.5055139", "0.50462997", "0.50462997", "0.50442064", "0.50327045", "0.5031739", "0.5021571", "0.50204295", "0.500959", "0.5007848", "0.5006695", "0.49856356", "0.49680227", "0.49485987", "0.49413386", "0.49399635", "0.49356726", "0.49214867", "0.48945242", "0.4889436", "0.48837295", "0.48788235", "0.48757985", "0.4872785", "0.48616737", "0.48592255", "0.485014", "0.48419654", "0.48417276", "0.4829842", "0.48296618", "0.48290887", "0.48198673", "0.48157325", "0.4809069", "0.47964028", "0.47903875", "0.47796747", "0.4766911", "0.47646236", "0.4760692", "0.4760315", "0.4759767", "0.47530344", "0.47441545", "0.47419035", "0.47403038", "0.47344476", "0.4734365", "0.4726433", "0.47105756", "0.4702123", "0.47014135", "0.4700191", "0.46997464", "0.4664775", "0.4649159", "0.46414205", "0.46333194", "0.46234334", "0.461465", "0.4609903", "0.46078748", "0.45759535", "0.45755517", "0.45658588", "0.45442015", "0.4537962", "0.45372587" ]
0.79472375
0
:callseq: scale_nearest(width, height) Scales the image using the nearestneighbor interpolation method. Nearestneighbor interpolation selects the value of the nearest pixel when calculating colors in the scaled image. == Example i = Axon::JPEG('test.jpg') i.scale_nearest(50, 75) i.width => 50 i.height => 75
def scale_nearest(*args) @source = NearestNeighborScaler.new(@source, *args) self end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def scale(width: @image.width, height: @image.height,\n algorithm: 'bilineal') # bilinear, nearest_neighbor\n if algorithm == 'nearest_neighbor'\n Image.new(@image.resample_nearest_neighbor(width, height), path)\n else\n Image.new(@image.resample_bilinear(width, height), path)\n end\n end", "def scale_bilinear(*args)\n @source = BilinearScaler.new(@source, *args)\n self\n end", "def scale(w, h, method = :bilinear)\n @image.send(\"resample_#{method}!\", w, h)\n self\n end", "def scale\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.scale(1.5)\n img.write('public' + @photo.attachment_url)\n end", "def scaleimage **opts\n Vips::Image.scale self, **opts\n end", "def scale_by_pixels(dimensions)\n out_pixels = sqrt(options[:width] * options[:height]).truncate\n src_pixels = sqrt(dimensions[0] * dimensions[1]).truncate\n out_pixels / src_pixels.to_f\n end", "def scale_image(preferred_width, preferred_height)\n # Retrieve the current height and width\n image_data = ActiveStorage::Analyzer::ImageAnalyzer.new(image).metadata\n new_width = image_data[:width]\n new_height = image_data[:height]\n\n # Adjust the width\n if new_width > preferred_width\n new_width = preferred_width\n new_height = (new_height * new_width) / image_data[:width]\n end\n\n # Adjust the height\n if new_height > preferred_height\n old_height = new_height\n new_height = preferred_height\n new_width = (new_width * new_height) / old_height\n end\n\n # Return the resized image\n image.variant(resize_to_limit: [new_width, new_height])\n end", "def scale_to_fit(width, height)\n @image = @image.scale_to_fit(width, height)\n self\n end", "def resize_retina_image(image_filename)\n \n image_name = File.basename(image_filename)\n \n image = Magick::Image.read(image_filename).first # Read the image\n new_image = image.scale(SCALE_BY)\n \n if new_image.write(image_filename) # Overwrite image file\n puts \"Resizing Image (#{SCALE_BY}): #{image_name}\"\n else\n puts \"Error: Couldn't resize image #{image_name}\"\n end\n \nend", "def resizeImages\n # For each of the 9 images\n for counter in (1..9)\n pngName = \"./images/\" + counter.to_s() + \".png\"\n image = Magick::Image.read(pngName).first\n # Make the new image 25% larger\n thumb = image.scale(1.25)\n thumb.write(pngName)\n end\n end", "def resize_photos_helper(photo)\n return nil if photo.blank?\n image = MiniMagick::Image.open(self.photo.url)\n [[:height,300], [:width, 600]].each do |param, num|\n if image.send(param) > num \n scaling_percent = (num / image.send(param).to_f)*100\n image.sample(scaling_percent.to_s + \"%\")\n end\n end\n return image\n end", "def fit\n if self.needs_to_be_resized?\n rmagick_img.resize_to_fit!(@x, @y)\n else\n rmagick_img.resize_to_fit(@x, @y)\n end\n end", "def resize_to_fit(new_width, new_height)\n width, height = FastImage.size(self.current_path)\n width_ratio = new_width.to_f / width.to_f\n height_when_width_used = height * width_ratio\n if height_when_width_used <= new_height\n new_height = height_when_width_used\n else\n height_ratio = new_height.to_f / height.to_f\n new_width = width * height_ratio\n end\n FastImage.resize(self.current_path, self.current_path, new_width, new_height)\n end", "def resample!(image, width, height)\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resample \"#{width}x#{height}\"\n end\n end\n end", "def optimized_image(image,x,y)\n return image.variant(resize_to_fill: [x,y]).processed\n end", "def resize_and_optimize(width, height)\n manipulate! do |img|\n img.format(\"jpg\") do |c|\n c.quality \"70\"\n c.resize \"#{width}x#{height}\"\n end\n\n img\n end\n end", "def scaled_using(source, destination)\n Scale.transform(self).using(source, destination)\n end", "def small(input) # Method that returns the image\n self.images[input].variant(resize: \"300x300\").processed # Resizing the image and return it\n end", "def upRes(file_path)\t\n\t\toriginal_image = Magick::Image.read(file_path) { self.density = \"300.0x300.0\" }\n\t\toriginal_image.each do |image|\n\t\t\t image = image.resample(300.0, 300.0)\n\t\t\t image.write(file_path) { self.quality = 100 }\n\t\tend\n\tend", "def process_small_image\n small_image.encode!(:png).convert!('-resize 50x50 -gravity center -background none -extent 50x50')\n end", "def scaled_to(destination)\n Scale.transform(self).to(destination)\n end", "def scale_to_fit(new_width, new_height, &block)\n squish(*scale_dimensions_to_fit(new_width, new_height), &block)\n end", "def fit_to_scale(rough_ratio)\n nearest_scale_ratio = 0 # FIXME: why not 1.0?\n\n if rough_ratio > 0\n rough_tonic = 2 ** (Math.log(rough_ratio) / Math.log(2)).floor\n\n ratios_and_deltas = scale_ratios.map do |scale_ratio|\n\n # bring scale_ratio into rough_ratio's 8ve\n scale_ratio *= 2 while scale_ratio < rough_tonic\n scale_ratio /= 2 while scale_ratio > (rough_tonic * 2)\n\n delta = (rough_ratio - scale_ratio).abs\n {:scale_ratio => scale_ratio, :delta => delta}\n end\n\n # FIXME!!!!!!!!!!!! HUGE FUCKING BUG; MAKES NO SENSE!\n # says delta is nil, when it's obviously not!!\n # \n ratios_and_deltas.each do |rd|\n if rd[:delta].nil?\n error \"NULL DELTA! #{rd.inspect}\" \n return 0\n end\n end\n\n nearest_scale_ratio = ratios_and_deltas.sort{|x, y| x[:delta] <=> y[:delta]}.first[:scale_ratio]\n end\n\n return nearest_scale_ratio\n end", "def scale(factor=0.75, quality: nil)\n \n read() do |img|\n \n img2 = img.scale(factor) \n write img2, quality\n \n end\n \n end", "def resize_to_fit!(image, width, height)\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resize \"#{width}x#{height}\"\n end\n end\n end", "def scale_to(new_size)\n scale_to(new_size, background:nil)\n end", "def fit_image(*args)\n @p.fit_image(self, *args)\n end", "def poster(input, output)\n \n input = input \n output = output \n \n scale(input, output)\n\n #Demonstrate the Image#polaroid method\n img = Magick::Image.read(output).first\n result = img.posterize\n \n #Write \n result.write(output)\n\nend", "def resize_to_fit width, height\n manipulate! do |image|\n cols = image.width\n rows = image.height\n\n if width != cols or height != rows\n scale = [width/cols.to_f, height/rows.to_f].min\n cols = (scale * (cols + 0.5)).round\n rows = (scale * (rows + 0.5)).round\n image.resize cols, rows do |img|\n yield(img) if block_given?\n img.save current_path\n end\n end\n end\n end", "def resample inimage, dpi, outimage=nil\n m_begin \"resample\"\n img = get_image(inimage)\n old_dpi = (image_dpi inimage)[0]\n if old_dpi != dpi then\n if false\n out = img.resample(dpi)\n elsif \n old_dpi = (image_dpi inimage)[0]\n ratio = dpi / old_dpi\n out = img.sample(ratio)\n out.density = \"#{dpi}x#{dpi}\"\n end\n else\n out = img\n end\n outimage = inimage if outimage.nil?\n put_image(outimage, out)\n m_end \"resample\"\n end", "def resize_to_limit(new_width, new_height)\n manipulate! do |image|\n image = resize_image(image,new_width,new_height) if new_width < image.x_size || new_height < image.y_size\n image\n end\n end", "def scale_within(new_size)\n target_size = SugarCube::CoreGraphics::Size(new_size)\n image_size = self.size\n\n if CGSizeEqualToSize(target_size, self.size)\n return self\n end\n\n width = image_size.width\n height = image_size.height\n\n target_width = target_size.width\n target_height = target_size.height\n\n width_factor = target_width / width\n height_factor = target_height / height\n\n if width_factor < height_factor\n scale_factor = width_factor\n else\n scale_factor = height_factor\n end\n\n if scale_factor == 1\n return self\n end\n\n scaled_size = CGSize.new(width * scale_factor, height * scale_factor)\n return scale_to(scaled_size)\n end", "def scaled_from(source)\n Scale.transform(self).from(source)\n end", "def resize_to_limit(width, height)\n width = dimension_from width\n height = dimension_from height\n manipulate! do |img|\n geometry = Magick::Geometry.new(width, height, 0, 0, Magick::GreaterGeometry)\n new_img = img.change_geometry(geometry) do |new_width, new_height|\n img.resize(new_width, new_height)\n end\n destroy_image(img)\n new_img = yield(new_img) if block_given?\n new_img\n end\n end", "def resize_image uri, options = { }\n\n\t# parse id, mime type from image uri\n\tformat = uri.split('/').last.match(/\\.(.+)$/)[1]\n\tid = uri.split('/').last.sub(/\\..+$/, '').slugify\n\n\t# resize image and save to /tmp\n\timage = Image.read(uri)[0]\n\t\n\t# calculate width/height based on percentage of \n\t# difference of width from absolute value of 150\n\tif options[:width]\n\t\twidth = options[:width]\n\t\tscale = (image.page.width - width) / image.page.width.to_f\n\t\theight = image.page.height - (image.page.height * scale)\n\n\t\timage = image.thumbnail(width, height)\n\t\timage.write(\n\t\t\tpath = \"/tmp/#{id}-constrainedw.#{format}\"\n\t\t)\t\t\n\n\telsif options[:height]\n\t\theight = options[:height]\n\t\tscale = (image.page.height - height) / image.page.height.to_f\n\t\twidth = image.page.width - (image.page.width * scale)\n\n\t\timage = image.thumbnail(width, height)\n\t\timage.write(\n\t\t\tpath = \"/tmp/#{id}-thumbh.#{format}\"\n\t\t)\n\n\telse\n\t\twidth = 150\n\t\tscale = (image.page.width - width) / image.page.width.to_f\n\t\theight = image.page.height - (image.page.height * scale)\n\n\t\timage = image.thumbnail(width, height)\n\t\timage.write(\n\t\t\tpath = \"/tmp/#{id}-thumb.#{format}\"\n\t\t)\n\n\tend\n\n path\nend", "def process_image(src, dest, maxw, maxh)\n i = QuickMagick::Image.read(src).first\n # AMF - added quality setting to limit size of images (some sites had high quality jpeg, so files sizes were still big)\n i.quality = 75\n w, h = i.width, i.height\n extra = (w - h/(maxh.to_f/maxw.to_f)).to_i\n if extra > 0\n i.shave(\"#{extra>>1}x0\") if i.width > i.height\n w -= extra\n end\n if w > maxw or h > maxh\n i.resize(\"#{maxw}x#{maxh}\")\n end\n i.save(dest)\n end", "def resize(width,height)\n\t\t@buffer=@buffer.scale(width, height, :bilinear)\n\tend", "def resize_to_limit!(image, width, height)\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resize \"#{width}x#{height}>\"\n end\n end\n end", "def resize_to_limit(new_width, new_height)\n manipulate! do |image|\n image = resize_image(image,new_width,new_height) if new_width < image.width || new_height < image.height\n image\n end\n end", "def test_fit_within_smaller\n ImageScience.with_image @biggie do |img|\n img.fit_within(100, 100) do |thumb|\n assert thumb.save(@tmppath)\n end\n end\n\n assert File.exists?(@tmppath)\n\n ImageScience.with_image @tmppath do |img|\n assert_kind_of ImageScience, img\n assert_equal 100, img.width\n end\n end", "def scale_to(new_size, background:background)\n new_size = SugarCube::CoreGraphics::Size(new_size)\n\n image_size = self.size\n\n if CGSizeEqualToSize(image_size, new_size)\n return self\n end\n\n new_image = nil\n width = image_size.width\n height = image_size.height\n\n target_width = new_size.width\n target_height = new_size.height\n\n scale_factor = 0.0\n scaled_width = target_width\n scaled_height = target_height\n\n thumbnail_point = CGPoint.new(0.0, 0.0)\n width_factor = target_width / width\n height_factor = target_height / height\n\n if width_factor < height_factor\n scale_factor = width_factor\n else\n scale_factor = height_factor\n end\n\n scaled_width = width * scale_factor\n scaled_height = height * scale_factor\n\n # center the image\n\n if width_factor < height_factor\n thumbnail_point.y = (target_height - scaled_height) * 0.5\n elsif width_factor > height_factor\n thumbnail_point.x = (target_width - scaled_width) * 0.5\n end\n\n # this is actually the interesting part:\n\n UIGraphicsBeginImageContextWithOptions(new_size, false, self.scale)\n\n if background\n background = background.uicolor\n context = UIGraphicsGetCurrentContext()\n background.setFill\n CGContextAddRect(context, [[0, 0], new_size])\n CGContextDrawPath(context, KCGPathFill)\n end\n\n thumbnail_rect = CGRectZero\n thumbnail_rect.origin = thumbnail_point\n thumbnail_rect.size.width = scaled_width\n thumbnail_rect.size.height = scaled_height\n\n self.drawInRect(thumbnail_rect)\n\n new_image = UIGraphicsGetImageFromCurrentImageContext()\n UIGraphicsEndImageContext()\n\n raise \"could not scale image\" unless new_image\n\n return new_image\n end", "def resize_to_fill(new_width, new_height)\n manipulate! do |image|\n\n image = resize_image image, new_width, new_height, :max\n\n if image.width > new_width\n top = 0\n left = (image.width - new_width) / 2\n elsif image.height > new_height\n left = 0\n top = (image.height - new_height) / 2\n else\n left = 0\n top = 0\n end\n\n # Floating point errors can sometimes chop off an extra pixel\n # TODO: fix all the universe so that floating point errors never happen again\n new_height = image.height if image.height < new_height\n new_width = image.width if image.width < new_width\n\n image.extract_area(left, top, new_width, new_height)\n\n end\n end", "def pixel\n image_name_list = get_image_name_list ELEMENTS_PATH\n image_name_list.each { |image_name| minimize(image_name) }\n end", "def get_scaled_size(image, width_bound, height_bound)\n width_multiplier = 1.0 * width_bound / image.columns\n height_multiplier = 1.0 * height_bound / image.rows\n\n if image.rows * width_multiplier <= height_bound\n width_multiplier\n else\n height_multiplier\n end\n end", "def resize_to_fill(new_width, new_height)\n manipulate! do |image|\n\n image = resize_image image, new_width, new_height, :max\n\n if image.x_size > new_width\n top = 0\n left = (image.x_size - new_width) / 2\n elsif image.y_size > new_height\n left = 0\n top = (image.y_size - new_height) / 2\n else\n left = 0\n top = 0\n end\n\n image.extract_area(left, top, new_width, new_height)\n\n end\n end", "def scale_aspect_to_fill_size(aSize)\n if aSize.width/aSize.height > size.width/size.height\n croppedImg = image_by_cropping_to_center_size(CGSize.new(size.width, (size.width/aSize.width * aSize.height).to_i))\n else\n croppedImg = image_by_cropping_to_center_size(CGSize.new((size.height/aSize.height * aSize.width).to_i, size.height))\n end\n\n croppedImg.scale_to_size(aSize)\n end", "def resize_all(size_constraint)\n require 'rmagick'\n\n Dir.new('.').each do |f|\n if f.match(/jpg/)\n if (i = Magick::Image.read(f).first)\n i.resize_to_fit!(size_constraint)\n i.write(f)\n end\n end\n end\nend", "def resize_to_fit(new_width, new_height)\n manipulate! do |image|\n resize_image(image,new_width,new_height)\n end\n end", "def resize_to_fit(new_width, new_height)\n manipulate! do |image|\n resize_image(image,new_width,new_height)\n end\n end", "def reduce_to(size, max_size, ratio = 1, allow_enlarge = false, min_max = false)\n ret = size.dup\n\n if min_max\n if max_size[:width] < max_size[:height] != size[:width] < size[:height]\n max_size[:width], max_size[:height] = max_size[:height], max_size[:width]\n end\n end\n\n if allow_enlarge\n if ret[:width] < max_size[:width]\n scale = max_size[:width].to_f / ret[:width].to_f\n ret[:width] = ret[:width] * scale\n ret[:height] = ret[:height] * scale\n end\n\n if max_size[:height] && (ret[:height] < ratio * max_size[:height])\n scale = max_size[:height].to_f / ret[:height].to_f\n ret[:width] = ret[:width] * scale\n ret[:height] = ret[:height] * scale\n end\n end\n\n if ret[:width] > ratio * max_size[:width]\n scale = max_size[:width].to_f / ret[:width].to_f\n ret[:width] = ret[:width] * scale\n ret[:height] = ret[:height] * scale\n end\n\n if max_size[:height] && (ret[:height] > ratio * max_size[:height])\n scale = max_size[:height].to_f / ret[:height].to_f\n ret[:width] = ret[:width] * scale\n ret[:height] = ret[:height] * scale\n end\n\n ret[:width] = ret[:width].round\n ret[:height] = ret[:height].round\n ret\n end", "def reduce_to(size, max_size, ratio = 1, allow_enlarge = false, min_max = false)\n ret = size.dup\n\n if min_max\n if max_size[:width] < max_size[:height] != size[:width] < size[:height]\n max_size[:width], max_size[:height] = max_size[:height], max_size[:width]\n end\n end\n\n if allow_enlarge\n if ret[:width] < max_size[:width]\n scale = max_size[:width].to_f / ret[:width].to_f\n ret[:width] = ret[:width] * scale\n ret[:height] = ret[:height] * scale\n end\n\n if max_size[:height] && (ret[:height] < ratio * max_size[:height])\n scale = max_size[:height].to_f / ret[:height].to_f\n ret[:width] = ret[:width] * scale\n ret[:height] = ret[:height] * scale\n end\n end\n\n if ret[:width] > ratio * max_size[:width]\n scale = max_size[:width].to_f / ret[:width].to_f\n ret[:width] = ret[:width] * scale\n ret[:height] = ret[:height] * scale\n end\n\n if max_size[:height] && (ret[:height] > ratio * max_size[:height])\n scale = max_size[:height].to_f / ret[:height].to_f\n ret[:width] = ret[:width] * scale\n ret[:height] = ret[:height] * scale\n end\n\n ret[:width] = ret[:width].round\n ret[:height] = ret[:height].round\n ret\n end", "def scale( scale_x, scale_y = scale_x )\n dup.scale!(scale_x, scale_y)\n end", "def resizeImage(imageName)\n image = MiniMagick::Image.open(imageName)\n height = image.height\n width = image.width\n\n if height > width\n ratio = 128.0 / height\n reHeight = (height * ratio).floor\n reWidth = (width * ratio).floor\n else\n ratio = 128.0 / width\n reHeight = (height * ratio).floor\n reWidth = (width * ratio).floor\n end\n\n image.resize(\"#{reHeight} x #{reWidth}\")\n image.write(\"resize.jpg\")\n end", "def process_image(path)\n picture_name = File.basename(path)\n thumbnail_dir = File.join(File.dirname(path), \"thumbnails\")\n thumbnail_path = File.join(thumbnail_dir, \"#{File.basename(picture_name, File.extname(picture_name))}.jpg\")\n Dir.mkdir(thumbnail_dir) unless File.exist?(thumbnail_dir)\n\n image_optim = ImageOptim.new\n\n image = MiniMagick::Image.open(path)\n image_prop = {\n \"name\" => picture_name,\n \"thumb\" => \"thumbnails/#{picture_name}\",\n \"height\" => image.height,\n \"width\" => image.width\n }\n\n return image_prop if File.exist?(thumbnail_path)\n\n# -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB\n\n image.format \"jpeg\" unless File.extname(picture_name) == \"jpg\"\n image.combine_options do |b|\n b.resize \"#{MAX_DIMENSION}>\"\n b.sampling_factor \"4:2:0\"\n b.strip\n b.interlace \"JPEG\"\n b.colorspace \"RGB\"\n b.quality 85\n end\n image.write thumbnail_path\n\n image_optim.optimize_image!(path)\n image_optim.optimize_image!(thumbnail_path)\n\n image_prop\nend", "def resizeImage(file, size)\n img_orig = Magick::Image.read(\"public/#{file}\").first\n \n width = img_orig.columns\n height = img_orig.rows\n \n if(width > size || height > size)\n if(width > height)\n height = size * height / width\n width = size\n else\n width = size * height / width\n height = size\n end\n \n img = img_orig.resize_to_fit(width, height)\n \n img.write(\"public/#{file}\")\n end\n end", "def resize_image(params)\n # The path of the image\n path = \"public/images/#{params[1]}/#{@tempo.id}_#{params[1]}.#{params[0]}\"\n # Read the image\n img = Magick::Image.read(\"public/images/original/#{@original_image_name}\").first\n # Resize and Crop the image\n target = Magick::Image.new(params[2], params[3])\n thumb = img.resize_to_fill!(params[2], params[3])\n target.composite(thumb, Magick::CenterGravity, Magick::CopyCompositeOp).write(path)\n # Insert the width and height into an object\n @tempo.width, @tempo.height = \"#{params[2]}\", \"#{params[3]}\"\n # Add the link and tags to its DB\n add_linkID_tagsID(path,params[1])\n # Delete the image after uploading it to the storage\n File.delete(path)\n end", "def resize(image, height:, width:)\n n_channels = image.shape[2]\n\n if n_channels.nil?\n bilinear_resize(image, height, width)\n else\n resized = image.class.zeros(height, width, n_channels)\n n_channels.times { |c| resized[true, true, c] = bilinear_resize(image[true, true, c], height, width) }\n resized\n end\n end", "def resize\n @image.resize \"#{@placement[:a]}x#{OUTER}\\!\"\n end", "def resize_to_limit(width, height)\n manipulate! do |image|\n image = resize_image(image, width, height) if width < image.x_size || height < image.y_size\n image\n end\n self\n end", "def convert_image\n i = 0 \n main = [small\t=\t[\"jpg\",\"small\",240,160], \n\t medium\t=\t[\"jpg\",\"medium\",640,427], \n\t large\t=\t[\"jpg\",\"large\",1024,683]]\n while i < main.count\n # Runs the resize function with params to each size\n resize_image(main[i])\n i +=1\n end\n end", "def tile_crop_resize(image, dpi)\n size = {\n 'x' => image.columns,\n 'y' => image.rows\n }\n\n resize = false\n\n ['x', 'y'].each do |a|\n if (@field['size' + a])\n size[a] = @field['size' + a]*dpi\n resize = true\n end\n end\n\n if (@field['tile'])\n image = tile_image(image, dpi) if @field['tile']\n elsif (resize)\n scaleX = size['x']/image.columns\n scaleY = size['y']/image.rows\n\n scale = scaleX\n scale = scaleY if scaleY > scaleX\n\n image.resize!(image.columns*scale, image.rows*scale, Magick::LanczosFilter, 0.7)\n end\n\n image.crop!(Magick::CenterGravity, size['x'], size['y']) if (@field['crop'])\n\n return image\n end", "def fit_within(max_w, max_h)\n w, h = width, height\n\n if w > max_w.to_i or h > max_h.to_i\n\n w_ratio = max_w.quo(w)\n h_ratio = max_h.quo(h)\n\n if (w_ratio < h_ratio)\n h = (h * w_ratio)\n w = (w * w_ratio)\n else\n h = (h * h_ratio)\n w = (w * h_ratio)\n end\n end\n\n if block_given?\n self.resize(w, h) do |image|\n yield image\n end\n else\n self.resize(w, h)\n end\n end", "def resize_to_fill_at\n image = ManagedImage.from_path(params[:image])\n width = params[:width].to_i\n height = params[:height].to_i\n x = params[:x].to_f / 100\n y = params[:y].to_f / 100\n render json: image.resize_to_fill_at(width, height, x, y)\n end", "def resize_to_fill!(image, width, height, gravity: \"Center\")\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resize \"#{width}x#{height}^\"\n cmd.gravity gravity\n cmd.background \"rgba(255,255,255,0.0)\" # transparent\n cmd.extent \"#{width}x#{height}\"\n end\n end\n end", "def resize_to_fill_and_save_dimensions(new_width, new_height)\n img = ::MiniMagick::Image.from_file(current_path)\n width, height = img['width'], img['height']\n \n resize_to_fill(new_width, new_height)\n \n w_ratio = width.to_f / new_width.to_f\n h_ratio = height.to_f / new_height.to_f\n \n ratio = [w_ratio, h_ratio].min\n \n model.send(\"#{mounted_as}_w=\", ratio * new_width)\n model.send(\"#{mounted_as}_h=\", ratio * new_height)\n model.send(\"#{mounted_as}_x=\", (width - model.send(\"#{mounted_as}_w\")) / 2)\n model.send(\"#{mounted_as}_y=\", (height - model.send(\"#{mounted_as}_h\")) / 2)\n end", "def scale\n scale_factor = 20 # template.png height divided by canvas height\n self.image_x *= scale_factor\n self.image_y *= scale_factor\n self.height *= scale_factor\n self.width *= scale_factor\n self.rotation *= 180 / Math::PI\n end", "def open_image id, filename, target_dpi=nil\n m_begin \"open_image\"\n# Read in the file as an imagelist. The new image will be in the first position of the array.\n img = ImageList.new(filename)\n img = img[0]\n put_image(id, img)\n if !target_dpi.nil?\n img = resample id, target_dpi\n end\n m_end \"open_image\"\n end", "def image_background(scale, image_path)\n image = Magick::Image.read(image_path)\n if scale != 1.0\n image[0].resize!(scale) # TODO: Resize with new scale (crop if necessary for wide graph)\n end\n image[0]\n end", "def dynamic_resize_to_fit(size)\n resize_to_fit *(model.class::IMAGE_CONFIG[size])\n end", "def resize_to_limit(new_width, new_height)\n width, height = FastImage.size(self.current_path)\n if width > new_width || height > new_height\n resize_to_fit(new_width, new_height)\n end\n end", "def initialize(options = {})\n super\n @nearest = options[:nearest] || 0.1\n end", "def scale(value)\n @tileset.scale = value\n end", "def strict_resize image, w, h\n image.resize \"#{ w }x#{ h }!\"\n image\n end", "def scale_by num\n min = 0.001\n num = min if num < min and num > -min\n self.x = self.x / num\n self.y = self.y / num\n self\n end", "def resize(path)\n gravity = @options.key?(:gravity) ? @options[:gravity] : 'Center'\n\n img = MiniMagick::Image.open(@file)\n cols, rows = img[:dimensions]\n\n img.combine_options do |cmd|\n if @width != cols || @height != rows\n scale_x = @width/cols.to_f\n scale_y = @height/rows.to_f\n\n if scale_x >= scale_y\n cols = (scale_x * (cols + 0.5)).round\n rows = (scale_x * (rows + 0.5)).round\n cmd.resize \"#{cols}\"\n else\n cols = (scale_y * (cols + 0.5)).round\n rows = (scale_y * (rows + 0.5)).round\n cmd.resize \"x#{rows}\"\n end\n end\n\n cmd.quality @options[:quality] if @options.key?(:quality)\n cmd.gravity gravity\n cmd.background 'rgba(255,255,255,0.0)'\n cmd.extent \"#{@width}x#{@height}\" if cols != @width || rows != @height\n end\n\n img.write(path)\n end", "def small_image_url\n self.small_image.convert('-resize 50%').url\n end", "def resize_to_fit(width, height)\n manipulate! do |image|\n resize_image image, width, height\n end\n self\n end", "def image_as_medium_thumbnail\n image.variant(resize_to_fill: [350, 350]).processed\n end", "def get_card_imagescaled_of(scale_lbl,lbl)\r\n unless @cards_scaled_info[scale_lbl]\r\n @log.warn(\"get_card_imagescaled_of no scale inforrmation found\")\r\n return get_card_image_of(lbl)\r\n end\r\n unless @cards_scaled[scale_lbl]\r\n # intialize hash to store all reduced cards. Use the card label to get it.\r\n @cards_scaled[scale_lbl] = {}\r\n end\r\n unless @cards_scaled[scale_lbl][lbl]\r\n # first time that this scaled image is accessed, create it\r\n @cards_scaled[scale_lbl][lbl] = load_create_scaled_img(scale_lbl, lbl)\r\n end\r\n return @cards_scaled[scale_lbl][lbl]\r\n end", "def scale(value)\r\n value * @height/2 + @height/4\r\n end", "def extract_thumb(input, output, width, height)\n Image::Editing::ResizeToFill.new(input, output, width, height).run\n end", "def resize_to_fit(width, height)\n width = dimension_from width\n height = dimension_from height\n manipulate! do |img|\n img.resize_to_fit!(width, height)\n img = yield(img) if block_given?\n img\n end\n end", "def rescale_input(value, source_scaler, dest_scaler)\n if source_scaler\n descaled = source_scaler.descale(value)\n dest_scaler ? dest_scaler.scale(descaled) : descaled\n elsif dest_scaler\n dest_scaler.scale(value)\n end\n end", "def resize_with_fill(img, w, h, n, color)\n n ||= 0\n img.resize_to_fit! w-n*2, h-n*2\n background = ::Magick::Image.new(w, h) { self.background_color = color }\n background.composite(img, Magick::CenterGravity, Magick::OverCompositeOp)\n end", "def scale_to_fill(new_size, scale: scale)\n scale_to_fill(new_size, position: :center, scale: scale)\n end", "def SetImageScale(scale)\n\t\t@img_scale = scale;\n\tend", "def optimize_image!(original)\n original = Path.convert(original)\n return unless (result = optimize_image(original))\n result.replace(original)\n OptimizedPath.new(original, result.original_size)\n end", "def scale_to_cover(new_width, new_height, &block)\n raise ArgumentError, \"must supply the width and/or height\" if new_width.nil? && new_height.nil?\n if new_height.nil? || (!new_width.nil? && height*new_width > width*new_height)\n squish(new_width, height*new_width/width, &block)\n else\n squish(width*new_height/height, new_height, &block)\n end\n end", "def create_resized_image\n create_image do |xfrm|\n if size\n MiniMagick::Tool::Convert.new do |cmd|\n cmd << xfrm.path # input\n cmd.flatten\n cmd.resize(size)\n cmd << xfrm.path # output\n end\n end\n end\n end", "def scale_fixed old_min, old_max, new_min, new_max\n self.map do |elem|\n Rya::ExtendedClasses::MATH.scale elem, old_min, old_max, new_min, new_max\n end\n end", "def scale_by_bounds(dimensions)\n x = options[:width] / dimensions[0].to_f\n y = options[:height] / dimensions[1].to_f\n x * dimensions[1] > options[:height] ? y : x\n end", "def update!(**args)\n @nearest_neighbors = args[:nearest_neighbors] if args.key?(:nearest_neighbors)\n end", "def scale(*args)\n r = Rect.new x, y, w, h\n r.resolution = r.resolution * Vector2[args.singularize]\n r\n end", "def resize_to_fill\n image = ManagedImage.from_path(params[:image])\n width = params[:width].to_i\n height = params[:height].to_i\n render json: image.resize_to_fill(width, height)\n end", "def resize_to_fit(width, height)\n manipulate! do |img|\n img.resize \"#{width}x#{height}\"\n img = yield(img) if block_given?\n img\n end\n end", "def scale_to_fill(new_size)\n scale_to_fill(new_size, position: :center)\n end", "def round!(target: COMMON_SCALE_FACTORS, direction: 0)\n # Scale can no longer be considered to be generated from string.\n @source_string = nil\n\n # If the scale factor is smaller than 1, round its inverse to an sensible\n # number. In 1:x, x should be the sensible value, not its inverse.\n downsize = @factor < 1\n @factor = 1 / @factor if downsize\n direction = -direction if downsize\n\n coefficient, exponent = split_number(@factor)\n coefficient = round_to_target(coefficient, target, direction)\n\n # Sometimes Rational is included and overrides Ruby core math functionality.\n # Ensure result is float to honor API contract and avoid unexpected\n # consequence elsewhere.\n @factor = (coefficient * 10**exponent).to_f\n\n @factor = 1 / @factor if downsize\n\n self\n end", "def shrink_to_fit(new_width, new_height, &block)\n new_width, new_height = scale_dimensions_to_fit(new_width, new_height)\n return block.call(self) if new_width >= width && new_height >= height\n squish(new_width, new_height, &block)\n end", "def resize_to_fit width, height\n process :resize_to_fit => [width, height]\n end", "def find_and_resize!(path)\n check_and_resize_images(path)\n end" ]
[ "0.7143473", "0.5917895", "0.5883907", "0.5648101", "0.5527938", "0.549518", "0.54871935", "0.5457946", "0.54511553", "0.5260264", "0.5172822", "0.5139375", "0.50794816", "0.5040413", "0.5021077", "0.50138474", "0.4997212", "0.49891388", "0.49704787", "0.49383867", "0.48814666", "0.48771903", "0.48753363", "0.4851389", "0.48418057", "0.48253638", "0.4822331", "0.48151723", "0.48099527", "0.48021054", "0.47679067", "0.476074", "0.47591463", "0.4750136", "0.47452104", "0.47369775", "0.47357813", "0.47263202", "0.47091565", "0.46999866", "0.46980956", "0.46852982", "0.46852228", "0.46827868", "0.468203", "0.46807674", "0.46799466", "0.4673511", "0.4673511", "0.46606052", "0.46606052", "0.46574056", "0.46521166", "0.46435994", "0.46376446", "0.46261796", "0.46257088", "0.4612516", "0.46086225", "0.4599865", "0.45984507", "0.45936", "0.45928174", "0.45833856", "0.45812374", "0.45791602", "0.45770398", "0.4552544", "0.45409495", "0.4523703", "0.45210242", "0.4520284", "0.451867", "0.45138696", "0.4512056", "0.44959524", "0.44947717", "0.44844988", "0.4477929", "0.44732958", "0.44667634", "0.44489247", "0.44303018", "0.4429865", "0.44287902", "0.44208458", "0.4416237", "0.44096386", "0.43990785", "0.43930534", "0.43858197", "0.43674526", "0.43582484", "0.43574712", "0.43538395", "0.43522492", "0.4331688", "0.4330385", "0.43291467", "0.43204486" ]
0.7812567
0
:callseq: fit(width, height) Scales the image to fit inside given box dimensions while maintaining the aspect ratio. == Example i = Axon::JPEG('test.jpg') i.fit(5, 20) i.width => 5 i.height => 10
def fit(*args) @source = Fit.new(@source, *args) self end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def resize_to_fit width, height\n process :resize_to_fit => [width, height]\n end", "def scale_to_fit(width, height)\n @image = @image.scale_to_fit(width, height)\n self\n end", "def resize_to_fit!(image, width, height)\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resize \"#{width}x#{height}\"\n end\n end\n end", "def resize_to_fit(width, height)\n manipulate! do |image|\n resize_image image, width, height\n end\n self\n end", "def resize_to_fit width, height\n manipulate! do |image|\n cols = image.width\n rows = image.height\n\n if width != cols or height != rows\n scale = [width/cols.to_f, height/rows.to_f].min\n cols = (scale * (cols + 0.5)).round\n rows = (scale * (rows + 0.5)).round\n image.resize cols, rows do |img|\n yield(img) if block_given?\n img.save current_path\n end\n end\n end\n end", "def resize_to_fit(width, height)\n width = dimension_from width\n height = dimension_from height\n manipulate! do |img|\n img.resize_to_fit!(width, height)\n img = yield(img) if block_given?\n img\n end\n end", "def fit(pipeline, width, height)\n pipeline.resize_to_fit!(width, height)\n end", "def resize_to_fit(width, height)\n manipulate! do |img|\n img.manipulate!(:resize => \"#{width}x#{height}\")\n img = yield(img) if block_given?\n img\n end\n end", "def resize_to_fit(width, height)\n manipulate! do |img|\n img.resize \"#{width}x#{height}\"\n img = yield(img) if block_given?\n img\n end\n end", "def resize_to_fit(new_width, new_height)\n manipulate! do |image|\n resize_image(image,new_width,new_height)\n end\n end", "def resize_to_fit(new_width, new_height)\n manipulate! do |image|\n resize_image(image,new_width,new_height)\n end\n end", "def fit\n if self.needs_to_be_resized?\n rmagick_img.resize_to_fit!(@x, @y)\n else\n rmagick_img.resize_to_fit(@x, @y)\n end\n end", "def scale_to_fit(new_width, new_height, &block)\n squish(*scale_dimensions_to_fit(new_width, new_height), &block)\n end", "def fit_to(options = {})\n self.fit_to_width = options[:width] || 999\n self.fit_to_height = options[:height] || 999\n [@fit_to_width, @fit_to_height]\n end", "def resize_to_fit\n image = ManagedImage.from_path(params[:image])\n width = params[:width].to_i\n height = params[:height].to_i\n render json: image.resize_to_fit(width, height)\n end", "def fit_within(max_w, max_h)\n w, h = width, height\n\n if w > max_w.to_i or h > max_h.to_i\n\n w_ratio = max_w.quo(w)\n h_ratio = max_h.quo(h)\n\n if (w_ratio < h_ratio)\n h = (h * w_ratio)\n w = (w * w_ratio)\n else\n h = (h * h_ratio)\n w = (w * h_ratio)\n end\n end\n\n if block_given?\n self.resize(w, h) do |image|\n yield image\n end\n else\n self.resize(w, h)\n end\n end", "def resize_to_fit(new_width, new_height)\n width, height = FastImage.size(self.current_path)\n width_ratio = new_width.to_f / width.to_f\n height_when_width_used = height * width_ratio\n if height_when_width_used <= new_height\n new_height = height_when_width_used\n else\n height_ratio = new_height.to_f / height.to_f\n new_width = width * height_ratio\n end\n FastImage.resize(self.current_path, self.current_path, new_width, new_height)\n end", "def fit_image(*args)\n @p.fit_image(self, *args)\n end", "def test_fit_within_smaller\n ImageScience.with_image @biggie do |img|\n img.fit_within(100, 100) do |thumb|\n assert thumb.save(@tmppath)\n end\n end\n\n assert File.exists?(@tmppath)\n\n ImageScience.with_image @tmppath do |img|\n assert_kind_of ImageScience, img\n assert_equal 100, img.width\n end\n end", "def resize_to_limit!(image, width, height)\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resize \"#{width}x#{height}>\"\n end\n end\n end", "def dynamic_resize_to_fit(size)\n resize_to_fit *(model.class::IMAGE_CONFIG[size])\n end", "def crop_to_fit(width, height)\n @image = @image.crop_to_fit(width, height)\n self\n end", "def resizeImage(width,height)\n if @image != nil\n @image.resize(width,height)\n @image.applyOn(@imageBox)\n end\n end", "def resize_and_optimize(width, height)\n manipulate! do |img|\n img.format(\"jpg\") do |c|\n c.quality \"70\"\n c.resize \"#{width}x#{height}\"\n end\n\n img\n end\n end", "def resize_to_fill!(image, width, height, gravity: \"Center\")\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resize \"#{width}x#{height}^\"\n cmd.gravity gravity\n cmd.background \"rgba(255,255,255,0.0)\" # transparent\n cmd.extent \"#{width}x#{height}\"\n end\n end\n end", "def expand_to_fit(new_width, new_height, &block)\n new_width, new_height = scale_dimensions_to_fit(new_width, new_height)\n return block.call(self) if new_width <= width && new_height <= height\n squish(new_width, new_height, &block)\n end", "def resize_to_fill\n image = ManagedImage.from_path(params[:image])\n width = params[:width].to_i\n height = params[:height].to_i\n render json: image.resize_to_fill(width, height)\n end", "def resize_to_fill(width, height)\n manipulate! do |image|\n image = resize_image image, width, height, :max\n top = 0\n left = 0\n\n if image.x_size > width\n left = (image.x_size - width) / 2\n elsif image.y_size > height\n top = (image.y_size - height) / 2\n end\n\n image.extract_area left, top, width, height\n end\n self\n end", "def resize_to_limit(width, height)\n width = dimension_from width\n height = dimension_from height\n manipulate! do |img|\n geometry = Magick::Geometry.new(width, height, 0, 0, Magick::GreaterGeometry)\n new_img = img.change_geometry(geometry) do |new_width, new_height|\n img.resize(new_width, new_height)\n end\n destroy_image(img)\n new_img = yield(new_img) if block_given?\n new_img\n end\n end", "def resize_to_fill(width, height, gravity=::Magick::CenterGravity)\n width = dimension_from width\n height = dimension_from height\n manipulate! do |img|\n img.crop_resized!(width, height, gravity)\n img = yield(img) if block_given?\n img\n end\n end", "def resize_to_fill(width, height, gravity = 'Center')\n manipulate! do |img|\n cols, rows = img.dimensions[:x].to_i, img.dimensions[:y].to_i\n opt={}\n if width != cols || height != rows\n scale = [width/cols.to_f, height/rows.to_f].max\n cols = (scale * (cols + 0.5)).round\n rows = (scale * (rows + 0.5)).round\n opt[:resize] = \"#{cols}x#{rows}\"\n end\n opt[:gravity] = gravity\n opt[:background] = \"rgba(255,255,255,0.0)\"\n opt[:extent] = \"#{width}x#{height}\" if cols != width || rows != height\n img.manipulate!(opt)\n img = yield(img) if block_given?\n img\n end\n end", "def resize_to(width, height); end", "def shrink_to_fit(new_width, new_height, &block)\n new_width, new_height = scale_dimensions_to_fit(new_width, new_height)\n return block.call(self) if new_width >= width && new_height >= height\n squish(new_width, new_height, &block)\n end", "def resize_to_fill(new_width, new_height)\n manipulate! do |image|\n\n image = resize_image image, new_width, new_height, :max\n\n if image.x_size > new_width\n top = 0\n left = (image.x_size - new_width) / 2\n elsif image.y_size > new_height\n left = 0\n top = (image.y_size - new_height) / 2\n else\n left = 0\n top = 0\n end\n\n image.extract_area(left, top, new_width, new_height)\n\n end\n end", "def resize_to_fit(cols, rows = nil)\n rows ||= cols\n change_geometry(Geometry.new(cols, rows)) do |ncols, nrows|\n resize(ncols, nrows)\n end\n end", "def scale_dimensions_to_fit(new_width, new_height)\n raise ArgumentError, \"must supply the width and/or height\" if new_width.nil? && new_height.nil?\n if new_height.nil? || (!new_width.nil? && height*new_width < width*new_height)\n return [new_width, height*new_width/width]\n else\n return [width*new_height/height, new_height]\n end\n end", "def resize(width, height)\n end", "def scale_to_fit_container( aspect, container_width, container_height )\n width, height = aspect.split( Optparser::ASPECT_CHOICE_CUSTOM_PREFIX ).last.split( 'x' ).collect{|x| x.to_f}\n factor = container_height / container_width > height / width ? container_width / width : container_height / height\n @logger.debug( \"Scaling factor to fit custom aspect ratio #{ width } x #{ height } in #{ @options.size } container: #{ factor }\" )\n width_scaled = width * factor\n height_scaled = height * factor\n return width_scaled.floor, height_scaled.floor\n end", "def resize_all(size_constraint)\n require 'rmagick'\n\n Dir.new('.').each do |f|\n if f.match(/jpg/)\n if (i = Magick::Image.read(f).first)\n i.resize_to_fit!(size_constraint)\n i.write(f)\n end\n end\n end\nend", "def resize_to_limit(width, height)\n manipulate! do |image|\n image = resize_image(image, width, height) if width < image.x_size || height < image.y_size\n image\n end\n self\n end", "def resize(width, height); end", "def resize_to_limit(width, height)\n manipulate! do |img|\n img.resize \"#{width}x#{height}>\"\n img = yield(img) if block_given?\n img\n end\n end", "def my_resize(width, height)\n manipulate! do |img|\n img.resize \"#{width}x#{height}!\"\n img\n end\n end", "def fit_width; end", "def resize_to_fill(new_width, new_height)\n manipulate! do |image|\n\n image = resize_image image, new_width, new_height, :max\n\n if image.width > new_width\n top = 0\n left = (image.width - new_width) / 2\n elsif image.height > new_height\n left = 0\n top = (image.height - new_height) / 2\n else\n left = 0\n top = 0\n end\n\n # Floating point errors can sometimes chop off an extra pixel\n # TODO: fix all the universe so that floating point errors never happen again\n new_height = image.height if image.height < new_height\n new_width = image.width if image.width < new_width\n\n image.extract_area(left, top, new_width, new_height)\n\n end\n end", "def resize_to_fill_at\n image = ManagedImage.from_path(params[:image])\n width = params[:width].to_i\n height = params[:height].to_i\n x = params[:x].to_f / 100\n y = params[:y].to_f / 100\n render json: image.resize_to_fill_at(width, height, x, y)\n end", "def scale(width: @image.width, height: @image.height,\n algorithm: 'bilineal') # bilinear, nearest_neighbor\n if algorithm == 'nearest_neighbor'\n Image.new(@image.resample_nearest_neighbor(width, height), path)\n else\n Image.new(@image.resample_bilinear(width, height), path)\n end\n end", "def resize_to_limit(width, height)\n manipulate! do |img|\n img.manipulate!(:resize => \"#{width}x#{height}>\")\n img = yield(img) if block_given?\n img\n end\n end", "def fit_to_pages(width = 0, height = 0)\n @fit_page = 1\n @fit_width = width\n @fit_height = height\n end", "def resize_and_save!(height = MAX_HEIGHT, width = MAX_WIDTH, validate = true)\n #KS- Only do thumbnailing if the Image Magick library can be loaded.\n # This is to make setup easier for other developers- they are not\n # required to have Image Magick.\n # More information on Image Magick is available at \n # http://studio.imagemagick.org/RMagick/doc/usage.html\n if RMAGICK_SUPPORTED\n #MES- Turn the blob into an ImageMagick object\n img = Magick::Image.from_blob(data).first\n if img.nil?\n logger.info \"Failed to resize image #{self.name}- unable to create RMagick wrapper for image\"\n return nil\n end\n \n #MES- Shrink the image\n self.data = img.change_geometry(\"#{MAX_WIDTH}x#{MAX_HEIGHT}\"){ |cols, rows, img| \n if img.rows > rows || img.columns > cols\n img.resize!(cols, rows)\n else\n img\n end\n }.to_blob\n end\n \n successful = save_with_validation(validate)\n raise \"Error: picture #{self.id} not saved properly\" if !successful\n end", "def cut_to_fit(options)\n %Q{-thumbnail #{options.width}x#{options.height}^ \\\n -gravity #{options.gravity} \\\n -unsharp 0x.5 \\\n -auto-orient \\\n -extent #{options.width}x#{options.height}}\n end", "def resize_to_fill_and_save_dimensions(new_width, new_height)\n img = ::MiniMagick::Image.from_file(current_path)\n width, height = img['width'], img['height']\n \n resize_to_fill(new_width, new_height)\n \n w_ratio = width.to_f / new_width.to_f\n h_ratio = height.to_f / new_height.to_f\n \n ratio = [w_ratio, h_ratio].min\n \n model.send(\"#{mounted_as}_w=\", ratio * new_width)\n model.send(\"#{mounted_as}_h=\", ratio * new_height)\n model.send(\"#{mounted_as}_x=\", (width - model.send(\"#{mounted_as}_w\")) / 2)\n model.send(\"#{mounted_as}_y=\", (height - model.send(\"#{mounted_as}_h\")) / 2)\n end", "def resize_to_fill(width, height, gravity = 'Center')\n manipulate! do |img|\n img.resize(\"#{width}x#{height}^\")\n \t.gravity(gravity)\n \t.background(\"rgba(255,255,255,0.0)\")\n \t.extent(\"#{width}x#{height}\")\n img = yield(img) if block_given?\n img\n end\n end", "def resize(width,height)\n\t\t@buffer=@buffer.scale(width, height, :bilinear)\n\tend", "def small(input) # Method that returns the image\n self.images[input].variant(resize: \"300x300\").processed # Resizing the image and return it\n end", "def resize(image, height:, width:)\n n_channels = image.shape[2]\n\n if n_channels.nil?\n bilinear_resize(image, height, width)\n else\n resized = image.class.zeros(height, width, n_channels)\n n_channels.times { |c| resized[true, true, c] = bilinear_resize(image[true, true, c], height, width) }\n resized\n end\n end", "def resize_to_limit(new_width, new_height)\n width, height = FastImage.size(self.current_path)\n if width > new_width || height > new_height\n resize_to_fit(new_width, new_height)\n end\n end", "def resize_to_limit(new_width, new_height)\n manipulate! do |image|\n image = resize_image(image,new_width,new_height) if new_width < image.x_size || new_height < image.y_size\n image\n end\n end", "def resize_to_limit(new_width, new_height)\n manipulate! do |image|\n image = resize_image(image,new_width,new_height) if new_width < image.width || new_height < image.height\n image\n end\n end", "def setImage(image, width: nil, height: nil)\n @image = Asset.new(image)\n @image.resize(width, height) if (width != nil && height != nil)\n @image.applyOn(@imageBox)\n end", "def resize_image\n image = params[:fleet][:image]\n return if image.nil?\n\n begin\n image = MiniMagick::Image.new(image.tempfile.path)\n image.resize '175x260>'\n rescue MiniMagick::Error\n # errors here will be caught in model validation\n end\n end", "def fill(pipeline, width, height, gravity = \"Center\")\n pipeline.resize_to_fill!(width, height, gravity: gravity)\n end", "def resize_to_fit(win, padding=20)\n if(padding.is_a?(Hash))\n w_pad = padding[:width_pad]\n h_pad = padding[:height_pad]\n else\n w_pad = h_pad = padding\n end\n auto_resize(win, h_pad, :height)\n auto_resize(win, w_pad, :width)\n center_window(win)\n end", "def create_resized_image\n create_image do |xfrm|\n if size\n MiniMagick::Tool::Convert.new do |cmd|\n cmd << xfrm.path # input\n cmd.flatten\n cmd.resize(size)\n cmd << xfrm.path # output\n end\n end\n end\n end", "def resizeImage(file, size)\n img_orig = Magick::Image.read(\"public/#{file}\").first\n \n width = img_orig.columns\n height = img_orig.rows\n \n if(width > size || height > size)\n if(width > height)\n height = size * height / width\n width = size\n else\n width = size * height / width\n height = size\n end\n \n img = img_orig.resize_to_fit(width, height)\n \n img.write(\"public/#{file}\")\n end\n end", "def limit(pipeline, width, height)\n pipeline.resize_to_limit!(width || \"!\", height || \"!\")\n end", "def resize_pic(filename,resizewidth,out_path)\n nw = resizewidth\n n = File.basename(filename)\n i = QuickMagick::Image.read(filename).first\n w = i.width.to_f # Retrieves width in pixels\n h = i.height.to_f # Retrieves height in pixels\n pr = w/h\n nh = nw/pr \n i.resize \"#{nw}x#{nh}!\"\n i.save \"#{out_path}/#{n}\"\nend", "def get_scaled_size(image, width_bound, height_bound)\n width_multiplier = 1.0 * width_bound / image.columns\n height_multiplier = 1.0 * height_bound / image.rows\n\n if image.rows * width_multiplier <= height_bound\n width_multiplier\n else\n height_multiplier\n end\n end", "def resize(width, height, resize_method)\n cropping = (resize_method != :resize_scale)\n\n # Calculate aspect ratios\n source_ratio = size.width / size.height\n target_ratio = width / height\n\n # Determine what side of the source image to use for proportional scaling\n scale_width = (source_ratio <= target_ratio)\n\n # Proportionally scale source image\n scaled_width, scaled_height = nil, nil\n if cropping && scale_width\n scaling_factor = 1.0 / source_ratio\n scaled_width = width\n scaled_height = (width * scaling_factor).round\n else\n scaling_factor = source_ratio\n scaled_width = (height * scaling_factor).round\n scaled_height = height\n end\n scale_factor = scaled_height / size.height\n\n # Calculate compositing rectangles\n source_rect = nil\n if cropping\n dest_x, dest_y = nil, nil\n case resize_method\n when :resize_crop\n # Crop center\n dest_x = ((scaled_width - width) / 2.0).round\n dest_y = ((scaled_height - height) / 2.0).round\n when :resize_crop_start\n # Crop top or left (prefer top)\n if scale_width\n # Crop top\n dest_x = ((scaled_width - width) / 2.0).round\n dest_y = (scaled_height - height).round\n else\n # Crop left\n dest_x = 0.0\n dest_y = ((scaled_height - height) / 2.0).round\n end\n when :resize_crop_end\n # Crop bottom or right\n if scale_width\n # Crop bottom\n dest_x = 0.0\n dest_y = 0.0\n else\n # Crop right\n dest_x = (scaled_width - width).round\n dest_y = ((scaled_height - height) / 2.0).round\n end\n end\n source_rect = [dest_x / scale_factor, dest_y / scale_factor, width / scale_factor, height / scale_factor]\n else\n width = scaled_width\n height = scaled_height\n source_rect = [0, 0, size.width, size.height]\n end\n\n result = OSX::NSImage.alloc.initWithSize([width, height])\n result.lockFocus\n OSX::NSGraphicsContext.currentContext.setImageInterpolation(OSX::NSImageInterpolationHigh)\n drawInRect_fromRect_operation_fraction([0, 0, width, height], source_rect, OSX::NSCompositeSourceOver, 1.0)\n result.unlockFocus\n result\n end", "def resize!(*args)\n width, height = Geometry.new(*args).dimensions\n resize(\"#{width}x#{height}^\").crop(width, height).repage\n end", "def resize\n image = ManagedImage.from_path(params[:image])\n width = params[:width].to_i\n height = params[:height].to_i\n render json: image.resize(width, height)\n end", "def normalized_sizes(width, height)\n if width.to_i > @image.width\n width = @image.width\n end\n if height.to_i > @image.height\n height = @image.height\n end\n \"#{width}x#{height}\"\n end", "def scale_by(width_factor, height_factor, &block)\n squish(width*width_factor, height*height_factor, &block)\n end", "def test_method_size\n width, height = (1..100).to_a.sample( 2 )\n base_image = Magick::Image.new( width, height )\n image_adapter = Image::AdapterMagickImage.new( base_image )\n \n # maps width/height to size( :x ) / size ( :y )\n assert_equal width, image_adapter.size( :x )\n assert_equal height, image_adapter.size( :y )\n end", "def scale(w, h, method = :bilinear)\n @image.send(\"resample_#{method}!\", w, h)\n self\n end", "def scale_aspect_to_fill_size(aSize)\n if aSize.width/aSize.height > size.width/size.height\n croppedImg = image_by_cropping_to_center_size(CGSize.new(size.width, (size.width/aSize.width * aSize.height).to_i))\n else\n croppedImg = image_by_cropping_to_center_size(CGSize.new((size.height/aSize.height * aSize.width).to_i, size.height))\n end\n\n croppedImg.scale_to_size(aSize)\n end", "def resample!(image, width, height)\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.resample \"#{width}x#{height}\"\n end\n end\n end", "def strict_resize image, w, h\n image.resize \"#{ w }x#{ h }!\"\n image\n end", "def large_process\n case [model.attachable_type, model.image_type]\n when ['User', 'avatar'] then\n resize_to_fill 1024, 683 # 3x2\n when ['User', 'inspiration'] then\n resize_to_fit 1024, 9999 # fixed width\n when ['Message', 'avatar'] then\n resize_to_fit 1024, 9999 # fixed width\n when ['Message', 'alternate'] then\n resize_to_fit 1024, 9999 # fixed width\n when ['Alternative', 'avatar'] then\n resize_to_fill 1024, 683 # 3x2\n else\n resize_to_fit 1024, 9999 # fixed width\n end\n # TODO: Test and implement this.\n # fix_exif_rotation\n quality 70\n end", "def resize_to_height(height)\n manipulate! do |img|\n if img.rows >= height\n # here we're sizing down, so the new width cannot be more than img.columns\n img.resize_to_fit!(img.columns, height)\n else\n # should rarely be called; here we're sizing up, so if we scale the height by height.fo_f / img.rows, then the new width\n # can't be more than 2 * (img.columns * (height.to_f / img.rows)).ceil, since aspect the aspect ratio is preserved. (The 2\n # is unncessary, and is just there to be safe ;)\n img.resize_to_fit!(2 * (img.columns * height.to_f / img.rows).ceil, height)\n end\n img = yield(img) if block_given?\n img\n end\n end", "def set_offer_image_dimensions\n if offer_image.queued_for_write[:full_size]\n geometry = Paperclip::Geometry.from_file(offer_image.queued_for_write[:full_size])\n self.offer_image_width = geometry.width\n self.offer_image_height = geometry.height\n end\n end", "def scale(factor=0.75, quality: nil)\n \n read() do |img|\n \n img2 = img.scale(factor) \n write img2, quality\n \n end\n \n end", "def resize(path, image, size)\n Rails.logger.warn \"resize method\"\n return false if size.split('x').count!=2\n Rails.logger.warn \"before File.exists? check: #{size.split('x').count}\"\n return false if !File.exists?(File.join(path))\n\n Rails.logger.warn \"before mkdir: #{path}/#{id}\"\n FileUtils.mkdir_p \"#{path}/thumbnails/#{id}\" if !File.exists?(File.join(path, 'thumbnails', id.to_s))\n\n image_original_path = \"#{path}/#{image}\"\n image_resized_path = \"#{path}/thumbnails/#{id}/#{size}_#{image}\"\n\n width = size.split('x')[0]\n height = size.split('x')[1]\n\n Rails.logger.warn \"Magick::Image.read(#{image_original_path})\"\n begin\n i = Magick::Image.read(image_original_path).first\n Rails.logger.warn \"before i.resize_to_fit\"\n i.resize_to_fit(width.to_i,height.to_i).write(image_resized_path)\n rescue Exception => e\n Rails.logger.error e\n end\n\n true\n end", "def calcImgSizes(res, file, maxheight, maxwidth, grid)\n myres = res.to_f\n myheight = `identify -format \"%h\" \"#{file}\"`\n myheight = myheight.to_f\n myheightininches = (myheight / myres)\n mywidth = `identify -format \"%w\" \"#{file}\"`\n mywidth = mywidth.to_f\n mywidthininches = (mywidth / myres)\n # if current height or width exceeds max, resize to max, proportionately\n if mywidthininches > maxwidth or myheightininches > maxheight then\n targetheight = maxheight * myres\n targetwidth = maxwidth * myres\n `convert \"#{file}\" -density #{myres} -resize \"#{targetwidth}x#{targetheight}>\" -quality 100 \"#{file}\"`\n end\n myheight = `identify -format \"%h\" \"#{file}\"`\n myheight = myheight.to_f\n myheightininches = (myheight / myres)\n mymultiple = ((myheight / myres) * 72.0) / grid\n if mymultiple <= 1\n resizecmd = \"\"\n else\n newheight = ((mymultiple.floor * grid) / 72.0) * myres\n resizecmd = \"-resize \\\"x#{newheight}\\\" \"\n end\n return resizecmd\nrescue => e\n return \"error method calcImgSize: #{e}\"\nend", "def set_image_dimensions\n\t\tif !self.image_width.is_a?(Numeric) || !self.image_file_name.nil?\t \n\t\t if !image.queued_for_write[:original].nil?\n\t\t geo = Paperclip::Geometry.from_file(image.queued_for_write[:original])\n\t\t self.image_width = geo.width\n\t\t self.image_height = geo.height\n\t\t end\n\t\tend\n\tend", "def resize_image(image, options = {})\n processor = ::RedArtisan::CoreImage::Processor.new(image)\n size = options[:size]\n size = size.first if size.is_a?(Array) && size.length == 1\n if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))\n if size.is_a?(Fixnum)\n processor.fit(size)\n else\n processor.resize(size[0], size[1])\n end\n else\n new_size = get_image_size(image) / size.to_s\n processor.resize(new_size[0], new_size[1])\n end\n \n destination = options[:to] || @file\n AttachmentFu::Pixels::Image.new destination do |img|\n processor.render do |result|\n img.width, img.height = get_image_size(result)\n result.save destination, OSX::NSJPEGFileType\n end\n end\n end", "def scale_within(new_size)\n target_size = SugarCube::CoreGraphics::Size(new_size)\n image_size = self.size\n\n if CGSizeEqualToSize(target_size, self.size)\n return self\n end\n\n width = image_size.width\n height = image_size.height\n\n target_width = target_size.width\n target_height = target_size.height\n\n width_factor = target_width / width\n height_factor = target_height / height\n\n if width_factor < height_factor\n scale_factor = width_factor\n else\n scale_factor = height_factor\n end\n\n if scale_factor == 1\n return self\n end\n\n scaled_size = CGSize.new(width * scale_factor, height * scale_factor)\n return scale_to(scaled_size)\n end", "def resizeImageFocus(width,height)\n if @imageFocus != nil\n @imageFocus.resize(width,height)\n end\n end", "def set_size(params = {})\n @width = params[:width] if params[:width]\n @height = params[:height] if params[:height]\n @x_scale = params[:x_scale] if params[:x_scale]\n @y_scale = params[:y_scale] if params[:y_scale]\n @x_offset = params[:x_offset] if params[:x_offset]\n @y_offset = params[:y_offset] if params[:y_offset]\n end", "def resize\n @image.resize \"#{@placement[:a]}x#{OUTER}\\!\"\n end", "def fit_graphics(*args)\n @p.fit_graphics(self, *args)\n end", "def resize_image\n unless logo.nil?\n if logo.height != 100\n self.logo = logo.thumb('x100') # resize height and maintain aspect ratio\n end\n end\n end", "def fit1(x_crate, y_crate, x_box, y_box)\n\n x_axis_fit = x_crate / x_box\n y_axis_fit = y_crate / y_box\n\n total_fit = x_axis_fit * y_axis_fit\n\n return total_fit\n\nend", "def fit; end", "def tile_crop_resize(image, dpi)\n size = {\n 'x' => image.columns,\n 'y' => image.rows\n }\n\n resize = false\n\n ['x', 'y'].each do |a|\n if (@field['size' + a])\n size[a] = @field['size' + a]*dpi\n resize = true\n end\n end\n\n if (@field['tile'])\n image = tile_image(image, dpi) if @field['tile']\n elsif (resize)\n scaleX = size['x']/image.columns\n scaleY = size['y']/image.rows\n\n scale = scaleX\n scale = scaleY if scaleY > scaleX\n\n image.resize!(image.columns*scale, image.rows*scale, Magick::LanczosFilter, 0.7)\n end\n\n image.crop!(Magick::CenterGravity, size['x'], size['y']) if (@field['crop'])\n\n return image\n end", "def set_dimensions!\n if RMAGICK_SUPPORTED\n #MES- Turn the blob into an ImageMagick object\n img = Magick::Image.from_blob(data).first\n if img.nil?\n raise \"Error: could not get imagemagick image from picture #{self.id}'s data\"\n end\n \n #KS- grab width & height and save them\n self.height = img.rows\n self.width = img.columns\n end\n end", "def resize_image(img, size)\n size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)\n if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))\n size = [size, size] if size.is_a?(Fixnum)\n img.thumbnail!(*size)\n elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75\n dimensions = size[1..size.size].split(\"x\")\n img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i)\n elsif size.is_a?(String) && size =~ /^b.*$/ # Resize w/border - example geometry string: b75x75\n dimensions = size[1..size.size].split(\"x\")\n img.change_geometry(dimensions.join(\"x\")) do |cols, rows, image|\n image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows )\n end\n img.background_color = \"black\"\n x_offset = (img.columns - dimensions[0].to_i) / 2\n y_offset = (img.rows - dimensions[1].to_i) / 2\n img = img.extent(dimensions[0].to_i, dimensions[1].to_i, x_offset, y_offset)\n else\n img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) }\n end\n img.strip! unless attachment_options[:keep_profile]\n temp_paths.unshift write_to_temp_file(img.to_blob)\n end", "def set_rect(width, height)\n @width, @height = width, height\n zoom_x, zoom_y = (@width.to_f/@image_w.to_f)*@scale[0], (@height.to_f/@image_h.to_f)*@scale[1]\n @background.zoom_x, @background.zoom_y = zoom_x, zoom_y\n if @frame then @frame.zoom_x, @frame.zoom_y = zoom_x, zoom_y end\n end", "def create_resized_image\n create_image do |xfrm|\n if size\n xfrm.flatten\n xfrm.resize(size)\n end\n end\n end", "def resize(path)\n gravity = @options.key?(:gravity) ? @options[:gravity] : 'Center'\n\n img = MiniMagick::Image.open(@file)\n cols, rows = img[:dimensions]\n\n img.combine_options do |cmd|\n if @width != cols || @height != rows\n scale_x = @width/cols.to_f\n scale_y = @height/rows.to_f\n\n if scale_x >= scale_y\n cols = (scale_x * (cols + 0.5)).round\n rows = (scale_x * (rows + 0.5)).round\n cmd.resize \"#{cols}\"\n else\n cols = (scale_y * (cols + 0.5)).round\n rows = (scale_y * (rows + 0.5)).round\n cmd.resize \"x#{rows}\"\n end\n end\n\n cmd.quality @options[:quality] if @options.key?(:quality)\n cmd.gravity gravity\n cmd.background 'rgba(255,255,255,0.0)'\n cmd.extent \"#{@width}x#{@height}\" if cols != @width || rows != @height\n end\n\n img.write(path)\n end", "def setSize(width, height)\n setWidth(width)\n setHeight(height)\n end" ]
[ "0.7722023", "0.7651965", "0.7620072", "0.75771636", "0.75520515", "0.734139", "0.7337059", "0.73110384", "0.72737026", "0.7128217", "0.7128217", "0.7058629", "0.6775835", "0.6749554", "0.672748", "0.66617566", "0.66500825", "0.65700096", "0.65528005", "0.6536908", "0.6467356", "0.63933474", "0.63416964", "0.63365006", "0.63088286", "0.62894833", "0.6133283", "0.6125582", "0.60910815", "0.60634685", "0.60596806", "0.60440594", "0.60230905", "0.5989219", "0.5972356", "0.5970145", "0.5941839", "0.5929867", "0.59246504", "0.59188074", "0.59133893", "0.58962137", "0.5892885", "0.5882902", "0.58682525", "0.58637327", "0.5850027", "0.5817592", "0.5767817", "0.57537025", "0.5750191", "0.57487786", "0.5738126", "0.571685", "0.562768", "0.5627611", "0.5619635", "0.56025463", "0.5600769", "0.55964124", "0.5592516", "0.5555178", "0.55519944", "0.5547257", "0.5540109", "0.55399555", "0.5539222", "0.55297613", "0.55067056", "0.5505982", "0.5500065", "0.5488969", "0.5483633", "0.54749745", "0.5465918", "0.54469675", "0.54396266", "0.54328716", "0.54287", "0.5424959", "0.5402728", "0.53945345", "0.53905755", "0.5380259", "0.53621686", "0.53589416", "0.5349666", "0.53482985", "0.5347131", "0.5344616", "0.5337127", "0.5332387", "0.5320316", "0.53176534", "0.5314895", "0.5295732", "0.5295031", "0.529405", "0.528808", "0.52849686", "0.52827257" ]
0.0
-1
:callseq: crop(width, height, x_offset = 0, y_offset = 0) Crops the image and extracts regions. If the region extends beyond the boundaries of the image then the cropped image will be truncated at the boundaries. == Example i = Axon::JPEG('test.jpg') i.crop(50, 75, 10, 20) c.width => 50 c.height => 75 == Example of Cropping Past the Boundaries i = Axon::JPEG('test.jpg') i.crop(50, 75, 60, 20) i.width => 40 note that this is not 50
def crop(*args) @source = Cropper.new(@source, *args) self end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cropper(crop_width, crop_height)\n manipulate! do |img|\n width = img.columns\n height= img.rows\n if width == crop_width and height==crop_height then\n img\n else\n img.crop(width / 2,height / 2,crop_width,crop_height)\n end\n end\n end", "def crop!(image, width, height, x_offset = 0, y_offset = 0, gravity: \"NorthWest\")\n with_minimagick(image) do |img|\n img.combine_options do |cmd|\n yield cmd if block_given?\n cmd.gravity gravity\n cmd.crop \"#{width}x#{height}+#{x_offset}+#{y_offset}\"\n end\n end\n end", "def execute_crop(image, crop, x, y, width, height)\n require 'RMagick'\n # load in the original image\n old_image = Magick::Image::read(self.send(image).path).first\n # crop it at the desired position\n new_image = old_image.crop(x.to_i, y.to_i, width.to_i, height.to_i, true)\n # scale the image to the correct size if needed\n desired_width, desired_height = Image.detailed_dimensions(self.class, image, crop)\n if desired_width\n clean_desired_width = desired_width.gsub(/\\D/, '').to_f\n if desired_width.include?('>')\n new_image.scale!(clean_desired_width/width.to_f) if (width > clean_desired_width)\n elsif desired_width.include?('^')\n new_image.scale!(clean_desired_width/width.to_f) if (width < clean_desired_width)\n else\n new_image.scale!(clean_desired_width/width.to_f)\n end\n elsif desired_height\n clean_desired_height = desired_height.gsub(/\\D/, '').to_f\n if desired_height.include?('>')\n new_image.scale!(clean_desired_height/height.to_f) if (height > clean_desired_height)\n elsif desired_height.include?('^')\n new_image.scale!(clean_desired_height/height.to_f) if (height < clean_desired_height)\n else\n new_image.scale!(clean_desired_height/height.to_f)\n end\n end\n \n # need to make sure the image is the size it wanted to be in the first place as a pixel or 2 can b lost in the maths from the views\n # only do this if the requested dims allow it.\n if desired_width.to_i != 0 && desired_height.to_i != 0\n new_image.scale!(desired_width.to_i, desired_height.to_i)\n end\n \n FileUtils.mkdir_p(File.dirname(self.send(image).path(crop).to_s))\n new_image.write(self.send(image).path(crop).to_s)\n end", "def with_crop(left, top, right, bottom); end", "def crop\n return if model.crop_x.blank?\n resize_to_limit(300, 300)\n manipulate! do |img|\n x = model.crop_x.to_i\n y = model.crop_y.to_i\n w = model.crop_w.to_i\n h = model.crop_h.to_i\n img.crop!(x, y, w, h)\n end\n end", "def crop!(left: 0, top: 0, width: nil, height: nil)\n manipulate! do |image|\n begin\n do_crop image, left, top, width, height\n rescue VIPS::Error => e\n e.message =~ /extract_area/ ? image : raise(e)\n end\n end\n end", "def crop image, x0 = 0, y0 = 0, w = 100, h = 100, scale = 1\n x0 = (x0.to_f * scale).to_i\n y0 = (y0.to_f * scale).to_i\n\n w = (w.to_f * scale).to_i\n h = (h.to_f * scale).to_i\n\n image.crop \"#{ w }x#{ h }+#{ x0 }+#{ y0 }\"\n image\n end", "def crop(crop, input=nil, output=nil)\n inout \"crop=x=%{left}:y=%{top}:w=%{width}:h=%{height}\", input, output, crop\n end", "def cut\n rmagick_img.crop_resized!(@x, @y, gravity)\n end", "def crop_to(width, height)\n # Checks that crop area is defined and crop should be done.\n if ((crop_args[0] == crop_args[2]) || (crop_args[1] == crop_args[3]))\n # If not creates default image and saves it's dimensions.\n resize_to_fill_and_save_dimensions(width, height)\n else\n args = crop_args + [width, height]\n crop_and_resize(*args)\n end\n end", "def crop\n return unless model.can_be_cropped?\n manipulate! do |image|\n image.combine_options do |command|\n command.crop(model.magick_thumbnail_coordinates)\n end\n image\n end\n end", "def crop(x, y, crop_width, crop_height)\n dup.crop!(x, y, crop_width, crop_height)\n end", "def cut_image(source, width, height, dest = nil)\r\n dest ||= default_dest(source, \"cut\")\r\n image = MiniMagick::Image.from_file(source)\r\n image.crop \"#{width}x#{height}+0+0\"\r\n image.write dest\r\n dest\r\n end", "def crop!(x,y,width,height)\n @x, @y, @w, @h = x, y, width, height\n self\n end", "def crop_to_fit(width, height)\n @image = @image.crop_to_fit(width, height)\n self\n end", "def crop(*args)\n with_command %(-crop \"#{Geometry.new(*args).to_s(true)}\")\n end", "def cropping_mask\n return if crop_from.blank? || crop_size.blank?\n\n crop_from = point_from_string(read_attribute(:crop_from))\n crop_size = sizes_from_string(read_attribute(:crop_size))\n\n point_and_mask_to_points(crop_from, crop_size)\n end", "def magick_crop_rect\n [x1, y1, x2-x1, y2-y1]\n end", "def crop!(x, y, w, h)\n prefull, orig = model.actual_dimensions(:prefull), model.actual_dimensions\n ratio = [orig[0].to_f / prefull[0], orig[1].to_f / prefull[1]].min\n x, y, w, h = [x, y, w, h].map { |n| (n * ratio).floor }\n manipulate! do |img|\n img.crop \"#{w}x#{h}+#{x}+#{y}\"\n img = yield(img) if block_given?\n img\n end\n end", "def setCropArea(x, y, width, height)\n setCropAreaX(x)\n setCropAreaY(y)\n setCropAreaWidth(width)\n setCropAreaHeight(height)\n self\n end", "def setCropArea(x, y, width, height)\n setCropAreaX(x)\n setCropAreaY(y)\n setCropAreaWidth(width)\n setCropAreaHeight(height)\n self\n end", "def setCropArea(x, y, width, height)\n setCropAreaX(x)\n setCropAreaY(y)\n setCropAreaWidth(width)\n setCropAreaHeight(height)\n self\n end", "def crop\n block = block_given? ? Proc.new : Arigatomation::LUMINANCE\n left_x, right_x, top_y, bottom_y = lrc.x, ulc.x, lrc.y, ulc.y\n changed = false\n\n each do |point|\n if !block.call(self[point])\n changed = true\n left_x = point.x if point.x < left_x\n right_x = point.x if point.x > right_x\n top_y = point.y if point.y < top_y\n bottom_y = point.y if point.y > bottom_y\n end\n end\n\n return self unless changed\n $log.debug \"CROPPED to #{[left_x, top_y, right_x, bottom_y].join(\", \")}\"\n capture(Arigatomation::Point.new(left_x, top_y), Arigatomation::Point.new(right_x, bottom_y))\n rescue\n $log.error \"Crop error: #{$!}\"\n end", "def cropping_mask\n return if crop_from.blank? || crop_size.blank?\n crop_from = read_attribute(:crop_from).split('x')\n crop_size = read_attribute(:crop_size).split('x')\n {\n x1: crop_from[0].to_i,\n y1: crop_from[1].to_i,\n x2: crop_from[0].to_i + crop_size[0].to_i,\n y2: crop_from[1].to_i + crop_size[1].to_i\n }\n end", "def crop(rect)\n if self.scale > 1.0\n rect = CGRectMake(rect.origin.x * self.scale,\n rect.origin.y * self.scale,\n rect.size.width * self.scale,\n rect.size.height * self.scale)\n end\n\n cgimage = CGImageCreateWithImageInRect(self.CGImage, rect)\n result = UIImage.imageWithCGImage(cgimage, scale:self.scale, orientation:self.imageOrientation)\n\n return result\n end", "def extract_image(coords)\n @image.crop(*coords, true)\n end", "def resize_and_crop(size) \n manipulate! do |image| \n if image[:width] < image[:height]\n remove = (image[:height] - 135).round \n image.shave(\"0x#{remove}\") \n elsif image[:width] > image[:height] \n remove = ((image[:width] - image[:height])/2).round\n image.shave(\"#{remove}x0\")\n end\n image.resize(\"#{size}\")\n image\n end\n end", "def crop(x, y, w, h)\n clone.crop!(x, y, w, h)\n end", "def crop_avatar(args)\n self.crop_x = args[\"crop_x\"]\n self.crop_y = args[\"crop_y\"]\n self.crop_w = args[\"crop_w\"]\n self.crop_h = args[\"crop_h\"]\n avatar.reprocess!\n end", "def extract_image(coords)\n i = @image.crop(*coords, true)\n end", "def crop(quality = 80)\n result = image.combine_options do |img|\n img.quality quality.to_s\n img.crop dimensions\n end\n File.open result.path\n end", "def crop(area)\n reset_meta_data\n segments.each do |seg|\n seg.crop(area)\n update_meta_data(seg) unless seg.empty?\n end\n segments.delete_if { |seg| seg.empty? }\n end", "def cover_and_crop(new_width, new_height, &block)\n scale_to_cover(new_width, new_height) do |scaled|\n return block.call(scaled) if new_width == scaled.width && new_height == scaled.height\n scaled.crop_to(new_width || width, new_height || height, &block)\n end\n end", "def side_crop side, rowcol, image, starting, outimage=nil\n m_begin \"side_crop\"\n raise \"number expected\" unless starting.class == Fixnum\n raise \"side wrong: #{side}\" unless [:top, :bottom, :left, :right].member? side\n raise \"rowcol wrong: #{rowcol}\" unless [:row, :column].member? rowcol\n img = get_image(image)\n case [side, rowcol]\n when [:left, :column]\n cropped = img.excerpt(starting, 0, img.columns-starting, img.rows)\n when [:right, :column]\n cropped = img.excerpt(0, 0, img.columns-starting, img.rows)\n when [:top, :row]\n cropped = img.excerpt(0, starting, img.columns, img.rows-starting)\n when [:bottom, :row]\n cropped = img.excerpt(0, 0, img.columns, img.rows-starting)\n else\n raise \"invalid rowcol and side combination\"\n end\n outimage = image if outimage.nil?\n put_image(outimage, cropped)\n m_end \"side_crop\"\n end", "def crop?\n @crop\n end", "def crop?\n @crop\n end", "def resize_and_crop(size)\n manipulate! do |image|\n Rails.logger.error '----------- image:'\n Rails.logger.error image.inspect\n\n if image[:width] < image[:height]\n remove = ((image[:height] - image[:width]) / 2).round\n image.shave(\"0x#{remove}\")\n elsif image[:width] > image[:height]\n remove = ((image[:width] - image[:height]) / 2).round\n image.shave(\"#{remove}x0\")\n end\n image.resize(\"#{size}x#{size}\")\n image\n end\n end", "def crop(t, l, b, r)\n orig_w = orig_h = 460\n new_w = r - l\n new_h = t - b\n o_x = l\n o_y = orig_h - t\n geom = \"#{new_w.round}x#{new_h.round}+#{o_x.round}+#{o_y.round}\"\n `convert #{@fn} -crop #{geom} +repage #{@fn}`\n end", "def crop_top_rows image, starting_row, outimage=nil\n raise \"number expected\" unless starting_row.class == Fixnum\n m_begin \"crop_top_rows\"\n img = get_image(image)\n cropped = img.excerpt(0, starting_row, img.columns, img.rows-starting_row)\n outimage = image if outimage.nil?\n put_image(outimage, cropped)\n m_end \"crop_top_rows\"\n end", "def manualcrop\n if model.crop?\n x = model.x.to_d\n y = model.y.to_d\n x2 = model.x2.to_d\n y2 = model.y2.to_d\n scale = model.scale.to_d\n\n manipulate! do |img|\n img = img.scale(1/scale)\n img = img.crop(x, y, x2-x, y2-y)\n end\n end\n end", "def crop(geometry, anchor = :mc, anchor_y = nil)\n \t if anchor.is_a?(Symbol)\n easy_crop(geometry, anchor)\n\t else\n\t manual_crop(geometry, anchor, anchor_y)\n end\n \tend", "def square_image_crop\n if (self.crops)\n if !(self.crop_x.nil? || self.crop_y.nil? || self.crop_w.nil? || self.crop_h.nil?)\n @image = MiniMagick::Image.open(self.photo.url)\n # if image is larger than our max screen size, the cropped image will be incorrect (resizing)\n @image.sample(((700/@image[:width].to_f) * 100).to_s + \"%\") if @image[:width] > 700\n @image.crop(\"#{self.crop_w}x#{self.crop_h}+#{self.crop_x}+#{self.crop_y}\")\n @image.set(\"page\", \"#{self.crop_w}x#{self.crop_h}+#{self.crop_x}+#{self.crop_y}\") \n self.square_image = @image\n end\n end\n end", "def max_crop_area_growth(crop_from, crop_size)\n {\n top: crop_from[:y],\n right: image_size[:width] - crop_from[:x] - crop_size[:width],\n bottom: image_size[:height] - crop_from[:y] - crop_size[:height],\n left: crop_from[:x],\n }\n end", "def crop! (xoff, yoff, width, height)\n @transforms << \"CR#{xoff},#{yoff},#{width},#{height}\"\n self\n end", "def crop_from_after_crop_area_resize(crop_from, crop_size, old_crop_size, gravity)\n if old_crop_size[:width] != crop_size[:width]\n case gravity[:x]\n # No adjustment when left\n when \"center\"\n crop_from[:x] += (old_crop_size[:width] - crop_size[:width]) / 2\n when \"right\"\n crop_from[:x] += old_crop_size[:width] - crop_size[:width]\n end\n end\n\n if old_crop_size[:height] != crop_size[:height]\n case gravity[:y]\n # No adjustment when top\n when \"center\"\n crop_from[:y] += (old_crop_size[:height] - crop_size[:height]) / 2\n when \"bottom\"\n crop_from[:y] += old_crop_size[:height] - crop_size[:height]\n end\n end\n\n crop_from\n end", "def resize(width, height, resize_method)\n cropping = (resize_method != :resize_scale)\n\n # Calculate aspect ratios\n source_ratio = size.width / size.height\n target_ratio = width / height\n\n # Determine what side of the source image to use for proportional scaling\n scale_width = (source_ratio <= target_ratio)\n\n # Proportionally scale source image\n scaled_width, scaled_height = nil, nil\n if cropping && scale_width\n scaling_factor = 1.0 / source_ratio\n scaled_width = width\n scaled_height = (width * scaling_factor).round\n else\n scaling_factor = source_ratio\n scaled_width = (height * scaling_factor).round\n scaled_height = height\n end\n scale_factor = scaled_height / size.height\n\n # Calculate compositing rectangles\n source_rect = nil\n if cropping\n dest_x, dest_y = nil, nil\n case resize_method\n when :resize_crop\n # Crop center\n dest_x = ((scaled_width - width) / 2.0).round\n dest_y = ((scaled_height - height) / 2.0).round\n when :resize_crop_start\n # Crop top or left (prefer top)\n if scale_width\n # Crop top\n dest_x = ((scaled_width - width) / 2.0).round\n dest_y = (scaled_height - height).round\n else\n # Crop left\n dest_x = 0.0\n dest_y = ((scaled_height - height) / 2.0).round\n end\n when :resize_crop_end\n # Crop bottom or right\n if scale_width\n # Crop bottom\n dest_x = 0.0\n dest_y = 0.0\n else\n # Crop right\n dest_x = (scaled_width - width).round\n dest_y = ((scaled_height - height) / 2.0).round\n end\n end\n source_rect = [dest_x / scale_factor, dest_y / scale_factor, width / scale_factor, height / scale_factor]\n else\n width = scaled_width\n height = scaled_height\n source_rect = [0, 0, size.width, size.height]\n end\n\n result = OSX::NSImage.alloc.initWithSize([width, height])\n result.lockFocus\n OSX::NSGraphicsContext.currentContext.setImageInterpolation(OSX::NSImageInterpolationHigh)\n drawInRect_fromRect_operation_fraction([0, 0, width, height], source_rect, OSX::NSCompositeSourceOver, 1.0)\n result.unlockFocus\n result\n end", "def crop!(x, y, w, h)\n ptr = self.class.create_image_ptr(w, h, alpha_blending?)\n ::GD2::GD2FFI.send(:gdImageCopy, ptr, image_ptr, 0, 0, x.to_i, y.to_i, w.to_i, h.to_i)\n init_with_image(ptr)\n end", "def recreate_cropped_image\n if file.exists?\n img = ThumbMagick::Image.new(file.path('tocrop'))\n img.\n thumbnail(\"#{ (resize * 100).to_i }%\").\n crop(\"#{crop_w}x#{crop_h}\", crop_x, crop_y).\n write(file.path('cropped'))\n end \n end", "def validate_rect image, width, height, x1, x2, y1, y2\n begin\n assert x1 >= 0\n assert x2 >= 0\n assert x1 <= image.width\n assert x2 <= image.width\n assert x1 <= x2\n assert y1 >= 0\n assert y2 >= 0\n assert y1 <= image.height\n assert y2 <= image.height\n assert y1 <= y2\n rescue => e\n raise ManagedImage::InvalidCropError, \"Crop coordinates #{x1}, #{x2}, #{y1}, #{y2} is invalid for image with size #{image.width}x#{image.height}\"\n end\n end", "def crop_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :GET, 'File')\n end", "def crop_bgimg\n if crop_x.present?\n bgimg.cache_stored_file!\n bgimg.retrieve_from_cache!(bgimg.cache_name)\n bgimg.recreate_versions!\n end\n end", "def crop_rows!\n if crop\n local_copy.in_place :tail, \"+#{crop.first}\"\n local_copy.in_place :head, (crop.last - crop.first + 1)\n end\n end", "def easy_crop(geometry, anchor)\n ow,oh = dimensions # Before crop\n \t w,h = geometry.strip.split('x').map{|n|n.to_i} # Target dimensions\n \t\tanchor_x, anchor_y = case anchor\n \t\t\twhen :tl\n \t\t\t\t[ 0 , 0 ]\n \t\t\twhen :tc\n \t\t\t\t[ ((ow - w) / 2.0).round , 0]\n \t\t\twhen :tr\n \t\t\t\t[ ow - w , 0 ]\n \t\t\twhen :ml\n \t\t\t\t[ 0 , ((oh - h) / 2.0).round ]\n \t\t\twhen :mc\n \t\t\t\t[ ((ow - w) / 2.0).round , ((oh - h) / 2.0).round ]\n \t\t\twhen :mr\n \t\t\t\t[ ow - w , ((oh - h) / 2.0).round ]\n \t\t\twhen :bl\n \t\t\t\t[ 0 , oh - h]\n \t\t\twhen :bc\n \t\t\t\t[ ((ow - w) / 2.0).round , oh - h ]\n \t\t\twhen :br\n \t\t\t\t[ ow - w , oh - h]\n \t\tend\n \t\tmanual_crop(geometry, anchor_x, anchor_y)\n\t end", "def shrink_crop_area(size, crop_size)\n if has_wider_aspect_ratio?(size, crop_size) # => requested wider size, shrink y\n crop_size[:height] = crop_size[:height] * aspect_ratio(crop_size) / aspect_ratio(size)\n else # => shrink x\n crop_size[:width] = crop_size[:width] * aspect_ratio(size) / aspect_ratio(crop_size)\n end\n\n round_dimensions(crop_size)\n end", "def crop_insets(number)\n jpg_path = $jpg_path.gsub(\"{CHART_NUMBER}\", number.to_s)\n preprocessed_jpg_path = $preprocessed_jpg_path.gsub(\"{CHART_NUMBER}\", number.to_s)\n \n res = $dbh.query(\"SELECT * FROM ocpn_nga_charts WHERE number=#{number}\")\n\n while row = res.fetch_hash do\n puts \"Cropping insets and generating their corners for chart #{row[\"number\"]}\"\n \n # If rotated, use preprocessed JPG\n if (row[\"prerotate\"].to_i != 0)\n jpg = preprocessed_jpg_path\n else\n jpg = jpg_path\n end\n end\n res = $dbh.query(\"SELECT *, (SELECT MIN(x) FROM ocpn_nga_kap_point WHERE point_type='CROP' AND active=1 AND kap_id=k.kap_id) AS x, (SELECT MAX(x) FROM ocpn_nga_kap_point WHERE point_type='CROP' AND active=1 AND kap_id=k.kap_id) AS x1, (SELECT MIN(y) FROM ocpn_nga_kap_point WHERE point_type='CROP' AND active=1 AND kap_id=k.kap_id) AS y, (SELECT MAX(y) FROM ocpn_nga_kap_point WHERE point_type='CROP' AND active=1 AND kap_id=k.kap_id) AS y1 FROM ocpn_nga_kap k WHERE bsb_type!='BASE' AND active=1 AND number=#{number}\")\n while row = res.fetch_hash do\n corner_size = row[\"cornersize\"]\n puts corner_size\n # check whether the data entered are ok\n if(row[\"x\"].to_i >= 0 && row[\"y\"].to_i >= 0 && row[\"x1\"].to_i > row[\"x\"].to_i && row[\"y1\"].to_i > row[\"y\"].to_i)\n inset_path = $inset_path.gsub(\"{CHART_NUMBER}\", number.to_s).gsub(\"{INSET}\", row[\"inset_id\"])\n `#{$convert_command} #{jpg} -crop #{row[\"x1\"].to_i - row[\"x\"].to_i}x#{row[\"y1\"].to_i - row[\"y\"].to_i}+#{row[\"x\"]}+#{row[\"y\"]} #{inset_path}`\n \n # create corner cut-outs\n corner_path = $corner_path.gsub(\"{CHART_NUMBER}\", number.to_s).gsub(\"{INSET}\", row[\"inset_id\"]).gsub(\"{CORNER}\", 'sw')\n `#{$convert_command} #{inset_path} -gravity SouthWest -crop #{corner_size}x#{corner_size}+0+0 -depth 8 -type Palette -colors 32 png8:#{corner_path}`\n corner_path = $corner_path.gsub(\"{CHART_NUMBER}\", number.to_s).gsub(\"{INSET}\", row[\"inset_id\"]).gsub(\"{CORNER}\", 'nw')\n `#{$convert_command} #{inset_path} -gravity NorthWest -crop #{corner_size}x#{corner_size}+0+0 -depth 8 -type Palette -colors 32 png8:#{corner_path}`\n corner_path = $corner_path.gsub(\"{CHART_NUMBER}\", number.to_s).gsub(\"{INSET}\", row[\"inset_id\"]).gsub(\"{CORNER}\", 'ne')\n `#{$convert_command} #{inset_path} -gravity NorthEast -crop #{corner_size}x#{corner_size}+0+0 -depth 8 -type Palette -colors 32 png8:#{corner_path}`\n corner_path = $corner_path.gsub(\"{CHART_NUMBER}\", number.to_s).gsub(\"{INSET}\", row[\"inset_id\"]).gsub(\"{CORNER}\", 'se')\n `#{$convert_command} #{inset_path} -gravity SouthEast -crop #{corner_size}x#{corner_size}+0+0 -depth 8 -type Palette -colors 32 png8:#{corner_path}`\n \n $dbh.query(\"UPDATE ocpn_nga_kap SET cropped=CURRENT_TIMESTAMP() WHERE kap_id=#{row[\"kap_id\"]}\")\n end\n end\n end", "def image_by_cropping_to_rect(aRect)\n if aRect.is_a? CGRect\n cropped = CGImageCreateWithImageInRect(self.CGImage, [[aRect.origin.x*self.scale, aRect.origin.y*self.scale], [aRect.size.width*self.scale, aRect.size.height*self.scale]])\n else\n cropped = CGImageCreateWithImageInRect(self.CGImage, [[aRect[0][0]*self.scale, aRect[0][1]*self.scale], [aRect[1][0]*self.scale, aRect[1][1]*self.scale]])\n end\n UIImage.imageWithCGImage(cropped, scale:self.scale, orientation:self.imageOrientation)\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?\n end", "def crop_selector driver, selector, image_location\n el = driver.find_element(:css, selector)\n image = MiniMagick::Image.open(image_location)\n image.crop \"#{el.rect.width}x#{el.rect.height}+#{el.rect.x}+#{el.rect.y}\"\n image.write(image_location)\n end", "def cropping?\n !!crop_x and !!crop_y and !!crop_w and !!crop_h\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_ratio.blank?\n end", "def thumb_crop\n { x: model.profile_image_crop_param_x,\n y: model.profile_image_crop_param_y,\n width: model.profile_image_crop_param_width,\n height: model.profile_image_crop_param_height,\n crop: :crop\n }\n end", "def crop\n return unless model.cropping?\n manipulate! do |img|\n if original_filename.present? && File.extname(original_filename) == '.png'\n image_png = PngQuantizator::Image.new(model.send(mounted_as).path)\n image_png.quantize_to(model.send(mounted_as).path)\n else\n Piet.optimize(model.send(mounted_as).path, :quality => 50)\n end\n image ||= ::Magick::Image::read(model.send(mounted_as).path).first\n x = model.crop_x.to_i * (model.rate.to_f)\n y = model.crop_y.to_i * model.rate.to_f\n w = model.crop_w.to_i * model.rate.to_f\n h = model.crop_h.to_i * model.rate.to_f\n image.crop!(x.to_i, y.to_i, w.to_i, h.to_i)\n end\n end", "def cropping?\n !crop_x.blank? and !crop_y.blank? and !crop_w.blank? and !crop_h.blank?\n end", "def crop\n @organization = Organization.find(params[:id])\n respond_with(@organization)\n end", "def cropping?\n !self.crop_x.blank? && !self.crop_y.blank? && !self.crop_w.blank? && !self.crop_h.blank?\n end", "def crop_logo\n logo.recreate_versions! if crop_logo_x.present?\n end", "def selectionRectChanged(imageView)\n if imageBrowserView.selectionIndexes.count == 1\n index = imageBrowserView.selectionIndexes.firstIndex\n images[index].crop = NSStringFromRect( imageView.selectionRect )\n end\n end", "def save_cropped_image(src, dest, x, y, width, height, quality = 75)\n if src.is_a? Magick::Image\n img = src\n else\n img = Magick::Image::read(src).first\n end\n\n quality = quality * 100 if quality < 1\n\n # The crop method retains the offset information in the cropped image.\n # To reset the offset data, adding true as the last argument to crop.\n cropped = img.crop(x, y, width, height, true)\n cropped.write(dest) { @quality = quality }\n end", "def crop(type)\n self.crops.find { |c| c.type == type }\n end", "def crop_older(cutofftime)\n \tcrop_at(normalize_time_input(cutofftime))\n end", "def create\n @crop = @image.crops.build(params[:crop])\n\n respond_to do |format|\n if @crop.save\n flash[:notice] = 'Crop was successfully created.'\n format.html { redirect_to([@image, :crops]) }\n format.xml { render :xml => @crop, :status => :created, :location => @crop }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @crop.errors, :status => :unprocessable_entity }\n end\n end\n end", "def edit_crop_rectangle(left, top, width, height, image_file, opts = {})\n data, _status_code, _headers = edit_crop_rectangle_with_http_info(left, top, width, height, image_file, opts)\n data\n end", "def resize_to_fill(new_width, new_height)\n manipulate! do |image|\n\n image = resize_image image, new_width, new_height, :max\n\n if image.x_size > new_width\n top = 0\n left = (image.x_size - new_width) / 2\n elsif image.y_size > new_height\n left = 0\n top = (image.y_size - new_height) / 2\n else\n left = 0\n top = 0\n end\n\n image.extract_area(left, top, new_width, new_height)\n\n end\n end", "def set_crop\n @crop = Crop.find(params[:id])\n end", "def set_crop\n @crop = Crop.find(params[:id])\n end", "def set_crop\n @crop = Crop.find(params[:id])\n end", "def crop_layer(other_layer, crop_type)\n if crop_type == \"uni\"\n Log.info \"Uni dimension intersection\"\n # More cases have to be handled.\n new_bounds = self.bounds.outer_crop other_layer.bounds\n if self.type == Layer::LAYER_NORMAL\n left_offset = new_bounds.left - self.bounds.left\n top_offset = new_bounds.top - self.bounds.top\n self.crop_image_by_bounds(left_offset, top_offset, new_bounds.width, new_bounds.height)\n Log.info \"Cropped image #{self.extracted_image_path}\"\n end\n \n self.bounds = new_bounds\n self.initial_bounds = new_bounds\n end\n end", "def crop\n\n @project = Project.user_readable(current_user, params[:project_id])\n\n if @project\n\n @video = @project.videos.find(params[:photo_to_crop_id])\n @video.crop_x = params[:coordinates][:crop_x].to_i.to_s\n @video.crop_y = params[:coordinates][:crop_y].to_i.to_s\n @video.crop_w = params[:coordinates][:crop_w].to_i.to_s\n @video.crop_h = params[:coordinates][:crop_h].to_i.to_s\n\n if @video.image.reprocess!\n respond_to do |format|\n format.json { render :json => [:project_video_id => @video.id,\n refresh_photo_url: @video.image(:medium)\n ],\n :status => :ok }\n end\n\n else\n respond_to do |format|\n format.json { render :json => @video.errors, :status => :unprocessable_entity }\n end\n end\n\n else\n not_authorized\n end\n\n end", "def crop_canvas(c, h)\n return c.crop(0, 0, c.width, h) if c.height > h\n c\n end", "def crop(area)\n points.delete_if{ |pt| not area.contains? pt }\n end", "def can_be_cropped?\n thumbnail_coordinates.present? &&\n thumbnail_coordinates['x'].to_i > 0 &&\n thumbnail_coordinates['y'].to_i > 0 &&\n thumbnail_coordinates['h'].to_i > 0 &&\n thumbnail_coordinates['w'].to_i > 0\n end", "def can_be_cropped?\n thumbnail_coordinates.present? &&\n thumbnail_coordinates['x'].to_i > 0 &&\n thumbnail_coordinates['y'].to_i > 0 &&\n thumbnail_coordinates['h'].to_i > 0 &&\n thumbnail_coordinates['w'].to_i > 0\n end", "def resize_to_fill(width, height)\n manipulate! do |image|\n image = resize_image image, width, height, :max\n top = 0\n left = 0\n\n if image.x_size > width\n left = (image.x_size - width) / 2\n elsif image.y_size > height\n top = (image.y_size - height) / 2\n end\n\n image.extract_area left, top, width, height\n end\n self\n end", "def crop_and_save_image( image, ri )\n\n design_template = ri.version.design_template\n image_name = ri.image_name\n path = ri.get_path\n\n height = get_original_height( design_template, image_name )\n width = get_original_width( design_template, image_name )\n\n image = resize_with_crop( image, width.to_f, height.to_f )\n\n image.format 'png'\n # Any name will do, the AI script will just place all of the images\n # found in the collage folder.\n full_path = path + '/image.png'\n image.write( full_path )\n return true\n end", "def scale_crop=(v)\n Axlsx.validate_boolean v\n @scale_crop = v\n end", "def setCropAreaX(x)\n if (!(Integer(x) >= 0))\n raise Error.new(Pdfcrowd.create_invalid_value_message(x, \"setCropAreaX\", \"pdf-to-text\", \"Must be a positive integer number or 0.\", \"set_crop_area_x\"), 470);\n end\n \n @fields['crop_area_x'] = x\n self\n end", "def create_crop\n \n # Get source Fedora object\n begin\n image_id = params[:pid]\n LockedObject.obtain_lock(params[:pid], \"image - generate detail\", current_user.id) \n source_fedora_object = Multiresimage.find(image_id)\n \n authorize! :show, source_fedora_object\n \n # Get the new crop boundaries\n x=params[:x]\n y=params[:y]\n width=params[:width]\n height=params[:height]\n \n new_image = Multiresimage.new(:pid=>mint_pid(\"dil-local\"))\n #puts \"\\nNEW IMAGE: x:\" + x + \"y:\" + y + \"width:\" + width + \"height:\" + height + \"\\n\"\n\t #@dil_collection.set_collection_type('Multiresimage')\n\n # Get source SVG datastream\n source_svg_ds = source_fedora_object.DELIV_OPS \n \n # Get new SVG datastream\n new_svg_ds = new_image.DELIV_OPS \n\n # Get source <image> for copying\n image_node = source_svg_ds.find_by_terms(:svg_image)\n \n # Add the <image> object\n new_svg_ds.add_image(image_node)\n\n\t # Update SVG\n new_svg_ds.add_rect(x, y, width, height)\n \n #Add properties datastream with depositor (user) info\n new_image.apply_depositor_metadata(current_user.user_key)\n \n #new_svg_ds.dirty = true\n new_image.save!\n\n # Get source VRA datastream\n source_vra_ds = source_fedora_object.datastreams[\"VRA\"]\n #source_vra_image=source_vra_ds.find_by_terms(:vra) \n #vra_ds = new_image.VRA\n #vra_ds.add_image(source_vra_image)\n \n #copy VRA ds from source image object\n new_image.VRA.content = source_vra_ds.content\n \n #replace pid in VRA with crop's pid \n new_image.replace_pid_in_vra(image_id, new_image.pid)\n\t\n\t # Add [DETAIL] to title in VRA\n\t new_image.titleSet_display = new_image.titleSet_display << \" [DETAIL]\"\n\t\n \t # Add image and VRA behavior via their cmodels\n new_image.add_relationship(:has_model, \"info:fedora/inu:VRACModel\")\n new_image.add_relationship(:has_model, \"info:fedora/inu:imageCModel\")\n \n #Add isCropOf relationship to crop\n new_image.add_relationship(:is_crop_of, \"info:fedora/#{source_fedora_object.pid}\")\n \n #Add hasCrop relationship to image\n source_fedora_object.add_relationship(:has_crop, \"info:fedora/#{new_image.pid}\")\n source_fedora_object.save\n \n #Edit rightsMetadata datastream\n new_image.edit_users=[current_user.user_key]\n \n new_image.save\n \n #add the detail to the detail collection\n personal_collection_search_result = current_user.get_details_collection\n DILCollection.add_image_to_personal_collection(personal_collection_search_result, DIL_CONFIG['dil_details_collection'], new_image, current_user.user_key)\n\n # get the dil_collection pid from the referer\n if request.referer =~ /dil_collections/\n url_array = request.referer.split( '/' )\n dil_collections_index = url_array.find_index( 'dil_collections' )\n\n # get the dil_collection\n dil_collection = DILCollection.find( url_array[ dil_collections_index + 1 ] )\n # insert the detail if the current user is the collection owner\n dil_collection.insert_member( new_image ) if dil_collection.owner == current_user.uid\n dil_collection_url = \"/dil_collections/#{ dil_collection.pid }/#{ new_image.pid }\"\n end\n\n ensure\n LockedObject.release_lock(params[:pid])\n end\n\n destination_url = dil_collection_url || \"/multiresimages/\" + new_image.pid\n\n respond_to do |wants|\n wants.html { redirect_to url_for(:action=>\"show\", :controller=>\"multiresimages\", :id=>new_image.pid) }\n wants.xml { render :inline =>'<success pid=\"'+ destination_url + '\"/>' }\n end\n end", "def uncrop!(x1, y1 = x1, x2 = x1, y2 = y1)\n ptr = self.class.create_image_ptr(x1 + width + x2, y1 + height + y2, alpha_blending?)\n ::GD2::GD2FFI.send(:gdImageCopy, ptr, image_ptr, x1.to_i, y1.to_i, 0, 0, width.to_i, height.to_i)\n init_with_image(ptr)\n end", "def crop_params\n params.require(:crops).permit(:name, :description, :image)\n end", "def uncrop(x1, y1 = x1, x2 = x1, y2 = y1)\n clone.uncrop!(x1, y1, x2, y2)\n end", "def tile_crop_resize(image, dpi)\n size = {\n 'x' => image.columns,\n 'y' => image.rows\n }\n\n resize = false\n\n ['x', 'y'].each do |a|\n if (@field['size' + a])\n size[a] = @field['size' + a]*dpi\n resize = true\n end\n end\n\n if (@field['tile'])\n image = tile_image(image, dpi) if @field['tile']\n elsif (resize)\n scaleX = size['x']/image.columns\n scaleY = size['y']/image.rows\n\n scale = scaleX\n scale = scaleY if scaleY > scaleX\n\n image.resize!(image.columns*scale, image.rows*scale, Magick::LanczosFilter, 0.7)\n end\n\n image.crop!(Magick::CenterGravity, size['x'], size['y']) if (@field['crop'])\n\n return image\n end", "def cut_to_fit(options)\n %Q{-thumbnail #{options.width}x#{options.height}^ \\\n -gravity #{options.gravity} \\\n -unsharp 0x.5 \\\n -auto-orient \\\n -extent #{options.width}x#{options.height}}\n end", "def setCropAreaX(x)\n unless /(?i)^0$|^[0-9]*\\.?[0-9]+(pt|px|mm|cm|in)$/.match(x)\n raise Error.new(Pdfcrowd.create_invalid_value_message(x, \"setCropAreaX\", \"image-to-image\", \"The value must be specified in inches \\\"in\\\", millimeters \\\"mm\\\", centimeters \\\"cm\\\", pixels \\\"px\\\", or points \\\"pt\\\".\", \"set_crop_area_x\"), 470);\n end\n \n @fields['crop_area_x'] = x\n self\n end", "def create_cropped_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :POST, 'File')\n end", "def setCropAreaWidth(width)\n unless /(?i)^0$|^[0-9]*\\.?[0-9]+(pt|px|mm|cm|in)$/.match(width)\n raise Error.new(Pdfcrowd.create_invalid_value_message(width, \"setCropAreaWidth\", \"image-to-image\", \"The value must be specified in inches \\\"in\\\", millimeters \\\"mm\\\", centimeters \\\"cm\\\", pixels \\\"px\\\", or points \\\"pt\\\".\", \"set_crop_area_width\"), 470);\n end\n \n @fields['crop_area_width'] = width\n self\n end", "def crops(image)\n image = image.to_sym\n if images[image][:styles].blank?\n {}\n else\n images[image][:styles].delete_if{|k,v| k == :sample}\n end\n end", "def slice_rect(slice, image_width, image_height)\n left = slice[:left]\n top = slice[:top]\n bottom = slice[:bottom]\n right = slice[:right]\n width = slice[:width]\n height = slice[:height]\n\n rect = {}\n\n if not left.nil?\n rect[:left] = left\n\n # in this case, it must be left+width or left+right, or left-to-end\n if not right.nil?\n rect[:width] = image_width - right - left\n elsif not width.nil?\n rect[:width] = width\n else\n # then this is left-to-end\n rect[:width] = image_width - left\n end\n elsif not right.nil?\n # in this case it must be right+width or right-to-end\n if not width.nil?\n rect[:left] = image_width - width - right\n rect[:width] = width\n else\n rect[:left] = image_width - right\n rect[:width] = right\n end\n else\n rect[:left] = 0\n rect[:width] = image_width\n end\n\n if not top.nil?\n rect[:top] = top\n\n # in this case, it must be top+height or top+bottom or top-to-bottom\n if not bottom.nil?\n rect[:height] = image_height - bottom - top\n elsif not height.nil?\n rect[:height] = height\n else\n rect[:height] = image_height - top\n end\n elsif not bottom.nil?\n # in this case it must be bottom+height\n if not height.nil?\n rect[:top] = image_height - height - bottom\n rect[:height] = height\n else\n rect[:top] = image_height - bottom\n rect[:height] = bottom\n end\n else\n rect[:top] = 0\n rect[:height] = image_height\n end\n\n if rect[:left] == 0 and rect[:top] == 0 and rect[:width] == image_width and rect[:height] == image_height\n return nil\n end\n\n return rect\n end" ]
[ "0.7682654", "0.76611024", "0.741268", "0.7372462", "0.73018813", "0.72667557", "0.70802885", "0.7049784", "0.70281863", "0.6989052", "0.68854666", "0.682947", "0.6705565", "0.66106725", "0.65904933", "0.65126276", "0.6457028", "0.6446116", "0.6355576", "0.6315622", "0.6315622", "0.63140064", "0.62856203", "0.6275987", "0.6271951", "0.6253086", "0.62426716", "0.62067586", "0.6204604", "0.61957735", "0.61765164", "0.61423254", "0.614185", "0.6129597", "0.60965633", "0.60965633", "0.6056701", "0.60452825", "0.6044097", "0.6036015", "0.602705", "0.60187364", "0.59966373", "0.59599775", "0.59234506", "0.5896018", "0.5889765", "0.5846516", "0.581659", "0.5812901", "0.5793982", "0.57602763", "0.57399255", "0.5701375", "0.5696935", "0.5636799", "0.5593854", "0.5589035", "0.5589035", "0.5589035", "0.5585208", "0.5569937", "0.55623466", "0.55571395", "0.5556558", "0.55414134", "0.55325466", "0.5523565", "0.55107254", "0.5508456", "0.5508427", "0.5484746", "0.5478298", "0.5466629", "0.5464969", "0.54596925", "0.54338324", "0.54338324", "0.54338324", "0.5414624", "0.53830343", "0.5375932", "0.53385437", "0.5329113", "0.5329113", "0.53183454", "0.53168553", "0.5309726", "0.52959305", "0.5260165", "0.52523494", "0.5222058", "0.5210953", "0.5195952", "0.5189111", "0.5177605", "0.5174505", "0.5164655", "0.51495874", "0.5148769" ]
0.6344204
19
:callseq: jpeg(io_out [, options]) Writes the image to +io_out+ as compressed JPEG data. Returns the number of bytes written. If the image has an alpha channel it will be stripped. +options+ may contain the following symbols: :bufsize the maximum size in bytes of the writes that will be made to +io_out+ :quality JPEG quality on a 0..100 scale. :exif Raw exif string that will be saved in the header. :icc_profile Raw ICC profile string that will be saved in the header. == Example i = Axon::JPEG('input.jpg') io_out = File.open('output.jpg', 'w') i.jpeg(io_out, :quality => 88) writes the image to output.jpg
def jpeg(*args) case @source.components when 2,4 then @source = AlphaStripper.new(@source) end JPEG.write(@source, *args) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compress_jpg(input, quality = 80, output = nil)\n unless output.nil?\n FileUtils.cp(input, output)\n input = output\n end\n\n options = [\n '-q -p -f',\n \"--max=#{quality}\",\n '--strip-all',\n '--all-progressive',\n input.shellescape\n ]\n\n command = \"jpegoptim #{options.join(' ')}\"\n `#{command}`\n\n return output unless output.nil?\n input\n end", "def jpeg(quality = nil)\n size = FFI::MemoryPointer.new(:pointer)\n ptr = ::GD2::GD2FFI.send(:gdImageJpegPtr, image_ptr, size, quality || -1)\n ptr.get_bytes(0, size.get_int(0))\n ensure\n ::GD2::GD2FFI.send(:gdFree, ptr)\n end", "def write(output_filename:, quality: 10)\n out_image = ImageList.new\n\n # Add rows to big picture\n @rows.values.each do |row|\n out_image.push(row.append(false))\n end\n\n out_image.append(true).write(output_filename) do\n self.format = \"JPEG\"\n self.quality = quality\n end\n end", "def export(filename_or_io, options = {})\n format = self.class.extract_format(filename_or_io, options)\n\n size = FFI::MemoryPointer.new(:pointer)\n\n case format\n when :jpeg, :jpg\n write_sym = :gdImageJpegPtr\n args = [size, options.delete(:quality) || -1]\n when :png\n write_sym = :gdImagePngPtrEx\n args = [size, options.delete(:level) || -1]\n when :gif\n write_sym = :gdImageGifPtr\n args = [size]\n when :wbmp\n write_sym = :gdImageWBMPPtr\n fgcolor = options.delete(:fgcolor)\n raise ArgumentError, 'Missing required option :fgcolor' if fgcolor.nil?\n\n args = [size, color2pixel(fgcolor)]\n when :gd\n write_sym = :gdImageGdPtr\n args = [size]\n when :gd2\n write_sym = :gdImageGd2Ptr\n args = [options.delete(:chunk_size) || 0, options.delete(:fmt) || FMT_COMPRESSED, size]\n else\n raise UnrecognizedImageTypeError, 'Format (or file extension) is not recognized'\n end\n\n output = case filename_or_io\n when String\n File.open(filename_or_io, 'wb')\n else\n filename_or_io\n end\n\n begin\n img = ::GD2::GD2FFI.send(write_sym, image_ptr, *args)\n output.write(img.get_bytes(0, size.get_int(0)))\n ensure\n ::GD2::GD2FFI.gdFree(img)\n end\n\n output.flush\n output.rewind\n\n output\n end", "def compress_png(input, quality = 80, output = nil)\n # Override file if no output selected\n output = input if output.nil?\n\n # PNGQuant does not allow update in place, so we save in a temp file\n output_tmp = Tempfile.new('temp_png').path\n\n options = [\n input.shellescape,\n '--force',\n \"--quality 01-#{quality}\",\n \"--output #{output_tmp.shellescape}\"\n ]\n\n command = \"pngquant #{options.join(' ')}\"\n `#{command}`\n\n # Move the tmp file back to the real output\n FileUtils.mv(output_tmp, output)\n\n output\n end", "def write_picture(args = {})\n if @picture[\"n\"] == 0\n raise FlacInfoError, \"There is no METADATA_BLOCK_PICTURE\"\n end\n\n if args.has_key?(:n)\n n = args[:n]\n else\n n = 1\n end\n\n # \"image/jpeg\" => \"jpeg\"\n extension = @picture[n][\"mime_type\"].split(\"/\")[1]\n\n if not args.has_key?(:outfile)\n if @tags[\"album\"] == nil or @tags[\"album\"] == \"\"\n outfile = \"flacimage#{n}.#{extension}\"\n else\n # Try to use contents of \"album\" tag for the filename\n outfile = \"#{@tags[\"album\"]}#{n}.#{extension}\"\n end\n else\n outfile = \"#{args[:outfile]}.#{extension}\"\n end\n\n in_p = File.new(@filename, \"rb\")\n out_p = is_io?(args[:outfile]) ? args[:outfile] : File.new(outfile, \"wb\")\n out_p.binmode # For Windows folks...\n\n in_p.seek(@picture[n]['raw_data_offset'], IO::SEEK_CUR)\n raw_data = in_p.read(@picture[n]['raw_data_length'])\n out_p.write(raw_data)\n\n in_p.close\n if is_io?(args[:outfile])\n out_p.rewind\n else\n out_p.close\n end\n\n nil\n end", "def use_jpeg?(_user = nil)\n CONFIG[\"jpeg_enable\"] && has_jpeg?\n end", "def quality(percent)\n write_opts[:Q] = percent\n get_image\n end", "def generate_jpeg(force_regen = false)\n return true unless image?\n return true unless CONFIG[\"jpeg_enable\"]\n return true unless width && height\n # Only generate JPEGs for PNGs. Don't do it for files that are already JPEGs; we'll just add\n # artifacts and/or make the file bigger. Don't do it for GIFs; they're usually animated.\n return true if (file_ext.downcase != \"png\")\n\n # We can generate the image during upload or offline. Use tempfile_path\n # if it exists, otherwise use file_path.\n path = tempfile_path\n path = file_path unless File.exist?(path)\n unless File.exist?(path)\n errors.add(:file, \"not found\")\n throw :abort\n end\n\n # If we already have the image, don't regenerate it.\n if !force_regen && jpeg_width.is_a?(Integer)\n return true\n end\n\n size = Moebooru::Resizer.reduce_to({ :width => width, :height => height }, { :width => CONFIG[\"jpeg_width\"], :height => CONFIG[\"jpeg_height\"] }, CONFIG[\"jpeg_ratio\"])\n begin\n Moebooru::Resizer.resize(file_ext, path, tempfile_jpeg_path, size, CONFIG[\"jpeg_quality\"])\n rescue => x\n errors.add \"jpeg\", \"couldn't be created: #{x}\"\n throw :abort\n end\n\n self.jpeg_width = size[:width]\n self.jpeg_height = size[:height]\n self.jpeg_size = File.size(tempfile_jpeg_path)\n self.jpeg_crc32 = Moebooru::Hasher.compute_one(tempfile_jpeg_path, :crc32)\n\n true\n end", "def generate_compressed path, img\n img.write(path) { self.quality = 70 }\n end", "def quality(percent)\n manipulate! do |image|\n @_format_opts = { :quality => percent } if jpeg? || @_format=='jpeg'\n image\n end\n end", "def encode_png_image_pass_to_stream(stream, color_mode, compression = ZLib::DEFAULT_COMPRESSION)\n\n if compression < Zlib::BEST_COMPRESSION && color_mode == ChunkyPNG::COLOR_TRUECOLOR_ALPHA\n # Fast RGBA saving routine\n stream << pixels.pack(\"xN#{width}\" * height)\n \n elsif compression < Zlib::BEST_COMPRESSION && color_mode == ChunkyPNG::COLOR_TRUECOLOR\n # Fast RGB saving routine\n line_packer = 'x' + ('NX' * width)\n stream << pixels.pack(line_packer * height)\n \n else\n # Normal saving routine\n pixel_size = Color.bytesize(color_mode)\n pixel_encoder = case color_mode\n when ChunkyPNG::COLOR_TRUECOLOR then lambda { |color| Color.to_truecolor_bytes(color) }\n when ChunkyPNG::COLOR_TRUECOLOR_ALPHA then lambda { |color| Color.to_truecolor_alpha_bytes(color) }\n when ChunkyPNG::COLOR_INDEXED then lambda { |color| [encoding_palette.index(color)] }\n when ChunkyPNG::COLOR_GRAYSCALE then lambda { |color| Color.to_grayscale_bytes(color) }\n when ChunkyPNG::COLOR_GRAYSCALE_ALPHA then lambda { |color| Color.to_grayscale_alpha_bytes(color) }\n else raise ChunkyPNG::NotSupported, \"Cannot encode pixels for this mode: #{color_mode}!\"\n end\n\n previous_bytes = Array.new(pixel_size * width, 0)\n each_scanline do |line|\n unencoded_bytes = line.map(&pixel_encoder).flatten\n stream << encode_png_scanline_paeth(unencoded_bytes, previous_bytes, pixel_size).pack('C*')\n previous_bytes = unencoded_bytes\n end\n end\n end", "def jpeg_file(path, *args)\n File.open(path, 'wb') do |f|\n jpeg(f, *args)\n end\n end", "def setJpegQuality(quality)\n if (!(Integer(quality) >= 1 && Integer(quality) <= 100))\n raise Error.new(Pdfcrowd.create_invalid_value_message(quality, \"setJpegQuality\", \"html-to-pdf\", \"The value must be in the range 1-100.\", \"set_jpeg_quality\"), 470);\n end\n \n @fields['jpeg_quality'] = quality\n self\n end", "def encode(format, options = {})\n # Sorry .jpeg lovers, I'm one of you too but the standard is jpg\n format = 'jpg' if format.to_s == 'jpeg'\n format = format.to_s\n \n raise ArgumentError, \"invalid format: #{format}\" unless %w(jpg png gif).include?(format)\n \n @canvas.encode format, options\n end", "def write_to(io, *options); end", "def quality(percentage)\n manipulate! do |img|\n img.write(current_path){ self.quality = percentage }\n img = yield(img) if block_given?\n img\n end\nend", "def to_jpeg(path, options = {})\n return raise Exceptions::InvalidFileFormatError unless valid_output_format?(path, 'jpeg')\n screenshot(path, 'jpeg', options)\n end", "def compress\n input_len = @input.bytesize\n tmp = optipng(quantize(@input))\n\n # Check to see whether we've improved the situation\n output_len = tmp.bytesize\n if input_len > output_len\n $LOG.debug \" %d bytes -> %d bytes = %.1f%%\" % [ input_len, output_len, 100 * output_len/input_len ] if $LOG.debug?\n @output = tmp\n @modified = true\n else\n $LOG.debug \" no gain\" if $LOG.debug?\n @output = @input\n @modified = false\n end\n self\n end", "def write!(opts = {})\n if requires_output_file?\n raise NoMethodError, \"You cannot use Image#write(output) with \"\\\n \"the #{current_utility} command\"\n end\n\n command = build_command(path)\n run(command, opts)\n self\n end", "def write_out\n File.delete(@path) if File.exist?(@path)\n File.open(@path, mode: 'w', encoding: @img_data.encoding) { |f| f.write(@img_data) }\n end", "def write(output, opts = {})\n output_path = parse_input(output, false)\n\n FileUtils.copy_file(path, output_path) unless requires_output_file?\n\n command = build_command(output_path)\n run(command, opts)\n GraphicsMagick::Image.new(output_path)\n end", "def img_resize( dat, w, h, options = {} )\n quality = options[:quality]\n format = options[:format]\n\n begin\n img = GD2::Image.load(dat)\n if h == 0\n h = ( w / img.aspect ).to_i\n end\n\n puts \"resizing image… width: #{w}, height: #{h}, quality: #{quality}\" if $debug\n\n # make sure it doesn't upscale image\n res = img.size\n\n if res[0] < w and res[1] < h\n w = res[0]\n h = res[1]\n elsif res[0] < w\n w = res[0]\n h = (w / img.aspect).to_i\n elsif res[1] < h\n h = res[1]\n w = (h / img.aspect).to_i\n end\n\n nimg = img.resize( w, h )\n\n if img_type(dat) == :jpeg and quality\n nimg.jpeg( quality.to_i )\n else\n case img_type(dat)\n when :png\n nimg.png\n when :jpeg\n nimg.jpeg\n when :gif\n nimg.gif\n else\n raise 'img_resize(), unknown output format'\n end\n end\n rescue => errmsg\n puts \"error: resize failed. #{w} #{h} #{quality}\"\n p errmsg\n return nil\n end\nend", "def convert_png_to_jpg(img_path)\n print_status(\"Converting #{img_path} to JPG to reduce image quality to #{JPGQUALITY}\")\n basename = File.basename(img_path, '.png')\n img = MiniMagick::Image.open(img_path)\n img.format('JPEG')\n img.quality(JPGQUALITY)\n dst = \"#{WORKFOLDER}/#{basename}.jpg\"\n img.write(dst)\n dst\nend", "def write(io, proc = nil)\t# :yields: track, num_tracks, index\n writer = @writer_class.new(self, block_given?() ? Proc.new() : proc)\n writer.write_to(io)\n end", "def compress\n return :input_too_short if buf.size < 2\n return :input_too_large if buf.size > 0xFFFFFF\n\n outstream = ArrayOStream.new\n .u8(0x11).u16(buf.size).u8(buf.size >> 16)\n\n outbuffer = [8 * 4 + 1] * 33\n outbuffer[0] = 0\n bufferlength = 1\n bufferedBlocks = 0\n readBytes = 0\n while readBytes < buf.size\n if bufferedBlocks == 8\n outstream.write(outbuffer[0, bufferlength])\n outbuffer[0] = 0\n bufferlength = 1\n bufferedBlocks = 0\n end\n\n oldLength = [readBytes, 0x1000].min\n disp, length = occurrence_length(readBytes,\n [buf.size - readBytes, 0x10110].min, readBytes - oldLength, oldLength)\n if length < 3\n outbuffer[bufferlength] = buf[readBytes]\n readBytes += 1\n bufferlength += 1\n else\n readBytes += length\n outbuffer[0] |= (1 << (7 - bufferedBlocks)) & 0xFF\n case\n when length > 0x110\n outbuffer[bufferlength] = 0x10\n outbuffer[bufferlength] |= ((length - 0x111) >> 12) & 0x0F\n bufferlength += 1\n outbuffer[bufferlength] = ((length - 0x111) >> 4) & 0xFF\n bufferlength += 1\n outbuffer[bufferlength] = ((length - 0x111) << 4) & 0xF0\n when length > 0x10\n outbuffer[bufferlength] = 0x00\n outbuffer[bufferlength] |= ((length - 0x111) >> 4) & 0x0F\n bufferlength += 1\n outbuffer[bufferlength] = ((length - 0x111) << 4) & 0xF0\n else\n outbuffer[bufferlength] = ((length - 1) << 4) & 0xF0\n end\n outbuffer[bufferlength] |= ((disp - 1) >> 8) & 0x0F\n bufferlength += 1\n outbuffer[bufferlength] = (disp - 1) & 0xFF\n bufferlength += 1\n end\n\n bufferedBlocks += 1\n end\n\n if bufferedBlocks > 0\n outstream.write(outbuffer[0, bufferlength])\n end\n\n outstream.buf\n end", "def compress_output(codec, type)\n properties['mapred.output.compress'] = 'true'\n properties['mapred.output.compression.codec'] = case codec\n when :default then Java::OrgApacheHadoopIoCompress::DefaultCodec.java_class.name\n when :gzip then Java::OrgApacheHadoopIoCompress::GzipCodec.java_class.name\n else raise \"Codec #{codec} not yet supported by cascading.jruby\"\n end\n properties['mapred.output.compression.type'] = case type\n when :none then Java::OrgApacheHadoopIo::SequenceFile::CompressionType::NONE.to_s\n when :record then Java::OrgApacheHadoopIo::SequenceFile::CompressionType::RECORD.to_s\n when :block then Java::OrgApacheHadoopIo::SequenceFile::CompressionType::BLOCK.to_s\n else raise \"Compression type '#{type}' not supported\"\n end\n end", "def thumbnail(width, input, output)\n profile_normalization_args=[\"--eprofile\", srgb_profile_path, \"--delete\"]\n vips_jpg_params=\"[Q=#{@jpeg_q },interlace,optimize_coding,strip]\"\n args = if width\n # The image will be resized to fit within a box\n # which is `width` wide and very, very very tall.\n # See:\n # https://github.com/libvips/libvips/issues/781\n # https://github.com/libvips/ruby-vips/issues/150\n [\n vips_thumbnail_command, input.path,\n *profile_normalization_args,\n \"--size\", \"#{width}x1000000\",\n \"-o\", \"#{output.path}#{vips_jpg_params}\"\n ]\n else\n [ vips_command, \"copy\", input.path,\n *profile_normalization_args,\n \"#{output.path}#{vips_jpg_params}\"\n ]\n end\n @cmd.run(*args)\n end", "def save_cropped_image(src, dest, x, y, width, height, quality = 75)\n if src.is_a? Magick::Image\n img = src\n else\n img = Magick::Image::read(src).first\n end\n\n quality = quality * 100 if quality < 1\n\n # The crop method retains the offset information in the cropped image.\n # To reset the offset data, adding true as the last argument to crop.\n cropped = img.crop(x, y, width, height, true)\n cropped.write(dest) { @quality = quality }\n end", "def write_to(io, *options)\n options = options.first.is_a?(Hash) ? options.shift : {}\n encoding = options[:encoding] || options[0]\n if Nokogiri.jruby?\n save_options = options[:save_with] || options[1]\n indent_times = options[:indent] || 0\n else\n save_options = options[:save_with] || options[1] || SaveOptions::FORMAT\n indent_times = options[:indent] || 2\n end\n indent_text = options[:indent_text] || \" \"\n\n # Any string times 0 returns an empty string. Therefore, use the same\n # string instead of generating a new empty string for every node with\n # zero indentation.\n indentation = indent_times.zero? ? \"\" : (indent_text * indent_times)\n\n config = SaveOptions.new(save_options.to_i)\n yield config if block_given?\n\n native_write_to(io, encoding, indentation, config.options)\n end", "def save\n\n properties = {}\n # exif = {}\n # KCGImagePropertyExifDictionary\n # exif[KCGImagePropertyExifUserComment] = 'Image downloaded from www.sheetmusicplus.com'\n # exif[KCGImagePropertyExifAuxOwnerName] = 'www.sheetmusicplus.com'\n if @filetype == :pdf\n CGPDFContextEndPage(@ctx)\n CGContextFlush(@ctx)\n return\n elsif @filetype == :png\n format = NSPNGFileType\n elsif @filetype == :tif\n format = NSTIFFFileType\n properties[NSImageCompressionMethod] = NSTIFFCompressionLZW\n #properties[NSImageCompressionMethod] = NSTIFFCompressionNone\n elsif @filetype == :gif\n format = NSGIFFileType\n #properties[NSImageDitherTransparency] = 0 # 1 = dithered, 0 = not dithered\n #properties[NSImageRGBColorTable] = nil # For GIF input and output. It consists of a 768 byte NSData object that contains a packed RGB table with each component being 8 bits.\n elsif @filetype == :jpg\n format = NSJPEGFileType\n properties[NSImageCompressionFactor] = @quality # (jpeg compression, 0.0 = max, 1.0 = none)\n #properties[NSImageEXIFData] = exif\n end\n cgimageref = CGBitmapContextCreateImage(@ctx) # => CGImageRef\n bitmaprep = NSBitmapImageRep.alloc.initWithCGImage(cgimageref) # => NSBitmapImageRep\n blob = bitmaprep.representationUsingType(format, properties:properties) # => NSConcreteData\n blob.writeToFile(@output, atomically:true)\n true\n end", "def resize_and_write_file(filename, filename_output, max_width, max_height = nil)\n pic = Magick::Image.read(filename).first\n img_width, img_height = pic.columns, pic.rows\n ratio = img_width.to_f / max_width.to_f\n\n if max_height.nil?\n max_height = img_height / ratio\n end\n\n pic.change_geometry!(\"#{max_width}x#{max_height}>\") { |cols, rows, img|\n img.resize_to_fit!(cols, rows)\n img.write filename_output\n img.destroy!\n }\n\n nbytes, content = File.size(filename_output), nil\n File.open(filename_output, \"rb\") { |f| content = f.read nbytes }\n content\nend", "def write_to(io)\n\t@io = io\n\t@bytes_written = 0\n\twrite_header()\n\t@update_block.call(nil, @seq.tracks.length, 0) if @update_block\n\t@seq.tracks.each_with_index do |track, i|\n write_track(track)\n @update_block.call(track, @seq.tracks.length, i) if @update_block\n\tend\n end", "def write_to(io)\n\t@io = io\n\t@bytes_written = 0\n\twrite_header()\n\t@update_block.call(nil, @seq.tracks.length, 0) if @update_block\n\t@seq.tracks.each_with_index do |track, i|\n write_track(track)\n @update_block.call(track, @seq.tracks.length, i) if @update_block\n\tend\n end", "def save_impl(format, file)\n ImageIO.write(@src, format, file)\n end", "def optimize_for_pagespeed\n # according to https://developers.google.com/speed/docs/insights/OptimizeImages\n if self.file.content_type == 'image/jpeg'\n # convert orig.jpg -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG orig_converted.jpg\n manipulate! do |img|\n img.sampling_factor '4:2:0'\n img.strip\n img.quality 85\n img.interlace 'JPEG'\n img\n end\n else\n # convert cuppa.png -strip cuppa_converted.png\n manipulate! do |img|\n img.strip\n img\n end\n end\n end", "def resize_image(img, size)\n img.delete_profile('*')\n\n # resize_image take size in a number of formats, we just want\n # Strings in the form of \"crop: WxH\"\n if (size.is_a?(String) && size =~ /^crop: (\\d*)x(\\d*)/i) ||\n (size.is_a?(Array) && size.first.is_a?(String) &&\n size.first =~ /^crop: (\\d*)x(\\d*)/i)\n img.crop_resized!($1.to_i, $2.to_i)\n # We need to save the resized image in the same way the\n # orignal does.\n quality = img.format.to_s[/JPEG/] && get_jpeg_quality\n out_file = write_to_temp_file(img.to_blob { self.quality = quality if quality })\n self.temp_paths.unshift out_file\n else\n old_resize_image(img, size) # Otherwise let attachment_fu handle it\n end\n end", "def to_jpg(*a)\n to_blob('jpg', *a)\n end", "def write(io, force)\n # You must use ancestor methods to work with report data:\n # 1) iterator.data_size => returns source data size (calls #count on data\n # retrieved from 'source')\n # 2) iterator.data_each => yields given block for each source data element\n # 3) table.build_header => returns Array of report column names\n # 4) table.build_row(object) => returns Array of report cell\n # values (same order as header)\n # 5) events_handler.progress(progress, total) => call to iterate job progress\n # 6) events_handler.error(error) => call to handle error in job\n #\n # HINT: You may override data_size and data_each, to retrieve them\n # effectively\n fail NotImplementedError\n end", "def process_image(src, dest, maxw, maxh)\n i = QuickMagick::Image.read(src).first\n # AMF - added quality setting to limit size of images (some sites had high quality jpeg, so files sizes were still big)\n i.quality = 75\n w, h = i.width, i.height\n extra = (w - h/(maxh.to_f/maxw.to_f)).to_i\n if extra > 0\n i.shave(\"#{extra>>1}x0\") if i.width > i.height\n w -= extra\n end\n if w > maxw or h > maxh\n i.resize(\"#{maxw}x#{maxh}\")\n end\n i.save(dest)\n end", "def put_page_convert_to_jpeg_with_http_info(name, page_number, out_path, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: PdfApi.put_page_convert_to_jpeg ...\"\n end\n # verify the required parameter 'name' is set\n if @api_client.config.client_side_validation && name.nil?\n fail ArgumentError, \"Missing the required parameter 'name' when calling PdfApi.put_page_convert_to_jpeg\"\n end\n # verify the required parameter 'page_number' is set\n if @api_client.config.client_side_validation && page_number.nil?\n fail ArgumentError, \"Missing the required parameter 'page_number' when calling PdfApi.put_page_convert_to_jpeg\"\n end\n # verify the required parameter 'out_path' is set\n if @api_client.config.client_side_validation && out_path.nil?\n fail ArgumentError, \"Missing the required parameter 'out_path' when calling PdfApi.put_page_convert_to_jpeg\"\n end\n # resource path\n local_var_path = \"/pdf/{name}/pages/{pageNumber}/convert/jpeg\".sub('{' + 'name' + '}', name.to_s).sub('{' + 'pageNumber' + '}', page_number.to_s)\n\n # query parameters\n query_params = {}\n query_params[:'outPath'] = out_path\n query_params[:'width'] = opts[:'width'] if !opts[:'width'].nil?\n query_params[:'height'] = opts[:'height'] if !opts[:'height'].nil?\n query_params[:'folder'] = opts[:'folder'] if !opts[:'folder'].nil?\n query_params[:'storage'] = opts[:'storage'] if !opts[:'storage'].nil?\n query_params[:'password'] = opts[:'password'] if !opts[:'password'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n # Fix header in file\n post_body = nil\n\n # http body (model)\n # Fix header in file\n # post_body = nil\n auth_names = ['JWT']\n data, status_code, headers = @api_client.call_api(:PUT, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'AsposeResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PdfApi#put_page_convert_to_jpeg\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def quality(percentage)\n manipulate! do |img|\n img.write(current_path){ self.quality = percentage }\n img = yield(img) if block_given?\n img\n end\n end", "def create_jp2_remote( img_location )\r\n Sidekiq::Logging.logger.info(\"about to create jp2 staging\")\r\n stdout, stdeerr, status = Open3.capture3(\"#{DIL_CONFIG['openjpeg2_location']}bin/opj_compress -i #{img_location} -o #{jp2_img_path} -t 1024,1024 -r 15\")\r\n Sidekiq::Logging.logger.info(\"out #{stdout}\")\r\n Sidekiq::Logging.logger.info(\"err #{stdeerr}\")\r\n Sidekiq::Logging.logger.info(\"status #{status}\")\r\n end", "def write_buffer(io = ::StringIO.new, encrypter: nil)\n io.binmode if io.respond_to?(:binmode)\n zos = new(io, stream: true, encrypter: encrypter)\n yield zos\n zos.close_buffer\n end", "def write(io, constraints = {})\n to_datastream(constraints).write(io)\n end", "def write(io, constraints = {})\n to_datastream(constraints).write(io)\n end", "def compress!(img)\n puts 'Compressing image.'\n image_optim = ImageOptim.new(allow_lossy: true, verbose: false, skip_missing_workers: true, optipng: false,\n pngcrush: false, pngquant: { allow_lossy: true },\n advpng: false, pngout: false, svgo: false)\n image_optim.optimize_image(img)\n puts 'compressed.'\n end", "def to_jpg(*a)\n to_image(*a).to_blob{|i| i.format = 'jpg' }\n end", "def jpeg?(image)\n cur_page.jpeg?(image)\n end", "def make_exif(thumbnail = false)\n option = thumbnail ? \"-mkexif -rgt\" : \"-mkexif\"\n Jhead.call(option, @match, @pattern)\n end", "def resize!(options)\n options = options.symbolize_keys\n raise ArgumentError, ':size must be included in resize options' unless options[:size]\n\n # load image\n img = rmagick_image.dup\n\n # Find dimensions\n x, y = size_to_xy(options[:size])\n\n # prevent upscaling unless :usample param exists.\n unless options[:upsample]\n x = img.columns if x > img.columns\n y = img.rows if y > img.rows\n end\n\n # Perform image resize\n case\n when options[:crop] && !options[:crop].is_a?(Hash) && img.respond_to?(:crop_resized!)\n # perform resize and crop\n scale_and_crop(img, [x, y], options[:offset])\n when options[:stretch]\n # stretch the image, ignoring aspect ratio\n stretch(img, [x, y]) \n else\n # perform the resize without crop\n scale(img, [x, y]) \n end\n\n if options[:format]\n img.format = options[:format].to_s.upcase\n img.strip!\n end\n\n options[:quality] ? img.to_blob { self.quality = options[:quality].to_i } : img.to_blob\n end", "def io_out\n raise NotImplementedError, 'Not implemented'\n end", "def compress(stream_or_string, options={})\n raise ArgumentError, 'Option :type required' unless options.key?(:type)\n\n string = stringify(stream_or_string)\n\n case options[:type].to_s\n when 'js'\n options = default_js_options.merge(options)\n when 'css'\n options = default_css_options.merge(options)\n else\n raise ArgumentError, 'Unknown resource type: %s' % options[:type]\n end\n\n command = [ options.delete(:java) || 'java', '-jar', JAR_FILE ]\n command.concat(command_arguments(options))\n\n stdout_str, stderr_str, status = Open3.capture3(command.join(' '), stdin_data: string, binmode: true)\n unless status.success?\n raise \"Compression failed: #{stderr_str}\"\n end\n stdout_str\n end", "def format\n \"image/jpeg\"\n end", "def encode_png_pixelstream(color_mode = ChunkyPNG::COLOR_TRUECOLOR, interlace = ChunkyPNG::INTERLACING_NONE, compression = ZLib::DEFAULT_COMPRESSION)\n\n if color_mode == ChunkyPNG::COLOR_INDEXED && (encoding_palette.nil? || !encoding_palette.can_encode?)\n raise ChunkyPNG::ExpectationFailed, \"This palette is not suitable for encoding!\"\n end\n\n case interlace\n when ChunkyPNG::INTERLACING_NONE then encode_png_image_without_interlacing(color_mode, compression)\n when ChunkyPNG::INTERLACING_ADAM7 then encode_png_image_with_interlacing(color_mode, compression)\n else raise ChunkyPNG::NotSupported, \"Unknown interlacing method: #{interlace}!\"\n end\n end", "def write(output_filename)\n Trace::get_logger.info('Image.write') { \"Writing output file...\" }\n \n output_file = ChunkyPNG::Image.new(@width, @height, ChunkyPNG::Color::TRANSPARENT)\n \n @width.times do |x|\n @height.times do |y|\n output_file[x,y] = @pixels[[x,y]].get_color\n end\n end\n \n output_file.save(\"#{output_filename}.png\", :interlace => false)\n end", "def generate(write_path, size_type)\n if SUPPORTED_FILE_TYPES.include? File.extname(read_path)\n image = Magick::Image.read(read_path).first\n write_image image, write_path, size_type\n else\n write_default_image write_path, size_type\n end\n end", "def thumbnail_file(input_path, output_path, options = {})\n opts = {\n :format => File.extname(output_path).sub(/^\\./, '')\n }.merge(options)\n \n data = SmartImage.thumbnail File.read(input_path), opts\n File.open(output_path, 'w') { |file| file << data }\n end", "def compress_img (files = [])\n\t\t\n\t\tunless which('convert')\n\t\t\tputs \"WARNING: ImageMagick is not installed on your system. Skipping image compression...\"\n\t\t\treturn\n\t\tend\n\t\t\n\t\tunless files.is_a? Array\n\t\t\tfiles = [files]\n\t\tend\n\n\t\tfiles.each do |file|\n\n\t\t\tfname = get_filename(file)\n\n\t\t\tcompress_cmd = \n\t\t\t\t\t\t\t\t\"convert -strip \" + \n\t\t\t\t\t\t\t\t# uncomment to enable gaussian blur (smaller files but blurry)\n\t\t\t\t\t\t\t\t#\"-gaussian-blur 0.01 \" +\n\t\t\t\t\t\t\t\t# uncomment to enable interlacing (progressive compression for jpeg)\n\t\t\t\t\t\t\t\t#\"-interlace Plane \" +\n\t\t\t\t\t\t\t\t\"#{fname} -resize #{$img_options[:max_width]}x#{$img_options[:max_height]}\\\\> \" + \n\t\t \t\t\t\t\t\"-compress #{$img_options[:compress_type]} -quality #{$img_options[:quality]} \" + \n\t\t \t\t\t\t\t\"#{get_raw_filename(fname) + '.' + $img_options[:output_ext]}\"\n\t\t\t\n\t\t # invoke system ImageMagick\n\t\t system(compress_cmd)\n\t\t # remove the old file (if applicable)\n\t\t if (get_ext(fname) != (\".\" + $img_options[:output_ext]))\n\t\t \tsystem(\"rm #{fname}\")\n\t\t end\n\n\t\tend\n\n\tend", "def quality_and_strip(percentage)\n manipulate! do |img|\n img.format('jpg') # We want to enforce jpeg so we can use good compression.\n img.strip # Do not store EXIF data in the thumb to save space\n img.quality(percentage.to_s)\n img = yield(img) if block_given?\n img\n end\n end", "def generate_jpg(outage)\n # TODO: put this into its own function\n jpg_output = \"#{FailureIsolation::DotFiles}/#{outage.log_name}.jpg\"\n\n @dot_generator.generate_jpg(outage, jpg_output)\n\n jpg_output\n end", "def write_ppm(ios, format=\"P6\")\n if not PIXMAP_FORMATS.include?(format)\n raise NotImplementedError, \"pixmap format #{format} has not been implemented\" \n end\n ios.puts format, \"#{@width} #{@height}\", \"255\"\n ios.binmode if PIXMAP_BINARY_FORMATS.include?(format)\n each_pixel do |x, y|\n case format\n when \"P3\" then ios.print @data[x][y].values.join(\" \"),\"\\n\"\n when \"P6\" then ios.print @data[x][y].values.pack('C3')\n end\n end\n end", "def write_to(io)\n end", "def write_to(io)\n end", "def pretty_print(io = $stdout, **options)\n # Handle the special case that Ruby PrettyPrint expects `pretty_print`\n # to be a customized pretty printing function for a class\n return io.pp_object(self) if defined?(PP) && io.is_a?(PP)\n\n io = File.open(options[:to_file], \"w\") if options[:to_file]\n\n color_output = options.fetch(:color_output) { io.respond_to?(:isatty) && io.isatty }\n @colorize = color_output ? Polychrome.new : Monochrome.new\n\n if options[:scale_bytes]\n total_allocated_output = scale_bytes(total_allocated_memsize)\n total_retained_output = scale_bytes(total_retained_memsize)\n else\n total_allocated_output = \"#{total_allocated_memsize} bytes\"\n total_retained_output = \"#{total_retained_memsize} bytes\"\n end\n\n io.puts \"Total allocated: #{total_allocated_output} (#{total_allocated} objects)\"\n io.puts \"Total retained: #{total_retained_output} (#{total_retained} objects)\"\n\n unless options[:detailed_report] == false\n TYPES.each do |type|\n METRICS.each do |metric|\n NAMES.each do |name|\n dump_data(io, type, metric, name, options)\n end\n end\n end\n\n io.puts\n print_string_reports(io, options)\n end\n\n io.close if io.is_a? File\n end", "def compress!; end", "def processed_image(image, options = {})\n size = options[:size]\n upsample = !!options[:upsample]\n\n return image unless size.present? && has_convertible_format?\n\n if options[:crop]\n crop(size, options[:crop_from], options[:crop_size], upsample)\n else\n resize(size, upsample)\n end\n end", "def convert_to_jpg(quality, image_file, opts = {})\n data, _status_code, _headers = convert_to_jpg_with_http_info(quality, image_file, opts)\n data\n end", "def process_image(path)\n picture_name = File.basename(path)\n thumbnail_dir = File.join(File.dirname(path), \"thumbnails\")\n thumbnail_path = File.join(thumbnail_dir, \"#{File.basename(picture_name, File.extname(picture_name))}.jpg\")\n Dir.mkdir(thumbnail_dir) unless File.exist?(thumbnail_dir)\n\n image_optim = ImageOptim.new\n\n image = MiniMagick::Image.open(path)\n image_prop = {\n \"name\" => picture_name,\n \"thumb\" => \"thumbnails/#{picture_name}\",\n \"height\" => image.height,\n \"width\" => image.width\n }\n\n return image_prop if File.exist?(thumbnail_path)\n\n# -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB\n\n image.format \"jpeg\" unless File.extname(picture_name) == \"jpg\"\n image.combine_options do |b|\n b.resize \"#{MAX_DIMENSION}>\"\n b.sampling_factor \"4:2:0\"\n b.strip\n b.interlace \"JPEG\"\n b.colorspace \"RGB\"\n b.quality 85\n end\n image.write thumbnail_path\n\n image_optim.optimize_image!(path)\n image_optim.optimize_image!(thumbnail_path)\n\n image_prop\nend", "def write_image(image, write_path, size_type)\n size = find_size size_type\n image.resize_to_fill!(size[0], size[1]) if size_type\n image.format = \"PNG\" if image.format == \"SVG\"\n write_path.gsub!(/.svg/i, \".png\")\n image.write write_path\n end", "def compression?; end", "def write_to(filename, options = {})\n # Gzip contents if filename has '.gz'\n options[:compress] ||= File.extname(filename) == '.gz'\n\n FileUtils.mkdir_p File.dirname(filename)\n\n File.open(\"#{filename}+\", 'wb') do |f|\n if options[:compress]\n # Run contents through `Zlib`\n gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)\n gz.write to_s\n gz.close\n else\n # Write out as is\n f.write to_s\n f.close\n end\n end\n\n # Atomic write\n FileUtils.mv(\"#{filename}+\", filename)\n\n # Set mtime correctly\n File.utime(mtime, mtime, filename)\n\n nil\n ensure\n # Ensure tmp file gets cleaned up\n FileUtils.rm(\"#{filename}+\") if File.exist?(\"#{filename}+\")\n end", "def optipng(content)\n input = Tempfile.new([SecureRandom.hex(16), \".png\"])\n output = Tempfile.new([SecureRandom.hex(16), \".png\"])\n begin\n raise PngError, \"optipng not found in PATH=#{ENV['PATH']}\" unless which(\"optipng\")\n # Make sure the files are in the right state before we run the shell process\n output_path = output.to_path\n input_path = input.to_path\n input.write(content)\n input.close\n output.close\n cmd = \"optipng -quiet -force -clobber -out #{output_path} #{input_path} \"\n `#{cmd}`\n if $?.exitstatus != 0\n raise \"Failed to execute optipng: #{cmd}\"\n end\n File.read output_path\n ensure\n input.unlink\n output.unlink\n end\n end", "def compress(img, path)\n puts 'Compressing image.'\n image_optim = ImageOptim.new(allow_lossy: true, verbose: false, skip_missing_workers: true, optipng: false,\n pngcrush: false, pngquant: { allow_lossy: true },\n advpng: false, pngout: false, svgo: false)\n File.rename(image_optim.optimize_image(img), path)\n puts 'Image copied and compressed.'\n end", "def compress_gzip(data)\n buffer = StringIO.new('','w')\n compressor = Zlib::GzipWriter.new(buffer)\n begin\n compressor.write(data)\n ensure\n compressor.close()\n end\n buffer.string\n end", "def output(base_uri, input_name, output_name, options, gif, output_folder)\n base_uri = base_uri + 'output/'\n if gif\n else\n Dir.mkdir(base_uri) unless Dir.exist?(base_uri)\n end\n\n if output_name.nil?\n rando = '_' + (0...4).map { 65.+(rand(26)).chr }.join.downcase\n settings_file = File.new(base_uri + input_name + rando + '.txt', 'w')\n settings_file.puts(options.to_s)\n settings_file.close\n base_uri + input_name + rando + '.png'\n elsif gif || output_folder\n @base_uri = base_uri + \"#{input_name}/\"\n # needs to be refactored to create an output folder instead of a sequence folder\n FileUtils.mkdir_p(@sequence_folder) unless Dir.exist?(@sequence_folder)\n settings_file = File.new(@sequence_folder + output_name + '.txt', 'w')\n settings_file.puts(options.to_s)\n settings_file.close\n @sequence_folder + output_name + '.png'\n elsif !gif && !output_folder\n settings_file = File.new(base_uri + output_name + '.txt', 'w')\n settings_file.puts(options.to_s)\n settings_file.close\n base_uri + output_name + '.png'\n end\n end", "def write(path)\n @img_rw.rch = @rch\n @img_rw.gch = @gch\n @img_rw.bch = @bch\n @img_rw.write(path)\n end", "def write_image id, name_suffix=\"\"\n m_begin \"write_image\"\n filename = \"./temp/\" +id.to_s+name_suffix+\".gif\"\n get_image(id).write(filename)\n m_end \"write_image\"\n end", "def add_json_output_options(opt)\n opt.on(\"--[no-]pretty\", \"Generate a pretty JSON document\") do |value|\n io_options[:json][:pretty] = value\n end \n end", "def convert_to_jpg_with_http_info(quality, image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ConvertApi.convert_to_jpg ...'\n end\n # verify the required parameter 'quality' is set\n if @api_client.config.client_side_validation && quality.nil?\n fail ArgumentError, \"Missing the required parameter 'quality' when calling ConvertApi.convert_to_jpg\"\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ConvertApi.convert_to_jpg\"\n end\n # resource path\n local_var_path = '/image/convert/to/jpg/{quality}'.sub('{' + 'quality' + '}', quality.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/octet-stream'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ConvertApi#convert_to_jpg\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def put_compressed ob\n data = Boss.dump(ob)\n whdr TYPE_EXTRA, TCOMPRESSED\n type = case data.length\n when 0..160\n 0\n when 161..8192\n data = Zlib::Deflate.new.deflate(data, Zlib::FINISH)\n 1\n else\n data = Zlib::Deflate.new.deflate(data, Zlib::FINISH)\n 1\n #data = Bzip2.compress data\n #2\n end\n whdr type, data.length\n wbin data\n end", "def write_string(type=DEFAULT_OUT_TYPE, out_options={})\n png_transformer(type.to_s, out_options) do |type_s, _out_opts|\n obconv = out_options[:obconv] || OpenBabel::OBConversion.new\n obconv.set_out_format(type_s)\n obconv.add_opts!(:out, _out_opts)\n obconv.write_string(@ob)\n end\n end", "def write filename, compress=nil\n STDERR.puts(\"Writing #{self.inspect} to #{filename}\")\n x = super(filename)\n `gzip #{filename}` if compress\n x\n end", "def save_as(filename, size = :medium)\n format = size.to_sym == :original ? self.original_format : 'jpg'\n filename = \"#{filename}.#{format}\"\n\n if File.exists?(filename) or not self.url(size)\n false\n else\n f = File.new(filename, 'w+')\n f.puts open(self.url(size)).read\n f.close\n f\n end\n end", "def save_impl(format, file)\n write_new_image format, FileImageOutputStream.new(file)\n end", "def gzip_compress(s)\n io = StringIO.new('w')\n w = Zlib::GzipWriter.new(io)\n w.write(s)\n w.close\n io.string\nend", "def old_resize_image(img, size)\n size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)\n if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))\n size = [size, size] if size.is_a?(Fixnum)\n img.thumbnail!(*size)\n elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75\n dimensions = size[1..size.size].split(\"x\")\n img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i)\n else\n img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) }\n end\n self.width = img.columns if respond_to?(:width)\n self.height = img.rows if respond_to?(:height)\n img.strip! unless attachment_options[:keep_profile]\n quality = img.format.to_s[/JPEG/] && get_jpeg_quality\n out_file = write_to_temp_file(img.to_blob { self.quality = quality if quality })\n temp_paths.unshift out_file\n self.size = File.size(self.temp_path)\n end", "def make_tempfile(input, options = {})\n tempfile = Tempfile.new('image-upload')\n tempfile.set_encoding(Encoding::BINARY) if tempfile.respond_to?(:set_encoding)\n tempfile.binmode\n buffer = \"\"\n while input.read(1024 * 4, buffer)\n entire_buffer_written_out = false\n while !entire_buffer_written_out\n written = tempfile.write(buffer)\n entire_buffer_written_out = written == Rack::Utils.bytesize(buffer)\n if !entire_buffer_written_out\n buffer.slice!(0 .. written - 1)\n end\n end\n end\n tempfile.rewind\n {:tempfile => tempfile}.merge(options)\n end", "def encode_png_pixelstream(color_mode = ChunkyPNG::COLOR_TRUECOLOR, bit_depth = 8, interlace = ChunkyPNG::INTERLACING_NONE, filtering = ChunkyPNG::FILTER_NONE)\n if color_mode == ChunkyPNG::COLOR_INDEXED\n raise ChunkyPNG::ExpectationFailed, \"This palette is not suitable for encoding!\" if encoding_palette.nil? || !encoding_palette.can_encode?\n raise ChunkyPNG::ExpectationFailed, \"This palette has too many colors!\" if encoding_palette.size > (1 << bit_depth)\n end\n\n case interlace\n when ChunkyPNG::INTERLACING_NONE then encode_png_image_without_interlacing(color_mode, bit_depth, filtering)\n when ChunkyPNG::INTERLACING_ADAM7 then encode_png_image_with_interlacing(color_mode, bit_depth, filtering)\n else raise ChunkyPNG::NotSupported, \"Unknown interlacing method: #{interlace}!\"\n end\n end", "def resize_and_optimize(width, height)\n manipulate! do |img|\n img.format(\"jpg\") do |c|\n c.quality \"70\"\n c.resize \"#{width}x#{height}\"\n end\n\n img\n end\n end", "def write(io)\n io = BinData::IO.new(io) unless BinData::IO === io\n\n do_write(io)\n io.flush\n self\n end", "def poster(input, output)\n \n input = input \n output = output \n \n scale(input, output)\n\n #Demonstrate the Image#polaroid method\n img = Magick::Image.read(output).first\n result = img.posterize\n \n #Write \n result.write(output)\n\nend", "def generate_ios input_file, json_file, output\n\tguide_json = parse json_file\n\n\tfor item in guide_json[\"images\"] do \n\t\timage_size = item[\"size\"].split('x')\n\n\t\tscale = Integer(item[\"scale\"].gsub('x', ''))\n\n\t\timage_name = item[\"filename\"]\n\t\t\n\t\tout = \"#{output}/#{image_name}\"\n\n\t\tscale_to_width input_file, (image_size[0].to_f*scale).to_i.to_s, (image_size[1].to_f*scale).to_i.to_s, \"\\\"\" + out + \"\\\"\"\n\n\t puts out\n\tend\nend", "def execute(iInputData, oOutputData)\n lRawSample = iInputData.Header.getEncodedString([@Value]*iInputData.Header.NbrChannels)\n # Write complete buffers\n lNbrCompleteBuffers = @NbrSamples/MAX_BUFFER_SAMPLES\n if (lNbrCompleteBuffers > 0)\n lCompleteRawBuffer = lRawSample*MAX_BUFFER_SAMPLES\n lNbrCompleteBuffers.times do |iIdx|\n oOutputData.pushRawBuffer(lCompleteRawBuffer)\n end\n end\n # Write last buffer\n lLastBufferSize = @NbrSamples % MAX_BUFFER_SAMPLES\n if (lLastBufferSize > 0)\n oOutputData.pushRawBuffer(lRawSample*lLastBufferSize)\n end\n\n return nil\n end", "def encode_png_image_without_interlacing(color_mode, compression = ZLib::DEFAULT_COMPRESSION)\n stream = \"\"\n encode_png_image_pass_to_stream(stream, color_mode, compression)\n stream\n end", "def compression\n configuration[:copy_compression] || :gzip\n end", "def write_to_fastq (fh, header, sequence, quality)\n\tfh.write('@' + header + \"\\n\")\n\tfh.write(sequence)\n\tfh.write(\"\\n+\\n\")\n\tfh.write(quality + \"\\n\")\nend", "def save_thumbnail(name)\n name = \"-\" if name == STDOUT\n Jhead.call(\"-st\", name.shellescape, @match, @pattern)\n end", "def resize(path)\n img = MiniMagick::Image.open(@file)\n img.combine_options do |c|\n c.quality @options[:quality] if @options[:quality]\n c.resize \"#{@width}x#{@height}>\"\n end\n\n img.write(path)\n end", "def create_size src,dest,params\n return nil if !File.exists?(src)\n i = Image.new(src)\n params[:to] = dest\n FileUtils.mkdir_p File.dirname(dest)\n i.out params\n @hooks.create(:original => src,\n :sized => dest,\n :not_found => params[:not_found],\n :autogenerated => params[:autogenerated],\n :width => params[:width],\n :height => params[:height]) if @hooks && !params[:skiphook]\n end" ]
[ "0.63904643", "0.5964231", "0.5818225", "0.56014895", "0.55442303", "0.528265", "0.51608825", "0.51367235", "0.5063151", "0.49861535", "0.49382746", "0.49120033", "0.48495376", "0.48303932", "0.47554582", "0.47347322", "0.46941128", "0.46901345", "0.4676059", "0.46240562", "0.4592998", "0.45883244", "0.45850736", "0.45368248", "0.45215172", "0.4517965", "0.45086536", "0.4506503", "0.45028937", "0.44746816", "0.44558978", "0.44486603", "0.44322526", "0.44322526", "0.4403131", "0.4386591", "0.4382851", "0.4352227", "0.43457365", "0.4334445", "0.4332449", "0.43239373", "0.4289875", "0.42799866", "0.42693892", "0.42693892", "0.4251815", "0.42453992", "0.42427763", "0.4240255", "0.42401522", "0.4214766", "0.42013717", "0.41981232", "0.41814956", "0.4168298", "0.4162675", "0.41624177", "0.41580147", "0.41576475", "0.4133723", "0.41285953", "0.4121344", "0.4121344", "0.41204393", "0.40983105", "0.4096483", "0.40898257", "0.40873668", "0.40853643", "0.4080426", "0.40714794", "0.4054303", "0.4042557", "0.4038255", "0.40339234", "0.402592", "0.40244123", "0.40210629", "0.40189704", "0.4015593", "0.40120777", "0.40100512", "0.40087333", "0.40060169", "0.3998276", "0.39969462", "0.39919165", "0.39905018", "0.39903507", "0.39753208", "0.39730307", "0.39718968", "0.3971482", "0.39627713", "0.39617133", "0.3957144", "0.39528403", "0.39516374", "0.3950409" ]
0.5372031
5
:callseq: jpeg_file(path [, options]) Writes the image to a new file at +path+ as compressed JPEG data. Returns the number of bytes written. If the image has an alpha channel it will be stripped. See Axonjpeg for a description of +options+. == Example Axon.png_file("image.png") do |image| image.jpeg_file("image.jpg") saves the image to "image.jpeg" end
def jpeg_file(path, *args) File.open(path, 'wb') do |f| jpeg(f, *args) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def jpeg(*args)\n case @source.components\n when 2,4 then @source = AlphaStripper.new(@source)\n end\n JPEG.write(@source, *args)\n end", "def to_jpeg(path, options = {})\n return raise Exceptions::InvalidFileFormatError unless valid_output_format?(path, 'jpeg')\n screenshot(path, 'jpeg', options)\n end", "def generate_compressed path, img\n img.write(path) { self.quality = 70 }\n end", "def compress_img (files = [])\n\t\t\n\t\tunless which('convert')\n\t\t\tputs \"WARNING: ImageMagick is not installed on your system. Skipping image compression...\"\n\t\t\treturn\n\t\tend\n\t\t\n\t\tunless files.is_a? Array\n\t\t\tfiles = [files]\n\t\tend\n\n\t\tfiles.each do |file|\n\n\t\t\tfname = get_filename(file)\n\n\t\t\tcompress_cmd = \n\t\t\t\t\t\t\t\t\"convert -strip \" + \n\t\t\t\t\t\t\t\t# uncomment to enable gaussian blur (smaller files but blurry)\n\t\t\t\t\t\t\t\t#\"-gaussian-blur 0.01 \" +\n\t\t\t\t\t\t\t\t# uncomment to enable interlacing (progressive compression for jpeg)\n\t\t\t\t\t\t\t\t#\"-interlace Plane \" +\n\t\t\t\t\t\t\t\t\"#{fname} -resize #{$img_options[:max_width]}x#{$img_options[:max_height]}\\\\> \" + \n\t\t \t\t\t\t\t\"-compress #{$img_options[:compress_type]} -quality #{$img_options[:quality]} \" + \n\t\t \t\t\t\t\t\"#{get_raw_filename(fname) + '.' + $img_options[:output_ext]}\"\n\t\t\t\n\t\t # invoke system ImageMagick\n\t\t system(compress_cmd)\n\t\t # remove the old file (if applicable)\n\t\t if (get_ext(fname) != (\".\" + $img_options[:output_ext]))\n\t\t \tsystem(\"rm #{fname}\")\n\t\t end\n\n\t\tend\n\n\tend", "def jpeg(quality = nil)\n size = FFI::MemoryPointer.new(:pointer)\n ptr = ::GD2::GD2FFI.send(:gdImageJpegPtr, image_ptr, size, quality || -1)\n ptr.get_bytes(0, size.get_int(0))\n ensure\n ::GD2::GD2FFI.send(:gdFree, ptr)\n end", "def convert_png_to_jpg(img_path)\n print_status(\"Converting #{img_path} to JPG to reduce image quality to #{JPGQUALITY}\")\n basename = File.basename(img_path, '.png')\n img = MiniMagick::Image.open(img_path)\n img.format('JPEG')\n img.quality(JPGQUALITY)\n dst = \"#{WORKFOLDER}/#{basename}.jpg\"\n img.write(dst)\n dst\nend", "def generate_jpeg(force_regen = false)\n return true unless image?\n return true unless CONFIG[\"jpeg_enable\"]\n return true unless width && height\n # Only generate JPEGs for PNGs. Don't do it for files that are already JPEGs; we'll just add\n # artifacts and/or make the file bigger. Don't do it for GIFs; they're usually animated.\n return true if (file_ext.downcase != \"png\")\n\n # We can generate the image during upload or offline. Use tempfile_path\n # if it exists, otherwise use file_path.\n path = tempfile_path\n path = file_path unless File.exist?(path)\n unless File.exist?(path)\n errors.add(:file, \"not found\")\n throw :abort\n end\n\n # If we already have the image, don't regenerate it.\n if !force_regen && jpeg_width.is_a?(Integer)\n return true\n end\n\n size = Moebooru::Resizer.reduce_to({ :width => width, :height => height }, { :width => CONFIG[\"jpeg_width\"], :height => CONFIG[\"jpeg_height\"] }, CONFIG[\"jpeg_ratio\"])\n begin\n Moebooru::Resizer.resize(file_ext, path, tempfile_jpeg_path, size, CONFIG[\"jpeg_quality\"])\n rescue => x\n errors.add \"jpeg\", \"couldn't be created: #{x}\"\n throw :abort\n end\n\n self.jpeg_width = size[:width]\n self.jpeg_height = size[:height]\n self.jpeg_size = File.size(tempfile_jpeg_path)\n self.jpeg_crc32 = Moebooru::Hasher.compute_one(tempfile_jpeg_path, :crc32)\n\n true\n end", "def compress(img, path)\n puts 'Compressing image.'\n image_optim = ImageOptim.new(allow_lossy: true, verbose: false, skip_missing_workers: true, optipng: false,\n pngcrush: false, pngquant: { allow_lossy: true },\n advpng: false, pngout: false, svgo: false)\n File.rename(image_optim.optimize_image(img), path)\n puts 'Image copied and compressed.'\n end", "def write(path)\n @img_rw.rch = @rch\n @img_rw.gch = @gch\n @img_rw.bch = @bch\n @img_rw.write(path)\n end", "def resize(path)\n img = MiniMagick::Image.open(@file)\n img.combine_options do |c|\n c.quality @options[:quality] if @options[:quality]\n c.resize \"#{@width}x#{@height}>\"\n end\n\n img.write(path)\n end", "def compress_jpg(input, quality = 80, output = nil)\n unless output.nil?\n FileUtils.cp(input, output)\n input = output\n end\n\n options = [\n '-q -p -f',\n \"--max=#{quality}\",\n '--strip-all',\n '--all-progressive',\n input.shellescape\n ]\n\n command = \"jpegoptim #{options.join(' ')}\"\n `#{command}`\n\n return output unless output.nil?\n input\n end", "def write( path )\n base_image.write( path )\n end", "def write_picture(args = {})\n if @picture[\"n\"] == 0\n raise FlacInfoError, \"There is no METADATA_BLOCK_PICTURE\"\n end\n\n if args.has_key?(:n)\n n = args[:n]\n else\n n = 1\n end\n\n # \"image/jpeg\" => \"jpeg\"\n extension = @picture[n][\"mime_type\"].split(\"/\")[1]\n\n if not args.has_key?(:outfile)\n if @tags[\"album\"] == nil or @tags[\"album\"] == \"\"\n outfile = \"flacimage#{n}.#{extension}\"\n else\n # Try to use contents of \"album\" tag for the filename\n outfile = \"#{@tags[\"album\"]}#{n}.#{extension}\"\n end\n else\n outfile = \"#{args[:outfile]}.#{extension}\"\n end\n\n in_p = File.new(@filename, \"rb\")\n out_p = is_io?(args[:outfile]) ? args[:outfile] : File.new(outfile, \"wb\")\n out_p.binmode # For Windows folks...\n\n in_p.seek(@picture[n]['raw_data_offset'], IO::SEEK_CUR)\n raw_data = in_p.read(@picture[n]['raw_data_length'])\n out_p.write(raw_data)\n\n in_p.close\n if is_io?(args[:outfile])\n out_p.rewind\n else\n out_p.close\n end\n\n nil\n end", "def save_impl(format, file)\n ImageIO.write(@src, format, file)\n end", "def write_image id, name_suffix=\"\"\n m_begin \"write_image\"\n filename = \"./temp/\" +id.to_s+name_suffix+\".gif\"\n get_image(id).write(filename)\n m_end \"write_image\"\n end", "def compress_file(*path)\n compressed_path = path.dup\n compressed_path.push(\"#{compressed_path.pop}.gz\")\n base_file = File.open(for_file(path))\n create_file(compressed_path) do |file|\n compressor = Zlib::GzipWriter.new(file)\n while data = base_file.read(2048)\n compressor.write(data)\n end\n compressor.close\n end\n end", "def png_file(path, *args)\n File.open(path, 'wb') do |f|\n png(f, *args)\n end\n end", "def save_impl(format, file)\n write_new_image format, FileImageOutputStream.new(file)\n end", "def encode_png_image_pass_to_stream(stream, color_mode, compression = ZLib::DEFAULT_COMPRESSION)\n\n if compression < Zlib::BEST_COMPRESSION && color_mode == ChunkyPNG::COLOR_TRUECOLOR_ALPHA\n # Fast RGBA saving routine\n stream << pixels.pack(\"xN#{width}\" * height)\n \n elsif compression < Zlib::BEST_COMPRESSION && color_mode == ChunkyPNG::COLOR_TRUECOLOR\n # Fast RGB saving routine\n line_packer = 'x' + ('NX' * width)\n stream << pixels.pack(line_packer * height)\n \n else\n # Normal saving routine\n pixel_size = Color.bytesize(color_mode)\n pixel_encoder = case color_mode\n when ChunkyPNG::COLOR_TRUECOLOR then lambda { |color| Color.to_truecolor_bytes(color) }\n when ChunkyPNG::COLOR_TRUECOLOR_ALPHA then lambda { |color| Color.to_truecolor_alpha_bytes(color) }\n when ChunkyPNG::COLOR_INDEXED then lambda { |color| [encoding_palette.index(color)] }\n when ChunkyPNG::COLOR_GRAYSCALE then lambda { |color| Color.to_grayscale_bytes(color) }\n when ChunkyPNG::COLOR_GRAYSCALE_ALPHA then lambda { |color| Color.to_grayscale_alpha_bytes(color) }\n else raise ChunkyPNG::NotSupported, \"Cannot encode pixels for this mode: #{color_mode}!\"\n end\n\n previous_bytes = Array.new(pixel_size * width, 0)\n each_scanline do |line|\n unencoded_bytes = line.map(&pixel_encoder).flatten\n stream << encode_png_scanline_paeth(unencoded_bytes, previous_bytes, pixel_size).pack('C*')\n previous_bytes = unencoded_bytes\n end\n end\n end", "def save(path='result.jpg')\n @canvas.write(path)\n end", "def convert_jpg_to_png(img_path)\n print_status(\"Converting #{img_path} back to PNG\")\n basename = File.basename(img_path, '.jpg')\n img = MiniMagick::Image.open(img_path)\n img.format('PNG')\n dst = \"#{WORKFOLDER}/#{basename}.png\"\n img.write(dst)\n dst\nend", "def generate(write_path, size_type)\n if SUPPORTED_FILE_TYPES.include? File.extname(read_path)\n image = Magick::Image.read(read_path).first\n write_image image, write_path, size_type\n else\n write_default_image write_path, size_type\n end\n end", "def write_out(path = nil)\n return img unless path\n FileUtils.mkdir_p File.dirname(path)\n img.write(path)\n path\n rescue Errno::ENOENT\n puts_and_exit(\"Path not found '#{path}'\")\n end", "def write!(opts = {})\n if requires_output_file?\n raise NoMethodError, \"You cannot use Image#write(output) with \"\\\n \"the #{current_utility} command\"\n end\n\n command = build_command(path)\n run(command, opts)\n self\n end", "def export(filename_or_io, options = {})\n format = self.class.extract_format(filename_or_io, options)\n\n size = FFI::MemoryPointer.new(:pointer)\n\n case format\n when :jpeg, :jpg\n write_sym = :gdImageJpegPtr\n args = [size, options.delete(:quality) || -1]\n when :png\n write_sym = :gdImagePngPtrEx\n args = [size, options.delete(:level) || -1]\n when :gif\n write_sym = :gdImageGifPtr\n args = [size]\n when :wbmp\n write_sym = :gdImageWBMPPtr\n fgcolor = options.delete(:fgcolor)\n raise ArgumentError, 'Missing required option :fgcolor' if fgcolor.nil?\n\n args = [size, color2pixel(fgcolor)]\n when :gd\n write_sym = :gdImageGdPtr\n args = [size]\n when :gd2\n write_sym = :gdImageGd2Ptr\n args = [options.delete(:chunk_size) || 0, options.delete(:fmt) || FMT_COMPRESSED, size]\n else\n raise UnrecognizedImageTypeError, 'Format (or file extension) is not recognized'\n end\n\n output = case filename_or_io\n when String\n File.open(filename_or_io, 'wb')\n else\n filename_or_io\n end\n\n begin\n img = ::GD2::GD2FFI.send(write_sym, image_ptr, *args)\n output.write(img.get_bytes(0, size.get_int(0)))\n ensure\n ::GD2::GD2FFI.gdFree(img)\n end\n\n output.flush\n output.rewind\n\n output\n end", "def compress_png(input, quality = 80, output = nil)\n # Override file if no output selected\n output = input if output.nil?\n\n # PNGQuant does not allow update in place, so we save in a temp file\n output_tmp = Tempfile.new('temp_png').path\n\n options = [\n input.shellescape,\n '--force',\n \"--quality 01-#{quality}\",\n \"--output #{output_tmp.shellescape}\"\n ]\n\n command = \"pngquant #{options.join(' ')}\"\n `#{command}`\n\n # Move the tmp file back to the real output\n FileUtils.mv(output_tmp, output)\n\n output\n end", "def save\n\n properties = {}\n # exif = {}\n # KCGImagePropertyExifDictionary\n # exif[KCGImagePropertyExifUserComment] = 'Image downloaded from www.sheetmusicplus.com'\n # exif[KCGImagePropertyExifAuxOwnerName] = 'www.sheetmusicplus.com'\n if @filetype == :pdf\n CGPDFContextEndPage(@ctx)\n CGContextFlush(@ctx)\n return\n elsif @filetype == :png\n format = NSPNGFileType\n elsif @filetype == :tif\n format = NSTIFFFileType\n properties[NSImageCompressionMethod] = NSTIFFCompressionLZW\n #properties[NSImageCompressionMethod] = NSTIFFCompressionNone\n elsif @filetype == :gif\n format = NSGIFFileType\n #properties[NSImageDitherTransparency] = 0 # 1 = dithered, 0 = not dithered\n #properties[NSImageRGBColorTable] = nil # For GIF input and output. It consists of a 768 byte NSData object that contains a packed RGB table with each component being 8 bits.\n elsif @filetype == :jpg\n format = NSJPEGFileType\n properties[NSImageCompressionFactor] = @quality # (jpeg compression, 0.0 = max, 1.0 = none)\n #properties[NSImageEXIFData] = exif\n end\n cgimageref = CGBitmapContextCreateImage(@ctx) # => CGImageRef\n bitmaprep = NSBitmapImageRep.alloc.initWithCGImage(cgimageref) # => NSBitmapImageRep\n blob = bitmaprep.representationUsingType(format, properties:properties) # => NSConcreteData\n blob.writeToFile(@output, atomically:true)\n true\n end", "def export_image(filepath, seconds)\n # TODO support more file types\n type = case File.extname(filepath).downcase\n when '.pct', '.pict' then 'PICT'\n when '.tif', '.tiff' then 'TIFF'\n when '.jpg', '.jpeg' then 'JPEG'\n when '.png' then 'PNGf'\n when '.tga' then 'TPIC'\n when '.bmp' then 'BMPf'\n when '.psd' then '8BPS'\n else raise QuickTime::Error, \"Unable to guess ostype from file extension of #{filepath}\"\n end\n export_image_type(filepath, seconds, type)\n end", "def export_image(filepath, seconds)\n # TODO support more file types\n type = case File.extname(filepath).downcase\n when '.pct', '.pict' then 'PICT'\n when '.tif', '.tiff' then 'TIFF'\n when '.jpg', '.jpeg' then 'JPEG'\n when '.png' then 'PNGf'\n when '.tga' then 'TPIC'\n when '.bmp' then 'BMPf'\n when '.psd' then '8BPS'\n else raise QuickTime::Error, \"Unable to guess ostype from file extension of #{filepath}\"\n end\n export_image_type(filepath, seconds, type)\n end", "def write(file_name = 'graph.png')\n to_image.write(file_name)\n end", "def resize_and_write_file(filename, filename_output, max_width, max_height = nil)\n pic = Magick::Image.read(filename).first\n img_width, img_height = pic.columns, pic.rows\n ratio = img_width.to_f / max_width.to_f\n\n if max_height.nil?\n max_height = img_height / ratio\n end\n\n pic.change_geometry!(\"#{max_width}x#{max_height}>\") { |cols, rows, img|\n img.resize_to_fit!(cols, rows)\n img.write filename_output\n img.destroy!\n }\n\n nbytes, content = File.size(filename_output), nil\n File.open(filename_output, \"rb\") { |f| content = f.read nbytes }\n content\nend", "def write(output_filename:, quality: 10)\n out_image = ImageList.new\n\n # Add rows to big picture\n @rows.values.each do |row|\n out_image.push(row.append(false))\n end\n\n out_image.append(true).write(output_filename) do\n self.format = \"JPEG\"\n self.quality = quality\n end\n end", "def write_out\n File.delete(@path) if File.exist?(@path)\n File.open(@path, mode: 'w', encoding: @img_data.encoding) { |f| f.write(@img_data) }\n end", "def process\n format = directives.fetch(:format, 'jpg')\n encode_file(format, directives)\n end", "def upRes(file_path)\t\n\t\toriginal_image = Magick::Image.read(file_path) { self.density = \"300.0x300.0\" }\n\t\toriginal_image.each do |image|\n\t\t\t image = image.resample(300.0, 300.0)\n\t\t\t image.write(file_path) { self.quality = 100 }\n\t\tend\n\tend", "def export(filename)\n @image.save(filename, :interlace => true)\n end", "def write_to_image(x, y, color)\n\t\t\t@image.pixel_color(x, y, color)\n\t\t\t@image.write(@file_name)\n\t\tend", "def resize(path)\n gravity = @options.key?(:gravity) ? @options[:gravity] : 'Center'\n\n img = MiniMagick::Image.open(@file)\n cols, rows = img[:dimensions]\n\n img.combine_options do |cmd|\n if @width != cols || @height != rows\n scale_x = @width/cols.to_f\n scale_y = @height/rows.to_f\n\n if scale_x >= scale_y\n cols = (scale_x * (cols + 0.5)).round\n rows = (scale_x * (rows + 0.5)).round\n cmd.resize \"#{cols}\"\n else\n cols = (scale_y * (cols + 0.5)).round\n rows = (scale_y * (rows + 0.5)).round\n cmd.resize \"x#{rows}\"\n end\n end\n\n cmd.quality @options[:quality] if @options.key?(:quality)\n cmd.gravity gravity\n cmd.background 'rgba(255,255,255,0.0)'\n cmd.extent \"#{@width}x#{@height}\" if cols != @width || rows != @height\n end\n\n img.write(path)\n end", "def png(*args)\n PNG.write(@source, *args)\n end", "def write_image(image, write_path, size_type)\n size = find_size size_type\n image.resize_to_fill!(size[0], size[1]) if size_type\n image.format = \"PNG\" if image.format == \"SVG\"\n write_path.gsub!(/.svg/i, \".png\")\n image.write write_path\n end", "def compress!\n File.open(@file_path, 'w') { |file| file.write(output) } if compress.modified?\n self\n end", "def process_image(path)\n picture_name = File.basename(path)\n thumbnail_dir = File.join(File.dirname(path), \"thumbnails\")\n thumbnail_path = File.join(thumbnail_dir, \"#{File.basename(picture_name, File.extname(picture_name))}.jpg\")\n Dir.mkdir(thumbnail_dir) unless File.exist?(thumbnail_dir)\n\n image_optim = ImageOptim.new\n\n image = MiniMagick::Image.open(path)\n image_prop = {\n \"name\" => picture_name,\n \"thumb\" => \"thumbnails/#{picture_name}\",\n \"height\" => image.height,\n \"width\" => image.width\n }\n\n return image_prop if File.exist?(thumbnail_path)\n\n# -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB\n\n image.format \"jpeg\" unless File.extname(picture_name) == \"jpg\"\n image.combine_options do |b|\n b.resize \"#{MAX_DIMENSION}>\"\n b.sampling_factor \"4:2:0\"\n b.strip\n b.interlace \"JPEG\"\n b.colorspace \"RGB\"\n b.quality 85\n end\n image.write thumbnail_path\n\n image_optim.optimize_image!(path)\n image_optim.optimize_image!(thumbnail_path)\n\n image_prop\nend", "def resize_image(file_name,resize_file_name=\"test\",resized_width=0,resized_height=0,render_file_as=\"png\")\n image = Image.import(file_name)\n resize_image = image.resize(resized_width, resized_height,true)\n\n file=File.new(resize_file_name,\"wb\")\n if render_file_as == \"png\"\n file.write resize_image.png\n elsif\t render_file_as == \"jpeg\"\n file.write resize_image.jpeg\n elsif\t render_file_as == \"gd\"\n file.write resize_image.gd\n elsif\t render_file_as == \"gd2\"\n file.write resize_image.gd2\n else\n puts \"Provide proper image\"\n end\n file.close\n end", "def convert_to_jpg(quality, image_file, opts = {})\n data, _status_code, _headers = convert_to_jpg_with_http_info(quality, image_file, opts)\n data\n end", "def write_image(&block)\n @image = GD2::Image.new(@width, @height)\n self.instance_eval(&block)\n @image.export(self.full_path)\n end", "def write_to(filename, options = {})\n # Gzip contents if filename has '.gz'\n options[:compress] ||= File.extname(filename) == '.gz'\n\n FileUtils.mkdir_p File.dirname(filename)\n\n File.open(\"#{filename}+\", 'wb') do |f|\n if options[:compress]\n # Run contents through `Zlib`\n gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)\n gz.write to_s\n gz.close\n else\n # Write out as is\n f.write to_s\n f.close\n end\n end\n\n # Atomic write\n FileUtils.mv(\"#{filename}+\", filename)\n\n # Set mtime correctly\n File.utime(mtime, mtime, filename)\n\n nil\n ensure\n # Ensure tmp file gets cleaned up\n FileUtils.rm(\"#{filename}+\") if File.exist?(\"#{filename}+\")\n end", "def save_image(filename)\n\t\t@image.save(filename, :interlace => true)\t\t\n\tend", "def to_jpg(*a)\n to_blob('jpg', *a)\n end", "def export_to_jpg file\n width = @panel.get_width\n height = @panel.get_height\n\n buffered_image = BufferedImage.new width, height, BufferedImage::TYPE_INT_RGB\n graphics = buffered_image.create_graphics\n @panel.paint(graphics);\n\n cropping_rectangle = self.get_bounding_rectangle\n cropped_image = buffered_image.get_subimage cropping_rectangle.get_x,\n cropping_rectangle.get_y,\n cropping_rectangle.get_width,\n cropping_rectangle.get_height\n\n output_file = java.io.File.new file\n\n ImageIO.write cropped_image, \"jpg\", output_file\n\n end", "def compress(directory, file)\n compression.compress_command + [file, directory]\n end", "def compress(folder, file, options={})\n format = COMPRESS_FORMAT[File.extname(file)]\n if format\n __send__(format, folder, file, options)\n else\n raise ArgumentError, \"unknown compression format -- #{format}\"\n end\n end", "def write(dir = self.dir, filename = self.filename)\n FileUtils.mkdir_p(File.join(WRITE_DIR, dir))\n self.image.write(File.join(WRITE_DIR, dir, filename))\n end", "def save_img(filename)\n @img.save(filename, :fast_rgb)\n end", "def write filename, compress=nil\n STDERR.puts(\"Writing #{self.inspect} to #{filename}\")\n x = super(filename)\n `gzip #{filename}` if compress\n x\n end", "def via_files(filename, thumbnail_width)\n thumb = Vips::Image.thumbnail filename, thumbnail_width, crop: \"centre\"\n\n thumb.write_to_buffer \".jpg\"\nend", "def manipulate!(save_image = false)\n cache_stored_file! if !cached?\n @_gimage ||= ::GraphicsMagick::Image.new(current_path)\n @_gimage = yield(@_gimage)\n @_image.write(current_path) if save_image\n @_gimage\n rescue => e\n raise CarrierWave::ProcessingError.new(\"Failed to manipulate file! #{e}\")\n end", "def png(file)\n file.write PNG_HEADER\n\n # Make sure IEND is actually at the end (Ruby 1.9).\n iend = @chunks.delete 'IEND'\n @chunks['IEND'] = iend\n\n @chunks.each do |type, data|\n data.each do |data_part|\n file.write [data_part.length, type].pack('NA*')\n file.write data_part\n file.write [Zlib::crc32(type + data_part)].pack('N')\n end\n end\n end", "def create_modified_jpeg(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :POST, 'File')\n end", "def save_as(filename, size = :medium)\n format = size.to_sym == :original ? self.original_format : 'jpg'\n filename = \"#{filename}.#{format}\"\n\n if File.exists?(filename) or not self.url(size)\n false\n else\n f = File.new(filename, 'w+')\n f.puts open(self.url(size)).read\n f.close\n f\n end\n end", "def encode(format, options = {})\n # Sorry .jpeg lovers, I'm one of you too but the standard is jpg\n format = 'jpg' if format.to_s == 'jpeg'\n format = format.to_s\n \n raise ArgumentError, \"invalid format: #{format}\" unless %w(jpg png gif).include?(format)\n \n @canvas.encode format, options\n end", "def to_jpg(*a)\n to_image(*a).to_blob{|i| i.format = 'jpg' }\n end", "def use_jpeg?(_user = nil)\n CONFIG[\"jpeg_enable\"] && has_jpeg?\n end", "def thumbnail_file(input_path, output_path, options = {})\n opts = {\n :format => File.extname(output_path).sub(/^\\./, '')\n }.merge(options)\n \n data = SmartImage.thumbnail File.read(input_path), opts\n File.open(output_path, 'w') { |file| file << data }\n end", "def write_file!\n file = File.new( path, \"w\")\n \n file.write(@source)\n file.close\n end", "def write(output, opts = {})\n output_path = parse_input(output, false)\n\n FileUtils.copy_file(path, output_path) unless requires_output_file?\n\n command = build_command(output_path)\n run(command, opts)\n GraphicsMagick::Image.new(output_path)\n end", "def write_gpx filename, gpx\n $stderr.puts \"Writing #{filename}\" if $verbose\n File.open filename, 'w:UTF-8' do |file|\n file.write gpx\n end\nend", "def save(data, path, format=nil)\n \t\tformat ||= get_format(path)\n\n\t\t\tinit_encoder(data)\n\n \t\tcase format.to_sym\n \t\t\twhen :jpg, :jpeg\n \t\t\t\tres = save_as_jpeg(path)\n \t\t\twhen :png\n \t\t\t\tres = save_as_png(path)\n \t\t\twhen :tiff, :tif\n \t\t\t\tres = save_as_tiff(path)\n \t\t\twhen :eps\n \t\t\t\tres = save_as_eps(path)\n \t\t\telse\n \t\t\t close; raise RQR::FormatNotFoundException.new(\"invalid format! #{format}\")\n \t\tend\n \n close\n \n if res != 0\n raise RQR::ImageException.new(\"qrcode image error! #{path} wasn't created.\")\n \t\tend\n \tend", "def compress_file!(file_name)\n zipped = \"#{file_name}.gz\"\n Zlib::GzipWriter.open(zipped) do |gz|\n gz.mtime = File.mtime(file_name)\n gz.orig_name = file_name\n gz.write File.binread(file_name)\n end\n p \" compressing (gzip) #{file_name} - before: #{File.size(file_name)} after: #{File.size(zipped)}\"\n zipped\n end", "def img_to_pdf(file, outdir)\n img = Magick::Image.read(file[:path]).first\n # resize the image if its too big (e.g., taken with a digital camera)\n if img.columns > 1000 || img.rows > 1000\n # resize such that it's 1000px in width\n scale = 1\n if img.columns > img.rows\n scale = 1000.0 / img.columns\n else\n scale = 1000.0 / img.rows\n end\n img = img.resize(scale)\n end\n img.write(\"pdf:#{outdir}\") { self.quality = 75 }\n end", "def write(output_filename)\n Trace::get_logger.info('Image.write') { \"Writing output file...\" }\n \n output_file = ChunkyPNG::Image.new(@width, @height, ChunkyPNG::Color::TRANSPARENT)\n \n @width.times do |x|\n @height.times do |y|\n output_file[x,y] = @pixels[[x,y]].get_color\n end\n end\n \n output_file.save(\"#{output_filename}.png\", :interlace => false)\n end", "def export(filename)\n @image.save(filename, interlace: true)\n end", "def uploadoriginal(file,path)\n\text = File.extname(file)\n \tif ext.upcase == \".JPG\"\n \t\textfinal = \".jpg\"\n \telsif ext.upcase == \".JPEG\"\n \t\textfinal = \".jpg\"\n \telsif ext.upcase == \".GIF\"\n \t\textfinal = \".gif\"\n \telsif ext.upcase == \".PNG\"\n \t\textfinal = \".png\"\n \tend\t\n\t\t\n\t\t\n \t#nombre original de la imagen\n \tfilename_orig = File.basename(file, '.*')\n\n \t#remove white space in image name\n \tfilename_orig = filename_orig.gsub(\" \",\"-\")\n\n \twidth = 800\n\n \timage = Magick::Image.read(file).first\n\n \twidthimage = image.columns\n \theightimage = image.rows\n \theight = (width * heightimage) / widthimage\n \tthumbnail = image.thumbnail(width, height)\n\n\n \tfinalname = path + \"800-\" + filename_orig + extfinal\n \tq=99\n \tthumbnail.write(finalname){ self.quality = q }\n return filename_orig + extfinal\n \nend", "def create_png_file(png_file_path, colors, matrix, square_size)\n if png_file_path =~ /\\.png$/i\n ppm_file_path = png_file_path.gsub(/\\.png$/, '.ppm')\n else\n ppm_file_path = png_file_path + '.ppm'\n end\n\n if !create_ppm_file(ppm_file_path, colors, matrix, square_size)\n return false\n end\n\n system(\"#{PNG_CONVERTER} #{ppm_file_path} #{png_file_path}\")\n if $?.exited? && $?.exitstatus == 0\n result = true\n else\n result = false\n end\n\n File.delete(ppm_file_path)\n return result\nend", "def operation(*args)\n src_file, out_file = args\n image = Vips::Image.new_from_file src_file\n factor = public_send options[:method], image.size\n image.resize(factor).write_to_file out_file\n end", "def save_cropped_image(src, dest, x, y, width, height, quality = 75)\n if src.is_a? Magick::Image\n img = src\n else\n img = Magick::Image::read(src).first\n end\n\n quality = quality * 100 if quality < 1\n\n # The crop method retains the offset information in the cropped image.\n # To reset the offset data, adding true as the last argument to crop.\n cropped = img.crop(x, y, width, height, true)\n cropped.write(dest) { @quality = quality }\n end", "def write(output_path)\n FileUtils.copy_file @path, output_path\n run_command \"identify\", output_path # Verify that we have a good image\n end", "def process_image(src, dest, maxw, maxh)\n i = QuickMagick::Image.read(src).first\n # AMF - added quality setting to limit size of images (some sites had high quality jpeg, so files sizes were still big)\n i.quality = 75\n w, h = i.width, i.height\n extra = (w - h/(maxh.to_f/maxw.to_f)).to_i\n if extra > 0\n i.shave(\"#{extra>>1}x0\") if i.width > i.height\n w -= extra\n end\n if w > maxw or h > maxh\n i.resize(\"#{maxw}x#{maxh}\")\n end\n i.save(dest)\n end", "def bgsave; end", "def bgsave; end", "def blob_generate(write_path, size_type = nil)\n if SUPPORTED_FILE_TYPES.include? File.extname(write_path)\n image = Magick::Image.from_blob(read_path).first\n write_image image, write_path, size_type\n else\n write_default_image write_path, size_type\n end\n end", "def generate_thumbnail path, img\n img = img.resize_to_fit 200,200\n img.write path\n end", "def test_progressive_dct_based_jpeg_image\n testname = '35w x 35h progressive jpeg image.'\n data = %w(\n FF D8 FF E0 00 10 4A 46 49 46 00 01 02 01 00 96\n 00 96 00 00 FF E1 04 E7 45 78 69 66 00 00 4D 4D\n 00 2A 00 00 00 08 00 07 01 12 00 03 00 00 00 01\n 00 01 00 00 01 1A 00 05 00 00 00 01 00 00 00 62\n 01 1B 00 05 00 00 00 01 00 00 00 6A 01 28 00 03\n 00 00 00 01 00 02 00 00 01 31 00 02 00 00 00 14\n 00 00 00 72 01 32 00 02 00 00 00 14 00 00 00 86\n 87 69 00 04 00 00 00 01 00 00 00 9C 00 00 00 C8\n 00 00 00 96 00 00 00 01 00 00 00 96 00 00 00 01\n 41 64 6F 62 65 20 50 68 6F 74 6F 73 68 6F 70 20\n 37 2E 30 00 32 30 30 38 3A 30 39 3A 30 39 20 32\n 32 3A 32 33 3A 31 32 00 00 00 00 03 A0 01 00 03\n 00 00 00 01 FF FF 00 00 A0 02 00 04 00 00 00 01\n 00 00 00 23 A0 03 00 04 00 00 00 01 00 00 00 23\n 00 00 00 00 00 00 00 06 01 03 00 03 00 00 00 01\n 00 06 00 00 01 1A 00 05 00 00 00 01 00 00 01 16\n 01 1B 00 05 00 00 00 01 00 00 01 1E 01 28 00 03\n 00 00 00 01 00 02 00 00 02 01 00 04 00 00 00 01\n 00 00 01 26 02 02 00 04 00 00 00 01 00 00 03 B9\n 00 00 00 00 00 00 00 48 00 00 00 01 00 00 00 48\n 00 00 00 01 FF D8 FF E0 00 10 4A 46 49 46 00 01\n 02 01 00 48 00 48 00 00 FF ED 00 0C 41 64 6F 62\n 65 5F 43 4D 00 02 FF EE 00 0E 41 64 6F 62 65 00\n 64 80 00 00 00 01 FF DB 00 84 00 0C 08 08 08 09\n 08 0C 09 09 0C 11 0B 0A 0B 11 15 0F 0C 0C 0F 15\n 18 13 13 15 13 13 18 11 0C 0C 0C 0C 0C 0C 11 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 01 0D 0B 0B 0D\n 0E 0D 10 0E 0E 10 14 0E 0E 0E 14 14 0E 0E 0E 0E\n 14 11 0C 0C 0C 0C 0C 11 11 0C 0C 0C 0C 0C 0C 11\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C FF C0 00 11\n 08 00 23 00 23 03 01 22 00 02 11 01 03 11 01 FF\n DD 00 04 00 03 FF C4 01 3F 00 00 01 05 01 01 01\n 01 01 01 00 00 00 00 00 00 00 03 00 01 02 04 05\n 06 07 08 09 0A 0B 01 00 01 05 01 01 01 01 01 01\n 00 00 00 00 00 00 00 01 00 02 03 04 05 06 07 08\n 09 0A 0B 10 00 01 04 01 03 02 04 02 05 07 06 08\n 05 03 0C 33 01 00 02 11 03 04 21 12 31 05 41 51\n 61 13 22 71 81 32 06 14 91 A1 B1 42 23 24 15 52\n C1 62 33 34 72 82 D1 43 07 25 92 53 F0 E1 F1 63\n 73 35 16 A2 B2 83 26 44 93 54 64 45 C2 A3 74 36\n 17 D2 55 E2 65 F2 B3 84 C3 D3 75 E3 F3 46 27 94\n A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56 66\n 76 86 96 A6 B6 C6 D6 E6 F6 37 47 57 67 77 87 97\n A7 B7 C7 D7 E7 F7 11 00 02 02 01 02 04 04 03 04\n 05 06 07 07 06 05 35 01 00 02 11 03 21 31 12 04\n 41 51 61 71 22 13 05 32 81 91 14 A1 B1 42 23 C1\n 52 D1 F0 33 24 62 E1 72 82 92 43 53 15 63 73 34\n F1 25 06 16 A2 B2 83 07 26 35 C2 D2 44 93 54 A3\n 17 64 45 55 36 74 65 E2 F2 B3 84 C3 D3 75 E3 F3\n 46 94 A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5\n 56 66 76 86 96 A6 B6 C6 D6 E6 F6 27 37 47 57 67\n 77 87 97 A7 B7 C7 FF DA 00 0C 03 01 00 02 11 03\n 11 00 3F 00 F5 54 0B 33 71 AB 79 AC BF 75 83 53\n 5B 01 7B 84 F1 B9 95 EE 73 54 F2 1C E6 D1 63 9B\n F4 9A C7 16 FC 40 5C F7 49 B7 1A FA 19 51 BF 23\n 1B 2C B4 3A EC 7B 2D 65 76 6E 23 DC FD 06 FB 58\n FF 00 A4 CB 92 53 1E B9 F5 9B 3E 96 DB 8D 83 D3\n B2 85 A7 DB 56 53 D8 1B 5C E9 EE 0F 7E E6 37 FE\n B8 AF FD 5B FD AA 71 9E EE A2 CB 6A 26 36 D7 7B\n C5 8F 07 5D EE DE 27 F4 7F 43 E9 21 E5 D5 85 8D\n 59 39 B9 04 56 EE 45 D9 6F F7 79 7A 6D 1E FF 00\n EA AB 9D 0A C3 67 4D AC 9A AC C7 01 CF 0C A6 D2\n 4B DA D0 E7 7A 61 FE A4 BF E8 7E FA 4A 74 12 49\n 24 94 FF 00 FF D0 F5 2B DA 5D 4D 8D 1C B9 A4 7D\n E1 66 F4 FB BA 7F 50 C3 C7 17 D4 CF 59 B5 33 F4\n 57 06 97 00 47 2D 9F CC 74 7D 26 2D 55 CC 7D 61\n CD 7F 40 38 66 BA 99 76 16 4D CE AD EC B8 4B 69\n 2E 06 C6 7A 76 0F 73 37 D9 EC D8 EF EC 24 A7 61\n 95 74 7C 70 6F 6B 28 AF 61 FE 72 1B 20 8F DD 77\n D2 44 E9 97 8C 8C 63 7B 5A E6 36 CB 2C 21 AE D1\n D0 1E EA F5 1F D8 58 1F 57 FA 95 DD 6B 23 25 B5\n D5 5E 23 31 F6 13 63 1A 1E F9 70 73 76 56 F7 7B\n 6A FE 6F 7F D0 FC F5 D3 63 D1 56 3D 2C A6 A6 ED\n AD 82 1A 12 52 44 92 49 25 3F FF D1 F5 55 47 AD\n C7 EC AC AD DE 84 7A 6E 9F B5 4F A3 11 FE 1B 67\n BF 67 F5 17 CC 69 24 A7 E9 6F AB BB 7F 66 55 B7\n EC BB 60 47 D8 B7 7A 5C 7F C2 7E 93 FC F5 A8 BE\n 55 49 25 3F 55 24 BE 55 49 25 3F FF D9 FF ED 09\n 94 50 68 6F 74 6F 73 68 6F 70 20 33 2E 30 00 38\n 42 49 4D 04 25 00 00 00 00 00 10 00 00 00 00 00\n 00 00 00 00 00 00 00 00 00 00 00 38 42 49 4D 03\n ED 00 00 00 00 00 10 00 96 00 00 00 01 00 01 00\n 96 00 00 00 01 00 01 38 42 49 4D 04 26 00 00 00\n 00 00 0E 00 00 00 00 00 00 00 00 00 00 3F 80 00\n 00 38 42 49 4D 04 0D 00 00 00 00 00 04 00 00 00\n 1E 38 42 49 4D 04 19 00 00 00 00 00 04 00 00 00\n 1E 38 42 49 4D 03 F3 00 00 00 00 00 09 00 00 00\n 00 00 00 00 00 01 00 38 42 49 4D 04 0A 00 00 00\n 00 00 01 00 00 38 42 49 4D 27 10 00 00 00 00 00\n 0A 00 01 00 00 00 00 00 00 00 01 38 42 49 4D 03\n F5 00 00 00 00 00 48 00 2F 66 66 00 01 00 6C 66\n 66 00 06 00 00 00 00 00 01 00 2F 66 66 00 01 00\n A1 99 9A 00 06 00 00 00 00 00 01 00 32 00 00 00\n 01 00 5A 00 00 00 06 00 00 00 00 00 01 00 35 00\n 00 00 01 00 2D 00 00 00 06 00 00 00 00 00 01 38\n 42 49 4D 03 F8 00 00 00 00 00 70 00 00 FF FF FF\n FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF\n FF FF FF 03 E8 00 00 00 00 FF FF FF FF FF FF FF\n FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 03\n E8 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF\n FF FF FF FF FF FF FF FF FF FF FF 03 E8 00 00 00\n 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF\n FF FF FF FF FF FF FF 03 E8 00 00 38 42 49 4D 04\n 08 00 00 00 00 00 10 00 00 00 01 00 00 02 40 00\n 00 02 40 00 00 00 00 38 42 49 4D 04 1E 00 00 00\n 00 00 04 00 00 00 00 38 42 49 4D 04 1A 00 00 00\n 00 03 59 00 00 00 06 00 00 00 00 00 00 00 00 00\n 00 00 23 00 00 00 23 00 00 00 12 00 54 00 43 00\n 50 00 5F 00 43 00 69 00 72 00 63 00 6C 00 65 00\n 5F 00 42 00 61 00 6C 00 6C 00 61 00 73 00 74 00\n 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00\n 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00\n 00 00 23 00 00 00 23 00 00 00 00 00 00 00 00 00\n 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00\n 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 01\n 00 00 00 00 00 00 6E 75 6C 6C 00 00 00 02 00 00\n 00 06 62 6F 75 6E 64 73 4F 62 6A 63 00 00 00 01\n 00 00 00 00 00 00 52 63 74 31 00 00 00 04 00 00\n 00 00 54 6F 70 20 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 4C 65 66 74 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 42 74 6F 6D 6C 6F 6E 67 00 00 00 23 00 00\n 00 00 52 67 68 74 6C 6F 6E 67 00 00 00 23 00 00\n 00 06 73 6C 69 63 65 73 56 6C 4C 73 00 00 00 01\n 4F 62 6A 63 00 00 00 01 00 00 00 00 00 05 73 6C\n 69 63 65 00 00 00 12 00 00 00 07 73 6C 69 63 65\n 49 44 6C 6F 6E 67 00 00 00 00 00 00 00 07 67 72\n 6F 75 70 49 44 6C 6F 6E 67 00 00 00 00 00 00 00\n 06 6F 72 69 67 69 6E 65 6E 75 6D 00 00 00 0C 45\n 53 6C 69 63 65 4F 72 69 67 69 6E 00 00 00 0D 61\n 75 74 6F 47 65 6E 65 72 61 74 65 64 00 00 00 00\n 54 79 70 65 65 6E 75 6D 00 00 00 0A 45 53 6C 69\n 63 65 54 79 70 65 00 00 00 00 49 6D 67 20 00 00\n 00 06 62 6F 75 6E 64 73 4F 62 6A 63 00 00 00 01\n 00 00 00 00 00 00 52 63 74 31 00 00 00 04 00 00\n 00 00 54 6F 70 20 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 4C 65 66 74 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 42 74 6F 6D 6C 6F 6E 67 00 00 00 23 00 00\n 00 00 52 67 68 74 6C 6F 6E 67 00 00 00 23 00 00\n 00 03 75 72 6C 54 45 58 54 00 00 00 01 00 00 00\n 00 00 00 6E 75 6C 6C 54 45 58 54 00 00 00 01 00\n 00 00 00 00 00 4D 73 67 65 54 45 58 54 00 00 00\n 01 00 00 00 00 00 06 61 6C 74 54 61 67 54 45 58\n 54 00 00 00 01 00 00 00 00 00 0E 63 65 6C 6C 54\n 65 78 74 49 73 48 54 4D 4C 62 6F 6F 6C 01 00 00\n 00 08 63 65 6C 6C 54 65 78 74 54 45 58 54 00 00\n 00 01 00 00 00 00 00 09 68 6F 72 7A 41 6C 69 67\n 6E 65 6E 75 6D 00 00 00 0F 45 53 6C 69 63 65 48\n 6F 72 7A 41 6C 69 67 6E 00 00 00 07 64 65 66 61\n 75 6C 74 00 00 00 09 76 65 72 74 41 6C 69 67 6E\n 65 6E 75 6D 00 00 00 0F 45 53 6C 69 63 65 56 65\n 72 74 41 6C 69 67 6E 00 00 00 07 64 65 66 61 75\n 6C 74 00 00 00 0B 62 67 43 6F 6C 6F 72 54 79 70\n 65 65 6E 75 6D 00 00 00 11 45 53 6C 69 63 65 42\n 47 43 6F 6C 6F 72 54 79 70 65 00 00 00 00 4E 6F\n 6E 65 00 00 00 09 74 6F 70 4F 75 74 73 65 74 6C\n 6F 6E 67 00 00 00 00 00 00 00 0A 6C 65 66 74 4F\n 75 74 73 65 74 6C 6F 6E 67 00 00 00 00 00 00 00\n 0C 62 6F 74 74 6F 6D 4F 75 74 73 65 74 6C 6F 6E\n 67 00 00 00 00 00 00 00 0B 72 69 67 68 74 4F 75\n 74 73 65 74 6C 6F 6E 67 00 00 00 00 00 38 42 49\n 4D 04 11 00 00 00 00 00 01 01 00 38 42 49 4D 04\n 14 00 00 00 00 00 04 00 00 00 01 38 42 49 4D 04\n 0C 00 00 00 00 03 D5 00 00 00 01 00 00 00 23 00\n 00 00 23 00 00 00 6C 00 00 0E C4 00 00 03 B9 00\n 18 00 01 FF D8 FF E0 00 10 4A 46 49 46 00 01 02\n 01 00 48 00 48 00 00 FF ED 00 0C 41 64 6F 62 65\n 5F 43 4D 00 02 FF EE 00 0E 41 64 6F 62 65 00 64\n 80 00 00 00 01 FF DB 00 84 00 0C 08 08 08 09 08\n 0C 09 09 0C 11 0B 0A 0B 11 15 0F 0C 0C 0F 15 18\n 13 13 15 13 13 18 11 0C 0C 0C 0C 0C 0C 11 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 01 0D 0B 0B 0D 0E\n 0D 10 0E 0E 10 14 0E 0E 0E 14 14 0E 0E 0E 0E 14\n 11 0C 0C 0C 0C 0C 11 11 0C 0C 0C 0C 0C 0C 11 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C FF C0 00 11 08\n 00 23 00 23 03 01 22 00 02 11 01 03 11 01 FF DD\n 00 04 00 03 FF C4 01 3F 00 00 01 05 01 01 01 01\n 01 01 00 00 00 00 00 00 00 03 00 01 02 04 05 06\n 07 08 09 0A 0B 01 00 01 05 01 01 01 01 01 01 00\n 00 00 00 00 00 00 01 00 02 03 04 05 06 07 08 09\n 0A 0B 10 00 01 04 01 03 02 04 02 05 07 06 08 05\n 03 0C 33 01 00 02 11 03 04 21 12 31 05 41 51 61\n 13 22 71 81 32 06 14 91 A1 B1 42 23 24 15 52 C1\n 62 33 34 72 82 D1 43 07 25 92 53 F0 E1 F1 63 73\n 35 16 A2 B2 83 26 44 93 54 64 45 C2 A3 74 36 17\n D2 55 E2 65 F2 B3 84 C3 D3 75 E3 F3 46 27 94 A4\n 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56 66 76\n 86 96 A6 B6 C6 D6 E6 F6 37 47 57 67 77 87 97 A7\n B7 C7 D7 E7 F7 11 00 02 02 01 02 04 04 03 04 05\n 06 07 07 06 05 35 01 00 02 11 03 21 31 12 04 41\n 51 61 71 22 13 05 32 81 91 14 A1 B1 42 23 C1 52\n D1 F0 33 24 62 E1 72 82 92 43 53 15 63 73 34 F1\n 25 06 16 A2 B2 83 07 26 35 C2 D2 44 93 54 A3 17\n 64 45 55 36 74 65 E2 F2 B3 84 C3 D3 75 E3 F3 46\n 94 A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56\n 66 76 86 96 A6 B6 C6 D6 E6 F6 27 37 47 57 67 77\n 87 97 A7 B7 C7 FF DA 00 0C 03 01 00 02 11 03 11\n 00 3F 00 F5 54 0B 33 71 AB 79 AC BF 75 83 53 5B\n 01 7B 84 F1 B9 95 EE 73 54 F2 1C E6 D1 63 9B F4\n 9A C7 16 FC 40 5C F7 49 B7 1A FA 19 51 BF 23 1B\n 2C B4 3A EC 7B 2D 65 76 6E 23 DC FD 06 FB 58 FF\n 00 A4 CB 92 53 1E B9 F5 9B 3E 96 DB 8D 83 D3 B2\n 85 A7 DB 56 53 D8 1B 5C E9 EE 0F 7E E6 37 FE B8\n AF FD 5B FD AA 71 9E EE A2 CB 6A 26 36 D7 7B C5\n 8F 07 5D EE DE 27 F4 7F 43 E9 21 E5 D5 85 8D 59\n 39 B9 04 56 EE 45 D9 6F F7 79 7A 6D 1E FF 00 EA\n AB 9D 0A C3 67 4D AC 9A AC C7 01 CF 0C A6 D2 4B\n DA D0 E7 7A 61 FE A4 BF E8 7E FA 4A 74 12 49 24\n 94 FF 00 FF D0 F5 2B DA 5D 4D 8D 1C B9 A4 7D E1\n 66 F4 FB BA 7F 50 C3 C7 17 D4 CF 59 B5 33 F4 57\n 06 97 00 47 2D 9F CC 74 7D 26 2D 55 CC 7D 61 CD\n 7F 40 38 66 BA 99 76 16 4D CE AD EC B8 4B 69 2E\n 06 C6 7A 76 0F 73 37 D9 EC D8 EF EC 24 A7 61 95\n 74 7C 70 6F 6B 28 AF 61 FE 72 1B 20 8F DD 77 D2\n 44 E9 97 8C 8C 63 7B 5A E6 36 CB 2C 21 AE D1 D0\n 1E EA F5 1F D8 58 1F 57 FA 95 DD 6B 23 25 B5 D5\n 5E 23 31 F6 13 63 1A 1E F9 70 73 76 56 F7 7B 6A\n FE 6F 7F D0 FC F5 D3 63 D1 56 3D 2C A6 A6 ED AD\n 82 1A 12 52 44 92 49 25 3F FF D1 F5 55 47 AD C7\n EC AC AD DE 84 7A 6E 9F B5 4F A3 11 FE 1B 67 BF\n 67 F5 17 CC 69 24 A7 E9 6F AB BB 7F 66 55 B7 EC\n BB 60 47 D8 B7 7A 5C 7F C2 7E 93 FC F5 A8 BE 55\n 49 25 3F 55 24 BE 55 49 25 3F FF D9 00 38 42 49\n 4D 04 21 00 00 00 00 00 55 00 00 00 01 01 00 00\n 00 0F 00 41 00 64 00 6F 00 62 00 65 00 20 00 50\n 00 68 00 6F 00 74 00 6F 00 73 00 68 00 6F 00 70\n 00 00 00 13 00 41 00 64 00 6F 00 62 00 65 00 20\n 00 50 00 68 00 6F 00 74 00 6F 00 73 00 68 00 6F\n 00 70 00 20 00 37 00 2E 00 30 00 00 00 01 00 38\n 42 49 4D 04 06 00 00 00 00 00 07 00 08 01 01 00\n 01 01 00 FF E1 12 48 68 74 74 70 3A 2F 2F 6E 73\n 2E 61 64 6F 62 65 2E 63 6F 6D 2F 78 61 70 2F 31\n 2E 30 2F 00 3C 3F 78 70 61 63 6B 65 74 20 62 65\n 67 69 6E 3D 27 EF BB BF 27 20 69 64 3D 27 57 35\n 4D 30 4D 70 43 65 68 69 48 7A 72 65 53 7A 4E 54\n 63 7A 6B 63 39 64 27 3F 3E 0A 3C 3F 61 64 6F 62\n 65 2D 78 61 70 2D 66 69 6C 74 65 72 73 20 65 73\n 63 3D 22 43 52 22 3F 3E 0A 3C 78 3A 78 61 70 6D\n 65 74 61 20 78 6D 6C 6E 73 3A 78 3D 27 61 64 6F\n 62 65 3A 6E 73 3A 6D 65 74 61 2F 27 20 78 3A 78\n 61 70 74 6B 3D 27 58 4D 50 20 74 6F 6F 6C 6B 69\n 74 20 32 2E 38 2E 32 2D 33 33 2C 20 66 72 61 6D\n 65 77 6F 72 6B 20 31 2E 35 27 3E 0A 3C 72 64 66\n 3A 52 44 46 20 78 6D 6C 6E 73 3A 72 64 66 3D 27\n 68 74 74 70 3A 2F 2F 77 77 77 2E 77 33 2E 6F 72\n 67 2F 31 39 39 39 2F 30 32 2F 32 32 2D 72 64 66\n 2D 73 79 6E 74 61 78 2D 6E 73 23 27 20 78 6D 6C\n 6E 73 3A 69 58 3D 27 68 74 74 70 3A 2F 2F 6E 73\n 2E 61 64 6F 62 65 2E 63 6F 6D 2F 69 58 2F 31 2E\n 30 2F 27 3E 0A 0A 20 3C 72 64 66 3A 44 65 73 63\n 72 69 70 74 69 6F 6E 20 61 62 6F 75 74 3D 27 75\n 75 69 64 3A 34 37 38 34 61 35 39 66 2D 37 65 64\n 66 2D 31 31 64 64 2D 39 61 37 39 2D 61 31 62 66\n 63 38 33 61 61 63 63 36 27 0A 20 20 78 6D 6C 6E\n 73 3A 78 61 70 4D 4D 3D 27 68 74 74 70 3A 2F 2F\n 6E 73 2E 61 64 6F 62 65 2E 63 6F 6D 2F 78 61 70\n 2F 31 2E 30 2F 6D 6D 2F 27 3E 0A 20 20 3C 78 61\n 70 4D 4D 3A 44 6F 63 75 6D 65 6E 74 49 44 3E 61\n 64 6F 62 65 3A 64 6F 63 69 64 3A 70 68 6F 74 6F\n 73 68 6F 70 3A 34 37 38 34 61 35 39 64 2D 37 65\n 64 66 2D 31 31 64 64 2D 39 61 37 39 2D 61 31 62\n 66 63 38 33 61 61 63 63 36 3C 2F 78 61 70 4D 4D\n 3A 44 6F 63 75 6D 65 6E 74 49 44 3E 0A 20 3C 2F\n 72 64 66 3A 44 65 73 63 72 69 70 74 69 6F 6E 3E\n 0A 0A 3C 2F 72 64 66 3A 52 44 46 3E 0A 3C 2F 78\n 3A 78 61 70 6D 65 74 61 3E 0A 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 0A 3C 3F 78 70 61 63\n 6B 65 74 20 65 6E 64 3D 27 77 27 3F 3E FF EE 00\n 21 41 64 6F 62 65 00 64 40 00 00 00 01 03 00 10\n 03 02 03 06 00 00 00 00 00 00 00 00 00 00 00 00\n FF DB 00 84 00 01 01 01 01 01 01 01 01 01 01 01\n 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01\n 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01\n 02 02 02 02 02 02 02 02 02 02 02 03 03 03 03 03\n 03 03 03 03 03 01 01 01 01 01 01 01 01 01 01 01\n 02 02 01 02 02 03 03 03 03 03 03 03 03 03 03 03\n 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03\n 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03\n 03 03 03 03 03 03 FF C2 00 11 08 00 23 00 23 03\n )\n @image.__send__(\"process_jpg\", [data.join('')].pack('H*'))\n assert_equal(@type, @image.type)\n assert_equal(35, @image.width)\n assert_equal(35, @image.height)\n end", "def to_image(filename = 'filename.png')\n png = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color::TRANSPARENT)\n height.times do |j|\n width.times do |i|\n png[i, j] = ChunkyPNG::Color.rgb(\n (red[i, j] * 255).to_i,\n (green[i, j] * 255).to_i,\n (blue[i, j] * 255).to_i\n )\n end\n end\n png.save(filename, :interlace => true)\n end", "def write(path, colorize = false)\n end", "def write_to_file(file_name)\n header = \"P6 #{@width} #{@height} #{@max_val}\"\n File.open(file_name, \"wb\") do |file|\n file.puts(header)\n @raster.flatten!\n @raster.each_with_index do |byte, index|\n file.print byte.chr\n end\n end\n end", "def write(dest)\n dest_path = File.join(@dst_dir, @name)\n\n puts \"#{dest_path}\"\n\n return false if File.exist? dest_path and !modified?\n\n @@mtimes[path] = mtime\n\n FileUtils.mkdir_p(File.dirname(dest_path))\n image = ::MiniMagick::Image.open(path)\n\n @commands.each_pair do |command, arg|\n image.combine_options do |c|\n arg.each do |option|\n option.each {|command, value| c.send command,value}\n end\n end\n end\n\n image.format(@format, 1) if @format\n image.write dest_path\n puts \"Writing to #{dest_path}\"\n true\n end", "def create_gzip_file(file) \n unless (MIME::Types.type_for(file).first.try(:media_type)==\"image\" or MIME::Types.type_for(file).first.try(:raw_sub_type)==\"x-shockwave-flash\")\n file_name=file.gsub(\"#{Rails.root}/public/\",\"\")\n new_file_path=\"#{Rails.root}/s3_assets/#{file_name}\"\n base_name=File.basename(file)\n dir_name=new_file_path.gsub(base_name,\"\")\n #no need to compress image files\n FileUtils.mkdir_p(dir_name) unless File.directory? dir_name\n system(\"gzip -c #{file} > #{new_file_path}\")\n end\n end", "def to_jpg\n load_image\n end", "def end(args = {})\n \n if args[:file]\n file = args[:file]\n else\n if !args[:filename]\n file = \"#{@dir}/#{@name}.gif\"\n else\n file = \"#{@dir}/#{filename}\"\n end\n end\n \n rotate = args[:rotate] || 0\n step = args[:step] || 1\n max_width = args[:max_width] || Lava::DEFAULT_MAX_WIDTH\n max_height = args[:max_height] || Lava::DEFAULT_MAX_HEIGHT\n speed = args[:speed] || Lava::DEFAULT_SPEED\n \n \n rimages = Magick::ImageList.new\n (0 ... samples.count ).step(step).each do |i|\n s = samples[i]\n s.rimage.rotate! rotate\n s.rimage.resize_to_fit!(max_width, max_height)\n rimages << s.rimage\n end\n rimages.ticks_per_second = speed\n rimages.write(file)\n end", "def resize_image(img_path)\n img = MiniMagick::Image.open(img_path)\n print_status(\"Original #{img_path} dimension = #{img.height}x#{img.width}\")\n new_width = img.width - (img.width * REIZEPERT).to_i\n new_height = img.height - (img.height * REIZEPERT).to_i\n img = img.resize(\"#{new_width}x#{new_height}\")\n print_status(\"Resized #{img_path} dimension = #{img.height}x#{img.width}\")\n img.write(img_path)\nend", "def image\n assert_file!\n @image ||= ChunkyPNG::Image.from_file(@path)\n end", "def write(dest)\n dest_path = destination(dest)\n puts 'Create ... ' + dest_path\n return false if File.exist? dest_path and !modified?\n\n @@mtimes[path] = mtime\n\n FileUtils.mkdir_p(File.dirname(dest_path))\n image = ::MiniMagick::Image.open(path)\n image.combine_options do |c|\n @commands.each_pair do |command, arg|\n c.send command, arg\n end\n end\n image.write dest_path\n\n true\n end", "def quality(percentage)\n manipulate! do |img|\n img.write(current_path){ self.quality = percentage }\n img = yield(img) if block_given?\n img\n end\nend", "def compress!(img)\n puts 'Compressing image.'\n image_optim = ImageOptim.new(allow_lossy: true, verbose: false, skip_missing_workers: true, optipng: false,\n pngcrush: false, pngquant: { allow_lossy: true },\n advpng: false, pngout: false, svgo: false)\n image_optim.optimize_image(img)\n puts 'compressed.'\n end", "def upload\n to_png_file do |png_path|\n File.open(png_path, 'rb') do |file|\n S3.put_object bucket: Giffy::Configuration.aws.bucket, key: key, body: file\n end\n S3.put_object_acl acl: 'public-read', bucket: Giffy::Configuration.aws.bucket, key: key\n end\n end", "def upload\n to_png_file do |png_path|\n File.open(png_path, 'rb') do |file|\n S3.put_object bucket: Giffy::Configuration.aws.bucket, key: key, body: file\n end\n S3.put_object_acl acl: 'public-read', bucket: Giffy::Configuration.aws.bucket, key: key\n end\n end", "def write(path)\n File.unlink(path) if File.exists?(path)\n Zip::Archive.open(path, Zip::CREATE) { |zipfile|\n zipfile.add_buffer(INDEX_PATH, htmlize(index))\n @book.media.each { |mpath|\n zipfile.add_buffer(mpath, @book.read_media(mpath))\n }\n unless @book.cover == COVER_PATH\n zipfile.add_buffer(COVER_PATH, to_png_data(@book.cover))\n end\n }\n path\n end", "def write_file(data)\n\toutput_file = data.pack(\"C*\")\n\n\tbegin\n\t\tFile.open(\"stego_out.bmp\", \"w\") {|file| file.write(output_file)}\n\trescue\n\t\traise \"File's cooked\"\n\tend\nend", "def compress!\n compress\n \n File.open(@input_file, 'w') do |file|\n file.puts @compressed_css\n end\n end", "def write_image(filename, decoded_image)\r\n\r\n f = File.new \"./public/images/blog/#{filename}\", \"wb\"\r\n f.write(decoded_image)\r\n f.close if f\r\n\r\n end" ]
[ "0.62616533", "0.6066551", "0.59234285", "0.5789741", "0.57895213", "0.5787651", "0.5714007", "0.5708735", "0.56916076", "0.56242615", "0.560582", "0.55802304", "0.5488504", "0.5437542", "0.54049474", "0.53955424", "0.5385785", "0.5368424", "0.5361975", "0.5354941", "0.53473115", "0.52915853", "0.524004", "0.52163684", "0.52150816", "0.5193142", "0.51904756", "0.5152937", "0.5152937", "0.51460207", "0.5139249", "0.5127941", "0.5125806", "0.5108711", "0.51062185", "0.5084222", "0.50779706", "0.50760865", "0.5041885", "0.5024856", "0.5024592", "0.50213885", "0.5015015", "0.50033504", "0.49950483", "0.49931422", "0.49835816", "0.4970954", "0.49679983", "0.49661517", "0.49496612", "0.49432093", "0.49321485", "0.49109238", "0.49103254", "0.48989108", "0.48988602", "0.48906305", "0.4850734", "0.48496285", "0.4839828", "0.48331612", "0.482321", "0.4807894", "0.48049283", "0.48046327", "0.47868657", "0.4781074", "0.47778282", "0.47674906", "0.4754492", "0.47410554", "0.4733973", "0.47239697", "0.47192535", "0.47192395", "0.46981364", "0.4696038", "0.4696038", "0.46862644", "0.46756023", "0.46688503", "0.46634042", "0.46583593", "0.46554592", "0.46549746", "0.46529257", "0.4650026", "0.46466115", "0.4642394", "0.46419626", "0.4640904", "0.46401608", "0.4637595", "0.4630077", "0.4630077", "0.46160007", "0.46110046", "0.459915", "0.45953295" ]
0.7635153
0
:callseq: png(io_out) Writes the image to +io_out+ as compressed PNG data. Returns the number of bytes written. == Example i = Axon::JPEG('input.png') io_out = File.open('output.png', 'w') i.png(io_out) writes the image to output.png
def png(*args) PNG.write(@source, *args) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compress_png(input, quality = 80, output = nil)\n # Override file if no output selected\n output = input if output.nil?\n\n # PNGQuant does not allow update in place, so we save in a temp file\n output_tmp = Tempfile.new('temp_png').path\n\n options = [\n input.shellescape,\n '--force',\n \"--quality 01-#{quality}\",\n \"--output #{output_tmp.shellescape}\"\n ]\n\n command = \"pngquant #{options.join(' ')}\"\n `#{command}`\n\n # Move the tmp file back to the real output\n FileUtils.mv(output_tmp, output)\n\n output\n end", "def encode_png_image_pass_to_stream(stream, color_mode, compression = ZLib::DEFAULT_COMPRESSION)\n\n if compression < Zlib::BEST_COMPRESSION && color_mode == ChunkyPNG::COLOR_TRUECOLOR_ALPHA\n # Fast RGBA saving routine\n stream << pixels.pack(\"xN#{width}\" * height)\n \n elsif compression < Zlib::BEST_COMPRESSION && color_mode == ChunkyPNG::COLOR_TRUECOLOR\n # Fast RGB saving routine\n line_packer = 'x' + ('NX' * width)\n stream << pixels.pack(line_packer * height)\n \n else\n # Normal saving routine\n pixel_size = Color.bytesize(color_mode)\n pixel_encoder = case color_mode\n when ChunkyPNG::COLOR_TRUECOLOR then lambda { |color| Color.to_truecolor_bytes(color) }\n when ChunkyPNG::COLOR_TRUECOLOR_ALPHA then lambda { |color| Color.to_truecolor_alpha_bytes(color) }\n when ChunkyPNG::COLOR_INDEXED then lambda { |color| [encoding_palette.index(color)] }\n when ChunkyPNG::COLOR_GRAYSCALE then lambda { |color| Color.to_grayscale_bytes(color) }\n when ChunkyPNG::COLOR_GRAYSCALE_ALPHA then lambda { |color| Color.to_grayscale_alpha_bytes(color) }\n else raise ChunkyPNG::NotSupported, \"Cannot encode pixels for this mode: #{color_mode}!\"\n end\n\n previous_bytes = Array.new(pixel_size * width, 0)\n each_scanline do |line|\n unencoded_bytes = line.map(&pixel_encoder).flatten\n stream << encode_png_scanline_paeth(unencoded_bytes, previous_bytes, pixel_size).pack('C*')\n previous_bytes = unencoded_bytes\n end\n end\n end", "def export(filename_or_io, options = {})\n format = self.class.extract_format(filename_or_io, options)\n\n size = FFI::MemoryPointer.new(:pointer)\n\n case format\n when :jpeg, :jpg\n write_sym = :gdImageJpegPtr\n args = [size, options.delete(:quality) || -1]\n when :png\n write_sym = :gdImagePngPtrEx\n args = [size, options.delete(:level) || -1]\n when :gif\n write_sym = :gdImageGifPtr\n args = [size]\n when :wbmp\n write_sym = :gdImageWBMPPtr\n fgcolor = options.delete(:fgcolor)\n raise ArgumentError, 'Missing required option :fgcolor' if fgcolor.nil?\n\n args = [size, color2pixel(fgcolor)]\n when :gd\n write_sym = :gdImageGdPtr\n args = [size]\n when :gd2\n write_sym = :gdImageGd2Ptr\n args = [options.delete(:chunk_size) || 0, options.delete(:fmt) || FMT_COMPRESSED, size]\n else\n raise UnrecognizedImageTypeError, 'Format (or file extension) is not recognized'\n end\n\n output = case filename_or_io\n when String\n File.open(filename_or_io, 'wb')\n else\n filename_or_io\n end\n\n begin\n img = ::GD2::GD2FFI.send(write_sym, image_ptr, *args)\n output.write(img.get_bytes(0, size.get_int(0)))\n ensure\n ::GD2::GD2FFI.gdFree(img)\n end\n\n output.flush\n output.rewind\n\n output\n end", "def write(output_filename)\n Trace::get_logger.info('Image.write') { \"Writing output file...\" }\n \n output_file = ChunkyPNG::Image.new(@width, @height, ChunkyPNG::Color::TRANSPARENT)\n \n @width.times do |x|\n @height.times do |y|\n output_file[x,y] = @pixels[[x,y]].get_color\n end\n end\n \n output_file.save(\"#{output_filename}.png\", :interlace => false)\n end", "def compress_jpg(input, quality = 80, output = nil)\n unless output.nil?\n FileUtils.cp(input, output)\n input = output\n end\n\n options = [\n '-q -p -f',\n \"--max=#{quality}\",\n '--strip-all',\n '--all-progressive',\n input.shellescape\n ]\n\n command = \"jpegoptim #{options.join(' ')}\"\n `#{command}`\n\n return output unless output.nil?\n input\n end", "def png(file)\n file.write PNG_HEADER\n\n # Make sure IEND is actually at the end (Ruby 1.9).\n iend = @chunks.delete 'IEND'\n @chunks['IEND'] = iend\n\n @chunks.each do |type, data|\n data.each do |data_part|\n file.write [data_part.length, type].pack('NA*')\n file.write data_part\n file.write [Zlib::crc32(type + data_part)].pack('N')\n end\n end\n end", "def write(output_filename:, quality: 10)\n out_image = ImageList.new\n\n # Add rows to big picture\n @rows.values.each do |row|\n out_image.push(row.append(false))\n end\n\n out_image.append(true).write(output_filename) do\n self.format = \"JPEG\"\n self.quality = quality\n end\n end", "def convert_to_png(input_pdf, output_file)\n pdf = Magick::ImageList.new(input_pdf) { self.density = 200 }\n pdf.write(output_file)\nend", "def write_out\n File.delete(@path) if File.exist?(@path)\n File.open(@path, mode: 'w', encoding: @img_data.encoding) { |f| f.write(@img_data) }\n end", "def convert_png_to_jpg(img_path)\n print_status(\"Converting #{img_path} to JPG to reduce image quality to #{JPGQUALITY}\")\n basename = File.basename(img_path, '.png')\n img = MiniMagick::Image.open(img_path)\n img.format('JPEG')\n img.quality(JPGQUALITY)\n dst = \"#{WORKFOLDER}/#{basename}.jpg\"\n img.write(dst)\n dst\nend", "def jpeg(quality = nil)\n size = FFI::MemoryPointer.new(:pointer)\n ptr = ::GD2::GD2FFI.send(:gdImageJpegPtr, image_ptr, size, quality || -1)\n ptr.get_bytes(0, size.get_int(0))\n ensure\n ::GD2::GD2FFI.send(:gdFree, ptr)\n end", "def write(output, opts = {})\n output_path = parse_input(output, false)\n\n FileUtils.copy_file(path, output_path) unless requires_output_file?\n\n command = build_command(output_path)\n run(command, opts)\n GraphicsMagick::Image.new(output_path)\n end", "def png_to_ico!(filename_array, output_filename)\n png_to_ico(filename_array, output_filename, true)\n end", "def save_impl(format, file)\n ImageIO.write(@src, format, file)\n end", "def png_resize_to_ico(input_filename, sizes_array, output_filename)\n output_dir = ICO::Utils.png_to_sizes(input_filename, sizes_array)\n filename_array = Dir.glob(File.join(output_dir, '**/*'))\n png_to_ico(filename_array, output_filename)\n end", "def generate_compressed path, img\n img.write(path) { self.quality = 70 }\n end", "def encode_png_image_without_interlacing(color_mode, compression = ZLib::DEFAULT_COMPRESSION)\n stream = \"\"\n encode_png_image_pass_to_stream(stream, color_mode, compression)\n stream\n end", "def write_image(image, write_path, size_type)\n size = find_size size_type\n image.resize_to_fill!(size[0], size[1]) if size_type\n image.format = \"PNG\" if image.format == \"SVG\"\n write_path.gsub!(/.svg/i, \".png\")\n image.write write_path\n end", "def encode_png_pixelstream(color_mode = ChunkyPNG::COLOR_TRUECOLOR, interlace = ChunkyPNG::INTERLACING_NONE, compression = ZLib::DEFAULT_COMPRESSION)\n\n if color_mode == ChunkyPNG::COLOR_INDEXED && (encoding_palette.nil? || !encoding_palette.can_encode?)\n raise ChunkyPNG::ExpectationFailed, \"This palette is not suitable for encoding!\"\n end\n\n case interlace\n when ChunkyPNG::INTERLACING_NONE then encode_png_image_without_interlacing(color_mode, compression)\n when ChunkyPNG::INTERLACING_ADAM7 then encode_png_image_with_interlacing(color_mode, compression)\n else raise ChunkyPNG::NotSupported, \"Unknown interlacing method: #{interlace}!\"\n end\n end", "def main()\n img = ImageList.new($input)\n convert = ImageList.new\n page = Magick::Rectangle.new(0,0,0,0)\n $total_ops = (img.rows * img.columns).to_f\n\n for i in 0..img.rows\n for j in 0..img.columns\n pixel = generate_hex_pixel(rgb_to_hex(img.pixel_color(j,i)))\n convert << pixel\n page.x = j * pixel.columns\n page.y = i * pixel.rows\n pixel.page = page\n progress()\n end\n end\n\n puts 'Writing image, this could take a while...'\n convert.mosaic.write($output)\nend", "def write!(opts = {})\n if requires_output_file?\n raise NoMethodError, \"You cannot use Image#write(output) with \"\\\n \"the #{current_utility} command\"\n end\n\n command = build_command(path)\n run(command, opts)\n self\n end", "def png(level = nil)\n size = FFI::MemoryPointer.new(:pointer)\n ptr = ::GD2::GD2FFI.send(:gdImagePngPtrEx, image_ptr, size, level.to_i || -1)\n ptr.get_bytes(0, size.get_int(0))\n ensure\n ::GD2::GD2FFI.send(:gdFree, ptr)\n end", "def save\n\n properties = {}\n # exif = {}\n # KCGImagePropertyExifDictionary\n # exif[KCGImagePropertyExifUserComment] = 'Image downloaded from www.sheetmusicplus.com'\n # exif[KCGImagePropertyExifAuxOwnerName] = 'www.sheetmusicplus.com'\n if @filetype == :pdf\n CGPDFContextEndPage(@ctx)\n CGContextFlush(@ctx)\n return\n elsif @filetype == :png\n format = NSPNGFileType\n elsif @filetype == :tif\n format = NSTIFFFileType\n properties[NSImageCompressionMethod] = NSTIFFCompressionLZW\n #properties[NSImageCompressionMethod] = NSTIFFCompressionNone\n elsif @filetype == :gif\n format = NSGIFFileType\n #properties[NSImageDitherTransparency] = 0 # 1 = dithered, 0 = not dithered\n #properties[NSImageRGBColorTable] = nil # For GIF input and output. It consists of a 768 byte NSData object that contains a packed RGB table with each component being 8 bits.\n elsif @filetype == :jpg\n format = NSJPEGFileType\n properties[NSImageCompressionFactor] = @quality # (jpeg compression, 0.0 = max, 1.0 = none)\n #properties[NSImageEXIFData] = exif\n end\n cgimageref = CGBitmapContextCreateImage(@ctx) # => CGImageRef\n bitmaprep = NSBitmapImageRep.alloc.initWithCGImage(cgimageref) # => NSBitmapImageRep\n blob = bitmaprep.representationUsingType(format, properties:properties) # => NSConcreteData\n blob.writeToFile(@output, atomically:true)\n true\n end", "def save_impl(format, file)\n write_new_image format, FileImageOutputStream.new(file)\n end", "def write(io_or_file=\"chart.png\")\n return io_or_file.write(fetch) if io_or_file.respond_to?(:write)\n open(io_or_file, \"w+\") { |io| io.write(fetch) }\n end", "def jpeg(*args)\n case @source.components\n when 2,4 then @source = AlphaStripper.new(@source)\n end\n JPEG.write(@source, *args)\n end", "def write_image id, name_suffix=\"\"\n m_begin \"write_image\"\n filename = \"./temp/\" +id.to_s+name_suffix+\".gif\"\n get_image(id).write(filename)\n m_end \"write_image\"\n end", "def encode_png_image_with_interlacing(color_mode, compression = ZLib::DEFAULT_COMPRESSION)\n stream = \"\"\n 0.upto(6) do |pass|\n subcanvas = self.class.adam7_extract_pass(pass, self)\n subcanvas.encoding_palette = encoding_palette\n subcanvas.encode_png_image_pass_to_stream(stream, color_mode, compression)\n end\n stream\n end", "def convert_jpg_to_png(img_path)\n print_status(\"Converting #{img_path} back to PNG\")\n basename = File.basename(img_path, '.jpg')\n img = MiniMagick::Image.open(img_path)\n img.format('PNG')\n dst = \"#{WORKFOLDER}/#{basename}.png\"\n img.write(dst)\n dst\nend", "def quantize(content, colors = 256)\n raise PngError, \"pngquant not found in PATH=#{ENV['PATH']}\" unless which(\"pngquant\")\n out = \"\"\n exit_code, err_msg = Open3.popen3(\"pngquant #{colors}\") do |stdin, stdout, stderr, wait_thr|\n stdin.write(content)\n out << stdout.read\n [wait_thr.value, stderr.gets(nil)]\n end\n\n raise(PngError, err_msg) if exit_code != 0\n out\n end", "def write_png_from_svg(input, output, width, height)\n success = true\n begin\n Magick::Image.read(input).first.resize(width, height).write(output)\n rescue\n success = false\n end\n success\nend", "def png_transformer(type_s, out_options={}, &block)\n orig_out_options = out_options[:size]\n if type_s == 'png'\n png_output = true\n type_s = 'svg'\n if out_options[:size]\n unless out_options[:size].to_s =~ /x/i\n out_options[:size] = out_options[:size].to_s + 'x' + out_options[:size].to_s\n end\n end\n else\n if out_options[:size].is_a?(String) && (out_options[:size] =~ /x/i)\n warn 'can only use the width dimension for this format'\n out_options[:size] = out_options[:size].split(/x/i).first\n end\n end\n image_blob = block.call(type_s, out_options)\n if png_output\n st = StringIO.new\n image = MiniMagick::Image.read(image_blob, 'svg')\n image.format('png')\n # would like to resize as an svg, then output the png of proper\n # granularity...\n image.resize(out_options[:size]) if out_options[:size]\n image_blob = image.write(st).string\n end\n out_options[:size] = orig_out_options\n image_blob\n end", "def to_png\n return @png_data if !@png_data.nil?\n image = minimagick_image\n image.resize '16x16!'\n image.format 'png'\n image.strip\n @png_data = image.to_blob\n raise FaviconParty::InvalidData.new(\"Empty png\") if @png_data.empty?\n @png_data\n end", "def write_to_image(x, y, color)\n\t\t\t@image.pixel_color(x, y, color)\n\t\t\t@image.write(@file_name)\n\t\tend", "def is_png\n return @is_png unless @is_png.nil?\n @is_png = png_header == [137, 80, 78, 71, 13, 10, 26, 10].pack('C*')\n @is_png\n end", "def png_file(path, *args)\n File.open(path, 'wb') do |f|\n png(f, *args)\n end\n end", "def write_picture(args = {})\n if @picture[\"n\"] == 0\n raise FlacInfoError, \"There is no METADATA_BLOCK_PICTURE\"\n end\n\n if args.has_key?(:n)\n n = args[:n]\n else\n n = 1\n end\n\n # \"image/jpeg\" => \"jpeg\"\n extension = @picture[n][\"mime_type\"].split(\"/\")[1]\n\n if not args.has_key?(:outfile)\n if @tags[\"album\"] == nil or @tags[\"album\"] == \"\"\n outfile = \"flacimage#{n}.#{extension}\"\n else\n # Try to use contents of \"album\" tag for the filename\n outfile = \"#{@tags[\"album\"]}#{n}.#{extension}\"\n end\n else\n outfile = \"#{args[:outfile]}.#{extension}\"\n end\n\n in_p = File.new(@filename, \"rb\")\n out_p = is_io?(args[:outfile]) ? args[:outfile] : File.new(outfile, \"wb\")\n out_p.binmode # For Windows folks...\n\n in_p.seek(@picture[n]['raw_data_offset'], IO::SEEK_CUR)\n raw_data = in_p.read(@picture[n]['raw_data_length'])\n out_p.write(raw_data)\n\n in_p.close\n if is_io?(args[:outfile])\n out_p.rewind\n else\n out_p.close\n end\n\n nil\n end", "def generate(write_path, size_type)\n if SUPPORTED_FILE_TYPES.include? File.extname(read_path)\n image = Magick::Image.read(read_path).first\n write_image image, write_path, size_type\n else\n write_default_image write_path, size_type\n end\n end", "def process_png(data)\n type = 'png'\n width = 0\n height = 0\n x_dpi = 96\n y_dpi = 96\n\n offset = 8\n data_length = data.size\n\n # Search through the image data to read the height and width in th the\n # IHDR element. Also read the DPI in the pHYs element.\n while offset < data_length\n\n length = data[offset + 0, 4].unpack1(\"N\")\n png_type = data[offset + 4, 4].unpack1(\"A4\")\n\n case png_type\n when \"IHDR\"\n width = data[offset + 8, 4].unpack1(\"N\")\n height = data[offset + 12, 4].unpack1(\"N\")\n when \"pHYs\"\n x_ppu = data[offset + 8, 4].unpack1(\"N\")\n y_ppu = data[offset + 12, 4].unpack1(\"N\")\n units = data[offset + 16, 1].unpack1(\"C\")\n\n if units == 1\n x_dpi = x_ppu * 0.0254\n y_dpi = y_ppu * 0.0254\n end\n end\n\n offset = offset + length + 12\n\n break if png_type == \"IEND\"\n end\n raise \"#{filename}: no size data found in png image.\\n\" unless height\n\n [type, width, height, x_dpi, y_dpi]\n end", "def encode_png_pixelstream(color_mode = ChunkyPNG::COLOR_TRUECOLOR, bit_depth = 8, interlace = ChunkyPNG::INTERLACING_NONE, filtering = ChunkyPNG::FILTER_NONE)\n if color_mode == ChunkyPNG::COLOR_INDEXED\n raise ChunkyPNG::ExpectationFailed, \"This palette is not suitable for encoding!\" if encoding_palette.nil? || !encoding_palette.can_encode?\n raise ChunkyPNG::ExpectationFailed, \"This palette has too many colors!\" if encoding_palette.size > (1 << bit_depth)\n end\n\n case interlace\n when ChunkyPNG::INTERLACING_NONE then encode_png_image_without_interlacing(color_mode, bit_depth, filtering)\n when ChunkyPNG::INTERLACING_ADAM7 then encode_png_image_with_interlacing(color_mode, bit_depth, filtering)\n else raise ChunkyPNG::NotSupported, \"Unknown interlacing method: #{interlace}!\"\n end\n end", "def to_png(*a)\n to_blob('png', *a)\n end", "def io_out\n raise NotImplementedError, 'Not implemented'\n end", "def make_png(ui_image)\n\t\timg = UIImagePNGRepresentation(image)\n\t\treturn img\n\tend", "def encode_png_image_pass_to_stream(stream, color_mode, bit_depth, filtering)\n start_pos = stream.bytesize\n pixel_size = Color.pixel_bytesize(color_mode)\n line_width = Color.scanline_bytesize(color_mode, bit_depth, width)\n\n # Determine the filter method\n encode_method = encode_png_pixels_to_scanline_method(color_mode, bit_depth)\n filter_method = case filtering\n when ChunkyPNG::FILTER_NONE then nil\n when ChunkyPNG::FILTER_SUB then :encode_png_str_scanline_sub\n when ChunkyPNG::FILTER_UP then :encode_png_str_scanline_up\n when ChunkyPNG::FILTER_AVERAGE then :encode_png_str_scanline_average\n when ChunkyPNG::FILTER_PAETH then :encode_png_str_scanline_paeth\n else raise ArgumentError, \"Filtering method #{filtering} is not supported\"\n end\n\n 0.upto(height - 1) do |y|\n stream << send(encode_method, row(y))\n end\n\n # Now, apply filtering if any\n if filter_method\n (height - 1).downto(0) do |y|\n pos = start_pos + y * (line_width + 1)\n prev_pos = y == 0 ? nil : pos - (line_width + 1)\n send(filter_method, stream, pos, prev_pos, line_width, pixel_size)\n end\n end\n end", "def to_image(filename = 'filename.png')\n png = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color::TRANSPARENT)\n height.times do |j|\n width.times do |i|\n png[i, j] = ChunkyPNG::Color.rgb(\n (red[i, j] * 255).to_i,\n (green[i, j] * 255).to_i,\n (blue[i, j] * 255).to_i\n )\n end\n end\n png.save(filename, :interlace => true)\n end", "def generate_jpg(outage)\n # TODO: put this into its own function\n jpg_output = \"#{FailureIsolation::DotFiles}/#{outage.log_name}.jpg\"\n\n @dot_generator.generate_jpg(outage, jpg_output)\n\n jpg_output\n end", "def to_png(*a)\n PNG.new(to_canvas(*a)).to_blob\n end", "def write_out(path = nil)\n return img unless path\n FileUtils.mkdir_p File.dirname(path)\n img.write(path)\n path\n rescue Errno::ENOENT\n puts_and_exit(\"Path not found '#{path}'\")\n end", "def create_write_data script_filename, output_extension\n # Normalize the output extension.\n output_extension.upcase!\n output_extension = output_extension.split('.').tap{ |ext| ext.shift }.join('.') if output_extension =~ /^\\./\n\n if output_extension == 'SVG'\n create_svg script_filename\n else\n begin\n require 'RMagick'\n\n format_support = Magick.formats[output_extension]\n raise(ArgumentError, \"RMagick cannot write format '#{output_extension}'\") if format_support.nil? || format_support[2] == '-'\n\n image = Magick::Image::from_blob(create_svg(script_filename)) { self.format = 'SVG' }\n image[0].format = output_extension\n image[0].to_blob\n\n rescue LoadError\n raise(ArgumentError, \"RMagick not found; cannot write PDF\")\n end\n end\n end", "def generate_png\n img = IMGKit.new(url).to_png\n file = File.new(\"#{id}-full.png\", \"w\", :encoding => 'ascii-8bit')\n file.write(img)\n return file.path\n end", "def write_string(type=DEFAULT_OUT_TYPE, out_options={})\n png_transformer(type.to_s, out_options) do |type_s, _out_opts|\n obconv = out_options[:obconv] || OpenBabel::OBConversion.new\n obconv.set_out_format(type_s)\n obconv.add_opts!(:out, _out_opts)\n obconv.write_string(@ob)\n end\n end", "def resize_and_write_file(filename, filename_output, max_width, max_height = nil)\n pic = Magick::Image.read(filename).first\n img_width, img_height = pic.columns, pic.rows\n ratio = img_width.to_f / max_width.to_f\n\n if max_height.nil?\n max_height = img_height / ratio\n end\n\n pic.change_geometry!(\"#{max_width}x#{max_height}>\") { |cols, rows, img|\n img.resize_to_fit!(cols, rows)\n img.write filename_output\n img.destroy!\n }\n\n nbytes, content = File.size(filename_output), nil\n File.open(filename_output, \"rb\") { |f| content = f.read nbytes }\n content\nend", "def write(output_path)\n FileUtils.copy_file @path, output_path\n run_command \"identify\", output_path # Verify that we have a good image\n end", "def operation(*args)\n src_file, out_file = args\n image = Vips::Image.new_from_file src_file\n factor = public_send options[:method], image.size\n image.resize(factor).write_to_file out_file\n end", "def write(path)\n @img_rw.rch = @rch\n @img_rw.gch = @gch\n @img_rw.bch = @bch\n @img_rw.write(path)\n end", "def poster(input, output)\n \n input = input \n output = output \n \n scale(input, output)\n\n #Demonstrate the Image#polaroid method\n img = Magick::Image.read(output).first\n result = img.posterize\n \n #Write \n result.write(output)\n\nend", "def to_chunky_image\n iob = Qt::Buffer.new(Qt::ByteArray.new)\n iob.open(Qt::IODevice::ReadWrite)\n save(iob, \"PNG\")\n iob.reset\n img = ChunkyPNG::Image.from_blob(iob.readAll.data)\n iob.close\n iob = nil\n img\n end", "def quality(percentage)\n manipulate! do |img|\n img.write(current_path){ self.quality = percentage }\n img = yield(img) if block_given?\n img\n end\nend", "def encode_png_image_without_interlacing(color_mode, bit_depth = 8, filtering = ChunkyPNG::FILTER_NONE)\n stream = \"\".b\n encode_png_image_pass_to_stream(stream, color_mode, bit_depth, filtering)\n stream\n end", "def to_png(*a)\n to_image(*a).to_blob{|i| i.format ='png' }\n end", "def write_image(&block)\n @image = GD2::Image.new(@width, @height)\n self.instance_eval(&block)\n @image.export(self.full_path)\n end", "def output=(io); end", "def to_png_file\n to_pdf_file do |pdf_path|\n Dir.mktmpdir(ident) do |output_directory|\n png_path = File.join(output_directory, ident + '.png')\n system convert, *CONVERT_OPTIONS, pdf_path, png_path\n raise PNGConversionFailed, self unless File.exist?(png_path)\n\n yield png_path\n File.unlink png_path\n end\n end\n end", "def to_png_file\n to_pdf_file do |pdf_path|\n Dir.mktmpdir(ident) do |output_directory|\n png_path = File.join(output_directory, ident + '.png')\n system convert, *CONVERT_OPTIONS, pdf_path, png_path\n raise PNGConversionFailed, self unless File.exist?(png_path)\n\n yield png_path\n File.unlink png_path\n end\n end\n end", "def write(file_name = 'graph.png')\n to_image.write(file_name)\n end", "def image\n @sys_image = resource_find(params[:id])\n uploaded_io = params[:file]\n _size = File.size(uploaded_io)\n write_resource(@sys_image, uploaded_io.read, \"ndz\")\n redirect_to(@sys_image) \n end", "def encode_png_image_with_interlacing(color_mode, bit_depth = 8, filtering = ChunkyPNG::FILTER_NONE)\n stream = \"\".b\n 0.upto(6) do |pass|\n subcanvas = self.class.adam7_extract_pass(pass, self)\n subcanvas.encoding_palette = encoding_palette\n subcanvas.encode_png_image_pass_to_stream(stream, color_mode, bit_depth, filtering)\n end\n stream\n end", "def write_to(io)\n end", "def write_to(io)\n end", "def write_default_image(write_path, size_type)\n image = Magick::Image.read(\"public/default_icon.png\").first\n ext = File.extname(write_path)\n write_path.gsub!(/#{ext}/i, \".png\") unless ext.empty?\n write_image image, write_path, size_type\n end", "def write(char, color = @options[:color], size = @options[:size])\n path = image_path(char, color, size)\n \n # Let's not regenerate the same image if the font hasn't changed\n return path if(path.exist? && @font.mtime <= path.mtime)\n \n img = self.render(char, color, size)\n \n img.write(path.to_s) do\n self.format = \"PNG32\"\n end \n \n path\n end", "def jpeg_file(path, *args)\n File.open(path, 'wb') do |f|\n jpeg(f, *args)\n end\n end", "def compress!(img)\n puts 'Compressing image.'\n image_optim = ImageOptim.new(allow_lossy: true, verbose: false, skip_missing_workers: true, optipng: false,\n pngcrush: false, pngquant: { allow_lossy: true },\n advpng: false, pngout: false, svgo: false)\n image_optim.optimize_image(img)\n puts 'compressed.'\n end", "def output_image\r\n @icon.each do |data|\r\n puts data.join\r\n end\r\n end", "def to_datastream(constraints = {})\n encoding = determine_png_encoding(constraints)\n\n ds = Datastream.new\n ds.header_chunk = Chunk::Header.new(\n width: width,\n height: height,\n color: encoding[:color_mode],\n depth: encoding[:bit_depth],\n interlace: encoding[:interlace]\n )\n\n if encoding[:color_mode] == ChunkyPNG::COLOR_INDEXED\n ds.palette_chunk = encoding_palette.to_plte_chunk\n ds.transparency_chunk = encoding_palette.to_trns_chunk unless encoding_palette.opaque?\n end\n data = encode_png_pixelstream(encoding[:color_mode], encoding[:bit_depth], encoding[:interlace], encoding[:filtering])\n ds.data_chunks = Chunk::ImageData.split_in_chunks(data, encoding[:compression])\n ds.end_chunk = Chunk::End.new\n ds\n end", "def blob_generate(write_path, size_type = nil)\n if SUPPORTED_FILE_TYPES.include? File.extname(write_path)\n image = Magick::Image.from_blob(read_path).first\n write_image image, write_path, size_type\n else\n write_default_image write_path, size_type\n end\n end", "def create_png_file(png_file_path, colors, matrix, square_size)\n if png_file_path =~ /\\.png$/i\n ppm_file_path = png_file_path.gsub(/\\.png$/, '.ppm')\n else\n ppm_file_path = png_file_path + '.ppm'\n end\n\n if !create_ppm_file(ppm_file_path, colors, matrix, square_size)\n return false\n end\n\n system(\"#{PNG_CONVERTER} #{ppm_file_path} #{png_file_path}\")\n if $?.exited? && $?.exitstatus == 0\n result = true\n else\n result = false\n end\n\n File.delete(ppm_file_path)\n return result\nend", "def png_header\n return @png_header unless @png_header.nil?\n _pos = @_io.pos\n @_io.seek(ofs_img)\n @png_header = @_io.read_bytes(8)\n @_io.seek(_pos)\n @png_header\n end", "def compress(img, path)\n puts 'Compressing image.'\n image_optim = ImageOptim.new(allow_lossy: true, verbose: false, skip_missing_workers: true, optipng: false,\n pngcrush: false, pngquant: { allow_lossy: true },\n advpng: false, pngout: false, svgo: false)\n File.rename(image_optim.optimize_image(img), path)\n puts 'Image copied and compressed.'\n end", "def write(io)\n io = BinData::IO.new(io) unless BinData::IO === io\n\n do_write(io)\n io.flush\n self\n end", "def write_out(file: $OUTFILE)\n puts \"Writing out to #{file}\" if $DEBUGGING\n extension = file.dup #filename with any extension\n file[file.index('.')..-1] = '.ppm'\n #$GRID = create_grid()\n outfile = File.open(file, 'w')\n outfile << \"P3 #$RESOLUTION #$RESOLUTION 255\\n\" #Header in 1 line\n\n #Write PPM data\n for row in @rgb_grid\n for pixel in row\n for rgb in pixel\n outfile << rgb\n outfile << ' '\n end\n outfile << ' '\n end\n outfile << \"\\n\"\n end\n outfile.close()\n\n #Convert filetype\n print %x[convert #{file} #{extension}]\n if not extension[\"ppm\"]\n print %x[rm #{file}] end\n end", "def encode64( png )\n return Base64.encode64(png)\n end", "def write(output_path = nil) \n output_path = @input_path if output_path.nil?\n FileUtils.copy_file @path, output_path\n verify_image(output_path)\n self\n end", "def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend", "def export_png(icon_size = 200)\n @glyphs.glob('*.svg').map do |p|\n # puts p.dirname.inspect.yellow\n # puts p.basename.inspect.red\n # puts p.basename('.svg').inspect.yellow\n png_file = @root.join('tmp', 'png', p.basename('.svg').to_s + '.png')\n command(\"convert -background none -size #{icon_size}x#{icon_size} #{p} #{png_file}\")\n end\n end", "def generate_tile_image(output_path, type = :png)\n generate_tile unless @i.nil?\n @i.write(File.join(output_path, \"#{name}.#{type}\"))\n end", "def write_to(io)\n\t@io = io\n\t@bytes_written = 0\n\twrite_header()\n\t@update_block.call(nil, @seq.tracks.length, 0) if @update_block\n\t@seq.tracks.each_with_index do |track, i|\n write_track(track)\n @update_block.call(track, @seq.tracks.length, i) if @update_block\n\tend\n end", "def write_to(io)\n\t@io = io\n\t@bytes_written = 0\n\twrite_header()\n\t@update_block.call(nil, @seq.tracks.length, 0) if @update_block\n\t@seq.tracks.each_with_index do |track, i|\n write_track(track)\n @update_block.call(track, @seq.tracks.length, i) if @update_block\n\tend\n end", "def export_to_jpg file\n width = @panel.get_width\n height = @panel.get_height\n\n buffered_image = BufferedImage.new width, height, BufferedImage::TYPE_INT_RGB\n graphics = buffered_image.create_graphics\n @panel.paint(graphics);\n\n cropping_rectangle = self.get_bounding_rectangle\n cropped_image = buffered_image.get_subimage cropping_rectangle.get_x,\n cropping_rectangle.get_y,\n cropping_rectangle.get_width,\n cropping_rectangle.get_height\n\n output_file = java.io.File.new file\n\n ImageIO.write cropped_image, \"jpg\", output_file\n\n end", "def to_file\n a = []\n\n @sprites.product(@palettes).each do |pair|\n a << pair.first.to_canvas(pair.last)\n end\n\n combine_canvas(a).to_datastream\n end", "def export(filename)\n @image.save(filename, :interlace => true)\n end", "def write( path )\n base_image.write( path )\n end", "def write(output_to); end", "def save(outname)\n generate_temp_file\n\n cmd = \"convert \"\n\n if not @args.empty?\n cmd += \"#{@args.join(' ')} \"\n end\n\n cmd += \"#{Shellwords.escape(@filename)} #{Shellwords.escape(outname)}\"\n\n PDFToImage.exec(cmd)\n\n return true\n end", "def write_ppm(ios, format=\"P6\")\n if not PIXMAP_FORMATS.include?(format)\n raise NotImplementedError, \"pixmap format #{format} has not been implemented\" \n end\n ios.puts format, \"#{@width} #{@height}\", \"255\"\n ios.binmode if PIXMAP_BINARY_FORMATS.include?(format)\n each_pixel do |x, y|\n case format\n when \"P3\" then ios.print @data[x][y].values.join(\" \"),\"\\n\"\n when \"P6\" then ios.print @data[x][y].values.pack('C3')\n end\n end\n end", "def imagemagick?; end", "def create_size src,dest,params\n return nil if !File.exists?(src)\n i = Image.new(src)\n params[:to] = dest\n FileUtils.mkdir_p File.dirname(dest)\n i.out params\n @hooks.create(:original => src,\n :sized => dest,\n :not_found => params[:not_found],\n :autogenerated => params[:autogenerated],\n :width => params[:width],\n :height => params[:height]) if @hooks && !params[:skiphook]\n end", "def output_image\r\n @image.each do |cell|\r\n puts cell.join\r\n end\r\n end", "def to_image\n # TODO: generate Image object from PatchedImage contents\n raise NotImplementedError\n end", "def save_cropped_image(src, dest, x, y, width, height, quality = 75)\n if src.is_a? Magick::Image\n img = src\n else\n img = Magick::Image::read(src).first\n end\n\n quality = quality * 100 if quality < 1\n\n # The crop method retains the offset information in the cropped image.\n # To reset the offset data, adding true as the last argument to crop.\n cropped = img.crop(x, y, width, height, true)\n cropped.write(dest) { @quality = quality }\n end" ]
[ "0.69359374", "0.6256808", "0.6150044", "0.59207785", "0.57372075", "0.57175267", "0.5687176", "0.55965036", "0.55744183", "0.5539418", "0.55202305", "0.5517066", "0.5509904", "0.5502224", "0.5496602", "0.5472919", "0.54127526", "0.5406111", "0.5379772", "0.53405535", "0.5309787", "0.5306007", "0.5293536", "0.52741826", "0.52678406", "0.5259779", "0.5257993", "0.5255137", "0.52095646", "0.5199478", "0.517328", "0.5171031", "0.5168849", "0.5150875", "0.5140924", "0.5126892", "0.5120213", "0.51142824", "0.5103829", "0.5089024", "0.5074153", "0.50411713", "0.5037298", "0.50261825", "0.50102305", "0.5010133", "0.5007218", "0.50036234", "0.4991798", "0.49549538", "0.49434775", "0.49275845", "0.49115226", "0.49049067", "0.48960644", "0.48949528", "0.48933357", "0.4875103", "0.48685488", "0.4864952", "0.4857865", "0.48571154", "0.4836932", "0.4836932", "0.48309717", "0.48192772", "0.48175922", "0.48168916", "0.48168916", "0.48128283", "0.48111358", "0.47974625", "0.47967008", "0.47718036", "0.47690687", "0.47669712", "0.4763916", "0.4763014", "0.47572517", "0.47363016", "0.47354332", "0.47311282", "0.47240633", "0.4724048", "0.4718729", "0.47156024", "0.47152573", "0.47152573", "0.47006437", "0.4683532", "0.46787181", "0.4671152", "0.4671021", "0.46673355", "0.4666416", "0.46616176", "0.46613416", "0.465599", "0.46520206", "0.46489453" ]
0.6128945
3
:callseq: png_file(path) Writes the image to a new file at +path+ as compressed PNG data. Returns the number of bytes written. == Example Axon.jpeg_file("image.jpg") do |image| image.png_file("image.png") saves the image to "image.jpeg" end
def png_file(path, *args) File.open(path, 'wb') do |f| png(f, *args) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def jpeg_file(path, *args)\n File.open(path, 'wb') do |f|\n jpeg(f, *args)\n end\n end", "def png(file)\n file.write PNG_HEADER\n\n # Make sure IEND is actually at the end (Ruby 1.9).\n iend = @chunks.delete 'IEND'\n @chunks['IEND'] = iend\n\n @chunks.each do |type, data|\n data.each do |data_part|\n file.write [data_part.length, type].pack('NA*')\n file.write data_part\n file.write [Zlib::crc32(type + data_part)].pack('N')\n end\n end\n end", "def png(*args)\n PNG.write(@source, *args)\n end", "def encode_png_image_pass_to_stream(stream, color_mode, compression = ZLib::DEFAULT_COMPRESSION)\n\n if compression < Zlib::BEST_COMPRESSION && color_mode == ChunkyPNG::COLOR_TRUECOLOR_ALPHA\n # Fast RGBA saving routine\n stream << pixels.pack(\"xN#{width}\" * height)\n \n elsif compression < Zlib::BEST_COMPRESSION && color_mode == ChunkyPNG::COLOR_TRUECOLOR\n # Fast RGB saving routine\n line_packer = 'x' + ('NX' * width)\n stream << pixels.pack(line_packer * height)\n \n else\n # Normal saving routine\n pixel_size = Color.bytesize(color_mode)\n pixel_encoder = case color_mode\n when ChunkyPNG::COLOR_TRUECOLOR then lambda { |color| Color.to_truecolor_bytes(color) }\n when ChunkyPNG::COLOR_TRUECOLOR_ALPHA then lambda { |color| Color.to_truecolor_alpha_bytes(color) }\n when ChunkyPNG::COLOR_INDEXED then lambda { |color| [encoding_palette.index(color)] }\n when ChunkyPNG::COLOR_GRAYSCALE then lambda { |color| Color.to_grayscale_bytes(color) }\n when ChunkyPNG::COLOR_GRAYSCALE_ALPHA then lambda { |color| Color.to_grayscale_alpha_bytes(color) }\n else raise ChunkyPNG::NotSupported, \"Cannot encode pixels for this mode: #{color_mode}!\"\n end\n\n previous_bytes = Array.new(pixel_size * width, 0)\n each_scanline do |line|\n unencoded_bytes = line.map(&pixel_encoder).flatten\n stream << encode_png_scanline_paeth(unencoded_bytes, previous_bytes, pixel_size).pack('C*')\n previous_bytes = unencoded_bytes\n end\n end\n end", "def convert_jpg_to_png(img_path)\n print_status(\"Converting #{img_path} back to PNG\")\n basename = File.basename(img_path, '.jpg')\n img = MiniMagick::Image.open(img_path)\n img.format('PNG')\n dst = \"#{WORKFOLDER}/#{basename}.png\"\n img.write(dst)\n dst\nend", "def create_png_file(png_file_path, colors, matrix, square_size)\n if png_file_path =~ /\\.png$/i\n ppm_file_path = png_file_path.gsub(/\\.png$/, '.ppm')\n else\n ppm_file_path = png_file_path + '.ppm'\n end\n\n if !create_ppm_file(ppm_file_path, colors, matrix, square_size)\n return false\n end\n\n system(\"#{PNG_CONVERTER} #{ppm_file_path} #{png_file_path}\")\n if $?.exited? && $?.exitstatus == 0\n result = true\n else\n result = false\n end\n\n File.delete(ppm_file_path)\n return result\nend", "def write(path)\n @img_rw.rch = @rch\n @img_rw.gch = @gch\n @img_rw.bch = @bch\n @img_rw.write(path)\n end", "def compress_png(input, quality = 80, output = nil)\n # Override file if no output selected\n output = input if output.nil?\n\n # PNGQuant does not allow update in place, so we save in a temp file\n output_tmp = Tempfile.new('temp_png').path\n\n options = [\n input.shellescape,\n '--force',\n \"--quality 01-#{quality}\",\n \"--output #{output_tmp.shellescape}\"\n ]\n\n command = \"pngquant #{options.join(' ')}\"\n `#{command}`\n\n # Move the tmp file back to the real output\n FileUtils.mv(output_tmp, output)\n\n output\n end", "def convert_png_to_jpg(img_path)\n print_status(\"Converting #{img_path} to JPG to reduce image quality to #{JPGQUALITY}\")\n basename = File.basename(img_path, '.png')\n img = MiniMagick::Image.open(img_path)\n img.format('JPEG')\n img.quality(JPGQUALITY)\n dst = \"#{WORKFOLDER}/#{basename}.jpg\"\n img.write(dst)\n dst\nend", "def write( path )\n base_image.write( path )\n end", "def write_to_image(x, y, color)\n\t\t\t@image.pixel_color(x, y, color)\n\t\t\t@image.write(@file_name)\n\t\tend", "def generate_compressed path, img\n img.write(path) { self.quality = 70 }\n end", "def write_image id, name_suffix=\"\"\n m_begin \"write_image\"\n filename = \"./temp/\" +id.to_s+name_suffix+\".gif\"\n get_image(id).write(filename)\n m_end \"write_image\"\n end", "def save_as_png(file)\n to_png.save(file, :fast_rgba)\n end", "def save_impl(format, file)\n write_new_image format, FileImageOutputStream.new(file)\n end", "def generate(write_path, size_type)\n if SUPPORTED_FILE_TYPES.include? File.extname(read_path)\n image = Magick::Image.read(read_path).first\n write_image image, write_path, size_type\n else\n write_default_image write_path, size_type\n end\n end", "def write(file_name = 'graph.png')\n to_image.write(file_name)\n end", "def save_png(path, margin=4)\n scale = 8\n w = (width+margin+margin)*scale\n h = (width+margin+margin)*scale\n canvas = PNG::Canvas.new w,h\n points.each do |p|\n for x in (0..scale-1)\n for y in (0..scale-1)\n canvas.point( (p[0]+margin)*scale+x,\n h-(p[1]+margin)*scale-y,\n PNG::Color::Black )\n end\n end\n end\n\n png = PNG.new canvas\n png.save path\n end", "def write(output_filename)\n Trace::get_logger.info('Image.write') { \"Writing output file...\" }\n \n output_file = ChunkyPNG::Image.new(@width, @height, ChunkyPNG::Color::TRANSPARENT)\n \n @width.times do |x|\n @height.times do |y|\n output_file[x,y] = @pixels[[x,y]].get_color\n end\n end\n \n output_file.save(\"#{output_filename}.png\", :interlace => false)\n end", "def save_impl(format, file)\n ImageIO.write(@src, format, file)\n end", "def save(path='result.jpg')\n @canvas.write(path)\n end", "def write_image(&block)\n @image = GD2::Image.new(@width, @height)\n self.instance_eval(&block)\n @image.export(self.full_path)\n end", "def image\n assert_file!\n @image ||= ChunkyPNG::Image.from_file(@path)\n end", "def resize(path)\n img = MiniMagick::Image.open(@file)\n img.combine_options do |c|\n c.quality @options[:quality] if @options[:quality]\n c.resize \"#{@width}x#{@height}>\"\n end\n\n img.write(path)\n end", "def upRes(file_path)\t\n\t\toriginal_image = Magick::Image.read(file_path) { self.density = \"300.0x300.0\" }\n\t\toriginal_image.each do |image|\n\t\t\t image = image.resample(300.0, 300.0)\n\t\t\t image.write(file_path) { self.quality = 100 }\n\t\tend\n\tend", "def png(level = nil)\n size = FFI::MemoryPointer.new(:pointer)\n ptr = ::GD2::GD2FFI.send(:gdImagePngPtrEx, image_ptr, size, level.to_i || -1)\n ptr.get_bytes(0, size.get_int(0))\n ensure\n ::GD2::GD2FFI.send(:gdFree, ptr)\n end", "def write(dir = self.dir, filename = self.filename)\n FileUtils.mkdir_p(File.join(WRITE_DIR, dir))\n self.image.write(File.join(WRITE_DIR, dir, filename))\n end", "def save\n\n properties = {}\n # exif = {}\n # KCGImagePropertyExifDictionary\n # exif[KCGImagePropertyExifUserComment] = 'Image downloaded from www.sheetmusicplus.com'\n # exif[KCGImagePropertyExifAuxOwnerName] = 'www.sheetmusicplus.com'\n if @filetype == :pdf\n CGPDFContextEndPage(@ctx)\n CGContextFlush(@ctx)\n return\n elsif @filetype == :png\n format = NSPNGFileType\n elsif @filetype == :tif\n format = NSTIFFFileType\n properties[NSImageCompressionMethod] = NSTIFFCompressionLZW\n #properties[NSImageCompressionMethod] = NSTIFFCompressionNone\n elsif @filetype == :gif\n format = NSGIFFileType\n #properties[NSImageDitherTransparency] = 0 # 1 = dithered, 0 = not dithered\n #properties[NSImageRGBColorTable] = nil # For GIF input and output. It consists of a 768 byte NSData object that contains a packed RGB table with each component being 8 bits.\n elsif @filetype == :jpg\n format = NSJPEGFileType\n properties[NSImageCompressionFactor] = @quality # (jpeg compression, 0.0 = max, 1.0 = none)\n #properties[NSImageEXIFData] = exif\n end\n cgimageref = CGBitmapContextCreateImage(@ctx) # => CGImageRef\n bitmaprep = NSBitmapImageRep.alloc.initWithCGImage(cgimageref) # => NSBitmapImageRep\n blob = bitmaprep.representationUsingType(format, properties:properties) # => NSConcreteData\n blob.writeToFile(@output, atomically:true)\n true\n end", "def to_png(file, dir = '', pal = @palette)\n dir << '/' unless dir.empty? || dir.end_with?('/')\n FileUtils.mkpath(dir) unless Dir.exist?(dir)\n\n path = dir << file\n path << '.png' unless path.downcase.end_with?('.png')\n\n to_canvas(pal).save(path)\n end", "def write_image(image, write_path, size_type)\n size = find_size size_type\n image.resize_to_fill!(size[0], size[1]) if size_type\n image.format = \"PNG\" if image.format == \"SVG\"\n write_path.gsub!(/.svg/i, \".png\")\n image.write write_path\n end", "def to_png_file\n to_pdf_file do |pdf_path|\n Dir.mktmpdir(ident) do |output_directory|\n png_path = File.join(output_directory, ident + '.png')\n system convert, *CONVERT_OPTIONS, pdf_path, png_path\n raise PNGConversionFailed, self unless File.exist?(png_path)\n\n yield png_path\n File.unlink png_path\n end\n end\n end", "def to_png_file\n to_pdf_file do |pdf_path|\n Dir.mktmpdir(ident) do |output_directory|\n png_path = File.join(output_directory, ident + '.png')\n system convert, *CONVERT_OPTIONS, pdf_path, png_path\n raise PNGConversionFailed, self unless File.exist?(png_path)\n\n yield png_path\n File.unlink png_path\n end\n end\n end", "def write_out(path = nil)\n return img unless path\n FileUtils.mkdir_p File.dirname(path)\n img.write(path)\n path\n rescue Errno::ENOENT\n puts_and_exit(\"Path not found '#{path}'\")\n end", "def to_image(filename = 'filename.png')\n png = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color::TRANSPARENT)\n height.times do |j|\n width.times do |i|\n png[i, j] = ChunkyPNG::Color.rgb(\n (red[i, j] * 255).to_i,\n (green[i, j] * 255).to_i,\n (blue[i, j] * 255).to_i\n )\n end\n end\n png.save(filename, :interlace => true)\n end", "def write(output_path)\n FileUtils.copy_file @path, output_path\n run_command \"identify\", output_path # Verify that we have a good image\n end", "def convert_to_png(input_pdf, output_file)\n pdf = Magick::ImageList.new(input_pdf) { self.density = 200 }\n pdf.write(output_file)\nend", "def write!(opts = {})\n if requires_output_file?\n raise NoMethodError, \"You cannot use Image#write(output) with \"\\\n \"the #{current_utility} command\"\n end\n\n command = build_command(path)\n run(command, opts)\n self\n end", "def generate_png\n img = IMGKit.new(url).to_png\n file = File.new(\"#{id}-full.png\", \"w\", :encoding => 'ascii-8bit')\n file.write(img)\n return file.path\n end", "def resize_and_write_file(filename, filename_output, max_width, max_height = nil)\n pic = Magick::Image.read(filename).first\n img_width, img_height = pic.columns, pic.rows\n ratio = img_width.to_f / max_width.to_f\n\n if max_height.nil?\n max_height = img_height / ratio\n end\n\n pic.change_geometry!(\"#{max_width}x#{max_height}>\") { |cols, rows, img|\n img.resize_to_fit!(cols, rows)\n img.write filename_output\n img.destroy!\n }\n\n nbytes, content = File.size(filename_output), nil\n File.open(filename_output, \"rb\") { |f| content = f.read nbytes }\n content\nend", "def compress(img, path)\n puts 'Compressing image.'\n image_optim = ImageOptim.new(allow_lossy: true, verbose: false, skip_missing_workers: true, optipng: false,\n pngcrush: false, pngquant: { allow_lossy: true },\n advpng: false, pngout: false, svgo: false)\n File.rename(image_optim.optimize_image(img), path)\n puts 'Image copied and compressed.'\n end", "def compress_img (files = [])\n\t\t\n\t\tunless which('convert')\n\t\t\tputs \"WARNING: ImageMagick is not installed on your system. Skipping image compression...\"\n\t\t\treturn\n\t\tend\n\t\t\n\t\tunless files.is_a? Array\n\t\t\tfiles = [files]\n\t\tend\n\n\t\tfiles.each do |file|\n\n\t\t\tfname = get_filename(file)\n\n\t\t\tcompress_cmd = \n\t\t\t\t\t\t\t\t\"convert -strip \" + \n\t\t\t\t\t\t\t\t# uncomment to enable gaussian blur (smaller files but blurry)\n\t\t\t\t\t\t\t\t#\"-gaussian-blur 0.01 \" +\n\t\t\t\t\t\t\t\t# uncomment to enable interlacing (progressive compression for jpeg)\n\t\t\t\t\t\t\t\t#\"-interlace Plane \" +\n\t\t\t\t\t\t\t\t\"#{fname} -resize #{$img_options[:max_width]}x#{$img_options[:max_height]}\\\\> \" + \n\t\t \t\t\t\t\t\"-compress #{$img_options[:compress_type]} -quality #{$img_options[:quality]} \" + \n\t\t \t\t\t\t\t\"#{get_raw_filename(fname) + '.' + $img_options[:output_ext]}\"\n\t\t\t\n\t\t # invoke system ImageMagick\n\t\t system(compress_cmd)\n\t\t # remove the old file (if applicable)\n\t\t if (get_ext(fname) != (\".\" + $img_options[:output_ext]))\n\t\t \tsystem(\"rm #{fname}\")\n\t\t end\n\n\t\tend\n\n\tend", "def write(path = @path)\n \n gline = Gruff::Line.new(@size)\n @methods.each do |m, args|\n gline.send(\"#{m}=\", args)\n end\n @dataxy.each do |dxy| \n gline.dataxy(dxy[0], dxy[1], dxy[2]) \n end\n\n @filename ||= filename(@methods[:title])\n @filename ||= \"rbPlot\"\n gline.write(path + @filename + '.png')\n end", "def upload\n to_png_file do |png_path|\n File.open(png_path, 'rb') do |file|\n S3.put_object bucket: Giffy::Configuration.aws.bucket, key: key, body: file\n end\n S3.put_object_acl acl: 'public-read', bucket: Giffy::Configuration.aws.bucket, key: key\n end\n end", "def upload\n to_png_file do |png_path|\n File.open(png_path, 'rb') do |file|\n S3.put_object bucket: Giffy::Configuration.aws.bucket, key: key, body: file\n end\n S3.put_object_acl acl: 'public-read', bucket: Giffy::Configuration.aws.bucket, key: key\n end\n end", "def save_img(filename)\n @img.save(filename, :fast_rgb)\n end", "def write_out\n File.delete(@path) if File.exist?(@path)\n File.open(@path, mode: 'w', encoding: @img_data.encoding) { |f| f.write(@img_data) }\n end", "def pngcrush(image)\n if SUPPORTS_PNGCRUSH && config[:pngcrush]\n crushed = \"#{image}.crushed\"\n `pngcrush -rem alla -reduce -brute #{image} #{crushed}`\n FileUtils.mv(crushed, image) \n end\n end", "def save_png(filename)\n save_svg(filename)\n Dir.cd_to(filename) do |basename|\n system(\"convert \\\"#{basename}.svg\\\" \\\"#{basename}.png\\\"\") || system(\"rsvg-convert \\\"#{basename}.svg\\\" -o \\\"#{basename}.png\\\"\")\n end\n end", "def write_image(filename, decoded_image)\r\n\r\n f = File.new \"./public/images/blog/#{filename}\", \"wb\"\r\n f.write(decoded_image)\r\n f.close if f\r\n\r\n end", "def write_picture(args = {})\n if @picture[\"n\"] == 0\n raise FlacInfoError, \"There is no METADATA_BLOCK_PICTURE\"\n end\n\n if args.has_key?(:n)\n n = args[:n]\n else\n n = 1\n end\n\n # \"image/jpeg\" => \"jpeg\"\n extension = @picture[n][\"mime_type\"].split(\"/\")[1]\n\n if not args.has_key?(:outfile)\n if @tags[\"album\"] == nil or @tags[\"album\"] == \"\"\n outfile = \"flacimage#{n}.#{extension}\"\n else\n # Try to use contents of \"album\" tag for the filename\n outfile = \"#{@tags[\"album\"]}#{n}.#{extension}\"\n end\n else\n outfile = \"#{args[:outfile]}.#{extension}\"\n end\n\n in_p = File.new(@filename, \"rb\")\n out_p = is_io?(args[:outfile]) ? args[:outfile] : File.new(outfile, \"wb\")\n out_p.binmode # For Windows folks...\n\n in_p.seek(@picture[n]['raw_data_offset'], IO::SEEK_CUR)\n raw_data = in_p.read(@picture[n]['raw_data_length'])\n out_p.write(raw_data)\n\n in_p.close\n if is_io?(args[:outfile])\n out_p.rewind\n else\n out_p.close\n end\n\n nil\n end", "def write_raster_file(fn)\n raise(\"File not exist\") unless File.file?(fn)\n puts \"> oled-exp draw #{fn}\" if @verbose\n system(\"oled-exp\",\"draw\",fn)\n #sync_spawn(\"oled-exp\",@opt,\"draw\",fn) >> issue with file location...\n end", "def process_png(data)\n type = 'png'\n width = 0\n height = 0\n x_dpi = 96\n y_dpi = 96\n\n offset = 8\n data_length = data.size\n\n # Search through the image data to read the height and width in th the\n # IHDR element. Also read the DPI in the pHYs element.\n while offset < data_length\n\n length = data[offset + 0, 4].unpack1(\"N\")\n png_type = data[offset + 4, 4].unpack1(\"A4\")\n\n case png_type\n when \"IHDR\"\n width = data[offset + 8, 4].unpack1(\"N\")\n height = data[offset + 12, 4].unpack1(\"N\")\n when \"pHYs\"\n x_ppu = data[offset + 8, 4].unpack1(\"N\")\n y_ppu = data[offset + 12, 4].unpack1(\"N\")\n units = data[offset + 16, 1].unpack1(\"C\")\n\n if units == 1\n x_dpi = x_ppu * 0.0254\n y_dpi = y_ppu * 0.0254\n end\n end\n\n offset = offset + length + 12\n\n break if png_type == \"IEND\"\n end\n raise \"#{filename}: no size data found in png image.\\n\" unless height\n\n [type, width, height, x_dpi, y_dpi]\n end", "def quality(percentage)\n manipulate! do |img|\n img.write(current_path){ self.quality = percentage }\n img = yield(img) if block_given?\n img\n end\nend", "def write(output, opts = {})\n output_path = parse_input(output, false)\n\n FileUtils.copy_file(path, output_path) unless requires_output_file?\n\n command = build_command(output_path)\n run(command, opts)\n GraphicsMagick::Image.new(output_path)\n end", "def export(filename)\n @image.save(filename, :interlace => true)\n end", "def blob_generate(write_path, size_type = nil)\n if SUPPORTED_FILE_TYPES.include? File.extname(write_path)\n image = Magick::Image.from_blob(read_path).first\n write_image image, write_path, size_type\n else\n write_default_image write_path, size_type\n end\n end", "def compress_file(*path)\n compressed_path = path.dup\n compressed_path.push(\"#{compressed_path.pop}.gz\")\n base_file = File.open(for_file(path))\n create_file(compressed_path) do |file|\n compressor = Zlib::GzipWriter.new(file)\n while data = base_file.read(2048)\n compressor.write(data)\n end\n compressor.close\n end\n end", "def manipulate!(save_image = false)\n cache_stored_file! if !cached?\n @_gimage ||= ::GraphicsMagick::Image.new(current_path)\n @_gimage = yield(@_gimage)\n @_image.write(current_path) if save_image\n @_gimage\n rescue => e\n raise CarrierWave::ProcessingError.new(\"Failed to manipulate file! #{e}\")\n end", "def jpeg(quality = nil)\n size = FFI::MemoryPointer.new(:pointer)\n ptr = ::GD2::GD2FFI.send(:gdImageJpegPtr, image_ptr, size, quality || -1)\n ptr.get_bytes(0, size.get_int(0))\n ensure\n ::GD2::GD2FFI.send(:gdFree, ptr)\n end", "def write_swap_file(filename, decoded_image)\n\n f = File.new \"./public/swap/#{filename}\", \"wb\"\n f.write(decoded_image)\n f.close if f\n\n end", "def write_to_file(file_name)\n header = \"P6 #{@width} #{@height} #{@max_val}\"\n File.open(file_name, \"wb\") do |file|\n file.puts(header)\n @raster.flatten!\n @raster.each_with_index do |byte, index|\n file.print byte.chr\n end\n end\n end", "def operation(*args)\n src_file, out_file = args\n image = Vips::Image.new_from_file src_file\n factor = public_send options[:method], image.size\n image.resize(factor).write_to_file out_file\n end", "def jpeg(*args)\n case @source.components\n when 2,4 then @source = AlphaStripper.new(@source)\n end\n JPEG.write(@source, *args)\n end", "def draw_img(x, y, i, pen)\n\t\tx = x.to_i\n\t\ty = y.to_i\n\n\t\tfilename = sprintf( \"frames/frame-%05d.png\", i )\n\t\tif File.exists? filename\n\t\t\tpng = ChunkyPNG::Image.from_file( filename )\n\t\telse\n\t\t\tpng = ChunkyPNG::Image.new(@img_width, @img_height, ChunkyPNG::Color::BLACK)\n\t\tend\n\n\t\t# Draw each dot as a 3x3 square of pixels\n\t\t((x-1)..(x+1)).each do |xi|\n\t\t\tnext if xi < 1 || xi >= @img_width\n\n\t\t\t((y-1)..(y+1)).each do |yi|\n\t\t\t\tnext if yi < 1 || yi >= @img_height\n\n\t\t\t\tpng[xi, yi] = pen\n\t\t\tend\n\t\tend\n\n\t\tpng.save( filename, :fast_rgb )\n\tend", "def write(dest)\n dest_path = destination(dest)\n puts 'Create ... ' + dest_path\n return false if File.exist? dest_path and !modified?\n\n @@mtimes[path] = mtime\n\n FileUtils.mkdir_p(File.dirname(dest_path))\n image = ::MiniMagick::Image.open(path)\n image.combine_options do |c|\n @commands.each_pair do |command, arg|\n c.send command, arg\n end\n end\n image.write dest_path\n\n true\n end", "def write(output_path = nil) \n output_path = @input_path if output_path.nil?\n FileUtils.copy_file @path, output_path\n verify_image(output_path)\n self\n end", "def to_file\n a = []\n\n @sprites.product(@palettes).each do |pair|\n a << pair.first.to_canvas(pair.last)\n end\n\n combine_canvas(a).to_datastream\n end", "def encode_png_pixelstream(color_mode = ChunkyPNG::COLOR_TRUECOLOR, interlace = ChunkyPNG::INTERLACING_NONE, compression = ZLib::DEFAULT_COMPRESSION)\n\n if color_mode == ChunkyPNG::COLOR_INDEXED && (encoding_palette.nil? || !encoding_palette.can_encode?)\n raise ChunkyPNG::ExpectationFailed, \"This palette is not suitable for encoding!\"\n end\n\n case interlace\n when ChunkyPNG::INTERLACING_NONE then encode_png_image_without_interlacing(color_mode, compression)\n when ChunkyPNG::INTERLACING_ADAM7 then encode_png_image_with_interlacing(color_mode, compression)\n else raise ChunkyPNG::NotSupported, \"Unknown interlacing method: #{interlace}!\"\n end\n end", "def write(dest)\n dest_path = File.join(@dst_dir, @name)\n\n puts \"#{dest_path}\"\n\n return false if File.exist? dest_path and !modified?\n\n @@mtimes[path] = mtime\n\n FileUtils.mkdir_p(File.dirname(dest_path))\n image = ::MiniMagick::Image.open(path)\n\n @commands.each_pair do |command, arg|\n image.combine_options do |c|\n arg.each do |option|\n option.each {|command, value| c.send command,value}\n end\n end\n end\n\n image.format(@format, 1) if @format\n image.write dest_path\n puts \"Writing to #{dest_path}\"\n true\n end", "def save_rmagick(path, margin=4)\n scale = 8\n w = (width+margin+margin)*scale\n h = (width+margin+margin)*scale\n canvas = Magick::Image.new(w,h);\n gc = Magick::Draw.new\n gc.fill('black')\n gc.stroke('black')\n points.each do |p|\n gc.rectangle( (p[0]+margin)*scale,(p[1]+margin)*scale,\n (p[0]+margin)*scale+scale-1,(p[1]+margin)*scale+scale-1 )\n end\n gc.draw(canvas)\n canvas.write(path) { self.depth = 8; }\n end", "def write_file(data)\n\toutput_file = data.pack(\"C*\")\n\n\tbegin\n\t\tFile.open(\"stego_out.bmp\", \"w\") {|file| file.write(output_file)}\n\trescue\n\t\traise \"File's cooked\"\n\tend\nend", "def write(path)\n File.unlink(path) if File.exists?(path)\n Zip::Archive.open(path, Zip::CREATE) { |zipfile|\n zipfile.add_buffer(INDEX_PATH, htmlize(index))\n @book.media.each { |mpath|\n zipfile.add_buffer(mpath, @book.read_media(mpath))\n }\n unless @book.cover == COVER_PATH\n zipfile.add_buffer(COVER_PATH, to_png_data(@book.cover))\n end\n }\n path\n end", "def draw_image(data, row_number, digit)\n size = 28\n png = ChunkyPNG::Image.new(size, size, ChunkyPNG::Color::WHITE)\n data.each_with_index do |value, index|\n png[index % size, index / size] = ChunkyPNG::Color.rgb(255 - value.to_i, 255 - value.to_i, 255 - value.to_i)\n end\n png.save(\"images/#{digit}/digit_row_#{row_number}.png\", interlace: true)\nend", "def save_tile(image, dest_path, x, y, width, height, quality)\n image = if image.is_a? Magick::Image\n image\n else\n Magick::Image::read(image).first\n end\n\n quality = quality * 100 if quality < 1\n\n tile = image.crop(x, y, width, height, true)\n tile.write(dest_path)\n end", "def main()\n img = ImageList.new($input)\n convert = ImageList.new\n page = Magick::Rectangle.new(0,0,0,0)\n $total_ops = (img.rows * img.columns).to_f\n\n for i in 0..img.rows\n for j in 0..img.columns\n pixel = generate_hex_pixel(rgb_to_hex(img.pixel_color(j,i)))\n convert << pixel\n page.x = j * pixel.columns\n page.y = i * pixel.rows\n pixel.page = page\n progress()\n end\n end\n\n puts 'Writing image, this could take a while...'\n convert.mosaic.write($output)\nend", "def draw_from_png(file_name,x,y,alpha=100)\n draw_from_picture(1,file_name,x,y,alpha)\n end", "def export_to_jpg file\n width = @panel.get_width\n height = @panel.get_height\n\n buffered_image = BufferedImage.new width, height, BufferedImage::TYPE_INT_RGB\n graphics = buffered_image.create_graphics\n @panel.paint(graphics);\n\n cropping_rectangle = self.get_bounding_rectangle\n cropped_image = buffered_image.get_subimage cropping_rectangle.get_x,\n cropping_rectangle.get_y,\n cropping_rectangle.get_width,\n cropping_rectangle.get_height\n\n output_file = java.io.File.new file\n\n ImageIO.write cropped_image, \"jpg\", output_file\n\n end", "def png(base_filename)\n check_that_dot_is_installed\n mk_tmp_dir\n abs_path = \"#{TMP_DIR}/#{base_filename}.png\"\n write_png(abs_path)\n system \"open #{abs_path}\"\n end", "def quantize(content, colors = 256)\n raise PngError, \"pngquant not found in PATH=#{ENV['PATH']}\" unless which(\"pngquant\")\n out = \"\"\n exit_code, err_msg = Open3.popen3(\"pngquant #{colors}\") do |stdin, stdout, stderr, wait_thr|\n stdin.write(content)\n out << stdout.read\n [wait_thr.value, stderr.gets(nil)]\n end\n\n raise(PngError, err_msg) if exit_code != 0\n out\n end", "def export(filename)\n @image.save(filename, interlace: true)\n end", "def write_gpx filename, gpx\n $stderr.puts \"Writing #{filename}\" if $verbose\n File.open filename, 'w:UTF-8' do |file|\n file.write gpx\n end\nend", "def save_screenshot(png_path)\n extension = File.extname(png_path).downcase\n if extension != '.png'\n ::Appium::Logger.warn 'name used for saved screenshot does not match file type. ' \\\n 'It should end with .png extension'\n end\n File.open(png_path, 'wb') { |f| f << screenshot_as(:png) }\n end", "def via_files(filename, thumbnail_width)\n thumb = Vips::Image.thumbnail filename, thumbnail_width, crop: \"centre\"\n\n thumb.write_to_buffer \".jpg\"\nend", "def write(output_filename:, quality: 10)\n out_image = ImageList.new\n\n # Add rows to big picture\n @rows.values.each do |row|\n out_image.push(row.append(false))\n end\n\n out_image.append(true).write(output_filename) do\n self.format = \"JPEG\"\n self.quality = quality\n end\n end", "def save_image(filename)\n\t\t@image.save(filename, :interlace => true)\t\t\n\tend", "def write_png_from_svg(input, output, width, height)\n success = true\n begin\n Magick::Image.read(input).first.resize(width, height).write(output)\n rescue\n success = false\n end\n success\nend", "def save_to_file image\n File.open('uml.png', 'wb') do |file|\n file << image.body\n end if image\n end", "def to_file(name: 'screen.png')\n if name === 'ascii'\n system \"clear\" #clear the terminal screen\n Magick::Image::from_blob(to_svg).first.inspect_bitstream(width, height)\n else\n Magick::Image::from_blob(to_svg).first.write(name)\n end\n end", "def img_to_pdf(file, outdir)\n img = Magick::Image.read(file[:path]).first\n # resize the image if its too big (e.g., taken with a digital camera)\n if img.columns > 1000 || img.rows > 1000\n # resize such that it's 1000px in width\n scale = 1\n if img.columns > img.rows\n scale = 1000.0 / img.columns\n else\n scale = 1000.0 / img.rows\n end\n img = img.resize(scale)\n end\n img.write(\"pdf:#{outdir}\") { self.quality = 75 }\n end", "def to_jpeg(path, options = {})\n return raise Exceptions::InvalidFileFormatError unless valid_output_format?(path, 'jpeg')\n screenshot(path, 'jpeg', options)\n end", "def end(args = {})\n \n if args[:file]\n file = args[:file]\n else\n if !args[:filename]\n file = \"#{@dir}/#{@name}.gif\"\n else\n file = \"#{@dir}/#{filename}\"\n end\n end\n \n rotate = args[:rotate] || 0\n step = args[:step] || 1\n max_width = args[:max_width] || Lava::DEFAULT_MAX_WIDTH\n max_height = args[:max_height] || Lava::DEFAULT_MAX_HEIGHT\n speed = args[:speed] || Lava::DEFAULT_SPEED\n \n \n rimages = Magick::ImageList.new\n (0 ... samples.count ).step(step).each do |i|\n s = samples[i]\n s.rimage.rotate! rotate\n s.rimage.resize_to_fit!(max_width, max_height)\n rimages << s.rimage\n end\n rimages.ticks_per_second = speed\n rimages.write(file)\n end", "def export_image(filepath, seconds)\n # TODO support more file types\n type = case File.extname(filepath).downcase\n when '.pct', '.pict' then 'PICT'\n when '.tif', '.tiff' then 'TIFF'\n when '.jpg', '.jpeg' then 'JPEG'\n when '.png' then 'PNGf'\n when '.tga' then 'TPIC'\n when '.bmp' then 'BMPf'\n when '.psd' then '8BPS'\n else raise QuickTime::Error, \"Unable to guess ostype from file extension of #{filepath}\"\n end\n export_image_type(filepath, seconds, type)\n end", "def export_image(filepath, seconds)\n # TODO support more file types\n type = case File.extname(filepath).downcase\n when '.pct', '.pict' then 'PICT'\n when '.tif', '.tiff' then 'TIFF'\n when '.jpg', '.jpeg' then 'JPEG'\n when '.png' then 'PNGf'\n when '.tga' then 'TPIC'\n when '.bmp' then 'BMPf'\n when '.psd' then '8BPS'\n else raise QuickTime::Error, \"Unable to guess ostype from file extension of #{filepath}\"\n end\n export_image_type(filepath, seconds, type)\n end", "def resize_image(img_path)\n img = MiniMagick::Image.open(img_path)\n print_status(\"Original #{img_path} dimension = #{img.height}x#{img.width}\")\n new_width = img.width - (img.width * REIZEPERT).to_i\n new_height = img.height - (img.height * REIZEPERT).to_i\n img = img.resize(\"#{new_width}x#{new_height}\")\n print_status(\"Resized #{img_path} dimension = #{img.height}x#{img.width}\")\n img.write(img_path)\nend", "def write_swap_file(filename, decoded_image)\n\n f = File.new \"./public/swap/#{filename}\", \"wb\"\n # f = File.new \"../public/swap/#{filename}\", \"wb\" # inline testing path\n f.write(decoded_image)\n f.close if f\n\nend", "def write_swap_file(filename, decoded_image)\n\n f = File.new \"./public/swap/#{filename}\", \"wb\"\n # f = File.new \"../public/swap/#{filename}\", \"wb\" # inline testing path\n f.write(decoded_image)\n f.close if f\n\nend", "def write_images\n # Enumerate all the files in the zip and write any that are in the media directory to the output buffer (which is used to generate the new zip file)\n @file.read_files do |entry| # entry is a file entry in the zip\n if entry.name.include? IMAGE_DIR_NAME\n # Check if this is an image being replaced\n current_image = @images.select { |image| !@relationship_manager.get_relationship(image.id).nil? and entry.name.include? @relationship_manager.get_relationship(image.id)[:target] }.first\n\n unless current_image.nil?\n replacement_path = current_image.path\n data = ::File.read(replacement_path)\n else\n entry.get_input_stream { |is| data = is.sysread }\n end\n\n @file.output_stream.put_next_entry(entry.name)\n @file.output_stream.write data\n end\n end\n\n # Create any new images\n @unique_image_paths = []\n @images.select { |image| image.is_new }.each do |new_image|\n next if @unique_image_paths.include? new_image.target # we only want to write each image once\n @unique_image_paths << new_image.target\n @file.output_stream.put_next_entry(\"word/#{new_image.target}\")\n @file.output_stream.write ::File.read(new_image.path)\n end\n end", "def compress!\n File.open(@file_path, 'w') { |file| file.write(output) } if compress.modified?\n self\n end", "def convert_to_png(image_uri)\n path_without_ext = File.join(File.dirname(image_uri), File.basename(image_uri, '.*'))\n end_image = path_without_ext + '.png'\n image = Image.read(image_uri).first\n image.write(end_image)\n end_image\n end", "def compress_file\n folder = \"./\"\n zipfile_name = \"./test_file.zip\"\n\n Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|\n zipfile.add(@file_name, File.join(folder, @file_name))\n end\n\n zipped_size = File.size('test_file.zip')\n @zip_test_ratio = (zipped_size * 1.0) / @file_size\n @zip_test_ratio = -1 if @file_size < 1000\n\n File.delete(\"./test_file.zip\")\n end" ]
[ "0.6506414", "0.63885915", "0.60311306", "0.5949819", "0.5875201", "0.5871904", "0.57511646", "0.572426", "0.57190067", "0.5678481", "0.5675133", "0.56727326", "0.5557379", "0.5436052", "0.5430585", "0.5412409", "0.5401728", "0.5397639", "0.539142", "0.53458035", "0.53252643", "0.5298677", "0.52949023", "0.52787405", "0.52537733", "0.52439326", "0.52370965", "0.5224139", "0.52207583", "0.5210312", "0.5189656", "0.5189656", "0.51582354", "0.51542735", "0.5130046", "0.5111162", "0.5105461", "0.51051533", "0.5086029", "0.5079323", "0.50469476", "0.50360036", "0.50184715", "0.50184715", "0.5016513", "0.5014595", "0.500725", "0.5006985", "0.5005637", "0.49985754", "0.49683422", "0.4935607", "0.49285173", "0.4923898", "0.49134105", "0.49048492", "0.48963565", "0.48780304", "0.48630306", "0.48395154", "0.48389032", "0.4837107", "0.4828839", "0.48223296", "0.48206145", "0.48191962", "0.48163036", "0.48138416", "0.48048207", "0.47971818", "0.47782573", "0.47771204", "0.47732437", "0.47717696", "0.4767676", "0.4755315", "0.47538581", "0.47495732", "0.47459462", "0.47448975", "0.47434765", "0.4740843", "0.47391135", "0.47385034", "0.47296995", "0.4729434", "0.47105777", "0.47038957", "0.4700983", "0.47009325", "0.46905598", "0.46904716", "0.46904716", "0.46863237", "0.4685449", "0.4685449", "0.4681891", "0.46664327", "0.46649814", "0.46616948" ]
0.6734233
0
Gets the components in the image.
def components @source.components end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def components\n key_image.coords + c_array + r_array\n end", "def components\n return @components\n end", "def components\n @world.get_components(self)\n end", "def components\n\t\t\t\treturn @components.values unless (@components.nil?)\n\t\t\t\treturn nil\n\t\t\tend", "def components\n\t\treturn self.world.components_for( self )\n\tend", "def components\n [r, s]\n end", "def components\n if @components.nil?\n @components = self.class.components(self.key)\n end\n @components\n end", "def image_elements #:nodoc:\n @image_elements[0...number_elements]\n end", "def components\n arr = Arrays.new(@nb) { [] }\n (0...@component.size).each { |v| arr[@component[v]] << v }\n end", "def components\n arr = Arrays.new(@nb) { [] }\n (0...@component.size).each { |v| arr[@component[v]] << v }\n end", "def components\n\t\t\t@components ||= []\n\t\tend", "def components\n components = Backlogjp.base._command \"getComponents\", self.id\n components.map {|hash| Component.new(hash)}\n end", "def article_components_for(article)\n article.pictures[1..-1] || []\n end", "def all_components()\n comps = self.components.map do |c|\n if c.is_a?(Eddy::Models::Loop::Base)\n c.all_contents()\n elsif c.is_a?(Eddy::Models::Segment)\n c\n else\n raise Eddy::Errors::RenderError\n end\n end\n return comps.flatten\n end", "def value\n @components\n end", "def components\n result = []\n\n @children.each do |_key, child_group|\n child_group.each do |child|\n result << child if child.is_a?(Component)\n end\n end\n\n result\n end", "def get_fields\n # vips_image_get_fields() was added in libvips 8.5\n return [] unless Vips.respond_to? :vips_image_get_fields\n\n array = Vips.vips_image_get_fields self\n\n names = []\n p = array\n until (q = p.read_pointer).null?\n names << q.read_string\n GLib.g_free q\n p += FFI::Type::POINTER.size\n end\n GLib.g_free array\n\n names\n end", "def components; end", "def all_components()\n return self.components.map do |comp|\n case comp\n when Eddy::Summary::Loop then [comp, comp.all_components()]\n when Eddy::Summary::Segment then comp\n else raise Eddy::Errors::Error\n end\n end.flatten\n end", "def elements\n\n # We'll build up an array of co-ordinates\n pieces = []\n\n # And work through the current bricks\n @bricks[@rotation].each do |brick|\n\n # Apply the current grid position to this bricks\n pieces.append( [ @grid_row + brick[0], @grid_col + brick[1] ] )\n\n end\n\n return pieces\n\n end", "def color_components\n check_if_opacity_changed\n @color_components ||= if @color.is_a? Color::Set\n # Extract colour component arrays; see +def color=+ where colour set\n # size is enforced\n [\n @color[0].to_a, @color[1].to_a, @color[2].to_a\n ]\n else\n # All vertex colours are the same\n c_a = @color.to_a\n [\n c_a, c_a, c_a\n ]\n end\n end", "def names\n Tk.execute(:image, :names).to_a\n end", "def color_components\n check_if_opacity_changed\n @color_components ||= if @color.is_a? Color::Set\n # Splat the colours from the set; see +def color=+ where colour set\n # size is enforced\n [\n *@color[0].to_a, *@color[1].to_a, *@color[2].to_a, *@color[3].to_a\n ]\n else\n # All vertex colours are the same\n c_a = @color.to_a\n [\n *c_a, *c_a, *c_a, *c_a\n ]\n end\n end", "def images\n self.class.images\n end", "def image_points\n [\n @state.ctm_transform(0, 0),\n @state.ctm_transform(0, 1),\n @state.ctm_transform(1, 0),\n @state.ctm_transform(1, 1)\n ]\n end", "def list\n @_componentable_container.keys\n end", "def components\n @components ||= self.class.registered_components.inject({}){ |res, name| res.merge(name.to_sym => send(COMPONENT_METHOD_NAME % name)) }\n end", "def components\n @components ||= self.class.registered_components.inject({}){ |res, name| res.merge(name.to_sym => send(COMPONENT_METHOD_NAME % name)) }\n end", "def component\n simplelist(tk_send('component'))\n end", "def components\n\n end", "def available_components\n components = []\n @components.each_key do |k|\n components << k if @components[k].registered?\n end\n components\n end", "def pixels(i)\r\n i.get_pixels \r\n end", "def rows #:nodoc:\n @components\n end", "def cgimage\n return self.CGImage\n end", "def select_image\n compute.images.map { |i| [i.name, i.id] }\n end", "def images\n []\n end", "def channels\n Imgrb::PngMethods::channels(@image_type)\n end", "def child_components()\n @child_components\n end", "def components\n fetch(:capnotify_component_list)\n end", "def get_components(project_id=nil)\n return self.project.components if project_id.nil?\n project = client.Project.find(project_id)\n return project.components\n end", "def component_types; @component_types; end", "def images\n self.assets.find_all{ |asset| asset.image? }\n end", "def contents\n image.contents[image_offset, size]\n end", "def contents\n image.contents[image_offset, size]\n end", "def image_elements(identifier)\n platform.images_for(identifier.clone)\n end", "def images\n [assets.find_all { |asset| asset.is_a? MDL::BorealisImage }].flatten\n end", "def gather_components(category)\n component_list = Array.new\n config = self.config[category]\n\n # Throw out false values\n config.keys.reject {|i| self[i].class == FalseClass}.each do |comp_name|\n # Special cases for now...\n next if comp_name.match(\"startup_sequence\")\n next if comp_name.match(\"hid\")\n\n # Make sure our corresponding component actually exists. \n comp_template = Component.find_by_name_and_category(comp_name, category)\n if !comp_template\n raise BuildError.new(message: \"sketch component not found: #{comp_name}\")\n end\n \n # If our particular item is a hash or array, we assume it has\n # nested attributes.\n if config[comp_name].class == Hash || config[comp_name].class == Array\n context = config[comp_name]\n else\n # Find if our value is a blob referring to another component\n context = config\n component = Component.find_by_name_and_category(config[comp_name], \"blob\")\n if !component.nil?\n context = {comp_name => component.global}\n end\n end\n component_list.push(return_segments(comp_template, context))\n end\n\n # Special case for this one for now\n seq = context = nil\n startup_seq = config['startup_sequence']\n if startup_seq\n if startup_seq.present?\n seq = Component.find_by_name(\"startup_sequence\")\n component_list.push(return_segments(seq, context))\n elsif Component.find_by_name(startup_seq)\n if Component.find_by_name(startup_seq).category == \"pattern\"\n seq = Component.find_by_name(\"startup_pattern\")\n context = startup_seq\n component_list.push(return_segments(seq, context))\n # TODO: if we're running a pattern at startup make sure the pattern\n # itself is actually included.\n end\n end\n end\n component_list\n end", "def components\n @contents.inject([]) do |m,c|\n if c.is_a?( Symbol )\n m += space.role( c )\n else\n m << c\n end\n m\n end\n end", "def get_neighbors image\n coord = image.get_cell_coordinates(self)\n v_neighbors = [image.get_cell(coord[0], coord[1]-1), image.get_cell(coord[0], coord[1]+1)]\n h_neighbors = [image.get_cell(coord[0]-1, coord[1]), image.get_cell(coord[0]+1, coord[1])]\n neighbors = (v_neighbors + h_neighbors).compact\n end", "def imgs obj\n Image.find(obj.image_ids)\n end", "def getComponent()\n @component\n end", "def image_pixels(image_path)\n image = Magick::Image.from_blob(File.read(image_path)).first\n sx, sy = image.columns, image.rows\n \n grid = Array.new(sy) { Array.new }\n x, y = 0, 0\n image.each_pixel do |pixel|\n grid[y].concat [pixel.red, pixel.green, pixel.blue].map { |channel|\n ((255 * channel) / Magick::QuantumRange).to_i\n }\n x += 1\n if x == sx\n x = 0\n y += 1\n end\n end\n grid\nend", "def visual_elements\n return @visual_elements\n end", "def images\n return @canonical_image_pool if @canonical_image_pool\n Egi::Fedcloud::Vmhound::Log.debug \"[#{self.class}] Retrieving all images\"\n check_retval @image_pool.info_all!\n\n @canonical_image_pool = []\n @image_pool.each { |image| @canonical_image_pool << canonical_image(image) }\n @canonical_image_pool\n end", "def images\n images = @anchors.select { |a| a.object.is_a?(Pic) }\n images.map { |a| a.object }\n end", "def index\n @image_to_parts = ImageToPart.all\n end", "def rows id\n get_image(id).rows\n end", "def components(key)\n response = fetch({:key => \"#{key}/components\"})\n Field.new(response.parsed_response)\n end", "def image_names\n images.map { |i| i.name }.join(\"|\")\n end", "def image\n return @children['image'][:value]\n end", "def components\n @components ||= enabled_components.map { |component| component.new(@context) }\n end", "def calculate_components\n x = @norm * Math.cos(@orientation.rad)\n y = @norm * Math.sin(@orientation.rad)\n @components = { x: x, y: y }\n end", "def geometry\n image = load_image\n\n \"#{image.columns}x#{image.rows}\"\n end", "def bands\n Vips.vips_image_get_bands self\n end", "def get_component\n component_getter = ComponentGetter.new()\n #@graph, @visual_graph = component_getter.get_component(@graph, @visual_graph)\n component_getter.get_component(@graph, @visual_graph)\n end", "def images; end", "def pixels; end", "def entities\r\n result = []\r\n result.concat( patches )\r\n result.concat( edges )\r\n result.concat( control_points )\r\n result\r\n end", "def get_repository_images\n\n raw_images = self.get_raw_repository_images\n\n images = []\n\n raw_images.each do |image|\n images << RaisEcs::ContainerImage.new({\n local_image_id: image.id[0...12],\n primary_image_tag: image.id[0...12],\n local_repository: self,\n local_image_object: image,\n image_created_dt: Time.at(image.info['Created'])\n })\n end\n\n return images\n\n end", "def pixels_color_list\n color_list = ['', '', '', '', '', '', '', '']\n image_name_list = get_image_name_list PIXELS_PATH\n image_name_list.each do |image_name|\n color_list = pixel_color_list(image_name, color_list)\n end\n color_list.each(&:chop!)\n color_list\n # => like this: ['hogehoge.jpg,foobar.jpg', ... 'last.jpg,final.jpg']\n end", "def image_models\n @image_models ||= []\n end", "def get\n unless @image.kind_of? Magick::Image\n raise TypeError, \"images must be set and be an instance of RMagick::Image\"\n end\n \n draw\n @image #returns image with grid drawn on top\n end", "def contained_attributes\n @images.map(&:attribute).uniq\n end", "def my_pieces()\n\t\treturn @board.get_pieces_by_owner(@color)\n\tend", "def competing_image_labels\n return image.image_labels.select{ |il| (not il.target.nil?) && (not il == self) }\n end", "def get(entity)\n @components[entity.id] \n end", "def find_comps\n\t\tcomps.each do |c|\n\t\t\tc.comp_tag + ' '\n\t\tend\n\tend", "def index\n @cp_images = Image.all\n end", "def base_aug_components(opts = {})\n ret = self.array.select { |element| element.depth == 1 }.map { |element| element.aug_component }\n if components = opts[:components]\n matching_component_ids = components.map(&:id)\n ret.reject!{ |aug_component| ! matching_component_ids.include?(aug_component.id) }\n end\n ret\n end", "def software_image_list\n super\n end", "def parse_components\n\tcomp_list = comp_schema\n\tcorners = []\n\tcomp_list.keys.each { |id|\n\t\t#lb_curr = lower_bounds id \n\t\tadj_comps = []\n\t\touter_comp = DP.get_comp_pid id\n\t\tDP.comps.each{|inner_comp|\n\t\t\tnext if inner_comp.definition.name == 'region'\n\t\t\tnext if outer_comp == inner_comp \n\t\t\talen = check_adj outer_comp, inner_comp\n\t\t\t\n\t\t\tif alen > 2\n\t\t\t\tnext if inner_comp.definition.name == 'region'\n\t\t\t\tadj_comps << inner_comp.persistent_id\n\t\t\t\tadj_comps.length == 1 ? (type = :single) : (type = :double)\n\t\t\t\tcomp_list[id][:type] = type\n\t\t\t\t#corners << inner_comp.persistent_id) if adj_comps.length > 1\n\t\t\tend\n\t\t}\n\t\t\n\t\tif adj_comps.length == 2\n\t\t\t#puts \"adj\"+adj_comps.to_s\n\t\t\t#DP.sel.add outer_comp\n\t\tend\n\n\t\tcomp_list[id][:adj] = adj_comps\n\t\t# comp_list.keys.each{ |cid|\n\t\t# \tnext if cid == id\n\t\t# \tlb_comp = lower_bounds cid\n\t\t# \tsame_pts = []\n\t\t# \tlb_curr.each {|lb_pt|\n\t\t# \t\tlb_comp.each{|lb_pt1|\n\t\t# \t\t\tsame_pts << lb_pt1 if lb_pt == lb_pt1\n\t\t# \t\t}\n\t\t# \t}\n\t\t# \tadj << cid if same_pts.length > 1\n\t\t# }\n\t}\n\treturn comp_list#, corners\nend", "def containers_for_image(img = docker_image)\n `docker ps -aq -f ancestor=#{img}`.split(\"\\n\")\n end", "def image\n images.first\n end", "def cur_image\n self\n end", "def read_row radius\n @image.format('png')\n p = ChunkyPNG::Image.from_io(StringIO.new(@image.to_blob))\n a = (0...p.width).to_a.map{ |x| p[x, radius] }\n end", "def get_named_components()\n r = Hash.new\n names = get_component_names\n names.each { |n|\n begin\n r[n] = get_component_any(n)\n rescue\n end\n }\n return r\nend", "def get_named_components()\n r = Hash.new\n names = get_component_names\n names.each { |n|\n begin\n r[n] = get_component_any(n)\n rescue\n end\n }\n return r\nend", "def properties\n component ? component.properties : []\n end", "def create_components\n [\"red\", \"green\", \"blue\", \"gray\"].each_with_index do |item, i|\n create_trackbar(item, i)\n create_fields(item, i)\n end \n end", "def available_images; Image.all - images; end", "def available_images; Image.all - images; end", "def index\n @ivn_components = IvnComponent.all\n end", "def show\n @image = Image.find(params[:id])\n @tags = @image.tags.split(',')\n end", "def parts\n @parts\n end", "def get_array_of_solid_blocks\n @solid_blocks = []\n\n @map_image_key.each_key do |key|\n if (key.upcase == key) and (key != ',')\n @solid_blocks.push(key)\n end\n end\n end", "def load_components\n\t\t\t\treturn @data['components'].map do |componentstr|\n\t\t\t\t\tcomponent = componentstr.to_sym\n\t\t\t\t\tif (Instances::Components.constants.include? component)\n\t\t\t\t\t\tnext [component, Instances::Components.const_get(component).new]\n\t\t\t\t\telse\n\t\t\t\t\t\t## Component doesn't exist, display warning\n\t\t\t\t\t\tinstance_type = get_instance_type_classname\n\t\t\t\t\t\tclassname = get_classname\n\t\t\t\t\t\tlog \"WARNING: #{instance_type} '#{classname}' tried to load Component '#{componentstr}' which doesn't exist.\"\n\t\t\t\t\t\tnext nil\n\t\t\t\t\tend\n\t\t\t\tend .reject { |x| !x } .to_h if (@data['components'])\n\t\t\tend", "def coordinates(image)\n image.each_with_index.flat_map do |row,x|\n (0...row.length).find_all{|i| row[i] == @char }.map{|y| [x,y] }\n end\n end" ]
[ "0.75917554", "0.69255954", "0.686619", "0.686495", "0.6783539", "0.6776296", "0.6724951", "0.66866016", "0.6670473", "0.6670473", "0.6605553", "0.6443981", "0.63614225", "0.620369", "0.6099445", "0.609107", "0.6051297", "0.6039096", "0.5942996", "0.58960235", "0.5885776", "0.58826464", "0.5868597", "0.5822672", "0.58219904", "0.57978624", "0.5789002", "0.5789002", "0.5772657", "0.5770683", "0.57683384", "0.5709068", "0.5679179", "0.5661277", "0.5636313", "0.5599172", "0.5596467", "0.5578679", "0.5554398", "0.55396247", "0.55045736", "0.54789716", "0.5473385", "0.5473385", "0.5469831", "0.54633254", "0.5438875", "0.54230964", "0.542085", "0.54117084", "0.54109335", "0.5373791", "0.5357678", "0.535712", "0.5355199", "0.53507483", "0.5345209", "0.53339976", "0.5331781", "0.53193086", "0.5312388", "0.53010964", "0.5296054", "0.52920043", "0.52903813", "0.5282899", "0.52816767", "0.5272569", "0.5266053", "0.5262592", "0.52618873", "0.5248933", "0.52327025", "0.52305615", "0.5223889", "0.5220584", "0.5219414", "0.5180084", "0.517336", "0.5168239", "0.5154992", "0.5150663", "0.5147628", "0.5142188", "0.51366097", "0.51159084", "0.51159084", "0.51122665", "0.51078063", "0.50932944", "0.50932944", "0.50921786", "0.50897044", "0.5087641", "0.50866145", "0.50714135", "0.50698966" ]
0.65710306
14
Gets the width of the image.
def width @source.width end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def width\n @image.width\n end", "def width\n image_ptr[:sx]\n end", "def width\n image.empty? ? 0 : image.first.size\n end", "def width\n @image[0].length\n end", "def image_width\n\t\t\t@data[\"originalimage\"][\"width\"] if @data[\"originalimage\"]\n\t\tend", "def image_width\n\t\t\t@data[\"image\"][\"width\"]\n\t\tend", "def width\n Vips.vips_image_get_width self\n end", "def width\n rmagick_image.columns\n end", "def image_width\n @image_width ||=\n if image_node.has_attribute?('width')\n image_node.attribute('width').value.to_i\n elsif image_node.has_attribute?('style')\n regex = /width:\\s?(?<px>\\d+|(\\d+?\\.\\d+))px/\n match = image_node.attribute('style').value.match(regex)\n match['px'].to_i if match && match['px']\n end\n end", "def width_of image; return run(\"sips #{image} -g pixelWidth\").split(' ').last.to_i end", "def width\n\t\t\t\t\t@image.base_columns\n\t\t\t\tend", "def image_width\n end", "def getWidth\n @width\n end", "def getWidth\n @width\n end", "def getWidth\n @width\n end", "def width\n get_geometry if @width.nil?\n return @width\n end", "def image_width(image_width)\n end", "def pixel_width\n @sensor_width / @width_in_pixels\n end", "def getWidth\n @width\n end", "def width\n return @width\n end", "def getWidth\n @width\n end", "def getDimensions\r\n @imageheights = @image.length\r\n @imagewidth = @image[0].length\r\n puts \"image dimensions are #{@imagewidth} by #{@imageheights}\"\r\n end", "def width\r\n assert_exists\r\n return @o.invoke(\"width\").to_s\r\n end", "def getWidth\n\t\t@width\n\tend", "def width\n dimensions.first\n end", "def width\n @dimensions.x\n end", "def get_width; end", "def width\n dimensions()[:x]\n end", "def width\n metadata[:width] if valid?\n end", "def pixelwidth\n end", "def screenshot_width_for(game)\n return 0 if game.nil? || game.image_width.nil?\n return game.image_width\n end", "def width\n @maps[:background][0].size\n end", "def width\r\n return self.rect.width\r\n end", "def image_size\n end", "def width\n return self.src_rect.width\n end", "def height\n image.size\n end", "def width(style_name='original')\n geometry(style_name).width.to_i\n end", "def height\n @image.length\n end", "def image_width_pixels(module_count)\n\n\t\treturn module_count * @config[:square_size_px]\n\n\tend", "def get_width()\n Shape.api_not_implemented(self)\n end", "def get_width(dta)\n get_dimension('width', dta)\n end", "def width\n size_a[0]\n end", "def height\n rmagick_image.rows\n end", "def thumbnail_width\n\t\t\t@data[\"thumbnail\"][\"width\"]\n\t\tend", "def height\n @image.height\n end", "def width\n bounds[:right] - bounds[:left]\n end", "def width\n bounds[:right] - bounds[:left]\n end", "def width\n self.size[:x]\n end", "def width\n size.last\n end", "def width\n size.last\n end", "def width\n return self.rect.width\n end", "def get_width\n # FIXME: I don't know how portable it is.\n default_width = 80\n begin\n tiocgwinsz = 0x5413\n data = [0, 0, 0, 0].pack(\"SSSS\")\n if @out.ioctl(tiocgwinsz, data) >= 0 then\n #rows, cols, xpixels, ypixels = data.unpack(\"SSSS\")\n cols = data.unpack(\"SSSS\")[1]\n if cols >= 0 then cols else default_width end\n else\n default_width\n end\n rescue Exception\n default_width\n end\n end", "def width\n source_node[:width].to_i\n end", "def width\n ['N', 'S'].include?(@orientation) ? @width : @height\n end", "def width\n if clear_border?\n geometry.width\n\n else\n border.width\n\n end\n end", "def width\n @width\n end", "def width(_data_length, _item_size, viewport)\n return viewport.rect.width\n end", "def length\n images.size\n end", "def width\n barcode.encoding.length * xdim\n end", "def width; rect.width; end", "def width\n @width || Vedeu.width\n end", "def width\n @ole.Width\n end", "def width\n @ole.Width\n end", "def width\n if @x_offset + @width > @source.width\n [@source.width - @x_offset, 0].max\n else\n @width\n end\n end", "def width\n `#{clientRect}.width`\n end", "def width(path)\n io_for(path).width\n end", "def frame_count\n image.get(\"height\") / size.y\n end", "def thumbnail_width\n\t\t\t@data[\"thumbnail\"][\"width\"] if @data[\"thumbnail\"]\n\t\tend", "def width # width of bboxpoint\n\t\tself.coords[2] - self.coords[0]\n\tend", "def height\n image_ptr[:sy]\n end", "def size\n data\n image.filesize\n end", "def width\n @x1 - @x0\n end", "def width\n attr('width')\n end", "def width\n @box.width\n end", "def width\n @box.width\n end", "def width\r\n @content[pn(:MediaBox)][2]\r\n end", "def width\n length * xdim\n end", "def width\n length * xdim\n end", "def width\n begin\n (@num_cols.to_i) * (@col_width.to_i + @gutter.to_i)\n rescue\n 0\n end\n end", "def width\n assert_exists\n driver.execute_script \"return arguments[0].width\", @element\n end", "def pixels\n \n return width.to_i * height.to_i\n \n end", "def width(pagenum=1)\n cgpdfpage = page(pagenum)\n mediabox = CGPDFPageGetBoxRect(cgpdfpage, KCGPDFMediaBox) # => CGRect\n width = mediabox.size.width # CGRectGetWidth(mediabox)\n width\n end", "def value_width\n @width\n end", "def width\n bounds.right\n end", "def width\n raise NotImplementedError\n end", "def size(rect)\n return rect.width\n end", "def width\n @map[0].size\n end", "def size\n @images.size\n end", "def width(style_name=nil)\n style_name ||= reflection.default_style\n if style_name.equal?(:original)\n from_examination :@original_width\n else\n dimensions(style_name).at(0)\n end\n end", "def width\r\n has_width? ? parms[0].to_i : 0\r\n end", "def extract_dimensions\n return unless image?\n tempfile = image.queued_for_write[:original]\n\n # Silently return, if there's no `width` and `height`\n # Prevents old migrations from crashing\n return unless self.respond_to?(:width) && self.respond_to?(:height)\n\n # Works with uploaded files and existing files\n path_or_url = if !tempfile.nil? then\n # Uploading new file\n tempfile.path\n else\n if image.options[:storage] === :s3\n image.url\n else\n image.path\n end\n end\n\n geometry = Paperclip::Geometry.from_file(path_or_url)\n self.width = geometry.width.to_i\n self.height = geometry.height.to_i\n end", "def width\n return nil unless @width ## this is required otherwise checking for nil will fail\n if @width < 0\n return ( FFI::NCurses.COLS + @width ) - self.col + 1\n end\n @width\n end", "def image_size(path)\n magick = MiniMagick::Image.open path\n \"#{magick.width}x#{magick.height}\"\nend", "def width; @width ||= GeoWeb::Map.map_extent(zoom, tile_width); end", "def width\n self.resolution.first unless self.resolution.nil? || many?\n end", "def width\r\n return (@x2-@x1).abs\r\n end", "def thumb_width\n width * thumb_height / height\n end", "def width\n @animation.width\n end", "def calc_width; Graphics.width; end", "def width\n return @window_width # outer width\nend" ]
[ "0.8697535", "0.854393", "0.8308485", "0.8259735", "0.8184614", "0.81736064", "0.8134202", "0.8132018", "0.8096049", "0.775171", "0.7582849", "0.7553192", "0.7429262", "0.7405392", "0.7405392", "0.7329711", "0.7294532", "0.7271352", "0.7265897", "0.7252846", "0.72255766", "0.7198554", "0.7131607", "0.7113031", "0.70981747", "0.70151305", "0.6957401", "0.69366705", "0.6929414", "0.69264185", "0.689978", "0.687904", "0.6802759", "0.67790526", "0.67741287", "0.67460406", "0.67103505", "0.66933244", "0.66918945", "0.666967", "0.66669196", "0.66467744", "0.65918", "0.65815055", "0.6572927", "0.6569153", "0.6569153", "0.65686405", "0.65331674", "0.65331674", "0.6526613", "0.65110934", "0.6509494", "0.6506261", "0.65004057", "0.64896643", "0.64769", "0.6464792", "0.6462159", "0.6457411", "0.6452012", "0.6447467", "0.6447467", "0.64351875", "0.6411668", "0.64089805", "0.63870907", "0.638064", "0.6356058", "0.63557315", "0.6331546", "0.63227093", "0.6308906", "0.62949944", "0.6293844", "0.6287581", "0.62690663", "0.62690663", "0.62670976", "0.62535506", "0.6241276", "0.6223792", "0.6196784", "0.6196274", "0.6183715", "0.6182513", "0.61822164", "0.61604893", "0.61574924", "0.6155622", "0.61395395", "0.61300445", "0.6129572", "0.6113825", "0.6102489", "0.6101348", "0.60972", "0.6073401", "0.6068511", "0.6064713" ]
0.6504203
54
Gets the height of the image.
def height @source.height end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def height\n image.size\n end", "def height\n image_ptr[:sy]\n end", "def height\n @image.height\n end", "def image_height\n\t\t\t@data[\"image\"][\"height\"]\n\t\tend", "def height\n rmagick_image.rows\n end", "def image_height\n\t\t\t@data[\"originalimage\"][\"height\"] if @data[\"originalimage\"]\n\t\tend", "def height\n Vips.vips_image_get_height self\n end", "def image_height(image)\n args = [vips_header_command, '-f', 'Ysize', image.path]\n @cmd.run(*args).out.to_i\n end", "def height\n @image.length\n end", "def image_height(image_handle)\n end", "def image_height\n end", "def height\n dimensions.last\n end", "def height\n @dimensions.y\n end", "def height\n return @height\n end", "def height\n dimensions()[:y]\n end", "def height\n get_geometry if @height.nil?\n return @height\n end", "def height\n return data.height\n end", "def screenshot_height_for(game)\n return 0 if game.nil? || game.image_height.nil?\n return game.image_height\n end", "def pixel_height\n @sensor_height / @height_in_pixels\n end", "def height\n metadata[:height] if valid?\n end", "def height\n size_a[1]\n end", "def height\n case target\n when :editable then height_for_editable_target\n when :cc, :kiddom, :qti, :schoology then image_height\n end\n end", "def height\n\t\treturn @height\n\tend", "def fullheight\n return self.bitmap.height.to_f * self.zoom_y\n end", "def thumbnail_height\n\t\t\t@data[\"thumbnail\"][\"height\"]\n\t\tend", "def height\n bounds[:bottom] - bounds[:top]\n end", "def height\n bounds[:bottom] - bounds[:top]\n end", "def pixelheight\n end", "def height\n size.first\n end", "def height\n size.first\n end", "def height\n (self.width.to_f * (9.to_f/16.to_f)).to_i\n end", "def height\r\n assert_exists\r\n return @o.invoke(\"height\").to_s\r\n end", "def height\n return nil unless @height\n if @height < 0\n return ((FFI::NCurses.LINES + @height) - self.row) + 1\n #return (FFI::NCurses.LINES + @height) \n end\n @height\n end", "def height\n content.size\n end", "def height\n if @y_offset + @height > @source.height\n [@source.height - @y_offset, 0].max\n else\n @height\n end\n end", "def getDimensions\r\n @imageheights = @image.length\r\n @imagewidth = @image[0].length\r\n puts \"image dimensions are #{@imagewidth} by #{@imageheights}\"\r\n end", "def thumbnail_height\n\t\t\t@data[\"thumbnail\"][\"height\"] if @data[\"thumbnail\"]\n\t\tend", "def height(name)\n Tk.execute(:image, :height, name)\n end", "def height\n if clear_border?\n geometry.height\n\n else\n border.height\n\n end\n end", "def height\n barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100)\n end", "def height\n barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100)\n end", "def height\n line_count = layout.line_count\n h = (line_count - 1) * layout.spacing\n line_count.times do |i|\n h += layout.get_line_bounds(i).height\n end\n h\n end", "def get_height\n return get_keyword_value(\"FLOOR-HEIGHT\").to_f\n end", "def frame_count\n image.get(\"height\") / size.y\n end", "def height\n self.resolution.last unless self.resolution.nil? || many?\n end", "def height\n attr('height')\n end", "def height\n attributes.map { |field| field.height }.max\n end", "def height\n @maps[:background].size\n end", "def height(style_name='original')\n geometry(style_name).height.to_i\n end", "def height(_data_length, _item_size, viewport)\n return viewport.rect.height\n end", "def preview_max_height\n geometry = image_style_geometry\n geometry.present? ? geometry.height.to_i : 100\n end", "def height\r\n @content[pn(:MediaBox)][3]\r\n end", "def height(path)\n io_for(path).height\n end", "def height\n lines.size\n end", "def height\n lines.size\n end", "def height\n assert_exists\n driver.execute_script \"return arguments[0].height\", @element\n end", "def GetPageHeight()\n\t\treturn @h;\n\tend", "def height\n memoized_info[:height]\n end", "def height\n # raise NotImplementedError\n # return 0 if @root.nil?\n return height_helper(@root, 0, 1)\n end", "def height\n return 0 if @root == nil\n\n current = @root\n\n return height_helper(current, 1, 1)\n end", "def get_height(dta)\n get_dimension('height', dta)\n end", "def height\n @ole.Height\n end", "def height\n @ole.Height\n end", "def height\n return height_helper(@root, 0, 1)\n end", "def height\n return height_helper(@root, 0, 1)\n end", "def height\n features.intersection(Features::HEIGHT)\n end", "def height\n return 0 if @root.nil?\n return hegiht_helper(@root)\n end", "def height\n return 0 if @root.nil?\n return height_helper(@root, 0, 1)\n end", "def height\n TILE_BASE_HEIGHT\n end", "def height\n rows\n end", "def retrieve_height(param)\n unless (height = param[:height])\n height = self::DEFAULT_HEIGHT if param[:list_direction] == :vertical\n height ||= param[:list_height]\n height ||= self::DEFAULT_HEIGHT\n end\n return height\n end", "def height\n @rows * @block_size\n end", "def height; rect.height; end", "def height\n current_node = @root\n\n return height_helper(current_node)\n end", "def height(style_name=nil)\n style_name ||= reflection.default_style\n if style_name.equal?(:original)\n from_examination :@original_height\n else\n dimensions(style_name).at(1)\n end\n end", "def height\n top + bottom\n end", "def height\n @y1 - @y0\n end", "def height\n return self.src_rect.height\n end", "def height\n return height_helper(@root, 0)\n end", "def height\n return height_helper(@root, 0)\n end", "def height\n @height\n end", "def height\n `#{clientRect}.height`\n end", "def height\n instance.options[:height]\n end", "def height(pagenum=1)\n cgpdfpage = page(pagenum)\n mediabox = CGPDFPageGetBoxRect(cgpdfpage, KCGPDFMediaBox) # => CGRect\n height = mediabox.size.height # CGRectGetHeight(mediabox)\n height\n end", "def scroll_height\n self.scroll_size[:y]\n end", "def height\n @screenplay.line_height * @lines.size\n end", "def height\r\n return (@y2-@y1).abs\r\n end", "def height\n return height_helper(@root)\n end", "def height\n file.height\n end", "def height()\n\t\t@pokemon_api[\"height\"]\n\tend", "def image_size\n end", "def height\n ['N', 'S'].include?(@orientation) ? @height : @width\n end", "def height\n count = 0\n if @root != nil\n count = height_helper(@root)\n end\n return count\n end", "def size\n data\n image.filesize\n end", "def height\n array.size\n end", "def height; end", "def height; end", "def height\n return self.rect.height\n end", "def height\n @height || 100\n end", "def height\n @bottom_edge - @top_edge\n end" ]
[ "0.868352", "0.8597373", "0.8539739", "0.83560395", "0.8275449", "0.8221125", "0.81993854", "0.8046682", "0.7958535", "0.7801322", "0.76953936", "0.7344727", "0.72934014", "0.72673", "0.7234544", "0.7232246", "0.72312737", "0.71938944", "0.7190046", "0.7152863", "0.7113009", "0.70891494", "0.70479363", "0.7035664", "0.699579", "0.6965942", "0.6965942", "0.69402725", "0.6907415", "0.6907415", "0.6895898", "0.6890654", "0.6865345", "0.6850595", "0.6835285", "0.68209004", "0.6811872", "0.6810401", "0.67980677", "0.6790577", "0.6790577", "0.67817783", "0.67773336", "0.67676836", "0.67276853", "0.67264515", "0.6723771", "0.6716895", "0.6710423", "0.6695901", "0.6695639", "0.6682771", "0.66536546", "0.66365546", "0.66365546", "0.6631918", "0.6627964", "0.66051316", "0.65987927", "0.65959305", "0.65941733", "0.6588207", "0.6588207", "0.65780044", "0.65780044", "0.65735364", "0.65556234", "0.6549544", "0.6541668", "0.6536369", "0.6514936", "0.6499951", "0.64956594", "0.6494852", "0.648482", "0.64815193", "0.6479633", "0.64746463", "0.64675564", "0.64675564", "0.64623874", "0.6449738", "0.644595", "0.64399225", "0.64334744", "0.64126784", "0.6411582", "0.6409684", "0.6406497", "0.64001566", "0.639517", "0.63926375", "0.6392364", "0.6386784", "0.63759977", "0.6360046", "0.6360046", "0.6355944", "0.63458145", "0.63423574" ]
0.6566409
66