query
stringlengths 7
9.55k
| document
stringlengths 10
363k
| metadata
dict | negatives
listlengths 0
101
| negative_scores
listlengths 0
101
| document_score
stringlengths 3
10
| document_rank
stringclasses 102
values |
|---|---|---|---|---|---|---|
PATCH/PUT /preparar_mates/1 PATCH/PUT /preparar_mates/1.json
|
def update
@empresa = Empresa.find(params[:empresa_id])
@producto = @empresa.productos.find(params[:producto_id])
@preparar_mate = @producto.preparar_mates.find(params[:id])
respond_to do |format|
if @preparar_mate.update(preparar_mate_params)
format.html { redirect_to empresa_producto_preparar_mates_path, notice: 'Preparar mate was successfully updated.' }
format.json { render :show, status: :ok, location: @preparar_mate }
else
format.html { render :edit }
format.json { render json: @preparar_mate.errors, status: :unprocessable_entity }
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def update\n if @person.seat\n render json: {errors: 'Cannot update a seated person'}, status: 422\n else\n @person.update person_params\n render json: @person\n end\n end",
"def update\n @mate = Mate.find(params[:id])\n\n respond_to do |format|\n if @mate.update_attributes(params[:mate])\n format.html { redirect_to @mate, notice: 'Mate was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: {errors: @mate.errors}, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @maker_master.update(maker_master_params)\n format.html { redirect_to @maker_master, notice: 'Maker master was successfully updated.' }\n format.json { render :show, status: :ok, location: @maker_master }\n else\n format.html { render :edit }\n format.json { render json: @maker_master.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @team_mate = TeamMate.find(params[:id])\n\n respond_to do |format|\n if @team_mate.update_attributes(params[:team_mate])\n format.html { redirect_to @team_mate, notice: 'Team mate was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @team_mate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @kota_stone.update(kota_stone_params)\n format.html { redirect_to kota_stones_url, notice: 'Kota stone was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @kota_stone.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_from_mobile\n\t\tif !params[:id].nil?\n\t\t\t@protege = Protege.find(params[:id])\n\t\t\tif @protege.update_attributes(protege_mobile)\n\t\t\t\trender json: {status: \"success\"}\n\t\t\telse\n\t\t\t\trender json: {status: \"failure\"}\n\t\t\tend\n\t\telse\n\t\t\trender json: {status: \"failure\"}\n\t\tend\n\n\tend",
"def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end",
"def update\n @rayon = Rayon.find(params[:id])\n\n respond_to do |format|\n if @rayon.update_attributes(params[:rayon])\n format.html { redirect_to @rayon, notice: 'Rayon was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @rayon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @mini_map_road = MiniMapRoad.find(params[:id])\n\n respond_to do |format|\n if @mini_map_road.update_attributes(params[:mini_map_road])\n format.html { redirect_to @mini_map_road, notice: 'Mini map road was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @mini_map_road.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @maker.update(maker_params)\n format.html { redirect_to @maker, notice: 'Maker was successfully updated.' }\n format.json { render :show, status: :ok, location: @maker }\n else\n format.html { render :edit }\n format.json { render json: @maker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @maker.update(maker_params)\n format.html { redirect_to @maker, notice: \"Maker was successfully updated.\" }\n format.json { render :show, status: :ok, location: @maker }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @maker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @premio = Premio.find(params[:id])\n\n respond_to do |format|\n if @premio.update_attributes(params[:premio])\n format.html { redirect_to @premio, :notice => 'Premio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @premio.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @premio = Premio.find(params[:id])\n\n respond_to do |format|\n if @premio.update_attributes(params[:premio])\n format.html { redirect_to @premio, notice: 'Premio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @premio.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update \n sneaker = find_sneaker\n # update! exceptions will be handled by the rescue_from ActiveRecord::RecordInvalid code\n sneaker.update(sneaker_params)\n render json: sneaker\n end",
"def update\n @moose = Moose.find(params[:id])\n\n respond_to do |format|\n if @moose.update_attributes(params[:moose])\n format.html { redirect_to @moose, notice: 'Moose was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @moose.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @stone = Stone.find(params[:id])\n\n respond_to do |format|\n if @stone.update_attributes(params[:stone])\n format.html { redirect_to @stone, notice: 'Stone was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @stone.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n client=Client.find_by_id params[:id]\n if client!= nil\n client.cedula=params[:cedula] ? params[:cedula]: client.cedula\n client.sector=params[:sector] ? params[:sector]: client.sector\n client.nombre=params[:nombre] ? params[:nombre]: client.nombre\n client.telefono=params[:telefono] ? params[:telefono]: client.telefono\n client.pagina=params[:pagina] ? params[:pagina]: client.pagina\n client.direccion=params[:direccion] ? params[:direccion]: client.direccion\n if client.save\n render(json: client, status: 201)\n end \n else\n render(json: client.errors, status: 404)\n end \n end",
"def update\n if (admin_priveledge? == false) && (myself?(params[:id]) == false)\n redirect_to teammates_path, :notice => \"Die noetigen Rechte fehlen.\"\n return\n end\n\n @teammate = Teammate.find(params[:id])\n\n respond_to do |format|\n if @teammate.update_attributes(params[:teammate])\n format.html { redirect_to @teammate, :notice => 'Teammate was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @teammate.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @male_shot_put_head.update(male_shot_put_head_params)\n format.html { redirect_to @male_shot_put_head, notice: 'Male shot put head was successfully updated.' }\n format.json { render :show, status: :ok, location: @male_shot_put_head }\n else\n format.html { render :edit }\n format.json { render json: @male_shot_put_head.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @plasmid_probe.update(plasmid_probe_params)\n format.html { redirect_to @plasmid_probe, notice: 'Plasmid probe was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @plasmid_probe.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\nrespond_to do |format|\nif @pin.update(pin_params)\nformat.html { redirect_to @pin, notice: 'Pin was successfully updated.' }\nformat.json { head :no_content }\nelse\nformat.html { render action: 'edit' }\nformat.json { render json: @pin.errors, status: :unprocessable_entity }\nend\nend\nend",
"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 respond_to do |format|\n if @mountain.update(mountain_params)\n format.html { redirect_to @mountain, notice: 'Mountain was successfully updated.' }\n format.json { render :show, status: :ok, location: @mountain }\n else\n format.html { render :edit }\n format.json { render json: @mountain.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @teammate = Teammate.find(params[:id])\n\n respond_to do |format|\n if @teammate.update_attributes(params[:teammate])\n format.html { redirect_to @teammate, notice: 'Teammate was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @teammate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @proteinname.update(proteinname_params)\n format.html { redirect_to @proteinname, notice: 'Proteinname was successfully updated.' }\n format.json { render :show, status: :ok, location: @proteinname }\n else\n format.html { render :edit }\n format.json { render json: @proteinname.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @matome.update(matome_params)\n format.html { redirect_to @matome, notice: 'Matome was successfully updated.' }\n format.json { render :show, status: :ok, location: @matome }\n else\n format.html { render :edit }\n format.json { render json: @matome.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @matome.update(matome_params)\n format.html { redirect_to @matome, notice: 'Matome was successfully updated.' }\n format.json { render :show, status: :ok, location: @matome }\n else\n format.html { render :edit }\n format.json { render json: @matome.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @maturi.update(maturi_params)\n format.html { redirect_to @maturi, notice: 'Maturi was successfully updated.' }\n format.json { render :show, status: :ok, location: @maturi }\n else\n format.html { render :edit }\n format.json { render json: @maturi.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @student_cell_leader = StudentCellLeader.find(params[:id])\n\n respond_to do |format|\n if @student_cell_leader.update_attributes(params[:student_cell_leader])\n format.html { redirect_to @student_cell_leader, notice: 'Student cell leader was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @student_cell_leader.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n #Finding the specific chore where the id matches the one we pass in with the body\n @v1_chore = Chore.where(id: params[:id]).first\n #Here we're checking if we have user_id in our body, and if we do, we'll change the selected chore's properties\n #with the parameters of the body, we go through the specific group to our specific chore with the path\n if v1_chore_params[:user_id]\n @v1_chore.user_id = params[:user_id]\n @v1_chore.assigned = true\n if @v1_chore.save\n render :show, status: :ok\n end\n else\n render json: @v1_chore.errors, status: :unprocessable_entity\n end\n end",
"def update!(**args)\n @remodelings = args[:remodelings] if args.key?(:remodelings)\n @single_token = args[:single_token] if args.key?(:single_token)\n end",
"def update\n @protein = Protein.find(params[:id])\n\n respond_to do |format|\n if @protein.update_attributes(params[:protein])\n format.html { redirect_to @protein, notice: 'Protein was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @protein.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @prim.update(prim_params)\n format.html { redirect_to @prim, notice: 'Prim was successfully updated.' }\n format.json { render :show, status: :ok, location: @prim }\n else\n format.html { render :edit }\n format.json { render json: @prim.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @teammate.update(teammate_params)\n format.html { redirect_to pitch_teammate_path(@pitch, @teammate), notice: \"O Tripulante <strong>#{@teammate.user.name}</strong> foi atualizado.\" }\n format.json { render :show, status: :ok, location: [@pitch, @teammate] }\n else\n format.html { render :edit }\n format.json { render json: @teammate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_attr\n #sanity checks \n @persona = current_persona\n @mediaset = @persona.mediasets.find(params[:id])\n \n respond_to do |format|\n @mediaset.update_attributes( params[:mediaset] )\n format.json{ respond_with_bip(@mediaset) }\n end\n end",
"def update\n respond_to do |format|\n if @manga.update(manga_params)\n format.html { redirect_to @manga, notice: 'Manga was successfully updated.' }\n format.json { render :show, status: :ok, location: @manga }\n else\n format.html { render :edit }\n format.json { render json: @manga.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @maker.update(maker_params)\n format.html { redirect_to @maker, notice: 'Maker was successfully updated.' }\n format.json { render :show, status: :ok, location: @maker }\n else\n format.html { render :edit }\n format.json { render json: @maker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @manga = Manga.find(params[:id])\n\n respond_to do |format|\n if @manga.update_attributes(params[:manga])\n format.html { redirect_to @manga, notice: 'Manga was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @manga.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mld_mate.update(mld_mate_params)\n format.html { redirect_to @mld_mate, notice: \"Mld mate was successfully updated.\" }\n format.json { render :show, status: :ok, location: @mld_mate }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @mld_mate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @individual.update(individual_params)\n format.html { redirect_to @individual, notice: 'Individual was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @individual.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @microposr = Microposr.find(params[:id])\n\n respond_to do |format|\n if @microposr.update_attributes(params[:microposr])\n format.html { redirect_to @microposr, notice: 'Microposr was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @microposr.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @latstraps1.update(latstraps1_params)\n format.html { redirect_to \"/latstraps1s\"}\n format.json { render :show, status: :ok, location: @latstraps1 }\n else\n format.html { render :edit }\n format.json { render json: @latstraps1.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @beacon.update(beacon_params)\n Beacon.gimbal_update_beacon(@beacon)\n format.html { redirect_to @beacon, notice: 'Beacon was successfully updated.' }\n format.json { render :template => \"owners/show\", status: :ok, location: @beacon }\n else\n format.html { render :edit }\n format.json { render json: @beacon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @profesium.update(profesium_params)\n format.html { redirect_to @profesium, notice: 'Profesium was successfully updated.' }\n format.json { render :show, status: :ok, location: @profesium }\n else\n format.html { render :edit }\n format.json { render json: @profesium.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @premise.update(premise_params)\n format.html { redirect_to @premise, notice: 'Premise was successfully updated.' }\n format.json { render :show, status: :ok, location: @premise }\n else\n format.html { render :edit }\n format.json { render json: @premise.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n apartment = Apartment.find(params[:id])\n apartment.update_attributes(apartment_params)\n render json: apartment\n end",
"def update\n respond_to do |format|\n if @waiter.update(waiter_params.slice(:name, :email, :mobile))\n format.html { redirect_to waiters_manager_path(current_user), notice: i18n_notice('updated',@waiter) }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @waiter.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @pick.update_attributes(picks_params)\n format.html { redirect_to games_path, notice: 'Pick was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @pick.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @missionmaker = Missionmaker.find(params[:id])\n\n respond_to do |format|\n if @missionmaker.update_attributes(params[:missionmaker])\n format.html { redirect_to @missionmaker, notice: 'Missionmaker was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @missionmaker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @microposst = Microposst.find(params[:id])\n\n respond_to do |format|\n if @microposst.update_attributes(params[:microposst])\n format.html { redirect_to @microposst, notice: 'Microposst was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @microposst.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mechon.update(mechon_params)\n format.html { redirect_to @mechon, notice: 'Mechon was successfully updated.' }\n format.json { render :show, status: :ok, location: @mechon }\n else\n format.html { render :edit }\n format.json { render json: @mechon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @minister.update(minister_params)\n format.html { redirect_to @minister, notice: 'Minister was successfully updated.' }\n format.json { render :show, status: :ok, location: @minister }\n else\n format.html { render :edit }\n format.json { render json: @minister.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @mint_coin = @coin.mint_coins.find(params[:id])\n\n respond_to do |format|\n if @mint_coin.update_attributes(params[:mint_coin])\n format.html { redirect_to coin_mint_coins_url([@coin]), :notice => 'Mint coin was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @mint_coin.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n params[:examination][:usesOfDrug_ids] ||= []\n params[:examination][:resistancesToDrug_ids] ||= []\n params[:examination][:mutation_ids] ||= []\n @examination = Examination.find(params[:id])\n\n respond_to do |format|\n if @examination.update_attributes(params[:examination])\n format.html { redirect_to @examination, notice: 'Examination was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @examination.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @m1.update(m1_params)\n format.html { redirect_to @m1, notice: 'M1 was successfully updated.' }\n format.json { render :show, status: :ok, location: @m1 }\n else\n format.html { render :edit }\n format.json { render json: @m1.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @materia_prima.update(materia_prima_params)\n format.html { redirect_to @materia_prima, notice: 'Materia prima was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @materia_prima.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if request.content_type == \"application/json\"\n # .update is like a \"update people set ...\" in sql\n if @person.update(person_params)\n render json: @person\n else\n render json: @person.errors, status: :not_found\n end\n else\n render status: :bad_request\n end\n end",
"def update\n @ref_protein = RefProtein.find(params[:id])\n\n respond_to do |format|\n if @ref_protein.update_attributes(params[:ref_protein])\n format.html { redirect_to @ref_protein, notice: 'Ref protein was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ref_protein.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @persona = Persona.find(params[:id])\n \n respond_to do |format|\n if @persona.update_attributes(params[:persona])\n format.json { head :ok }\n else\n format.json { render :json => @persona.errors,\n :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @major.update(major_params)\n format.html { redirect_to @major, notice: 'Major was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @major.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @leader = Leader.find(params[:id])\n\n respond_to do |format|\n if @leader.update_attributes(params[:leader])\n format.html { redirect_to @leader, notice: 'Leader was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @leader.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @primer = Primer.find(params[:id])\n\n respond_to do |format|\n if @primer.update_attributes(params[:primer])\n format.html { redirect_to @primer, notice: 'Primer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @primer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @osm.update(osm_params)\n format.html { redirect_to @osm, notice: 'Osm was successfully updated.' }\n format.json { render :show, status: :ok, location: @osm }\n else\n format.html { render :edit }\n format.json { render json: @osm.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @request.assign_json_attributes(params) if @request.resume?\n respond_to do |format|\n if @request.update(request_params)\n format.html { redirect_to @request, notice: 'Request was successfully updated.' }\n format.json { render :show, status: :ok, location: @request }\n else\n format.html { render :edit }\n format.json { render json: @request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @major.update(major_params)\n format.html { redirect_to @major, notice: 'Major was successfully updated.' }\n format.json { render :show, status: :ok, location: @major }\n else\n format.html { render :edit }\n format.json { render json: @major.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @maze.update(maze_params)\n format.html { redirect_to @maze, notice: 'Labirinto atualizado com sucesso.' }\n format.json { render :show, status: :ok, location: @maze }\n else\n format.html { render :edit }\n format.json { render json: @maze.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @plate.update(plate_params)\n format.html { redirect_to @plate, notice: 'Plate was successfully updated.' }\n format.json { render :show, status: :ok, location: @plate }\n else\n format.html { render :edit }\n format.json { render json: @plate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @enzyme = Enzyme.find(params[:id])\n @hmm_profiles = HmmProfile.find_all_by_id(params[:hmm_profile_ids])\n \n @enzyme.hmm_profiles.destroy_all\n respond_to do |format|\n if @enzyme.update_attributes(params[:enzyme])\n if @hmm_profiles\n @hmm_profiles.each do |profile|\n enzyme_profile = EnzymeProfile.new()\n enzyme_profile.hmm_profile_id = profile.id\n enzyme_profile.enzyme_id = @enzyme.id\n enzyme_profile.save\n end\n end\n\n format.html { redirect_to @enzyme, notice: 'Enzyme was successfully updated.' }\n format.json { head :no_content }\n else\n @hmm_profiles = HmmProfile.all\n @parent_candidates = Enzyme.all\n format.html { render action: \"edit\" }\n format.json { render json: @enzyme.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if params[:kid][:id]\n @kid = Kid.find(params[:kid][:id])\n else\n @kid = Kid.find_by_user_id_and_local_id(params[:kid][:user_id],params[:kid][:local_id])\n end\n params[:kid].delete(:user_id)\n params[:kid].delete(:id)\n if @kid.update_attributes(params[:kid])\n render json: @kid\n else\n render json: @kid.errors, status: :unprocessable_entity\n end\n end",
"def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def update\n respond_to do |format|\n if @plate.update(plate_params)\n format.html { redirect_to [@client, @budget, @mobile], notice: 'Chapa atualizada com sucesso.' }\n format.json { render :show, status: :ok, location: @plate }\n else\n format.html { render :edit }\n format.json { render json: @plate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @moresmallarmorinfo = Moresmallarmorinfo.find(params[:id])\n\n respond_to do |format|\n if @moresmallarmorinfo.update_attributes(params[:moresmallarmorinfo])\n format.html { redirect_to @moresmallarmorinfo, notice: 'Moresmallarmorinfo was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @moresmallarmorinfo.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @major = Major.find(params[:id])\n\n respond_to do |format|\n if @major.update_attributes(params[:major])\n format.html { redirect_to @major, notice: 'Major was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @major.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @individual.update(individual_params)\n format.html { redirect_to @individual, notice: 'Individual was successfully updated.' }\n format.json { render :show, status: :ok, location: @individual }\n else\n format.html { render :edit }\n format.json { render json: @individual.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @pinjam.update(pinjam_params)\n format.html { redirect_to @pinjam, notice: 'Pinjam was successfully updated.' }\n format.json { render :show, status: :ok, location: @pinjam }\n else\n format.html { render :edit }\n format.json { render json: @pinjam.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @malejump_head.update(malejump_head_params)\n format.html { redirect_to @malejump_head, notice: 'Malejump head was successfully updated.' }\n format.json { render :show, status: :ok, location: @malejump_head }\n else\n format.html { render :edit }\n format.json { render json: @malejump_head.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @mind_map.update(mind_map_params)\n render :show, status: :ok\n else\n render json: @mind_map.errors, status: :unprocessable_entity\n end\n end",
"def update\n @my_ministry = MyMinistry.find(params[:id])\n\n respond_to do |format|\n if @my_ministry.update_attributes(params[:my_ministry])\n format.html { redirect_to @my_ministry, notice: 'My ministry was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @my_ministry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @spawner = Spawner.find(params[:id])\n @fieldtrips = Fieldtrip.all\n\n respond_to do |format|\n if @spawner.update_attributes(spawner_params)\n format.html { redirect_to @spawner, notice: 'Spawner was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @spawner.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @pet_true.update(pet_true_params)\n format.html { redirect_to @pet_true, notice: 'Pet true was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @pet_true.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mile.update(mile_params)\n format.html { redirect_to @mile, notice: 'Mile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @rat.update(rat_params)\n format.html { redirect_to @rat, notice: 'Rat was successfully updated.' }\n format.json { render :show, status: :ok, location: @rat }\n else\n format.html { render :edit }\n format.json { render json: @rat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @ami = Ami.find(params[:id])\n\n respond_to do |format|\n if @ami.update_attributes(params[:ami])\n format.html { redirect_to @ami, notice: 'Ami was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ami.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @mineral = Mineral.find(params[:id])\n \n respond_to do |format|\n if @mineral.update_attributes(params[:mineral])\n format.html { redirect_to @mineral, notice: 'Mineral was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mineral.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @jamaat = Jamaat.find(params[:id])\n\n respond_to do |format|\n if @jamaat.update_attributes(params[:jamaat])\n format.html { redirect_to @jamaat, notice: 'Jamaat was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @jamaat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @leadership.update(leadership_params)\n format.html { redirect_to @leadership, notice: 'Leadership was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @leadership.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n mountain = Mountain.find params[:id]\n mountain.update mountain_params\n redirect_to (mountains_path)\n end",
"def update\n @mrj = Mrj.find(params[:id])\n\n respond_to do |format|\n if @mrj.update_attributes(params[:mrj])\n format.html { redirect_to @mrj, notice: 'Mrj was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @mrj.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @sphere = Sphere.find(params[:id])\n\n respond_to do |format|\n if @sphere.update_attributes(params[:sphere])\n format.html { redirect_to @sphere, notice: 'Sphere a été édité avec succès.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sphere.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mata_matum.update(mata_matum_params)\n format.html { redirect_to @mata_matum, notice: 'Mata matum was successfully updated.' }\n format.json { render :show, status: :ok, location: @mata_matum }\n else\n format.html { render :edit }\n format.json { render json: @mata_matum.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @person = Person.find(params[:id]) \n respond_to do |format|\n if @person.update(person_params)\n format.json { render json: @person, status: :ok }\n else\n format.json { render json: @person.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @mini_game.update(mini_game_params)\n render json: @mini_game, status: :ok\n else\n render json: @mini_game.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @pin.update(pin_params)\n format.html { redirect_to @pin, notice: 'Pin was successfully updated.' }\n format.json { render :show, status: :ok, location: @pin }\n else\n format.html { render :edit }\n format.json { render json: @pin.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n Rails.logger.debug \"GOT TO matches -> update\"\n match = Match.find(params[:match_id].to_i)\n requestor = match.user_for_id(params[:requestor_id].to_i)\n recipient = match.user_for_id(params[:requested_id].to_i)\n match.ask_for_cards(requestor: requestor, recipient: recipient, card_rank: params['rank'].upcase)\n match.save!\n render json: nil, status: :ok\n end",
"def update\n respond_to do |format|\n if @raw_material.update(raw_material_params)\n format.html { redirect_to @raw_material, notice: 'Raw material was successfully updated.' }\n format.json { render :show, status: :ok, location: @raw_material }\n else\n format.html { render :edit }\n format.json { render json: @raw_material.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @raw_material.update(raw_material_params)\n format.html { redirect_to @raw_material, notice: 'Raw material was successfully updated.' }\n format.json { render :show, status: :ok, location: @raw_material }\n else\n format.html { render :edit }\n format.json { render json: @raw_material.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @seat_manufacturer.update_attributes(params[:seat_manufacturer])\n format.html { redirect_to @seat_manufacturer, notice: 'Seat manufacturer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @seat_manufacturer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @climate = Climate.find(params[:id])\n\n respond_to do |format|\n if @climate.update_attributes(params[:climate])\n format.html { redirect_to climates_path, notice: 'Climate was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @climate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n new_properties = params[:d]\n profile = Profile[params[:id]]\n profile.update_with(new_properties)\n\n respond_with(profile) do |format|\n format.json { render json: profile.stripped }\n end\n end",
"def update!(**args)\n @affinity = args[:affinity] if args.key?(:affinity)\n @attribution = args[:attribution] if args.key?(:attribution)\n @best_display_name = args[:best_display_name] if args.key?(:best_display_name)\n @block_type = args[:block_type] if args.key?(:block_type)\n @circle_id = args[:circle_id] if args.key?(:circle_id)\n @contact_group_id = args[:contact_group_id] if args.key?(:contact_group_id)\n @contact_id = args[:contact_id] if args.key?(:contact_id)\n @custom_response_masking_type = args[:custom_response_masking_type] if args.key?(:custom_response_masking_type)\n @deleted = args[:deleted] if args.key?(:deleted)\n @deprecated_blocked = args[:deprecated_blocked] if args.key?(:deprecated_blocked)\n @deprecated_membership_circle_id = args[:deprecated_membership_circle_id] if args.key?(:deprecated_membership_circle_id)\n @deprecated_membership_contact_group_id = args[:deprecated_membership_contact_group_id] if args.key?(:deprecated_membership_contact_group_id)\n @device_contact_info = args[:device_contact_info] if args.key?(:device_contact_info)\n @identity_info = args[:identity_info] if args.key?(:identity_info)\n @in_viewer_domain = args[:in_viewer_domain] if args.key?(:in_viewer_domain)\n @incoming_block_type = args[:incoming_block_type] if args.key?(:incoming_block_type)\n @last_update_time_micros = args[:last_update_time_micros] if args.key?(:last_update_time_micros)\n @model = args[:model] if args.key?(:model)\n @object_type = args[:object_type] if args.key?(:object_type)\n @owner_id = args[:owner_id] if args.key?(:owner_id)\n @owner_user_type = args[:owner_user_type] if args.key?(:owner_user_type)\n @plus_page_type = args[:plus_page_type] if args.key?(:plus_page_type)\n @previous_person_id = args[:previous_person_id] if args.key?(:previous_person_id)\n @profile_owner_stats = args[:profile_owner_stats] if args.key?(:profile_owner_stats)\n @scoring_info = args[:scoring_info] if args.key?(:scoring_info)\n @user_visible_stats = args[:user_visible_stats] if args.key?(:user_visible_stats)\n end"
] |
[
"0.60174227",
"0.5998688",
"0.5731182",
"0.5701388",
"0.5689525",
"0.56807256",
"0.56611806",
"0.565699",
"0.5638485",
"0.5633029",
"0.56301004",
"0.56210715",
"0.5616712",
"0.5614435",
"0.5582845",
"0.5559411",
"0.5553166",
"0.55479866",
"0.55236256",
"0.55137575",
"0.55026376",
"0.54999065",
"0.5497813",
"0.54961115",
"0.5473507",
"0.5472038",
"0.5472038",
"0.5469996",
"0.54596555",
"0.5456619",
"0.5455967",
"0.5451204",
"0.545036",
"0.544505",
"0.54407537",
"0.54388684",
"0.5434259",
"0.54341394",
"0.5432625",
"0.5432122",
"0.5431437",
"0.5427418",
"0.5422211",
"0.5419634",
"0.5406816",
"0.5401501",
"0.54000133",
"0.5387605",
"0.5387573",
"0.5387065",
"0.5384138",
"0.538363",
"0.5383507",
"0.5373196",
"0.5368405",
"0.5366054",
"0.5364427",
"0.5364387",
"0.536318",
"0.53609353",
"0.53519154",
"0.53518087",
"0.5351508",
"0.53460264",
"0.5342264",
"0.53363895",
"0.53337264",
"0.53334826",
"0.5332154",
"0.5324047",
"0.53188074",
"0.53187525",
"0.53165567",
"0.53150195",
"0.53115886",
"0.5305613",
"0.53045505",
"0.53027964",
"0.53025997",
"0.5302433",
"0.530077",
"0.5293416",
"0.52902067",
"0.5289671",
"0.5289516",
"0.5289403",
"0.5288748",
"0.52867854",
"0.5284698",
"0.5282465",
"0.5280162",
"0.52799505",
"0.5276181",
"0.5275138",
"0.52743834",
"0.52743834",
"0.52699345",
"0.5266276",
"0.5261302",
"0.5259694"
] |
0.62828004
|
0
|
DELETE /preparar_mates/1 DELETE /preparar_mates/1.json
|
def destroy
@empresa = Empresa.find(params[:empresa_id])
@producto = @empresa.productos.find(params[:producto_id])
@preparar_mate = @producto.preparar_mates.find(params[:id])
@preparar_mate.destroy
respond_to do |format|
format.html { redirect_to empresa_producto_preparar_mates_path, notice: 'Preparar mate was successfully destroyed.' }
format.json { head :no_content }
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def destroy\n @mld_mate.destroy\n respond_to do |format|\n format.html { redirect_to mld_mates_url, notice: \"Mld mate was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mate = Mate.find(params[:id])\n @mate.destroy\n\n respond_to do |format|\n format.html { redirect_to mates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @stone = Stone.find(params[:id])\n @stone.destroy\n\n respond_to do |format|\n format.html { redirect_to stones_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @kota_stone.destroy\n respond_to do |format|\n format.html { redirect_to kota_stones_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @team_mate = TeamMate.find(params[:id])\n @team_mate.destroy\n\n respond_to do |format|\n format.html { redirect_to team_mates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @teammate = Teammate.find(params[:id])\n @teammate.destroy\n\n respond_to do |format|\n format.html { redirect_to teammates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @rayon = Rayon.find(params[:id])\n @rayon.destroy\n\n respond_to do |format|\n format.html { redirect_to rayons_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mini_map_road = MiniMapRoad.find(params[:id])\n @mini_map_road.destroy\n\n respond_to do |format|\n format.html { redirect_to mini_map_roads_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @maze.destroy\n respond_to do |format|\n format.html { redirect_to mazes_url, notice: 'Labirinto destruído com sucesso.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @manga = Manga.find(params[:id])\n @manga.destroy\n\n respond_to do |format|\n format.html { redirect_to mangas_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @climate = Climate.find(params[:id])\n @climate.destroy\n\n respond_to do |format|\n format.html { redirect_to climates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @maturi.destroy\n respond_to do |format|\n format.html { redirect_to maturis_url, notice: 'Maturi was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n Roommate.destroy(@roommate.id)\n set_roommates\n respond_to do |format|\n format.html { redirect_to roommates_url, notice: 'Roommate was successfully deleted.' }\n format.json { head :no_content }\n format.js\n end\n end",
"def delete\n client.delete(\"/#{id}\")\n end",
"def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end",
"def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def destroy\n @male_shot_put_head.destroy\n respond_to do |format|\n format.html { redirect_to male_shot_put_heads_url, notice: 'Male shot put head was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @protein = Protein.find(params[:id])\n @protein.destroy\n\n respond_to do |format|\n format.html { redirect_to proteins_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @alum_mat.destroy\n respond_to do |format|\n format.html { redirect_to alum_mats_url, notice: 'Alum mat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @makrana_marble.destroy\n respond_to do |format|\n format.html { redirect_to makrana_marbles_url }\n format.json { head :no_content }\n end\n end",
"def delete\n render json: Alien.delete(params[\"id\"])\n end",
"def destroy\n @profesium.destroy\n respond_to do |format|\n format.html { redirect_to profesia_url, notice: 'Profesium was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mata_matum.destroy\n respond_to do |format|\n format.html { redirect_to mata_mata_url, notice: 'Mata matum was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @aream.destroy\n respond_to do |format|\n format.html { redirect_to areams_url }\n format.json { head :no_content }\n end\n end",
"def destroy\r\n @protein.destroy\r\n respond_to do |format|\r\n format.html { redirect_to proteins_url }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @three.destroy\n respond_to do |format|\n format.html { redirect_to threes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ref_protein = RefProtein.find(params[:id])\n @ref_protein.destroy\n\n respond_to do |format|\n format.html { redirect_to ref_proteins_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @matrixspecy.destroy\n respond_to do |format|\n format.html { redirect_to matrixspecies_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @m1.destroy\n respond_to do |format|\n format.html { redirect_to m1s_url, notice: 'M1 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend",
"def destroy\n @asteroid.destroy\n respond_to do |format|\n format.html { redirect_to asteroids_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @major.destroy\n respond_to do |format|\n format.html { redirect_to majors_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ami = Ami.find(params[:id])\n @ami.destroy\n\n respond_to do |format|\n format.html { redirect_to amis_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @manga.destroy\n respond_to do |format|\n format.html { redirect_to mangas_url, notice: 'Manga was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @manga.destroy\n respond_to do |format|\n format.html { redirect_to mangas_url, notice: 'Manga was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @matome.destroy\n respond_to do |format|\n format.html { redirect_to matomes_url, notice: 'Matome was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @matome.destroy\n respond_to do |format|\n format.html { redirect_to matomes_url, notice: 'Matome was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @pharmaceutical_master.destroy\n respond_to do |format|\n format.html { redirect_to pharmaceutical_masters_url, notice: DELETE_NOTICE }\n format.json { head :no_content }\n end\n end",
"def destroy\n @vertices_scene1.destroy\n respond_to do |format|\n format.html { redirect_to vertices_scene1s_url, notice: 'Vertices scene1 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @odeme_akademist = Odeme::Akademist.find(params[:id])\n @odeme_akademist.destroy\n\n respond_to do |format|\n format.html { redirect_to odeme_akademists_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @premio = Premio.find(params[:id])\n @premio.destroy\n\n respond_to do |format|\n format.html { redirect_to premios_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @premio = Premio.find(params[:id])\n @premio.destroy\n\n respond_to do |format|\n format.html { redirect_to premios_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @persona = Persona.find(params[:id])\n @persona.destroy\n\n respond_to do |format|\n format.json { head :ok }\n end\n \n end",
"def destroy\n @plate.destroy\n respond_to do |format|\n format.html { redirect_to plates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @osm.destroy\n respond_to do |format|\n format.html { redirect_to osms_url, notice: 'Osm was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @pharmacy.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n @sneaker.destroy\n Sneaker.reindex\n respond_to do |format|\n format.html { redirect_to sneaker_url, notice: 'Pin was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mile.destroy\n respond_to do |format|\n format.html { redirect_to miles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @moresmallarmorinfo = Moresmallarmorinfo.find(params[:id])\n @moresmallarmorinfo.destroy\n\n respond_to do |format|\n format.html { redirect_to moresmallarmorinfos_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @microposst = Microposst.find(params[:id])\n @microposst.destroy\n\n respond_to do |format|\n format.html { redirect_to micropossts_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mattress = Mattress.find(params[:id])\n @mattress.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_mattresses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @areco = Areco.find(params[:id])\n @areco.destroy\n\n respond_to do |format|\n format.html { redirect_to arecos_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 @mountain.destroy\n respond_to do |format|\n format.html { redirect_to mountains_url, notice: 'Mountain was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @beacon = Beacon.find(params[:id])\n @beacon.destroy\n\n respond_to do |format|\n format.html { redirect_to beacons_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @roadcrime = Roadcrime.find(params[:id])\n @roadcrime.destroy\n\n respond_to do |format|\n format.html { redirect_to roadcrimes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @jam_circle.destroy\n respond_to do |format|\n format.html { redirect_to jam_circles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @nudge.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n @materia = Materia.find(params[:id])\n @materia.destroy\n\n respond_to do |format|\n format.html { redirect_to materia_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @major = Major.find(params[:id])\n @major.destroy\n\n respond_to do |format|\n format.html { redirect_to majors_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @missionmaker = Missionmaker.find(params[:id])\n @missionmaker.destroy\n\n respond_to do |format|\n format.html { redirect_to missionmakers_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @uginuce.sheep.update status:'na farmi'\n @uginuce.destroy\n respond_to do |format|\n format.html { redirect_to uginuces_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n teammate_name = @teammate.name\n @teammate.destroy\n respond_to do |format|\n format.html { redirect_to pitch_teammates_path(@pitch), notice: \"O Tripulante <strong>#{teammate_name}</strong> foi removido e será notificado.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @midia.destroy\n\n respond_to do |format|\n format.html { redirect_to midias_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @v1_chore = Chore.where(id: params[:id])\n if @v1_chore.destroy\n head(:ok)\n else\n head(:unprocessable_entity)\n end\n end",
"def destroy\n @mob.destroy\n respond_to do |format|\n format.html { redirect_to mobs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @baton = Baton.find(params[:id])\n @baton.destroy\n\n respond_to do |format|\n format.html { redirect_to batons_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n\n @scene.destroy\n\n respond_to do |format|\n format.html { redirect_to action: \"index\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @moonwalk.destroy\n respond_to do |format|\n format.html { redirect_to moonwalks_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @occupant = Occupant.find(params[:id])\n @occupant.destroy\n\n respond_to do |format|\n format.html { redirect_to occupants_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @retroaspecto = Retroaspecto.find(params[:id])\n @retroaspecto.destroy\n\n respond_to do |format|\n format.html { redirect_to retroaspectos_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @plate.destroy\n respond_to do |format|\n format.html { redirect_to client_budget_mobile_url(@client, @budget, @mobile), notice: \"Chapa deletada com sucesso.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mercadorium.destroy\n respond_to do |format|\n format.html { redirect_to mercadoria_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n mountain = Mountain.find params[:id]\n mountain.destroy\n redirect_to (mountains_path)\n end",
"def destroy\n @plasmid_probe.destroy\n respond_to do |format|\n format.html { redirect_to plasmid_probes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @aucrecord.destroy\n respond_to do |format|\n format.html { redirect_to aucrecords_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @nominee.destroy\n respond_to do |format|\n format.html { redirect_to nominees_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ref_sanatorium = Ref::Sanatorium.find(params[:id])\n @ref_sanatorium.destroy\n\n respond_to do |format|\n format.html { redirect_to ref_sanatoria_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @medium_road = MediumRoad.find(params[:id])\n @medium_road.destroy\n\n respond_to do |format|\n format.html { redirect_to medium_roads_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @flat.destroy\n\n respond_to do |format|\n format.html { redirect_to flats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mineral.destroy\n respond_to do |format|\n format.html { redirect_to minerals_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @c_rodinny_stav.destroy\n respond_to do |format|\n format.html { redirect_to c_rodinny_stavs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @proteinname.destroy\n respond_to do |format|\n format.html { redirect_to proteinnames_url, notice: 'Proteinname was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n id = params[:id]\n @physical_rack = PhysicalRack.any_of({_id: id}, {name: id.gsub('-', '.')}).first\n @physical_rack.destroy\n\n respond_to do |format|\n format.html { redirect_to physical_racks_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @json.destroy\n respond_to do |format|\n format.html { redirect_to jsons_url, notice: 'Json was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @json.destroy\n respond_to do |format|\n format.html { redirect_to jsons_url, notice: 'Json was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @miniature.destroy\n respond_to do |format|\n format.html { redirect_to miniatures_url, notice: 'Miniature was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mae.destroy\n respond_to do |format|\n format.html { redirect_to maes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ministerio = Ministerio.find(params[:id])\n @ministerio.destroy\n\n respond_to do |format|\n format.html { redirect_to ministerios_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @maker_master.destroy\n respond_to do |format|\n format.html { redirect_to maker_masters_url, notice: 'Maker master was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @jamaat = Jamaat.find(params[:id])\n @jamaat.destroy\n\n respond_to do |format|\n format.html { redirect_to jamaats_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @mou.destroy\n respond_to do |format|\n format.html { redirect_to mous_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @microposr = Microposr.find(params[:id])\n @microposr.destroy\n\n respond_to do |format|\n format.html { redirect_to microposrs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @stroke.destroy\n respond_to do |format|\n format.html { redirect_to strokes_url, notice: 'Stroke was successfully destroyed.' }\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\r\n @antenne = Antenne.find(params[:id])\r\n @antenne.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to antennes_url }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @three60.destroy\n respond_to do |format|\n format.html { redirect_to edit_admin_good_url(@good, anchor: \"three60\") }\n format.json { head :no_content }\n end\n end",
"def destroy\n @coin_set = CoinSet.find(params[:id])\n @coin_set.destroy\n\n respond_to do |format|\n format.html { redirect_to coin_sets_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @consensu = Consensu.find(params[:id])\n @consensu.destroy\n\n respond_to do |format|\n format.html { redirect_to consensus_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @moose = Moose.find(params[:id])\n @moose.destroy\n\n respond_to do |format|\n format.html { redirect_to mooses_url }\n format.json { head :no_content }\n end\n end"
] |
[
"0.688922",
"0.671094",
"0.6630015",
"0.6618255",
"0.6605488",
"0.65292263",
"0.65272784",
"0.6520473",
"0.64592975",
"0.6458089",
"0.6454195",
"0.64133364",
"0.63949627",
"0.63940597",
"0.63857144",
"0.63722825",
"0.6369918",
"0.63647854",
"0.6321003",
"0.63159484",
"0.6314111",
"0.6307984",
"0.63048863",
"0.63026386",
"0.63021165",
"0.6300214",
"0.62974435",
"0.62968016",
"0.62771255",
"0.62769943",
"0.6275172",
"0.627006",
"0.6262639",
"0.6261394",
"0.6261394",
"0.62578785",
"0.62578785",
"0.62547666",
"0.6251694",
"0.6248704",
"0.624702",
"0.624702",
"0.6246945",
"0.6246037",
"0.6245454",
"0.62439674",
"0.62434006",
"0.6240732",
"0.62403136",
"0.62379414",
"0.62321615",
"0.6231941",
"0.6230545",
"0.6229372",
"0.62245387",
"0.6222439",
"0.6220476",
"0.6219313",
"0.6219246",
"0.6217983",
"0.6215616",
"0.62068367",
"0.62066054",
"0.62063164",
"0.6205258",
"0.6204238",
"0.6203748",
"0.62027955",
"0.6199955",
"0.6195187",
"0.6195043",
"0.6193112",
"0.6189652",
"0.6187851",
"0.61863697",
"0.61851674",
"0.6183517",
"0.6180106",
"0.6177396",
"0.61685497",
"0.6167225",
"0.6166433",
"0.6164336",
"0.61610496",
"0.6158853",
"0.6158853",
"0.6154365",
"0.6152372",
"0.61506075",
"0.61493444",
"0.6148468",
"0.6148447",
"0.6147529",
"0.6146529",
"0.61462235",
"0.6144348",
"0.61442",
"0.6141457",
"0.613918",
"0.61374855"
] |
0.6569586
|
5
|
Use callbacks to share common setup or constraints between actions. Never trust parameters from the scary internet, only allow the white list through.
|
def preparar_mate_params
params.require(:preparar_mate).permit(:título, :descrición)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def action_hook; end",
"def set_required_actions\n # TODO: check what fields change to asign required fields\n end",
"def before_action \n end",
"def before_setup; end",
"def my_action_params\n params.require(:my_action).permit(:name, :url, :active, :provider_id)\n end",
"def define_action_hook; end",
"def before_setup\n # do nothing by default\n end",
"def action_methods; end",
"def action_methods; end",
"def action_methods; end",
"def pre_authorize_cb=(_arg0); end",
"def determine_valid_action\n\n end",
"def action_enable\n end",
"def action_locator_args()\n \n end",
"def actions; end",
"def setup_controller_for_warden; end",
"def add_actions; end",
"def pre_authorize_cb; end",
"def action_params\n params.require(:action).permit(:name, :status, :user_id)\n end",
"def before_dispatch(env); end",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def before_run; end",
"def before_bootstrap; end",
"def before_filter; end",
"def after_view_setup\n end",
"def setup(_context)\n end",
"def rails_controller_callbacks\n # don't verify CSRF token as part of callbacks, Rodauth will do that\n rails_controller_forgery_protection { false }\n\n rails_controller_instance.run_callbacks(:process_action) do\n # turn the setting back to default so that form tags generate CSRF tags\n rails_controller_forgery_protection { rails_controller.allow_forgery_protection }\n\n yield\n end\n end",
"def run_actions; end",
"def setup\n # override and do something appropriate\n end",
"def user_action_params\n Rails.logger.info(\"params: #{params}\")\n params.require(:user_action).permit([:description,:action_type,:action_subtype,:flyer_id,:user_id,:data])\n end",
"def form_setup\n\tend",
"def prepare_for_action\n # #don't save stuff between requests\n NotRelational::RepositoryFactory.instance.clear_session_cache\n @@page_blurbs =Set.new\n @renderer_params={}\n $current_weblab=nil\n @current_user=nil\n @displayed_blurb_names=Set.new\n # if BannedIp.is_banned?(request.remote_ip)\n # head(401)\n # return\n # end\n\n prepare_language_for_action\n prepare_powerbar_for_action\n prepare_rendermode_for_action\n prepare_weblab_for_action\n\n\n self.page_title=\"Rengine\"\n self.no_wrap=false\n return true\n end",
"def define_action_helpers; end",
"def set_caller_params\n end",
"def before_bootstrap\n end",
"def action_run\n end",
"def post_setup\n end",
"def setup\n # override this if needed\n end",
"def set_actions\n actions :all\n end",
"def buy_action_params\n params.require(:buy_action).permit(:title, :description, :link, :priority)\n end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def adjust_params()\n \n if params[:action] == 'index'\n return true;\n end\n \n if params[:action] == 'show'\n return true;\n end\n \n # If its one of the following:\n # POST /entities\n # POST /databases/entities\n if params[:action] == 'create'\n # If the database id is provided as a separate param or as part of the url,\n # Set that in to the database resource if not alredy provided.\n if params[:database_id] or params[:database]\n params[:entity][:database_id] = params[:database_id] || \n params[:database] if !params[:entity][:database_id]\n end\n \n return true;\n end\n \n if params[:action] == 'update'\n return true;\n end\n \n if params[:action] == 'destroy'\n return true;\n end\n \n \n \n # In all cases, the request is not handled by this controller!\n render :text => \"The requested action is \\\"#{params[:action]}\\\" \" + \n \" on controller \\\"#{params[:controller]}\\\" while I am\" + \n \" \\\"#{self.class.name}\\\" and cannot handle your request.\",:status => 400 and return false;\n \n end",
"def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end",
"def on_pre_request( request ); end",
"def before_request\n end",
"def action\n end",
"def setup\n\t\t# Do nothing\n\tend",
"def setup\n\t\t# Do nothing\n\tend",
"def handle_unverified_request\n unless action_name == \"fire_object_search\" || action_name == \"fire_populate_drop_down\" \n super\n end\n end",
"def before_actions(*logic)\n self.before_actions = logic\n end",
"def prepare\n remember_remember_me\n remember_signup_flow_type\n remember_signup_flow_origin_type\n remember_signup_flow_destination\n remember_signup_flow_network\n redirect_to auth_path(params[:network] || 'facebook')\n end",
"def setup\n # this method gets called before *each* omniauth endpoint call, so try to avoid logging when we're returning from\n # oauth'ing\n unless stored_register_redirect\n reg_redirect = params[:r]\n reg_redirect ||= request.referer if params[:ot] && (params[:ot] == \"far\") # facebook auth referral\n store_register_redirect(reg_redirect)\n end\n\n unless stored_auth_redirect\n auth_redirect = params[:r]\n auth_redirect ||= root_path if params[:state] && (params[:state] == 'w')\n store_auth_redirect(auth_redirect)\n end\n\n remember_remember_me\n remember_signup_flow_scope\n remember_signup_flow_type\n remember_signup_flow_origin_type\n remember_signup_flow_destination\n remember_signup_flow_network\n render :text => \"Setup complete.\", :status => 404\n end",
"def call_to_action_params\n params.permit(:description, :button_text, :button_link, :position, :bg_color, :bg_border_size, :bg_border_type, :bg_border_color, :bg_border_radius, :btn_color, :btn_border_size, :btn_border_type, :btn_border_color, :btn_border_radius, :user_id, :brand_id)\n end",
"def on_pre_request( request )\n end",
"def before_dispatch(_env)\n end",
"def action\n end",
"def action_target()\n \n end",
"def action_arguments\n\t\t\t\treturn @action_arguments if @action_arguments\n\t\t\t\t## Get all parameters (arguments) from method\n\t\t\t\t## Than collect and sort parameters into hash\n\t\t\t\t@ctrl.instance_method(@action).parameters\n\t\t\t\t\t.each_with_object(req: [], opt: []) do |param, hash|\n\t\t\t\t\t\t## Only required parameters must be in `:req`\n\t\t\t\t\t\thash[param[0]] << param[1]\n\t\t\t\t\tend\n\t\t\tend",
"def before_perform\n end",
"def action\n super\n end",
"def default_action; end",
"def configure_permitted_parameters\n\t\t[:sign_up, :account_update].each do |action|\n\t\tdevise_parameter_sanitizer.for(action).push(:admin)\n\t\tend\n\tend",
"def after_setup\n # do nothing by default\n end",
"def set_min_up_members_action(opts)\n opts = check_params(opts,[:min_up_actions])\n super(opts)\n end",
"def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend",
"def before_players_ready\r\n end",
"def around_hooks; end",
"def expected_permitted_parameter_names; end",
"def _my_action_action\n {:text => \"Not used\"}\n end",
"def lookup_action; end",
"def additional_action_buttons\n nil\n end",
"def initialize(*args)\n super\n @action = :set\nend",
"def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end",
"def skip_actions; end",
"def before\n end",
"def action args = {}\n\t\tend",
"def action_argument_required?\n !AVAILABLE_ACTIONS.empty?\n end",
"def define_action_helpers?; end",
"def calendar_action_params\n params.require(:calendar_action).permit(:holder, :title, :icon, :description, :responsible, :text_color, :color, :action_type)\n end",
"def initialize(*args)\n super\n @action = :create\nend",
"def initialize(*args)\n super\n @action = :create\nend",
"def initialize(*args)\n super\n @action = :create\nend",
"def initialize(*args)\n super\n @action = :create\nend",
"def initialize(*args)\n super\n @action = :create\nend",
"def initialize(*args)\n super\n @action = :create\nend",
"def initialize(*args)\n super\n @action = :create\nend",
"def initialize(*args)\n super\n @action = :create\nend",
"def before_resolution\n end",
"def process(action, *args)\n insert_action_controller_testing_into_base\n\n if Rails::VERSION::MAJOR <= 4\n # Rails 4 changes the method signature. In rails 3, parameters is the first argument.\n # In Rails 4, it's the second.\n if args.first.is_a?(String)\n parameters = (args[1] ||= {})\n else\n parameters = (args[0] ||= {})\n end\n else\n parameters = (args[0] ||= {})\n end\n\n response.recycle_cached_body!\n\n if Rails::VERSION::MAJOR <= 4\n if _default_version.present? && parameters[:version].blank? && parameters['version'].blank?\n parameters[:version] = _default_version\n end\n else\n if _default_version.present? && parameters[:params][:version].blank?\n parameters[:params][:version] = _default_version\n end\n end\n\n super action, *args\n end",
"def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end",
"def setup \n @user = current_user\n end",
"def initialize_before_opts\n end",
"def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end",
"def setup(&block)\n before(:each, &block)\n end",
"def custom_prepare_ransack_params; end",
"def min_up_members_action\n super\n end"
] |
[
"0.60899144",
"0.6081489",
"0.6010213",
"0.5874203",
"0.579901",
"0.57524973",
"0.5592823",
"0.5515582",
"0.5515582",
"0.5515582",
"0.5406058",
"0.54022133",
"0.53855455",
"0.53680074",
"0.53510565",
"0.5347828",
"0.5346682",
"0.53387135",
"0.53360146",
"0.5315981",
"0.53034574",
"0.53034574",
"0.53017515",
"0.5297669",
"0.52935475",
"0.5278745",
"0.5239784",
"0.52372044",
"0.5226603",
"0.5224492",
"0.5217911",
"0.5215967",
"0.5210968",
"0.5202708",
"0.5200634",
"0.5199772",
"0.5194795",
"0.5188428",
"0.51797074",
"0.5178206",
"0.51737976",
"0.5172623",
"0.5172623",
"0.5172623",
"0.5172623",
"0.5172623",
"0.51711744",
"0.5169581",
"0.5167828",
"0.5167213",
"0.51564986",
"0.5132579",
"0.5132579",
"0.5113505",
"0.51128435",
"0.5109751",
"0.51058906",
"0.50986004",
"0.5095886",
"0.50815624",
"0.5063885",
"0.5044318",
"0.5043572",
"0.50291073",
"0.50258833",
"0.5004112",
"0.4994644",
"0.4989111",
"0.49887118",
"0.49836212",
"0.49736342",
"0.49693292",
"0.49659377",
"0.49631307",
"0.49619862",
"0.4959977",
"0.49587217",
"0.49567538",
"0.49531043",
"0.4952907",
"0.49525884",
"0.49510866",
"0.4947334",
"0.49446",
"0.49426818",
"0.49426818",
"0.49426818",
"0.49426818",
"0.49426818",
"0.49426818",
"0.49426818",
"0.49426818",
"0.49399993",
"0.49328408",
"0.49217525",
"0.49187404",
"0.49186587",
"0.49127394",
"0.49121195",
"0.4906975",
"0.489727"
] |
0.0
|
-1
|
Before filters Confirms an admin user.
|
def admin_user
redirect_to(root_url) unless current_user.admin?
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def authorize_admin\n return if current_customer.admin?\n redirect_to root_path, alert: 'Admins only!' unless current_customer and current_customer.admin?\n end",
"def admin_user\n redirect_to(root_url) and flash[:danger] = \"Only admins can do that!\" unless current_user.admin?\n\n end",
"def verify_admin\n if !current_user.present? || current_user.email != I18n.t('general.admin_email')\n redirect_to concerts_path\n flash[:notice] = I18n.t('general.log_as_admin')\n end\n end",
"def admin_user\n unless current_user && current_user.admin?\n redirect_to login_url, notice: \"admin can only do this action.\" \n end\n end",
"def admin_user\n unless @is_admin\n flash[:danger] = \"Must be admin to modify recipes\"\n redirect_to(recipes_url) \n end\n end",
"def admin_required\n if current_user && current_user.admin\n return\n end\n redirect_to \"/login\", notice: 'Logga in som administratör.'\n end",
"def authorize_admin\n return unless !current_admin\n redirect_to root_path, alert: 'Admins only!'\n end",
"def admin_user\n unless this_is_admin?(current_user)\n flash[:danger] = \"You don't have the rights for this action.\"\n redirect_to(root_url)\n end\n end",
"def admin_user\n unless this_is_admin?(current_user)\n flash[:danger] = \"You don't have the rights for this action.\"\n redirect_to(root_url)\n end\n end",
"def authorize_admin\n return unless !current_user.admin?\n redirect_to root_path, alert: 'Admins only!'\n end",
"def authorize_admin\n return unless !current_user.admin?\n redirect_to root_path, alert: 'Admins only!'\n end",
"def admin_user\n unless current_user.is_admin?\n flash[:danger] = \"Keine Berechtigung.\"\n redirect_to(root_url)\n end\n end",
"def admin_user\n unless current_user.is_admin?\n flash[:danger] = \"Keine Berechtigung.\"\n redirect_to(root_url)\n end\n end",
"def authorizeAdmin\n redirect_to '/adminlogin' unless admin_user\n end",
"def admin_authorize\n \tunless User.find(session[:user_id]).user_type == \"admin\"\n \t\tsession[:original_uri] = nil\n\t\t flash[:warning] = \"You are not authorized to view this page!\"\n\t\t redirect_to(root_path)\n \tend\n end",
"def admin_user\n unless @is_admin\n flash[:danger] = \"Must be admin to modify recipes\"\n redirect_to(recipes_url) \n end\n end",
"def admin_user \n if (!current_user.lunches_admin?) \n flash[:alert] = 'You not allowed to edit menu.'\n \n redirect_to(root_url)\n end\n end",
"def authorize_admin\n return unless current_user.admin?\n redirect_to root_path, alert: 'Admins only!'\n end",
"def ensure_admin\n unless current_user && current_user.admin\n flash[:notice] = \"You are not authorized to perform this action\"\n redirect_back(fallback_location: root_path)\n end\n\n end",
"def allow_if_admin\n unless is_admin?\n flash[:danger] = \"Administration permissions needed to access to this page\"\n redirect_to new_user_session_path\n end\n end",
"def authorize_admin!\n unless admin?\n flash[:alert] = 'Unauthorized access'\n redirect_to home_path\n false\n end\n end",
"def admin_user\n\t\tunless admin? \n\t\t\tflash[:danger] = \"Only administrators have access to this page\"\n\t\t\tredirect_back_or(root_url) \n\t\tend\n\tend",
"def authorize_admin\n redirect_to root_path, flash: {:error => \"User don't have admin privileges\"} unless isAdmin?\n end",
"def authorize_admin\n redirect_to root_path, notice: \"You don't have access to admin pages.\" if !current_user.admin?\n end",
"def restrict_to_admin\n unless is_admin\n flash[:danger] = \"You are not an administrator.\"\n redirect_to root_url\n end\n end",
"def authenticate_admin!\n unless current_user.admin?\n flash[:danger] = \"Sorry, you don't have premissions for this action.\"\n redirect_to root_path\n else\n true\n end\n end",
"def admin_user\n unless ( logged_in? && current_user.admin? )\n store_location\n flash[:danger] = \"У Вас недостаточно прав для выполнения этой операции.\"\n redirect_to root_url\n end \n # redirect_to(root_url) unless current_user.admin?\n end",
"def admin_user!\n unless signed_in? and current_user.admin?\n\t flash[:notice]=\"Por favor inicie sesión como administrador\".encode('UTF-8')\n\t redirect_back(fallback_location: root_path) \n end\n end",
"def admin_user\n if(!current_user.admin?)\n flash[:danger] = \"Access Denied. Admin required\"\n redirect_to root_url\n end\n end",
"def admin_user\n unless logged_in? && current_user.is_admin?\n flash[:danger] = \"Must be admin to modify ingredients\"\n redirect_to(ingredients_url) \n end\n end",
"def admin_user\n if user_signed_in? && current_user.adminrole?\n flash.now[:success] = \"Admin Access Granted\"\n else\n redirect_to root_path\n end\n end",
"def admin_user\n redirect_to(root_path) unless (current_user != nil && current_user.admin == true)\n end",
"def authorize_admin!\n\t\tredirect_to new_admin_session_path unless current_admin\n\tend",
"def admin_user\n redirect_to root_url, notice: \"You do not have permission to view or edit this information.\" unless current_user.admin?\n end",
"def authenticate_admin_user!\n unless current_user && current_user.admin?\n redirect_to login_path, alert: t(:please_log_in_as_admin)\n end\n end",
"def admin_user\n #redirect_to(root_url) unless\n current_user.admin?\n end",
"def admin_user\n #redirect_to(root_url) unless\n current_user.admin?\n end",
"def admin_user\n redirect_to(admin_admins_path) unless current_user.admin?\n end",
"def adminprotected!\n if authorized? == true and isuseradmin? == true\n return\n else redirect '/denied'\n end\n end",
"def admin_user\n if (!current_user || current_user.username != 'admin')\n redirect_to(root_url)\n end\n end",
"def admin_authorize\n unless admin?\n unauthorized_access\n end\n end",
"def admin_user\n\t\t\tflash_text = \"Administrative privilege required to perform this action.\"\n\t\t\tflash[:danger] = flash_text unless current_user.admin?\n\t\t\tredirect_to(root_url) unless current_user.admin?\n\t\tend",
"def admin_user\n redirect_to(root_url) unless user_signed_in? && current_user.admin?\n end",
"def admin_user\n redirect_to(root_url) unless user_signed_in? && current_user.admin?\n end",
"def admin_user\n redirect_to(root_url) unless !current_user?(@user) && current_user.admin?\n end",
"def admin_user\n\t\t\tredirect_to(root_url) unless current_user.admin?\n\t\tend",
"def admin_user\n\t\t\tredirect_to(root_url) unless current_user.admin?\n\t\tend",
"def confirm_admin\n redirect_to root_path unless current_user.admin?\n end",
"def admin_user\n redirect_to(root_path) unless current_user.try(:admin?) || current_user?(@user)\n end",
"def req_admin\n unless curr_user.admin\n flash[:danger] = \"You must be admin to go there!\"\n redirect_to root_url\n end\n end",
"def admin_user\n\t\t\tredirect_to(root_url) unless current_user.admin?\n\t end",
"def check_admin_status\n if current_user.nil? || !current_user.admin?\n flash[:alert] = \"Access denied. Please login as an admin user\"\n redirect_to root_url\n end\n end",
"def check_admin_status\n if current_user.nil? || !current_user.admin?\n flash[:alert] = \"Access denied. Please login as an admin user\"\n redirect_to root_url\n end\n end",
"def admin_user\n unless current_user.admin?\n flash[:danger] = \"You do not have the permission to do that.\"\n redirect_to home_path\n end\n end",
"def admin_user\n redirect_to(current_user) unless current_user.admin?\n end",
"def admin_only\n if !Volt.current_user.admin\n redirect_to '/login'\n end\n end",
"def not_change_my_admin\n #今回、「一般ユーザーとする」として登録しようとしている場合\n if admin_status==0\n # if User.where.not(id: 1).size == 0\n if id == current_user_id\n errors.add(\" \",I18n.t(\"activerecord.errors.messages.restrict_change_admin\"))\n # errors.add(:cd, I18n.t(\"activerecord.errors.messages.restrict_dependent_destroy.myself\"))\n end\n end\n end",
"def be_admin\n if current_user.switch_to(\"admin\")\n flash[:notice] = \"You have now an 'admin' role\"\n else\n flash[:error] = \"You are not authorized to have a 'admin' role\"\n end\n redirect_to( request.env[\"HTTP_REFERER\"])\n end",
"def ensure_admin_user!\n redirect_to(news_path, :alert => \"You may not perform this action on News!\") and return unless user_signed_in? && current_user.admin?\n end",
"def admin_user\n unless admin_user?\n redirect_to login_url\n end\n end",
"def admin_user\n\t\tredirect_to(root_url) unless current_user.admin?\n\tend",
"def admin_user\n\t\tredirect_to(root_url) unless current_user.admin?\n\tend",
"def admin_user\n\t\tredirect_to(root_url) unless current_user.admin?\n\tend",
"def admin_user\n if !current_user.admin\n flash[:danger] = 'Please note that only administrators can create categories'\n end\n\n end",
"def authorize_admin!\n redirect_to login_path unless current_user\n end",
"def admin_user\n render_forbidden unless current_user.admin?\n end",
"def admin_actions\n unless @current_admin.is_super_admin\n flash[:error]=\"You are not authorized to navigate to this page \"\n redirect_to admin_index_path\n return\n end\n end",
"def admin_user\n if logged_in?\n redirect_to root_url unless current_user.admin?\n elsif\n #flash[:failure] = \"Invalid Request\"\n redirect_to(root_url)\n end\n end",
"def admin_user\n if logged_in?\n redirect_to root_url unless current_user.admin?\n elsif\n #flash[:failure] = \"Invalid Request\"\n redirect_to(root_url)\n end\n end",
"def admin_check\n render_401 && return unless current_user\n render_403 && return unless current_user.admin?\n end",
"def admin_user\n\t\tredirect_to(root_path) unless current_user.admin?\n\tend",
"def admin_user\n redirect_to(root_url) unless current_user && current_user.admin?\n end",
"def admin_user\n\t unless current_user.admin?\n flash[:danger] = \"Log in as Admin.\"\n redirect_to(root_url)\n\t end \n\t end",
"def check_if_admin\n if !current_user.admin?\n flash[:alert] = 'Sorry, only admins allowed!'\n redirect_to root_path\n end\n end",
"def confirm_admin\n \tunless session[:admin]\n \t\tflash[:notice] = \"You are not an admin.\"\n \t\tredirect_to(user_path( :id => session[:user_id]))\n \tend\n end",
"def require_admin\n if logged_in? and !current_user\n flash[:danger] = \"Only admin users can perform that action.\"\n redirect_to root_path\n end\n end",
"def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end",
"def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end",
"def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end",
"def admin_user\n redirect_to(root_url) unless current_user.is_admin?\n end"
] |
[
"0.713229",
"0.710992",
"0.7098981",
"0.70898515",
"0.7083098",
"0.7023689",
"0.7018312",
"0.701766",
"0.701766",
"0.699869",
"0.699869",
"0.69962054",
"0.69962054",
"0.6994126",
"0.69935423",
"0.69934475",
"0.6989941",
"0.6962073",
"0.69528276",
"0.6946117",
"0.6945809",
"0.6935861",
"0.6934314",
"0.69273746",
"0.6920709",
"0.6917071",
"0.6907417",
"0.68904585",
"0.68800235",
"0.6864859",
"0.68625605",
"0.6862449",
"0.6861702",
"0.6860129",
"0.6858704",
"0.68581986",
"0.68581986",
"0.68540466",
"0.6841894",
"0.6837878",
"0.6836989",
"0.6815724",
"0.68130136",
"0.68130136",
"0.6812356",
"0.6810113",
"0.6810113",
"0.6808631",
"0.6807586",
"0.6801706",
"0.6799412",
"0.6795491",
"0.6795491",
"0.6790674",
"0.67878115",
"0.6781805",
"0.6779824",
"0.6776081",
"0.67685986",
"0.6767616",
"0.6765659",
"0.6765659",
"0.6765659",
"0.6762452",
"0.67413497",
"0.6736911",
"0.67368567",
"0.6735613",
"0.6735613",
"0.67295027",
"0.6725976",
"0.6719158",
"0.6717072",
"0.6716487",
"0.6716001",
"0.6715425",
"0.6712535",
"0.6712535",
"0.6712535",
"0.6712535"
] |
0.0
|
-1
|
Retrieve all the tag guids for a provided service entry and tag group
|
def tag_guids_for_tag_group(service_entry, tag_group)
guids = service_entry['TagGuids']
return [] if guids.blank?
# The first element of the tag strings ARE the tag group. We'll group
# by that value and return the requested group. This saves a fair amount
# of logic from having to be copy and pasted sifting out only the guids we
# need for a particular operation
Array.wrap(guids).group_by { |guid| service_tag_parts(guid).first }[tag_group] || []
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def tags\n get.tagGuids\n end",
"def get_tags() tag_ids.inject([]) { |l, tag_id| l << get_tag_from_id(tag_id) } end",
"def add_tag_return_IDs(tag)\n # Split and strip the tags\n tags = tag.split(\",\").collect{|x| x.strip}\n i = 0\n iDs = []\n while i < tags.count do\n # Check if tag exist, if not - add it\n if Teg.find_by_teg(tags[i]).nil?\n\tTeg.new(:teg => tags[i]).save\n end\n # Insert into array the id of the tag\n iDs << Teg.find_by_teg(tags[i]).id\n i +=1\n end\n # return the IDs\n return iDs\n end",
"def tags\n entries = Entry.all\n # Create a list of all the tags, as a String\n tags_list = String.new\n entries.each do |entry|\n tags_list << entry.tags + \" \"\n end\n # Convert the String to a global array, removing the duplicate elements\n $tags_array = tags_list.split.uniq\n end",
"def get_tags\n\t\t\ttaglist = read_command_output( 'hg', 'tags' )\n\t\t\treturn taglist.split( /\\n/ ).collect {|tag| tag[/^\\S+/] }\n\t\tend",
"def tag_service(dialogs_tags_hash)\n log_and_update_message(:info, \"Processing tag_service...\", true)\n\n # Look for tags with a sequence_id of 0 to tag the service\n dialogs_tags_hash.fetch(0, {}).each do |key, value|\n log_and_update_message(:info, \"Processing tag: #{key.inspect} value: #{value.inspect}\")\n tag_category = key.downcase\n Array.wrap(value).each do |tag_entry|\n process_tag(tag_category, tag_entry.downcase)\n end\n end\n log_and_update_message(:info, \"Processing tag_service...Complete\", true)\nend",
"def get_tag_list\n # body = {\n # cmd: \"get_tag_list\"\n # }\n\n end",
"def collections_from_service_entry_tags(service_entry)\n concept_ids = concept_ids_from_service_entry_tags(service_entry)\n\n return [] if concept_ids.blank?\n\n response = cmr_client.get_collections_by_post({ concept_id: concept_ids, page_size: concept_ids.size }, token)\n if response.success?\n response.body.fetch('items', [])\n else\n []\n end\n end",
"def find_by_group(group)\n service_list.select { |_, metadata| metadata[:groups].include?(group) }.keys\n end",
"def tag_groups\n build_tag_groups_array RubyRedtail::Query.run(\"settings/taggroups\", @api_hash, \"GET\")\n end",
"def tags\n @tags ||= tag_class.in_challenge(collection).group(:id)\n end",
"def get_guids(record)\n arr = []\n record.each do |r|\n arr.push(r[\"guid\"])\n end\n return arr\n end",
"def tags(params = {})\n @tags ||= MailchimpAPI::Tag.find(:all, params: { member_id: id }.deep_merge(prefix_options).deep_merge(params))\n end",
"def tags\n @group.tags\n end",
"def tags\n object.tags.map {|tag| tag.id}\n end",
"def docker_tag_ids(id)\n criteria = {:type_ids => [Runcible::Extensions::DockerTag.content_type],\n :fields => {:unit => [], :association => ['unit_id']}}\n\n unit_search(id, criteria).map { |i| i['unit_id'] }\n end",
"def getTags()\n dataHash = @item_json['data']\n tagSet = Set.new\n\n dataHash.each do |itemId, item|\n item['tags'].each do |tag|\n tagSet.add(tag)\n end\n end\n\n return tagSet.to_a\n end",
"def get_tags(tenant_id, entity_type_id,entity_id)\n return @instance.get_tags(tenant_id, entity_type_id,entity_id)\n end",
"def get_tags_for_select() tag_ids.inject([]) { |l, tag_id| l << [get_tag_from_id(tag_id).label, tag_id] } end",
"def getEntityList_by_group_id( group_id, per_page, page)\n params = Hash.new\n params['group_id'] = group_id\n params['per_page'] = per_page\n params['page'] = page\n return doCurl(\"get\",\"/entity/list_by_group_id\",params)\n end",
"def tags\n libraries.collect(&:tag_id)\n end",
"def return_all_tags\n @tags.uniq.each { |tag| puts tag }\n end",
"def get_tag_list\n args = receive_should_validate?\n get('redtube.Tags.getTagList', {}, [], args[:should_validate])\n end",
"def tags(package)\n importer = package.importer\n all_tags = importer.run_git_bare(package, \"tag\")\n all_tags.find_all do |tag_name|\n end\n end",
"def _get_tags(tag)\n tags = if tag.attr['tags'] && !tag.attr['tags'].blank?\n Tag.from_list(tag.attr['tags'], false) # false parameter -> not to create missing tags\n elsif tag.locals.page.respond_to?(:requested_tags)\n tag.locals.page.requested_tags\n elsif tag.locals.page\n tag.locals.page.attached_tags.visible\n else\n []\n end\n tag.locals.tags = tags.uniq.compact\n end",
"def tags\n request_libraries.collect(&:tag_id)\n end",
"def getToolsSyndicateInfogroup( entity_id, destructive)\n params = Hash.new\n params['entity_id'] = entity_id\n params['destructive'] = destructive\n return doCurl(\"get\",\"/tools/syndicate/infogroup\",params)\n end",
"def tags tag_name\n find_elements :tag_name, tag_name\n end",
"def host_tags(host_id, source=nil, by_source=false)\n @tag_svc.get(host_id, source, by_source)\n end",
"def group_ids(table)\n @group_ids ||= {}\n @group_ids[table] ||=\n table.to_s.classify.constantize.\n where(\"#{type_tag}_id\" => id).\n order(user_group_id: :asc).distinct.\n pluck(:user_group_id)\n end",
"def service_tagging(service, dialogs_options_hash)\n log(:info, \"Processing service_tagging...\", true)\n # Setup regular expression for service dialog tags\n tags_regex = /^dialog_tag_0_(.*)/i\n\n # Look for tags with a sequence_id of 0 to tag the service\n dialogs_options_hash[0].each do |k, v|\n log(:info, \"Processing Tag Key:<#{k.inspect}> Value:<#{v.inspect}>\")\n next if v.blank?\n if tags_regex =~ k\n tag_category = $1.downcase\n tag_value = v.downcase\n process_tags( tag_category, true, tag_value )\n log(:info, \"Adding Tag: {#{k.inspect} => #{v.inspect}} to Service:<#{service.name}>\")\n service.tag_assign(\"#{tag_category}/#{tag_value}\")\n end # if tags_regex\n end # dialogs_options_hash[0].each\nend",
"def service_ids\n services.collect { |s| s[\"id\"] }\n end",
"def get_server_tags \n tags_list = `rs_tag --list`\n # remove unnecessary \\n from the tags list \n tags_list.gsub(/\\n/, \" \").split(\",\")\n end",
"def tag(tags = self.tags)\n tags.to_s.split(/\\s*,\\s*/).uniq\n end",
"def all_tags context = :tags\n ActsAsTaggableOn::Tagging.where(context: context).select(:tag_id).distinct.includes(:tag).map(&:tag)\n end",
"def tags(id)\n wf_event_id?(id)\n api.get([id, 'tag'].uri_concat)\n end",
"def getGUIDURSIWBIC(studyID)\r\n\ttags = $piggybank.list_subjects(studyID)\r\n\ttags.each_with_index do |subj, index|\r\n\t\ttags[index] = [$piggybank.get_tags(subj)[\"RDoC GUID\"], subj.ursi, \r\n\t\t\t\t\t\t$piggybank.get_tags(subj)[\"WBIC\"]]\r\n\tend\r\n\t\r\n\treturn tags\r\nend",
"def tag\n tags.to_s.split(/\\s*,\\s*/).uniq\n end",
"def tags(client)\n client.get(\"#{PATH}/tags\")\n end",
"def tags\n @tags ||= begin\n resp = @client.access_token.get('/reader/api/0/tag/list?output=json')\n raise \"unable to retrieve the list of tags for user \\\"#{user_id}\\\": #{resp.inspect}\" unless resp.code_type == Net::HTTPOK\n JSON.parse(resp.body)['tags'].collect do |hash|\n Google::Reader::Tag.new(hash.merge({:client => @client}))\n end\n end\n end",
"def tags\n\t\tresponse = self.server.run_with_json_template( :tags )\n\t\treturn response.flatten.map {|tag| Hglib::Repo::Tag.new(self, **tag) }\n\tend",
"def tags(force_reload = false)\n unless force_reload\n return @tag_list unless @tag_list.nil? \n end\n return nil unless self.id\n \n @tag_list = GroupTagList.new({:group_id => self.id})\n return @tag_list\n end",
"def linked_tags\n taggings.map {|tagging| tagging.tag.value}\n end",
"def my_tag_list\n self.taggings.order('id ASC').map(&:tag).map(&:name)\n end",
"def tags() ; info[:tags] ; end",
"def tags() ; info[:tags] ; end",
"def getDeviceAliases()\n result = Array.new\n qs = <<END_QS1\nSELECT DISTINCT tag\nFROM `device_tags` \nEND_QS1\n begin\n @my.query(qs).each() { | t | \n result.push(t) \n }\n rescue MysqlError => e\n err_str = \"Inventory - Could not execute query in getDeviceAliases\"\n p err_str\n MObject.debug err_str\n end\n MObject.debug(\"Got result\")\n result\n end",
"def service_tagging(service, dialogs_tags_hash)\n log(:info, \"Processing service_tagging...\", true)\n unless dialogs_tags_hash[0].nil?\n dialogs_tags_hash[0].each do |k, v|\n log(:info, \"Adding Tag: {#{k.inspect} => #{v.inspect}} to Service:<#{service.name}>\")\n process_tags( k, true, v )\n service.tag_assign(\"#{k}/#{v}\")\n end\n end\n log(:info, \"Processing service_tagging...Complete\", true)\nend",
"def list\n tags = api_client.tags.by_resource(resource_hrefs:\n [api_client.get_instance.href]).first.tags\n ::MachineTag::Set.new(tags.map { |tag| tag['name'] })\n end",
"def get_asset_group_tags_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: AssetGroupApi.get_asset_group_tags ...'\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling AssetGroupApi.get_asset_group_tags\"\n end\n # resource path\n local_var_path = '/api/3/asset_groups/{id}/tags'.sub('{' + 'id' + '}', id.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json;charset=UTF-8'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = []\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'ReferencesWithTagIDLink')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: AssetGroupApi#get_asset_group_tags\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def list_tags 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_tags_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::ArtifactRegistry::V1beta2::ListTagsResponse.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def scan_list_uids\r\n\t\tpost= { \"token\" => @token } \r\n\t\tdocxml=nessus_request('scan/list', post)\r\n\t\tuuids=Array.new\r\n\t\tdocxml.root.elements['contents'].elements['scans'].elements['scanList'].each_element('//scan') {|scan| uuids.push(scan.elements['uuid'].text) }\r\n\t\treturn uuids\r\n\tend",
"def get_all_tags\n print \"Fetching tags...\\r\" if @options[:verbose]\n\n check_github_response { github_fetch_tags }\n end",
"def fetch_tags\n\t\tbegin\n\t\t\ticons = Icon.select(\"DISTINCT tag\").where(\"tag <> ''\").order('tag')\n\t\t\tresult = []\n\t\n\t\t\ticons.each do |icon|\n\t\t\t\tresult.push(icon.tag)\n\t\t\tend\n\t\n\t\t\toutput result\n\t\trescue Exception => exception\n\t\t\terror exception.message, :not_found\n\t\tend\n\tend",
"def _tagging\n t_tagging[:tag_id].in(self.tags) unless self.tags.length == 0\n end",
"def do_query(query_tags, options = {})\n query_tags = [query_tags] if query_tags.is_a?(String)\n Chef::Log.info \"Tagged query_tags: #{query_tags}\"\n match_all = options.fetch(:match_all, false)\n resources = api_client.tags.by_tag(resource_type: 'instances', tags: query_tags, match_all: match_all)\n Chef::Log.info \"Tagged resources: #{resources}\"\n\n tags_hash = {}\n if resources.first\n links = resources.first.links\n if links\n links.each do |link|\n Chef::Log.info \"Tagged Resource Cloud:#{link['href'].split('/')[0..3].join('/')}\"\n next unless api_client.get_instance.show.cloud.href == link['href'].split('/')[0..3].join('/')\n next unless api_client.resource(link['href']).state == 'operational'\n resource_tags = api_client.tags.by_resource(resource_hrefs: [link['href']]) # .first.tags\n tags_hash[link['href']] = {\n 'tags' => resource_tags.first.tags.map { |tag| tag['name'] },\n }\n end\n end\n end\n tags_set_array = []\n tags_hash.values.each do |value|\n tags_set_array << ::MachineTag::Set.new(value['tags'])\n end\n tags_set_array\n end",
"def group_ids\n @attributes[:group_ids]\n end",
"def group_ids\n @attributes[:group_ids]\n end",
"def group_ids\n @attributes[:group_ids]\n end",
"def retrieve_tags\n # noop\n end",
"def tag_names #helper method\n # gets tag names in an array\n self.tags.map { |tag| tag.name }\n end",
"def tag_list(list = [])\n taggings = ActsAsTaggableOn::Tagging.find_all_by_taggable_id(id)\n if taggings\n taggings.each do |tagging|\n next unless tagging.context == 'interest'\n list << ActsAsTaggableOn::Tag.find(tagging.tag_id).name\n end\n end\n # return empty default or tags retrieved via ActsAsTaggableOn\n list\n end",
"def github_fetch_tags\n tags = []\n page_i = 0\n count_pages = calculate_pages(@client, \"tags\", {})\n\n iterate_pages(@client, \"tags\") do |new_tags|\n page_i += PER_PAGE_NUMBER\n print_in_same_line(\"Fetching tags... #{page_i}/#{count_pages * PER_PAGE_NUMBER}\")\n tags.concat(new_tags)\n end\n print_empty_line\n\n if tags.count == 0\n Helper.log.warn \"Warning: Can't find any tags in repo. \\\nMake sure, that you push tags to remote repo via 'git push --tags'\"\n else\n Helper.log.info \"Found #{tags.count} tags\"\n end\n # tags are a Sawyer::Resource. Convert to hash\n tags.map { |resource| stringify_keys_deep(resource.to_hash) }\n end",
"def get_tags(artist_id, options={})\n api_response = @api_client.make_api_request(:GET, \"artist/tags\", {:artistId => artist_id}, options)\n @api_client.tag_digestor.list_from_xml(api_response.content.tags)\n end",
"def get_tags_for_context(context)\n ActsAsTaggableOn::Tag.includes(:taggings)\n .where(\"taggings.context = '#{context}'\")\n .select(\"DISTINCT tags.*\")\n .map(&:name)\n end",
"def get_tag(upload_id)\n \ttag =[]\n uploaded_media_id = UploadedMedium.find(upload_id)\n tag_ids = TagUploadedMedium.joins(:tag).where(\"uploaded_media_id = ?\",uploaded_media_id).map{|tag_data| \"#{tag_data.tag_id}\"}\n tag_ids.each do |tag_id|\n tag <<\tTag.find(tag_id).tag_name\n end\n tag.join(\",\")\n end",
"def report_list_uids\r\n post = { \"token\" => @token }\r\n docxml = nessus_request('report/list', post)\r\n uuids = Array.new\r\n docxml.root.elements['contents'].elements['reports'].each_element('//report') do |report| \r\n uuids.push(report.elements['name'].text)\r\n end\r\n return uuids\r\n end",
"def get_tags\n\ttags = Set.new\n\t@site.articles.each do |post|\n\t\tif(post[:tags].nil?) \n\t\t\tpost[:tags] = Array.new\n\t\t\tpost[:tags] << \"(none)\"\n\t\t\ttags << \"(none)\"\n\t\telse\n\t\t\tpost[:tags].each do |tag|\n\t\t\t\ttags << tag\n\t\t\tend\n\t\tend\n\tend\n\ttags.to_a\nend",
"def group_ids\n groups.map{|g| g.id}\n end",
"def tags(options={})\n do_query(nil, @agent.identity, options) do |result|\n if result.kind_of?(Hash)\n yield(result.size == 1 ? result.values.first['tags'] : [])\n else\n yield result\n end\n end\n end",
"def service_tagging(service, dialogs_tags_hash)\n log(:info, \"Processing service_tagging...\", true)\n unless dialogs_tags_hash[0].nil?\n dialogs_tags_hash[0].each do |k,v|\n log(:info, \"Adding Tag: {#{k.inspect} => #{v.inspect}} to Service: #{service.name}\")\n process_tags( k, true, v )\n service.tag_assign(\"#{k}/#{v}\")\n end\n end\n log(:info, \"Processing service_tagging...Complete\", true)\n end",
"def get_tag 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_get_tag_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::ArtifactRegistry::V1beta2::Tag.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def tags\n get('tags')\n end",
"def taggable_document_collection_groups_container\n Rails.cache.fetch(taggable_document_collection_groups_cache_digest, expires_in: 1.day) do\n DocumentCollection.latest_edition.alphabetical.includes(:groups).flat_map do |collection|\n collection.groups.map { |group| [\"#{collection.title} (#{group.heading})\", group.id] }\n end\n end\n end",
"def uids\n return [] unless valid?\n\n queries.search(name_query).merged_uids\n end",
"def tags()\n\t\t\treturn @metadata.attributes[:tags].to_a\n\t\tend",
"def extract_ids\n # no-op\n end",
"def index\n @tags, @tags_attached = TagService.list(current_user.id)\n end",
"def tag_names\n self.entity_tags.map(&:tag).map(&:name)\n end",
"def get_tags\n @logger.info(\"#{__method__}: Getting tags from git\")\n output = `cd #{@conf.clone_path} && git tag`\n tags = output.split(\"\\n\")\n tags.each do |t|\n @logger.debug(\"#{__method__}: #{t}\")\n end\n tags\n end",
"def get_hostids_by_group(name)\n hostids = []\n hosts = get_hosts_by_group(name)\n if hosts == nil\n return nil\n else\n hosts.each { |host| hostids.push(host[\"hostid\"].to_i) }\n return hostids\n end\n end",
"def tags_from(options={})\n get(get_tags_uri, { :site_id => options[:blog]})\n end",
"def find_all_by_all_service_tags(tags)\n return [] if tags.empty?\n\n locator.find_all_by_tags(tags).map { |service| service['credentials'] }\n end",
"def get\n\t\tformat = getFormat(params)\n\n\t\tquery_text =\"\nselect * from tags \nwhere tag_normalized like '#{cleanTag(params[:tag])}%'\"\n\n\t\tresults = Tag.find_by_sql(query_text)\n\n\t\ttags = results.inject([]) {|res, tag|\n\t\t\tres << \n\t\t\t\t{\n\t\t\t\t\t:tag_value => tag.tag_value, \n\t\t\t\t\t:tag_normalized => tag.tag_normalized, \n\t\t\t\t\t:id => tag.id}\n\t\t\t\t}\n\n\t\trender format.to_sym => tags\n\tend",
"def tags_from_reference(reference)\n response = client.get(\"2.0/tracks/reference/#{reference}/tags\")\n\n response.map { |tag| Struct::Tag.new(tag) }\n end",
"def get_groups\n `id -nG #{name}`.split(' ')\n end",
"def group_ids\n groups.pluck(:id)\n end",
"def all\n response= handle_errors{ self.class.get('/get')}\n response[\"tags\"][\"tag\"].collect do |tag| \n t= Rubycious::Tag.new(tag)\n end\n end",
"def groups\n group_ids.split(',').inject(Array.new) do |arr,gid|\n arr << Ecore::Group.where(:id => gid).first\n end\n end",
"def deli_tags(uri, id)\n begin\n md5 = Digest::MD5.hexdigest(uri)\n target = \"http://badges.del.icio.us/feeds/json/url/data?hash=#{md5}\"\n json = open(target).read\n deli = JSON.load(json)[0]\n tags = \"\"\n if deli['top_tags'].class == Hash then\n all_tags = deli['top_tags'].sort_by {|k,v| v}.reverse.map{|i|i[0]}\n if all_tags.size > 8 then\n all_tags = all_tags.first(8) << '...'\n end\n tags = '(' << all_tags.join(', ') << ')'\n end\n if deli['total_posts'].to_i > 0 then\n response = \"#{id}: (deli) #{deli['total_posts']} links, tagged #{tags}\"\n $q_meta.enq response\n end\n rescue\n puts \"problem fetching deli for #{uri}\"\n end\nend",
"def tag_list\n data[:tag_list]\n end",
"def tag_list\n data[:tag_list]\n end",
"def get_tags()\n db = connect_to_database()\n return db.execute(\"SELECT * FROM tags\")\n end",
"def gettag()\n omnifocus.tags.get.each do |tagg|\n\t tagg.tags.get.each do |t|\n\t\t\t if t.name.get == \"Today\" \n\t\t\t\t return t\n\t\t\t end\n\t\t end \n\n end\n\n end",
"def qihu_get_all(campaign_se_id)\n adgroups = Array.new\n group_service = Qihu::DianJing::Client.new(get_auth).group\n response = group_service.getIdListByCampaignId(campaignId: campaign_se_id)\n id_list = JSON.parse(response.body)[\"groupIdList\"]\n id_list.each do |id|\n adgroup = AgaApiFactory::Model::Adgroup.new\n adgroup.se_id = id.to_i\n adgroup.adgroup_name = id \n adgroup.price = 0\n adgroup.negative_words = \"\"\n adgroup.exact_negative_words = \"\"\n adgroup.status = 0\n adgroup.se_status = adgroup.status\n adgroups << adgroup\n end\n adgroups\n end",
"def tags\n @result.keys\n end",
"def get_tags\n [['pxb', 'PXB'], ['ind', 'Individuals'], ['bus', 'Businesses'], ['grp', 'Peer Groups']]\n end",
"def tag_list\n tags.map(&:name).join(\", \")\n end",
"def get_tag_link_list\r\n story_tag_links = StoryTagLink.find :all, \r\n :select => 'id', \r\n :conditions => ['story_id = ?', self.id]\r\n \r\n if story_tag_links.length > 0 \r\n # Tags for this story exist, get the tags\r\n tags = StoryTagLink.find_by_sql ['SELECT tags.name AS name FROM stories LEFT JOIN story_tag_links ON story_tag_links.story_id = stories.id LEFT JOIN tags ON tags.id = story_tag_links.tag_id WHERE stories.id = ?', self.id]\r\n\r\n tag_links = Array.new\r\n\r\n for tag in tags\r\n tag_links.push '<a href=\"#\">' + tag.name + '</a>'\r\n end\r\n\r\n tag_link_list = tag_links * ', '\r\n else\r\n tag_link_list = ''\r\n end\r\n \r\n return tag_link_list\r\n end",
"def pulled_tags\n @list.pullin ? @list.taggings.where(user_id: @list.owner_id).includes(:tag).map(&:tag) : []\n end"
] |
[
"0.68090504",
"0.6358161",
"0.58911306",
"0.57307017",
"0.56719035",
"0.56540555",
"0.5642764",
"0.5616005",
"0.5607584",
"0.55675405",
"0.55518913",
"0.55439836",
"0.5536333",
"0.55092025",
"0.547324",
"0.546704",
"0.5419871",
"0.5419157",
"0.5414881",
"0.5395047",
"0.53818494",
"0.5379148",
"0.53412455",
"0.53383887",
"0.5296769",
"0.52443975",
"0.5232584",
"0.52233654",
"0.52136725",
"0.52012104",
"0.5194843",
"0.51927406",
"0.51897186",
"0.5186331",
"0.5178991",
"0.5173485",
"0.51692146",
"0.5168657",
"0.51591426",
"0.51494753",
"0.5145931",
"0.5145696",
"0.5127219",
"0.51236475",
"0.5117469",
"0.5117469",
"0.5116326",
"0.5112146",
"0.5094391",
"0.5089576",
"0.5088747",
"0.50867945",
"0.50844437",
"0.50708336",
"0.5051942",
"0.5050938",
"0.5049282",
"0.5049282",
"0.5049282",
"0.50444776",
"0.5042786",
"0.5039749",
"0.5037524",
"0.5034653",
"0.50261897",
"0.5022171",
"0.5020279",
"0.5007244",
"0.5006667",
"0.500535",
"0.5005133",
"0.50045884",
"0.50029385",
"0.49967912",
"0.4996273",
"0.4995776",
"0.49703398",
"0.49662173",
"0.49621487",
"0.4958353",
"0.49525097",
"0.4937601",
"0.49363703",
"0.4935245",
"0.49337217",
"0.49297404",
"0.49247748",
"0.49229687",
"0.49228746",
"0.49189773",
"0.49151906",
"0.49151906",
"0.49048638",
"0.49022743",
"0.48988974",
"0.48962402",
"0.48928225",
"0.48882994",
"0.48880225",
"0.48810926"
] |
0.8447853
|
0
|
Provided a service entry this will pull out concept ids from tag guids and request the collections from CMR
|
def collections_from_service_entry_tags(service_entry)
concept_ids = concept_ids_from_service_entry_tags(service_entry)
return [] if concept_ids.blank?
response = cmr_client.get_collections_by_post({ concept_id: concept_ids, page_size: concept_ids.size }, token)
if response.success?
response.body.fetch('items', [])
else
[]
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def get_datasets_for_service_implementation(params = {})\n # service_interface_guid is not a permitted param for CMR but we need it for this call\n # so we'll use delete to pop the value from the params hash\n response = echo_client.get_service_entries(echo_provider_token, params.delete('service_interface_guid'))\n\n if response.success?\n service_entries = Array.wrap(response.parsed_body.fetch('Item', []))\n\n dataset_guids = service_entries.map do |service_entry|\n Array.wrap((service_entry['TagGuids'] || {}).fetch('Item', [])).group_by { |guid| guid.split('_', 3).first }['DATASET'] || []\n end\n\n if dataset_guids.any?\n # Merge any provided (permitted) params with the conecpt ids retrieved\n cmr_params = {\n concept_id: dataset_guids.flatten.map { |guid| guid.split('_', 3).last }\n }.merge(params)\n\n get_provider_collections(cmr_params)\n else\n {}\n end\n else\n response.parsed_body\n end\n end",
"def tag_provider_collections_single_post\n post_body = nil\n post_body_providers = ''\n EOSDIS_PROVIDERS.each do |provider|\n if !provider.blank?\n provider = provider.strip\n Rails.logger.info(\"Processing provider: #{provider}\")\n #ensure that provider is present\n if (@all_providers[provider] != nil)\n Rails.logger.info(\"LOCATED PROVIDER: #{provider}\")\n # COLLECTIONS ARE BEING TAGGED so let's check if there are collections for each provider\n # help with debugging of timing issues since the tagging occurs at midnight and perhaps the collections expected\n # in the results set are tagged after that\n response = RestClient::Request.execute :method => :get, :url => \"#{@catalog_rest_endpoint}collections\",\n headers: {params: {provider: provider}},\n :verify_ssl => OpenSSL::SSL::VERIFY_NONE\n hits = response.headers[:cmr_hits].to_i\n if hits > 0\n Rails.logger.info(\"PROVIDER #{provider} HAS #{hits} COLLECTIONS\")\n post_body_providers = post_body_providers + '{\"provider\": \"' + provider + '\"},'\n end\n else\n Rails.logger.info(\"COULD NOT LOCATE PROVIDER: #{provider}\")\n end\n end\n end\n if (!post_body_providers.blank?)\n post_body_providers = post_body_providers.chomp(',')\n post_body = '{\n \"condition\": {\"or\" : [' + post_body_providers +\n ']}}'\n Rails.logger.info(\"POST request body: #{post_body}\")\n # one request takes much longer so we must increase the read_timeout (seconds)\n response = RestClient::Request.execute :method => :post, :url => \"#{@catalog_rest_endpoint}tags/#{@tag}/associations/by_query\", :payload => post_body,\n :headers => {'Authorization' => @token, 'Content-Type' => 'application/json'},\n :verify_ssl => OpenSSL::SSL::VERIFY_NONE, :timeout => 240\n if (response.code != 200)\n Rails.logger.info(\"COULD NOT TAG PROVIDERS, ERROR: #{response.code}, BODY: #{response.body} \")\n else\n Rails.logger.info(\"SUCCESSFULY TAGGED ALL PROVIDERS\")\n end\n end\n end",
"def retrieve_concept_list_from_params params, key, alternate_size\n concept_ids = []\n if params.has_key?(key)\n concept_ids = JSON.parse(params[key]).map { |fc| fc[\"id\"] }\n get_all_concepts = false\n concept_ids.each do |concept_id|\n if concept_id == \"nil\"\n get_all_concepts = true\n break\n end\n end\n end\n\n if get_all_concepts\n concepts = @course.topicconcepts.concepts\n elsif concept_ids.size > 0\n concepts = @course.topicconcepts.concepts.where(id: concept_ids)\n elsif alternate_size > 0\n concepts = @course.topicconcepts.concepts.limit(alternate_size)\n else\n concepts = []\n end\n\n concepts\n end",
"def service_list\n uri = URI.parse(@url)\n http = Net::HTTP.new(uri.host, uri.port, @proxy_addr, @proxy_port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Get.new(uri.request_uri)\n request.basic_auth user, passwd\n request.add_field 'X-ID-TENANT-NAME', id_domain\n http.request(request)\n end",
"def service_request(service); end",
"def get_service_implementations_with_datasets(params = {})\n # Retrieve all service entries for the current provider\n response = echo_client.get_service_entries_by_provider(echo_provider_token, current_provider_guid)\n\n if response.success?\n service_entries = Array.wrap(response.parsed_body.fetch('Item', [])).sort_by { |option| option['Name'].downcase }\n\n # Allow filtering the results by name (This is really slow and not recommended, but is a necessary feature)\n unless params.fetch('name', nil).blank?\n service_entries.select! { |s| s['Name'].downcase.start_with?(params['name'].downcase) }\n end\n\n # Filter down our list of all service entries that belong to the current provider to\n # just those with EntryType of SERVICE_IMPLEMENTATION and that have collections assigned to them\n service_entries.select! do |s|\n s['EntryType'] == 'SERVICE_IMPLEMENTATION' &&\n Array.wrap((s['TagGuids'] || {}).fetch('Item', [])).any? { |t| t.split('_', 3).include?('DATASET') }\n end\n\n service_entries\n else\n response.parsed_body\n end\n end",
"def acquire_service_data\n if config[:tags] && config[:service]\n tags = config[:tags].split(',').to_set\n services = []\n Diplomat::Health.service(config[:service]).each do |s|\n if s['Service']['Tags'].to_set.superset? tags\n services.push(*s['Checks'])\n end\n end\n services\n elsif config[:nodename]\n data = []\n begin\n services = Diplomat::Node.get(config[:nodename]).Services\n rescue StandardError\n services = {}\n end\n services.each_value do |service|\n Diplomat::Health.checks(service['Service']).each do |check|\n data.push(check) if check.Node == config[:nodename]\n end\n end\n data\n elsif config[:all]\n Diplomat::Health.state('any')\n else\n Diplomat::Health.checks(config[:service])\n end\n end",
"def get_multiple_entries (entries)\n\n\t\tif entries.nil? then\n\t\t\treturn \"{}\"\n\t\tend\n\nputs \"get_multiple_entries: #{entries}\"\n#\t\tq_string = entries[:uniprotIds].join(',')\n\t\tentries_pairs = entries.split(',')\n\t\taccessions = entries_pairs.map { |it|\n\t\t\tit.split(';')[0]\n\t\t}\n\t\tq_string = accessions.join(',')\n\t\turl = DBFETCH_URL.gsub(/xxxx/, q_string)\n\n\t\toptions = {}\n\t\tsubstring = ''\n\t\tif options[:limit].nil? then\n\t\t\toptions[:limit] = @limit\n\t\tend\n\t\toptions[:q] = substring\n\n#\t\turl = URI.parse(req_url)\n\t\tresults = request(url, options)\n\t\tif results.body == \"\" then # no concept found\n\t\t\tputs \"No concept found!\"\n\t\t\t@parsed_results = {:concept_uuid => nil, :concept_label => nil, :tag_uuid => nil, :tag_label => nil}\n\t\t\treturn @parsed_results\n\n\t\telsif results.code.to_i != 200 then\n\t\t\tputs \"DBFetch service is not working properly!\"\n\t\t\treturn nil\n\n\t\telse\n\t\t\t# from dbfetch service, what we get is xml\n\t\t\tuniprotxml2json (results.body)\n#\t\t\treturn true\n\t\tend\n\n\tend",
"def show_service(client, args, options)\n response = client.get(\"#{RESOURCE_PATH}/#{args[0]}\")\n\n if CloudClient::is_error?(response)\n [response.code.to_i, response.to_s]\n else\n #[0,response.body]\n if options[:json]\n [0,response.body]\n else\n str=\"%-20s: %-20s\"\n str_h1=\"%-80s\"\n\n document_hash = JSON.parse(response.body)\n template = document_hash['DOCUMENT']['TEMPLATE']['BODY']\n\n CLIHelper.print_header(str_h1 % \"SERVICE #{document_hash['DOCUMENT']['ID']} INFORMATION\")\n\n puts str % [\"ID\", document_hash['DOCUMENT']['ID']]\n puts str % [\"NAME\", document_hash['DOCUMENT']['NAME']]\n puts str % [\"USER\", document_hash['DOCUMENT']['UNAME']]\n puts str % [\"GROUP\",document_hash['DOCUMENT']['GNAME']]\n\n puts str % [\"STRATEGY\", template['deployment']]\n puts str % [\"SERVICE STATE\", Service.state_str(template['state'])]\n puts str % [\"SHUTDOWN\", template['shutdown_action']] if template['shutdown_action']\n\n puts\n\n CLIHelper.print_header(str_h1 % \"PERMISSIONS\",false)\n\n [\"OWNER\", \"GROUP\", \"OTHER\"].each { |e|\n mask = \"---\"\n mask[0] = \"u\" if document_hash['DOCUMENT']['PERMISSIONS'][\"#{e}_U\"] == \"1\"\n mask[1] = \"m\" if document_hash['DOCUMENT']['PERMISSIONS'][\"#{e}_M\"] == \"1\"\n mask[2] = \"a\" if document_hash['DOCUMENT']['PERMISSIONS'][\"#{e}_A\"] == \"1\"\n\n puts str % [e, mask]\n }\n\n puts\n\n template['roles'].each {|role|\n CLIHelper.print_header(\"ROLE #{role['name']}\", false)\n\n puts str % [\"ROLE STATE\", Role.state_str(role['state'])]\n puts str % [\"PARENTS\", role['parents'].join(', ')] if role['parents']\n puts str % [\"VM TEMPLATE\", role['vm_template']]\n puts str % [\"CARDINALITY\", role['cardinality']]\n puts str % [\"MIN VMS\", role['min_vms']] if role['min_vms']\n puts str % [\"MAX VMS\", role['max_vms']] if role['max_vms']\n puts str % [\"COOLDOWN\", \"#{role['cooldown']}s\"] if role['cooldown']\n puts str % [\"SHUTDOWN\", role['shutdown_action']] if role['shutdown_action']\n\n puts \"NODES INFORMATION\"\n NODE_TABLE.show(role['nodes'])\n\n if !role['elasticity_policies'].nil? && role['elasticity_policies'].size > 0 || !role['scheduled_policies'].nil? && role['scheduled_policies'].size > 0\n puts\n puts \"ELASTICITY RULES\"\n\n if role['elasticity_policies'] && role['elasticity_policies'].size > 0\n puts\n# puts \"ELASTICITY POLICIES\"\n CLIHelper::ShowTable.new(nil, self) do\n column :ADJUST, \"\", :left, :size=>12 do |d|\n adjust_str(d)\n end\n\n column :EXPRESSION, \"\", :left, :size=>48 do |d|\n if !d['expression_evaluated'].nil?\n d['expression_evaluated']\n else\n d['expression']\n end\n end\n\n column :'EVALS', \"\", :right, :size=>5 do |d|\n if d['period_number']\n \"#{d['true_evals'].to_i}/#{d['period_number']}\"\n else\n \"-\"\n end\n end\n\n column :PERIOD, \"\", :size=>6 do |d|\n d['period'] ? \"#{d['period']}s\" : '-'\n end\n\n column :COOL, \"\", :size=>5 do |d|\n d['cooldown'] ? \"#{d['cooldown']}s\" : '-'\n end\n\n default :ADJUST, :EXPRESSION, :EVALS, :PERIOD, :COOL\n end.show([role['elasticity_policies']].flatten, {})\n end\n\n if role['scheduled_policies'] && role['scheduled_policies'].size > 0\n puts\n# puts \"SCHEDULED POLICIES\"\n CLIHelper::ShowTable.new(nil, self) do\n column :ADJUST, \"\", :left, :size=>12 do |d|\n adjust_str(d)\n end\n\n column :TIME, \"\", :left, :size=>67 do |d|\n if d['start_time']\n Time.parse(d['start_time']).to_s\n else\n d['recurrence']\n end\n end\n\n default :ADJUST, :TIME\n end.show([role['scheduled_policies']].flatten, {})\n end\n end\n\n puts\n }\n\n puts\n\n CLIHelper.print_header(str_h1 % \"LOG MESSAGES\",false)\n\n if template['log']\n template['log'].each { |log|\n t = Time.at(log['timestamp']).strftime(\"%m/%d/%y %H:%M\")\n puts \"#{t} [#{log['severity']}] #{log['message']}\"\n }\n end\n\n 0\n end\n end\nend",
"def find_collections_for_form\n Hyrax::CollectionsService.new(self).search_results(:edit)\n end",
"def find_services(params, serviceDir)\n service_files = []\n if ((services = params[:services]) != nil)\n services.each do |name|\n s = {}\n s[:name] = name\n s[:require] = \"omf-aggmgr/ogs_#{name}/#{name}\"\n s[:config] = \"#{name}.yaml\"\n service_files << s\n end\n else\n MObject.debug('gridservices', \"Loading all available services from #{serviceDir}\")\n Dir.foreach(serviceDir) do |filename|\n if (filename =~ /\\.yaml$/) then\n s = {}\n s[:name] = name = filename.split('.')[0]\n s[:require] = \"omf-aggmgr/ogs_#{name}/#{name}\"\n s[:config] = filename\n service_files << s\n end\n end\n end\n service_files\nend",
"def service(id)\n request :get, \"/services/#{id}\"\n end",
"def edit\n @service = Service.find(params[:id])\n @category = Service.categories.keys\n\n end",
"def calendar_by_service(service_id)\n get \"/gtfs/calendar/serviceId/#{service_id}\"\n end",
"def get_services\n reply = @client.call(:get_services)\n\n data = reply.body.dig(:get_services_response,\n :get_services_result,\n :array_of_string)\n data = check_if_data_exists(data)\n\n data.map do |attrs|\n {\n id: Integer(attrs[:string][0], 10),\n name: attrs[:string][1]\n }\n end\n end",
"def service_ids\n services.collect { |s| s[\"id\"] }\n end",
"def cmc_inventory(service_tag, options={})\n options[:url] = ASM::PrivateUtil.chassis_ra_url(options[:url])\n url = \"%s/?filter=eq,serviceTag,%s\" % [options[:url], service_tag]\n data = ASM::Api.sign { RestClient.get(url, :accept => :json) }\n JSON.parse(data).first\n end",
"def services()\n return @data[\"access\"][\"serviceCatalog\"]\n end",
"def collect_idl_files\n recipes.each { |rcp| rcp.collect_idl_files }\n end",
"def next\n return nil unless next?\n ensure_service!\n grpc = @client.service.list_collections @parent, token: token, max: @max, read_time: @read_time\n self.class.from_grpc grpc, @client, @parent, max: @max, read_time: @read_time\n end",
"def process_claim_services(clm)\n row = @cnf['CLAIM_SERVICE_START_LINE']-1\n while(row < @cnf['CLAIM_SERVICE_END_LINE'])\n \n # New line characters may in a blank line\n if @cntnt[row].length > 1\n clm_items = ClaimServiceInformation.new\n @cnf['CLAIM_SERVICE'].each { |k, v| clm_items[k] = @cntnt[row][v[1]-1, v[2]].strip }\n @cnf['CLAIM_SERVICE_DATES'].each { |k, v| clm_items[k] = frame_date(@cntnt[row][v[1]-1, v[2]].strip) }\n @clm_fl_info.total_svcline_count += 1\n p clm_items\n clm.claim_service_informations << clm_items\n end\n row += 1\n end\n end",
"def servers(service_id)\n request :get, \"/services/#{service_id}/servers\"\n end",
"def collection_list\n truncate_limit = (params[:truncate] || 60).to_i\n collections = {}\n registration_collection_ids_for_apo(params[:apo_id]).each do |col_id|\n col_druid = col_id.gsub(/^druid:/, '')\n col_title_field = SolrDocument::FIELD_TITLE\n\n # grab the collection title from Solr, or fall back to DOR\n solr_doc = Dor::SearchService.query(\"id:\\\"#{col_id}\\\"\",\n rows: 1,\n fl: col_title_field)['response']['docs'].first\n if solr_doc.present? && solr_doc[col_title_field].present?\n collections[col_id] = \"#{short_label(solr_doc[col_title_field].first, truncate_limit)} (#{col_druid})\"\n else\n Honeybadger.notify(\"Unable to find title of the collection #{col_id} in Solr. Checking Fedora, but this is slow.\")\n begin # Title not found in Solr, so check DOR\n collection = Dor.find(col_id)\n collections[col_id] = \"#{short_label(collection.label, truncate_limit)} (#{col_druid})\"\n rescue ActiveFedora::ObjectNotFoundError\n Honeybadger.notify(\"Unable to find the collection #{col_id} in Fedora, but it's listed in the administrativeMetadata datastream for #{params[:apo_id]}\")\n col_not_found_warning = \"#{params[:apo_id]} lists collection #{col_id} for registration, but it wasn't found in Fedora.\"\n Rails.logger.warning col_not_found_warning\n end\n end\n end\n\n # before returning the list, sort by collection name, and add a \"None\" option at the top\n collections = { '' => 'None' }.merge((collections.sort_by { |_k, col_title| col_title }).to_h)\n respond_to do |format|\n format.any(:json, :xml) { render request.format.to_sym => collections }\n end\n end",
"def search\n if params[:collection_ids]\n data = {:sites => [], :clusters => []}\n params[:collection_ids].each do |id|\n result = search_by_collection id, params\n data[:sites].concat result[:sites] if result[:sites]\n data[:clusters].concat result[:clusters] if result[:clusters]\n end\n render json: data\n else\n render json: []\n end\n end",
"def places(collection_id)\n PublicEarth::Db::Place.find_from_search(*(PublicEarth::Db::Place.many.in_collection(collection_id).map { |result| result['in_collection'] }))\n end",
"def list_services(client, args, options)\n response = client.get(RESOURCE_PATH)\n\n if CloudClient::is_error?(response)\n [response.code.to_i, response.to_s]\n else\n #[0,response.body]\n if options[:json]\n [0,response.body]\n else\n array_list = JSON.parse(response.body)\n SERVICE_TABLE.show(array_list['DOCUMENT_POOL']['DOCUMENT'])\n 0\n end\n end\nend",
"def fetch_scenarios\n collection = connect_to_mongo\n scenarios = {}\n collection.find.each { |doc| scenarios.merge!(doc) }\n scenarios.delete('_id')\n scenarios\nend",
"def tag_guids_for_tag_group(service_entry, tag_group)\n guids = service_entry['TagGuids']\n\n return [] if guids.blank?\n\n # The first element of the tag strings ARE the tag group. We'll group\n # by that value and return the requested group. This saves a fair amount\n # of logic from having to be copy and pasted sifting out only the guids we\n # need for a particular operation\n Array.wrap(guids).group_by { |guid| service_tag_parts(guid).first }[tag_group] || []\n end",
"def service_imports(schema, service, package)\n list = []\n \n # custom package provided during generation\n pkg = options[:namespace]\n pkg += \".\" if pkg.present?\n \n # import request and response of operations\n service.operations.each do |name, definition|\n if (definition.request_property)\n if (pkg.present?)\n list.push(pkg + valid_class_name(definition.request_property.type))\n else\n list.push(get_slashed_package_name(get_namespace(schema.data_types[valid_class_name(definition.request_property.type)].package || package) + \".\" + valid_class_name(definition.request_property.type)))\n end\n end\n if (definition.response)\n if (pkg.present?)\n list.push(pkg + valid_class_name(definition.response))\n else\n list.push(get_slashed_package_name(get_namespace(schema.data_types[valid_class_name(definition.response)].package || package) + \".\" + valid_class_name(definition.response)))\n end\n end\n if (definition.fault)\n if (pkg.present?)\n list.push(pkg + valid_class_name(definition.response))\n else\n list.push(get_slashed_package_name(get_namespace(schema.data_types[valid_class_name(definition.fault)].package || package) + \".\" + valid_class_name(definition.fault)))\n end\n end\n end\n # mandatory imports\n list += WSDLServiceImport\n list.uniq.sort\n end",
"def getAllTargetCollections\n return sendRequest('GET', PATH_ADD_TC)\n end",
"def getAllTargetCollections\n return sendRequest('GET', PATH_ADD_TC)\n end",
"def collection\n feature_id = nil\n if params[:feature_id]\n feature_id = params[:feature_id]\n elsif params[:id]\n feature_id = object.feature_id\n end\n if params[:filter].blank? && !feature_id.blank?\n search_results = parent_object.definitions\n elsif !params[:filter].blank?\n search_results = Definition.search(params[:filter])\n search_results = search_results.where(:feature_id => feature_id) if feature_id\n else\n search_results = []\n end\n @collection = search_results.empty? ? search_results : search_results.page(params[:page])\n end",
"def index\n conditions = { :client_id => @client.id }\n if params[\"tags\"]\n conditions.merge!({:tags => params[\"tags\"]})\n end\n\n @collections = Collection.where(conditions).order('updated_at DESC')\n @collections.reject! { |item| ! item.read?(@user, @client) }\n\n entries = Array.new\n if @collections\n @collections.each do |item|\n entries << item.info_hash(@user, @client)\n end\n end\n render_json :entry => entries and return\n end",
"def get_by_org_key_and_service_key(org_key, service_key, incoming={})\n HttpClient::Preconditions.assert_class('org_key', org_key, String)\n HttpClient::Preconditions.assert_class('service_key', service_key, String)\n opts = HttpClient::Helper.symbolize_keys(incoming)\n query = {\n :limit => HttpClient::Preconditions.assert_class_or_nil('limit', opts.delete(:limit), Integer),\n :offset => HttpClient::Preconditions.assert_class_or_nil('offset', opts.delete(:offset), Integer)\n }.delete_if { |k, v| v.nil? }\n @client.request(\"/#{CGI.escape(org_key)}/#{CGI.escape(service_key)}\").with_query(query).get.map { |hash| Apidoc::Models::Version.new(hash) }\n end",
"def services\n related_objects_by_type(\"Service\")\n end",
"def load_services(svcs)\n unless @services\n @services = Gruf.services.concat(svcs)\n @services.uniq!\n end\n @services\n end",
"def getAllTargetCollections()\n return sendHttpRequest(nil, \"GET\", @@PATH_ADD_TC)\n end",
"def get_provider_collections(params = {})\n collection_params = {\n 'provider' => current_user.provider_id,\n 'page_size' => 25\n }.stringify_keys.merge(params.stringify_keys)\n\n Rails.logger.debug \"Provider Collection Request parameters: #{collection_params}\" unless request.xhr?\n\n if collection_params.key?('short_name')\n collection_params['short_name'].concat('*')\n\n # In order to search with the wildcard parameter we need to tell CMR to use it\n collection_params['options'] = {\n 'short_name' => {\n 'pattern' => true\n }\n }\n end\n\n # Adds wildcard searching\n collection_params['keyword'].concat('*') if collection_params.key?('keyword')\n\n # Retreive the collections from CMR, allowing a few additional parameters\n cmr_client.get_collections_by_post(collection_params, token).body\n end",
"def search_requests( cid )\n url = \"#{self.url}?auth=#{self.authtoken}&cid=#{cid}\"\n status, response = rest_get( url )\n return status, response['details'] if ok?( status ) && response['details']\n return status, ''\n end",
"def collection_ids\n # Get the ids of the existing collections from the form.\n collection_ids = Hash(collections_for_registration).values.map { |elem| elem.fetch(:id) }\n if collection_radio == \"create\"\n collection_ids << create_collection(model.externalIdentifier)\n elsif collection[:collection].present? # guard against empty string\n collection_ids << collection[:collection]\n end\n collection_ids\n end",
"def find_concept_ids(concept_type, concept_search_term)\n if concept_type.blank? and concept_search_term.blank?\n raise ArgumentError, \"Please provide either a concept type or a concept search term\"\n end\n concept_ids = []\n \n #This is the concept type case\n if concept_search_term.blank?\n concept_ids = Concept.find(:all, :conditions => [\"concept_type_id = ?\", concept_type.concept_type_id])\n elsif concent_type.blank?\n \n else\n \n end\n end",
"def d_scribe(options)\n body, format = parse_body(options)\n params = body[:options]\n #debug \"Body & Format = \", opts.inspect + \", \" + format.inspect\n urns = params[:urns]\n debug 'Describe: URNS: ', urns.inspect, ' Options: ', params.inspect\n credentials = body[:credentials]\n\n if urns.nil? || urns.empty?\n @return_struct[:code][:geni_code] = 1 # Bad Arguments\n @return_struct[:output] = \"Argument 'urns' is either empty or nil.\"\n @return_struct[:value] = ''\n return ['application/json', JSON.pretty_generate(@return_struct)]\n end\n\n # SLICE == ACCOUNT / SLIVER == LEASE\n # Must provide full slice URN, e.g /urn:publicid:IDN+omf:netmode+account+__default__\n slice_urn, slivers_only, error_code, error_msg = parse_samant_urns(urns)\n\n if error_code != 0\n @return_struct[:code][:geni_code] = error_code\n @return_struct[:output] = error_msg\n @return_struct[:value] = ''\n return ['application/json', JSON.pretty_generate(@return_struct)]\n end\n\n authorizer = options[:req].session[:authorizer]\n raise OMF::SFA::AM::InsufficientPrivilegesException.new unless credentials[:account][:name] == urns.first\n # debug authorizer.inspect\n resources = []\n leases = []\n if slivers_only\n urns.each do |urn|\n l = @am_manager.find_samant_lease(urn, authorizer) # TODO maybe check thoroughly if slice_urn of slivers is the same as the authenticated user's\n resources << l\n leases << l\n l.isReservationOf.each do |comp|\n resources << comp if comp.hasSliceID == authorizer.account[:urn]\n end\n end\n else\n resources = @am_manager.find_all_samant_leases(slice_urn, $acceptable_lease_states, authorizer)\n leases = resources.dup\n components = @am_manager.find_all_samant_components_for_account(slice_urn, authorizer)\n #components.collect! { |r| (r.kind_of?SAMANT::Uxv) && r.hasParent ? r.hasParent : r } # Replace child nodes with parent nodes\n resources.concat(components)\n end\n # TODO uncomment to obtain rspeck, commented out because it's very time-wasting\n # used_for_side_effect = OMF::SFA::AM::Rest::ResourceHandler.rspecker(resources, :Offering) # -> creates the advertisement rspec file inside /ready4translation (less detailed, sfa enabled)\n res = OMF::SFA::AM::Rest::ResourceHandler.omn_response_json(resources, options) # -> returns the json formatted results (more detailed, omn enriched)\n\n value = {}\n value[:omn_rspec] = res\n value[:geni_urn] = slice_urn\n value[:geni_slivers] = []\n leases.each do |lease|\n tmp = {}\n tmp[:geni_sliver_urn] = lease.to_uri.to_s\n tmp[:geni_expires] = lease.expirationTime.to_s\n tmp[:geni_allocation_status] = if lease.hasReservationState.uri == SAMANT::ALLOCATED.uri then \"geni_allocated\"\n elsif lease.hasReservationState.uri == SAMANT::PROVISIONED.uri then \"geni_provisioned\"\n else \"geni_unallocated\"\n end\n tmp[:geni_operational_status] = \"NO_INFO\" # lease.isReservationOf.hasResourceStatus.to_s # TODO Match geni_operational_status with an ontology concept\n value[:geni_slivers] << tmp\n end\n\n @return_struct[:code][:geni_code] = 0\n @return_struct[:value] = value\n @return_struct[:output] = ''\n return ['application/json', JSON.pretty_generate(@return_struct)]\n rescue OMF::SFA::AM::InsufficientPrivilegesException => e\n @return_struct[:code][:geni_code] = 3\n @return_struct[:output] = e.to_s\n @return_struct[:value] = ''\n return ['application/json', JSON.pretty_generate(@return_struct)]\n end",
"def sword_services\n Utility.find_elements_by_namespace_and_name(extensions, \"http://purl.org/net/sword/terms/\", \"service\")\n end",
"def fetch_urls_from_feedly\n yaml = YAML.load_file('env.yaml')\n client = Feedlr::Client.new(oauth_access_token: yaml['account']['feedly']['access_token'])\n client.user_subscriptions.map{|m|\n # puts m.id\n hotentries = client.stream_entries_contents(m.id, :count => 5 ).items\n return hotentries\n };\nend",
"def getTargetCollection(tcId)\n path = PATH_GET_TC.dup\n path[PLACEHOLDER_TC_ID] = tcId\n return sendRequest('POST', path)\n end",
"def getTargetCollection(tcId)\n path = PATH_GET_TC.dup\n path[PLACEHOLDER_TC_ID] = tcId\n return sendRequest('POST', path)\n end",
"def service_resources(release_doc)\n release_doc.resources.select { |r| r.is_a?(Kubernetes::Resource::Service) }\n end",
"def get(key, scope = :first, options = {}, meta = nil)\n custom_params = []\n custom_params << use_named_parameter('wait', options[:wait]) if options[:wait]\n custom_params << use_named_parameter('index', options[:index]) if options[:index]\n custom_params << use_named_parameter('dc', options[:dc]) if options[:dc]\n custom_params << use_named_parameter('filter', options[:filter]) if options[:filter]\n custom_params += [*options[:tag]].map { |value| use_named_parameter('tag', value) } if options[:tag]\n\n ret = send_get_request(@conn, [\"/v1/catalog/service/#{key}\"], options, custom_params)\n if meta && ret.headers\n meta[:index] = ret.headers['x-consul-index'] if ret.headers['x-consul-index']\n meta[:knownleader] = ret.headers['x-consul-knownleader'] if ret.headers['x-consul-knownleader']\n meta[:lastcontact] = ret.headers['x-consul-lastcontact'] if ret.headers['x-consul-lastcontact']\n end\n\n if scope == :all\n JSON.parse(ret.body).map { |service| OpenStruct.new service }\n else\n OpenStruct.new JSON.parse(ret.body).first\n end\n end",
"def fetch_many(ids, req_params = nil, eds_params = nil)\n req_params ||= params\n search_service.fetch_many(ids, req_params, eds_params)\n end",
"def add_collected_query\n return if options[:collection_ids].present? || !collected?\n body.must(:query_string, \"collections.id\" => \"*\")\n end",
"def call\n reference_objects = if cache_reponse = @redis.hget(@collection_identifier, @collection_params)\n from_cache(cache_reponse)\n else\n from_query\n end\n\n ReferencesMap.new(@aggregator, reference_objects)\n end",
"def available_collections\n api = API.new\n params = {:limit => 9999, :preserve_original => true}\n response = api.send_and_receive('collections', {:params => params})\n response.map {|n| [n['title'], n['identifier']]}\n end",
"def get key, scope=:first, options=nil, meta=nil\n\n url = [\"/v1/catalog/service/#{key}\"]\n url += check_acl_token\n url << use_named_parameter('wait', options[:wait]) if options and options[:wait]\n url << use_named_parameter('index', options[:index]) if options and options[:index]\n url << use_named_parameter('dc', options[:dc]) if options and options[:dc]\n url << use_named_parameter('tag', options[:tag]) if options and options[:tag]\n\n # If the request fails, it's probably due to a bad path\n # so return a PathNotFound error.\n begin\n ret = @conn.get concat_url url\n rescue Faraday::ClientError\n raise Diplomat::PathNotFound\n end\n\n if meta and ret.headers\n meta[:index] = ret.headers[\"x-consul-index\"]\n meta[:knownleader] = ret.headers[\"x-consul-knownleader\"]\n meta[:lastcontact] = ret.headers[\"x-consul-lastcontact\"]\n end\n\n if scope == :all\n return JSON.parse(ret.body).map { |service| OpenStruct.new service }\n end\n\n return OpenStruct.new JSON.parse(ret.body).first\n end",
"def read_collections\n site.collections.each_value do |collection|\n next if collection.data?\n\n collection.read\n end\n end",
"def collection_or_multi_id_collection\n if multi_ids_request?\n selector = {multi_id_key => multi_ids}\n set_collection(resource_class.in(selector))\n else\n collection\n end\n end",
"def set_service\n @service = Service.includes(lineup: :programme).find(params[:id])\n end",
"def add(service)\n @list ||= []\n @list << service unless @list.find{|s| s.url == service.url && s.verb == service.verb}\n @list\n end",
"def tag_service(dialogs_tags_hash)\n log_and_update_message(:info, \"Processing tag_service...\", true)\n\n # Look for tags with a sequence_id of 0 to tag the service\n dialogs_tags_hash.fetch(0, {}).each do |key, value|\n log_and_update_message(:info, \"Processing tag: #{key.inspect} value: #{value.inspect}\")\n tag_category = key.downcase\n Array.wrap(value).each do |tag_entry|\n process_tag(tag_category, tag_entry.downcase)\n end\n end\n log_and_update_message(:info, \"Processing tag_service...Complete\", true)\nend",
"def services(query = {})\n get('service', query)\n end",
"def analyze(service_name)\n # Locate API and resource json files\n json = ''\n unless @json_paths.detect { |path| json = File.join(path, service_name.camel_case + '.api.json'); File.exist?(json) }\n puts \"Hmm there doesn't seem to be a #{service_name.camel_case}.api.json file at #{@json_paths.join(' ,')}, you sure you got that right? (use --paths to specify the location of the JSON files)\"\n exit 1\n end\n\n # read resource definitions\n res_json = []\n @json_paths.each do |path|\n f = File.join(path, service_name.camel_case + '.resources.json')\n res_json << f if File.exist?(f)\n end\n if res_json == []\n puts(\"Hmm there doesn't seem to be a #{service_name.camel_case}.resources.json file \" +\n \"at #{@json_paths.join(' ,')}, are you sure you got that right? \" +\n \"(use --paths to specify the location of the JSON files)\")\n exit 1\n end\n # actually load the definitions and merge the top-level values\n resources = {}\n res_json.each do |rj|\n rr = JSON.load(IO.read(rj))\n rr.each_pair do |k,v|\n if resources.key?(k)\n if resources[k].is_a?(Array)\n resources[k] += v\n else\n resources[k].merge!(v)\n end\n else\n resources[k] = v\n end\n end\n end\n\n service = JSON.load(IO.read(json))\n registry = ResourceRegistry.new\n operations = service['operations'].keys\n # First try with RESOURCE_ACTIONS operation prefixes\n candidates, remaining = operations.partition { |o| is_resource_action?(o, primary_only: true) }\n # If no results then try with SECONDARY_RESOURCE_ACTIONS operation prefixes\n if candidates.empty?\n candidates, remaining = operations.partition { |o| is_resource_action?(o) }\n end\n\n # 1. Identify resources by using well known operation prefixes\n candidates.each do |c|\n name = c.gsub(/^(#{ALL_ACTIONS.join('|')})/, '')\n if name.underscore =~ /_for_/\n remaining << c\n else\n registry.add_resource_operation(name, service['operations'][c], service['shapes'])\n end\n end\n\n # 2. Collect custom actions that apply to identified resources\n matched = []\n remaining.each do |r|\n candidates = registry.resource_names.select { |n| r =~ /(#{n}|#{n.pluralize})$/ }\n next if candidates.empty?\n matched << r\n candidates.sort { |a, b| b.size <=> a.size } # Longer name first\n name = candidates.first\n registry.add_resource_operation(name, service['operations'][r], service['shapes'])\n end\n\n # 3. Leverage resource.json if present to identify id fields and links\n shapes = to_underscore(service['shapes'])\n resources['resources'].each do |name, res|\n next unless res['shape']\n # Let's see if we find an exact match\n existing = registry.resources.select { |n, r| r.orig_name == name }\n if !existing.empty?\n # We found an exact match, use that shape\n if existing.size > 1\n puts \"Found ambiguous match: multiple resources with name #{name}...\"\n next\n end\n existing.values.first.shape = res['shape'].underscore\n else\n existing = registry.resources.select { |n, r| r.shape == res['shape'].underscore }\n if existing.size > 1\n puts \"Found ambiguous match: multiple resources with shape #{res['shape']}...\"\n next\n end\n end\n next if existing.empty?\n r = existing.values.first\n shape = shapes[r.shape]\n if shape\n members = shape['members'].keys || []\n res['identifiers'].each do |i|\n candidate = i['memberName'] || i['name']\n next if candidate.nil?\n candidate = candidate.underscore\n if !members.include?(candidate)\n candidate = \"#{r.name}_#{candidate}\"\n next unless members.include?(candidate)\n end\n if r.primary_id.nil?\n r.primary_id = candidate\n else\n r.secondary_ids ||= []\n r.secondary_ids << candidate\n end\n end\n end\n end\n\n # 4. Build service level custom actions for unmapped actions\n not_mapped = remaining - matched\n service_actions = not_mapped.inject({}) { |m, nm| m[nm.underscore] = Operation.to_action(service['operations'][nm]); m }\n\n # 5. Cleanup resources for which we couldn't find an id field\n no_ids = registry.delete_incomplete_resources.sort\n @errors = []\n @errors << \"** Failed to find an id for the following resources:\\n #{no_ids.join(\"\\n \")}\" unless no_ids.empty?\n\n # We're done!\n ::Analyzer::ServiceDefinition.new('name' => service['metadata']['serviceFullName'],\n 'url' => \"/aws/#{service['metadata']['endpointPrefix']}\",\n 'metadata' => service['metadata'],\n 'resources' => registry.resources.inject({}) { |m, (k, v)| m[k.underscore] = v; m },\n 'actions' => service_actions,\n 'shapes' => shapes)\n end",
"def read_service_types()\n types = []\n @client.services.each do |type|\n types << type.label\n end\n\n types\n end",
"def provided_service_links\n links.joins(:service).merge(provided_services)\n end",
"def provided_service_links\n links.joins(:service).merge(provided_services)\n end",
"def service_imports(schema, service, package)\n list = []\n\n # custom package provided during generation\n pkg = options[:namespace]\n pkg += \".\" if pkg.present?\n\n # import request and response of operations\n service.operations.each do |name, definition|\n if (definition.request_property)\n if (pkg.present?)\n list.push(pkg + validate_class_name(definition.request_property.type))\n else\n list.push(convert_ns_to_package(schema.data_types[validate_class_name(definition.request_property.type)].package || package) + \".\" + validate_class_name(definition.request_property.type))\n end\n end\n if (definition.response_property)\n if (pkg.present?)\n list.push(pkg + validate_class_name(definition.response_property.type))\n else\n list.push(convert_ns_to_package(schema.data_types[validate_class_name(definition.response_property.type)].package || package) + \".\" + validate_class_name(definition.response_property.type))\n end\n end\n if (definition.fault_property)\n if (pkg.present?)\n list.push(pkg + validate_class_name(definition.fault_property.type))\n else\n list.push(convert_ns_to_package(schema.data_types[validate_class_name(definition.fault_property.type)].package || package) + \".\" + validate_class_name(definition.fault_property.type))\n end\n end\n end\n\n # mandatory imports\n list += ServiceImportWSDL\n list.uniq.sort\n end",
"def services\n begin\n resp = _get build_agent_url('services')\n rescue\n logger.warn('Unable to request all the services on this through the HTTP API')\n return nil\n end\n # Consul returns id => ConsulServiceObjects.\n s_hash = JSON.parse(resp)\n s_hash.keys.map { |n| Consul::Model::Service.new.extend(Consul::Model::Service::Representer).from_hash(s_hash[n]) }\n end",
"def get_collection\n @book_series = BookSeries.find(params[:book_series_id])\n @collection = @book_series.collections.find(params[:collection_id])\n @book_series_1 = BookSeries.first\n end",
"def inject(services_container); end",
"def set_service_list\n @service_list = ServiceList.find(params[:id])\n end",
"def service_requests_list\n @service_requests = ServiceRequest.get_all_service_requests(@page)\n end",
"def service_list\n @service_list ||= {}\n end",
"def computeDependences(list)\n dependences = OCMSet.new\n\n OCMSet::SECTIONS.each do |section|\n @require[section].each do |req|\n found = false\n\n list.each do |iface|\n for context in iface.provide do\n if context[section].include?(req) then\n dependences[section] << iface\n found = true\n break\n end\n end\n end\n\n raise \"#{@id.name}: no dependence found for #{req.name}.\" unless found\n end\n end\n\n return dependences.values.flatten.uniq\n end",
"def dig_components(tmp_assembly_collection, api_params)\n tmp_assembly_collection.map do |one_assembly|\n a0 = one_assembly.components.map do |one_component|\n unless one_component.empty?\n one_component = Components.new.show(api_params.merge('id' => one_component)).components\n end\n end\n one_assembly.asms_id(api_params[:asms_id])\n # set the_id in assembly. we need it for destroy\n one_assembly.components.replace(a0)\n @baked << one_assembly\n end\n Rails.logger.debug '>-- ASC: START'\n Rails.logger.debug \"#{@baked}\"\n Rails.logger.debug '> ASC: END'\n end",
"def collections\n return [] if name.nil?\n\n query = Solr::Query.new(\n collections_query,\n 100,\n fq: \"-ancestor_id_ssim:[* TO *]\"\n )\n query.to_a\n end",
"def collections_to_include\n return \"\" unless collections\n \"--collection #{[*collections].join(\" \")}\"\n end",
"def list\n tags = api_client.tags.by_resource(resource_hrefs:\n [api_client.get_instance.href]).first.tags\n ::MachineTag::Set.new(tags.map { |tag| tag['name'] })\n end",
"def term_candidates(cyc_id)\n return @term_cache[cyc_id] unless @term_cache[cyc_id].nil?\n @term_cache[cyc_id] = create_candidate_set(\"\",[@name_service.find_by_id(cyc_id)])\n end",
"def read_facts_xinetd_services(srvs, type = 'std')\n xinetd_services = {}\n\n srvs.each do |srv|\n srv_name = \"srv_#{srv}\"\n xinetd_services[srv_name] = check_xinetd_service(srv, type)\n end\n\n xinetd_services\nend",
"def do_query(query_tags, options = {})\n query_tags = [query_tags] if query_tags.is_a?(String)\n Chef::Log.info \"Tagged query_tags: #{query_tags}\"\n match_all = options.fetch(:match_all, false)\n resources = api_client.tags.by_tag(resource_type: 'instances', tags: query_tags, match_all: match_all)\n Chef::Log.info \"Tagged resources: #{resources}\"\n\n tags_hash = {}\n if resources.first\n links = resources.first.links\n if links\n links.each do |link|\n Chef::Log.info \"Tagged Resource Cloud:#{link['href'].split('/')[0..3].join('/')}\"\n next unless api_client.get_instance.show.cloud.href == link['href'].split('/')[0..3].join('/')\n next unless api_client.resource(link['href']).state == 'operational'\n resource_tags = api_client.tags.by_resource(resource_hrefs: [link['href']]) # .first.tags\n tags_hash[link['href']] = {\n 'tags' => resource_tags.first.tags.map { |tag| tag['name'] },\n }\n end\n end\n end\n tags_set_array = []\n tags_hash.values.each do |value|\n tags_set_array << ::MachineTag::Set.new(value['tags'])\n end\n tags_set_array\n end",
"def get id\n @services[id]\n end",
"def fetch_replica_sets(release_docs)\n if release_docs.any? { |rd| rd.resource_template.any? { |r| r[:kind] == \"Deployment\" } }\n fetch_grouped(:replica_sets, 'apps/v1')\n else\n [] # save time\n end\n end",
"def lookup_services(extension, arg)\n extension += \"/#{arg}\"\n uri = URI.parse(API_URL + extension)\n response = connect(uri)\n puts response.body\n end",
"def getTargetCollection(tcId)\n path = @@PATH_GET_TC.dup\n path[@@PLACEHOLDER_TC_ID] = tcId\n return sendHttpRequest(nil, \"POST\", path)\n end",
"def services\n\n end",
"def cv\n @collection = @project.data_collections.get(params[:collection_id])\n @schema_cv_hash={}\n @collection.schema.each do |s|\n link_hash={}\n if s.controlled_vocabulary_id\n @schema_cv_hash[s.id] = Yogo::Collection::Property.get(s.controlled_vocabulary_id).data_collection\n s.data_collection.items.each do |i|\n link_hash = link_hash.merge({i[s.name] => @schema_cv_hash[s.id].items.first(\"field_#{s.controlled_vocabulary_id.to_s.gsub('-','_')}\".to_sym=>i[s.name])})\n end\n @schema_cv_hash[s.name]=link_hash\n end\n end\n end",
"def services\n end",
"def service_courses\n Course.find :all, :conditions => { :ts_year => year, :ts_quarter => quarter_code, :ts_service => true }\n end",
"def get(user: nil, account_id: nil, service: nil, fields: nil, endpoint: nil, sort: nil, extra_path: nil, range: nil, ids: nil, query: {}, headers: {}, count: nil, entries: nil, method: :get)\n prep_call(user: user, account_id: account_id, service: service, query: query, headers: headers, required_arguments: ['user', 'service', 'endpoint'], binding: binding)\n\n host = Driver::Assemblers.host user: user, service: service, account_id: account_id\n path = Driver::Assemblers.path service: service, endpoint: endpoint, extra_path: extra_path, ids: ids\n query = Driver::Assemblers.query user: user, account_id: account_id, service: service, endpoint: endpoint, query: query, range: range\n\n query[:fields] = fields if Services[service].type == 'data' && fields\n\n request = Driver::Request.create(method: method, url: [host, path].join, query: query, headers: headers)\n request.call\n end",
"def perform(retrieval_id, base_url, cmr_env)\n # Using find_by because we obfuscate the id of Retrieval and the default\n # `find` method will look for an obfuscated id instead of the raw integer\n retrieval = Retrieval.find_by(id: retrieval_id)\n\n retrieval.collections.each do |collection_hash|\n # We only allow users to select 1 access method per collection now but the javascript has not been updated\n method = collection_hash.fetch('serviceOptions', {}).fetch('accessMethod', [])[0]\n\n # TODO: Rather than just 'skipping this collection, notify the user of\n # the error. NOTE that a user should not be able to make this happen\n next if method.blank?\n\n params = Rack::Utils.parse_nested_query(collection_hash['params'])\n params['temporal'] = params.delete('override_temporal') if params['override_temporal']\n params.reject! { |p| %w(datasource short_name).include?(p) }\n\n # We'll use RetrievalCollection to separate out each collection within the order\n retrieval_collection = RetrievalCollection.create!(\n retrieval_id: retrieval_id,\n collection_id: collection_hash['id'],\n access_method: method,\n granule_params: params\n )\n\n # Determines the number of granules requested adjusted for a defined maximum number\n granule_count = retrieval_collection.adjusted_granule_count\n\n # Split up large orders taking into account the limited granule collection tags\n page_size = retrieval_collection.max_order_size\n page_num = 0\n\n until page_num * page_size > granule_count\n page_num += 1\n\n params[:page_size] = page_size\n params[:page_num] = page_num\n\n if method['type'] == 'order'\n # `Stage For Delivery` Access Method\n legacy_services_order = LegacyServicesOrder.create(\n retrieval_collection: retrieval_collection,\n search_params: params\n )\n\n SubmitLegacyServicesJob.set(queue: queue_name).perform_later(\n legacy_services_order,\n cmr_env\n )\n elsif method['type'] == 'service'\n # `Customize` Access Method\n catalog_rest_order = CatalogRestOrder.create(\n retrieval_collection: retrieval_collection,\n search_params: params\n )\n\n SubmitCatalogRestJob.set(queue: queue_name).perform_later(\n catalog_rest_order,\n base_url\n )\n end\n end\n end\n end",
"def set_service_ids\n service_ids = FP::Vars.services_on_this_instance.join(',')\n Facter.add(:service_ids) { setcode { service_ids} }\nend",
"def get_related_basic_and_medicationknowledge(formulary_id, output_directory)\n p \"===============================================================\"\n p \"Getting all Basic and MedicationKnowledge related to Formulary with ID= #{formulary_id}...\"\n id_digits = formulary_id.split(\"-\").last\n basic_files = get_resource_json_files(\"output/Basic\").select { |f_name| f_name.include?(id_digits) }\n basic_resources = basic_files.map { |json_f| JSON.parse(File.read(json_f), symbolize_names: true) }\n # Get the reference ids to retrieve related medication_knowledge_resources\n ref_ids = basic_resources.map { |resource| resource[:id].split(\"-\").last }\n medication_knowledge_files = get_resource_json_files(\"output/MedicationKnowledge\").select { |f_name| ref_ids.any? { |id| f_name.include?(id) } }\n medication_knowledge_resources = medication_knowledge_files.map { |json_f| JSON.parse(File.read(json_f), symbolize_names: true) }\n\n p \"There are #{basic_resources.size} Basic resources and #{medication_knowledge_resources.size} MedicationKnowledge resources related to Formulary with ID = #{formulary_id}\"\n\n generate_ndjson(\"Basic\", basic_resources, output_directory)\n generate_ndjson(\"MedicationKnowledge\", medication_knowledge_resources, output_directory)\nend",
"def term_candidates(cyc_id)\n return @term_cache[cyc_id] unless @term_cache[cyc_id].nil?\n @term_cache[cyc_id] = create_candidate_set(\"\",[@name_service.find_by_id(cyc_id)])\n end",
"def list_collections manifest\n list = []\n\n manifest.collections.each do |pid|\n pidparts = pid.split(':')\n pid = pidparts[0].downcase + ':' + pidparts[1]\n list.push pid\n end\n\n return list\n end",
"def tags\n get.tagGuids\n end",
"def getCollections\n Community.getCollections(dso)\n end",
"def idl_includes(*incs)\n @recipe.idl_includes << incs.flatten.compact\n end",
"def service_provider_line_items(service_provider, items)\n service_provider_items = []\n items.map(&:sub_service_request_id).each do |ssr|\n if service_provider.identity.is_service_provider?(SubServiceRequest.find(ssr))\n service_provider_items << SubServiceRequest.find(ssr).line_items\n end\n end\n service_provider_items.flatten.uniq\n end",
"def resource_collection\n client.run_status.run_context.resource_collection\n end",
"def containers_ids\n containers(:response_format => :id_array)\n end",
"def get_feature_collection(params)\n http = Net::HTTP.new(@city_db_url, @port)\n http.read_timeout = 1000\n if @city_db_is_https\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n\n request = Net::HTTP::Post.new('/api/search.json')\n request.add_field('Content-Type', 'application/json')\n request.add_field('Accept', 'application/json')\n request.body = JSON.generate(params)\n request.basic_auth(ENV['URBANOPT_USERNAME'], ENV['URBANOPT_PASSWORD'])\n\n response = http.request(request)\n if response.code != '200' # success\n @runner.registerError(\"Bad response #{response.code}\")\n @runner.registerError(response.body)\n return {}\n end\n\n return JSON.parse(response.body, symbolize_names: true)\n end",
"def service\n @service ||= fetcher.get(Service, service_id)\n end"
] |
[
"0.67045355",
"0.5408727",
"0.52200097",
"0.5209009",
"0.5118803",
"0.5095901",
"0.5079721",
"0.5060224",
"0.4980422",
"0.4968335",
"0.492527",
"0.49205932",
"0.49064764",
"0.48901784",
"0.48868728",
"0.48775038",
"0.48773345",
"0.48670405",
"0.48604652",
"0.4857313",
"0.48411334",
"0.48272753",
"0.4805104",
"0.4802209",
"0.47963607",
"0.47930107",
"0.47674674",
"0.4766868",
"0.47605044",
"0.47504798",
"0.4749051",
"0.47426322",
"0.47329834",
"0.4724668",
"0.47228092",
"0.47197863",
"0.47114608",
"0.4702184",
"0.46922097",
"0.4675386",
"0.46660942",
"0.46645156",
"0.46615428",
"0.4660834",
"0.46582898",
"0.46569183",
"0.46563816",
"0.46523297",
"0.46368006",
"0.46366617",
"0.46195737",
"0.46186304",
"0.46178395",
"0.46115315",
"0.4611297",
"0.46039152",
"0.46034396",
"0.46024698",
"0.45958078",
"0.4592319",
"0.4588567",
"0.45837274",
"0.45837274",
"0.4583244",
"0.45768166",
"0.4573052",
"0.45704424",
"0.45591536",
"0.45542464",
"0.45520943",
"0.45511168",
"0.45496386",
"0.4548615",
"0.45406356",
"0.4537754",
"0.45368993",
"0.45279422",
"0.45268166",
"0.45250246",
"0.45205057",
"0.45141876",
"0.4513707",
"0.45088586",
"0.4508317",
"0.4507776",
"0.45034254",
"0.4502754",
"0.4493066",
"0.44919407",
"0.4483965",
"0.4482405",
"0.44821244",
"0.44734615",
"0.44728896",
"0.44712818",
"0.44675642",
"0.44670755",
"0.4467059",
"0.44654337",
"0.44651887"
] |
0.7808586
|
0
|
Delete the user's connections deletes all connections of the user given his hash
|
def hash_delete(opts = {})
hash_delete_with_http_info(opts)
nil
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def remove_connection\n\n\t\t# Set A and B\n\t\ta = self.current_user.id\n\t\tb = params[:user_id]\n\n\t\t# Delete both A -> B and B -> A (If we missed any duplicated records)\n\t\tConnection.where('(`owned_by` = ? && `user_id` = ?) || (`user_id` = ? && `owned_by` = ?)', a, b, a, b).each do |x|\n\t\t\tx.destroy\n\t\tend\n\t\t\n\t\t# Return to my connections\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to :my_connections }\n\t\tend\n\tend",
"def delete\n self.users.each do |id|\n user = User.find_by_id(id)\n next if user.nil?\n user.databases.delete(self._id)\n user.working_db_id = nil if user.working_db == self\n user.save\n end\n super\n end",
"def delete_all_active_connections\n super\n end",
"def delete_all_connections!\n @connections.each { |cnx| cnx.parent = nil }\n @connections = []\n end",
"def delete_user\n \tputs 'Delete user action'\n users = connection_store.collect_all(:chat_users)\n WebsocketRails[:chatroom].trigger(:client_disconnected, users.to_json) \n end",
"def deleteDisConUser(idUser,idChannel)\n \n begin\n query = \"DELETE FROM `#{DB_NAME}`.`#{USER_LIST_IN_CHAN_TABBLE}` WHERE `#{USER_LIST_IN_CHAN_TABBLE}`.`user_id_user` = ? AND `#{USER_LIST_IN_CHAN_TABBLE}`.`channel_id_channel` = ?\"\n queryReset = \"ALTER TABLE #{USER_LIST_IN_CHAN_TABBLE} AUTO_INCREMENT = 1\"\n self.connect unless self.connected? # => connect to the DB server if not connected\n sth = @dbh.prepare(query)\n sth.execute(idUser,idChannel)\n sth = @dbh.prepare(queryReset)\n sth.execute\n \n sth.finish\n rescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\n @dbh.rollback\n rescue Exception => e \n puts \"error!!! -> : #{e.to_s}\"\n \n ensure\n # disconnect from server\n @dbh.disconnect if @connected\n @connected=false\n end\n \n \n end",
"def delete_user\n print_status(\"Current MySQL Users & Host Info: \")\n query = @db.query('SELECT group_concat(0x0a,host,0x3a,user) FROM mysql.user;')\n query.each { |x| puts \"#{x[0]}\".white }\n print_line(\"\")\n user = Readline.readline(\"(Username to DROP)> \", true)\n host = Readline.readline(\"(Host Entry for #{user.chomp} to DROP)> \", true)\n answer = Readline.readline(\"(Confirm: DROP #{user.chomp}@#{host.chomp} (Y/N))> \", true)\n if \"#{answer.chomp.upcase}\" == \"YES\" or \"#{answer.chomp.upcase}\" == \"Y\"\n print_status(\"OK, sending DROP request.....\")\n begin\n query = @db_connection.query('USE mysql;')\n query = @db_connection.query(\"DROP USER '#{user.chomp}'@'#{host.chomp}';\")\n query = @db_connection.query('FLUSH PRIVILEGES;')\n rescue Mysql::Error => e\n print_error(\"Problem with DROP!\")\n print_error(\"#{e}\")\n end\n print_status(\"Updated MySQL Users & Host Info: \")\n query = @db.query('SELECT group_concat(0x0a,host,0x3a,user) FROM mysql.user;')\n query.each { |x| print_line(\"#{x[0]}\") }\n print_line(\"\")\n else\n print_error(\"OK, aborting User DROP and Returning to Main Menu...\")\n end\n end",
"def disconnect_all_users( msg )\n\t\t@users.each do |user|\n\t\t\t@reactor.unregister( user.socket )\n\t\t\tuser.disconnect( msg )\n\t\tend\n\t\t@users.clear\n\tend",
"def delete_users\n delete(users_path)\n end",
"def delete_active_connection\n super\n end",
"def delete(name)\n @connections.delete(name)\n end",
"def disconnect\n if @current_user.fitbit_user\n @current_user.fitbit_user.unsubscribe_from_notifications rescue nil\n #@current_user.fitbit_user.destroy (MySQL error when deleting from view... have to do it manually)\n ActiveRecord::Base.connection.execute \"delete from fbskeleton.fitbit_users where id = #{@current_user.fitbit_user.id}\"\n end\n\n # set it to nil if it is FITBIT\n @current_user.update_column(:active_device,nil) if @current_user.active_device == 'FITBIT'\n \n head :ok \n end",
"def disconnectAllUsers( msg )\n\t\t@users.each {|user|\n\t\t\t@reactor.unregister( user.socket )\n\t\t\tuser.disconnect( msg )\n\t\t}\n\t\t@users.clear\n\tend",
"def destroy\n @conn = current_user.conns.find(params[:id])\n @conn.destroy\n\n respond_to do |format|\n format.html { redirect_to conns_url }\n format.json { head :no_content }\n end\n end",
"def delete\n connection.delete_user id\n nil\n end",
"def destroy\n REDIS.srem REDIS_SET, @user.id\n self.class.broadcast\n end",
"def delete\n CONNECTION.execute(\"DELETE FROM users WHERE id = #{self.id};\")\n end",
"def delete\n\t\tcurrent_user\n\t\tcurrent_user.regexpressions.destroy_all\n\t\tcurrent_user.tasks.destroy_all\n\t\tcurrent_user.clouds.destroy_all\n\t\tcurrent_user.platforms.destroy_all\n\t\tcurrent_user.demos.destroy_all\n\t\tcurrent_user.favorites.destroy_all\n\tend",
"def purge_db\n\tUser.delete_all\n\tSubscription.delete_all\n\tDorkus.delete_all\nend",
"def delete_connections(id, connection_name, args = {}, options = {}, &block)\n # Deletes a given connection\n raise AuthenticationError.new(nil, nil, \"Delete requires an access token\") unless access_token\n graph_call(\"#{id}/#{connection_name}\", args, \"delete\", options, &block)\n end",
"def delete\n @linked_user.delete(@uri)\n end",
"def destroy\n ## 그동안 주고받았던 모든 쪽지를 지워야 계정이 삭제됨.\n Message.all.each do |x|\n if current_user.id == x.user_id\n x.destroy\n end\n end\n \n Conversation.all.each do |y|\n if current_user.id == y.sender_id\n y.destroy\n end\n end\n\n Post.all.where(user_id: current_user.id).each do |z|\n @post = Post.find(z.id)\n @post.update(user_id: 1)\n end\n\n Comment.all.where(user_id: current_user.id).each do |z|\n @comment = Comment.find(z.id)\n @comment.update(user_id: 1)\n end\n\n Invite.find_by(code: current_user.invite_code).destroy\n super\n end",
"def on_shutdown\n logger.debug \"Disconnecting user: #{@user} from channel: #{@channel}.\"\n @@connections[@channel].delete(@user)\n end",
"def remove(id, connection)\n found = find(id)\n\n if found.nil?\n return\n else\n @users[found[:index]][:connections].delete connection\n\n if @users[found[:index]][:connections].empty?\n @chat.root_room.shout Chat::Message.system(\"#{@users[found[:index]][:user].name} left\", @users[found[:index]][:user]).to_json\n @users.delete_at found[:index]\n else\n @chat.root_room.shout Chat::Message.system(\"#{@users[found[:index]][:user].name} left #{connection.room.identifier}\", @users[found[:index]][:user]).to_json\n end\n end\n end",
"def cdb_destroy\n couchdb.delete(\"webui_user\", @name, @couchdb_rev)\n end",
"def delete\n # no need to delete all the associations because root_folder.delete does it\n self.root_folder.delete self\n # remove all friendships where the user is the source\n Friendship.all(source_id: self.id).destroy!\n # remove all friendships where the user is the target\n Friendship.all(target_id: self.id).destroy!\n\n # remove all associations where this user receives a file >BY< another user\n SharedToMeAssociation.all(user_id: self.id).destroy!\n # remove all associations where this user shared a file >TO< another user\n SharedByMeAssociation.all(user_id: self.id).destroy!\n\n self.destroy!\n end",
"def disconnect!() @connections.each_value(&:disconnect) end",
"def unregister(uuid)\n if $connections.has_key? (@user.uuid)\n $connections.delete(@user.uuid)\n end\n end",
"def destroy\n conn.delete(self_link)\n end",
"def clear_active_connections!\n clear_cache!(@@active_connections) do |name, conn|\n conn.disconnect!\n end\n end",
"def delete\n Authentication.where(user_id: id).each { |auth| auth.delete }\n super\n end",
"def destroy\n transaction do\n clean\n connection.delete \"DELETE FROM user_subscriptions WHERE subscription_id = #{id}\"\n connection.delete \"DELETE FROM subscriptions WHERE id = #{id}\"\n end\n end",
"def remove_user(user)\n self.users.delete(user.user_id)\n user.databases.delete(self._id)\n self.save\n user.save\n end",
"def destroy_collaborated_wikis_before_delete\n #1 fetch list of wiki_ids for that the user is a collaborator on\n wiki_ids = $redis.smembers(self.collaborated_wikis_hash_key)\n #2 iterate over those wiki ids and remove instances where that user/wiki relationship exists\n #not sure about the below\n wiki_ids.each do |wiki_id|\n $redis.srem(Wiki.wiki_collaborators_hash_key(wiki_id), self.id)\n end\n $redis.del(self.collaborated_wikis_hash_key)\n end",
"def eliminar\n usuario = User.find(params[:id])\n usuario.bots.each {|bot|\n bot.palabras.destroy_all\n bot.botCiudads.destroy_all\n bot.tweets.destroy_all\n bot.destroy\n }\n usuario.destroy \n redirect_to(usuarios_path, :notice => \"Bot Eliminado\")\n end",
"def destroy_clients\n Client.destroy_all if has_different_client_uid?\n end",
"def delete_connection(relation_name, other_object, bidi)\n return Relation.delete(relation_name, self.node, other_object.node, bidi)\n end",
"def dropUserTable\n @conn.exec(\"DROPE users\")\n end",
"def clear_users\n @users = {}\n end",
"def clear_users\n @users = {}\n end",
"def delete_save(params, userid)\n db = connect()\n db.execute('DELETE FROM users_discussions WHERE UserId=? AND DiscId=?', userid, params[\"id\"])\n end",
"def destroy\n @user = User.find(params.require(:id))\n\n if @user == current_user\n flash[:alert] = t('users.msg.cannot_delete_yourself')\n raise 'Cannot delete yourself'\n end\n\n # delete user from zabbix\n begin\n @user.zabbix_servers.each do |s|\n z = Zabbix.new(s.fqdn, current_user.email, current_user.encrypted_password)\n z.delete_user(@user.email)\n end\n rescue StandardError => ex\n flash[:alert] = I18n.t('users.msg.error', msg: ex.message)\n raise\n end\n\n # delete user from SkyHopper\n @user.destroy\n\n flash[:notice] = t('users.msg.deleted', name: @user.email)\n redirect_to(action: :index)\n end",
"def delete_user nick\n $log.debug(\"Users.add_user\") { \"Removing user #{nick} on #{@connection.name}\" }\n\n delete nick\n end",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\t\tSite.where(:user_id => params[:id]).each do |site|\n\t\t\tsite.destroy\n\t\t\tputs \"chciałbym usunąć adres #{site.adres.to_yaml}\"\n\t\t\n\t\tend\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(users_url) }\n\t\t\tformat.xml\t{ head :ok }\n\t\tend\n\tend",
"def remove_users\r\n @userAdmin.destroy\r\n @user2.destroy\r\n @user3.destroy\r\n end",
"def delete_user(id)\n\n db = connect_to_db(\"db/db.db\")\n\n db.execute(\"DELETE FROM posts WHERE user_id = ?\", id)\n \n db.execute(\"DELETE FROM users WHERE id = ?\", id)\n\n end",
"def clear_reloadable_connections!\n if @@allow_concurrency\n # With concurrent connections @@active_connections is\n # a hash keyed by thread id.\n @@active_connections.each do |thread_id, conns|\n conns.each do |name, conn|\n if conn.requires_reloading?\n conn.disconnect!\n @@active_connections[thread_id].delete(name)\n end\n end\n end\n else\n @@active_connections.each do |name, conn|\n if conn.requires_reloading?\n conn.disconnect!\n @@active_connections.delete(name)\n end\n end\n end\n end",
"def disconnect!\n @reserved_connections.each do |name,conn|\n checkin conn\n end\n @reserved_connections = {}\n @connections.each do |conn|\n conn.disconnect!\n end\n @connections = []\n end",
"def delete_user\n client.delete(user)\n end",
"def delete_db_post account\n # Tell the user\n puts \"> Tar bort kontot från databasen\".green\n\n # Connect to the database\n conn = PG.connect( dbname: DB_DATABASE_NAME, user: DB_USER, password: DB_PASSWORD )\n\n # Delete the account\n res = conn.exec \"DELETE FROM #{DB_ACCOUNTS_TABLE} WHERE userid = '#{account['userid']}'\" unless $simulate\n\n # Close the connection\n conn.close\nend",
"def disconn(user_id)\r\n @waiting.delete(user_id)\r\n end",
"def delete_user(id)\n elektron_identity.delete(\"users/#{id}\")\n end",
"def delete\n DB.exec(\"DELETE FROM users WHERE id = #{@id};\")\n # DB.exec(\"DELETE FROM checkouts WHERE user_id = #{@id};\") --> delete books from users checkout history, but does not delete the books from the database??\n end",
"def delete_user\n end",
"def clear_reloadable_connections!\n @reserved_connections.each do |name, conn|\n checkin conn\n end\n @reserved_connections = {}\n @connections.each do |conn|\n conn.disconnect! if conn.requires_reloading?\n end\n @connections = []\n end",
"def delete\n TeamsUser.where(team_id: self.id).find_each(&:destroy)\n node = TeamNode.find_by(node_object_id: self.id)\n node.destroy if node\n self.destroy\n end",
"def destroy m\n\t\t@users[m.user.nick].destroy\n m.reply \"boom!\"\n end",
"def delete_state_for_user(opts = {})\n uri = \"/v3/botstate/#{opts['channel_id']}/users/#{opts['user_id']}\"\n api_delete(uri)\n end",
"def clear_all()\n User.destroy_all\n Hashtag.destroy_all\n Mention.destroy_all\n Tweet.destroy_all\n Follow.destroy_all\n # Hashtag_tweets.destroy_all\nend",
"def delete_all_users\n all_dns = []\n as_manager do | conn |\n conn.search(user_root_dn,\n LDAP::LDAP_SCOPE_SUBTREE,\n '(objectClass=inetOrgPerson)',\n %w{ cn }) do | entry |\n all_dns << entry.dn\n conn.delete(entry.dn)\n end\n end\n all_dns\n end",
"def deleteuser(del_id)\n db.execute(\"DELETE FROM users WHERE user_id=?\", del_id)\n db.execute(\"DELETE FROM listings WHERE user_id=?\", del_id)\nend",
"def destroy\n #since we have no id in user table, the usual @user.destroy will not work, since rails convention require each table to have id...thus we use delete_all , this is dangerous if we have no unique id\n @user = User.delete_all(:id => params[:id])\n \n redirect_to users_path, :notice => \"User telah berhasil di delete\"\n \n end",
"def delete_database\n options = {\n :query => {\n 'ZOHO_ACTION' => 'DELETEDATABASE',\n 'ZOHO_DATABASE_NAME' => database_name,\n }\n }\n send_request get_user_uri, 'post', options\n end",
"def clear_db\n\t\tdb = SQLite3::Database.open \"simpl.db\"\n\t\tdb.execute \"DELETE FROM user;\"\n\t\tdb.execute \"DELETE FROM merchant;\"\n\t\tdb.execute \"DELETE FROM transactions;\"\n\tend",
"def clear_db\n\t\tdb = SQLite3::Database.open \"simpl.db\"\n\t\tdb.execute \"DELETE FROM user;\"\n\t\tdb.execute \"DELETE FROM merchant;\"\n\t\tdb.execute \"DELETE FROM transactions;\"\n\tend",
"def destroy\n @user = User.find_by(uuid:params[:uuid])\n @user.characters.all.each do |x| x.destroy end\n @user.answers.all.each do |x| x.destroy end\n @user.destroy\n redirect_to users_path\n end",
"def delete_unused_host_only_networks\n end",
"def delete\r\n Marketplace::Database.instance.call_users(self)\r\n Marketplace::Database.instance.delete_user(self)\r\n ImageUploader.delete_image(self.picture, settings.root) if self.picture != nil\r\n items = Marketplace::Database.instance.items_by_user(self)\r\n items.each{ |item| item.delete }\r\n end",
"def delete_connection_user(connection_id, user_email)\n raise Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty?\n raise Auth0::InvalidParameter, 'Must supply a valid user email' if user_email.to_s.empty?\n path = \"#{connections_path}/#{connection_id}/users\"\n request_params = {\n email: user_email\n }\n delete(path, request_params)\n end",
"def delete_db_post\n # Tell the user\n puts \"> Tar bort aliaset från databasen\".green\n\n # Connect to the database\n conn = PG.connect( dbname: DB_DATABASE_NAME, user: DB_USER, password: DB_PASSWORD )\n\n # Delete the account\n res = conn.exec \"DELETE FROM #{DB_ALIAS_TABLE} WHERE address = '#{$alias}' AND userid = '#{$email}'\" unless $simulate\n\n # Close the connection\n conn.close\nend",
"def forget_everything\n empty_session!\n PersistentUser.new(@user).delete\n end",
"def disconnect_all\n @connections.clear\n @readers.clear\n end",
"def delete_by_id(user_id)\n Iterable.request(conf, \"/users/byUserId/#{user_id}\").delete\n end",
"def destroy\n HerosUsers.destroy_all(:user_id => @user.id)\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def obliterate()\n @@users_by_uid.delete(@uid)\n @@users_by_nick.delete(Channel.to_lower(@nick))\n part_all()\n end",
"def clear\n connections.synchronize do\n connections.map(&:last).each(&closer)\n connections.clear\n end\n end",
"def unconnect(args)\n raise ArgumentError, \"No object given.\" if !args[\"object\"]\n object = args[\"object\"].to_sym\n raise ArgumentError, \"Object doesnt exist: '#{object}'.\" if !@callbacks.key?(object)\n\n if args[\"conn_id\"]\n conn_ids = [args[\"conn_id\"]]\n elsif args[\"conn_ids\"]\n conn_ids = args[\"conn_ids\"]\n else\n raise ArgumentError, \"Could not figure out connection IDs.\"\n end\n\n conn_ids.each do |conn_id|\n raise Errno::ENOENT, \"Conn ID doest exist: '#{conn_id}' (#{args}).\" if !@callbacks[object].key?(conn_id)\n @callbacks[object].delete(conn_id)\n end\n end",
"def delete_tunnel\n super\n end",
"def destroy\n current_user.graph.destroy(current_user.id) if current_user\n super\n end",
"def remove_and_close(connection)\n @connections.delete(connection)\n close_connection(connection)\n end",
"def deleteUser(userInfo)\r\n\t\tnum = 0\r\n\t\tuser_id = 0\r\n\t\tuserInfo.each_pair { | name, value |\r\n\t\t\tif(name == \"user_id\")\r\n\t\t\t\tuser_id = value\r\n\t\t\telse\r\n\t\t\t\tputs \"wrong parameter: #{name}\"\r\n\t\t\t\treturn \"wrong parameter: #{name}\"\r\n\t\t\tend\t\t\t\t\r\n\t\t}\r\n\r\n\t\tputs \"Connecting to database...\"\r\n\t\tbegin\r\n\t\t\t# connect to the MySQL server\r\n\t\t\tdbh = DBI.connect(\"DBI:Mysql:#{$db}:#{$db_ip}\",\"#{$user}\", \"#{$pass}\")\r\n\t\t\t\r\n\t\t\tnum = dbh.do(\"DELETE FROM nitlab.b9tj1_users WHERE id = '#{user_id}' AND id!='62'\")\r\n\t\t\tif (num == 1)\r\n\t\t\t\tputs \"User deleted...\"\r\n\t\t\t\treturn 0\r\n\t\t\tend\r\n\t\t\t\r\n\t\trescue DBI::DatabaseError => e\r\n\t\t\tputs \"An error occurred\"\r\n\t\t\tputs \"Error code: #{e.err}\"\r\n\t\t\tputs \"Error message: #{e.errstr}\"\r\n\t\tensure\r\n\t\t\t# disconnect from server\r\n\t\t\tdbh.disconnect if dbh\r\n\t\tend\r\n\t\t\t\r\n\t\treturn -1\r\n\tend",
"def destroy_suggested_connections(connecter_id, connectee_id)\n connection_ids = [connecter_id, connectee_id]\n suggested_connection_ids = SuggestedConnection.where(user_id: connection_ids, connectee_id: connection_ids).pluck('id')\n suggested_connection_ids.each do |id|\n SuggestedConnection.destroy(id)\n end\n end",
"def destroy\n\t\t@user.delete\n\tend",
"def Elimina_Utente()\n Category.delete_all(user_id: self.id)\n Dish.delete_all(user_id: self.id)\n Ingredient.delete_all(user_id: self.id)\n Medium.destroy_all(user_id: self.id)\n Menu.delete_all(user_id: self.id)\n Profile.destroy_all(user_id: self.id)\n self.destroy()\n end",
"def destroy\n @connection.destroy\n respond_to do |format|\n format.html { redirect_to connections_url }\n format.json { head :no_content }\n end\n end",
"def delete_user(username)\n\t\t\t\t@session['datastore'][username] = nil\n\t\t\tend",
"def destroy_users\n user = User.find(params[:id])\n \n # Delete user\n user.destroy\n\n # Sign out of any machines user is on\n Devise.sign_out_all_scopes ? sign_out : sign_out(:user)\n set_flash_message! :notice, :destroyed\n \n @users = User.all\n render \"manage\"\n end",
"def destroy\n @cu = User.find_by(id: current_user.id)\n deleteAll(@cu.events)\n deleteAll(@cu.notifications)\n deleteAll(Notification.where(notification_type: 1, sender_id: @cu.id))\n deleteAll(Notification.where(notification_type: 2, sender_id: @cu.id))\n deleteAll(Attending.where(user_id: @cu.id))\n deleteAll(Comment.where(user_id: @cu.id))\n deleteAll(Review.where(user_id: @cu.id))\n deleteAll(Friend.where(user_id: @cu.id))\n deleteAll(Friend.where(friend_id: @cu.id))\n \n #delete account with devise method\n resource.destroy\n Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)\n set_flash_message! :notice, :destroyed\n yield resource if block_given?\n respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }\n end",
"def remove_everything_about_testuser\n list_of_activerecords = [\n Follow.find_by(leader_id: TESTUSER_ID),\n Follow.find_by(user_id: TESTUSER_ID),\n Mention.find_by(username: TESTUSER_NAME),\n Tweet.find_by(user_id: TESTUSER_ID),\n User.find_by(username: TESTUSER_NAME)\n ]\n list_of_activerecords.each { |ar| destroy_and_save(ar) }\nend",
"def destroy\n @user = User.find(params.require(:id))\n\n # delete user from zabbix\n z = @zabbix\n begin\n z.delete_user(@user.email)\n rescue => ex\n flash[:alert] = \"Zabbix 処理中にエラーが発生しました #{ex.message}\"\n redirect_to(action: :index) and return\n end\n\n #delete user from SkyHopper\n @user.destroy\n\n flash[:notice] = I18n.t('users.msg.deleted')\n redirect_to(action: :index)\n end",
"def destroy\n @users_db.destroy\n respond_to do |format|\n format.html { redirect_to users_dbs_url, notice: 'Users db was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n connection.close\n end",
"def destroy\n begin\n client = DiscourseApi::Client.new(\"https://intranet.cuhappycorner.com\")\n client.api_key = \"1729b13700d45e58d2e3d81c1bee5431a5167244e75389c07bb613fae54777ee\"\n client.api_username = \"ckho\"\n user = client.by_external_id(current_user.id)\n client.log_out(user[\"id\"]) if user\n rescue\n # nothing\n ensure\n super\n end\n end",
"def purge\n @user.destroy\n redirect_to admin_users_path\n end",
"def destroy\n @user = User.find(params[:id])\n\n post = Post.find(:all, :conditions => [\"user_id = ?\", @user.id])\n for n in 0 ... post.size do\n Post.destroyCascade(post[n])\n end\n\n vote = Vote.find(:all, :conditions => [\"user_id = ?\", @user.id])\n for n in 0 ... vote.size do\n Vote.destroyCascade(vote[n])\n end\n comment = Comment.find(:all, :conditions => [\"user_id = ?\", @user.id])\n for n in 0 ... comment.size do\n Comment.destroyCascade(comment[n])\n end\n commentvote = CommentVote.find(:all, :conditions => [\"user_id = ?\", @user.id])\n for n in 0 ... commentvote.size do\n CommentVote.destroyCascade(commentvote[n])\n end\n\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :ok }\n end\n end",
"def delete(connection)\n @streams[connection.class.to_s].delete(connection)\n end",
"def delete nick\n\t\t@users.delete ['nick', nick]\n\tend",
"def disconnect\n disconnect_all\n end",
"def remove_connection\n flash[:notice] = I18n.t(:remove_social_connection)\n\t Authentication.remove_conn(current_gamer.id, params[:provider])\n\t redirect_to \"/gamers/edit\"\n\tend",
"def clear_all_in_database\n Tweet.destroy_all\n User.destroy_all\n Follow.destroy_all\n end",
"def clear_all_in_database\n Tweet.destroy_all\n User.destroy_all\n Follow.destroy_all\n end"
] |
[
"0.7291358",
"0.7119551",
"0.70424676",
"0.69227475",
"0.68673384",
"0.6829997",
"0.6545845",
"0.64653",
"0.64640343",
"0.64288175",
"0.6352213",
"0.6336974",
"0.63357735",
"0.6302564",
"0.62957335",
"0.627434",
"0.62651306",
"0.6263058",
"0.62563527",
"0.62464637",
"0.62413245",
"0.62386596",
"0.6218966",
"0.6212931",
"0.61813873",
"0.6172093",
"0.6135141",
"0.61101115",
"0.6096085",
"0.6092293",
"0.6064382",
"0.6051176",
"0.60431975",
"0.6041507",
"0.6031509",
"0.6014791",
"0.6004922",
"0.59909207",
"0.59803826",
"0.59711164",
"0.5956004",
"0.59478015",
"0.594317",
"0.5942372",
"0.5930077",
"0.59288406",
"0.5913405",
"0.5907036",
"0.5899946",
"0.5899364",
"0.5882862",
"0.58811176",
"0.58668524",
"0.58592856",
"0.5846489",
"0.58451474",
"0.58438814",
"0.58354795",
"0.5820298",
"0.58112335",
"0.58100295",
"0.5809221",
"0.5808271",
"0.58020353",
"0.58020353",
"0.57829595",
"0.5780508",
"0.57772684",
"0.57622594",
"0.575775",
"0.5742452",
"0.57357",
"0.57343096",
"0.57310724",
"0.5723058",
"0.5721803",
"0.5721447",
"0.5716536",
"0.571626",
"0.5711135",
"0.5710437",
"0.57098585",
"0.57075673",
"0.570406",
"0.57039165",
"0.5702355",
"0.56992316",
"0.569847",
"0.5696314",
"0.56958157",
"0.568098",
"0.56788933",
"0.56746703",
"0.5673599",
"0.56696755",
"0.56627566",
"0.563639",
"0.56317306",
"0.562677",
"0.56219155",
"0.56219155"
] |
0.0
|
-1
|
Delete the user&39;s connections deletes all connections of the user given his hash
|
def hash_delete_with_http_info(opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersManagementApi.hash_delete ...'
end
# resource path
local_var_path = '/hash'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['api_key']
data, status_code, headers = @api_client.call_api(:DELETE, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersManagementApi#hash_delete\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def remove_connection\n\n\t\t# Set A and B\n\t\ta = self.current_user.id\n\t\tb = params[:user_id]\n\n\t\t# Delete both A -> B and B -> A (If we missed any duplicated records)\n\t\tConnection.where('(`owned_by` = ? && `user_id` = ?) || (`user_id` = ? && `owned_by` = ?)', a, b, a, b).each do |x|\n\t\t\tx.destroy\n\t\tend\n\t\t\n\t\t# Return to my connections\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to :my_connections }\n\t\tend\n\tend",
"def delete_user\n \tputs 'Delete user action'\n users = connection_store.collect_all(:chat_users)\n WebsocketRails[:chatroom].trigger(:client_disconnected, users.to_json) \n end",
"def deleteDisConUser(idUser,idChannel)\n \n begin\n query = \"DELETE FROM `#{DB_NAME}`.`#{USER_LIST_IN_CHAN_TABBLE}` WHERE `#{USER_LIST_IN_CHAN_TABBLE}`.`user_id_user` = ? AND `#{USER_LIST_IN_CHAN_TABBLE}`.`channel_id_channel` = ?\"\n queryReset = \"ALTER TABLE #{USER_LIST_IN_CHAN_TABBLE} AUTO_INCREMENT = 1\"\n self.connect unless self.connected? # => connect to the DB server if not connected\n sth = @dbh.prepare(query)\n sth.execute(idUser,idChannel)\n sth = @dbh.prepare(queryReset)\n sth.execute\n \n sth.finish\n rescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\n @dbh.rollback\n rescue Exception => e \n puts \"error!!! -> : #{e.to_s}\"\n \n ensure\n # disconnect from server\n @dbh.disconnect if @connected\n @connected=false\n end\n \n \n end",
"def delete\n self.users.each do |id|\n user = User.find_by_id(id)\n next if user.nil?\n user.databases.delete(self._id)\n user.working_db_id = nil if user.working_db == self\n user.save\n end\n super\n end",
"def delete_user\n print_status(\"Current MySQL Users & Host Info: \")\n query = @db.query('SELECT group_concat(0x0a,host,0x3a,user) FROM mysql.user;')\n query.each { |x| puts \"#{x[0]}\".white }\n print_line(\"\")\n user = Readline.readline(\"(Username to DROP)> \", true)\n host = Readline.readline(\"(Host Entry for #{user.chomp} to DROP)> \", true)\n answer = Readline.readline(\"(Confirm: DROP #{user.chomp}@#{host.chomp} (Y/N))> \", true)\n if \"#{answer.chomp.upcase}\" == \"YES\" or \"#{answer.chomp.upcase}\" == \"Y\"\n print_status(\"OK, sending DROP request.....\")\n begin\n query = @db_connection.query('USE mysql;')\n query = @db_connection.query(\"DROP USER '#{user.chomp}'@'#{host.chomp}';\")\n query = @db_connection.query('FLUSH PRIVILEGES;')\n rescue Mysql::Error => e\n print_error(\"Problem with DROP!\")\n print_error(\"#{e}\")\n end\n print_status(\"Updated MySQL Users & Host Info: \")\n query = @db.query('SELECT group_concat(0x0a,host,0x3a,user) FROM mysql.user;')\n query.each { |x| print_line(\"#{x[0]}\") }\n print_line(\"\")\n else\n print_error(\"OK, aborting User DROP and Returning to Main Menu...\")\n end\n end",
"def delete_all_active_connections\n super\n end",
"def delete_all_connections!\n @connections.each { |cnx| cnx.parent = nil }\n @connections = []\n end",
"def delete\n connection.delete_user id\n nil\n end",
"def delete\n CONNECTION.execute(\"DELETE FROM users WHERE id = #{self.id};\")\n end",
"def destroy\n @conn = current_user.conns.find(params[:id])\n @conn.destroy\n\n respond_to do |format|\n format.html { redirect_to conns_url }\n format.json { head :no_content }\n end\n end",
"def delete_users\n delete(users_path)\n end",
"def delete\n @linked_user.delete(@uri)\n end",
"def disconnect_all_users( msg )\n\t\t@users.each do |user|\n\t\t\t@reactor.unregister( user.socket )\n\t\t\tuser.disconnect( msg )\n\t\tend\n\t\t@users.clear\n\tend",
"def delete(name)\n @connections.delete(name)\n end",
"def cdb_destroy\n couchdb.delete(\"webui_user\", @name, @couchdb_rev)\n end",
"def disconnect\n if @current_user.fitbit_user\n @current_user.fitbit_user.unsubscribe_from_notifications rescue nil\n #@current_user.fitbit_user.destroy (MySQL error when deleting from view... have to do it manually)\n ActiveRecord::Base.connection.execute \"delete from fbskeleton.fitbit_users where id = #{@current_user.fitbit_user.id}\"\n end\n\n # set it to nil if it is FITBIT\n @current_user.update_column(:active_device,nil) if @current_user.active_device == 'FITBIT'\n \n head :ok \n end",
"def disconnectAllUsers( msg )\n\t\t@users.each {|user|\n\t\t\t@reactor.unregister( user.socket )\n\t\t\tuser.disconnect( msg )\n\t\t}\n\t\t@users.clear\n\tend",
"def remove(id, connection)\n found = find(id)\n\n if found.nil?\n return\n else\n @users[found[:index]][:connections].delete connection\n\n if @users[found[:index]][:connections].empty?\n @chat.root_room.shout Chat::Message.system(\"#{@users[found[:index]][:user].name} left\", @users[found[:index]][:user]).to_json\n @users.delete_at found[:index]\n else\n @chat.root_room.shout Chat::Message.system(\"#{@users[found[:index]][:user].name} left #{connection.room.identifier}\", @users[found[:index]][:user]).to_json\n end\n end\n end",
"def delete_active_connection\n super\n end",
"def delete_connections(id, connection_name, args = {}, options = {}, &block)\n # Deletes a given connection\n raise AuthenticationError.new(nil, nil, \"Delete requires an access token\") unless access_token\n graph_call(\"#{id}/#{connection_name}\", args, \"delete\", options, &block)\n end",
"def delete_user nick\n $log.debug(\"Users.add_user\") { \"Removing user #{nick} on #{@connection.name}\" }\n\n delete nick\n end",
"def destroy\n REDIS.srem REDIS_SET, @user.id\n self.class.broadcast\n end",
"def on_shutdown\n logger.debug \"Disconnecting user: #{@user} from channel: #{@channel}.\"\n @@connections[@channel].delete(@user)\n end",
"def delete\n\t\tcurrent_user\n\t\tcurrent_user.regexpressions.destroy_all\n\t\tcurrent_user.tasks.destroy_all\n\t\tcurrent_user.clouds.destroy_all\n\t\tcurrent_user.platforms.destroy_all\n\t\tcurrent_user.demos.destroy_all\n\t\tcurrent_user.favorites.destroy_all\n\tend",
"def delete_save(params, userid)\n db = connect()\n db.execute('DELETE FROM users_discussions WHERE UserId=? AND DiscId=?', userid, params[\"id\"])\n end",
"def destroy\n conn.delete(self_link)\n end",
"def delete_user\n end",
"def delete_connection(relation_name, other_object, bidi)\n return Relation.delete(relation_name, self.node, other_object.node, bidi)\n end",
"def delete_user\n client.delete(user)\n end",
"def delete_user(id)\n elektron_identity.delete(\"users/#{id}\")\n end",
"def destroy\n @user = User.find(params.require(:id))\n\n if @user == current_user\n flash[:alert] = t('users.msg.cannot_delete_yourself')\n raise 'Cannot delete yourself'\n end\n\n # delete user from zabbix\n begin\n @user.zabbix_servers.each do |s|\n z = Zabbix.new(s.fqdn, current_user.email, current_user.encrypted_password)\n z.delete_user(@user.email)\n end\n rescue StandardError => ex\n flash[:alert] = I18n.t('users.msg.error', msg: ex.message)\n raise\n end\n\n # delete user from SkyHopper\n @user.destroy\n\n flash[:notice] = t('users.msg.deleted', name: @user.email)\n redirect_to(action: :index)\n end",
"def dropUserTable\n @conn.exec(\"DROPE users\")\n end",
"def delete_user(id)\n\n db = connect_to_db(\"db/db.db\")\n\n db.execute(\"DELETE FROM posts WHERE user_id = ?\", id)\n \n db.execute(\"DELETE FROM users WHERE id = ?\", id)\n\n end",
"def unregister(uuid)\n if $connections.has_key? (@user.uuid)\n $connections.delete(@user.uuid)\n end\n end",
"def delete_db_post account\n # Tell the user\n puts \"> Tar bort kontot från databasen\".green\n\n # Connect to the database\n conn = PG.connect( dbname: DB_DATABASE_NAME, user: DB_USER, password: DB_PASSWORD )\n\n # Delete the account\n res = conn.exec \"DELETE FROM #{DB_ACCOUNTS_TABLE} WHERE userid = '#{account['userid']}'\" unless $simulate\n\n # Close the connection\n conn.close\nend",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\t\tSite.where(:user_id => params[:id]).each do |site|\n\t\t\tsite.destroy\n\t\t\tputs \"chciałbym usunąć adres #{site.adres.to_yaml}\"\n\t\t\n\t\tend\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(users_url) }\n\t\t\tformat.xml\t{ head :ok }\n\t\tend\n\tend",
"def destroy\n ## 그동안 주고받았던 모든 쪽지를 지워야 계정이 삭제됨.\n Message.all.each do |x|\n if current_user.id == x.user_id\n x.destroy\n end\n end\n \n Conversation.all.each do |y|\n if current_user.id == y.sender_id\n y.destroy\n end\n end\n\n Post.all.where(user_id: current_user.id).each do |z|\n @post = Post.find(z.id)\n @post.update(user_id: 1)\n end\n\n Comment.all.where(user_id: current_user.id).each do |z|\n @comment = Comment.find(z.id)\n @comment.update(user_id: 1)\n end\n\n Invite.find_by(code: current_user.invite_code).destroy\n super\n end",
"def delete_user(username)\n\t\t\t\t@session['datastore'][username] = nil\n\t\t\tend",
"def delete_state_for_user(opts = {})\n uri = \"/v3/botstate/#{opts['channel_id']}/users/#{opts['user_id']}\"\n api_delete(uri)\n end",
"def disconnect!() @connections.each_value(&:disconnect) end",
"def delete_database\n options = {\n :query => {\n 'ZOHO_ACTION' => 'DELETEDATABASE',\n 'ZOHO_DATABASE_NAME' => database_name,\n }\n }\n send_request get_user_uri, 'post', options\n end",
"def delete nick\n\t\t@users.delete ['nick', nick]\n\tend",
"def deleteUser(userInfo)\r\n\t\tnum = 0\r\n\t\tuser_id = 0\r\n\t\tuserInfo.each_pair { | name, value |\r\n\t\t\tif(name == \"user_id\")\r\n\t\t\t\tuser_id = value\r\n\t\t\telse\r\n\t\t\t\tputs \"wrong parameter: #{name}\"\r\n\t\t\t\treturn \"wrong parameter: #{name}\"\r\n\t\t\tend\t\t\t\t\r\n\t\t}\r\n\r\n\t\tputs \"Connecting to database...\"\r\n\t\tbegin\r\n\t\t\t# connect to the MySQL server\r\n\t\t\tdbh = DBI.connect(\"DBI:Mysql:#{$db}:#{$db_ip}\",\"#{$user}\", \"#{$pass}\")\r\n\t\t\t\r\n\t\t\tnum = dbh.do(\"DELETE FROM nitlab.b9tj1_users WHERE id = '#{user_id}' AND id!='62'\")\r\n\t\t\tif (num == 1)\r\n\t\t\t\tputs \"User deleted...\"\r\n\t\t\t\treturn 0\r\n\t\t\tend\r\n\t\t\t\r\n\t\trescue DBI::DatabaseError => e\r\n\t\t\tputs \"An error occurred\"\r\n\t\t\tputs \"Error code: #{e.err}\"\r\n\t\t\tputs \"Error message: #{e.errstr}\"\r\n\t\tensure\r\n\t\t\t# disconnect from server\r\n\t\t\tdbh.disconnect if dbh\r\n\t\tend\r\n\t\t\t\r\n\t\treturn -1\r\n\tend",
"def destroy_clients\n Client.destroy_all if has_different_client_uid?\n end",
"def delete\n Authentication.where(user_id: id).each { |auth| auth.delete }\n super\n end",
"def delete_user(username, removehome=false)\n\t\t\tend",
"def deleteuser(del_id)\n db.execute(\"DELETE FROM users WHERE user_id=?\", del_id)\n db.execute(\"DELETE FROM listings WHERE user_id=?\", del_id)\nend",
"def purge_db\n\tUser.delete_all\n\tSubscription.delete_all\n\tDorkus.delete_all\nend",
"def destroy m\n\t\t@users[m.user.nick].destroy\n m.reply \"boom!\"\n end",
"def eliminar\n usuario = User.find(params[:id])\n usuario.bots.each {|bot|\n bot.palabras.destroy_all\n bot.botCiudads.destroy_all\n bot.tweets.destroy_all\n bot.destroy\n }\n usuario.destroy \n redirect_to(usuarios_path, :notice => \"Bot Eliminado\")\n end",
"def destroy\n transaction do\n clean\n connection.delete \"DELETE FROM user_subscriptions WHERE subscription_id = #{id}\"\n connection.delete \"DELETE FROM subscriptions WHERE id = #{id}\"\n end\n end",
"def destroy_collaborated_wikis_before_delete\n #1 fetch list of wiki_ids for that the user is a collaborator on\n wiki_ids = $redis.smembers(self.collaborated_wikis_hash_key)\n #2 iterate over those wiki ids and remove instances where that user/wiki relationship exists\n #not sure about the below\n wiki_ids.each do |wiki_id|\n $redis.srem(Wiki.wiki_collaborators_hash_key(wiki_id), self.id)\n end\n $redis.del(self.collaborated_wikis_hash_key)\n end",
"def delete_connection_user(connection_id, user_email)\n raise Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty?\n raise Auth0::InvalidParameter, 'Must supply a valid user email' if user_email.to_s.empty?\n path = \"#{connections_path}/#{connection_id}/users\"\n request_params = {\n email: user_email\n }\n delete(path, request_params)\n end",
"def disconn(user_id)\r\n @waiting.delete(user_id)\r\n end",
"def delete\n # no need to delete all the associations because root_folder.delete does it\n self.root_folder.delete self\n # remove all friendships where the user is the source\n Friendship.all(source_id: self.id).destroy!\n # remove all friendships where the user is the target\n Friendship.all(target_id: self.id).destroy!\n\n # remove all associations where this user receives a file >BY< another user\n SharedToMeAssociation.all(user_id: self.id).destroy!\n # remove all associations where this user shared a file >TO< another user\n SharedByMeAssociation.all(user_id: self.id).destroy!\n\n self.destroy!\n end",
"def delete_db_post\n # Tell the user\n puts \"> Tar bort aliaset från databasen\".green\n\n # Connect to the database\n conn = PG.connect( dbname: DB_DATABASE_NAME, user: DB_USER, password: DB_PASSWORD )\n\n # Delete the account\n res = conn.exec \"DELETE FROM #{DB_ALIAS_TABLE} WHERE address = '#{$alias}' AND userid = '#{$email}'\" unless $simulate\n\n # Close the connection\n conn.close\nend",
"def remove_user(user)\n self.users.delete(user.user_id)\n user.databases.delete(self._id)\n self.save\n user.save\n end",
"def clear_users\n @users = {}\n end",
"def destroy\n HerosUsers.destroy_all(:user_id => @user.id)\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find_by(uuid:params[:uuid])\n @user.characters.all.each do |x| x.destroy end\n @user.answers.all.each do |x| x.destroy end\n @user.destroy\n redirect_to users_path\n end",
"def clear_users\n @users = {}\n end",
"def destroy\n @users_db.destroy\n respond_to do |format|\n format.html { redirect_to users_dbs_url, notice: 'Users db was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete\n DB.exec(\"DELETE FROM users WHERE id = #{@id};\")\n # DB.exec(\"DELETE FROM checkouts WHERE user_id = #{@id};\") --> delete books from users checkout history, but does not delete the books from the database??\n end",
"def delete\n TeamsUser.where(team_id: self.id).find_each(&:destroy)\n node = TeamNode.find_by(node_object_id: self.id)\n node.destroy if node\n self.destroy\n end",
"def delete_all_users\n all_dns = []\n as_manager do | conn |\n conn.search(user_root_dn,\n LDAP::LDAP_SCOPE_SUBTREE,\n '(objectClass=inetOrgPerson)',\n %w{ cn }) do | entry |\n all_dns << entry.dn\n conn.delete(entry.dn)\n end\n end\n all_dns\n end",
"def remove_users\r\n @userAdmin.destroy\r\n @user2.destroy\r\n @user3.destroy\r\n end",
"def delete\r\n Marketplace::Database.instance.call_users(self)\r\n Marketplace::Database.instance.delete_user(self)\r\n ImageUploader.delete_image(self.picture, settings.root) if self.picture != nil\r\n items = Marketplace::Database.instance.items_by_user(self)\r\n items.each{ |item| item.delete }\r\n end",
"def obliterate()\n @@users_by_uid.delete(@uid)\n @@users_by_nick.delete(Channel.to_lower(@nick))\n part_all()\n end",
"def delete_user (db, user_name)\n\tdb.execute(\"DELETE FROM users WHERE user_name=?\", [user_name])\nend",
"def destroy\n #since we have no id in user table, the usual @user.destroy will not work, since rails convention require each table to have id...thus we use delete_all , this is dangerous if we have no unique id\n @user = User.delete_all(:id => params[:id])\n \n redirect_to users_path, :notice => \"User telah berhasil di delete\"\n \n end",
"def clear_active_connections!\n clear_cache!(@@active_connections) do |name, conn|\n conn.disconnect!\n end\n end",
"def delete_user(userid) \n $db.execute('DELETE FROM users WHERE userid=?', userid)\n end",
"def destroy\n @connection.destroy\n respond_to do |format|\n format.html { redirect_to connections_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find(params.require(:id))\n\n # delete user from zabbix\n z = @zabbix\n begin\n z.delete_user(@user.email)\n rescue => ex\n flash[:alert] = \"Zabbix 処理中にエラーが発生しました #{ex.message}\"\n redirect_to(action: :index) and return\n end\n\n #delete user from SkyHopper\n @user.destroy\n\n flash[:notice] = I18n.t('users.msg.deleted')\n redirect_to(action: :index)\n end",
"def delete_user\n system('clear')\n puts \"Type \" + \"DELETE\".red.underline + \" if you are sure you want to delete #{self.name}?\"\n puts \"User any other input to return to menu\\n\\n\"\n print \">> \"\n confirm = gets.chomp\n system('clear')\n if confirm.downcase == \"delete\"\n GameSession.all.each do |game|\n if game.user_id == self.id\n game.destroy\n end\n end\n self.destroy\n puts \"Your username has been deleted.\"\n end_program\n else\n menu(self)\n end\n end",
"def delete_by_id(user_id)\n Iterable.request(conf, \"/users/byUserId/#{user_id}\").delete\n end",
"def destroy\n current_user.graph.destroy(current_user.id) if current_user\n super\n end",
"def disconnect!\n @reserved_connections.each do |name,conn|\n checkin conn\n end\n @reserved_connections = {}\n @connections.each do |conn|\n conn.disconnect!\n end\n @connections = []\n end",
"def delete_user(user_id:, params:)\n connection.delete(\"users/#{user_id}\", params).body\n end",
"def destroy_users\n user = User.find(params[:id])\n \n # Delete user\n user.destroy\n\n # Sign out of any machines user is on\n Devise.sign_out_all_scopes ? sign_out : sign_out(:user)\n set_flash_message! :notice, :destroyed\n \n @users = User.all\n render \"manage\"\n end",
"def delete\n CONNECTION.execute(\"DELETE FROM links WHERE id = #{self.id};\")\n end",
"def destroy\n\t\t@user.delete\n\tend",
"def destroy\n begin\n client = DiscourseApi::Client.new(\"https://intranet.cuhappycorner.com\")\n client.api_key = \"1729b13700d45e58d2e3d81c1bee5431a5167244e75389c07bb613fae54777ee\"\n client.api_username = \"ckho\"\n user = client.by_external_id(current_user.id)\n client.log_out(user[\"id\"]) if user\n rescue\n # nothing\n ensure\n super\n end\n end",
"def remove_connection\n flash[:notice] = I18n.t(:remove_social_connection)\n\t Authentication.remove_conn(current_gamer.id, params[:provider])\n\t redirect_to \"/gamers/edit\"\n\tend",
"def destroy\r\n\t\t\tif @user != nil\r\n\t\t\t\t@user.quit\r\n\t\t\tend\r\n\t\t\tsuper\r\n\t\tend",
"def delete\n appctrl_delete( 'User' )\n end",
"def destroy\n @connpass.destroy\n respond_to do |format|\n format.html { redirect_to connpasses_url, notice: 'Connpass was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete_user_account\n # delete their favorites before deleting user\n # list_to_delete = Favorite.where(user_id:current_user.id)\n binding.pry\n User.all.destroy(current_user.id)\n puts \"Your account have been removed! I will never tell, xoxo\"\n end",
"def destroy\n @connection = Connection.find(params[:id])\n @connection.destroy\n\n respond_to do |format|\n format.html { redirect_to connections_url }\n format.json { head :ok }\n end\n end",
"def destroy_user(id)\n #TODO:\n # ADD SOME USER LEVEL TO AVOID THESE\n end",
"def local_remove(body)\n key_hash = _user_keyhash(body)\n raise \"Invalid username\" unless key_hash\n raise \"That user is signed in!\" if @var[:presence][key_hash]\n @connection.comm.rsa_keys.delete(body)\n @connection.comm.names.delete(key_hash)\n @var[:user_keys].delete body\n _save_env\n _notice \"User '#{body}' has been removed from your key repository\"\nend",
"def logout\n $redis.del \"userhash:#{session['userhash']}\"\n session['userhash']=nil\n session['user']=nil\n end",
"def deleteUserSocial_network( user_id, social_network)\n params = Hash.new\n params['user_id'] = user_id\n params['social_network'] = social_network\n return doCurl(\"delete\",\"/user/social_network\",params)\n end",
"def destroy_suggested_connections(connecter_id, connectee_id)\n connection_ids = [connecter_id, connectee_id]\n suggested_connection_ids = SuggestedConnection.where(user_id: connection_ids, connectee_id: connection_ids).pluck('id')\n suggested_connection_ids.each do |id|\n SuggestedConnection.destroy(id)\n end\n end",
"def user_delete(user_id)\n\t\tdelete_call = Curl::Easy.http_delete(\"#{@ip_address}:#{@port_2}/v2.0/users/#{user_id}\"\n\t\t) do |curl|\n\t\t\tcurl.headers['x-auth-token'] = @token\n\t\t\tcurl.headers['userId'] = user_id\n\t\tend\n\t\n\tend",
"def delete_user_account\n # delete their favorites before deleting user\n User.all.destroy(current_user.id)\n puts \"\n Your account have been removed! I will never tell, xoxo\n \"\n \n end",
"def delete_account\n @connection.request({\n :method => 'DELETE'\n }) \n end",
"def destroy\n @user_trick.destroy\n end",
"def Elimina_Utente()\n Category.delete_all(user_id: self.id)\n Dish.delete_all(user_id: self.id)\n Ingredient.delete_all(user_id: self.id)\n Medium.destroy_all(user_id: self.id)\n Menu.delete_all(user_id: self.id)\n Profile.destroy_all(user_id: self.id)\n self.destroy()\n end",
"def purge\n @user.destroy\n redirect_to admin_users_path\n end",
"def destroy\n @connection = Connection.find(params[:id])\n @connection.destroy\n\n respond_to do |format|\n format.html { redirect_to connections_url }\n format.json { head :no_content }\n end\n end"
] |
[
"0.71147436",
"0.7039122",
"0.684653",
"0.6843536",
"0.6751942",
"0.6667826",
"0.6588732",
"0.6472285",
"0.64481276",
"0.64242244",
"0.6418976",
"0.6407883",
"0.6344136",
"0.6292175",
"0.6284981",
"0.62649214",
"0.62378716",
"0.6226134",
"0.6214355",
"0.6202315",
"0.61889744",
"0.6176346",
"0.61659676",
"0.61164534",
"0.60737514",
"0.6062088",
"0.60436046",
"0.60368645",
"0.6034352",
"0.60332817",
"0.60156554",
"0.5999597",
"0.5987468",
"0.5984947",
"0.59784174",
"0.596004",
"0.5943605",
"0.59375644",
"0.5936818",
"0.5931748",
"0.5925431",
"0.59084475",
"0.59078395",
"0.59015167",
"0.58933395",
"0.5885374",
"0.58819264",
"0.5877392",
"0.58713484",
"0.5866584",
"0.58596915",
"0.58493537",
"0.58477813",
"0.5847292",
"0.58408695",
"0.583766",
"0.5837239",
"0.583095",
"0.58243555",
"0.58093673",
"0.5808341",
"0.5804634",
"0.58045286",
"0.57950884",
"0.57945174",
"0.5794174",
"0.5782807",
"0.5782328",
"0.57797164",
"0.57736474",
"0.57581717",
"0.5753948",
"0.57472116",
"0.57426983",
"0.5731389",
"0.5721767",
"0.5716211",
"0.5711544",
"0.57071924",
"0.56993026",
"0.56948364",
"0.56941456",
"0.5680757",
"0.5670677",
"0.56635",
"0.5662901",
"0.5636854",
"0.5632688",
"0.56270295",
"0.5615789",
"0.5614504",
"0.56117374",
"0.56092644",
"0.5608802",
"0.56058913",
"0.560115",
"0.55991036",
"0.55959505",
"0.55884176",
"0.5588106",
"0.55866426"
] |
0.0
|
-1
|
Delete the given user configurations. deletions on keys prefixed by 'biapi.' (except callback_url) are ignored keys (string): list of coma separated keys to be deleted.
|
def users_id_user_config_delete(id_user, opts = {})
users_id_user_config_delete_with_http_info(id_user, opts)
nil
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def destroy\n @userconfig.destroy\n respond_to do |format|\n format.html { redirect_to userconfigs_url, notice: \"Userconfig was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def delete_by_id(user_id)\n Iterable.request(conf, \"/users/byUserId/#{user_id}\").delete\n end",
"def users_id_user_config_delete_with_http_info(id_user, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: UsersManagementApi.users_id_user_config_delete ...'\n end\n # verify the required parameter 'id_user' is set\n if @api_client.config.client_side_validation && id_user.nil?\n fail ArgumentError, \"Missing the required parameter 'id_user' when calling UsersManagementApi.users_id_user_config_delete\"\n end\n # resource path\n local_var_path = '/users/{id_user}/config'.sub('{' + 'id_user' + '}', id_user.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/x-www-form-urlencoded'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['api_key']\n data, status_code, headers = @api_client.call_api(:DELETE, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: UsersManagementApi#users_id_user_config_delete\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def user_management_delete_user id\n # the base uri for api requests\n query_builder = Configuration.BASE_URI.dup\n\n # prepare query string for API call\n query_builder << \"/v1/users\"\n\n # process optional query parameters\n query_builder = APIHelper.append_url_with_query_parameters query_builder, {\n \"id\" => id,\n \"client_id\" => @client_id,\n \"client_secret\" => @client_secret,\n }\n\n # validate and preprocess url\n query_url = APIHelper.clean_url query_builder\n\n # prepare headers\n headers = {\n \"user-agent\" => \"IAMDATA V1\",\n \"accept\" => \"application/json\"\n }\n\n # invoke the API call request to fetch the response\n response = Unirest.delete query_url, headers:headers\n\n # Error handling using HTTP status codes\n if response.code == 404\n raise APIException.new \"Not found\", 404, response.raw_body\n elsif response.code == 401\n raise APIException.new \"Unauthorized\", 401, response.raw_body\n elsif !(response.code.between?(200,206)) # [200,206] = HTTP OK\n raise APIException.new \"HTTP Response Not OK\", response.code, response.raw_body\n end\n\n response.body\n end",
"def destroy\n @user_device_configuration = UserDeviceConfiguration.find(params[:id])\n @user_device_configuration.destroy\n\n respond_to do |format|\n format.html { redirect_to user_device_configurations_url }\n format.json { head :ok }\n end\n end",
"def delete(user_id:)\n path = '/users/{userId}'\n .gsub('{userId}', user_id)\n\n if user_id.nil?\n raise Appwrite::Exception.new('Missing required parameter: \"userId\"')\n end\n\n params = {\n }\n \n headers = {\n \"content-type\": 'application/json',\n }\n\n @client.call(\n method: 'DELETE',\n path: path,\n headers: headers,\n params: params,\n )\n end",
"def delete_users\n delete(users_path)\n end",
"def delete(user_id)\n self.class.delete(\"/#{@api_ver}/users/#{user_id}\", default_options_to_merge_with)\n end",
"def user_delete(user_id)\n\t\tdelete_call = Curl::Easy.http_delete(\"#{@ip_address}:#{@port_2}/v2.0/users/#{user_id}\"\n\t\t) do |curl|\n\t\t\tcurl.headers['x-auth-token'] = @token\n\t\t\tcurl.headers['userId'] = user_id\n\t\tend\n\t\n\tend",
"def delete_user\n client.delete(user)\n end",
"def remove_application(user_ids)\n\n return if user_ids.nil? or user_ids.empty?\n\n SqlHelper.validate_token([user_ids])\n\n con = [\"(xtype='#{Comment::XTYPE_APPLY}')\"]\n con << \"(item_id=#{self.item_id})\"\n\n user_con_a = []\n user_ids.each do |user_id|\n user_con_a << \"(user_id=#{user_id.to_i})\"\n end\n\n con << '(' + user_con_a.join(' or ') + ')'\n\n Comment.destroy_all(con.join(' and '))\n end",
"def delete_users_choices\n choices = get_choices\n choices.each do |choice|\n choice.delete\n end\n end",
"def delete_user(iam_client)\n\n\n\t# Remove Login Profile\n\tbegin\n\t\tiam_client.delete_login_profile({\n\t\t\tuser_name: Options[:username],\n\t\t})\n\trescue Exception => e\n\t\tputs \"Login profile already gone\"\n\tend\n\n\t# Remove Access Keys\n\tbegin\n\t\tresp = iam_client.list_access_keys({\n\t\t\tuser_name: Options[:username]\n\t\t})\n\t\tresp.access_key_metadata.each do |k|\n\t\t\tresp = iam_client.delete_access_key({\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t\taccess_key_id: k.access_key_id # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"issue removing access keys: #{e.message}\"\n\tend\t\t\t\n\n\t# Remove MFA\n\tbegin \n\t\tresp = iam_client.list_mfa_devices({\n\t\t\tuser_name: Options[:username]\n\t\t})\n\n\t\t# First deactivate then remove. I don't think you can have multiple MFA, but the structure says you can\n\t\tresp.mfa_devices.each do |d|\n\t\t\tiam_client.deactivate_mfa_device({\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t\tserial_number: d.serial_number, # required\n\t\t\t})\n\t\t\tiam_client.delete_virtual_mfa_device({\n\t\t\t\tserial_number: d.serial_number, # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"issue removing MFA Devices: #{e.message}\"\n\tend\n\n\t# Remove managed policies\n\tbegin \n\t\tresp = iam_client.list_attached_user_policies({\n\t\t\tuser_name: Options[:username]\n\t\t})\n\t\tresp.attached_policies.each do |p|\n\t\t\tiam_client.detach_user_policy({\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t\tpolicy_arn: p.policy_arn, # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"issue removing inline policies: #{e.message}\"\n\tend\n\n\t# Remove inline policies\n\tbegin \n\t\tresp = iam_client.list_user_policies({\n\t\t\tuser_name: Options[:username]\n\t\t})\n\t\tresp.policy_names.each do |p|\n\t\t\tiam_client.delete_user_policy({\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t\tpolicy_name: p, # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"issue removing inline policies: #{e.message}\"\n\tend\n\n\t# Remove from Groups\n\tbegin \n\t\tresp = iam_client.list_groups_for_user({\n\t\t\tuser_name: Options[:username]\n\t\t})\n\t\tresp.groups.each do |g|\n\t\t\tiam_client.remove_user_from_group({\n\t\t\t\tgroup_name: g.group_name, # required\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"issue removing from groups: #{e.message}\"\n\tend\n\n\t# Purge CodeCommit SSH Keys\n\tbegin\n\t\tresp = iam_client.list_ssh_public_keys({\n\t\t\tuser_name: Options[:username],\n\t\t})\n\t\tresp.ssh_public_keys.each do |key|\n\t\t\tresp = iam_client.delete_ssh_public_key({\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t\tssh_public_key_id: key.ssh_public_key_id, # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"Issue removing SSH Keys #{e.message}\"\n\tend\n\n\t# yay. Can finally do what I came for.\n\tbegin\n\t\tiam_client.delete_user({\n\t\t\tuser_name: Options[:username],\n\t\t})\n\t\texit 0\n\trescue Aws::IAM::Errors::DeleteConflict => e\n\t\tputs \"Other error deleting user: #{e.message}\"\n\t\texit 1\n\trescue Aws::IAM::Errors::NoSuchEntity =>e \n\t\tputs \"No such user #{Options[:username]} to delete.\"\n\t\texit 1\n\tend\nend",
"def delete_user_key(user, key_id, options = {})\n boolean_from_response :delete, \"/users/#{user}/keys/#{key_id}\", options\n end",
"def destroy\n if params[:id] != current_user.id\n return\n end\n if params[:conf] != \"true\"\n \n @user = User.find(params[:id])\n @user.destroy\n \n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end\n end",
"def delete\n appctrl_delete( 'User' )\n end",
"def delete user_id, options={}, headers={}\n @connection.delete \"users/#{user_id}.json\", options, headers\n end",
"def DeleteUser id\n \n APICall(path: \"users/#{id}.json\",method: 'DELETE')\n \n end",
"def remove_approver_from_contracts(user)\n\n self.connection.execute(\"delete users from users \\\n inner join contracts on contracts.id = users.contract_id \\\n where contracts.client_id = #{id.to_s} and users.id = #{user.id.to_s}\")\n\n end",
"def delete\n\t\tcurrent_user\n\t\tcurrent_user.regexpressions.destroy_all\n\t\tcurrent_user.tasks.destroy_all\n\t\tcurrent_user.clouds.destroy_all\n\t\tcurrent_user.platforms.destroy_all\n\t\tcurrent_user.demos.destroy_all\n\t\tcurrent_user.favorites.destroy_all\n\tend",
"def remove_ssh_keys(user_id, keys, parent_op=nil)\n return if keys.empty?\n keys_attrs = get_updated_ssh_keys(user_id, keys)\n Application.run_in_application_lock(self) do\n return unless user_id.nil? || Ability.has_permission?(user_id, :ssh_to_gears, Application, role_for(user_id), self)\n op_group = PendingAppOpGroup.new(op_type: :update_configuration, args: {\"remove_keys_attrs\" => keys_attrs}, parent_op: parent_op, user_agent: self.user_agent)\n self.pending_op_groups.push op_group\n result_io = ResultIO.new\n self.run_jobs(result_io)\n result_io\n end\n end",
"def delete\r\n Marketplace::Database.instance.call_users(self)\r\n Marketplace::Database.instance.delete_user(self)\r\n ImageUploader.delete_image(self.picture, settings.root) if self.picture != nil\r\n items = Marketplace::Database.instance.items_by_user(self)\r\n items.each{ |item| item.delete }\r\n end",
"def delete(params = {})\n case @api.version\n when 'v1'\n response = self.class.post(@api.delete_config[:url],\n :query => { :auth_token => @token }.merge(params),\n :headers => @api.headers\n )\n when 'v2'\n response = self.class.delete(@api.delete_config[:url],\n :query => { :auth_token => @token },\n :headers => @api.headers\n )\n end\n\n ErrorHandler.response_code_to_exception_for :user, user_id, response\n true\n end",
"def delete_access_config 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_delete_access_config_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::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def destroy\n if @user.account.present? && @user.account.accountable.is_a?(Npo)\n @user.npo.npo_events.create(npo_event_status: NpoEventStatus.user_deleted, user: current_user, description: \"Deleting User: #{@user.email}\")\n end\n sso_user_setting = @user.user_settings.where(setting_type: 'sisense_sso').first\n if sso_user_setting.present?\n Rails.logger.info(\"sso_user_setting for user id: #{@user.id} - #{sso_user_setting.inspect}\")\n Producer.publish({ :message_type => Fox::QueueTypes::ANALYTICS_QUEUE, :analytics_type => SisenseUserService::DELETE_SSO_USER, :sisense_user_id => sso_user_setting.setting_value })\n end\n\n @user.destroy\n redirect_path = current_user.account.is_channel_partner? ? edit_account_settings_path : account_path\n\n respond_to do |format|\n format.html { redirect_to redirect_path }\n format.json { head :ok }\n end\n end",
"def delete_configuration\n super\n end",
"def delete_configuration\n super\n end",
"def action_remove\n notifying_block do\n delete_config\n end\n end",
"def delete_all_configurations\n super\n end",
"def delete_all_configurations\n super\n end",
"def delete(config, org_guid)\n token = @client.token\n\n user_setup_obj = UsersSetup.new(config)\n admin_token = user_setup_obj.get_admin_token\n\n # elevate user just to delete organization\n @client.token = admin_token\n org = @client.organization(org_guid)\n deleted = org.delete(:recursive => true)\n\n # then put token back to the initial one\n @client.token = token\n deleted\n end",
"def deleteUser(userInfo)\r\n\t\tnum = 0\r\n\t\tuser_id = 0\r\n\t\tuserInfo.each_pair { | name, value |\r\n\t\t\tif(name == \"user_id\")\r\n\t\t\t\tuser_id = value\r\n\t\t\telse\r\n\t\t\t\tputs \"wrong parameter: #{name}\"\r\n\t\t\t\treturn \"wrong parameter: #{name}\"\r\n\t\t\tend\t\t\t\t\r\n\t\t}\r\n\r\n\t\tputs \"Connecting to database...\"\r\n\t\tbegin\r\n\t\t\t# connect to the MySQL server\r\n\t\t\tdbh = DBI.connect(\"DBI:Mysql:#{$db}:#{$db_ip}\",\"#{$user}\", \"#{$pass}\")\r\n\t\t\t\r\n\t\t\tnum = dbh.do(\"DELETE FROM nitlab.b9tj1_users WHERE id = '#{user_id}' AND id!='62'\")\r\n\t\t\tif (num == 1)\r\n\t\t\t\tputs \"User deleted...\"\r\n\t\t\t\treturn 0\r\n\t\t\tend\r\n\t\t\t\r\n\t\trescue DBI::DatabaseError => e\r\n\t\t\tputs \"An error occurred\"\r\n\t\t\tputs \"Error code: #{e.err}\"\r\n\t\t\tputs \"Error message: #{e.errstr}\"\r\n\t\tensure\r\n\t\t\t# disconnect from server\r\n\t\t\tdbh.disconnect if dbh\r\n\t\tend\r\n\t\t\t\r\n\t\treturn -1\r\n\tend",
"def delete\n params = self.class.prepare_params_for(:delete, \"userName\" => user_name)\n response = self.class.perform(params)\n self.class.check_response(response)\n end",
"def destroy\n \n\tif signed_in?\n\t\t@current_client = current_user.username\n\t\tif current_user.username == 'admin'\n\t\t\t@clientconfig = Clientconfig.find(params[:id])\n\t\t\t@clientconfig.destroy\n\t\telse\n\t\t\tredirect_to home_path\n\t\tend\n\telse\n\t\tredirect_to signin_path\n\tend\n\n respond_to do |format|\n format.html { redirect_to clientconfigs_url }\n format.json { head :no_content }\n end\n end",
"def delete_multiple(keys = [])\n verify_connection_url\n\n keys.each { |key| delete key }\n end",
"def destroy\n result = current_user.user_settings.find(params[:id])\n result.destroy\n\n respond_with result\n end",
"def delete_user_custom_attribute(key, user_id)\n delete(\"/users/#{user_id}/custom_attributes/#{key}\")\n end",
"def delete_user(user_id:, params:)\n connection.delete(\"users/#{user_id}\", params).body\n end",
"def destroy\n conf.delete 'api'\n end",
"def local_remove(body)\n key_hash = _user_keyhash(body)\n raise \"Invalid username\" unless key_hash\n raise \"That user is signed in!\" if @var[:presence][key_hash]\n @connection.comm.rsa_keys.delete(body)\n @connection.comm.names.delete(key_hash)\n @var[:user_keys].delete body\n _save_env\n _notice \"User '#{body}' has been removed from your key repository\"\nend",
"def delete_user(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DeleteUser'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'https'\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :user_name\n\t\t\targs[:query]['UserName'] = optional[:user_name]\n\t\tend\n\t\tself.run(args)\n\tend",
"def delete(key)\n @config.delete(key.to_s)\n end",
"def delete()\n @client.make_request(:delete, @client.concat_user_path(\"#{DOMAIN_PATH}/#{domain_id}/endpoints/#{id}\"))[0]\n end",
"def delete(key)\n self.config.delete(key)\n end",
"def batch_delete_user_links 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_batch_delete_user_links_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::Protobuf::Empty.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def delete_kms_config 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_delete_kms_config_request request_pb\n query_string_params = if query_string_params.any?\n query_string_params.to_h { |p| p.split \"=\", 2 }\n else\n {}\n end\n\n response = @client_stub.make_http_request(\n verb,\n uri: uri,\n body: body || \"\",\n params: query_string_params,\n options: options\n )\n operation = ::Gapic::Rest::TransportOperation.new response\n result = ::Google::Longrunning::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def revoke(user_id)\n require_user\n\n user = User.find(user_id)\n user.secrets.each do |secret|\n secret.destroy\n end\n\n user.destroy\n end",
"def delete\n @linked_user.delete(@uri)\n end",
"def delete\n fail CoachClient::NotFound unless exist?\n invalidate if @user2_confirmed\n if @user1_confirmed\n response = CoachClient::Request.delete(url, username: @user1.username,\n password: @user1.password)\n set_user_confirmed(response.to_h)\n end\n true\n end",
"def test_user_delete\n # Get the user info\n user = get_user_by_username('test-ruby-user12356')\n # Check to see if the returned user was the correct one.\n # Doubles to check whether the returned data exists in a proper form\n assert_equal('test-ruby-user12356', user['UserName'])\n # Delete the user based upon the returned user's id\n ap delete_user_data(user['UserId'])\n # assert if referencing this user, again, causes an error.\n user = get_user_by_username('test-ruby-user12356')\n assert_raise { delete_user_data(user['UserId']) }\n end",
"def delete_communication_channel_type(user_id,type,address,opts={})\n query_param_keys = [\n \n ]\n\n form_param_keys = [\n \n ]\n\n # verify existence of params\n raise \"user_id is required\" if user_id.nil?\n raise \"type is required\" if type.nil?\n raise \"address is required\" if address.nil?\n # set default values and merge with input\n options = underscored_merge_opts(opts,\n :user_id => user_id,\n :type => type,\n :address => address\n )\n\n # resource path\n path = path_replace(\"/v1/users/{user_id}/communication_channels/{type}/{address}\",\n :user_id => user_id,\n :type => type,\n :address => address)\n headers = nil\n form_params = select_params(options, form_param_keys)\n query_params = select_params(options, query_param_keys)\n if opts[:next_page]\n pagination_params = page_params_load(:delete, path)\n query_params.merge! pagination_params if pagination_params\n end\n response = mixed_request(:delete, path, query_params, form_params, headers)\n page_params_store(:delete, path)\n CommunicationChannel.new(response)\n end",
"def deleteDisConUser(idUser,idChannel)\n \n begin\n query = \"DELETE FROM `#{DB_NAME}`.`#{USER_LIST_IN_CHAN_TABBLE}` WHERE `#{USER_LIST_IN_CHAN_TABBLE}`.`user_id_user` = ? AND `#{USER_LIST_IN_CHAN_TABBLE}`.`channel_id_channel` = ?\"\n queryReset = \"ALTER TABLE #{USER_LIST_IN_CHAN_TABBLE} AUTO_INCREMENT = 1\"\n self.connect unless self.connected? # => connect to the DB server if not connected\n sth = @dbh.prepare(query)\n sth.execute(idUser,idChannel)\n sth = @dbh.prepare(queryReset)\n sth.execute\n \n sth.finish\n rescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\n @dbh.rollback\n rescue Exception => e \n puts \"error!!! -> : #{e.to_s}\"\n \n ensure\n # disconnect from server\n @dbh.disconnect if @connected\n @connected=false\n end\n \n \n end",
"def delete_per_instance_configs request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n uri, body, _query_string_params = transcode_delete_per_instance_configs_request request_pb\n response = @client_stub.make_post_request(\n uri: uri,\n body: body,\n options: options\n )\n result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, response if block_given?\n result\n end",
"def delete_all\n destroy_user_preferences!\n render json: { code: params[:code] }, status: :ok, serializer: DeleteAllUserPreferencesSerializer\n end",
"def destroy\n @configuration_key.destroy\n respond_to do |format|\n format.html { redirect_to configuration_keys_url }\n format.json { head :no_content }\n end\n end",
"def delete_user(user)\n res1 = remove_filtered_grouping_policy(0, user)\n res2 = remove_filtered_policy(0, user)\n res1 || res2\n end",
"def remove_all_keys\n\t\tdelete(\"/user/keys\")\n\tend",
"def remove_all_keys\n\t\tdelete(\"/user/keys\")\n\tend",
"def hash_delete(field)\n choose do |menu|\n menu.prompt = \"Please select to remove: \"\n menu.index = :number\n menu.index_suffix = ') '\n menu.choice(:quit, 'Quit') {result = false}\n values = []\n AppConfig.config[field].each do |key, value|\n values << \"#{key} => #{value}\"\n end\n menu.choices(*values) do |value, details|\n if value =~ /(.*\\S)\\s+=>/\n AppConfig.config[field].delete($1)\n end\n end\n end\n end",
"def delete_all_test_users\n\n if @appAccessToken.nil?\n _obtain_app_access_token\n end\n\n users = list_test_users()\n users.each do |user|\n delete_test_user(user['id'])\n end\n end",
"def deleteUserNotifications(u)\n @ns = getUserNotifications(u)\n @ns.each do |n|\n n.destroy\n end\n redirect_to \"/notifications\", notice: \"All notifications deleted.\"\n end",
"def destroy_configuration_with_http_info(configuration_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: UsersApi.destroy_configuration ...'\n end\n # verify the required parameter 'configuration_id' is set\n if @api_client.config.client_side_validation && configuration_id.nil?\n fail ArgumentError, \"Missing the required parameter 'configuration_id' when calling UsersApi.destroy_configuration\"\n end\n # resource path\n local_var_path = '/users/me/configurations/{configuration_id}'.sub('{' + 'configuration_id' + '}', CGI.escape(configuration_id.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: UsersApi#destroy_configuration\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def delete_user\n print_status(\"Current MySQL Users & Host Info: \")\n query = @db.query('SELECT group_concat(0x0a,host,0x3a,user) FROM mysql.user;')\n query.each { |x| puts \"#{x[0]}\".white }\n print_line(\"\")\n user = Readline.readline(\"(Username to DROP)> \", true)\n host = Readline.readline(\"(Host Entry for #{user.chomp} to DROP)> \", true)\n answer = Readline.readline(\"(Confirm: DROP #{user.chomp}@#{host.chomp} (Y/N))> \", true)\n if \"#{answer.chomp.upcase}\" == \"YES\" or \"#{answer.chomp.upcase}\" == \"Y\"\n print_status(\"OK, sending DROP request.....\")\n begin\n query = @db_connection.query('USE mysql;')\n query = @db_connection.query(\"DROP USER '#{user.chomp}'@'#{host.chomp}';\")\n query = @db_connection.query('FLUSH PRIVILEGES;')\n rescue Mysql::Error => e\n print_error(\"Problem with DROP!\")\n print_error(\"#{e}\")\n end\n print_status(\"Updated MySQL Users & Host Info: \")\n query = @db.query('SELECT group_concat(0x0a,host,0x3a,user) FROM mysql.user;')\n query.each { |x| print_line(\"#{x[0]}\") }\n print_line(\"\")\n else\n print_error(\"OK, aborting User DROP and Returning to Main Menu...\")\n end\n end",
"def delete_user(username, removehome=false)\n\t\t\tend",
"def delete current_user\n raise RequestError.new(:internal_error, \"Delete: no user specified\") if current_user.nil?\n\n # remove all its files\n self.files.each { |item| item.delete current_user }\n # remove all its children, meaning all its subdirectories. (all sub-sub-directories and sub-files will me removed as well)\n self.childrens.each { |children| children.delete current_user }\n\n if current_user.id != self.user_id then # if random owner \n # remove all links between this folder and the current user only\n FileUserAssociation.all(x_file_id: self.id, user_id: current_user.id).destroy!\n # remove all associations where this folder is a children of a folder belonging to the current user only\n FolderFolderAssociation.all(children_id: self.id).each do |asso|\n asso.destroy! if current_user.x_files.get(asso.parent_id)\n end\n # No sharing for folders: no SharedToMeAssociations\n\n else # if true owner \n # remove all links between this folder and ALL users\n FileUserAssociation.all(x_file_id: self.id).destroy!\n # remove all associations where this folder is a children of a folder belonging ALL users\n FolderFolderAssociation.all(children_id: self.id).destroy!\n # No sharing for folders: no SharedByMeAssociations\n\n # No need to remove the association where this folder is a parent (of a file or folder)\n # because the children have already been removed and all theirs associations\n #\n # FolderFolderAssociation.all(parent_id: self.id).destroy!\n # FileFolderAssociation.all(parent_id: self.id).destroy!\n \n # now remove the entity\n self.destroy!\n end\n end",
"def delete_user\n end",
"def delete(key)\n configuration.delete(key)\n end",
"def chimp_remove(options, delete_user=true, send_goodbye=false, send_notify=false)\n begin\n raise MailChimpAPI::DeleteError, \"Email and Mailing List Id can't be nil\" if (options[:email].nil? || options[:mailing_list_id].nil?)\n @client.call(\"listUnsubscribe\", @api_key, options[:mailing_list_id], options[:email], delete_user, send_goodbye, send_notify) \n rescue XMLRPC::FaultException => e\n raise MailChimpAPI::DeleteError, e.faultString\n end \n end",
"def delete_user(user)\n users = roles\n existing = users[\"cloudant\"]\n \n existing.delete(user) if existing\n update_roles(users)\n end",
"def backend_deleteUser(param) \n @Tasks.delete(param) if @Tasks.include? param \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 @user_car_setting.destroy\n respond_to do |format|\n format.html { redirect_to _user_car_settings_url, notice: 'Configuración eliminada' }\n format.json { head :no_content }\n end\n end",
"def delete(filters, user)\n if filters.empty?\n body = \"sql=DELETE FROM #{@id}\"\n connector.post \"https://www.googleapis.com/fusiontables/v2/query\", body\n else\n row_ids = query_row_ids(filters)\n row_ids.each do |row_id|\n body = \"sql=DELETE FROM #{@id} WHERE ROWID = '#{row_id}';\"\n connector.post \"https://www.googleapis.com/fusiontables/v2/query\", body\n end\n end\n end",
"def delete_webhook_config(id, name=nil)\n\t\tputs \"Attempting to delete configuration for webhook id: #{id}.\"\n\n\t\tif @api_tier == 'premium'\n\t\t\t@uri_path = \"#{@uri_path}/all/#{name}/webhooks/#{id}.json\"\n\t\telse\n\t\t\t@uri_path = \"#{@uri_path}/webhooks/#{id}.json\"\n\t\tend\n\n\t\tresponse = @twitter_api.make_delete_request(@uri_path)\n\n\t\tif response == '204'\n\t\t\tputs \"Webhook configuration for #{id} was successfully deleted.\"\n\t\telse\n\t\t\tputs response\n\t\tend\n\n\t\tresponse\n\tend",
"def delete_user_route(user)\n self.client.delete(\"gh.storage.user.#{user}\")\n end",
"def delete_state_for_user(opts = {})\n uri = \"/v3/botstate/#{opts['channel_id']}/users/#{opts['user_id']}\"\n api_delete(uri)\n end",
"def delete_app_members(owner:, platform:, app_id:, users:)\n endpoint = \"/api/users/#{owner}/platforms/#{platform}/apps/#{app_id}/members\"\n res = api.delete endpoint do |request|\n request.headers['Content-Type'] = 'application/x-www-form-urlencoded'\n request.body = URI.encode_www_form(\n users: users\n )\n end\n Response.new(res)\n end",
"def remove_user\n query_api '/rest/user', nil, 'DELETE'\n end",
"def delete_user(user_name:)\n validate_user_name(:user_name, user_name)\n\n wrap_response(@connection.delete(user_path(user_name))).fmap { |r| SftpgoClient::ApiResponse.new(r.body) }\n end",
"def clear_auth\n [:apikey, :username, :authkey].each { |key| DEFAULT_PARAMS.delete(key) }\n end",
"def delete(user)\n @@contact_list.delete(user)\n end",
"def delete(*args)\n arguments(args)\n params = arguments.params\n params['data'] = arguments.remaining unless arguments.remaining.empty?\n\n delete_request(\"/user/emails\", params)\n end",
"def delete_user_link 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_delete_user_link_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::Protobuf::Empty.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def delete_user request_pb, options:, &block\n request_json = JSON.parse ::Google::Showcase::V1beta1::DeleteUserRequest.encode_json(request_pb)\n\n uri = \"/v1beta1/#{request_pb.name}\"\n\n result_json = @client_stub.make_delete_request(\n uri: uri,\n options: options,\n &block\n )\n\n ::Google::Protobuf::Empty.decode_json result_json[:body]\n end",
"def cfgremove(fabrickey, cfgname, *zonenames)\n result = @zones.altercfg(fabrickey, 'REMOVE', cfgname, *zonenames)\n result[1]\n end",
"def delete_communication_channel_id(user_id,id,opts={})\n query_param_keys = [\n \n ]\n\n form_param_keys = [\n \n ]\n\n # verify existence of params\n raise \"user_id is required\" if user_id.nil?\n raise \"id is required\" if id.nil?\n # set default values and merge with input\n options = underscored_merge_opts(opts,\n :user_id => user_id,\n :id => id\n )\n\n # resource path\n path = path_replace(\"/v1/users/{user_id}/communication_channels/{id}\",\n :user_id => user_id,\n :id => id)\n headers = nil\n form_params = select_params(options, form_param_keys)\n query_params = select_params(options, query_param_keys)\n if opts[:next_page]\n pagination_params = page_params_load(:delete, path)\n query_params.merge! pagination_params if pagination_params\n end\n response = mixed_request(:delete, path, query_params, form_params, headers)\n page_params_store(:delete, path)\n CommunicationChannel.new(response)\n end",
"def delete_user(id)\n elektron_identity.delete(\"users/#{id}\")\n end",
"def webhelper_delete_all_signing_keys(username, password, base_url = @base_url)\r\n private_resource = RestClient::Resource.new base_url + \"/api/v1/keys\", {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.get :accept => :json\r\n json = JSON.parse(response)\r\n\r\n puts \"\"\r\n # delete ios signing_keys\r\n puts \"+ Delete iOS signing-key: \"\r\n json['keys']['ios']['all'].each do |i|\r\n url = base_url + i['link']\r\n private_resource = RestClient::Resource.new url , {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.delete \r\n puts \"+ \" + response.to_str\r\n end\r\n # delete android signing_keys\r\n puts \"+ Delete Android signing-key: \"\r\n json['keys']['android']['all'].each do |i|\r\n url = base_url + i['link']\r\n private_resource = RestClient::Resource.new url , {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.delete \r\n puts \"+ \" + response.to_str\r\n end\r\n # delete blackberry signing_keys\r\n puts \"+ Delete BlackBerry signing-key: \"\r\n json['keys']['blackberry']['all'].each do |i|\r\n url = base_url + i['link']\r\n private_resource = RestClient::Resource.new url , {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.delete \r\n puts \"+ \" + response.to_str\r\n end\r\n end",
"def user_delete(user_id)\n res = http_delete(:uri=>\"/users/#{user_id}\", :fields=>x_cookie)\n return res.code\n end",
"def destroy\n @user_setting.destroy\n respond_to do |format|\n format.html { redirect_to user_settings_url, notice: 'User setting was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def remove\n system(\"qconf -duser #{name}\")\n end",
"def delete(user = nil, reason = nil, comment = nil, options = {})\n self.class.delete \"#{Invoice::KILLBILL_API_INVOICES_PREFIX}/#{invoice_id}/#{invoice_item_id}/cba\",\n to_json,\n {\n :accountId => account_id\n },\n {\n :user => user,\n :reason => reason,\n :comment => comment,\n }.merge(options)\n end",
"def delete(user = nil, reason = nil, comment = nil, options = {})\n self.class.delete \"#{Invoice::KILLBILL_API_INVOICES_PREFIX}/#{invoice_id}/#{invoice_item_id}/cba\",\n to_json,\n {\n :accountId => account_id\n },\n {\n :user => user,\n :reason => reason,\n :comment => comment,\n }.merge(options)\n end",
"def delete_user_attribute_definition(name, headers=default_headers)\n @logger.info(\"Deleting the \\\"#{name}\\\" User Attribute Definition\")\n delete(\"#{@api_url}/userAttributeDefinitions/#{encode(name)}\", headers)\n end",
"def destroy\n @global_config = AppConfig.find(params[:id])\n @global_config.destroy\n\n respond_to do |format|\n format.html { redirect_to global_configs_url }\n format.json { head :no_content }\n end\n end",
"def delete_user_authentication_methods(user_id)\n raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty?\n\n delete \"#{users_path}/#{user_id}/authentication-methods\" \n end",
"def delete(key)\n @configuration.delete(key)\n end",
"def delete(key)\n @configuration.delete(key)\n end",
"def delete(key)\n @configuration.delete(key)\n end",
"def destroy\n @app_config = AppConfig.find(params[:id])\n @app_config.destroy\n\n respond_to do |format|\n format.html { redirect_to app_configs_url }\n format.json { head :no_content }\n end\n end"
] |
[
"0.6190237",
"0.60056967",
"0.5939117",
"0.58024246",
"0.5745868",
"0.56886286",
"0.56784123",
"0.567366",
"0.5672965",
"0.56620175",
"0.5642824",
"0.5607411",
"0.5581179",
"0.5533959",
"0.5527929",
"0.55043656",
"0.54897654",
"0.5470818",
"0.5467372",
"0.54495454",
"0.54377395",
"0.54374564",
"0.5433226",
"0.5430276",
"0.54213345",
"0.54206175",
"0.54206175",
"0.5403059",
"0.5389442",
"0.5389442",
"0.53841126",
"0.53546137",
"0.53476226",
"0.53177935",
"0.5307314",
"0.5304863",
"0.5303403",
"0.52981216",
"0.52975935",
"0.5293671",
"0.5291081",
"0.52790606",
"0.52710426",
"0.5252889",
"0.52521443",
"0.5251335",
"0.52362573",
"0.5235042",
"0.52259135",
"0.5221704",
"0.52184355",
"0.5213038",
"0.52107376",
"0.5210618",
"0.5205926",
"0.52001643",
"0.5197219",
"0.5197219",
"0.51944757",
"0.5190567",
"0.51837975",
"0.51810634",
"0.5176911",
"0.5173627",
"0.51734954",
"0.51666224",
"0.516256",
"0.51540405",
"0.51501447",
"0.51468545",
"0.51411515",
"0.5134995",
"0.513174",
"0.51304436",
"0.5126735",
"0.51257443",
"0.5121212",
"0.51145536",
"0.5105877",
"0.51049167",
"0.50987995",
"0.5093555",
"0.50866127",
"0.50844264",
"0.5083169",
"0.50659883",
"0.50644475",
"0.50506896",
"0.5048443",
"0.504798",
"0.5047484",
"0.5045288",
"0.5045288",
"0.50450796",
"0.5044379",
"0.50435126",
"0.50424224",
"0.50424224",
"0.50424224",
"0.50362897"
] |
0.6246653
|
0
|
Delete the given user configurations. deletions on keys prefixed by &39;biapi.&39; (except callback_url) are ignored keys (string): list of coma separated keys to be deleted.
|
def users_id_user_config_delete_with_http_info(id_user, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersManagementApi.users_id_user_config_delete ...'
end
# verify the required parameter 'id_user' is set
if @api_client.config.client_side_validation && id_user.nil?
fail ArgumentError, "Missing the required parameter 'id_user' when calling UsersManagementApi.users_id_user_config_delete"
end
# resource path
local_var_path = '/users/{id_user}/config'.sub('{' + 'id_user' + '}', id_user.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['api_key']
data, status_code, headers = @api_client.call_api(:DELETE, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersManagementApi#users_id_user_config_delete\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def users_id_user_config_delete(id_user, opts = {})\n users_id_user_config_delete_with_http_info(id_user, opts)\n nil\n end",
"def destroy\n @userconfig.destroy\n respond_to do |format|\n format.html { redirect_to userconfigs_url, notice: \"Userconfig was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def delete_by_id(user_id)\n Iterable.request(conf, \"/users/byUserId/#{user_id}\").delete\n end",
"def user_management_delete_user id\n # the base uri for api requests\n query_builder = Configuration.BASE_URI.dup\n\n # prepare query string for API call\n query_builder << \"/v1/users\"\n\n # process optional query parameters\n query_builder = APIHelper.append_url_with_query_parameters query_builder, {\n \"id\" => id,\n \"client_id\" => @client_id,\n \"client_secret\" => @client_secret,\n }\n\n # validate and preprocess url\n query_url = APIHelper.clean_url query_builder\n\n # prepare headers\n headers = {\n \"user-agent\" => \"IAMDATA V1\",\n \"accept\" => \"application/json\"\n }\n\n # invoke the API call request to fetch the response\n response = Unirest.delete query_url, headers:headers\n\n # Error handling using HTTP status codes\n if response.code == 404\n raise APIException.new \"Not found\", 404, response.raw_body\n elsif response.code == 401\n raise APIException.new \"Unauthorized\", 401, response.raw_body\n elsif !(response.code.between?(200,206)) # [200,206] = HTTP OK\n raise APIException.new \"HTTP Response Not OK\", response.code, response.raw_body\n end\n\n response.body\n end",
"def delete_users\n delete(users_path)\n end",
"def delete_user\n client.delete(user)\n end",
"def delete(user_id)\n self.class.delete(\"/#{@api_ver}/users/#{user_id}\", default_options_to_merge_with)\n end",
"def delete(user_id:)\n path = '/users/{userId}'\n .gsub('{userId}', user_id)\n\n if user_id.nil?\n raise Appwrite::Exception.new('Missing required parameter: \"userId\"')\n end\n\n params = {\n }\n \n headers = {\n \"content-type\": 'application/json',\n }\n\n @client.call(\n method: 'DELETE',\n path: path,\n headers: headers,\n params: params,\n )\n end",
"def user_delete(user_id)\n\t\tdelete_call = Curl::Easy.http_delete(\"#{@ip_address}:#{@port_2}/v2.0/users/#{user_id}\"\n\t\t) do |curl|\n\t\t\tcurl.headers['x-auth-token'] = @token\n\t\t\tcurl.headers['userId'] = user_id\n\t\tend\n\t\n\tend",
"def destroy\n @user_device_configuration = UserDeviceConfiguration.find(params[:id])\n @user_device_configuration.destroy\n\n respond_to do |format|\n format.html { redirect_to user_device_configurations_url }\n format.json { head :ok }\n end\n end",
"def remove_application(user_ids)\n\n return if user_ids.nil? or user_ids.empty?\n\n SqlHelper.validate_token([user_ids])\n\n con = [\"(xtype='#{Comment::XTYPE_APPLY}')\"]\n con << \"(item_id=#{self.item_id})\"\n\n user_con_a = []\n user_ids.each do |user_id|\n user_con_a << \"(user_id=#{user_id.to_i})\"\n end\n\n con << '(' + user_con_a.join(' or ') + ')'\n\n Comment.destroy_all(con.join(' and '))\n end",
"def delete_user_key(user, key_id, options = {})\n boolean_from_response :delete, \"/users/#{user}/keys/#{key_id}\", options\n end",
"def delete_users_choices\n choices = get_choices\n choices.each do |choice|\n choice.delete\n end\n end",
"def delete user_id, options={}, headers={}\n @connection.delete \"users/#{user_id}.json\", options, headers\n end",
"def destroy\n if params[:id] != current_user.id\n return\n end\n if params[:conf] != \"true\"\n \n @user = User.find(params[:id])\n @user.destroy\n \n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end\n end",
"def delete_user(iam_client)\n\n\n\t# Remove Login Profile\n\tbegin\n\t\tiam_client.delete_login_profile({\n\t\t\tuser_name: Options[:username],\n\t\t})\n\trescue Exception => e\n\t\tputs \"Login profile already gone\"\n\tend\n\n\t# Remove Access Keys\n\tbegin\n\t\tresp = iam_client.list_access_keys({\n\t\t\tuser_name: Options[:username]\n\t\t})\n\t\tresp.access_key_metadata.each do |k|\n\t\t\tresp = iam_client.delete_access_key({\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t\taccess_key_id: k.access_key_id # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"issue removing access keys: #{e.message}\"\n\tend\t\t\t\n\n\t# Remove MFA\n\tbegin \n\t\tresp = iam_client.list_mfa_devices({\n\t\t\tuser_name: Options[:username]\n\t\t})\n\n\t\t# First deactivate then remove. I don't think you can have multiple MFA, but the structure says you can\n\t\tresp.mfa_devices.each do |d|\n\t\t\tiam_client.deactivate_mfa_device({\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t\tserial_number: d.serial_number, # required\n\t\t\t})\n\t\t\tiam_client.delete_virtual_mfa_device({\n\t\t\t\tserial_number: d.serial_number, # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"issue removing MFA Devices: #{e.message}\"\n\tend\n\n\t# Remove managed policies\n\tbegin \n\t\tresp = iam_client.list_attached_user_policies({\n\t\t\tuser_name: Options[:username]\n\t\t})\n\t\tresp.attached_policies.each do |p|\n\t\t\tiam_client.detach_user_policy({\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t\tpolicy_arn: p.policy_arn, # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"issue removing inline policies: #{e.message}\"\n\tend\n\n\t# Remove inline policies\n\tbegin \n\t\tresp = iam_client.list_user_policies({\n\t\t\tuser_name: Options[:username]\n\t\t})\n\t\tresp.policy_names.each do |p|\n\t\t\tiam_client.delete_user_policy({\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t\tpolicy_name: p, # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"issue removing inline policies: #{e.message}\"\n\tend\n\n\t# Remove from Groups\n\tbegin \n\t\tresp = iam_client.list_groups_for_user({\n\t\t\tuser_name: Options[:username]\n\t\t})\n\t\tresp.groups.each do |g|\n\t\t\tiam_client.remove_user_from_group({\n\t\t\t\tgroup_name: g.group_name, # required\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"issue removing from groups: #{e.message}\"\n\tend\n\n\t# Purge CodeCommit SSH Keys\n\tbegin\n\t\tresp = iam_client.list_ssh_public_keys({\n\t\t\tuser_name: Options[:username],\n\t\t})\n\t\tresp.ssh_public_keys.each do |key|\n\t\t\tresp = iam_client.delete_ssh_public_key({\n\t\t\t\tuser_name: Options[:username], # required\n\t\t\t\tssh_public_key_id: key.ssh_public_key_id, # required\n\t\t\t})\n\t\tend\n\trescue Exception => e\n\t\tputs \"Issue removing SSH Keys #{e.message}\"\n\tend\n\n\t# yay. Can finally do what I came for.\n\tbegin\n\t\tiam_client.delete_user({\n\t\t\tuser_name: Options[:username],\n\t\t})\n\t\texit 0\n\trescue Aws::IAM::Errors::DeleteConflict => e\n\t\tputs \"Other error deleting user: #{e.message}\"\n\t\texit 1\n\trescue Aws::IAM::Errors::NoSuchEntity =>e \n\t\tputs \"No such user #{Options[:username]} to delete.\"\n\t\texit 1\n\tend\nend",
"def delete\r\n Marketplace::Database.instance.call_users(self)\r\n Marketplace::Database.instance.delete_user(self)\r\n ImageUploader.delete_image(self.picture, settings.root) if self.picture != nil\r\n items = Marketplace::Database.instance.items_by_user(self)\r\n items.each{ |item| item.delete }\r\n end",
"def delete\n\t\tcurrent_user\n\t\tcurrent_user.regexpressions.destroy_all\n\t\tcurrent_user.tasks.destroy_all\n\t\tcurrent_user.clouds.destroy_all\n\t\tcurrent_user.platforms.destroy_all\n\t\tcurrent_user.demos.destroy_all\n\t\tcurrent_user.favorites.destroy_all\n\tend",
"def DeleteUser id\n \n APICall(path: \"users/#{id}.json\",method: 'DELETE')\n \n end",
"def delete\n appctrl_delete( 'User' )\n end",
"def destroy\n if @user.account.present? && @user.account.accountable.is_a?(Npo)\n @user.npo.npo_events.create(npo_event_status: NpoEventStatus.user_deleted, user: current_user, description: \"Deleting User: #{@user.email}\")\n end\n sso_user_setting = @user.user_settings.where(setting_type: 'sisense_sso').first\n if sso_user_setting.present?\n Rails.logger.info(\"sso_user_setting for user id: #{@user.id} - #{sso_user_setting.inspect}\")\n Producer.publish({ :message_type => Fox::QueueTypes::ANALYTICS_QUEUE, :analytics_type => SisenseUserService::DELETE_SSO_USER, :sisense_user_id => sso_user_setting.setting_value })\n end\n\n @user.destroy\n redirect_path = current_user.account.is_channel_partner? ? edit_account_settings_path : account_path\n\n respond_to do |format|\n format.html { redirect_to redirect_path }\n format.json { head :ok }\n end\n end",
"def local_remove(body)\n key_hash = _user_keyhash(body)\n raise \"Invalid username\" unless key_hash\n raise \"That user is signed in!\" if @var[:presence][key_hash]\n @connection.comm.rsa_keys.delete(body)\n @connection.comm.names.delete(key_hash)\n @var[:user_keys].delete body\n _save_env\n _notice \"User '#{body}' has been removed from your key repository\"\nend",
"def delete(config, org_guid)\n token = @client.token\n\n user_setup_obj = UsersSetup.new(config)\n admin_token = user_setup_obj.get_admin_token\n\n # elevate user just to delete organization\n @client.token = admin_token\n org = @client.organization(org_guid)\n deleted = org.delete(:recursive => true)\n\n # then put token back to the initial one\n @client.token = token\n deleted\n end",
"def remove_ssh_keys(user_id, keys, parent_op=nil)\n return if keys.empty?\n keys_attrs = get_updated_ssh_keys(user_id, keys)\n Application.run_in_application_lock(self) do\n return unless user_id.nil? || Ability.has_permission?(user_id, :ssh_to_gears, Application, role_for(user_id), self)\n op_group = PendingAppOpGroup.new(op_type: :update_configuration, args: {\"remove_keys_attrs\" => keys_attrs}, parent_op: parent_op, user_agent: self.user_agent)\n self.pending_op_groups.push op_group\n result_io = ResultIO.new\n self.run_jobs(result_io)\n result_io\n end\n end",
"def delete(params = {})\n case @api.version\n when 'v1'\n response = self.class.post(@api.delete_config[:url],\n :query => { :auth_token => @token }.merge(params),\n :headers => @api.headers\n )\n when 'v2'\n response = self.class.delete(@api.delete_config[:url],\n :query => { :auth_token => @token },\n :headers => @api.headers\n )\n end\n\n ErrorHandler.response_code_to_exception_for :user, user_id, response\n true\n end",
"def deleteUser(userInfo)\r\n\t\tnum = 0\r\n\t\tuser_id = 0\r\n\t\tuserInfo.each_pair { | name, value |\r\n\t\t\tif(name == \"user_id\")\r\n\t\t\t\tuser_id = value\r\n\t\t\telse\r\n\t\t\t\tputs \"wrong parameter: #{name}\"\r\n\t\t\t\treturn \"wrong parameter: #{name}\"\r\n\t\t\tend\t\t\t\t\r\n\t\t}\r\n\r\n\t\tputs \"Connecting to database...\"\r\n\t\tbegin\r\n\t\t\t# connect to the MySQL server\r\n\t\t\tdbh = DBI.connect(\"DBI:Mysql:#{$db}:#{$db_ip}\",\"#{$user}\", \"#{$pass}\")\r\n\t\t\t\r\n\t\t\tnum = dbh.do(\"DELETE FROM nitlab.b9tj1_users WHERE id = '#{user_id}' AND id!='62'\")\r\n\t\t\tif (num == 1)\r\n\t\t\t\tputs \"User deleted...\"\r\n\t\t\t\treturn 0\r\n\t\t\tend\r\n\t\t\t\r\n\t\trescue DBI::DatabaseError => e\r\n\t\t\tputs \"An error occurred\"\r\n\t\t\tputs \"Error code: #{e.err}\"\r\n\t\t\tputs \"Error message: #{e.errstr}\"\r\n\t\tensure\r\n\t\t\t# disconnect from server\r\n\t\t\tdbh.disconnect if dbh\r\n\t\tend\r\n\t\t\t\r\n\t\treturn -1\r\n\tend",
"def delete_user(user_id:, params:)\n connection.delete(\"users/#{user_id}\", params).body\n end",
"def destroy\n result = current_user.user_settings.find(params[:id])\n result.destroy\n\n respond_with result\n end",
"def remove_approver_from_contracts(user)\n\n self.connection.execute(\"delete users from users \\\n inner join contracts on contracts.id = users.contract_id \\\n where contracts.client_id = #{id.to_s} and users.id = #{user.id.to_s}\")\n\n end",
"def delete_access_config 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_delete_access_config_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::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def delete\n params = self.class.prepare_params_for(:delete, \"userName\" => user_name)\n response = self.class.perform(params)\n self.class.check_response(response)\n end",
"def delete_user(username, removehome=false)\n\t\t\tend",
"def delete_configuration\n super\n end",
"def delete_configuration\n super\n end",
"def delete_all\n destroy_user_preferences!\n render json: { code: params[:code] }, status: :ok, serializer: DeleteAllUserPreferencesSerializer\n end",
"def delete_user_custom_attribute(key, user_id)\n delete(\"/users/#{user_id}/custom_attributes/#{key}\")\n end",
"def delete_user(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DeleteUser'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'https'\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :user_name\n\t\t\targs[:query]['UserName'] = optional[:user_name]\n\t\tend\n\t\tself.run(args)\n\tend",
"def delete_multiple(keys = [])\n verify_connection_url\n\n keys.each { |key| delete key }\n end",
"def delete(key)\n @config.delete(key.to_s)\n end",
"def hash_delete(field)\n choose do |menu|\n menu.prompt = \"Please select to remove: \"\n menu.index = :number\n menu.index_suffix = ') '\n menu.choice(:quit, 'Quit') {result = false}\n values = []\n AppConfig.config[field].each do |key, value|\n values << \"#{key} => #{value}\"\n end\n menu.choices(*values) do |value, details|\n if value =~ /(.*\\S)\\s+=>/\n AppConfig.config[field].delete($1)\n end\n end\n end\n end",
"def delete\n @linked_user.delete(@uri)\n end",
"def action_remove\n notifying_block do\n delete_config\n end\n end",
"def remove_all_keys\n\t\tdelete(\"/user/keys\")\n\tend",
"def remove_all_keys\n\t\tdelete(\"/user/keys\")\n\tend",
"def delete\n fail CoachClient::NotFound unless exist?\n invalidate if @user2_confirmed\n if @user1_confirmed\n response = CoachClient::Request.delete(url, username: @user1.username,\n password: @user1.password)\n set_user_confirmed(response.to_h)\n end\n true\n end",
"def delete_user(user)\n res1 = remove_filtered_grouping_policy(0, user)\n res2 = remove_filtered_policy(0, user)\n res1 || res2\n end",
"def destroy\n \n\tif signed_in?\n\t\t@current_client = current_user.username\n\t\tif current_user.username == 'admin'\n\t\t\t@clientconfig = Clientconfig.find(params[:id])\n\t\t\t@clientconfig.destroy\n\t\telse\n\t\t\tredirect_to home_path\n\t\tend\n\telse\n\t\tredirect_to signin_path\n\tend\n\n respond_to do |format|\n format.html { redirect_to clientconfigs_url }\n format.json { head :no_content }\n end\n end",
"def deleteUserNotifications(u)\n @ns = getUserNotifications(u)\n @ns.each do |n|\n n.destroy\n end\n redirect_to \"/notifications\", notice: \"All notifications deleted.\"\n end",
"def delete(key)\n self.config.delete(key)\n end",
"def delete_all_configurations\n super\n end",
"def delete_all_configurations\n super\n end",
"def delete_user\n print_status(\"Current MySQL Users & Host Info: \")\n query = @db.query('SELECT group_concat(0x0a,host,0x3a,user) FROM mysql.user;')\n query.each { |x| puts \"#{x[0]}\".white }\n print_line(\"\")\n user = Readline.readline(\"(Username to DROP)> \", true)\n host = Readline.readline(\"(Host Entry for #{user.chomp} to DROP)> \", true)\n answer = Readline.readline(\"(Confirm: DROP #{user.chomp}@#{host.chomp} (Y/N))> \", true)\n if \"#{answer.chomp.upcase}\" == \"YES\" or \"#{answer.chomp.upcase}\" == \"Y\"\n print_status(\"OK, sending DROP request.....\")\n begin\n query = @db_connection.query('USE mysql;')\n query = @db_connection.query(\"DROP USER '#{user.chomp}'@'#{host.chomp}';\")\n query = @db_connection.query('FLUSH PRIVILEGES;')\n rescue Mysql::Error => e\n print_error(\"Problem with DROP!\")\n print_error(\"#{e}\")\n end\n print_status(\"Updated MySQL Users & Host Info: \")\n query = @db.query('SELECT group_concat(0x0a,host,0x3a,user) FROM mysql.user;')\n query.each { |x| print_line(\"#{x[0]}\") }\n print_line(\"\")\n else\n print_error(\"OK, aborting User DROP and Returning to Main Menu...\")\n end\n end",
"def deleteDisConUser(idUser,idChannel)\n \n begin\n query = \"DELETE FROM `#{DB_NAME}`.`#{USER_LIST_IN_CHAN_TABBLE}` WHERE `#{USER_LIST_IN_CHAN_TABBLE}`.`user_id_user` = ? AND `#{USER_LIST_IN_CHAN_TABBLE}`.`channel_id_channel` = ?\"\n queryReset = \"ALTER TABLE #{USER_LIST_IN_CHAN_TABBLE} AUTO_INCREMENT = 1\"\n self.connect unless self.connected? # => connect to the DB server if not connected\n sth = @dbh.prepare(query)\n sth.execute(idUser,idChannel)\n sth = @dbh.prepare(queryReset)\n sth.execute\n \n sth.finish\n rescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\n @dbh.rollback\n rescue Exception => e \n puts \"error!!! -> : #{e.to_s}\"\n \n ensure\n # disconnect from server\n @dbh.disconnect if @connected\n @connected=false\n end\n \n \n end",
"def test_user_delete\n # Get the user info\n user = get_user_by_username('test-ruby-user12356')\n # Check to see if the returned user was the correct one.\n # Doubles to check whether the returned data exists in a proper form\n assert_equal('test-ruby-user12356', user['UserName'])\n # Delete the user based upon the returned user's id\n ap delete_user_data(user['UserId'])\n # assert if referencing this user, again, causes an error.\n user = get_user_by_username('test-ruby-user12356')\n assert_raise { delete_user_data(user['UserId']) }\n end",
"def chimp_remove(options, delete_user=true, send_goodbye=false, send_notify=false)\n begin\n raise MailChimpAPI::DeleteError, \"Email and Mailing List Id can't be nil\" if (options[:email].nil? || options[:mailing_list_id].nil?)\n @client.call(\"listUnsubscribe\", @api_key, options[:mailing_list_id], options[:email], delete_user, send_goodbye, send_notify) \n rescue XMLRPC::FaultException => e\n raise MailChimpAPI::DeleteError, e.faultString\n end \n end",
"def delete_kms_config 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_delete_kms_config_request request_pb\n query_string_params = if query_string_params.any?\n query_string_params.to_h { |p| p.split \"=\", 2 }\n else\n {}\n end\n\n response = @client_stub.make_http_request(\n verb,\n uri: uri,\n body: body || \"\",\n params: query_string_params,\n options: options\n )\n operation = ::Gapic::Rest::TransportOperation.new response\n result = ::Google::Longrunning::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def revoke(user_id)\n require_user\n\n user = User.find(user_id)\n user.secrets.each do |secret|\n secret.destroy\n end\n\n user.destroy\n end",
"def delete(*args)\n arguments(args)\n params = arguments.params\n params['data'] = arguments.remaining unless arguments.remaining.empty?\n\n delete_request(\"/user/emails\", params)\n end",
"def destroy\n @configuration_key.destroy\n respond_to do |format|\n format.html { redirect_to configuration_keys_url }\n format.json { head :no_content }\n end\n end",
"def delete()\n @client.make_request(:delete, @client.concat_user_path(\"#{DOMAIN_PATH}/#{domain_id}/endpoints/#{id}\"))[0]\n end",
"def delete_state_for_user(opts = {})\n uri = \"/v3/botstate/#{opts['channel_id']}/users/#{opts['user_id']}\"\n api_delete(uri)\n end",
"def delete_communication_channel_type(user_id,type,address,opts={})\n query_param_keys = [\n \n ]\n\n form_param_keys = [\n \n ]\n\n # verify existence of params\n raise \"user_id is required\" if user_id.nil?\n raise \"type is required\" if type.nil?\n raise \"address is required\" if address.nil?\n # set default values and merge with input\n options = underscored_merge_opts(opts,\n :user_id => user_id,\n :type => type,\n :address => address\n )\n\n # resource path\n path = path_replace(\"/v1/users/{user_id}/communication_channels/{type}/{address}\",\n :user_id => user_id,\n :type => type,\n :address => address)\n headers = nil\n form_params = select_params(options, form_param_keys)\n query_params = select_params(options, query_param_keys)\n if opts[:next_page]\n pagination_params = page_params_load(:delete, path)\n query_params.merge! pagination_params if pagination_params\n end\n response = mixed_request(:delete, path, query_params, form_params, headers)\n page_params_store(:delete, path)\n CommunicationChannel.new(response)\n end",
"def delete(key)\n configuration.delete(key)\n end",
"def delete_user(user)\n users = roles\n existing = users[\"cloudant\"]\n \n existing.delete(user) if existing\n update_roles(users)\n end",
"def destroy\n @user_car_setting.destroy\n respond_to do |format|\n format.html { redirect_to _user_car_settings_url, notice: 'Configuración eliminada' }\n format.json { head :no_content }\n end\n end",
"def delete_user\n end",
"def remove\n system(\"qconf -duser #{name}\")\n end",
"def delete_user(user_name:)\n validate_user_name(:user_name, user_name)\n\n wrap_response(@connection.delete(user_path(user_name))).fmap { |r| SftpgoClient::ApiResponse.new(r.body) }\n end",
"def delete_all_test_users\n\n if @appAccessToken.nil?\n _obtain_app_access_token\n end\n\n users = list_test_users()\n users.each do |user|\n delete_test_user(user['id'])\n end\n end",
"def delete_user(id)\n elektron_identity.delete(\"users/#{id}\")\n end",
"def batch_delete_user_links 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_batch_delete_user_links_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::Protobuf::Empty.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def delete_user_route(user)\n self.client.delete(\"gh.storage.user.#{user}\")\n end",
"def delete current_user\n raise RequestError.new(:internal_error, \"Delete: no user specified\") if current_user.nil?\n\n # remove all its files\n self.files.each { |item| item.delete current_user }\n # remove all its children, meaning all its subdirectories. (all sub-sub-directories and sub-files will me removed as well)\n self.childrens.each { |children| children.delete current_user }\n\n if current_user.id != self.user_id then # if random owner \n # remove all links between this folder and the current user only\n FileUserAssociation.all(x_file_id: self.id, user_id: current_user.id).destroy!\n # remove all associations where this folder is a children of a folder belonging to the current user only\n FolderFolderAssociation.all(children_id: self.id).each do |asso|\n asso.destroy! if current_user.x_files.get(asso.parent_id)\n end\n # No sharing for folders: no SharedToMeAssociations\n\n else # if true owner \n # remove all links between this folder and ALL users\n FileUserAssociation.all(x_file_id: self.id).destroy!\n # remove all associations where this folder is a children of a folder belonging ALL users\n FolderFolderAssociation.all(children_id: self.id).destroy!\n # No sharing for folders: no SharedByMeAssociations\n\n # No need to remove the association where this folder is a parent (of a file or folder)\n # because the children have already been removed and all theirs associations\n #\n # FolderFolderAssociation.all(parent_id: self.id).destroy!\n # FileFolderAssociation.all(parent_id: self.id).destroy!\n \n # now remove the entity\n self.destroy!\n end\n end",
"def user_delete(user_id)\n res = http_delete(:uri=>\"/users/#{user_id}\", :fields=>x_cookie)\n return res.code\n end",
"def delete(filters, user)\n if filters.empty?\n body = \"sql=DELETE FROM #{@id}\"\n connector.post \"https://www.googleapis.com/fusiontables/v2/query\", body\n else\n row_ids = query_row_ids(filters)\n row_ids.each do |row_id|\n body = \"sql=DELETE FROM #{@id} WHERE ROWID = '#{row_id}';\"\n connector.post \"https://www.googleapis.com/fusiontables/v2/query\", body\n end\n end\n end",
"def delete(user)\n @@contact_list.delete(user)\n end",
"def delete_ssh_key(id, options = {})\n user_id = options.delete :user_id\n if user_id.to_i.zero?\n delete(\"/user/keys/#{id}\")\n else\n delete(\"/users/#{user_id}/keys/#{id}\")\n end\n end",
"def destroy\n @user_setting.destroy\n respond_to do |format|\n format.html { redirect_to user_settings_url, notice: 'User setting was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete_user_attribute_definition(name, headers=default_headers)\n @logger.info(\"Deleting the \\\"#{name}\\\" User Attribute Definition\")\n delete(\"#{@api_url}/userAttributeDefinitions/#{encode(name)}\", headers)\n end",
"def backend_deleteUser(param) \n @Tasks.delete(param) if @Tasks.include? param \n end",
"def delete_save(params, userid)\n db = connect()\n db.execute('DELETE FROM users_discussions WHERE UserId=? AND DiscId=?', userid, params[\"id\"])\n end",
"def delete_user(user, options = {})\n boolean_from_response :delete, \"/users/#{user}\", options\n end",
"def delete_user_link 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_delete_user_link_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::Protobuf::Empty.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\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 remove_user\n query_api '/rest/user', nil, 'DELETE'\n end",
"def destroy_configuration_with_http_info(configuration_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: UsersApi.destroy_configuration ...'\n end\n # verify the required parameter 'configuration_id' is set\n if @api_client.config.client_side_validation && configuration_id.nil?\n fail ArgumentError, \"Missing the required parameter 'configuration_id' when calling UsersApi.destroy_configuration\"\n end\n # resource path\n local_var_path = '/users/me/configurations/{configuration_id}'.sub('{' + 'configuration_id' + '}', CGI.escape(configuration_id.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: UsersApi#destroy_configuration\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def cfgremove(fabrickey, cfgname, *zonenames)\n result = @zones.altercfg(fabrickey, 'REMOVE', cfgname, *zonenames)\n result[1]\n end",
"def delete_app_members(owner:, platform:, app_id:, users:)\n endpoint = \"/api/users/#{owner}/platforms/#{platform}/apps/#{app_id}/members\"\n res = api.delete endpoint do |request|\n request.headers['Content-Type'] = 'application/x-www-form-urlencoded'\n request.body = URI.encode_www_form(\n users: users\n )\n end\n Response.new(res)\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n redirect_to settings_path\n end",
"def delete_per_instance_configs request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n uri, body, _query_string_params = transcode_delete_per_instance_configs_request request_pb\n response = @client_stub.make_post_request(\n uri: uri,\n body: body,\n options: options\n )\n result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, response if block_given?\n result\n end",
"def delete_user_provider(user_id, provider_name)\n raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty?\n raise Auth0::InvalidParameter, 'Must supply a valid provider name' if provider_name.to_s.empty?\n path = \"#{users_path}/#{user_id}/multifactor/#{provider_name}\"\n delete(path)\n end",
"def delete(key)\n @configuration.delete(key)\n end",
"def delete(key)\n @configuration.delete(key)\n end",
"def delete(key)\n @configuration.delete(key)\n end",
"def delete_user request_pb, options:, &block\n request_json = JSON.parse ::Google::Showcase::V1beta1::DeleteUserRequest.encode_json(request_pb)\n\n uri = \"/v1beta1/#{request_pb.name}\"\n\n result_json = @client_stub.make_delete_request(\n uri: uri,\n options: options,\n &block\n )\n\n ::Google::Protobuf::Empty.decode_json result_json[:body]\n end",
"def destroy\n conf.delete 'api'\n end",
"def remove_user\n query_api \"/rest/user\", nil, \"DELETE\"\n end",
"def delete_user_account\n # delete their favorites before deleting user\n User.all.destroy(current_user.id)\n puts \"\n Your account have been removed! I will never tell, xoxo\n \"\n \n end",
"def delete_communication_channel_id(user_id,id,opts={})\n query_param_keys = [\n \n ]\n\n form_param_keys = [\n \n ]\n\n # verify existence of params\n raise \"user_id is required\" if user_id.nil?\n raise \"id is required\" if id.nil?\n # set default values and merge with input\n options = underscored_merge_opts(opts,\n :user_id => user_id,\n :id => id\n )\n\n # resource path\n path = path_replace(\"/v1/users/{user_id}/communication_channels/{id}\",\n :user_id => user_id,\n :id => id)\n headers = nil\n form_params = select_params(options, form_param_keys)\n query_params = select_params(options, query_param_keys)\n if opts[:next_page]\n pagination_params = page_params_load(:delete, path)\n query_params.merge! pagination_params if pagination_params\n end\n response = mixed_request(:delete, path, query_params, form_params, headers)\n page_params_store(:delete, path)\n CommunicationChannel.new(response)\n end",
"def delete\n decoded_access_token = JWT.decode(params[:accessToken], 's3cr3t', true, algorithm: 'HS256')\n decoded_refresh_token = JWT.decode(params[:refreshToken], 's3cr3t', true, algorithm: 'HS256')\n # Check if token was decoded\n if decoded_access_token && decoded_refresh_token\n @user = User.find_by(id: decoded_access_token[0]['user_id'])\n if @user # user exists\n Blacklist.find_by(jwt: params[:accessToken]).delete\n Blacklist.find_by(jwt: params[:refreshToken]).delete\n User.find_by(id: @user.id).delete\n render json: {status: \"User was succesfully deleted\"}\n else\n render json: {error: \"Invalid User\"}\n end\n else # token is null\n render json: {error: \"Invalid Tokens\"}\n end\n end"
] |
[
"0.63192755",
"0.6188074",
"0.6020709",
"0.57504666",
"0.5740285",
"0.5730853",
"0.5721952",
"0.5720881",
"0.56811994",
"0.5675205",
"0.56726784",
"0.56510687",
"0.5618423",
"0.560963",
"0.55755097",
"0.55283844",
"0.5501779",
"0.5474209",
"0.5467514",
"0.54620034",
"0.5459944",
"0.54376346",
"0.5433023",
"0.5426084",
"0.54186565",
"0.5416787",
"0.54060686",
"0.5387622",
"0.5381792",
"0.5373922",
"0.5370561",
"0.53449106",
"0.5342579",
"0.5342579",
"0.5340431",
"0.53324825",
"0.532545",
"0.5323346",
"0.5314105",
"0.530232",
"0.5298427",
"0.5288931",
"0.5286777",
"0.5286777",
"0.52807033",
"0.5261184",
"0.5258025",
"0.52557456",
"0.5252199",
"0.5250888",
"0.5250888",
"0.5249327",
"0.52438647",
"0.5238349",
"0.52324283",
"0.52303547",
"0.5223963",
"0.5223263",
"0.52211213",
"0.5213316",
"0.5209903",
"0.5205135",
"0.5194379",
"0.5190103",
"0.51894057",
"0.51869345",
"0.5173338",
"0.5172822",
"0.51688933",
"0.5163238",
"0.51580036",
"0.51418304",
"0.51415044",
"0.51254404",
"0.51191825",
"0.51123095",
"0.51052725",
"0.5104233",
"0.5100602",
"0.5093332",
"0.5087328",
"0.50872076",
"0.50833684",
"0.5082018",
"0.50801706",
"0.5075729",
"0.50661224",
"0.50514066",
"0.50511146",
"0.5049734",
"0.5047186",
"0.5046878",
"0.5046878",
"0.5046878",
"0.5039487",
"0.5033675",
"0.5030668",
"0.5029675",
"0.5024714",
"0.50231457"
] |
0.58200103
|
3
|
Get configuration of a user.
|
def users_id_user_config_get(id_user, opts = {})
data, _status_code, _headers = users_id_user_config_get_with_http_info(id_user, opts)
data
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def user\n return @user ? @user : Dotfu.config_user\n end",
"def get_user_conf(name, profile = 'default')\n return @config.find(name, profile) if @config\n @config = make_user_conf\n msg = 'Run the command `configure`'\n raise Idcf::Cli::CliError, msg unless @config\n\n @config.find(name, profile)\n end",
"def user_for_conf_snippet(config)\n user = config[:user]\n if user.to_i > 0\n user = User.active.find(user)\n elsif user.is_a? String\n user = User.active.find_by_email(user)\n end\n\n app_type = config[:app_type]\n user = User.use_batch_user(app_type) if user.nil? && app_type\n user\n end",
"def user_configuration\n @user_configuration ||=\n begin\n path = File.join(::Rails.root, 'config', 'sunspot.yml')\n if File.exist?(path)\n File.open(path) do |file|\n processed = ERB.new(file.read).result\n YAML.load(processed)[::Rails.env]\n end\n else\n {}\n end\n end\n end",
"def user_configuration\n @user_configuration ||=\n begin\n path = File.join(::Rails.root, 'config', 'sunspot.yml')\n if File.exist?(path)\n File.open(path) do |file|\n YAML.load(file)[::Rails.env]\n end\n end\n end\n end",
"def user\n conf['api']['user']\n end",
"def get_user(id)\n @client.raw('get', \"/config/users/#{id}\")\n end",
"def user\n return config[:user] unless config[:user].nil?\n\n require \"train/transports/ssh\"\n Train::Transports::SSH.default_options[:user][:default]\n end",
"def user_configuration\n @user_configuration ||= begin\n path = File.join(::Rails.root, 'config', 'piwik.yml')\n if File.exist?(path)\n File.open(path) do |file|\n processed = ERB.new(file.read).result\n YAML.load(processed)[::Rails.env]['piwik']\n end\n else\n {}\n end\n end\n end",
"def user\n Reggora::Resources::User.new(config)\n end",
"def load_config()\n rspec_file = '.rspec'\n full_config = YAML::load(File.open('./config/users.yaml')) # full YML\n puts \"\\n>Loaded user configuration for: \" + ENV['env_name'].to_s # only section of YML that is relevant for the particular environment\n return full_config[ENV['env_name']] # only section of YML that is relevant for the particular environment\nend",
"def user_id\n config.present? ? config[:user_id] : ''\n end",
"def find_user_setting\n\t\t# find the user setting\n\t\t@user = devise_current_user.profile_setting\n\tend",
"def user\n conf['dashboard']['user']\n end",
"def user_config(key)\n Autoproj.user_config(key)\nend",
"def set_userconfig\n @userconfig = Userconfig.find(params[:id])\n end",
"def email\n connect\n user = self.class.query('CMD_API_SHOW_USER_CONFIG',\n :user => resource[:username]\n )\n return user[\"email\"]\n end",
"def default_user\n if (user_id = config.user_id).present?\n User.where(:id => user_id).first\n else\n nil\n end\n end",
"def set_config_user\n @config_user = ConfigUser.find(params[:id])\n end",
"def user\n @user ||= opts.fetch(:user, parsed_opt('user'))\n end",
"def for_user(user)\n self.class.new(@config, user)\n end",
"def config\n @config ||= read_config\n end",
"def get_config()\n return @api.do_request(\"GET\", get_base_api_path() + \"/config\")\n end",
"def get_user_info\n response = send_method(:get_user_info)\n user_from(response)\n end",
"def get_user_info\n get(\"/api/v1/oauth_user_info.json\")\n end",
"def find_user_setting\n\t\t# find the user setting\n\t\t@user = current_user.profile_setting\n\tend",
"def get_user\n return if @user # no extra http calls\n url = URI.escape(\"#{@options[:cas_server]}/#{@options[:uid]}.#{@options[:format]}\")\n response = Casport.get(url)\n if response.success?\n @user = response.parsed_response\n else\n @user = nil\n end\n end",
"def configuration\n Configuration::get\n end",
"def configuration\n Configuration::get\n end",
"def user_id; config[:user_id]; end",
"def user\n ActiveScaffold::Registry.user_settings[user_settings_key]\n end",
"def get_config\n\t\tend",
"def config\n @config ||= load_config\n end",
"def users_id_user_config_get_with_http_info(id_user, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: UsersManagementApi.users_id_user_config_get ...'\n end\n # verify the required parameter 'id_user' is set\n if @api_client.config.client_side_validation && id_user.nil?\n fail ArgumentError, \"Missing the required parameter 'id_user' when calling UsersManagementApi.users_id_user_config_get\"\n end\n # resource path\n local_var_path = '/users/{id_user}/config'.sub('{' + 'id_user' + '}', id_user.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/x-www-form-urlencoded'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['api_key']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Object')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: UsersManagementApi#users_id_user_config_get\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def user\n @user ||= @repo.config.username\n end",
"def user\n return Etc.getlogin\n end",
"def config_get(id)\n Configuration.get(id)\n end",
"def user_configuration_from_key( *keys )\n keys.inject(user_configuration) do |hash, key|\n hash[key] if hash\n end\n end",
"def userinfo\n unless defined?(@userinfo)\n @userinfo = solr_url.userinfo if solr_url\n user = user_configuration_from_key('solr', 'user')\n pass = user_configuration_from_key('solr', 'pass')\n @userinfo ||= [ user, pass ].compact.join(\":\") if user && pass\n @userinfo ||= default_userinfo\n end\n @userinfo\n end",
"def user \n @user ||= @repo.config.username\n end",
"def get_user(user_id:)\n parse(JSON.parse(connection.get(\"users/#{user_id}\").body))\n end",
"def loadUser(userName)\n if(userName == nil)\n return nil\n end\n userFile = @CONFIG_ROOT+@CONFIG_REST_PATH+userName+\".yaml\"\n if File.exist?(userFile)\n user = YAML.load_file(userFile)\n #puts \"User: #{user}\"\n return user\n end\n return nil\n end",
"def getUserDetails\n\t\tuser = java.util.HashMap.new()\n\t\t# user name\n\t\tuser.put(KEY_NAME, @pref.getString(KEY_NAME, nil))\n\t\t\n\t\t# user email id\n\t\tuser.put(KEY_EMAIL, @pref.getString(KEY_EMAIL, nil))\n\t\t\n\t\t# return user\n\t\treturn user;\n\tend",
"def user_configuration_from_key( *keys )\n keys.inject(user_configuration) do |hash, key|\n hash[key] if hash\n end\n end",
"def user\n @user ||= @uri && client.user(@uri.split(':')[2])\n end",
"def config( untrusted: false )\n\t\toptions = { untrusted: untrusted }\n\t\tconfig = self.server.run_with_json_template( :showconfig, **options )\n\t\treturn Hglib::Config.new( config )\n\tend",
"def userinfo\n if @user.nil?\n nil\n elsif @password.nil?\n @user\n else\n @user + ':' + @password\n end\n end",
"def get_user \n\t\treturn User.find(self.user_id)\n\tend",
"def user_info\n response = from_server \"api/user.json\"\n response.data\n end",
"def list_users\n abort \"You have no users within your config file!\".yellow if config.empty?\n puts \"\\nUser Configuration\"\n config.each do |k, v|\n next if k == 'current_user'\n puts \"\\nEnvironment: #{k}\"\n print_hash_values v\n end\n\n list_current_user if current_user_exists?\n end",
"def getUser()\n\t\treturn @user\n\tend",
"def retrieve(user_id:)\n User.new get_request(\"users/#{user_id}\").body.dig(\"user\")\n end",
"def user\n return ENV['USER']\n end",
"def get(user_id, campaign_key)\n # example code to fetch it\n # You could also fetch from DB like User.find_by_vwo_id(user_id).settings\n @@user_storage[user_id]\n end",
"def configuration\n _get(\"/system/configuration\") { |json| json }\n end",
"def client\n @client ||= begin\n config(file: true) if !user_id\n User.new(user_id, password, security_code)\n end\n end",
"def login_from_config\n self.current_user = User.find(BETY_USER) if defined? BETY_USER\n end",
"def username\n @config['username']\n end",
"def user=(value)\n conf['api']['user'] = value\n end",
"def user(user=nil, options = {})\n get User.path(user), options\n end",
"def get_current_user_options\n response = get_current_user_meta('options')\n ret = {}\n response['query']['userinfo']['options'].each { |k, v| ret[k] = v }\n end",
"def configuration(name)\n Alchemy::Config.get(name)\n end",
"def phone_configuration\n MfaContext.new(current_user).phone_configurations.first\n end",
"def config\n path = config_path\n @config ||= path.exist? ? JSON.parse(path.read) : {}\n end",
"def get_users(options)\n @client.raw('get', '/config/users', options)\n end",
"def database_config(db)\n puts \"database config called for #{db}\"\n database = YAML::load_file('config/database.yml')\n return (database[\"#{db}\"]['username'] || database[\"#{db}\"]['user']), database[\"#{db}\"]['password'], database[\"#{db}\"]['database'], database[\"#{db}\"]['host']\nend",
"def config\n @options[:config]\n end",
"def config\n configuration\n end",
"def user\n UserRepository.find(user_id)\n end",
"def user\n return self['user'] if self['user'].is_a?(User)\n User.new(self['user']) if self['user']\n end",
"def user_info\n auth_hash['user_info']\n end",
"def getUser(sessionId, userName)\n fullPath = \"#{@APPLICATION_HOME}/dashboard/.profiles/#{userName}.yaml\"\n if(userName != nil)\n\n return YAML.load_file(fullPath)\n end\n end",
"def config( user_email, user_name )\n\n log.info(x) { \"[git] local config for user.email => #{user_email}\" }\n log.info(x) { \"[git] local config for user.name => #{user_name}\" }\n path_to_dot_git = File.join( @git_folder_path, \".git\" )\n git_config_email_cmd = \"git --git-dir=#{path_to_dot_git} --work-tree=#{@git_folder_path} config --local user.email \\\"#{user_email}\\\";\"\n git_config_name_cmd = \"git --git-dir=#{path_to_dot_git} --work-tree=#{@git_folder_path} config --local user.name \\\"#{user_name}\\\";\"\n log.info(x) { \"[git] configure user.email command => #{git_config_email_cmd}\" }\n log.info(x) { \"[git] configure user.name command => #{git_config_name_cmd}\" }\n %x[#{git_config_email_cmd}];\n %x[#{git_config_name_cmd}];\n log.info(x) { \"[git] has locally configured the user.email and user.name properties.\" }\n\n end",
"def user(user_name)\n OctocatHerder::User.fetch(user_name, connection)\n end",
"def config\n requester.config \n end",
"def get_user(name)\n @file = \"/private/var/db/dslocal/nodes//#{resource[:dslocal_node]}/users/#{name}.plist\"\n NSMutableDictionary.dictionaryWithContentsOfFile(@file)\n end",
"def get_user_info\n userTokenInfo = request.env['oauth.token']\n @user = userTokenInfo.user\n end",
"def user_info\n\t\t@user_info ||= fetch_latest_user_info\n\tend",
"def config\n @config_file\n end",
"def get_user(name)\n file = \"#{@@path_to_user_plists}/#{name}.plist\"\n user = NSMutableDictionary.dictionaryWithContentsOfFile(file)\n end",
"def file( config_file )\n unless File.exists?( config_file )\n raise BadConfigurationException, \"No user defined configuration \" + \n \"file found at #{config_file}.\"\n else\n begin\n config = YAML.load_file(config_file)\n unless config.respond_to? :[]\n raise BadConfigurationException, \"YAML file expected to contain \"+\n \"a hash but did not. Fix #{config_file} and try again.\" \n else\n return config.symbolize_keys!(:deep)\n end\n rescue Exception => e\n raise BadConfigurationException, \"Failed to load user defined \" +\n \"configuration file #{config_file}.\\n\\t#{e}\"\n end\n end \n end",
"def user()\n return @data[\"access\"][\"user\"]\n end",
"def user\n User.load(self.user_id)\n end",
"def user\n\t\t\treturn nil if ! logged_in?\n\n\t\t\tPicombo::Session.instance.get('user')\n\t\tend",
"def config\r\n @configuration\r\n end",
"def get_actual_config\n @config\n end",
"def user\n {user_id: self.object.user.id,\n user_name: self.object.user.name\n }\n end",
"def config\n if Config.config.nil? or Config.config.empty?\n begin\n Config.config = Configuration.load_config(Config.config_file,\n Config.config_options)\n rescue Errno::ENOENT\n Config.config = {}\n end\n end\n\n return Config.config\n end",
"def get_user(user_name:)\n validate_user_name(:user_name, user_name)\n\n wrap_response(@connection.get(user_path(user_name))).fmap { |r|\n SftpgoClient::User.new(r.body)\n }\n end",
"def user\n @user ||= Hyrax::Migrator::HyraxCore::User.find(config.migration_user)\n end",
"def get_user\n @user = User.find(params[:user_id])\n end",
"def user\n @user ||= OctocatHerder::User.fetch(@raw['user'], connection)\n end",
"def auth\n cfg_get(:auth)\n end",
"def config_path\n NginxStage.pun_config_path(user: user)\n end",
"def get_user(user_id)\n return User.find(user_id)\n end",
"def configuration\n cfg = {}\n cfg[:author_avpair] = @author_avpair.name if (@author_avpair)\n cfg[:command_authorization_profile] = @command_authorization_profile.name if (@command_authorization_profile)\n cfg[:disabled] = self.disabled? if (self.disabled?)\n cfg[:enable_password] = @enable_password if (@enable_password)\n cfg[:enable_password_expires_on] = @enable_password_expires_on.to_s if (@enable_password_expires_on)\n cfg[:enable_password_lifespan] = @enable_password_lifespan if (@enable_password_lifespan != 0)\n cfg[:enable_acl] = @enable_acl.name if (@enable_acl)\n cfg[:encryption] = @encryption.to_s if (@encryption)\n cfg[:login_acl] = @login_acl.name if (@login_acl)\n cfg[:login_password] = @login_password if (@login_password)\n cfg[:login_password_expires_on] = @login_password_expires_on.to_s if (@login_password_expires_on)\n cfg[:login_password_lifespan] = @login_password_lifespan if (@login_password_lifespan != 0)\n cfg[:salt] = @salt if (@salt)\n cfg[:user_group] = @user_group.name if (@user_group)\n return(cfg)\n end",
"def user\r\n return for_context(nil, false) { |c| c.user }\r\n end",
"def get(user_id)\n get_request(t_url(:user, user_id))\n end",
"def get_config_file_for(name)\n if File.exists?(\"#{user_dir}/config/#{name}\")\n \"#{user_dir}/config/#{name}\"\n else\n \"#{root_dir}/config/#{name}\"\n end\n end",
"def user\n parse!\n @user\n end"
] |
[
"0.7608732",
"0.69656116",
"0.695211",
"0.6923802",
"0.6881822",
"0.68037903",
"0.66993177",
"0.6683868",
"0.659677",
"0.6588131",
"0.6494486",
"0.6449822",
"0.63754636",
"0.63709944",
"0.63602316",
"0.63568",
"0.63528556",
"0.63398063",
"0.6335",
"0.6328503",
"0.6317483",
"0.6293827",
"0.6272786",
"0.62626946",
"0.62000483",
"0.61994207",
"0.61936647",
"0.6150077",
"0.6150077",
"0.6103837",
"0.6103068",
"0.60283965",
"0.5983031",
"0.59539324",
"0.5936213",
"0.59235543",
"0.59184647",
"0.5911295",
"0.591091",
"0.59014463",
"0.5892764",
"0.58915955",
"0.58824056",
"0.58796924",
"0.58754987",
"0.5872274",
"0.58697236",
"0.58676606",
"0.58666474",
"0.5863029",
"0.58480674",
"0.58406407",
"0.5840465",
"0.5839107",
"0.5818183",
"0.5804923",
"0.57832795",
"0.57830137",
"0.5769027",
"0.57673204",
"0.5762951",
"0.57561904",
"0.5753141",
"0.5747415",
"0.57464707",
"0.57303876",
"0.57187223",
"0.57174766",
"0.571704",
"0.5711914",
"0.5704374",
"0.57024205",
"0.57014686",
"0.56865114",
"0.5685322",
"0.5683726",
"0.5683552",
"0.56795216",
"0.5671741",
"0.5666263",
"0.5663733",
"0.5663088",
"0.5662078",
"0.5656702",
"0.5656441",
"0.5653076",
"0.56479645",
"0.5638435",
"0.56088185",
"0.56071264",
"0.5601423",
"0.55947834",
"0.55944616",
"0.5589737",
"0.55856097",
"0.55854404",
"0.5585222",
"0.55849916",
"0.5584263",
"0.5580016"
] |
0.65630186
|
10
|
Get configuration of a user.
|
def users_id_user_config_get_with_http_info(id_user, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersManagementApi.users_id_user_config_get ...'
end
# verify the required parameter 'id_user' is set
if @api_client.config.client_side_validation && id_user.nil?
fail ArgumentError, "Missing the required parameter 'id_user' when calling UsersManagementApi.users_id_user_config_get"
end
# resource path
local_var_path = '/users/{id_user}/config'.sub('{' + 'id_user' + '}', id_user.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['api_key']
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Object')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersManagementApi#users_id_user_config_get\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def user\n return @user ? @user : Dotfu.config_user\n end",
"def get_user_conf(name, profile = 'default')\n return @config.find(name, profile) if @config\n @config = make_user_conf\n msg = 'Run the command `configure`'\n raise Idcf::Cli::CliError, msg unless @config\n\n @config.find(name, profile)\n end",
"def user_for_conf_snippet(config)\n user = config[:user]\n if user.to_i > 0\n user = User.active.find(user)\n elsif user.is_a? String\n user = User.active.find_by_email(user)\n end\n\n app_type = config[:app_type]\n user = User.use_batch_user(app_type) if user.nil? && app_type\n user\n end",
"def user_configuration\n @user_configuration ||=\n begin\n path = File.join(::Rails.root, 'config', 'sunspot.yml')\n if File.exist?(path)\n File.open(path) do |file|\n processed = ERB.new(file.read).result\n YAML.load(processed)[::Rails.env]\n end\n else\n {}\n end\n end\n end",
"def user_configuration\n @user_configuration ||=\n begin\n path = File.join(::Rails.root, 'config', 'sunspot.yml')\n if File.exist?(path)\n File.open(path) do |file|\n YAML.load(file)[::Rails.env]\n end\n end\n end\n end",
"def user\n conf['api']['user']\n end",
"def get_user(id)\n @client.raw('get', \"/config/users/#{id}\")\n end",
"def user\n return config[:user] unless config[:user].nil?\n\n require \"train/transports/ssh\"\n Train::Transports::SSH.default_options[:user][:default]\n end",
"def user_configuration\n @user_configuration ||= begin\n path = File.join(::Rails.root, 'config', 'piwik.yml')\n if File.exist?(path)\n File.open(path) do |file|\n processed = ERB.new(file.read).result\n YAML.load(processed)[::Rails.env]['piwik']\n end\n else\n {}\n end\n end\n end",
"def user\n Reggora::Resources::User.new(config)\n end",
"def users_id_user_config_get(id_user, opts = {})\n data, _status_code, _headers = users_id_user_config_get_with_http_info(id_user, opts)\n data\n end",
"def load_config()\n rspec_file = '.rspec'\n full_config = YAML::load(File.open('./config/users.yaml')) # full YML\n puts \"\\n>Loaded user configuration for: \" + ENV['env_name'].to_s # only section of YML that is relevant for the particular environment\n return full_config[ENV['env_name']] # only section of YML that is relevant for the particular environment\nend",
"def user_id\n config.present? ? config[:user_id] : ''\n end",
"def find_user_setting\n\t\t# find the user setting\n\t\t@user = devise_current_user.profile_setting\n\tend",
"def user\n conf['dashboard']['user']\n end",
"def user_config(key)\n Autoproj.user_config(key)\nend",
"def set_userconfig\n @userconfig = Userconfig.find(params[:id])\n end",
"def email\n connect\n user = self.class.query('CMD_API_SHOW_USER_CONFIG',\n :user => resource[:username]\n )\n return user[\"email\"]\n end",
"def default_user\n if (user_id = config.user_id).present?\n User.where(:id => user_id).first\n else\n nil\n end\n end",
"def set_config_user\n @config_user = ConfigUser.find(params[:id])\n end",
"def user\n @user ||= opts.fetch(:user, parsed_opt('user'))\n end",
"def for_user(user)\n self.class.new(@config, user)\n end",
"def config\n @config ||= read_config\n end",
"def get_config()\n return @api.do_request(\"GET\", get_base_api_path() + \"/config\")\n end",
"def get_user_info\n response = send_method(:get_user_info)\n user_from(response)\n end",
"def get_user_info\n get(\"/api/v1/oauth_user_info.json\")\n end",
"def find_user_setting\n\t\t# find the user setting\n\t\t@user = current_user.profile_setting\n\tend",
"def get_user\n return if @user # no extra http calls\n url = URI.escape(\"#{@options[:cas_server]}/#{@options[:uid]}.#{@options[:format]}\")\n response = Casport.get(url)\n if response.success?\n @user = response.parsed_response\n else\n @user = nil\n end\n end",
"def configuration\n Configuration::get\n end",
"def configuration\n Configuration::get\n end",
"def user_id; config[:user_id]; end",
"def user\n ActiveScaffold::Registry.user_settings[user_settings_key]\n end",
"def get_config\n\t\tend",
"def config\n @config ||= load_config\n end",
"def user\n @user ||= @repo.config.username\n end",
"def user\n return Etc.getlogin\n end",
"def config_get(id)\n Configuration.get(id)\n end",
"def user_configuration_from_key( *keys )\n keys.inject(user_configuration) do |hash, key|\n hash[key] if hash\n end\n end",
"def userinfo\n unless defined?(@userinfo)\n @userinfo = solr_url.userinfo if solr_url\n user = user_configuration_from_key('solr', 'user')\n pass = user_configuration_from_key('solr', 'pass')\n @userinfo ||= [ user, pass ].compact.join(\":\") if user && pass\n @userinfo ||= default_userinfo\n end\n @userinfo\n end",
"def user \n @user ||= @repo.config.username\n end",
"def get_user(user_id:)\n parse(JSON.parse(connection.get(\"users/#{user_id}\").body))\n end",
"def loadUser(userName)\n if(userName == nil)\n return nil\n end\n userFile = @CONFIG_ROOT+@CONFIG_REST_PATH+userName+\".yaml\"\n if File.exist?(userFile)\n user = YAML.load_file(userFile)\n #puts \"User: #{user}\"\n return user\n end\n return nil\n end",
"def getUserDetails\n\t\tuser = java.util.HashMap.new()\n\t\t# user name\n\t\tuser.put(KEY_NAME, @pref.getString(KEY_NAME, nil))\n\t\t\n\t\t# user email id\n\t\tuser.put(KEY_EMAIL, @pref.getString(KEY_EMAIL, nil))\n\t\t\n\t\t# return user\n\t\treturn user;\n\tend",
"def user_configuration_from_key( *keys )\n keys.inject(user_configuration) do |hash, key|\n hash[key] if hash\n end\n end",
"def user\n @user ||= @uri && client.user(@uri.split(':')[2])\n end",
"def config( untrusted: false )\n\t\toptions = { untrusted: untrusted }\n\t\tconfig = self.server.run_with_json_template( :showconfig, **options )\n\t\treturn Hglib::Config.new( config )\n\tend",
"def userinfo\n if @user.nil?\n nil\n elsif @password.nil?\n @user\n else\n @user + ':' + @password\n end\n end",
"def get_user \n\t\treturn User.find(self.user_id)\n\tend",
"def user_info\n response = from_server \"api/user.json\"\n response.data\n end",
"def list_users\n abort \"You have no users within your config file!\".yellow if config.empty?\n puts \"\\nUser Configuration\"\n config.each do |k, v|\n next if k == 'current_user'\n puts \"\\nEnvironment: #{k}\"\n print_hash_values v\n end\n\n list_current_user if current_user_exists?\n end",
"def getUser()\n\t\treturn @user\n\tend",
"def user\n return ENV['USER']\n end",
"def retrieve(user_id:)\n User.new get_request(\"users/#{user_id}\").body.dig(\"user\")\n end",
"def get(user_id, campaign_key)\n # example code to fetch it\n # You could also fetch from DB like User.find_by_vwo_id(user_id).settings\n @@user_storage[user_id]\n end",
"def configuration\n _get(\"/system/configuration\") { |json| json }\n end",
"def client\n @client ||= begin\n config(file: true) if !user_id\n User.new(user_id, password, security_code)\n end\n end",
"def username\n @config['username']\n end",
"def login_from_config\n self.current_user = User.find(BETY_USER) if defined? BETY_USER\n end",
"def user=(value)\n conf['api']['user'] = value\n end",
"def user(user=nil, options = {})\n get User.path(user), options\n end",
"def get_current_user_options\n response = get_current_user_meta('options')\n ret = {}\n response['query']['userinfo']['options'].each { |k, v| ret[k] = v }\n end",
"def configuration(name)\n Alchemy::Config.get(name)\n end",
"def phone_configuration\n MfaContext.new(current_user).phone_configurations.first\n end",
"def get_users(options)\n @client.raw('get', '/config/users', options)\n end",
"def config\n path = config_path\n @config ||= path.exist? ? JSON.parse(path.read) : {}\n end",
"def database_config(db)\n puts \"database config called for #{db}\"\n database = YAML::load_file('config/database.yml')\n return (database[\"#{db}\"]['username'] || database[\"#{db}\"]['user']), database[\"#{db}\"]['password'], database[\"#{db}\"]['database'], database[\"#{db}\"]['host']\nend",
"def config\n @options[:config]\n end",
"def config\n configuration\n end",
"def user\n UserRepository.find(user_id)\n end",
"def user\n return self['user'] if self['user'].is_a?(User)\n User.new(self['user']) if self['user']\n end",
"def user_info\n auth_hash['user_info']\n end",
"def getUser(sessionId, userName)\n fullPath = \"#{@APPLICATION_HOME}/dashboard/.profiles/#{userName}.yaml\"\n if(userName != nil)\n\n return YAML.load_file(fullPath)\n end\n end",
"def config( user_email, user_name )\n\n log.info(x) { \"[git] local config for user.email => #{user_email}\" }\n log.info(x) { \"[git] local config for user.name => #{user_name}\" }\n path_to_dot_git = File.join( @git_folder_path, \".git\" )\n git_config_email_cmd = \"git --git-dir=#{path_to_dot_git} --work-tree=#{@git_folder_path} config --local user.email \\\"#{user_email}\\\";\"\n git_config_name_cmd = \"git --git-dir=#{path_to_dot_git} --work-tree=#{@git_folder_path} config --local user.name \\\"#{user_name}\\\";\"\n log.info(x) { \"[git] configure user.email command => #{git_config_email_cmd}\" }\n log.info(x) { \"[git] configure user.name command => #{git_config_name_cmd}\" }\n %x[#{git_config_email_cmd}];\n %x[#{git_config_name_cmd}];\n log.info(x) { \"[git] has locally configured the user.email and user.name properties.\" }\n\n end",
"def user(user_name)\n OctocatHerder::User.fetch(user_name, connection)\n end",
"def config\n requester.config \n end",
"def get_user(name)\n @file = \"/private/var/db/dslocal/nodes//#{resource[:dslocal_node]}/users/#{name}.plist\"\n NSMutableDictionary.dictionaryWithContentsOfFile(@file)\n end",
"def get_user_info\n userTokenInfo = request.env['oauth.token']\n @user = userTokenInfo.user\n end",
"def user_info\n\t\t@user_info ||= fetch_latest_user_info\n\tend",
"def config\n @config_file\n end",
"def get_user(name)\n file = \"#{@@path_to_user_plists}/#{name}.plist\"\n user = NSMutableDictionary.dictionaryWithContentsOfFile(file)\n end",
"def user()\n return @data[\"access\"][\"user\"]\n end",
"def file( config_file )\n unless File.exists?( config_file )\n raise BadConfigurationException, \"No user defined configuration \" + \n \"file found at #{config_file}.\"\n else\n begin\n config = YAML.load_file(config_file)\n unless config.respond_to? :[]\n raise BadConfigurationException, \"YAML file expected to contain \"+\n \"a hash but did not. Fix #{config_file} and try again.\" \n else\n return config.symbolize_keys!(:deep)\n end\n rescue Exception => e\n raise BadConfigurationException, \"Failed to load user defined \" +\n \"configuration file #{config_file}.\\n\\t#{e}\"\n end\n end \n end",
"def user\n User.load(self.user_id)\n end",
"def user\n\t\t\treturn nil if ! logged_in?\n\n\t\t\tPicombo::Session.instance.get('user')\n\t\tend",
"def config\r\n @configuration\r\n end",
"def get_actual_config\n @config\n end",
"def user\n {user_id: self.object.user.id,\n user_name: self.object.user.name\n }\n end",
"def config\n if Config.config.nil? or Config.config.empty?\n begin\n Config.config = Configuration.load_config(Config.config_file,\n Config.config_options)\n rescue Errno::ENOENT\n Config.config = {}\n end\n end\n\n return Config.config\n end",
"def get_user(user_name:)\n validate_user_name(:user_name, user_name)\n\n wrap_response(@connection.get(user_path(user_name))).fmap { |r|\n SftpgoClient::User.new(r.body)\n }\n end",
"def user\n @user ||= Hyrax::Migrator::HyraxCore::User.find(config.migration_user)\n end",
"def get_user\n @user = User.find(params[:user_id])\n end",
"def auth\n cfg_get(:auth)\n end",
"def user\n @user ||= OctocatHerder::User.fetch(@raw['user'], connection)\n end",
"def config_path\n NginxStage.pun_config_path(user: user)\n end",
"def configuration\n cfg = {}\n cfg[:author_avpair] = @author_avpair.name if (@author_avpair)\n cfg[:command_authorization_profile] = @command_authorization_profile.name if (@command_authorization_profile)\n cfg[:disabled] = self.disabled? if (self.disabled?)\n cfg[:enable_password] = @enable_password if (@enable_password)\n cfg[:enable_password_expires_on] = @enable_password_expires_on.to_s if (@enable_password_expires_on)\n cfg[:enable_password_lifespan] = @enable_password_lifespan if (@enable_password_lifespan != 0)\n cfg[:enable_acl] = @enable_acl.name if (@enable_acl)\n cfg[:encryption] = @encryption.to_s if (@encryption)\n cfg[:login_acl] = @login_acl.name if (@login_acl)\n cfg[:login_password] = @login_password if (@login_password)\n cfg[:login_password_expires_on] = @login_password_expires_on.to_s if (@login_password_expires_on)\n cfg[:login_password_lifespan] = @login_password_lifespan if (@login_password_lifespan != 0)\n cfg[:salt] = @salt if (@salt)\n cfg[:user_group] = @user_group.name if (@user_group)\n return(cfg)\n end",
"def user\r\n return for_context(nil, false) { |c| c.user }\r\n end",
"def get_user(user_id)\n return User.find(user_id)\n end",
"def get_config_file_for(name)\n if File.exists?(\"#{user_dir}/config/#{name}\")\n \"#{user_dir}/config/#{name}\"\n else\n \"#{root_dir}/config/#{name}\"\n end\n end",
"def get(user_id)\n get_request(t_url(:user, user_id))\n end",
"def user\n parse!\n @user\n end"
] |
[
"0.7609335",
"0.6966791",
"0.69535536",
"0.692331",
"0.6881345",
"0.6804492",
"0.6700519",
"0.66837746",
"0.65965873",
"0.65890956",
"0.65634537",
"0.6495379",
"0.64509004",
"0.6375615",
"0.63716185",
"0.6361218",
"0.63578093",
"0.63537747",
"0.6339722",
"0.63357955",
"0.6328564",
"0.63165015",
"0.6293581",
"0.62731826",
"0.62628436",
"0.6200622",
"0.619951",
"0.6194288",
"0.61500794",
"0.61500794",
"0.6104588",
"0.6103582",
"0.60286397",
"0.59827733",
"0.5937308",
"0.5924171",
"0.5918831",
"0.5912507",
"0.5911765",
"0.5902537",
"0.58920664",
"0.5890923",
"0.5882544",
"0.5880937",
"0.5875752",
"0.5872064",
"0.58702457",
"0.58674115",
"0.58671236",
"0.58647597",
"0.58478236",
"0.58405346",
"0.5839881",
"0.58384544",
"0.5818562",
"0.580459",
"0.57842827",
"0.57841116",
"0.57693815",
"0.57661897",
"0.57632554",
"0.5756013",
"0.5753036",
"0.57481176",
"0.57468927",
"0.5730514",
"0.57186216",
"0.571762",
"0.5717041",
"0.57113475",
"0.57045966",
"0.57023513",
"0.5701695",
"0.56864536",
"0.5685172",
"0.56845176",
"0.56839484",
"0.5679466",
"0.5671746",
"0.5666751",
"0.56638443",
"0.566347",
"0.56616354",
"0.56577283",
"0.5656744",
"0.56532013",
"0.56479955",
"0.5638174",
"0.5608342",
"0.5606558",
"0.5600887",
"0.5595692",
"0.5594759",
"0.55901825",
"0.5586027",
"0.5585839",
"0.5585124",
"0.55845624",
"0.55838066",
"0.5580101"
] |
0.5954582
|
34
|
Change configuration of a user. modifications on keys prefixed by 'biapi.' (except callback_url) are ignored
|
def users_id_user_config_post(id_user, opts = {})
users_id_user_config_post_with_http_info(id_user, opts)
nil
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def user=(value)\n conf['api']['user'] = value\n end",
"def config_user\n atts = {}\n u = @device.user\n unless params[:name].blank?\n return render json: {:status=>11, :message=>'用户名已经设置,不能修改'} if u.name\n return render json: {:status=>12, :message=>'用户名已存在'} if User.find_by_name params[:name]\n atts[:name] = params[:name]\n end\n unless params[:email].blank?\n unless u.email.eql?(params[:email])\n return render json: {:status=>13, :message=>'邮箱已经注册过'} if User.find_by_email params[:email]\n end\n atts[:email] = params[:email]\n end \n unless params[:pass].blank?\n return render json: {:status=>14, :message=>'密码已经设置'} if u.password\n atts[:password] = params[:pass] \n end\n\n atts[:score_mode] = params[:score_mode] unless params[:score_mode].blank?\n atts[:tee] = params[:default_tee] unless params[:default_tee].blank?\n \n u.update_attributes(atts) \n \n ret = {:status=>0}\n unless params[:password].blank?\n @device.update_token\n ret[:token] = @device.token\n end\n render json: ret\n end",
"def upgrade_api_key_for(user)\n user.update(api_key: 2)\n end",
"def set_userconfig\n @userconfig = Userconfig.find(params[:id])\n end",
"def method_missing(method, *args)\n args.unshift(method.to_s)\n set_user_config args\n end",
"def set_config_user\n @config_user = ConfigUser.find(params[:id])\n end",
"def set_user; end",
"def apply_user_config(user_id)\r\n user_id = user_id.to_i\r\n exec(\r\n 'require_once(\"auth.inc\");',\r\n \"$user_entry = $config[\\\"system\\\"][\\\"user\\\"][#{user_id}];\",\r\n '$user_groups = array();',\r\n 'foreach ($config[\"system\"][\"group\"] as $gidx => $group) {',\r\n ' if (is_array($group[\"member\"])) {',\r\n \" if (in_array(#{user_id}, $group[\\\"member\\\"])) { $user_groups[] = $group[\\\"name\\\"]; }\",\r\n ' }',\r\n '}',\r\n # Intentionally run set_groups before and after to ensure group membership gets fully applied.\r\n 'local_user_set_groups($user_entry, $user_groups);',\r\n 'local_user_set($user_entry);',\r\n 'local_user_set_groups($user_entry, $user_groups);'\r\n )\r\n end",
"def user=(value)\n conf['dashboard']['user'] = value\n end",
"def set_config\n @me = current_user\n @profile = Profile.find_by user_id: current_user.id\n @preference = Preference.find_by user_id: current_user.id\n end",
"def update\n coop = @user.coop_id\n\n # If they requested a co-op switch, send a request to their MemCo\n # Else, update their settings\n if @user.update_attributes(user_params)\n user_switched?(coop) ?\n request_switch(coop) :\n flash[:success] = \"Settings updated\"\n redirect_to @user\n else\n render \"edit\"\n end\n end",
"def configure\n # Consumer details come from registering an app at https://dev.twitter.com/\n # Once you have consumer details, use \"ebooks auth\" for new access tokens\n self.consumer_key = 't9g6TgrUYsZ4R5aeArsM2C36G' # Your app consumer key\n self.consumer_secret = 'olto6fNhfZz0CZwtx4uaFFpoyW88KG4LZnuaMFtWkvhgWq3897' # Your app consumer secret\n\n # Users to block instead of interacting with\n self.blacklist = ['']\n\n # Range in seconds to randomize delay when bot.delay is called\n self.delay_range = 1..6\n\t\n\t@userinfo = {}\n end",
"def modify_user(user)\n query_api_object Model::User, '/rest/user', user.to_hash, 'PUT'\n end",
"def update_user\n end",
"def update_config(show_main_tour: nil, show_mobile_tour: nil, show_feed_tour: nil, show_entry_tour: nil,\n show_kb_shortcuts_tour: nil)\n new_config = {}\n new_config[:show_main_tour] = show_main_tour if !show_main_tour.nil?\n new_config[:show_mobile_tour] = show_mobile_tour if !show_mobile_tour.nil?\n new_config[:show_feed_tour] = show_feed_tour if !show_feed_tour.nil?\n new_config[:show_entry_tour] = show_entry_tour if !show_entry_tour.nil?\n new_config[:show_kb_shortcuts_tour] = show_kb_shortcuts_tour if !show_kb_shortcuts_tour.nil?\n Rails.logger.info \"Updating user #{self.id} - #{self.email} with show_main_tour #{show_main_tour}, \" +\n \"show_mobile_tour #{show_mobile_tour}, show_feed_tour #{show_feed_tour}, \" +\n \"show_entry_tour #{show_entry_tour}, show_kb_shortcuts_tour #{show_kb_shortcuts_tour}\"\n self.update new_config if new_config.length > 0\n end",
"def correct_user_config\n\t\t@user = current_user.id\n\t\t@config = Config.find(params[:id])\n\t\tredirect_to(root_url) unless @user == @config.user_id\n\tend",
"def update\n \n @user.address = Address.new(\"address\" => params[:user][:address])\n \n config = Configuration.new()\n config.square = params[:user][:raio]\n config.address = Address.new(\"address\" => params[:user][:configuration_address])\n @user.configuration = config.as_json\n \n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to root_url, notice: 'Usuário atualizado com sucesso.' }\n format.json { render :show, status: :ok, location: @user }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def user_config(key)\n Autoproj.user_config(key)\nend",
"def update!\n @authorize = nil\n update_plan! &&\n resp = put(\"/users/#{username}.xml\", {\n :user_key => apikey,\n \"user[first_name]\" => first_name,\n \"user[last_name]\" => last_name\n })\n end",
"def test_user_update\n new_data = {\n 'OrgDefinedId' => 'ruby-test',\n 'FirstName' => 'Test-User',\n 'MiddleName' => 'changed',\n 'LastName' => 'Test',\n 'ExternalEmail' => nil, # Predefines user data, in the case that\n 'UserName' => 'test-ruby-user1234', # there is are variables left out in the JSON\n 'Activation' => {\n 'IsActive' => true\n }\n }\n user_id = get_user_by_username(new_data['UserName'])['UserId']\n update_user_data(user_id, new_data)\n end",
"def user_update_me(opts = {})\n if Configuration.debugging\n Configuration.logger.debug \"Calling API: UserApi#user_update_me ... opts: #{opts}\"\n end\n\n # resource path\n path = \"/user\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n _header_accept = ['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript']\n _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result\n\n # HTTP header 'Content-Type'\n _header_content_type = ['application/json', 'application/x-www-form-urlencoded']\n header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)\n\n # form parameters\n form_params = {}\n form_params[\"firstname\"] = opts[:'firstname'] if opts[:'firstname']\n form_params[\"lastname\"] = opts[:'lastname'] if opts[:'lastname']\n form_params[\"oldPassword\"] = opts[:'old_password'] if opts[:'old_password']\n form_params[\"newPassword\"] = opts[:'new_password'] if opts[:'new_password']\n form_params[\"newPasswordConfirm\"] = opts[:'new_password_confirm'] if opts[:'new_password_confirm']\n form_params[\"country\"] = opts[:'country'] if opts[:'country']\n form_params[\"pgpPubKey\"] = opts[:'pgp_pub_key'] if opts[:'pgp_pub_key']\n\n # http body (model)\n post_body = nil\n\n\n auth_names = []\n result = @api_client.call_api(:PUT, path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'User')\n if Configuration.debugging\n Configuration.logger.debug \"API called: UserApi#user_update_me. Result: #{result.inspect}\"\n end\n return result\n end",
"def twofa\n @user = current_user\n \n if params[:user]\n if @user.update_attributes params.require(:user).permit(:gauth_enabled,:password,:password_confirmation)\n if (params[:user][:gauth_enabled] == '1')\n flash[:info] = \"Two-factor authentication has been enabled\"\n else\n flash[:warn] = \"Two-factor authentication was not enabled\"\n end\n redirect_to admin_twofa_path\n return \n else\n flash[:error] = \"Something went wrong while trying to update your settings\"\n end\n end\n \n if !@user.twofa_enabled?\n @user.regenerate_secret!\n end\n end",
"def modify_user(user)\n query_api_object User, \"/rest/user\", user.dump(), \"PUT\"\n end",
"def configure\n # Users to block instead of interacting with\n self.blacklist = ['mcamargo1997']\n\n # Range in seconds to randomize delay when bot.delay is called\n self.delay_range = 1..6\n\n @userinfo = {}\n @botinfo = {\n ENV[\"BOT_NAME_1\"] => BotInfo.new(ENV[\"BOT_NAME_1\"]),\n ENV[\"BOT_NAME_2\"] => BotInfo.new(ENV[\"BOT_NAME_2\"])\n }\n end",
"def tweak\n current_user.update(tweak_params)\n\n redirect_back(fallback_location: settings_path)\n end",
"def change_user_bonuses # :root: :norobots:\n return unless (@user2 = find_or_goto_index(User, params[:id].to_s))\n if is_in_admin_mode?\n if request.method != \"POST\"\n # Reformat bonuses as string for editing, one entry per line.\n @val = \"\"\n if @user2.bonuses\n vals = @user2.bonuses.map do |points, reason|\n sprintf(\"%-6d %s\", points, reason.gsub(/\\s+/, \" \"))\n end\n @val = vals.join(\"\\n\")\n end\n else\n # Parse new set of values.\n @val = params[:val]\n line_num = 0\n errors = false\n bonuses = []\n @val.split(\"\\n\").each do |line|\n line_num += 1\n if (match = line.match(/^\\s*(\\d+)\\s*(\\S.*\\S)\\s*$/))\n bonuses.push([match[1].to_i, match[2].to_s])\n else\n flash_error(\"Syntax error on line #{line_num}.\")\n errors = true\n end\n end\n # Success: update user's contribution.\n unless errors\n contrib = @user2.contribution.to_i\n # Subtract old bonuses.\n if @user2.bonuses\n @user2.bonuses.each do |points, _reason|\n contrib -= points\n end\n end\n # Add new bonuses\n bonuses.each do |points, _reason|\n contrib += points\n end\n # Update database.\n @user2.bonuses = bonuses\n @user2.contribution = contrib\n @user2.save\n Transaction.put_user(\n id: @user2,\n set_bonuses: bonuses,\n set_contribution: contrib\n )\n redirect_to(action: \"show_user\", id: @user2.id)\n end\n end\n else\n redirect_to(action: \"show_user\", id: @user2.id)\n end\n end",
"def update_user(options)\n patch(\"/user\", options, 3)\n end",
"def update_config\n @user_config = UserConfig.find(params[:id])\n respond_to do |format|\n if @user_config.update(user_config_params)\n format.html { redirect_to users_path, :flash => {:success => 'Timer setting was successfully updated.' }}\n format.json { head :no_content }\n else\n format.html { render user: 'setting' }\n format.json { render json: @user_config.errors, status: :unprocessable_entity }\n end\n end\n end",
"def user(user)\n @options[:user] = user\n end",
"def update_user( user, page, new_password = nil )\n # load fields from LDAP\n user.uniqueid = page[0][@settings['ldap_field_uid']][0]\n user.preferred_name = page[0][@settings['ldap_field_nickname']][0] unless page[0][@settings['ldap_field_nickname']].nil? \n user.first_name = page[0][@settings['ldap_field_firstname']][0]\n user.middle_name = page[0][@settings['ldap_field_middlename']][0] unless page[0][@settings['ldap_field_middlename']].nil?\n user.last_name = page[0][@settings['ldap_field_lastname']][0]\n user.instructor = false\n user.activated = true\n if page[0][@settings['ldap_field_affiliation']].nil?\n user.affiliation = \"unknown\" \n else \n user.affiliation = page[0][@settings['ldap_field_affiliation']].join(', ') \n\n inst_affiliations = @settings['instructor_affiliation'].split(',')\n page[0][@settings['ldap_field_affiliation']].each do |x|\n inst_affiliations.each do |instructor_affiliation|\n if x.downcase.eql?( instructor_affiliation.downcase )\n user.instructor = true\n end\n end\n end\n end\n\n user.personal_title = page[0][@settings['ldap_field_personaltitle']][0] unless page[0][@settings['ldap_field_personaltitle']].nil?\n user.office_hours = page[0][@settings['ldap_field_officehours']][0] unless page[0][@settings['ldap_field_officehours']].nil?\n user.phone_number = page[0][@settings['ldap_field_phone']][0] unless page[0][@settings['ldap_field_phone']].nil?\n user.email = page[0][@settings['ldap_field_email']][0]\n \n unless new_password.nil?\n user.update_password( new_password )\n end\n \n if ! user.save\n raise SecurityError, \"Unable to save user: #{user.errors.full_messages.join(', ')}\", caller\n end\n \n return user\n end",
"def update!\n unless id\n raise \"user can not be updated before it is created.\"\n end\n hash = \"W10=\"\n\n payload = {\n \"id\" => id,\n \"email\" => @email_address,\n \"time_zone\" => @time_zone,\n \"country\" => @country,\n \"preferred_language\" => @language,\n \"receive_campaign_emails\" => \"true\",\n \"hash\" => hash,\n \"username\" => @email_address,\n \"last_login_at\" => get_last_login_at!,\n \"password\" => @password,\n \"password_confirmation\" => @confirm_password,\n \"user\" => {\n \"email\" => @email_address,\n \"password\" => @password,\n \"password_confirmation\" => @confirm_password,\n \"time_zone\" => @time_zone,\n \"receive_campaign_emails\" => \"true\",\n \"country\" => @country,\n \"preferred_language\" => @language\n }\n }\n\n response = authenticated_request(:put, \"api/client/users/#{id}\", payload: payload)\n response[:status]\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def setup_award_wallet_user_from_sample_data(account)\n user = get_award_wallet_user_from_callback(account)\n result = refresh_award_wallet_user_from_sample_data(user)\n account.reload\n result\n end",
"def config\n if params[:key].blank?\n flash.now[:notice] = \"Key can not be empty.\"\n return\n end\n @key = params[:key].to_s.downcase.to_sym\n if message = Kopal::KopalPreference.deprecated?(@key)\n flash.now[:notice] = \"<code>#{@key}</code> is deprecated. #{message}\"\n return\n end\n unless Kopal::KopalPreference.preference_name_valid? @key\n flash.now[:notice] = \"Invalid key <code>#{@key}</code>.\"\n return\n end\n if request.post?\n begin\n @profile_user[@key] = params[:value]\n rescue ActiveRecord::RecordInvalid => e\n flash.now[:notice] = \"<b>ERROR:</b> #{e.message}\"\n return\n end\n flash[:highlight] = \"Key <code>#{@key}</code> set to <code>#{@profile_user[@key]}</code>.\"\n redirect_to @kopal_route.home\n return\n else\n @present_value = @profile_user[@key]\n end\n unless @present_value\n render 'config', :status => 400 #doesn't work\n end\n end",
"def customize_new_user(user)\n # user.level = User::Levels::MEMBER\n # user.can_approve_posts = false\n # user.can_upload_free = false\n # user.is_super_voter = false\n #\n # user.base_upload_limit = 10\n # user.comment_threshold = -1\n # user.blacklisted_tags = [\"spoilers\", \"guro\", \"scat\", \"furry -rating:s\"].join(\"\\n\")\n # user.default_image_size = \"large\"\n # user.per_page = 20\n # user.disable_tagged_filenames = false\n true\n end",
"def set_user_data(opts = {})\n uri = \"/v3/botstate/#{opts['channel_id']}/users/#{opts['user_id']}\"\n api_post(uri, opts['bot_data'])\n end",
"def update_user(auth_token, user = {})\n if @api_host.present? && user.present?\n begin\n request_url = @api_host + \"/api/v1/profile\"\n payload = Hash.new\n payload[:user] = user\n request_headers = { \"Content-Type\" => \"application/json\", \"Authorization\" => \"Bearer \" + auth_token.to_s }\n response = RestClient.post(request_url, payload.to_json, request_headers)\n result = JSON.parse(response.body)\n Rails.logger.info \"===== update user result ===== #{result} =====\"\n result\n rescue RestClient::ExceptionWithResponse => e\n error = JSON.parse(e.response)\n Rails.logger.warn \"===== update user errors ===== #{error} =====\"\n error\n end\n end\n end",
"def update_users_password(args = {}) \n put(\"/users.json/backoffice/#{args[:userId]}/password/#{args[:password]}\", args)\nend",
"def update_users_password(args = {}) \n put(\"/users.json/backoffice/#{args[:userId]}/password/#{args[:password]}\", args)\nend",
"def update\n # @user = User.find(params[:id])\n @user = current_user # makes our views \"cleaner\" and more consistent\n params[:user][:existing_identity_attrs] ||= {}\n unless configatron.user_can_change_login\n params[:user].delete(:login)\n @user_login_is_readonly = true\n end\n \n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = \"Account updated!\"\n format.html { redirect_to account_url }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_from_barkbox_user_data user_data\n self.barkbox_user_id = user_data[:id]\n end",
"def user_for_conf_snippet(config)\n user = config[:user]\n if user.to_i > 0\n user = User.active.find(user)\n elsif user.is_a? String\n user = User.active.find_by_email(user)\n end\n\n app_type = config[:app_type]\n user = User.use_batch_user(app_type) if user.nil? && app_type\n user\n end",
"def user_id; config[:user_id]; end",
"def userinfo_set(userinfo)\n rebuild_uri :userinfo => userinfo\n end",
"def configure(config)\n\t\t\tvalid_configs = [:next_uid, :max_key_age, :tags, :sudo_group]\n\t\t\tto_use_config = config.select{|k,v| valid_configs.include?(k)}\n\t\t\t@metadata.attributes.update do |item_data|\n\t\t\t\titem_data.set(to_use_config)\n\t\t\t\tif(config.has_key?(:user_file_bucket))\n\t\t\t\t\tif(config[:user_file_bucket])\n\t\t\t\t\t\titem_data.set(:user_file_bucket => config[:user_file_bucket])\n\t\t\t\t\telse\n\t\t\t\t\t\titem_data.delete(:user_file_bucket)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tif(@metadata.attributes[:identity] == nil)\n\t\t\t\t\titem_data.set(:identity => 0)\n\t\t\t\telse\n\t\t\t\t\titem_data.add(:identity => 1)\n\t\t\t\tend\n\t\t\tend\n\t\tend",
"def attr_user_app\n set_keys(USER_APP_KEY,USER_MASTER_KEY)\n end",
"def set_omniauth_user(user)\n # Setup OmniAuth to return the correct metatda for this user.\n OmniAuth.config.add_mock(:twitter, {\n uid: user.uid,\n info: {\n name: user.name\n }\n })\n end",
"def update\n respond_to do |format|\n if @userconfig.update(userconfig_params)\n format.html { redirect_to taskstorages_path, notice: \"Userconfig was successfully updated.\" }\n format.json { render :show, status: :ok, location: taskstorages_path }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: taskstorages_path.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_user(handle, description= {})\n request(Net::HTTP::Put, \"/api/#{API_VERSION}/user/#{handle}\", nil, description, true)\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'Your settings have been saved.'\n format.html { redirect_to(:controller=> 'biker_view') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def set_users\n\n end",
"def update_user(data, options = {})\n GoodData::Domain.update_user(data, { client: client }.merge(options))\n end",
"def update!(**args)\n @apple_sign_in_config = args[:apple_sign_in_config] if args.key?(:apple_sign_in_config)\n @client_id = args[:client_id] if args.key?(:client_id)\n @client_secret = args[:client_secret] if args.key?(:client_secret)\n @enabled = args[:enabled] if args.key?(:enabled)\n @name = args[:name] if args.key?(:name)\n end",
"def hubssolib_current_user=(new_user)\n hubssolib_set_user_data(new_user)\n end",
"def user\n conf['api']['user']\n end",
"def alternative_config!\n JabberAdmin.configure do |conf|\n conf.username = 'admin@jabber.local'\n conf.password = 'defaultpw'\n conf.url = 'http://jabber.local/api'\n end\nend",
"def add_api_key\n @user = current_user\n if @user.present?\n @user.api_key = generate_api_key(16, 'user')\n @user.save\n end\n end",
"def set_user_setting\n @current_user.create_default_user_setting unless @current_user.user_setting\n @user_setting = @current_user.user_setting\n end",
"def set_api_v1_user\n @api_v1_user = Api::V1::User.find(params[:id])\n end",
"def save\r\n SystemConfig.set :auth, to_h, true\r\n end",
"def create_user(resource)\n session = Puppet::NetDev::CE::Device.session\n\n set_user_xml = '<rpc><edit-config><target><running/></target><default-operation>merge</default-operation><error-option>rollback-on-error</error-option><config><aaa xmlns=\"http://www.huawei.com/netconf/vrp\" content-version=\"1.0\" format-version=\"1.0\"><lam><users><user operation=\"merge\"><userName>' + (resource[:name]).to_s + '</userName>'\n\n if resource[:password]\n set_user_xml += '<password>' + (resource[:password]).to_s + '</password>'\n end\n\n set_user_xml += '</user></users></lam></aaa></config></edit-config></rpc>'\n\n session.rpc.do_config(set_user_xml)\n end",
"def update!(**args)\n @user_info = args[:user_info] if args.key?(:user_info)\n end",
"def set_usuario\n \n end",
"def change_user_profile(uid, fields)\n changes = fields.map do |k, v|\n { \"name\" => k, \"value\" => v, \"delete\" => 0 }\n end\n\n cl = client(\"Users\", uid)\n response = cl.call(:change_user_profile, \"message\" => { \"uid\" => uid, \"changes\" => changes })\n raise Error unless response.success?\n\n return [ response.to_hash[:change_user_profile_response][:return] ].flatten.inject({}) do |m, f|\n m[f[:name]] = f[:reason] if !f[:success]\n m\n end\n rescue Savon::SOAPFault => e\n process_error e\n end",
"def update(&block)\n Logger.d \"Updating user\"\n\n # TODO - change to post in actual network call\n json = {\n :user => {\n :name => get(:name),\n :email => get(:email),\n :gcm_token => get(:gcm_token)\n },\n :auth_token => get(:auth_token)\n }.to_json\n\n network_put(CONFIG.get(:user_save), nil, json, @on_api_call_failed) do |user_object|\n if is_valid_network_user_object?(user_object)\n @data = user_object\n Logger.d(\"Success in @user.update => \" + user_object.to_s)\n serialiaze() # Write the object to persistent storage\n block.call(@data)\n end\n end\n end",
"def save\n vals = to_h\n vals.delete(:username)\n vals.delete_if { |_k, v| v.nil? || v.to_s.empty? }\n vals[:password] = vals.delete(:newpassword) if vals[:newpassword]\n payload = Gyoku.xml(user: vals)\n response = CoachClient::Request.put(url, username: @username,\n password: @password,\n payload: payload,\n content_type: :xml)\n unless response.code == 200 || response.code == 201\n fail CoachClient::NotSaved.new(self), 'Could not save user'\n end\n @password = vals[:password]\n @newpassword = nil\n self\n end",
"def set(user_obj)\n # example code to set it\n # You could also set in DB i.e User.find(id).update_attributes(user_id: user_obj[:userId], settings: user_obj)\n @@user_storage[user_obj[:userId]] = user_obj\n end",
"def config_user_params\n params.require(:config_user).permit(:user_id, :category_id, :nombre, :slogan, :descripcion, :direccion, :pagina, :facebook, :whatsapp, :telefono, :horario, :condiciones_higiene, :tipo_entrega, :costo_envio, :compra_minima, :metodo_pago, :factura, :beneficiario, :cuenta, :banco, :aviso, :comentario, :vista_card, :logo, :estado, :ciudad, :reparto, :mostrar_direccion, :recibir_whatsapp)\n end",
"def user=(user)\n\t\tfname= \"#{self.class.name}.#{__method__}\"\n\t\tLOG.debug(fname) {\"user=user=#{user}\"}\n\t\t@user=user\n\t#def_user(user)\n\tend",
"def update\n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to setting_path, notice: '프로필 수정이 완료되었습니다' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def before_save_user\n self.encrypted_password.encode! 'utf-8'\n\n # If demo is enabled, demo user cannot change email or password nor be locked\n if Feedbunch::Application.config.demo_enabled\n demo_email = Feedbunch::Application.config.demo_email\n if email_changed? && self.email_was == demo_email\n Rails.logger.info 'Somebody attempted to change the demo user email. Blocking the attempt.'\n self.errors.add :email, 'Cannot change demo user email'\n self.email = demo_email\n end\n\n demo_password = Feedbunch::Application.config.demo_password\n if encrypted_password_changed? && self.email == demo_email\n Rails.logger.info 'Somebody attempted to change the demo user password. Blocking the attempt.'\n self.errors.add :password, 'Cannot change demo user password'\n self.password = demo_password\n end\n\n if locked_at_changed? && self.email == demo_email\n Rails.logger.info 'Keeping demo user from being locked because of too many authentication failures'\n self.locked_at = nil\n end\n\n if unlock_token_changed? && self.email == demo_email\n Rails.logger.info 'Removing unlock token for demo user, demo user cannot be locked out'\n self.unlock_token = nil\n end\n end\n end",
"def update_api_user_from_hash (user_hash)\n logger.debug2 \"user_hash = #{user_hash}\"\n allowed_fields = [:permissions, :api_profile_picture_url]\n invalid_fields = user_hash.keys - allowed_fields\n if invalid_fields.size > 0\n return ['.post_login_user_invalid_field',\n {:provider => provider, :apiname => (API_DOWNCASE_NAME[:provider] || provider),\n :userid => user_id, :field => invalid_fields.first}]\n\n end\n # permissions\n update_attribute(:permissions, user_hash[:permissions]) if user_hash.has_key? :permissions\n # profile picture\n if user_hash.has_key?(:api_profile_picture_url)\n logger.debug2 \"update profile picture: api_profile_picture_url = #{user_hash[:api_profile_picture_url]}\"\n key, options = User.update_profile_image(user_id, user_hash[:api_profile_picture_url])\n return [key, options] if key # error when updating profile picture information\n end\n # ok\n nil\n end",
"def set_user\n params.delete :matched_desc\n params.delete :host_prep\n params.delete :would_ret\n @user = User.where(user_id: params[:userId])\n end",
"def change_user_bonuses\n return unless (@user2 = find_or_goto_index(User, params[:id].to_s))\n\n if in_admin_mode?\n if request.method != \"POST\"\n # Reformat bonuses as string for editing, one entry per line.\n @val = \"\"\n if @user2.bonuses\n vals = @user2.bonuses.map do |points, reason|\n format(\"%-6d %s\", points, reason.gsub(/\\s+/, \" \"))\n end\n @val = vals.join(\"\\n\")\n end\n else\n # Parse new set of values.\n @val = params[:val]\n line_num = 0\n errors = false\n bonuses = []\n @val.split(\"\\n\").each do |line|\n line_num += 1\n if (match = line.match(/^\\s*(\\d+)\\s*(\\S.*\\S)\\s*$/))\n bonuses.push([match[1].to_i, match[2].to_s])\n else\n flash_error(\"Syntax error on line #{line_num}.\")\n errors = true\n end\n end\n # Success: update user's contribution.\n unless errors\n contrib = @user2.contribution.to_i\n # Subtract old bonuses.\n @user2.bonuses&.each_key do |points|\n contrib -= points\n end\n # Add new bonuses\n bonuses.each do |(points, _reason)|\n contrib += points\n end\n # Update database.\n @user2.bonuses = bonuses\n @user2.contribution = contrib\n @user2.save\n redirect_to(action: \"show_user\", id: @user2.id)\n end\n end\n else\n redirect_to(action: \"show_user\", id: @user2.id)\n end\n end",
"def switch_user(newuser)\n return if newuser.to_s == self.user.to_s\n @rye_opts ||= {}\n @rye_user = newuser\n disconnect\n end",
"def capture_user_data\n\n # add a user config row entry\n user_data = Userconfig.new(username: session[:userinfo].blank? ? \"\" : session[:userinfo]['info']['name'],\n date: DateTime.now,\n company: session[:company],\n okta: session[:okta] == \"on\" ? true : false,\n logo_url: session[:logo],\n home_url: session[:background],\n vault: true,\n resources: session[:resources] == \"on\" ? true : false,\n onboarding_tasks: session[:onboarding] == \"on\" ? true : false,\n medical_credentialing: session[:medical_credentialing] == \"on\" ? true : false,\n loan_origination: session[:loan_docs] == \"on\" ? true : false,\n upload_sign: session[:upload_sign] == \"on\" ? true : false,\n tax_return: session[:tax_return] == \"on\" ? true : false,\n submit_claim: session[:create_claim] == \"on\" ? true : false,\n eventstream: session[:eventstream] == \"on\" ? true : false)\n user_data.save\n end",
"def set_userfb\n @user = Userfb.find(params[:id])\n end",
"def update_profile(user)\n create_feed(user, {:title => 'Profile changed', :description => \"#{create_link(user)}'s changed his profile\"})\n end",
"def update\n respond_with ApidUser.update(params[:id], params[:apid_user])\n rescue ActiveRecord::RecordNotFound\n respond_with ApidUser::StateChangeError\n end",
"def update\n result = current_user.user_settings.find(params[:id])\n\n result.update_attributes(get_params_user_setting())\n\n respond_with result\n\n end",
"def update!(**args)\n @allow_password_signup = args[:allow_password_signup] if args.key?(:allow_password_signup)\n @autodelete_anonymous_users = args[:autodelete_anonymous_users] if args.key?(:autodelete_anonymous_users)\n @client = args[:client] if args.key?(:client)\n @disable_auth = args[:disable_auth] if args.key?(:disable_auth)\n @display_name = args[:display_name] if args.key?(:display_name)\n @email_privacy_config = args[:email_privacy_config] if args.key?(:email_privacy_config)\n @enable_anonymous_user = args[:enable_anonymous_user] if args.key?(:enable_anonymous_user)\n @enable_email_link_signin = args[:enable_email_link_signin] if args.key?(:enable_email_link_signin)\n @hash_config = args[:hash_config] if args.key?(:hash_config)\n @inheritance = args[:inheritance] if args.key?(:inheritance)\n @mfa_config = args[:mfa_config] if args.key?(:mfa_config)\n @monitoring = args[:monitoring] if args.key?(:monitoring)\n @name = args[:name] if args.key?(:name)\n @password_policy_config = args[:password_policy_config] if args.key?(:password_policy_config)\n @recaptcha_config = args[:recaptcha_config] if args.key?(:recaptcha_config)\n @sms_region_config = args[:sms_region_config] if args.key?(:sms_region_config)\n @test_phone_numbers = args[:test_phone_numbers] if args.key?(:test_phone_numbers)\n end",
"def apply_grip_config(config)\n if !config.is_a?(Array)\n config = [config]\n end\n config.each do |entry|\n if !entry.key?('control_uri')\n next\n end\n client = PubControlClient.new(entry['control_uri'])\n if entry.key?('control_iss')\n client.set_auth_jwt({'iss' => entry['control_iss']}, entry['key'])\n end\n super_add_client(client)\n end\n end",
"def set_user_attributes(user_hash)\n self.name = user_hash[:name]\n self.email = user_hash[:email]\n self.password = user_hash[:password]\n self.password_confirmation = user_hash[:password_confirmation]\n self.admin = false\n self.confirmed = false\n end",
"def set_user_info\n @user_info = UserInfo.find(params[:id])\n authorize @user_info\n end",
"def set_user(user, pass)\n set :user, user\n set :password, pass\n close_sessions\nend",
"def set_user\n zeus = User.find(@zeus_user.id)\n zeus.state = User.states['retrieved_password']\n zeus.save!\n \n request.session[:rbac_user_id] = @zeus_user.id\n end",
"def set_user(v)\n set_userinfo(v, @password)\n v\n end",
"def set_user\n @user = User.find(params[:user_id])\n authorize! :update, @user\n\n if @user.account.present? && @user.account.id.to_s == params[:id]\n @account = @user.account\n else\n @account = nil\n end\n end",
"def set_user\n\t\t@active = \"user\"\n\t\t@user = current_user\n\tend",
"def set_api_user\n RequestStore.store[:current_user] = User.system_user\n end",
"def user_add(username, password,\n config = Hash.new)\n default_config = {\n :add_user => true,\n :password => password,\n :comment => \"\",\n :use_mail => true,\n :use_ftp => false,\n :use_file_sharing => false,\n :mail_quota => 200, # in MB\n :virus_check => false,\n :spam_filter => false\n }\n\n user_setting(username,\n default_config.merge(config))\n end",
"def on_behalf_of_user_id=(value)\n @on_behalf_of_user_id = value\n end",
"def set_babysitter\n @request_group.request.update_babysitter(current_user)\n end",
"def user_id=(value)\n if value == @defaults['userId']\n @values.delete 'userId' if @values.key? 'userId'\n else\n @values['userId'] = value\n end\n end"
] |
[
"0.7109322",
"0.6529216",
"0.6244948",
"0.6223898",
"0.6085352",
"0.6064649",
"0.5969934",
"0.5936848",
"0.59160584",
"0.5885103",
"0.58494216",
"0.5841188",
"0.58111435",
"0.5807677",
"0.5742263",
"0.574219",
"0.57405156",
"0.5706894",
"0.5702117",
"0.56985927",
"0.56782925",
"0.56381965",
"0.56344295",
"0.56127334",
"0.5608212",
"0.5593917",
"0.5572418",
"0.55716556",
"0.55415887",
"0.5530419",
"0.55276364",
"0.55177045",
"0.55177045",
"0.55177045",
"0.55177045",
"0.55177045",
"0.55177045",
"0.55177045",
"0.5516858",
"0.55039144",
"0.5502057",
"0.5497825",
"0.5487075",
"0.5477681",
"0.5469942",
"0.5469942",
"0.54649127",
"0.5464734",
"0.5459366",
"0.54575676",
"0.54352814",
"0.5432153",
"0.5425193",
"0.54093254",
"0.54052263",
"0.5398491",
"0.53954774",
"0.53921723",
"0.53870463",
"0.5381687",
"0.5368592",
"0.5368263",
"0.5362788",
"0.53621966",
"0.5351408",
"0.5349397",
"0.5347515",
"0.5341272",
"0.53384674",
"0.5338165",
"0.5336661",
"0.53340614",
"0.5332829",
"0.5328451",
"0.53213",
"0.5320897",
"0.53201056",
"0.5315805",
"0.5306597",
"0.5304702",
"0.5304494",
"0.5298437",
"0.5298381",
"0.52963376",
"0.52944314",
"0.52935946",
"0.52919316",
"0.52878654",
"0.5280118",
"0.52789366",
"0.5272802",
"0.5258035",
"0.52553",
"0.5252845",
"0.52525",
"0.52481925",
"0.5248124",
"0.5247714",
"0.5247058",
"0.5244703",
"0.5234591"
] |
0.0
|
-1
|
Change configuration of a user. modifications on keys prefixed by &39;biapi.&39; (except callback_url) are ignored
|
def users_id_user_config_post_with_http_info(id_user, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersManagementApi.users_id_user_config_post ...'
end
# verify the required parameter 'id_user' is set
if @api_client.config.client_side_validation && id_user.nil?
fail ArgumentError, "Missing the required parameter 'id_user' when calling UsersManagementApi.users_id_user_config_post"
end
# resource path
local_var_path = '/users/{id_user}/config'.sub('{' + 'id_user' + '}', id_user.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['api_key']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersManagementApi#users_id_user_config_post\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def user=(value)\n conf['api']['user'] = value\n end",
"def config_user\n atts = {}\n u = @device.user\n unless params[:name].blank?\n return render json: {:status=>11, :message=>'用户名已经设置,不能修改'} if u.name\n return render json: {:status=>12, :message=>'用户名已存在'} if User.find_by_name params[:name]\n atts[:name] = params[:name]\n end\n unless params[:email].blank?\n unless u.email.eql?(params[:email])\n return render json: {:status=>13, :message=>'邮箱已经注册过'} if User.find_by_email params[:email]\n end\n atts[:email] = params[:email]\n end \n unless params[:pass].blank?\n return render json: {:status=>14, :message=>'密码已经设置'} if u.password\n atts[:password] = params[:pass] \n end\n\n atts[:score_mode] = params[:score_mode] unless params[:score_mode].blank?\n atts[:tee] = params[:default_tee] unless params[:default_tee].blank?\n \n u.update_attributes(atts) \n \n ret = {:status=>0}\n unless params[:password].blank?\n @device.update_token\n ret[:token] = @device.token\n end\n render json: ret\n end",
"def upgrade_api_key_for(user)\n user.update(api_key: 2)\n end",
"def set_userconfig\n @userconfig = Userconfig.find(params[:id])\n end",
"def user=(value)\n conf['dashboard']['user'] = value\n end",
"def method_missing(method, *args)\n args.unshift(method.to_s)\n set_user_config args\n end",
"def set_config_user\n @config_user = ConfigUser.find(params[:id])\n end",
"def update\n coop = @user.coop_id\n\n # If they requested a co-op switch, send a request to their MemCo\n # Else, update their settings\n if @user.update_attributes(user_params)\n user_switched?(coop) ?\n request_switch(coop) :\n flash[:success] = \"Settings updated\"\n redirect_to @user\n else\n render \"edit\"\n end\n end",
"def set_user; end",
"def apply_user_config(user_id)\r\n user_id = user_id.to_i\r\n exec(\r\n 'require_once(\"auth.inc\");',\r\n \"$user_entry = $config[\\\"system\\\"][\\\"user\\\"][#{user_id}];\",\r\n '$user_groups = array();',\r\n 'foreach ($config[\"system\"][\"group\"] as $gidx => $group) {',\r\n ' if (is_array($group[\"member\"])) {',\r\n \" if (in_array(#{user_id}, $group[\\\"member\\\"])) { $user_groups[] = $group[\\\"name\\\"]; }\",\r\n ' }',\r\n '}',\r\n # Intentionally run set_groups before and after to ensure group membership gets fully applied.\r\n 'local_user_set_groups($user_entry, $user_groups);',\r\n 'local_user_set($user_entry);',\r\n 'local_user_set_groups($user_entry, $user_groups);'\r\n )\r\n end",
"def update_config(show_main_tour: nil, show_mobile_tour: nil, show_feed_tour: nil, show_entry_tour: nil,\n show_kb_shortcuts_tour: nil)\n new_config = {}\n new_config[:show_main_tour] = show_main_tour if !show_main_tour.nil?\n new_config[:show_mobile_tour] = show_mobile_tour if !show_mobile_tour.nil?\n new_config[:show_feed_tour] = show_feed_tour if !show_feed_tour.nil?\n new_config[:show_entry_tour] = show_entry_tour if !show_entry_tour.nil?\n new_config[:show_kb_shortcuts_tour] = show_kb_shortcuts_tour if !show_kb_shortcuts_tour.nil?\n Rails.logger.info \"Updating user #{self.id} - #{self.email} with show_main_tour #{show_main_tour}, \" +\n \"show_mobile_tour #{show_mobile_tour}, show_feed_tour #{show_feed_tour}, \" +\n \"show_entry_tour #{show_entry_tour}, show_kb_shortcuts_tour #{show_kb_shortcuts_tour}\"\n self.update new_config if new_config.length > 0\n end",
"def modify_user(user)\n query_api_object Model::User, '/rest/user', user.to_hash, 'PUT'\n end",
"def set_config\n @me = current_user\n @profile = Profile.find_by user_id: current_user.id\n @preference = Preference.find_by user_id: current_user.id\n end",
"def update_user\n end",
"def configure\n # Consumer details come from registering an app at https://dev.twitter.com/\n # Once you have consumer details, use \"ebooks auth\" for new access tokens\n self.consumer_key = 't9g6TgrUYsZ4R5aeArsM2C36G' # Your app consumer key\n self.consumer_secret = 'olto6fNhfZz0CZwtx4uaFFpoyW88KG4LZnuaMFtWkvhgWq3897' # Your app consumer secret\n\n # Users to block instead of interacting with\n self.blacklist = ['']\n\n # Range in seconds to randomize delay when bot.delay is called\n self.delay_range = 1..6\n\t\n\t@userinfo = {}\n end",
"def test_user_update\n new_data = {\n 'OrgDefinedId' => 'ruby-test',\n 'FirstName' => 'Test-User',\n 'MiddleName' => 'changed',\n 'LastName' => 'Test',\n 'ExternalEmail' => nil, # Predefines user data, in the case that\n 'UserName' => 'test-ruby-user1234', # there is are variables left out in the JSON\n 'Activation' => {\n 'IsActive' => true\n }\n }\n user_id = get_user_by_username(new_data['UserName'])['UserId']\n update_user_data(user_id, new_data)\n end",
"def update\n \n @user.address = Address.new(\"address\" => params[:user][:address])\n \n config = Configuration.new()\n config.square = params[:user][:raio]\n config.address = Address.new(\"address\" => params[:user][:configuration_address])\n @user.configuration = config.as_json\n \n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to root_url, notice: 'Usuário atualizado com sucesso.' }\n format.json { render :show, status: :ok, location: @user }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def tweak\n current_user.update(tweak_params)\n\n redirect_back(fallback_location: settings_path)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def set_User(value)\n set_input(\"User\", value)\n end",
"def update_user(options)\n patch(\"/user\", options, 3)\n end",
"def config\n if params[:key].blank?\n flash.now[:notice] = \"Key can not be empty.\"\n return\n end\n @key = params[:key].to_s.downcase.to_sym\n if message = Kopal::KopalPreference.deprecated?(@key)\n flash.now[:notice] = \"<code>#{@key}</code> is deprecated. #{message}\"\n return\n end\n unless Kopal::KopalPreference.preference_name_valid? @key\n flash.now[:notice] = \"Invalid key <code>#{@key}</code>.\"\n return\n end\n if request.post?\n begin\n @profile_user[@key] = params[:value]\n rescue ActiveRecord::RecordInvalid => e\n flash.now[:notice] = \"<b>ERROR:</b> #{e.message}\"\n return\n end\n flash[:highlight] = \"Key <code>#{@key}</code> set to <code>#{@profile_user[@key]}</code>.\"\n redirect_to @kopal_route.home\n return\n else\n @present_value = @profile_user[@key]\n end\n unless @present_value\n render 'config', :status => 400 #doesn't work\n end\n end",
"def update!\n @authorize = nil\n update_plan! &&\n resp = put(\"/users/#{username}.xml\", {\n :user_key => apikey,\n \"user[first_name]\" => first_name,\n \"user[last_name]\" => last_name\n })\n end",
"def correct_user_config\n\t\t@user = current_user.id\n\t\t@config = Config.find(params[:id])\n\t\tredirect_to(root_url) unless @user == @config.user_id\n\tend",
"def user_config(key)\n Autoproj.user_config(key)\nend",
"def twofa\n @user = current_user\n \n if params[:user]\n if @user.update_attributes params.require(:user).permit(:gauth_enabled,:password,:password_confirmation)\n if (params[:user][:gauth_enabled] == '1')\n flash[:info] = \"Two-factor authentication has been enabled\"\n else\n flash[:warn] = \"Two-factor authentication was not enabled\"\n end\n redirect_to admin_twofa_path\n return \n else\n flash[:error] = \"Something went wrong while trying to update your settings\"\n end\n end\n \n if !@user.twofa_enabled?\n @user.regenerate_secret!\n end\n end",
"def modify_user(user)\n query_api_object User, \"/rest/user\", user.dump(), \"PUT\"\n end",
"def update!\n unless id\n raise \"user can not be updated before it is created.\"\n end\n hash = \"W10=\"\n\n payload = {\n \"id\" => id,\n \"email\" => @email_address,\n \"time_zone\" => @time_zone,\n \"country\" => @country,\n \"preferred_language\" => @language,\n \"receive_campaign_emails\" => \"true\",\n \"hash\" => hash,\n \"username\" => @email_address,\n \"last_login_at\" => get_last_login_at!,\n \"password\" => @password,\n \"password_confirmation\" => @confirm_password,\n \"user\" => {\n \"email\" => @email_address,\n \"password\" => @password,\n \"password_confirmation\" => @confirm_password,\n \"time_zone\" => @time_zone,\n \"receive_campaign_emails\" => \"true\",\n \"country\" => @country,\n \"preferred_language\" => @language\n }\n }\n\n response = authenticated_request(:put, \"api/client/users/#{id}\", payload: payload)\n response[:status]\n end",
"def user_update_me(opts = {})\n if Configuration.debugging\n Configuration.logger.debug \"Calling API: UserApi#user_update_me ... opts: #{opts}\"\n end\n\n # resource path\n path = \"/user\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n _header_accept = ['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript']\n _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result\n\n # HTTP header 'Content-Type'\n _header_content_type = ['application/json', 'application/x-www-form-urlencoded']\n header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)\n\n # form parameters\n form_params = {}\n form_params[\"firstname\"] = opts[:'firstname'] if opts[:'firstname']\n form_params[\"lastname\"] = opts[:'lastname'] if opts[:'lastname']\n form_params[\"oldPassword\"] = opts[:'old_password'] if opts[:'old_password']\n form_params[\"newPassword\"] = opts[:'new_password'] if opts[:'new_password']\n form_params[\"newPasswordConfirm\"] = opts[:'new_password_confirm'] if opts[:'new_password_confirm']\n form_params[\"country\"] = opts[:'country'] if opts[:'country']\n form_params[\"pgpPubKey\"] = opts[:'pgp_pub_key'] if opts[:'pgp_pub_key']\n\n # http body (model)\n post_body = nil\n\n\n auth_names = []\n result = @api_client.call_api(:PUT, path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'User')\n if Configuration.debugging\n Configuration.logger.debug \"API called: UserApi#user_update_me. Result: #{result.inspect}\"\n end\n return result\n end",
"def update_user( user, page, new_password = nil )\n # load fields from LDAP\n user.uniqueid = page[0][@settings['ldap_field_uid']][0]\n user.preferred_name = page[0][@settings['ldap_field_nickname']][0] unless page[0][@settings['ldap_field_nickname']].nil? \n user.first_name = page[0][@settings['ldap_field_firstname']][0]\n user.middle_name = page[0][@settings['ldap_field_middlename']][0] unless page[0][@settings['ldap_field_middlename']].nil?\n user.last_name = page[0][@settings['ldap_field_lastname']][0]\n user.instructor = false\n user.activated = true\n if page[0][@settings['ldap_field_affiliation']].nil?\n user.affiliation = \"unknown\" \n else \n user.affiliation = page[0][@settings['ldap_field_affiliation']].join(', ') \n\n inst_affiliations = @settings['instructor_affiliation'].split(',')\n page[0][@settings['ldap_field_affiliation']].each do |x|\n inst_affiliations.each do |instructor_affiliation|\n if x.downcase.eql?( instructor_affiliation.downcase )\n user.instructor = true\n end\n end\n end\n end\n\n user.personal_title = page[0][@settings['ldap_field_personaltitle']][0] unless page[0][@settings['ldap_field_personaltitle']].nil?\n user.office_hours = page[0][@settings['ldap_field_officehours']][0] unless page[0][@settings['ldap_field_officehours']].nil?\n user.phone_number = page[0][@settings['ldap_field_phone']][0] unless page[0][@settings['ldap_field_phone']].nil?\n user.email = page[0][@settings['ldap_field_email']][0]\n \n unless new_password.nil?\n user.update_password( new_password )\n end\n \n if ! user.save\n raise SecurityError, \"Unable to save user: #{user.errors.full_messages.join(', ')}\", caller\n end\n \n return user\n end",
"def save\n vals = to_h\n vals.delete(:username)\n vals.delete_if { |_k, v| v.nil? || v.to_s.empty? }\n vals[:password] = vals.delete(:newpassword) if vals[:newpassword]\n payload = Gyoku.xml(user: vals)\n response = CoachClient::Request.put(url, username: @username,\n password: @password,\n payload: payload,\n content_type: :xml)\n unless response.code == 200 || response.code == 201\n fail CoachClient::NotSaved.new(self), 'Could not save user'\n end\n @password = vals[:password]\n @newpassword = nil\n self\n end",
"def update_users_password(args = {}) \n put(\"/users.json/backoffice/#{args[:userId]}/password/#{args[:password]}\", args)\nend",
"def update_users_password(args = {}) \n put(\"/users.json/backoffice/#{args[:userId]}/password/#{args[:password]}\", args)\nend",
"def update\n # @user = User.find(params[:id])\n @user = current_user # makes our views \"cleaner\" and more consistent\n params[:user][:existing_identity_attrs] ||= {}\n unless configatron.user_can_change_login\n params[:user].delete(:login)\n @user_login_is_readonly = true\n end\n \n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = \"Account updated!\"\n format.html { redirect_to account_url }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def attr_user_app\n set_keys(USER_APP_KEY,USER_MASTER_KEY)\n end",
"def set_user_data(opts = {})\n uri = \"/v3/botstate/#{opts['channel_id']}/users/#{opts['user_id']}\"\n api_post(uri, opts['bot_data'])\n end",
"def save\r\n SystemConfig.set :auth, to_h, true\r\n end",
"def user_for_conf_snippet(config)\n user = config[:user]\n if user.to_i > 0\n user = User.active.find(user)\n elsif user.is_a? String\n user = User.active.find_by_email(user)\n end\n\n app_type = config[:app_type]\n user = User.use_batch_user(app_type) if user.nil? && app_type\n user\n end",
"def update_config\n @user_config = UserConfig.find(params[:id])\n respond_to do |format|\n if @user_config.update(user_config_params)\n format.html { redirect_to users_path, :flash => {:success => 'Timer setting was successfully updated.' }}\n format.json { head :no_content }\n else\n format.html { render user: 'setting' }\n format.json { render json: @user_config.errors, status: :unprocessable_entity }\n end\n end\n end",
"def change_user_bonuses # :root: :norobots:\n return unless (@user2 = find_or_goto_index(User, params[:id].to_s))\n if is_in_admin_mode?\n if request.method != \"POST\"\n # Reformat bonuses as string for editing, one entry per line.\n @val = \"\"\n if @user2.bonuses\n vals = @user2.bonuses.map do |points, reason|\n sprintf(\"%-6d %s\", points, reason.gsub(/\\s+/, \" \"))\n end\n @val = vals.join(\"\\n\")\n end\n else\n # Parse new set of values.\n @val = params[:val]\n line_num = 0\n errors = false\n bonuses = []\n @val.split(\"\\n\").each do |line|\n line_num += 1\n if (match = line.match(/^\\s*(\\d+)\\s*(\\S.*\\S)\\s*$/))\n bonuses.push([match[1].to_i, match[2].to_s])\n else\n flash_error(\"Syntax error on line #{line_num}.\")\n errors = true\n end\n end\n # Success: update user's contribution.\n unless errors\n contrib = @user2.contribution.to_i\n # Subtract old bonuses.\n if @user2.bonuses\n @user2.bonuses.each do |points, _reason|\n contrib -= points\n end\n end\n # Add new bonuses\n bonuses.each do |points, _reason|\n contrib += points\n end\n # Update database.\n @user2.bonuses = bonuses\n @user2.contribution = contrib\n @user2.save\n Transaction.put_user(\n id: @user2,\n set_bonuses: bonuses,\n set_contribution: contrib\n )\n redirect_to(action: \"show_user\", id: @user2.id)\n end\n end\n else\n redirect_to(action: \"show_user\", id: @user2.id)\n end\n end",
"def configure\n # Users to block instead of interacting with\n self.blacklist = ['mcamargo1997']\n\n # Range in seconds to randomize delay when bot.delay is called\n self.delay_range = 1..6\n\n @userinfo = {}\n @botinfo = {\n ENV[\"BOT_NAME_1\"] => BotInfo.new(ENV[\"BOT_NAME_1\"]),\n ENV[\"BOT_NAME_2\"] => BotInfo.new(ENV[\"BOT_NAME_2\"])\n }\n end",
"def update_user(data, options = {})\n GoodData::Domain.update_user(data, { client: client }.merge(options))\n end",
"def setup_award_wallet_user_from_sample_data(account)\n user = get_award_wallet_user_from_callback(account)\n result = refresh_award_wallet_user_from_sample_data(user)\n account.reload\n result\n end",
"def customize_new_user(user)\n # user.level = User::Levels::MEMBER\n # user.can_approve_posts = false\n # user.can_upload_free = false\n # user.is_super_voter = false\n #\n # user.base_upload_limit = 10\n # user.comment_threshold = -1\n # user.blacklisted_tags = [\"spoilers\", \"guro\", \"scat\", \"furry -rating:s\"].join(\"\\n\")\n # user.default_image_size = \"large\"\n # user.per_page = 20\n # user.disable_tagged_filenames = false\n true\n end",
"def hubssolib_current_user=(new_user)\n hubssolib_set_user_data(new_user)\n end",
"def update_from_barkbox_user_data user_data\n self.barkbox_user_id = user_data[:id]\n end",
"def userinfo_set(userinfo)\n rebuild_uri :userinfo => userinfo\n end",
"def user(user)\n @options[:user] = user\n end",
"def user_key=(key)\n @user_key = key\n self.user ||= Spotlight::Engine.user_class.find_by_user_key(key)\n self.user ||= Spotlight::Engine.user_class.invite!(email: user_key, skip_invitation: true)\n user.user_key = key\n end",
"def set_user(v)\n set_userinfo(v, @password)\n v\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'Your settings have been saved.'\n format.html { redirect_to(:controller=> 'biker_view') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @apple_sign_in_config = args[:apple_sign_in_config] if args.key?(:apple_sign_in_config)\n @client_id = args[:client_id] if args.key?(:client_id)\n @client_secret = args[:client_secret] if args.key?(:client_secret)\n @enabled = args[:enabled] if args.key?(:enabled)\n @name = args[:name] if args.key?(:name)\n end",
"def user_add(username, password,\n config = Hash.new)\n default_config = {\n :add_user => true,\n :password => password,\n :comment => \"\",\n :use_mail => true,\n :use_ftp => false,\n :use_file_sharing => false,\n :mail_quota => 200, # in MB\n :virus_check => false,\n :spam_filter => false\n }\n\n user_setting(username,\n default_config.merge(config))\n end",
"def update_user(auth_token, user = {})\n if @api_host.present? && user.present?\n begin\n request_url = @api_host + \"/api/v1/profile\"\n payload = Hash.new\n payload[:user] = user\n request_headers = { \"Content-Type\" => \"application/json\", \"Authorization\" => \"Bearer \" + auth_token.to_s }\n response = RestClient.post(request_url, payload.to_json, request_headers)\n result = JSON.parse(response.body)\n Rails.logger.info \"===== update user result ===== #{result} =====\"\n result\n rescue RestClient::ExceptionWithResponse => e\n error = JSON.parse(e.response)\n Rails.logger.warn \"===== update user errors ===== #{error} =====\"\n error\n end\n end\n end",
"def update_profile(user)\n create_feed(user, {:title => 'Profile changed', :description => \"#{create_link(user)}'s changed his profile\"})\n end",
"def update\n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to setting_path, notice: '프로필 수정이 완료되었습니다' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def switch_user(newuser)\n return if newuser.to_s == self.user.to_s\n @rye_opts ||= {}\n @rye_user = newuser\n disconnect\n end",
"def password=(value)\n conf['api']['password'] = value\n end",
"def update_user(handle, description= {})\n request(Net::HTTP::Put, \"/api/#{API_VERSION}/user/#{handle}\", nil, description, true)\n end",
"def change_user_profile(uid, fields)\n changes = fields.map do |k, v|\n { \"name\" => k, \"value\" => v, \"delete\" => 0 }\n end\n\n cl = client(\"Users\", uid)\n response = cl.call(:change_user_profile, \"message\" => { \"uid\" => uid, \"changes\" => changes })\n raise Error unless response.success?\n\n return [ response.to_hash[:change_user_profile_response][:return] ].flatten.inject({}) do |m, f|\n m[f[:name]] = f[:reason] if !f[:success]\n m\n end\n rescue Savon::SOAPFault => e\n process_error e\n end",
"def update\n\t\t@user = User.find(params[:id])\n\t\trespond_to do |format|\n\t\t\tif @user.update_attributes(user_params)\n\t\t\t\tRails.logger.warn(\"Your settings have been successfully updated.\")\n\t\t\t\tflash.now[:success] = \"Your settings have been successfully updated.\"\n\t\t\t\tformat.html {redirect_to root_url}\n\t\t\telse\n\t\t\t\tRails.logger.warn(\"Please be sure to fill out your email, password, and password confirmation.\")\n\t\t\t\tformat.html {redirect_to edit_user_path}\n\t\t\t\tflash[:error] = \"Please be sure to fill out your email, password, and password confirmation.\"\n\t\t\tend\n\t\tend\n\tend",
"def update\n respond_to do |format|\n if @userconfig.update(userconfig_params)\n format.html { redirect_to taskstorages_path, notice: \"Userconfig was successfully updated.\" }\n format.json { render :show, status: :ok, location: taskstorages_path }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: taskstorages_path.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_user_attributes(user_hash)\n self.name = user_hash[:name]\n self.email = user_hash[:email]\n self.password = user_hash[:password]\n self.password_confirmation = user_hash[:password_confirmation]\n self.admin = false\n self.confirmed = false\n end",
"def before_save_user\n self.encrypted_password.encode! 'utf-8'\n\n # If demo is enabled, demo user cannot change email or password nor be locked\n if Feedbunch::Application.config.demo_enabled\n demo_email = Feedbunch::Application.config.demo_email\n if email_changed? && self.email_was == demo_email\n Rails.logger.info 'Somebody attempted to change the demo user email. Blocking the attempt.'\n self.errors.add :email, 'Cannot change demo user email'\n self.email = demo_email\n end\n\n demo_password = Feedbunch::Application.config.demo_password\n if encrypted_password_changed? && self.email == demo_email\n Rails.logger.info 'Somebody attempted to change the demo user password. Blocking the attempt.'\n self.errors.add :password, 'Cannot change demo user password'\n self.password = demo_password\n end\n\n if locked_at_changed? && self.email == demo_email\n Rails.logger.info 'Keeping demo user from being locked because of too many authentication failures'\n self.locked_at = nil\n end\n\n if unlock_token_changed? && self.email == demo_email\n Rails.logger.info 'Removing unlock token for demo user, demo user cannot be locked out'\n self.unlock_token = nil\n end\n end\n end",
"def create_user(resource)\n session = Puppet::NetDev::CE::Device.session\n\n set_user_xml = '<rpc><edit-config><target><running/></target><default-operation>merge</default-operation><error-option>rollback-on-error</error-option><config><aaa xmlns=\"http://www.huawei.com/netconf/vrp\" content-version=\"1.0\" format-version=\"1.0\"><lam><users><user operation=\"merge\"><userName>' + (resource[:name]).to_s + '</userName>'\n\n if resource[:password]\n set_user_xml += '<password>' + (resource[:password]).to_s + '</password>'\n end\n\n set_user_xml += '</user></users></lam></aaa></config></edit-config></rpc>'\n\n session.rpc.do_config(set_user_xml)\n end",
"def update_current_logged_in_users_password(args = {}) \n put(\"/users.json/current/password\", args)\nend",
"def set_change_password(user)\n user.update_column(:must_change_passwd, true)\n session[:pwd] = 1\n end",
"def alternative_config!\n JabberAdmin.configure do |conf|\n conf.username = 'admin@jabber.local'\n conf.password = 'defaultpw'\n conf.url = 'http://jabber.local/api'\n end\nend",
"def set_user\n zeus = User.find(@zeus_user.id)\n zeus.state = User.states['retrieved_password']\n zeus.save!\n \n request.session[:rbac_user_id] = @zeus_user.id\n end",
"def user=(new_user)\n @user = new_user[0..100]\n end",
"def add_api_key\n @user = current_user\n if @user.present?\n @user.api_key = generate_api_key(16, 'user')\n @user.save\n end\n end",
"def update\n params[:user].reject! { |k,v|\n !['name','email','facebook_uid'].include?k || (k=='password' && v != '' && v == params[:password_verify])\n }\n @user = User.find(current_user.id)\n\n respond_to do |format|\n if params[:user]['facebook_uid'] and params[:user]['facebook_uid'] != \"\"\n params[:user].delete 'facebook_uid' if current_facebook_user.nil? or current_facebook_client.nil? or current_facebook_user.id != params[:user]['facebook_uid']\n end\n if @user.update_attributes(params[:user])\n if @user.facebook_uid and current_facebook_user and current_facebook_client\n if current_facebook_user.id == @user.facebook_uid\n @user.facebook_session_key = current_facebook_client.access_token\n end\n end\n format.html { redirect_to @user, notice: 'User was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_user(user, host, attributes)\n attributes.symbolize_keys\n\n user = ::MySQL::User.find_by_username_and_host(user, host)\n return false if user.nil? || !attributes.include?(:password)\n !!user.set_password(attributes[:password])\n end",
"def config_user_params\n params.require(:config_user).permit(:user_id, :category_id, :nombre, :slogan, :descripcion, :direccion, :pagina, :facebook, :whatsapp, :telefono, :horario, :condiciones_higiene, :tipo_entrega, :costo_envio, :compra_minima, :metodo_pago, :factura, :beneficiario, :cuenta, :banco, :aviso, :comentario, :vista_card, :logo, :estado, :ciudad, :reparto, :mostrar_direccion, :recibir_whatsapp)\n end",
"def set_user_setting\n @current_user.create_default_user_setting unless @current_user.user_setting\n @user_setting = @current_user.user_setting\n end",
"def update\n @user = current_user\n @tab = params[:tab]\n @on_my_account = true\n\n # do in two steps so we can see user.changes\n @user.attributes = params[:user]\n @user.update_subscriptions('http://sowhatsthedeal.com/my_account_email', nil, true)\n\n if @user.errors.empty? and @user.save\n @user.update_cim_profile\n flash.now[:notice] = \"Your #{@tab == 'personal' ? 'account has' : 'email preferences have' } been updated!\"\n end\n \n if request.xhr?\n render :text => \"success\"\n else \n render :action => @user.errors.on(:password) ? 'change_password' : 'show'\n end\n end",
"def update(&block)\n Logger.d \"Updating user\"\n\n # TODO - change to post in actual network call\n json = {\n :user => {\n :name => get(:name),\n :email => get(:email),\n :gcm_token => get(:gcm_token)\n },\n :auth_token => get(:auth_token)\n }.to_json\n\n network_put(CONFIG.get(:user_save), nil, json, @on_api_call_failed) do |user_object|\n if is_valid_network_user_object?(user_object)\n @data = user_object\n Logger.d(\"Success in @user.update => \" + user_object.to_s)\n serialiaze() # Write the object to persistent storage\n block.call(@data)\n end\n end\n end",
"def user_id; config[:user_id]; end",
"def update\n result = current_user.user_settings.find(params[:id])\n\n result.update_attributes(get_params_user_setting())\n\n respond_with result\n\n end",
"def update\n \n oldUser = User.find(current_user.id)\n @user = User.find(current_user.id)\n\n successfully_updated = if needs_password?(@user, account_update_params)\n @user.update_with_password(account_update_params)\n else\n # remove the virtual current_password attribute update_without_password\n # doesn't know how to ignore it\n params[:user].delete(:current_password)\n @user.update_without_password(account_update_params)\n end\n\n if successfully_updated\n \n ## Move the user profile photo from tmp to user directory\n if @user.profile_photo!=\"\"\n move_tmp_user_photo(@user)\n end\n \n #update latitude longitude here ...\n if @user.user_type == \"fan\" || @user.user_type == \"artist\"\n #//check if the address has been changed\n addressChanged = !((oldUser.country_id == @user.country_id) && (oldUser.state_id == @user.state_id) && (oldUser.zip ==@user.zip) && (oldUser.city == @user.city))\n if addressChanged\n fullAddress = \"\"\n countryName = \"\"\n stateName = \"\"\n if @user.country_id.to_i > 0\n countryRow = Country.where(\"id = ? \",@user.country_id.to_i).take\n if countryRow != nil\n countryName = countryRow.country_name\n end\n end\n \n if @user.state_id.to_i > 0\n stateRow = State.where(\"id = ? \",@user.state_id.to_i).take\n if stateRow != nil\n stateName = stateRow.state_name\n end\n end\n \n if @user.zip.to_s != \"\"\n fullAddress = URI.encode(@user.zip)\n end\n \n if @user.city.to_s !=\"\"\n if fullAddress.blank?\n fullAddress = URI.encode(@user.city)\n else\n fullAddress += \",\"+URI.encode(@user.city)\n end \n end\n \n if stateName !=\"\"\n if fullAddress.blank?\n fullAddress = URI.encode(stateName)\n else\n fullAddress += \",\"+URI.encode(stateName)\n end \n end\n \n if countryName !=\"\"\n if fullAddress.blank?\n fullAddress = URI.encode(countryName)\n else\n fullAddress += \",\"+URI.encode(countryName)\n end \n end\n \n #render text: fullAddress and return\n if !fullAddress.blank?\n lat_long = Geocoder.coordinates(fullAddress)\n cUser = User.find(@user.id);\n if lat_long!=nil\n cUser.update_attributes(:latitude => lat_long[0],:longitude => lat_long[1])\n end \n end \n end \n end\n \n set_flash_message :notice, :updated\n # Sign in the user bypassing validation in case his password changed\n sign_in @user, :bypass => true\n redirect_to after_update_path_for(@user)\n else\n render \"edit\"\n end\n end",
"def set(user_obj)\n # example code to set it\n # You could also set in DB i.e User.find(id).update_attributes(user_id: user_obj[:userId], settings: user_obj)\n @@user_storage[user_obj[:userId]] = user_obj\n end",
"def set_usuario\n \n end",
"def update_user(user, options = {})\n put \"/users/#{user}\", options\n end",
"def set_user(user, pass)\n set :user, user\n set :password, pass\n close_sessions\nend",
"def set_omniauth_user(user)\n # Setup OmniAuth to return the correct metatda for this user.\n OmniAuth.config.add_mock(:twitter, {\n uid: user.uid,\n info: {\n name: user.name\n }\n })\n end",
"def disable_password_reset(username, first, last, app,config)\n puts \" Setting password reset to false for |#{username}|.\" if $options.verbose\n # need to get the admin setting code put in place NOTENOTENOTE\n # if config['source']['admins'].include?(nickname)\n # admin = true\n # else\n # admin = false\n # end\n admin = false\n begin\n result = app.provision.update_user(username, first, last, nil, nil, admin.to_s, nil, \"false\", nil )\n STDERR.puts \"Result: #{result}\" if $options.debug\n update = true\n rescue GData::GDataError => e\n if e.code == \"1300\"\n STDERR.puts \" => Set password reset to false #{username} exists\" if $options.verbose\n update = true\n elsif e.code == \"1000\"\n STDERR.puts \" => setting password reset to false #{username} unknown error\" if $options.verbose\n update = false\n #retry\n else\n STDERR.puts \"Error creating user: #{username}\" if $options.verbose\n raise e\n end\n end\nend",
"def disable_password_reset(username, first, last, app,config)\n puts \" Setting password reset to false for |#{username}|.\" if $options.verbose\n # need to get the admin setting code put in place NOTENOTENOTE\n # if config['source']['admins'].include?(nickname)\n # admin = true\n # else\n # admin = false\n # end\n admin = false\n begin\n result = app.provision.update_user(username, first, last, nil, nil, admin.to_s, nil, \"false\", nil )\n STDERR.puts \"Result: #{result}\" if $options.debug\n update = true\n rescue GData::GDataError => e\n if e.code == \"1300\"\n STDERR.puts \" => Set password reset to false #{username} exists\" if $options.verbose\n update = true\n elsif e.code == \"1000\"\n STDERR.puts \" => setting password reset to false #{username} unknown error\" if $options.verbose\n update = false\n #retry\n else\n STDERR.puts \"Error creating user: #{username}\" if $options.verbose\n raise e\n end\n end\nend",
"def disable_password_reset(username, first, last, app,config)\n puts \" Setting password reset to false for |#{username}|.\" if $options.verbose\n # need to get the admin setting code put in place NOTENOTENOTE\n # if config['source']['admins'].include?(nickname)\n # admin = true\n # else\n # admin = false\n # end\n admin = false\n begin\n result = app.provision.update_user(username, first, last, nil, nil, admin.to_s, nil, \"false\", nil )\n STDERR.puts \"Result: #{result}\" if $options.debug\n update = true\n rescue GData::GDataError => e\n if e.code == \"1300\"\n STDERR.puts \" => Set password reset to false #{username} exists\" if $options.verbose\n update = true\n elsif e.code == \"1000\"\n STDERR.puts \" => setting password reset to false #{username} unknown error\" if $options.verbose\n update = false\n #retry\n else\n STDERR.puts \"Error creating user: #{username}\" if $options.verbose\n raise e\n end\n end\nend",
"def username(u)\n @config[:username] = u\n end",
"def update_user(id, attributes)\n elektron_identity.put(\"users/#{id}\") { { user: attributes } }.body[\n \"user\"\n ]\n end",
"def update\n @user = current_user\n if @user.update_attributes(params[:user])\n flash[:notice] = \"Updated your account settings!\"\n redirect_to(account_path)\n else\n @title = \"Account and Notification Settings\"\n flash[:error] = \"Error updating your account settings.\"\n render(:action => 'show')\n end\n end",
"def cmd_notify_pushover_set_user_key(*args)\n\t\t\t\tif args.length > 0\n\t\t\t\t\tprint_status(\"Setting pushover user(s) key to #{args[0]}\")\n\t\t\t\t\t@user_key = args[0]\n\t\t\t\telse\n\t\t\t\t\tprint_error(\"Please provide a value\")\n\t\t\t\tend\n\t\t\tend",
"def update!(**args)\n @user_info = args[:user_info] if args.key?(:user_info)\n end",
"def set_userinfo(user, password = nil)\n unless password\n user, password = split_userinfo(user)\n end\n @user = user\n @password = password if password\n\n [@user, @password]\n end",
"def update_api_user_from_hash (user_hash)\n logger.debug2 \"user_hash = #{user_hash}\"\n allowed_fields = [:permissions, :api_profile_picture_url]\n invalid_fields = user_hash.keys - allowed_fields\n if invalid_fields.size > 0\n return ['.post_login_user_invalid_field',\n {:provider => provider, :apiname => (API_DOWNCASE_NAME[:provider] || provider),\n :userid => user_id, :field => invalid_fields.first}]\n\n end\n # permissions\n update_attribute(:permissions, user_hash[:permissions]) if user_hash.has_key? :permissions\n # profile picture\n if user_hash.has_key?(:api_profile_picture_url)\n logger.debug2 \"update profile picture: api_profile_picture_url = #{user_hash[:api_profile_picture_url]}\"\n key, options = User.update_profile_image(user_id, user_hash[:api_profile_picture_url])\n return [key, options] if key # error when updating profile picture information\n end\n # ok\n nil\n end"
] |
[
"0.69964856",
"0.6478783",
"0.61852056",
"0.5980127",
"0.5947022",
"0.59314996",
"0.58462554",
"0.5830617",
"0.58166987",
"0.5806823",
"0.5792529",
"0.57718337",
"0.57278264",
"0.57106036",
"0.57029784",
"0.56980497",
"0.5697889",
"0.5694463",
"0.5691392",
"0.5691392",
"0.5691392",
"0.5691392",
"0.5691392",
"0.5691392",
"0.5691392",
"0.56904274",
"0.56836987",
"0.56695867",
"0.5636307",
"0.5633921",
"0.56277335",
"0.562405",
"0.56198496",
"0.56168133",
"0.5602129",
"0.5598049",
"0.5548234",
"0.5526415",
"0.5526415",
"0.5510544",
"0.54960316",
"0.54800075",
"0.54688185",
"0.54681414",
"0.5452564",
"0.5436117",
"0.54243183",
"0.54216933",
"0.5410295",
"0.54075843",
"0.54063624",
"0.5404317",
"0.5399644",
"0.5392695",
"0.5385354",
"0.53794",
"0.5374381",
"0.5368179",
"0.5348275",
"0.534663",
"0.5343869",
"0.53389406",
"0.5337924",
"0.5337659",
"0.53362286",
"0.5332197",
"0.53315955",
"0.5327429",
"0.5326507",
"0.5320098",
"0.53154767",
"0.53151596",
"0.5314681",
"0.5313741",
"0.53134876",
"0.5311241",
"0.5305596",
"0.52989763",
"0.52921796",
"0.529183",
"0.5281781",
"0.527814",
"0.52766716",
"0.52718157",
"0.52648544",
"0.5262448",
"0.52618444",
"0.5254291",
"0.5247586",
"0.5247585",
"0.5242689",
"0.52309054",
"0.52309054",
"0.52309054",
"0.5230895",
"0.52297115",
"0.5227933",
"0.52253556",
"0.5225169",
"0.52225196",
"0.5217186"
] |
0.0
|
-1
|
Delete the user This endpoint deletes the user.
|
def users_id_user_delete(id_user, opts = {})
data, _status_code, _headers = users_id_user_delete_with_http_info(id_user, opts)
data
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def delete_user\n client.delete(user)\n end",
"def delete_user(user)\n delete user_path(user)\n end",
"def destroy\n @user.destroy\n render json: {message: 'User was Deleted'}\n end",
"def destroy\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user.destroy\n head :no_content\n end",
"def delete\n connection.delete_user id\n nil\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def delete\n @user.destroy\n respond_to do |format|\n format.html { redirect_to v1_resources_users_all_path, notice: 'User was deleted.' }\n format.json { head :no_content }\n end\n end",
"def delete_user\n end",
"def remove_user\n query_api \"/rest/user\", nil, \"DELETE\"\n end",
"def destroy\n @user.destroy\n format.json { head :no_content }\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n user = User.find(params[:id])\n user.destroy\n head :no_content\n end",
"def delete_user(id)\n @user = User.destroy(id)\n end",
"def delete(user_id)\n self.class.delete(\"/#{@api_ver}/users/#{user_id}\", default_options_to_merge_with)\n end",
"def delete user_id, options={}, headers={}\n @connection.delete \"users/#{user_id}.json\", options, headers\n end",
"def destroy\n if @user.destroy\n head :ok\n else\n head :internal_server_error\n end\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def DeleteUser id\n \n APICall(path: \"users/#{id}.json\",method: 'DELETE')\n \n end",
"def destroy\n\t\t@user.delete\n\tend",
"def destroy\n\t\t# Log out before deleting user if logged in as user to be deleted.\n\t\tsession[\"current_user_id\"] = nil if session[\"current_user_id\"] == @user.id\n\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to users_url }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend",
"def destroy\n user = User.find(params[:id]) # from url, nothing to do with table\n user.destroy\n render json: user\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_users_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'user was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n if @user\n @user.destroy\n render json: { message: 'user succefully destroy' }, status: 200\n else\n render json: { error: 'unable destroy' }, status: 400\n end\n end",
"def remove_user\n query_api '/rest/user', nil, 'DELETE'\n end",
"def destroy\n\t\t@user = User.find params[:id]\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to users_url }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend",
"def delete_user\n user = User.where(email: user_params[:email]).first\n response = user.destroy\n @api_response[:code] = @response_codes[:success]\n @api_response[:result] = response\n\n rescue Exception => e\n @errors, @api_response = api_exception_handler(e)\n ensure\n send_response(@api_response, @errors)\n end",
"def delete_user\n service_response = AdminManagement::Users::DeleteUser.new(params).perform\n render_api_response(service_response)\n end",
"def destroy\n @user = get_user(params[:id])\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.login_name} deleted\"\n rescue Exception => e\n flash[:notice] = e.message\n end\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: '用户已删除。' }\n format.json { head :no_content }\n end\n end",
"def delete\n @user = User.find(params[:id])\n @user.delete\n redirect_to root_path\n end",
"def delete\n @user = User.find(params[:id])\n end",
"def delete\n @user = User.find(params[:id])\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n flash[:notice] = \"User deleted successfully.\"\n redirect_to admin_user_path\n end",
"def destroy\n\t\t@user.destroy\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to(admin_users_url) }\n format.xml { head :ok }\n end\n website.add_log(user: current_user, action: \"Deleted user #{@user.name}\")\n end",
"def destroy\n @user.destroy!\n\n render nothing: true, status: :no_content\n end",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\tredirect_to users_path\n\tend",
"def destroy\n logger.debug(\"user destroy\")\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n respond_with(@user)\n end",
"def delete_user(id)\n get_user_byid(id).destroy\n end",
"def destroy\n\t\tif !isAdmin\n\t\t\tredirect_to @user\n\t\t\treturn\n\t\tend\n\t\t@user.destroy\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to '/signout', notice: '<span class=\"alert alert-success\">User was deleted.</span>' }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n record_activity(\"deleted user: \" + @user.email)\n redirect_to users_path, :notice => \"User deleted\"\n end",
"def destroy\n @user.destroy\n\n respond_with(@user, location: users_url, notice: 'User was successfully destroyed.')\n end",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(users_path) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend",
"def destroy\n query_params = save_query_params\n @user.destroy\n respond_to do |format|\n format.html { redirect_to admin_users_path + query_params, notice: t('views.admin.users.user_deleted_successfully') }\n end\n end",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(users_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(users_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend",
"def destroy\n\t\t@user ||= User.find(params[:id])\n\t\t@user.destroy\n\t\trespond_with @user\n\tend",
"def delete_user(user_name:)\n validate_user_name(:user_name, user_name)\n\n wrap_response(@connection.delete(user_path(user_name))).fmap { |r| SftpgoClient::ApiResponse.new(r.body) }\n end",
"def destroy\n if @user.destroy\n redirect_to users_url, notice: 'User was successfully destroyed.' and return\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n flash[:notice] = 'User was successfully deleted.'\n format.html { redirect_to(admin_users_url) }\n format.xml { head :ok }\n end\n end",
"def delete\n user = User.delete_user(params[:id]) # Delete an existing user\n\n if user != nil # If the user was deleted successfully\n response = { content: user, message: \"User has been deleted successfully\", status: 200 } # Return the corresponding user\n\n render json: response, status: 200\n else # If the user was not destroyed\n response = { content: {}, message: \"User not found\", status: 404 } \n\n render json: response, status: 404 # Return 'not found'\n end\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n\t\tUser.find(params[:id]).destroy\n\t\tflash[:success] = \"User deleted\"\n\t\tredirect_to users_url\n\tend",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to dm_core.admin_users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n user = User.find(params[:id])\n user.destroy\n redirect_to users_path, :notice => \"User deleted.\"\n end",
"def destroy\n user.destroy\n respond_to do |format|\n format.html { redirect_to admin_users_url, notice: 'User was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n userToBeRemoved = User.find(params[:id])\n userToBeRemoved.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.name} deleted\"\n rescue StandardError => e\n flash[:notice] = e.message\n end\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n\t\tUser.find(params[:id]).delete\n\t\tflash[:success] = \"Deleted current user\"\n\t\tredirect_to users_path\n\tend",
"def destroy\n @user = User.shod(params[:id])\n authorize! :delete, @user\n @user.destroy\n flash[:user_delete] = t('user_delete')\n redirect_to users_path\n end",
"def destroy\n\t\t@user.destroy\n\t\tredirect_to users_path\n\n\tend",
"def destroy\n debugger\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def delete_user(user_id:, params:)\n connection.delete(\"users/#{user_id}\", params).body\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user.destroy\n redirect_to users_path, notice: (I18n.t :act_delete)\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n redirect_to users_path, :notice => 'User was successfully deleted.'\n end",
"def destroy\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.name} deleted\"\n rescue StandardError => e\n flash[:notice] = e.message\n end\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n\n end",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(user_index_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend",
"def delete_user(user_id)\n raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty?\n path = \"#{users_path}/#{user_id}\"\n delete(path)\n end",
"def destroy\n begin\n user = User.find(params[:user_id])\n if user.destroy\n render body: nil, status: 204\n else\n render json: { errors: user.errors.messages }, status: 422\n end\n rescue => e\n render json: { errors: e.message }, status: 404\n end\n end",
"def destroy\n @user = User.find(params[:id])\n if @user.destroy\n flash[:success] = \"User has been deleted!\"\n redirect_to users_url\n end\n end",
"def destroy\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.name} was successfully deleted\"\n rescue StandardError => e\n flash[:notice] = e.message\n end\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to administrators_url, notice: 'User was successfully deleted.' }\n format.json { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to users_path, :notice => \"User was successfully delete.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find(params[:id]).destroy\n flash[:success] = \"User deleted!\"\n redirect_to users_url\n end",
"def destroy\n @user = User.find(params[:id])\n @user.deleted = true\n if @user.save\n redirect_to(users_path, :alert => 'User deleted successfully.')\n end\n end",
"def delete\n @linked_user.delete(@uri)\n end",
"def destroy\n @user = User.find_by_id_or_username params[:id]\n @user.destroy\n render api_delete @user\n end",
"def destroy\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user.destroy\n\n head :no_content\n end",
"def destroy\n user = User.find(params[:id])\n user.destroy\n redirect_to users_path\n end",
"def destroy\n @user = User.find(params[:id])\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.name} deleted\"\n rescue Exception => e\n flash[:notice] = e.message\n end\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = V1::User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(v1_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n puts \"******* destroy *******\"\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n end\n end",
"def destroy\r\n\r\n @user.destroy\r\n\r\n save_users_log(current_user.email, 'user_deleted',@user.to_json)\r\n\r\n respond_to do |format|\r\n format.html { redirect_to users_url, notice: 'User was successfully deleted.' }\r\n end\r\n end"
] |
[
"0.8994034",
"0.83634824",
"0.831132",
"0.8307018",
"0.8307018",
"0.830556",
"0.8278325",
"0.82694113",
"0.8266111",
"0.8265773",
"0.82599425",
"0.8257647",
"0.82379633",
"0.81614834",
"0.81159216",
"0.8096064",
"0.8054096",
"0.80469877",
"0.8036824",
"0.80363715",
"0.8027458",
"0.8022889",
"0.8020813",
"0.8017271",
"0.80103916",
"0.79971117",
"0.79843867",
"0.7982461",
"0.79706484",
"0.79596925",
"0.7952689",
"0.79298955",
"0.792909",
"0.7928617",
"0.7928617",
"0.7925628",
"0.7921893",
"0.79176503",
"0.7902817",
"0.7901073",
"0.78994787",
"0.7898903",
"0.7894359",
"0.7888279",
"0.78863335",
"0.7885859",
"0.78853875",
"0.788538",
"0.78777236",
"0.78777236",
"0.7877079",
"0.78569233",
"0.78561753",
"0.7849038",
"0.78442436",
"0.7843097",
"0.7842061",
"0.7841531",
"0.78411454",
"0.78396803",
"0.78386265",
"0.7834271",
"0.78262454",
"0.78200555",
"0.78173023",
"0.7814035",
"0.7813679",
"0.78125685",
"0.78058416",
"0.780465",
"0.78000414",
"0.7799894",
"0.7787837",
"0.77865046",
"0.7776511",
"0.7774277",
"0.7770345",
"0.7766397",
"0.7766397",
"0.7766397",
"0.7766397",
"0.77657056",
"0.77657056",
"0.77657056",
"0.77657056",
"0.77657056",
"0.77657056",
"0.77657056",
"0.7763217",
"0.7758174",
"0.7756891",
"0.77563244",
"0.77561575",
"0.7751535",
"0.7750455",
"0.7750455",
"0.7746569",
"0.77397543",
"0.77379787",
"0.77347505",
"0.77345914"
] |
0.0
|
-1
|
Delete the user This endpoint deletes the user.
|
def users_id_user_delete_with_http_info(id_user, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersManagementApi.users_id_user_delete ...'
end
# verify the required parameter 'id_user' is set
if @api_client.config.client_side_validation && id_user.nil?
fail ArgumentError, "Missing the required parameter 'id_user' when calling UsersManagementApi.users_id_user_delete"
end
# resource path
local_var_path = '/users/{id_user}'.sub('{' + 'id_user' + '}', id_user.to_s)
# query parameters
query_params = {}
query_params[:'expand'] = opts[:'expand'] if !opts[:'expand'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['api_key']
data, status_code, headers = @api_client.call_api(:DELETE, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'User')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersManagementApi#users_id_user_delete\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def delete_user\n client.delete(user)\n end",
"def delete_user(user)\n delete user_path(user)\n end",
"def destroy\n @user.destroy\n render json: {message: 'User was Deleted'}\n end",
"def destroy\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user.destroy\n head :no_content\n end",
"def delete\n connection.delete_user id\n nil\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def delete\n @user.destroy\n respond_to do |format|\n format.html { redirect_to v1_resources_users_all_path, notice: 'User was deleted.' }\n format.json { head :no_content }\n end\n end",
"def delete_user\n end",
"def remove_user\n query_api \"/rest/user\", nil, \"DELETE\"\n end",
"def destroy\n @user.destroy\n format.json { head :no_content }\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n user = User.find(params[:id])\n user.destroy\n head :no_content\n end",
"def delete_user(id)\n @user = User.destroy(id)\n end",
"def delete(user_id)\n self.class.delete(\"/#{@api_ver}/users/#{user_id}\", default_options_to_merge_with)\n end",
"def delete user_id, options={}, headers={}\n @connection.delete \"users/#{user_id}.json\", options, headers\n end",
"def destroy\n if @user.destroy\n head :ok\n else\n head :internal_server_error\n end\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def DeleteUser id\n \n APICall(path: \"users/#{id}.json\",method: 'DELETE')\n \n end",
"def destroy\n\t\t@user.delete\n\tend",
"def destroy\n\t\t# Log out before deleting user if logged in as user to be deleted.\n\t\tsession[\"current_user_id\"] = nil if session[\"current_user_id\"] == @user.id\n\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to users_url }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend",
"def destroy\n user = User.find(params[:id]) # from url, nothing to do with table\n user.destroy\n render json: user\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_users_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'user was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n if @user\n @user.destroy\n render json: { message: 'user succefully destroy' }, status: 200\n else\n render json: { error: 'unable destroy' }, status: 400\n end\n end",
"def remove_user\n query_api '/rest/user', nil, 'DELETE'\n end",
"def destroy\n\t\t@user = User.find params[:id]\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to users_url }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend",
"def delete_user\n user = User.where(email: user_params[:email]).first\n response = user.destroy\n @api_response[:code] = @response_codes[:success]\n @api_response[:result] = response\n\n rescue Exception => e\n @errors, @api_response = api_exception_handler(e)\n ensure\n send_response(@api_response, @errors)\n end",
"def delete_user\n service_response = AdminManagement::Users::DeleteUser.new(params).perform\n render_api_response(service_response)\n end",
"def destroy\n @user = get_user(params[:id])\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.login_name} deleted\"\n rescue Exception => e\n flash[:notice] = e.message\n end\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: '用户已删除。' }\n format.json { head :no_content }\n end\n end",
"def delete\n @user = User.find(params[:id])\n @user.delete\n redirect_to root_path\n end",
"def delete\n @user = User.find(params[:id])\n end",
"def delete\n @user = User.find(params[:id])\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n flash[:notice] = \"User deleted successfully.\"\n redirect_to admin_user_path\n end",
"def destroy\n\t\t@user.destroy\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to(admin_users_url) }\n format.xml { head :ok }\n end\n website.add_log(user: current_user, action: \"Deleted user #{@user.name}\")\n end",
"def destroy\n @user.destroy!\n\n render nothing: true, status: :no_content\n end",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\tredirect_to users_path\n\tend",
"def destroy\n logger.debug(\"user destroy\")\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n respond_with(@user)\n end",
"def delete_user(id)\n get_user_byid(id).destroy\n end",
"def destroy\n\t\tif !isAdmin\n\t\t\tredirect_to @user\n\t\t\treturn\n\t\tend\n\t\t@user.destroy\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to '/signout', notice: '<span class=\"alert alert-success\">User was deleted.</span>' }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n record_activity(\"deleted user: \" + @user.email)\n redirect_to users_path, :notice => \"User deleted\"\n end",
"def destroy\n @user.destroy\n\n respond_with(@user, location: users_url, notice: 'User was successfully destroyed.')\n end",
"def destroy\n query_params = save_query_params\n @user.destroy\n respond_to do |format|\n format.html { redirect_to admin_users_path + query_params, notice: t('views.admin.users.user_deleted_successfully') }\n end\n end",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(users_path) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend",
"def destroy\n\t\t@user ||= User.find(params[:id])\n\t\t@user.destroy\n\t\trespond_with @user\n\tend",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(users_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(users_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend",
"def delete_user(user_name:)\n validate_user_name(:user_name, user_name)\n\n wrap_response(@connection.delete(user_path(user_name))).fmap { |r| SftpgoClient::ApiResponse.new(r.body) }\n end",
"def destroy\n if @user.destroy\n redirect_to users_url, notice: 'User was successfully destroyed.' and return\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n flash[:notice] = 'User was successfully deleted.'\n format.html { redirect_to(admin_users_url) }\n format.xml { head :ok }\n end\n end",
"def delete\n user = User.delete_user(params[:id]) # Delete an existing user\n\n if user != nil # If the user was deleted successfully\n response = { content: user, message: \"User has been deleted successfully\", status: 200 } # Return the corresponding user\n\n render json: response, status: 200\n else # If the user was not destroyed\n response = { content: {}, message: \"User not found\", status: 404 } \n\n render json: response, status: 404 # Return 'not found'\n end\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to dm_core.admin_users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n\t\tUser.find(params[:id]).destroy\n\t\tflash[:success] = \"User deleted\"\n\t\tredirect_to users_url\n\tend",
"def destroy\n user = User.find(params[:id])\n user.destroy\n redirect_to users_path, :notice => \"User deleted.\"\n end",
"def destroy\n user.destroy\n respond_to do |format|\n format.html { redirect_to admin_users_url, notice: 'User was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n userToBeRemoved = User.find(params[:id])\n userToBeRemoved.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.name} deleted\"\n rescue StandardError => e\n flash[:notice] = e.message\n end\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n\t\tUser.find(params[:id]).delete\n\t\tflash[:success] = \"Deleted current user\"\n\t\tredirect_to users_path\n\tend",
"def destroy\n @user = User.shod(params[:id])\n authorize! :delete, @user\n @user.destroy\n flash[:user_delete] = t('user_delete')\n redirect_to users_path\n end",
"def destroy\n\t\t@user.destroy\n\t\tredirect_to users_path\n\n\tend",
"def destroy\n debugger\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def delete_user(user_id:, params:)\n connection.delete(\"users/#{user_id}\", params).body\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user.destroy\n redirect_to users_path, notice: (I18n.t :act_delete)\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n redirect_to users_path, :notice => 'User was successfully deleted.'\n end",
"def destroy\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.name} deleted\"\n rescue StandardError => e\n flash[:notice] = e.message\n end\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n\n end",
"def destroy\n\t\t@user = User.find(params[:id])\n\t\t@user.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(user_index_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend",
"def delete_user(user_id)\n raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty?\n path = \"#{users_path}/#{user_id}\"\n delete(path)\n end",
"def destroy\n begin\n user = User.find(params[:user_id])\n if user.destroy\n render body: nil, status: 204\n else\n render json: { errors: user.errors.messages }, status: 422\n end\n rescue => e\n render json: { errors: e.message }, status: 404\n end\n end",
"def destroy\n @user = User.find(params[:id])\n if @user.destroy\n flash[:success] = \"User has been deleted!\"\n redirect_to users_url\n end\n end",
"def destroy\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.name} was successfully deleted\"\n rescue StandardError => e\n flash[:notice] = e.message\n end\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to administrators_url, notice: 'User was successfully deleted.' }\n format.json { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to users_path, :notice => \"User was successfully delete.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find(params[:id]).destroy\n flash[:success] = \"User deleted!\"\n redirect_to users_url\n end",
"def destroy\n @user = User.find(params[:id])\n @user.deleted = true\n if @user.save\n redirect_to(users_path, :alert => 'User deleted successfully.')\n end\n end",
"def delete\n @linked_user.delete(@uri)\n end",
"def destroy\n @user = User.find_by_id_or_username params[:id]\n @user.destroy\n render api_delete @user\n end",
"def destroy\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user.destroy\n\n head :no_content\n end",
"def destroy\n user = User.find(params[:id])\n user.destroy\n redirect_to users_path\n end",
"def destroy\n @user = User.find(params[:id])\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.name} deleted\"\n rescue Exception => e\n flash[:notice] = e.message\n end\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = V1::User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(v1_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n puts \"******* destroy *******\"\n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n end\n end",
"def destroy\r\n\r\n @user.destroy\r\n\r\n save_users_log(current_user.email, 'user_deleted',@user.to_json)\r\n\r\n respond_to do |format|\r\n format.html { redirect_to users_url, notice: 'User was successfully deleted.' }\r\n end\r\n end"
] |
[
"0.89939404",
"0.8363811",
"0.8311711",
"0.8307197",
"0.8307197",
"0.83056855",
"0.8277762",
"0.8269919",
"0.8266554",
"0.8266329",
"0.82593787",
"0.8258428",
"0.8237813",
"0.81619376",
"0.811557",
"0.8096101",
"0.8053589",
"0.804691",
"0.8036841",
"0.803655",
"0.8028147",
"0.8023097",
"0.80215096",
"0.8017111",
"0.8010433",
"0.7997172",
"0.79839724",
"0.7982382",
"0.7971031",
"0.79600054",
"0.795226",
"0.79296464",
"0.79295325",
"0.79290974",
"0.79290974",
"0.7925099",
"0.79217607",
"0.79177725",
"0.790327",
"0.7900923",
"0.78993505",
"0.78993434",
"0.78941464",
"0.78878284",
"0.788659",
"0.78860873",
"0.7885294",
"0.7884995",
"0.78774667",
"0.78773177",
"0.78773177",
"0.78570765",
"0.7855969",
"0.78488284",
"0.7844217",
"0.784332",
"0.78418994",
"0.7841758",
"0.78412265",
"0.78398144",
"0.7839136",
"0.7834067",
"0.78261",
"0.7820327",
"0.7817607",
"0.78144133",
"0.7812624",
"0.7812582",
"0.78058684",
"0.78047186",
"0.7799877",
"0.7799766",
"0.778752",
"0.77869695",
"0.7776512",
"0.7774201",
"0.7771466",
"0.776709",
"0.776709",
"0.776709",
"0.776709",
"0.77662784",
"0.77662784",
"0.77662784",
"0.77662784",
"0.77662784",
"0.77662784",
"0.77662784",
"0.7763583",
"0.775849",
"0.7756937",
"0.77566785",
"0.77561986",
"0.7752694",
"0.77510846",
"0.77510846",
"0.77469265",
"0.77394456",
"0.7738056",
"0.7734809",
"0.77347946"
] |
0.0
|
-1
|
Get the main profile
|
def users_id_user_profiles_main_get(id_user, opts = {})
data, _status_code, _headers = users_id_user_profiles_main_get_with_http_info(id_user, opts)
data
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def profile\n @property[:profile]\n end",
"def current_profile\n current_session.profile\n end",
"def profile; Profile.get(self.profile_id); end",
"def profile\n @profile ||= GATEWAY.get_profile_details(self.profile_id) unless profile_id.nil?\n end",
"def profile\n threaded[:profile] ||= Profile.load\n end",
"def profile\n threaded[:profile] ||= Profile.load\n end",
"def profile\n @profile ||= Profile.find_for_uid_and_network(self.uid, self.provider)\n end",
"def profile()\n title = Sketchup.active_model.title or 'Untitled'\n @@profilemap[title]\n end",
"def profile\n env['profile']\n end",
"def profile\n if Configuration.host_based_profiles\n request_hostname\n else\n CurrentUser.user_settings[:profile].to_sym if CurrentUser.user_settings[:profile]\n end\n end",
"def _profile\n @link['profile']\n end",
"def profile\n @profile ||= repository_profile\n end",
"def profile_name\n return self.profile.name\n end",
"def current_profile\n @profile ||= JSON.parse($redis.get(\"profile\"))\n end",
"def default_profile\n profiles.find_by_id(default_profile_id)\n end",
"def profile; end",
"def profile; end",
"def profileName \n \"profileName\" \n end",
"def mvp_profile\n owned_profiles.last\n end",
"def get_profile\n begin\n client.profile(fields: PROFILE_FIELDS)\n rescue Exception => e\n logger.error \"Linkedin #get_profile error #{e}\"\n end\n end",
"def profile\n unless @profile\n if associated_profile\n @profile = Profile.new(associated_profile)\n else\n options = {:fields => 'user_id', :includes => 'Profile'}\n options = options.merge(:access_token => token, :access_secret => secret) if (token && secret)\n tmp = User.find(username, options)\n @profile = Profile.new(tmp.associated_profile)\n end\n end\n @profile\n end",
"def default_profile\n active_profiles.select {|prof| prof.can_start_instance?}.first\n end",
"def profile\n super\n end",
"def profile\n super\n end",
"def profile(force = false)\n force ? @profile = get_profile : @profile ||= get_profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile_id\n Settings.cybersource.profile_id\n end",
"def extract_profile(args)\n return args.shift if args.first.is_a?(Management::Profile)\n return args.pop if args.last.is_a?(Management::Profile)\n profile\n end",
"def profile\n return nil unless user_loa3\n\n mvi_response&.profile\n end",
"def get_profile\n path = self.api_root + '/register/profile'\n process_firecloud_request(:get, path)\n end",
"def get_profile_id\n if user_signed_in? && current_user.profile\n @profile_id = current_user.profile.id\n end\n end",
"def profile\n @profile = current_user\n end",
"def get_profile\n\n # Auth\n token = auth\n\n # Get Client info based on fields provided\n client = LinkedIn::Client.new(API_KEY, API_SECRET, token)\n client.profile(:fields => @profile_fields)\n end",
"def first\n Profile.all.first\n end",
"def current_profile\n @current_profile ||= Account.find_by(subdomain: current_subdomain) if current_subdomain\n end",
"def get_prebuilt_profile(pak)\n profile = nil\n profile = get_storage_object(pak)\n Rails.logger.debug(\"#{self.class.name.to_s}.#{__method__}() returns: #{profile}\")\n profile\n end",
"def profile\n check_auth :profile\n \n response = connection.post do |req|\n req.url '/user/profile'\n req.body = { :format => @format }\n end\n response.body[0]\n end",
"def get_profile\n \n profil =\n Excon.get(\n 'https://eastus.api.cognitive.microsoft.com/speaker/identification/v2.0/text-independent/profiles',\n headers: {\n 'Content-Type' => 'application/json',\n 'Ocp-Apim-Subscription-Key' => \"3c43bca9ad884fe39518a5cf3925e707\"\n },\n body: JSON.generate(\"locale\": 'en-us')\n )\n return profil.body\n parsed = JSON.parse(profil.body)\n return parsed['profiles']\n rescue Excon::Error => e\n puts \"Error: #{e}\"\n\n end",
"def get_profile_information\n # body = {\n # cmd: \"get_profile_information\"\n # }\n\n end",
"def get_profile\n self.class.get '/members/private', @options\n end",
"def get_existing_profile(usr_prf)\n raise Utility::Errors::NotFound, \"Invalid UserProfile!\" unless usr_prf.present?\n get_prebuilt_profile(usr_prf.person_authentication_key)\n end",
"def get_bot_profile\n bot_profile = command.event.bot.profile.on(command.event.server)\n end",
"def profile\n @profile ||= EbanqApi::Profile.new(self)\n end",
"def profile(name)\n @profiles.find { |p| p.name == name }\n end",
"def prof_file\n base_info_file + '.profile'\n end",
"def profile\n\t\tif user_signed_in?\n\t\t\tdb_entry = UserSetting.where(username: current_user.username)[0]\n\t\t\tif db_entry != nil\n\t\t\t\thandle = db_entry.handle\n\t\t\t\t@problems_solved, @contests_attempted = build_solved_problems_and_attempted_contests(handle)\n\t\t\t\t@@handle_shared = handle\n\t\t\t\t@@problems_solved_shared = @problems_solved\n\t\t\t\t@@contests_attempted_shared = @contests_attempted\n\t\t\tend\n\t\tend\n\tend",
"def get_app_profile instance_id, app_profile_id\n instances.get_app_profile name: app_profile_path(instance_id, app_profile_id)\n end",
"def get_existing_profile(usr_prf)\n raise Utility::Errors::NotFound, \"Invalid UserProfile!\" unless usr_prf.present?\n get_prebuilt_profile(usr_prf.person_authenticated_key)\n end",
"def current_profile\n profile = profiles.detect {|a| a.default == true}\n unless profile\n profile = profiles.first\n profile.update_attribute(:default, true) if profile\n end\n profile\n end",
"def profile\n\t\t@user = User.find(current_user)\n\tend",
"def findProfile(profile_id)\n # assuming there is only one profile with this profile_id\n @profile = Profile.where(identity: profile_id).first\n return @profile\n end",
"def profile_url\n @data[:profile_url]\n end",
"def profile\n @profile ||= @request.do_request { FacebookUserProfile.populate(user) }\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def profile\n\n end",
"def profile\n raw = client.get @json['user']['links']['self']\n client.factory.create(GoodData::Profile, raw)\n end",
"def profile\n if @profile\n return @profile\n end\n\n @profile ||= begin\n h = profile_xml_to_hash(@catalog.search @route => @name )\n @new = false\n h\n rescue RestClient::ResourceNotFound\n # The resource is new\n @new = true\n {}\n end.freeze\n end",
"def current_user\n current_user_for_profile_management\n end",
"def profileNamespace \n \"profileNamespace\" \n end",
"def myprofile\n \n end",
"def get_node_profile\n rpc_get_fact_direct('node_profile')\n end",
"def profiles; end",
"def profile(profile_name:)\n claim_url = \"#{@@profile_service_url}/profile/#{profile_name}/next\"\n response = Faraday.get claim_url\n profile = JSON.parse(response.body)\n raise \"No profile available for #{profile_name}\" unless profile\n profile\n end",
"def get_profile_script(env); end",
"def profile_type\n return @profile_type if @profile_type\n\n @profile_type = Spaceship.provisioning_profile.development\n\n @profile_type\n end",
"def profile\n @profile ||= begin\n profile_xml = repository.datastream(:pid => pid, :dsid => dsid)\n profile_xml.gsub! '<datastreamProfile', '<datastreamProfile xmlns=\"http://www.fedora.info/definitions/1/0/management/\"' unless profile_xml =~ /xmlns=/\n doc = Nokogiri::XML(profile_xml)\n h = doc.xpath('/management:datastreamProfile/*', {'management' => \"http://www.fedora.info/definitions/1/0/management/\"} ).inject({}) do |sum, node|\n sum[node.name] ||= []\n sum[node.name] << node.text\n sum\n end\n h.select { |key, value| value.length == 1 }.each do |key, value|\n h[key] = value.first\n end\n\n h\n rescue\n {}\n end\n end",
"def profile(username)\n Person.profile(username, @api_key, @https)\n end",
"def profile\n \n end",
"def profile_collection\n run_context.profile_collection\n end",
"def full_name\n return '' unless profile\n profile.full_name\n end",
"def get_app_profile instance_id, app_profile_id\n execute do\n instances.get_app_profile(\n app_profile_path(instance_id, app_profile_id)\n )\n end\n end",
"def get_profile(connector, id, options={})\n brief = options.delete :brief || false\n json = connector.prepare_and_invoke_api_call(\n \"profiles/v1/providers/#{id}\" + (brief ? \"/brief\" : \"\"), :method=>:get)\n return self.new(json['profile'])\n end",
"def load_profile(name); end",
"def profile_details\n # Since 15th September 2016 certificates and devices are hidden behind another request\n # see https://github.com/fastlane/fastlane/issues/6137 for more information\n @profile_details ||= client.provisioning_profile_details(provisioning_profile_id: self.id, mac: mac?)\n end",
"def username\n profile['Username']\n end",
"def name\n profile.user.name\n end",
"def profile_name\n name.present? ? name : identifier\n end",
"def get_profile(profile_id)\n @type = Type::CIM_GET_PROFILE\n handle_profile_id(profile_id)\n make_request\n end",
"def profile\n\t\t@user = current_user\n\tend",
"def set_profile\n end",
"def profile?(profile=RC.current_profile)\n self.profile == (profile || 'default').to_s\n end",
"def to_profile\n #load!\n profile = Profile.new(root, name)\n to_h.each do |k,v|\n next if PROFILE_OMIT.include?(k.to_s)\n profile.__send__(\"#{k}=\", v)\n end\n profile.resources.homepage = homepage\n profile.resources.repository = repository\n profile\n end",
"def profile\n @user = current_user\n end",
"def get_user_profile_description\n get_profile_description(\"Users\")\n end",
"def single_config\n default = begin\n if profile.is_a?(Hash)\n profile\n elsif [String, Symbol].include?(profile.class)\n available[profile] ||\n raise(ProfileError, \"Profile #{profile.inspect} is undefined\")\n else\n available[:default] ||\n raise(ProfileError, 'No default profile defined')\n end\n end\n {:default => default}\n end",
"def profile_mode\n super\n end",
"def profile_mode\n super\n end",
"def profile_url\r\n infoxml = get_info\r\n return infoxml.at('profileurl').inner_text\r\n end",
"def profile\n render_json 0,\"ok\",current_member.as_profile\n end"
] |
[
"0.77435035",
"0.7699092",
"0.76730734",
"0.7653545",
"0.7648848",
"0.7648848",
"0.74617994",
"0.74278915",
"0.74256885",
"0.7421994",
"0.7342259",
"0.7243791",
"0.7160768",
"0.71177125",
"0.7114089",
"0.7097658",
"0.7097658",
"0.7089299",
"0.702054",
"0.6997733",
"0.6988198",
"0.69798505",
"0.69700426",
"0.69700426",
"0.69423044",
"0.69203883",
"0.69203883",
"0.69203883",
"0.69203883",
"0.69203883",
"0.69203883",
"0.69110554",
"0.6898429",
"0.6893447",
"0.68774885",
"0.6869433",
"0.6868163",
"0.68005604",
"0.67921203",
"0.67750317",
"0.67712265",
"0.6768505",
"0.67607576",
"0.6699476",
"0.66987884",
"0.6687364",
"0.667746",
"0.6670115",
"0.66688013",
"0.66683346",
"0.6647855",
"0.66405594",
"0.66240245",
"0.6604807",
"0.6598783",
"0.6576886",
"0.6557575",
"0.6556644",
"0.65462184",
"0.65462184",
"0.65462184",
"0.65462184",
"0.65462184",
"0.65462184",
"0.65462184",
"0.65462184",
"0.6522635",
"0.6517679",
"0.65106094",
"0.6501893",
"0.6498457",
"0.6470698",
"0.64558655",
"0.64472747",
"0.64422625",
"0.6418623",
"0.64128834",
"0.640611",
"0.64059293",
"0.64010173",
"0.63964903",
"0.6394191",
"0.63847136",
"0.636854",
"0.63673294",
"0.6360169",
"0.63482267",
"0.63306487",
"0.6328436",
"0.63105845",
"0.6299471",
"0.62856",
"0.6282981",
"0.62817866",
"0.6278971",
"0.62778044",
"0.6272859",
"0.62648505",
"0.62648505",
"0.62611294",
"0.6240546"
] |
0.0
|
-1
|
Get the main profile
|
def users_id_user_profiles_main_get_with_http_info(id_user, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersManagementApi.users_id_user_profiles_main_get ...'
end
# verify the required parameter 'id_user' is set
if @api_client.config.client_side_validation && id_user.nil?
fail ArgumentError, "Missing the required parameter 'id_user' when calling UsersManagementApi.users_id_user_profiles_main_get"
end
# resource path
local_var_path = '/users/{id_user}/profiles/main'.sub('{' + 'id_user' + '}', id_user.to_s)
# query parameters
query_params = {}
query_params[:'expand'] = opts[:'expand'] if !opts[:'expand'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['api_key']
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Profile')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersManagementApi#users_id_user_profiles_main_get\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def profile\n @property[:profile]\n end",
"def current_profile\n current_session.profile\n end",
"def profile; Profile.get(self.profile_id); end",
"def profile\n @profile ||= GATEWAY.get_profile_details(self.profile_id) unless profile_id.nil?\n end",
"def profile\n threaded[:profile] ||= Profile.load\n end",
"def profile\n threaded[:profile] ||= Profile.load\n end",
"def profile\n @profile ||= Profile.find_for_uid_and_network(self.uid, self.provider)\n end",
"def profile()\n title = Sketchup.active_model.title or 'Untitled'\n @@profilemap[title]\n end",
"def profile\n env['profile']\n end",
"def profile\n if Configuration.host_based_profiles\n request_hostname\n else\n CurrentUser.user_settings[:profile].to_sym if CurrentUser.user_settings[:profile]\n end\n end",
"def _profile\n @link['profile']\n end",
"def profile\n @profile ||= repository_profile\n end",
"def profile_name\n return self.profile.name\n end",
"def current_profile\n @profile ||= JSON.parse($redis.get(\"profile\"))\n end",
"def default_profile\n profiles.find_by_id(default_profile_id)\n end",
"def profile; end",
"def profile; end",
"def profileName \n \"profileName\" \n end",
"def mvp_profile\n owned_profiles.last\n end",
"def get_profile\n begin\n client.profile(fields: PROFILE_FIELDS)\n rescue Exception => e\n logger.error \"Linkedin #get_profile error #{e}\"\n end\n end",
"def profile\n unless @profile\n if associated_profile\n @profile = Profile.new(associated_profile)\n else\n options = {:fields => 'user_id', :includes => 'Profile'}\n options = options.merge(:access_token => token, :access_secret => secret) if (token && secret)\n tmp = User.find(username, options)\n @profile = Profile.new(tmp.associated_profile)\n end\n end\n @profile\n end",
"def default_profile\n active_profiles.select {|prof| prof.can_start_instance?}.first\n end",
"def profile\n super\n end",
"def profile\n super\n end",
"def profile(force = false)\n force ? @profile = get_profile : @profile ||= get_profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile_id\n Settings.cybersource.profile_id\n end",
"def extract_profile(args)\n return args.shift if args.first.is_a?(Management::Profile)\n return args.pop if args.last.is_a?(Management::Profile)\n profile\n end",
"def profile\n return nil unless user_loa3\n\n mvi_response&.profile\n end",
"def get_profile\n path = self.api_root + '/register/profile'\n process_firecloud_request(:get, path)\n end",
"def get_profile_id\n if user_signed_in? && current_user.profile\n @profile_id = current_user.profile.id\n end\n end",
"def profile\n @profile = current_user\n end",
"def get_profile\n\n # Auth\n token = auth\n\n # Get Client info based on fields provided\n client = LinkedIn::Client.new(API_KEY, API_SECRET, token)\n client.profile(:fields => @profile_fields)\n end",
"def first\n Profile.all.first\n end",
"def current_profile\n @current_profile ||= Account.find_by(subdomain: current_subdomain) if current_subdomain\n end",
"def get_prebuilt_profile(pak)\n profile = nil\n profile = get_storage_object(pak)\n Rails.logger.debug(\"#{self.class.name.to_s}.#{__method__}() returns: #{profile}\")\n profile\n end",
"def profile\n check_auth :profile\n \n response = connection.post do |req|\n req.url '/user/profile'\n req.body = { :format => @format }\n end\n response.body[0]\n end",
"def get_profile\n \n profil =\n Excon.get(\n 'https://eastus.api.cognitive.microsoft.com/speaker/identification/v2.0/text-independent/profiles',\n headers: {\n 'Content-Type' => 'application/json',\n 'Ocp-Apim-Subscription-Key' => \"3c43bca9ad884fe39518a5cf3925e707\"\n },\n body: JSON.generate(\"locale\": 'en-us')\n )\n return profil.body\n parsed = JSON.parse(profil.body)\n return parsed['profiles']\n rescue Excon::Error => e\n puts \"Error: #{e}\"\n\n end",
"def get_profile_information\n # body = {\n # cmd: \"get_profile_information\"\n # }\n\n end",
"def get_profile\n self.class.get '/members/private', @options\n end",
"def get_existing_profile(usr_prf)\n raise Utility::Errors::NotFound, \"Invalid UserProfile!\" unless usr_prf.present?\n get_prebuilt_profile(usr_prf.person_authentication_key)\n end",
"def get_bot_profile\n bot_profile = command.event.bot.profile.on(command.event.server)\n end",
"def profile\n @profile ||= EbanqApi::Profile.new(self)\n end",
"def profile(name)\n @profiles.find { |p| p.name == name }\n end",
"def prof_file\n base_info_file + '.profile'\n end",
"def profile\n\t\tif user_signed_in?\n\t\t\tdb_entry = UserSetting.where(username: current_user.username)[0]\n\t\t\tif db_entry != nil\n\t\t\t\thandle = db_entry.handle\n\t\t\t\t@problems_solved, @contests_attempted = build_solved_problems_and_attempted_contests(handle)\n\t\t\t\t@@handle_shared = handle\n\t\t\t\t@@problems_solved_shared = @problems_solved\n\t\t\t\t@@contests_attempted_shared = @contests_attempted\n\t\t\tend\n\t\tend\n\tend",
"def get_app_profile instance_id, app_profile_id\n instances.get_app_profile name: app_profile_path(instance_id, app_profile_id)\n end",
"def get_existing_profile(usr_prf)\n raise Utility::Errors::NotFound, \"Invalid UserProfile!\" unless usr_prf.present?\n get_prebuilt_profile(usr_prf.person_authenticated_key)\n end",
"def current_profile\n profile = profiles.detect {|a| a.default == true}\n unless profile\n profile = profiles.first\n profile.update_attribute(:default, true) if profile\n end\n profile\n end",
"def profile\n\t\t@user = User.find(current_user)\n\tend",
"def findProfile(profile_id)\n # assuming there is only one profile with this profile_id\n @profile = Profile.where(identity: profile_id).first\n return @profile\n end",
"def profile_url\n @data[:profile_url]\n end",
"def profile\n @profile ||= @request.do_request { FacebookUserProfile.populate(user) }\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def default_profile\n super\n end",
"def profile\n\n end",
"def profile\n raw = client.get @json['user']['links']['self']\n client.factory.create(GoodData::Profile, raw)\n end",
"def profile\n if @profile\n return @profile\n end\n\n @profile ||= begin\n h = profile_xml_to_hash(@catalog.search @route => @name )\n @new = false\n h\n rescue RestClient::ResourceNotFound\n # The resource is new\n @new = true\n {}\n end.freeze\n end",
"def current_user\n current_user_for_profile_management\n end",
"def profileNamespace \n \"profileNamespace\" \n end",
"def myprofile\n \n end",
"def get_node_profile\n rpc_get_fact_direct('node_profile')\n end",
"def profiles; end",
"def profile(profile_name:)\n claim_url = \"#{@@profile_service_url}/profile/#{profile_name}/next\"\n response = Faraday.get claim_url\n profile = JSON.parse(response.body)\n raise \"No profile available for #{profile_name}\" unless profile\n profile\n end",
"def get_profile_script(env); end",
"def profile_type\n return @profile_type if @profile_type\n\n @profile_type = Spaceship.provisioning_profile.development\n\n @profile_type\n end",
"def profile\n @profile ||= begin\n profile_xml = repository.datastream(:pid => pid, :dsid => dsid)\n profile_xml.gsub! '<datastreamProfile', '<datastreamProfile xmlns=\"http://www.fedora.info/definitions/1/0/management/\"' unless profile_xml =~ /xmlns=/\n doc = Nokogiri::XML(profile_xml)\n h = doc.xpath('/management:datastreamProfile/*', {'management' => \"http://www.fedora.info/definitions/1/0/management/\"} ).inject({}) do |sum, node|\n sum[node.name] ||= []\n sum[node.name] << node.text\n sum\n end\n h.select { |key, value| value.length == 1 }.each do |key, value|\n h[key] = value.first\n end\n\n h\n rescue\n {}\n end\n end",
"def profile(username)\n Person.profile(username, @api_key, @https)\n end",
"def profile\n \n end",
"def profile_collection\n run_context.profile_collection\n end",
"def full_name\n return '' unless profile\n profile.full_name\n end",
"def get_app_profile instance_id, app_profile_id\n execute do\n instances.get_app_profile(\n app_profile_path(instance_id, app_profile_id)\n )\n end\n end",
"def get_profile(connector, id, options={})\n brief = options.delete :brief || false\n json = connector.prepare_and_invoke_api_call(\n \"profiles/v1/providers/#{id}\" + (brief ? \"/brief\" : \"\"), :method=>:get)\n return self.new(json['profile'])\n end",
"def load_profile(name); end",
"def profile_details\n # Since 15th September 2016 certificates and devices are hidden behind another request\n # see https://github.com/fastlane/fastlane/issues/6137 for more information\n @profile_details ||= client.provisioning_profile_details(provisioning_profile_id: self.id, mac: mac?)\n end",
"def username\n profile['Username']\n end",
"def name\n profile.user.name\n end",
"def profile_name\n name.present? ? name : identifier\n end",
"def get_profile(profile_id)\n @type = Type::CIM_GET_PROFILE\n handle_profile_id(profile_id)\n make_request\n end",
"def profile\n\t\t@user = current_user\n\tend",
"def set_profile\n end",
"def profile?(profile=RC.current_profile)\n self.profile == (profile || 'default').to_s\n end",
"def to_profile\n #load!\n profile = Profile.new(root, name)\n to_h.each do |k,v|\n next if PROFILE_OMIT.include?(k.to_s)\n profile.__send__(\"#{k}=\", v)\n end\n profile.resources.homepage = homepage\n profile.resources.repository = repository\n profile\n end",
"def profile\n @user = current_user\n end",
"def get_user_profile_description\n get_profile_description(\"Users\")\n end",
"def single_config\n default = begin\n if profile.is_a?(Hash)\n profile\n elsif [String, Symbol].include?(profile.class)\n available[profile] ||\n raise(ProfileError, \"Profile #{profile.inspect} is undefined\")\n else\n available[:default] ||\n raise(ProfileError, 'No default profile defined')\n end\n end\n {:default => default}\n end",
"def profile_mode\n super\n end",
"def profile_mode\n super\n end",
"def profile_url\r\n infoxml = get_info\r\n return infoxml.at('profileurl').inner_text\r\n end",
"def profile\n render_json 0,\"ok\",current_member.as_profile\n end"
] |
[
"0.77435035",
"0.7699092",
"0.76730734",
"0.7653545",
"0.7648848",
"0.7648848",
"0.74617994",
"0.74278915",
"0.74256885",
"0.7421994",
"0.7342259",
"0.7243791",
"0.7160768",
"0.71177125",
"0.7114089",
"0.7097658",
"0.7097658",
"0.7089299",
"0.702054",
"0.6997733",
"0.6988198",
"0.69798505",
"0.69700426",
"0.69700426",
"0.69423044",
"0.69203883",
"0.69203883",
"0.69203883",
"0.69203883",
"0.69203883",
"0.69203883",
"0.69110554",
"0.6898429",
"0.6893447",
"0.68774885",
"0.6869433",
"0.6868163",
"0.68005604",
"0.67921203",
"0.67750317",
"0.67712265",
"0.6768505",
"0.67607576",
"0.6699476",
"0.66987884",
"0.6687364",
"0.667746",
"0.6670115",
"0.66688013",
"0.66683346",
"0.6647855",
"0.66405594",
"0.66240245",
"0.6604807",
"0.6598783",
"0.6576886",
"0.6557575",
"0.6556644",
"0.65462184",
"0.65462184",
"0.65462184",
"0.65462184",
"0.65462184",
"0.65462184",
"0.65462184",
"0.65462184",
"0.6522635",
"0.6517679",
"0.65106094",
"0.6501893",
"0.6498457",
"0.6470698",
"0.64558655",
"0.64472747",
"0.64422625",
"0.6418623",
"0.64128834",
"0.640611",
"0.64059293",
"0.64010173",
"0.63964903",
"0.6394191",
"0.63847136",
"0.636854",
"0.63673294",
"0.6360169",
"0.63482267",
"0.63306487",
"0.6328436",
"0.63105845",
"0.6299471",
"0.62856",
"0.6282981",
"0.62817866",
"0.6278971",
"0.62778044",
"0.6272859",
"0.62648505",
"0.62648505",
"0.62611294",
"0.6240546"
] |
0.0
|
-1
|
Create a token Create an access_token for this user and get it.
|
def users_id_user_token_post(id_user, application, opts = {})
data, _status_code, _headers = users_id_user_token_post_with_http_info(id_user, application, opts)
data
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def access_token\n User.create_access_token(self)\n end",
"def generate_access_token\n self.access_token ||= self.create_access_token\n save && access_token\n end",
"def create\n require 'digest/sha1'\n \n @access_token = AccessToken.new\n @access_token.user_id = current_user.id\n @access_token.last_access = Time.now\n @access_token.token = Digest::SHA1.hexdigest Time.now.to_s\n @access_token.active = true\n \n respond_to do |format|\n if @access_token.save\n format.html { redirect_to(@access_token, :notice => 'Access token was successfully created.') }\n format.xml { render :xml => @access_token, :status => :created, :location => @access_token }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @access_token.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create_token\n client_requested_expires_in = server.jwt['exp'].to_i - server.jwt['iat'].to_i\n server_expires_in = Authorization::Token.access_token_expires_in(configuration, client)\n if server_expires_in\n expires_in = (client_requested_expires_in > 0 && client_requested_expires_in <= server_expires_in) ? client_requested_expires_in : server_expires_in\n else\n expires_in = nil\n end\n @access_token = AccessToken.find_or_create_for(application: client.application, resource_owner: resource_owner, scopes: scopes, expires_in: expires_in, use_refresh_token: configuration.refresh_token_enabled?)\n end",
"def access_token\n @access_token ||= AccessToken.new(caller_service: caller_service, authorizator_service: authorizator_service)\n end",
"def generate_token\n token_hash = SecureRandom.hex\n token_hash.force_encoding('utf-8')\n access_tokens.create(token: token_hash, token_expire: Time.now + DEFAULT_TOKEN_EXPIRE)\n end",
"def generate_token\n token_hash = SecureRandom.hex\n token_hash.force_encoding('utf-8')\n access_tokens.create(token: token_hash, token_expire: Time.now + DEFAULT_TOKEN_EXPIRE)\n end",
"def generate_auth_token\n token = AuthToken.new(user: self)\n token if token.save\n end",
"def generate_access_token\n begin\n self.access_token = User.new_token\n end while ApiKey.exists?(access_token: access_token)\n end",
"def access_token\n @access_token ||= begin\n if oauth_options[:oauth_verifier]\n request_token.get_access_token(:oauth_verifier => oauth_options[:oauth_verifier])\n else\n request_token.get_access_token\n end\n end\n end",
"def get_access_token\n raise HyvesException, 'You need an request token to make get an access token' if request_token.nil?\n @access_token = request_token.get_access_token\n\n @userid = request_token.response[\"userid\"]\n @expiredate = Time.at(request_token.response[\"expiredate\"].to_i) if not request_token.response[\"expiredate\"].nil?\n\n @access_token\n end",
"def build_token(access_token)\n return OAuth2::AccessToken.new CLIENT, access_token\n end",
"def create\n puts \"MESSAGE 14 IN CREATE\"\n @auth = request.env['omniauth.auth']['credentials']\n # The following statement saves the tokens to the database\n Token.create(\n access_token: @auth['token'],\n refresh_token: @auth['refresh_token'],\n expires_at: Time.at(@auth['expires_at']).to_datetime)\n end",
"def create\n token_response = ResourceAccessTokens::CreateService.new(current_user, resource, create_params).execute\n\n if token_response.success?\n @resource_access_token = token_response.payload[:access_token]\n PersonalAccessToken.redis_store!(key_identity, @resource_access_token.token)\n\n redirect_to resource_access_tokens_path, notice: _(\"Your new access token has been created.\")\n else\n redirect_to resource_access_tokens_path, alert: _(\"Failed to create new access token: %{token_response_message}\") % { token_response_message: token_response.message }\n end\n end",
"def create\n super\n \n if @access_token.client.uses_account_sid\n # Never expire this token. It will be expired when the user explicitly\n # ends their session (by logging out), and possibly after a configurable\n # amount of time, if the provider is using expiration scheduling\n # (see the sessions:expire rake task).\n @access_token.expires_at = Time.mktime(2100, 12, 31)\n end\n \n authorization_code = Oauth2Providable::AuthorizationCode.find_by_token(params[:code])\n @access_token.account_sid = authorization_code.account_sid\n @access_token.client_sid = params[:client_sid]\n @access_token.save\n end",
"def generate_access_token\n self.access_token = SecureRandom.hex(64)\n end",
"def token\n @access_token.token\n end",
"def create_access_token(id:, type: nil)\n params = {\n id: id,\n type: type\n }\n client.make_request('/create-access-token', 'post', params: params)\n end",
"def create\n client.authorization_code = params[:code]\n access_token = client.access_token!\n puts access_token\n end",
"def create\n user = User.create!(user_params)\n render json: { token: user.auth_token }\n end",
"def create\n @model = AccessToken.new(access_token_params)\n @model.user = current_user\n\n respond_to do |format|\n if @model.save\n format.html { redirect_to @model, notice: 'Access token was successfully created.' }\n format.json { render :show, status: :created, location: @model }\n else\n format.html { render :new }\n format.json { render json: @model.errors, status: :unprocessable_entity }\n end\n end\n end",
"def access_token\n user_token = @user_token\n goat.transaction do\n if user_token.access_token.nil?\n user_token.access_token = request_token.get_access_token\n if !user_token.access_token.nil?\n goat[user_token.user] = user_token\n end\n end\n end\n @user_token = user_token\n @user_token.access_token\n end",
"def create\n @access_token = AccessToken.new(params[:access_token])\n\n respond_to do |format|\n if @access_token.save\n format.html { redirect_to @access_token, notice: 'Access token was successfully created.' }\n format.json { render json: @access_token, status: :created, location: @access_token }\n else\n format.html { render action: \"new\" }\n format.json { render json: @access_token.errors, status: :unprocessable_entity }\n end\n end\n end",
"def token\n access_token = @token_manager.access_token\n raise 'CloudTools::IAMAuth Unable to retrieve the access token from token manager.' if access_token.nil?\n\n access_token\n end",
"def access_token\n @access_token ||= OAuth::AccessToken.new(consumer, @token, @secret)\n end",
"def token\n return @token if @token\n\n options = @options.merge(\n body: {\n client_id: @client_id,\n client_secret: @client_secret,\n grant_type: 'client_credentials'\n },\n headers: {\n 'Accept' => 'application/json',\n 'Host' => uri.host\n }\n )\n url = \"#{@base_url}/auth/oauth/v2/token\"\n\n @logger.debug(\"Request token from #{url}\")\n\n response = raises_unless_success do\n HTTParty.post(url, options)\n end.parsed_response\n\n @token = Token.new(\n *response.values_at('access_token', 'token_type', 'expires_in', 'scope')\n )\n end",
"def token\n return @access_token if @access_token && !needs_refresh?\n\n update_access_token\n @access_token\n end",
"def access_token\n @access_token ||= OAuth::AccessToken.new(consumer, @token, @secret)\n end",
"def token_generate\n res = call('auth.token_generate')\n\n return unless res || res['token']\n\n res['token']\n end",
"def set_access_token\n access_tokens.create(token: SecureRandom.urlsafe_base64(20))\n end",
"def create_set_and_add_token\n token = SecureRandom.urlsafe_base64\n @user.token = token\n response.headers['X-AUTH-TOKEN'] = token\n end",
"def access_token\n OAuth::AccessToken.new(consumer, oauth_token, oauth_token_secret)\n end",
"def get_token\n begin\n @response = RestClient.post(\n @consumer[:token_request_url],\n client_id: @consumer[:client_id],\n client_secret: @consumer[:client_secret],\n grant_type: @consumer[:grant_type],\n resource: @consumer[:resource]\n )\n\n @consumer[:token] = 'Bearer ' + JSON.parse(@response)['access_token']\n @consumer[:token_expiry] = JSON.parse(@response)['expires_on']\n rescue => error\n puts(\"ERROR - Token Request Failed - #{error}\")\n end\n @consumer[:token]\n end",
"def access_token\n # Fetch from cache. We can expect this to be `nil` if unset or expired.\n #\n access_token = read_cache\n\n return access_token if access_token\n\n fetch_new_access_token\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def token\n auth_client.token(settings.oauth2_token).tap do |token|\n settings.save_oauth2_token(token.to_hash)\n end\n end",
"def acquire_token()\n response_body = JSON.load(`#{cli_path} account get-access-token -o json --resource #{@settings.token_audience}`)\n \n @token_expires_on = Time.parse(response_body['expiresOn'])\n @token_type = response_body['tokenType']\n @token = response_body['accessToken']\n rescue\n raise AzureCliError, 'Error acquiring token from the Azure CLI'\n end",
"def get_access_token\n\t\treturn @credentials.get_access_token\n\tend",
"def access_token()\n if @access_token_obj\n @access_token_obj.token\n else\n return nil\n end\n end",
"def bearer_token\n # Put the url together\n url = \"#{API_HOST}#{TOKEN_PATH}\"\n\n # Build our params hash\n params = {\n client_id: @client_id,\n client_secret: @client_secret,\n grant_type: GRANT_TYPE\n }\n\n response = HTTP.post(url, params: params)\n parsed = response.parse\n\n \"#{parsed['token_type']} #{parsed['access_token']}\"\n end",
"def create_token\n Rails.logger.info(\"Enter Create Token\")\n \n # create token\n token = GenerateToken.unique_token\n access_token = self.create_access_token( token: token, role: {})\n raise et(\"account.create_token_failed\") if access_token.blank?\n\n true\n rescue => e \n Rails.logger.error(\"**** ERROR **** #{e.message}\")\n end",
"def generate_token\n new_token =\n SimpleTokenAuthentication::TokenGenerator.instance.generate_token\n update(authentication_token: new_token)\n self\n end",
"def fetch_access_token\n client.unauthenticated_request(:POST, '/v1/security/oauth2/token',\n grant_type: 'client_credentials',\n client_id: client.client_id,\n client_secret: client.client_secret)\n end",
"def init_oauth_access_token\n @oauth_access_token = OAuth2::AccessToken.new(\n User.new_oauth_client,\n read_attribute(:access_token),\n {\n :refresh_token => read_attribute(:refresh_token),\n :expires_at => read_attribute(:access_token_expires_at)\n }\n )\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def generate_access_token\n token_string = \"#{@username}:#{@password}\"\n return Base64.strict_encode64(token_string)\n end",
"def get_access_token()\n url = URI.parse(TOKEN_ENDPOINT)\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n req = Net::HTTP::Post.new(url.path)\n req.basic_auth(@clientId, @clientSecret)\n req.set_form_data({'grant_type' => 'client_credentials'})\n res = http.request(req)\n JSON.parse(res.body)['access_token']\n end",
"def create_access_token\n hash = nil\n Songkick::OAuth2.generate_id do |token|\n hash = Songkick::OAuth2.hashify(token) \n end\n return hash\n end",
"def fetch\n response = request.post(path: \"/#{base_path}/token\", claims_token: claims_token.static)\n\n self.access_token = Oj.load(response.body)['token']\n self\n end",
"def generate_token\n self.status = STATUS[:present]\n self.access_token = SecureRandom.urlsafe_base64(45, true)\n self.expires = Time.zone.now.to_i + TOKEN_LIFE\n self.login_time = Time.zone.now\n self.user_events.build(event_name: 'Login', event_time: Time.zone.now)\n save\n self.access_token\n end",
"def get_access_token(grant_type, options = {})\n object_from_response(GogoKit::OAuthToken,\n GogoKit::OAuthTokenRepresenter,\n :post,\n oauth_token_endpoint,\n body: token_request_body(grant_type, options),\n headers: token_request_headers)\n end",
"def access_token\n @attributes[:access_token] || client.token\n end",
"def access_token\n @attributes[:access_token] || client.token\n end",
"def access_token\n @attributes[:access_token] || client.token\n end",
"def create\n user = User.find_by(email: auth_params[:email])\n if user&.valid_password?(auth_params[:password])\n @token = user.api_tokens.find_or_create_by(name: (auth_params[:name] || \"default\")) do |token|\n token.make_token.save!\n end\n render json: {\n token: @token.token\n }\n else\n head :unauthorized\n end\n end",
"def call\n # after user login, will pass the user-id to the JWT to create token\n return nil unless user\n\n return JsonWebToken.create_token(user_id: user.id), user\n end",
"def access_token\n @access_token ||= ShakeTheCounter::Authentication.renew_access_token(client_id: id, client_secret: secret, refresh_token: refresh_token)[\"access_token\"]\n end",
"def find_or_create_from_access_token(user, access_token, new_token = nil)\n if access_token.class.ancestors.include?(Oauth2Token)\n token = access_token\n else\n if user\n token = self.find_or_initialize_by_user_id_and_token(user.id, access_token.token)\n else\n token = self.find_or_initialize_by_token(access_token.token)\n end\n end\n\n token = if new_token then set_details(new_token, access_token) else set_details(access_token, token) end\n\n token.save! if token.new_record? or token.changed?\n\n token\n end",
"def access_token\n @auth.access_token\n end",
"def access_token\n @oauth_access_token ||= ::OAuth::AccessToken.new(consumer, @access_token, @access_secret)\n end",
"def bearer_token\n # Put the url together\n url = \"#{API_HOST}#{TOKEN_PATH}\"\n\n raise \"Please set your CLIENT_ID\" if CLIENT_ID.nil?\n raise \"Please set your CLIENT_SECRET\" if CLIENT_SECRET.nil?\n\n # Build our params hash\n params = {\n client_id: CLIENT_ID,\n client_secret: CLIENT_SECRET,\n grant_type: GRANT_TYPE\n }\n\n response = HTTP.post(url, params: params)\n parsed = response.parse\n\n \"#{parsed['token_type']} #{parsed['access_token']}\"\nend",
"def create_api_token\n begin\n ApiToken.create(api_consumer: self)\n end\n end",
"def build_access_token\n verifier = request.params[\"code\"]\n client.auth_code.get_token(verifier, token_params.to_hash(:symbolize_keys => true), deep_symbolize(options.auth_token_params))\n end",
"def generate_access_token\n begin\n self.token = SecureRandom.hex\n end while self.class.exists?(token: token)\n end",
"def generate_access_token\n begin\n self.token = SecureRandom.hex\n end while self.class.exists?(token: token)\n end",
"def access_token\n # Synchronization is needed, otherwise race condition may ensue:\n # Let's assume token has expired, and two threads ask for a new token.\n # Both proceed to fetch the token from remote server, both return,\n # but the first token is no longer valid.\n MUTEX.synchronize do\n token = Nordea::Siirto.redis.get(KEY)\n return token if token\n\n Nordea::Siirto.log('Requesting new access token...')\n payload = response.body\n\n token = payload['access_token']\n expires_in = payload['expires_in'] - EXPIRATION_BUFFER\n Nordea::Siirto.redis.set(KEY, token)\n Nordea::Siirto.redis.expire(KEY, expires_in)\n\n token\n end\n end",
"def bearer_token\n # Put the url together\n url = \"#{API_HOST}#{TOKEN_PATH}\"\n\n raise \"Please set your CLIENT_ID\" if CLIENT_ID.nil?\n raise \"Please set your CLIENT_SECRET\" if CLIENT_SECRET.nil?\n\n # Build our params hash\n params = {\n client_id: CLIENT_ID,\n client_secret: CLIENT_SECRET,\n grant_type: GRANT_TYPE\n }\n\n response = HTTP.post(url, params: params)\n parsed = response.parse\n\n \"#{parsed['token_type']} #{parsed['access_token']}\"\nend",
"def token\n\t\t@token = ApiKey.find_by_user_id(self.id)\n\t\tif @token == nil\n\t\t\t\treturn ApiKey.create!(user: self)\n\t\telse\n\t\t\t\treturn @token\n\t\tend\n\tend",
"def get_access_token(auth_code)\n @access_token = @oauth_client.auth_code.get_token(auth_code, :redirect_uri => @redirect_uri)\n @token = @access_token.token\n @refresh_token = @access_token.refresh_token\n @token_expires_at = @access_token.expires_at\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def get_access_token\n\t\t\tif @access_token.nil?\n\t\t\t\t# do we have it cached on disk?\n\t\t\t\ttmp_file = get_access_token_file\n\n\t\t\t\tif File.exist? tmp_file\n\t\t\t\t\t@logger.info 'Fetching cached auth token from disk'\n\t\t\t\t\tset_access_token(File.read(tmp_file).strip)\n\t\t\t\tend\n\t\t\tend\n\n\t\t\t# try again, get a fresh token\n\t\t\tif @access_token.nil?\n\t\t\t\turi = URI(\"https://#{@club_name}.tidyclub.com/oauth/token\")\n\t\t\t\t@logger.info \"Fetching a fresh token from #{uri}\"\n\t\t\t\thttps = Net::HTTP.new(uri.host, uri.port)\n\t\t\t\thttps.use_ssl = true\n\t\t\t\tpayload = {\n\t\t\t\t\t\tclient_id: client_id,\n\t\t\t\t\t\tclient_secret: client_secret,\n\t\t\t\t\t\tusername: user_name,\n\t\t\t\t\t\tpassword: password,\n\t\t\t\t\t\tgrant_type: 'password'\n\t\t\t\t}\n\t\t\t\trequest = Net::HTTP::Post.new(uri.path)\n\n\t\t\t\trequest.set_form_data payload\n\t\t\t\tresponse = https.request(request)\n\n\t\t\t\tif response.content_type != 'application/json'\n\t\t\t\t\tmsg = \"Expecting a JSON response, got a response type of '#{response.content_type}' instead\"\n\t\t\t\t\t@logger.error msg\n\t\t\t\t\traise TidyClub::ApiCallBad, msg\n\t\t\t\tend\n\n\t\t\t\tif response.code.to_i == 200\n\t\t\t\t\tr = JSON.parse response.body\n\t\t\t\t\tset_access_token r['access_token']\n\t\t\t\telse\n\t\t\t\t\tmsg = \"Authentication Failed - response code was: #{response.code} - #{response.message}\"\n\t\t\t\t\t@logger.error msg\n\t\t\t\t\traise TidyClub::ApiCallBad, msg\n\t\t\t\tend\n\t\t\tend\n\t\t\t@access_token = nil if @access_token == ''\n\n\t\t\tif @access_token.nil?\n\t\t\t\tmsg = 'There is no valid access token'\n\t\t\t\t@logger.error msg\n\t\t\t\traise AuthenticationError, msg\n\t\t\tend\n\n\t\t\t@access_token\n\t\tend",
"def get_access_token(options={})\n response=consumer.token_request(consumer.http_method,(consumer.access_token_url? ? consumer.access_token_url : consumer.access_token_path),self,options)\n OAuth::AccessToken.new(consumer,response[:oauth_token],response[:oauth_token_secret])\n end",
"def get_new_access_token\n now = Time.now\n params = {\n body: {\n grant_type: 'urn:ietf:params:oauth:grant-type:uma-ticket',\n ticket: retrieve_ticket,\n client_id: key_info['oxtrust_client_id'],\n client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',\n client_assertion: generate_json_web_token(now),\n scope: 'oxtrust-api-read oxtrust-api-write'\n }\n }\n req = HTTParty.post('https://localhost/oxauth/restv1/token', params)\n if req.code == 200\n token = req['access_token']\n save_access_token(token, now.to_i + 86_400)\n token\n else\n Puppet.err(\n \"Gluu API HTTP #{req.code}: #{req['error_description']}\",\n )\n end\n end",
"def get_access_token\n auth = storage['authentication']\n return auth['access_token'] if auth && auth['expires'] > Time.now.to_i\n\n auth = authenticate_client\n storage['authentication'] = auth\n auth['access_token']\n end",
"def create_token\n return api_call('request-token',{\"apiKey\"=> @@_api_key });\n end",
"def retrieve_token!\n body = request_token\n # Refresh our token early so that it won't expire while a request is in-flight. We expect 15m\n # expirys for tokens but are careful not to trim the expiry by too much, just in case\n expires_in = body['expires_in'].seconds\n if expires_in - AUTH_TOKEN_PREEMPTIVE_EXPIRY_MINUTES > 0\n expires_in -= AUTH_TOKEN_PREEMPTIVE_EXPIRY_MINUTES\n end\n token = \"#{body['token_type']} #{body['access_token']}\"\n Rails.cache.write(AUTH_TOKEN_CACHE_KEY, token, expires_in: expires_in)\n token\n end",
"def token_generator(user_id, user_ip)\n return unless user_id\n\n user = User.find(user_id)\n\n access_token = user.tokens.create(token: token_creator, request_ip: user_ip)\n JsonWebToken.encode(\n token: access_token.token,\n request_ip: access_token.request_ip\n )\n end",
"def get_access_token! name = nil\n oauth_instance(name).get_access_token!(oauth_request_env)\n end",
"def create_access_token(user_id)\n # Create new access token\n token = JWT.encode({user_id: user_id, type: \"access\", salt: token_salt()}, 's3cr3t')\n exp_time = Time.now + 15*60 # 15 minutes\n Blacklist.create({ jwt: token, expiration: exp_time })\n end",
"def create\n oauth_verifier = params[:oauth_verifier]\n\n if oauth_verifier\n request_token = session[:tumblr_request_token]\n access_token = request_token.get_access_token(\n :oauth_verifier => oauth_verifier) \n\n self.current_user.tumblr_access_token = access_token.token\n self.current_user.tumblr_access_token_secret = access_token.secret\n\n self.current_user.save!\n end\n\n rescue => ex\n handle_exception(ex)\n end",
"def create_new_auth_token(client_id=nil)\n client_id ||= SecureRandom.urlsafe_base64(nil, false)\n last_token ||= nil\n token = SecureRandom.urlsafe_base64(nil, false)\n token_hash = ::BCrypt::Password.create(token)\n expiry = (Time.now + DeviseTokenAuth.token_lifespan).to_i\n\n if self.tokens[client_id] && self.tokens[client_id]['token']\n last_token = self.tokens[client_id]['token']\n end\n\n self.tokens[client_id] = {\n token: token_hash,\n expiry: expiry,\n last_token: last_token,\n updated_at: Time.now\n }\n\n return build_auth_header(token, client_id)\n end",
"def auth_token\n TokenProvider.issue_token(\n first_name: object.first_name,\n last_name: object.last_name,\n username: object.username,\n user_id: object.id,\n role: object.role\n )\n end",
"def auth_token\n AuthToken.new payload: { sub: user.id }\n end",
"def get_access_token\n @oauth_access_token = oauth_request.get_access_token\n @authenticated_user_uri = oauth_consumer.token_request_response[\"Content-Location\"]\n end",
"def create_new_auth_token(client_id=nil)\n client_id ||= SecureRandom.urlsafe_base64(nil, false)\n last_token ||= nil\n token = SecureRandom.urlsafe_base64(nil, false)\n token_hash = BCrypt::Password.create(token)\n expiry = (Time.now + DeviseTokenAuth.token_lifespan).to_i\n\n if self.tokens[client_id] and self.tokens[client_id]['token']\n last_token = self.tokens[client_id]['token']\n end\n\n self.tokens[client_id] = {\n token: token_hash,\n expiry: expiry,\n last_token: last_token,\n updated_at: Time.now\n }\n\n self.save!\n\n return build_auth_header(token, client_id)\n end",
"def create_token\n @user = User.find(params[:id])\n @token = Token.generate(@user)\n\n respond_to do |format|\n if @token.save\n format.html { redirect_to action: 'index'}\n format.json { render :show, status: :created, location: @token }\n else\n format.html { render :new }\n format.json { render json: @token.errors, status: :unprocessable_entity }\n end\n end\n end",
"def get_access_token name = nil\n oauth_instance(name).get_access_token(oauth_request_env)\n end",
"def create\n user = User.find_for_authentication(email: user_params[:email])\n\n if user && user.valid_password?(user_params[:password])\n user.generate_authentication_token\n\n expose({\n user_id: user.id,\n token: user.authentication_token\n })\n else\n error! :unauthenticated\n end\n end",
"def access_token\n Rails.cache.fetch(\"googl_access_token\", expires_in: 50.minutes) do \n request = { query: { client_id: ENV['GOOGL_CLIENT_ID'],\n client_secret: ENV['GOOGL_CLIENT_SECRET'],\n refresh_token: ENV['GOOGL_REFRESH_TOKEN'],\n grant_type: \"refresh_token\"} }\n\n result = self.class.post(\"/oauth2/v3/token\", request)\n\n result.parsed_response[\"access_token\"]\n end\n end",
"def create\n @user = User.create_or_find_by(user_params)\n my_token = issue_token(@user)\n\n render json: {user: @user, token: my_token}\n # render json: @user\n \n end",
"def acquire_token\n token_acquire_url = TOKEN_ACQUIRE_URL.dup\n token_acquire_url['{authentication_endpoint}'] = @settings.authentication_endpoint\n token_acquire_url['{tenant_id}'] = @tenant_id\n\n url = URI.parse(token_acquire_url)\n\n connection = Faraday.new(:url => url, :ssl => MsRest.ssl_options) do |builder|\n builder.adapter Faraday.default_adapter\n end\n\n request_body = REQUEST_BODY_PATTERN.dup\n request_body['{resource_uri}'] = ERB::Util.url_encode(@settings.token_audience)\n request_body['{client_id}'] = ERB::Util.url_encode(@client_id)\n request_body['{username}'] = ERB::Util.url_encode(@username)\n request_body['{password}'] = ERB::Util.url_encode(@password)\n\n response = connection.get do |request|\n request.headers['content-type'] = 'application/x-www-form-urlencoded'\n request.body = request_body\n end\n\n fail AzureOperationError,\n 'Couldn\\'t login to Azure, please verify your tenant id, client id and username/password' unless response.status == 200\n\n response_body = JSON.load(response.body)\n @token = response_body['access_token']\n @token_expires_on = Time.at(Integer(response_body['expires_on']))\n @token_type = response_body['token_type']\n end",
"def store_access_token(data)\n @access_token = data['access_token']\n @expires_at = Time.now + data['expires_in']\n end",
"def get_access_token(request_token = @request_token)\n # response = @consumer.token_request(@consumer.http_method,\n # (@consumer.access_token_url? ? @consumer.access_token_url : @consumer.access_token_path),\n # request_token,\n # {},\n # headers)\n\n # @access_token = ::OAuth::AccessToken.new(@consumer, response[:oauth_token], response[:oauth_token_secret])\n @access_token = request_token.get_access_token\n end",
"def call\n if user\n {access_token:JsonWebToken.encode(user_id: user.id),\n user_role: user.role}\n end \n end",
"def access_token\n @access_token\n end"
] |
[
"0.837983",
"0.7738527",
"0.7649867",
"0.7432391",
"0.7368562",
"0.73682564",
"0.73682564",
"0.73566306",
"0.72725546",
"0.7208799",
"0.7194847",
"0.7132002",
"0.7124675",
"0.7063991",
"0.7047327",
"0.7031162",
"0.7015049",
"0.70109236",
"0.7001952",
"0.69994843",
"0.69932663",
"0.6985946",
"0.6985874",
"0.69719744",
"0.6957197",
"0.6955775",
"0.69529724",
"0.69427776",
"0.69369197",
"0.6931398",
"0.69217914",
"0.69169134",
"0.6875921",
"0.68729305",
"0.68714225",
"0.68714225",
"0.68714225",
"0.6871341",
"0.6870992",
"0.6868174",
"0.6867405",
"0.6863658",
"0.6843802",
"0.6836949",
"0.683643",
"0.6834402",
"0.6824881",
"0.6824881",
"0.68239737",
"0.6803419",
"0.68002397",
"0.6791589",
"0.6789507",
"0.6782346",
"0.67791235",
"0.67791235",
"0.67791235",
"0.6778838",
"0.67534715",
"0.6753025",
"0.67478335",
"0.6743449",
"0.67403823",
"0.67221814",
"0.67219114",
"0.67181283",
"0.6714145",
"0.6714145",
"0.67073536",
"0.6700022",
"0.6696897",
"0.6695512",
"0.66887635",
"0.66887635",
"0.66887635",
"0.66887635",
"0.6658521",
"0.6656149",
"0.6649209",
"0.66491884",
"0.66361916",
"0.6629653",
"0.66239876",
"0.66231287",
"0.66227794",
"0.6597607",
"0.65899587",
"0.6589642",
"0.6585919",
"0.6583701",
"0.6579629",
"0.6572608",
"0.65697217",
"0.6551514",
"0.6550541",
"0.65494096",
"0.65439796",
"0.6540597",
"0.6540047",
"0.65396535",
"0.6536603"
] |
0.0
|
-1
|
Create a token Create an access_token for this user and get it.
|
def users_id_user_token_post_with_http_info(id_user, application, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersManagementApi.users_id_user_token_post ...'
end
# verify the required parameter 'id_user' is set
if @api_client.config.client_side_validation && id_user.nil?
fail ArgumentError, "Missing the required parameter 'id_user' when calling UsersManagementApi.users_id_user_token_post"
end
# verify the required parameter 'application' is set
if @api_client.config.client_side_validation && application.nil?
fail ArgumentError, "Missing the required parameter 'application' when calling UsersManagementApi.users_id_user_token_post"
end
# resource path
local_var_path = '/users/{id_user}/token'.sub('{' + 'id_user' + '}', id_user.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded'])
# form parameters
form_params = {}
form_params['application'] = application
# http body (model)
post_body = nil
auth_names = ['api_key']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Object')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersManagementApi#users_id_user_token_post\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def access_token\n User.create_access_token(self)\n end",
"def generate_access_token\n self.access_token ||= self.create_access_token\n save && access_token\n end",
"def create\n require 'digest/sha1'\n \n @access_token = AccessToken.new\n @access_token.user_id = current_user.id\n @access_token.last_access = Time.now\n @access_token.token = Digest::SHA1.hexdigest Time.now.to_s\n @access_token.active = true\n \n respond_to do |format|\n if @access_token.save\n format.html { redirect_to(@access_token, :notice => 'Access token was successfully created.') }\n format.xml { render :xml => @access_token, :status => :created, :location => @access_token }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @access_token.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create_token\n client_requested_expires_in = server.jwt['exp'].to_i - server.jwt['iat'].to_i\n server_expires_in = Authorization::Token.access_token_expires_in(configuration, client)\n if server_expires_in\n expires_in = (client_requested_expires_in > 0 && client_requested_expires_in <= server_expires_in) ? client_requested_expires_in : server_expires_in\n else\n expires_in = nil\n end\n @access_token = AccessToken.find_or_create_for(application: client.application, resource_owner: resource_owner, scopes: scopes, expires_in: expires_in, use_refresh_token: configuration.refresh_token_enabled?)\n end",
"def generate_token\n token_hash = SecureRandom.hex\n token_hash.force_encoding('utf-8')\n access_tokens.create(token: token_hash, token_expire: Time.now + DEFAULT_TOKEN_EXPIRE)\n end",
"def generate_token\n token_hash = SecureRandom.hex\n token_hash.force_encoding('utf-8')\n access_tokens.create(token: token_hash, token_expire: Time.now + DEFAULT_TOKEN_EXPIRE)\n end",
"def access_token\n @access_token ||= AccessToken.new(caller_service: caller_service, authorizator_service: authorizator_service)\n end",
"def generate_auth_token\n token = AuthToken.new(user: self)\n token if token.save\n end",
"def generate_access_token\n begin\n self.access_token = User.new_token\n end while ApiKey.exists?(access_token: access_token)\n end",
"def access_token\n @access_token ||= begin\n if oauth_options[:oauth_verifier]\n request_token.get_access_token(:oauth_verifier => oauth_options[:oauth_verifier])\n else\n request_token.get_access_token\n end\n end\n end",
"def get_access_token\n raise HyvesException, 'You need an request token to make get an access token' if request_token.nil?\n @access_token = request_token.get_access_token\n\n @userid = request_token.response[\"userid\"]\n @expiredate = Time.at(request_token.response[\"expiredate\"].to_i) if not request_token.response[\"expiredate\"].nil?\n\n @access_token\n end",
"def build_token(access_token)\n return OAuth2::AccessToken.new CLIENT, access_token\n end",
"def create\n puts \"MESSAGE 14 IN CREATE\"\n @auth = request.env['omniauth.auth']['credentials']\n # The following statement saves the tokens to the database\n Token.create(\n access_token: @auth['token'],\n refresh_token: @auth['refresh_token'],\n expires_at: Time.at(@auth['expires_at']).to_datetime)\n end",
"def create\n token_response = ResourceAccessTokens::CreateService.new(current_user, resource, create_params).execute\n\n if token_response.success?\n @resource_access_token = token_response.payload[:access_token]\n PersonalAccessToken.redis_store!(key_identity, @resource_access_token.token)\n\n redirect_to resource_access_tokens_path, notice: _(\"Your new access token has been created.\")\n else\n redirect_to resource_access_tokens_path, alert: _(\"Failed to create new access token: %{token_response_message}\") % { token_response_message: token_response.message }\n end\n end",
"def create\n super\n \n if @access_token.client.uses_account_sid\n # Never expire this token. It will be expired when the user explicitly\n # ends their session (by logging out), and possibly after a configurable\n # amount of time, if the provider is using expiration scheduling\n # (see the sessions:expire rake task).\n @access_token.expires_at = Time.mktime(2100, 12, 31)\n end\n \n authorization_code = Oauth2Providable::AuthorizationCode.find_by_token(params[:code])\n @access_token.account_sid = authorization_code.account_sid\n @access_token.client_sid = params[:client_sid]\n @access_token.save\n end",
"def generate_access_token\n self.access_token = SecureRandom.hex(64)\n end",
"def token\n @access_token.token\n end",
"def create_access_token(id:, type: nil)\n params = {\n id: id,\n type: type\n }\n client.make_request('/create-access-token', 'post', params: params)\n end",
"def create\n client.authorization_code = params[:code]\n access_token = client.access_token!\n puts access_token\n end",
"def create\n user = User.create!(user_params)\n render json: { token: user.auth_token }\n end",
"def create\n @model = AccessToken.new(access_token_params)\n @model.user = current_user\n\n respond_to do |format|\n if @model.save\n format.html { redirect_to @model, notice: 'Access token was successfully created.' }\n format.json { render :show, status: :created, location: @model }\n else\n format.html { render :new }\n format.json { render json: @model.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @access_token = AccessToken.new(params[:access_token])\n\n respond_to do |format|\n if @access_token.save\n format.html { redirect_to @access_token, notice: 'Access token was successfully created.' }\n format.json { render json: @access_token, status: :created, location: @access_token }\n else\n format.html { render action: \"new\" }\n format.json { render json: @access_token.errors, status: :unprocessable_entity }\n end\n end\n end",
"def access_token\n user_token = @user_token\n goat.transaction do\n if user_token.access_token.nil?\n user_token.access_token = request_token.get_access_token\n if !user_token.access_token.nil?\n goat[user_token.user] = user_token\n end\n end\n end\n @user_token = user_token\n @user_token.access_token\n end",
"def token\n access_token = @token_manager.access_token\n raise 'CloudTools::IAMAuth Unable to retrieve the access token from token manager.' if access_token.nil?\n\n access_token\n end",
"def token\n return @token if @token\n\n options = @options.merge(\n body: {\n client_id: @client_id,\n client_secret: @client_secret,\n grant_type: 'client_credentials'\n },\n headers: {\n 'Accept' => 'application/json',\n 'Host' => uri.host\n }\n )\n url = \"#{@base_url}/auth/oauth/v2/token\"\n\n @logger.debug(\"Request token from #{url}\")\n\n response = raises_unless_success do\n HTTParty.post(url, options)\n end.parsed_response\n\n @token = Token.new(\n *response.values_at('access_token', 'token_type', 'expires_in', 'scope')\n )\n end",
"def access_token\n @access_token ||= OAuth::AccessToken.new(consumer, @token, @secret)\n end",
"def token\n return @access_token if @access_token && !needs_refresh?\n\n update_access_token\n @access_token\n end",
"def access_token\n @access_token ||= OAuth::AccessToken.new(consumer, @token, @secret)\n end",
"def token_generate\n res = call('auth.token_generate')\n\n return unless res || res['token']\n\n res['token']\n end",
"def set_access_token\n access_tokens.create(token: SecureRandom.urlsafe_base64(20))\n end",
"def create_set_and_add_token\n token = SecureRandom.urlsafe_base64\n @user.token = token\n response.headers['X-AUTH-TOKEN'] = token\n end",
"def access_token\n OAuth::AccessToken.new(consumer, oauth_token, oauth_token_secret)\n end",
"def get_token\n begin\n @response = RestClient.post(\n @consumer[:token_request_url],\n client_id: @consumer[:client_id],\n client_secret: @consumer[:client_secret],\n grant_type: @consumer[:grant_type],\n resource: @consumer[:resource]\n )\n\n @consumer[:token] = 'Bearer ' + JSON.parse(@response)['access_token']\n @consumer[:token_expiry] = JSON.parse(@response)['expires_on']\n rescue => error\n puts(\"ERROR - Token Request Failed - #{error}\")\n end\n @consumer[:token]\n end",
"def access_token\n # Fetch from cache. We can expect this to be `nil` if unset or expired.\n #\n access_token = read_cache\n\n return access_token if access_token\n\n fetch_new_access_token\n end",
"def token\n auth_client.token(settings.oauth2_token).tap do |token|\n settings.save_oauth2_token(token.to_hash)\n end\n end",
"def acquire_token()\n response_body = JSON.load(`#{cli_path} account get-access-token -o json --resource #{@settings.token_audience}`)\n \n @token_expires_on = Time.parse(response_body['expiresOn'])\n @token_type = response_body['tokenType']\n @token = response_body['accessToken']\n rescue\n raise AzureCliError, 'Error acquiring token from the Azure CLI'\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def get_access_token\n\t\treturn @credentials.get_access_token\n\tend",
"def access_token()\n if @access_token_obj\n @access_token_obj.token\n else\n return nil\n end\n end",
"def bearer_token\n # Put the url together\n url = \"#{API_HOST}#{TOKEN_PATH}\"\n\n # Build our params hash\n params = {\n client_id: @client_id,\n client_secret: @client_secret,\n grant_type: GRANT_TYPE\n }\n\n response = HTTP.post(url, params: params)\n parsed = response.parse\n\n \"#{parsed['token_type']} #{parsed['access_token']}\"\n end",
"def create_token\n Rails.logger.info(\"Enter Create Token\")\n \n # create token\n token = GenerateToken.unique_token\n access_token = self.create_access_token( token: token, role: {})\n raise et(\"account.create_token_failed\") if access_token.blank?\n\n true\n rescue => e \n Rails.logger.error(\"**** ERROR **** #{e.message}\")\n end",
"def generate_token\n new_token =\n SimpleTokenAuthentication::TokenGenerator.instance.generate_token\n update(authentication_token: new_token)\n self\n end",
"def fetch_access_token\n client.unauthenticated_request(:POST, '/v1/security/oauth2/token',\n grant_type: 'client_credentials',\n client_id: client.client_id,\n client_secret: client.client_secret)\n end",
"def init_oauth_access_token\n @oauth_access_token = OAuth2::AccessToken.new(\n User.new_oauth_client,\n read_attribute(:access_token),\n {\n :refresh_token => read_attribute(:refresh_token),\n :expires_at => read_attribute(:access_token_expires_at)\n }\n )\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def generate_access_token\n token_string = \"#{@username}:#{@password}\"\n return Base64.strict_encode64(token_string)\n end",
"def get_access_token()\n url = URI.parse(TOKEN_ENDPOINT)\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n req = Net::HTTP::Post.new(url.path)\n req.basic_auth(@clientId, @clientSecret)\n req.set_form_data({'grant_type' => 'client_credentials'})\n res = http.request(req)\n JSON.parse(res.body)['access_token']\n end",
"def create_access_token\n hash = nil\n Songkick::OAuth2.generate_id do |token|\n hash = Songkick::OAuth2.hashify(token) \n end\n return hash\n end",
"def fetch\n response = request.post(path: \"/#{base_path}/token\", claims_token: claims_token.static)\n\n self.access_token = Oj.load(response.body)['token']\n self\n end",
"def generate_token\n self.status = STATUS[:present]\n self.access_token = SecureRandom.urlsafe_base64(45, true)\n self.expires = Time.zone.now.to_i + TOKEN_LIFE\n self.login_time = Time.zone.now\n self.user_events.build(event_name: 'Login', event_time: Time.zone.now)\n save\n self.access_token\n end",
"def get_access_token(grant_type, options = {})\n object_from_response(GogoKit::OAuthToken,\n GogoKit::OAuthTokenRepresenter,\n :post,\n oauth_token_endpoint,\n body: token_request_body(grant_type, options),\n headers: token_request_headers)\n end",
"def access_token\n @attributes[:access_token] || client.token\n end",
"def access_token\n @attributes[:access_token] || client.token\n end",
"def access_token\n @attributes[:access_token] || client.token\n end",
"def create\n user = User.find_by(email: auth_params[:email])\n if user&.valid_password?(auth_params[:password])\n @token = user.api_tokens.find_or_create_by(name: (auth_params[:name] || \"default\")) do |token|\n token.make_token.save!\n end\n render json: {\n token: @token.token\n }\n else\n head :unauthorized\n end\n end",
"def access_token\n @access_token ||= ShakeTheCounter::Authentication.renew_access_token(client_id: id, client_secret: secret, refresh_token: refresh_token)[\"access_token\"]\n end",
"def call\n # after user login, will pass the user-id to the JWT to create token\n return nil unless user\n\n return JsonWebToken.create_token(user_id: user.id), user\n end",
"def find_or_create_from_access_token(user, access_token, new_token = nil)\n if access_token.class.ancestors.include?(Oauth2Token)\n token = access_token\n else\n if user\n token = self.find_or_initialize_by_user_id_and_token(user.id, access_token.token)\n else\n token = self.find_or_initialize_by_token(access_token.token)\n end\n end\n\n token = if new_token then set_details(new_token, access_token) else set_details(access_token, token) end\n\n token.save! if token.new_record? or token.changed?\n\n token\n end",
"def access_token\n @auth.access_token\n end",
"def access_token\n @oauth_access_token ||= ::OAuth::AccessToken.new(consumer, @access_token, @access_secret)\n end",
"def bearer_token\n # Put the url together\n url = \"#{API_HOST}#{TOKEN_PATH}\"\n\n raise \"Please set your CLIENT_ID\" if CLIENT_ID.nil?\n raise \"Please set your CLIENT_SECRET\" if CLIENT_SECRET.nil?\n\n # Build our params hash\n params = {\n client_id: CLIENT_ID,\n client_secret: CLIENT_SECRET,\n grant_type: GRANT_TYPE\n }\n\n response = HTTP.post(url, params: params)\n parsed = response.parse\n\n \"#{parsed['token_type']} #{parsed['access_token']}\"\nend",
"def create_api_token\n begin\n ApiToken.create(api_consumer: self)\n end\n end",
"def build_access_token\n verifier = request.params[\"code\"]\n client.auth_code.get_token(verifier, token_params.to_hash(:symbolize_keys => true), deep_symbolize(options.auth_token_params))\n end",
"def generate_access_token\n begin\n self.token = SecureRandom.hex\n end while self.class.exists?(token: token)\n end",
"def generate_access_token\n begin\n self.token = SecureRandom.hex\n end while self.class.exists?(token: token)\n end",
"def access_token\n # Synchronization is needed, otherwise race condition may ensue:\n # Let's assume token has expired, and two threads ask for a new token.\n # Both proceed to fetch the token from remote server, both return,\n # but the first token is no longer valid.\n MUTEX.synchronize do\n token = Nordea::Siirto.redis.get(KEY)\n return token if token\n\n Nordea::Siirto.log('Requesting new access token...')\n payload = response.body\n\n token = payload['access_token']\n expires_in = payload['expires_in'] - EXPIRATION_BUFFER\n Nordea::Siirto.redis.set(KEY, token)\n Nordea::Siirto.redis.expire(KEY, expires_in)\n\n token\n end\n end",
"def bearer_token\n # Put the url together\n url = \"#{API_HOST}#{TOKEN_PATH}\"\n\n raise \"Please set your CLIENT_ID\" if CLIENT_ID.nil?\n raise \"Please set your CLIENT_SECRET\" if CLIENT_SECRET.nil?\n\n # Build our params hash\n params = {\n client_id: CLIENT_ID,\n client_secret: CLIENT_SECRET,\n grant_type: GRANT_TYPE\n }\n\n response = HTTP.post(url, params: params)\n parsed = response.parse\n\n \"#{parsed['token_type']} #{parsed['access_token']}\"\nend",
"def token\n\t\t@token = ApiKey.find_by_user_id(self.id)\n\t\tif @token == nil\n\t\t\t\treturn ApiKey.create!(user: self)\n\t\telse\n\t\t\t\treturn @token\n\t\tend\n\tend",
"def get_access_token(auth_code)\n @access_token = @oauth_client.auth_code.get_token(auth_code, :redirect_uri => @redirect_uri)\n @token = @access_token.token\n @refresh_token = @access_token.refresh_token\n @token_expires_at = @access_token.expires_at\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def get_access_token\n\t\t\tif @access_token.nil?\n\t\t\t\t# do we have it cached on disk?\n\t\t\t\ttmp_file = get_access_token_file\n\n\t\t\t\tif File.exist? tmp_file\n\t\t\t\t\t@logger.info 'Fetching cached auth token from disk'\n\t\t\t\t\tset_access_token(File.read(tmp_file).strip)\n\t\t\t\tend\n\t\t\tend\n\n\t\t\t# try again, get a fresh token\n\t\t\tif @access_token.nil?\n\t\t\t\turi = URI(\"https://#{@club_name}.tidyclub.com/oauth/token\")\n\t\t\t\t@logger.info \"Fetching a fresh token from #{uri}\"\n\t\t\t\thttps = Net::HTTP.new(uri.host, uri.port)\n\t\t\t\thttps.use_ssl = true\n\t\t\t\tpayload = {\n\t\t\t\t\t\tclient_id: client_id,\n\t\t\t\t\t\tclient_secret: client_secret,\n\t\t\t\t\t\tusername: user_name,\n\t\t\t\t\t\tpassword: password,\n\t\t\t\t\t\tgrant_type: 'password'\n\t\t\t\t}\n\t\t\t\trequest = Net::HTTP::Post.new(uri.path)\n\n\t\t\t\trequest.set_form_data payload\n\t\t\t\tresponse = https.request(request)\n\n\t\t\t\tif response.content_type != 'application/json'\n\t\t\t\t\tmsg = \"Expecting a JSON response, got a response type of '#{response.content_type}' instead\"\n\t\t\t\t\t@logger.error msg\n\t\t\t\t\traise TidyClub::ApiCallBad, msg\n\t\t\t\tend\n\n\t\t\t\tif response.code.to_i == 200\n\t\t\t\t\tr = JSON.parse response.body\n\t\t\t\t\tset_access_token r['access_token']\n\t\t\t\telse\n\t\t\t\t\tmsg = \"Authentication Failed - response code was: #{response.code} - #{response.message}\"\n\t\t\t\t\t@logger.error msg\n\t\t\t\t\traise TidyClub::ApiCallBad, msg\n\t\t\t\tend\n\t\t\tend\n\t\t\t@access_token = nil if @access_token == ''\n\n\t\t\tif @access_token.nil?\n\t\t\t\tmsg = 'There is no valid access token'\n\t\t\t\t@logger.error msg\n\t\t\t\traise AuthenticationError, msg\n\t\t\tend\n\n\t\t\t@access_token\n\t\tend",
"def get_access_token(options={})\n response=consumer.token_request(consumer.http_method,(consumer.access_token_url? ? consumer.access_token_url : consumer.access_token_path),self,options)\n OAuth::AccessToken.new(consumer,response[:oauth_token],response[:oauth_token_secret])\n end",
"def get_access_token\n auth = storage['authentication']\n return auth['access_token'] if auth && auth['expires'] > Time.now.to_i\n\n auth = authenticate_client\n storage['authentication'] = auth\n auth['access_token']\n end",
"def get_new_access_token\n now = Time.now\n params = {\n body: {\n grant_type: 'urn:ietf:params:oauth:grant-type:uma-ticket',\n ticket: retrieve_ticket,\n client_id: key_info['oxtrust_client_id'],\n client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',\n client_assertion: generate_json_web_token(now),\n scope: 'oxtrust-api-read oxtrust-api-write'\n }\n }\n req = HTTParty.post('https://localhost/oxauth/restv1/token', params)\n if req.code == 200\n token = req['access_token']\n save_access_token(token, now.to_i + 86_400)\n token\n else\n Puppet.err(\n \"Gluu API HTTP #{req.code}: #{req['error_description']}\",\n )\n end\n end",
"def create_token\n return api_call('request-token',{\"apiKey\"=> @@_api_key });\n end",
"def retrieve_token!\n body = request_token\n # Refresh our token early so that it won't expire while a request is in-flight. We expect 15m\n # expirys for tokens but are careful not to trim the expiry by too much, just in case\n expires_in = body['expires_in'].seconds\n if expires_in - AUTH_TOKEN_PREEMPTIVE_EXPIRY_MINUTES > 0\n expires_in -= AUTH_TOKEN_PREEMPTIVE_EXPIRY_MINUTES\n end\n token = \"#{body['token_type']} #{body['access_token']}\"\n Rails.cache.write(AUTH_TOKEN_CACHE_KEY, token, expires_in: expires_in)\n token\n end",
"def token_generator(user_id, user_ip)\n return unless user_id\n\n user = User.find(user_id)\n\n access_token = user.tokens.create(token: token_creator, request_ip: user_ip)\n JsonWebToken.encode(\n token: access_token.token,\n request_ip: access_token.request_ip\n )\n end",
"def get_access_token! name = nil\n oauth_instance(name).get_access_token!(oauth_request_env)\n end",
"def create_access_token(user_id)\n # Create new access token\n token = JWT.encode({user_id: user_id, type: \"access\", salt: token_salt()}, 's3cr3t')\n exp_time = Time.now + 15*60 # 15 minutes\n Blacklist.create({ jwt: token, expiration: exp_time })\n end",
"def create\n oauth_verifier = params[:oauth_verifier]\n\n if oauth_verifier\n request_token = session[:tumblr_request_token]\n access_token = request_token.get_access_token(\n :oauth_verifier => oauth_verifier) \n\n self.current_user.tumblr_access_token = access_token.token\n self.current_user.tumblr_access_token_secret = access_token.secret\n\n self.current_user.save!\n end\n\n rescue => ex\n handle_exception(ex)\n end",
"def create_new_auth_token(client_id=nil)\n client_id ||= SecureRandom.urlsafe_base64(nil, false)\n last_token ||= nil\n token = SecureRandom.urlsafe_base64(nil, false)\n token_hash = ::BCrypt::Password.create(token)\n expiry = (Time.now + DeviseTokenAuth.token_lifespan).to_i\n\n if self.tokens[client_id] && self.tokens[client_id]['token']\n last_token = self.tokens[client_id]['token']\n end\n\n self.tokens[client_id] = {\n token: token_hash,\n expiry: expiry,\n last_token: last_token,\n updated_at: Time.now\n }\n\n return build_auth_header(token, client_id)\n end",
"def auth_token\n TokenProvider.issue_token(\n first_name: object.first_name,\n last_name: object.last_name,\n username: object.username,\n user_id: object.id,\n role: object.role\n )\n end",
"def auth_token\n AuthToken.new payload: { sub: user.id }\n end",
"def get_access_token\n @oauth_access_token = oauth_request.get_access_token\n @authenticated_user_uri = oauth_consumer.token_request_response[\"Content-Location\"]\n end",
"def create_new_auth_token(client_id=nil)\n client_id ||= SecureRandom.urlsafe_base64(nil, false)\n last_token ||= nil\n token = SecureRandom.urlsafe_base64(nil, false)\n token_hash = BCrypt::Password.create(token)\n expiry = (Time.now + DeviseTokenAuth.token_lifespan).to_i\n\n if self.tokens[client_id] and self.tokens[client_id]['token']\n last_token = self.tokens[client_id]['token']\n end\n\n self.tokens[client_id] = {\n token: token_hash,\n expiry: expiry,\n last_token: last_token,\n updated_at: Time.now\n }\n\n self.save!\n\n return build_auth_header(token, client_id)\n end",
"def create_token\n @user = User.find(params[:id])\n @token = Token.generate(@user)\n\n respond_to do |format|\n if @token.save\n format.html { redirect_to action: 'index'}\n format.json { render :show, status: :created, location: @token }\n else\n format.html { render :new }\n format.json { render json: @token.errors, status: :unprocessable_entity }\n end\n end\n end",
"def get_access_token name = nil\n oauth_instance(name).get_access_token(oauth_request_env)\n end",
"def access_token\n Rails.cache.fetch(\"googl_access_token\", expires_in: 50.minutes) do \n request = { query: { client_id: ENV['GOOGL_CLIENT_ID'],\n client_secret: ENV['GOOGL_CLIENT_SECRET'],\n refresh_token: ENV['GOOGL_REFRESH_TOKEN'],\n grant_type: \"refresh_token\"} }\n\n result = self.class.post(\"/oauth2/v3/token\", request)\n\n result.parsed_response[\"access_token\"]\n end\n end",
"def create\n user = User.find_for_authentication(email: user_params[:email])\n\n if user && user.valid_password?(user_params[:password])\n user.generate_authentication_token\n\n expose({\n user_id: user.id,\n token: user.authentication_token\n })\n else\n error! :unauthenticated\n end\n end",
"def create\n @user = User.create_or_find_by(user_params)\n my_token = issue_token(@user)\n\n render json: {user: @user, token: my_token}\n # render json: @user\n \n end",
"def acquire_token\n token_acquire_url = TOKEN_ACQUIRE_URL.dup\n token_acquire_url['{authentication_endpoint}'] = @settings.authentication_endpoint\n token_acquire_url['{tenant_id}'] = @tenant_id\n\n url = URI.parse(token_acquire_url)\n\n connection = Faraday.new(:url => url, :ssl => MsRest.ssl_options) do |builder|\n builder.adapter Faraday.default_adapter\n end\n\n request_body = REQUEST_BODY_PATTERN.dup\n request_body['{resource_uri}'] = ERB::Util.url_encode(@settings.token_audience)\n request_body['{client_id}'] = ERB::Util.url_encode(@client_id)\n request_body['{username}'] = ERB::Util.url_encode(@username)\n request_body['{password}'] = ERB::Util.url_encode(@password)\n\n response = connection.get do |request|\n request.headers['content-type'] = 'application/x-www-form-urlencoded'\n request.body = request_body\n end\n\n fail AzureOperationError,\n 'Couldn\\'t login to Azure, please verify your tenant id, client id and username/password' unless response.status == 200\n\n response_body = JSON.load(response.body)\n @token = response_body['access_token']\n @token_expires_on = Time.at(Integer(response_body['expires_on']))\n @token_type = response_body['token_type']\n end",
"def store_access_token(data)\n @access_token = data['access_token']\n @expires_at = Time.now + data['expires_in']\n end",
"def get_access_token(request_token = @request_token)\n # response = @consumer.token_request(@consumer.http_method,\n # (@consumer.access_token_url? ? @consumer.access_token_url : @consumer.access_token_path),\n # request_token,\n # {},\n # headers)\n\n # @access_token = ::OAuth::AccessToken.new(@consumer, response[:oauth_token], response[:oauth_token_secret])\n @access_token = request_token.get_access_token\n end",
"def call\n if user\n {access_token:JsonWebToken.encode(user_id: user.id),\n user_role: user.role}\n end \n end",
"def access_token\n @access_token\n end"
] |
[
"0.837982",
"0.7739091",
"0.7649804",
"0.74348253",
"0.7369935",
"0.7369935",
"0.7369023",
"0.735615",
"0.7272942",
"0.7210471",
"0.7195461",
"0.71338403",
"0.7125111",
"0.7064586",
"0.70482475",
"0.7031742",
"0.7016605",
"0.7011514",
"0.7003396",
"0.6998269",
"0.6992987",
"0.69862705",
"0.69862634",
"0.6973969",
"0.6959087",
"0.69582933",
"0.69549394",
"0.6944127",
"0.69385546",
"0.69324094",
"0.69226927",
"0.69182754",
"0.6878191",
"0.6874914",
"0.68736076",
"0.6872062",
"0.6871787",
"0.6871787",
"0.6871787",
"0.68690366",
"0.68687767",
"0.68649256",
"0.6844742",
"0.68376815",
"0.6837542",
"0.68347985",
"0.68250483",
"0.68250483",
"0.68241173",
"0.6805055",
"0.6801101",
"0.67930686",
"0.679091",
"0.67824954",
"0.6780338",
"0.6780338",
"0.6780338",
"0.6778946",
"0.6754264",
"0.6753575",
"0.6749181",
"0.6744218",
"0.67415315",
"0.67238",
"0.67218685",
"0.6719305",
"0.67153275",
"0.67153275",
"0.67099875",
"0.6701635",
"0.6697258",
"0.66972154",
"0.66895705",
"0.66895705",
"0.66895705",
"0.66895705",
"0.66593",
"0.6656314",
"0.66502976",
"0.66497344",
"0.66372615",
"0.6632098",
"0.6624161",
"0.6623822",
"0.662287",
"0.65970737",
"0.65920967",
"0.6589631",
"0.65852934",
"0.6583284",
"0.65816563",
"0.65730613",
"0.65708256",
"0.65521026",
"0.65504605",
"0.65492034",
"0.65451753",
"0.65410066",
"0.6540946",
"0.6538399",
"0.6537536"
] |
0.0
|
-1
|
Find the sum of all the primes below two million. ======Slower brute force method======= def is_prime?(number) is_prime = true 2.upto(Math.sqrt(number).floor) do |num| if number % num == 0 is_prime = false break end end is_prime end def find_primes(limit) primes_array = [] (2...limit).each do |x| primes_array << x if is_prime?(x) end primes_array end using the Sieve of Eratosthenes
|
def find_primes(limit)
num_array = (2...limit).to_a
num_array.each_with_index do |val, index|
if val
index += val
while index < limit-2
num_array[index] = nil
index += val
end
else
next
end
end
num_array.compact
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def brute_force_primes(limit)\n \n primes = []\n complexity = 0\n # we know that 0,1 can't be prime\n # start at 2 and create a Range upto the limit\n (2..limit).each{|number|\n complexity += 1\n is_prime = true\n \n # any number is divisible by 1\n # so start at 2\n (2..number).each{|n|\n complexity += 1\n # ensure the number being tested is not the number in the loop\n unless number == n\n # continue unless the local loop value of n is a factor of number\n unless number % n != 0\n is_prime = false\n break\n end\n end\n }\n \n primes << number if is_prime\n }\n puts \"O(n**2): #{(limit**2).to_s}\"\n puts \"Complexity: #{complexity.to_s}\"\n return primes\n \nend",
"def consecutive_prime_below_one_million\n @max_limit = 1000_000\n generate_prime_numbers()\n # number_of_primes = 0\n result = 0\n\n count_prime_sum = @prime_numbers_sum.length\n number_of_primes = 1\n # i_index = 0\n count_prime_sum.times do |i_index|\n for j in (count_prime_sum - 1).downto(i_index + number_of_primes ) do\n difference = @prime_numbers_sum[j] - @prime_numbers_sum[i_index]\n if (j - i_index > number_of_primes) && difference < @max_limit && ( @prime_numbers.include? difference) #\n number_of_primes, result = j - i_index, difference\n break\n end\n end ## end of j\n end ## end of i\n\n puts '=============================================================================================='\n puts 'Q2: Which prime, below one million, can be written as the sum of the most consecutive primes?'\n puts \"Sol: Result For Finding consecutive prime below #{@max_limit} : #{result}, and \\n Number of primes in those are #{number_of_primes}\"\n puts '=============================================================================================='\n\n end",
"def sieve(limit)\n bound = Math.sqrt(limit).ceil\n sieve = (0..limit+1).collect{ true }\n p = 2\n while !p.nil? && p <= bound\n q = p*p\n while q <= limit\n sieve[q] = false\n q = q + p\n end\n p =(p+1 .. limit).find{ |n| sieve[n] }\n end\n (2..limit).select{ |n| sieve[n]}\nend",
"def getPrimes()\n oldlimit = $primelimit + 1\n $primelimit *= 2\n\n for i in oldlimit...$primelimit\n isPrime = true\n $primes.each do |p|\n if i % p == 0\n isPrime = false\n break\n end\n end\n if isPrime\n $primes << i\n end\n end\n\nend",
"def get_primes(limit)\n primes = []\n (2...limit).each do |number|\n primes << number if is_prime?(number)\n end\n primes\nend",
"def prime_numbers(limit = 1_000_000)\n all_numbers = Hash[(2..limit).map { |v| [v, 0] }]\n\n border = Math.sqrt(limit).to_i\n\n next_prime = 1\n while next_prime < border\n next_prime = all_numbers.find { |_, v| v.zero? }[0]\n\n all_numbers[next_prime] = -1\n\n all_numbers.each do |key, value|\n all_numbers.delete key if value.zero? && (key % next_prime).zero?\n end\n end\n all_numbers.keys\nend",
"def sieveOfErathosthenes(limit)\n\ta = Array.new(limit, true) \n\tsqLimit = limit ** 0.5\n\t2.upto(sqLimit) do |x|\n\t\tif(a[x]) then\n\t\t\tj = x ** 2\n\t\t\twhile(j < limit)\n\t\t\t\ta[j] = false\n\t\t\t\tj += x\n\t\t\tend\n\t\tend\n\tend\n\ta[0], a[1] = false, false\n\ta\nend",
"def get_consecutive_prime_below_one_million(primes)\n sumation = 0;\n prime_number_list = []\n number_of_primes = 0 \n primes.each_with_index do | prime_number , i |\n # puts \"#{prime_number} - #{i}\"\n @sum = @sum + prime_number\n @primeSum[i+1] = @sum if @sum < @limit;\n end\n # puts \"#{@primeSum}\"\n\n count_of_primeSum = @primeSum.length\n number_of_primes = 1 \n count_of_primeSum.times do |i|\n for j in (count_of_primeSum - 1).downto(i + number_of_primes ) do\n difference = @primeSum[j] - @primeSum[i]\n\n if (j-i > number_of_primes) && (difference < limit) && ( primes.include? difference)\n # puts \"#{i}--#{j}\"\n \n prime_number_list = primes[i...j]\n number_of_primes = j-i\n sumation = difference \n end\n end\n end\n @result[:sumation] = sumation \n @result[:number_of_terms] = number_of_primes \n @result[:prime_number_list] = prime_number_list \n\n @result\n end",
"def getSumPrime()\n def isPrime(n)\n return false if n <= 1\n 2.upto(Math.sqrt(n).to_i) do |x|\n return false if n%x == 0\n end\n true\n end\n\n sum=0\n (2..2000000).each { |x| sum=sum+x if isPrime(x) }\n puts sum\nend",
"def simpleSieve(limit)\n\n i = 2\n\tmark = initArray(limit);\n\tuntil i*i >= limit do\n\n\t\tif mark[i] == false\n\t\t\t# If not marked yet, then its a prime\n\t\t\t$prime.push(i);\n\n\t\t\tj = i;\n\t\t\tuntil j >= limit do\n\n\t\t\t mark[j] = true\n\t\t\t j += i\n\n\t\t\tend\n\t\tend\n\t\ti=1+i\n\n\tend\n\nend",
"def test2(limit)\n\ttotal = 0\n\t2.upto(limit) do |x|\n\t\tif isPrime(x) then total += x end\n\tend\n\ttotal \nend",
"def find_primes(input)\n\t\n\tprimes = Array.new\n\t\n\tlimit = Math.sqrt(input)\n\t\n\tnumber_to_test = 2\n\t\n\tif number_to_test > limit\n\t\treturn Array[input]\n\tend\n\t\n\twhile input % number_to_test != 0 && number_to_test < limit\n\t\tnumber_to_test += 1\n\tend\n\t\n\tif input % number_to_test == 0\n\t\treturn find_primes(number_to_test) + find_primes(input/number_to_test)\n\tend\n\n\treturn Array[input]\n\t\t\nend",
"def find_primes(input)\n\t\n\tprimes = Array.new\n\t\n\tlimit = Math.sqrt(input)\n\t\n\tnumber_to_test = 2\n\t\n\tif number_to_test > limit\n\t\treturn Array[input]\n\tend\n\t\n\twhile input % number_to_test != 0 && number_to_test < limit\n\t\tnumber_to_test += 1\n\tend\n\t\n\tif input % number_to_test == 0\n\t\treturn find_primes(number_to_test) + find_primes(input/number_to_test)\n\tend\n\n\treturn Array[input]\n\t\t\nend",
"def summation_of_primes_2(max)\n sieve = Array.new(max, true)\n sieve[0] = sieve[1] = false # 0 and 1 aren't primes\n sum = 0\n\n p = 2\n while p < sieve.size\n # Mark all composites off\n k = 1\n while k * p < max\n sieve[k * p] = false\n k += 1\n end\n\n sum += p\n\n # Find next prime\n while !sieve[p] and p < sieve.size\n p += 1\n end\n end\n\n sum\nend",
"def sum_primes max_number\n sum = 2\n (3..max_number).each do |test_num|\n next if test_num.even?\n prime = true\n # sqrttest = test_num**0.5\n (2..Math.sqrt(test_num)).each do |factor|\n prime = false if (test_num % factor == 0)\n break unless prime\n end\n sum += test_num if prime\n #puts test_num if prime\n end\n return sum\nend",
"def eratosthenes_sieve(max_number)\n numbers = (0..max_number+1).to_a\n bound = Math.sqrt(max_number).to_i\n\n (2..bound+1).each do |current|\n if numbers[current]\n (current+current..max_number+1).step(current).each do |j| numbers[j] = nil end\n end\n end\n\n return numbers.compact![2..-1]\nend",
"def get_primes limit\n\tnums = (1...limit).select { |n| n.prime? }\n\n\tp nums\nend",
"def prime_numbers\n # start with the first prime number\n primes = [2]\n # find the rest of the prime numbers\n (2..1000).each do |i|\n add_next_prime_number(primes)\n end\n return primes\nend",
"def primes_upto( xmax )\n # primes have no factors except for 1 and self\n primes = [ 2 ]\n ( 3..xmax ).each do |i|\n puts i if 0 == ( i % 1000 )\n is_prime = true\n primes.each do |p|\n break if p > ( i / 2 )\n if 0 == ( i % p )\n is_prime = false\n break\n end\n end # p\n primes << i if is_prime\n end # i\n return primes\nend",
"def eratosthenes_sieve(nth_prime)\n top = nth_prime * 10\n # this is really kludgy, you might have to increase 10 if you want\n # nth primes above 10k. It seems to work fine for all numbers under\n # 10k. I need to read up on prime number theory to find out when this fails.\n sieve = []\n (2..top).each { |i| sieve[i] = i }\n for i in 2 .. Math.sqrt(top)\n next unless sieve[i]\n (i*i).step(top, i) do |j|\n sieve[j] = nil\n end\n end\n sieve.compact[nth_prime]\nend",
"def ten\n acc = 0\n (find_primes_below 2000000).each do |i|\n acc = acc + i\n end\n return acc \nend",
"def find_prime\n x = 2\n while @prime_numbers.count < @total\n @prime_numbers << x if prime?(x)\n x += 1\n end\n end",
"def sum_of_all_primes(limit)\n list_of_all_numbers = (2..limit).to_a #create a list of numbers from 2 to limit\n primes = get_primes(list_of_all_numbers)\n\n puts \"Primes #{primes}\"\n puts \"Sum of all primes #{primes.sum}\"\nend",
"def compute_primes\n nums = (@max_checked..@max_checked * 2).map { |x| x.odd? ? x : nil }.to_a\n 1.upto(@primes.index { |p| p * p > @max_checked * 2 }) do |i|\n start_idx = -@max_checked % @primes[i] # prime[i]'s 1st multiple's index\n\n (start_idx..nums.size).step(@primes[i]) { |x| nums[x] = nil }\n end\n @max_checked *= 2\n @primes += nums.compact\n end",
"def prime_sieve(limit)\n \n limitn = limit+1\n primes = []\n \n # Fill in prime truth table\n for i in 0..limitn do\n primes[i] = true\n end\n \n primes[0] = false\n primes[1] = false\n \n primes.each_with_index{|prime,i|\n unless i < 2\n range = Range.new(i*i,limitn)\n range.step(i) {|index| primes[index] = false}\n end\n }\n \n true_primes = []\n primes.each_with_index{|value,i|\n true_primes << i if value == true\n }\n \n return true_primes\n \nend",
"def sieve_of_eratosthenes(max)\n if max < 1 || !(max.is_a?(Integer))\n raise TypeError.new \"the number given must be an integer greater than zero\"\n end\n\n root = Integer.sqrt(max)\n primes = Array.new(max + 1) { |i| i.odd? || i == 2 } #every prime number other than 2 is an odd number.\n\n #to find all the prime numbers until max, it will be enough just to perform the sifting only by the prime numbers, which do not exceed the root of max.\n 3.step(root, 2).each do |i|\n next unless primes[i] # next if not initialized as prime\n #i*i, i*i+i, i*i+2i, i*i+3i\n (i * i).step(max, i) do |j|\n primes[j] = false\n end\n end\n\n #Select all prime numbers\n 2.upto(max).select { |i| primes[i] }\nend",
"def solution_3(num)\n starting_time = Time.now\n\n # actual sieve of eratosthenes\n potential_primes = (2..num).to_a\n potential_primes.each_with_index do |val, index|\n if val\n index += val\n while index < num\n potential_primes[index] = nil\n index += val\n end\n else\n next\n end\n end\n\n primes = potential_primes.compact\n\n p \"Sum of first #{num} primes: #{primes.reduce(:+)}\"\n\n p \"In #{Time.now - starting_time} seconds\"\nend",
"def summation_of_primes(limit)\n primes = [2]\n accum = 3\n\n while primes[primes.length - 1] < limit\n\n if primes.all?{|ele| accum % ele != 0}\n primes << accum\n end\n accum += 2\n\n end\n primes.pop\n # p primes\n sum = primes.reduce(:+)\n sum\nend",
"def GetPrimes (maximum)\t\n\t# Construct and execute the Sieve\n\tsqrtMaximum = Math.sqrt(maximum).to_i\n\tprimeTracker = Array.new(maximum,true)\n\t\n\tfor i in 2...sqrtMaximum\n\t\tnext if !primeTracker[i]\n\t\t\n\t\tstart = i + i\n\t\t\n\t\tfor j in (start...maximum).step(i)\n\t\t\tprimeTracker[j] = false;\n\t\tend\n\tend\n\t\n\tprimes = []\n\t\n\t# Generate the list of primes to return\n\tfor k in 2...maximum\n\t\tprimes.push(k) if primeTracker[k]\n\tend\n\t\n\treturn primes\nend",
"def add_primes_upto(max)\n primes = [2, 3]\n primes_index = 1\n sum = 2 + 3\n\n 5.step(max, 2).each do|current_number|\n val_is_prime = true\n primes.each do|prime|\n if prime > Math.sqrt(current_number).to_i\n break\n elsif current_number % prime == 0 then\n val_is_prime = false\n break\n end\n end\n if val_is_prime && current_number < max then\n primes_index = primes_index + 1\n primes[primes_index] = current_number\n sum = sum + current_number\n end\n end\n return sum\nend",
"def sum_primes(num)\n nums = Hash.new{true}\n\n (2...num**(0.5)).each do |x|\n if nums[x]\n i = x\n while x*i < num\n nums[x*i] = false\n i += 1\n end\n end\n end\n \n sum = 0\n (2...num).each { |x| sum += x if nums[x] }\n sum\nend",
"def prime_factor\n max = 600851475143**0.5\n\n for i in (1..max).step(2)\n if 600851475143 % i == 0\n if is_prime(i)\n ans = i\n end\n end\n end\n ans\nend",
"def get_primes\n j = 0\n\n while j < @limit \n prime_number = is_prime\n if prime_number\n @prime_numbers.push(prime_number)\n j += 1\n end\n @count += 1\n end\n\n return @prime_numbers\n end",
"def primes_upto(limit)\n numbers = (2..limit).to_a\n numbers.each do |prime|\n if prime\n nonprime = prime + prime\n while nonprime <= limit\n numbers[nonprime - 2] = nil\n nonprime += prime\n end\n end\n end\n numbers.compact\nend",
"def p10\n\tprimes = []\n\tPrime.each do |prime|\n\t\tbreak if prime >= 2000000\n\t\tprimes << prime\n\tend\n\t# puts primes\n\tprimes.reduce(:+)\nend",
"def prime_sum(limit)\n Prime.each(limit).inject :+\n end",
"def primes_sum\n primeArr = []\n num = 2\n while num < 2000000\n if is_prime num\n primeArr << num\n end\n num += 1\n end\n primeArr.reduce(:+)\nend",
"def run\n puts sum_of_primes_below(10)\n #=> 17\n\n puts sum_of_primes_below(2_000_000)\n #=> ??\nend",
"def find_more_primes\n candidates_max = @known_primes.last * 2\n candidates = ((@max_checked + 1)..candidates_max).step(2).to_a\n sieving_primes = primes_to_sieve(candidates_max)\n\n offsets = Array.new(sieving_primes.size) do |i|\n (-(candidates.first + sieving_primes[i]) / 2) % sieving_primes[i]\n end\n\n sieving_primes.zip(offsets).each do |prime, offset|\n while offset < candidates.size do\n candidates[offset] = nil\n offset += prime\n end\n end\n\n @known_primes += candidates.compact\n @max_checked = candidates_max\n end",
"def sum_of_primes(limit)\n answer = 0\n\n Prime.each(limit) do |i|\n answer += i\n end\n puts answer\nend",
"def primes(n) \n max = Math::sqrt(n).truncate\n (2..max).each {|val|\n if n % val == 0 then\n p val\n primes(n/val)\n return\n elsif val == max then\n p n\n return\n end\n }\nend",
"def primes\n\t\t# primes = []\n\t\t# primes << 2\n\t\tprimes = [2] # combined previous two lines\n\t\tx = 3\n\n\t\tloop do\n\t\t\tbreak if primes.length == @n_primes # End loop when desired number has been calculated\n\t\t# while primes.length < @n_primes # Alternative 1 to loop do, break\n\t\t# until primes.length == @n_primes # Alternative 2 to loop do, break\n\t\t\ty = 3\n\t\t\ty += 2 until x % y == 0 # Loop to test if x is divisible by any odd number below it, y\n\t\t\tprimes << x if x == y # If the (odd) number was not divisible by any (odd) below itself, it is a prime\n\t\t\tx += 2\n\t\tend\n\n\t\treturn primes\n\tend",
"def calculate(number)\n sieve_limit = upper_limit_for(number)\n primes = sieve_upto sieve_limit\n primes[0..number-1]\n end",
"def prime2(nprime)\n\n primes = [2]\n factors = {}\n\n num = 3\n while primes.size < nprime do\n\n root = Math.sqrt(num).floor\n isprime = true\n\n primes.each{ |prime|\n break if prime > root\n if num % prime == 0\n isprime = false\n break\n end\n }\n\n primes << num if isprime\n num += 1\n\n printf(\"\\r%d\", primes.size) if primes.size % 1000.0 == 0\n\n end\n\n return primes\n\nend",
"def generate_primes(upper_limit)\n primes = Array.new\n \n # Tally is a list of factors or prime numbers found.\n # We must use a running ceiling value called max_factor to calculate factors\n # to. max_tally_for_prime stores the maximum factor tallied for each prime\n # that was found.\n tally = Set.new \n max_tally_for_prime = Hash.new\n max_factor = 100\n \n i = 2\n while primes.length < upper_limit do\n if tally.include?(i) == false\n primes.push i\n \n # Fill tally with multiples of the prime found\n j = i\n while j <= max_factor do\n tally.add j\n max_tally_for_prime[i] = j\n j += i\n end \n end\n i += 1\n \n # When we reach half way to the max factor the ceiling is doubled and the\n # tally is extended\n if i > max_factor/2\n max_factor = max_factor*2\n primes.each do |prime|\n j = max_tally_for_prime[prime]\n while j <= max_factor\n j += prime\n tally.add j\n end\n max_tally_for_prime[prime] = j\n end\n end\n end\n return primes\nend",
"def primes\n arr=Array.new\n arr[1]=false\n (2..1000).each {|i| arr[i]=true}\n (2..1000).each {|i| (i/2).floor\n (2..1000).each {|j| (j/i).floor\n arr[i*j] = false\n }}\n for i in 1..1000\n if arr[i] == true\n puts i\n end\n end\nend",
"def find_primes(n)\n # use the Sieve of Eratosthenes method\n # http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\n\n # 1. \"create a list of consecutive integers from 2 to n\"\n # an empty hash will do\n sieve = {}\n\n # 2. \"initially, let p equal 2, the first prime number\"\n p = 2\n\n while true\n # 3. \"starting from p, count up in increments of p and mark each of these numbers \n # greater than p itself in the list.\"\n # optimization: can start from p*p\n i = p * p\n while i <= n\n sieve[i] = true\n i += p\n end\n\n # 4. \"find the number greater than p in the list that is not marked. if there was no such\n # number, stop. otherwise, let p now equal this number (which is the next prime) and repeat\n # from step 3.\"\n old_p = p\n new_p = nil\n for i in (old_p + 1)..n\n if not sieve[i]\n new_p = i\n break\n end\n end\n if not new_p\n break\n end\n p = new_p\n end\n\n # everything not marked is prime.\n primes = []\n for i in 2..n\n if not sieve[i]\n primes.push(i)\n end\n end\n\n primes\nend",
"def count_primes_fast(n)\n is_prime = [false, false]\n (2...n).each do |x|\n is_prime[x] = true;\n end\n\n tail = Math.sqrt(n).ceil\n for i in 2..tail\n next if !is_prime[i]\n (i*i...n).step(i) do |j|\n is_prime[j] = false\n end\n end\n\n count = 0\n for k in 0...n\n count += 1 if is_prime[k]\n end\n count\nend",
"def count_primes(number)\n # create an array from 2-num\n # for each number in the array of possible primes\n # modulo the number by each n\n # if the number % n is 0, it's not a prime number\n # unless the number and n are the same\n possible_primes = (2...number).to_a\n possible_primes.select! do |num|\n # need to return true if num is prime, false if it is not\n # binding.pry if num == 3\n half_num = num\n results = (2...half_num).select do |n|\n # if num % n == 0, means that n evenly divides into num making it not prime\n num % n == 0\n end\n results.empty?\n # any number within results evenly divided into the num\n # making the num not prime\n # so if results is empty, it means that nothing divided into the num\n # making the num prime\n end\n possible_primes.count\nend",
"def primes()\n return [] if @number < 2\n # build Boolean array to use for sieve with buffer to align indices\n sieve_array = Array.new(2, false) + Array.new(@number-1, true)\n # perform Sieve of Eratosthenes eliminations\n (2..Math.sqrt(@number).to_i).each do |i|\n (i**2..@number).step(i) {|j| sieve_array[j] = false} if sieve_array[i] == true\n end\n # return numbers by corresponding index that are still true\n (2..@number).collect {|index| index if sieve_array[index] == true}.compact\n end",
"def GetPrimes (maximum)\n\t# Clear the input vector in case there is existing data\n\tprimes = []\n\t\n\t# There are no primes less than 2\n\tif (maximum < 2)\n\t\treturn\n\tend\n\t\n\t# Construct and execute the Sieve\n\tsqrtMaximum = Math.sqrt(maximum).to_i\n\tprimeTracker = Array.new(maximum,true)\n\t\n\tfor i in 2...sqrtMaximum\n\t\tif (!primeTracker[i])\n\t\t\tnext\n\t\tend\n\t\t\n\t\tfor j in ((i+i)...maximum).step(i)\n\t\t\tif (j < 0) # Guard against integer overflow\n\t\t\t\tbreak\n\t\t\tend\n\t\t\t\n\t\t\tprimeTracker[j] = false\n\t\tend\n\tend\n\t\n\t# Generate the list of primes to return\n\tfor k in 2...maximum\n\t\tif (primeTracker[k] == true)\n\t\t\tprimes.push(k)\n\t\tend\n\tend\n\t\n\treturn primes\nend",
"def GetPrimes (maximum)\n\t# Clear the input vector in case there is existing data\n\tprimes = []\n\t\n\t# There are no primes less than 2\n\tif (maximum < 2)\n\t\treturn\n\tend\n\t\n\t# Construct and execute the Sieve\n\tsqrtMaximum = Math.sqrt(maximum).to_i\n\tprimeTracker = Array.new(maximum,true)\n\t\n\tfor i in 2...sqrtMaximum\n\t\tif (!primeTracker[i])\n\t\t\tnext\n\t\tend\n\t\t\n\t\tfor j in ((i+i)...maximum).step(i)\n\t\t\tif (j < 0) # Guard against integer overflow\n\t\t\t\tbreak\n\t\t\tend\n\t\t\t\n\t\t\tprimeTracker[j] = false\n\t\tend\n\tend\n\t\n\t# Generate the list of primes to return\n\tfor k in 2...maximum\n\t\tif (primeTracker[k] == true)\n\t\t\tprimes.push(k)\n\t\tend\n\tend\n\t\n\treturn primes\nend",
"def GetPrimes (maximum)\n\t# Clear the input vector in case there is existing data\n\tprimes = []\n\t\n\t# There are no primes less than 2\n\tif (maximum < 2)\n\t\treturn\n\tend\n\t\n\t# Construct and execute the Sieve\n\tsqrtMaximum = Math.sqrt(maximum).to_i\n\tprimeTracker = Array.new(maximum,true)\n\t\n\tfor i in 2...sqrtMaximum\n\t\tif (!primeTracker[i])\n\t\t\tnext\n\t\tend\n\t\t\n\t\tfor j in ((i+i)...maximum).step(i)\n\t\t\tif (j < 0) # Guard against integer overflow\n\t\t\t\tbreak\n\t\t\tend\n\t\t\t\n\t\t\tprimeTracker[j] = false\n\t\tend\n\tend\n\t\n\t# Generate the list of primes to return\n\tfor k in 2...maximum\n\t\tif (primeTracker[k] == true)\n\t\t\tprimes.push(k)\n\t\tend\n\tend\n\t\n\treturn primes\nend",
"def find_primes_under(num)\n\tprimes = [2]\n\tcounter = 3\n\twhile primes[-1] < num\n\t\tcounter2 = 2\n\t\twhile counter2 <= counter\n\t\t\tif counter % counter2 == 0\n\t\t\t\tbreak\n\t\t\telsif\n\t\t\t\tcounter2 * counter2 > counter\n\t\t\t\tprimes << counter\n\t\t\t\tbreak\n\t\t\tend\n\t\t\tcounter2 += 1\n\t\tend\n\tcounter += 1\n\tend\n\tprimes[0..-2]\nend",
"def getMaxPrime(numb)\n def isPrime(n)\n return false if n <= 1\n 2.upto(Math.sqrt(n).to_i) do |x|\n return false if n%x == 0\n end\n true\n end\n\n primes = []\n (2..10000).each { |x| primes << x if isPrime(x) }\n \n max = 0\n primes.each do |i|\n if numb % i == 0\n max = i\n end\n end\n puts max\nend",
"def prime(max)\n (1..max).select { |x| (1..max).count { |y| x % y == 0 } == 2 }\nend",
"def problem10()\n\tsum = 0; Prime.each(2000000) {|i| sum += i}; return sum\nend",
"def sum_of_primes_below(n)\n sum = 0\n require 'prime'\n Prime.each(n) do |prime|\n sum += prime\n end\n\n sum\nend",
"def problem_77a\n primes = Primes.upto(100)\n\n # off is the offset in the prime array, we can work down :-)\n solve = lambda do |a,off,max|\n n = 0\n while a[off] < max && (a.length-off) >= 2 \n a[off] += a.pop\n n += 1 if (a & primes).length == a.uniq.length\n n += solve.call(a.dup,off+1,a[off]) if a.length - off > 1\n end\n n\n end\n m = 0\n (2..100).each do |num|\n break if (m = solve.call([1] * num,0,num-1)) > 5000\n puts \"#{num} => #{m}\"\n end\n m\nend",
"def is_prime(n)\n # Returns True if n is prime. \n # This is modified and refactored for Ruby and for numbers less than 2.\n # So far, this is the fastest method I've found.\n # The idea is that all primes except 2 and 3 are of the form 6k - 1 and 6k + 1.\n # Also, this is 4 times faster than #prime_v2?, which is itself 247 times faster than #prime?\n if n < 2 \n return false\n elsif n == 2 or n == 3\n return true\n elsif n % 2 == 0 or n % 3 == 0\n return false\n else\n square_root = (n ** 0.5).to_i\n i = 5\n w = 2\n\n while i <= square_root\n if n % i == 0\n return false\n end\n\n i += w\n w = 6 - w\n end\n end\n\n return true\nend",
"def sumPrimes\n i = 1999999\n sum = 2\n \n # note that this code will never count 2 as prime simply because it never tests 2. \n # For eficiency, it skips all evens, inadvertently skips 2. \n # make a better fix later. for now, initialize sum to 2. \n # was written in reverse order to check if 2 was counted as prime\n while i > 0\n if isPrime(i)\n puts i \n sum += i\n end\n i -= 2\n end\n \n return sum\n \nend",
"def consecutive_prime_sum\n sum = 0\n cumulative_sum = Prime.take_while { |n| n < 50000 } .map { |n| sum += n }\n \n max = 953\n max_terms = i = 21\n while i < cumulative_sum.length\n j = i - max_terms - 1\n diff = 0\n while j >= 0 && diff < 1_000_000\n diff = cumulative_sum[i] - cumulative_sum[j]\n if Prime.prime?(diff)\n max = diff\n max_terms = i - j\n end\n j-=1\n end\n i+=1\n end\n max\nend",
"def find_primes\n canidates = (0..@max_num).to_a\n k=2\n while(k<= canidates.size/2)\n j=2\n while(j<= canidates.size/2)\n prod = k*j\n if prod <= @max_num\n canidates[prod] = nil\n end\n j+=1\n end\n k+=1\n end\n res = canidates.compact\n res.shift(2)\n res\n end",
"def p7\n\tprimes = [2]\n\t(1...10001).each do\n\t\tprime = next_prime(primes[-1])\n\t\tprimes << prime\n\tend\n\tprimes[-1]\nend",
"def prime(n)\n\tif $primes[n] then\n\t\t$primes[n]\n\telse\n while n - $primes.length > 100\n prime (n + $primes.length) / 2\n end\n\t\tc = prime(n-1) + 2\n\t\ti = 1\n\t\twhile $primes[i]**2 <= c\n\t\t\tif c % $primes[i] == 0\n\t\t\t\tc += 2\n\t\t\t\ti = 1\n\t\t\telse\n\t\t\t\ti += 1\n\t\t\tend\n\t\tend\n\t\t$primes[n] = c\n\tend\nend",
"def primes_up_to(max)\n repository = (0..max).collect{true} #=> Create flag array\n limit = (max ** 0.5) #=> establish search limit\n\n for index in 2..limit #=> search through flag aray\n next if !repository[index]\n num = (index * 2)\n while num <= max #=> unflag multiples of primes\n repository[num] = false\n num += index\n end\n end\n\n # => convert numbers into arrays\n primes = repository.collect.with_index do |flag, value|\n value if flag\n end\n\n # return cleaned array\n primes.shift\n primes.shift\n primes.compact\nend",
"def primes_from_2( x )\n # primes have no factors except for 1 and self\n primes = [ 2 ]\n i = 2\n while primes.size < x\n i += 1\n is_prime = true\n primes.each do |p|\n #( 2..( i ** 0.5 ).floor ).each do |p|\n #break if p > ( i / 2 )\n break if p > ( i ** 0.5 )\n if 0 == ( i % p )\n is_prime = false\n break\n end\n end # p\n primes << i if is_prime\n i += 1 # skip the next integer (it's even)\n end # while\n return primes[ -1 ]\nend",
"def sieve_eratosthenes(biggest_num)\n primes = (0..biggest_num).to_a\n primes[0] = primes[1] = nil\n\n counter = 0\n primes.each do |p|\n next unless p\n\n break if p*p > biggest_num\n counter += 1\n\n (p*p).step(biggest_num,p) { |m| primes[m] = nil }\n end\n primes.compact\nend",
"def nth_prime(n)\n nums = (0..10000).to_a\n result = []\n\n nums.each do |i| \n if prime?(i) == true\n result.push(i)\n end\n end\n\n\n return result[n]\nend",
"def solution_1\n starting_time = Time.now\n\n total = 0\n\n all_primes(MAX_NUM).each { |prime| total += prime }\n\n p \"Sum of first #{MAX_NUM} primes: #{total}\"\n p \"In #{Time.now - starting_time} seconds\"\nend",
"def bc_get_prime_numbers(size)\n n = 1\n primes = []\n notprime = Hash.new\n\n until primes.size > size do\n\n n+=1\n\n # if I am known not prime, continue\n if notprime[n] then next end\n\n # check to see if I'm prime (abort instantly on finding divisor)\n (2..Math.sqrt(n)+1).each{|i| print \"Checking #{n} vs #{i}\\n\"; if n%i==0 then notprime[n]=1; print \"NOT A PRIME!\\n\"; next; end}\n\n # I'm prime, so add me to array + mark my multiples as being not\n # prime, but the fewer primes I need to get, the fewer multiples I\n # mark\n\n primes.push(n)\n (2..(size-primes.size())).each{|i| notprime[i*n] = 1}\n end\n primes\nend",
"def euler010\n target = 2e6\n sum = 0\n\n each_prime do |p,i|\n break if p >= target\n sum += p\n end\n\n sum\nend",
"def get_n_primes(n)\n return [] if n < 1\n primes = [2]\n candidate = 3\n\n while primes.length < n\n is_prime = true # default assume the number is prime\n primes.each do |prime|\n if candidate % prime == 0\n is_prime = false\n break\n end\n\n break if prime >= Math.sqrt(candidate)\n end\n\n primes << candidate if is_prime\n candidate += 2\n end\n\n primes\nend",
"def isPrimePrime n\n\n if n == 2\n return true\n elsif n < 2\n return false\n end\n\n j = 1\n i = @@listOfPrimes[j]\n\n while i <= (Math.sqrt n).floor\n\n if n % i == 0\n return false\n end\n\n if @@listOfPrimes[j+1] == nil\n @@listOfPrimes[j+1] = getNextPrime(@@listOfPrimes[j])\n end\n\n j+=1\n i = @@listOfPrimes[j]\n\n end\n\n return true\nend",
"def largest_prime_sum(limit)\n prime = get_primes(limit)\n sum_prime = sum_primes(prime)\n max_length = -1\n largest_prime_number = -1\n \n (0...prime.length).each do |i|\n (0...i).each do |j|\n break if (sum_prime[i] - sum_prime[j] > limit) \n consective_sum = sum_prime[i] - sum_prime[j]\n if ((max_length < i-j+1) and is_prime?(consective_sum))\n max_length = i-j+1\n largest_prime_number = consective_sum\n end\n \n end\n end\n largest_prime_number\nend",
"def next_prime(primes)\n\tlast_prime = primes.last\n\ttest = last_prime\n\tfound = false\n\twhile !found\n\t\ttest = test + 2\n\t\tmax = Math.sqrt(test).div(1)\n\n\t\tfor fact in primes do\n\t\t\tif test % fact == 0\n\t\t\t\tbreak\n\t\t\tend\n\t\t\tif fact > max\n\t\t\t\tfound = true\n\t\t\tend\n\t\tend\n\tend\n\tprimes.push(test)\nend",
"def nextPrime(last_prime)\n i = 2\n last_prime = last_prime + 1\n too_far = last_prime * last_prime\n #we'll continue our search for too_far times //rewrite this later\n #too_far.times do |z|\n loop do #iterate until you find a prime\n loop do #check last_prime for primehood\n if last_prime == i\n return last_prime\n end\n break if last_prime % i == 0\n i = i + 1\n end\n i = 2\n last_prime = last_prime + 1\n end\nend",
"def primes_up_to(limit)\n root_limit = Math.sqrt(limit)\n values = (2..limit).to_a\n j = 0\n candidate = values[j]\n while candidate < root_limit\n values.delete_if { |i| (i % candidate == 0 and i != candidate) }\n j+=1\n puts \"#{j}: #{values.length} values remain\"\n candidate = values[j]\n end\n values\nend",
"def nth_prime(n)\n primes = []\n x = 2\n while primes.size < n\n primes << x if (2..Math.sqrt(x)).all? {|i| x % i != 0 }\n x += 1\n end\n primes\nend",
"def specific_prime(n)\n\na = (2..n) # list of integers 2 through \nprimes = Array.new\n\nprimes = a.select { |x| (2..Math.sqrt(x)).none? { |d| (x % d).zero? }}\n\nputs primes[10000]\n# answer => 104,743\n\nend",
"def get_primes(upper_bound)\n primes = []\n (2..upper_bound).each do |potential_prime|\n is_prime = true #default to true if the below loop doesn't prove it false\n (2..(potential_prime - 1)).each do |divisor| #we start from 2 because that is the first number\n #that we know is not prime - 1 is there so we don't divide the number by itself because\n #we know that it is possible\n if potential_prime % divisor == 0\n is_prime = false\n break\n end\n end\n\n #HERE - we know if is_prime is true, it must be prime\n if is_prime\n primes << potential_prime #this is how you get all the numbers to the max number\n end\nend\n\n return primes\nend",
"def eratosthenes(limit)\n nlist = [nil, nil, *2..limit]\n (2..Math.sqrt(limit)).each do |x|\n (x ** 2..limit).step(x) { |y| nlist[y] = nil } if nlist[x]\n end\n nlist.compact!\nend",
"def sieve(nth_prime)\n primes = [2]\n num = 2\n while primes.length <= nth_prime do\n primes << num if !primes.any? {|prime| num % prime == 0}\n num +=1\n end\n return primes[primes.length-2] # -2 because we don't put 1 (because every number is divisble by 1) and index is from 0 to x thus -2\nend",
"def main\n # GC::Profiler.enable\n # limit = 10 ** 6\n limit = 5 * (10 ** 7)\n prime_limit = (limit * Math.sqrt(2)).to_i\n prime_cache = Prime::Cache.new(prime_limit)\n primes = prime_cache.primes.select {|prime| prime % 8 == 1 || prime % 8 == 7}\n prime_cache = nil\n prime_length = primes.length\n puts \"Primes cached. Length: #{prime_length}\"\n\n # GC.disable\n sqrts = []\n tick = Time.new\n primes.each_with_index do |prime, prime_index|\n if prime_index % (10 ** 4) == 0\n tock = Time.new\n puts \"#{prime_index}/#{prime_length}\\t#{tock - tick}\"\n tick = tock\n end\n sqrts << modular_sqrt((prime + 1)/2, prime)\n end\n puts \"Square roots cached\"\n # GC.enable\n\n is_prime_per_n = [true] * (limit + 1)\n [0, 1].each do |exception_index|\n is_prime_per_n[exception_index] = false\n end\n\n primes.each_with_index do |prime, prime_index|\n puts \"#{prime_index}/#{prime_length}\" if prime_index % (10 ** 5) == 0\n sqrt1 = sqrts[prime_index]\n\n [sqrt1, prime - sqrt1].each do |sqrt|\n raise \"#{prime}'s sqrt is 0\" if sqrt == 0\n if sqrt == 1\n sqrt += prime\n end\n \n if sqrt <= limit && (2 * sqrt * sqrt - 1 != prime)\n is_prime_per_n[sqrt] = false\n end\n sqrt += prime\n\n while sqrt <= limit\n is_prime_per_n[sqrt] = false\n sqrt += prime\n end\n end\n end\n\n count = 0\n is_prime_per_n.each_with_index do |is_prime, n|\n if is_prime\n count += 1\n end\n end\n\n p count\n # puts GC::Profiler.result\nend",
"def primes (n)\r\n primes = Array.new(n) { |index| index+=1 }\r\n return primes.select { |x| factors(x).length == 2 }\r\nend",
"def all_primes(number)\n primes = []\n (2...number).each do |num|\n if prime?(num)\n primes << num \n end\n end\n primes\nend",
"def GetPrimes (maximum)\n\t# Clear the input vector in case there is existing data\n\tprimes = []\n\t\n\t# There are no primes less than 2\n\tif (maximum < 2)\n\t\treturn\n\tend\n\t\n\t# Construct and execute the Sieve\n\tsqrtMaximum = Math.sqrt(maximum).to_i\n\tprimeTracker = Array.new(maximum,true)\n\t\n\tfor i in 2...sqrtMaximum\n\t\tif (!primeTracker[i])\n\t\t\tnext\n\t\tend\n\t\t\n\t\tfor j in ((i+i)...maximum).step(i)\n\t\t\tif (j < 0) # Guard against integer overflow\n\t\t\t\tbreak\n\t\t\tend\n\t\t\t\n\t\t\tprimeTracker[j] = false\n\t\tend\n\tend\n\t\n\treturn primeTracker\nend",
"def find_primes(int1, int2)\n nums = (int1..int2).to_a\n nums.select { |num| is_prime?(num) }\nend",
"def get_primes(n)\n primes = [2]\n pp = 0\n i = 3\n while pp < n do\n if i%2 != 0\n counter = 0\n prime = 1\n while counter < primes.length do\n if (i%primes[counter] == 0)\n prime = 0\n break;\n end\n counter += 1\n end\n if prime == 1\n primes.push(i)\n pp +=1\n end\n end\n i+=1\n end\n return primes[n-1]\nend",
"def sum_primes_below(target)\n prime_sum = 0\n (2..target).each do |i|\n if is_prime?(i)\n prime_sum += i\n end\n end\n\n prime_sum\nend",
"def primesInRange(low, high)\n\n\t# Compute all primes smaller or equal to\n\t# square root of high using simple sieve\n\n\tlimit = (Math.sqrt(high)) + 1;\n\tsimpleSieve(limit);\n\n\t# Count of elements in given range\n\tn = high - low + 1;\n\n\t# Declaring boolean only for [low, high]\n \tmark = initArray((n+1));\n\n\t# Use the found primes by\n\t# simpleSieve() to find\n\t# primes in given range\n\t$prime.each_with_index do |val, i|\n\t\t# Find the minimum number in [low..high] that is\n\t\t# a multiple of prime[i] (divisible by prime[i])\n\t\tloLim = low / val * val\n\t\tif loLim < low\n\t\t\tloLim += val;\n\t\tend\n\t\tif loLim==val\n\t\t\tloLim += val;\n\t\tend\n\n\t# Mark multiples of prime[i] in [low..high]:\n\t#\tWe are marking j - low for j, i.e. each number\n\t#\tin range [low, high] is\tmapped to [0, high - low]\n\t#\tso if range is [50, 100] marking 50 corresponds\n\t#\tto marking 0, marking 51 corresponds to 1 and\n\t#\tso on.\n # Also if the current j is prime don't mark\n\t#\tit as true.In this way we need to allocate space only\n\t#\tfor range\n\tj = loLim;\n\t\tuntil j > high do\n\t\t if j != val\n\t\t mark[j - low] = true;\n\t\t end\n\t\t j += val\n\t\tend\n\tend\n\n\t# Numbers which are not marked\n\t# in range, are prime\n\to = []\n\tfor i in low..high do\n if mark[i - low]==false\n o.push(i);\n end\n end\n puts(\"[OUTPUT] %s\" % o.join(\",\"));\nend",
"def sup_limit(max)\n (1..Float::INFINITY).lazy.map{|i| [i,Prime.take(i).reduce(:+)]}.detect{|i,sum| sum >= max}.first\nend",
"def sieve_eratosthenes(len)\r\n\tprimes = [2]\r\n\tn = 2\r\n\r\n\t# Keep finding primes until requested length is reached\r\n\tuntil primes.length == len\r\n\t\t# Increase next number to test by one\r\n\t\tn += 1 \r\n\r\n\t\t# Test n against all numbers in prime array\r\n\t\t# If n is divisible by a prime, break and get next number to test\r\n\t\tis_prime = true\r\n\t\tprimes.each do |p|\r\n\t\t\tif n%p == 0\r\n\t\t\t\tis_prime = false \r\n\t\t\t\tbreak\r\n\t\t\tend\r\n\t\tend\r\n\t\t# If n is not divisible by previous primes, push to primes array\r\n\t\tprimes << n if is_prime\r\n\tend\r\n\tputs primes.last\r\nend",
"def check_prime? n \nn_max_two=Math.sqrt(n).floor \nnot_count=0 \nfor i in 2..n_max_two\n if n % i == 0 \nnot_count +=1 \n end \nend \nif not_count > 0 \n return false \n else \n return true \nend \nend",
"def prime_series\n t = self\n limit = Math.sqrt(t)\n a = (2..t).to_a\n n = 2\n while (n < limit) do\n x = n*2\n begin\n a[x-2]=2\n x+=n\n end until (x > t )\n begin\n n+=1\n end until ( a[n-2] != 2 )\n end\n a.uniq!\n end",
"def primes(n)\n return (2..n).select {|x| factors(x).size() == 2}\nend",
"def sieve(n)\n\tprimes = []\n\ta = Array.new(n, true)\n\t2.step(Math.sqrt(n).to_i) do |i|\n\t\tif a[i]\n\t\t\tprimes.push(i)\n\t\t\t\n\t\t\ti.step(n-1, i) do |k|\n\t\t\t\ta[k] = false\n\t\t\tend\n\t\tend\n\tend\n\n\tMath.sqrt(n).to_i.step(n-1) do |i|\n\t\tif a[i]\n\t\t\tprimes.push(i)\n\t\tend\n\tend\n\n\treturn primes\nend",
"def prime_list(number_of_primes)\n return [] if number_of_primes < 1\n prime_numbers = Array.new\n for num in 2..9999999 do\n if is_prime_num(num, prime_numbers)\n prime_numbers.push(num)\n break if prime_numbers.length == number_of_primes\n end\n end\n return prime_numbers\n end",
"def collect_primes(number)\n \n sieve = [nil, nil] + (2 .. number).to_a\n \n (2 .. Math.sqrt(number)).each do |n|\n next unless sieve[n]\n (n*n).step(number, n) do |num|\n sieve[num] = nil\n end\n end\n \n primes = []\n sieve.each do |x|\n if x != nil\n primes << x\n end\n end\n return primes\nend",
"def primes_under(n)\n candidates = (3..n).step(2).to_a\n primes = [2]\n\n until primes.last > n ** 0.5\n primes << candidates.shift\n candidates.reject! {|candidate| candidate % primes[-1] == 0}\n end\n\n primes + candidates\nend"
] |
[
"0.813076",
"0.80596143",
"0.7968878",
"0.7820366",
"0.77713615",
"0.77585334",
"0.76862514",
"0.7626614",
"0.7622976",
"0.7612283",
"0.755954",
"0.7521138",
"0.7521138",
"0.750969",
"0.74998975",
"0.7493728",
"0.74544764",
"0.7450481",
"0.7421679",
"0.73789036",
"0.7355006",
"0.7353273",
"0.7344367",
"0.7342821",
"0.7308888",
"0.730512",
"0.7293366",
"0.72877216",
"0.7287213",
"0.72799325",
"0.7268998",
"0.7266912",
"0.7226342",
"0.72222793",
"0.7219519",
"0.7204543",
"0.71911323",
"0.7186202",
"0.71856415",
"0.7172847",
"0.7144508",
"0.71339864",
"0.7121496",
"0.7115409",
"0.71010137",
"0.70960313",
"0.7090798",
"0.7084212",
"0.7081783",
"0.706664",
"0.70626515",
"0.70626515",
"0.70626515",
"0.7054141",
"0.7042561",
"0.7038515",
"0.70381117",
"0.7035084",
"0.70317733",
"0.7027123",
"0.7013794",
"0.70115095",
"0.70077586",
"0.69982976",
"0.69978255",
"0.6997503",
"0.6986065",
"0.6984419",
"0.6981106",
"0.6976563",
"0.69737995",
"0.6973404",
"0.69677305",
"0.69597036",
"0.6956511",
"0.69515634",
"0.6947725",
"0.69264984",
"0.6922353",
"0.69195956",
"0.69190526",
"0.6918811",
"0.6918473",
"0.6916912",
"0.6905073",
"0.69043684",
"0.6903703",
"0.6898119",
"0.686453",
"0.6861614",
"0.6861226",
"0.6859763",
"0.68440205",
"0.68413836",
"0.6838949",
"0.6835076",
"0.6818176",
"0.6814658",
"0.681285",
"0.6801947"
] |
0.74824417
|
16
|
Create a recurrence from the given frequency
|
def every(frequency, options = {})
branch options.merge(every: frequency)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def recurrence\n { ATTR_RECURRENCE[@attribute] => 1 }\n end",
"def recurrence\n unless read_attribute(:recurrence).empty?\n IceCube::Rule.from_hash(read_attribute(:recurrence))\n end\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def calculate(frequency, frequency_integer, start_date, end_date)\n first_due_date = @calendar.roll_forward(start_date)\n base_dates = [first_due_date]\n return [base_dates, base_dates] if frequency == 'Once'\n\n frequency_symbol = get_frequency_symbol(frequency)\n grace_dates = [first_due_date.advance(frequency_symbol => frequency_integer)]\n\n base_date = start_date\n end_date = calculate_end_date(start_date, end_date)\n\n while base_date < end_date\n grace_date = base_date.advance(frequency_symbol => frequency_integer*2)\n base_date = base_date.advance(frequency_symbol => frequency_integer)\n base_dates << @calendar.roll_forward(base_date)\n grace_dates << @calendar.roll_forward(grace_date)\n end\n\n [base_dates, grace_dates]\n end",
"def frequency_of( frequency )\n case frequency.to_s\n when 'always'\n (1.0/0.0)\n when 'once'\n 1\n when 'never'\n 0\n else\n Float(frequency).to_i\n end\n end",
"def frequency_distribution (sequence, length_pattern)\n assert(length_pattern > 0, \"The pattern length must be grater than 0\")\n frequency = Hash.new\n index = 0\n while index < sequence.length do\n codon = sequence[index .. index + length_pattern - 1]\n frequency[codon] == nil ? frequency[codon] = 1 : frequency[codon] += 1\n index += length_pattern\n end\n frequency\nend",
"def recurrence\n nil\n end",
"def frequency\n growth_rate = 2 ** (1.0 / 12)\n frequency = 440 * (growth_rate ** semitones_from_A4)\n frequency.round(3)\n end",
"def process\n @recurrences.each { |r| process_recurrence(r) }\n end",
"def create_freq_regexs\n @frequency_regex = /#{word_frequency[0..10].join(\"|\")}/\n end",
"def repeat_freq(nums, initial_val)\n sum = initial_val\n past_freqs = Set[initial_val]\n index = 0\n # This is an infinite loop so assumes that the problem has a solution\n while true\n sum += nums[index]\n return sum if past_freqs.add?(sum).nil?\n index += 1\n # Reset the index if it needs to loop\n index = 0 if index == nums.length\n end\nend",
"def create(opts)\n @frequence = opts[:frequence] if opts[:frequence].in? Recurrence::FREQUENCES\n @monthly = array_to_integer(opts[:monthly])\n @count = to_integer(opts[:count])\n @until = string_to_date(opts[:until])\n self\n end",
"def calculate_sequence\n old_sequence.split('')[1..-1].each(&method(:fill_recurrence))\n\n apply_recurrence\n\n recurrences.flatten.join\n end",
"def frequency_length\n if @freq == :daily\n @interval * 1\n elsif @freq == :weekly\n @interval * 7\n elsif @frequency == :monthly\n @interval * 29 # technically this is short, but I think it is fine for now\n end\n end",
"def set_recurring_frequency\n @recurring_frequency = RecurringFrequency.find(params[:id])\n end",
"def initialize(frequency)\n @frequency = frequency\n end",
"def get_freq\n #instantiate with values to ensure consistent ordering\n freq = { 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0 }\n #sum up freqencies of each number\n last_100 = get_last_100\n last_100.each do |item|\n freq[item.to_i] += 1\n end\n # convert to percentage\n freq.each do |key, val|\n #divide by real length to handle case of less than 100 outputs\n freq[key] = val / last_100.length.to_f\n end\n freq\n end",
"def recurrence\n return @recurrence\n end",
"def recurrence\n return @recurrence\n end",
"def repeat(input)\n self.frequencies = Set.new [0]\n self.changes = input.split(' ').map(&:to_i)\n new_frequency = 0\n index = 0\n loop do\n new_frequency += changes[index]\n puts \"#{frequencies.size} : #{new_frequency}\"\n index = index == changes.size - 1 ? 0 : index + 1\n break if frequencies.include?(new_frequency)\n\n frequencies << new_frequency\n end\n new_frequency\n end",
"def fill_recurrence(number)\n if old_num == number\n self.recc += 1\n else\n apply_recurrence\n self.old_num = number\n self.recc = 1\n end\n end",
"def next!\n self.start = self.send(:\"next_#{frequency}_in_recurrence\") \n self\n end",
"def frequency\n FREQUENCY\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def frequency\n frequency_quantity.send(frequency_type.name.pluralize)\n end",
"def rebalance_frequency(rf = nil) # rubocop:todo Naming/MethodParameterName\n if rf\n @assignments_since_rebalancing = 0\n @rebalance_frequency = rf\n rebalance!\n end\n @rebalance_frequency\n end",
"def note_frequency_calculator base_frequency, steps_to_next_note\n # TODO: Add a multiplier for KHz\n @bf = base_frequency\n @steps = steps_to_next_note\n return (@bf * 1.059463094359 ** @steps).round(2)\n end",
"def recurrence_rule\n parsed_data['recurrenceRule']\n end",
"def frequency\n interval || 1.year\n end",
"def angular_frequency\n @angular_frequency ||= 2.0 * Math::PI * frequency\n end",
"def accumulate term, docid, frequency, index\n @doc_count += 1\n @tot_freq += frequency.to_i\n end",
"def parse_rrule recurrence\n rule = recurrence.find do |rec|\n /\\ARRULE/.match(rec)\n end\n\n return nil unless rule\n rule = rule.split(':')[1]\n params = {\n validations: {}\n }\n\n rule.split(';').each do |rule|\n (name, value) = rule.split('=')\n value.strip!\n case name\n when 'FREQ'\n params[:freq] = value.downcase\n when 'INTERVAL'\n params[:interval] = value.to_i\n when 'COUNT'\n params[:count] = value.to_i\n when 'UNTIL'\n params[:until] = Time.parse(value).utc\n when 'WKST'\n params[:wkst] = day_to_symbol(value)\n when 'BYSECOND'\n params[:validations][:second_of_minute] = value.split(',').collect(&:to_i)\n when 'BYMINUTE'\n params[:validations][:minute_of_hour] = value.split(',').collect(&:to_i)\n when 'BYHOUR'\n params[:validations][:hour_of_day] = value.split(',').collect(&:to_i)\n when 'BYDAY'\n dows = {}\n days = []\n value.split(',').each do |expr|\n day = day_to_symbol(expr.strip[-2..-1])\n # day with occurence\n if expr.strip.length > 2\n occ = expr[0..-3].to_i\n dows[day].nil? ? dows[day] = [occ] : dows[day].push(occ)\n days.delete(to_wday(day))\n else\n days.push to_wday(day) if dows[day].nil?\n end\n end\n params[:validations][:day_of_week] = dows unless dows.empty?\n unless days.empty?\n # days = days.sort_by do |day|\n # day\n # end\n params[:validations][:day] = days\n end\n when 'BYMONTHDAY'\n params[:validations][:day_of_month] = value.split(',').collect(&:to_i)\n when 'BYMONTH'\n params[:validations][:month_of_year] = value.split(',').collect(&:to_i)\n when 'BYYEARDAY'\n params[:validations][:day_of_year] = value.split(',').collect(&:to_i)\n when 'BYSETPOS'\n else\n raise \"Invalid or unsupported rrule command: #{name}\"\n end\n end\n\n params[:interval] ||= 1\n params.delete(:wkst) unless params[:freq] == 'weekly'\n params\n end",
"def next_occurrence(start, continue=false)\n if @freq == :weekly\n wday = start.wday\n days = decode_by_day # i.e. [[1,1]] -\n # we want the first occurance where wday <= given day\n # example: schedule is [:mo,:we,:fr]\n # days = [[1,1],[1,3],[1,5]]\n # if our start is Sunday (wday=0), we want to stop on Monday (0 <= 1)\n # if our start is Tuesday (wday=2), we want to stop on Wednesday ( 2 <= 3)\n # if our start is Saturday (wday=6), we want the following Monday\n day_index = days.index { |day| wday <= day[1] }\n # if it is nil, we want the earliest day of the week\n if continue && day_index.nil?\n # I'd like to assume they are in order, but is that guaranteed?\n day_index = first_day\n # We then need to bump up the start a week\n start+=7\n elsif day_index.nil?\n return nil\n end\n # day will be the wday of the first matching date\n day = days[day_index][1]\n # we want to return the start plus the number of days till the firt match\n start + (day - wday)\n elsif @freq == :monthly && @by_day\n # Given the start we can grab month/year\n # go through each of the days and\n # return if it is greater than start\n # else ask if it needs to go to the following month (recursion)\n days = decode_by_day\n days.each do |d|\n day_in_month = day_of_month(start.year,start.month,*d, start.offset) # star to break array into two attributes\n return day_in_month if day_in_month >= start\n end\n # if it didn't find a match, then ask if it needs to continue\n if continue\n # Call the next month\n next_month = DateTime.new(start.year,start.month+1,1,0,0,0, start.offset)\n self.next_occurrence(next_month, continue)\n else\n nil\n end\n elsif @freq == :monthly && @by_month_day\n # Given start we know the day of month and we loop around\n # by_month_day until we find one bigger (unless negative). If not, retun nil unless continue = true,\n # in which case, grab the first one from by_month, and get it from the next month\n start_days_in_month = Time.days_in_month(start.month, start.year)\n neg_start = start.mday - start_days_in_month\n month_days = @by_month_day.split(',').map(&:to_i).sort\n day_index = month_days.index do |mday|\n if mday < 0\n # handle negatives\n neg_start <= mday\n else\n start.mday <= mday\n end\n end\n if !day_index.nil? && month_days[day_index] <= start_days_in_month\n day = month_days[day_index]\n DateTime.new(start.year, start.month, day,0,0,0, start.offset)\n elsif continue\n DateTime.new(start.year, start.month+1, month_days.first,0,0,0, start.offset)\n else\n nil\n end\n end\n end",
"def map_schedule_item_frequency parsed_item\n parsed_item[\"number\"].to_s + map_schedule_item_unit(parsed_item[\"unit\"])\n end",
"def create\n @recurring_frequency = RecurringFrequency.new(recurring_frequency_params)\n\n respond_to do |format|\n if @recurring_frequency.save\n format.html { redirect_to @recurring_frequency, notice: 'Recurring frequency was successfully created.' }\n format.json { render :show, status: :created, location: @recurring_frequency }\n else\n format.html { render :new }\n format.json { render json: @recurring_frequency.errors, status: :unprocessable_entity }\n end\n end\n end",
"def freq(f=false)\n if f\n @dial_freq=f-@carrier\n else\n # If the last time we checked the dial frequency is more than\n # @fexpire seconds ago, re-read the frequency and update the\n # timestamp.\n if Time.now().to_i-@ftime>@fexpire\n @dial_freq=(self.radio_freq()+self.get_carrier()).to_i\n @ftime=Time.now().to_i\n end\n return (@dial_freq+self.get_carrier()).to_i\n end\n end",
"def get_frequency_symbol(frequency)\n string_to_symbol = {\n 'Every X Years' => 'years',\n 'Every X Months' => 'months',\n 'Every X Weeks' => 'weeks',\n 'Every X Days' => 'days'\n }\n\n string_to_symbol[frequency].to_sym\n end",
"def period\n 4/frequency\n end",
"def recurring; end",
"def get_frequency(frequencies,digit,position)\n frequencies[position][digit]\nend",
"def frequency_in_words\n @cron_expression.frequency_in_words\n end",
"def to_frequency(value)\n IceCube::Schedule.from_ical(value) if value.present?\n end",
"def calcCalibrationFrequency(freqs)\n\tsum = 0\n\tsums = []\n\tcycles = 0\n\ti = 0\n\tputs \"Calculating calibration freq\"\n\tputs \"this will take a bit\"\n\twhile (!(sums.include? sum))\n\t\tsums.push(sum)\n\t\tsum += freqs[i]\n\t\tif ((i + 1) >= freqs.length)\n\t\t\ti = 0\n\t\t\tcycles += 1\n\t\telse\n\t\t\ti += 1\n\t\tend\n\tend\n\tputs sum\nend",
"def index\n @recurring_frequencies = RecurringFrequency.all\n end",
"def recurring_frequency_params\n params.require(:recurring_frequency).permit(:frequency, :description)\n end",
"def fix_frequency\n return unless frequency.duration > 1.month\n if frequency.duration < 12.months\n if intervals.all? { |i| i.first_datetime.day == i.last_datetime.day }\n frequency.duration = frequency.units[:months].months\n end\n else\n if intervals.all? { |i| i.first_datetime.month == i.last_datetime.month && i.first_datetime.day == i.last_datetime.day }\n frequency.duration = (frequency.duration / 12.months).floor.years\n end\n end\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def rrule(*args)\n if args[0].is_a?(Hash)\n freq = __value({ :freq => args[0].delete(:freq) })\n others = args[0].empty? ? nil : __value(args[0])\n args[0] = [freq, others].compact.join(';')\n end\n method_missing(:rrule, *args)\n end",
"def getFrequency()\n# @config[\"demandFactoryConf\"][\"frequency\"]\n interval = @config[\"demandFactoryConf\"][\"configList\"][0][\"interval\"] ;\n return 60 * 60 / interval.to_f ;\n end",
"def create_recurrences(transaction)\n CreateRecurrencesJob.perform_later(\n transaction.class.to_s,\n transaction.id.to_s\n )\n end",
"def frequency\n \n end",
"def recurrence=(new_rule)\n if RecurringSelect.is_valid_rule?(new_rule)\n rule = RecurringSelect.dirty_hash_to_rule(new_rule).to_hash\n write_attribute(:recurrence, rule)\n else\n write_attribute(:recurrence, nil)\n end\n end",
"def to_occurrence(date)\n date = next_occurrence(date) if date.is_a?(Date)\n event = Event.new\n event.start_datetime = date\n event.end_datetime = date + duration\n event.title = title\n event.description = description\n event.location = location\n event.id = id\n event.user = user\n event.is_recurrence!\n event.set_as_persisted!\n event.freeze\n end",
"def compute_frequencies\n @transitions.map { |value, transition_hash|\n sum = 0.0\n transition_hash.each { |succ_value, occurencies| \n sum += occurencies\n }\n \n transition_hash.each { |succ_value, occurencies|\n @frequencies[value] ||= Hash.new{0}\n @frequencies[value][succ_value] = occurencies/sum \n }\n }\n end",
"def factorials_rec(n)\n return [1] if n <= 1\n\n facts = factorials_rec(n-1)\n facts << facts.last * (n-1)\nend",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def next_occurrences\n result = []\n\n occurrences = Invoice.belonging_to(id).count\n next_date = next_invoice_date\n max_date = [Date.current, finishing_date.blank? ? Date.current + 1 : finishing_date].min\n\n while next_date <= max_date and (max_occurrences.nil? or occurrences < max_occurrences) do\n result.append(next_date)\n occurrences += 1\n next_date += period.send period_type\n end\n\n result\n end",
"def next\n recurrence.next if recurring?\n end",
"def count_freq\n hash = Hash.new(0)\n self.each do |element|\n hash[element] +=1\n end\n return hash\n end",
"def generate_sleep_freq(sleep_mins)\n freq = Hash.new(0)\n sleep_mins.each { |m| freq[m] += 1 }\n freq\nend",
"def get_tweet_counts_per_frequency(freq, tweet_name, start_time, end_time)\n \n end",
"def set_recurrence\n @recurrence = Recurrence.find(params[:id])\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def frequency=( freq )\n @frequency = freq.to_i\n @frequency_data = FREQUENCY[ @frequency ]\n end",
"def get_frequency()\n return(get_cmd('FA;',0.1,0.5,3).gsub(/^FA/,'').gsub(/;$/,'').to_i)\nend",
"def update_frequency\n metadata[dataset_uri][dct.accrualPeriodicity.to_s][0] rescue nil\n end",
"def correct_time(time, frequency)\n time -= frequency while time > Time.now\n time += frequency while time < Time.now\n time\nend",
"def pattern\n if valid_period?\n @pattern = eval(\"RecurringTodos::#{recurring_period.capitalize}RecurrencePattern.new(user)\")\n @pattern.build_from_recurring_todo(self)\n end\n @pattern\n end",
"def calcFrequency(freqs)\n\tsum = freqs.reduce(0, :+)\n\tputs sum\nend",
"def calcuate_frequencies(sequences)\n freq_array = Array.new(4) {|i|Array.new(10){|i| 0}} #2-dimensional array, second dimension initialised to 0's\n sequences.each do |seq|\n for position in 0..3\n freq_array[position][seq[position].to_i] += 1 #increment frequency value by 1\n end\n end\n freq_array\nend",
"def factorials_rec(num)\n return [1] if num == 1\n\n facts = factorials_rec(num-1)\n\n facts << facts.last * (num - 1)\n\n facts\nend",
"def frequency string\n $frequencies[string]\nend",
"def frequency=(f)\n\t\t\traise \"Unknown frequency type\" unless FREQS_TYPES.has_key?(f)\n\t\t\t@frequency = f\n\t\tend",
"def expression\n case frequency\n when :every\n DayOfWeek.new(day_of_week)\n else\n DayInMonth.new(day_of_week, frequency)\n end\n end",
"def DoR1(period)\n retval = '' # what we return\n accum = Hash.new() # where we accumulate data to report\n\n # get a list of VTRs between these dates and make a hash of the formNote\n rows = Vtr.where(\"date(date) between ? and ?\", period['lodate'].to_s(:db), period['hidate'].to_s(:db))\n rows.each do |row|\n k = row['formNote']\n accum[k] = 0 if accum[k].nil?\n accum[k] += 1\n end\n\n retval = accum.inspect\n end",
"def get_document_frequency(term)\n\t\t\t@term_hash[term]\n\t\tend",
"def factorials_rec(num)\n return 1 if num == 0 \n return [1] if num == 1\n fact = [1]\n\n fact << [(fact[-1] * factorials_rec(num-1))]\n# (2) \n# 4 * fact_rc(3) 2\n# 3 * fact_rc(2) 6\n# 2 * fact_rc(1) 2\n# 1 * fact(rc 0 )\nend",
"def fibs_rec(count)\n return [0,1,1].take(count) if count < 3\n prev_fibs = fibs_rec(count - 1)\n prev_fibs + [prev_fibs[-2] + prev_fibs[-1]]\nend",
"def occurrences(params={count: MAX_OCCURRENCE_COUNT})\n if(recurs?)\n if(params[:after])\n search_offset = params[:after].localtime.utc_offset - schedule.start_time.localtime.utc_offset\n elsif(params[:until])\n search_offset = params[:until].localtime.utc_offset - schedule.start_time.localtime.utc_offset\n end\n \n #reset schedule to utc\n schedule.start_time.utc\n schedule.end_time.utc\n \n schedules = if(params[:until])\n if(params[:after])\n schedule.occurrences_between(params[:after] - self.schedule.duration + search_offset, params[:until] + search_offset)\n else\n schedule.occurrences(params[:until] + search_offset)\n end\n elsif params[:count]\n if params[:after]\n schedule.next_occurrences(params[:count], params[:after] - self.schedule.duration + search_offset)\n else\n schedule.next_occurrences(params[:count], Time.zone.now - self.schedule.duration)\n end \n end\n \n if(schedules)\n \n #turn schedules [Time] into self.classes\n schedules.map { |time| duplicate(time - schedule.start_time + (self.start.localtime.utc_offset - time.localtime.utc_offset)) }\n else\n []\n end\n else\n [self]\n end\n end",
"def fib_rec(sequence_length)\n if sequence_length == 0\n return [0]\n elsif sequence_length == 1\n return [0,1]\n end\n\n return fib_rec(sequence_length - 1) << fib_rec(sequence_length - 1)[-1] + fib_rec(sequence_length - 2)[-1]\n\n\nend",
"def schedule_recurring_task_creation(task)\n recurring_scheduler = Scheduler.new\n @recurring_schedulers << recurring_scheduler\n\n recurring_scheduler.schedule.every \"#{Helpers.convert_frequency_to_seconds(task.frequency).to_s}s\" do\n new_task = Task.new\n new_task.description = task.description\n new_task.frequency = task.frequency\n new_task.creation_date = Time.now.getlocal\n new_task.target_date = Helpers.calculate_task_target_date(\n new_task.creation_date,\n new_task.frequency\n )\n new_task.recurring_scheduler_id = recurring_scheduler.id\n\n new_task.create_reminder_notification\n new_task.create_failed_notification\n\n add_task(new_task)\n end\n end",
"def schedule_every (freq, params={}, &block)\n\n params = prepare_params(params)\n params[:every] = freq\n\n first_at = params[:first_at]\n first_in = params[:first_in]\n\n #params[:delayed] = true if first_at or first_in\n\n first_at = if first_at\n at_to_f(first_at)\n elsif first_in\n Time.now.to_f + Rufus.duration_to_f(first_in)\n else\n Time.now.to_f + Rufus.duration_to_f(freq) # not triggering immediately\n end\n\n do_schedule_at(first_at, params, &block)\n end",
"def factorials_rec(num)\n return [1,1].take(num) if num < 2\n facts = factorials_rec(num - 1)\n facts + [facts.last * (num - 1)]\nend",
"def frequency(diapason: 440, height: '8')\n index = NOTES.index(@letter)\n (diapason.to_f / height_decimal(height)) * 2**(@octave + ((index - 9.0) / 12))\n end",
"def schedule\n \"#{frequency_quantity} #{frequency_type.name.pluralize} at #{execution_time}\"\n end",
"def get_fact_rec(num)\n if num == 0\n return 1\n else\n return num *= get_fact(num-1)\n end\nend",
"def overall_frequency\n categories.inject(0) { |carry, item| carry + item[1] }\n end",
"def fibo_rec(target_number)\n if target_number<1\n\t$series[0]=0\n return 0\n \n elsif target_number=1\n \t$series[1]=1\n \tfibo_rec 0\n return 1\n\n else\n\t\tans=fibo_rec(target_number-1)+(fibo_rec(target_number-2))\t\n\t\t$series[target_number]=ans\n\t\treturn ans\n\tend\n\treturn $series\nend",
"def transform\n raise \"No input data\" unless @data\n (0..@freq.size-1).each do |k|\n @data.each_with_index do |d,i|\n @freq[k] = Complex(\n @freq[k].real + d * Math.cos( 2 * Math::PI * k * i / @data.size ),\n @freq[k].imag - d * Math.sin( 2 * Math::PI * k * i / @data.size )\n )\n end\n end\n return @freq\n end",
"def get_tweet_counts_per_frequency(freq, tweet_name, start_time, end_time)\n case freq\n when \"minute\"\n delta = 60\n when \"hour\"\n delta = 3600\n else\n delta = 86400\n end\n\n t = Hash.new(0)\n if @tweets.key?(tweet_name)\n @tweets[tweet_name].each do |time|\n next if time < start_time || time > end_time\n t[(time - start_time) / delta] += 1\n end\n end\n\n result = []\n (0..((end_time - start_time) / delta)).each do |i|\n result.push(t[i])\n end\n\n result\n end",
"def radio_step_freq _value\n send_cmd(\"radio_step_freq #{_value}\")\n end",
"def genFreqTable(string)\n freqTable = Hash.new\n string.split(\"\").each do |i| #loop through every character in the string\n if freqTable.has_key?(string[i]) #if key already exists\n freqTable[string[i]] += 1 #increments its frequency\n else\n freqTable[string[i]] = 1 #else its a new key so set its frequency to 1\n end\n end\n return freqTable\nend",
"def find_repetition_interval(repetition, e_factor)\n return 6 if repetition == 1\n (repetition * e_factor).round\n end",
"def frequencies\n $heap[:word_freqs] = {}\n $heap[:count] = 0 # we need because of operator order, see below\n # A little flavour of the real Forth style here...\n while $stack.length > 0\n # ...but the following line is not in style, because the \n # naive implementation would be too slow\n if $heap[:word_freqs].include? $stack.last\n # Increment the frequency, postfix style: f 1 +\n $stack.push $heap[:word_freqs][$stack.last] # push f\n $stack.push 1\n $stack.push $stack.pop + $stack.pop\n else\n $stack.push 1\n end\n # Load the updated freq back onto heap\n $heap[:count] = $stack.pop\n $heap[:word_freqs][$stack.pop] = $heap[:count] # can't write head[_][stack.pop] = stack.pop\n end\n # Push result onto the stack\n $stack.push $heap[:word_freqs]\n $heap[:word_freqs] = nil; $heap[:count] = nil # Don't need this variable\nend",
"def frequencies\n inject(Hash.new(0)) { |h,v| h[v] += 1; h }\n end",
"def recurrence_params\n params.require(:recurrence).permit(:title, :start_time, :description, :recurring)\n end",
"def load_frequencies\n frequencies = {}\n\n frequencies_table = conn.exec <<-SQL\n SELECT * FROM gtf_frequencies\n SQL\n\n frequencies_table.each do |trip_id, start_time, end_time, headway_secs|\n st = GoogleTransitFeed::parse_time( start_time )\n et = GoogleTransitFeed::parse_time( end_time )\n hs = headway_secs.to_i\n # If there is not a key in the hash then creates the key\n frequencies[trip_id] ||=[]\n # Fills all the starting times for the trip\n while st <= et\n frequencies[trip_id] << st\n st += hs\n end\n end\n\n # Traverse the frequencies hash and subtract the first start time from all values\n frequencies.each do |key, row|\n first = row[0]\n frequencies[key] = []\n row.each do |f|\n frequencies[key] << f - first\n end\n end\n return frequencies\n end"
] |
[
"0.65145075",
"0.6428962",
"0.6237867",
"0.6183278",
"0.6152973",
"0.6152973",
"0.61239976",
"0.60252553",
"0.5992055",
"0.59302026",
"0.59113914",
"0.5873501",
"0.58342814",
"0.5833177",
"0.5823272",
"0.58088017",
"0.57808685",
"0.5740985",
"0.57049984",
"0.570419",
"0.5668446",
"0.5668446",
"0.5659843",
"0.56423503",
"0.56261635",
"0.55977726",
"0.55322224",
"0.5521423",
"0.54894954",
"0.5486788",
"0.5482342",
"0.54785854",
"0.5446384",
"0.5433138",
"0.54154724",
"0.54123133",
"0.5396337",
"0.5387852",
"0.53703636",
"0.5366722",
"0.5343955",
"0.5332089",
"0.53197134",
"0.5255082",
"0.52526146",
"0.52475023",
"0.5246445",
"0.52400035",
"0.5216912",
"0.5216264",
"0.52086604",
"0.52042574",
"0.5203236",
"0.52004623",
"0.51778",
"0.51740074",
"0.517328",
"0.5169528",
"0.51584893",
"0.5157614",
"0.51542073",
"0.51536614",
"0.5146347",
"0.5144279",
"0.5130642",
"0.51209325",
"0.5102497",
"0.5078532",
"0.5077951",
"0.50636804",
"0.5053934",
"0.50490576",
"0.50489026",
"0.50468874",
"0.5043285",
"0.5033524",
"0.50254226",
"0.49848878",
"0.4973518",
"0.4955155",
"0.49431267",
"0.4937746",
"0.4935984",
"0.49340874",
"0.4916411",
"0.49052602",
"0.490032",
"0.4883254",
"0.48647913",
"0.48505548",
"0.48501575",
"0.48356062",
"0.4835399",
"0.48344293",
"0.48336124",
"0.48278534",
"0.48239473",
"0.4822419",
"0.48222074",
"0.48210993"
] |
0.48806503
|
88
|
Create a minutely recurrence.
|
def minutely(options = {})
branch options.merge(every: :minute)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def recurrence\n nil\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def create(opts)\n @frequence = opts[:frequence] if opts[:frequence].in? Recurrence::FREQUENCES\n @monthly = array_to_integer(opts[:monthly])\n @count = to_integer(opts[:count])\n @until = string_to_date(opts[:until])\n self\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def fill_recurrence(number)\n if old_num == number\n self.recc += 1\n else\n apply_recurrence\n self.old_num = number\n self.recc = 1\n end\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def recurrence\n { ATTR_RECURRENCE[@attribute] => 1 }\n end",
"def add_recurrence(type: :week, on: on = nil, at: at = nil)\n type = type.to_sym\n unless [:week, :day].include? type\n raise \"Type must be either :week or :day\"\n end\n if type == :week and (on.nil? or (on.is_a?(Array) and on.empty?))\n raise \"Weekdays must be specified when selecting the :week type\"\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if self.schedule.nil?\n schedule = Montrose::Schedule.new\n end\n if at.nil?\n raise \"Time must be specified in parameter 'at'\"\n else\n schedule.add Montrose.every(type, on: on, at: at).starts(created_at)\n self.write_attribute(self.class.schedulable_attribute, schedule)\n end\n end",
"def recurrence\n unless read_attribute(:recurrence).empty?\n IceCube::Rule.from_hash(read_attribute(:recurrence))\n end\n end",
"def recurring; end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def recurrence\n return @recurrence\n end",
"def recurrence\n return @recurrence\n end",
"def calc_next_run\n RunAtPeriodicJob.new(:name => self.name, :job => self.job, :run_at_minutes => self.run_at_minutes)\n end",
"def schedule_recurring_task_creation(task)\n recurring_scheduler = Scheduler.new\n @recurring_schedulers << recurring_scheduler\n\n recurring_scheduler.schedule.every \"#{Helpers.convert_frequency_to_seconds(task.frequency).to_s}s\" do\n new_task = Task.new\n new_task.description = task.description\n new_task.frequency = task.frequency\n new_task.creation_date = Time.now.getlocal\n new_task.target_date = Helpers.calculate_task_target_date(\n new_task.creation_date,\n new_task.frequency\n )\n new_task.recurring_scheduler_id = recurring_scheduler.id\n\n new_task.create_reminder_notification\n new_task.create_failed_notification\n\n add_task(new_task)\n end\n end",
"def schedule_repetition\n self.due = Date.today + interval\n self.studied_at = Date.today\n end",
"def next!\n self.start = self.send(:\"next_#{frequency}_in_recurrence\") \n self\n end",
"def start_recurring_payment\n return unless recurring_period.present?\n run_at = nil\n if recurring_period.to_s.is_i? # each custom days\n run_at = recurring_period.to_i.days.from_now\n # run_at = recurring_period.to_i.minutes.from_now\n else\n case recurring_period\n when 'daily'\n run_at = 1.day.from_now\n when 'weekly'\n run_at = 7.days.from_now\n when 'monthly'\n run_at = 1.month.from_now\n when 'quarterly'\n run_at = 3.months.from_now\n when 'biannually'\n run_at = 6.months.from_now\n when 'yearly'\n run_at = 1.year.from_now\n end\n end\n Delayed::Job.enqueue(LongTasks::RecurringPaymentNotification.new(id), run_at: run_at - 1.day) if run_at && ['tithe', 'partnership'].include?(goal)\n Delayed::Job.enqueue(LongTasks::RecurringPayment.new(id), run_at: run_at) if run_at\n end",
"def new_schedule(*args)\n if !args.all? { |e| e.is_a?(Integer) && e >= 0 && e <= 6 }\n return \"Please enter a number from 0-6 where each number represents a day of the week. 0 represents Sunday, 1 represents Monday, etc.\"\n end\n schedule1 = Schedule.new(self.first_event, duration: self.duration_mins.minutes )\n schedule1.add_recurrence_rule Rule.weekly.day(args)\n self.schedule = schedule1\n self.save!\n end",
"def future_single_event_creation\n self.schedule.next_occurrences(12).each do |occurrence|\n # TODO: Hot-Fix for Bug #83, unti ice_cube's issue 84 is resolved\n occurrence = occurrence.without_ms\n\n if !self.schedule.extimes.map(&:to_i).include? occurrence.to_i\n SingleEvent.where(event_id: self.id,\n occurrence: occurrence,\n based_on_rule: true).first_or_create\n end\n end\n end",
"def set_recurrence\n @recurrence = Recurrence.find(params[:id])\n end",
"def next\n recurrence.next if recurring?\n end",
"def create_recurrences(transaction)\n CreateRecurrencesJob.perform_later(\n transaction.class.to_s,\n transaction.id.to_s\n )\n end",
"def next_meeting(after_time = Time.now.utc )\n # puts \"Looking up next meeting after #{after_time}\"\n if recurrence_frequency.blank?\n return start_time\n end\n\n if after_time < start_time\n return start_time\n end \n\n after_time = after_time.local_from_utc(self.time_zone) \n\n\n # Advance the starting time in the case when it falls after the beginning of\n # a meeting on the same day. We do this so that we can use \"day precision\"\n # (PDate.day) in the Runt library instead of \"minute precision\" (PDate.min),\n # which performs terribly.\n start_time = start_time_local\n if(after_time.hour > start_time.hour or ( after_time.hour == start_time.hour and after_time.min > start_time.min))\n after_time = after_time + 1.day\n after_time = Time.gm(after_time.year, after_time.month, after_time.day, 0, 0)\n end\n\n case recurrence_frequency\n when 'daily'\n end_time = after_time + 25.hours \n # after_time -= 1.day\n start_date = PDate.day(after_time.year, after_time.month, after_time.day , after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'weekdays'\n # Make the range over 3 days so that Friday night searches will still turn\n # up Monday as the next day.\n end_time = after_time + 3.days\n start_date = PDate.day(after_time.year, after_time.month, after_time.day, after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'monthly'\n eom = (after_time + 40.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eom.year, eom.month, eom.day)\n when 'weekly'\n eow = (after_time + 8.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eow.year, eow.month, eow.day)\n when 'yearly'\n # Just doing \"after_time + 367.days\" results in a bit of a performance hit\n # as hundreds of days are compared. We'll try to narrow it a bit. Not too\n # much, because we don't have time to actually write unit tests and make\n # sure the narrowing code works. :) Which is why the comment is here.\n st = after_time + 250.days\n et = st + 150.days\n start_date = PDate.day(st.year, st.month, st.day)\n end_date = PDate.day(et.year, et.month, et.day)\n end \n # puts \" Range #{start_date.to_s} - #{end_date.to_s}\"\n d_range = DateRange.new(start_date, end_date)\n sched = Schedule.new\n event = Event.new((self.invitation.name rescue \"no name\"))\n sched.add(event,self.runt_expression)\n dates = sched.dates(event,d_range)\n\n next_mtg = dates.first\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, start_time_local.hour, start_time_local.min)\n result = nil\n begin\n result = next_mtg_time.local_to_utc(self.time_zone)\n rescue TZInfo::PeriodNotFound\n # This only happens when the time is during the one hour which is skipped\n # during the transition to DST. For example, only on Sun Mar 08 02:15:00\n # (see ticket #744).\n next_hour = start_time_local.hour + 1\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, next_hour, start_time_local.min)\n retry\n end\n return result\n end",
"def set_first_repetition\n first_repetition_date = Date.today + rand(1..3).days\n repetitions.create planned_date: first_repetition_date, actual_date: first_repetition_date\n end",
"def process\n @recurrences.each { |r| process_recurrence(r) }\n end",
"def set_next_repetition\n if repetitions.order(\"id ASC\").last.successful\n self.consecutive_successful_repetitions += 1\n next_planned_interval = rand((repetitions.last_planned_interval * 2)..(repetitions.last_planned_interval * 3))\n else\n self.consecutive_successful_repetitions = 0\n next_planned_interval = rand(1..3)\n end\n save\n if consecutive_successful_repetitions < WhRails::Application.config.max_consecutive_successful_repetitions\n # repetitions.last.actual_date is always the current date.\n next_repetition_date = repetitions.order(\"id ASC\").last.actual_date + next_planned_interval.days\n repetitions.create planned_date: next_repetition_date, actual_date: next_repetition_date\n else\n self.learned_on = Date.today\n save\n end\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def calculate_sequence\n old_sequence.split('')[1..-1].each(&method(:fill_recurrence))\n\n apply_recurrence\n\n recurrences.flatten.join\n end",
"def create_expenses\n expense_id = nil\n @expense = @account.expenses.create(expense_params)\n step = params[:expense_form][:recurrence].to_i\n\n if @expense.valid? && step != 0\n @expense.month_id = @expense.due_date.mon\n @expense.save \n start_month = @expense.due_date.mon + step\n number_of_months = step\n (start_month..12).step(step).each do |month|\n @expense = @account.expenses.new(expense_params)\n @expense.month_id = month\n @expense.due_date = @expense.due_date.to_date >> number_of_months\n number_of_months += step\n @expense.related_to = expense_id || @expense.id\n @expense.save\n expense_id ||= @expense.id\n end\n elsif @expense.valid?\n @expense.month_id = @expense.due_date.mon\n @expense.save\n end\n @expense.valid?\n end",
"def pattern\n if valid_period?\n @pattern = eval(\"RecurringTodos::#{recurring_period.capitalize}RecurrencePattern.new(user)\")\n @pattern.build_from_recurring_todo(self)\n end\n @pattern\n end",
"def make_constant_schedule(name, temperature)\n s = OpenStudio::Model::ScheduleRuleset.new(@model)\n s.setName(name)\n s.defaultDaySchedule.addValue(OpenStudio::Time.new(\"24:00:00\"), OpenStudio::convert(temperature, \"F\", \"C\").get)\n\ts\n end",
"def rep(rule, min=1, max=Infinity, &block)\n ext(Repeat.new(min, max, rule), block)\n end",
"def rep(rule, min=1, max=Infinity, &block)\n ext(Repeat.new(rule, min, max), block)\n end",
"def calc_next_run\n self.next_run_at = nil\n end",
"def build_reminders\n\t\treminds = self.reminders.last(10).to_a\t\t\n\t\t(10 - self.reminders.count).times do\n\t\t\treminds << self.reminders.build\n\t\tend\n\t\treminds\n\tend",
"def create_activity_factory_wrapper\n if recurrence\n create_activity_factory({\n # Fields copied straight from +Activity+ model\n name:name,\n description:description,\n vendor_id:vendor_id,\n vendor_name:vendor_name,\n bookings_available:bookings_available,\n price:price,\n start: start,\n # Fields inferred from +Activity+ model\n duration: (start && finish && finish - start)\n }.merge(recurrence) )\n return !activity_factory.new_record?\n end\n end",
"def create_inbetween_occurrences?\n return unless recurrence.present?\n\n recurrency&.to_i == 7 && recurrence.recurrency&.to_i == 14\n end",
"def create\n timer = Timer.new(\n last_rang: Time.now,\n time_increment: params[:time_increment],\n increment_unit: params[:increment_unit],\n timerable_id: params[:timerable_id],\n timerable_type: params[:timerable_type],\n repeating: params[:repeating] \n )\n\n if timer.save\n user = timer.timerable.user\n text = \"your medication\"\n ReminderJob.set(wait: eval(\"#{timer.time_increment}.#{timer.increment_unit}\")).perform_later(timer, user.phone_number, text)\n\n render json: {message: 'Reminder created successfully'}, status: :created\n else \n render json: {errors: timer.errors.full_messages}, status: :bad_request\n end\n end",
"def recurrence_at\n unless @recurrence_at.nil?\n return @recurrence_at\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if schedule.nil?\n return nil\n end\n # montrose stores the \"at\" times in an array with\n # time[0] = hour\n # time[1] = mins\n # time[2] = secs\n schedule.rules.first.to_h[:at].map{|time| [time[0].to_s.rjust(2,\"0\"),time[1].to_s.rjust(2,\"0\")].join(\":\")}.join(\", \")\n end",
"def recurrence=(new_rule)\n if RecurringSelect.is_valid_rule?(new_rule)\n rule = RecurringSelect.dirty_hash_to_rule(new_rule).to_hash\n write_attribute(:recurrence, rule)\n else\n write_attribute(:recurrence, nil)\n end\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def payment_schedule(from_date = nil)\n schedule = []\n if recurring_payments?\n (0...recurring_number).each do |period|\n xdays = period * recurring_period\n schedule << { due_on: (from_date ? from_date.to_date + xdays.days : xdays),\n period_payment: payment_price,\n total_due: (period + 1) * payment_price }\n end\n # adjust the last entry\n schedule.last[:total_due] = price\n schedule.last[:period_payment] = price - (recurring_number - 1) * payment_price\n else\n schedule << { due_on: (from_date ? from_date.to_date : 0), period_payment: payment_price, total_due: payment_price }\n end\n schedule\n end",
"def recurrence_rule\n parsed_data['recurrenceRule']\n end",
"def recurring\n self.recurrence.present?\n end",
"def recurrence_params\n params.require(:recurrence).permit(:title, :start_time, :description, :recurring)\n end",
"def calc_next_run\n nil\n end",
"def calc_next_run\n nil\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def _create_resevation(base, subject, owner)\n\t\t\t\t\t\n\t\t\t\t\t# Create reservation\n\t\t\t\t\treservation = RicReservation.reservation_model.new\n\t\t\t\t\treservation.kind = \"event\"\n\t\t\t\t\treservation.event = self\n\t\t\t\t\treservation.date_from = base\n\t\t\t\t\treservation.date_to = base + (self.date_to - self.date_from).to_i.days\n\t\t\t\t\treservation.time_from = self.time_from\n\t\t\t\t\treservation.time_to = self.time_to\n\n\t\t\t\t\t# Bind subject\n\t\t\t\t\tif !subject.nil?\n\t\t\t\t\t\treservation.size = subject.size\n\t\t\t\t\t\treservation.subject = subject\n\t\t\t\t\telse\n\t\t\t\t\t\treservation.size = self.default_reservation_size\n\t\t\t\t\tend\n\n\t\t\t\t\t# Bind owner\n\t\t\t\t\tif !owner.nil?\n\t\t\t\t\t\treservation.owner_name = owner.name if !owner.name.nil?\n\t\t\t\t\t\treservation.owner = owner if owner.is_a?(ActiveRecord::Base) # In case owner is not ActiveRecord, only name can be stored\n\t\t\t\t\tend\n\n\t\t\t\t\treturn reservation\n\t\t\t\tend",
"def create_first_round\n for i in 1..4\t\n Round.create(:slam_id => self.id, :roundNumber => i)\n end\n end",
"def repeat(min=0, max=nil)\n Parslet::Atoms::Repetition.new(self, min, max)\n end",
"def make_reminder(minutes_before = 510)\n Google::Apis::CalendarV3::EventReminder.new({\n minutes: minutes_before,\n reminder_method: 'popup'\n })\nend",
"def next_occurrence(start, continue=false)\n if @freq == :weekly\n wday = start.wday\n days = decode_by_day # i.e. [[1,1]] -\n # we want the first occurance where wday <= given day\n # example: schedule is [:mo,:we,:fr]\n # days = [[1,1],[1,3],[1,5]]\n # if our start is Sunday (wday=0), we want to stop on Monday (0 <= 1)\n # if our start is Tuesday (wday=2), we want to stop on Wednesday ( 2 <= 3)\n # if our start is Saturday (wday=6), we want the following Monday\n day_index = days.index { |day| wday <= day[1] }\n # if it is nil, we want the earliest day of the week\n if continue && day_index.nil?\n # I'd like to assume they are in order, but is that guaranteed?\n day_index = first_day\n # We then need to bump up the start a week\n start+=7\n elsif day_index.nil?\n return nil\n end\n # day will be the wday of the first matching date\n day = days[day_index][1]\n # we want to return the start plus the number of days till the firt match\n start + (day - wday)\n elsif @freq == :monthly && @by_day\n # Given the start we can grab month/year\n # go through each of the days and\n # return if it is greater than start\n # else ask if it needs to go to the following month (recursion)\n days = decode_by_day\n days.each do |d|\n day_in_month = day_of_month(start.year,start.month,*d, start.offset) # star to break array into two attributes\n return day_in_month if day_in_month >= start\n end\n # if it didn't find a match, then ask if it needs to continue\n if continue\n # Call the next month\n next_month = DateTime.new(start.year,start.month+1,1,0,0,0, start.offset)\n self.next_occurrence(next_month, continue)\n else\n nil\n end\n elsif @freq == :monthly && @by_month_day\n # Given start we know the day of month and we loop around\n # by_month_day until we find one bigger (unless negative). If not, retun nil unless continue = true,\n # in which case, grab the first one from by_month, and get it from the next month\n start_days_in_month = Time.days_in_month(start.month, start.year)\n neg_start = start.mday - start_days_in_month\n month_days = @by_month_day.split(',').map(&:to_i).sort\n day_index = month_days.index do |mday|\n if mday < 0\n # handle negatives\n neg_start <= mday\n else\n start.mday <= mday\n end\n end\n if !day_index.nil? && month_days[day_index] <= start_days_in_month\n day = month_days[day_index]\n DateTime.new(start.year, start.month, day,0,0,0, start.offset)\n elsif continue\n DateTime.new(start.year, start.month+1, month_days.first,0,0,0, start.offset)\n else\n nil\n end\n end\n end",
"def create\n @event_recurrence = EventRecurrence.new(event_recurrence_params)\n\n respond_to do |format|\n if @event_recurrence.save\n format.html { redirect_to @event_recurrence, notice: 'Event recurrence was successfully created.' }\n format.json { render :show, status: :created, location: @event_recurrence }\n else\n format.html { render :new }\n format.json { render json: @event_recurrence.errors, status: :unprocessable_entity }\n end\n end\n end",
"def parse_rrule recurrence\n rule = recurrence.find do |rec|\n /\\ARRULE/.match(rec)\n end\n\n return nil unless rule\n rule = rule.split(':')[1]\n params = {\n validations: {}\n }\n\n rule.split(';').each do |rule|\n (name, value) = rule.split('=')\n value.strip!\n case name\n when 'FREQ'\n params[:freq] = value.downcase\n when 'INTERVAL'\n params[:interval] = value.to_i\n when 'COUNT'\n params[:count] = value.to_i\n when 'UNTIL'\n params[:until] = Time.parse(value).utc\n when 'WKST'\n params[:wkst] = day_to_symbol(value)\n when 'BYSECOND'\n params[:validations][:second_of_minute] = value.split(',').collect(&:to_i)\n when 'BYMINUTE'\n params[:validations][:minute_of_hour] = value.split(',').collect(&:to_i)\n when 'BYHOUR'\n params[:validations][:hour_of_day] = value.split(',').collect(&:to_i)\n when 'BYDAY'\n dows = {}\n days = []\n value.split(',').each do |expr|\n day = day_to_symbol(expr.strip[-2..-1])\n # day with occurence\n if expr.strip.length > 2\n occ = expr[0..-3].to_i\n dows[day].nil? ? dows[day] = [occ] : dows[day].push(occ)\n days.delete(to_wday(day))\n else\n days.push to_wday(day) if dows[day].nil?\n end\n end\n params[:validations][:day_of_week] = dows unless dows.empty?\n unless days.empty?\n # days = days.sort_by do |day|\n # day\n # end\n params[:validations][:day] = days\n end\n when 'BYMONTHDAY'\n params[:validations][:day_of_month] = value.split(',').collect(&:to_i)\n when 'BYMONTH'\n params[:validations][:month_of_year] = value.split(',').collect(&:to_i)\n when 'BYYEARDAY'\n params[:validations][:day_of_year] = value.split(',').collect(&:to_i)\n when 'BYSETPOS'\n else\n raise \"Invalid or unsupported rrule command: #{name}\"\n end\n end\n\n params[:interval] ||= 1\n params.delete(:wkst) unless params[:freq] == 'weekly'\n params\n end",
"def increase_busy_counter\n @recurrence.increment! :busy_count\n end",
"def now_and_every(interval, recur = T.unsafe(nil), &block); end",
"def create\n @event_recurrence = EventRecurrence.new(event_recurrence_params)\n @call = Call.new(call_params)\n @call.event_recurrence = @event_recurrence \n\n respond_to do |format|\n if @call.save && @event_recurrence.save\n format.html { redirect_to @call, notice: 'Call was successfully created.' }\n format.json { render :show, status: :created, location: @call }\n else\n format.html { render :new }\n format.json { render json: @call.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @activity = Activity.create activity_params\n status = @activity.new_record? ? 400 : 201\n if @activity.recurrence\n render json: @activity.activity_factory.activities.as_json, status:status\n else\n respond_with @activity, status:status\n end\n end",
"def process_recurrence(recurrence)\n return true unless recurrence.today?\n recurrence.update_job\n end",
"def factorials_rec(num)\n if num == 1\n [1]\n else\n recs = factorials_rec(num - 1)\n recs << (num - 1) * recs.last\n end\nend",
"def evaulate_schedule\n 5\n end",
"def schedule_with_periodicity(jobs=parse_jobs())\n # see parse_input.rb\n #jobs = parse_jobs()\n jobs.each do |job|\n unless job.periodicity == 0 or jobs.map{ |j| j.id }.count(job.id) > 1\n # duplicate periodic job and fix arrival and relative_deadline\n periodic_job = job.dup\n periodic_job.arrival = job.periodicity + job.arrival\n periodic_job.relative_deadline = periodic_job.arrival + periodic_job.deadline\n # insert it at the good arrival place in the array of jobs\n i = 0\n jobs.map do |j|\n if periodic_job.arrival > jobs[i].arrival and\n (jobs[i+1].nil? or periodic_job.arrival < jobs[i+1].arrival)\n jobs.insert(i + 1, periodic_job)\n break\n end\n i += 1\n end\n end\n end\n return jobs\nend",
"def recurring(opts={})\n all({DataMapper::Events.recurrence_key.not => nil}.merge(opts))\n end",
"def minimize\n # create a new one, or modify the current one in place,\n # and return it\n FiniteAutomaton.new \n end",
"def schedule_payment! amount, due_at = Time.now\n scheduled_payments.create :amount => amount, :due_at => due_at\n end",
"def factorials_rec(num)\n return [1] if num == 1\n\n facts = factorials_rec(num-1)\n\n facts << facts.last * (num - 1)\n\n facts\nend",
"def date_calc(start,day_start,day_duration,round)\n time=start;schedule=[]\n round.size.times do |r|\n#print day_start+day_duration;print \"\\n\"\n if time >= day_start + day_duration\n#print time;print \"\\n\"\n time=day_start+1.day\n day_start = time\n end\n schedule[r] = time\n time+=HEAT_INTERVAL\n end\n\n return schedule\n end",
"def create\n @time_slot = TimeSlot.new(params[:time_slot])\n @time_slot.user_id = current_identity.user_id\n\t@recurrence_array = []\n respond_to do |format|\n if @time_slot.save\n format.html { redirect_to @time_slot, notice: 'Time slot was successfully created.' }\n format.json { render json: @time_slot, status: :created, location: @time_slot }\n else\n format.html { render action: \"new\" }\n format.json { render json: @time_slot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def to_occurrence(date)\n date = next_occurrence(date) if date.is_a?(Date)\n event = Event.new\n event.start_datetime = date\n event.end_datetime = date + duration\n event.title = title\n event.description = description\n event.location = location\n event.id = id\n event.user = user\n event.is_recurrence!\n event.set_as_persisted!\n event.freeze\n end",
"def set_event_recurrence\n @event_recurrence = EventRecurrence.find(params[:id])\n end",
"def work(interval = 5.0)\n end",
"def schedule(hash)\n run_job = Proc.new do\n if hash['make_after'].to_i > 0\n EM::Timer.new(hash['make_after']) do\n self.storage.load(hash) { |hash| do_job(JR.make(hash)) }\n end\n else\n EM.next_tick do\n self.storage.load(hash) { |hash| do_job(JR.make(hash)) }\n end\n end\n end\n\n if hash['defer'] == 'true'\n EM.defer { run_job.call }\n else\n run_job.call\n end\n end",
"def generate_grow required_depth \n generate( [:cyclic, :terminating], required_depth )\n end",
"def factorials_rec(num)\n return 1 if num == 0 \n return [1] if num == 1\n fact = [1]\n\n fact << [(fact[-1] * factorials_rec(num-1))]\n# (2) \n# 4 * fact_rc(3) 2\n# 3 * fact_rc(2) 6\n# 2 * fact_rc(1) 2\n# 1 * fact(rc 0 )\nend",
"def recurrence_to_events!(now = Time.now.utc)\n recurring.each {|r| r.recurrence_to_events!(now)}\n end",
"def calculate_next_delivery\n interval = @schedulable.repeat_every\n next_delivery_date =\n case\n when @schedulable.company_survey.counter == 0 || @schedulable.time.present?\n set_next_delivery\n when @schedulable.repeat_mode == 'd'\n @schedulable.next_delivery_at + interval.days\n when @schedulable.repeat_mode == 'w'\n @schedulable.next_delivery_at + interval.weeks\n end\n\n @schedulable.update_column(:next_delivery_at, next_delivery_date)\n next_delivery_date\n end",
"def next_collection\n # pry\n rule = IceCube::Rule.from_yaml(self.schedule)\n schedule = IceCube::Schedule.new(Time.now)\n schedule.add_recurrence_rule(rule)\n date = schedule.next_occurrence(Time.now)\n # puts date\n # date\n end",
"def new\n @goal = Goal.new(recurrence_id: params[:recurrence_id])\n end",
"def fill! num=@pool-@count\n raise CreatorError, NO_CONSTRUCTOR_MSG if @create.nil?\n \n return 0 if full?\n num = @pool-num.abs if num < 0\n return 0 if num <= 0\n \n objs = num.times.map(&@create.method(:call))\n expr_addition = objs.zip([Time.now]*num)\n \n threadsafe do\n @expr_hash.merge(expr_addition)\n @stack.push *objs\n @count += num\n end\n \n start_purging!\n\t\t\n\t\tnum\n\tend",
"def create_default_estimated_date\n Date.today + 7\n end",
"def create_reservation(base = self.date_from, subject = nil, owner = nil)\n\t\t\t\t\t\n\t\t\t\t\t# Create reservation\n\t\t\t\t\treservation = _create_resevation(base, subject, owner)\n\n\t\t\t\t\t# Store\n\t\t\t\t\treservation.save\n\n\t\t\t\t\treturn reservation\n\t\t\t\tend",
"def initialize\n @interval = 1\n @wkst = :mo\n @id = rand(100)\n @duration = 0 # 1 day\n @event_start = DateTime.new\n end",
"def make_resevation(date_range)\n available_rooms = get_available_rooms(date_range)\n if available_rooms.length < 1\n raise ArgumentError\n end\n new_reservation = Hotel::Reservation.new(date_range,available_rooms[0])\n @reservations << new_reservation\n return new_reservation\n end",
"def add_reminder; end",
"def create_for_period(future_period, notification_times, border_time)\n existing_times = future_period.notifications.all.map { |n| n.time }\n notification_times.each do |time|\n if !existing_times.include?(time) && border_time < time\n future_period.notifications.create!(time: time)\n end\n end\n end",
"def update_interval\n self.interval =\n case repetitions\n when 1 then 1\n when 2 then 6\n else\n (repetitions - 1) * easiness_factor\n end\n end",
"def factorials_rec(n)\n return [1] if n <= 1\n\n facts = factorials_rec(n-1)\n facts << facts.last * (n-1)\nend",
"def factorials_rec(num)\n return [1] if num <= 1\n fact = factorials_rec(num-1)\n fact << (num-1) * fact.last\nend",
"def factorials_rec(num)\n return [1] if num == 1\n return [] if num == 0\n prev_seq = factorials_rec(num-1)\n prev_seq << factorials(num)\n prev_seq\n\nend",
"def new_autopay_rent(price, from_date)\r\n new_auto_pay_rent = AutoPay.new({:renter_id => self.id,\r\n :property_id => self.property.id,\r\n :object => self.actual_rent.auto_pay.object,\r\n :price => price,\r\n :category => \"in\",\r\n :groupp => \"najem\",\r\n :last_pay => from_date,\r\n :repeat => self.actual_rent.auto_pay.repeat,\r\n :added => Time.now.to_i}) \r\n new_auto_pay_rent.save\r\n return new_auto_pay_rent\r\n end",
"def create\n\t @reminder = current_user.reminders.create(params[:reminder])\n\t \n\t if @reminder.save\n\t \trecord_activity(\"created new reminder: \" + @reminder.id.to_s)\n\t \tredirect_to user_reminders_path(current_user), :notice => \"reminder created successfully\"\n\t else\n\t \tredirect_to user_reminders_path(current_user), :alert => \"reminder has failed to create for some reason\"\n\t end\n\tend",
"def calc(start, duration)\n return start if duration == 0\n a_day = SAME_DAY\n\n utc_start = to_utc(start)\n\n while duration != 0\n\n if a_day == PREVIOUS_DAY\n\t utc_start -= DAY\n\t a_day = SAME_DAY\n utc_start = Time.gm(utc_start.year, utc_start.month, utc_start.day,LAST_TIME_IN_DAY.hour, LAST_TIME_IN_DAY.min)\n\t week = find_weekpattern(utc_start)\n\t \n\t if week.working?(utc_start)\n\t duration += 1\n\t end\n else\n\t week = find_weekpattern(utc_start)\n end\n utc_start, duration, a_day = week.calc(utc_start, duration, a_day)\n end\n to_local(utc_start)\n end",
"def add_repeating_request(url, interval, content)\n @nodes << RepeatingRequest.new(page_config, url, interval, content)\n end",
"def factorials_rec(num)\n return [1] if num == 1\n factorials_rec(num-1) + [(1...num).to_a.reduce(:*)]\nend",
"def tail_rec_factorial(n)\n return tail_rec_factorial_(n, 1)\nend",
"def duplicate()\n duplicate_week=Week.new(@start,@finish)\n duplicate_values=Array.new(@values.size)\n @values.each_index {|index|\n duplicate_values[index]=@values[index].duplicate\n }\n duplicate_week.values=duplicate_values \n duplicate_week.days=@days\n duplicate_week.start=@start\n duplicate_week.finish=@finish\n duplicate_week.week_total=@week_total\n duplicate_week.total=@total\n duplicate_week.refresh\n return duplicate_week\n end"
] |
[
"0.66744834",
"0.6583623",
"0.6312478",
"0.6312478",
"0.6079936",
"0.60001713",
"0.5985342",
"0.595669",
"0.5955776",
"0.5936313",
"0.57971424",
"0.57487583",
"0.57210255",
"0.5664733",
"0.56121784",
"0.56121784",
"0.56100047",
"0.5603608",
"0.55753374",
"0.5529704",
"0.5525787",
"0.54696476",
"0.54687196",
"0.54104835",
"0.53779584",
"0.5346588",
"0.5336035",
"0.52690285",
"0.5244526",
"0.5240157",
"0.521294",
"0.5207643",
"0.5185024",
"0.51560116",
"0.5148128",
"0.51398844",
"0.5113463",
"0.5105687",
"0.5102854",
"0.50875443",
"0.50466025",
"0.504307",
"0.5031016",
"0.5016198",
"0.49852842",
"0.49618405",
"0.49502268",
"0.49413416",
"0.4887683",
"0.4871348",
"0.4871348",
"0.48689726",
"0.4842405",
"0.48384932",
"0.48379153",
"0.48341548",
"0.48290935",
"0.4827046",
"0.48161456",
"0.48032907",
"0.47870043",
"0.47705632",
"0.47585443",
"0.47487494",
"0.47269815",
"0.47041622",
"0.46884885",
"0.4687793",
"0.4672661",
"0.46655762",
"0.46603528",
"0.4636782",
"0.46272367",
"0.46184647",
"0.46142158",
"0.46137673",
"0.46099135",
"0.46053562",
"0.4605155",
"0.46049154",
"0.46044585",
"0.46042404",
"0.45924437",
"0.45893952",
"0.45874098",
"0.4583987",
"0.4552224",
"0.45514166",
"0.45376658",
"0.45368537",
"0.453574",
"0.4528788",
"0.45205492",
"0.45064238",
"0.45049396",
"0.4500594",
"0.4498878",
"0.44934255",
"0.4483654",
"0.44758183",
"0.44748646"
] |
0.0
|
-1
|
Create a hourly recurrence.
|
def hourly(options = {})
branch options.merge(every: :hour)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def schedule_recurring_task_creation(task)\n recurring_scheduler = Scheduler.new\n @recurring_schedulers << recurring_scheduler\n\n recurring_scheduler.schedule.every \"#{Helpers.convert_frequency_to_seconds(task.frequency).to_s}s\" do\n new_task = Task.new\n new_task.description = task.description\n new_task.frequency = task.frequency\n new_task.creation_date = Time.now.getlocal\n new_task.target_date = Helpers.calculate_task_target_date(\n new_task.creation_date,\n new_task.frequency\n )\n new_task.recurring_scheduler_id = recurring_scheduler.id\n\n new_task.create_reminder_notification\n new_task.create_failed_notification\n\n add_task(new_task)\n end\n end",
"def add_recurrence(type: :week, on: on = nil, at: at = nil)\n type = type.to_sym\n unless [:week, :day].include? type\n raise \"Type must be either :week or :day\"\n end\n if type == :week and (on.nil? or (on.is_a?(Array) and on.empty?))\n raise \"Weekdays must be specified when selecting the :week type\"\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if self.schedule.nil?\n schedule = Montrose::Schedule.new\n end\n if at.nil?\n raise \"Time must be specified in parameter 'at'\"\n else\n schedule.add Montrose.every(type, on: on, at: at).starts(created_at)\n self.write_attribute(self.class.schedulable_attribute, schedule)\n end\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def make_constant_schedule(name, temperature)\n s = OpenStudio::Model::ScheduleRuleset.new(@model)\n s.setName(name)\n s.defaultDaySchedule.addValue(OpenStudio::Time.new(\"24:00:00\"), OpenStudio::convert(temperature, \"F\", \"C\").get)\n\ts\n end",
"def add_hours(hours = 1)\n hours = hours.to_i\n cur_hour = @t_hour\n next_hour = cur_hour + hours\n \n if next_hour >= 24\n @t_hour = 0\n self.add_days(1)\n hours_left = (hours - 1) - (24 - cur_hour)\n self.add_hours(hours_left) if hours_left > 0\n elsif next_hour < 0\n @t_hour = 23\n self.add_days(-1)\n hours_left = hours + cur_hour + 1\n self.add_hours(hours_left) if hours_left < 0\n else\n @t_hour = next_hour\n end\n \n return self\n end",
"def hour()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Hour::HourRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def hour() end",
"def generate_assistances_for_one_day\n [8, 13, 15, 18].each_with_index do |hour, index|\n create(:assistance, \n happening_at: assistance_day.change(hour: hour),\n employee: employee,\n kind: index.even? ? 'in' : 'out')\n end\n end",
"def schedule_repetition\n self.due = Date.today + interval\n self.studied_at = Date.today\n end",
"def new_schedule(*args)\n if !args.all? { |e| e.is_a?(Integer) && e >= 0 && e <= 6 }\n return \"Please enter a number from 0-6 where each number represents a day of the week. 0 represents Sunday, 1 represents Monday, etc.\"\n end\n schedule1 = Schedule.new(self.first_event, duration: self.duration_mins.minutes )\n schedule1.add_recurrence_rule Rule.weekly.day(args)\n self.schedule = schedule1\n self.save!\n end",
"def weekly_time_generator(args = {:start_time => Time.now, :end_time => nil, :cron => ''})\n begin\n return [] if args[:cron].blank?\n\n # get cron as hash\n cron = cron_date args[:cron]\n\n # get the first value of the cron which is an integer and the pevious index\n # ex: cron = '41 * * * *' - we want to know that it starts every hour (prev index before the number) in the 41-st minute\n for k, v in cron do\n at = v\n break if v.class == 'Fixnum'\n # break in ruby continues the last iteration..\n every = k if v == '*'\n end\n\n changed_time = start_time = cron_generate_date args[:cron], args[:start_time]\n end_time = args[:end_time]\n\n # end_time is nil?\n end_time = Time.now.end_of_week if !end_time.respond_to? :year\n # end_time should not be longer than the end of this week\n end_time = end_time > start_time.end_of_week ? start_time.end_of_week : end_time\n\n all = []\n while changed_time <= end_time\n all << changed_time #changed_time.strftime(\"%d.%m.%Y %H:%M\")\n changed_time += 1.send(every)\n end\n\n all\n\n rescue => ex\n send_mail \"#{ex.class}: #{ex.message}. args: #{args}\" \n end\n\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def createDailyWins(contest,cp)\n cdate = contest.start_date.to_date\n prize_per_day = 2\n while cdate <= contest.end_date.to_date\n for i in (1..prize_per_day)\n time = \"#{(0..23).to_a.sample}:#{(0..59).to_a.sample}:#{(0..59).to_a.sample} Rome\"\n wintime = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" \"+ time)\n wintime_end = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" 23:59:59\")\n \n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n while Instantwin.where(\"unique_id=?\",unique_id).present?\n @hash_counter += 1\n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n end\n \n iw = Instantwin.new\n iw.contest_periodicity_id = cp.id\n iw.title = \"Daily\"\n iw.time_to_win_start = wintime\n iw.time_to_win_end = wintime_end\n iw.unique_id = unique_id\n iw.save\n @hash_counter += 1\n end\n cdate += 1\n end\n end",
"def next_meeting(after_time = Time.now.utc )\n # puts \"Looking up next meeting after #{after_time}\"\n if recurrence_frequency.blank?\n return start_time\n end\n\n if after_time < start_time\n return start_time\n end \n\n after_time = after_time.local_from_utc(self.time_zone) \n\n\n # Advance the starting time in the case when it falls after the beginning of\n # a meeting on the same day. We do this so that we can use \"day precision\"\n # (PDate.day) in the Runt library instead of \"minute precision\" (PDate.min),\n # which performs terribly.\n start_time = start_time_local\n if(after_time.hour > start_time.hour or ( after_time.hour == start_time.hour and after_time.min > start_time.min))\n after_time = after_time + 1.day\n after_time = Time.gm(after_time.year, after_time.month, after_time.day, 0, 0)\n end\n\n case recurrence_frequency\n when 'daily'\n end_time = after_time + 25.hours \n # after_time -= 1.day\n start_date = PDate.day(after_time.year, after_time.month, after_time.day , after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'weekdays'\n # Make the range over 3 days so that Friday night searches will still turn\n # up Monday as the next day.\n end_time = after_time + 3.days\n start_date = PDate.day(after_time.year, after_time.month, after_time.day, after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'monthly'\n eom = (after_time + 40.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eom.year, eom.month, eom.day)\n when 'weekly'\n eow = (after_time + 8.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eow.year, eow.month, eow.day)\n when 'yearly'\n # Just doing \"after_time + 367.days\" results in a bit of a performance hit\n # as hundreds of days are compared. We'll try to narrow it a bit. Not too\n # much, because we don't have time to actually write unit tests and make\n # sure the narrowing code works. :) Which is why the comment is here.\n st = after_time + 250.days\n et = st + 150.days\n start_date = PDate.day(st.year, st.month, st.day)\n end_date = PDate.day(et.year, et.month, et.day)\n end \n # puts \" Range #{start_date.to_s} - #{end_date.to_s}\"\n d_range = DateRange.new(start_date, end_date)\n sched = Schedule.new\n event = Event.new((self.invitation.name rescue \"no name\"))\n sched.add(event,self.runt_expression)\n dates = sched.dates(event,d_range)\n\n next_mtg = dates.first\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, start_time_local.hour, start_time_local.min)\n result = nil\n begin\n result = next_mtg_time.local_to_utc(self.time_zone)\n rescue TZInfo::PeriodNotFound\n # This only happens when the time is during the one hour which is skipped\n # during the transition to DST. For example, only on Sun Mar 08 02:15:00\n # (see ticket #744).\n next_hour = start_time_local.hour + 1\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, next_hour, start_time_local.min)\n retry\n end\n return result\n end",
"def recurring; end",
"def load_hours\n @day = Schedule.first\n @hours = Array.new(48)\n\n @hours[0] =@day.h0\n @hours[1] =@day.h1\n @hours[2] =@day.h2\n @hours[3] =@day.h3\n @hours[4] =@day.h4\n @hours[5] =@day.h5\n @hours[6] =@day.h6\n @hours[7] =@day.h7\n @hours[8] =@day.h8\n @hours[9] =@day.h9\n @hours[10]=@day.h10\n @hours[11]=@day.h11\n @hours[12]=@day.h12\n @hours[13]=@day.h13\n @hours[14]=@day.h14\n @hours[15]=@day.h15\n @hours[16]=@day.h16\n @hours[17]=@day.h17\n @hours[18]=@day.h18\n @hours[19]=@day.h19\n @hours[20]=@day.h20\n @hours[21]=@day.h21\n @hours[22]=@day.h22\n @hours[23]=@day.h23\n @hours[24]=@day.h24\n @hours[25]=@day.h25\n @hours[26]=@day.h26\n @hours[27]=@day.h27\n @hours[28]=@day.h28\n @hours[29]=@day.h29\n @hours[30]=@day.h30\n @hours[31]=@day.h31\n @hours[32]=@day.h32\n @hours[33]=@day.h33\n @hours[34]=@day.h34\n @hours[35]=@day.h35\n @hours[36]=@day.h36\n @hours[37]=@day.h37\n @hours[38]=@day.h38\n @hours[39]=@day.h39\n @hours[40]=@day.h40\n @hours[41]=@day.h41\n @hours[42]=@day.h42\n @hours[43]=@day.h43\n @hours[44]=@day.h44\n @hours[45]=@day.h45\n @hours[46]=@day.h46\n @hours[47]=@day.h47\n\n return @hours\n end",
"def add_time(hour: nil, proj: nil, date: nil, custom_num: nil, fill_value: nil, note: nil, costcodes: nil)\n # check if day already found\n day = self.days.where(:date => date).first\n if day\n result = day.add_time(hour: hour, proj: proj, date: date, custom_num: custom_num, fill_value: fill_value, note: note, cost_codes: costcodes)\n else\n day = Day.new\n result = day.add_time(hour: hour, proj: proj, date: date, custom_num: custom_num, fill_value: fill_value, note: note, cost_codes: costcodes)\n self.days << result[:day]\n end\n refresh_project_total(result: result, proj: proj)\n save\n publish(:add_time_successful, result)\n end",
"def set_hour_created\n self.hour_created = Time.now.in_time_zone('Eastern Time (US & Canada)').hour\n end",
"def create\n @time_slot = TimeSlot.new(params[:time_slot])\n @time_slot.user_id = current_identity.user_id\n\t@recurrence_array = []\n respond_to do |format|\n if @time_slot.save\n format.html { redirect_to @time_slot, notice: 'Time slot was successfully created.' }\n format.json { render json: @time_slot, status: :created, location: @time_slot }\n else\n format.html { render action: \"new\" }\n format.json { render json: @time_slot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def daily_midnight\n logger.info \" daily_midnight\"\n PersistStatsJob.create({})\n Gift.send_expiration_reminders(5)\n Gift.send_expiration_reminders(3)\n Gift.send_expiration_reminders(1)\n end",
"def fill_schedule\n @schedule.each do |key,value|\n (6..20).each { |n| @schedule[key][\"#{n}:30 - #{n+1}:30\"] = \"0\" }\n end\n end",
"def schedule_updates\n schedule_updates_in(24.hours, 48.hours)\n end",
"def build_hash hash, date, worked_hours, departur_hour\n hash[\"#{date.strftime(\"%F\")}\"] = {total: worked_hours, arrival_hour: date, departur_hour: departur_hour}\n hash[:total_worked] += worked_hours\n hash[:total_days] += 1\n return hash\n end",
"def create(opts)\n @frequence = opts[:frequence] if opts[:frequence].in? Recurrence::FREQUENCES\n @monthly = array_to_integer(opts[:monthly])\n @count = to_integer(opts[:count])\n @until = string_to_date(opts[:until])\n self\n end",
"def create60ggWins(contest,cp)\n beginning_date = contest.start_date.to_date\n day_range = (contest.end_date.to_date - contest.start_date.to_date).to_i\n total_prizes = 10\n winner_inserted = 0\n \n while winner_inserted < total_prizes\n offest_day_win = (0..day_range).to_a.sample\n winday = beginning_date + offest_day_win\n winhour = \"#{(0..23).to_a.sample}:#{(0..59).to_a.sample}:#{(0..59).to_a.sample} Rome\"\n wintime = Time.parse(winday.strftime(\"%Y-%m-%d\") +\" \"+ winhour)\n \n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n while Instantwin.where(\"unique_id=?\",unique_id).present?\n @hash_counter += 1\n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n end\n \n iw = Instantwin.new\n iw.contest_periodicity_id = cp.id\n iw.title = \"Random\"\n iw.time_to_win_start = wintime\n iw.unique_id = unique_id\n iw.save\n winner_inserted += 1\n @hash_counter += 1\n end\n end",
"def grandclock(presenthour,&block)\n \n for i in (1..presenthour)\n block.call\n end\n \nend",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def date_calc(start,day_start,day_duration,round)\n time=start;schedule=[]\n round.size.times do |r|\n#print day_start+day_duration;print \"\\n\"\n if time >= day_start + day_duration\n#print time;print \"\\n\"\n time=day_start+1.day\n day_start = time\n end\n schedule[r] = time\n time+=HEAT_INTERVAL\n end\n\n return schedule\n end",
"def add_occurrences!(event, at = [])\n Array(at).each do |time|\n OccurrenceEntry.create!(:post_id => id, :label => event, :at => time)\n end\n end",
"def initialize(hours)\n @hatched = hours\n end",
"def create\n\n unless params[:hour][:start_date].nil?\n params[:hour][:start_date] = DateTime.strptime(params[:hour][:start_date], \"%d/%m/%Y %I:%M%p\") unless ((DateTime.parse(params[:hour][:start_date]) rescue ArgumentError) == ArgumentError)\n end\n \n unless params[:hour][:end_date].nil?\n params[:hour][:end_date] = DateTime.strptime(params[:hour][:end_date], \"%d/%m/%Y %I:%M%p\") unless ((DateTime.parse(params[:hour][:end_date]) rescue ArgumentError) == ArgumentError)\n end\n \n p params[:hour][:start_date]\n p params[:hour][:end_date]\n sleep 5\n @hour = Hour.new(params[:hour])\n\n respond_to do |format|\n if @hour.save\n format.html { redirect_to @hour, notice: t(:successfully_created) }\n format.json { render json: @hour, status: :created, location: @hour }\n else\n format.html { render action: \"new\" }\n format.json { render json: @hour.errors, status: :unprocessable_entity }\n end\n end\n end",
"def addHour(hour)\n addMin(hour * 60) ;\n end",
"def time_slots\n\n # you can book by the hour, and you can stay for an hour\n reservation_interval = 1.hour\n\n # Determine the earliest time we will allow reservation\n # It can't be in the past, we'll start 10 minutes from now\n start_time = Time.zone.now + 10.minutes\n # Then we have to round to the next hour block\n start_time = Time.zone.at( (start_time.to_f / reservation_interval).ceil * reservation_interval )\n # Then, if we are still earlier than opening hour, just use the opening hour\n # We can use the 'max' Array method\n start_time = [start_time, start_time.change(hour: opening_hour)].max\n\n # Determine the furthest in the future we will allow reservations\n end_time = (start_time + 3.days).change(hour: closing_hour)\n\n # Now, we want to make a list of every hour between our start_time and our end_time\n # For this we can use a begin... end while condition loop.\n # We'll start with an empty array that will hold all the hours,\n # and a variable to hold each hour, which we will keep increasing by 1 hour, and then add to our array\n # Our loop condition will have us stop looping once we've reached the end time\n\n all_times = []\n a_time = start_time\n\n begin\n\n # add this time to our list of times\n all_times << a_time\n\n # increment the time\n a_time += reservation_interval\n\n # Once we get to closing time, we have to skip ahead to the next day's opening\n # That way you can't make a reservation at 2am\n if (a_time + reservation_interval) > a_time.change(hour: closing_hour)\n a_time = (a_time + 1.day).change(hour:opening_hour)\n end\n\n end while a_time < end_time\n\n all_times\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def hourly\n (0..23).collect { |h| redis.get(\"#{prefix_hourly}:#{Time.now.year}:#{Time.now.month}:#{Time.now.day}:#{h}\").to_i }\n end",
"def create\n @day = params[:day]\n @month = params[:month]\n @year = params[:year]\n @date = @day + \" \" + Date::MONTHNAMES[@month.to_i] + \" \" + @year\n lessons = Array.new\n dayandtime = Array.new\n lesson_objects = Array.new\n t = Array.new\n for i in 0..9\n unless params[(\"hour\"+i.to_s).to_sym] == \"hrs\"\n if params[(\"min\"+i.to_s).to_sym] == \"mins\"\n params[(\"min\"+i.to_s).to_sym] = \"00\"\n end\n lessons[i] = {:hour => params[(\"hour\"+i.to_s).to_sym], :min => params[(\"min\"+i.to_s).to_sym]}\n #dayandtime[i] = Time.local_time(@year.to_i, @month.to_i, @day.to_i, (lessons[i][:hour]).to_i, (lessons[i][:min]).to_i)\n t[i] = DateTime.civil(@year.to_i, @month.to_i, @day.to_i, (lessons[i][:hour]).to_i, (lessons[i][:min]).to_i)\n if Time.utc(t[i].year, t[i].month, t[i].day, t[i].hour, t[i].min).in_time_zone(\"Europe/Berlin\").dst?\n t[i] = Time.utc(t[i].year, t[i].month, t[i].day, t[i].hour-2, t[i].min)\n else\n t[i] =Time.utc(t[i].year, t[i].month, t[i].day, t[i].hour-1, t[i].min)\n end\n lesson_objects.push({:name => t[i].in_time_zone(\"Europe/Berlin\").to_s(:time),\n :start_at => t[i].to_formatted_s(:db),\n :end_at => (t[i] + (60*60)).to_formatted_s(:db),\n :color => \"#2E8B57\"})\n #lesson_objects.push({:name => dayandtime[i].to_s(:time),\n # :start_at => dayandtime[i].utc.to_formatted_s(:db),\n # :end_at => (dayandtime[i] + (60*60)).utc.to_formatted_s(:db),\n # :color => \"#2E8B57\"})\n end\n end\n lessons_object = Lesson.create(lesson_objects)\n recently_created_lessons = Lesson.find(:all).find_all{|l| l.created_at.to_datetime >= Time.now-7200}\n recently_created_after_school_lessons = recently_created_lessons.find_all{|t| t.start_at.to_datetime.hour > 14 || (t.start_at.to_datetime.hour > 13 && t.start_at.to_datetime.min > 29)}\n new_lessons_after_1530 = lesson_objects.find_all{|t| t[:start_at].to_datetime.hour > 14 || (t[:start_at].to_datetime.hour > 13 && t[:start_at].to_datetime.min > 29)}\n if new_lessons_after_1530.length > 0 && recently_created_after_school_lessons.length <= new_lessons_after_1530.length\n students = Student.find(:all).find_all{|s| s.after_school==true}\n students.each do |student|\n email_school_children(student)\n end\n end\n \n redirect_to(:controller => \"teaching\", :action => \"studentzone\", :year => @year, :month => @month)\n\n end",
"def add_hourly_params()\n\n current_utc_hour = Time.now.utc.strftime(\"%H\").to_i\n\n if current_utc_hour > 0\n last_utc_hour = current_utc_hour - 1\n end\n\n myhash = Hash.new\n myhash[\"since\"] = Time.now.utc.strftime(\"%Y-%m-%dT00:00:00Z\")\n myhash[\"hours\"] = last_utc_hour.to_s\n\n return myhash\nend",
"def hours(num)\n t = current_time + num * SECONDS_IN_HOUR\n {\n type: :datetime,\n value: t.iso8601\n }\n end",
"def each_hours(n=1, offset=0, dur=1)\n each_seconds(n*60*60, offset*60*60, dur*60*60)\n end",
"def rational_hour(seconds); end",
"def generate_daytime_distribution \n \n end",
"def create\n @operation_hours = OperationHour.paginate(:page => params[:page], :per_page => 30).order('updated_at DESC')\n @operation_hour = OperationHour.create(params[:operation_hour])\n end",
"def grandfather_clock &block\n hour = (Time.new.hour + 11)%12 + 1\n\n hour.times(&block)\nend",
"def recurrence_at\n unless @recurrence_at.nil?\n return @recurrence_at\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if schedule.nil?\n return nil\n end\n # montrose stores the \"at\" times in an array with\n # time[0] = hour\n # time[1] = mins\n # time[2] = secs\n schedule.rules.first.to_h[:at].map{|time| [time[0].to_s.rjust(2,\"0\"),time[1].to_s.rjust(2,\"0\")].join(\":\")}.join(\", \")\n end",
"def schedule_updates\n schedule_update_in(48.hours)\n end",
"def add_to_schedule(string)\n string = correct_format(string)\n parts = string.split(\"-\")\n hour1 = Integer(parts[0].split(\":\")[0])\n hour2 = Integer(parts[1].split(\":\")[0])\n if hour2 == hour1 + 1\n @schedule[parts[2]][\"#{parts[0]} - #{parts[1]}\"] = \"#{@rails_id}\" #\"1\" #schedule[parts[2]].push(\"#{parts[0]}-#{parts[1]}\")\n else \n while hour1 != hour2\n @schedule[parts[2]][\"#{hour1}:30 - #{hour1+1}:30\"] = \"#{@rails_id}\" #\"1\"\n hour1 = hour1+1\n end\n end\n return parts\n end",
"def hours\n Thread.current[:datet_mode] = :hours\n return self\n end",
"def grandfather_clock &block\r\n hour = (Time.new.hour + 11)%12 + 1\r\n\r\n hour.times(&block)\r\nend",
"def lazy_hour=(newhour)\n newhour = newhour.to_f\n \n #Add days for every 24 hours given.\n if newhour > 24 or newhour < 0\n days = (newhour.to_f / 24.0).floor\n newhour -= (days.to_f * 24.0)\n self.add_days(days)\n end\n \n #Convert any decimals to setting minute.\n diff = newhour - newhour.floor\n self.lazy_min = diff * 60 if diff > 0.0\n \n #Set the actual hour.\n self.hour = newhour.floor\n \n self\n end",
"def recurrence\n unless read_attribute(:recurrence).empty?\n IceCube::Rule.from_hash(read_attribute(:recurrence))\n end\n end",
"def initialize(with_time=true)\n @with_time\n @day = Day.new # the time schedule for the mechanic\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def hours; self * HOUR; end",
"def hours; self * HOUR; end",
"def add_oneshot_at exact_time, timer_proc\n return nil unless timer_proc\n\n timer = Timer.new :timers => self, :exact_time => exact_time, :periodical => false, :timer_proc => timer_proc\n add timer\n timer\n end",
"def succ\n next_hour = Hour.new(\"12 AM\")\n\n next_time = (@hour + 1) % 24\n next_hour.instance_eval { @hour = next_time }\n #puts \" succ called: next_hour is #{next_hour}, #{@hour}, #{next_time}\"\n next_hour\n end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def initialize(args)\n @name = args[\"name\"]\n @start_date = args[\"start_date\"]\n @end_date = args[\"end_date\"]\n @location = args[\"location\"]\n @description = args[\"description\"]\n\n @start_time = args[\"start_time\"] if args.include? \"start_time\"\n\n @end_time = args[\"end_time\"] if args.include? \"end_time\"\n\n @is_repeated = true if args.include? \"repetition_freq\" and args[\"repetition_freq\"] != \"\"\n @has_alarm = true if args.include? \"alarm_time_unit\" and args[\"alarm_time_unit\"] != \"\"\n\n if args.include? \"wholeday\"\n @is_all_day = true\n else\n @is_all_day = false\n end\n\n if @start_date.include? \"/\"\n @is_us_format = true\n else\n @is_us_format = false\n end\n\n # Valid values are between 1 and 2147483647, excluding 0\n # \"asdf\".to_i -> 0\n if @is_repeated\n @repetition_freq = args[\"repetition_freq\"]\n value = args[\"repetition_interval\"]\n if value == \"\" or value.to_i > 2147483647 or value.to_i < 1\n @repetition_interval = \"1\"\n else\n @repetition_interval = value\n end\n @repetition_freq = \"YEARLY\" if @repetition_freq == \"Years\" || @repetition_freq == \"Jahre\"\n @repetition_freq = \"MONTHLY\" if @repetition_freq == \"Months\" || @repetition_freq == \"Monate\"\n @repetition_freq = \"WEEKLY\" if @repetition_freq == \"Weeks\" || @repetition_freq == \"Wochen\"\n @repetition_freq = \"DAILY\" if @repetition_freq == \"Days\" || @repetition_freq == \"Tage\"\n end\n\n if @has_alarm\n @alarm_time_unit = args[\"alarm_time_unit\"]\n alarm_value = args[\"alarm_time_value\"]\n if alarm_value == \"\" or alarm_value.to_i > 2147483647 or alarm_value.to_i < 1\n @alarm_time_value = \"1\"\n else\n @alarm_time_value = alarm_value\n end\n @alarm_time_unit = \"D\" if @alarm_time_unit == \"Day(s)\" || @alarm_time_unit == \"Tag(e)\"\n @alarm_time_unit = \"H\" if @alarm_time_unit == \"Hour(s)\" || @alarm_time_unit == \"Stunde(n)\"\n @alarm_time_unit = \"M\" if @alarm_time_unit == \"Minute(s)\" || @alarm_time_unit == \"Minute(n)\"\n end\n\n end",
"def create\n if(params[:oper] && params[:oper] != '')\n timecard = Timecard.find(params[:timecard_id])\n # the hour the we should use\n if(params[:oper] == 'edit')\n hour = timecard.hours.find(params[:id])\n # save a historical\n old_information = \"Description:#{hour.description}-----Initial Time:#{hour.initial_time}-----End Time:#{hour.end_time}\" if(hour)\n else\n hour = Hour.new\n end\n if(hour)\n hour.description = params[:description]\n hour.date = params[:date]\n hour.intime = params[:initial_time]\n hour.entime = params[:end_time]\n hour.timecard = timecard\n if(hour.save)\n if(old_information)\n new_value = \"Description:#{hour.description}-----Initial Time:#{hour.initial_time}-----End Time:#{hour.end_time}\" \n HistoricalHour.create(:old_value=>old_information, :new_value=>new_value, :hour_id=>hour.id, :user=>current_member)\n end\n render :json=>\"{\\\"success\\\":true,\\\"message\\\":\\\"Great! you just added an hour in your timesheet.\\\"}\"\n else\n render :json=>\"{\\\"success\\\":false,\\\"message\\\":\\\"#{first_error(hour)}\\\"}\"\n end\n else\n render :json=>\"{\\\"success\\\":false,\\\"message\\\":\\\"Oops, you tried to do an invalid operation.\\\"}\"\n end\n else\n render :json=>\"{\\\"success\\\":false,\\\"message\\\":\\\"Oops, you tried to do an invalid operation.\\\"}\"\n end\n end",
"def weekly_pay(rate, hours = 40)\n hours * rate\nend",
"def create_recurrences(transaction)\n CreateRecurrencesJob.perform_later(\n transaction.class.to_s,\n transaction.id.to_s\n )\n end",
"def initialize(start,finish,type=1)\n hours_in_days_in_week=[24,24,24,24,24,24,24]\n @days=hours_in_days_in_week.size\n @values=Array.new(7) {|index| Day.new(type)}\n @start=DateTime.new(start.year,start.month,start.day)\n @finish=DateTime.new(finish.year,finish.month,finish.day)\n \n set_attributes\n end",
"def next_scheduled_at\n reviewed_at + (24.hours * next_interval)\n end",
"def save_hours\n @day = Schedule.find(params[:monthday])\n\n @pitch.schedule.h0 = hours[0]\n @pitch.schedule.h1 = hours[1]\n @pitch.schedule.h2 = hours[2]\n @pitch.schedule.h3 = hours[3]\n @pitch.schedule.h4 = hours[4]\n @pitch.schedule.h5 = hours[5]\n @pitch.schedule.h6 = hours[6]\n @pitch.schedule.h7 = hours[7]\n @pitch.schedule.h8 = hours[8]\n @pitch.schedule.h9 = hours[9]\n @pitch.schedule.h10 = hours[10]\n @pitch.schedule.h11 = hours[11]\n @pitch.schedule.h12 = hours[12]\n @pitch.schedule.h13 = hours[13]\n @pitch.schedule.h14 = hours[14]\n @pitch.schedule.h15 = hours[15]\n @pitch.schedule.h16 = hours[16]\n @pitch.schedule.h17 = hours[17]\n @pitch.schedule.h18 = hours[18]\n @pitch.schedule.h19 = hours[19]\n @pitch.schedule.h20 = hours[20]\n @pitch.schedule.h21 = hours[21]\n @pitch.schedule.h22 = hours[22]\n @pitch.schedule.h23 = hours[23]\n @pitch.schedule.h24 = hours[24]\n @pitch.schedule.h25 = hours[25]\n @pitch.schedule.h26 = hours[26]\n @pitch.schedule.h27 = hours[27]\n @pitch.schedule.h28 = hours[28]\n @pitch.schedule.h29 = hours[29]\n @pitch.schedule.h30 = hours[30]\n @pitch.schedule.h31 = hours[31]\n @pitch.schedule.h32 = hours[32]\n @pitch.schedule.h33 = hours[33]\n @pitch.schedule.h34 = hours[34]\n @pitch.schedule.h35 = hours[35]\n @pitch.schedule.h36 = hours[36]\n @pitch.schedule.h37 = hours[37]\n @pitch.schedule.h38 = hours[38]\n @pitch.schedule.h39 = hours[39]\n @pitch.schedule.h40 = hours[40]\n @pitch.schedule.h41 = hours[41]\n @pitch.schedule.h42 = hours[42]\n @pitch.schedule.h43 = hours[43]\n @pitch.schedule.h44 = hours[44]\n @pitch.schedule.h45 = hours[45]\n @pitch.schedule.h46 = hours[46]\n @pitch.schedule.h47 = hours[47]\n\n return hours\n end",
"def start_periodic_timers; end",
"def start_periodic_timers; end",
"def time_slots\n collection=[]\n start_time=Time.now.beginning_of_hour\n end_time=Time.now.tomorrow.midnight-1.hour\n time=start_time\n\n while time < end_time\n collection<<[time.beginning_of_hour.hour, time.beginning_of_hour]\n time=time+1.hour\n end\n\n collection\n end",
"def hour\n set_function_and_argument(:hour, nil)\n end",
"def generate_schedule(courses)\n num_days = 5\n num_time_slots = 111 # num of 5 minute intervals from 8:00am - 5:15pm\n schedule = Array.new(num_time_slots) { Array.new(num_days, 0)} # important !!!!!\n \n courses.each do |course|\n if course.meetingtime_start.nil? or course.meetingtime_end.nil? or \n course.meeting_days.nil?\n next\n end\n \n start_time = parse_time(course.meetingtime_start)\n end_time = parse_time(course.meetingtime_end)\n days = parse_day(course.meeting_days)\n schedule = insert_course(schedule, days, start_time, end_time)\n end\n \n # print_schedule(schedule)\n \n return schedule\n end",
"def create\n @schedule = Schedule.new(schedule_params)\n puts 'yoooo'\n rangeStart = Date.strptime(\"#{schedule_params['start(2i)']}/#{schedule_params['start(3i)']}/#{schedule_params['start(1i)']}\", \"%m/%d/%Y\")\n rangeEnd = Date.strptime(\"#{schedule_params['end(2i)']}/#{schedule_params['end(3i)']}/#{schedule_params['end(1i)']}\", \"%m/%d/%Y\")\n\n @shifts = Shift.all\n @employees = Employee.all\n\n days = %w(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)\n\n availability = [\n :mon_start,\n :mon_end,\n :tues_start,\n :tues_end,\n :wed_start,\n :wed_end,\n :thurs_start,\n :thurs_end,\n :fri_start,\n :fri_end,\n :sat_start,\n :sat_end,\n :sun_start,\n :sun_end\n ]\n\n @recent_schedule = Schedule.order(\"created_at\").last\n\n if @recent_schedule.blank?\n new_schedule_id = 1\n else\n new_schedule_id = @recent_schedule.schedule_id + 1\n end\n\n days.each_with_index do |dayName, dayOfTheWeek|\n @shifts.each do |s|\n\n s.active_days.split(\",\")\n\n if( s.active_days.include? days[dayOfTheWeek] )\n startTime = time_to_int(s.start)\n endTime = time_to_int(s.end)\n\n @employees.each do |e|\n employee_start_time = time_to_int(e[availability[dayOfTheWeek]])\n employee_end_time = time_to_int(e[availability[dayOfTheWeek + 1]])\n\n if employee_start_time.blank? == false && employee_end_time.blank? == false\n if(startTime >= employee_start_time && endTime <= employee_end_time)\n @schedule = Schedule.create(:schedule_id => new_schedule_id, :shift_id => s.id, :employee => e.name, :date => Time.now, :start => rangeStart, :end => rangeEnd)\n end\n end\n\n end\n end\n end\n end\n\n respond_to do |format|\n if @schedule.save\n format.html { redirect_to :action => \"show\", :id => new_schedule_id}\n format.json { render :show, status: :created, location: @schedule }\n else\n format.html { render :new }\n format.json { render json: @schedule.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @staffhour = Staffhour.new(staffhour_params)\n \n @accruel_rate = Accruel_rate.find(@staffhour.accruel_rate_id).rate\n @wk_accrued_hrs = @staffhour.hours * @accruel_rate\n \n @staffhour.update(wk_accrued_hours: @wk_accrued_hrs)\n @staffhour.save!\n\n respond_to do |format|\n if @staffhour.save\n format.html { redirect_to @staffhour, notice: 'Staffhour was successfully created.' }\n format.json { render :show, status: :created, location: @staffhour }\n else\n format.html { render :new }\n format.json { render json: @staffhour.errors, status: :unprocessable_entity }\n end\n end\n end",
"def future_single_event_creation\n self.schedule.next_occurrences(12).each do |occurrence|\n # TODO: Hot-Fix for Bug #83, unti ice_cube's issue 84 is resolved\n occurrence = occurrence.without_ms\n\n if !self.schedule.extimes.map(&:to_i).include? occurrence.to_i\n SingleEvent.where(event_id: self.id,\n occurrence: occurrence,\n based_on_rule: true).first_or_create\n end\n end\n end",
"def generate_assistances_with_one_day_difference\n (0..2).each do |extra_day|\n create(:good_entry_assistance, \n happening_at: base_date + extra_day.days,\n employee: employee) \n end\n end",
"def create\n @inventory_template = InventoryTemplate.new(params[:inventory_template])\n # @inventory_template.restaurant = current_owner.restaurant\n\n @intervals = []\n 24.times do |h| \n 4.times do |m| \n if h<10 and m!=0\n @intervals << \"0#{h}:#{m*15}\" \n elsif h<10 and m==0\n @intervals << \"0#{h}:00\" \n elsif h>=10 and m!=0\n @intervals << \"#{h}:#{m*15}\" \n elsif h>=10 and m==0\n @intervals << \"#{h}:0#{m*15}\" \n else\n @intervals << \"#{h}:#{m*15}\" \n end\n end\n end\n @intervals << \"24:00\"\n\n @intervals.each do |interval| \n quan = params[:inventory_template][:quantity_available][\"#{@intervals.index(interval)}\".to_s]\n unless interval == \"24:00\" or quan.to_i == 0\n \n @inventory_template = InventoryTemplate.new(inventory_template_group_id: params[:inventory_template][:inventory_template_group_id])\n # @inventory_template = InventoryTemplate.new(name: params[:inventory_template][:name])\n # @inventory_template.restaurant = current_owner.restaurant\n # @inventory_template.primary = params[:inventory_template][:primary]\n \n @inventory_template.start_time = interval\n @inventory_template.end_time = @intervals[@intervals.index(interval)+1]\n @inventory_template.quantity_available = quan\n\n @inventory_template.save\n end \n end \n\n redirect_to :back,\n notice: 'Inventory Template was successfully created.'#inventory_templates_path\n end",
"def initialize(hour, minute)\n set_time hour, minute\n end",
"def calc_next_run\n RunAtPeriodicJob.new(:name => self.name, :job => self.job, :run_at_minutes => self.run_at_minutes)\n end",
"def create_timing\n if @freak_number.present?\n self.timing_expression = @freak_number + \" \" + @freak_interval\n elsif @reactive_expression.present?\n self.timing_expression = @reactive_expression\n end\n self.timing_duration = \"\" if @until_radio == \"nodate\"\n self.timing_duration = @duration_number + \" \" + @duration_unit if @until_radio == \"date\" and self.timing_until.blank? and @duration_number and @duration_unit\n end",
"def grandfather_clock &block\n hour = Time.new.hour\n if hour >= 13\n hour = hour - 12\n end\n if hour == 0\n hour = 12\n end\n hour.times do\n block.call\n end\nend",
"def program(tasks, hour, &task)\n\ttasks[hour] = task\nend",
"def schedule\n \"#{frequency_quantity} #{frequency_type.name.pluralize} at #{execution_time}\"\n end",
"def occurrence_hash(default_duration) #:nodoc:\n date_time = self.to_ri_cal_date_time_value\n {:start => date_time,\n :end => date_time.advance(:hours => 24, :seconds => -1)}\n end",
"def create_new_sched(dr_hrly, hrly_base, offset)\n offset_hrly = dr_hrly.map { |x| x * offset }\n sched_hrly = [hrly_base, offset_hrly].transpose.map { |x| x.reduce(:+) }\n sched_hrly = sched_hrly.map { |i| UnitConversions.convert(i, 'F', 'C') }\n return sched_hrly\n end",
"def new_work_period(options = {})\n options.merge!({employee_id: id})\n EmployeeWorkPeriod.new(options)\n end",
"def initialize\n @tag_name = self.class.to_s.split(\"::\").last.downcase\n @schedule = IceCube::Schedule.new(1.month.ago.beginning_of_day)\n @schedule.add_recurrence_rule IceCube::Rule.daily\n # For example, add these if your schedule doesn't occur on weekends\n #@schedule.add_exception_rule IceCube::Rule.weekly.day(:saturday)\n #@schedule.add_exception_rule IceCube::Rule.weekly.day(:sunday)\n end",
"def initialize(hour, minute, second, interval)\n @hour = hour\n @minute = minute\n @second = second\n @interval = interval\n end",
"def business_hours_later( hours)\n now = Time.now # freeze it here for this cycle of call, or it keeps changing every second\n wanted = (hours.to_i.hours / 1.second) # convert hours to seconds\n available = available_work_seconds( now) # how much available today\n # if we have enough time today, just tell the time possible today\n # if we will run out of time today, check next working day, add run-over seconds to the start-of-day\n (available > wanted) ? ( now + wanted.seconds) : ( next_workday(now) + (wanted - available).seconds)\n end",
"def generate_schedule\n \tschedule = Array.new\n \tqueue = Array.new\n \tcurrent_job = nil\n \tcurrent_job_execution_time = 0\n\n \tfor time in 0...hyper_period\n \t\t# add released tasks to queue\n \t\tqueue += get_released_jobs time\n\n \t\t# give the current job credit for execution in last step\n \t\tcurrent_job_execution_time += 1 unless current_job.nil?\n\n \t\t#check if current task is finished\n \t\tif !!current_job and current_job[:task].worst_case_execution_time == current_job_execution_time\n \t\t\t#task is finished\n \t\t\tcurrent_job = nil\n \t\t\tcurrent_job_execution_time = 0\n \t\tend\n\n \t\t#find a task to execute\n \t\tif current_job.nil?\n \t\t\tcurrent_job = get_highest_priorty_task(queue)\n \t\t\tqueue.delete(current_job)\n \t\tend\n\n \t\t# if we are missing a deadline task set is not schedulable\n \t\tif !!current_job and time >= current_job[:deadline]\n \t\t\treturn nil\n \t\tend\n\n \t\t# add current job to schedule\n \t\tschedule.push(current_job.nil? ? 0 : current_job[:task].id)\n\n \t\t#log whats executing in this slot\n \t\t#puts \"Slot #{time + 1} \" + (current_job.nil? ? \"Idle\" : current_job[:task].name)\n \tend\n\n \t# if queue isn't empty, then return nil\n \treturn nil unless queue.empty?\n\n \t#return schedule\n \tschedule\n end",
"def schedule(hash)\n run_job = Proc.new do\n if hash['make_after'].to_i > 0\n EM::Timer.new(hash['make_after']) do\n self.storage.load(hash) { |hash| do_job(JR.make(hash)) }\n end\n else\n EM.next_tick do\n self.storage.load(hash) { |hash| do_job(JR.make(hash)) }\n end\n end\n end\n\n if hash['defer'] == 'true'\n EM.defer { run_job.call }\n else\n run_job.call\n end\n end",
"def seed_app_dining_periods\n start_hash = { 'Breakfast' => 8, 'Lunch' => 11, 'Dinner' => 16, 'Brunch' => 9, 'Late Night' => 20 }\n\n DiningOpportunity.all.each { |opp|\n DiningPlace.all.each { |dp|\n (0..6).each { |dow|\n start_hour = start_hash[opp.dining_opportunity_type]\n unless start_hour.blank?\n DiningPeriod.current_or_create_new(start_time: Time.now.change(hour: start_hour, min: rand(60)), end_time: Time.now.change(hour: start_hour + 3, min: rand(60)), day_of_week: dow, dining_opportunity_id: opp.id, dining_place_id: dp.id, institution_id: 1)\n end\n }\n }\n }\nend",
"def schedule(spec)\n @task.schedule = Cloud::Cycler::Schedule.parse(spec)\n end",
"def initialize(person, date)\n @person = person\n if (date.class == \"string\".class )\n\n @key_day = Date.strptime(date)\n else\n @key_day = date\n end\n week_begin = @key_day - @key_day.wday + 1\n week_end = @key_day - @key_day.wday + 7\n\n @items = {}\n tsi = TimesheetItem.find(:all, :conditions => [ \"hr_person_id = ? AND TO_DAYS(date) >= TO_DAYS(?) AND TO_DAYS(date) <= TO_DAYS(?)\", \n person, week_begin.strftime(\"%Y-%m-%d\"), week_end.strftime(\"%Y-%m-%d\") ])\n# raise week_begin.strftime + \"...\" + week_end.strftime\n\n @hours = 0\n tsi.each do | item |\n wday = item.date.wday() - 1\n if (wday == -1) then wday = 6 end\n if (@items [ wday ].nil?)\n @items[ wday ] = []\n end\n @items[ wday ].push(item)\n @hours = @hours + ((item.end - item.begin) / 3600)\n end\n end",
"def recurrence\n nil\n end",
"def grandfather_clock(&block)\n (Time.new.hour % 12).times do\n block.call\n end\nend",
"def advance_by_a_day\n scheduler = Scheduler.new(tasks, user_preferences)\n tasks_and_time = scheduler.call\n\n advanced_tasks = tasks_and_time.map do |task, time_to_advance|\n task.running_calculation ||= task.completed_hours\n task.running_calculation += time_to_advance\n task\n end\n\n @tasks = advanced_tasks.reject do |task|\n task.running_calculation >= task.estimated_hours\n end + tasks.reject do |task|\n advanced_tasks.map(&:id).include? task.id\n end\n\n tasks_and_time\n end",
"def hours\n \n end",
"def add_blocks_to_schedule(time_blocks, schedule, recurring)\n time_blocks.each do |block|\n day_of_week = block.split(\"_\")[0]\n time = block.split(\"_\")[1]\n start_time = Time.utc(\"2011\", nil, nil, time.split(\" - \")[0])\n end_time = Time.utc(\"2011\", nil, nil, time.split(\" - \")[1])\n \n if Day.exists?(day_of_week, schedule.id)\n day = Day.where(:name => day_of_week, :schedule_id => schedule.id).first\n else\n day = Day.new(:name => day_of_week, :schedule_id => schedule.id)\n day.save\n end\n \n if !TimeBlock.exists?(start_time, end_time, day.id, recurring)\n time_block = TimeBlock.new(:start_time => start_time, :end_time => end_time, :day_id => day.id, :recurring => recurring)\n time_block.save\n end\n end\n end"
] |
[
"0.6487369",
"0.6236406",
"0.62175435",
"0.6142382",
"0.59277886",
"0.58617777",
"0.5800348",
"0.5797229",
"0.5793554",
"0.5763702",
"0.5737585",
"0.5731232",
"0.5694806",
"0.5694206",
"0.56823105",
"0.565393",
"0.56336975",
"0.56027997",
"0.5570435",
"0.55280983",
"0.55270606",
"0.5482185",
"0.5457253",
"0.54566765",
"0.54406303",
"0.54369986",
"0.54283816",
"0.54253197",
"0.5417448",
"0.54028773",
"0.5399949",
"0.53944105",
"0.5374792",
"0.53589183",
"0.5352778",
"0.5344926",
"0.534157",
"0.5316008",
"0.53049797",
"0.5286097",
"0.5275847",
"0.52642536",
"0.5251024",
"0.52452046",
"0.52430046",
"0.5238405",
"0.5226841",
"0.5217208",
"0.52140236",
"0.52139926",
"0.52099377",
"0.5208112",
"0.51964664",
"0.5185824",
"0.5185824",
"0.51809865",
"0.51807827",
"0.516541",
"0.5157036",
"0.5144266",
"0.5136331",
"0.5136142",
"0.51337475",
"0.51286775",
"0.5117961",
"0.51147646",
"0.5109587",
"0.5106003",
"0.5106003",
"0.51044995",
"0.5101435",
"0.5094169",
"0.5087771",
"0.5086719",
"0.5084185",
"0.50792104",
"0.5077683",
"0.5070591",
"0.50680333",
"0.5059004",
"0.50575334",
"0.5057402",
"0.5052585",
"0.5050428",
"0.50486606",
"0.5047751",
"0.5043646",
"0.50333154",
"0.5019249",
"0.5017731",
"0.5014832",
"0.50109535",
"0.5004871",
"0.50047857",
"0.5002882",
"0.49882406",
"0.49855214",
"0.49756676",
"0.4973176"
] |
0.59106463
|
6
|
Create a daily recurrence.
|
def daily(options = {})
branch options.merge(every: :day)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def create_daily_tests()\n\n Rails.logger.info \"Checking for Daily test runs\"\n\n # get instances of a daily test run\n tests_to_add_to_stack = RecurringSchedule.get_daily_tests()\n setup_scheduled_test(tests_to_add_to_stack)\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def schedule_repetition\n self.due = Date.today + interval\n self.studied_at = Date.today\n end",
"def new_schedule(*args)\n if !args.all? { |e| e.is_a?(Integer) && e >= 0 && e <= 6 }\n return \"Please enter a number from 0-6 where each number represents a day of the week. 0 represents Sunday, 1 represents Monday, etc.\"\n end\n schedule1 = Schedule.new(self.first_event, duration: self.duration_mins.minutes )\n schedule1.add_recurrence_rule Rule.weekly.day(args)\n self.schedule = schedule1\n self.save!\n end",
"def daily_midnight\n logger.info \" daily_midnight\"\n PersistStatsJob.create({})\n Gift.send_expiration_reminders(5)\n Gift.send_expiration_reminders(3)\n Gift.send_expiration_reminders(1)\n end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def add_recurrence(type: :week, on: on = nil, at: at = nil)\n type = type.to_sym\n unless [:week, :day].include? type\n raise \"Type must be either :week or :day\"\n end\n if type == :week and (on.nil? or (on.is_a?(Array) and on.empty?))\n raise \"Weekdays must be specified when selecting the :week type\"\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if self.schedule.nil?\n schedule = Montrose::Schedule.new\n end\n if at.nil?\n raise \"Time must be specified in parameter 'at'\"\n else\n schedule.add Montrose.every(type, on: on, at: at).starts(created_at)\n self.write_attribute(self.class.schedulable_attribute, schedule)\n end\n end",
"def schedule_recurring_task_creation(task)\n recurring_scheduler = Scheduler.new\n @recurring_schedulers << recurring_scheduler\n\n recurring_scheduler.schedule.every \"#{Helpers.convert_frequency_to_seconds(task.frequency).to_s}s\" do\n new_task = Task.new\n new_task.description = task.description\n new_task.frequency = task.frequency\n new_task.creation_date = Time.now.getlocal\n new_task.target_date = Helpers.calculate_task_target_date(\n new_task.creation_date,\n new_task.frequency\n )\n new_task.recurring_scheduler_id = recurring_scheduler.id\n\n new_task.create_reminder_notification\n new_task.create_failed_notification\n\n add_task(new_task)\n end\n end",
"def create(opts)\n @frequence = opts[:frequence] if opts[:frequence].in? Recurrence::FREQUENCES\n @monthly = array_to_integer(opts[:monthly])\n @count = to_integer(opts[:count])\n @until = string_to_date(opts[:until])\n self\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def update_daily_happiness_distributions! \n HappinessEntry.dates.each do |date|\n uid = uid_for_day(date)\n entries_for_date = HappinessEntry.on_date(date)\n update_happiness_distribution! uid, :day, entries_for_date \n end\n end",
"def daily_morning\n logger.info \" daily_morning\"\n run('Newsletter', :send!)\n end",
"def recurrence_to_events!(now = Time.now.utc)\n recurring.each {|r| r.recurrence_to_events!(now)}\n end",
"def recurring; end",
"def to_occurrence(date)\n date = next_occurrence(date) if date.is_a?(Date)\n event = Event.new\n event.start_datetime = date\n event.end_datetime = date + duration\n event.title = title\n event.description = description\n event.location = location\n event.id = id\n event.user = user\n event.is_recurrence!\n event.set_as_persisted!\n event.freeze\n end",
"def daily_requests_for(time = Time.now)\n find_or_create_daily_requests_for(time)\n end",
"def initialize(d=Date.today)\n if d.instance_of? Time\n rd = Date.civil(d.year, d.month, d.day)\n elsif d.instance_of? DateTime\n rd = Date.jd(d.jd)\n else\n rd = d.dup # always make a duplicate before modifying arguments\n end\n raise ArgumentError, \"Must pass Date, DateTime, or Time object\" unless rd.instance_of? Date\n @attachments = []\n @days = []\n rd -= 1 while rd.wday > 0\n # puts \"Got past first while\"\n # puts rd\n @days << rd\n for i in (1...7)\n @days[i] = (rd + i)\n end\n # puts \"Got past for\"\n @days.freeze\n end",
"def add_days(date, n)\n date + n * DAY\n end",
"def daily_selector=(selector)\n case selector\n when 'daily_every_x_day'\n self.only_work_days = false\n when 'daily_every_work_day'\n self.only_work_days = true\n else\n raise Exception.new, \"unknown daily recurrence pattern: '#{selector}'\"\n end\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def process_recurrence(recurrence)\n return true unless recurrence.today?\n recurrence.update_job\n end",
"def daily\n respond_with PostDailyList.last_or_create\n end",
"def create_day\n trip = Trip.find(params[:id])\n offset = 0\n trip.days.all.each do |day|\n offset += 1\n end\n @day = Day.new({\"date\" => trip.beginning + offset , \"trip\" => trip})\n trip.update_attribute(:duration, trip.attributes['duration'] + 1)\n trip.save\n respond_to do |format|\n if @day.save\n format.html { redirect_to trip, notice: 'Day was successfully created.' }\n format.json { render :show, status: :created, location: @day }\n else\n format.html { render home_path }\n format.json { render json: @day.errors, status: :unprocessable_entity }\n end\n end\n end",
"def date_calc(start,day_start,day_duration,round)\n time=start;schedule=[]\n round.size.times do |r|\n#print day_start+day_duration;print \"\\n\"\n if time >= day_start + day_duration\n#print time;print \"\\n\"\n time=day_start+1.day\n day_start = time\n end\n schedule[r] = time\n time+=HEAT_INTERVAL\n end\n\n return schedule\n end",
"def add_dat\n add_daily_attendance(:dat)\n end",
"def generate_daytime_distribution \n \n end",
"def create_expenses\n expense_id = nil\n @expense = @account.expenses.create(expense_params)\n step = params[:expense_form][:recurrence].to_i\n\n if @expense.valid? && step != 0\n @expense.month_id = @expense.due_date.mon\n @expense.save \n start_month = @expense.due_date.mon + step\n number_of_months = step\n (start_month..12).step(step).each do |month|\n @expense = @account.expenses.new(expense_params)\n @expense.month_id = month\n @expense.due_date = @expense.due_date.to_date >> number_of_months\n number_of_months += step\n @expense.related_to = expense_id || @expense.id\n @expense.save\n expense_id ||= @expense.id\n end\n elsif @expense.valid?\n @expense.month_id = @expense.due_date.mon\n @expense.save\n end\n @expense.valid?\n end",
"def start_recurring_payment\n return unless recurring_period.present?\n run_at = nil\n if recurring_period.to_s.is_i? # each custom days\n run_at = recurring_period.to_i.days.from_now\n # run_at = recurring_period.to_i.minutes.from_now\n else\n case recurring_period\n when 'daily'\n run_at = 1.day.from_now\n when 'weekly'\n run_at = 7.days.from_now\n when 'monthly'\n run_at = 1.month.from_now\n when 'quarterly'\n run_at = 3.months.from_now\n when 'biannually'\n run_at = 6.months.from_now\n when 'yearly'\n run_at = 1.year.from_now\n end\n end\n Delayed::Job.enqueue(LongTasks::RecurringPaymentNotification.new(id), run_at: run_at - 1.day) if run_at && ['tithe', 'partnership'].include?(goal)\n Delayed::Job.enqueue(LongTasks::RecurringPayment.new(id), run_at: run_at) if run_at\n end",
"def sequential_day\n ActionPlan.sequential_day_for(week,day)\n end",
"def create_recurrences(transaction)\n CreateRecurrencesJob.perform_later(\n transaction.class.to_s,\n transaction.id.to_s\n )\n end",
"def create\n @day ||= Weekday.day\n @days ||= Weekday.days\n @batch = Weekday.set_day(params[:weekday][:batch_id], params[:weekdays])\n flash[:notice] = t('weekday_create')\n end",
"def set_first_repetition\n first_repetition_date = Date.today + rand(1..3).days\n repetitions.create planned_date: first_repetition_date, actual_date: first_repetition_date\n end",
"def sequential_day\n puts \"AI.sequential_day = #{action_plan.sequential_day} + #{day-1}\"\n action_plan.sequential_day + day-1\n end",
"def create_default_estimated_date\n Date.today + 7\n end",
"def createDailyWins(contest,cp)\n cdate = contest.start_date.to_date\n prize_per_day = 2\n while cdate <= contest.end_date.to_date\n for i in (1..prize_per_day)\n time = \"#{(0..23).to_a.sample}:#{(0..59).to_a.sample}:#{(0..59).to_a.sample} Rome\"\n wintime = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" \"+ time)\n wintime_end = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" 23:59:59\")\n \n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n while Instantwin.where(\"unique_id=?\",unique_id).present?\n @hash_counter += 1\n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n end\n \n iw = Instantwin.new\n iw.contest_periodicity_id = cp.id\n iw.title = \"Daily\"\n iw.time_to_win_start = wintime\n iw.time_to_win_end = wintime_end\n iw.unique_id = unique_id\n iw.save\n @hash_counter += 1\n end\n cdate += 1\n end\n end",
"def create_daily_data\n data = {\n sign: @sign_name.to_s,\n duration: 'daily',\n horoscope_text: get_daily_horoscope,\n }\n @horoscope = Horoscope.new(data)\n if @horoscope.save\n intensity = @theastrologer_content.css(\"div.row.daily-meta div[1] p[1]\").text.split(':').last.gsub(' ', '').to_s\n keywords = @theastrologer_content.css(\"div.row.daily-meta div[2] p[1]\").text.split(':').last.gsub(' ', '')\n mood = @theastrologer_content.css(\"div.row.daily-meta div[1] p[2]\").text.split(':').last.gsub(' ', '')\n @horoscope.other_details.create(\n [\n {\n detail_type: \"intensity\",\n detail: intensity\n },\n {\n detail_type: \"keywords\",\n detail: keywords\n },\n {\n detail_type: \"mood\",\n detail: mood\n }\n ]\n )\n end\n end",
"def find_next_day\n day = @date.to_date + ((@schedule.start_date - @date.to_date) % @schedule.period_num)\n return day\n end",
"def todays_recurrences\n today = Time.zone.today\n Recurrence.where('recurrences.date = ? OR recurrences.date ISNULL', today)\n end",
"def day()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Day::DayRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def process\n @recurrences.each { |r| process_recurrence(r) }\n end",
"def daily\n logger.info \" daily\"\n end",
"def next_day(date, number_of_day)\n date += 1 + (((number_of_day-1)-date.wday) % 7)\n end",
"def calculate_next_delivery\n interval = @schedulable.repeat_every\n next_delivery_date =\n case\n when @schedulable.company_survey.counter == 0 || @schedulable.time.present?\n set_next_delivery\n when @schedulable.repeat_mode == 'd'\n @schedulable.next_delivery_at + interval.days\n when @schedulable.repeat_mode == 'w'\n @schedulable.next_delivery_at + interval.weeks\n end\n\n @schedulable.update_column(:next_delivery_at, next_delivery_date)\n next_delivery_date\n end",
"def recurrence\n unless read_attribute(:recurrence).empty?\n IceCube::Rule.from_hash(read_attribute(:recurrence))\n end\n end",
"def recurrence\n { ATTR_RECURRENCE[@attribute] => 1 }\n end",
"def makeDays\n\t\thowManyDaysAgo = (rand()*CONFERENCE_START).round(0)+18\n\t\tlengthDays = (rand()*CONFERENCE_DAYS_MAX_DIFF).round() + CONFERENCE_DAYS_BASIC\n\t\t@startDate = (Date.today-howManyDaysAgo)\n\t\t@endDate = (Date.today-howManyDaysAgo+lengthDays)\n\t\t# That's the end of fields you want to print\t\n\t\t@days = Array.new\n\t\t(howManyDaysAgo-lengthDays..howManyDaysAgo).each{|x| @days << (CDay.new((Date.today-x), self))\t}\n\t\t@days.reverse! # If we want them in correct order\n\t\t# Discounts, some weird stuff may happen here, like functional programming\n\t\t@discounts = Array.new\n\t\tdays = DISCOUNT_DAYS.map{|x| x+((rand()-0.5)*DISCOUNT_DAYS_MAX_DIFF).round(0)}\n\t\tammounts = DISCOUNT_AMMOUNTS.map{|x| x+((rand()-0.5)*DISCOUNT_AMMOUNTS_MAX_DIFF).round(2)}\n\t\t(0..2).each{|x| @discounts << Discount.new(((@startDate)-days[x].to_i-1), ((@startDate)-days[x+1].to_i), self, ammounts[x])}\n\tend",
"def new_day()\n\n puts 'inside new_day' if @debug\n\n @archive_path = Time.now.strftime(\"%Y/%b/%-d\").downcase\n\n @indexpath = File.join(@filepath, @archive_path, 'index.xml')\n FileX.mkdir_p File.dirname(@indexpath)\n\n\n if FileX.exists? @indexpath then\n @dx = Dynarex.new @indexpath\n else\n\n puts 'creating a new dx file' if @debug\n @dx = Dynarex.new @schema, debug: @debug\n @dx.order = 'descending'\n @dx.default_key = @default_key\n @dx.xslt = @dx_xslt\n @dx.title = @title\n @dx.identifier = @identifier\n end\n\n end",
"def next_meeting(after_time = Time.now.utc )\n # puts \"Looking up next meeting after #{after_time}\"\n if recurrence_frequency.blank?\n return start_time\n end\n\n if after_time < start_time\n return start_time\n end \n\n after_time = after_time.local_from_utc(self.time_zone) \n\n\n # Advance the starting time in the case when it falls after the beginning of\n # a meeting on the same day. We do this so that we can use \"day precision\"\n # (PDate.day) in the Runt library instead of \"minute precision\" (PDate.min),\n # which performs terribly.\n start_time = start_time_local\n if(after_time.hour > start_time.hour or ( after_time.hour == start_time.hour and after_time.min > start_time.min))\n after_time = after_time + 1.day\n after_time = Time.gm(after_time.year, after_time.month, after_time.day, 0, 0)\n end\n\n case recurrence_frequency\n when 'daily'\n end_time = after_time + 25.hours \n # after_time -= 1.day\n start_date = PDate.day(after_time.year, after_time.month, after_time.day , after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'weekdays'\n # Make the range over 3 days so that Friday night searches will still turn\n # up Monday as the next day.\n end_time = after_time + 3.days\n start_date = PDate.day(after_time.year, after_time.month, after_time.day, after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'monthly'\n eom = (after_time + 40.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eom.year, eom.month, eom.day)\n when 'weekly'\n eow = (after_time + 8.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eow.year, eow.month, eow.day)\n when 'yearly'\n # Just doing \"after_time + 367.days\" results in a bit of a performance hit\n # as hundreds of days are compared. We'll try to narrow it a bit. Not too\n # much, because we don't have time to actually write unit tests and make\n # sure the narrowing code works. :) Which is why the comment is here.\n st = after_time + 250.days\n et = st + 150.days\n start_date = PDate.day(st.year, st.month, st.day)\n end_date = PDate.day(et.year, et.month, et.day)\n end \n # puts \" Range #{start_date.to_s} - #{end_date.to_s}\"\n d_range = DateRange.new(start_date, end_date)\n sched = Schedule.new\n event = Event.new((self.invitation.name rescue \"no name\"))\n sched.add(event,self.runt_expression)\n dates = sched.dates(event,d_range)\n\n next_mtg = dates.first\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, start_time_local.hour, start_time_local.min)\n result = nil\n begin\n result = next_mtg_time.local_to_utc(self.time_zone)\n rescue TZInfo::PeriodNotFound\n # This only happens when the time is during the one hour which is skipped\n # during the transition to DST. For example, only on Sun Mar 08 02:15:00\n # (see ticket #744).\n next_hour = start_time_local.hour + 1\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, next_hour, start_time_local.min)\n retry\n end\n return result\n end",
"def expression\n case frequency\n when :every\n DayOfWeek.new(day_of_week)\n else\n DayInMonth.new(day_of_week, frequency)\n end\n end",
"def next_collection\n # pry\n rule = IceCube::Rule.from_yaml(self.schedule)\n schedule = IceCube::Schedule.new(Time.now)\n schedule.add_recurrence_rule(rule)\n date = schedule.next_occurrence(Time.now)\n # puts date\n # date\n end",
"def make_constant_schedule(name, temperature)\n s = OpenStudio::Model::ScheduleRuleset.new(@model)\n s.setName(name)\n s.defaultDaySchedule.addValue(OpenStudio::Time.new(\"24:00:00\"), OpenStudio::convert(temperature, \"F\", \"C\").get)\n\ts\n end",
"def calculate(frequency, frequency_integer, start_date, end_date)\n first_due_date = @calendar.roll_forward(start_date)\n base_dates = [first_due_date]\n return [base_dates, base_dates] if frequency == 'Once'\n\n frequency_symbol = get_frequency_symbol(frequency)\n grace_dates = [first_due_date.advance(frequency_symbol => frequency_integer)]\n\n base_date = start_date\n end_date = calculate_end_date(start_date, end_date)\n\n while base_date < end_date\n grace_date = base_date.advance(frequency_symbol => frequency_integer*2)\n base_date = base_date.advance(frequency_symbol => frequency_integer)\n base_dates << @calendar.roll_forward(base_date)\n grace_dates << @calendar.roll_forward(grace_date)\n end\n\n [base_dates, grace_dates]\n end",
"def days()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Days::DaysRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def daily\n (0..Stats.days_in_month).collect { |d| redis.get(\"#{prefix_daily}:#{Time.now.year}:#{Time.now.month}:#{d}\").to_i }\n end",
"def add_occurrences!(event, at = [])\n Array(at).each do |time|\n OccurrenceEntry.create!(:post_id => id, :label => event, :at => time)\n end\n end",
"def create_default_repeat_instances\n case repeat\n when 'DAI'\n self.create_default_daily_instances\n when 'WEE'\n self.create_default_weekly_instances\n when ('MON' || 'ANU')\n self.create_default_monthy_or_anual_instance\n end\n end",
"def day(date)\n \n days = self.days(14)\n \n day = Object\n \n days.each do |dayEach|\n break day = dayEach if dayEach.dia == date.strftime(\"%d-%m-%Y\") \n end\n \n day\n \n end",
"def set_recurrence\n @recurrence = Recurrence.find(params[:id])\n end",
"def track_daily_stats\n # if there is no constant defined,\n unless defined?(DOCS_DAILY)\n keys = DOCS.dup\n keys.delete_if {|k,v| DOCS_DAILY_REMOVE.include?(k)}\n self.class.const_set(\"DOCS_DAILY\", keys)\n end\n\n\n # create the daily stat indicator key\n today = Time.now.strftime(\"%Y%m%d\") #20120614\n todays_stats_key = \"stats::#{today}\"\n\n # check if stats have been run today\n todays_stats_exist = DocumentStore.document_exists?(todays_stats_key)\n\n # if not, run the stats for today\n unless todays_stats_exist\n\n # set today's stat key immediately, this just indicates that the stats have been run today\n # this will fail if the key gets added between check above and now (nanoseconds),\n # will rescue below and do nothing\n DocumentStore.create_document(todays_stats_key, 1, {:quiet => false})\n\n # iterate through and retrieve values for each key, and store them as a daily value\n DOCS_DAILY.each do |k,doc_key|\n # get value of document\n doc_val = DocumentStore.get_document(doc_key)\n\n # create key for today's stats for that key\n daily_key = doc_key + \"::#{today}\"\n\n # store value with daily stat key\n DocumentStore.create_document(daily_key, doc_val)\n end\n end\n\n\n rescue Couchbase::Error::KeyExists\n # do nothing if todays_stats_key exists when trying to create\n\n end",
"def each_day(&block)\n calendar_range.map { |day| Day.new(day, requests_for(day)) }\n .each(&block)\n end",
"def create\n\t\n #ESTO SE VA DESCOMENTAR CUANDO SE INSERTE EL START_DATE Y EL END_DATE DEL FORMULARIO DE RENEWAL\n puts 'Aki va el array de Renewal'\n puts system_renewal_params\n puts 'Aki termina el arrayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'\n contract = System::Contract.find(system_renewal_params[:contract_id])\n @email = contract.supplier.email\n @start_date=Date.new(system_renewal_params[\"start_date(1i)\"].to_i,system_renewal_params[\"start_date(2i)\"].to_i,system_renewal_params[\"start_date(3i)\"].to_i)\n @end_date=Date.new(system_renewal_params[\"end_date(1i)\"].to_i,system_renewal_params[\"end_date(2i)\"].to_i,system_renewal_params[\"end_date(3i)\"].to_i)\n\t\tt0=Time.new(system_renewal_params[\"start_date(1i)\"].to_i,system_renewal_params[\"start_date(2i)\"].to_i,system_renewal_params[\"start_date(3i)\"].to_i)\n t1=Time.new(system_renewal_params[\"end_date(1i)\"].to_i,system_renewal_params[\"end_date(2i)\"].to_i,system_renewal_params[\"end_date(3i)\"].to_i)\n \n\t puts 'Aki va el parametro start_date sssssssssssssssssssssssssssssssssss'\n puts t1\n if params[:notification_date].nil?\n file_yaml = YAML.load_file \"#{Rails.root}/config/config.yml\"\n @before_days = file_yaml[\"production\"]['notification_time'].to_i.days\n else\n @before_days = params[:notification_date].to_i.days\n end\n \n @recordar = t0 - @before_days\n @recordar2 = t1 - @before_days\n puts 'aki va el recordatorio al iniciar la renovacion'\n puts @recordar\n puts 'aki terminaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'\n puts @email\n puts 'aki termina emailllllllllllllllllllllllllllllllllllllllllllllllllllllll'\n \n @email_departamento = contract.device.location.email \n array_mailer = [@email, @email_departamento]\n \n @delayed_id_start = ApplicationMailer.delay(run_at: @recordar).send_mail(array_mailer, contract,'create_renewal', @start_date, @end_date)\n @delayed_id_end = ApplicationMailer.delay(run_at: @recordar2).send_mail(array_mailer, contract,'create_renewal', @start_date, @end_date)\n \n\t@start_date_google=system_renewal_params[\"start_date(1i)\"].to_s + '-' + system_renewal_params[\"start_date(2i)\"].to_s + '-' + system_renewal_params[\"start_date(3i)\"].to_s + 'T10:00:52-05:00'\n\t@end_date_google=system_renewal_params[\"end_date(1i)\"].to_s + '-' + system_renewal_params[\"end_date(2i)\"].to_s + '-' + system_renewal_params[\"end_date(3i)\"].to_s + 'T10:00:52-05:00'\n\t@x=System::Contract.find(system_renewal_params[:contract_id])\n\t@google_event_start = System::Renewal.event_insert(@start_date_google,@start_date_google,@x.description,'neuro')\n @google_event_end= System::Renewal.event_insert(@end_date_google,@end_date_google,@x.description,'neuro')\n\n\t@system_renewal = System::Renewal.new(contract_id: system_renewal_params[:contract_id], start_date: @start_date, end_date: @end_date, monto: system_renewal_params[:monto], google_event_start: @google_event_start, google_event_end: @google_event_end, delayed_id_start: @delayed_id_start.id, delayed_id_end: @delayed_id_end.id)\n\n respond_to do |format|\n if @system_renewal.save\n @system_renewal.created_at.in_time_zone\n \n \n\tformat.html { redirect_to @system_renewal, notice: 'Renewal was successfully created.' }\n format.json { render :show, status: :created, location: @system_renewal }\n format.js { redirect_to @system_renewal, notice: 'Renewal was successfully created.' }\n else\n format.html { render :new }\n format.json { render json: @system_renewal.errors, status: :unprocessable_entity }\n format.js { render :new }\n end\n end\n end",
"def create\n @event_recurrence = EventRecurrence.new(event_recurrence_params)\n\n respond_to do |format|\n if @event_recurrence.save\n format.html { redirect_to @event_recurrence, notice: 'Event recurrence was successfully created.' }\n format.json { render :show, status: :created, location: @event_recurrence }\n else\n format.html { render :new }\n format.json { render json: @event_recurrence.errors, status: :unprocessable_entity }\n end\n end\n end",
"def init_days\n (start_time.to_date..end_time.to_date).each do |t|\n Day.create date: t, availability: self.aasm_state, boat: boat, booking: self\n end\n end",
"def daily_docs\n user = User.last\n\n\n write_docs = DocMethod.order(\"RANDOM()\").missing_docs.first(rand(0..8))\n read_docs = DocMethod.order(\"RANDOM()\").with_docs.first(rand(0..8))\n\n write_docs = DocMethod.order(\"RANDOM()\").first(rand(0..8)) if write_docs.blank?\n read_docs = DocMethod.order(\"RANDOM()\").first(rand(0..8)) if read_docs.blank?\n\n ::UserMailer.daily_docs(user: user, write_docs: write_docs, read_docs: read_docs)\n end",
"def each_days(n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt.to_date + offset }\n s.increment { |dt,i| dt.to_date + i }\n s.span { |dt| dt.to_date + dur }\n end\n end",
"def calorie_sum_by_day\n\n end",
"def create_date_field(task, relative_date)\n if task.has_key?('days')\n task['date'] = relative_date + task['days'].to_i\n end\n\n if task.has_key?('subtasks') && task['subtasks'].any?\n task['subtasks'].each { |subtask|\n create_date_field(subtask, relative_date)\n }\n end\nend",
"def skel_daily( path_storage, section_path )\n entry_range = path_storage.find\n first_time, last_time = entry_range.last.created, entry_range.first.created\n start = Time.mktime( first_time.year, first_time.month, first_time.day, 0, 0, 0 ) + 1\n stop = Time.mktime( last_time.year, last_time.month, last_time.day, 23, 59, 59 )\n days = []\n one_day = 24 * 60 * 60\n until start > stop\n day_entries = path_storage.within( start, start + one_day - 1 )\n days << [day_entries.last.created, day_entries] unless day_entries.empty?\n start += one_day\n end\n days.extend Hobix::Enumerable\n days.each_with_neighbors do |prev, curr, nextd| \n page = Page.new( curr[0].strftime( \"%Y/%m/%d\" ), section_path )\n page.prev = prev[0].strftime( \"%Y/%m/%d\" ) if prev\n page.next = nextd[0].strftime( \"%Y/%m/%d\" ) if nextd\n page.timestamp = curr[0]\n page.updated = path_storage.last_updated( curr[1] )\n yield :page => page, :entries => curr[1]\n end\n end",
"def recurrence\n nil\n end",
"def day() end",
"def daily_new(options = {})\n request_model = @request_model_factory.daily_new_request_model(options)\n response = @network_client.perform_request(request_model)\n parse_point_response(response)\n end",
"def each_friday( n=1, offset=0, dur=1); each_wdays(self.Fri,n,offset,dur); end",
"def update!(**args)\n @daily_recurrence = args[:daily_recurrence] if args.key?(:daily_recurrence)\n @every = args[:every] if args.key?(:every)\n @monthly_recurrence = args[:monthly_recurrence] if args.key?(:monthly_recurrence)\n @recurrence_end_date = args[:recurrence_end_date] if args.key?(:recurrence_end_date)\n @recurrence_start = args[:recurrence_start] if args.key?(:recurrence_start)\n @repeat_count = args[:repeat_count] if args.key?(:repeat_count)\n @repeat_forever = args[:repeat_forever] if args.key?(:repeat_forever)\n @single_recurrence = args[:single_recurrence] if args.key?(:single_recurrence)\n @weekly_recurrence = args[:weekly_recurrence] if args.key?(:weekly_recurrence)\n @yearly_recurrence = args[:yearly_recurrence] if args.key?(:yearly_recurrence)\n end",
"def create_activity_factory_wrapper\n if recurrence\n create_activity_factory({\n # Fields copied straight from +Activity+ model\n name:name,\n description:description,\n vendor_id:vendor_id,\n vendor_name:vendor_name,\n bookings_available:bookings_available,\n price:price,\n start: start,\n # Fields inferred from +Activity+ model\n duration: (start && finish && finish - start)\n }.merge(recurrence) )\n return !activity_factory.new_record?\n end\n end",
"def daily\n object # Initializing to make sure that the passed in day is\n # acceptable. Else a 404 will be raised.\n render :template => \"weekly_digests/show\"\n rescue ActiveRecord::RecordNotFound\n rescue_404\n end",
"def initialize\n @tag_name = self.class.to_s.split(\"::\").last.downcase\n @schedule = IceCube::Schedule.new(1.month.ago.beginning_of_day)\n @schedule.add_recurrence_rule IceCube::Rule.daily\n # For example, add these if your schedule doesn't occur on weekends\n #@schedule.add_exception_rule IceCube::Rule.weekly.day(:saturday)\n #@schedule.add_exception_rule IceCube::Rule.weekly.day(:sunday)\n end",
"def daily\n if dates_ok?\n @entries = Entry.where('user_id = ?\n AND \"time\"(date) BETWEEN ? AND ?\n AND CAST(date AS DATE) >= ? and CAST(date AS DATE) <= ?', current_user.id, params[:timeFrom], params[:timeTo], Date.parse(params[:dateFrom]), Date.parse(params[:dateTo])).\n select('CAST(date AS DATE), sum(calories) as calories').group('CAST(date AS DATE)')\n else\n @entries = Entry.where('user_id = ?', current_user.id).\n select('CAST(date AS DATE), sum(calories) as calories').group('CAST(date AS DATE)')\n end\n end",
"def addDays(date)\n\n #puts 'in addDays'\n #puts date\n if date.saturday? then\n #puts \"sat\"\n date1 = date.next_day(7)\n return date1\n elsif date.sunday? then\n #puts \"sun\"\n date1 = date.next_day(8)\n return date1\n else\n #puts 'other'\n date1 = date.next_day(7)\n end\n return date1\n end",
"def next_day\n advance(days: 1)\n end",
"def days\n Thread.current[:datet_mode] = :days\n return self\n end",
"def add_rep(date = Date.current, period = 1)\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.add_rep(date, period)\n return\n end\n\n # make sure date now or in future\n if date < Date.current\n puts \"date before today\"\n return\n end\n\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n \n end",
"def daily_events_for_id(id, action, date = default_date_range)\n additional_params = {\n flat: 1,\n label: \"#{id} - #{action}\"\n }\n response = api_params('Events.getName', 'day', date, additional_params)\n results_array(response, 'nb_events')\n end",
"def discount_of_the_day(day)\n case day\n when (0..(DISCOUNT_PERIOD_1_START_DAY - 1)) then 0\n when (DISCOUNT_PERIOD_1_START_DAY..(DISCOUNT_PERIOD_2_START_DAY - 1)) then DISCOUNT_PERIOD_1_RATE\n when (DISCOUNT_PERIOD_2_START_DAY..(DISCOUNT_PERIOD_3_START_DAY - 1)) then DISCOUNT_PERIOD_2_RATE\n else DISCOUNT_PERIOD_3_RATE\n end\n end",
"def scheduled_at_date\n (model.scheduled_at || Time.zone.now + 7.days).strftime(\"%m/%-d/%Y\")\n end",
"def schedule(db, date, patient_id, time)\n\tdb.execute(\"INSERT INTO calendar (date, patient_id, time) VALUES (?, ?, ?)\", [date, patient_id, time])\nend",
"def next_day(date)\n date + (60 * 60 * 24)\n end",
"def create_reminder(date, reminder)\r\n norm_date = normalize_date(date)\r\n $DB.execute(\"INSERT INTO reminders (date, reminder) VALUES (?,?)\",\r\n [norm_date, reminder])\r\nend",
"def sprint_day(date)\n return -1 unless start_date && end_date\n return -1 if date < start_date\n return (duration + 1) if date > end_date\n\n counter_date = start_date\n day = 1\n \n while (counter_date < date)\n if counter_date.wday == 0 || counter_date.wday == 6\n counter_date += 1\n next\n else\n counter_date += 1\n end\n\n day += 1\n end\n \n day\n end",
"def occurrence_days(item)\n occurrence_days_cache[item.representation]\n end",
"def create\n @event_recurrence = EventRecurrence.new(event_recurrence_params)\n @call = Call.new(call_params)\n @call.event_recurrence = @event_recurrence \n\n respond_to do |format|\n if @call.save && @event_recurrence.save\n format.html { redirect_to @call, notice: 'Call was successfully created.' }\n format.json { render :show, status: :created, location: @call }\n else\n format.html { render :new }\n format.json { render json: @call.errors, status: :unprocessable_entity }\n end\n end\n end",
"def recurring(opts={})\n all({DataMapper::Events.recurrence_key.not => nil}.merge(opts))\n end",
"def create_notification_for_date(date)\n notification_type.constantize.create! :recipient => subscriber, :date => date\n end",
"def each_sunday( n=1, offset=0, dur=1); each_wdays(self.Sun,n,offset,dur); end"
] |
[
"0.73362285",
"0.7017756",
"0.65977263",
"0.6593396",
"0.62268525",
"0.62245",
"0.62103426",
"0.6174135",
"0.6157488",
"0.6111112",
"0.6105825",
"0.6092715",
"0.6059412",
"0.59560364",
"0.5940169",
"0.5940169",
"0.5919528",
"0.5911028",
"0.59017324",
"0.5893936",
"0.58616406",
"0.5836479",
"0.5790827",
"0.5756615",
"0.57554835",
"0.5748707",
"0.57462585",
"0.57367754",
"0.57333505",
"0.57237",
"0.5720629",
"0.5652481",
"0.5634555",
"0.5624599",
"0.56092024",
"0.56029665",
"0.55608207",
"0.55387574",
"0.5533815",
"0.5531415",
"0.55232906",
"0.5480895",
"0.5478022",
"0.545399",
"0.5446662",
"0.5425709",
"0.5401967",
"0.5385739",
"0.53652185",
"0.5356198",
"0.534015",
"0.5338829",
"0.5338806",
"0.53250515",
"0.5304931",
"0.529711",
"0.5295162",
"0.5285208",
"0.5284623",
"0.5279173",
"0.5278653",
"0.52614874",
"0.5253877",
"0.5247068",
"0.52441776",
"0.5242416",
"0.5242238",
"0.52417684",
"0.52407634",
"0.5237956",
"0.52153164",
"0.5200162",
"0.518845",
"0.51763326",
"0.51707226",
"0.51524746",
"0.51509213",
"0.514119",
"0.51407945",
"0.51329684",
"0.5127795",
"0.5124785",
"0.51200724",
"0.5110906",
"0.51079005",
"0.5106674",
"0.51061726",
"0.5103522",
"0.50963867",
"0.50818545",
"0.5072121",
"0.50674134",
"0.5061379",
"0.50511926",
"0.50448185",
"0.5044731",
"0.504467",
"0.50410837",
"0.50398976"
] |
0.60408163
|
14
|
Create a weekly recurrence.
|
def weekly(options = {})
branch options.merge(every: :week)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def weeks() 7 * days end",
"def new_schedule(*args)\n if !args.all? { |e| e.is_a?(Integer) && e >= 0 && e <= 6 }\n return \"Please enter a number from 0-6 where each number represents a day of the week. 0 represents Sunday, 1 represents Monday, etc.\"\n end\n schedule1 = Schedule.new(self.first_event, duration: self.duration_mins.minutes )\n schedule1.add_recurrence_rule Rule.weekly.day(args)\n self.schedule = schedule1\n self.save!\n end",
"def add_recurrence(type: :week, on: on = nil, at: at = nil)\n type = type.to_sym\n unless [:week, :day].include? type\n raise \"Type must be either :week or :day\"\n end\n if type == :week and (on.nil? or (on.is_a?(Array) and on.empty?))\n raise \"Weekdays must be specified when selecting the :week type\"\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if self.schedule.nil?\n schedule = Montrose::Schedule.new\n end\n if at.nil?\n raise \"Time must be specified in parameter 'at'\"\n else\n schedule.add Montrose.every(type, on: on, at: at).starts(created_at)\n self.write_attribute(self.class.schedulable_attribute, schedule)\n end\n end",
"def create_weekly_tests()\n\n Rails.logger.info \"Checking for Weekly test runs\"\n\n # get instances of a weekly test run\n tests_to_add_to_stack = RecurringSchedule.get_weekly_tests_for_today()\n setup_scheduled_test(tests_to_add_to_stack)\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def weeks ; self * 7.days ; end",
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def next_week(x = 1)\n\t\tself + (604800 * x)\n\tend",
"def next_week_in weeks\n Week.find_by(initial_day: initial_day+( weeks * 7.days))\n end",
"def setup_weeks(week_start)\n a_date = self.first\n the_last = self.last\n @weeks = []\n\n while (a_date < the_last)\n @weeks << Koyomi::Week.new(a_date, week_start)\n a_date += WEEK_DAYS\n end\n @weeks\n end",
"def week; end",
"def create_weekly_data\n number = @slide_number.to_i + 1\n data_content = Nokogiri::HTML(\n open(\n \"#{ENV['API_DOMAIN_2']}#{ENV['API_DOMAIN_2_WEEKLY']}\"\n )\n ).css(\"div.shareable-section-wrapper\")\n return {} if data_content.blank?\n\n data = {\n sign: @sign_name.to_s,\n duration: \"weekly\",\n horoscope_text: data_content.css(\"div[#{number}]\").text.split(' ')[1..-1].join(' ')\n } if data_content\n Horoscope.create(data) if data_content and data\n end",
"def create_invoices_for_week\n InvoiceGenerator.create_invoices_for_week(self)\n end",
"def weekly_event_schedule\n utc_time = Time.now.utc\n\n # find TZs where it's ~08:45 on a Monday morning\n matching_tzs = TriggerService.monday_morning_timezones(utc_time)\n\n # create app events for each TZ\n robot = User.find(1)\n matching_tzs.each do |tz|\n next unless User.where(time_zone: tz.name).count > 0\n\n meta_data = { \n time_zone: tz.name, \n processor: 'Ns2::Processors::ScheduledNotificationsProcessor', \n utc_run_time: utc_time\n }\n # robot is dummy data, as this doesn't quite fit our model.\n AppEventService.create(robot, robot, \"weekly_event_schedule\", meta_data)\n end\n end",
"def week\n @week ||= (((date-start_of_month)+1)/7.0).ceil\n end",
"def week\n first_day_of_week = @date.monday\n \n days_of_week = []\n 7.times do |time|\n days_of_week << day_and_types(first_day_of_week + time.days)\n end \n \n days_of_week\n end",
"def generate_and_update_newsletter_for_current_week\n date = Date.today\n generate_and_update_newsletter(Newsletter::WEEKLY, date.cweek, date.month, date.year)\n end",
"def next_week\n if self.class == Date\n self + 7\n elsif self.class == Time\n self + (60 * 60 * 24 * 7)\n end\n end",
"def next_week\n if self.class == Date\n self + 7\n elsif self.class == Time\n self + (60 * 60 * 24 * 7)\n end\n end",
"def weekly(workspace_id, params={})\n get_report('weekly', workspace_id, params)\n end",
"def each_weeks(n=1, offset=0, dur=1)\n each_days(n*7, offset*7, dur*7)\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def mweek; (5 - wday + day) / 7 end",
"def weekly(response)\n # Set up our client\n destiny_client = DestinyAPI::Base.new(api_key)\n # Build the activity message with weekly info\n build_activity_message(destiny_client.weekly_strike, response)\n end",
"def weeks; self * WEEK; end",
"def weeks; self * WEEK; end",
"def find_next_week\n if @schedule.days == 0\n date = @date + ((@schedule.start_date.wday - @date.wday) % 7) + (7 * ((@schedule.start_date - @date) % @schedule.period_num))\n return date\n else\n date = @date + find_next_in_bitmask(@schedule.days, @date.wday, 7)\n\n if @date.wday >= bitmask(@schedule.days).length\n date += periods_to_add * 7\n end\n\n return date\n end\n end",
"def week_num()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::WeekNum::WeekNumRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def weeks\n result = end_week - start_week + 1\n weeks = Date.new(start_date.year, 12, 31).strftime('%W').to_i\n result < 0 ? result + weeks : result\n end",
"def weekly(response)\n # Set up our client\n destiny_client = Destiny::Client.new(api_key)\n # Set attachment color\n color = \"#f39c12\"\n # Set attachment thumb_url\n thumb_url = \"http://i.imgur.com/HhXoUCX.png\"\n # Build the activity message with weekly info\n build_activity_message(destiny_client.weekly_strike, response, color, thumb_url)\n end",
"def week\n @year = params[:year].to_i\n @month = params[:month].to_i\n @day = params[:day].to_i\n @date = Date.new(@year, @month, @day)\n @work_times = WorkTime.find_by_start_date(@date)\n end",
"def week(date = Date.today)\n day = monday(date)\n (day..day + 6)\n end",
"def weeks ; Duration[self * 604800] ; end",
"def weekly_time_generator(args = {:start_time => Time.now, :end_time => nil, :cron => ''})\n begin\n return [] if args[:cron].blank?\n\n # get cron as hash\n cron = cron_date args[:cron]\n\n # get the first value of the cron which is an integer and the pevious index\n # ex: cron = '41 * * * *' - we want to know that it starts every hour (prev index before the number) in the 41-st minute\n for k, v in cron do\n at = v\n break if v.class == 'Fixnum'\n # break in ruby continues the last iteration..\n every = k if v == '*'\n end\n\n changed_time = start_time = cron_generate_date args[:cron], args[:start_time]\n end_time = args[:end_time]\n\n # end_time is nil?\n end_time = Time.now.end_of_week if !end_time.respond_to? :year\n # end_time should not be longer than the end of this week\n end_time = end_time > start_time.end_of_week ? start_time.end_of_week : end_time\n\n all = []\n while changed_time <= end_time\n all << changed_time #changed_time.strftime(\"%d.%m.%Y %H:%M\")\n changed_time += 1.send(every)\n end\n\n all\n\n rescue => ex\n send_mail \"#{ex.class}: #{ex.message}. args: #{args}\" \n end\n\n end",
"def create(opts)\n @frequence = opts[:frequence] if opts[:frequence].in? Recurrence::FREQUENCES\n @monthly = array_to_integer(opts[:monthly])\n @count = to_integer(opts[:count])\n @until = string_to_date(opts[:until])\n self\n end",
"def week\n working_date = DateTime.new(self.year, 1, 1)\n working_date.week_day_start = self.week_day_start\n working_date = (working_date-working_date.send(\"wday_offset\"))\n week_num = 0\n working_date.step(self) { |a_day| \n if a_day.wday == _week_day_numbers.first\n week_num += 1\n end\n }\n week_num\n end",
"def schedule_repetition\n self.due = Date.today + interval\n self.studied_at = Date.today\n end",
"def weekly(range)\n data = range(range, :skip_bitmap_count => true)\n\n data = data.group_by { |date, value| date.beginning_of_week }\n case self.type\n when :counter\n sum_up_grouped_data(data)\n when :bitmap\n bitmap_or_grouped_data(data)\n end\n end",
"def weekly_pay(rate, hours = 40)\n hours * rate\nend",
"def weekly\n user = User.first\n TipMailer.weekly(user)\n end",
"def update_weekly_happiness_distributions! \n HappinessEntry.beginning_of_week_days.each do |beginning_of_week_day|\n uid = uid_for_week(beginning_of_week_day)\n end_of_week_day = beginning_of_week_day.end_of_week\n entries_for_week = HappinessEntry.in_week(beginning_of_week_day, end_of_week_day)\n update_happiness_distribution! uid, :week, entries_for_week \n end\n end",
"def create_or_update_weekly_goal(opts)\n unless opts[:type] && [:steps, :distance, :floors].include?(opts[:type])\n raise InvalidArgumentError, 'Must specify type in order to create or update a weekly goal. One of (:steps, :distance, or :floors) is required.'\n end\n\n unless opts[:value]\n raise InvalidArgumentError, 'Must specify value of the weekly goal to be created or updated.'\n end\n\n post(\"/user/#{@user_id}/activities/goals/weekly.json\", opts)\n end",
"def each_wdays(wd,n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt.to_date + (wd - dt.to_date.wday)%7 + offset*7 }\n s.increment { |dt,i| dt.to_date + i*7 }\n s.span { |dt| dt.to_date + dur }\n end\n end",
"def week_from_today\n ::Date.today + 7\n end",
"def weeks\n\t\treturn self * 7.days\n\tend",
"def weeks\n\t\treturn self * 7.days\n\tend",
"def week\n stamp = params[:stamp].to_i\n interval = (params[:interval] || 10).to_i\n plus_weeks = (params[:plus_weeks] || 0).to_i\n context = (params[:context] || 0).to_i == 1 ? true : false\n time = Time.at(stamp).utc\n\n # Calculate monday from given date\n wday = time.wday\n # Adjust for sunday when we want to start on a monday\n wday = 7 if wday == 0\n\n date = time - (wday.days - 1.days)\n\n date = date + plus_weeks.weeks\n\n # Number of days in week range if we add context, we add the surrounding weeks as well\n days = context ? (7 * 3) - 1 : 6\n\n # If context we'll start at the monday before\n if context\n date -= 7.days\n end\n\n\n\n week_data = []\n week_dates = []\n\n buckets = 0.step((60 * 24) - 1, interval).to_a\n\n (0..days).each do |day|\n interval_data = Hash.new { |h, k| h[k] = [] }\n\n data = GlucoseSensorData.by_day(date.to_date, :field => :timestamp)\n\n data.each do |datum|\n minutes = datum.timestamp.min + (datum.timestamp.hour * 60)\n # At first seems like a no op but this actually buckets minutes into intervals\n bucket = (minutes / interval) * interval\n\n interval_data[bucket] << datum\n end\n\n week_context = nil\n\n if context\n week_number = day / 7\n if week_number == 0\n week_context = \"before\"\n elsif week_number == 1\n week_context = \"current\"\n else\n week_context = \"after\"\n end\n else\n week_context = \"current\"\n end\n\n buckets.each do |bucket|\n datum = {}\n\n datums = interval_data[bucket]\n # Averages glucose values if there are more than one datum for that bucket\n if datums.length > 0\n datum[:glucose] = datums.inject(0.0) { |sum, d| sum + d.glucose } / datums.size\n #datum[:timestamp] = datums[0].timestamp.to_i\n end\n datum[:timestamp] = (date + bucket.minutes).to_i\n datum[:week_context] = week_context\n\n\n datum[:time] = bucket\n datum[:day] = date.strftime(\"%A\").downcase\n datum[:date] = date.to_i\n week_data << datum\n end\n\n week_dates.push({ :week_context => week_context, :day => date.strftime(\"%A\").downcase, :date => date.to_i })\n date += 1.days\n end\n\n render :json => { :data => week_data, :interval => interval, :week_dates => week_dates }\n end",
"def recurring; end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def weeks\n self.to_i * 604_800\n end",
"def duplicate()\n duplicate_week=Week.new(@start,@finish)\n duplicate_values=Array.new(@values.size)\n @values.each_index {|index|\n duplicate_values[index]=@values[index].duplicate\n }\n duplicate_week.values=duplicate_values \n duplicate_week.days=@days\n duplicate_week.start=@start\n duplicate_week.finish=@finish\n duplicate_week.week_total=@week_total\n duplicate_week.total=@total\n duplicate_week.refresh\n return duplicate_week\n end",
"def schedule_recurring_task_creation(task)\n recurring_scheduler = Scheduler.new\n @recurring_schedulers << recurring_scheduler\n\n recurring_scheduler.schedule.every \"#{Helpers.convert_frequency_to_seconds(task.frequency).to_s}s\" do\n new_task = Task.new\n new_task.description = task.description\n new_task.frequency = task.frequency\n new_task.creation_date = Time.now.getlocal\n new_task.target_date = Helpers.calculate_task_target_date(\n new_task.creation_date,\n new_task.frequency\n )\n new_task.recurring_scheduler_id = recurring_scheduler.id\n\n new_task.create_reminder_notification\n new_task.create_failed_notification\n\n add_task(new_task)\n end\n end",
"def weekday()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Weekday::WeekdayRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def first_wday; (wday - day + 1) % 7 end",
"def weekly(user)\n @user = user\n week = ApplicationController.helpers.current_theater_week\n @current_week = Movie.current_week\n\n subject = default_i18n_subject(begin: l(week.begin, format: :long),\n end: l(week.end, format: :long))\n\n headers['List-Unsubscribe'] = unsubscribe_url(email: user.email)\n mail(to: user.email,\n subject: subject)\n end",
"def ops_calendar\n # setup calendar cells\n @today = Date.today - 3\n if @today.strftime(\"%a\") == \"Mon\"\n @start_date = @today\n else\n @start_date = @today\n until @start_date.strftime(\"%a\") == \"Mon\"\n @start_date -= 1\n end\n end\n @end_date = @start_date+21\n @date_range = (@start_date..@end_date)\n @weeks = @date_range.to_a.in_groups_of(3)\n\n\n end",
"def find_weekpattern(date)\n # find the pattern that fits the date\n #\n if date < @from\n result = Week.new(Time.at(0), @from - MINUTE, WORK_TYPE)\n elsif date > to\n result = Week.new(@to + MINUTE, Time.new(9999), WORK_TYPE)\n else\n\n date = Time.gm(date.year, date.month, date.day)\n\n result = @weeks.find { |week| week.start <= date && week.finish >= date }\n end\n result\n end",
"def createDailyWins(contest,cp)\n cdate = contest.start_date.to_date\n prize_per_day = 2\n while cdate <= contest.end_date.to_date\n for i in (1..prize_per_day)\n time = \"#{(0..23).to_a.sample}:#{(0..59).to_a.sample}:#{(0..59).to_a.sample} Rome\"\n wintime = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" \"+ time)\n wintime_end = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" 23:59:59\")\n \n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n while Instantwin.where(\"unique_id=?\",unique_id).present?\n @hash_counter += 1\n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n end\n \n iw = Instantwin.new\n iw.contest_periodicity_id = cp.id\n iw.title = \"Daily\"\n iw.time_to_win_start = wintime\n iw.time_to_win_end = wintime_end\n iw.unique_id = unique_id\n iw.save\n @hash_counter += 1\n end\n cdate += 1\n end\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def each_wednesday(n=1, offset=0, dur=1); each_wdays(self.Wed,n,offset,dur); end",
"def add_working_days(date, working_days)\n if working_days > 0\n weeks = working_days / (7 - non_working_week_days.size)\n result = weeks * 7\n days_left = working_days - weeks * (7 - non_working_week_days.size)\n cwday = date.cwday\n while days_left > 0\n cwday += 1\n unless non_working_week_days.include?(((cwday - 1) % 7) + 1)\n days_left -= 1\n end\n result += 1\n end\n next_working_date(date + result)\n else\n date\n end\n end",
"def reportable_weeks(options = {})\n week = options[:from] ? from_time(options[:from]) : earliest_week\n last_in_sequence = current\n [week].tap do |weeks|\n while week != last_in_sequence\n week = week.next\n weeks << week\n end\n end\n end",
"def convertDailyToWeeklyData()\n aggregateData(ChartDirector::ArrayMath.new(@timeStamps).selectStartOfWeek())\n end",
"def week_payout(date = Date.current, start_day = \"monday\")\n if !date.is_a? Date\n puts \"Must pass in a date\"\n return\n end\n\n # make sure using rep_parent\n node = self.get_rep_parent\n\n # calculate start and end of week\n week_start = date.\n beginning_of_week(start_date = start_day.to_sym)\n week_end = date.\n end_of_week(start_date = start_day.to_sym)\n date_range = week_start..week_end\n \n # get payout of children\n child_payout = 0 \n node.children.each do |child|\n child_payout += child.week_payout(date, start_day)\n end\n\n # if no week requirement\n if node.is_infinite?\n # get all from this week\n week_reps = self.rep_parent.repititions.\n where(\"completed_date >= ? AND completed_date <= ?\",\n week_start, week_end)\n if week_reps >= node.count\n return node.reward + child_payout\n elsif Date.current > week_end\n return node.penalty + child_payout\n else\n return child_payout\n end\n \n end\n \n \n # there is a week requirement, get reward/ penalty\n act_payout = 0\n if node.state == Activity::COMPLETE and \n date_range.include? node.completed_date\n act_payout = node.reward\n elsif node.state == Activity::EXPIRED and\n date_range.include? node.expiration_date\n act_payout = -1 * node.penalty\n \n end\n \n return child_payout + act_payout\n end",
"def each_sunday( n=1, offset=0, dur=1); each_wdays(self.Sun,n,offset,dur); end",
"def next_working_date(date)\n cwday = date.cwday\n days = 0\n while non_working_week_days.include?(((cwday + days - 1) % 7) + 1)\n days += 1\n end\n date + days\n end",
"def each_saturday( n=1, offset=0, dur=1); each_wdays(self.Sat,n,offset,dur); end",
"def week\n self.range('week')\n end",
"def days_to_add(desired)\n # c is current day of week, d is desired next day of week\n # f( c, d ) = g( c, d ) mod 7, g( c, d ) > 7\n # = g( c, d ), g( c, d ) <= 7\n # g( c, d ) = [7 - (c - d)] = 7 - c + d\n # where 0 <= c < 7 and 0 <= d < 7\n n = (7 - DateTime.now.wday + desired);\n (n > 7) ? n % 7 : n\nend",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def create\n @wb_id = params[:requisition][:wb_id]\n\t@week = params[:requisition][:week]\n\t@requisition = Requisition.new(requisition_params)\n\t@requisition.user_id = current_user.id\n\t@requisition.school_id = current_user.school_id\n respond_to do |format|\n if @requisition.save\n format.html { redirect_to add_requisition_requisitions_path(wb_id: @wb_id, week: @week), notice: 'Requisition was successfully created.' }\n format.json { render action: 'show', status: :created, location: @requisition }\n else\n format.html { redirect_to :back, notice: 'Requisition already exists.' }\n format.json { render json: @requisition.errors, status: :unprocessable_entity }\n end\n end\n end",
"def start_of_week_with_wkst(wkst)\n wkst ||= 1\n date = ::Date.civil(self.year, self.month, self.day)\n date -= 1 while date.wday != wkst\n date\n end",
"def workpattern(opts = {}, persist = nil)\n args = all_workpattern_options(opts)\n\n persist.store(name: @name, workpattern: args) if !persist.nil?\n\n args = standardise_args(args)\n\n upd_start = work_pattern.to_utc(args[:start])\n upd_finish = work_pattern.to_utc(args[:finish])\n\n while upd_start <= upd_finish\n\n\t current_wp = work_pattern.find_weekpattern(upd_start)\n\n if current_wp.start == upd_start\n if current_wp.finish > upd_finish\n clone_wp = fetch_updatable_week_pattern(current_wp,\n upd_finish + DAY,\n current_wp.finish,\n upd_start,\n upd_finish)\n update_and_store_week_pattern(clone_wp, args)\n upd_start = upd_finish + DAY\n else # (current_wp.finish == upd_finish)\n current_wp.workpattern(args[:days], args[:from_time],\n args[:to_time], args[:work_type])\n upd_start = current_wp.finish + DAY\n end\n else\n clone_wp = fetch_updatable_week_pattern(current_wp, current_wp.start,\n upd_start - DAY, upd_start)\n if clone_wp.finish > upd_finish\n after_wp = fetch_updatable_week_pattern(clone_wp,\n upd_start,\n upd_finish,\n upd_finish + DAY)\n weeks << after_wp\n end\n update_and_store_week_pattern(clone_wp, args)\n upd_start = clone_wp.finish + DAY\n end\n end\n end",
"def beginning_of_week; end",
"def beginning_of_week; end",
"def cweek\n end",
"def build_shifts\n shifts = Person.find(params[:id]).shifts.order(start: :asc)\n #init working_weeks\n working_weeks = [[[shifts[0]]]]\n if shifts[0].start.strftime(\"%U\").to_i != shifts[0].end.strftime(\"%U\").to_i or\n shifts[0].start.wday != shifts[0].end.wday\n #check for which it is because you have to append different things to different places.\n if shifts[0].start.strftime(\"%U\").to_i != shifts[0].end.strftime(\"%U\").to_i\n #duplicate the current shift and add it\n working_weeks.append [[shifts[0].dup]]\n #then set the dup's start and the original's end so you know what day it is later.\n working_weeks[0][0][0].end = working_weeks[0][0][0].start.end_of_day\n working_weeks[-1][-1][-1].start = working_weeks[-1][-1][-1].end.beginning_of_day\n elsif shifts[0].start.wday != shifts[0].end.wday\n working_weeks[0].append [shifts[0].dup]\n working_weeks[0][0][0].end = working_weeks[0][0][0].start.end_of_day\n working_weeks[-1][-1][-1].start = working_weeks[-1][-1][-1].end.beginning_of_day\n end\n #you incremented day so get the first day's display info set up. only one shift so pad it\n #with a nil at the front and 3 at the back. array's length has to be 7\n working_weeks[0][0].append(nil)\n #time before shift\n working_weeks[0][0].append(shifts[0].start.hour * 2 + shifts[0].start.min / 30)\n #time during shift\n working_weeks[0][0].append(48 - (shifts[0].start.hour * 2 + shifts[0].start.min / 30))\n 3.times do\n working_weeks[0][0].append 0\n end\n end\n shifts.drop(1)\n shifts.each_with_index do |shift, idx|\n #byebug\n #get the first bit of the shift in if it's on a different day\n #only setting the previous day's bit here so that day's array will be cleaned up afterwards\n #working shift's start is changed to get that started\n if shift.start.strftime(\"%U\").to_i != shift.end.strftime(\"%U\").to_i or\n shift.start.wday != shift.end.wday\n\n if shift.start.strftime(\"%U\").to_i != shift.end.strftime(\"%U\").to_i\n working_weeks.append([[shift.dup]])\n elsif shift.start.wday != shift.end.wday\n working_weeks[-1].append([shift.dup])\n end\n working_weeks[-1][-1][-1].end = working_weeks[-1][-1][-1].start.end_of_day\n shift.start = shift.end.beginning_of_day\n end\n\n if shift.start.strftime(\"%U\").to_i != shifts[idx - 1].end.strftime(\"%U\").to_i or\n shift.start.wday != shifts[idx - 1].end.wday\n\n #new day/month so set the last day's display info\n if working_weeks[-1][-1][1].nil?\n working_weeks[-1][-1].append(nil)\n end\n working_weeks[-1][-1].append(working_weeks[-1][-1][0].start.hour * 2 + \n working_weeks[-1][-1][0].start.min / 30)\n #add 1 to the end time because it might be 23:59 if it was set by \n working_weeks[-1][-1].append((working_weeks[-1][-1][0].end.hour * 2 +\n (working_weeks[-1][-1][0].end.min + 1) / 30) -\n (working_weeks[-1][-1][0].start.hour * 2 +\n working_weeks[-1][-1][0].start.min / 30))\n #if there's only one we just need to set the end\n if working_weeks[-1][-1][1].nil?\n working_weeks[-1][-1].append(48 - (working_weeks[-1][-1][0].end.hour * 2 +\n (working_weeks[-1][-1][0].end.min + 1) / 30))\n 2.times do\n working_weeks[-1][-1].append 0\n end\n #otherwise step to the second shift\n else\n working_weeks[-1][-1].append((working_weeks[-1][-1][0].start.hour * 2 +\n (working_weeks[-1][-1][0].start.min) / 30) -\n (working_weeks[-1][-1][1].end.hour * 2 +\n (working_weeks[-1][-1][1].end.min + 1) / 30))\n working_weeks[-1][-1].append((working_weeks[-1][-1][1].end.hour * 2 +\n (working_weeks[-1][-1][1].end.min + 1) / 30) -\n (working_weeks[-1][-1][1].start.hour * 2 +\n working_weeks[-1][-1][1].start.min / 30))\n working_weeks[-1][-1].append(48 - (working_weeks[-1][-1][1].end.hour * 2 + \n (working_weeks[-1][-1][1].end.min + 1) / 30))\n end\n\n end\n if shift.start.strftime(\"%U\").to_i != shifts[idx - 1].end.strftime(\"%U\").to_i\n working_weeks.append [[shift]]\n elsif shift.start.wday != shifts[idx - 1].end.wday\n working_weeks[-1].append [shift]\n else\n working_weeks[-1][-1].append shift\n end\n \n\n end\n return working_weeks\n end",
"def week_payout(date = Date.current, start_day = \"monday\")\n if !date.is_a? Date\n puts \"Must pass in a date\"\n return\n end\n\n # make sure using rep_parent\n node = self\n if !self.rep_parent.nil?\n node = self.rep_parent\n end\n \n # calculate start and end of week\n week_start = date.\n beginning_of_week(start_date = start_day.to_sym)\n week_end = date.\n end_of_week(start_date = start_day.to_sym)\n \n # get payout of children\n count = 0 \n node.children.each do |child|\n count = count + child.week_payout(date, start_day)\n end\n \n # get reward\n act_payout = 0\n week_reps = node.repititions.\n where(\"completed_date >= ? AND completed_date <= ?\",\n week_start, week_end)\n week_reps.each do |rep|\n if (rep.state == Activity::COMPLETE)\n act_payout = act_payout + node.reward\n end\n end\n \n # get penalty\n week_reps = node.repititions.\n where(\"expiration_date >= ? AND expiration_date <= ?\",\n week_start, week_end)\n week_reps.each do |rep|\n if (rep.state == Activity::EXPIRED)\n act_payout = act_payout - node.penalty\n end\n end\n \n return count + act_payout\n end",
"def create\n @day ||= Weekday.day\n @days ||= Weekday.days\n @batch = Weekday.set_day(params[:weekday][:batch_id], params[:weekdays])\n flash[:notice] = t('weekday_create')\n end",
"def set_weekly_schedule\n @weekly_schedule = WeeklySchedule.find(params[:id])\n end",
"def week( date = Date.today )\n (0...weeks.size).find { |i| weeks[i].include? date } + 1\n end",
"def set_weekly_load\n sum_weekly_load = 0 + @daily_load\n # get all surveys from the past 6 days + today\n one_week_ago_start = @start_of_today - (6 * SECONDS_IN_ONE_DAY)\n surveys_this_week = Survey.for_user(@user_id).post_practice.surveys_for_week(one_week_ago_start, @end_of_today)\n # sum all surveys\n surveys_this_week.each do |survey|\n if survey.session_load.nil?\n return\n else\n sum_weekly_load += survey.session_load\n end\n end\n return sum_weekly_load\n end",
"def each_thursday( n=1, offset=0, dur=1); each_wdays(self.Thu,n,offset,dur); end",
"def expression\n case frequency\n when :every\n DayOfWeek.new(day_of_week)\n else\n DayInMonth.new(day_of_week, frequency)\n end\n end",
"def create_recurrences(transaction)\n CreateRecurrencesJob.perform_later(\n transaction.class.to_s,\n transaction.id.to_s\n )\n end",
"def +(num)\n # raise ArgumentError, \"Must pass Integer or Float\" unless rnum = num.to_i\n Week.new(@days[6] + num.to_i)\n end",
"def change_week\n @tasks = @company.tasks\n @timesheet = Timesheet.new\n @timesheet.timesheet_line_items.build\n\n cur_week = params[:date].to_date\n @week = cur_week.beginning_of_week\n if params[:cur_week]== \"next_week\"\n @week = @week+ 7.days\n else\n @week = @week- 7.days\n end\n respond_to do |format|\n format.js\n end\n end",
"def fortnights ; self * 2.weeks ; end",
"def week_index\n @week_index ||= date.wday\n end",
"def registration_weeks\n result = 0\n weeks = 0\n if registration_start_date && registration_end_date\n weeks = Date.new(registration_start_date.year, 12, 31).\n strftime('%W').to_i\n\n result = get_registration_end_week - get_registration_start_week + 1\n end\n result < 0 ? result + weeks : result\n end",
"def each_friday( n=1, offset=0, dur=1); each_wdays(self.Fri,n,offset,dur); end",
"def week\n @todoas = Todoa.where(user_id: current_user.id,done: false).where('due BETWEEN ? AND ?', Date.today, Date.today + 7.day)\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def weeks\n\t\tk = offset( first_day.cwday )\n\n [ first_week( k ) ] + middle_weeks( DPW - k )\n end",
"def sequential_day\n ActionPlan.sequential_day_for(week,day)\n end",
"def set_project_weekly\n @project_weekly = ProjectWeekly.find(params[:id])\n end",
"def create_default_estimated_date\n Date.today + 7\n end"
] |
[
"0.7258167",
"0.70177436",
"0.6931422",
"0.6872182",
"0.669048",
"0.66295546",
"0.65753394",
"0.65362185",
"0.64588416",
"0.6399074",
"0.63694876",
"0.63147646",
"0.6279019",
"0.62297064",
"0.62051916",
"0.6201109",
"0.61874104",
"0.61564213",
"0.6124599",
"0.6124599",
"0.6082932",
"0.6044308",
"0.60435706",
"0.60128117",
"0.5983224",
"0.5982332",
"0.5982332",
"0.59487176",
"0.5940325",
"0.59075415",
"0.5894127",
"0.58920205",
"0.5875507",
"0.5870938",
"0.58679634",
"0.5862787",
"0.58619887",
"0.5860711",
"0.5849764",
"0.5844208",
"0.58426267",
"0.58419573",
"0.58126533",
"0.5809849",
"0.57908833",
"0.5771971",
"0.5771971",
"0.57710785",
"0.5769616",
"0.57645273",
"0.5740449",
"0.57367504",
"0.57186264",
"0.5718097",
"0.56808424",
"0.5677297",
"0.5673793",
"0.56628346",
"0.5652906",
"0.5629099",
"0.5629099",
"0.5619517",
"0.561185",
"0.56071395",
"0.5590265",
"0.558778",
"0.5569746",
"0.55571795",
"0.5557164",
"0.5535146",
"0.5527653",
"0.5526291",
"0.55123675",
"0.5505628",
"0.54908335",
"0.54736423",
"0.54736423",
"0.5468582",
"0.54539245",
"0.5450856",
"0.54317504",
"0.5427765",
"0.5420863",
"0.54187465",
"0.541444",
"0.54142016",
"0.54139256",
"0.5400668",
"0.5395883",
"0.5393272",
"0.5388626",
"0.53875184",
"0.5379452",
"0.53785074",
"0.5377579",
"0.5374377",
"0.53709316",
"0.5370725",
"0.53703976"
] |
0.68449664
|
5
|
Create a monthly recurrence.
|
def monthly(options = {})
branch options.merge(every: :month)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def create(opts)\n @frequence = opts[:frequence] if opts[:frequence].in? Recurrence::FREQUENCES\n @monthly = array_to_integer(opts[:monthly])\n @count = to_integer(opts[:count])\n @until = string_to_date(opts[:until])\n self\n end",
"def create_expenses\n expense_id = nil\n @expense = @account.expenses.create(expense_params)\n step = params[:expense_form][:recurrence].to_i\n\n if @expense.valid? && step != 0\n @expense.month_id = @expense.due_date.mon\n @expense.save \n start_month = @expense.due_date.mon + step\n number_of_months = step\n (start_month..12).step(step).each do |month|\n @expense = @account.expenses.new(expense_params)\n @expense.month_id = month\n @expense.due_date = @expense.due_date.to_date >> number_of_months\n number_of_months += step\n @expense.related_to = expense_id || @expense.id\n @expense.save\n expense_id ||= @expense.id\n end\n elsif @expense.valid?\n @expense.month_id = @expense.due_date.mon\n @expense.save\n end\n @expense.valid?\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def monthly\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def generate_month_expenses\n Expense.all.each do |expense|\n MonthExpense.create(month_id: self.id, expense_id: expense.id)\n end\n end",
"def schedule_recurring_task_creation(task)\n recurring_scheduler = Scheduler.new\n @recurring_schedulers << recurring_scheduler\n\n recurring_scheduler.schedule.every \"#{Helpers.convert_frequency_to_seconds(task.frequency).to_s}s\" do\n new_task = Task.new\n new_task.description = task.description\n new_task.frequency = task.frequency\n new_task.creation_date = Time.now.getlocal\n new_task.target_date = Helpers.calculate_task_target_date(\n new_task.creation_date,\n new_task.frequency\n )\n new_task.recurring_scheduler_id = recurring_scheduler.id\n\n new_task.create_reminder_notification\n new_task.create_failed_notification\n\n add_task(new_task)\n end\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def each_july( n=1); each_monthnum(self.Jul,n); end",
"def create_results\n loop_start_date = start_date.at_beginning_of_month\n loop_end_date = end_date.at_beginning_of_month\n\n while loop_start_date < loop_end_date\n result_start_date = loop_start_date\n result_end_date = loop_start_date.next_month\n \n results.create(start_date: result_start_date, end_date: result_end_date, amount: 0, precision: 'month', status: 0)\n\n loop_start_date = result_end_date\n end\n end",
"def create_monthly_data\n number = @slide_number.to_i + 1\n monthly_data = Nokogiri::HTML(\n open(\n \"#{ENV['API_DOMAIN_2']}#{ENV['API_DOMAIN_2_MONTHLY']}\"\n )\n ).css(\"div.shareable-section-wrapper\").last\n\n data = {\n sign: @sign_name.to_s,\n duration: \"monthly\",\n horoscope_text: monthly_data.css(\"div[#{number}]\").text.split(' ')[1..-1].join(' ')\n } if monthly_data\n Horoscope.create(data) if monthly_data and data\n end",
"def each_may( n=1); each_monthnum(self.May,n); end",
"def month()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Month::MonthRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def add_recurrence(type: :week, on: on = nil, at: at = nil)\n type = type.to_sym\n unless [:week, :day].include? type\n raise \"Type must be either :week or :day\"\n end\n if type == :week and (on.nil? or (on.is_a?(Array) and on.empty?))\n raise \"Weekdays must be specified when selecting the :week type\"\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if self.schedule.nil?\n schedule = Montrose::Schedule.new\n end\n if at.nil?\n raise \"Time must be specified in parameter 'at'\"\n else\n schedule.add Montrose.every(type, on: on, at: at).starts(created_at)\n self.write_attribute(self.class.schedulable_attribute, schedule)\n end\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurring; end",
"def schedule_repetition\n self.due = Date.today + interval\n self.studied_at = Date.today\n end",
"def monthly_timesheet\n \n end",
"def create_date_value\n \n 1.upto(months.length) do |month|\n 1.upto(month) do |day|\n arr << [\"2015#{day}#{month}\", day_of_week]\n end\n end\nend",
"def each_monthnum(nmonth,n=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt >> (nmonth - dt.month)%12 }\n s.increment { |dt,i| dt.to_date >> i*12 } \n s.span { |dt| dt.to_date >> 1 }\n end\n end",
"def fixed_monthly_payment(amount, months, ir )\n amount*( ir * ( 1 + ir ) **months )/(( 1 + ir )**months - 1 )\nend",
"def each_months(n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt.to_date >> offset }\n s.increment { |dt,i| dt.to_date >> i }\n s.span { |dt| dt.to_date >> dur }\n end\n end",
"def <<(n)\n date_with_offset(-n, :month)\n end",
"def month() end",
"def months() 30 * days end",
"def start_recurring_payment\n return unless recurring_period.present?\n run_at = nil\n if recurring_period.to_s.is_i? # each custom days\n run_at = recurring_period.to_i.days.from_now\n # run_at = recurring_period.to_i.minutes.from_now\n else\n case recurring_period\n when 'daily'\n run_at = 1.day.from_now\n when 'weekly'\n run_at = 7.days.from_now\n when 'monthly'\n run_at = 1.month.from_now\n when 'quarterly'\n run_at = 3.months.from_now\n when 'biannually'\n run_at = 6.months.from_now\n when 'yearly'\n run_at = 1.year.from_now\n end\n end\n Delayed::Job.enqueue(LongTasks::RecurringPaymentNotification.new(id), run_at: run_at - 1.day) if run_at && ['tithe', 'partnership'].include?(goal)\n Delayed::Job.enqueue(LongTasks::RecurringPayment.new(id), run_at: run_at) if run_at\n end",
"def make_days\n month = (1..@day_num).collect do |day|\n Day.new(Date.parse(\"#{@year}-#{@month}-#{day}\"))\n end\n\n month[0].date.wday.times { month.insert(0, Day.new(Date.new))}\n month\n end",
"def increment_by_days count\n new_day = @day\n new_month = @month\n new_year = @year \n \n while count > 0\n days_to_next_month = days_in_month(new_month, new_year) - new_day + 1\n \n if (days_to_next_month > count)\n new_day = new_day + count\n count = 0 \n else\n new_day = 1\n new_month = new_month + 1\n if (new_month > 12)\n new_month = 1\n new_year = new_year + 1\n end\n \n count = count - days_to_next_month \n end\n end\n \n return MyDate.new new_day, new_month, new_year\n end",
"def each_june( n=1); each_monthnum(self.Jun,n); end",
"def end_of_month\n self.class.new year, month + 1, 0\n end",
"def new_schedule(*args)\n if !args.all? { |e| e.is_a?(Integer) && e >= 0 && e <= 6 }\n return \"Please enter a number from 0-6 where each number represents a day of the week. 0 represents Sunday, 1 represents Monday, etc.\"\n end\n schedule1 = Schedule.new(self.first_event, duration: self.duration_mins.minutes )\n schedule1.add_recurrence_rule Rule.weekly.day(args)\n self.schedule = schedule1\n self.save!\n end",
"def setup_months(start_month, end_month)\n @months = []\n while start_month <= end_month\n @months << start_month\n start_month += 1\n end\n end",
"def each_march( n=1); each_monthnum(self.Mar,n); end",
"def period\n case self.recurring_month\n when 12\n 1.year # 1.year != 12.months\n else\n self.recurring_month.months\n end\n end",
"def next!\n if @date.month + 1 > 12\n @date = Date.new(@date.year+1,@date.month,1)\n else\n @date = Date.new(@date.year,@date.month+1,1)\n end\n end",
"def each_april( n=1); each_monthnum(self.Apr,n); end",
"def each_october( n=1); each_monthnum(self.Oct,n); end",
"def period_in_words\n case recurring_month\n when 12\n 'yearly'\n when 1\n 'monthly'\n when 0\n \"once\"\n else\n \"every #{recurring_month} months\"\n end\n end",
"def make_premium(month_number)\n self.premium_expiry_date = Time.now + month_number.to_i.months\n self.save\n end",
"def get_next_month(number)\n month = number.to_i < @start.day ? (@start.month == 12 ? 1 : @start.month + 1) : @start.month\n end",
"def create_recurrences(transaction)\n CreateRecurrencesJob.perform_later(\n transaction.class.to_s,\n transaction.id.to_s\n )\n end",
"def months\n Thread.current[:datet_mode] = :months\n return self\n end",
"def months ; self * 30.days ; end",
"def next_month(from)\n from.next_month.change(day: 1)\n end",
"def each_december( n=1); each_monthnum(self.Dec,n); end",
"def schedule_payment! amount, due_at = Time.now\n scheduled_payments.create :amount => amount, :due_at => due_at\n end",
"def next_month(months = 1)\n advance(months: months)\n end",
"def add_month_to_db\n \n year, month = Macroval.most_recent_month \n \n new_month = (month == 12) ? 1 : month+1\n new_year = (month == 12) ? year+1 : year\n \n Macroval.create( :year_month => new_year+new_month.to_f/100 ) \n \n redirect_to :action => 'add_latest_data'\n \n end",
"def move_to_next_month\n self.date = self.date + 1.month\n self.save!\n end",
"def each_february( n=1); each_monthnum(self.Feb,n); end",
"def each_january( n=1); each_monthnum(self.Jan,n); end",
"def pattern\n if valid_period?\n @pattern = eval(\"RecurringTodos::#{recurring_period.capitalize}RecurrencePattern.new(user)\")\n @pattern.build_from_recurring_todo(self)\n end\n @pattern\n end",
"def next_meeting(after_time = Time.now.utc )\n # puts \"Looking up next meeting after #{after_time}\"\n if recurrence_frequency.blank?\n return start_time\n end\n\n if after_time < start_time\n return start_time\n end \n\n after_time = after_time.local_from_utc(self.time_zone) \n\n\n # Advance the starting time in the case when it falls after the beginning of\n # a meeting on the same day. We do this so that we can use \"day precision\"\n # (PDate.day) in the Runt library instead of \"minute precision\" (PDate.min),\n # which performs terribly.\n start_time = start_time_local\n if(after_time.hour > start_time.hour or ( after_time.hour == start_time.hour and after_time.min > start_time.min))\n after_time = after_time + 1.day\n after_time = Time.gm(after_time.year, after_time.month, after_time.day, 0, 0)\n end\n\n case recurrence_frequency\n when 'daily'\n end_time = after_time + 25.hours \n # after_time -= 1.day\n start_date = PDate.day(after_time.year, after_time.month, after_time.day , after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'weekdays'\n # Make the range over 3 days so that Friday night searches will still turn\n # up Monday as the next day.\n end_time = after_time + 3.days\n start_date = PDate.day(after_time.year, after_time.month, after_time.day, after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'monthly'\n eom = (after_time + 40.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eom.year, eom.month, eom.day)\n when 'weekly'\n eow = (after_time + 8.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eow.year, eow.month, eow.day)\n when 'yearly'\n # Just doing \"after_time + 367.days\" results in a bit of a performance hit\n # as hundreds of days are compared. We'll try to narrow it a bit. Not too\n # much, because we don't have time to actually write unit tests and make\n # sure the narrowing code works. :) Which is why the comment is here.\n st = after_time + 250.days\n et = st + 150.days\n start_date = PDate.day(st.year, st.month, st.day)\n end_date = PDate.day(et.year, et.month, et.day)\n end \n # puts \" Range #{start_date.to_s} - #{end_date.to_s}\"\n d_range = DateRange.new(start_date, end_date)\n sched = Schedule.new\n event = Event.new((self.invitation.name rescue \"no name\"))\n sched.add(event,self.runt_expression)\n dates = sched.dates(event,d_range)\n\n next_mtg = dates.first\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, start_time_local.hour, start_time_local.min)\n result = nil\n begin\n result = next_mtg_time.local_to_utc(self.time_zone)\n rescue TZInfo::PeriodNotFound\n # This only happens when the time is during the one hour which is skipped\n # during the transition to DST. For example, only on Sun Mar 08 02:15:00\n # (see ticket #744).\n next_hour = start_time_local.hour + 1\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, next_hour, start_time_local.min)\n retry\n end\n return result\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def update_monthly_happiness_distributions! \n HappinessEntry.beginning_of_month_days.each do |beginning_of_month_day|\n uid = uid_for_month(beginning_of_month_day)\n end_of_month_day = beginning_of_month_day.end_of_month\n entries_for_month = HappinessEntry.in_month(beginning_of_month_day, end_of_month_day)\n update_happiness_distribution! uid, :month, entries_for_month \n end\n end",
"def >>(months)\n y, m = (@year * 12 + (@month - 1) + months).divmod(12)\n m, = (m + 1) .divmod(1)\n d = @day\n d -= 1 until self.class.valid?(y, m, d)\n self.class.new(y,m,d)\n end",
"def add_months(months = 1)\n months = months.to_i\n cur_month = @t_month\n cur_day = @t_day\n next_month = cur_month + months.to_i\n \n #Check if we have to alter the amount of years based on the month-change.\n if next_month > 12 or next_month <= 0\n years = (next_month.to_f / 12.0).floor\n \n newmonth = next_month - (years * 12)\n if newmonth == 0\n newmonth = 12\n years -= 1\n end\n \n self.month = newmonth\n self.add_years(years) if years != 0\n else\n raise \"Invalid month: '#{next_month}'.\" if next_month <= 0 or next_month > 12\n @t_month = next_month\n @t_day = 1\n end\n \n \n #If the month changed, and the day was the last day of the previous month, and there isnt that many days in the new month, set the day to the last day of the current month.\n dim = self.days_in_month\n \n if dim < cur_day\n @t_day = dim\n else\n @t_day = cur_day\n end\n \n return self\n end",
"def months; self * MONTH; end",
"def payment_schedule(from_date = nil)\n schedule = []\n if recurring_payments?\n (0...recurring_number).each do |period|\n xdays = period * recurring_period\n schedule << { due_on: (from_date ? from_date.to_date + xdays.days : xdays),\n period_payment: payment_price,\n total_due: (period + 1) * payment_price }\n end\n # adjust the last entry\n schedule.last[:total_due] = price\n schedule.last[:period_payment] = price - (recurring_number - 1) * payment_price\n else\n schedule << { due_on: (from_date ? from_date.to_date : 0), period_payment: payment_price, total_due: payment_price }\n end\n schedule\n end",
"def set_monthly\n @monthly = Monthly.find(params[:id])\n end",
"def calculate_month_and_next_month(year, month)\n check_date = Time.new(year, month)\n {:actual => check_date, :next => check_date.next_month}\n end",
"def maximum_number_of_months_to_recur\n self.period.length_in_months -\n self.period.month_for_date(date)\n end",
"def monthly\n NewsletterMailer.monthly\n end",
"def monthly\n keys = redis.keys(\"#{prefix_monthly}:*\")\n keys.zip(redis.mget(keys)).inject({}) { |t,p| t.merge(p.first.sub(\"#{prefix_monthly}:\", '') => p.last.to_i) }\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def month=(_arg0); end",
"def process\n @recurrences.each { |r| process_recurrence(r) }\n end",
"def fix_frequency\n return unless frequency.duration > 1.month\n if frequency.duration < 12.months\n if intervals.all? { |i| i.first_datetime.day == i.last_datetime.day }\n frequency.duration = frequency.units[:months].months\n end\n else\n if intervals.all? { |i| i.first_datetime.month == i.last_datetime.month && i.first_datetime.day == i.last_datetime.day }\n frequency.duration = (frequency.duration / 12.months).floor.years\n end\n end\n end",
"def every (date, &block)\n #debugger\n # need a way to differentiate monthly from weekly (e.g. every monday)\n # need a way to designate once a month (e.g. first monday or third monday) @period=:incremental\n if (date == :monthly) or (date == :month)\n # need a way to reconcile incremental/monthly/duration\n #@period = :monthly\n @increment=1.month\n else\n #@period=:incremental\n @increment=date\n end\n instance_eval &block\n cleanup\n end",
"def create_monthly_session(user)\n today = DateTime.now\n year = today.year\n month = today.month\n current_monthly_session = MonthlySession.new(:month => month, :year => year)\n current_monthly_session.user = user\n current_monthly_session.available_sessions = ENV['COMMUNITY_MONTHLY_SESSION_LIMIT']\n current_monthly_session.save!\n return current_monthly_session\n end",
"def each_august( n=1); each_monthnum(self.Aug,n); end",
"def initialize(month, start_date)\n @start_date = start_date\n raise(ArgumentError, \"Must start on Sunday\") if start_date.wday != 0\n\n @days = []\n (start_date..start_date + 6).each do |date|\n @days << Day.new(month, date)\n end\n end",
"def process_recurrence(recurrence)\n return true unless recurrence.today?\n recurrence.update_job\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def calculate_this_month\n site_id = params[:id]\n date_end = DateTime.now\n nrday = date_end.day.to_i\n nrday -= 1\n date_start = DateTime.now-nrday.days\n Delayed::Job.enqueue CalculateSite.new(site_id,date_start,date_end)\n #calculate_month(site_id,date_start,date_end)\n render :nothing => true\n end",
"def set_first_repetition\n first_repetition_date = Date.today + rand(1..3).days\n repetitions.create planned_date: first_repetition_date, actual_date: first_repetition_date\n end",
"def each_day_of_month(nday,dur=1)\n build_subrange do |s|\n s.step = 1\n s.adjust_range { |r| day_range(r) }\n s.offset do |dt| \n totdays = ((Date.civil(dt.year,dt.month,1) >> 1)-1).day\n dt.to_date + (nday - dt.day)%totdays\n end\n s.increment { |dt,i| dt.to_date >> i }\n s.span { |dt| dt.to_date + dur }\n end\n end",
"def add_month(age) \n GenFactor::sanitize_age((age + (1.0/12.0)))\n end",
"def expression\n case frequency\n when :every\n DayOfWeek.new(day_of_week)\n else\n DayInMonth.new(day_of_week, frequency)\n end\n end",
"def months ; Duration[self * 30 * 86400] ; end",
"def test_yearly_by_month_loop\n parse(\n 'FREQ=YEARLY;INTERVAL=1;UNTIL=20120203T225959Z;BYMONTH=2;BYSETPOS=1;BYDAY=SU,MO,TU,WE,TH,FR,SA',\n '2012-01-01 15:45:00',\n [\n '2012-02-01 15:45:00'\n ],\n '2012-01-29 23:00:00'\n )\n end",
"def monthly_payment(salary_per_annum)\n return salary_per_annum / 12\nend",
"def monthly(range)\n data = range(range, :skip_bitmap_count => true)\n\n data = data.group_by { |date, value| date.beginning_of_month }\n case self.type\n when :counter\n sum_up_grouped_data(data)\n when :bitmap\n bitmap_or_grouped_data(data)\n end\n end",
"def frm(r, n, po)\n\t## \n\t# interest rate is converted to fraction and made a monthly\n\tr = r.to_f/100/12\n\t##\n\t#number of years is converted to number of months\n\tn = n * 12\n\t##\n\t#monthly payment is calculated\n\tc = (r / (1 - (1+r) ** -n) ) * po\n\treturn c\nend",
"def create\n @sale_invoice = @monthly_movement.sale_invoices.build(params[:sale_invoice])\n @sale_invoice.date = \"#{params[:sale_invoice][:date].to_i + 1}/#{MonthlyMovement::MONTHS[@monthly_movement.month.to_sym]}/#{@monthly_movement.year}\".to_datetime\n @title = t('view.sale_invoices.new_title', month: @monthly_movement.month, year: @monthly_movement.year)\n\n respond_to do |format|\n if @sale_invoice.save\n format.html { redirect_to monthly_movement_sale_invoices_path(@monthly_movement), notice: t('view.sale_invoices.correctly_created') }\n format.json { render json: monthly_movement_sale_invoices_path(@monthly_movement), status: :created, location: @sale_invoice }\n else\n format.html { render action: 'new' }\n format.json { render json: @sale_invoice.errors, status: :unprocessable_entity }\n end\n end\n end",
"def get_monthly_payments(loan, interest, months)\n loan * (interest / (1 - (1 + interest)**(-months)))\nend",
"def month; end",
"def month; end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def set_recurrence\n @recurrence = Recurrence.find(params[:id])\n end",
"def create\n @monthly = current_user.monthlies.new(params[:monthly])\n\n respond_to do |format|\n if @monthly.save\n session[:monthly] = @monthly\n #format.html { redirect_to @monthly, notice: 'Monthly was successfully created.' }\n format.html { redirect_to time_records_url }\n format.json { render json: @monthly, status: :created, location: @monthly }\n else\n format.html { render action: \"new\" }\n format.json { render json: @monthly.errors, status: :unprocessable_entity }\n end\n end\n end",
"def increment_month!\n if month != 12\n # just bump up a number\n self.date = ZDate.format_date(year_str, month + 1)\n else\n self.date = ZDate.format_date(year + 1)\n end\n end",
"def expiration_month\n @months = [\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\"10\",\"11\",\"12\"]\n end",
"def nwrug_meet_for year, month\n beginning_of_month = Date.civil(year, month, 1)\n nwrug = beginning_of_month + (18 - beginning_of_month.wday)\n nwrug += 7 if beginning_of_month.wday > 4\n\n # Make sure we skip to the next month if we've gone past this month's meet\n if nwrug < Date.today\n if month == 12\n month = 1\n year += 1\n else\n month += 1\n end\n nwrug = nwrug_meet_for year, month\n end\n\n nwrug\nend",
"def get_monthly_values(resource, attribute)\n PatternsEngine.get_pattern_results(resource.send(\"#{attribute}_monthly_baseline\"),\n get_sorted_patterns(resource, \"#{attribute}_monthly_baseline\"),\n \"Month\",@report.start_date, @report.end_date)\n end",
"def create_batch\n all_months.each do |month|\n cash_flow = find_or_build_cash_flow(month, @category.id)\n\n cash_flow.planned = cash_flow_params[:value]\n cash_flow.save!\n end\n\n render json: { success: true }, status: :created\n end",
"def date_next_month(month)\n t = Time.now\n m = month || t.month + 1\n Time.utc(t.year, m, 1)\n end"
] |
[
"0.7131427",
"0.67616975",
"0.6515934",
"0.6245374",
"0.6135469",
"0.6029013",
"0.59832036",
"0.58939636",
"0.58793277",
"0.58254385",
"0.5818626",
"0.5780765",
"0.5768481",
"0.57178134",
"0.56691515",
"0.56400436",
"0.56400436",
"0.56329787",
"0.5617006",
"0.5615539",
"0.5614469",
"0.56066775",
"0.5591834",
"0.5559721",
"0.55461794",
"0.5537109",
"0.55316955",
"0.5529157",
"0.55252343",
"0.55176485",
"0.5502841",
"0.54976344",
"0.5483495",
"0.5464647",
"0.5456549",
"0.54514337",
"0.54344326",
"0.5413925",
"0.53934836",
"0.5385931",
"0.5383291",
"0.53741515",
"0.5372648",
"0.536981",
"0.53590614",
"0.5346231",
"0.5343894",
"0.5342453",
"0.5337378",
"0.53326726",
"0.53152937",
"0.5301183",
"0.52988005",
"0.5293457",
"0.52876705",
"0.5277331",
"0.5275417",
"0.5258983",
"0.5258192",
"0.5255621",
"0.5251055",
"0.5250804",
"0.52476084",
"0.52388",
"0.5216867",
"0.5214081",
"0.5208764",
"0.52078927",
"0.52068144",
"0.51994765",
"0.5188347",
"0.5182623",
"0.518225",
"0.5181538",
"0.51797134",
"0.5178208",
"0.516458",
"0.51623267",
"0.5157852",
"0.5131754",
"0.51296026",
"0.5120648",
"0.5118146",
"0.51047426",
"0.5086027",
"0.5084391",
"0.50836885",
"0.5081228",
"0.50798446",
"0.50798446",
"0.5060778",
"0.50605875",
"0.5052678",
"0.5033387",
"0.5028985",
"0.5020558",
"0.5020506",
"0.5015572",
"0.49960592"
] |
0.60182357
|
7
|
Create a yearly recurrence.
|
def yearly(options = {})
branch options.merge(every: :year)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def get_next_yr\n\tset_cur_year(get_cur_year+1)\nend",
"def no_repeat_years(first_year, last_year)\nend",
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def make_year(year, bias); end",
"def new_year(date) = ::Date.new(Integer === date ? date : date(date).year, 1, 1, reform_jd).new_start(::Date::GREGORIAN)",
"def each_years(n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| Date.civil(dt.year + offset, dt.month, dt.day) }\n s.increment { |dt,i| Date.civil(dt.year + i, dt.month, dt.day) }\n s.span { |dt| Date.civil(dt.year + dur, dt.month, dt.day) }\n end \n end",
"def calculate_yearly_rents_years\n convert_lease_transaction_date\n years = @lbtt_return.lease_end_date.year - @lbtt_return.lease_start_date.year\n years += 1 if @lbtt_return.lease_end_date >= @lbtt_return.lease_start_date.next_year(years)\n years\n end",
"def next_year(years = 1)\n advance(years: years)\n end",
"def add_years(years = 1)\n @t_year = @t_year + years.to_i\n return self\n end",
"def years() 365 * days end",
"def year(input) = new_year(input).year - 621",
"def succ\n FiscalYear.new(self + 1)\n end",
"def next_year\n AcademicYear.find_by(year: self.year + 1)\n end",
"def advance_years(years)\n advance_to_date(to_date >> (years*12))\n end",
"def years ; self * 365.days ; end",
"def future(year, month, day)\n years = (10 ** 9) / 60 / 60 / 24 / 365\n days = (10 ** 9) / 60 / 60 / 24 % 365\n\n year = year + years\n \n\nend",
"def grow_one_year(starting_balance, growth_rate)\n starting_balance * (1.0 + growth_rate)\nend",
"def next_years\n current_year = Time.now.year\n current_year..(current_year + 4)\n end",
"def years; self * YEAR; end",
"def start_year\n Time.now.year - 18\n end",
"def year_calculations\n\t\t@prev_beg_range = @beg_range.to_date.beginning_of_year.prev_year\n\t\t@prev_end_range = @beg_range.to_date.beginning_of_year-1.day\n\t\t@next_beg_range = @beg_range.to_date.next_year.beginning_of_year\n\t\t@next_end_range = @beg_range.to_date.next_year.end_of_year\n\tend",
"def create(opts)\n @frequence = opts[:frequence] if opts[:frequence].in? Recurrence::FREQUENCES\n @monthly = array_to_integer(opts[:monthly])\n @count = to_integer(opts[:count])\n @until = string_to_date(opts[:until])\n self\n end",
"def calculate_years(principal, interest, tax, desired)\n# principal amount\n year = 0\n while principal < desired\n year += 1\n income = principal * interest\n principal += income - income * tax\n end\n year\nend",
"def effective_year\n if next_year_start_at && Time.zone.now < 1.year.from_now(next_year_start_at)\n if Time.zone.now < next_year_start_at\n return Time.zone.now.year\n elsif Time.zone.now >= next_year_start_at\n if Time.zone.now.year == next_year_start_at.year\n return Time.zone.now.year + 1\n else\n return Time.zone.now.year\n end\n end\n elsif Time.zone.now.month == 12 && Time.zone.now.day >= 1\n return Time.zone.now.year + 1\n end\n\n Time.zone.now.year\n end",
"def year()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Year::YearRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def new_year(input)\n equinox = Integer === input ? @astro.solar_event(:march_equinox, input) : @astro.previous(:march_equinox, input)\n date = local_date(equinox)\n equinox.localtime(utc_offset).hour < 12 ? date : date + 1\n end",
"def year_frac()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::YearFrac::YearFracRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def years ; Duration[self * 365 * 86400, :years] ; end",
"def years\n Thread.current[:datet_mode] = :years\n return self\n end",
"def start_year\n Time.now.year - 75\n end",
"def new(year = -4712, month = 1, day = 1, sg = ITALY)\n # we can catch this here already\n raise ArgumentError, \"invalid date\" if month > 12\n \n unless valid_civil?(year, month, day, sg)\n raise ArgumentError, \"invalid date, because it falls in the dropped days range of the calendar reform\"\n end\n \n components = NSDateComponents.new\n components.year = year\n components.month = month\n components.day = day\n \n # TODO: check when this can return `nil' instead of a date\n date = GREGORIAN_CALENDAR.dateFromComponents(components)\n interval = date.timeIntervalSinceReferenceDate\n \n mrdate = alloc.initWithTimeIntervalSinceReferenceDate(interval)\n mrdate.sg = sg\n \n # no positive wrap around!\n if mrdate.day < day && (mrdate.month == (month + 1) % 12)\n raise ArgumentError, \"invalid date\"\n end\n \n mrdate\n end",
"def year(year_range = (1930..1950))\n rand(year_range)\nend",
"def gas_year\n y = year\n if self< Date.new(y,10,1)\n y\n else\n y+1\n end\n end",
"def current_planning_year_year\n current_fiscal_year_year + 1\n end",
"def in_the_last_year\n date_factory(Time.random(:year_range=>1))\n end",
"def recurring; end",
"def build_school_year(year=nil)\n return SchoolYear.new if year.blank?\n\n starting_day = (year.is_a? Date) ? year : start_date_from_year(year)\n SchoolYear.new(start_date: starting_day, end_date: starting_day.next_year)\n end",
"def index\n @year = set_year\n @travel_dates = TravelDate.for_year(set_year)\n @first_year = TravelDate.first_year\n @final_year = TravelDate.final_year\n @next_year = @year + 1\n @prev_year = @year - 1\n end",
"def new_years_day_for(year)\n nyd = Date.new(year,1,1)\n if nyd.saturday?\n Date.new(year,1,3)\n elsif nyd.sunday?\n Date.new(year,1,2)\n else\n nyd\n end\n end",
"def increment_by_days count\n new_day = @day\n new_month = @month\n new_year = @year \n \n while count > 0\n days_to_next_month = days_in_month(new_month, new_year) - new_day + 1\n \n if (days_to_next_month > count)\n new_day = new_day + count\n count = 0 \n else\n new_day = 1\n new_month = new_month + 1\n if (new_month > 12)\n new_month = 1\n new_year = new_year + 1\n end\n \n count = count - days_to_next_month \n end\n end\n \n return MyDate.new new_day, new_month, new_year\n end",
"def no_repeat_years(first_yr, last_yr)\n result = []\n (first_yr..last_yr).each do |num|\n if not_repeat_year?(num)\n result << num\n end\n end\n result\nend",
"def to_rd\n normal_days = 365 * (@year - 1)\n leap_days = (((@year - 1) / 4).floor -\n ((@year - 1) / 100).floor +\n ((@year - 1) / 400).floor)\n # The following formula assumes that February has 30 days.\n previous_days = ((367 * @month - 362) / 12).floor\n # Correction for the previous formula.\n correction = nil\n # We are before February, no correction needed.\n if @month <= 2\n correction = 0\n # Leap year => February has 29 days - 30 = -1.\n elsif leap?\n correction = -1\n # Normal year => February has 28 days - 30 = -2.\n else\n correction = -2\n end\n return (EPOCH - 1 + normal_days + leap_days + previous_days +\n correction + @day)\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).reduce([]) do |output, el|\n if not_repeat_year?(el)\n output << el\n else\n output\n end\n end\nend",
"def year() end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def year\n Faker::Time.backward(days: rand_in_range(365, 5475), period: :all, format: '%Y').to_i\n end",
"def to_years; Rational === @val ? @val/12 : @val/12.0 end",
"def to_rd\n return EPOCH + 365*(@year-1) + 30*(@month-1) + @day - 1\n end",
"def compute_yearwise(incomes_or_deductions)\n income_deduction_per_year = Hash.new(0)\n\n incomes_or_deductions.each do |income_deduction|\n working_days_in_year = Float(52*5)\n daily_income = 0\n\n case income_deduction.frequency\n when \"daily\"\n daily_income = income_deduction.amount_in_cents\n when \"weekly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year/52)\n when \"biweekly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year/26)\n when \"monthly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year/12)\n when \"quarterly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year/4)\n when \"half_yearly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year/2)\n when \"yearly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year)\n end\n\n income_deduction.start_date = TimeKeeper.date_of_record.beginning_of_year if income_deduction.start_date.to_s.eql? \"01-01-0001\" || income_deduction.start_date.blank?\n income_deduction.end_date = TimeKeeper.date_of_record.end_of_year if income_deduction.end_date.to_s.eql? \"01-01-0001\" || income_deduction.end_date.blank?\n years = (income_deduction.start_date.year..income_deduction.end_date.year)\n\n years.to_a.each do |year|\n actual_days_worked = compute_actual_days_worked(year, income_deduction.start_date, income_deduction.end_date)\n income_deduction_per_year[year] += actual_days_worked * daily_income\n end\n end\n\n income_deduction_per_year.merge(income_deduction_per_year) { |k, v| Integer(v) rescue v }\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def initialize(start_year=nil)\n start_year ||= find_default_start_year\n @start_date = Date.new(start_year,8,1)\n @end_date = Date.new((start_year + 1),7,31)\n end",
"def fridays_in_year(year)\n current_week = 1\n current_day = 5\n current_date = DateTime.commercial(year, current_week, current_day)\n fridays_per_month = Array.new(12,0)\n while current_date.year == year\n fridays_per_month[current_date.month - 1] += 1\n current_date += 7\n end\n fridays_per_month\nend",
"def calculate_fiscal_year(date = Date.current)\n date >= Date.new(date.year, 05, 01) ? date.year+1 : date.year\n end",
"def year\n ((semester - 1) / 2) + 1\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).reduce([]) do |arr, year|\n if not_repeat_year?(year)\n arr << year\n else\n arr\n end\n end\nend",
"def create_yearly_data\n number = @slide_number.to_i + 1\n yearly_data = Nokogiri::HTML(\n open(\n \"#{ENV['API_DOMAIN_2']}#{Time.now.year}-horoscope\"\n )\n ).css(\"div.shareable-section-wrapper.shareable-yearly\").last\n return {} if yearly_data.blank?\n inner_data = yearly_data.css(\"div[#{number}] p\")\n final_data = \"\"\n inner_data.css(\"p\").each do |para|\n final_data = final_data + para.text + \"</br></br></t>\"\n end\n\n data = {\n sign: @sign_name.to_s,\n duration: \"yearly\",\n horoscope_text: final_data\n } if final_data\n Horoscope.create(data) if final_data and data\n end",
"def get_year_ary\n (Date.today.year-99..Date.today.year).inject([]){|x,y| x << y}.reverse\n end",
"def init_yearly_interest_for(account)\n @task_manager.every '1y' do\n pay_interest_on account\n end\n end",
"def years\n self.to_i * 31_557_600\n end",
"def next!\n if @date.month + 1 > 12\n @date = Date.new(@date.year+1,@date.month,1)\n else\n @date = Date.new(@date.year,@date.month+1,1)\n end\n end",
"def create_expenses\n expense_id = nil\n @expense = @account.expenses.create(expense_params)\n step = params[:expense_form][:recurrence].to_i\n\n if @expense.valid? && step != 0\n @expense.month_id = @expense.due_date.mon\n @expense.save \n start_month = @expense.due_date.mon + step\n number_of_months = step\n (start_month..12).step(step).each do |month|\n @expense = @account.expenses.new(expense_params)\n @expense.month_id = month\n @expense.due_date = @expense.due_date.to_date >> number_of_months\n number_of_months += step\n @expense.related_to = expense_id || @expense.id\n @expense.save\n expense_id ||= @expense.id\n end\n elsif @expense.valid?\n @expense.month_id = @expense.due_date.mon\n @expense.save\n end\n @expense.valid?\n end",
"def real_study_years\n if finished?\n end_date = finished_on.to_time\n elsif absolved?\n end_date = disert_theme.defense_passed_on.to_time\n else\n end_date = Time.now\n end\n return (end_date - enrolled_on.to_time).div(1.year) + 1\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def apply_rule(rule, from_offset, to_offset, year); end",
"def apply_rule(rule, from_offset, to_offset, year); end",
"def range\n beginning_of_period..(self.next_year).beginning_of_period\n end",
"def make_tick_dates(from_year, to_year, interval)\n (from_year..to_year).step(interval).map { |year| Date.new(year,1,1) }\n end",
"def no_repeat_years(first_yr, last_yr)\n array = []\n (first_yr..last_yr).each do |year|\n array << year if not_repeat_year?(year)\n end\n array\nend",
"def yearly_discount(int_disc)\n\t 12.0 * (1.0 - (int_disc ** (1.0/12.0)))\n end",
"def end_year\n Time.now.year - 90\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select { |e| not_repeat_year?(e) }\nend",
"def day_of_year\n (seconds_since_start_of_year / D_SECS).to_i + 1\n end",
"def make_one_year_older\n @age += 1\n end",
"def recurrence\n { ATTR_RECURRENCE[@attribute] => 1 }\n end",
"def make_one_year_older\n @age +=1\n end",
"def create_date_value\n \n 1.upto(months.length) do |month|\n 1.upto(month) do |day|\n arr << [\"2015#{day}#{month}\", day_of_week]\n end\n end\nend",
"def year1\n @year1 = @subtotal3 + @mobilisation + @tupe\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select{|yr|not_repeat_year?(yr)}\nend",
"def get_years_to_date_collection\n (get_system_asset_starting_year..Date.today.year).to_a\n end",
"def a_year()\n now = Time.now\n if now.month < 4\n now.year - 1\n else\n now.year\n end\nend",
"def yearly_rate(*args)\n if paid?\n if yearly?\n rate(*args) / duration_parts[0] #number of years\n else\n rate(*args) / duration_in_months * 12\n end\n else\n nil\n end\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select {|x| not_repeat_year?(x) }\nend",
"def frequency\n interval || 1.year\n end",
"def setup_yearly_rents\n model = load_step\n (0..@lbtt_return.yearly_rents.size - 1).each do |i|\n @lbtt_return.yearly_rents[i].rent ||= @lbtt_return.annual_rent\n end\n model\n end",
"def year\n self.range('year')\n end",
"def period\n case self.recurring_month\n when 12\n 1.year # 1.year != 12.months\n else\n self.recurring_month.months\n end\n end",
"def end_of_month\n self.class.new year, month + 1, 0\n end",
"def create\n @calendar = Calendar.new(calendar_params)\n dstart = Date.new(@calendar.year_c, 1, 1)\n dfinish = Date.new(@calendar.year_c + 1, 1, 1)\n while dstart < dfinish\n cld = Calendar.new\n cld.year_c = @calendar.year_c\n cld.date_c = dstart\n cld.is_output = (dstart.wday == 6 or dstart.wday == 0 ? true : false)\n cld.save\n dstart = dstart + 1.day\n end\n\n respond_to do |format|\n format.html { redirect_to calendars_path(year: @calendar.year_c), notice: 'Calendar was successfully created.' }\n end\n end",
"def year_week\n @year_week ||= (((date-start_of_year)+1)/7.0).ceil\n end",
"def fiscal_new_year_date(date = Date.current)\n Date.new(calculate_fiscal_year(date),05,01)\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select { |year| not_repeat_year?(year) }\nend",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def initialized_year_hash\n year_in_range = self.startDate.year\n year_hash = {}\n while year_in_range <= self.endDate.year\n year_hash[year_in_range] = BigDecimal(0.0, 10)\n year_in_range += 1\n end\n year_hash\n end",
"def fy(d)\n\t\td = d.to_date\n\t\tif(d.month >= 2)\n\t\t\treturn (d.year+1)\n\t\telse\n\t\t\treturn d.year\n\t\tend\n\tend",
"def w_year; end",
"def each_july( n=1); each_monthnum(self.Jul,n); end",
"def cwyear\n end"
] |
[
"0.6312094",
"0.6305786",
"0.6294956",
"0.6265978",
"0.6024861",
"0.6016748",
"0.5953853",
"0.59454286",
"0.5941457",
"0.5908073",
"0.5851626",
"0.5850015",
"0.583518",
"0.5827798",
"0.5819018",
"0.577236",
"0.5748866",
"0.57324785",
"0.5728791",
"0.5721094",
"0.5694056",
"0.56908935",
"0.5672119",
"0.5653407",
"0.564967",
"0.564407",
"0.5617291",
"0.56170887",
"0.56156445",
"0.5596241",
"0.5594866",
"0.5590379",
"0.5582518",
"0.55809397",
"0.55379206",
"0.55249345",
"0.54969996",
"0.5490768",
"0.54879165",
"0.54737896",
"0.5468637",
"0.54634684",
"0.5460318",
"0.5455363",
"0.5450278",
"0.5450278",
"0.5449402",
"0.54382914",
"0.54284084",
"0.54203373",
"0.5417046",
"0.54155415",
"0.541083",
"0.5406852",
"0.54036605",
"0.5402082",
"0.53903484",
"0.53875834",
"0.537243",
"0.5364299",
"0.5358365",
"0.5353827",
"0.534839",
"0.53418493",
"0.5336941",
"0.5336941",
"0.53294694",
"0.53292567",
"0.53292286",
"0.53263974",
"0.53262264",
"0.5325153",
"0.5321808",
"0.53106385",
"0.53073084",
"0.5303401",
"0.5301606",
"0.52970845",
"0.5296482",
"0.5290109",
"0.52745765",
"0.52738065",
"0.52711314",
"0.5269825",
"0.52656204",
"0.5256092",
"0.52509034",
"0.5248928",
"0.5248438",
"0.5231013",
"0.52260673",
"0.5225175",
"0.52210885",
"0.52197504",
"0.5193469",
"0.51919687",
"0.5186981",
"0.51854205",
"0.51849425"
] |
0.59366906
|
10
|
Create a recurrence starting at given timestamp.
|
def starts(starts_at)
merge(starts: starts_at)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def create_recurrences(transaction)\n CreateRecurrencesJob.perform_later(\n transaction.class.to_s,\n transaction.id.to_s\n )\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def schedule_recurring_task_creation(task)\n recurring_scheduler = Scheduler.new\n @recurring_schedulers << recurring_scheduler\n\n recurring_scheduler.schedule.every \"#{Helpers.convert_frequency_to_seconds(task.frequency).to_s}s\" do\n new_task = Task.new\n new_task.description = task.description\n new_task.frequency = task.frequency\n new_task.creation_date = Time.now.getlocal\n new_task.target_date = Helpers.calculate_task_target_date(\n new_task.creation_date,\n new_task.frequency\n )\n new_task.recurring_scheduler_id = recurring_scheduler.id\n\n new_task.create_reminder_notification\n new_task.create_failed_notification\n\n add_task(new_task)\n end\n end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def add_recurrence(type: :week, on: on = nil, at: at = nil)\n type = type.to_sym\n unless [:week, :day].include? type\n raise \"Type must be either :week or :day\"\n end\n if type == :week and (on.nil? or (on.is_a?(Array) and on.empty?))\n raise \"Weekdays must be specified when selecting the :week type\"\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if self.schedule.nil?\n schedule = Montrose::Schedule.new\n end\n if at.nil?\n raise \"Time must be specified in parameter 'at'\"\n else\n schedule.add Montrose.every(type, on: on, at: at).starts(created_at)\n self.write_attribute(self.class.schedulable_attribute, schedule)\n end\n end",
"def set_first_repetition\n first_repetition_date = Date.today + rand(1..3).days\n repetitions.create planned_date: first_repetition_date, actual_date: first_repetition_date\n end",
"def create(opts)\n @frequence = opts[:frequence] if opts[:frequence].in? Recurrence::FREQUENCES\n @monthly = array_to_integer(opts[:monthly])\n @count = to_integer(opts[:count])\n @until = string_to_date(opts[:until])\n self\n end",
"def add_occurrences!(event, at = [])\n Array(at).each do |time|\n OccurrenceEntry.create!(:post_id => id, :label => event, :at => time)\n end\n end",
"def initialize(timestamp)\n @timestamp = timestamp\n @records = []\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def schedule_start_timestamp(timestamp)\n @schedule_start_timestamp = timestamp\n end",
"def start_recurring_payment\n return unless recurring_period.present?\n run_at = nil\n if recurring_period.to_s.is_i? # each custom days\n run_at = recurring_period.to_i.days.from_now\n # run_at = recurring_period.to_i.minutes.from_now\n else\n case recurring_period\n when 'daily'\n run_at = 1.day.from_now\n when 'weekly'\n run_at = 7.days.from_now\n when 'monthly'\n run_at = 1.month.from_now\n when 'quarterly'\n run_at = 3.months.from_now\n when 'biannually'\n run_at = 6.months.from_now\n when 'yearly'\n run_at = 1.year.from_now\n end\n end\n Delayed::Job.enqueue(LongTasks::RecurringPaymentNotification.new(id), run_at: run_at - 1.day) if run_at && ['tithe', 'partnership'].include?(goal)\n Delayed::Job.enqueue(LongTasks::RecurringPayment.new(id), run_at: run_at) if run_at\n end",
"def schedule_repetition\n self.due = Date.today + interval\n self.studied_at = Date.today\n end",
"def future_single_event_creation\n self.schedule.next_occurrences(12).each do |occurrence|\n # TODO: Hot-Fix for Bug #83, unti ice_cube's issue 84 is resolved\n occurrence = occurrence.without_ms\n\n if !self.schedule.extimes.map(&:to_i).include? occurrence.to_i\n SingleEvent.where(event_id: self.id,\n occurrence: occurrence,\n based_on_rule: true).first_or_create\n end\n end\n end",
"def new_schedule(*args)\n if !args.all? { |e| e.is_a?(Integer) && e >= 0 && e <= 6 }\n return \"Please enter a number from 0-6 where each number represents a day of the week. 0 represents Sunday, 1 represents Monday, etc.\"\n end\n schedule1 = Schedule.new(self.first_event, duration: self.duration_mins.minutes )\n schedule1.add_recurrence_rule Rule.weekly.day(args)\n self.schedule = schedule1\n self.save!\n end",
"def to_occurrence(date)\n date = next_occurrence(date) if date.is_a?(Date)\n event = Event.new\n event.start_datetime = date\n event.end_datetime = date + duration\n event.title = title\n event.description = description\n event.location = location\n event.id = id\n event.user = user\n event.is_recurrence!\n event.set_as_persisted!\n event.freeze\n end",
"def create_time_request\n TimeRequest.create(\n time: [ Time.new(2000, 1, 1, 14, 0, 0, \"+00:00\").utc, Time.new(2000, 1, 1, 13, 0, 0, \"+00:00\").utc, Time.new(2000, 1, 1, 12, 0, 0, \"+00:00\").utc ].sample,\n reservation: Reservation.all.sample,\n check_in: [true, false].sample,\n status: 'pending'\n )\nend",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def create_for_period(future_period, notification_times, border_time)\n existing_times = future_period.notifications.all.map { |n| n.time }\n notification_times.each do |time|\n if !existing_times.include?(time) && border_time < time\n future_period.notifications.create!(time: time)\n end\n end\n end",
"def _create_resevation(base, subject, owner)\n\t\t\t\t\t\n\t\t\t\t\t# Create reservation\n\t\t\t\t\treservation = RicReservation.reservation_model.new\n\t\t\t\t\treservation.kind = \"event\"\n\t\t\t\t\treservation.event = self\n\t\t\t\t\treservation.date_from = base\n\t\t\t\t\treservation.date_to = base + (self.date_to - self.date_from).to_i.days\n\t\t\t\t\treservation.time_from = self.time_from\n\t\t\t\t\treservation.time_to = self.time_to\n\n\t\t\t\t\t# Bind subject\n\t\t\t\t\tif !subject.nil?\n\t\t\t\t\t\treservation.size = subject.size\n\t\t\t\t\t\treservation.subject = subject\n\t\t\t\t\telse\n\t\t\t\t\t\treservation.size = self.default_reservation_size\n\t\t\t\t\tend\n\n\t\t\t\t\t# Bind owner\n\t\t\t\t\tif !owner.nil?\n\t\t\t\t\t\treservation.owner_name = owner.name if !owner.name.nil?\n\t\t\t\t\t\treservation.owner = owner if owner.is_a?(ActiveRecord::Base) # In case owner is not ActiveRecord, only name can be stored\n\t\t\t\t\tend\n\n\t\t\t\t\treturn reservation\n\t\t\t\tend",
"def calc_next_run\n RunAtPeriodicJob.new(:name => self.name, :job => self.job, :run_at_minutes => self.run_at_minutes)\n end",
"def enqueue_at(job, precise_timestamp)\n build_worker(job).schedule(time_at: Time.at(precise_timestamp))\n end",
"def create_timestamp(line)\n\t\tTime.strptime(line[1], '%Q')\n\tend",
"def addTimelineElement(template, line, current, index)\n\ttime_point = Nokogiri::XML::Node.new(\"when\", template)\n\ttime_point['id'] = 'timepoint_' + (index + 1).to_s \n\ttime_point['since'] = 'timepoint_begin'\n\t\t\t\n\ttime_point['interval'] = srt_time_to_milliseconds(line.start_time)\n\n\tcurrent.add_next_sibling(time_point)\n\tcurrent.add_next_sibling(\"\\n\")\n\n\treturn time_point\nend",
"def schedule_new_record(row)\n ETL::Engine.logger.debug \"writing new record\"\n if scd_type == 2\n row[scd_effective_date_field] = @timestamp\n row[scd_end_date_field] = '9999-12-31 00:00:00'\n row[scd_latest_version_field] = true\n end\n buffer << row\n end",
"def next_meeting(after_time = Time.now.utc )\n # puts \"Looking up next meeting after #{after_time}\"\n if recurrence_frequency.blank?\n return start_time\n end\n\n if after_time < start_time\n return start_time\n end \n\n after_time = after_time.local_from_utc(self.time_zone) \n\n\n # Advance the starting time in the case when it falls after the beginning of\n # a meeting on the same day. We do this so that we can use \"day precision\"\n # (PDate.day) in the Runt library instead of \"minute precision\" (PDate.min),\n # which performs terribly.\n start_time = start_time_local\n if(after_time.hour > start_time.hour or ( after_time.hour == start_time.hour and after_time.min > start_time.min))\n after_time = after_time + 1.day\n after_time = Time.gm(after_time.year, after_time.month, after_time.day, 0, 0)\n end\n\n case recurrence_frequency\n when 'daily'\n end_time = after_time + 25.hours \n # after_time -= 1.day\n start_date = PDate.day(after_time.year, after_time.month, after_time.day , after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'weekdays'\n # Make the range over 3 days so that Friday night searches will still turn\n # up Monday as the next day.\n end_time = after_time + 3.days\n start_date = PDate.day(after_time.year, after_time.month, after_time.day, after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'monthly'\n eom = (after_time + 40.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eom.year, eom.month, eom.day)\n when 'weekly'\n eow = (after_time + 8.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eow.year, eow.month, eow.day)\n when 'yearly'\n # Just doing \"after_time + 367.days\" results in a bit of a performance hit\n # as hundreds of days are compared. We'll try to narrow it a bit. Not too\n # much, because we don't have time to actually write unit tests and make\n # sure the narrowing code works. :) Which is why the comment is here.\n st = after_time + 250.days\n et = st + 150.days\n start_date = PDate.day(st.year, st.month, st.day)\n end_date = PDate.day(et.year, et.month, et.day)\n end \n # puts \" Range #{start_date.to_s} - #{end_date.to_s}\"\n d_range = DateRange.new(start_date, end_date)\n sched = Schedule.new\n event = Event.new((self.invitation.name rescue \"no name\"))\n sched.add(event,self.runt_expression)\n dates = sched.dates(event,d_range)\n\n next_mtg = dates.first\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, start_time_local.hour, start_time_local.min)\n result = nil\n begin\n result = next_mtg_time.local_to_utc(self.time_zone)\n rescue TZInfo::PeriodNotFound\n # This only happens when the time is during the one hour which is skipped\n # during the transition to DST. For example, only on Sun Mar 08 02:15:00\n # (see ticket #744).\n next_hour = start_time_local.hour + 1\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, next_hour, start_time_local.min)\n retry\n end\n return result\n end",
"def recurrence_at\n unless @recurrence_at.nil?\n return @recurrence_at\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if schedule.nil?\n return nil\n end\n # montrose stores the \"at\" times in an array with\n # time[0] = hour\n # time[1] = mins\n # time[2] = secs\n schedule.rules.first.to_h[:at].map{|time| [time[0].to_s.rjust(2,\"0\"),time[1].to_s.rjust(2,\"0\")].join(\":\")}.join(\", \")\n end",
"def next!\n self.start = self.send(:\"next_#{frequency}_in_recurrence\") \n self\n end",
"def create\n @time_slot = TimeSlot.new(params[:time_slot])\n @time_slot.user_id = current_identity.user_id\n\t@recurrence_array = []\n respond_to do |format|\n if @time_slot.save\n format.html { redirect_to @time_slot, notice: 'Time slot was successfully created.' }\n format.json { render json: @time_slot, status: :created, location: @time_slot }\n else\n format.html { render action: \"new\" }\n format.json { render json: @time_slot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_next_repetition\n if repetitions.order(\"id ASC\").last.successful\n self.consecutive_successful_repetitions += 1\n next_planned_interval = rand((repetitions.last_planned_interval * 2)..(repetitions.last_planned_interval * 3))\n else\n self.consecutive_successful_repetitions = 0\n next_planned_interval = rand(1..3)\n end\n save\n if consecutive_successful_repetitions < WhRails::Application.config.max_consecutive_successful_repetitions\n # repetitions.last.actual_date is always the current date.\n next_repetition_date = repetitions.order(\"id ASC\").last.actual_date + next_planned_interval.days\n repetitions.create planned_date: next_repetition_date, actual_date: next_repetition_date\n else\n self.learned_on = Date.today\n save\n end\n end",
"def recurring; end",
"def rocket_job_restart_new_instance\n return if expired?\n attrs = attributes.dup\n rocket_job_restart_excludes.each { |attr| attrs.delete(attr) }\n\n # Copy across run_at for future dated jobs\n attrs['run_at'] = run_at if run_at && (run_at > Time.now)\n\n rocket_job_restart_create(attrs)\n end",
"def start(notification)\n # there is a super method for this\n super(notification)\n\n @start_time = Time.now\n\n doc = {\n 'type' => 'suite',\n 'start' => @start_time.strftime('%Y-%m-%d %H:%M:%S'),\n 'count' => notification.count,\n 'seed' => @seed,\n 'rev' => REVISION\n }\n return doc\n end",
"def initialize(created_at, interval)\n @created_at = created_at\n @interval = interval\n end",
"def next_occurrence(from_date)\n residue = @residue - residue_for(from_date)\n date = move_by from_date, residue.modulo(interval)\n time = Time.new(date.year, date.month, date.day, start_time.hour, start_time.min, start_time.sec)\n if (exx = exclusions.detect {|rule| rule.violated_by? time})\n if stops_by && time > stops_by\n nil\n else\n next_occurrence(move_by time, 1)\n end\n else\n time\n end\n end",
"def create_new_flights!\n new_flights = Array.new\n current_flight = Array.new\n new_flights << current_flight\n\n last_time = nil\n loop do\n results = telemetry.order(time: :asc).limit(1000)\n results = results.where('time > ?', last_time) if last_time\n results = results.pluck(:time)\n break if results.empty?\n\n results = results.to_a\n last_time = results.last.time\n\n results.each do |t|\n if current_flight.empty?\n current_flight << t.time\n elsif t.time > current_flight.last + NEW_FLIGHT_INTERVAL\n current_flight = Array.new\n new_flights << current_flight\n else\n current_flight[1] = t.time\n end\n end\n end\n\n created_flights = Array.new\n new_flights.each do |(start, stop)|\n next unless start && stop\n next if start == stop\n\n created_flights << flights.create!(recording_start_time: start, recording_end_time: stop, significant: nil)\n rescue ActiveRecord::RecordNotUnique\n retry # race condition in friendly_id\n end\n end",
"def makeShift(i)\n delta = self.template.get_period_start(i)\n \n shift = Shift.new\n\n shift.start = delta + (start - template.template_start)\n shift.end = delta + (stop - template.template_start)\n\n shift.shift_type = shift_type\n shift.comment = comment\n shift.template = self\n\n return shift\n end",
"def schedule_every (freq, params={}, &block)\n\n params = prepare_params(params)\n params[:every] = freq\n\n first_at = params[:first_at]\n first_in = params[:first_in]\n\n #params[:delayed] = true if first_at or first_in\n\n first_at = if first_at\n at_to_f(first_at)\n elsif first_in\n Time.now.to_f + Rufus.duration_to_f(first_in)\n else\n Time.now.to_f + Rufus.duration_to_f(freq) # not triggering immediately\n end\n\n do_schedule_at(first_at, params, &block)\n end",
"def create\n cnt = params[:tutor_availability][:repeat].to_i - 1\n params[:tutor_availability].delete :repeat\n @tutor_availability = TutorAvailability.new(params[:tutor_availability])\n\n respond_to do |format|\n if @tutor_availability.save\n if cnt > 0\n for i in 1..cnt\n new_ta = TutorAvailability.new(params[:tutor_availability])\n new_ta.start_time = @tutor_availability.start_time + 604800*i\n new_ta.save\n end\n end\n format.html { redirect_to tutor_availabilities_path, notice: 'Tutor availability was successfully created.' }\n format.json { render json: @tutor_availability, status: :created, location: @tutor_availability }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tutor_availability.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @preptime = Preptime.new()\n end",
"def creation_date\n time_frames = []\n (MULTIPLIER**2).times do |x|\n time_frames << midnight_tonight - ((x*3) + 1).month\n end\n date_range = (time_frames.sample..midnight_tonight)\n rand(date_range)\nend",
"def create_activity_factory_wrapper\n if recurrence\n create_activity_factory({\n # Fields copied straight from +Activity+ model\n name:name,\n description:description,\n vendor_id:vendor_id,\n vendor_name:vendor_name,\n bookings_available:bookings_available,\n price:price,\n start: start,\n # Fields inferred from +Activity+ model\n duration: (start && finish && finish - start)\n }.merge(recurrence) )\n return !activity_factory.new_record?\n end\n end",
"def start! search_id\n search = preload(:pseudo_graph_pattern).find_by! search_id: search_id\n search.pseudo_graph_pattern.update(started_at: Time.now.utc)\n search\n end",
"def recurrence\n nil\n end",
"def create\n @event_recurrence = EventRecurrence.new(event_recurrence_params)\n\n respond_to do |format|\n if @event_recurrence.save\n format.html { redirect_to @event_recurrence, notice: 'Event recurrence was successfully created.' }\n format.json { render :show, status: :created, location: @event_recurrence }\n else\n format.html { render :new }\n format.json { render json: @event_recurrence.errors, status: :unprocessable_entity }\n end\n end\n end",
"def next_scheduled_at\n reviewed_at + (24.hours * next_interval)\n end",
"def fill_recurrence(number)\n if old_num == number\n self.recc += 1\n else\n apply_recurrence\n self.old_num = number\n self.recc = 1\n end\n end",
"def set_recurrence\n @recurrence = Recurrence.find(params[:id])\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def create_record(url, ref)\n date_time = Faker::Time.between(@now - 10, @now).utc\n Entry.create(\n url: url,\n referrer: ref,\n created_at: date_time,\n )\nend",
"def initialize\n @interval = 1\n @wkst = :mo\n @id = rand(100)\n @duration = 0 # 1 day\n @event_start = DateTime.new\n end",
"def at ts\n spawn :@trange, time_to_long(ts)\n end",
"def cron_generate_date(cron, date)\n begin\n date = Time.now if !date.respond_to? :year\n\n # if date < Time.now.beginning_of_week then date = Time.now\n date = Time.now if date < Time.now.beginning_of_week\n \n cron = cron_date cron\n\n #get the key of the last *\n every = cron.select{ |k,v| v == '*' }.keys.last\n\n # we are comparing cron to the current date so:\n # if v == * then v = date.k\n for k,v in cron do\n #puts \"date.#{k}\"\n cron[k] = eval(\"date.#{k}\") if v.class == String\n end\n \n # convert cron in date\n cron = Time.local(cron[:year], cron[:month], cron[:day], cron[:hour], cron[:minute])\n\n # if generated date is < date then increment it by 1 on the first *\n # i.e. cron = '41 18 * * *' and date = '2012-03-15 19:37'.\n # generated date will be 2012-03-15 18:41 which is past date - we want the next cron date which is 2012-03-16 18:41\n cron += 1.send(every) if cron < date\n\n return cron\n rescue => ex\n send_mail \"#{ex.class}: #{ex.message}. cron: #{cron}, date: #{date}\" \n end\n end",
"def now_and_every(interval, recur = T.unsafe(nil), &block); end",
"def creation_date\n time_frames = []\n SCALAR.times do |x|\n time_frames << Time.now - ((x+1)*3).month\n end\n date_range = (time_frames.sample..Time.now)\n rand(date_range)\nend",
"def start_trial\n self.trial_started_at = Time.now if self.new_record?\n end",
"def scheduling_index\n @scheduling_index ||= SchedulingIndexByWeekDay.new(y_attribute).with_records_added(records)\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def generate(time, start, focus)\n outline = create_outline(time, start, focus)\n subsequences = outline.map { |type| create_subsequence(type) }\n sequence = subsequences.flatten\n end",
"def create_or_update_previous_runs!; end",
"def create_or_update_previous_runs!; end",
"def create_reservation(base = self.date_from, subject = nil, owner = nil)\n\t\t\t\t\t\n\t\t\t\t\t# Create reservation\n\t\t\t\t\treservation = _create_resevation(base, subject, owner)\n\n\t\t\t\t\t# Store\n\t\t\t\t\treservation.save\n\n\t\t\t\t\treturn reservation\n\t\t\t\tend",
"def record_creation_timestamp(path, timestamp)\n # Hook method: Linux filesystems doesn't store creation datetime\n end",
"def add_oneshot_at exact_time, timer_proc\n return nil unless timer_proc\n\n timer = Timer.new :timers => self, :exact_time => exact_time, :periodical => false, :timer_proc => timer_proc\n add timer\n timer\n end",
"def start_at\n today = Time.now\n Time.new(today.year, today.month, today.day, 9,0,0)\n end",
"def recurrence\n { ATTR_RECURRENCE[@attribute] => 1 }\n end",
"def recurrence_params\n params.require(:recurrence).permit(:title, :start_time, :description, :recurring)\n end",
"def weekly_time_generator(args = {:start_time => Time.now, :end_time => nil, :cron => ''})\n begin\n return [] if args[:cron].blank?\n\n # get cron as hash\n cron = cron_date args[:cron]\n\n # get the first value of the cron which is an integer and the pevious index\n # ex: cron = '41 * * * *' - we want to know that it starts every hour (prev index before the number) in the 41-st minute\n for k, v in cron do\n at = v\n break if v.class == 'Fixnum'\n # break in ruby continues the last iteration..\n every = k if v == '*'\n end\n\n changed_time = start_time = cron_generate_date args[:cron], args[:start_time]\n end_time = args[:end_time]\n\n # end_time is nil?\n end_time = Time.now.end_of_week if !end_time.respond_to? :year\n # end_time should not be longer than the end of this week\n end_time = end_time > start_time.end_of_week ? start_time.end_of_week : end_time\n\n all = []\n while changed_time <= end_time\n all << changed_time #changed_time.strftime(\"%d.%m.%Y %H:%M\")\n changed_time += 1.send(every)\n end\n\n all\n\n rescue => ex\n send_mail \"#{ex.class}: #{ex.message}. args: #{args}\" \n end\n\n end",
"def make_constant_schedule(name, temperature)\n s = OpenStudio::Model::ScheduleRuleset.new(@model)\n s.setName(name)\n s.defaultDaySchedule.addValue(OpenStudio::Time.new(\"24:00:00\"), OpenStudio::convert(temperature, \"F\", \"C\").get)\n\ts\n end",
"def schedule_for!\n unless self.parent_id\n starts_on = created_at\n course.lessons.all(order: :position).each do |lesson|\n unless scheduled_course.scheduled_lessons.where('lesson_id= ? and enrolment_id = ?',lesson.id, id ).first\n ScheduledLesson.create(student_user_id: self.student_user_id, enrolment_id: self.id, scheduled_course_id: scheduled_course.id, lesson_id: lesson.id )\n end\n end\n end\n end",
"def []( date )\n @sequence[ round( date )]\n end",
"def next\n recurrence.next if recurring?\n end",
"def update_recurrent_subscriptions\n notification_type_subscriptions.recurrent.each do |recurrent_subscription| \n recurrent_subscription.recurrence.update_attributes(:starts_at => ActiveSupport::TimeZone[timezone].parse(\"#{Date.today.to_s} #{recurrent_subscription.notification_type.constantize.time}\"))\n end\n end",
"def new_appointment(patient, date)\n Appointment.new(patient, self, date)\n end",
"def next(count = 1)\n dupe = self.dup\n dupe.assign_attributes start_time: start_time + push(count), end_time: end_time + push(count)\n dupe\n end",
"def from_now(t = Time.now); t + self; end",
"def from_now(t = Time.now); t + self; end",
"def set_next_run\n self.next_run_at = calc_next_run_at_date\n end",
"def new_appointment(a_Patient, date)\n \n Appointment.new(date, self, a_Patient)\n end",
"def timeRecordsForDate(brick, date)\n end",
"def daily_requests_for(time = Time.now)\n find_or_create_daily_requests_for(time)\n end",
"def recurrence_to_events!(now = Time.now.utc)\n recurring.each {|r| r.recurrence_to_events!(now)}\n end",
"def create\n @scheduled_task = ScheduledTask.new(params[:scheduled_task])\n p = params[:scheduled_task]\n d = DateTime.new(p[\"next_run(1i)\"].to_i, p[\"next_run(2i)\"].to_i, p[\"next_run(3i)\"].to_i, p[\"next_run(4i)\"].to_i, p[\"next_run(5i)\"].to_i)\n @scheduled_task.next_run = d\n\n respond_to do |format|\n if @scheduled_task.save\n format.html { redirect_to @scheduled_task, notice: 'Scheduled task was successfully created.' }\n format.json { render json: @scheduled_task, status: :created, location: @scheduled_task }\n else\n format.html { render action: \"new\" }\n format.json { render json: @scheduled_task.errors, status: :unprocessable_entity }\n end\n end\n end",
"def starting(starts_at)\n merge(starts: starts_at)\n end",
"def new_appointment(patient, date)\n Appointment.new(patient, self, date=\"\")\n end",
"def build_job(start_time, end_time)\n Job.create(\n :start_time => start_time, \n :end_time => end_time, \n :running_time => (end_time-start_time), \n :name => action_name\n )\n end",
"def add_repeating_request(url, interval, content)\n @nodes << RepeatingRequest.new(page_config, url, interval, content)\n end",
"def recurrence\n unless read_attribute(:recurrence).empty?\n IceCube::Rule.from_hash(read_attribute(:recurrence))\n end\n end",
"def next\n self.occurrences.where('date >= ?', Date.current).first\n end",
"def next_time (from=Time.now)\n\n @cron_line.next_time(from)\n end",
"def make_resevation(date_range)\n available_rooms = get_available_rooms(date_range)\n if available_rooms.length < 1\n raise ArgumentError\n end\n new_reservation = Hotel::Reservation.new(date_range,available_rooms[0])\n @reservations << new_reservation\n return new_reservation\n end",
"def register_reaper_process\n redis { |conn| conn.set(UNIQUE_REAPER, current_timestamp, nx: true, ex: drift_reaper_interval) }\n end",
"def started_at=(_arg0); end",
"def started_at=(_arg0); end",
"def started_at=(_arg0); end",
"def enqueue_at(_job, _timestamp)\n raise NotImplementedError, 'This queueing backend does not support scheduling jobs.'\n end",
"def set_initial_next_run\n self.next_run_at = Time.zone.now if self.next_run_at.nil?\n end"
] |
[
"0.6322667",
"0.62188363",
"0.6202473",
"0.6152839",
"0.5794456",
"0.5517323",
"0.5511164",
"0.55008435",
"0.54777026",
"0.53675365",
"0.52858794",
"0.5264492",
"0.5209583",
"0.5198844",
"0.5134599",
"0.5128384",
"0.511203",
"0.51014197",
"0.5084017",
"0.50579745",
"0.5035719",
"0.5035719",
"0.5030427",
"0.50109345",
"0.50052357",
"0.49738413",
"0.49680033",
"0.49675855",
"0.49478972",
"0.49450144",
"0.48955506",
"0.488282",
"0.48728687",
"0.4866646",
"0.48661235",
"0.48521107",
"0.48372847",
"0.483661",
"0.4823452",
"0.47929242",
"0.4790397",
"0.47631893",
"0.4762781",
"0.47506323",
"0.47503865",
"0.4746546",
"0.47404286",
"0.47294393",
"0.47213125",
"0.4715329",
"0.47117054",
"0.47014847",
"0.46991038",
"0.4697266",
"0.46924108",
"0.4682254",
"0.46763402",
"0.46722344",
"0.46582073",
"0.46453056",
"0.46426448",
"0.46419388",
"0.46362296",
"0.46326855",
"0.46326855",
"0.46280104",
"0.46199635",
"0.4619552",
"0.4617655",
"0.460712",
"0.46039018",
"0.4603013",
"0.45854834",
"0.45809957",
"0.45793936",
"0.45658287",
"0.456362",
"0.45624992",
"0.45588893",
"0.45531633",
"0.45531633",
"0.45455492",
"0.45402542",
"0.45369795",
"0.45363152",
"0.45305908",
"0.45266584",
"0.45249355",
"0.4522507",
"0.4521955",
"0.45200017",
"0.45100737",
"0.4504687",
"0.4502464",
"0.44996944",
"0.44994494",
"0.44982374",
"0.44982374",
"0.44982374",
"0.4487763",
"0.4487457"
] |
0.0
|
-1
|
Create a recurrence ending at given timestamp.
|
def until(ends_at)
merge(until: ends_at)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def end_timestamp\n timestamp + duration if duration\n end",
"def create_for_period(future_period, notification_times, border_time)\n existing_times = future_period.notifications.all.map { |n| n.time }\n notification_times.each do |time|\n if !existing_times.include?(time) && border_time < time\n future_period.notifications.create!(time: time)\n end\n end\n end",
"def create_recurrences(transaction)\n CreateRecurrencesJob.perform_later(\n transaction.class.to_s,\n transaction.id.to_s\n )\n end",
"def schedule_recurring_task_creation(task)\n recurring_scheduler = Scheduler.new\n @recurring_schedulers << recurring_scheduler\n\n recurring_scheduler.schedule.every \"#{Helpers.convert_frequency_to_seconds(task.frequency).to_s}s\" do\n new_task = Task.new\n new_task.description = task.description\n new_task.frequency = task.frequency\n new_task.creation_date = Time.now.getlocal\n new_task.target_date = Helpers.calculate_task_target_date(\n new_task.creation_date,\n new_task.frequency\n )\n new_task.recurring_scheduler_id = recurring_scheduler.id\n\n new_task.create_reminder_notification\n new_task.create_failed_notification\n\n add_task(new_task)\n end\n end",
"def end\n ends_at.strftime(\"%R\")\n end",
"def ending_at(date)\n set_end_date_and_raise_error_if_end_is_eariler_than_start(date)\n self\n end",
"def extend_empty_end_date\n if self.end_date == self.start_date && !self.repeat_mode.rule.empty?\n self.end_date = Date.today + 10.year\n end\n return self\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def end_of_day\n VoltTime.new(:utc, year, month, day, 23, 59, 59.999)\n end",
"def last_active_recurring_product_subscription_term_period_end_on\n if order = self.last_active_recurring_order\n order.created_at.to_date + last_active_recurring_product_subscription.term_in_days\n end\n end",
"def ends_at\n @ends_at ||= begin\n if period == :quarter\n starts_at.advance months: length * 3\n else\n starts_at.advance periods => length\n end\n end\n end",
"def ending_period\n start_period = self.period\n length = self.length\n return nil if start_period.nil?\n return start_period if length.nil? or length <= 1\n return start_period.find_following(length).last\n end",
"def end_of_day\n change(:hour => 23, :min => 59, :sec => 59, :usec => 999999.999)\n end",
"def end_date\n (created_at - 1.week).sunday - 1.day\n end",
"def expire!\n successor = BillingPeriod.create! booking: booking,\n start_date: start_of_next_period\n successor.delay.charge!\n end",
"def recurrence_to_events!(now = Time.now.utc)\n recurring.each {|r| r.recurrence_to_events!(now)}\n end",
"def ending(ends_at)\n merge(until: ends_at)\n end",
"def end_of_day\n change(\n hour: 23,\n min: 59,\n sec: 59,\n usec: Rational(999999999, 1000)\n )\n end",
"def next_meeting(after_time = Time.now.utc )\n # puts \"Looking up next meeting after #{after_time}\"\n if recurrence_frequency.blank?\n return start_time\n end\n\n if after_time < start_time\n return start_time\n end \n\n after_time = after_time.local_from_utc(self.time_zone) \n\n\n # Advance the starting time in the case when it falls after the beginning of\n # a meeting on the same day. We do this so that we can use \"day precision\"\n # (PDate.day) in the Runt library instead of \"minute precision\" (PDate.min),\n # which performs terribly.\n start_time = start_time_local\n if(after_time.hour > start_time.hour or ( after_time.hour == start_time.hour and after_time.min > start_time.min))\n after_time = after_time + 1.day\n after_time = Time.gm(after_time.year, after_time.month, after_time.day, 0, 0)\n end\n\n case recurrence_frequency\n when 'daily'\n end_time = after_time + 25.hours \n # after_time -= 1.day\n start_date = PDate.day(after_time.year, after_time.month, after_time.day , after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'weekdays'\n # Make the range over 3 days so that Friday night searches will still turn\n # up Monday as the next day.\n end_time = after_time + 3.days\n start_date = PDate.day(after_time.year, after_time.month, after_time.day, after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'monthly'\n eom = (after_time + 40.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eom.year, eom.month, eom.day)\n when 'weekly'\n eow = (after_time + 8.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eow.year, eow.month, eow.day)\n when 'yearly'\n # Just doing \"after_time + 367.days\" results in a bit of a performance hit\n # as hundreds of days are compared. We'll try to narrow it a bit. Not too\n # much, because we don't have time to actually write unit tests and make\n # sure the narrowing code works. :) Which is why the comment is here.\n st = after_time + 250.days\n et = st + 150.days\n start_date = PDate.day(st.year, st.month, st.day)\n end_date = PDate.day(et.year, et.month, et.day)\n end \n # puts \" Range #{start_date.to_s} - #{end_date.to_s}\"\n d_range = DateRange.new(start_date, end_date)\n sched = Schedule.new\n event = Event.new((self.invitation.name rescue \"no name\"))\n sched.add(event,self.runt_expression)\n dates = sched.dates(event,d_range)\n\n next_mtg = dates.first\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, start_time_local.hour, start_time_local.min)\n result = nil\n begin\n result = next_mtg_time.local_to_utc(self.time_zone)\n rescue TZInfo::PeriodNotFound\n # This only happens when the time is during the one hour which is skipped\n # during the transition to DST. For example, only on Sun Mar 08 02:15:00\n # (see ticket #744).\n next_hour = start_time_local.hour + 1\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, next_hour, start_time_local.min)\n retry\n end\n return result\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def current_end_time\n self.ends_at = DateTime.current\n save\n end",
"def add_recurrence(type: :week, on: on = nil, at: at = nil)\n type = type.to_sym\n unless [:week, :day].include? type\n raise \"Type must be either :week or :day\"\n end\n if type == :week and (on.nil? or (on.is_a?(Array) and on.empty?))\n raise \"Weekdays must be specified when selecting the :week type\"\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if self.schedule.nil?\n schedule = Montrose::Schedule.new\n end\n if at.nil?\n raise \"Time must be specified in parameter 'at'\"\n else\n schedule.add Montrose.every(type, on: on, at: at).starts(created_at)\n self.write_attribute(self.class.schedulable_attribute, schedule)\n end\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence\n nil\n end",
"def schedule_repetition\n self.due = Date.today + interval\n self.studied_at = Date.today\n end",
"def set_ends_at\n return unless self.duration && self.starts_at\n self.ends_at = starts_at + duration.hours\n end",
"def extend_trial(date)\n raise ArgumentError, \"Extending a subscription's trial requires a date in the future.\" unless date.future?\n\n subscription = as_stripe_subscription\n subscription.trial_end = date.to_i\n subscription.save\n\n update(trial_ends_at: date)\n\n self\n end",
"def effective_end_datetime\n end_date + 1.day + roster.switchover.minutes\n end",
"def end_time\n\t\tstart + 1.day\n\tend",
"def end_of_day(date_time)\n unless working_day?(date_time)\n return end_of_day(previous_working_day(date_time))\n end\n work_time = to_work_time(date_time)\n work_day = to_work_day(date_time)\n if work_time < work_day.start_time\n return end_of_day(previous_working_day(to_modified_date_time(date_time, WorkTime.new(12, 0))))\n end\n return to_modified_date_time(date_time, work_day.end_time)\n end",
"def stripe_customer_trial_ending(event, req)\n obj = event['data']['object']\n id = obj['customer']\n log.debug({ type: 'method', data: \"stripe_customer_trial_ending -- #{id}\" })\n trial_end_date = Time.at(obj['trial_end'])\n dealership = dealer_dao.get_by_customer_id(id)\n return false unless dealership && dealership.customer_id == id\n # Schedule Email reminder to customer about trial ending\n Lynr.producer('job').publish(Lynr::Queue::EmailJob.new('trial_end', {\n to: dealership.identity.email,\n subject: \"Lynr.co Trial Ends on #{trial_end_date.strftime('%B %d')}\",\n base_url: req.base_url,\n end_date: trial_end_date,\n support_email: Lynr.config('app').support_email,\n }))\n end",
"def schedule_new_record(row)\n ETL::Engine.logger.debug \"writing new record\"\n if scd_type == 2\n row[scd_effective_date_field] = @timestamp\n row[scd_end_date_field] = '9999-12-31 00:00:00'\n row[scd_latest_version_field] = true\n end\n buffer << row\n end",
"def recurring; end",
"def end_date\n Date.new((@number + 1), 1, 1).tuesday? ? Date.new((@number + 1), 1, 1) : Date.new(@number, 12, 31)\n end",
"def last_run_at\n super || self.schedule.try(:previous_occurrence)\n end",
"def add_occurrences!(event, at = [])\n Array(at).each do |time|\n OccurrenceEntry.create!(:post_id => id, :label => event, :at => time)\n end\n end",
"def end(value)\n merge(grcend: value.iso8601)\n end",
"def multi_day_end_event_for(assignment)\n attribs = event_attribs(assignment)\n attribs[:name] = \"#{attribs[:name]} (End)\"\n attribs[:starts_at] = attribs[:ends_at] - 1.day + 1.second\n events.build(attribs)\n end",
"def later?(timestamp)\n ends_at && timestamp > ends_at\n end",
"def end(value)\n merge(gadrend: value.iso8601)\n end",
"def end(value)\n merge(rvend: value.iso8601)\n end",
"def end_at(include_late_slack = true)\n s = assessment.end_at\n s += assessment.course.late_slack if include_late_slack\n apply_extension s, extension\n end",
"def recurrence=(new_rule)\n if RecurringSelect.is_valid_rule?(new_rule)\n rule = RecurringSelect.dirty_hash_to_rule(new_rule).to_hash\n write_attribute(:recurrence, rule)\n else\n write_attribute(:recurrence, nil)\n end\n end",
"def new_schedule(*args)\n if !args.all? { |e| e.is_a?(Integer) && e >= 0 && e <= 6 }\n return \"Please enter a number from 0-6 where each number represents a day of the week. 0 represents Sunday, 1 represents Monday, etc.\"\n end\n schedule1 = Schedule.new(self.first_event, duration: self.duration_mins.minutes )\n schedule1.add_recurrence_rule Rule.weekly.day(args)\n self.schedule = schedule1\n self.save!\n end",
"def end_of_day\n to_time.end_of_day\n end",
"def end_date\n\t\tself.next.start_date - 1\n\tend",
"def meeting_end(*args)\n options = Utils.extract_options!(args)\n meeting_update_status(options.merge(action: 'end'))\n end",
"def send_rating_emails_when_ends\n RateRentalJob.set(wait_until: self.end_date.tomorrow.noon).perform_later(self)\n RateSportingGoodJob.set(wait_until: self.end_date.tomorrow.noon).perform_later(self)\n end",
"def end(value)\n merge(leend: value.iso8601)\n end",
"def end(value)\n merge(bkend: value.iso8601)\n end",
"def ends_at=(val)\n raise Timely::ConfigurationError, \"starts_at must be set before setting ends_at\" unless starts_at\n\n duration_in_seconds = val - starts_at\n period_duration = period == :quarter ? 3.months : 1.send(period)\n\n self.length = (duration_in_seconds.to_f / period_duration).ceil\n\n reset\n end",
"def end_date\n\t \tTime.at(self.end_time) rescue nil\n\t end",
"def max_slack_after(ends_at)\n next_reservation = Reservation.new(entity: self, ends_at: ends_at).next\n (next_reservation.begins_at - next_reservation.slack_before.minutes - ends_at) / 1.minute if next_reservation.present?\n end",
"def finish!\n pseudo_graph_pattern.update finished_at: Time.now.utc\n end",
"def timer_ends_at\n # During task initialization, this is called by TimeableTask to schedule the TaskTimer.\n return @end_date if @end_date\n\n # Check for last existing associated TaskTimer\n task_timer = TaskTimer.where(task: self).order(:id).last\n return task_timer.submitted_at if task_timer\n\n # from_date should be appeal receipt date if the appeal is in the ESW docket\n from_date = appeal.receipt_date if appeal.evidence_submission_docket?\n\n # ...or from_date should be the date the hearing was scheduled if a hearing is present\n from_date ||= hearing.hearing_day&.scheduled_for if hearing.present?\n\n # ...or if no hearing is present, from_date should end when the hearing task was cancelled\n from_date ||= cancelled_schedule_hearing_task&.closed_at\n\n # if from_date is still nil, fall back to when this task was created\n from_date = ensure_from_date_set(from_date)\n\n # Add 90 days to the timer based on the date above\n from_date + 90.days\n end",
"def rocket_job_restart_new_instance\n return if expired?\n attrs = attributes.dup\n rocket_job_restart_excludes.each { |attr| attrs.delete(attr) }\n\n # Copy across run_at for future dated jobs\n attrs['run_at'] = run_at if run_at && (run_at > Time.now)\n\n rocket_job_restart_create(attrs)\n end",
"def ending_of_week\n if current_week.index(day) == 6\n self.class.new(year, month, current_week.last)\n elsif current_week.index(day) < 6\n if self.class == Date\n self + (6 - current_week.index(day))\n elsif self.class == Time\n self + (60 * 60 * 24 * (6 - current_week.index(day)))\n end\n end\n end",
"def ends_at\n started_at + client.clock_delta + length if started_at\n end",
"def create(opts)\n @frequence = opts[:frequence] if opts[:frequence].in? Recurrence::FREQUENCES\n @monthly = array_to_integer(opts[:monthly])\n @count = to_integer(opts[:count])\n @until = string_to_date(opts[:until])\n self\n end",
"def schedule_break start_time, end_time, rate = 0.0\n check_break start_time, end_time\n\n roadall.insert(-2, [start_time.to_i, nil, roadall.last.last])\n roadall.insert(-2, [end_time.to_i, nil, rate])\n end",
"def end\n @end_time = Time.now.utc\n end",
"def delete_recurrences(recurrence, modifier, date = nil)\n DeleteRecurrencesJob.perform_later(\n recurrence.class.to_s,\n recurrence.id.to_s,\n modifier,\n date\n )\n end",
"def ends_at\n starts_at + minutes.minutes\n end",
"def assign_trial_end_date\n self.trial_end_date = 2.weeks.from_now\n save!\n end",
"def now_and_every(interval, recur = T.unsafe(nil), &block); end",
"def end\n dates = self.children.map(&:end).compact\n #self.children.each { |c| \n # dates.push(c.end) unless c.end.nil?\n #}\n # set the end-date for this movie series if it has been changed\n # (like a child has been added or an existing has been removed)\n # Changing the :end attribute does not fire a logging, as :end\n # is set to be unloggable for series.\n last = dates.sort.last\n update_attribute_with_validation_skipping( :end, last ) unless self.attributes[\"end\"] == last or self.class == Season\n last\n end",
"def set_latest(rule_key, timestamp)\n @timestamps[rule_key]['latest_run'] = timestamp\n end",
"def recurrence_at\n unless @recurrence_at.nil?\n return @recurrence_at\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if schedule.nil?\n return nil\n end\n # montrose stores the \"at\" times in an array with\n # time[0] = hour\n # time[1] = mins\n # time[2] = secs\n schedule.rules.first.to_h[:at].map{|time| [time[0].to_s.rjust(2,\"0\"),time[1].to_s.rjust(2,\"0\")].join(\":\")}.join(\", \")\n end",
"def expireat(key, unix_time, **kwargs); end",
"def to_occurrence(date)\n date = next_occurrence(date) if date.is_a?(Date)\n event = Event.new\n event.start_datetime = date\n event.end_datetime = date + duration\n event.title = title\n event.description = description\n event.location = location\n event.id = id\n event.user = user\n event.is_recurrence!\n event.set_as_persisted!\n event.freeze\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def process_recurrence(recurrence)\n return true unless recurrence.today?\n recurrence.update_job\n end",
"def cancel\n subscription = as_stripe_subscription\n\n subscription.cancel_at_period_end = true\n\n subscription = subscription.save\n\n self.stripe_status = subscription.status\n\n # If the user was on trial, we will set the grace period to end when the trial\n # would have ended. Otherwise, we'll retrieve the end of the billing period\n # period and make that the end of the grace period for this current user.\n self.ends_at = on_trial ? trial_ends_at : Time.zone.at(subscription.current_period_end)\n\n save\n\n self\n end",
"def local_end_of_day\n t = @time.getlocal\n t = Time.new(t.year, t.month, t.day, 23, 59, 59.999)\n VoltTime.from_time(t)\n end",
"def end_date\n start_date + (duration * 60)\n end",
"def _record_end_time(records)\n end_time = DateTime.now\n unless records.empty?\n records.each do |record|\n record.end_at = end_time\n record.updated_at = end_time\n record.total_time += record.time_diff\n end\n end\n end",
"def _create_resevation(base, subject, owner)\n\t\t\t\t\t\n\t\t\t\t\t# Create reservation\n\t\t\t\t\treservation = RicReservation.reservation_model.new\n\t\t\t\t\treservation.kind = \"event\"\n\t\t\t\t\treservation.event = self\n\t\t\t\t\treservation.date_from = base\n\t\t\t\t\treservation.date_to = base + (self.date_to - self.date_from).to_i.days\n\t\t\t\t\treservation.time_from = self.time_from\n\t\t\t\t\treservation.time_to = self.time_to\n\n\t\t\t\t\t# Bind subject\n\t\t\t\t\tif !subject.nil?\n\t\t\t\t\t\treservation.size = subject.size\n\t\t\t\t\t\treservation.subject = subject\n\t\t\t\t\telse\n\t\t\t\t\t\treservation.size = self.default_reservation_size\n\t\t\t\t\tend\n\n\t\t\t\t\t# Bind owner\n\t\t\t\t\tif !owner.nil?\n\t\t\t\t\t\treservation.owner_name = owner.name if !owner.name.nil?\n\t\t\t\t\t\treservation.owner = owner if owner.is_a?(ActiveRecord::Base) # In case owner is not ActiveRecord, only name can be stored\n\t\t\t\t\tend\n\n\t\t\t\t\treturn reservation\n\t\t\t\tend",
"def save_end_at\n self.end_time = Time.zone.parse(\"#{date_published} #{@end_time_input}\" ) if ( @end_time_input.present? && date_published.present? )\n end",
"def complete_termination\n self.deleted_at = Time.now.utc\n self.end_date = Date.today\n end",
"def period(ending = ::Time.now)\n Period.new(moment, ending)\n end",
"def create\n @time_slot = TimeSlot.new(params[:time_slot])\n @time_slot.user_id = current_identity.user_id\n\t@recurrence_array = []\n respond_to do |format|\n if @time_slot.save\n format.html { redirect_to @time_slot, notice: 'Time slot was successfully created.' }\n format.json { render json: @time_slot, status: :created, location: @time_slot }\n else\n format.html { render action: \"new\" }\n format.json { render json: @time_slot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def ending_at\n @ending_at ||= parse_or_at(@attrs[:ending_at]) if @attrs[:ending_at]\n end",
"def end(value)\n merge(orend: value.iso8601)\n end",
"def start_recurring_payment\n return unless recurring_period.present?\n run_at = nil\n if recurring_period.to_s.is_i? # each custom days\n run_at = recurring_period.to_i.days.from_now\n # run_at = recurring_period.to_i.minutes.from_now\n else\n case recurring_period\n when 'daily'\n run_at = 1.day.from_now\n when 'weekly'\n run_at = 7.days.from_now\n when 'monthly'\n run_at = 1.month.from_now\n when 'quarterly'\n run_at = 3.months.from_now\n when 'biannually'\n run_at = 6.months.from_now\n when 'yearly'\n run_at = 1.year.from_now\n end\n end\n Delayed::Job.enqueue(LongTasks::RecurringPaymentNotification.new(id), run_at: run_at - 1.day) if run_at && ['tithe', 'partnership'].include?(goal)\n Delayed::Job.enqueue(LongTasks::RecurringPayment.new(id), run_at: run_at) if run_at\n end",
"def end_of_month\n self.class.new year, month + 1, 0\n end",
"def create_activity_factory_wrapper\n if recurrence\n create_activity_factory({\n # Fields copied straight from +Activity+ model\n name:name,\n description:description,\n vendor_id:vendor_id,\n vendor_name:vendor_name,\n bookings_available:bookings_available,\n price:price,\n start: start,\n # Fields inferred from +Activity+ model\n duration: (start && finish && finish - start)\n }.merge(recurrence) )\n return !activity_factory.new_record?\n end\n end",
"def ending\n # If there's a next chapter, return that timestamp\n # Else, if there's an event, but it's before the end of this chapter, return the timestamp of this chapter\n # Else return the timestamp of the user's last event\n if self.next\n self.next.beginning\n else\n Time.now + 1.hour\n end\n end",
"def end_date_time=(value)\n @end_date_time = value\n end",
"def end_date_time=(value)\n @end_date_time = value\n end",
"def end_date_time=(value)\n @end_date_time = value\n end",
"def end_date_time=(value)\n @end_date_time = value\n end",
"def end_date_time=(value)\n @end_date_time = value\n end",
"def end_date_time=(value)\n @end_date_time = value\n end",
"def end\n @organization_timeline_entry.ended_at = DateTime.now\n @organization_timeline_entry.save\n respond_with(@organization_timeline_entry, location: params[:url])\n end",
"def end_time\n end_at.strftime(\"%F\") if end_at\n end",
"def save!\n parse_timestamps\n # Create a deep copy of self and convert all timestamps to rfc822 to avoid OS specific rounding aberrations\n to_sync = Hash[self.keys.map { |label| [label, self[label].map(&:rfc822)] }]\n # Check existing occurrence_entries\n @object.occurrence_entries.each do |occurrence|\n # Delete occurrences that are not in this hash\n occurrence.destroy unless to_sync.has_key?(occurrence.label) && to_sync[occurrence.label].include?(occurrence.at.rfc822)\n # Remove existing occurrences from the hash of occurrences to create\n to_sync[occurrence.label].delete(occurrence.at.rfc822) if to_sync.has_key?(occurrence.label)\n end\n # Create missing occurrences\n to_sync.each do |label, timestamps|\n timestamps.each do |rfc822_timestring|\n OccurrenceEntry.create!(:post => @object, :label => label, :at => Time.rfc822(rfc822_timestring))\n end\n end\n end"
] |
[
"0.5763601",
"0.5387704",
"0.53857356",
"0.5185503",
"0.5135289",
"0.5082209",
"0.5046865",
"0.49230257",
"0.49175847",
"0.48854795",
"0.48763958",
"0.48498565",
"0.47798568",
"0.47605047",
"0.47566348",
"0.47039258",
"0.46834975",
"0.46650645",
"0.46538442",
"0.4641134",
"0.4638644",
"0.46374172",
"0.46186766",
"0.46155828",
"0.4603641",
"0.46012363",
"0.45995098",
"0.45995098",
"0.45984018",
"0.45973173",
"0.4574674",
"0.45522082",
"0.4547734",
"0.45426786",
"0.45312518",
"0.4529054",
"0.45200855",
"0.45179224",
"0.45130676",
"0.45092434",
"0.44989574",
"0.44904646",
"0.44863424",
"0.44840267",
"0.44702265",
"0.44652265",
"0.44550684",
"0.445218",
"0.44487405",
"0.44449612",
"0.4430288",
"0.44283363",
"0.4427492",
"0.44200397",
"0.4413448",
"0.44119105",
"0.4411209",
"0.4394977",
"0.43864578",
"0.43846574",
"0.43830642",
"0.4380967",
"0.4375336",
"0.43737423",
"0.43711883",
"0.43685153",
"0.43646875",
"0.4345161",
"0.43382126",
"0.43327096",
"0.43300945",
"0.43292308",
"0.43279508",
"0.43233126",
"0.43203172",
"0.4319729",
"0.43127537",
"0.42952606",
"0.42952248",
"0.42850068",
"0.42843634",
"0.4273661",
"0.42709336",
"0.4270814",
"0.4265299",
"0.42626652",
"0.42614734",
"0.42611676",
"0.42519853",
"0.42483672",
"0.42454052",
"0.42384782",
"0.42323503",
"0.42323503",
"0.42323503",
"0.42323503",
"0.42323503",
"0.42323503",
"0.42322046",
"0.42310974",
"0.42301396"
] |
0.0
|
-1
|
Create a recurrence occurring between the start and end of a given date range; :between is shorthand for separate :starts and :until options. When used with explicit :start and/or :until options, those will take precedence.
|
def between(date_range)
merge(between: date_range)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def for_date_range(beginning:, ending:)\n new_with_date_range(beginning, ending)\n end",
"def date_between (min, max)\n Predicate.new(:date_between, { min: min, max: max}) do |o|\n o >= min && o <= max\n end\n end",
"def between_dates(start, finish)\n start = start.chronify(guess: :begin, future: false) if start.is_a?(String)\n finish = finish.chronify(guess: :end) if finish.is_a?(String)\n WWID.new.filter_items(self, opt: { date_filter: [start, finish] })\n end",
"def booked_date_range\n { from: :start_date, to: :end_date }\n end",
"def between(start, finish=nil)\n @operator = :between\n if !finish.nil?\n @value = [start, finish]\n else\n @value = start\n end\n self\n end",
"def date_range\n @date_range ||= start_at..end_at\n end",
"def date_range( start_date, end_date )\n d_range = []\n cur_date = start_date \n\n until cur_date == end_date\n d_range << cur_date\n cur_date = Calendar.next_day( cur_date )\n end\n \n d_range << end_date\n end",
"def between_dates(start_date, end_date)\n start_date = coerce_date(start_date)\n end_date = coerce_date(end_date)\n time_sheet = TimeSheet.new\n each do |record|\n time_sheet << record if record[:date] >= start_date and\n record[:date] <= end_date\n end\n time_sheet\n end",
"def range\n (start_date...end_date) #exclusive date range\n end",
"def new_with_date_range(begin_date, end_date)\n report = new\n report.set_date_range(begin_date, end_date)\n report\n end",
"def to_range_within(range)\n nb_weeks_offset = self.weekly_recurring ? ((range.end - self.starts_at.to_datetime) / 7).to_i : 0\n r = Range.new(self.starts_at + nb_weeks_offset.week, self.ends_at + nb_weeks_offset.week)\n range.cover?(r.begin)&&range.cover?(r.end) ? r : nil\n end",
"def items_between(start_date, end_date, opts={})\n items do |obj|\n obj.restriction = { :and =>\n [\n {:is_greater_than_or_equal_to =>\n [\n {:field_uRI => {:field_uRI=>'item:DateTimeReceived'}},\n {:field_uRI_or_constant=>{:constant => {:value =>start_date}}}\n ]\n },\n {:is_less_than_or_equal_to =>\n [\n {:field_uRI => {:field_uRI=>'item:DateTimeReceived'}},\n {:field_uRI_or_constant=>{:constant => {:value =>end_date}}}\n ]\n }\n ]\n }\n end\n end",
"def in_range(*args)\n opts = args.last.kind_of?(Hash) ? args.pop : {}\n limit = opts[:limit]\n count = 1\n t_start, t_end = args.first.kind_of?(Range) ? [args.first.first, args.first.last] : [args.first,args.last]\n\n raise ArgumentError, \"must be a range or two date/time objects\" unless t_start and t_end\n\n self.start = t_start\n\n @in_range ||= begin\n result = []\n loop do\n next!\n break if count > limit if limit\n break if to_date > t_end\n result << to_date\n count += 1\n end\n\n result\n end\n end",
"def to_range\n start_date..end_date\n end",
"def to_range\n (@start_date..@end_date)\n end",
"def between(start_line, end_line=nil)\n return self unless start_line\n\n if start_line.is_a? Range\n end_line = start_line.last\n end_line -= 1 if start_line.exclude_end?\n\n start_line = start_line.first\n else\n end_line ||= start_line\n end\n\n if start_line > 0\n start_idx = @lines.index { |l| l.last >= start_line } || @lines.length\n else\n start_idx = start_line\n end\n\n if end_line > 0\n end_idx = (@lines.index { |l| l.last > end_line } || 0) - 1\n else\n end_idx = end_line\n end\n\n alter do\n @lines = @lines[start_idx..end_idx] || []\n end\n end",
"def specified_period\n @range = [@start_date, @end_date]\n end",
"def between(first_date, last_date)\n return [] if first_date > last_date\n current_date = first_date\n active_dates = []\n until current_date >= last_date\n active_dates << current_date if active?(current_date)\n current_date = current_date.next_day\n end\n\n active_dates\n rescue NoMethodError\n p 'provided date is not of valid type'\n nil\n end",
"def date_between(range)\n min_date = range.min.is_a?(Date) ? range.min : Date.parse(range.min)\n max_date = range.max.is_a?(Date) ? range.max : Date.parse(range.max)\n\n diff = (max_date - min_date).to_i\n min_date + rand(diff)\n end",
"def range_start=( value ); @range_start = value; rationalise_dates(); end",
"def setup_range(date)\n diff = date.wday - self.class.windex(start_wday)\n @first = date - (diff + ((diff < 0) ? DAYS : 0))\n @last = @first + DAYS - 1\n end",
"def attendance_between_dates_condition\n\t\t\"attendances.attendance_on BETWEEN '#{start_on}' AND '#{end_on}'\"\n\tend",
"def report_range(start_date, end_date)\n @start_date = start_date\n @end_date = end_date\n end",
"def rationalise_dates\n default_range = date_range()\n\n begin\n if ( not @range_month_start.blank? )\n year, month = unpack_string( @range_month_start )\n range_start = Date.new( year, month )\n elsif ( not @range_week_start.blank? )\n year, week = unpack_string( @range_week_start )\n range_start = Timesheet.date_for( year, week, TimesheetRow::FIRST_DAY, true )\n else\n range_start = Date.parse( @range_start )\n end\n rescue\n range_start = default_range.min\n end\n\n begin\n if ( not @range_month_end.blank? )\n year, month = unpack_string( @range_month_end )\n range_end = Date.new( year, month ).at_end_of_month()\n elsif ( not @range_week_end.blank? )\n year, week = unpack_string( @range_week_end )\n range_end = Timesheet.date_for( year, week, TimesheetRow::LAST_DAY, true )\n else\n range_end = Date.parse( @range_end )\n end\n rescue\n range_end = default_range.max\n end\n\n if ( range_end < range_start )\n @range = range_end..range_start\n else\n @range = range_start..range_end\n end\n\n # Hard-coded range throttle to 32 days (just over a \"longest month\") for\n # daily reports to avoid excessive server load.\n\n if ( @frequency_data[ :generator ] == :daily_report )\n @range = ( @range.last - 32.days )..( @range.last ) if ( @range.last.to_time - @range.first.to_time > 32.days )\n end\n end",
"def get_drs_from_range(start_date, end_date)\n self.delta_requests.select do |dr|\n begin\n dr.start_time > start_date and dr.start_time < end_date\n rescue\n false\n end\n end\n end",
"def between(start, finish, options={})\n field = options[:field] || by_star_field\n scope = where(\"#{field} >= ? AND #{field} <= ?\",\n start, finish)\n scope = scope.order(options[:order]) if options[:order]\n scope\n end",
"def date_range(from_date, until_date, options = {})\n options.symbolize_keys!\n format = options[:format] || :short\n separator = options[:separator] || \"-\"\n\n if format.to_sym == :short\n month_names = I18n.t(\"date.abbr_month_names\")\n else\n month_names = I18n.t(\"date.month_names\")\n end\n\n from_day = from_date.day\n from_month = month_names[from_date.month]\n from_year = from_date.year\n until_day = until_date.day\n\n dates = { from_day: from_day }\n\n if from_date.day == until_date.day && from_date.month == until_date.month && from_date.year == until_date.year\n date_format = \"same_day\"\n dates.merge!(day: from_day, month: from_month, year: from_year)\n elsif from_date.month == until_date.month && from_date.year == until_date.year\n date_format = \"same_month\"\n dates.merge!(until_day: until_day, month: from_month, year: from_year)\n else\n until_month = month_names[until_date.month]\n\n dates.merge!(from_month: from_month, until_month: until_month, until_day: until_day)\n\n if from_date.year == until_date.year\n date_format = \"different_months_same_year\"\n dates.merge!(year: from_year)\n else\n until_year = until_date.year\n\n date_format = \"different_years\"\n dates.merge!(from_year: from_year, until_year: until_year)\n end\n end\n\n I18n.t(\"date_range.#{format}.#{date_format}\", dates.merge(sep: separator))\n end",
"def between_dates(**mapping)\n render(STANDARD, BETWEEN_DATES, **mapping)\n end",
"def events_between(date_start, date_end, start = event_start)\n\n events = []\n current_date = date_start\n\n while current_date <= date_end\n current_date = next_event_after(current_date, start)\n if current_date <= date_end\n event = {start_date: current_date, end_date: current_date + duration}\n yield(event) if block_given?\n events << event\n end\n # add one day so it doesn't return the same day\n # probably shouldn't need to do this\n current_date += 1\n end\n\n events\n end",
"def validate_date_range(record, start_date_attr, start_date, end_date_attr)\n # retrieve end_date value\n end_date = record.send(end_date_attr)\n\n return if date_start_before_end?(start_date, end_date)\n\n record.errors.add(start_date_attr, :before_date_error)\n record.errors.add(end_date_attr, :after_date_error)\n end",
"def between(a, b = nil)\n Between.new(a.kind_of?(Range) ? a : a..b)\n end",
"def date_range(start_str, end_str)\n Date.parse(start_str)..Date.parse(end_str)\n rescue ArgumentError => e\n halt 400, { err: 'Invalid date(s)', msg: e.message }.to_json\n end",
"def date_between_dates(first, last)\n Faker::Date.between(first, last)\n end",
"def add_date_interval(predicate, start_date, end_date, fmt = nil)\n return if(start_date.blank? && end_date.blank?)\n if(start_date.blank?)\n add_date(predicate, start_date, true, fmt)\n elsif(end_date.blank?)\n add_date(predicate, end_date, true, fmt)\n else\n add(predicate, \"#{to_iso8601(parse_date(start_date, fmt))}/#{to_iso8601(parse_date(end_date, fmt))}\", required)\n end\n end",
"def between(from:, to:); end",
"def between(start_timestamp, end_timestamp, options={})\n request_params = {\n :started_at__gte => start_timestamp.to_i,\n :started_at__lte => end_timestamp.to_i\n }\n\n request_options = options.merge!(request_params)\n\n all(request_options)\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def between(start_line, end_line = nil)\n return self unless start_line\n\n code_range = CodeRange.new(start_line, end_line)\n\n alter do\n @lines = @lines[code_range.indices_range(@lines)] || []\n end\n end",
"def make_date_range from, to, keys = { sent: 0, received: 0 }\n\t\t\trange = Hash.new\n\t\t\treturn range if Time.at(to) < Time.at(from)\n\t\t\tfrom = Time.at(from).to_date\n\t\t\tto = Time.at(to).to_date\n\t\t\t(to - from).to_i.times { |i|\n\t\t\t\tindex = from + i.day\n\t\t\t\trange[index.to_s] = OpenStruct.new(keys.merge(date: index.to_time.to_i))\n\t\t\t}\n\t\t\trange\n\t\tend",
"def create_date_range(project_id, query_id, opts = {})\n post \"projects/#{project_id}/queries/#{query_id}/date-range\", opts\n end",
"def retrieve_date_range\n\t\t@free_period = false\n\t\t@from, @to = nil, nil\n\t\tperiod_type = params[:period_type]\n\t\tperiod = params[:period]\n\t\tfromdate = params[:from]\n\t\ttodate = params[:to]\n\n\t\tif (period_type == '1' || (period_type.nil? && !period.nil?)) \n\t\t case period.to_s\n\t\t when 'current_month'\n\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1)\n\t\t\t@to = (@from >> 1) - 1\n\t\t when 'last_month'\n\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n\t\t\t@to = (@from >> 1) - 1\n\t\t end\n\t\telsif period_type == '2' || (period_type.nil? && (!fromdate.nil? || !todate.nil?))\n\t\t begin; @from = Date.civil((fromdate.to_s.to_date).year,(fromdate.to_s.to_date).month, 1) unless fromdate.blank?; rescue; end\n\t\t begin; @to = (@from >> 1) - 1 unless @from.blank?; rescue; end\n\t\t if @from.blank?\n\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1)\n\t\t\t@to = (@from >> 1) - 1\n\t\t end\n\t\t @free_period = true\n\t\telse\n\t\t # default\n\t\t # 'current_month'\t\t\n\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1)\n\t\t\t@to = (@from >> 1) - 1\n\t\tend \n\t\t\n\t\t@from, @to = @to, @from if @from && @to && @from > @to\n\n\t end",
"def input_date_range(name, from, to)\n field = field_content(name)\n id = field_id(name)\n {\n id: id,\n name: name,\n description: prop(field, 'description'),\n label: prop(field, 'label'),\n from: input_date_month_year(value_by_key(from, 'name'), value_by_key(from, 'date')),\n to: input_date_month_year(value_by_key(to, 'name'), value_by_key(to, 'date')),\n }\n end",
"def set_date_range(begin_date, end_date)\n @begin_date = begin_date.to_date\n @end_date = end_date.to_date\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def between(start_dt, end_date)\n wrap(\n @inner.select do |event|\n stamp = Time.parse(event['created_at'])\n stamp >= start_dt && stamp <= end_date\n end,\n )\n end",
"def find_events_in_range(start_min, start_max,options = {})\n options[:max_results] ||= 25\n options[:order_by] ||= 'lastmodified' # other option is 'starttime'\n formatted_start_min = start_min.strftime(\"%Y-%m-%dT%H:%M:%S\")\n formatted_start_max = start_max.strftime(\"%Y-%m-%dT%H:%M:%S\")\n query = \"?start-min=#{formatted_start_min}&start-max=#{formatted_start_max}&recurrence-expansion-start=#{formatted_start_min}&recurrence-expansion-end=#{formatted_start_max}\"\n query = \"#{query}&orderby=#{options[:order_by]}&max-results=#{options[:max_results]}\"\n event_lookup(query)\n end",
"def between?(first_day, last_day)\n ((self.ends_at.to_date >= first_day) && (self.ends_at.to_date <= last_day)) || ((self.starts_at.to_date >= first_day) && (self.starts_at.to_date <= last_day))\n end",
"def retrieve_date_range\n @free_period = false\n @from, @to = nil, nil\n\n if params[:period_type] == '1' || (params[:period_type].nil? && !params[:period].nil?)\n case params[:period].to_s\n when 'today'\n @from = @to = Date.today\n when 'yesterday'\n @from = @to = Date.today - 1\n when 'current_week'\n @from = Date.today - (Date.today.cwday - 1)%7\n @to = @from + 6\n when 'last_week'\n @from = Date.today - 7 - (Date.today.cwday - 1)%7\n @to = @from + 6\n when '7_days'\n @from = Date.today - 7\n @to = Date.today\n when 'current_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1)\n @to = (@from >> 1) - 1\n when 'last_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n @to = (@from >> 1) - 1\n when '30_days'\n @from = Date.today - 30\n @to = Date.today\n when 'current_year'\n @from = Date.civil(Date.today.year, 1, 1)\n @to = Date.civil(Date.today.year, 12, 31)\n end\n elsif params[:period_type] == '2' || (params[:period_type].nil? && (!params[:from].nil? || !params[:to].nil?))\n begin; @from = params[:from].to_s.to_date unless params[:from].blank?; rescue; end\n begin; @to = params[:to].to_s.to_date unless params[:to].blank?; rescue; end\n @free_period = true\n else\n # default\n end\n \n @from, @to = @to, @from if @from && @to && @from > @to\n\n end",
"def determine_date_range\n case @time_frame\n when 'week' then (@date.beginning_of_week..@date.end_of_week)\n when 'month' then (@date.beginning_of_month..@date.end_of_month)\n end\n end",
"def query_user_for_date_range\n start_date, end_date = nil\n\n # untill we have both dates\n until start_date && end_date\n puts \"\\nFirst, we need a start date:\"\n start_date = query_user_for_date\n\n puts \"\\nNext, we need an end date:\"\n end_date = query_user_for_date\n\n if !date_range_valid?(start_date, end_date)\n puts \"Let's start again!\"\n start_date = end_date = nil\n end\n end\n return start_date, end_date # retunr both values as an array\nend",
"def add(from, to)\n @day.merge_range(@with_time ? Range.create_time_range(from, to) : from..to)\n day\n end",
"def query_user_for_date_range\n\tstart_date = nil\n\tend_date = nil\n\n\tuntil start_date && end_date\n\t\tputs \"\\n First, we need a start date.\"\n\t\tstart_date = query_user_for_date\n\n\t\tputs \"Next, we need an end date.\"\n\t\tend_date = query_user_for_date\n\n\t\tif !date_range_valid?(start_date, end_date)\n\t\t\tputs \"Let's try again\"\n\t\t\tstart_date = end_date = nil\n\t\tend\n\tend\n\n\treturn start_date, end_date\nend",
"def between(s,e,opts={})\n all(opts.merge!(:start.lte => e, :end.gte => s ))\n end",
"def make_resevation(date_range)\n available_rooms = get_available_rooms(date_range)\n if available_rooms.length < 1\n raise ArgumentError\n end\n new_reservation = Hotel::Reservation.new(date_range,available_rooms[0])\n @reservations << new_reservation\n return new_reservation\n end",
"def date_range\n errors.add(:start_date, 'can not be greater than end date') if start_date > end_date\n end",
"def dates_ranges\n (1..8).to_a.collect do |i|\n {\n start_date: i.days.ago,\n end_date: DateTime.now,\n num_of_days: i + 1\n }\n end\n end",
"def retrieve_date_range\n\t\t@free_period = false\n\t\t@from, @to = nil, nil\n\t\tperiod_type = session[controller_name][:period_type]\n\t\tperiod = session[controller_name][:period]\n\t\tfromdate = session[controller_name][:from]\n\t\ttodate = session[controller_name][:to]\n\t\t\n\t\tif (period_type == '1' || (period_type.nil? && !period.nil?)) \n\t\t case period.to_s\n\t\t\t when 'today'\n\t\t\t\t@from = @to = Date.today\n\t\t\t when 'yesterday'\n\t\t\t\t@from = @to = Date.today - 1\n\t\t\t when 'current_week'\n\t\t\t\t@from = getStartDay(Date.today - (Date.today.cwday - 1)%7)\n\t\t\t\t@to = @from + 6\n\t\t\t when 'last_week'\n\t\t\t\t@from =getStartDay(Date.today - 7 - (Date.today.cwday - 1)%7)\n\t\t\t\t@to = @from + 6\n\t\t\t when '7_days'\n\t\t\t\t@from = Date.today - 7\n\t\t\t\t@to = Date.today\n\t\t\t when 'current_month'\n\t\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1)\n\t\t\t\t@to = (@from >> 1) - 1\n\t\t\t when 'last_month'\n\t\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n\t\t\t\t@to = (@from >> 1) - 1\n\t\t\t when '30_days'\n\t\t\t\t@from = Date.today - 30\n\t\t\t\t@to = Date.today\n\t\t\t when 'current_year'\n\t\t\t\t@from = Date.civil(Date.today.year, 1, 1)\n\t\t\t\t@to = Date.civil(Date.today.year, 12, 31)\n\t end\n\t\telsif period_type == '2' || (period_type.nil? && (!fromdate.nil? || !todate.nil?))\n\t\t begin; @from = fromdate.to_s.to_date unless fromdate.blank?; rescue; end\n\t\t begin; @to = todate.to_s.to_date unless todate.blank?; rescue; end\n\t\t @free_period = true\n\t\telse\n\t\t # default\n\t\t # 'current_month'\t\t\n\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1)\n\t\t\t@to = (@from >> 1) - 1\n\t end \n\t\t\n\t\t@from, @to = @to, @from if @from && @to && @from > @to\n\n\tend",
"def retrieve_date_range\n\t\t@free_period = false\n\t\t@from, @to = nil, nil\n\t\tperiod_type = session[controller_name][:period_type]\n\t\tperiod = session[controller_name][:period]\n\t\tfromdate = session[controller_name][:from]\n\t\ttodate = session[controller_name][:to]\n\t\t\n\t\tif (period_type == '1' || (period_type.nil? && !period.nil?)) \n\t\t case period.to_s\n\t\t\t when 'today'\n\t\t\t\t@from = @to = Date.today\n\t\t\t when 'yesterday'\n\t\t\t\t@from = @to = Date.today - 1\n\t\t\t when 'current_week'\n\t\t\t\t@from = getStartDay(Date.today - (Date.today.cwday - 1)%7)\n\t\t\t\t@to = @from + 6\n\t\t\t when 'last_week'\n\t\t\t\t@from =getStartDay(Date.today - 7 - (Date.today.cwday - 1)%7)\n\t\t\t\t@to = @from + 6\n\t\t\t when '7_days'\n\t\t\t\t@from = Date.today - 7\n\t\t\t\t@to = Date.today\n\t\t\t when 'current_month'\n\t\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1)\n\t\t\t\t@to = (@from >> 1) - 1\n\t\t\t when 'last_month'\n\t\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n\t\t\t\t@to = (@from >> 1) - 1\n\t\t\t when '30_days'\n\t\t\t\t@from = Date.today - 30\n\t\t\t\t@to = Date.today\n\t\t\t when 'current_year'\n\t\t\t\t@from = Date.civil(Date.today.year, 1, 1)\n\t\t\t\t@to = Date.civil(Date.today.year, 12, 31)\n\t end\n\t\telsif period_type == '2' || (period_type.nil? && (!fromdate.nil? || !todate.nil?))\n\t\t begin; @from = fromdate.to_s.to_date unless fromdate.blank?; rescue; end\n\t\t begin; @to = todate.to_s.to_date unless todate.blank?; rescue; end\n\t\t @free_period = true\n\t\telse\n\t\t # default\n\t\t # 'current_month'\t\t\n\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1)\n\t\t\t@to = (@from >> 1) - 1\n\t end \n\t\t\n\t\t@from, @to = @to, @from if @from && @to && @from > @to\n\n\tend",
"def add_range(left, right)\n \n end",
"def add_range(left, right)\n \n end",
"def range(range_start, range_end, end_reached_cb=nil)\n if range_start == nil\n result = XML.new(name, attrs)\n else\n result = nil\n end\n @contents.each {|c|\n # end reached !\n if range_end and c.object_id == range_end.object_id\n end_reached_cb.call if end_reached_cb\n break\n end\n # start reached !\n if range_start and c.object_id == range_start.object_id\n result = XML.new(name, attrs)\n next\n end\n if result # We already started\n if c.is_a? XML\n break_me = false\n result.add! c.range(nil, range_end, lambda{ break_me = true })\n if break_me\n end_reached_cb.call if end_reached_cb\n break\n end\n else # String/XML_PI/XML_Comment\n result.add! c\n end\n else\n # Strings/XML_PI/XML_Comment obviously cannot start a range\n if c.is_a? XML\n break_me = false\n r = c.range(range_start, range_end, lambda{ break_me = true })\n if r\n # start reached !\n result = XML.new(name, attrs, r)\n end\n if break_me\n # end reached !\n end_reached_cb.call if end_reached_cb\n break\n end\n end\n end\n }\n return result\n end",
"def generate_payments start_date, end_date\n \tdates = start_date.step( end_date ).\n \t select { |date| date.day == bill.due_on }.\n \t map { |date| Payment.from date, bill, self }\n end",
"def find_in_date_range(participant_id:, start_date:, end_date:)\n response = request(\n :get_all_decns_at_issue_for_date_range,\n \"veteranID\": participant_id,\n \"startDate\": start_date,\n \"endDate\": end_date\n )\n response.body[:get_all_decns_at_issue_for_date_range_response][:decns_at_issue_for_date_range]\n end",
"def date_range_scope\n Article.where('created_at BETWEEN ? AND ?', @date_from, @date_to)\n end",
"def build_condition_for_date(start_date, end_date, start_date_string=\"created_at\", end_date_string=\"created_at\")\n\t\t\" #{start_date_string} >= '#{start_date.to_time}' and #{end_date_string} <= '#{end_date.to_time + 1.day}' \" if validate_date?(start_date,end_date)\n\tend",
"def get_occurrences(start_date, interval, end_date)\n\n start_date = Date.new(start_date.year,start_date.month,start_date.mday)\n end_date = Date.new(end_date.year,end_date.month,end_date.mday)\n raise ArgumentError, \"Start date (#{start_date}) should be less than or equal to end date (#{end_date})\" if (start_date>end_date)\n\n i_length, i_unit = parse_interval(interval)\n\n if i_length == 0.5 && ![:m, :y].include?(i_unit)\n raise ArgumentError, \"Semi- interval is not supported to this units (#{i_unit.to_s})\"\n end\n\n new_interval = case i_unit\n when :d then {:length=>i_length, :unit=>:days}\n when :w then {:length=>i_length*7, :unit=>:days}\n when :m then {:length=>i_length, :unit=>:months}\n when :y then {:length=>i_length*12, :unit=>:months}\n end\n\n if new_interval[:unit] == :days\n new_occurrences = 1 + ((end_date - start_date)/new_interval[:length]).to_i\n elsif new_interval[:unit] == :months\n new_occurrences = 1 + (months_between(end_date, start_date)/new_interval[:length]).to_i \n end\n return new_occurrences\n end",
"def in(*args)\n if args.size == 1 && (range = args.first).is_a?(Range)\n return Between.new(self, range)\n end\n\n In.new(self, *args)\n end",
"def date_between(from = nil, to = nil, format = '%D')\n raise ArgumentError, 'Invalid date format' if from.to_s.empty? || to.to_s.empty?\n\n start_date = from.nil? ? Date.today.strftime(format) : Date.strptime(from, format)\n end_date = to.nil? ? Date.today.strftime(format) : Date.strptime(to, format)\n\n Faker::Date.between(from: start_date, to: end_date).strftime(format)\n end",
"def retrieve_date_range_14\n @free_period = false\n @from, @to = nil, nil\n\n if params[:period_type] == '1' || (params[:period_type].nil? && !params[:period].nil?)\n case params[:period].to_s\n when 'today'\n @from = @to = Date.today\n when 'yesterday'\n @from = @to = Date.today - 1\n when 'current_week'\n @from = Date.today - (Date.today.cwday - 1)%7\n @to = @from + 6\n when 'last_week'\n @from = Date.today - 7 - (Date.today.cwday - 1)%7\n @to = @from + 6\n when '7_days'\n @from = Date.today - 7\n @to = Date.today\n when 'current_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1)\n @to = (@from >> 1) - 1\n when 'last_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n @to = (@from >> 1) - 1\n when '30_days'\n @from = Date.today - 30\n @to = Date.today\n when 'current_year'\n @from = Date.civil(Date.today.year, 1, 1)\n @to = Date.civil(Date.today.year, 12, 31)\n end\n elsif params[:period_type] == '2' || (params[:period_type].nil? && (!params[:from].nil? || !params[:to].nil?))\n begin; @from = params[:from].to_s.to_date unless params[:from].blank?; rescue; end\n begin; @to = params[:to].to_s.to_date unless params[:to].blank?; rescue; end\n @free_period = true\n else\n # default\n end\n\n @from, @to = @to, @from if @from && @to && @from > @to\n end",
"def between?(inclusive, start, stop, event)\n ((after?(inclusive, start, event)) &&\n (before?(inclusive, stop, event)))\nend",
"def reservations_by_date_range(date_range)\n res_by_date_range = @reservations.select do |res|\n res.date_range.overlaps?(date_range)\n end\n return res_by_date_range\n end",
"def add_reservation(start_date, end_date)\n @bookings << [start_date, end_date]\n end",
"def retrieve_date_range_11\n @free_period = false\n @from, @to = nil, nil\n\n if params[:period_type] == '1' || (params[:period_type].nil? && !params[:period].nil?)\n case params[:period].to_s\n when 'today'\n @from = @to = Date.today\n when 'yesterday'\n @from = @to = Date.today - 1\n when 'current_week'\n @from = Date.today - (Date.today.cwday - 1)%7\n @to = @from + 6\n when 'last_week'\n @from = Date.today - 7 - (Date.today.cwday - 1)%7\n @to = @from + 6\n when '7_days'\n @from = Date.today - 7\n @to = Date.today\n when 'current_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1)\n @to = (@from >> 1) - 1\n when 'last_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n @to = (@from >> 1) - 1\n when '30_days'\n @from = Date.today - 30\n @to = Date.today\n when 'current_year'\n @from = Date.civil(Date.today.year, 1, 1)\n @to = Date.civil(Date.today.year, 12, 31)\n end\n elsif params[:period_type] == '2' || (params[:period_type].nil? && (!params[:from].nil? || !params[:to].nil?))\n begin; @from = params[:from].to_s.to_date unless params[:from].blank?; rescue; end\n begin; @to = params[:to].to_s.to_date unless params[:to].blank?; rescue; end\n @free_period = true\n else\n # default\n end\n \n @from, @to = @to, @from if @from && @to && @from > @to\n @from ||= (TimeEntry.earilest_date_for_project(@project) || Date.today)\n @to ||= (TimeEntry.latest_date_for_project(@project) || Date.today)\n end",
"def url_params_for_date_range\n begin\n start_date = Date.parse(params[:start])\n end_date = Date.parse(params[:end])\n rescue ArgumentError\n halt 'Invalid date format'\n end\n\n # call for validation\n if !date_valid?(start_date)\n halt \"Start date must be after #{DATA_START_DATE} and before today.\"\n elsif !date_valid?(end_date)\n halt \"End date must be after #{DATA_START_DATE} and before today.\"\n elsif !date_range_valid?(start_date, end_date)\n halt 'Invalid date range!'\n end\n return start_date, end_date\nend",
"def range_rc(start_num, end_num)\n\n return [] if end_num <= start_num\n range_rc(start_num, end_num - 1) + [end_num - 1]\nend",
"def day_range(rng=self)\n if rng.respond_to?(:exclude_end?) && rng.exclude_end?\n Range.new(rng.begin.to_date, rng.end.to_date, true)\n else\n Range.new(rng.begin.to_date, rng.end.to_date + 1, true)\n end\n end",
"def declare_beg_range\n\t\t@beg_range = @beg_range.to_date \n\t\t@end_range = @end_range.to_date \n\tend",
"def between(expected, upper = nil)\n if expected.kind_of?(Range)\n set_relativity(:between, expected)\n elsif upper.nil?\n raise ArgumentError,\n 'You must supply an upper boundary for the collection size'\n else\n set_relativity(:between, (expected..upper))\n end\n end",
"def between(from, to)\n FFaker::Time.between(from, to).to_date\n end",
"def retrieve_date_range\n\t\t@free_period = false\n\t\t@from, @to = nil, nil\n\t\tperiod_type = session[:wkattendance][:period_type]\n\t\tperiod = session[:wkattendance][:period]\n\t\tfromdate = session[:wkattendance][:from]\n\t\ttodate = session[:wkattendance][:to]\n\t\tif (period_type == '1' || (period_type.nil? && !period.nil?)) \n\t\t case period.to_s\n\t\t when 'today'\n\t\t\t@from = @to = Date.today\n\t\t when 'yesterday'\n\t\t\t@from = @to = Date.today - 1\n\t\t when 'current_week'\n\t\t\t@from = getStartDay(Date.today - (Date.today.cwday - 1)%7)\n\t\t\t@to = Date.today #@from + 6\n\t\t when 'last_week'\n\t\t\t@from =getStartDay(Date.today - 7 - (Date.today.cwday - 1)%7)\n\t\t\t@to = @from + 6\n\t\t when '7_days'\n\t\t\t@from = Date.today - 7\n\t\t\t@to = Date.today\n\t\t when 'current_month'\n\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1)\n\t\t\t@to = Date.today #(@from >> 1) - 1\n\t\t when 'last_month'\n\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n\t\t\t@to = (@from >> 1) - 1\n\t\t when '30_days'\n\t\t\t@from = Date.today - 30\n\t\t\t@to = Date.today\n\t\t when 'current_year'\n\t\t\t@from = Date.civil(Date.today.year, 1, 1)\n\t\t\t@to = Date.today #Date.civil(Date.today.year, 12, 31)\n\t\t end\n\t\t#elsif params[:period_type] == '2' || (params[:period_type].nil? && (!params[:from].nil? || !params[:to].nil?))\n\t\telsif period_type == '2' || (period_type.nil? && (!fromdate.nil? || !todate.nil?))\n\t\t begin; @from = fromdate.to_s.to_date unless fromdate.blank?; rescue; end\n\t\t begin; @to = todate.to_s.to_date unless todate.blank?; rescue; end\n\t\t @free_period = true\n\t\telse\n\t\t # default\n\t\t # 'current_month'\t\t\n\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1)\n\t\t\t@to = Date.today #(@from >> 1) - 1\n\t\tend \n\n\t\t@from, @to = @to, @from if @from && @to && @from > @to\n\n\tend",
"def reserve_room(start_date, end_date)\n if start_date.class != Date || end_date.class != Date\n raise ArgumentError.new(\"Please input valid dates\")\n else\n reservation = Reservation.new(start_date, end_date)\n @reservations << reservation\n return reservation\n end\n end",
"def query_user_for_date_range\n start_date = nil\n end_date = nil\n\n puts \"\\nFirst, we need a start date.\"\n start_date = query_user_for_date\n\n puts \"\\nNext, we need an end date.\"\n end_date = query_user_for_date\n\n return start_date, end_date\nend",
"def overlapping_requests\n\t\tbetween_string = 'BETWEEN #{self.start_date} AND #{self.end_date}'\n\n\t\tCatRentalRequest\n\t\t\t.where.not(id: self.id)#don't want to pick self\n\t\t\t.where(cat_id: self.cat_id)\n\t\t\t.where.not('start_date > :end_date OR end_date < :start_date',\n\t\t\t\tstart_date: self.start_date,\n\t\t\t\tend_date: self.end_date)\n\tend",
"def range\n\t\t\t#(@end > @start) ? (@start .. @end) : (@end .. @start)\n\t\t\t(start .. self.end)\n\t\tend",
"def find_events_in_range(start_min, start_max, options = {})\n formatted_start_min = encode_time(start_min)\n formatted_start_max = encode_time(start_max)\n query = \"?timeMin=#{formatted_start_min}&timeMax=#{formatted_start_max}#{parse_options(options)}\"\n event_lookup(query)\n end",
"def range_check(date)\n if date < @start_date\n # puts \"Reconstruindo calculadora de feriados pois dia #{date} eh menor que #{@start_date} -> #{@end_date}\"\n build(date - 2.days, @end_date, @holidays)\n elsif date > @end_date\n # puts \"Reconstruindo calculadora de feriados pois dia #{date} eh maior que #{end_date}\"\n build(@start_date, date + 252.days, @holidays)\n end\n end",
"def query_range(left, right)\n \n end",
"def query_range(left, right)\n \n end",
"def set_time_range\n begin_date = Date.strptime(params[:begin_date], '%Y-%m-%d') rescue User.minimum(:created_at) rescue Date.new(2015)\n end_date = Date.strptime(params[:end_date], '%Y-%m-%d') rescue Time.zone.today\n @stats_time_range = (begin_date.beginning_of_day)..(end_date.end_of_day)\n end",
"def range \n Range.new(@first, @last)\n end",
"def range(range, options={})\n range = (range..range) if range.is_a? Date\n data = range.map do |date|\n case type\n when :counter\n value = Prisma.redis.get(Prisma.redis_key(name, date)).to_i\n when :bitmap\n bitstring = Prisma.redis.get(Prisma.redis_key(name, date)) || ''\n string = bitstring.unpack('b*').first\n value = options[:skip_bitmap_count] ? string : string.count('1')\n end\n\n [date, value]\n end\n\n Hash[data]\n end",
"def retrieve_date_range\n\t\t@free_period = false\n\t\t@from, @to = nil, nil\n\t\tperiod_type = session[:wkassetdepreciation][:period_type]\n\t\tperiod = session[:wkassetdepreciation][:period]\n\t\tfromdate = session[:wkassetdepreciation][:from]\n\t\ttodate = session[:wkassetdepreciation][:to]\n\t\t\n\t\tif (period_type == '1' || (period_type.nil? && !period.nil?)) \n\t\t case period.to_s\n\t\t\t when 'today'\n\t\t\t\t@from = @to = Date.today\n\t\t\t when 'yesterday'\n\t\t\t\t@from = @to = Date.today - 1\n\t\t\t when 'current_week'\n\t\t\t\t@from = getStartDay(Date.today - (Date.today.cwday - 1)%7)\n\t\t\t\t@to = @from + 6\n\t\t\t when 'last_week'\n\t\t\t\t@from =getStartDay(Date.today - 7 - (Date.today.cwday - 1)%7)\n\t\t\t\t@to = @from + 6\n\t\t\t when '7_days'\n\t\t\t\t@from = Date.today - 7\n\t\t\t\t@to = Date.today\n\t\t\t when 'current_month'\n\t\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1)\n\t\t\t\t@to = (@from >> 1) - 1\n\t\t\t when 'last_month'\n\t\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n\t\t\t\t@to = (@from >> 1) - 1\n\t\t\t when '30_days'\n\t\t\t\t@from = Date.today - 30\n\t\t\t\t@to = Date.today\n\t\t\t when 'current_year'\n\t\t\t\t@from = Date.civil(Date.today.year, 1, 1)\n\t\t\t\t@to = Date.civil(Date.today.year, 12, 31)\n\t end\n\t\telsif period_type == '2' || (period_type.nil? && (!fromdate.nil? || !todate.nil?))\n\t\t begin; @from = fromdate.to_s.to_date unless fromdate.blank?; rescue; end\n\t\t begin; @to = todate.to_s.to_date unless todate.blank?; rescue; end\n\t\t @free_period = true\n\t\telse\n\t\t # default\n\t\t # 'current_month'\t\t\n\t\t\t@from = Date.civil(Date.today.year, Date.today.month, 1)\n\t\t\t@to = (@from >> 1) - 1\n\t end \n\t\t\n\t\t@from, @to = @to, @from if @from && @to && @from > @to\n\n\tend",
"def set_service_range\n self.service_start_date ||= (service_except_dates + service_added_dates).min\n self.service_end_date ||= (service_except_dates + service_added_dates).max\n true\n end",
"def find_between(min, max)\n #place solution here\n end",
"def add_to_dates(start_date, end_date, new_occupancy)\n current_date = start_date.dup\n \n until current_date == end_date\n date_obj = find_date(current_date)\n \n if date_obj \n date_obj.add_occupancy(new_occupancy)\n else\n new_date_obj = Hotel::Date.new(current_date)\n @dates << new_date_obj\n new_date_obj.add_occupancy(new_occupancy)\n end\n \n current_date += 1\n end\n end",
"def events_between(start_date, end_date)\n # 1. The range is exclusive; and we look ahead 2 days in order to find\n # all-day events that end on the second day (UTC, at least).\n # 2. We convert .to_time before .to_date in order to convert the event's\n # start time from UTC to local before truncating it to the date.\n # 3. We finally return only the events we care about.\n @events.items_between(start_date, end_date + 2).map do |event|\n name = event.subject\n start = event.start\n Event.new(name, start.to_time)\n end.select do |event|\n event.date >= start_date && event.date <= end_date\n end\n end",
"def dayrange(start, finish)\n if start > finish\n s = start\n start = finish\n finish = s\n end\n days = [start]\n day = start + 1.day\n while day <= finish\n days << day\n day += 1.day\n end\n days\n end",
"def range(range_start, range_end)\n return [] if range_end < range_start\n return [range_end] if range_end == range_start\n result = [range_end]\n range(range_start, range_end - 1) + result\nend",
"def covering(date_range)\n merge(covering: date_range)\n end"
] |
[
"0.66740245",
"0.6222435",
"0.6163396",
"0.6138086",
"0.60597354",
"0.60344845",
"0.5962342",
"0.5943898",
"0.5922531",
"0.58850247",
"0.584501",
"0.57890815",
"0.5779814",
"0.5774257",
"0.57710946",
"0.57087713",
"0.5700853",
"0.5680202",
"0.56705374",
"0.56635654",
"0.5659538",
"0.56513906",
"0.56249607",
"0.56213343",
"0.56110376",
"0.56073236",
"0.5554679",
"0.5541935",
"0.55262",
"0.55094755",
"0.5471914",
"0.54605585",
"0.5458285",
"0.5450293",
"0.5448494",
"0.5445252",
"0.5406463",
"0.54061025",
"0.5386947",
"0.53731763",
"0.53644896",
"0.5346327",
"0.5343924",
"0.5342145",
"0.53394186",
"0.53308994",
"0.5307239",
"0.5263429",
"0.5244712",
"0.5230089",
"0.5206188",
"0.51943916",
"0.5188908",
"0.51881576",
"0.5186131",
"0.5167879",
"0.51588535",
"0.51588535",
"0.5151541",
"0.5151541",
"0.51471585",
"0.5146861",
"0.51352096",
"0.51275265",
"0.5127261",
"0.51252055",
"0.5116397",
"0.5105332",
"0.50991607",
"0.5093023",
"0.5082023",
"0.5080348",
"0.5078466",
"0.5074008",
"0.5064309",
"0.50581056",
"0.50508463",
"0.50466317",
"0.50415635",
"0.5035654",
"0.5028565",
"0.50199",
"0.5017886",
"0.50125587",
"0.501034",
"0.5010141",
"0.50040454",
"0.50040454",
"0.5003442",
"0.49984974",
"0.4990437",
"0.49672574",
"0.49547783",
"0.49536473",
"0.49526963",
"0.49518517",
"0.49467865",
"0.49463823",
"0.49446914"
] |
0.65354955
|
2
|
Create a recurrence which will only emit values within the date range, also called "masking."
|
def covering(date_range)
merge(covering: date_range)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def range_start=( value ); @range_start = value; rationalise_dates(); end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def range\n (start_date...end_date) #exclusive date range\n end",
"def setup_range(date)\n diff = date.wday - self.class.windex(start_wday)\n @first = date - (diff + ((diff < 0) ? DAYS : 0))\n @last = @first + DAYS - 1\n end",
"def __evolve_date__\n __evolve_range_naive__.transform_values! {|v| v&.__evolve_date__ }\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def get_drs_from_range(start_date, end_date)\n self.delta_requests.select do |dr|\n begin\n dr.start_time > start_date and dr.start_time < end_date\n rescue\n false\n end\n end\n end",
"def mask_for_time_slots\n offset = (ends_at.next_day.beginning_of_day - ends_at) / APPOINTMENT_INTERVAL\n slots_number = (ends_at - starts_at) / APPOINTMENT_INTERVAL\n ('1' * slots_number).to_i(2) << offset\n end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def to_range_within(range)\n nb_weeks_offset = self.weekly_recurring ? ((range.end - self.starts_at.to_datetime) / 7).to_i : 0\n r = Range.new(self.starts_at + nb_weeks_offset.week, self.ends_at + nb_weeks_offset.week)\n range.cover?(r.begin)&&range.cover?(r.end) ? r : nil\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def range_check(date)\n if date < @start_date\n # puts \"Reconstruindo calculadora de feriados pois dia #{date} eh menor que #{@start_date} -> #{@end_date}\"\n build(date - 2.days, @end_date, @holidays)\n elsif date > @end_date\n # puts \"Reconstruindo calculadora de feriados pois dia #{date} eh maior que #{end_date}\"\n build(@start_date, date + 252.days, @holidays)\n end\n end",
"def expand_service_range\n self.service_start_date ||= (service_except_dates + service_added_dates).min\n self.service_end_date ||= (service_except_dates + service_added_dates).max\n true\n end",
"def date_range( start_date, end_date )\n d_range = []\n cur_date = start_date \n\n until cur_date == end_date\n d_range << cur_date\n cur_date = Calendar.next_day( cur_date )\n end\n \n d_range << end_date\n end",
"def create_inbetween_occurrences?\n return unless recurrence.present?\n\n recurrency&.to_i == 7 && recurrence.recurrency&.to_i == 14\n end",
"def date_range\n @date_range ||= start_at..end_at\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def _reduce_202(val, _values, result)\n result = new_irange(val[0], val[1], val[2])\n \n result\nend",
"def specified_period\n @range = [@start_date, @end_date]\n end",
"def reset_local_range(start_date, end_date)\n if start_date.is_a?(Date) && end_date.is_a?(Date)\n @local_range = start_date.to_time.change(:hour => 6, :min => 30)..end_date.to_time.change(:hour => 6, :min => 30)\n elsif local_range.begin.acts_like_time? && local_range.end.acts_like_time?\n @local_range = start_date...end_date\n else\n raise ArgumentError, \"args must either be dates or times\"\n end\n if local_range.begin < begin_time or local_range.end > end_time\n logger.info \"reloading Timeseries #{symbol} #{local_range.begin.to_formatted_s(:ymd)} < #{begin_time.to_formatted_s(:ymd)} *OR* \"+\n \"#{local_range.end.to_formatted_s(:ymd)} > #{end_time.to_formatted_s(:ymd)}\"\n populate()\n puts \"repopulating timeseries on reset_local_range #{start_date}..#{end_date}\"\n else\n map_local_range()\n end\n end",
"def range(range, options={})\n range = (range..range) if range.is_a? Date\n data = range.map do |date|\n case type\n when :counter\n value = Prisma.redis.get(Prisma.redis_key(name, date)).to_i\n when :bitmap\n bitstring = Prisma.redis.get(Prisma.redis_key(name, date)) || ''\n string = bitstring.unpack('b*').first\n value = options[:skip_bitmap_count] ? string : string.count('1')\n end\n\n [date, value]\n end\n\n Hash[data]\n end",
"def for_date_range(beginning:, ending:)\n new_with_date_range(beginning, ending)\n end",
"def reservations_by_date_range(date_range)\n res_by_date_range = @reservations.select do |res|\n res.date_range.overlaps?(date_range)\n end\n return res_by_date_range\n end",
"def set_day_range(days, start_day, end_day)\n pos = Days.index(start_day)\n while pos != (Days.index(end_day) + 1) % 7\n days[pos] = true\n pos = (pos + 1) % 7\n end\n end",
"def recurrence_to_events!(now = Time.now.utc)\n recurring.each {|r| r.recurrence_to_events!(now)}\n end",
"def no_repeats(start_year, end_year)\n (start_year..end_year).to_a.select { |year| no_repeat?(year) }\nend",
"def no_repeats(year_start, year_end)\n no_repeats = []\n (year_start..year_end).each do |yr|\n no_repeats << yr if no_repeat?(yr)\n end\n\n no_repeats\nend",
"def extend_empty_end_date\n if self.end_date == self.start_date && !self.repeat_mode.rule.empty?\n self.end_date = Date.today + 10.year\n end\n return self\n end",
"def rationalise_dates\n default_range = date_range()\n\n begin\n if ( not @range_month_start.blank? )\n year, month = unpack_string( @range_month_start )\n range_start = Date.new( year, month )\n elsif ( not @range_week_start.blank? )\n year, week = unpack_string( @range_week_start )\n range_start = Timesheet.date_for( year, week, TimesheetRow::FIRST_DAY, true )\n else\n range_start = Date.parse( @range_start )\n end\n rescue\n range_start = default_range.min\n end\n\n begin\n if ( not @range_month_end.blank? )\n year, month = unpack_string( @range_month_end )\n range_end = Date.new( year, month ).at_end_of_month()\n elsif ( not @range_week_end.blank? )\n year, week = unpack_string( @range_week_end )\n range_end = Timesheet.date_for( year, week, TimesheetRow::LAST_DAY, true )\n else\n range_end = Date.parse( @range_end )\n end\n rescue\n range_end = default_range.max\n end\n\n if ( range_end < range_start )\n @range = range_end..range_start\n else\n @range = range_start..range_end\n end\n\n # Hard-coded range throttle to 32 days (just over a \"longest month\") for\n # daily reports to avoid excessive server load.\n\n if ( @frequency_data[ :generator ] == :daily_report )\n @range = ( @range.last - 32.days )..( @range.last ) if ( @range.last.to_time - @range.first.to_time > 32.days )\n end\n end",
"def set_service_range\n self.service_start_date ||= (service_except_dates + service_added_dates).min\n self.service_end_date ||= (service_except_dates + service_added_dates).max\n true\n end",
"def limit_default_range(search_params)\n return search_params if search_params\n now = Time.now\n current_month_start = DateTime.new(now.year,now.month,1)\n current_month_end = DateTime.now\n { 'day_gte' => current_month_start,\n 'day_lte' => current_month_end,\n 'user_id_eq' => current_user.id }\n end",
"def recurring(opts={})\n all({DataMapper::Events.recurrence_key.not => nil}.merge(opts))\n end",
"def no_repeats(year_start, year_end)\n result = []\n (year_start..year_end).each do |yr|\n result << yr if no_repeat?(yr)\n end\n result\nend",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def domain_for_event_occurrence(from, to)\n domain = TimeDomains::BoundlessTimeDomain.new\n domain.reference_start = DateTime.now.utc.midnight\n domain.duration = TimeDomains::Duration.new\n domain.duration.duration = 1440\n domain.duration.unit = TimeDomains::Duration::MINUTE\n domain.period = TimeDomains::Duration.new\n domain.period.duration = 1\n domain.period.unit = TimeDomains::Duration::DAY\n\n return domain\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select{|yr|not_repeat_year?(yr)}\nend",
"def no_repeats(year_start, year_end)\n return if year_start > year_end\n results = []\n \n (year_start .. year_end).each do |year|\n results << year if no_repeat?(year) \n end\n \n results\nend",
"def run_exclusion(date)\n case @schedule.exclusion_met\n when 'next'\n return date + ((@schedule.exclusion_met_day - date.wday) % 7)\n when 'previous'\n return date - ((date.wday - @schedule.exclusion_met_day) % 7)\n when 'cancel'\n return run_cancel_exclusion(date)\n end\n\n return date\n end",
"def _reduce_199(val, _values, result)\n result = new_irange(val[0], val[1], val[2])\n \n result\nend",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select { |e| not_repeat_year?(e) }\nend",
"def subset range\n new = Signal.new(:data => @data[range], :sample_rate => @sample_rate)\n new.instance_variable_set(:@frequency_domain, @frequency_domain)\n return new\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select {|x| not_repeat_year?(x) }\nend",
"def day_range(rng=self)\n if rng.respond_to?(:exclude_end?) && rng.exclude_end?\n Range.new(rng.begin.to_date, rng.end.to_date, true)\n else\n Range.new(rng.begin.to_date, rng.end.to_date + 1, true)\n end\n end",
"def override_all_day_based_on_duration\n starts_on = starts_at.to_date\n ends_on = ends_at.to_date\n if starts_on != ends_on\n self.all_day = true\n end\n true\n end",
"def soon range=4.days\n schedules.where(:when.lte => range.from_now)\n end",
"def right_date_scope(arr)\n return false unless arr[0].to_i.between?(2000, 2100)\n return false unless arr[1].to_i.between?(1, 12)\n return false unless arr[2].to_i.between?(1, 31)\n true\n end",
"def _reduce_518(val, _values, result)\n result = @builder.range_inclusive(val[0], val[1], val[2])\n \n result\nend",
"def retrieve_date_range_11\n @free_period = false\n @from, @to = nil, nil\n\n if params[:period_type] == '1' || (params[:period_type].nil? && !params[:period].nil?)\n case params[:period].to_s\n when 'today'\n @from = @to = Date.today\n when 'yesterday'\n @from = @to = Date.today - 1\n when 'current_week'\n @from = Date.today - (Date.today.cwday - 1)%7\n @to = @from + 6\n when 'last_week'\n @from = Date.today - 7 - (Date.today.cwday - 1)%7\n @to = @from + 6\n when '7_days'\n @from = Date.today - 7\n @to = Date.today\n when 'current_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1)\n @to = (@from >> 1) - 1\n when 'last_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n @to = (@from >> 1) - 1\n when '30_days'\n @from = Date.today - 30\n @to = Date.today\n when 'current_year'\n @from = Date.civil(Date.today.year, 1, 1)\n @to = Date.civil(Date.today.year, 12, 31)\n end\n elsif params[:period_type] == '2' || (params[:period_type].nil? && (!params[:from].nil? || !params[:to].nil?))\n begin; @from = params[:from].to_s.to_date unless params[:from].blank?; rescue; end\n begin; @to = params[:to].to_s.to_date unless params[:to].blank?; rescue; end\n @free_period = true\n else\n # default\n end\n \n @from, @to = @to, @from if @from && @to && @from > @to\n @from ||= (TimeEntry.earilest_date_for_project(@project) || Date.today)\n @to ||= (TimeEntry.latest_date_for_project(@project) || Date.today)\n end",
"def date_range(items, from, to)\n\n date_range_items = items.reject{ |item| item[\"date\"] < from }\n date_range_items.reject!{ |item| item[\"date\"] > to }\n\n return date_range_items\nend",
"def bra_all_ranges_per_date(date)\n bra_all_ranges = []\n ranges(date).each do |range|\n bra_all_ranges << bra_per_range(bra_key(range,date))\n end\n bra_all_ranges\nend",
"def no_repeat_years(first_yr, last_yr)\n years = (first_yr..last_yr).to_a\n years.select {|year| not_repeat_year?(year)}\n\nend",
"def __evolve_date__\n { \"$gte\" => min.__evolve_date__, \"$lte\" => max.__evolve_date__ }\n end",
"def restrict_date_range( objects )\n # set start_date to either passed param, or beginning of time\n start_date = params[:start_date].blank? ? Date.new(0) : Date.strptime(params[:start_date], \"%Y-%m-%d\")\n # set end_date to either passed param or now\n end_date = params[:end_date].blank? ? Date.today : Date.strptime(params[:end_date], \"%Y-%m-%d\")\n\n filtered = []\n objects.each do |obj|\n # apperantly things can have nil created_at\n if obj.created_at.blank?\n if params[:start_date].blank? && params[:end_date].blank?\n filtered += [obj]\n end\n elsif start_date <= obj.created_at.to_date && end_date >= obj.created_at.to_date\n filtered += [obj]\n end\n end\n return filtered\n end",
"def restrict_date_range( objects )\n # set start_date to either passed param, or beginning of time\n start_date = params[:start_date].blank? ? Date.new(0) : Date.strptime(params[:start_date], \"%Y-%m-%d\")\n # set end_date to either passed param or now\n end_date = params[:end_date].blank? ? Date.today : Date.strptime(params[:end_date], \"%Y-%m-%d\")\n\n filtered = []\n objects.each do |obj|\n # apperantly things can have nil created_at\n if obj.created_at.blank?\n if params[:start_date].blank? && params[:end_date].blank?\n filtered += [obj]\n end\n elsif start_date <= obj.created_at.to_date && end_date >= obj.created_at.to_date\n filtered += [obj]\n end\n end\n return filtered\n end",
"def restrict_date_range( objects )\n # set start_date to either passed param, or beginning of time\n start_date = params[:start_date].blank? ? Date.new(0) : Date.strptime(params[:start_date], \"%Y-%m-%d\")\n # set end_date to either passed param or now\n end_date = params[:end_date].blank? ? Date.today : Date.strptime(params[:end_date], \"%Y-%m-%d\")\n\n filtered = []\n objects.each do |obj|\n # apperantly things can have nil created_at\n if obj.created_at.blank?\n if params[:start_date].blank? && params[:end_date].blank?\n filtered += [obj]\n end\n elsif start_date <= obj.created_at.to_date && end_date >= obj.created_at.to_date\n filtered += [obj]\n end\n end\n return filtered\n end",
"def minimize_date_range(start_date, end_date, pennkey = nil)\n # Find default range\n default_range = date_range(pennkey)\n # Handle nil start and end date values\n start_date = start_date.nil? ? default_range.first : Date.parse(start_date)\n end_date = end_date.nil? ? default_range.last : Date.parse(end_date)\n # Build the output\n [\n [start_date, default_range.first].max,\n [end_date, default_range.last].min\n ]\n end",
"def retrieve_date_range_14\n @free_period = false\n @from, @to = nil, nil\n\n if params[:period_type] == '1' || (params[:period_type].nil? && !params[:period].nil?)\n case params[:period].to_s\n when 'today'\n @from = @to = Date.today\n when 'yesterday'\n @from = @to = Date.today - 1\n when 'current_week'\n @from = Date.today - (Date.today.cwday - 1)%7\n @to = @from + 6\n when 'last_week'\n @from = Date.today - 7 - (Date.today.cwday - 1)%7\n @to = @from + 6\n when '7_days'\n @from = Date.today - 7\n @to = Date.today\n when 'current_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1)\n @to = (@from >> 1) - 1\n when 'last_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n @to = (@from >> 1) - 1\n when '30_days'\n @from = Date.today - 30\n @to = Date.today\n when 'current_year'\n @from = Date.civil(Date.today.year, 1, 1)\n @to = Date.civil(Date.today.year, 12, 31)\n end\n elsif params[:period_type] == '2' || (params[:period_type].nil? && (!params[:from].nil? || !params[:to].nil?))\n begin; @from = params[:from].to_s.to_date unless params[:from].blank?; rescue; end\n begin; @to = params[:to].to_s.to_date unless params[:to].blank?; rescue; end\n @free_period = true\n else\n # default\n end\n\n @from, @to = @to, @from if @from && @to && @from > @to\n end",
"def calcs_for_date_range(start_date, end_date, abandon_rate)\n puts \"\\tFrom #{start_date} to #{end_date} inclusive:\"\n\n total_registrations = WasteExemptionsEngine::Registration.where(\n created_at: start_date.beginning_of_day..end_date.end_of_day\n ).count\n total_registrations_s = number_with_delimiter(total_registrations)\n puts \"\\tTotal registrations: #{total_registrations}, of which:\"\n\n assisted_digital_registrations = WasteExemptionsEngine::Registration.where(\n created_at: start_date.beginning_of_day..end_date.end_of_day,\n assistance_mode: \"full\"\n ).count\n assisted_digital_registrations_s = number_with_delimiter(assisted_digital_registrations)\n puts \"\\t... assisted digital: #{assisted_digital_registrations_s}\"\n\n fully_digital_registrations = WasteExemptionsEngine::Registration.where(\n created_at: start_date.beginning_of_day..end_date.end_of_day,\n assistance_mode: nil\n ).count\n fully_digital_registrations_s = number_with_delimiter(fully_digital_registrations)\n puts \"\\t... fully digital: #{fully_digital_registrations}\"\n\n delta = total_registrations - assisted_digital_registrations - fully_digital_registrations\n puts \"\\t(delta of #{delta} is due to some registrations not having metaData.route set)\" unless delta.zero?\n\n abandon_rate_s = number_to_percentage(100.0 * abandon_rate, precision: 0)\n non_abandon_rate_s = number_to_percentage(100.0 * (1 - abandon_rate), precision: 0)\n\n total_registrations_started = (total_registrations / (1.0 - abandon_rate)).round(0)\n total_registrations_started_s = number_with_delimiter(total_registrations_started.to_i)\n\n total_registrations_completed = fully_digital_registrations + assisted_digital_registrations + delta\n total_registrations_completed_s = number_with_delimiter(total_registrations_completed)\n\n total_registrations_started_online = (fully_digital_registrations / (1.0 - abandon_rate)).round(0)\n total_registrations_started_online_s = number_with_delimiter(total_registrations_started_online)\n\n total_registrations_abandoned = total_registrations_started - total_registrations_completed\n total_registrations_abandoned_s = number_with_delimiter(total_registrations_abandoned)\n\n puts \"\\tSo including abandoned attempts, estimated orders started = \" \\\n \"#{total_registrations_s} / (1 - #{abandon_rate_s}) = #{total_registrations_started_s}, of which: \"\n puts \"\\t... completed: #{total_registrations_completed_s}\"\n puts \"\\t... abandoned: #{total_registrations_abandoned_s}\"\n\n puts \"\\nSummary:\"\n puts \"\\t1. Total number of transactions started and completed online only: #{fully_digital_registrations_s}\"\n puts \"\\t2. Total number of transactions started online: ESTIMATED: #{total_registrations_started_online_s}\"\n puts \"\\t\\t(Estimated dropoff rate for the last 30 days: #{abandon_rate_s}\"\n puts \"\\t\\t so estimated completion (non-abandoned) rate for the last 30 days: #{non_abandon_rate_s}\"\n puts \"\\t\\t so given #{fully_digital_registrations_s} fully digital orders, \" \\\n \"estimated total orders started online = \" \\\n \"(#{fully_digital_registrations_s}/#{non_abandon_rate_s}) = #{total_registrations_started_online_s})\"\n puts \"\\t3. Number of online claims: #{fully_digital_registrations_s}\"\n puts \"\\t4. Total number of claims (online + offline + unknown): \" \\\n \"#{fully_digital_registrations_s} + #{assisted_digital_registrations_s} + \" \\\n \"#{delta} = #{total_registrations_completed_s}\"\n\n puts \"====================================================================================================\"\n end",
"def calc_date_mask(field_name)\n if params[:product][:\"#{field_name}(2i)\"] == '' and params[:product][:\"#{field_name}(3i)\"] != ''\n return\n elsif params[:product][:\"#{field_name}(2i)\"] == ''\n params[:product][:\"#{field_name}(2i)\"] = '1'\n params[:product][:\"#{field_name}(3i)\"] = '1'\n params[:product][:\"#{field_name}_mask\"] = :year\n elsif params[:product][:\"#{field_name}(3i)\"] == ''\n params[:product][:\"#{field_name}(3i)\"] = '1'\n params[:product][:\"#{field_name}_mask\"] = :year_month\n else\n params[:product][:\"#{field_name}_mask\"] = :year_month_day\n end\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).reduce([]) do |output, el|\n if not_repeat_year?(el)\n output << el\n else\n output\n end\n end\nend",
"def _reduce_193(val, _values, result)\n result = new_irange(val[0], val[1], val[2])\n \n result\nend",
"def _reduce_193(val, _values, result)\n result = new_irange(val[0], val[1], val[2])\n \n result\nend",
"def test_range\n series = Dataset::Series.new\n ary = (1950..2007).map {|n| [ n, rand(100) ]}\n series.add(*ary)\n assert_equal(58, series.data.size)\n assert_raise(RuntimeError) { series.range() }\n assert_raise(TypeError) { series.range(Dataset::Chron::YYYYMM.new(\"01/1980\")) }\n assert_raise(TypeError) { series.range(nil, Dataset::Chron::YYYYMM.new(\"01/1980\")) }\n s2 = series.range(Dataset::Chron::YYYY.new(1980))\n assert_equal(28, s2.data.size)\n assert_equal(Dataset::Chron::YYYY.new(1980), s2.chrons.min)\n assert_equal(Dataset::Chron::YYYY.new(2007), s2.chrons.max)\n end",
"def booked_date_range\n { from: :start_date, to: :end_date }\n end",
"def no_repeat_years(first_year, last_year)\nend",
"def _reduce_510(val, _values, result)\n result = @builder.range_inclusive(nil, val[0], val[1])\n \n result\nend",
"def date_calc(start,day_start,day_duration,round)\n time=start;schedule=[]\n round.size.times do |r|\n#print day_start+day_duration;print \"\\n\"\n if time >= day_start + day_duration\n#print time;print \"\\n\"\n time=day_start+1.day\n day_start = time\n end\n schedule[r] = time\n time+=HEAT_INTERVAL\n end\n\n return schedule\n end",
"def fill_alternate_missing_months(range_start_date = nil, range_end_date = nil, from: nil, to: nil)\n raise \"Cannot fill_alternate_missing_months on a series of frequency #{frequency}\" unless frequency == 'month'\n semi = find_sibling_for_freq('S')\n start_date = Date.parse(from || range_start_date) rescue first_observation\n end_date = Date.parse(to || range_end_date) rescue last_observation\n new_dp = {}\n date = start_date + 1.month\n while date < end_date do\n prevm = date - 1.month\n nextm = date + 1.month\n if data[prevm] && data[nextm]\n new_dp[date] = (data[prevm] + data[nextm]) / 2.0\n if semi && date.month % 6 == 0\n semi_date = date - 5.months\n semi_val = semi.at(semi_date)\n if semi_val\n redistribute_semi(semi_val, semi_date, new_dp)\n end\n end\n end\n date += 2.months ## track only the missing data points\n end\n new_transformation(\"Interpolation of alternate missing months from #{self}\", new_dp)\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def _reduce_528(val, _values, result)\n result = @builder.range_inclusive(val[0], val[1], val[2])\n\n result\nend",
"def workdays_in_range\n end_time ? (start_time.to_date..end_time.to_date).select { |d| (1..5).cover?(d.wday) }.size - offset : 1\n end",
"def unavailable_date_ranges_from_today\n self.reservations\n .where('end_date > ?', Date.today())\n .where(status: [1, 5])\n .map {|item| [item.start_date, item.end_date]}\n end",
"def reservations_by_date(date_query)\n res_list = []\n @reservations.each do |res|\n if res.range.include?(date_query)\n res_list << res\n end\n end \n return res_list \n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).to_a.select { |year| not_repeat_year?(year) }\nend",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select { |year| not_repeat_year?(year) }\nend",
"def date_range\n earliest = WorkPacket.find_earliest_by_tasks( @task_ids )\n latest = WorkPacket.find_latest_by_tasks( @task_ids )\n\n # If the earliest or latest work packet value is nil, both should be\n # nil (obviously) and this means there are no work packets for the\n # tasks. In that case we just span 'all of time' so that the user\n # can see explicitly there's no booked time. Generating a report over\n # some single day range just looks odd (user thinks \"why hasn't it\n # covered all dates\"). The hide-zero-columns option can be employed\n # to clear up the report.\n\n end_of_range = latest.nil? ? Date.current : latest.date.to_date\n start_of_range = earliest.nil? ? Date.new( Timesheet.allowed_range().min, 1, 1 ) : earliest.date.to_date\n\n return ( start_of_range..end_of_range )\n end",
"def regular_days_hash(regular_days, date_from, date_to)\n regular_days_hash = {}\n regular_days.each do |day|\n regular_days_hash[day.date.to_s] = day if day.date >= date_from && day.date <= date_to\n end\n regular_days_hash\n end",
"def set_boundaries\n days = calculate_start_and_end_day(@values[:year], @values[:time_frame])\n set_values(days)\n return \"Calculated interval for week from input:\" \\\n \" #{days[:actual]} - #{days[:next]}\"\n end",
"def _reduce_516(val, _values, result)\n result = @builder.range_inclusive(val[0], val[1], val[2])\n \n result\nend",
"def slice(start_x, end_x)\n if start_x.class == Fixnum\n if end_x.class == Fixnum\n dates[(start_x-1)..(end_x-1)]\n else\n dates[start_x-1..-1].select{|d| d <= end_x}\n end\n elsif start_x.class ==Date \n if end_x.class == Date\n dates.select{|d| d >= start_x and d <= end_x}\n else\n dates.select{|d| d >= start_x}[0..end_x-1]\n end\n end\n end",
"def todays_recurrences\n today = Time.zone.today\n Recurrence.where('recurrences.date = ? OR recurrences.date ISNULL', today)\n end",
"def all_day\n beginning_of_day..end_of_day\n end",
"def no_repeats(year_start, year_end)\n\tyear = year_start\n\tnon_repeat_years = []\n\twhile year <= year_end\n\t\tif no_repeat_year?(year)\n\t\t\tnon_repeat_years.push(year)\n\t\tend\n\t\tyear += 1\n\tend\n\tnon_repeat_years\nend",
"def sred_range_for_date(date=today_as_date)\n start_of_year = (Date.new(date.year, 1, 1)..Date.new(date.year, 7, 31))\n if start_of_year.include?(date)\n return \"#{(date.year - 1)}/#{date.year}\"\n else\n return \"#{date.year}/#{date.year + 1}\"\n end\n end",
"def refresh_trip_schedules!\n excluded_dates = exclusion_dates.order(:excluded_date).map(&:excluded_date)\n\n # Try to build a list of valid trip schedules between the two trip\n # boundries\n updated_trip_schedules = [] \n working_date = boundry_start\n while working_date + duration.days < boundry_end do\n potential_start = working_date.to_date\n potential_end = (working_date + duration.days).to_date\n potential_range = (potential_start..potential_end)\n\n # tick the working date\n working_date = working_date + 1.day\n\n # Check trip day of week exclusions\n # next unless potential_range.any? { |date| dow_restriction_indexes.any? { |exclusion| exclusion.include? date.wday }}\n next unless dow_restriction_indexes.any? { |required_dows| required_dows.all? { |required_dow| potential_range.any? { |date| required_dow == date.wday }}}\n\n # Check excluded dates\n next if excluded_dates.any? { |excluded_date| (potential_range).include? excluded_date.to_date }\n\n # Create a trip schedule if it doesn't already exist\n ap potential_start\n updated_trip_schedules << TripSchedule.where(\n :trip => self,\n :start_date => potential_start.in_time_zone('EST'),\n :end_date => potential_end.in_time_zone('EST')\n ).first_or_initialize\n end\n\n self.trip_schedules = updated_trip_schedules\n save!\n end",
"def shifts_cannot_overlap\n # day = weekday\n # shifts = employee.shifts.exclude_self(id).where(weekday: day)\n range = Range.new(time_start, time_end)\n # shifts = employee.shifts.exclude_self(id).on_day(weekday).valid_at(valid_from)\n # overlaps = shifts.in_range(range)\n overlaps = employee.shifts.exclude_self(id).on_day(weekday).valid_at(valid_from).in_range(range)\n overlap_error unless overlaps.empty?\n end",
"def to_range\n start_date..end_date\n end",
"def input_date_range(name, from, to)\n field = field_content(name)\n id = field_id(name)\n {\n id: id,\n name: name,\n description: prop(field, 'description'),\n label: prop(field, 'label'),\n from: input_date_month_year(value_by_key(from, 'name'), value_by_key(from, 'date')),\n to: input_date_month_year(value_by_key(to, 'name'), value_by_key(to, 'date')),\n }\n end",
"def range_for period \n (period / ( 60 * 60 * 24 ) * -1)..-1\n end",
"def set_duplicate_days_allowed\r\n @duplicate_days_allowed = @number_of_rounds - @number_of_groups\r\n @duplicate_days_allowed = 0 if @duplicate_days_allowed < 0\r\n end",
"def breakable_range; end",
"def adjust_dates(date)\n first_date = planned.minimum(:actual_date)\n if first_date && first_date < date\n gap = date - first_date\n planned.each do |repetition|\n repetition.increment!(:actual_date, gap)\n end\n end \n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).reduce([]) do |arr, year|\n if not_repeat_year?(year)\n arr << year\n else\n arr\n end\n end\nend",
"def event_range events\n [events.map(&:date).min.to_date, events.map(&:date).max.to_date]\nend",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def update_relatives_dates\n return if new_record?\n return unless force_relatives_dates\n return unless starts_at_changed? || ends_at_changed?\n return unless recurrence.present?\n return unless future_relatives.any?\n\n future_relatives.each do |outing|\n outing.assign_attributes(metadata: outing.metadata.merge({\n starts_at: outing.metadata[:starts_at] + (self.metadata[:starts_at] - starts_at_was),\n ends_at: outing.metadata[:ends_at] + (self.metadata[:ends_at] - ends_at_was)\n }))\n end\n end",
"def now_and_every(interval, recur = T.unsafe(nil), &block); end",
"def make_date_range from, to, keys = { sent: 0, received: 0 }\n\t\t\trange = Hash.new\n\t\t\treturn range if Time.at(to) < Time.at(from)\n\t\t\tfrom = Time.at(from).to_date\n\t\t\tto = Time.at(to).to_date\n\t\t\t(to - from).to_i.times { |i|\n\t\t\t\tindex = from + i.day\n\t\t\t\trange[index.to_s] = OpenStruct.new(keys.merge(date: index.to_time.to_i))\n\t\t\t}\n\t\t\trange\n\t\tend"
] |
[
"0.5772766",
"0.57313657",
"0.5722943",
"0.57097423",
"0.567828",
"0.56194764",
"0.5584516",
"0.5511722",
"0.55078065",
"0.54709476",
"0.5457419",
"0.542211",
"0.5421099",
"0.5386382",
"0.53843",
"0.53743654",
"0.53717947",
"0.53642535",
"0.53174984",
"0.5309649",
"0.52733326",
"0.52622324",
"0.52499795",
"0.5242839",
"0.52258486",
"0.5213473",
"0.520226",
"0.51986164",
"0.5157934",
"0.5157044",
"0.5136464",
"0.50945854",
"0.50791526",
"0.5077952",
"0.5075769",
"0.5075769",
"0.50720817",
"0.50710636",
"0.50704306",
"0.5065902",
"0.50650674",
"0.5058429",
"0.5056919",
"0.505264",
"0.50500184",
"0.50388914",
"0.5034163",
"0.5030486",
"0.50281805",
"0.50273675",
"0.50240445",
"0.50235397",
"0.5021785",
"0.50206333",
"0.50131667",
"0.50131667",
"0.50131667",
"0.50046843",
"0.50041324",
"0.50020015",
"0.49948528",
"0.49908212",
"0.4978679",
"0.4978679",
"0.49778494",
"0.4972752",
"0.49706355",
"0.4968579",
"0.49678987",
"0.49600706",
"0.49593064",
"0.49551517",
"0.49534467",
"0.49374914",
"0.4934305",
"0.49309018",
"0.4928708",
"0.4926293",
"0.49118334",
"0.49072543",
"0.49047044",
"0.48998827",
"0.48974344",
"0.48969254",
"0.4887028",
"0.488526",
"0.4881207",
"0.48811844",
"0.4879352",
"0.48793477",
"0.487747",
"0.48733458",
"0.4866674",
"0.4846431",
"0.4845933",
"0.4839707",
"0.4838732",
"0.48288175",
"0.48219684",
"0.4819407"
] |
0.5876295
|
0
|
Create a recurrence occurring within a timeofday range or ranges. Given time ranges will parse as timesofday and ignore given dates.
|
def during(time_of_day, *extras)
merge(during: time_of_day.array_concat(extras))
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def fetch_events_time(range_begin_in_secs, range_end_in_secs)\n #\n # collect from_time beginning of day (in seconds)\n #\n frt = self.from_time.beginning_of_day.to_i\n\n case self.recurrence_type\n when \"NO_RECURRENCE\"\n self.no_recurrence_dates(range_begin_in_secs, range_end_in_secs, frt)\n when \"EVERY_N_DAYS\"\n self.recur_every_n_days_dates(range_begin_in_secs, range_end_in_secs, frt)\n when \"EVERY_N_WEEKS\"\n self.recur_every_n_weeks_dates(range_begin_in_secs, range_end_in_secs, frt)\n when \"EVERY_N_MONTHS\"\n self.recur_every_n_months_dates(range_begin_in_secs, range_end_in_secs, frt)\n when \"EVERY_N_YEARS\"\n self.recur_every_n_years_dates(range_begin_in_secs, range_end_in_secs, frt)\n when \"EVERY_DAYS_OF_WEEK\"\n self.recur_every_days_of_week_dates(range_begin_in_secs, range_end_in_secs, frt)\n else\n []\n end\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def next_meeting(after_time = Time.now.utc )\n # puts \"Looking up next meeting after #{after_time}\"\n if recurrence_frequency.blank?\n return start_time\n end\n\n if after_time < start_time\n return start_time\n end \n\n after_time = after_time.local_from_utc(self.time_zone) \n\n\n # Advance the starting time in the case when it falls after the beginning of\n # a meeting on the same day. We do this so that we can use \"day precision\"\n # (PDate.day) in the Runt library instead of \"minute precision\" (PDate.min),\n # which performs terribly.\n start_time = start_time_local\n if(after_time.hour > start_time.hour or ( after_time.hour == start_time.hour and after_time.min > start_time.min))\n after_time = after_time + 1.day\n after_time = Time.gm(after_time.year, after_time.month, after_time.day, 0, 0)\n end\n\n case recurrence_frequency\n when 'daily'\n end_time = after_time + 25.hours \n # after_time -= 1.day\n start_date = PDate.day(after_time.year, after_time.month, after_time.day , after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'weekdays'\n # Make the range over 3 days so that Friday night searches will still turn\n # up Monday as the next day.\n end_time = after_time + 3.days\n start_date = PDate.day(after_time.year, after_time.month, after_time.day, after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'monthly'\n eom = (after_time + 40.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eom.year, eom.month, eom.day)\n when 'weekly'\n eow = (after_time + 8.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eow.year, eow.month, eow.day)\n when 'yearly'\n # Just doing \"after_time + 367.days\" results in a bit of a performance hit\n # as hundreds of days are compared. We'll try to narrow it a bit. Not too\n # much, because we don't have time to actually write unit tests and make\n # sure the narrowing code works. :) Which is why the comment is here.\n st = after_time + 250.days\n et = st + 150.days\n start_date = PDate.day(st.year, st.month, st.day)\n end_date = PDate.day(et.year, et.month, et.day)\n end \n # puts \" Range #{start_date.to_s} - #{end_date.to_s}\"\n d_range = DateRange.new(start_date, end_date)\n sched = Schedule.new\n event = Event.new((self.invitation.name rescue \"no name\"))\n sched.add(event,self.runt_expression)\n dates = sched.dates(event,d_range)\n\n next_mtg = dates.first\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, start_time_local.hour, start_time_local.min)\n result = nil\n begin\n result = next_mtg_time.local_to_utc(self.time_zone)\n rescue TZInfo::PeriodNotFound\n # This only happens when the time is during the one hour which is skipped\n # during the transition to DST. For example, only on Sun Mar 08 02:15:00\n # (see ticket #744).\n next_hour = start_time_local.hour + 1\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, next_hour, start_time_local.min)\n retry\n end\n return result\n end",
"def create_time_request\n TimeRequest.create(\n time: [ Time.new(2000, 1, 1, 14, 0, 0, \"+00:00\").utc, Time.new(2000, 1, 1, 13, 0, 0, \"+00:00\").utc, Time.new(2000, 1, 1, 12, 0, 0, \"+00:00\").utc ].sample,\n reservation: Reservation.all.sample,\n check_in: [true, false].sample,\n status: 'pending'\n )\nend",
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def find_in_range(time_from:, time_to:, time_windows: time_span_windows)\n #puts \"find_in_range, Recieve: diff: #{(time_to - time_from)}, time_from: #{time_from}, time_to: #{time_to}, time_window_left: #{time_windows.size}\"\n return [] if (time_to - time_from) < shorter_time_window_span\n\n while bucket = time_windows.shift\n next unless found_windows = find_fitting_windows(time_from, time_to, bucket)\n return found_windows +\n find_in_range(time_from: time_from, time_to: found_windows.first.fetch(:window_starts), time_windows: time_windows.clone) +\n find_in_range(time_from: found_windows.last.fetch(:window_finishes), time_to: time_to, time_windows: time_windows.clone)\n end\n end",
"def metrics_time_range(start_time, end_time)\n resource.metrics.for_time_range(start_time, end_time)\n end",
"def scope_by_time(time_boundaries)\n start_time, end_time = time_boundaries\n scope_end = num_lines - 1\n # short circuit the search if possible\n if (time_at(0) > end_time) or (time_at(-1) < start_time)\n @lines = []\n return @lines\n end\n scope_begin = find_first(start_time, 0, scope_end)\n scope_end = find_last(end_time, scope_begin, scope_end)\n @lines = @lines[scope_begin..scope_end]\n end",
"def date_calc(start,day_start,day_duration,round)\n time=start;schedule=[]\n round.size.times do |r|\n#print day_start+day_duration;print \"\\n\"\n if time >= day_start + day_duration\n#print time;print \"\\n\"\n time=day_start+1.day\n day_start = time\n end\n schedule[r] = time\n time+=HEAT_INTERVAL\n end\n\n return schedule\n end",
"def added_closest_temporal_range(temporal_range, indexes, days, count)\n index = temporal_range.index { |t| days >= t }\n if index\n range = temporal_range[index]\n indexes[range.to_s] = { 'days' => days, 'count' => count }\n end\nend",
"def make_items_with_ranges(*ranges_as_strings)\n ranges_as_strings.map { |range_as_string| stub( :date_ranges => [dr(range_as_string)] ) }\n end",
"def rationalise_dates\n default_range = date_range()\n\n begin\n if ( not @range_month_start.blank? )\n year, month = unpack_string( @range_month_start )\n range_start = Date.new( year, month )\n elsif ( not @range_week_start.blank? )\n year, week = unpack_string( @range_week_start )\n range_start = Timesheet.date_for( year, week, TimesheetRow::FIRST_DAY, true )\n else\n range_start = Date.parse( @range_start )\n end\n rescue\n range_start = default_range.min\n end\n\n begin\n if ( not @range_month_end.blank? )\n year, month = unpack_string( @range_month_end )\n range_end = Date.new( year, month ).at_end_of_month()\n elsif ( not @range_week_end.blank? )\n year, week = unpack_string( @range_week_end )\n range_end = Timesheet.date_for( year, week, TimesheetRow::LAST_DAY, true )\n else\n range_end = Date.parse( @range_end )\n end\n rescue\n range_end = default_range.max\n end\n\n if ( range_end < range_start )\n @range = range_end..range_start\n else\n @range = range_start..range_end\n end\n\n # Hard-coded range throttle to 32 days (just over a \"longest month\") for\n # daily reports to avoid excessive server load.\n\n if ( @frequency_data[ :generator ] == :daily_report )\n @range = ( @range.last - 32.days )..( @range.last ) if ( @range.last.to_time - @range.first.to_time > 32.days )\n end\n end",
"def set_datetimes( start_datetime, end_datetime )\n \n start_datetime, end_datetime = [ start_datetime, end_datetime ].sort\n \n set_dates( start_datetime.to_date, end_datetime.to_date )\n \n # Break the dates into a hash query format. \n hash = [ [ start_datetime, { fthours: '%H', ftmins: '%M' } ] , [ end_datetime, { tthours: '%H', ttmins: '%M' } ] ].inject({}) do |h, ( date, args )|\n args.each { |k,v| h[k.to_s] = date.strftime(v) } ; h\n end\n \n hash[ 'timetype' ] = 'between'\n hash[ 'befaft' ] = 'f'\n \n # Update the query with the new values\n update_query( hash )\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def create_for_period(future_period, notification_times, border_time)\n existing_times = future_period.notifications.all.map { |n| n.time }\n notification_times.each do |time|\n if !existing_times.include?(time) && border_time < time\n future_period.notifications.create!(time: time)\n end\n end\n end",
"def make_resevation(date_range)\n available_rooms = get_available_rooms(date_range)\n if available_rooms.length < 1\n raise ArgumentError\n end\n new_reservation = Hotel::Reservation.new(date_range,available_rooms[0])\n @reservations << new_reservation\n return new_reservation\n end",
"def schedule(startAt,endAt,opts={})\n ## Caching ##\n @schedules ||= {}\n if @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash]\n return @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash]\n end\n ## End Caching ##\n\n # TODO Handle events starting within the range but ending outside of it?\n\n # TODO Offload this selection to the database; okay for testing though\n # NOTE This is actually faster thanks to the query cache for small numbers of operating times, but not very scalable\n #all_regular_operating_times = OperatingTime.find(:all, :conditions => {:place_id => self.id, :override => 0}).select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)}\n #all_special_operating_times = OperatingTime.find(:all, :conditions => {:place_id => self.id, :override => 1}).select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)}\n # Select all relevant times (1 day buffer on each end)\n # NOTE Make sure to use generous date comparisons to allow for midnight rollovers\n all_regular_operating_times = OperatingTime.regular.by_place_id(self.id).in_range(startAt..endAt).find(:all)\n all_special_operating_times = OperatingTime.special.by_place_id(self.id).in_range(startAt..endAt).find(:all)\n\n puts \"\\nRegular OperatingTimes: #{all_regular_operating_times.inspect}\" if DEBUG\n puts \"\\nSpecial OperatingTimes: #{all_special_operating_times.inspect}\" if DEBUG\n\n regular_times = []\n special_times = []\n special_ranges = []\n\n all_special_operating_times.each do |ot|\n puts \"\\nSpecial Scheduling for: #{ot.inspect}\" if DEBUG\n\n # Special Case: Overriding with NO times (e.g. closed all day)\n if ot.start == 0 and ot.length == 0 and startAt.to_date <= ot.startDate\n # Block out the range, but don't add the \"null Times\"\n special_ranges << Range.new(ot.startDate,ot.endDate)\n next\n end\n\n # Start a day early if possible\n earlyStart = startAt-1.day < ot.startDate.midnight ? startAt.midnight : startAt - 1.day\n puts \"EarlyStart: #{earlyStart.inspect}\" if DEBUG\n\n # Calculate the next set up open/close times\n open,close = ot.next_times(earlyStart)\n next if open.nil? # No valid occurrences in the future\n\n while not open.nil? and open <= endAt do\n if DEBUG\n puts \"Open: #{open}\"\n puts \"Close: #{close}\"\n puts \"Start Date: #{ot.startDate} (#{ot.startDate.class})\"\n puts \"End Date: #{ot.endDate} (#{ot.endDate.class})\"\n end\n\n if close < startAt # Skip forward to the first occurrance in our time range\n puts \"Seeking: #{close} < #{startAt}\" if DEBUG\n open,close = ot.next_times(close)\n next\n end\n\n special_times << [open,close]\n special_ranges << Range.new(ot.startDate,ot.endDate)\n open,close = ot.next_times(close)\n end\n\n end\n\n puts \"\\nSpecial Times: #{special_times.inspect}\" if DEBUG\n puts \"\\nSpecial Ranges: #{special_ranges.inspect}\" if DEBUG\n\n all_regular_operating_times.each do |ot|\n puts \"\\nRegular Scheduling for: #{ot.inspect}\" if DEBUG\n\n # Start a day early if possible\n earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day\n puts \"EarlyStart: #{earlyStart.inspect}\" if DEBUG\n\n # Calculate the next set up open/close times\n open,close = ot.next_times(earlyStart)\n if DEBUG\n puts \"\"\n puts \"Open: #{open}\"\n puts \"Close: #{close}\"\n end\n\n if open.nil? # No valid occurrences in the future\n puts \"Skipping: No valid occurrences in the future.\" if DEBUG\n next\n end\n\n while not open.nil? and open <= endAt do\n if DEBUG\n puts \"\"\n puts \"Open: #{open}\"\n puts \"Close: #{close}\"\n end\n\n if close < startAt # Skip forward to the first occurrance in our time range\n puts \"Seeking: #{close} < #{startAt}\" if DEBUG\n open,close = ot.next_times(close)\n next\n end\n\n overridden = false\n special_ranges.each do |sr|\n overridden ||= sr.member?(open.to_date)\n end\n if overridden\n puts \"Overridden\" if DEBUG\n open,close = ot.next_times(close)\n next\n end\n\n # FIXME Causing an infinite loop; would be nice if this worked\n #open = startAt if open < startAt\n #close = endAt if close > endAt\n\n regular_times << [open,close]\n open,close = ot.next_times(close)\n end\n\n end\n\n puts \"\\nRegular Times: #{regular_times.inspect}\" if DEBUG\n\n # TODO Handle schedule overrides\n # TODO Handle combinations (i.e. part special, part regular)\n\n final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]}\n\n ## Truncate times larger than range ##\n if opts[:truncate]\n final_schedule.each_index do |i|\n final_schedule[i][0] = startAt.dup if final_schedule[i][0] < startAt\n final_schedule[i][1] = endAt.dup if final_schedule[i][1] > endAt\n end\n end\n ## End truncating ##\n\n ## Caching ##\n @schedules ||= {}\n @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash] = final_schedule\n ## End caching ##\n\n final_schedule\n end",
"def make_date_range from, to, keys = { sent: 0, received: 0 }\n\t\t\trange = Hash.new\n\t\t\treturn range if Time.at(to) < Time.at(from)\n\t\t\tfrom = Time.at(from).to_date\n\t\t\tto = Time.at(to).to_date\n\t\t\t(to - from).to_i.times { |i|\n\t\t\t\tindex = from + i.day\n\t\t\t\trange[index.to_s] = OpenStruct.new(keys.merge(date: index.to_time.to_i))\n\t\t\t}\n\t\t\trange\n\t\tend",
"def set_time_range\n begin_date = Date.strptime(params[:begin_date], '%Y-%m-%d') rescue User.minimum(:created_at) rescue Date.new(2015)\n end_date = Date.strptime(params[:end_date], '%Y-%m-%d') rescue Time.zone.today\n @stats_time_range = (begin_date.beginning_of_day)..(end_date.end_of_day)\n end",
"def times_for_schedule_update_requests(start_time, end_time)\n times = []\n\n task_time = start_time.beginning_of_day + 15.hours\n task_time += 1.day if task_time < start_time\n\n while task_time < end_time\n times << task_time\n task_time += 1.day\n end\n\n times\n end",
"def by_star(start_time, end_time, options = {}, &block)\n start_time = parse(start_time) \n end_time = parse(end_time)\n\n\n raise ParseError, \"End time is before start time, searching like this will return no results.\" if end_time < start_time\n field = options.delete(:field)\n ensure_valid_options(options)\n\n scoping = { :conditions => conditions_for_range(start_time, end_time, field) }.merge(options)\n result = scoped(scoping)\n result = result.scoped(block.call) if block_given?\n result\n end",
"def selectTimeIntervals(dbQuery)\n\n if dbQuery.nil?\n return\n end\n\n dbQuery = setTimePeriod(dbQuery)\n\n reportTime = params['reportTime'] || \"today\"\n\n fromDate = params['fromDate'] || Date.today.to_s\n begin\n toDate = params['toDate'] || (Date.parse(fromDate, \"YYYY-MM-DD\") + 1.day).to_s\n rescue\n toDate = Date.today.to_s # Just in case someone has meddled with the query string param and sent an invalid FROM date...\n end\n\n case reportTime.downcase\n when \"past_hour\"\n @timeSlot = \"minute\"\n @numTimeSlots = 5\n fromDate = 1.hour.ago\n toDate = Time.now\n dbQuery = dbQuery.select(\"MOD(cast(date_part('minute', timestamp) as INT), #{@numTimeSlots}) as time\")\n when \"past_day\"\n @timeSlot = \"hour\"\n @numTimeSlots = 24\n fromDate = 24.hours.ago\n toDate = Time.now\n dbQuery = dbQuery.select(\"date_part('hour', timestamp) as time\")\n when \"past_week\"\n fromDate = 7.days.ago\n toDate = Time.now\n @timeSlot = \"day\"\n @numTimeSlots = 7\n dbQuery = dbQuery.select(\"EXTRACT(day from timestamp - (current_timestamp - '7 day'::interval)) as time\")\n when \"past_month\"\n fromDate = 1.month.ago\n toDate = Time.now\n @timeSlot = \"week\"\n @numTimeSlots = ((toDate - fromDate)/1.week).ceil + 1\n startingNum = ActiveRecord::Base.connection.select_value(ActiveRecord::Base.send(:sanitize_sql_array, \n [\"select date_part('week', current_timestamp - '1 month'::interval)\"]))\n\n dbQuery = dbQuery.select(\"date_part('week', timestamp) - #{startingNum} as time\")\n when \"date_range\"\n begin\n fromDate = Date.parse(params['fromDate'], 'YYYY-MM-DD').to_time\n rescue\n fromDate = Date.today #if the incoming parameter is an invalid date format, then pick TODAY as the date!\n params['fromDate'] = fromDate.to_s\n end\n begin\n toDate = Date.parse(params['toDate'], 'YYYY-MM-DD').to_time + 1.day # end date should be inclusive in the range\n rescue\n # in case of parsing error, take FROMDATE + 1 as the end date...\n params['toDate'] = (Date.parse(params['fromDate'], 'YYYY-MM-DD') + 1.day).to_s\n toDate = (Date.parse(params['fromDate'], 'YYYY-MM-DD') + 1.day).to_time\n end\n\n numDays = ((toDate - fromDate)/1.day).round\n dbQuery = dbQuery.where(\"timestamp between '#{fromDate.strftime('%F')}' and '#{toDate.strftime('%F')}'\")\n if numDays > 70 then\n @timeSlot = \"month\"\n @numTimeSlots = ((toDate - fromDate)/1.month).ceil + 1\n startingNum = ActiveRecord::Base.connection.select_value(ActiveRecord::Base.send(:sanitize_sql_array, \n [\"select date_part('month', date '#{fromDate}')\"]))\n\n dbQuery = dbQuery.select(\"date_part('month', timestamp) - #{startingNum} as time\")\n elsif numDays > 31 then\n @timeSlot = \"week\"\n @numTimeSlots = ((toDate - fromDate)/1.week).ceil + 1\n startingNum = ActiveRecord::Base.connection.select_value(ActiveRecord::Base.send(:sanitize_sql_array, \n [\"select date_part('week', date '#{fromDate}')\"]))\n\n dbQuery = dbQuery.select(\"date_part('week', timestamp) - #{startingNum} as time\")\n else\n @timeSlot = \"day\"\n @numTimeSlots = numDays\n dbQuery = dbQuery.select(\"EXTRACT(day from timestamp - date '#{fromDate}') as time\")\n end\n else #default is TODAY\n fromDate = Time.mktime(Time.now.year, Time.now.month, Time.now.day)\n toDate = fromDate + 24.hours\n @timeSlot = \"hour\"\n @numTimeSlots = 24\n\n dbQuery = dbQuery.select(\"date_part('hour', timestamp) as time\")\n end\n\n dbQuery = dbQuery.group(:time).order(:time)\n\n return dbQuery\n\n end",
"def events(range_begin = nil, range_end = nil, time_filters_in_secs = [])\n #\n # If range_begin is nil, use from_time attribute from the model.\n #\n range_begin = range_begin || self.from_time\n range_begin = Event.convert_to_datetime(range_begin).beginning_of_day.to_i\n\n #\n # If range_end is nil, use recurrence_end attribute from the model.\n # note: range_end may still be nil if no recurrence_end is specified\n # note: range_end is exclusive. substract with DAY_IN_SECONDS to\n # become inclusive (see arshaw fullcalendar docs)\n #\n range_end = Event.convert_to_datetime(range_end).end_of_day.to_i - DAY_IN_SECONDS if range_end\n range_end = [range_end, self.recurrence_end.try(:end_of_day).try(:to_i)].compact.min\n\n arr = []\n self.fetch_events_time(range_begin, range_end).each do |e|\n event_from_time_in_secs = e +\n (self.from_time.hour * HOUR_IN_SECONDS) +\n (self.from_time.min * MINUTE_IN_SECONDS)\n event_thru_time_in_secs = event_from_time_in_secs + self.duration\n\n unless time_filters_in_secs.include? event_from_time_in_secs\n arr << Event.new(self, event_from_time_in_secs, event_thru_time_in_secs)\n end\n end\n\n arr\n end",
"def for_date_range(beginning:, ending:)\n new_with_date_range(beginning, ending)\n end",
"def set_time days\r\n days.each do |day,times|\r\n periods = times.split(\",\")\r\n periods.each do |period|\r\n start_time,end_time = period.split(\"-\")\r\n raise unless Time.parse(start_time) < Time.parse(end_time) \r\n #this will throw an exception if the day is invalid\r\n KlassSchedule.create :klass_id=>self.id,:start_time=>start_time,\r\n :end_time=>end_time,:day_of_week=>day\r\n end\r\n end \r\n end",
"def to_range_within(range)\n nb_weeks_offset = self.weekly_recurring ? ((range.end - self.starts_at.to_datetime) / 7).to_i : 0\n r = Range.new(self.starts_at + nb_weeks_offset.week, self.ends_at + nb_weeks_offset.week)\n range.cover?(r.begin)&&range.cover?(r.end) ? r : nil\n end",
"def parse_rrule recurrence\n rule = recurrence.find do |rec|\n /\\ARRULE/.match(rec)\n end\n\n return nil unless rule\n rule = rule.split(':')[1]\n params = {\n validations: {}\n }\n\n rule.split(';').each do |rule|\n (name, value) = rule.split('=')\n value.strip!\n case name\n when 'FREQ'\n params[:freq] = value.downcase\n when 'INTERVAL'\n params[:interval] = value.to_i\n when 'COUNT'\n params[:count] = value.to_i\n when 'UNTIL'\n params[:until] = Time.parse(value).utc\n when 'WKST'\n params[:wkst] = day_to_symbol(value)\n when 'BYSECOND'\n params[:validations][:second_of_minute] = value.split(',').collect(&:to_i)\n when 'BYMINUTE'\n params[:validations][:minute_of_hour] = value.split(',').collect(&:to_i)\n when 'BYHOUR'\n params[:validations][:hour_of_day] = value.split(',').collect(&:to_i)\n when 'BYDAY'\n dows = {}\n days = []\n value.split(',').each do |expr|\n day = day_to_symbol(expr.strip[-2..-1])\n # day with occurence\n if expr.strip.length > 2\n occ = expr[0..-3].to_i\n dows[day].nil? ? dows[day] = [occ] : dows[day].push(occ)\n days.delete(to_wday(day))\n else\n days.push to_wday(day) if dows[day].nil?\n end\n end\n params[:validations][:day_of_week] = dows unless dows.empty?\n unless days.empty?\n # days = days.sort_by do |day|\n # day\n # end\n params[:validations][:day] = days\n end\n when 'BYMONTHDAY'\n params[:validations][:day_of_month] = value.split(',').collect(&:to_i)\n when 'BYMONTH'\n params[:validations][:month_of_year] = value.split(',').collect(&:to_i)\n when 'BYYEARDAY'\n params[:validations][:day_of_year] = value.split(',').collect(&:to_i)\n when 'BYSETPOS'\n else\n raise \"Invalid or unsupported rrule command: #{name}\"\n end\n end\n\n params[:interval] ||= 1\n params.delete(:wkst) unless params[:freq] == 'weekly'\n params\n end",
"def domain_for_event_occurrence(from, to)\n domain = TimeDomains::BoundlessTimeDomain.new\n domain.reference_start = DateTime.now.utc.midnight\n domain.duration = TimeDomains::Duration.new\n domain.duration.duration = 1440\n domain.duration.unit = TimeDomains::Duration::MINUTE\n domain.period = TimeDomains::Duration.new\n domain.period.duration = 1\n domain.period.unit = TimeDomains::Duration::DAY\n\n return domain\n end",
"def time_range\n return 0 if start_hour.blank? || start_minute.blank?\n\n return 0 if end_hour.blank? || end_minute.blank?\n\n hours_between_times\n end",
"def date_range_for(period_name, time = nil)\n if period = date_periods[period_name.to_sym]\n period.call(parse_filtered_time(time))\n else\n raise \"Invalid period: #{period_name.inspect}\"\n end\n end",
"def create_time_periods(time_period_length = MSecPerHour)\n days = []\n time_periods = nil\n prev_start = @raw_data[0][0] + 1 # cross over into first day\n \n for data in @raw_data\n # Has data crossed over to next day?\n if prev_start > data[0] # Time increases throughout the day...\n days << time_periods if time_periods != nil\n \n cur_time_period = 0\n time_periods = [[]]\n \n puts \"New day: data=#{data[0]}\" if Verbose\n \n # Has data crossed over to next time period?\n elsif data[0] > ((cur_time_period + 1) * time_period_length)\n # Handle cases where the count is 0 for a time period\n while data[0] > ((cur_time_period + 1) * time_period_length)\n cur_time_period += 1\n time_periods[cur_time_period] = []\n end\n \n puts \"New time period: data=#{data[0]}\" if Verbose\n end\n \n time_periods[cur_time_period] << data\n prev_start = data[0]\n end\n \n # Add last time period\n days << time_periods\n days\n end",
"def now_and_every(interval, recur = T.unsafe(nil), &block); end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def initialize(time_window)\n @timeframes = [] \n \n for group in time_window.split(\";\")\n days, times = Array.new(7, false), []\n\n for item in group.split(\" \")\n # Range of values?\n if item.include?(\"-\")\n # Yes, Figure out if range is days or times\n range = item.split(\"-\")\n \n if Days.include?(range[0]) \n set_day_range(days, range[0], range[1])\n else\n times << TimeRange.new(range[0], range[1])\n end\n else\n days[Days.index(item)] = true if Days.include?(item)\n end\n end\n \n @timeframes << TimeFrame.new(days, times)\n end\n end",
"def schedule_raids(array)\n array.each do |key, value1|\n value1['raids'].each do |value2|\n unless Time.parse(value2['0']).past?\n new_cron(\n value2['0'], key, value2['key'],\n \"**#{value2['name']} Raid** is starting now!\"\n )\n end\n unless Time.parse(value2['15']).past?\n new_cron(\n value2['15'], key, value2['key'],\n \"**#{value2['name']} Raid** is starting in 15 minutes!\"\n )\n end\n unless Time.parse(value2['30']).past?\n new_cron(\n value2['30'], key, value2['key'],\n \"**#{value2['name']} Raid** is starting in 30 minutes!\"\n )\n end\n unless Time.parse(value2['45']).past?\n new_cron(\n value2['45'], key, value2['key'],\n \"**#{value2['name']} Raid** is starting in 45 minutes!\"\n )\n end\n next if Time.parse(value2['60']).past?\n new_cron(\n value2['60'], key, value2['key'],\n \"**#{value2['name']} Raid** is starting in 1 hour!\"\n )\n end\n end\nend",
"def retrieve_date_range_11\n @free_period = false\n @from, @to = nil, nil\n\n if params[:period_type] == '1' || (params[:period_type].nil? && !params[:period].nil?)\n case params[:period].to_s\n when 'today'\n @from = @to = Date.today\n when 'yesterday'\n @from = @to = Date.today - 1\n when 'current_week'\n @from = Date.today - (Date.today.cwday - 1)%7\n @to = @from + 6\n when 'last_week'\n @from = Date.today - 7 - (Date.today.cwday - 1)%7\n @to = @from + 6\n when '7_days'\n @from = Date.today - 7\n @to = Date.today\n when 'current_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1)\n @to = (@from >> 1) - 1\n when 'last_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n @to = (@from >> 1) - 1\n when '30_days'\n @from = Date.today - 30\n @to = Date.today\n when 'current_year'\n @from = Date.civil(Date.today.year, 1, 1)\n @to = Date.civil(Date.today.year, 12, 31)\n end\n elsif params[:period_type] == '2' || (params[:period_type].nil? && (!params[:from].nil? || !params[:to].nil?))\n begin; @from = params[:from].to_s.to_date unless params[:from].blank?; rescue; end\n begin; @to = params[:to].to_s.to_date unless params[:to].blank?; rescue; end\n @free_period = true\n else\n # default\n end\n \n @from, @to = @to, @from if @from && @to && @from > @to\n @from ||= (TimeEntry.earilest_date_for_project(@project) || Date.today)\n @to ||= (TimeEntry.latest_date_for_project(@project) || Date.today)\n end",
"def workpattern(days,from_time,to_time,type)\n DAYNAMES[days].each {|day| @values[day].workpattern(from_time,to_time,type)} \n refresh\n end",
"def create_inbetween_occurrences?\n return unless recurrence.present?\n\n recurrency&.to_i == 7 && recurrence.recurrency&.to_i == 14\n end",
"def get_drs_from_range(start_date, end_date)\n self.delta_requests.select do |dr|\n begin\n dr.start_time > start_date and dr.start_time < end_date\n rescue\n false\n end\n end\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def from_ranges\n self[:date_time_slot] = RangeSupport.range_to_string(self[:date_time_slot])\n end",
"def add_recurrence(type: :week, on: on = nil, at: at = nil)\n type = type.to_sym\n unless [:week, :day].include? type\n raise \"Type must be either :week or :day\"\n end\n if type == :week and (on.nil? or (on.is_a?(Array) and on.empty?))\n raise \"Weekdays must be specified when selecting the :week type\"\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if self.schedule.nil?\n schedule = Montrose::Schedule.new\n end\n if at.nil?\n raise \"Time must be specified in parameter 'at'\"\n else\n schedule.add Montrose.every(type, on: on, at: at).starts(created_at)\n self.write_attribute(self.class.schedulable_attribute, schedule)\n end\n end",
"def reset_local_range(start_date, end_date)\n if start_date.is_a?(Date) && end_date.is_a?(Date)\n @local_range = start_date.to_time.change(:hour => 6, :min => 30)..end_date.to_time.change(:hour => 6, :min => 30)\n elsif local_range.begin.acts_like_time? && local_range.end.acts_like_time?\n @local_range = start_date...end_date\n else\n raise ArgumentError, \"args must either be dates or times\"\n end\n if local_range.begin < begin_time or local_range.end > end_time\n logger.info \"reloading Timeseries #{symbol} #{local_range.begin.to_formatted_s(:ymd)} < #{begin_time.to_formatted_s(:ymd)} *OR* \"+\n \"#{local_range.end.to_formatted_s(:ymd)} > #{end_time.to_formatted_s(:ymd)}\"\n populate()\n puts \"repopulating timeseries on reset_local_range #{start_date}..#{end_date}\"\n else\n map_local_range()\n end\n end",
"def refresh_trip_schedules!\n excluded_dates = exclusion_dates.order(:excluded_date).map(&:excluded_date)\n\n # Try to build a list of valid trip schedules between the two trip\n # boundries\n updated_trip_schedules = [] \n working_date = boundry_start\n while working_date + duration.days < boundry_end do\n potential_start = working_date.to_date\n potential_end = (working_date + duration.days).to_date\n potential_range = (potential_start..potential_end)\n\n # tick the working date\n working_date = working_date + 1.day\n\n # Check trip day of week exclusions\n # next unless potential_range.any? { |date| dow_restriction_indexes.any? { |exclusion| exclusion.include? date.wday }}\n next unless dow_restriction_indexes.any? { |required_dows| required_dows.all? { |required_dow| potential_range.any? { |date| required_dow == date.wday }}}\n\n # Check excluded dates\n next if excluded_dates.any? { |excluded_date| (potential_range).include? excluded_date.to_date }\n\n # Create a trip schedule if it doesn't already exist\n ap potential_start\n updated_trip_schedules << TripSchedule.where(\n :trip => self,\n :start_date => potential_start.in_time_zone('EST'),\n :end_date => potential_end.in_time_zone('EST')\n ).first_or_initialize\n end\n\n self.trip_schedules = updated_trip_schedules\n save!\n end",
"def intervals\n parts = {}\n [:minute, :hour, :day, :month, :day_of_week].each do |granularity|\n if times = times_for(granularity)\n parts[granularity] = times\n end\n end\n\n merged_product parts\n # interval_list.concat times.map {|t| {granularity => t} }\n # m = expression[:minute]\n # m.split(\",\").each do |part|\n # time, divisor = part.split(\"/\")\n # start_time, end_time = time.split \"-\"\n\n # interval_list << {:minute => start_time.to_i}\n # end\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def between_dates(start_date, end_date)\n start_date = coerce_date(start_date)\n end_date = coerce_date(end_date)\n time_sheet = TimeSheet.new\n each do |record|\n time_sheet << record if record[:date] >= start_date and\n record[:date] <= end_date\n end\n time_sheet\n end",
"def in_range(*args)\n opts = args.last.kind_of?(Hash) ? args.pop : {}\n limit = opts[:limit]\n count = 1\n t_start, t_end = args.first.kind_of?(Range) ? [args.first.first, args.first.last] : [args.first,args.last]\n\n raise ArgumentError, \"must be a range or two date/time objects\" unless t_start and t_end\n\n self.start = t_start\n\n @in_range ||= begin\n result = []\n loop do\n next!\n break if count > limit if limit\n break if to_date > t_end\n result << to_date\n count += 1\n end\n\n result\n end\n end",
"def range(raw, while_supplies_last, by_appt_only)\n s = raw&.downcase&.squish\n return nil if s.blank? && !by_appt_only\n\n s = s.gsub(/weekdays/i, 'Monday - Friday')\n s = s.gsub(/weekends/i, 'Saturday - Sunday')\n\n if ['call', 'call to confirm', 'call to confirm for hours',\n 'call to confirm hours', 'check with facility'].include?(s)\n HS_CALL\n elsif ['check website'].include?(s)\n HS_CHECK_WEBSITE\n elsif ['24/7', '24 hours', 'open 24 hours', 'open 24hrs',\n 'open 24 hrs']\n .include?(s)\n HS_24_7\n elsif ['not available', 'not specified at this time.',\n 'not yet available', 'currently not accepting appointments.',\n 'currently closed.', 'currently closed',\n 'temporarily closed'].include?(s)\n HS_NOT_YET_AVAILABLE\n elsif by_appt_only && s.blank?\n every_day_specifier('by appointment only')\n elsif s =~ re(TIME_RANGE)\n every_day_specifier(normalize_time_span($LAST_MATCH_INFO))\n elsif s =~ re(EVERY_DAY_RANGE)\n same_time_some_days($LAST_MATCH_INFO, DAYS_OF_THE_WEEK, by_appt_only)\n elsif s =~ re(WEEKDAYS_RANGE)\n same_time_some_days($LAST_MATCH_INFO,\n DAYS_OF_THE_WEEK - %w[Saturday Sunday],\n by_appt_only)\n elsif s =~ re(TIME_DAY_RANGE) || s =~ re(DAY_TIME_RANGE)\n day_time_specifier($LAST_MATCH_INFO, by_appt_only)\n elsif s =~ re(CERTAIN_DAYS_24_HRS) ||\n s =~ re(TWENTY_FOUR_HRS_CERTAIN_DAYS)\n days = normalize_day_list($LAST_MATCH_INFO)\n create_spec(days, '24 hours')\n elsif s =~ re(CERTAIN_DAYS_TIME_DAY) || s =~ re(CERTAIN_DAYS_DAY_TIME)\n same_time_some_days($LAST_MATCH_INFO,\n normalize_day_list($LAST_MATCH_INFO),\n by_appt_only)\n elsif s =~ re(START_TIME_DAYS) || s =~ re(DAYS_START_TIME)\n start_time_only($LAST_MATCH_INFO, while_supplies_last, by_appt_only)\n elsif s =~ re(EVERY_DAY_START_TIME)\n start_time_only_days($LAST_MATCH_INFO, DAYS_OF_THE_WEEK,\n while_supplies_last, by_appt_only)\n elsif s =~ re(TWO_TIME_DAY_RANGE) || s =~ re(DAY_TWO_TIME_RANGE)\n day_two_time_specifier($LAST_MATCH_INFO)\n elsif s =~ re(DAY_RANGE)\n day_range_specifier($LAST_MATCH_INFO, while_supplies_last, by_appt_only)\n end\n end",
"def append_time_expense_date_cond(search,r_name,conditions_hash)\r\n \r\n search += \"AND time_entry_date Between :start_date AND :end_date \"\r\n \r\n time = nil\r\n case params[:report][:duration]\r\n when \"1\" #1 week\r\n time = 7.days.ago\r\n when \"2\" #2 weeks\r\n time = 14.days.ago\r\n when \"3\" #1month\r\n time = Time.zone.now.last_month\r\n when \"4\" #3months\r\n 3.times do |i|\r\n unless time\r\n time = Time.zone.now.last_month\r\n else\r\n time = time.last_month\r\n end\r\n end\r\n when \"range\" #Date Range\r\n r_name += \" entered between #{params[:date_start]} - #{params[:date_end]}\"\r\n conditions_hash[:start_date] = params[:date_start].to_time\r\n conditions_hash[:end_date] = params[:date_end].to_time + (23.9*60*60)\r\n end\r\n if params[:report][:duration] != \"range\"\r\n conditions_hash[:start_date] = time\r\n conditions_hash[:end_date] = Time.zone.now\r\n end\r\n [search,r_name]\r\n end",
"def next_times(at = Time.now)\n at = at.midnight unless at.respond_to? :offset\n return nil if length == 0\n return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate\n at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate\n\n # Next occurrence is later today\n # This is the only time the \"time\" actually matters;\n # after today, all we care about is the date\n if days_of_week_array[at.wday] and\n start >= at.offset\n open = at.midnight + start\n close = open + length\n return [open,close]\n end\n\n # We don't care about the time offset anymore, jump to the next midnight\n at = at.midnight + 1.day\n # NOTE This also has the added benefit of preventing an infinite loop\n # from occurring if +at+ gets shifted by 0.days further down.\n\n # Shift days_of_weekArray so that +at+ is first element\n dow = days_of_week_array[at.wday..-1] + days_of_week_array[0..(at.wday-1)]\n # NOTE The above call does something a little quirky:\n # In the event that at.wday = 0, it concatenates the array with itself.\n # Since we are only interested in the first true value, this does not\n # cause a problem, but could probably be cleaned up if done so carefully.\n\n # Next day of the week this schedule is valid for (relative to current day)\n shift = dow.index(true)\n if shift\n # Skip forward\n at = at + shift.days\n else\n # Give up, there are no more occurrences\n # TODO Test edge case: valid for 1 day/week\n return nil\n end\n\n # Recurse to rerun the validation routines\n return next_times(at)\n end",
"def timeRecordsForDate(brick, date)\n end",
"def time_slots\n\n # you can book by the hour, and you can stay for an hour\n reservation_interval = 1.hour\n\n # Determine the earliest time we will allow reservation\n # It can't be in the past, we'll start 10 minutes from now\n start_time = Time.zone.now + 10.minutes\n # Then we have to round to the next hour block\n start_time = Time.zone.at( (start_time.to_f / reservation_interval).ceil * reservation_interval )\n # Then, if we are still earlier than opening hour, just use the opening hour\n # We can use the 'max' Array method\n start_time = [start_time, start_time.change(hour: opening_hour)].max\n\n # Determine the furthest in the future we will allow reservations\n end_time = (start_time + 3.days).change(hour: closing_hour)\n\n # Now, we want to make a list of every hour between our start_time and our end_time\n # For this we can use a begin... end while condition loop.\n # We'll start with an empty array that will hold all the hours,\n # and a variable to hold each hour, which we will keep increasing by 1 hour, and then add to our array\n # Our loop condition will have us stop looping once we've reached the end time\n\n all_times = []\n a_time = start_time\n\n begin\n\n # add this time to our list of times\n all_times << a_time\n\n # increment the time\n a_time += reservation_interval\n\n # Once we get to closing time, we have to skip ahead to the next day's opening\n # That way you can't make a reservation at 2am\n if (a_time + reservation_interval) > a_time.change(hour: closing_hour)\n a_time = (a_time + 1.day).change(hour:opening_hour)\n end\n\n end while a_time < end_time\n\n all_times\n end",
"def create_time_slots\n return unless params[:start_time]\n\n start_time = Time.from_picker(params.delete(:start_time))\n end_time = Time.from_picker(params.delete(:end_time))\n\n return if end_time < start_time # Prevent infinite loop\n\n shift_length = params.delete(:shift_length).to_i\n shift_overlap = params.delete(:shift_overlap).to_i\n people_per_shift = params.delete(:people_per_shift)\n\n num_shifts = ((end_time - start_time) / shift_length).ceil\n return if num_shifts > 100 # Arbitrary threshold to prevent flooding database\n\n cur_time = start_time\n TimeSlot.transaction do\n while cur_time < end_time\n end_shift_time = cur_time + shift_length + shift_overlap\n TimeSlot.create! job: @job,\n start_time: cur_time,\n end_time: [end_shift_time, end_time].min,\n slots: people_per_shift\n cur_time += shift_length\n end\n end\n end",
"def time_range min, max\n spawn :@trange, [min, max].map { |e| time_to_long e }\n end",
"def load_time_ranges\n @time_ranges = ActiveSupport::HashWithIndifferentAccess.new\n time_ranges = @config['time']\n time_ranges.each do |t,r|\n time_range = ActiveSupport::HashWithIndifferentAccess.new\n src_ranges ||= r\n src_ranges.map { |k,v| time_range[k.to_sym] = rangify_time_boundaries(v) }\n @time_ranges[t.to_sym] = time_range\n end\n\n end",
"def events_in_range(start_date_time, end_date_time, home_time_zone = \"UTC\")\n # fetch not repeating events first\n event_instances = events.where(date: start_date_time...end_date_time, repeat: nil).to_a\n\n # then repeating events\n events.includes(:repeat_exceptions, category: :repeat_exceptions).where.not(repeat: nil).each do |rep_event| # get all repeating events\n event_instances.concat(rep_event.events_in_range(start_date_time, end_date_time, home_time_zone)) # and add them to the event array\n end\n\n event_instances = event_instances.sort_by(&:date) # and of course sort by date\n\n event_instances # and return\n end",
"def test_record_activity_detects_multiple_day_boundaries\n yesterday1 = Time.new(2012, 1, 29, 11) # Two days ago at 11:00am\n @timelog.record_activity('Arrived', yesterday1)\n yesterday2 = Time.new(2012, 1, 29, 12) # Two days ago at 12:00pm\n @timelog.record_activity('Reading mail', yesterday2)\n today1 = Time.new(2012, 1, 31, 15) # Today at 3:00pm\n @timelog.record_activity('Arrived', today1)\n today2 = Time.new(2012, 1, 31, 16) # Today at 4:00pm\n @timelog.record_activity('Reading mail', today2)\n @stream.rewind\n assert_equal(\"2012-01-29 11:00: Arrived\\n\" <<\n \"2012-01-29 12:00: Reading mail\\n\" <<\n \"\\n\" <<\n \"2012-01-31 15:00: Arrived\\n\" <<\n \"2012-01-31 16:00: Reading mail\\n\",\n @stream.read)\n end",
"def reservations_by_date_range(date_range)\n res_by_date_range = @reservations.select do |res|\n res.date_range.overlaps?(date_range)\n end\n return res_by_date_range\n end",
"def time_intervals(program,insert_repeat_interval = true)\n intervals = map{|d|d.time_intervals}.flatten.uniq.find_all{|i|program.interval === i.tstart}\n if program.repeat_first_interval and insert_repeat_interval\n firstinterval = intervals.min.copy\n firstinterval.shift!(-program.resolution*60)\n intervals << firstinterval\n end\n intervals\n end",
"def test_record_activity_detects_day_boundaries_across_midnight\n yesterday1 = Time.new(2012, 1, 30, 20, 47) # Yesterday at 8:47pm\n @timelog.record_activity('Arrived', yesterday1)\n yesterday2 = Time.new(2012, 1, 30, 20, 59) # Yesterday at 8:59pm\n @timelog.record_activity('Writing a test', yesterday2)\n today = Time.new(2012, 1, 31, 4) # Today at 4:00am\n @timelog.record_activity('Arrived', today)\n @stream.rewind\n assert_equal([{:start_time => Time.new(2012, 1, 30, 20, 47),\n :end_time => Time.new(2012, 1, 30, 20, 59),\n :description => 'Writing a test'}],\n @timelog.activities)\n assert_equal(\"2012-01-30 20:47: Arrived\\n\" <<\n \"2012-01-30 20:59: Writing a test\\n\" <<\n \"\\n\" <<\n \"2012-01-31 04:00: Arrived\\n\",\n @stream.read)\n end",
"def sensor_readings_between(start_time, end_time, kind)\n start_time.change usec: 0\n end_time.change usec: 0\n\n time_series = []\n value = sensor_at start_time, kind\n\n edges = edges_between(start_time, end_time).where(kind: kind).all\n time = start_time\n offset = 0\n while time < end_time\n while edges[offset] && edges[offset].created_at <= time\n edge = edges[offset]\n value = edge.value\n offset += 1\n end\n time_series.push ts: time.to_i, value: value\n time += 1.second\n end\n time_series\n end",
"def parse_time_range(expr, zone = nil)\r\n return nil unless expr && !expr.empty?\r\n zone ||= '+00:00'\r\n expr.split(' - ')[0..1].map {|t| parse_time(t.strip, zone)}\r\n end",
"def initialize(args)\n @name = args[\"name\"]\n @start_date = args[\"start_date\"]\n @end_date = args[\"end_date\"]\n @location = args[\"location\"]\n @description = args[\"description\"]\n\n @start_time = args[\"start_time\"] if args.include? \"start_time\"\n\n @end_time = args[\"end_time\"] if args.include? \"end_time\"\n\n @is_repeated = true if args.include? \"repetition_freq\" and args[\"repetition_freq\"] != \"\"\n @has_alarm = true if args.include? \"alarm_time_unit\" and args[\"alarm_time_unit\"] != \"\"\n\n if args.include? \"wholeday\"\n @is_all_day = true\n else\n @is_all_day = false\n end\n\n if @start_date.include? \"/\"\n @is_us_format = true\n else\n @is_us_format = false\n end\n\n # Valid values are between 1 and 2147483647, excluding 0\n # \"asdf\".to_i -> 0\n if @is_repeated\n @repetition_freq = args[\"repetition_freq\"]\n value = args[\"repetition_interval\"]\n if value == \"\" or value.to_i > 2147483647 or value.to_i < 1\n @repetition_interval = \"1\"\n else\n @repetition_interval = value\n end\n @repetition_freq = \"YEARLY\" if @repetition_freq == \"Years\" || @repetition_freq == \"Jahre\"\n @repetition_freq = \"MONTHLY\" if @repetition_freq == \"Months\" || @repetition_freq == \"Monate\"\n @repetition_freq = \"WEEKLY\" if @repetition_freq == \"Weeks\" || @repetition_freq == \"Wochen\"\n @repetition_freq = \"DAILY\" if @repetition_freq == \"Days\" || @repetition_freq == \"Tage\"\n end\n\n if @has_alarm\n @alarm_time_unit = args[\"alarm_time_unit\"]\n alarm_value = args[\"alarm_time_value\"]\n if alarm_value == \"\" or alarm_value.to_i > 2147483647 or alarm_value.to_i < 1\n @alarm_time_value = \"1\"\n else\n @alarm_time_value = alarm_value\n end\n @alarm_time_unit = \"D\" if @alarm_time_unit == \"Day(s)\" || @alarm_time_unit == \"Tag(e)\"\n @alarm_time_unit = \"H\" if @alarm_time_unit == \"Hour(s)\" || @alarm_time_unit == \"Stunde(n)\"\n @alarm_time_unit = \"M\" if @alarm_time_unit == \"Minute(s)\" || @alarm_time_unit == \"Minute(n)\"\n end\n\n end",
"def create\n if params[:pay_day] && params[:start_day] && params[:end_day]\n ::TimeEntry.where(pay_day: params[:pay_day]).update_all(pay_day: nil)\n ::TimeEntry.where(\"day>=? AND day<=?\",params[:start_day],params[:end_day]).update_all(pay_day: params[:pay_day])\n end\n redirect_to \"/time/#{params[:start_day]}\"\n end",
"def schedule_break start_time, end_time, rate = 0.0\n check_break start_time, end_time\n\n roadall.insert(-2, [start_time.to_i, nil, roadall.last.last])\n roadall.insert(-2, [end_time.to_i, nil, rate])\n end",
"def parse_time_range(time_string)\n return nil if time_string.nil?\n\n start_time =\n Chronic.parse(time_string.split('-').first.strip).seconds_since_midnight\n end_time =\n Chronic.parse(time_string.split('-').last.strip).seconds_since_midnight\n\n start_time...end_time\nend",
"def index\n if params[:date_range].blank?\n @time_slots = TimeSlot.all\n else\n input_start_time =\n input_end_time = \n @time_slots = TimeSlot.where(\"start_time > ? AND end_time < ?\", input_start_time, input_end_time)\n end\n end",
"def find_events_in_range(start_min, start_max,options = {})\n options[:max_results] ||= 25\n options[:order_by] ||= 'lastmodified' # other option is 'starttime'\n formatted_start_min = start_min.strftime(\"%Y-%m-%dT%H:%M:%S\")\n formatted_start_max = start_max.strftime(\"%Y-%m-%dT%H:%M:%S\")\n query = \"?start-min=#{formatted_start_min}&start-max=#{formatted_start_max}&recurrence-expansion-start=#{formatted_start_min}&recurrence-expansion-end=#{formatted_start_max}\"\n query = \"#{query}&orderby=#{options[:order_by]}&max-results=#{options[:max_results]}\"\n event_lookup(query)\n end",
"def merged_meetings(meeting_time_ranges)\n # assuming meetings can fall at most 12 30-minute blocks past 9am\n start_times = Array.new(13, nil) # array of start times at their index\n end_times = Array.new(13, nil) # array of end times - their index is their start time\n meeting_time_ranges.each do |meeting_time_range|\n start_time = meeting_time_range[0]\n end_time = meeting_time_range[1]\n\n # add start_time to start_times\n start_times[start_time] = start_time\n\n # add end_time to end_times at its start_time index, unless there is already a later end_time at that index\n end_times[start_time] = end_time unless !end_time[start_time].nil? && end_time[start_time] > end_time\n end\n\n merged_meeting_times = []\n\n # start_times look something like [0, nil, nil, 3, 4, nil, nil, nil, nil, 9, 10, nil]\n # end_times look something like [1, nil, nil, 5, 8, nil, nil, nil, nil, 10, 12, nil]\n last_start_time = nil\n last_end_time = nil\n start_times.each do |start_time|\n next if start_time.nil?\n\n if last_start_time.nil? # no values have been stored yet\n last_start_time = start_time\n last_end_time = end_times[start_time]\n next\n end\n\n if start_time <= last_end_time # current start_time is before the last end_time\n if start_time < last_start_time\n # current start_time earlier than last_start_time - assign as last_start_time\n last_start_time = start_time\n end\n\n if end_times[start_time] > last_end_time\n # current end_time later than last_end_time - assign it end_time as last_end_time\n last_end_time = end_times[start_time]\n end\n next\n end\n\n if start_time > last_end_time\n # we have reached the start of a new range - store the last range\n merged_meeting_times << [last_start_time, last_end_time]\n\n # reset the last_end_time and last_start_time to the current values\n last_start_time = start_time\n last_end_time = end_times[start_time]\n next\n end\n end\n\n # be sure to append the remaining last meeting time range\n merged_meeting_times << [last_start_time, last_end_time]\n\n merged_meeting_times\nend",
"def retrieve_date_range\n @free_period = false\n @from, @to = nil, nil\n\n if params[:period_type] == '1' || (params[:period_type].nil? && !params[:period].nil?)\n case params[:period].to_s\n when 'today'\n @from = @to = Date.today\n when 'yesterday'\n @from = @to = Date.today - 1\n when 'current_week'\n @from = Date.today - (Date.today.cwday - 1)%7\n @to = @from + 6\n when 'last_week'\n @from = Date.today - 7 - (Date.today.cwday - 1)%7\n @to = @from + 6\n when '7_days'\n @from = Date.today - 7\n @to = Date.today\n when 'current_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1)\n @to = (@from >> 1) - 1\n when 'last_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n @to = (@from >> 1) - 1\n when '30_days'\n @from = Date.today - 30\n @to = Date.today\n when 'current_year'\n @from = Date.civil(Date.today.year, 1, 1)\n @to = Date.civil(Date.today.year, 12, 31)\n end\n elsif params[:period_type] == '2' || (params[:period_type].nil? && (!params[:from].nil? || !params[:to].nil?))\n begin; @from = params[:from].to_s.to_date unless params[:from].blank?; rescue; end\n begin; @to = params[:to].to_s.to_date unless params[:to].blank?; rescue; end\n @free_period = true\n else\n # default\n end\n \n @from, @to = @to, @from if @from && @to && @from > @to\n\n end",
"def day_range_for(time)\n year = time.year\n month = time.month\n day = time.day\n timezone = Time.new.zone\n\n Range.new(\n DateTime.new(year, month, day, 0, 0, 0, timezone),\n DateTime.new(year, month, day, 23, 59, 59, timezone)\n )\n end",
"def events_in_time_range(start_date_string, end_date_string)\n return self.events if self.events.nil?\n\n if(start_date_string.is_a?(String))\n # I was told there would be no timezones :/\n start_time = DateTime.parse(start_date_string).to_time.utc\n end_time = DateTime.parse(end_date_string).to_time.utc\n else\n start_time = start_date_string\n end_time = end_date_string\n end\n\n self.events.select do |e| \n created_at_time = DateTime.parse(e.created_at).to_time.utc\n created_at_time >= start_time && created_at_time < end_time\n end\n end",
"def get_frontend_bounds_from_time_period(time_period)\n parts = /(\\d+)(\\w+)/.match(time_period)\n\n if parts.nil? or parts.size < 3 or parts[2].size < 1\n return {\n :from => time_period,\n :to => 'now',\n }\n end\n\n delta = (parts[1].to_i) * 3\n period = 0\n\n # really naive parsing of a time period\n case parts[2][0]\n when 's'\n period = 1\n when 'm'\n period = 60\n when 'h'\n period = 60 * 60\n when 'd'\n period = 60 * 60 * 24\n when 'w'\n period = 60 * 60 * 24 * 7\n else\n period = 60\n end\n\n {\n :from => Time.now.to_i - period * delta,\n :to => Time.now.to_i\n }\n end",
"def test_record_activity_detects_day_boundaries\n yesterday1 = Time.new(2012, 1, 31, 3, 47) # Yesterday at 3:47am\n @timelog.record_activity('Arrived', yesterday1)\n yesterday2 = Time.new(2012, 1, 31, 3, 59) # Yesterday at 3:59am\n @timelog.record_activity('Writing a test', yesterday2)\n today = Time.new(2012, 1, 31, 4) # Today at 4:00am\n @timelog.record_activity('Arrived', today)\n @stream.rewind\n assert_equal([{:start_time => Time.new(2012, 1, 31, 3, 47),\n :end_time => Time.new(2012, 1, 31, 3, 59),\n :description => 'Writing a test'}],\n @timelog.activities)\n assert_equal(\"2012-01-31 03:47: Arrived\\n\" <<\n \"2012-01-31 03:59: Writing a test\\n\" <<\n \"\\n\" <<\n \"2012-01-31 04:00: Arrived\\n\",\n @stream.read)\n end",
"def initialize(start_time, end_time, items)\n raise \"Items needs to be a hash\" if !items.is_a? Hash\n raise \"start_time and end_time must be DateTime objects\" if (!start_time.is_a?(DateTime) || !end_time.is_a?(DateTime))\n raise \"start_time must be less than end_time\" if start_time>=end_time\n\n @start_time = start_time \n @end_time = end_time\n @items = items\n end",
"def union(range)\n # Return self if nil (nothing new to add) or if it matches the other range (they are equivalent)\n return self.clone if range.nil?\n return self.clone if eql?(range)\n\n # Figure out which range starts earlier (to capture the most time)\n if low <= range.low\n earlier_start = self\n later_start = range\n else\n earlier_start = range\n later_start = self\n end\n \n # Figure out which ranges ends earlier (the more restrictive one)\n if high >= range.high\n earlier_end = self\n later_end = range\n else\n earlier_end = range\n later_end = self\n end\n \n result = []\n # We have continuous Ranges so we can return one Range to encapsulate both\n if earlier_start.contains?(later_start.low)\n result << Range.new(\"TS\", earlier_start.low.clone, later_end.high.clone, nil)\n else\n # The Ranges are disjoint, so we'll need to return two arrays to capture all of the potential times\n result << Range.new(\"TS\", earlier_start.low.clone, earlier_start.high.clone, nil)\n result << Range.new(\"TS\", later_start.low.clone, later_start.high.clone, nil)\n end\n end",
"def get_work_intervals(intervals)\n intervals\n .group_by do |interval|\n interval.time_in.to_date\n end\n .values\n end",
"def validate_time_slots times\n time_models = []\n times.each do |time|\n t = TimeSlot.new(from: time[:from], to: time[:to], opinion_poll: @opinion_poll)\n\n bad_request t.errors.messages and return unless t.valid?\n time_models.append t\n end\n time_models\n end",
"def time_range(rng=self,utc_offset=nil)\n if rng.begin.respond_to?(:sec) && rng.end.respond_to?(:sec)\n utc_offset ||= rng.begin.utc_offset\n Range.new( rng.begin.getlocal(utc_offset),\n rng.end.getlocal(utc_offset),\n rng.respond_to?(:exclude_end?) && rng.exclude_end?\n )\n else\n adj_rng = day_range(rng)\n b,e = adj_rng.begin, adj_rng.end\n Range.new( Time.new(b.year,b.month,b.day,0,0,0,utc_offset), \n Time.new(e.year,e.month,e.day,0,0,0,utc_offset), \n true\n )\n end\n end",
"def calculate(frequency, frequency_integer, start_date, end_date)\n first_due_date = @calendar.roll_forward(start_date)\n base_dates = [first_due_date]\n return [base_dates, base_dates] if frequency == 'Once'\n\n frequency_symbol = get_frequency_symbol(frequency)\n grace_dates = [first_due_date.advance(frequency_symbol => frequency_integer)]\n\n base_date = start_date\n end_date = calculate_end_date(start_date, end_date)\n\n while base_date < end_date\n grace_date = base_date.advance(frequency_symbol => frequency_integer*2)\n base_date = base_date.advance(frequency_symbol => frequency_integer)\n base_dates << @calendar.roll_forward(base_date)\n grace_dates << @calendar.roll_forward(grace_date)\n end\n\n [base_dates, grace_dates]\n end",
"def soon range=4.days\n schedules.where(:when.lte => range.from_now)\n end",
"def retrieve_date_range_14\n @free_period = false\n @from, @to = nil, nil\n\n if params[:period_type] == '1' || (params[:period_type].nil? && !params[:period].nil?)\n case params[:period].to_s\n when 'today'\n @from = @to = Date.today\n when 'yesterday'\n @from = @to = Date.today - 1\n when 'current_week'\n @from = Date.today - (Date.today.cwday - 1)%7\n @to = @from + 6\n when 'last_week'\n @from = Date.today - 7 - (Date.today.cwday - 1)%7\n @to = @from + 6\n when '7_days'\n @from = Date.today - 7\n @to = Date.today\n when 'current_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1)\n @to = (@from >> 1) - 1\n when 'last_month'\n @from = Date.civil(Date.today.year, Date.today.month, 1) << 1\n @to = (@from >> 1) - 1\n when '30_days'\n @from = Date.today - 30\n @to = Date.today\n when 'current_year'\n @from = Date.civil(Date.today.year, 1, 1)\n @to = Date.civil(Date.today.year, 12, 31)\n end\n elsif params[:period_type] == '2' || (params[:period_type].nil? && (!params[:from].nil? || !params[:to].nil?))\n begin; @from = params[:from].to_s.to_date unless params[:from].blank?; rescue; end\n begin; @to = params[:to].to_s.to_date unless params[:to].blank?; rescue; end\n @free_period = true\n else\n # default\n end\n\n @from, @to = @to, @from if @from && @to && @from > @to\n end",
"def create\n @time_slot = TimeSlot.new(params[:time_slot])\n @time_slot.user_id = current_identity.user_id\n\t@recurrence_array = []\n respond_to do |format|\n if @time_slot.save\n format.html { redirect_to @time_slot, notice: 'Time slot was successfully created.' }\n format.json { render json: @time_slot, status: :created, location: @time_slot }\n else\n format.html { render action: \"new\" }\n format.json { render json: @time_slot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def time_range\n start_time..end_time\n end",
"def temporal_to_rifcs(builder)\n temporal.each do |x|\n\n builder.coverage {\n builder.temporal {\n \n if (x =~ /^(\\d{4})$/ ||\n x =~ /^(\\d{4}-\\d{2})$/ ||\n x =~ /^(\\d{4}-\\d{2}-\\d{2})$/)\n # Single date (TODO: is having two date elements correct?)\n builder.date($~[1], type: 'dateFrom', dateFormat: 'W3CDTF')\n builder.date($~[1], type: 'dateTo', dateFormat: 'W3CDTF')\n\n elsif (x =~ /^(\\d{4})\\/(\\d{4})$/ ||\n x =~ /^(\\d{4}-\\d{2})\\/(\\d{4}-\\d{2})$/ ||\n x =~ /^(\\d{4}-\\d{2}-\\d{2})\\/(\\d{4}-\\d{2}-\\d{2})$/)\n # Date range\n builder.date($~[1], type: 'dateFrom', dateFormat: 'W3CDTF')\n builder.date($~[2], type: 'dateTo', dateFormat: 'W3CDTF')\n\n else\n # Unrecognised temporal value, treat as text\n builder.text_(x)\n end\n } # </temporal>\n } # </coverage>\n end\n\n end",
"def new_with_date_range(begin_date, end_date)\n report = new\n report.set_date_range(begin_date, end_date)\n report\n end",
"def sum_field_by_time_range(field, time_f)\n self.workout_records.select{ |r| time_f.call(r) }.map{ |r| r.send(field).to_f }.sum\n end",
"def random_time_range(range)\n min = time_to_float(range.min)\n max = time_to_float(range.max)\n time = Time.at(random(min..max))\n\n if defined?(DateTime) && range.min.is_a?(DateTime)\n time = time.to_datetime\n elsif range.min.is_a?(Date)\n time = time.to_date\n end\n\n return time\n end",
"def daily_requests_for(time = Time.now)\n find_or_create_daily_requests_for(time)\n end",
"def determine_date_range\n case @time_frame\n when 'week' then (@date.beginning_of_week..@date.end_of_week)\n when 'month' then (@date.beginning_of_month..@date.end_of_month)\n end\n end",
"def merged_meetings_2(meeting_time_ranges)\n # merged_meetings where we cannot assume how many time blocks\n meeting_time_ranges = meeting_time_ranges.sort\n\n merged_meeting_times = []\n\n last_start_time = nil\n last_end_time = nil\n meeting_time_ranges.each do |meeting_time_range|\n start_time = meeting_time_range[0]\n end_time = meeting_time_range[1]\n\n if last_start_time.nil? # no values have been stored yet\n last_start_time = start_time\n last_end_time = end_time\n next\n end\n\n if start_time <= last_end_time # current start_time is before the last end_time\n if start_time < last_start_time\n # current start_time earlier than last_start_time - assign as last_start_time\n last_start_time = start_time\n end\n\n if end_time > last_end_time\n # current end_time later than last_end_time - assign it end_time as last_end_time\n last_end_time = end_time\n end\n next\n end\n\n if start_time > last_end_time\n # we have reached the start of a new range - store the last range\n merged_meeting_times << [last_start_time, last_end_time]\n\n # reset the last_end_time and last_start_time to the current values\n last_start_time = start_time\n last_end_time = end_time\n next\n end\n end\n\n # be sure to append the remaining last meeting time range\n merged_meeting_times << [last_start_time, last_end_time]\n\n merged_meeting_times\nend",
"def make_event_times_array(dates_array, hour, min)\n\t\tevent_times = Array.new\n\n\t\tdates_array.each_index do |index|\n\t\t\n\t\t\tevent_times[index] = create_event_time(dates_array[index],hour, min)\n\t\tend\n\n\t\treturn event_times\n\tend",
"def intervals_in_range\n @user.intervals\n .where('DATE(time_in) BETWEEN ? AND ?', @date_range.begin.to_date, @date_range.end.to_date)\n .order(:time_in)\n end",
"def create_timing\n if @freak_number.present?\n self.timing_expression = @freak_number + \" \" + @freak_interval\n elsif @reactive_expression.present?\n self.timing_expression = @reactive_expression\n end\n self.timing_duration = \"\" if @until_radio == \"nodate\"\n self.timing_duration = @duration_number + \" \" + @duration_unit if @until_radio == \"date\" and self.timing_until.blank? and @duration_number and @duration_unit\n end",
"def setup_range(date)\n diff = date.wday - self.class.windex(start_wday)\n @first = date - (diff + ((diff < 0) ? DAYS : 0))\n @last = @first + DAYS - 1\n end",
"def conditions_for_time_qualifiers(time_qualifiers)\n return if time_qualifiers.empty?\n\n res = []\n time_qualifiers.each do |tq|\n start_time = tq.qualifiable.start_time\n end_time = tq.qualifiable.end_time\n column = tq.qualifiable_column\n column = Task.connection.quote_column_name(column)\n\n sql = \"tasks.#{ column } >= '#{ start_time.to_formatted_s(:db) }'\"\n sql += \" and tasks.#{ column } < '#{ end_time.to_formatted_s(:db) }'\"\n res << sql\n end\n\n res = res.join(\" or \")\n return \"(#{ res })\"\n end",
"def data(granularity=nil, range=nil, scope={}, select_keys={})\n unless granularity == :all_time\n range = self.default_range if range.nil?\n range = range.to_sym if range.is_a?(String)\n\n if range.is_a?(Symbol)\n granularity ||= self.default_granularity(range)\n range = RANGE_SELECTS[range].call\n end\n end\n\n granularity ||= self.default_granularity\n interval = GRANULARITIES[granularity]\n\n # Replace \"%{granular_key}\" with \"{{t}}\" placeholder for front-end data consumption\n data_lookup_keys = @increment_keys.keys.map { |k| sprintf( k, select_keys.merge(granular_key: \"{{t}}\") ) }.uniq\n\n if range\n start_at = self.time_key(range.first, interval)\n end_at = range.last.to_i\n range = (start_at..end_at).step(interval)\n\n # Replace \"%{granular_key}\" with e.g. \"monthly.1381536000\" for each date-key in range and convert to symbol :\"monthly.1381536000\"\n # for each combination of range array with @increment_keys.keys array.\n keys = range.to_a.product(@increment_keys.keys).map { |i, k| sprintf( k, select_keys.merge(granular_key: \"#{granularity}.#{i}\") ).to_sym }\n else\n keys = @increment_keys.keys.map { |k| sprintf( k, select_keys.merge(granular_key: granularity) ).to_sym }\n end\n keys << \"_id\"\n\n results = self.\n in(scope).\n where('$or' => keys.map{ |k| {k => { '$exists' => true}} }).\n only(*@scope_by, *keys).to_a\n\n return Granalytics::Data.new(\n granularity,\n range,\n data_lookup_keys,\n results\n )\n end",
"def check_schedule(range_of_days)\n\tif 1 > range_of_days.to_i\n\t\traise \"The schedule of the diary must last for at least one day.\"\n\telsif 40 < range_of_days.to_i\n\t\traise \"Save paper! Don't generate schedule for >40 days.\"\n\tend\n\t\n\t# Set the duration of the food diary\n\t$duration = range_of_days.to_i\nend"
] |
[
"0.60084087",
"0.55073476",
"0.5393154",
"0.5291464",
"0.5277832",
"0.52732146",
"0.5257287",
"0.520492",
"0.5191614",
"0.5173576",
"0.51333153",
"0.50888205",
"0.50587213",
"0.50401884",
"0.50280565",
"0.5011395",
"0.49947196",
"0.49723914",
"0.497119",
"0.49693468",
"0.4946814",
"0.49437502",
"0.49433202",
"0.4937705",
"0.49258244",
"0.49169144",
"0.49132407",
"0.487897",
"0.4864229",
"0.4863082",
"0.48584032",
"0.48560268",
"0.4855106",
"0.48542333",
"0.4836687",
"0.4833363",
"0.48310444",
"0.48264164",
"0.48137373",
"0.4809373",
"0.47857377",
"0.47790185",
"0.47677663",
"0.47632828",
"0.47433496",
"0.47422603",
"0.47407508",
"0.47397205",
"0.47335342",
"0.47263968",
"0.47224033",
"0.47219282",
"0.47125092",
"0.47115532",
"0.4711172",
"0.47109526",
"0.47069445",
"0.47002113",
"0.46949562",
"0.46931484",
"0.4692064",
"0.46659312",
"0.46639255",
"0.46615258",
"0.4647806",
"0.46334064",
"0.46332657",
"0.4632697",
"0.463162",
"0.4630067",
"0.46255133",
"0.4619817",
"0.4618905",
"0.4618312",
"0.46182224",
"0.46130764",
"0.4603162",
"0.46028918",
"0.46008006",
"0.4588316",
"0.4572853",
"0.45720795",
"0.45694318",
"0.45653042",
"0.45547438",
"0.45521662",
"0.45479646",
"0.45248488",
"0.45241955",
"0.45230666",
"0.452056",
"0.45195073",
"0.4515236",
"0.4509336",
"0.45046082",
"0.45042846",
"0.44933233",
"0.44922298",
"0.44914126",
"0.44912195",
"0.44883186"
] |
0.0
|
-1
|
Create a recurrence at given time
|
def at(time)
merge(at: time)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def add_recurrence(type: :week, on: on = nil, at: at = nil)\n type = type.to_sym\n unless [:week, :day].include? type\n raise \"Type must be either :week or :day\"\n end\n if type == :week and (on.nil? or (on.is_a?(Array) and on.empty?))\n raise \"Weekdays must be specified when selecting the :week type\"\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if self.schedule.nil?\n schedule = Montrose::Schedule.new\n end\n if at.nil?\n raise \"Time must be specified in parameter 'at'\"\n else\n schedule.add Montrose.every(type, on: on, at: at).starts(created_at)\n self.write_attribute(self.class.schedulable_attribute, schedule)\n end\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def schedule_recurring_task_creation(task)\n recurring_scheduler = Scheduler.new\n @recurring_schedulers << recurring_scheduler\n\n recurring_scheduler.schedule.every \"#{Helpers.convert_frequency_to_seconds(task.frequency).to_s}s\" do\n new_task = Task.new\n new_task.description = task.description\n new_task.frequency = task.frequency\n new_task.creation_date = Time.now.getlocal\n new_task.target_date = Helpers.calculate_task_target_date(\n new_task.creation_date,\n new_task.frequency\n )\n new_task.recurring_scheduler_id = recurring_scheduler.id\n\n new_task.create_reminder_notification\n new_task.create_failed_notification\n\n add_task(new_task)\n end\n end",
"def next_meeting(after_time = Time.now.utc )\n # puts \"Looking up next meeting after #{after_time}\"\n if recurrence_frequency.blank?\n return start_time\n end\n\n if after_time < start_time\n return start_time\n end \n\n after_time = after_time.local_from_utc(self.time_zone) \n\n\n # Advance the starting time in the case when it falls after the beginning of\n # a meeting on the same day. We do this so that we can use \"day precision\"\n # (PDate.day) in the Runt library instead of \"minute precision\" (PDate.min),\n # which performs terribly.\n start_time = start_time_local\n if(after_time.hour > start_time.hour or ( after_time.hour == start_time.hour and after_time.min > start_time.min))\n after_time = after_time + 1.day\n after_time = Time.gm(after_time.year, after_time.month, after_time.day, 0, 0)\n end\n\n case recurrence_frequency\n when 'daily'\n end_time = after_time + 25.hours \n # after_time -= 1.day\n start_date = PDate.day(after_time.year, after_time.month, after_time.day , after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'weekdays'\n # Make the range over 3 days so that Friday night searches will still turn\n # up Monday as the next day.\n end_time = after_time + 3.days\n start_date = PDate.day(after_time.year, after_time.month, after_time.day, after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'monthly'\n eom = (after_time + 40.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eom.year, eom.month, eom.day)\n when 'weekly'\n eow = (after_time + 8.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eow.year, eow.month, eow.day)\n when 'yearly'\n # Just doing \"after_time + 367.days\" results in a bit of a performance hit\n # as hundreds of days are compared. We'll try to narrow it a bit. Not too\n # much, because we don't have time to actually write unit tests and make\n # sure the narrowing code works. :) Which is why the comment is here.\n st = after_time + 250.days\n et = st + 150.days\n start_date = PDate.day(st.year, st.month, st.day)\n end_date = PDate.day(et.year, et.month, et.day)\n end \n # puts \" Range #{start_date.to_s} - #{end_date.to_s}\"\n d_range = DateRange.new(start_date, end_date)\n sched = Schedule.new\n event = Event.new((self.invitation.name rescue \"no name\"))\n sched.add(event,self.runt_expression)\n dates = sched.dates(event,d_range)\n\n next_mtg = dates.first\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, start_time_local.hour, start_time_local.min)\n result = nil\n begin\n result = next_mtg_time.local_to_utc(self.time_zone)\n rescue TZInfo::PeriodNotFound\n # This only happens when the time is during the one hour which is skipped\n # during the transition to DST. For example, only on Sun Mar 08 02:15:00\n # (see ticket #744).\n next_hour = start_time_local.hour + 1\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, next_hour, start_time_local.min)\n retry\n end\n return result\n end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurring; end",
"def recurrence\n nil\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def schedule_repetition\n self.due = Date.today + interval\n self.studied_at = Date.today\n end",
"def schedule(time, callback); end",
"def date_calc(start,day_start,day_duration,round)\n time=start;schedule=[]\n round.size.times do |r|\n#print day_start+day_duration;print \"\\n\"\n if time >= day_start + day_duration\n#print time;print \"\\n\"\n time=day_start+1.day\n day_start = time\n end\n schedule[r] = time\n time+=HEAT_INTERVAL\n end\n\n return schedule\n end",
"def fill_recurrence(number)\n if old_num == number\n self.recc += 1\n else\n apply_recurrence\n self.old_num = number\n self.recc = 1\n end\n end",
"def next_occurrence(from_date)\n residue = @residue - residue_for(from_date)\n date = move_by from_date, residue.modulo(interval)\n time = Time.new(date.year, date.month, date.day, start_time.hour, start_time.min, start_time.sec)\n if (exx = exclusions.detect {|rule| rule.violated_by? time})\n if stops_by && time > stops_by\n nil\n else\n next_occurrence(move_by time, 1)\n end\n else\n time\n end\n end",
"def recurrence\n { ATTR_RECURRENCE[@attribute] => 1 }\n end",
"def schedule_break start_time, end_time, rate = 0.0\n check_break start_time, end_time\n\n roadall.insert(-2, [start_time.to_i, nil, roadall.last.last])\n roadall.insert(-2, [end_time.to_i, nil, rate])\n end",
"def now_and_every(interval, recur = T.unsafe(nil), &block); end",
"def create_recurrences(transaction)\n CreateRecurrencesJob.perform_later(\n transaction.class.to_s,\n transaction.id.to_s\n )\n end",
"def set_next_repetition\n if repetitions.order(\"id ASC\").last.successful\n self.consecutive_successful_repetitions += 1\n next_planned_interval = rand((repetitions.last_planned_interval * 2)..(repetitions.last_planned_interval * 3))\n else\n self.consecutive_successful_repetitions = 0\n next_planned_interval = rand(1..3)\n end\n save\n if consecutive_successful_repetitions < WhRails::Application.config.max_consecutive_successful_repetitions\n # repetitions.last.actual_date is always the current date.\n next_repetition_date = repetitions.order(\"id ASC\").last.actual_date + next_planned_interval.days\n repetitions.create planned_date: next_repetition_date, actual_date: next_repetition_date\n else\n self.learned_on = Date.today\n save\n end\n end",
"def schedule(time, callback)\n handle = Handle.new(time.to_f, callback)\n \n index = bisect_left(@sequence, handle)\n \n # Maintain sorted order, O(logN) insertion time.\n @sequence.insert(index, handle)\n \n return handle\n end",
"def new_schedule(*args)\n if !args.all? { |e| e.is_a?(Integer) && e >= 0 && e <= 6 }\n return \"Please enter a number from 0-6 where each number represents a day of the week. 0 represents Sunday, 1 represents Monday, etc.\"\n end\n schedule1 = Schedule.new(self.first_event, duration: self.duration_mins.minutes )\n schedule1.add_recurrence_rule Rule.weekly.day(args)\n self.schedule = schedule1\n self.save!\n end",
"def create\n @time_slot = TimeSlot.new(params[:time_slot])\n @time_slot.user_id = current_identity.user_id\n\t@recurrence_array = []\n respond_to do |format|\n if @time_slot.save\n format.html { redirect_to @time_slot, notice: 'Time slot was successfully created.' }\n format.json { render json: @time_slot, status: :created, location: @time_slot }\n else\n format.html { render action: \"new\" }\n format.json { render json: @time_slot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def recurrence_at\n unless @recurrence_at.nil?\n return @recurrence_at\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if schedule.nil?\n return nil\n end\n # montrose stores the \"at\" times in an array with\n # time[0] = hour\n # time[1] = mins\n # time[2] = secs\n schedule.rules.first.to_h[:at].map{|time| [time[0].to_s.rjust(2,\"0\"),time[1].to_s.rjust(2,\"0\")].join(\":\")}.join(\", \")\n end",
"def calc_next_run\n RunAtPeriodicJob.new(:name => self.name, :job => self.job, :run_at_minutes => self.run_at_minutes)\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def create_time_request\n TimeRequest.create(\n time: [ Time.new(2000, 1, 1, 14, 0, 0, \"+00:00\").utc, Time.new(2000, 1, 1, 13, 0, 0, \"+00:00\").utc, Time.new(2000, 1, 1, 12, 0, 0, \"+00:00\").utc ].sample,\n reservation: Reservation.all.sample,\n check_in: [true, false].sample,\n status: 'pending'\n )\nend",
"def create_for_period(future_period, notification_times, border_time)\n existing_times = future_period.notifications.all.map { |n| n.time }\n notification_times.each do |time|\n if !existing_times.include?(time) && border_time < time\n future_period.notifications.create!(time: time)\n end\n end\n end",
"def make_constant_schedule(name, temperature)\n s = OpenStudio::Model::ScheduleRuleset.new(@model)\n s.setName(name)\n s.defaultDaySchedule.addValue(OpenStudio::Time.new(\"24:00:00\"), OpenStudio::convert(temperature, \"F\", \"C\").get)\n\ts\n end",
"def schedule(time, callback)\n handle = Handle.new(time.to_f, callback)\n\n index = bisect_left(@sequence, handle)\n\n # Maintain sorted order, O(logN) insertion time.\n @sequence.insert(index, handle)\n\n return handle\n end",
"def start_recurring_payment\n return unless recurring_period.present?\n run_at = nil\n if recurring_period.to_s.is_i? # each custom days\n run_at = recurring_period.to_i.days.from_now\n # run_at = recurring_period.to_i.minutes.from_now\n else\n case recurring_period\n when 'daily'\n run_at = 1.day.from_now\n when 'weekly'\n run_at = 7.days.from_now\n when 'monthly'\n run_at = 1.month.from_now\n when 'quarterly'\n run_at = 3.months.from_now\n when 'biannually'\n run_at = 6.months.from_now\n when 'yearly'\n run_at = 1.year.from_now\n end\n end\n Delayed::Job.enqueue(LongTasks::RecurringPaymentNotification.new(id), run_at: run_at - 1.day) if run_at && ['tithe', 'partnership'].include?(goal)\n Delayed::Job.enqueue(LongTasks::RecurringPayment.new(id), run_at: run_at) if run_at\n end",
"def reschedule_at(time, attempts)\n case attempts\n when (0..4)\n interval = 1.minute\n when (5..6)\n interval = 5.minutes\n else\n interval = 10.minutes\n end\n time + interval\n end",
"def reschedule_at(time, attempts)\n case attempts\n when (0..4)\n interval = 1.minute\n when (5..6)\n interval = 5.minutes\n else\n interval = 10.minutes\n end\n time + interval\n end",
"def next_time(time, schedule, closing_time)\n @time = time\n @schedule = schedule\n cycle_start_time = schedule.start_time - 24 * 60 * 60\n\n return nil unless find_acceptable_time_before(closing_time)\n number_of_days = number_of_days_between(@time, cycle_start_time)\n current_cycle_percentage = calculate_percentage(number_of_days)\n\n until current_cycle_percentage <= @acceptable_cycle_percentage\n @time += 1\n return nil unless find_acceptable_time_before(closing_time)\n number_of_days = number_of_days_between(@time, cycle_start_time)\n current_cycle_percentage = calculate_percentage(number_of_days)\n end\n\n @uses += 1 if @time\n @time\n end",
"def create\n timer = Timer.new(\n last_rang: Time.now,\n time_increment: params[:time_increment],\n increment_unit: params[:increment_unit],\n timerable_id: params[:timerable_id],\n timerable_type: params[:timerable_type],\n repeating: params[:repeating] \n )\n\n if timer.save\n user = timer.timerable.user\n text = \"your medication\"\n ReminderJob.set(wait: eval(\"#{timer.time_increment}.#{timer.increment_unit}\")).perform_later(timer, user.phone_number, text)\n\n render json: {message: 'Reminder created successfully'}, status: :created\n else \n render json: {errors: timer.errors.full_messages}, status: :bad_request\n end\n end",
"def next\n recurrence.next if recurring?\n end",
"def recurrence\n unless read_attribute(:recurrence).empty?\n IceCube::Rule.from_hash(read_attribute(:recurrence))\n end\n end",
"def add_oneshot_at exact_time, timer_proc\n return nil unless timer_proc\n\n timer = Timer.new :timers => self, :exact_time => exact_time, :periodical => false, :timer_proc => timer_proc\n add timer\n timer\n end",
"def generate(time, start, focus)\n outline = create_outline(time, start, focus)\n subsequences = outline.map { |type| create_subsequence(type) }\n sequence = subsequences.flatten\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def process\n @recurrences.each { |r| process_recurrence(r) }\n end",
"def rocket_job_cron_next_time(time = Time.now)\n RocketJob::Plugins::Rufus::CronLine.new(cron_schedule).next_time(time)\n end",
"def rocket_job_cron_next_time(time = Time.now)\n RocketJob::Plugins::Rufus::CronLine.new(cron_schedule).next_time(time)\n end",
"def schedule_at_relative(due_time, action)\n raise 'action cannot be nil' unless action\n\n schedule_at_relative_with_state(action, due_time, method(:invoke))\n end",
"def createDailyWins(contest,cp)\n cdate = contest.start_date.to_date\n prize_per_day = 2\n while cdate <= contest.end_date.to_date\n for i in (1..prize_per_day)\n time = \"#{(0..23).to_a.sample}:#{(0..59).to_a.sample}:#{(0..59).to_a.sample} Rome\"\n wintime = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" \"+ time)\n wintime_end = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" 23:59:59\")\n \n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n while Instantwin.where(\"unique_id=?\",unique_id).present?\n @hash_counter += 1\n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n end\n \n iw = Instantwin.new\n iw.contest_periodicity_id = cp.id\n iw.title = \"Daily\"\n iw.time_to_win_start = wintime\n iw.time_to_win_end = wintime_end\n iw.unique_id = unique_id\n iw.save\n @hash_counter += 1\n end\n cdate += 1\n end\n end",
"def set_first_repetition\n first_repetition_date = Date.today + rand(1..3).days\n repetitions.create planned_date: first_repetition_date, actual_date: first_repetition_date\n end",
"def correct_time(time, frequency)\n time -= frequency while time > Time.now\n time += frequency while time < Time.now\n time\nend",
"def add_occurrences!(event, at = [])\n Array(at).each do |time|\n OccurrenceEntry.create!(:post_id => id, :label => event, :at => time)\n end\n end",
"def schedule(time, callback)\n\t\t\tflush!\n\t\t\t\n\t\t\thandle = Handle.new(time.to_f, callback)\n\t\t\t\n\t\t\t@queue << handle\n\t\t\t\n\t\t\treturn handle\n\t\tend",
"def next!\n self.start = self.send(:\"next_#{frequency}_in_recurrence\") \n self\n end",
"def future_single_event_creation\n self.schedule.next_occurrences(12).each do |occurrence|\n # TODO: Hot-Fix for Bug #83, unti ice_cube's issue 84 is resolved\n occurrence = occurrence.without_ms\n\n if !self.schedule.extimes.map(&:to_i).include? occurrence.to_i\n SingleEvent.where(event_id: self.id,\n occurrence: occurrence,\n based_on_rule: true).first_or_create\n end\n end\n end",
"def initialize(with_time=true)\n @with_time\n @day = Day.new # the time schedule for the mechanic\n end",
"def create_expenses\n expense_id = nil\n @expense = @account.expenses.create(expense_params)\n step = params[:expense_form][:recurrence].to_i\n\n if @expense.valid? && step != 0\n @expense.month_id = @expense.due_date.mon\n @expense.save \n start_month = @expense.due_date.mon + step\n number_of_months = step\n (start_month..12).step(step).each do |month|\n @expense = @account.expenses.new(expense_params)\n @expense.month_id = month\n @expense.due_date = @expense.due_date.to_date >> number_of_months\n number_of_months += step\n @expense.related_to = expense_id || @expense.id\n @expense.save\n expense_id ||= @expense.id\n end\n elsif @expense.valid?\n @expense.month_id = @expense.due_date.mon\n @expense.save\n end\n @expense.valid?\n end",
"def build_job(start_time, end_time)\n Job.create(\n :start_time => start_time, \n :end_time => end_time, \n :running_time => (end_time-start_time), \n :name => action_name\n )\n end",
"def set_recurrence\n @recurrence = Recurrence.find(params[:id])\n end",
"def create(opts)\n @frequence = opts[:frequence] if opts[:frequence].in? Recurrence::FREQUENCES\n @monthly = array_to_integer(opts[:monthly])\n @count = to_integer(opts[:count])\n @until = string_to_date(opts[:until])\n self\n end",
"def calculate_sequence\n old_sequence.split('')[1..-1].each(&method(:fill_recurrence))\n\n apply_recurrence\n\n recurrences.flatten.join\n end",
"def sequential_day\n puts \"AI.sequential_day = #{action_plan.sequential_day} + #{day-1}\"\n action_plan.sequential_day + day-1\n end",
"def next_collection\n # pry\n rule = IceCube::Rule.from_yaml(self.schedule)\n schedule = IceCube::Schedule.new(Time.now)\n schedule.add_recurrence_rule(rule)\n date = schedule.next_occurrence(Time.now)\n # puts date\n # date\n end",
"def recurrence_params\n params.require(:recurrence).permit(:title, :start_time, :description, :recurring)\n end",
"def create_inbetween_occurrences?\n return unless recurrence.present?\n\n recurrency&.to_i == 7 && recurrence.recurrency&.to_i == 14\n end",
"def to_occurrence(date)\n date = next_occurrence(date) if date.is_a?(Date)\n event = Event.new\n event.start_datetime = date\n event.end_datetime = date + duration\n event.title = title\n event.description = description\n event.location = location\n event.id = id\n event.user = user\n event.is_recurrence!\n event.set_as_persisted!\n event.freeze\n end",
"def workpattern(days,from_time,to_time,type)\n DAYNAMES[days].each {|day| @values[day].workpattern(from_time,to_time,type)} \n refresh\n end",
"def schedule(event_type, time, queue=nil, connection=nil)\n new_event = Event.new(@events.length+1, event_type, time, queue, connection) # adds id to event as well\n @events << new_event\n @events.sort_by!{ |event| event.time } # sorts events by time, to always get the next event\n return new_event\n end",
"def reschedule_at(current_time, attempts)\n current_time + ((attempts**4) + 1).hours\n end",
"def reschedule(time)\r\n \"missing time\" if time.nil?\r\n\r\n time_rufus = Rufus.to_datetime time\r\n\r\n @job.unschedule unless (self.time == :forever)\r\n\r\n @job = @scheduler.at time_rufus.to_s do\r\n @timed_out = true\r\n @subscribers.each { |object| object.timed_out }\r\n end\r\n\r\n @time = time\r\n end",
"def recurrence_to_events!(now = Time.now.utc)\n recurring.each {|r| r.recurrence_to_events!(now)}\n end",
"def schedule_every (freq, params={}, &block)\n\n params = prepare_params(params)\n params[:every] = freq\n\n first_at = params[:first_at]\n first_in = params[:first_in]\n\n #params[:delayed] = true if first_at or first_in\n\n first_at = if first_at\n at_to_f(first_at)\n elsif first_in\n Time.now.to_f + Rufus.duration_to_f(first_in)\n else\n Time.now.to_f + Rufus.duration_to_f(freq) # not triggering immediately\n end\n\n do_schedule_at(first_at, params, &block)\n end",
"def evaulate_schedule\n 5\n end",
"def initialize(time, name, interval, recurring, callback)\n @time = time\n @name = name\n @interval = interval\n @recurring = recurring\n @callback = callback\n @cancelled = false\n\n if @name == nil\n @name = Time.now.gmtime.to_f.to_s.to_sym\n end\n end",
"def start_new_cycle(time = Time.now)\n @cycle_start = time\n @cycle_index += 1\n end",
"def schedule_raids(array)\n array.each do |key, value1|\n value1['raids'].each do |value2|\n unless Time.parse(value2['0']).past?\n new_cron(\n value2['0'], key, value2['key'],\n \"**#{value2['name']} Raid** is starting now!\"\n )\n end\n unless Time.parse(value2['15']).past?\n new_cron(\n value2['15'], key, value2['key'],\n \"**#{value2['name']} Raid** is starting in 15 minutes!\"\n )\n end\n unless Time.parse(value2['30']).past?\n new_cron(\n value2['30'], key, value2['key'],\n \"**#{value2['name']} Raid** is starting in 30 minutes!\"\n )\n end\n unless Time.parse(value2['45']).past?\n new_cron(\n value2['45'], key, value2['key'],\n \"**#{value2['name']} Raid** is starting in 45 minutes!\"\n )\n end\n next if Time.parse(value2['60']).past?\n new_cron(\n value2['60'], key, value2['key'],\n \"**#{value2['name']} Raid** is starting in 1 hour!\"\n )\n end\n end\nend",
"def start=(time); end",
"def create\n\t\n #ESTO SE VA DESCOMENTAR CUANDO SE INSERTE EL START_DATE Y EL END_DATE DEL FORMULARIO DE RENEWAL\n puts 'Aki va el array de Renewal'\n puts system_renewal_params\n puts 'Aki termina el arrayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'\n contract = System::Contract.find(system_renewal_params[:contract_id])\n @email = contract.supplier.email\n @start_date=Date.new(system_renewal_params[\"start_date(1i)\"].to_i,system_renewal_params[\"start_date(2i)\"].to_i,system_renewal_params[\"start_date(3i)\"].to_i)\n @end_date=Date.new(system_renewal_params[\"end_date(1i)\"].to_i,system_renewal_params[\"end_date(2i)\"].to_i,system_renewal_params[\"end_date(3i)\"].to_i)\n\t\tt0=Time.new(system_renewal_params[\"start_date(1i)\"].to_i,system_renewal_params[\"start_date(2i)\"].to_i,system_renewal_params[\"start_date(3i)\"].to_i)\n t1=Time.new(system_renewal_params[\"end_date(1i)\"].to_i,system_renewal_params[\"end_date(2i)\"].to_i,system_renewal_params[\"end_date(3i)\"].to_i)\n \n\t puts 'Aki va el parametro start_date sssssssssssssssssssssssssssssssssss'\n puts t1\n if params[:notification_date].nil?\n file_yaml = YAML.load_file \"#{Rails.root}/config/config.yml\"\n @before_days = file_yaml[\"production\"]['notification_time'].to_i.days\n else\n @before_days = params[:notification_date].to_i.days\n end\n \n @recordar = t0 - @before_days\n @recordar2 = t1 - @before_days\n puts 'aki va el recordatorio al iniciar la renovacion'\n puts @recordar\n puts 'aki terminaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'\n puts @email\n puts 'aki termina emailllllllllllllllllllllllllllllllllllllllllllllllllllllll'\n \n @email_departamento = contract.device.location.email \n array_mailer = [@email, @email_departamento]\n \n @delayed_id_start = ApplicationMailer.delay(run_at: @recordar).send_mail(array_mailer, contract,'create_renewal', @start_date, @end_date)\n @delayed_id_end = ApplicationMailer.delay(run_at: @recordar2).send_mail(array_mailer, contract,'create_renewal', @start_date, @end_date)\n \n\t@start_date_google=system_renewal_params[\"start_date(1i)\"].to_s + '-' + system_renewal_params[\"start_date(2i)\"].to_s + '-' + system_renewal_params[\"start_date(3i)\"].to_s + 'T10:00:52-05:00'\n\t@end_date_google=system_renewal_params[\"end_date(1i)\"].to_s + '-' + system_renewal_params[\"end_date(2i)\"].to_s + '-' + system_renewal_params[\"end_date(3i)\"].to_s + 'T10:00:52-05:00'\n\t@x=System::Contract.find(system_renewal_params[:contract_id])\n\t@google_event_start = System::Renewal.event_insert(@start_date_google,@start_date_google,@x.description,'neuro')\n @google_event_end= System::Renewal.event_insert(@end_date_google,@end_date_google,@x.description,'neuro')\n\n\t@system_renewal = System::Renewal.new(contract_id: system_renewal_params[:contract_id], start_date: @start_date, end_date: @end_date, monto: system_renewal_params[:monto], google_event_start: @google_event_start, google_event_end: @google_event_end, delayed_id_start: @delayed_id_start.id, delayed_id_end: @delayed_id_end.id)\n\n respond_to do |format|\n if @system_renewal.save\n @system_renewal.created_at.in_time_zone\n \n \n\tformat.html { redirect_to @system_renewal, notice: 'Renewal was successfully created.' }\n format.json { render :show, status: :created, location: @system_renewal }\n format.js { redirect_to @system_renewal, notice: 'Renewal was successfully created.' }\n else\n format.html { render :new }\n format.json { render json: @system_renewal.errors, status: :unprocessable_entity }\n format.js { render :new }\n end\n end\n end",
"def generate_schedule\r\n match_list = make_match_list\r\n schedule = make_empty_schedule\r\n # pp match_list\r\n # pp match_list.size\r\n\r\n scheduled_matches = []\r\n referee_count = 0\r\n move_to_next_slot = false\r\n\r\n schedule.each do |day|\r\n # puts \"#{day[:day]}\"\r\n day[:slots].each do |slots|\r\n # puts \" #{slots[:time]}\"\r\n\r\n match_count = -1\r\n move_to_next_slot = false\r\n match_to_validate = {}\r\n\r\n slots[:matches].each do |match|\r\n # puts \" scheduled (#{scheduled_matches.size})\"; pp scheduled_matches\r\n # puts \"match list (#{match_list.size})\"; pp match_list\r\n # puts \" to_val: \"; pp scheduled_matches\r\n while(!validate_rest_time(match_to_validate, scheduled_matches))\r\n match_count += 1 #next match on match_list\r\n # puts \" CLASH: mc=#{match_count} \"\r\n match_to_validate = {:teams=>match_list[match_count],:day => day[:day], :time => slots[:time]}\r\n\r\n if(match_list.size == match_count)\r\n # puts \"----> Move to next slot\"\r\n move_to_next_slot=true\r\n break\r\n end\r\n end\r\n\r\n # puts \"move_to_next_slot: #{move_to_next_slot}\"\r\n \r\n unless(move_to_next_slot)\r\n scheduled_matches << match_to_validate\r\n match[:referees] = REFEREES[referee_count%REFEREES.size]\r\n match[:score] = [0,0]\r\n match[:teams] = match_list.delete_at(match_count)\r\n # print \"Adding match: \"; pp match\r\n # puts \"-\"*34\r\n referee_count += 1\r\n match_count = 0\r\n match_to_validate = {:teams=>match_list[match_count], :day => match[:day], :time => match[:time]}\r\n else\r\n break\r\n end\r\n\r\n end\r\n\r\n end\r\n end\r\n\r\n schedule\r\n end",
"def ring\n every(2) do\n broadcast(:time, Time.now.httpdate)\n end\n end",
"def recurrence\n return @recurrence\n end",
"def recurrence\n return @recurrence\n end",
"def generate_daytime_distribution \n \n end",
"def next_time(*args)\n cron_schedule.next_time(*args)\n end",
"def schedule_every(n, &block)\r\n\r\n while true do\r\n before = Time.now\r\n\r\n block.call\r\n \r\n elapsed = Time.now - before\r\n interval = n - elapsed\r\n \r\n @logger.debug \"orders processing/delivery take #{elapsed} seconds.\"\r\n \r\n sleep(interval) if interval > 0\r\n end\r\n\r\nend",
"def at_time(time)\n resource = @initial\n\n puts \"[START] initial: #{initial}\" if COPIOUS_DEBUGGING\n puts \"[START] time: #{time}\" if COPIOUS_DEBUGGING\n\n if intervals_at_time(@harvesters, time).size > 1\n generate_pairs(intervals_at_time(@harvesters, time)).each_with_index do |pair, index|\n puts \"[DEBUG] #{index}: STARTING LOOP\" if COPIOUS_DEBUGGING\n start_time = pair[0]\n next_time = pair[1]\n puts \"#{index}: start_time: #{start_time}\" if COPIOUS_DEBUGGING\n\n harvesters = @harvesters[start_time]\n puts \"#{index}: harvesters: #{harvesters}\" if COPIOUS_DEBUGGING\n\n period = next_time - start_time\n puts \"#{index}: period: #{period}\" if COPIOUS_DEBUGGING\n\n harvested = time_to_resource(period, harvesters)\n resource += harvested\n puts \"#{index}: harvested: #{harvested}\" if COPIOUS_DEBUGGING\n\n consumed = consumed_in_interval(start_time, next_time)\n resource -= consumed\n puts \"#{index}: consumed: #{consumed}\" if COPIOUS_DEBUGGING\n\n puts \"#{index}: resource: #{resource}\" if COPIOUS_DEBUGGING\n end\n else\n resource -= consumed_at_time(0)\n puts \"0: resource: #{resource}\" if COPIOUS_DEBUGGING\n end\n\n if resource < 0\n raise(InvalidEconomyError, \"The Starcraft economy does not allow deficit spending (deficit of #{resource} #{@type} at #{time} seconds).\")\n end\n\n puts \"[FINISH] at_time: #{resource}\" if COPIOUS_DEBUGGING\n resource\n end",
"def at ts\n spawn :@trange, time_to_long(ts)\n end",
"def linear(time, start, change, total_time)\n return change * time / total_time + start\n end",
"def parse_rrule recurrence\n rule = recurrence.find do |rec|\n /\\ARRULE/.match(rec)\n end\n\n return nil unless rule\n rule = rule.split(':')[1]\n params = {\n validations: {}\n }\n\n rule.split(';').each do |rule|\n (name, value) = rule.split('=')\n value.strip!\n case name\n when 'FREQ'\n params[:freq] = value.downcase\n when 'INTERVAL'\n params[:interval] = value.to_i\n when 'COUNT'\n params[:count] = value.to_i\n when 'UNTIL'\n params[:until] = Time.parse(value).utc\n when 'WKST'\n params[:wkst] = day_to_symbol(value)\n when 'BYSECOND'\n params[:validations][:second_of_minute] = value.split(',').collect(&:to_i)\n when 'BYMINUTE'\n params[:validations][:minute_of_hour] = value.split(',').collect(&:to_i)\n when 'BYHOUR'\n params[:validations][:hour_of_day] = value.split(',').collect(&:to_i)\n when 'BYDAY'\n dows = {}\n days = []\n value.split(',').each do |expr|\n day = day_to_symbol(expr.strip[-2..-1])\n # day with occurence\n if expr.strip.length > 2\n occ = expr[0..-3].to_i\n dows[day].nil? ? dows[day] = [occ] : dows[day].push(occ)\n days.delete(to_wday(day))\n else\n days.push to_wday(day) if dows[day].nil?\n end\n end\n params[:validations][:day_of_week] = dows unless dows.empty?\n unless days.empty?\n # days = days.sort_by do |day|\n # day\n # end\n params[:validations][:day] = days\n end\n when 'BYMONTHDAY'\n params[:validations][:day_of_month] = value.split(',').collect(&:to_i)\n when 'BYMONTH'\n params[:validations][:month_of_year] = value.split(',').collect(&:to_i)\n when 'BYYEARDAY'\n params[:validations][:day_of_year] = value.split(',').collect(&:to_i)\n when 'BYSETPOS'\n else\n raise \"Invalid or unsupported rrule command: #{name}\"\n end\n end\n\n params[:interval] ||= 1\n params.delete(:wkst) unless params[:freq] == 'weekly'\n params\n end",
"def schedule_at_absolute_with_state(state, due_time, action)\n raise 'action cannot be nil' unless action\n\n due_time = now + 1 if due_time <= now && @increment_on_simultaneous\n\n super(state, due_time, action)\n end",
"def payment_schedule(from_date = nil)\n schedule = []\n if recurring_payments?\n (0...recurring_number).each do |period|\n xdays = period * recurring_period\n schedule << { due_on: (from_date ? from_date.to_date + xdays.days : xdays),\n period_payment: payment_price,\n total_due: (period + 1) * payment_price }\n end\n # adjust the last entry\n schedule.last[:total_due] = price\n schedule.last[:period_payment] = price - (recurring_number - 1) * payment_price\n else\n schedule << { due_on: (from_date ? from_date.to_date : 0), period_payment: payment_price, total_due: payment_price }\n end\n schedule\n end",
"def create_time_slots\n return unless params[:start_time]\n\n start_time = Time.from_picker(params.delete(:start_time))\n end_time = Time.from_picker(params.delete(:end_time))\n\n return if end_time < start_time # Prevent infinite loop\n\n shift_length = params.delete(:shift_length).to_i\n shift_overlap = params.delete(:shift_overlap).to_i\n people_per_shift = params.delete(:people_per_shift)\n\n num_shifts = ((end_time - start_time) / shift_length).ceil\n return if num_shifts > 100 # Arbitrary threshold to prevent flooding database\n\n cur_time = start_time\n TimeSlot.transaction do\n while cur_time < end_time\n end_shift_time = cur_time + shift_length + shift_overlap\n TimeSlot.create! job: @job,\n start_time: cur_time,\n end_time: [end_shift_time, end_time].min,\n slots: people_per_shift\n cur_time += shift_length\n end\n end\n end",
"def add_task task\n time, obj = task\n if time.is_a? Numeric\n time = Time.now + time\n elsif time.is_a? DateTime\n time = time.to_time\n end\n @schedule << [time, obj]\n sort_schedule\n write_schedule\n end",
"def reschedule(job, time = T.unsafe(nil)); end",
"def next_scheduled_at\n reviewed_at + (24.hours * next_interval)\n end",
"def recurrence=(new_rule)\n if RecurringSelect.is_valid_rule?(new_rule)\n rule = RecurringSelect.dirty_hash_to_rule(new_rule).to_hash\n write_attribute(:recurrence, rule)\n else\n write_attribute(:recurrence, nil)\n end\n end",
"def weekly_time_generator(args = {:start_time => Time.now, :end_time => nil, :cron => ''})\n begin\n return [] if args[:cron].blank?\n\n # get cron as hash\n cron = cron_date args[:cron]\n\n # get the first value of the cron which is an integer and the pevious index\n # ex: cron = '41 * * * *' - we want to know that it starts every hour (prev index before the number) in the 41-st minute\n for k, v in cron do\n at = v\n break if v.class == 'Fixnum'\n # break in ruby continues the last iteration..\n every = k if v == '*'\n end\n\n changed_time = start_time = cron_generate_date args[:cron], args[:start_time]\n end_time = args[:end_time]\n\n # end_time is nil?\n end_time = Time.now.end_of_week if !end_time.respond_to? :year\n # end_time should not be longer than the end of this week\n end_time = end_time > start_time.end_of_week ? start_time.end_of_week : end_time\n\n all = []\n while changed_time <= end_time\n all << changed_time #changed_time.strftime(\"%d.%m.%Y %H:%M\")\n changed_time += 1.send(every)\n end\n\n all\n\n rescue => ex\n send_mail \"#{ex.class}: #{ex.message}. args: #{args}\" \n end\n\n end",
"def schedule(uri); end",
"def next_occurrence(after = Time.now.utc)\n occurrence_solver.next_occurrence(after)\n end",
"def create\n @event_recurrence = EventRecurrence.new(event_recurrence_params)\n @call = Call.new(call_params)\n @call.event_recurrence = @event_recurrence \n\n respond_to do |format|\n if @call.save && @event_recurrence.save\n format.html { redirect_to @call, notice: 'Call was successfully created.' }\n format.json { render :show, status: :created, location: @call }\n else\n format.html { render :new }\n format.json { render json: @call.errors, status: :unprocessable_entity }\n end\n end\n end",
"def calculate_next_run_at(start_time = Time.zone.now)\n ideal_next_run = ideal_next_run_from(start_time)\n\n if ideal_next_run == cron_worker_next_run_from(start_time)\n ideal_next_run\n else\n cron_worker_next_run_from(ideal_next_run)\n end\n end",
"def next_time (from=Time.now)\n\n @cron_line.next_time(from)\n end"
] |
[
"0.6596704",
"0.65345025",
"0.63191724",
"0.6300665",
"0.6257965",
"0.61090726",
"0.6005817",
"0.5987461",
"0.59022444",
"0.59022444",
"0.5860779",
"0.5807715",
"0.5760633",
"0.5742953",
"0.5735306",
"0.5671758",
"0.55982333",
"0.55778056",
"0.55713254",
"0.55325234",
"0.5504447",
"0.54956055",
"0.5455227",
"0.5427341",
"0.537998",
"0.5375399",
"0.537244",
"0.5341255",
"0.53395844",
"0.53124624",
"0.5311545",
"0.52896327",
"0.52818125",
"0.52805233",
"0.5279062",
"0.5279062",
"0.52674675",
"0.5263595",
"0.5255147",
"0.521982",
"0.52190393",
"0.5218576",
"0.52110606",
"0.5205045",
"0.52019626",
"0.52019626",
"0.516759",
"0.51567143",
"0.5152561",
"0.5151701",
"0.51260626",
"0.5119977",
"0.511721",
"0.5115286",
"0.5095859",
"0.50956535",
"0.50927305",
"0.5090091",
"0.5088035",
"0.50851405",
"0.50775784",
"0.50700617",
"0.5061443",
"0.50556713",
"0.50551933",
"0.50543636",
"0.50455636",
"0.5042196",
"0.50406915",
"0.50405586",
"0.5035444",
"0.5027739",
"0.5015326",
"0.50127536",
"0.50103825",
"0.5004503",
"0.49975118",
"0.49941644",
"0.49814823",
"0.49812037",
"0.49812037",
"0.497053",
"0.49596295",
"0.4953971",
"0.49531612",
"0.49403462",
"0.49376813",
"0.49321765",
"0.49316743",
"0.4918073",
"0.49171677",
"0.49163985",
"0.49102983",
"0.49036115",
"0.49001804",
"0.48822993",
"0.48777452",
"0.4873304",
"0.48695642",
"0.48665655",
"0.48637247"
] |
0.0
|
-1
|
Create a recurrence with dates except dates given
|
def except(date)
merge(except: date)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def run_exclusion(date)\n case @schedule.exclusion_met\n when 'next'\n return date + ((@schedule.exclusion_met_day - date.wday) % 7)\n when 'previous'\n return date - ((date.wday - @schedule.exclusion_met_day) % 7)\n when 'cancel'\n return run_cancel_exclusion(date)\n end\n\n return date\n end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def todays_recurrences\n today = Time.zone.today\n Recurrence.where('recurrences.date = ? OR recurrences.date ISNULL', today)\n end",
"def recurrence_to_events!(now = Time.now.utc)\n recurring.each {|r| r.recurrence_to_events!(now)}\n end",
"def run_cancel_exclusion(date)\n date += 1\n\n return find_next_non_specific(date) if @schedule.days_month != '' && @schedule.days_month !='specific'\n\n date += find_next_in_bitmask(get_days_month(date), date.day, month_length(date))\n date += periods_to_add(date).months\n\n # required for dates with day larger than 28 (not included in all months)\n if @schedule.days > 0\n while bitmask(@schedule.days)[date.day] != '1' do\n date += find_next_in_bitmask(get_days_month, date.day, month_length(date))\n date += periods_to_add(date).months\n end\n end\n\n return date\n end",
"def adjust_dates(date)\n first_date = planned.minimum(:actual_date)\n if first_date && first_date < date\n gap = date - first_date\n planned.each do |repetition|\n repetition.increment!(:actual_date, gap)\n end\n end \n end",
"def getDatesFrom(date)\n if recurring\n events = recurrence.getDatesFrom(date).sort_by &:start\n events = Event.submitted\n publishedEvents = Array.new\n events.each do |event|\n\n #This is defined in Event.state enum\n enumValue = 4\n kidsReadyToPublish = event.revisions.where(\"state = ?\", enumValue)\n if kidsReadyToPublish.count > 0\n if (kidsReadyToPublish.last.recurring)\n publishedEvents.push(kidsReadyToPublish.last)\n end\n else\n if !event.parent.present?\n publishedEvents.push(event)\n end\n end\n end\n return publishedEvents\n end\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def sub_days(number)\n o = dup\n while number > 0\n if (o.day - 1) >= number\n o.date = ZDate.format_date(o.year_str, o.month_str, o.day - number)\n number = 0\n else\n number -= o.day\n o.decrement_month!\n end\n end\n o\n end",
"def get_not_worked_days start_date, end_date, employee_id\n not_worked_days = []\n if start_date != \"\" && end_date != \"\"\n start_date = DateTime.parse(start_date)\n end_date = DateTime.parse(end_date)\n for i in 0..get_difference_days(start_date, end_date) + 1\n current_date = start_date + i.days\n if !is_weekend?(current_date) && didnt_come_to_work?(employee_id, current_date)\n not_worked_days << current_date\n end\n end\n end\n return not_worked_days\n end",
"def find_next_non_specific(date)\n values = ['first', 'second', 'third', 'fourth']\n\n case @schedule.days_month\n when 'last'\n d = Date.new(date.year, date.month, -1)\n\n return d if @schedule.days_month_day == nil\n\n d -= ((d.wday - @schedule.days_month_day) % 7)\n\n if d < date\n d = d.at_beginning_of_month\n\n months_since_startdate = (d.year * 12 + d.month) - (@schedule.start_date.year * 12 + @schedule.start_date.month)\n \n months_to_add = @schedule.period_num\n if (months_since_startdate % @schedule.period_num) > 0\n months_to_add = @schedule.period_num - (months_since_startdate % @schedule.period_num)\n end\n\n d += months_to_add.months\n return find_next_non_specific(d)\n end\n\n return d\n else\n if @schedule.days_month_day == nil\n if values.index(@schedule.days_month) + 1 < date.day\n months_to_add = @schedule.period_num\n months_since_startdate = (date.year * 12 + date.month) - (@schedule.start_date.year * 12 + @schedule.start_date.month)\n if (months_since_startdate % @schedule.period_num) > 0\n months_to_add = @schedule.period_num - (months_since_startdate % @schedule.period_num)\n end\n date += months_to_add.months\n end\n \n return Date.new(date.year, date.month, values.index(@schedule.days_month)+1) if @schedule.days_month_day == nil\n end\n \n d = Date.new(date.year, date.month, 1)\n d += (@schedule.days_month_day - d.wday) % 7\n d += (7 * values.index(@schedule.days_month))\n\n if d < date\n d = d.at_beginning_of_month\n\n months_since_startdate = (d.year * 12 + d.month) - (@schedule.start_date.year * 12 + @schedule.start_date.month)\n \n months_to_add = @schedule.period_num\n if (months_since_startdate % @schedule.period_num) > 0\n months_to_add = @schedule.period_num - (months_since_startdate % @schedule.period_num)\n end\n\n d += months_to_add.months\n\n d = Date.new(d.year, d.month, 1)\n d += (@schedule.days_month_day - d.wday) % 7\n d += (7 * values.index(@schedule.days_month))\n end\n\n return d\n end\n end",
"def calculate(frequency, frequency_integer, start_date, end_date)\n first_due_date = @calendar.roll_forward(start_date)\n base_dates = [first_due_date]\n return [base_dates, base_dates] if frequency == 'Once'\n\n frequency_symbol = get_frequency_symbol(frequency)\n grace_dates = [first_due_date.advance(frequency_symbol => frequency_integer)]\n\n base_date = start_date\n end_date = calculate_end_date(start_date, end_date)\n\n while base_date < end_date\n grace_date = base_date.advance(frequency_symbol => frequency_integer*2)\n base_date = base_date.advance(frequency_symbol => frequency_integer)\n base_dates << @calendar.roll_forward(base_date)\n grace_dates << @calendar.roll_forward(grace_date)\n end\n\n [base_dates, grace_dates]\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def build_dates\n from = @start_date || @settlement\n temp = from\n\n @accrual_dates = []\n @payment_dates = []\n @periods = []\n\n unless @first_coupon_date.nil?\n from = @first_coupon_date\n @accrual_dates << from\n end\n\n @accrual_dates = @frequency.build(from, @maturity)\n\n @accrual_dates.each do |date|\n @periods << @day_count.period(temp, date)\n @payment_dates << @business_day.next_day(date, @calendar)\n temp = date\n end\n end",
"def date_range( start_date, end_date )\n d_range = []\n cur_date = start_date \n\n until cur_date == end_date\n d_range << cur_date\n cur_date = Calendar.next_day( cur_date )\n end\n \n d_range << end_date\n end",
"def dates_to_wdays (start_date, end_date)\n start_date.upto(end_date).to_a.inject([]) do |dates, t|\n return dates if dates.include? t.wday\n dates << t.wday\n end\n end",
"def initialize(d=Date.today)\n if d.instance_of? Time\n rd = Date.civil(d.year, d.month, d.day)\n elsif d.instance_of? DateTime\n rd = Date.jd(d.jd)\n else\n rd = d.dup # always make a duplicate before modifying arguments\n end\n raise ArgumentError, \"Must pass Date, DateTime, or Time object\" unless rd.instance_of? Date\n @attachments = []\n @days = []\n rd -= 1 while rd.wday > 0\n # puts \"Got past first while\"\n # puts rd\n @days << rd\n for i in (1...7)\n @days[i] = (rd + i)\n end\n # puts \"Got past for\"\n @days.freeze\n end",
"def workdays(calendar = Spok.default_calendar)\n (@start_date..@end_date).to_a.delete_if{ |date| Workday.restday?(date, calendar: calendar) }\n end",
"def recurrence\n nil\n end",
"def extend_empty_end_date\n if self.end_date == self.start_date && !self.repeat_mode.rule.empty?\n self.end_date = Date.today + 10.year\n end\n return self\n end",
"def dates(n = 0, per_page = 10)\n @dates = []\n n.upto(n + per_page) do |n|\n if first_at.wday == wday\n date = first_at + (n * 7).days\n elsif first_at.wday > wday\n date = first_at + (7 - first_at.wday + wday).days + (n * 7).days\n elsif first_at.wday < wday\n date = first_at + (wday - first_at.wday).days + (n * 7).days\n end\n\n @dates << [date, WorkTime.find_by_start_date(date)]\n end\n return @dates\n end",
"def recurring(opts={})\n all({DataMapper::Events.recurrence_key.not => nil}.merge(opts))\n end",
"def extractDateList(start_date, end_date)\n obj_start=Date.new(start_date[0..3].to_i, start_date[4..5].to_i, start_date[6..7].to_i)\n obj_end=Date.new(end_date[0..3].to_i, end_date[4..5].to_i, end_date[6..7].to_i)\n date_num=(obj_end-obj_start+1).to_i\n date_array=Array.new\n date_num.times do |i|\n date_now=obj_start+i\n date_array << date_now.strftime(\"%Y%m%d\")\n end\n date_array\nend",
"def keep_days\n today = Time.new.strftime('%Y%m%d')\n from_date = Date.parse today\n to_date = (from_date + 1) - @keep_days.to_i # +1 added to from_date to exclude the last day from range\n\n kept_days = (to_date..from_date).map { |date| date.strftime('%Y%m%d') }.sort\n end",
"def generate_payments start_date, end_date\n \tdates = start_date.step( end_date ).\n \t select { |date| date.day == bill.due_on }.\n \t map { |date| Payment.from date, bill, self }\n end",
"def working_days_after(start_date, num_working_days)\n start_date = to_date(start_date)\n populate_public_holiday_collection_for_year(start_date.year)\n working_days_offset(start_date, num_working_days, :forward)\n end",
"def __evolve_date__\n __evolve_range_naive__.transform_values! {|v| v&.__evolve_date__ }\n end",
"def working_days_from_date(date)\r\n date = date + 1.day if date.cwday == 6\r\n day_of_the_week = date.cwday == 7 ? 0 : date.cwday\r\n calendar_days, business_days = self, self\r\n result_date = day_of_the_week + business_days\r\n if (result_date >= 6)\r\n business_days -= (6 - day_of_the_week)\r\n calendar_days += 2\r\n weeks = business_days / 5\r\n calendar_days += (weeks * 2)\r\n end\r\n date + calendar_days.days\r\n end",
"def calculated_dates\n [period1_from_date,period1_end_date,\n period2_from_date, period2_end_date] \n end",
"def apply_dates(attributes)\n attributes[:date] ||= []\n attributes[:date] << attributes[:date_published]\n attributes[:date] << attributes[:date_available]\n attributes[:date] << attributes[:date_accepted]\n attributes[:date] << attributes[:date_submitted]\n attributes[:date].uniq!\n end",
"def build_pending_invoices\n next_occurrences.map do |issue_date|\n invoice = self.becomes(Invoice).dup\n \n invoice.period = nil\n invoice.period_type = nil\n invoice.starting_date = nil\n invoice.finishing_date = nil\n invoice.max_occurrences = nil\n\n self.items.each do |item|\n nitem = Item.new(item.attributes)\n nitem.id = nil\n item.taxes.each do |tax|\n nitem.taxes << tax\n end\n invoice.items << nitem\n end\n\n invoice.recurring_invoice = self\n invoice.issue_date = issue_date\n invoice.due_date = invoice.issue_date + days_to_due.days if days_to_due\n invoice.sent_by_email = false\n invoice.meta_attributes = meta_attributes\n\n invoice.items.each do |item|\n item.description.sub! \"$(issue_date)\", invoice.issue_date.strftime('%Y-%m-%d')\n item.description.sub! \"$(issue_date - period)\", (invoice.issue_date - period.send(period_type)).strftime('%Y-%m-%d')\n item.description.sub! \"$(issue_date + period)\", (invoice.issue_date + period.send(period_type)).strftime('%Y-%m-%d')\n end\n\n invoice\n end\n end",
"def next_occurrences\n result = []\n\n occurrences = Invoice.belonging_to(id).count\n next_date = next_invoice_date\n max_date = [Date.current, finishing_date.blank? ? Date.current + 1 : finishing_date].min\n\n while next_date <= max_date and (max_occurrences.nil? or occurrences < max_occurrences) do\n result.append(next_date)\n occurrences += 1\n next_date += period.send period_type\n end\n\n result\n end",
"def update_relatives_dates\n return if new_record?\n return unless force_relatives_dates\n return unless starts_at_changed? || ends_at_changed?\n return unless recurrence.present?\n return unless future_relatives.any?\n\n future_relatives.each do |outing|\n outing.assign_attributes(metadata: outing.metadata.merge({\n starts_at: outing.metadata[:starts_at] + (self.metadata[:starts_at] - starts_at_was),\n ends_at: outing.metadata[:ends_at] + (self.metadata[:ends_at] - ends_at_was)\n }))\n end\n end",
"def get_dates(arr) \ndayDifference = Date.today - 7.days\narr.select do |d| \nif d.created_at.to_date > dayDifference \n d \n end\nend \nend",
"def working_days_before(start_date, num_working_days)\n start_date = to_date(start_date)\n populate_public_holiday_collection_for_year(start_date.year)\n working_days_offset(start_date, num_working_days, :backward)\n end",
"def date_calc(start,day_start,day_duration,round)\n time=start;schedule=[]\n round.size.times do |r|\n#print day_start+day_duration;print \"\\n\"\n if time >= day_start + day_duration\n#print time;print \"\\n\"\n time=day_start+1.day\n day_start = time\n end\n schedule[r] = time\n time+=HEAT_INTERVAL\n end\n\n return schedule\n end",
"def refresh_trip_schedules!\n excluded_dates = exclusion_dates.order(:excluded_date).map(&:excluded_date)\n\n # Try to build a list of valid trip schedules between the two trip\n # boundries\n updated_trip_schedules = [] \n working_date = boundry_start\n while working_date + duration.days < boundry_end do\n potential_start = working_date.to_date\n potential_end = (working_date + duration.days).to_date\n potential_range = (potential_start..potential_end)\n\n # tick the working date\n working_date = working_date + 1.day\n\n # Check trip day of week exclusions\n # next unless potential_range.any? { |date| dow_restriction_indexes.any? { |exclusion| exclusion.include? date.wday }}\n next unless dow_restriction_indexes.any? { |required_dows| required_dows.all? { |required_dow| potential_range.any? { |date| required_dow == date.wday }}}\n\n # Check excluded dates\n next if excluded_dates.any? { |excluded_date| (potential_range).include? excluded_date.to_date }\n\n # Create a trip schedule if it doesn't already exist\n ap potential_start\n updated_trip_schedules << TripSchedule.where(\n :trip => self,\n :start_date => potential_start.in_time_zone('EST'),\n :end_date => potential_end.in_time_zone('EST')\n ).first_or_initialize\n end\n\n self.trip_schedules = updated_trip_schedules\n save!\n end",
"def days(from_date = first_day.date, to_date = last_day.date)\n from_date = Date.new(2017, 1, 1)\n to_date = Date.new(2017, 12, 31)\n\n @days ||= workdays.select { |day| day.hours > 0 && (from_date..to_date).include?(day.date) }\n end",
"def create_inbetween_occurrences?\n return unless recurrence.present?\n\n recurrency&.to_i == 7 && recurrence.recurrency&.to_i == 14\n end",
"def date_range(items, from, to)\n\n date_range_items = items.reject{ |item| item[\"date\"] < from }\n date_range_items.reject!{ |item| item[\"date\"] > to }\n\n return date_range_items\nend",
"def schedule_repetition\n self.due = Date.today + interval\n self.studied_at = Date.today\n end",
"def payment_dates_array_up_to_date(date)\n start_enrollment = self.order('enrollment_date ASC').limit(1).first\n stop_enrollment = self.order('cancel_date DESC').limit(1).first\n \n if start_enrollment and stop_enrollment \n start = start_enrollment.enrollment_date\n stop = stop_enrollment.cancel_date\n payment_dates_array = []\n \n if date < stop_enrollment.cancel_date\n length_in_months = Date.length_in_months_including_last(start, date)\n else\n length_in_months = Date.length_in_months_including_last(start, stop)\n end\n \n length_in_months.times do |add_month|\n payment_dates_array << ((start + Payment::DATE_SPACER) >> add_month)\n end\n return payment_dates_array\n else\n return []\n end \n end",
"def to_occurrence(date)\n date = next_occurrence(date) if date.is_a?(Date)\n event = Event.new\n event.start_datetime = date\n event.end_datetime = date + duration\n event.title = title\n event.description = description\n event.location = location\n event.id = id\n event.user = user\n event.is_recurrence!\n event.set_as_persisted!\n event.freeze\n end",
"def get_all_paydates_on_days(start_date, end_date, valid_days)\r\n #end the range here instead of end_date so that any payday failling between end_date and this will be included, which will then get paid inside start_date...end_date\r\n first_valid_payday_outside_range = get_next_valid_paydate(end_date)\r\n\r\n result = (start_date..first_valid_payday_outside_range).to_a.select! {|day| is_corresponding_paydate?(valid_days, day)}\r\n result.map! {|day| get_last_valid_paydate(day)}\r\n result.keep_if {|day| (start_date...end_date).cover?(day) }\r\n end",
"def cutoff_date\n case date.wday\n when 0\n date + (weeks.to_i * 7)\n when 1\n date + (weeks.to_i * 7) - 1\n when 2\n date + (weeks.to_i * 7) - 2\n when 3\n date + (weeks.to_i * 7) - 3\n when 4\n date + (weeks.to_i * 7) - 4\n when 5\n date + (weeks.to_i * 7) - 5\n when 6\n date + (weeks.to_i * 7) + 1\n end\n end",
"def each_days(n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt.to_date + offset }\n s.increment { |dt,i| dt.to_date + i }\n s.span { |dt| dt.to_date + dur }\n end\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).reduce([]) do |output, el|\n if not_repeat_year?(el)\n output << el\n else\n output\n end\n end\nend",
"def no_repeats(year_start, year_end)\n no_repeats = []\n (year_start..year_end).each do |yr|\n no_repeats << yr if no_repeat?(yr)\n end\n\n no_repeats\nend",
"def dates(start_at, end_on)\n start_at.to_datetime.step(end_on).select { |d| d.cwday == @day }\n end",
"def unpublish\n if !recurring\n unpublish_self\n end\n if owner_of_recurrence\n recurrence.unpublish_complete\n end\n if recurring_but_no_owner\n #Create an exclude for our recurrence\n Exclude.create(date: self.start, recurrence: recurrence.owner.recurrence)\n #We're no longer part of that recurrence\n self.recurrence = nil\n #unpublish us\n unpublish_self\n\n end\n\n end",
"def setup_range(date)\n diff = date.wday - self.class.windex(start_wday)\n @first = date - (diff + ((diff < 0) ? DAYS : 0))\n @last = @first + DAYS - 1\n end",
"def next_occurrence(from_date)\n residue = @residue - residue_for(from_date)\n date = move_by from_date, residue.modulo(interval)\n time = Time.new(date.year, date.month, date.day, start_time.hour, start_time.min, start_time.sec)\n if (exx = exclusions.detect {|rule| rule.violated_by? time})\n if stops_by && time > stops_by\n nil\n else\n next_occurrence(move_by time, 1)\n end\n else\n time\n end\n end",
"def add_to_dates(start_date, end_date, new_occupancy)\n current_date = start_date.dup\n \n until current_date == end_date\n date_obj = find_date(current_date)\n \n if date_obj \n date_obj.add_occupancy(new_occupancy)\n else\n new_date_obj = Hotel::Date.new(current_date)\n @dates << new_date_obj\n new_date_obj.add_occupancy(new_occupancy)\n end\n \n current_date += 1\n end\n end",
"def recalculate_dates(date = nil)\n if self.standing_line_items.count > 0\n date ||= Date.current\n current = date.in_time_zone(self.vendor.time_zone)\n self.standing_order_schedules.where(\"deliver_at > ? and created_at is null\", current).update_all(visible: false)\n current_next = current\n mlt = max_lead_time\n\n start_next = self.start_at.in_time_zone(self.vendor.time_zone)\n # allow start_at to be the first date selected if lead_time is met based on current date\n if current_next + mlt.days > start_next\n start_next += mlt.days\n end\n\n if current_next > start_next\n self.calculate_next(current_next, self.vendor, self.max_lead_time)\n else\n self.calculate_next(start_next, self.vendor, self.max_lead_time)\n end\n end\n end",
"def dates_ranges\n (1..8).to_a.collect do |i|\n {\n start_date: i.days.ago,\n end_date: DateTime.now,\n num_of_days: i + 1\n }\n end\n end",
"def pro_rated_days\n _date_begin = pro_rata_start_date\n _date_end = subscription_start_date\n if _date_begin.blank? || _date_end.blank?\n 0\n else\n ((_date_end - _date_begin) / 1.day).round(0).to_i # n days\n end\n end",
"def getSundays(d1,d2)\n d1 += 1 while (d1.wday != 0) # add days till starting on sunday\n sundays = []\n d1.step(d2,7) do |date| # move forward seven days for every sunday\n sundays .push date\n end\n sundays\nend",
"def add_days(date, n)\n date + n * DAY\n end",
"def no_repeats(start_year, end_year)\n (start_year..end_year).to_a.select { |year| no_repeat?(year) }\nend",
"def find_day_reservations(date)\n day_reservations = all_reservations.select do |number, reservation|\n start_date = reservation.check_in\n end_date = reservation.check_out\n (start_date...end_date).include?(Date.parse(date)) && reservation.status == :CONFIRMED\n end\n \n return day_reservations\n end",
"def getFirstSundays(d1,d2)\n d1 += 1 while (d1.mday != 1) unless d1.mday == 1\n firstSundays = []\n while d1 < d2\n d1 = d1 >> 1 # add a month\n firstSundays .push d1 if d1.wday == 0\n end\n firstSundays\nend",
"def payment_schedule(from_date = nil)\n schedule = []\n if recurring_payments?\n (0...recurring_number).each do |period|\n xdays = period * recurring_period\n schedule << { due_on: (from_date ? from_date.to_date + xdays.days : xdays),\n period_payment: payment_price,\n total_due: (period + 1) * payment_price }\n end\n # adjust the last entry\n schedule.last[:total_due] = price\n schedule.last[:period_payment] = price - (recurring_number - 1) * payment_price\n else\n schedule << { due_on: (from_date ? from_date.to_date : 0), period_payment: payment_price, total_due: payment_price }\n end\n schedule\n end",
"def gen_date(documents, events)\n today = Date.today\n dates = (documents + events).map { |doc|\n # For each item, parse it's last value into a date\n begin\n Date.parse doc.last\n rescue\n nil\n end\n # Reject any dates that are nil\n # Select those dates that are before today (have already happened)\n }.reject { |date| date.nil? }.select { |date| date <= today }.reverse\n\n # Choose the most recent date\n dates.last\nend",
"def build_transactions_next_retry_date!\n (transactions || []).each do |transaction|\n # Filter attempts matching that transaction and SCHEDULED for retry\n transaction.next_retry_date = (payment_attempts || []).select do |attempt|\n ((attempt.transaction_id && attempt.transaction_id == transaction.transaction_id) ||\n (attempt.transaction_external_key && attempt.transaction_external_key == transaction.transaction_external_key)) &&\n attempt.state_name == 'SCHEDULED'\n end.map do |attempt|\n attempt.effective_date\n end.first\n end\n end",
"def regular_days_hash(regular_days, date_from, date_to)\n regular_days_hash = {}\n regular_days.each do |day|\n regular_days_hash[day.date.to_s] = day if day.date >= date_from && day.date <= date_to\n end\n regular_days_hash\n end",
"def schedule(start_date, end_date, options = {})\n\t\t\tdates = (Date.parse(start_date)...Date.parse(end_date)).to_a\n\t\t\tif options[:exclude_weekends]\n\t\t\t\tdates.delete_if do |d|\n\t\t\t\t\td.wday == 0 || d.wday == 6\n\t\t\t\tend\n\t\t\tend\n\t\t\tif excludes = options[:exclude_dates]\n\t\t\t\tdates -= excludes.map {|d| Date.parse(d)}\t\n\t\t\tend\n\t\t\t@sprint.schedule = dates\n\t\tend",
"def generate from, upto\n events = []\n from.upto(upto).map { |date|\n wdays.each { |day| day.generate date, events }\n }\n events\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select{|yr|not_repeat_year?(yr)}\nend",
"def invalid_dates\n self.listing.reservations.each do |reservation|\n existing_reservations = reservation.checkin..reservation.checkout \n if existing_reservations.include?(self.checkin) || existing_reservations.include?(self.checkout)\n errors.add(:checkin_taken, \"The date is already taken\")\n end\n end \n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select { |e| not_repeat_year?(e) }\nend",
"def no_repeats(year_start, year_end)\n result = []\n (year_start..year_end).each do |yr|\n result << yr if no_repeat?(yr)\n end\n result\nend",
"def reschedule_on_with_earlier_date!(date)\n return if date.nil?\n\n if start_date.blank? || start_date != date\n if due_date.present?\n self.due_date = RedmineBetterGanttChart::Calendar.workdays_from_date(date, duration - 1)\n end\n self.start_date = date\n save\n end\n end",
"def add_working_days(date, working_days)\n if working_days > 0\n weeks = working_days / (7 - non_working_week_days.size)\n result = weeks * 7\n days_left = working_days - weeks * (7 - non_working_week_days.size)\n cwday = date.cwday\n while days_left > 0\n cwday += 1\n unless non_working_week_days.include?(((cwday - 1) % 7) + 1)\n days_left -= 1\n end\n result += 1\n end\n next_working_date(date + result)\n else\n date\n end\n end",
"def slice_instances_by_date(instances)\n instance_dates = instances.collect{|i| instance_date(i)}.sort.uniq\n instance_dates = instance_dates.slice_when{|prev, curr| prev != curr-1.day}.to_a\n\n group = {}\n\n instance_dates.each_with_index do |date_range, i|\n date_range.each do |date|\n group[i] ||= []\n group[i].push(instances.select{|i| instance_date(i)==date})\n end\n end\n\n group.inject({}) do |h,(k,v)|\n h[k] = v.flatten unless v.empty?\n h\n end.values.reject(&:empty?)\n end",
"def unavailable_dates\n errors[:base] << \"Unavailable dates.(-1)\" if start_date.present? && start_date < Time.zone.today\n errors[:base] << \"Unavailable dates.(-2)\" if (start_date.present? && end_date.present?) && start_date >= end_date\n errors[:base] << \"Unavailable dates.(-3)\" if (start_time.present? && end_time.present?) && start_time >= end_time\n errors[:base] << \"Unavailable dates.(-4)\" if (day_of_week.present? && week_of_month.present?) && ([0,1].exclude?(day_of_week) && week_of_month == 6)\n end",
"def recurring; end",
"def date_sub(expr, interval)\n interval = if interval.is_a?(Hash)\n h = {}\n interval.each{|k,v| h[k] = -v unless v.nil?}\n h\n else\n -interval\n end\n DateAdd.new(expr, interval)\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).reduce([]) do |arr, year|\n if not_repeat_year?(year)\n arr << year\n else\n arr\n end\n end\nend",
"def next_working_date(date)\n cwday = date.cwday\n days = 0\n while non_working_week_days.include?(((cwday + days - 1) % 7) + 1)\n days += 1\n end\n date + days\n end",
"def range_check(date)\n if date < @start_date\n # puts \"Reconstruindo calculadora de feriados pois dia #{date} eh menor que #{@start_date} -> #{@end_date}\"\n build(date - 2.days, @end_date, @holidays)\n elsif date > @end_date\n # puts \"Reconstruindo calculadora de feriados pois dia #{date} eh maior que #{end_date}\"\n build(@start_date, date + 252.days, @holidays)\n end\n end",
"def set_day_if_discarded; end",
"def every(step)\n c_time = self.begin.to_datetime\n finish_time = self.end.to_datetime.end_of_day\n f_compare = exclude_end? ? :< : :<=\n\n arr = []\n while c_time.send(f_compare, finish_time)\n arr << c_time.to_date\n c_time = c_time.advance(step)\n end\n arr\n end",
"def recurrence\n { ATTR_RECURRENCE[@attribute] => 1 }\n end",
"def get_dates_matche (date_matche,days_game)\n flag_continue=true\n while flag_continue do\n date_matche = date_matche + 1.days\n day_week=date_matche.wday\n if days_game.include?(day_week.to_s)\n return date_matche\n end \n end\n end",
"def stop_date\n\t\t#return Date.new(y=year+1, m=START_MONTH, d=START_DAY) - 1\n\t\treturn start_date.next_year.prev_day()\n\tend",
"def recurrence\n unless read_attribute(:recurrence).empty?\n IceCube::Rule.from_hash(read_attribute(:recurrence))\n end\n end",
"def specific_days_in_semester\n date_start = USDateParse(self.start_date)#USDateParse(self.start_date)\n date_end = USDateParse(self.end_date)#USDateParse(self.end_date)\n curr_date = date_start\n date_hash = Hash.new(0)\n while curr_date <= date_end do\n if (! self.individual_dates_with_no_classes.include?(curr_date))\n date_hash[curr_date.cwday] += 1\n end\n curr_date += 1\n end\n return date_hash\n end",
"def from_date(date)\n return self if date.blank?\n\n date = date.to_date.beginning_of_day\n\n where(validity_start_date: date..)\n end",
"def generate_assistances_with_one_day_difference\n (0..2).each do |extra_day|\n create(:good_entry_assistance, \n happening_at: base_date + extra_day.days,\n employee: employee) \n end\n end",
"def memberships_to_notify(date)\n treatment_group_memberships\n .status_enrolled\n .joins(treatment_group: :reminder_templates)\n .where(\"date_trunc('day', experiment_inclusion_date) + make_interval(days := reminder_templates.remind_on_in_days) = ?\", date)\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select {|x| not_repeat_year?(x) }\nend",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).to_a.select { |year| not_repeat_year?(year) }\nend",
"def periods_critical_days(periods, date_from, date_to)\n critical_days = {}\n periods.each do |period|\n period.critical_days.each do |critical_day|\n if critical_day.date >= date_from && critical_day.date <= date_to\n critical_days[critical_day.date.to_s] = critical_day\n end\n end\n end\n critical_days\n end",
"def scheduled_projects_ics(start_date = Date.today, end_date = 8.days.from_now)\n calendar = Icalendar::Calendar.new\n selected_entries_started = entries.where(start_date: start_date.to_date...end_date.to_date).all\n selected_entries_ended = entries.where(end_date: start_date.to_date...end_date.to_date).all\n selected_entries_started.concat(selected_entries_ended).uniq.each do |entry|\n calendar.add_event(entry.to_ics)\n end\n calendar\n end",
"def process_recurrence(recurrence)\n return true unless recurrence.today?\n recurrence.update_job\n end"
] |
[
"0.64138234",
"0.63034934",
"0.62600774",
"0.61709964",
"0.614366",
"0.610442",
"0.60958767",
"0.60365075",
"0.595503",
"0.5881428",
"0.58470994",
"0.5805628",
"0.57816535",
"0.5770195",
"0.57643354",
"0.5682022",
"0.56628776",
"0.5660224",
"0.5619742",
"0.5619656",
"0.5565689",
"0.5498666",
"0.54779637",
"0.54682404",
"0.54519546",
"0.5434539",
"0.54327977",
"0.54264724",
"0.5423066",
"0.54210997",
"0.53861314",
"0.53784376",
"0.53636944",
"0.5355958",
"0.5355188",
"0.5328813",
"0.5327891",
"0.5327052",
"0.53253233",
"0.5309893",
"0.5304268",
"0.5292558",
"0.5288797",
"0.5262885",
"0.5247239",
"0.5240469",
"0.52384603",
"0.5232405",
"0.5230616",
"0.5227483",
"0.52218664",
"0.5208583",
"0.51914155",
"0.5190699",
"0.5189943",
"0.51725805",
"0.51710075",
"0.5165228",
"0.51636845",
"0.5163672",
"0.5156765",
"0.5130863",
"0.51227224",
"0.5118236",
"0.51143044",
"0.51055133",
"0.5094701",
"0.5090813",
"0.50706315",
"0.5062395",
"0.5057236",
"0.50453746",
"0.50410396",
"0.5035621",
"0.5033801",
"0.5033024",
"0.5032339",
"0.5028858",
"0.50288236",
"0.50283724",
"0.50227946",
"0.5021956",
"0.5017311",
"0.5012296",
"0.49905008",
"0.49884656",
"0.4977016",
"0.49728644",
"0.49713647",
"0.49703556",
"0.49693084",
"0.49653912",
"0.4963912",
"0.49621844",
"0.49612263",
"0.49582246",
"0.49571845",
"0.49571404",
"0.49500144",
"0.49483353"
] |
0.54822737
|
22
|
Create a recurrence for given days of month
|
def day_of_month(days, *extras)
merge(mday: days.array_concat(extras))
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def increment_by_days count\n new_day = @day\n new_month = @month\n new_year = @year \n \n while count > 0\n days_to_next_month = days_in_month(new_month, new_year) - new_day + 1\n \n if (days_to_next_month > count)\n new_day = new_day + count\n count = 0 \n else\n new_day = 1\n new_month = new_month + 1\n if (new_month > 12)\n new_month = 1\n new_year = new_year + 1\n end\n \n count = count - days_to_next_month \n end\n end\n \n return MyDate.new new_day, new_month, new_year\n end",
"def make_days\n month = (1..@day_num).collect do |day|\n Day.new(Date.parse(\"#{@year}-#{@month}-#{day}\"))\n end\n\n month[0].date.wday.times { month.insert(0, Day.new(Date.new))}\n month\n end",
"def create_expenses\n expense_id = nil\n @expense = @account.expenses.create(expense_params)\n step = params[:expense_form][:recurrence].to_i\n\n if @expense.valid? && step != 0\n @expense.month_id = @expense.due_date.mon\n @expense.save \n start_month = @expense.due_date.mon + step\n number_of_months = step\n (start_month..12).step(step).each do |month|\n @expense = @account.expenses.new(expense_params)\n @expense.month_id = month\n @expense.due_date = @expense.due_date.to_date >> number_of_months\n number_of_months += step\n @expense.related_to = expense_id || @expense.id\n @expense.save\n expense_id ||= @expense.id\n end\n elsif @expense.valid?\n @expense.month_id = @expense.due_date.mon\n @expense.save\n end\n @expense.valid?\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def add_days(days = 1)\n days = days.to_i\n dim = self.days_in_month\n cur_day = @t_day\n next_day = cur_day + days\n \n if next_day > dim\n @t_day = 1\n self.add_months(1)\n days_left = (days - 1) - (dim - cur_day)\n self.add_days(days_left) if days_left != 0\n elsif next_day <= 0\n self.add_months(-1)\n @t_day = self.days_in_month\n days_left = days + cur_day\n self.add_days(days_left) if days_left != 0\n else\n @t_day = next_day\n end\n \n return self\n end",
"def monthly_dry_days(day)\n month_result_string(day).count('1')\n end",
"def count_of_days_in(month)\n 28 + (month + (month / 8)) % 2 + 2 % month + 2 * (1 / month)\nend",
"def each_july( n=1); each_monthnum(self.Jul,n); end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def create_date_value\n \n 1.upto(months.length) do |month|\n 1.upto(month) do |day|\n arr << [\"2015#{day}#{month}\", day_of_week]\n end\n end\nend",
"def get_days_month(date=nil)\n date ||= @date\n\n return @schedule.days if @schedule.days > 0\n\n if @schedule.days_month != 'specific'\n if @schedule.days_month == 'last' && @schedule.days_month_day == nil\n return 0b0 | (1 << date.at_end_of_month.day)\n end\n end\n\n return 0b0 | (1 << @schedule.start_date.day)\n end",
"def months() 30 * days end",
"def associated_day_of_months\n months = associated_months\n result = []\n \n\t start_date = event_start\n\t start_date = entry_deadline if is_opportunity?\n\t \t \n\t if !start_date.blank?\n #if we have no finish date then we only have the day of the event start\n if event_finish.blank?\n result = [100*start_date.month + start_date.day]\n else\n position_date = start_date\n while position_date <= event_finish\n result << 100*position_date.month + position_date.day\n position_date = position_date + 1.day\n break if result.length > 31 #no point iterating through years if we have all the days already\n end\n end\n end\n result.sort\n end",
"def day_months\n return create_monthly_dates day(1) if monthly?\n return mid_term_day_months if charged_in_code == LEGACY_MID_TERM\n day_months = []\n 1.upto(maximum_dates) do |index|\n break if empty_due_on? month: month(index), day: day(index)\n day_months << DueOnImportable.new(month(index), day(index))\n end\n day_months\n end",
"def each_may( n=1); each_monthnum(self.May,n); end",
"def each_june( n=1); each_monthnum(self.Jun,n); end",
"def find_next_non_specific(date)\n values = ['first', 'second', 'third', 'fourth']\n\n case @schedule.days_month\n when 'last'\n d = Date.new(date.year, date.month, -1)\n\n return d if @schedule.days_month_day == nil\n\n d -= ((d.wday - @schedule.days_month_day) % 7)\n\n if d < date\n d = d.at_beginning_of_month\n\n months_since_startdate = (d.year * 12 + d.month) - (@schedule.start_date.year * 12 + @schedule.start_date.month)\n \n months_to_add = @schedule.period_num\n if (months_since_startdate % @schedule.period_num) > 0\n months_to_add = @schedule.period_num - (months_since_startdate % @schedule.period_num)\n end\n\n d += months_to_add.months\n return find_next_non_specific(d)\n end\n\n return d\n else\n if @schedule.days_month_day == nil\n if values.index(@schedule.days_month) + 1 < date.day\n months_to_add = @schedule.period_num\n months_since_startdate = (date.year * 12 + date.month) - (@schedule.start_date.year * 12 + @schedule.start_date.month)\n if (months_since_startdate % @schedule.period_num) > 0\n months_to_add = @schedule.period_num - (months_since_startdate % @schedule.period_num)\n end\n date += months_to_add.months\n end\n \n return Date.new(date.year, date.month, values.index(@schedule.days_month)+1) if @schedule.days_month_day == nil\n end\n \n d = Date.new(date.year, date.month, 1)\n d += (@schedule.days_month_day - d.wday) % 7\n d += (7 * values.index(@schedule.days_month))\n\n if d < date\n d = d.at_beginning_of_month\n\n months_since_startdate = (d.year * 12 + d.month) - (@schedule.start_date.year * 12 + @schedule.start_date.month)\n \n months_to_add = @schedule.period_num\n if (months_since_startdate % @schedule.period_num) > 0\n months_to_add = @schedule.period_num - (months_since_startdate % @schedule.period_num)\n end\n\n d += months_to_add.months\n\n d = Date.new(d.year, d.month, 1)\n d += (@schedule.days_month_day - d.wday) % 7\n d += (7 * values.index(@schedule.days_month))\n end\n\n return d\n end\n end",
"def next_occurrence(start, continue=false)\n if @freq == :weekly\n wday = start.wday\n days = decode_by_day # i.e. [[1,1]] -\n # we want the first occurance where wday <= given day\n # example: schedule is [:mo,:we,:fr]\n # days = [[1,1],[1,3],[1,5]]\n # if our start is Sunday (wday=0), we want to stop on Monday (0 <= 1)\n # if our start is Tuesday (wday=2), we want to stop on Wednesday ( 2 <= 3)\n # if our start is Saturday (wday=6), we want the following Monday\n day_index = days.index { |day| wday <= day[1] }\n # if it is nil, we want the earliest day of the week\n if continue && day_index.nil?\n # I'd like to assume they are in order, but is that guaranteed?\n day_index = first_day\n # We then need to bump up the start a week\n start+=7\n elsif day_index.nil?\n return nil\n end\n # day will be the wday of the first matching date\n day = days[day_index][1]\n # we want to return the start plus the number of days till the firt match\n start + (day - wday)\n elsif @freq == :monthly && @by_day\n # Given the start we can grab month/year\n # go through each of the days and\n # return if it is greater than start\n # else ask if it needs to go to the following month (recursion)\n days = decode_by_day\n days.each do |d|\n day_in_month = day_of_month(start.year,start.month,*d, start.offset) # star to break array into two attributes\n return day_in_month if day_in_month >= start\n end\n # if it didn't find a match, then ask if it needs to continue\n if continue\n # Call the next month\n next_month = DateTime.new(start.year,start.month+1,1,0,0,0, start.offset)\n self.next_occurrence(next_month, continue)\n else\n nil\n end\n elsif @freq == :monthly && @by_month_day\n # Given start we know the day of month and we loop around\n # by_month_day until we find one bigger (unless negative). If not, retun nil unless continue = true,\n # in which case, grab the first one from by_month, and get it from the next month\n start_days_in_month = Time.days_in_month(start.month, start.year)\n neg_start = start.mday - start_days_in_month\n month_days = @by_month_day.split(',').map(&:to_i).sort\n day_index = month_days.index do |mday|\n if mday < 0\n # handle negatives\n neg_start <= mday\n else\n start.mday <= mday\n end\n end\n if !day_index.nil? && month_days[day_index] <= start_days_in_month\n day = month_days[day_index]\n DateTime.new(start.year, start.month, day,0,0,0, start.offset)\n elsif continue\n DateTime.new(start.year, start.month+1, month_days.first,0,0,0, start.offset)\n else\n nil\n end\n end\n end",
"def nwday_of_month(n)\n self + (nwday_day(n) - day).days\n end",
"def initialize(month, start_date)\n @start_date = start_date\n raise(ArgumentError, \"Must start on Sunday\") if start_date.wday != 0\n\n @days = []\n (start_date..start_date + 6).each do |date|\n @days << Day.new(month, date)\n end\n end",
"def day_of_month(*days)\n merge(mday: days)\n end",
"def each_february( n=1); each_monthnum(self.Feb,n); end",
"def generate_month_expenses\n Expense.all.each do |expense|\n MonthExpense.create(month_id: self.id, expense_id: expense.id)\n end\n end",
"def absolute_day(month, day)\n\n mo = {\n 1 => 31,\n 2 => 28,\n 3 => 31,\n 4 => 30,\n 5 => 31,\n 6 => 30,\n 7 => 31,\n 8 => 31,\n 9 => 30,\n 10 => 31,\n 11 => 30,\n 12 => 31,\n }\n\n # hash v. loop of arrays, computation v. memory tradeoff\n\n total_days = 0\n\n\n (1...month).each do |i| #1...month is (month-1)\n total_days += mo[i]\n end\n\n total_days + day\n\nend",
"def days; self * DAY; end",
"def days; self * DAY; end",
"def maximum_number_of_months_to_recur\n self.period.length_in_months -\n self.period.month_for_date(date)\n end",
"def each_december( n=1); each_monthnum(self.Dec,n); end",
"def months ; self * 30.days ; end",
"def each_months(n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt.to_date >> offset }\n s.increment { |dt,i| dt.to_date >> i }\n s.span { |dt| dt.to_date >> dur }\n end\n end",
"def each_monthnum(nmonth,n=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt >> (nmonth - dt.month)%12 }\n s.increment { |dt,i| dt.to_date >> i*12 } \n s.span { |dt| dt.to_date >> 1 }\n end\n end",
"def each_day_of_month(nday,dur=1)\n build_subrange do |s|\n s.step = 1\n s.adjust_range { |r| day_range(r) }\n s.offset do |dt| \n totdays = ((Date.civil(dt.year,dt.month,1) >> 1)-1).day\n dt.to_date + (nday - dt.day)%totdays\n end\n s.increment { |dt,i| dt.to_date >> i }\n s.span { |dt| dt.to_date + dur }\n end\n end",
"def nth_wday_of_month(w, d)\n self + (nth_wday_day(w, d) - day).days\n end",
"def update_monthly_happiness_distributions! \n HappinessEntry.beginning_of_month_days.each do |beginning_of_month_day|\n uid = uid_for_month(beginning_of_month_day)\n end_of_month_day = beginning_of_month_day.end_of_month\n entries_for_month = HappinessEntry.in_month(beginning_of_month_day, end_of_month_day)\n update_happiness_distribution! uid, :month, entries_for_month \n end\n end",
"def each_march( n=1); each_monthnum(self.Mar,n); end",
"def add_days(date, n)\n date + n * DAY\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def test_should_return_every_day_of_month\n assertion = Month.april(2003).every(:tuesday)\n assert_equal assertion.size, 5\n assert_equal assertion, [Date.new(2003,4,1),Date.new(2003,4,8),Date.new(2003,4,15),Date.new(2003,4,22),Date.new(2003,4,29)]\n end",
"def sub_days(number)\n o = dup\n while number > 0\n if (o.day - 1) >= number\n o.date = ZDate.format_date(o.year_str, o.month_str, o.day - number)\n number = 0\n else\n number -= o.day\n o.decrement_month!\n end\n end\n o\n end",
"def sequential_day\n puts \"AI.sequential_day = #{action_plan.sequential_day} + #{day-1}\"\n action_plan.sequential_day + day-1\n end",
"def date_calc(start,day_start,day_duration,round)\n time=start;schedule=[]\n round.size.times do |r|\n#print day_start+day_duration;print \"\\n\"\n if time >= day_start + day_duration\n#print time;print \"\\n\"\n time=day_start+1.day\n day_start = time\n end\n schedule[r] = time\n time+=HEAT_INTERVAL\n end\n\n return schedule\n end",
"def expression\n case frequency\n when :every\n DayOfWeek.new(day_of_week)\n else\n DayInMonth.new(day_of_week, frequency)\n end\n end",
"def extra_days(days_count, month_count, year_count, init_month, init_year)\n # Will keep increamenting them with surplus days\n days = days_count\n mth = init_month\n yr = init_year\n\n loop do\n days -= days_in_month(mth, yr)\n break if days <= 0\n mth += 1\n if mth > 12\n mth = 1; yr += 1\n end\n days_count = days\n end\n\n # Setting actual incremented values\n month_count += (mth - init_month)\n year_count += (yr - init_year)\n\n [days_count, month_count, year_count]\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def each_october( n=1); each_monthnum(self.Oct,n); end",
"def each_monday( n=1, offset=0, dur=1); each_wdays(self.Mon,n,offset,dur); end",
"def month\n running_days = 0\n DAYS_IN_MONTH.each_with_index do |days, idx|\n running_days += days\n return idx + 1 if self.day_of_year <= running_days\n end\n end",
"def create_results\n loop_start_date = start_date.at_beginning_of_month\n loop_end_date = end_date.at_beginning_of_month\n\n while loop_start_date < loop_end_date\n result_start_date = loop_start_date\n result_end_date = loop_start_date.next_month\n \n results.create(start_date: result_start_date, end_date: result_end_date, amount: 0, precision: 'month', status: 0)\n\n loop_start_date = result_end_date\n end\n end",
"def fixed_monthly_payment(amount, months, ir )\n amount*( ir * ( 1 + ir ) **months )/(( 1 + ir )**months - 1 )\nend",
"def days_in_month\n Time.send(\"month_days\", self.year, self.month)\n end",
"def days\n Advert.days_for_months(months)\n end",
"def days\n @days ||= months.map(&:days).flatten\n end",
"def test_should_retun_every_set_of_days_of_month_as_array\n assertion = Month.august(2006).every(:monday,:wednesday)\n # verify\n assert assertion.is_a?(Array)\n # check for data integrity\n assert_equal assertion.size, 9\n assert_equal assertion, [Date.new(2006,8,2),Date.new(2006,8,9),Date.new(2006,8,16),Date.new(2006,8,23),Date.new(2006,8,30),Date.new(2006,8,7),Date.new(2006,8,14),Date.new(2006,8,21),Date.new(2006,8,28)]\n end",
"def nwrug_meet_for year, month\n beginning_of_month = Date.civil(year, month, 1)\n nwrug = beginning_of_month + (18 - beginning_of_month.wday)\n nwrug += 7 if beginning_of_month.wday > 4\n\n # Make sure we skip to the next month if we've gone past this month's meet\n if nwrug < Date.today\n if month == 12\n month = 1\n year += 1\n else\n month += 1\n end\n nwrug = nwrug_meet_for year, month\n end\n\n nwrug\nend",
"def each_april( n=1); each_monthnum(self.Apr,n); end",
"def endless_numbered_days(year=2011,month=1)\n x = Date.new(year,month,-1).day\n y = Date.new(year,month,1).wday\n cal = {}\n 1.upto(x) do |i|\n cal[i] = [y]\n y += 1\n end\n return cal.to_json\n end",
"def find_months_to_generate\n @dates_of_each_month = []\n @dates = Event.all.pluck(:date)\n @dates.each do |date|\n @dates_of_each_month << date.beginning_of_month\n end\n @dates_of_each_month.uniq!\n end",
"def test_should_return_every_day_of_month_as_array\n assertion = Month.april(2003).every(:tuesday)\n assert_equal assertion.size, 5\n assert_equal assertion, [Date.new(2003,4,1),Date.new(2003,4,8),Date.new(2003,4,15),Date.new(2003,4,22),Date.new(2003,4,29)]\n end",
"def generate_daytime_distribution \n \n end",
"def decrement_by_days count\n new_day = @day\n new_month = @month\n new_year = @year \n \n while count > 0\n days_to_previous_month = days_in_month(new_month - 1, new_year) + new_day - 1\n \n if (new_day > count)\n new_day = new_day - count\n count = 0 \n else\n new_day = days_to_previous_month - count\n new_month = new_month - 1\n if (new_month < 1)\n new_month = 12\n new_year = new_year - 1\n end\n \n count = count - days_to_previous_month\n end\n end\n \n return MyDate.new new_day, new_month, new_year\n end",
"def discount_of_the_day(day)\n case day\n when (0..(DISCOUNT_PERIOD_1_START_DAY - 1)) then 0\n when (DISCOUNT_PERIOD_1_START_DAY..(DISCOUNT_PERIOD_2_START_DAY - 1)) then DISCOUNT_PERIOD_1_RATE\n when (DISCOUNT_PERIOD_2_START_DAY..(DISCOUNT_PERIOD_3_START_DAY - 1)) then DISCOUNT_PERIOD_2_RATE\n else DISCOUNT_PERIOD_3_RATE\n end\n end",
"def sequential_day\n ActionPlan.sequential_day_for(week,day)\n end",
"def setup_months(start_month, end_month)\n @months = []\n while start_month <= end_month\n @months << start_month\n start_month += 1\n end\n end",
"def solve( start = Date.new( 1901, 1, 1 ), stop = Date.new( 2000, 12, 31 ) )\n total = 0\n \n # Move to the first Sunday in the range, if not there already.\n start += (7 - start.wday) if !start.sunday?\n\n # Move forward a week at a time, counting the first-of-months we see.\n while start <= stop\n total += 1 if 1 == start.day\n start += 7\n end\n\n total\n end",
"def monthly\n end",
"def >>(months)\n y, m = (@year * 12 + (@month - 1) + months).divmod(12)\n m, = (m + 1) .divmod(1)\n d = @day\n d -= 1 until self.class.valid?(y, m, d)\n self.class.new(y,m,d)\n end",
"def distribute_days_evenly(allocated_days, available_days, num_of_rooms)\n allocation_keys = allocated_days.keys\n\n j = 0\n while j < (allocated_days.size * num_of_rooms)\n i = 0\n until i >= (allocation_keys.size - 1)\n month = allocation_keys[i]\n next_month = allocation_keys[i + 1]\n\n if (get_available_days(available_days, month) * num_of_rooms) > allocated_days[month] &&\n (allocated_days[month] % num_of_rooms != 0) &&\n (allocated_days[next_month] > (allocated_days.values.min * 0.75))\n allocated_days[month] += 1\n allocated_days[next_month] -= 1\n i += 2\n else\n i += 1\n end\n end\n j += 1\n end\n allocated_days\n end",
"def add_days(number)\n if number < 0\n return sub_days(number.abs)\n end\n o = dup # new ZDate object\n # Let's see what month we are going to end in\n while number > 0\n if o.days_left_in_month >= number\n o.date = ZDate.format_date(o.year_str, o.month_str, o.day + number)\n number = 0\n else\n number = number - 1 - o.days_left_in_month # it costs 1 day to increment the month\n o.increment_month!\n end\n end\n o\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def next_meeting(after_time = Time.now.utc )\n # puts \"Looking up next meeting after #{after_time}\"\n if recurrence_frequency.blank?\n return start_time\n end\n\n if after_time < start_time\n return start_time\n end \n\n after_time = after_time.local_from_utc(self.time_zone) \n\n\n # Advance the starting time in the case when it falls after the beginning of\n # a meeting on the same day. We do this so that we can use \"day precision\"\n # (PDate.day) in the Runt library instead of \"minute precision\" (PDate.min),\n # which performs terribly.\n start_time = start_time_local\n if(after_time.hour > start_time.hour or ( after_time.hour == start_time.hour and after_time.min > start_time.min))\n after_time = after_time + 1.day\n after_time = Time.gm(after_time.year, after_time.month, after_time.day, 0, 0)\n end\n\n case recurrence_frequency\n when 'daily'\n end_time = after_time + 25.hours \n # after_time -= 1.day\n start_date = PDate.day(after_time.year, after_time.month, after_time.day , after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'weekdays'\n # Make the range over 3 days so that Friday night searches will still turn\n # up Monday as the next day.\n end_time = after_time + 3.days\n start_date = PDate.day(after_time.year, after_time.month, after_time.day, after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'monthly'\n eom = (after_time + 40.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eom.year, eom.month, eom.day)\n when 'weekly'\n eow = (after_time + 8.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eow.year, eow.month, eow.day)\n when 'yearly'\n # Just doing \"after_time + 367.days\" results in a bit of a performance hit\n # as hundreds of days are compared. We'll try to narrow it a bit. Not too\n # much, because we don't have time to actually write unit tests and make\n # sure the narrowing code works. :) Which is why the comment is here.\n st = after_time + 250.days\n et = st + 150.days\n start_date = PDate.day(st.year, st.month, st.day)\n end_date = PDate.day(et.year, et.month, et.day)\n end \n # puts \" Range #{start_date.to_s} - #{end_date.to_s}\"\n d_range = DateRange.new(start_date, end_date)\n sched = Schedule.new\n event = Event.new((self.invitation.name rescue \"no name\"))\n sched.add(event,self.runt_expression)\n dates = sched.dates(event,d_range)\n\n next_mtg = dates.first\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, start_time_local.hour, start_time_local.min)\n result = nil\n begin\n result = next_mtg_time.local_to_utc(self.time_zone)\n rescue TZInfo::PeriodNotFound\n # This only happens when the time is during the one hour which is skipped\n # during the transition to DST. For example, only on Sun Mar 08 02:15:00\n # (see ticket #744).\n next_hour = start_time_local.hour + 1\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, next_hour, start_time_local.min)\n retry\n end\n return result\n end",
"def every (date, &block)\n #debugger\n # need a way to differentiate monthly from weekly (e.g. every monday)\n # need a way to designate once a month (e.g. first monday or third monday) @period=:incremental\n if (date == :monthly) or (date == :month)\n # need a way to reconcile incremental/monthly/duration\n #@period = :monthly\n @increment=1.month\n else\n #@period=:incremental\n @increment=date\n end\n instance_eval &block\n cleanup\n end",
"def each_january( n=1); each_monthnum(self.Jan,n); end",
"def count_wdays_on_first_of_months(start_date, end_date, day_of_week)\n days_count = 0\n \n if start_date.mday > 1\n start_date = (start_date >> 1) - start_date.mday + 1 # move to the 1st day of next month\n end\n \n while start_date < end_date\n days_count += 1 if start_date.wday == day_of_week\n start_date = start_date >> 1\n end\n \n days_count \nend",
"def solver(from_date, to_date, weekday)\n result = 0\n days_to_sunday = 7 - weekday\n new_date = from_date.increment_by_days days_to_sunday\n if (new_date.day == 1)\n result = result + 1\n end\n while new_date <= to_date\n if (new_date.day == 1)\n result = result + 1\n end\n new_date = new_date.increment_by_days 7\n end\n return result\nend",
"def month_days_interval(first_month_day)\n last_month_day = first_month_day.end_of_month\n\n first_week_day = first_month_day.beginning_of_week(:monday)\n last_week_day = last_month_day.end_of_week(:monday)\n\n while (last_week_day - first_week_day).to_i + 1 < DAYS_PER_MONTH\n last_week_day = last_week_day + 1.week\n end\n\n first_week_day .. last_week_day\n end",
"def days_in_month\n raw = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][self.month]\n self.month == 2 && leap_year? ? raw + 1 : raw\n end",
"def create(opts)\n @frequence = opts[:frequence] if opts[:frequence].in? Recurrence::FREQUENCES\n @monthly = array_to_integer(opts[:monthly])\n @count = to_integer(opts[:count])\n @until = string_to_date(opts[:until])\n self\n end",
"def period_in_words\n case recurring_month\n when 12\n 'yearly'\n when 1\n 'monthly'\n when 0\n \"once\"\n else\n \"every #{recurring_month} months\"\n end\n end",
"def test_should_retun_every_set_of_days_of_month\n assertion = Month.august(2006).every!(:monday,:wednesday)\n # verify\n assert assertion.is_a?(Hash)\n # monday assertions\n assert_equal assertion[:monday].size, 4\n assert_equal assertion[:monday], [Date.new(2006,8,7),Date.new(2006,8,14),Date.new(2006,8,21),Date.new(2006,8,28)]\n # wednesday assertions\n assert_equal assertion[:wednesday].size, 5\n assert_equal assertion[:wednesday],\n [Date.new(2006,8,2),Date.new(2006,8,9),Date.new(2006,8,16),Date.new(2006,8,23),Date.new(2006,8,30)]\n end",
"def effective_months\n return 0 if start_date > end_date\n y = (end_date.year - start_date.year) * 12\n m = (end_date.mon - start_date.mon)\n last_month_days = ((end_date.day - end_date.beginning_of_month.day) + 1).to_f / end_date.end_of_month.day\n first_month_days = ((start_date.end_of_month.day - start_date.day) + 1).to_f / start_date.end_of_month.day\n first_and_last = start_date.day - 1 == end_date.day ? 1 : last_month_days + first_month_days\n (y + m + first_and_last) - 1\n end",
"def referrals_needed_per_month\n 5 * monthly_transaction_goal\n end",
"def test_31day_mo\n Charges.new(Date.new(2011,01,15),\n Date.new(2011,02,15),\n\t\t1, 1, 20)\n charges = Charge.find_all_by_reservation_id 20\n assert_equal 1, charges.size\n assert_equal 1, charges[0].season_id\n assert_equal Date.new(2011,01,15), charges[0].start_date\n assert_equal Date.new(2011,02,15), charges[0].end_date\n assert_equal 1.0, charges[0].period.to_f\n assert_equal 288.0, charges[0].rate.to_f\n assert_equal 288.0, charges[0].amount.to_f\n assert_equal 0.0, charges[0].discount.to_f\n assert_equal Charge::MONTH, charges[0].charge_units\n end",
"def calorie_sum_by_day\n\n end",
"def month() end",
"def period\n case self.recurring_month\n when 12\n 1.year # 1.year != 12.months\n else\n self.recurring_month.months\n end\n end",
"def months; self * MONTH; end",
"def months ; Duration[self * 30 * 86400] ; end",
"def find_day_of_month(day=@day, first_day_of_month=@first_day_of_month)\r\n day = ((day - 1) + first_day_of_month) % 7\r\n return 7 if day == 0\r\n day\r\n end",
"def ops_calendar\n # setup calendar cells\n @today = Date.today - 3\n if @today.strftime(\"%a\") == \"Mon\"\n @start_date = @today\n else\n @start_date = @today\n until @start_date.strftime(\"%a\") == \"Mon\"\n @start_date -= 1\n end\n end\n @end_date = @start_date+21\n @date_range = (@start_date..@end_date)\n @weeks = @date_range.to_a.in_groups_of(3)\n\n\n end",
"def next_occurrences\n result = []\n\n occurrences = Invoice.belonging_to(id).count\n next_date = next_invoice_date\n max_date = [Date.current, finishing_date.blank? ? Date.current + 1 : finishing_date].min\n\n while next_date <= max_date and (max_occurrences.nil? or occurrences < max_occurrences) do\n result.append(next_date)\n occurrences += 1\n next_date += period.send period_type\n end\n\n result\n end",
"def fix_frequency\n return unless frequency.duration > 1.month\n if frequency.duration < 12.months\n if intervals.all? { |i| i.first_datetime.day == i.last_datetime.day }\n frequency.duration = frequency.units[:months].months\n end\n else\n if intervals.all? { |i| i.first_datetime.month == i.last_datetime.month && i.first_datetime.day == i.last_datetime.day }\n frequency.duration = (frequency.duration / 12.months).floor.years\n end\n end\n end",
"def periods_to_add(date=nil)\n date ||= @date\n case @schedule.period\n when 'weeks'\n weeks_to_add = 0\n if date.wday >= bitmask(@schedule.days).length\n weeks_since_startdate = (date - @schedule.start_date) / 7\n weeks_to_add = (@schedule.period_num - (weeks_since_startdate % @schedule.period_num)).to_i\n end\n\n return weeks_to_add\n when 'months'\n days = get_days_month(date)\n\n months_to_add = 0\n if date.day >= bitmask(days).length-1 || date.day <= bitmask(days).index('1')\n months_since_startdate = (date.year * 12 + date.month) - (@schedule.start_date.year * 12 + @schedule.start_date.month)\n \n if (months_since_startdate % @schedule.period_num) > 0\n months_to_add = @schedule.period_num - (months_since_startdate % @schedule.period_num)\n end\n end\n\n return months_to_add\n\n end\n end",
"def get_dates_matche (date_matche,days_game)\n flag_continue=true\n while flag_continue do\n date_matche = date_matche + 1.days\n day_week=date_matche.wday\n if days_game.include?(day_week.to_s)\n return date_matche\n end \n end\n end",
"def open_occurrences(days_out = 90, date_start = Time.zone.now)\n schedule = IceCube::Schedule.new(date_start)\n date_end = date_start + days_out.days\n\n # add a recurrence for each business day\n business_days.each do |bd|\n day = bd.name.downcase.to_sym\n schedule.add_recurrence_rule IceCube::Rule.weekly.day(day)\n end\n\n return schedule.occurrences(date_end)\n end",
"def mday() end",
"def each_days(n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt.to_date + offset }\n s.increment { |dt,i| dt.to_date + i }\n s.span { |dt| dt.to_date + dur }\n end\n end",
"def each_august( n=1); each_monthnum(self.Aug,n); end",
"def recurring; end",
"def add_months(months = 1)\n months = months.to_i\n cur_month = @t_month\n cur_day = @t_day\n next_month = cur_month + months.to_i\n \n #Check if we have to alter the amount of years based on the month-change.\n if next_month > 12 or next_month <= 0\n years = (next_month.to_f / 12.0).floor\n \n newmonth = next_month - (years * 12)\n if newmonth == 0\n newmonth = 12\n years -= 1\n end\n \n self.month = newmonth\n self.add_years(years) if years != 0\n else\n raise \"Invalid month: '#{next_month}'.\" if next_month <= 0 or next_month > 12\n @t_month = next_month\n @t_day = 1\n end\n \n \n #If the month changed, and the day was the last day of the previous month, and there isnt that many days in the new month, set the day to the last day of the current month.\n dim = self.days_in_month\n \n if dim < cur_day\n @t_day = dim\n else\n @t_day = cur_day\n end\n \n return self\n end"
] |
[
"0.6826446",
"0.65125054",
"0.6494034",
"0.63091743",
"0.6279078",
"0.62042826",
"0.6191677",
"0.6129483",
"0.5998871",
"0.5978166",
"0.5939013",
"0.59051806",
"0.5902541",
"0.58404195",
"0.583018",
"0.5819257",
"0.5808279",
"0.5802486",
"0.58024275",
"0.577403",
"0.57650954",
"0.5748897",
"0.57269216",
"0.5726142",
"0.57230073",
"0.57032466",
"0.57032466",
"0.57024205",
"0.5684982",
"0.5679537",
"0.56524324",
"0.56422687",
"0.56342536",
"0.56139797",
"0.55970395",
"0.5593296",
"0.5579656",
"0.5576728",
"0.5568705",
"0.5560193",
"0.55601496",
"0.5548681",
"0.55435705",
"0.553391",
"0.5497113",
"0.5496756",
"0.54902256",
"0.54828244",
"0.5475854",
"0.547529",
"0.5463082",
"0.54626834",
"0.5456301",
"0.54525703",
"0.5450637",
"0.544191",
"0.54324055",
"0.5431521",
"0.54291475",
"0.542705",
"0.54221725",
"0.5421116",
"0.54210573",
"0.54184854",
"0.54175466",
"0.5409009",
"0.54038763",
"0.5387864",
"0.53872615",
"0.5359776",
"0.535942",
"0.53587073",
"0.53544694",
"0.5351732",
"0.5350115",
"0.53476053",
"0.53446186",
"0.5343499",
"0.53327566",
"0.53274626",
"0.53235126",
"0.531935",
"0.53124875",
"0.53120464",
"0.5291211",
"0.5275104",
"0.5272496",
"0.52675545",
"0.5264199",
"0.52631265",
"0.5257206",
"0.5232565",
"0.52125704",
"0.52062976",
"0.5205757",
"0.51996756",
"0.519535",
"0.51933587",
"0.51922625",
"0.51752627"
] |
0.5536428
|
43
|
Create a recurrence for given days of week
|
def day_of_week(weekdays, *extras)
merge(day: weekdays.array_concat(extras))
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def weeks() 7 * days end",
"def solver(from_date, to_date, weekday)\n result = 0\n days_to_sunday = 7 - weekday\n new_date = from_date.increment_by_days days_to_sunday\n if (new_date.day == 1)\n result = result + 1\n end\n while new_date <= to_date\n if (new_date.day == 1)\n result = result + 1\n end\n new_date = new_date.increment_by_days 7\n end\n return result\nend",
"def week\n first_day_of_week = @date.monday\n \n days_of_week = []\n 7.times do |time|\n days_of_week << day_and_types(first_day_of_week + time.days)\n end \n \n days_of_week\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def next_week_in weeks\n Week.find_by(initial_day: initial_day+( weeks * 7.days))\n end",
"def each_wdays(wd,n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt.to_date + (wd - dt.to_date.wday)%7 + offset*7 }\n s.increment { |dt,i| dt.to_date + i*7 }\n s.span { |dt| dt.to_date + dur }\n end\n end",
"def each_wednesday(n=1, offset=0, dur=1); each_wdays(self.Wed,n,offset,dur); end",
"def days_to_add(desired)\n # c is current day of week, d is desired next day of week\n # f( c, d ) = g( c, d ) mod 7, g( c, d ) > 7\n # = g( c, d ), g( c, d ) <= 7\n # g( c, d ) = [7 - (c - d)] = 7 - c + d\n # where 0 <= c < 7 and 0 <= d < 7\n n = (7 - DateTime.now.wday + desired);\n (n > 7) ? n % 7 : n\nend",
"def new_schedule(*args)\n if !args.all? { |e| e.is_a?(Integer) && e >= 0 && e <= 6 }\n return \"Please enter a number from 0-6 where each number represents a day of the week. 0 represents Sunday, 1 represents Monday, etc.\"\n end\n schedule1 = Schedule.new(self.first_event, duration: self.duration_mins.minutes )\n schedule1.add_recurrence_rule Rule.weekly.day(args)\n self.schedule = schedule1\n self.save!\n end",
"def weeks ; self * 7.days ; end",
"def each_friday( n=1, offset=0, dur=1); each_wdays(self.Fri,n,offset,dur); end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def each_sunday( n=1, offset=0, dur=1); each_wdays(self.Sun,n,offset,dur); end",
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def days_in_week(*days)\n @test_time = @time if @test_time.nil?\n x_in_list_of_y(@test_time.wday, Configuration.parse_range(days,0...7).flatten)\n end",
"def getSundays(d1,d2)\n d1 += 1 while (d1.wday != 0) # add days till starting on sunday\n sundays = []\n d1.step(d2,7) do |date| # move forward seven days for every sunday\n sundays .push date\n end\n sundays\nend",
"def add_working_days(date, working_days)\n if working_days > 0\n weeks = working_days / (7 - non_working_week_days.size)\n result = weeks * 7\n days_left = working_days - weeks * (7 - non_working_week_days.size)\n cwday = date.cwday\n while days_left > 0\n cwday += 1\n unless non_working_week_days.include?(((cwday - 1) % 7) + 1)\n days_left -= 1\n end\n result += 1\n end\n next_working_date(date + result)\n else\n date\n end\n end",
"def sequential_day\n ActionPlan.sequential_day_for(week,day)\n end",
"def days_of_week\n\n # create an array for processing\n days_array = [sunday, monday, tuesday, wednesday, thursday, friday, saturday]\n int_array = Array.new\n for day in days_array\n day ? int_array.push(1) : int_array.push(0)\n end\n\n # process with little recursive function\n r(int_array, 0)\n # fix first value, see note below\n int_array[0] == -1 ? int_array[0] = 1 : nil\n\n # final passes, change values into useable string\n int_array[0] == 1 ? int_array[0] = 'Su' : nil\n int_array[1] == 1 ? int_array[1] = 'M' : nil\n int_array[2] == 1 ? int_array[2] = 'Tu' : nil\n int_array[3] == 1 ? int_array[3] = 'W' : nil\n int_array[4] == 1 ? int_array[4] = 'Th' : nil\n int_array[5] == 1 ? int_array[5] = 'F' : nil\n int_array[6] == 1 ? int_array[6] = 'Sa' : nil\n\n int_array.delete(0)\n int_array.map{ |x| x == -1 ? '-' : x}.uniq.join\n\n end",
"def each_saturday( n=1, offset=0, dur=1); each_wdays(self.Sat,n,offset,dur); end",
"def each_weeks(n=1, offset=0, dur=1)\n each_days(n*7, offset*7, dur*7)\n end",
"def working_days_from_date(date)\r\n date = date + 1.day if date.cwday == 6\r\n day_of_the_week = date.cwday == 7 ? 0 : date.cwday\r\n calendar_days, business_days = self, self\r\n result_date = day_of_the_week + business_days\r\n if (result_date >= 6)\r\n business_days -= (6 - day_of_the_week)\r\n calendar_days += 2\r\n weeks = business_days / 5\r\n calendar_days += (weeks * 2)\r\n end\r\n date + calendar_days.days\r\n end",
"def each_tuesday( n=1, offset=0, dur=1); each_wdays(self.Tue,n,offset,dur); end",
"def each_thursday( n=1, offset=0, dur=1); each_wdays(self.Thu,n,offset,dur); end",
"def weekday(days)\nt = Date.today\narr = []\n days.times do\n arr << \"ok\" if t.saturday? || t.sunday?; t = t - 1\n end\n arr.count\nend",
"def week; end",
"def week_days(options={}, &block)\n start_date = self\n result = []\n (start_date-wday_offset).step 7 do |a_day|\n a_day.week_day_start = self.week_day_start\n if block_given?\n yield a_day\n else\n result.push(a_day)\n end\n end\n result\n end",
"def calendar_wdays(starting_day = 0)\n start_week = Date.today.beginning_of_week + (starting_day - 1).days # In rails week start in monday and monday.wday is 1\n (start_week...start_week+7.days).collect { |day| I18n.l(day, :format => '%A') }\n end",
"def find_next_week\n if @schedule.days == 0\n date = @date + ((@schedule.start_date.wday - @date.wday) % 7) + (7 * ((@schedule.start_date - @date) % @schedule.period_num))\n return date\n else\n date = @date + find_next_in_bitmask(@schedule.days, @date.wday, 7)\n\n if @date.wday >= bitmask(@schedule.days).length\n date += periods_to_add * 7\n end\n\n return date\n end\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def nth_wday_day(w,d)\n 1 + (d - (wday - day + 1)) % 7 + w * 7\n end",
"def mweek; (5 - wday + day) / 7 end",
"def ops_calendar\n # setup calendar cells\n @today = Date.today - 3\n if @today.strftime(\"%a\") == \"Mon\"\n @start_date = @today\n else\n @start_date = @today\n until @start_date.strftime(\"%a\") == \"Mon\"\n @start_date -= 1\n end\n end\n @end_date = @start_date+21\n @date_range = (@start_date..@end_date)\n @weeks = @date_range.to_a.in_groups_of(3)\n\n\n end",
"def add_recurrence(type: :week, on: on = nil, at: at = nil)\n type = type.to_sym\n unless [:week, :day].include? type\n raise \"Type must be either :week or :day\"\n end\n if type == :week and (on.nil? or (on.is_a?(Array) and on.empty?))\n raise \"Weekdays must be specified when selecting the :week type\"\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if self.schedule.nil?\n schedule = Montrose::Schedule.new\n end\n if at.nil?\n raise \"Time must be specified in parameter 'at'\"\n else\n schedule.add Montrose.every(type, on: on, at: at).starts(created_at)\n self.write_attribute(self.class.schedulable_attribute, schedule)\n end\n end",
"def next_occurring(day_of_week)\n from_now = DAYS_INTO_WEEK.fetch(day_of_week) - wday\n from_now += 7 unless from_now > 0\n advance(days: from_now)\n end",
"def get_next_date_for_next_weekday(week_day)\n DateTime.now + days_to_add(week_day)\nend",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def next_weekday(date, weekdays)\n [weekdays].flatten.map{|wd| \n nwd = date - date.cwday + Date::WEEKDAYS.index(wd) + 1\n nwd += 7 if nwd <= date\n nwd\n }.sort[0]\n end",
"def nth_wday; (day - 1) / 7 end",
"def create\n @day ||= Weekday.day\n @days ||= Weekday.days\n @batch = Weekday.set_day(params[:weekday][:batch_id], params[:weekdays])\n flash[:notice] = t('weekday_create')\n end",
"def setup_weeks(week_start)\n a_date = self.first\n the_last = self.last\n @weeks = []\n\n while (a_date < the_last)\n @weeks << Koyomi::Week.new(a_date, week_start)\n a_date += WEEK_DAYS\n end\n @weeks\n end",
"def days_to_week_start(start_day = Date.beginning_of_week)\n start_day_number = DAYS_INTO_WEEK.fetch(start_day)\n (wday - start_day_number) % 7\n end",
"def date_calc(start,day_start,day_duration,round)\n time=start;schedule=[]\n round.size.times do |r|\n#print day_start+day_duration;print \"\\n\"\n if time >= day_start + day_duration\n#print time;print \"\\n\"\n time=day_start+1.day\n day_start = time\n end\n schedule[r] = time\n time+=HEAT_INTERVAL\n end\n\n return schedule\n end",
"def weekday()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Weekday::WeekdayRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def dayOfWeek\n days = 0;\n tempYear = MIN_YEAR\n while tempYear < @year\n days += SimpleDate.daysInYear(tempYear).to_i\n tempYear+=1\n end\n\n days = days + ordinalDate\n #puts \"days #{days}\"\n days = days % 7\n\n end",
"def nwday_day(n)\n w = n % 7\n 1 + (w - (wday - day + 1)) % 7 + n - w\n end",
"def update_weekly_happiness_distributions! \n HappinessEntry.beginning_of_week_days.each do |beginning_of_week_day|\n uid = uid_for_week(beginning_of_week_day)\n end_of_week_day = beginning_of_week_day.end_of_week\n entries_for_week = HappinessEntry.in_week(beginning_of_week_day, end_of_week_day)\n update_happiness_distribution! uid, :week, entries_for_week \n end\n end",
"def first_wday; (wday - day + 1) % 7 end",
"def next_working_date(date)\n cwday = date.cwday\n days = 0\n while non_working_week_days.include?(((cwday + days - 1) % 7) + 1)\n days += 1\n end\n date + days\n end",
"def next_weekday(weekday = 2)\n date = Date.today\n unless date.strftime(\"%w\") == weekday.to_s\n date += 1 + ((weekday -1 -date.wday) % 7)\n end\n date\n end",
"def weeks; self * WEEK; end",
"def weeks; self * WEEK; end",
"def week(date = Date.today)\n day = monday(date)\n (day..day + 6)\n end",
"def end_of_week; self + (6 - wday).days end",
"def weekdays\n wdays = []\n wdays << 0 if sun\n wdays << 1 if mon\n wdays << 2 if tue\n wdays << 3 if wed\n wdays << 4 if thu\n wdays << 5 if fri\n wdays << 6 if sat\n\n wdays\n end",
"def weeks\n result = end_week - start_week + 1\n weeks = Date.new(start_date.year, 12, 31).strftime('%W').to_i\n result < 0 ? result + weeks : result\n end",
"def calculate_workdays\n iteration_start_date = Date.parse(@iteration.start_date)\n iteration_end_date = Date.parse(@iteration.end_date)\n total_iteration_days = iteration_end_date - iteration_start_date + 1\n # number of total possible workdays within entire iteration\n total_workdays = 0\n curr_day = iteration_start_date\n for i in 1..total_iteration_days\n total_workdays += 1 if $conn.workspace.is_workday?(curr_day.to_s)\n curr_day += 1\n end\n total_workdays\n end",
"def workpattern(days,from_time,to_time,type)\n DAYNAMES[days].each {|day| @values[day].workpattern(from_time,to_time,type)} \n refresh\n end",
"def open_occurrences(days_out = 90, date_start = Time.zone.now)\n schedule = IceCube::Schedule.new(date_start)\n date_end = date_start + days_out.days\n\n # add a recurrence for each business day\n business_days.each do |bd|\n day = bd.name.downcase.to_sym\n schedule.add_recurrence_rule IceCube::Rule.weekly.day(day)\n end\n\n return schedule.occurrences(date_end)\n end",
"def next_occurrence(start, continue=false)\n if @freq == :weekly\n wday = start.wday\n days = decode_by_day # i.e. [[1,1]] -\n # we want the first occurance where wday <= given day\n # example: schedule is [:mo,:we,:fr]\n # days = [[1,1],[1,3],[1,5]]\n # if our start is Sunday (wday=0), we want to stop on Monday (0 <= 1)\n # if our start is Tuesday (wday=2), we want to stop on Wednesday ( 2 <= 3)\n # if our start is Saturday (wday=6), we want the following Monday\n day_index = days.index { |day| wday <= day[1] }\n # if it is nil, we want the earliest day of the week\n if continue && day_index.nil?\n # I'd like to assume they are in order, but is that guaranteed?\n day_index = first_day\n # We then need to bump up the start a week\n start+=7\n elsif day_index.nil?\n return nil\n end\n # day will be the wday of the first matching date\n day = days[day_index][1]\n # we want to return the start plus the number of days till the firt match\n start + (day - wday)\n elsif @freq == :monthly && @by_day\n # Given the start we can grab month/year\n # go through each of the days and\n # return if it is greater than start\n # else ask if it needs to go to the following month (recursion)\n days = decode_by_day\n days.each do |d|\n day_in_month = day_of_month(start.year,start.month,*d, start.offset) # star to break array into two attributes\n return day_in_month if day_in_month >= start\n end\n # if it didn't find a match, then ask if it needs to continue\n if continue\n # Call the next month\n next_month = DateTime.new(start.year,start.month+1,1,0,0,0, start.offset)\n self.next_occurrence(next_month, continue)\n else\n nil\n end\n elsif @freq == :monthly && @by_month_day\n # Given start we know the day of month and we loop around\n # by_month_day until we find one bigger (unless negative). If not, retun nil unless continue = true,\n # in which case, grab the first one from by_month, and get it from the next month\n start_days_in_month = Time.days_in_month(start.month, start.year)\n neg_start = start.mday - start_days_in_month\n month_days = @by_month_day.split(',').map(&:to_i).sort\n day_index = month_days.index do |mday|\n if mday < 0\n # handle negatives\n neg_start <= mday\n else\n start.mday <= mday\n end\n end\n if !day_index.nil? && month_days[day_index] <= start_days_in_month\n day = month_days[day_index]\n DateTime.new(start.year, start.month, day,0,0,0, start.offset)\n elsif continue\n DateTime.new(start.year, start.month+1, month_days.first,0,0,0, start.offset)\n else\n nil\n end\n end\n end",
"def each_days_of_week(*wdays)\n if wdays.empty?\n each_days\n else\n each_days.except {|dt| !wdays.include?(dt.wday) }\n end\n end",
"def week_payout(date = Date.current, start_day = \"monday\")\n if !date.is_a? Date\n puts \"Must pass in a date\"\n return\n end\n\n # make sure using rep_parent\n node = self.get_rep_parent\n\n # calculate start and end of week\n week_start = date.\n beginning_of_week(start_date = start_day.to_sym)\n week_end = date.\n end_of_week(start_date = start_day.to_sym)\n date_range = week_start..week_end\n \n # get payout of children\n child_payout = 0 \n node.children.each do |child|\n child_payout += child.week_payout(date, start_day)\n end\n\n # if no week requirement\n if node.is_infinite?\n # get all from this week\n week_reps = self.rep_parent.repititions.\n where(\"completed_date >= ? AND completed_date <= ?\",\n week_start, week_end)\n if week_reps >= node.count\n return node.reward + child_payout\n elsif Date.current > week_end\n return node.penalty + child_payout\n else\n return child_payout\n end\n \n end\n \n \n # there is a week requirement, get reward/ penalty\n act_payout = 0\n if node.state == Activity::COMPLETE and \n date_range.include? node.completed_date\n act_payout = node.reward\n elsif node.state == Activity::EXPIRED and\n date_range.include? node.expiration_date\n act_payout = -1 * node.penalty\n \n end\n \n return child_payout + act_payout\n end",
"def week_pattern\n year_weeks == 53 ? [5,4,5]+[4,4,5]*3 : [4,4,5]*4\n end",
"def day_of_week\n # Zellers: 0 = Saturday, 1 = Sunday, 2 = Monday, ..., 6 = Friday\n # day_of_week: 1 = Sunday, 7 = Saturday\n (zellers_congruence + 6) % 7\n end",
"def add_days(date, n)\n date + n * DAY\n end",
"def next_week(day = :monday)\n days_into_week = { :monday => 0, :tuesday => 1, :wednesday => 2,\n :thursday => 3, :friday => 4, :saturday => 5,\n :sunday => 6 }\n since(1.week).beginning_of_week.since(days_into_week[day].day).change(:hour => 0)\n end",
"def weekloop(sday,looptime,loopday)\r\n @sday = sday.to_date\r\n if @sday.wday < loopday\r\n @sday = @sday + (loopday - @sday.wday)\r\n elsif @sday.wday > loopday\r\n @sday = @sday - (@sday.wday - loopday) + 7\r\n end\r\n dayarray = []\r\n dayarray << @sday.to_s\r\n for i in 1...looptime do\r\n @sday = @sday + 7\r\n dayarray << @sday.to_date.to_s\r\n end\r\n return dayarray\r\n end",
"def populateWeek(timeS, course, duration, days, id, type)\n\n duration = duration*2 -1\n timeS = ((timeToDecimal(timeS)-8)*2).round\n\n if course !=''\n if type=='course'\n name = (course.faculty).to_s.upcase + (course.number).to_s\n elsif type == 'tutorial'\n name = (course.tutname).to_s.upcase\n else\n name = 'Course'\n end\n else\n name = 'NoName'\n end\n\n if days.include? \"Mo\"\n for i in 0..duration\n if @@mon[timeS + i][1] == false\n @@mon[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@mon[timeS + i][0])\n end\n end\n end\n if days.include? \"Tu\"\n for i in 0..duration\n if @@tue[timeS + i][1] == false\n @@tue[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@tue[timeS + i][0])\n end\n end\n end\n if days.include? \"We\"\n for i in 0..duration\n if @@wed[timeS + i][1] == false\n @@wed[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@wed[timeS + i][0])\n end\n end\n end\n if days.include? \"Th\"\n for i in 0..duration\n if @@thu[timeS + i][1] == false\n @@thu[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@thu[timeS + i][0])\n end\n end\n end\n if days.include? \"Fr\"\n for i in 0..duration\n if @@fri[timeS + i][1] == false\n @@fri[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@fri[timeS + i][0])\n end\n end\n end\n if days.include? \"Sa\"\n for i in 0..duration\n if @@sat[timeS + i][1] == false\n @@sat[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@sat[timeS + i][0])\n end\n end\n end\n if days.include? \"Su\"\n for i in 0..duration\n if @@sun[timeS + i][1] == false\n @@sun[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@sun[timeS + i][0])\n end\n end\n end\n end",
"def addDayOfWeekSpecification(time, dows)\n\t\tcurrentDow = time.wday\n\t\tnextDow = nil\n\t\tdows.each { |d|\n\t\t\tif d < currentDow\n\t\t\t\tdd = d + 7\n\t\t\telse\n\t\t\t\tdd = d\n\t\t\tend\n\t\t\tif nextDow.nil? or (dd < nextDow)\n\t\t\t\tnextDow = dd\n\t\t\tend\n\t\t}\n\t\tif nextDow\n\t\t\treturn time + (nextDow - currentDow) * 24 * 60 * 60\n\t\tend\n\t\treturn time\n\tend",
"def createDailyWins(contest,cp)\n cdate = contest.start_date.to_date\n prize_per_day = 2\n while cdate <= contest.end_date.to_date\n for i in (1..prize_per_day)\n time = \"#{(0..23).to_a.sample}:#{(0..59).to_a.sample}:#{(0..59).to_a.sample} Rome\"\n wintime = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" \"+ time)\n wintime_end = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" 23:59:59\")\n \n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n while Instantwin.where(\"unique_id=?\",unique_id).present?\n @hash_counter += 1\n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n end\n \n iw = Instantwin.new\n iw.contest_periodicity_id = cp.id\n iw.title = \"Daily\"\n iw.time_to_win_start = wintime\n iw.time_to_win_end = wintime_end\n iw.unique_id = unique_id\n iw.save\n @hash_counter += 1\n end\n cdate += 1\n end\n end",
"def week\n working_date = DateTime.new(self.year, 1, 1)\n working_date.week_day_start = self.week_day_start\n working_date = (working_date-working_date.send(\"wday_offset\"))\n week_num = 0\n working_date.step(self) { |a_day| \n if a_day.wday == _week_day_numbers.first\n week_num += 1\n end\n }\n week_num\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def weeks ; Duration[self * 604800] ; end",
"def events_seven_days()\n events = []\n today = Date.today\n for i in 0..6 do\n events += events_by_date(today + i)\n end\n return events\nend",
"def week\n stamp = params[:stamp].to_i\n interval = (params[:interval] || 10).to_i\n plus_weeks = (params[:plus_weeks] || 0).to_i\n context = (params[:context] || 0).to_i == 1 ? true : false\n time = Time.at(stamp).utc\n\n # Calculate monday from given date\n wday = time.wday\n # Adjust for sunday when we want to start on a monday\n wday = 7 if wday == 0\n\n date = time - (wday.days - 1.days)\n\n date = date + plus_weeks.weeks\n\n # Number of days in week range if we add context, we add the surrounding weeks as well\n days = context ? (7 * 3) - 1 : 6\n\n # If context we'll start at the monday before\n if context\n date -= 7.days\n end\n\n\n\n week_data = []\n week_dates = []\n\n buckets = 0.step((60 * 24) - 1, interval).to_a\n\n (0..days).each do |day|\n interval_data = Hash.new { |h, k| h[k] = [] }\n\n data = GlucoseSensorData.by_day(date.to_date, :field => :timestamp)\n\n data.each do |datum|\n minutes = datum.timestamp.min + (datum.timestamp.hour * 60)\n # At first seems like a no op but this actually buckets minutes into intervals\n bucket = (minutes / interval) * interval\n\n interval_data[bucket] << datum\n end\n\n week_context = nil\n\n if context\n week_number = day / 7\n if week_number == 0\n week_context = \"before\"\n elsif week_number == 1\n week_context = \"current\"\n else\n week_context = \"after\"\n end\n else\n week_context = \"current\"\n end\n\n buckets.each do |bucket|\n datum = {}\n\n datums = interval_data[bucket]\n # Averages glucose values if there are more than one datum for that bucket\n if datums.length > 0\n datum[:glucose] = datums.inject(0.0) { |sum, d| sum + d.glucose } / datums.size\n #datum[:timestamp] = datums[0].timestamp.to_i\n end\n datum[:timestamp] = (date + bucket.minutes).to_i\n datum[:week_context] = week_context\n\n\n datum[:time] = bucket\n datum[:day] = date.strftime(\"%A\").downcase\n datum[:date] = date.to_i\n week_data << datum\n end\n\n week_dates.push({ :week_context => week_context, :day => date.strftime(\"%A\").downcase, :date => date.to_i })\n date += 1.days\n end\n\n render :json => { :data => week_data, :interval => interval, :week_dates => week_dates }\n end",
"def generate from, upto\n events = []\n from.upto(upto).map { |date|\n wdays.each { |day| day.generate date, events }\n }\n events\n end",
"def week_days\n {\n \"1\" => 'mon',\n \"2\" => 'tue',\n \"3\" => 'wed',\n \"4\" => 'thu',\n \"5\" => 'fri',\n \"6\" => 'sat',\n \"7\" => 'sun'\n }\n end",
"def last_week( remaining_days )\n pad = DPW - remaining_days.length\n\t\tremaining_days + Array.new( pad )\n end",
"def week_payout(date = Date.current, start_day = \"monday\")\n if !date.is_a? Date\n puts \"Must pass in a date\"\n return\n end\n\n # make sure using rep_parent\n node = self\n if !self.rep_parent.nil?\n node = self.rep_parent\n end\n \n # calculate start and end of week\n week_start = date.\n beginning_of_week(start_date = start_day.to_sym)\n week_end = date.\n end_of_week(start_date = start_day.to_sym)\n \n # get payout of children\n count = 0 \n node.children.each do |child|\n count = count + child.week_payout(date, start_day)\n end\n \n # get reward\n act_payout = 0\n week_reps = node.repititions.\n where(\"completed_date >= ? AND completed_date <= ?\",\n week_start, week_end)\n week_reps.each do |rep|\n if (rep.state == Activity::COMPLETE)\n act_payout = act_payout + node.reward\n end\n end\n \n # get penalty\n week_reps = node.repititions.\n where(\"expiration_date >= ? AND expiration_date <= ?\",\n week_start, week_end)\n week_reps.each do |rep|\n if (rep.state == Activity::EXPIRED)\n act_payout = act_payout - node.penalty\n end\n end\n \n return count + act_payout\n end",
"def create_weekly_tests()\n\n Rails.logger.info \"Checking for Weekly test runs\"\n\n # get instances of a weekly test run\n tests_to_add_to_stack = RecurringSchedule.get_weekly_tests_for_today()\n setup_scheduled_test(tests_to_add_to_stack)\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def set_time days\r\n days.each do |day,times|\r\n periods = times.split(\",\")\r\n periods.each do |period|\r\n start_time,end_time = period.split(\"-\")\r\n raise unless Time.parse(start_time) < Time.parse(end_time) \r\n #this will throw an exception if the day is invalid\r\n KlassSchedule.create :klass_id=>self.id,:start_time=>start_time,\r\n :end_time=>end_time,:day_of_week=>day\r\n end\r\n end \r\n end",
"def get_start_of_week(d)\n d -= DAY until d.monday?\n d\n end",
"def next(day)\n x_weeks_from_day(1, day)\n end",
"def expression\n case frequency\n when :every\n DayOfWeek.new(day_of_week)\n else\n DayInMonth.new(day_of_week, frequency)\n end\n end",
"def week_date_ranges\n (1..ReportWeeks).map do |week|\n begin_date = @start_date + (7*(week-1))\n begin_date .. (begin_date + 6)\n end\n end",
"def create_date_value\n \n 1.upto(months.length) do |month|\n 1.upto(month) do |day|\n arr << [\"2015#{day}#{month}\", day_of_week]\n end\n end\nend",
"def day_in_week(args = nil)\n if args\n args.each do |key, val|\n case key\n when :mfirst\n else\n raise ArgumentError, \"Invalid key in arguments: '#{key}'.\"\n end\n end\n end\n \n #This is a monday - 0. Use this date to calculate up against.\n def_date = Datet.new(1970, 1, 4)\n \n if self > def_date\n days = Datet.days_between(def_date, self)\n factor = days.to_f / 7.0\n diw = days - (factor.floor * 7)\n else\n days = Datet.days_between(self, def_date)\n factor = days.to_f / 7.0\n diw = days - (factor.floor * 7)\n diw = 7 - diw\n diw = 0 if diw == 7\n end\n \n #Monday should be the first day in the week.\n if args and args[:mfirst]\n if diw == 0\n diw = 6\n else\n diw -= 1\n end\n end\n \n return diw\n end",
"def _week_day_numbers\n week_day_start = self.week_day_start\n week_day_start.capitalize if week_day_start.is_a? String\n [0, 1, 2, 3, 4, 5, 6].partition {|on| on >= day_names.index(week_day_start)%7 }.flatten\n end",
"def day_of_week(*weekdays)\n merge(day: weekdays)\n end",
"def succ\n Day.new @@days[(@@days.find_index { |d| d == day } + 1) % 7]\n end",
"def weeks\n\t\tk = offset( first_day.cwday )\n\n [ first_week( k ) ] + middle_weeks( DPW - k )\n end",
"def calc(start, duration)\n return start if duration == 0\n a_day = SAME_DAY\n\n utc_start = to_utc(start)\n\n while duration != 0\n\n if a_day == PREVIOUS_DAY\n\t utc_start -= DAY\n\t a_day = SAME_DAY\n utc_start = Time.gm(utc_start.year, utc_start.month, utc_start.day,LAST_TIME_IN_DAY.hour, LAST_TIME_IN_DAY.min)\n\t week = find_weekpattern(utc_start)\n\t \n\t if week.working?(utc_start)\n\t duration += 1\n\t end\n else\n\t week = find_weekpattern(utc_start)\n end\n utc_start, duration, a_day = week.calc(utc_start, duration, a_day)\n end\n to_local(utc_start)\n end",
"def weekdays\n Weekdays.new(self)\n end",
"def start_of_week; self - wday.days end",
"def get_dates_matche (date_matche,days_game)\n flag_continue=true\n while flag_continue do\n date_matche = date_matche + 1.days\n day_week=date_matche.wday\n if days_game.include?(day_week.to_s)\n return date_matche\n end \n end\n end",
"def set_day_range(days, start_day, end_day)\n pos = Days.index(start_day)\n while pos != (Days.index(end_day) + 1) % 7\n days[pos] = true\n pos = (pos + 1) % 7\n end\n end",
"def build_shifts\n shifts = Person.find(params[:id]).shifts.order(start: :asc)\n #init working_weeks\n working_weeks = [[[shifts[0]]]]\n if shifts[0].start.strftime(\"%U\").to_i != shifts[0].end.strftime(\"%U\").to_i or\n shifts[0].start.wday != shifts[0].end.wday\n #check for which it is because you have to append different things to different places.\n if shifts[0].start.strftime(\"%U\").to_i != shifts[0].end.strftime(\"%U\").to_i\n #duplicate the current shift and add it\n working_weeks.append [[shifts[0].dup]]\n #then set the dup's start and the original's end so you know what day it is later.\n working_weeks[0][0][0].end = working_weeks[0][0][0].start.end_of_day\n working_weeks[-1][-1][-1].start = working_weeks[-1][-1][-1].end.beginning_of_day\n elsif shifts[0].start.wday != shifts[0].end.wday\n working_weeks[0].append [shifts[0].dup]\n working_weeks[0][0][0].end = working_weeks[0][0][0].start.end_of_day\n working_weeks[-1][-1][-1].start = working_weeks[-1][-1][-1].end.beginning_of_day\n end\n #you incremented day so get the first day's display info set up. only one shift so pad it\n #with a nil at the front and 3 at the back. array's length has to be 7\n working_weeks[0][0].append(nil)\n #time before shift\n working_weeks[0][0].append(shifts[0].start.hour * 2 + shifts[0].start.min / 30)\n #time during shift\n working_weeks[0][0].append(48 - (shifts[0].start.hour * 2 + shifts[0].start.min / 30))\n 3.times do\n working_weeks[0][0].append 0\n end\n end\n shifts.drop(1)\n shifts.each_with_index do |shift, idx|\n #byebug\n #get the first bit of the shift in if it's on a different day\n #only setting the previous day's bit here so that day's array will be cleaned up afterwards\n #working shift's start is changed to get that started\n if shift.start.strftime(\"%U\").to_i != shift.end.strftime(\"%U\").to_i or\n shift.start.wday != shift.end.wday\n\n if shift.start.strftime(\"%U\").to_i != shift.end.strftime(\"%U\").to_i\n working_weeks.append([[shift.dup]])\n elsif shift.start.wday != shift.end.wday\n working_weeks[-1].append([shift.dup])\n end\n working_weeks[-1][-1][-1].end = working_weeks[-1][-1][-1].start.end_of_day\n shift.start = shift.end.beginning_of_day\n end\n\n if shift.start.strftime(\"%U\").to_i != shifts[idx - 1].end.strftime(\"%U\").to_i or\n shift.start.wday != shifts[idx - 1].end.wday\n\n #new day/month so set the last day's display info\n if working_weeks[-1][-1][1].nil?\n working_weeks[-1][-1].append(nil)\n end\n working_weeks[-1][-1].append(working_weeks[-1][-1][0].start.hour * 2 + \n working_weeks[-1][-1][0].start.min / 30)\n #add 1 to the end time because it might be 23:59 if it was set by \n working_weeks[-1][-1].append((working_weeks[-1][-1][0].end.hour * 2 +\n (working_weeks[-1][-1][0].end.min + 1) / 30) -\n (working_weeks[-1][-1][0].start.hour * 2 +\n working_weeks[-1][-1][0].start.min / 30))\n #if there's only one we just need to set the end\n if working_weeks[-1][-1][1].nil?\n working_weeks[-1][-1].append(48 - (working_weeks[-1][-1][0].end.hour * 2 +\n (working_weeks[-1][-1][0].end.min + 1) / 30))\n 2.times do\n working_weeks[-1][-1].append 0\n end\n #otherwise step to the second shift\n else\n working_weeks[-1][-1].append((working_weeks[-1][-1][0].start.hour * 2 +\n (working_weeks[-1][-1][0].start.min) / 30) -\n (working_weeks[-1][-1][1].end.hour * 2 +\n (working_weeks[-1][-1][1].end.min + 1) / 30))\n working_weeks[-1][-1].append((working_weeks[-1][-1][1].end.hour * 2 +\n (working_weeks[-1][-1][1].end.min + 1) / 30) -\n (working_weeks[-1][-1][1].start.hour * 2 +\n working_weeks[-1][-1][1].start.min / 30))\n working_weeks[-1][-1].append(48 - (working_weeks[-1][-1][1].end.hour * 2 + \n (working_weeks[-1][-1][1].end.min + 1) / 30))\n end\n\n end\n if shift.start.strftime(\"%U\").to_i != shifts[idx - 1].end.strftime(\"%U\").to_i\n working_weeks.append [[shift]]\n elsif shift.start.wday != shifts[idx - 1].end.wday\n working_weeks[-1].append [shift]\n else\n working_weeks[-1][-1].append shift\n end\n \n\n end\n return working_weeks\n end",
"def wday() end",
"def nth_wday(nth, wday_name)\n raise Koyomi::WrongRangeError if nth > weeks.size\n self.weeks[nth - 1].wday(wday_name)\n end"
] |
[
"0.7141109",
"0.67687577",
"0.6705868",
"0.66671085",
"0.66387415",
"0.65931875",
"0.65390134",
"0.65236366",
"0.65086555",
"0.64433205",
"0.6415727",
"0.6401179",
"0.6380372",
"0.636482",
"0.6303574",
"0.6299422",
"0.6268097",
"0.6265568",
"0.6252682",
"0.62521726",
"0.6218374",
"0.61690426",
"0.6157689",
"0.6118907",
"0.6082258",
"0.60816854",
"0.6077162",
"0.6076267",
"0.6062846",
"0.60427004",
"0.6025832",
"0.6022467",
"0.60133946",
"0.59993255",
"0.5983219",
"0.5980391",
"0.5969944",
"0.5966991",
"0.59225184",
"0.59198445",
"0.5896426",
"0.58960104",
"0.5883759",
"0.5853943",
"0.5846843",
"0.5836815",
"0.5836366",
"0.5823757",
"0.579658",
"0.5792637",
"0.5787616",
"0.5787616",
"0.578307",
"0.5769598",
"0.5765356",
"0.5755784",
"0.5746515",
"0.5743054",
"0.5740125",
"0.5735035",
"0.5733054",
"0.5729657",
"0.5726288",
"0.5713811",
"0.5707355",
"0.5705955",
"0.5704609",
"0.57042944",
"0.5703765",
"0.570082",
"0.5692952",
"0.56907976",
"0.56861246",
"0.5685726",
"0.56586426",
"0.56584996",
"0.565456",
"0.5652193",
"0.5644293",
"0.5643421",
"0.5636432",
"0.56348264",
"0.5626412",
"0.5621102",
"0.5617292",
"0.5613214",
"0.5611531",
"0.56071085",
"0.56004584",
"0.5598352",
"0.5597961",
"0.5575256",
"0.55700356",
"0.55647814",
"0.5562503",
"0.55600774",
"0.5557607",
"0.55560166",
"0.5555804",
"0.5548757"
] |
0.5557375
|
97
|
Create a recurrence for given days of year
|
def day_of_year(days, *extras)
merge(yday: days.array_concat(extras))
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def advent_days(year:)\n min_day .. max_day(year: year)\n end",
"def increment_by_days count\n new_day = @day\n new_month = @month\n new_year = @year \n \n while count > 0\n days_to_next_month = days_in_month(new_month, new_year) - new_day + 1\n \n if (days_to_next_month > count)\n new_day = new_day + count\n count = 0 \n else\n new_day = 1\n new_month = new_month + 1\n if (new_month > 12)\n new_month = 1\n new_year = new_year + 1\n end\n \n count = count - days_to_next_month \n end\n end\n \n return MyDate.new new_day, new_month, new_year\n end",
"def no_repeat_years(first_year, last_year)\nend",
"def new_years_day_for(year)\n nyd = Date.new(year,1,1)\n if nyd.saturday?\n Date.new(year,1,3)\n elsif nyd.sunday?\n Date.new(year,1,2)\n else\n nyd\n end\n end",
"def fridays_in_year(year)\n current_week = 1\n current_day = 5\n current_date = DateTime.commercial(year, current_week, current_day)\n fridays_per_month = Array.new(12,0)\n while current_date.year == year\n fridays_per_month[current_date.month - 1] += 1\n current_date += 7\n end\n fridays_per_month\nend",
"def day_of_year(*days)\n merge(yday: days)\n end",
"def days_in_year(year)\n ::Montrose::Utils.days_in_month(2, year) + 337\n end",
"def compute_yearwise(incomes_or_deductions)\n income_deduction_per_year = Hash.new(0)\n\n incomes_or_deductions.each do |income_deduction|\n working_days_in_year = Float(52*5)\n daily_income = 0\n\n case income_deduction.frequency\n when \"daily\"\n daily_income = income_deduction.amount_in_cents\n when \"weekly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year/52)\n when \"biweekly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year/26)\n when \"monthly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year/12)\n when \"quarterly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year/4)\n when \"half_yearly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year/2)\n when \"yearly\"\n daily_income = income_deduction.amount_in_cents / (working_days_in_year)\n end\n\n income_deduction.start_date = TimeKeeper.date_of_record.beginning_of_year if income_deduction.start_date.to_s.eql? \"01-01-0001\" || income_deduction.start_date.blank?\n income_deduction.end_date = TimeKeeper.date_of_record.end_of_year if income_deduction.end_date.to_s.eql? \"01-01-0001\" || income_deduction.end_date.blank?\n years = (income_deduction.start_date.year..income_deduction.end_date.year)\n\n years.to_a.each do |year|\n actual_days_worked = compute_actual_days_worked(year, income_deduction.start_date, income_deduction.end_date)\n income_deduction_per_year[year] += actual_days_worked * daily_income\n end\n end\n\n income_deduction_per_year.merge(income_deduction_per_year) { |k, v| Integer(v) rescue v }\n end",
"def day_of_year\n (seconds_since_start_of_year / D_SECS).to_i + 1\n end",
"def days_in_year(year = current.year)\n days_in_month(2, year) + 337\n end",
"def days_in_year(year)\n Time.days_in_month(2, year) + 337\n end",
"def future(year, month, day)\n years = (10 ** 9) / 60 / 60 / 24 / 365\n days = (10 ** 9) / 60 / 60 / 24 % 365\n\n year = year + years\n \n\nend",
"def countSundaysYear(year, startDay)\n\tsundays = 0\n\tday = startDay % 7\n\tif(isLeapYear(year))\n\t\tyear = $MonthsLeap\n\telse\n\t\tyear = $Months\n\tend\n\t\n\tyear.each do |x|\n\t\tif(day == 0)\n\t\t\tsundays += 1\n\t\tend\n\t\tday = ((day + x) % 7)\n\t\t\n\tend\n\t\n\treturn sundays\nend",
"def each_years(n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| Date.civil(dt.year + offset, dt.month, dt.day) }\n s.increment { |dt,i| Date.civil(dt.year + i, dt.month, dt.day) }\n s.span { |dt| Date.civil(dt.year + dur, dt.month, dt.day) }\n end \n end",
"def years() 365 * days end",
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def dayOfWeek\n days = 0;\n tempYear = MIN_YEAR\n while tempYear < @year\n days += SimpleDate.daysInYear(tempYear).to_i\n tempYear+=1\n end\n\n days = days + ordinalDate\n #puts \"days #{days}\"\n days = days % 7\n\n end",
"def days_in_year\n 365.25\nend",
"def make_year(year, bias); end",
"def get_next_yr\n\tset_cur_year(get_cur_year+1)\nend",
"def compute_actual_days_worked(year, start_date, end_date)\n working_days_in_year = Float(52*5)\n\n if Date.new(year, 1, 1) < start_date\n start_date_to_consider = start_date\n else\n start_date_to_consider = Date.new(year, 1, 1)\n end\n\n if Date.new(year, 1, 1).end_of_year < end_date\n end_date_to_consider = Date.new(year, 1, 1).end_of_year\n else\n end_date_to_consider = end_date\n end\n\n # we have to add one to include last day of work. We multiply by working_days_in_year/365 to remove weekends.\n ((end_date_to_consider - start_date_to_consider + 1).to_i * (working_days_in_year/365)).to_i #actual days worked in 'year'\n end",
"def year_calculations\n\t\t@prev_beg_range = @beg_range.to_date.beginning_of_year.prev_year\n\t\t@prev_end_range = @beg_range.to_date.beginning_of_year-1.day\n\t\t@next_beg_range = @beg_range.to_date.next_year.beginning_of_year\n\t\t@next_end_range = @beg_range.to_date.next_year.end_of_year\n\tend",
"def days_in_year\n return Datet.days_in_year(@t_year)\n end",
"def calculate_yearly_rents_years\n convert_lease_transaction_date\n years = @lbtt_return.lease_end_date.year - @lbtt_return.lease_start_date.year\n years += 1 if @lbtt_return.lease_end_date >= @lbtt_return.lease_start_date.next_year(years)\n years\n end",
"def create\n @calendar = Calendar.new(calendar_params)\n dstart = Date.new(@calendar.year_c, 1, 1)\n dfinish = Date.new(@calendar.year_c + 1, 1, 1)\n while dstart < dfinish\n cld = Calendar.new\n cld.year_c = @calendar.year_c\n cld.date_c = dstart\n cld.is_output = (dstart.wday == 6 or dstart.wday == 0 ? true : false)\n cld.save\n dstart = dstart + 1.day\n end\n\n respond_to do |format|\n format.html { redirect_to calendars_path(year: @calendar.year_c), notice: 'Calendar was successfully created.' }\n end\n end",
"def no_repeat_years(first_yr, last_yr)\n result = []\n (first_yr..last_yr).each do |num|\n if not_repeat_year?(num)\n result << num\n end\n end\n result\nend",
"def new_year(date) = ::Date.new(Integer === date ? date : date(date).year, 1, 1, reform_jd).new_start(::Date::GREGORIAN)",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def discount_of_the_day(day)\n case day\n when (0..(DISCOUNT_PERIOD_1_START_DAY - 1)) then 0\n when (DISCOUNT_PERIOD_1_START_DAY..(DISCOUNT_PERIOD_2_START_DAY - 1)) then DISCOUNT_PERIOD_1_RATE\n when (DISCOUNT_PERIOD_2_START_DAY..(DISCOUNT_PERIOD_3_START_DAY - 1)) then DISCOUNT_PERIOD_2_RATE\n else DISCOUNT_PERIOD_3_RATE\n end\n end",
"def real_study_years\n if finished?\n end_date = finished_on.to_time\n elsif absolved?\n end_date = disert_theme.defense_passed_on.to_time\n else\n end_date = Time.now\n end\n return (end_date - enrolled_on.to_time).div(1.year) + 1\n end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def day_of_year\n count = @t_day\n @@days_in_months.each_index do |key|\n break if key >= @t_month\n val = @@days_in_months[key]\n \n if key == 2 and Datet.gregorian_leap?(@t_year)\n count += 29\n else\n count += val.to_i\n end\n end\n \n return count\n end",
"def xday_countdown(yday, year)\n return unless $KILL_BOB\n r = (185 - yday) + (((yday < 59) && (leapp(year))) ? 1 : 0)\n while year < 9827\n # TODO : need to test if year var addition is correct\n year += 1\n r += (leapp(year) ? 366 : 365)\n end\n while year > 9827\n r-= (leapp(year) ? 366 : 365)\n year -= 1\n end\n return r\n end",
"def next_years\n current_year = Time.now.year\n current_year..(current_year + 4)\n end",
"def years ; self * 365.days ; end",
"def to_rd\n normal_days = 365 * (@year - 1)\n leap_days = (((@year - 1) / 4).floor -\n ((@year - 1) / 100).floor +\n ((@year - 1) / 400).floor)\n # The following formula assumes that February has 30 days.\n previous_days = ((367 * @month - 362) / 12).floor\n # Correction for the previous formula.\n correction = nil\n # We are before February, no correction needed.\n if @month <= 2\n correction = 0\n # Leap year => February has 29 days - 30 = -1.\n elsif leap?\n correction = -1\n # Normal year => February has 28 days - 30 = -2.\n else\n correction = -2\n end\n return (EPOCH - 1 + normal_days + leap_days + previous_days +\n correction + @day)\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def year(input) = new_year(input).year - 621",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).reduce([]) do |output, el|\n if not_repeat_year?(el)\n output << el\n else\n output\n end\n end\nend",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select { |e| not_repeat_year?(e) }\nend",
"def make_tick_dates(from_year, to_year, interval)\n (from_year..to_year).step(interval).map { |year| Date.new(year,1,1) }\n end",
"def day_in_year\n day = self.day\n \n 1.upto(self.month - 1) do |month_no|\n day += Datet.days_in_month(self.year, month_no)\n end\n \n return day\n end",
"def alt_year_from_fixed(date)\n approx = quotient(date - gregorian_epoch + 2, 146097/400.0)\n start = (gregorian_epoch +\n (365 * approx) +\n quotient(approx, 4) +\n -quotient(approx, 100) +\n quotient(approx, 400))\n (date < start) ? approx : (approx + 1)\n end",
"def daysInYear\n if leapYear?\n return 366\n else\n return 365\n end\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select{|yr|not_repeat_year?(yr)}\nend",
"def advance_years(years)\n advance_to_date(to_date >> (years*12))\n end",
"def endless_numbered_days(year=2011,month=1)\n x = Date.new(year,month,-1).day\n y = Date.new(year,month,1).wday\n cal = {}\n 1.upto(x) do |i|\n cal[i] = [y]\n y += 1\n end\n return cal.to_json\n end",
"def hash_days_number year\n hash = { 1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30,\n 7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31 }\n\n hash[2] = 29 if leap? year\n hash\nend",
"def next_year(years = 1)\n advance(years: years)\n end",
"def calculate_years(principal, interest, tax, desired)\n# principal amount\n year = 0\n while principal < desired\n year += 1\n income = principal * interest\n principal += income - income * tax\n end\n year\nend",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select {|x| not_repeat_year?(x) }\nend",
"def days_in_year(time)\n date = time.to_date\n ((date + 1.year) - date).to_i\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).reduce([]) do |arr, year|\n if not_repeat_year?(year)\n arr << year\n else\n arr\n end\n end\nend",
"def create_date_value\n \n 1.upto(months.length) do |month|\n 1.upto(month) do |day|\n arr << [\"2015#{day}#{month}\", day_of_week]\n end\n end\nend",
"def new(year = -4712, month = 1, day = 1, sg = ITALY)\n # we can catch this here already\n raise ArgumentError, \"invalid date\" if month > 12\n \n unless valid_civil?(year, month, day, sg)\n raise ArgumentError, \"invalid date, because it falls in the dropped days range of the calendar reform\"\n end\n \n components = NSDateComponents.new\n components.year = year\n components.month = month\n components.day = day\n \n # TODO: check when this can return `nil' instead of a date\n date = GREGORIAN_CALENDAR.dateFromComponents(components)\n interval = date.timeIntervalSinceReferenceDate\n \n mrdate = alloc.initWithTimeIntervalSinceReferenceDate(interval)\n mrdate.sg = sg\n \n # no positive wrap around!\n if mrdate.day < day && (mrdate.month == (month + 1) % 12)\n raise ArgumentError, \"invalid date\"\n end\n \n mrdate\n end",
"def update_annual_happiness_distributions! \n HappinessEntry.beginning_of_year_days.each do |beginning_of_year_day|\n uid = uid_for_year(beginning_of_year_day)\n end_of_year_day = beginning_of_year_day.end_of_year\n entries_for_year = HappinessEntry.in_year(beginning_of_year_day, end_of_year_day)\n update_happiness_distribution! uid, :year, entries_for_year \n end\n end",
"def friday_13th(year)\n date = Date.new(year)\n unlucky_days = 0\n 365.times do\n date = date + 1\n if date.friday? == true && date.mday == 13\n unlucky_days += 1\n end\n end\n unlucky_days\nend",
"def five_fridays(year)\n num_days = {\n 1=>31, 2=>28, 3=>31, 4=>30, 5=>31, 6=>30,\n 7=>31, 8=>31, 9=>30, 10=>31, 11=>30, 12=>31\n }\n\n five_fridays = 0\n num_days[2] = 29 if Date.new(year).leap?\n\n 1.upto(12) do |month|\n num_fridays = 0\n 1.upto(num_days[month]) do |day|\n date = Date.new(year, month, day)\n num_fridays += 1 if date.friday?\n end\n five_fridays += 1 if num_fridays >= 5\n end\n\n five_fridays\nend",
"def gas_year\n y = year\n if self< Date.new(y,10,1)\n y\n else\n y+1\n end\n end",
"def sred_range_for_date(date=today_as_date)\n start_of_year = (Date.new(date.year, 1, 1)..Date.new(date.year, 7, 31))\n if start_of_year.include?(date)\n return \"#{(date.year - 1)}/#{date.year}\"\n else\n return \"#{date.year}/#{date.year + 1}\"\n end\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).select { |year| not_repeat_year?(year) }\nend",
"def extra_days(days_count, month_count, year_count, init_month, init_year)\n # Will keep increamenting them with surplus days\n days = days_count\n mth = init_month\n yr = init_year\n\n loop do\n days -= days_in_month(mth, yr)\n break if days <= 0\n mth += 1\n if mth > 12\n mth = 1; yr += 1\n end\n days_count = days\n end\n\n # Setting actual incremented values\n month_count += (mth - init_month)\n year_count += (yr - init_year)\n\n [days_count, month_count, year_count]\n end",
"def make_days\n month = (1..@day_num).collect do |day|\n Day.new(Date.parse(\"#{@year}-#{@month}-#{day}\"))\n end\n\n month[0].date.wday.times { month.insert(0, Day.new(Date.new))}\n month\n end",
"def day_number_of_the_year day, month, hash \n if month > 1\n for i in 1...month\n day += hash[i]\n end\n end\n day\nend",
"def effective_year\n if next_year_start_at && Time.zone.now < 1.year.from_now(next_year_start_at)\n if Time.zone.now < next_year_start_at\n return Time.zone.now.year\n elsif Time.zone.now >= next_year_start_at\n if Time.zone.now.year == next_year_start_at.year\n return Time.zone.now.year + 1\n else\n return Time.zone.now.year\n end\n end\n elsif Time.zone.now.month == 12 && Time.zone.now.day >= 1\n return Time.zone.now.year + 1\n end\n\n Time.zone.now.year\n end",
"def next_year\n AcademicYear.find_by(year: self.year + 1)\n end",
"def start_new_year\n clean_associations(Candidate)\n AppFactory.create_seed_candidate\n today = Time.zone.today\n ConfirmationEvent.find_each do |ce|\n ce.chs_due_date = today\n ce.the_way_due_date = today\n ce.save\n end\n\n Rails.logger.info 'done start new year'\n end",
"def get_year_ary\n (Date.today.year-99..Date.today.year).inject([]){|x,y| x << y}.reverse\n end",
"def calculate(frequency, frequency_integer, start_date, end_date)\n first_due_date = @calendar.roll_forward(start_date)\n base_dates = [first_due_date]\n return [base_dates, base_dates] if frequency == 'Once'\n\n frequency_symbol = get_frequency_symbol(frequency)\n grace_dates = [first_due_date.advance(frequency_symbol => frequency_integer)]\n\n base_date = start_date\n end_date = calculate_end_date(start_date, end_date)\n\n while base_date < end_date\n grace_date = base_date.advance(frequency_symbol => frequency_integer*2)\n base_date = base_date.advance(frequency_symbol => frequency_integer)\n base_dates << @calendar.roll_forward(base_date)\n grace_dates << @calendar.roll_forward(grace_date)\n end\n\n [base_dates, grace_dates]\n end",
"def yearly(options = {})\n branch options.merge(every: :year)\n end",
"def yearly(options = {})\n branch options.merge(every: :year)\n end",
"def no_repeat_years(first_yr, last_yr)\n array = []\n (first_yr..last_yr).each do |year|\n array << year if not_repeat_year?(year)\n end\n array\nend",
"def fy(d)\n\t\td = d.to_date\n\t\tif(d.month >= 2)\n\t\t\treturn (d.year+1)\n\t\telse\n\t\t\treturn d.year\n\t\tend\n\tend",
"def compute_dr(day_of_the_year)\n #equation 23\n #inverse relative distance Earth-Sun\n dr = 1 + 0.033 * Math.cos((2 * Math::PI/365) * day_of_the_year)\nend",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).to_a.select { |year| not_repeat_year?(year) }\nend",
"def your_birthday_is_on_a_friday_in_the_year(birthday)\n until birthday.friday?\n birthday = Time.new birthday.year + 1, birthday.month, birthday.day\n end\n birthday.year\nend",
"def friday_13th(year)\n thirteenth = Date.new(year, 1, 13)\n count = 0\n 12.times do |month|\n count += 1 if thirteenth.friday?\n thirteenth = thirteenth.next_month\n end\n count\nend",
"def apply_function_day_of_year(scope, ast)\n scope, date = apply_ast(scope, ast.children.first)\n return scope, \"(date_part('doy', #{date})::integer)\"\n end",
"def to_rd\n return EPOCH + 365*(@year-1) + 30*(@month-1) + @day - 1\n end",
"def no_repeat_years(first_yr, last_yr)\n years = (first_yr..last_yr).to_a\n years.select {|year| not_repeat_year?(year)}\n\nend",
"def generate_daytime_distribution \n \n end",
"def days_to_years(days)\n days / 365\nend",
"def frequency\n interval || 1.year\n end",
"def no_repeats(year_start, year_end)\n no_repeats = []\n (year_start..year_end).each do |yr|\n no_repeats << yr if no_repeat?(yr)\n end\n\n no_repeats\nend",
"def transitions(year); end",
"def transitions(year); end",
"def start_year\n Time.now.year - 75\n end",
"def makeDays\n\t\thowManyDaysAgo = (rand()*CONFERENCE_START).round(0)+18\n\t\tlengthDays = (rand()*CONFERENCE_DAYS_MAX_DIFF).round() + CONFERENCE_DAYS_BASIC\n\t\t@startDate = (Date.today-howManyDaysAgo)\n\t\t@endDate = (Date.today-howManyDaysAgo+lengthDays)\n\t\t# That's the end of fields you want to print\t\n\t\t@days = Array.new\n\t\t(howManyDaysAgo-lengthDays..howManyDaysAgo).each{|x| @days << (CDay.new((Date.today-x), self))\t}\n\t\t@days.reverse! # If we want them in correct order\n\t\t# Discounts, some weird stuff may happen here, like functional programming\n\t\t@discounts = Array.new\n\t\tdays = DISCOUNT_DAYS.map{|x| x+((rand()-0.5)*DISCOUNT_DAYS_MAX_DIFF).round(0)}\n\t\tammounts = DISCOUNT_AMMOUNTS.map{|x| x+((rand()-0.5)*DISCOUNT_AMMOUNTS_MAX_DIFF).round(2)}\n\t\t(0..2).each{|x| @discounts << Discount.new(((@startDate)-days[x].to_i-1), ((@startDate)-days[x+1].to_i), self, ammounts[x])}\n\tend",
"def days; self * DAY; end",
"def days; self * DAY; end",
"def no_repeats(year_start, year_end)\n\tyear = year_start\n\tnon_repeat_years = []\n\twhile year <= year_end\n\t\tif no_repeat_year?(year)\n\t\t\tnon_repeat_years.push(year)\n\t\tend\n\t\tyear += 1\n\tend\n\tnon_repeat_years\nend",
"def add_days(date, n)\n date + n * DAY\n end",
"def get_day(year)\n new_time_or_datetime(year).add_with_convert(seconds)\n end",
"def calculate_fiscal_year(date = Date.current)\n date >= Date.new(date.year, 05, 01) ? date.year+1 : date.year\n end",
"def year_frac()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::YearFrac::YearFracRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def build_school_year(year=nil)\n return SchoolYear.new if year.blank?\n\n starting_day = (year.is_a? Date) ? year : start_date_from_year(year)\n SchoolYear.new(start_date: starting_day, end_date: starting_day.next_year)\n end",
"def years_for_date_of_work(repo_d)\n start, start_qualifier, finish, finish_qualifier = repo_d.start, repo_d.start_qualifier, repo_d.finish, repo_d.finish_qualifier\n\n if start.nil? || start.blank?\n return []\n end\n\n case start_qualifier\n when \"Undated\"\n # We're ignoring finish here, if start is undated, it's undated buddy.\n []\n when \"decade\"\n # We're ignoring finish_date in this case\n first_three = start.strip.slice(0..2)\n return [] unless first_three =~ /\\A\\d+\\Z/ # not a good date\n\n return ((first_three + \"0\").to_i .. (first_three + \"9\").to_i).to_a\n when \"century\"\n # We're ignoring finish_date in this case\n first_two = start.strip.slice(0..1)\n return [] unless first_two =~ /\\A\\d+\\Z/ # not a good date\n\n return ((first_two + \"00\").to_i .. (first_two + \"99\").to_i).to_a\n when /\\A\\s*(\\d\\d\\d\\d)\\s*-\\s*(\\d\\d\\d\\d)/\n # we have a date range in start date, just use that ignore finish date\n # Catalogers aren't _supposed_ to enter this, but the 'hint' is\n # confusing and I think some may have.\n return ($1.to_i .. $2.to_i).to_a\n end\n\n # For all other types of start date (circa, before, after, as well as blank)\n # we're just going to index it as the date we've got, if we've got one.\n start_year = start.slice(0..3)\n return [] unless start_year =~ /\\A\\d+\\Z/ # not a good date\n start_year = start_year.to_i\n\n finish_year = (finish || \"\").slice(0..3).to_i # will be 0 if was blank or non-numeric\n\n # If finish year is before start year, or empty (in which case it'll be 0),\n # just use start date, best we can do.\n if finish_year <= start_year\n return [start_year]\n else\n # we have both years, ignore 'before' or 'circa' qualifiers\n # on finish, don't know what we'd do with those, just treat it\n # like a year.\n return (start_year..finish_year).to_a\n end\n end",
"def get_day(offset, year); end",
"def get_day(offset, year); end",
"def get_day(offset, year); end"
] |
[
"0.6317235",
"0.6261399",
"0.6261066",
"0.624109",
"0.622821",
"0.6200521",
"0.61757034",
"0.61427826",
"0.6092044",
"0.6035289",
"0.60295033",
"0.6023175",
"0.6008881",
"0.5977193",
"0.59730315",
"0.59266484",
"0.5899192",
"0.5872805",
"0.5840942",
"0.58381826",
"0.5830785",
"0.5804878",
"0.5798253",
"0.5768091",
"0.57529753",
"0.5744034",
"0.57424086",
"0.5740872",
"0.57367873",
"0.5727776",
"0.5726858",
"0.5723854",
"0.56880504",
"0.567893",
"0.5668323",
"0.56675667",
"0.56534123",
"0.56499594",
"0.5645137",
"0.56415266",
"0.5626324",
"0.56246686",
"0.5604888",
"0.56034875",
"0.5596882",
"0.55932456",
"0.55924386",
"0.55911577",
"0.55897313",
"0.55883336",
"0.5582853",
"0.5574434",
"0.5542447",
"0.5537622",
"0.55342746",
"0.5523246",
"0.5518994",
"0.551308",
"0.55089045",
"0.55031824",
"0.54978526",
"0.5493646",
"0.548833",
"0.54732233",
"0.5470969",
"0.546503",
"0.54612476",
"0.5455469",
"0.54468304",
"0.54378617",
"0.54378617",
"0.54378355",
"0.54358524",
"0.542929",
"0.5414808",
"0.54138315",
"0.5413573",
"0.53990734",
"0.5398382",
"0.539434",
"0.5388599",
"0.5372666",
"0.53640527",
"0.53603905",
"0.53573585",
"0.53573585",
"0.5348828",
"0.5347975",
"0.53474885",
"0.53474885",
"0.5345677",
"0.5345094",
"0.53376734",
"0.5337588",
"0.5329875",
"0.53255874",
"0.53214985",
"0.53184795",
"0.53184795",
"0.53184795"
] |
0.60654324
|
9
|
Create a recurrence for given hours of day
|
def hour_of_day(hours, *extras)
merge(hour: hours.array_concat(extras))
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def date_calc(start,day_start,day_duration,round)\n time=start;schedule=[]\n round.size.times do |r|\n#print day_start+day_duration;print \"\\n\"\n if time >= day_start + day_duration\n#print time;print \"\\n\"\n time=day_start+1.day\n day_start = time\n end\n schedule[r] = time\n time+=HEAT_INTERVAL\n end\n\n return schedule\n end",
"def add_hours(hours = 1)\n hours = hours.to_i\n cur_hour = @t_hour\n next_hour = cur_hour + hours\n \n if next_hour >= 24\n @t_hour = 0\n self.add_days(1)\n hours_left = (hours - 1) - (24 - cur_hour)\n self.add_hours(hours_left) if hours_left > 0\n elsif next_hour < 0\n @t_hour = 23\n self.add_days(-1)\n hours_left = hours + cur_hour + 1\n self.add_hours(hours_left) if hours_left < 0\n else\n @t_hour = next_hour\n end\n \n return self\n end",
"def generate_assistances_for_one_day\n [8, 13, 15, 18].each_with_index do |hour, index|\n create(:assistance, \n happening_at: assistance_day.change(hour: hour),\n employee: employee,\n kind: index.even? ? 'in' : 'out')\n end\n end",
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def createDailyWins(contest,cp)\n cdate = contest.start_date.to_date\n prize_per_day = 2\n while cdate <= contest.end_date.to_date\n for i in (1..prize_per_day)\n time = \"#{(0..23).to_a.sample}:#{(0..59).to_a.sample}:#{(0..59).to_a.sample} Rome\"\n wintime = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" \"+ time)\n wintime_end = Time.parse(cdate.strftime(\"%Y-%m-%d\") +\" 23:59:59\")\n \n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n while Instantwin.where(\"unique_id=?\",unique_id).present?\n @hash_counter += 1\n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n end\n \n iw = Instantwin.new\n iw.contest_periodicity_id = cp.id\n iw.title = \"Daily\"\n iw.time_to_win_start = wintime\n iw.time_to_win_end = wintime_end\n iw.unique_id = unique_id\n iw.save\n @hash_counter += 1\n end\n cdate += 1\n end\n end",
"def load_hours\n @day = Schedule.first\n @hours = Array.new(48)\n\n @hours[0] =@day.h0\n @hours[1] =@day.h1\n @hours[2] =@day.h2\n @hours[3] =@day.h3\n @hours[4] =@day.h4\n @hours[5] =@day.h5\n @hours[6] =@day.h6\n @hours[7] =@day.h7\n @hours[8] =@day.h8\n @hours[9] =@day.h9\n @hours[10]=@day.h10\n @hours[11]=@day.h11\n @hours[12]=@day.h12\n @hours[13]=@day.h13\n @hours[14]=@day.h14\n @hours[15]=@day.h15\n @hours[16]=@day.h16\n @hours[17]=@day.h17\n @hours[18]=@day.h18\n @hours[19]=@day.h19\n @hours[20]=@day.h20\n @hours[21]=@day.h21\n @hours[22]=@day.h22\n @hours[23]=@day.h23\n @hours[24]=@day.h24\n @hours[25]=@day.h25\n @hours[26]=@day.h26\n @hours[27]=@day.h27\n @hours[28]=@day.h28\n @hours[29]=@day.h29\n @hours[30]=@day.h30\n @hours[31]=@day.h31\n @hours[32]=@day.h32\n @hours[33]=@day.h33\n @hours[34]=@day.h34\n @hours[35]=@day.h35\n @hours[36]=@day.h36\n @hours[37]=@day.h37\n @hours[38]=@day.h38\n @hours[39]=@day.h39\n @hours[40]=@day.h40\n @hours[41]=@day.h41\n @hours[42]=@day.h42\n @hours[43]=@day.h43\n @hours[44]=@day.h44\n @hours[45]=@day.h45\n @hours[46]=@day.h46\n @hours[47]=@day.h47\n\n return @hours\n end",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def build_hash hash, date, worked_hours, departur_hour\n hash[\"#{date.strftime(\"%F\")}\"] = {total: worked_hours, arrival_hour: date, departur_hour: departur_hour}\n hash[:total_worked] += worked_hours\n hash[:total_days] += 1\n return hash\n end",
"def hours_in_day(*hours)\n @test_time = @time if @test_time.nil?\n x_in_list_of_y(@test_time.hour, Configuration.parse_range(hours).flatten)\n end",
"def find_hour(hours)\n if hours >= 0\n hours % 24\n else\n until hours >= 0\n hours += 24\n end\n hours\n end\nend",
"def advance_by_a_day\n scheduler = Scheduler.new(tasks, user_preferences)\n tasks_and_time = scheduler.call\n\n advanced_tasks = tasks_and_time.map do |task, time_to_advance|\n task.running_calculation ||= task.completed_hours\n task.running_calculation += time_to_advance\n task\n end\n\n @tasks = advanced_tasks.reject do |task|\n task.running_calculation >= task.estimated_hours\n end + tasks.reject do |task|\n advanced_tasks.map(&:id).include? task.id\n end\n\n tasks_and_time\n end",
"def hour_of_day(*hours)\n merge(hour: hours)\n end",
"def next_meeting(after_time = Time.now.utc )\n # puts \"Looking up next meeting after #{after_time}\"\n if recurrence_frequency.blank?\n return start_time\n end\n\n if after_time < start_time\n return start_time\n end \n\n after_time = after_time.local_from_utc(self.time_zone) \n\n\n # Advance the starting time in the case when it falls after the beginning of\n # a meeting on the same day. We do this so that we can use \"day precision\"\n # (PDate.day) in the Runt library instead of \"minute precision\" (PDate.min),\n # which performs terribly.\n start_time = start_time_local\n if(after_time.hour > start_time.hour or ( after_time.hour == start_time.hour and after_time.min > start_time.min))\n after_time = after_time + 1.day\n after_time = Time.gm(after_time.year, after_time.month, after_time.day, 0, 0)\n end\n\n case recurrence_frequency\n when 'daily'\n end_time = after_time + 25.hours \n # after_time -= 1.day\n start_date = PDate.day(after_time.year, after_time.month, after_time.day , after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'weekdays'\n # Make the range over 3 days so that Friday night searches will still turn\n # up Monday as the next day.\n end_time = after_time + 3.days\n start_date = PDate.day(after_time.year, after_time.month, after_time.day, after_time.hour, after_time.min)\n end_date = PDate.day(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min)\n when 'monthly'\n eom = (after_time + 40.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eom.year, eom.month, eom.day)\n when 'weekly'\n eow = (after_time + 8.days)\n start_date = PDate.day(after_time.year, after_time.month, after_time.day)\n end_date = PDate.day(eow.year, eow.month, eow.day)\n when 'yearly'\n # Just doing \"after_time + 367.days\" results in a bit of a performance hit\n # as hundreds of days are compared. We'll try to narrow it a bit. Not too\n # much, because we don't have time to actually write unit tests and make\n # sure the narrowing code works. :) Which is why the comment is here.\n st = after_time + 250.days\n et = st + 150.days\n start_date = PDate.day(st.year, st.month, st.day)\n end_date = PDate.day(et.year, et.month, et.day)\n end \n # puts \" Range #{start_date.to_s} - #{end_date.to_s}\"\n d_range = DateRange.new(start_date, end_date)\n sched = Schedule.new\n event = Event.new((self.invitation.name rescue \"no name\"))\n sched.add(event,self.runt_expression)\n dates = sched.dates(event,d_range)\n\n next_mtg = dates.first\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, start_time_local.hour, start_time_local.min)\n result = nil\n begin\n result = next_mtg_time.local_to_utc(self.time_zone)\n rescue TZInfo::PeriodNotFound\n # This only happens when the time is during the one hour which is skipped\n # during the transition to DST. For example, only on Sun Mar 08 02:15:00\n # (see ticket #744).\n next_hour = start_time_local.hour + 1\n next_mtg_time = Time.gm(next_mtg.year, next_mtg.month, next_mtg.day, next_hour, start_time_local.min)\n retry\n end\n return result\n end",
"def business_hours_later( hours)\n now = Time.now # freeze it here for this cycle of call, or it keeps changing every second\n wanted = (hours.to_i.hours / 1.second) # convert hours to seconds\n available = available_work_seconds( now) # how much available today\n # if we have enough time today, just tell the time possible today\n # if we will run out of time today, check next working day, add run-over seconds to the start-of-day\n (available > wanted) ? ( now + wanted.seconds) : ( next_workday(now) + (wanted - available).seconds)\n end",
"def add_recurrence(type: :week, on: on = nil, at: at = nil)\n type = type.to_sym\n unless [:week, :day].include? type\n raise \"Type must be either :week or :day\"\n end\n if type == :week and (on.nil? or (on.is_a?(Array) and on.empty?))\n raise \"Weekdays must be specified when selecting the :week type\"\n end\n schedule = self.read_attribute(self.class.schedulable_attribute)\n if self.schedule.nil?\n schedule = Montrose::Schedule.new\n end\n if at.nil?\n raise \"Time must be specified in parameter 'at'\"\n else\n schedule.add Montrose.every(type, on: on, at: at).starts(created_at)\n self.write_attribute(self.class.schedulable_attribute, schedule)\n end\n end",
"def new_schedule(*args)\n if !args.all? { |e| e.is_a?(Integer) && e >= 0 && e <= 6 }\n return \"Please enter a number from 0-6 where each number represents a day of the week. 0 represents Sunday, 1 represents Monday, etc.\"\n end\n schedule1 = Schedule.new(self.first_event, duration: self.duration_mins.minutes )\n schedule1.add_recurrence_rule Rule.weekly.day(args)\n self.schedule = schedule1\n self.save!\n end",
"def workpattern(days,from_time,to_time,type)\n DAYNAMES[days].each {|day| @values[day].workpattern(from_time,to_time,type)} \n refresh\n end",
"def time_slots\n\n # you can book by the hour, and you can stay for an hour\n reservation_interval = 1.hour\n\n # Determine the earliest time we will allow reservation\n # It can't be in the past, we'll start 10 minutes from now\n start_time = Time.zone.now + 10.minutes\n # Then we have to round to the next hour block\n start_time = Time.zone.at( (start_time.to_f / reservation_interval).ceil * reservation_interval )\n # Then, if we are still earlier than opening hour, just use the opening hour\n # We can use the 'max' Array method\n start_time = [start_time, start_time.change(hour: opening_hour)].max\n\n # Determine the furthest in the future we will allow reservations\n end_time = (start_time + 3.days).change(hour: closing_hour)\n\n # Now, we want to make a list of every hour between our start_time and our end_time\n # For this we can use a begin... end while condition loop.\n # We'll start with an empty array that will hold all the hours,\n # and a variable to hold each hour, which we will keep increasing by 1 hour, and then add to our array\n # Our loop condition will have us stop looping once we've reached the end time\n\n all_times = []\n a_time = start_time\n\n begin\n\n # add this time to our list of times\n all_times << a_time\n\n # increment the time\n a_time += reservation_interval\n\n # Once we get to closing time, we have to skip ahead to the next day's opening\n # That way you can't make a reservation at 2am\n if (a_time + reservation_interval) > a_time.change(hour: closing_hour)\n a_time = (a_time + 1.day).change(hour:opening_hour)\n end\n\n end while a_time < end_time\n\n all_times\n end",
"def grandclock(presenthour,&block)\n \n for i in (1..presenthour)\n block.call\n end\n \nend",
"def fill_schedule\n @schedule.each do |key,value|\n (6..20).each { |n| @schedule[key][\"#{n}:30 - #{n+1}:30\"] = \"0\" }\n end\n end",
"def set_time days\r\n days.each do |day,times|\r\n periods = times.split(\",\")\r\n periods.each do |period|\r\n start_time,end_time = period.split(\"-\")\r\n raise unless Time.parse(start_time) < Time.parse(end_time) \r\n #this will throw an exception if the day is invalid\r\n KlassSchedule.create :klass_id=>self.id,:start_time=>start_time,\r\n :end_time=>end_time,:day_of_week=>day\r\n end\r\n end \r\n end",
"def refrigerate_for_hours\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 9 )\n value = nil\n refrigerate_for_hours_start_index = @input.index\n num24 = nil\n\n success = false # flag used for memoization\n\n begin\n # rule memoization\n if @state.backtracking > 0 and already_parsed_rule?( __method__ )\n success = true\n return value\n end\n # at line 164:5: refrigerate ( WS for_ WS num WS hours )? EOF\n @state.following.push( TOKENS_FOLLOWING_refrigerate_IN_refrigerate_for_hours_583 )\n refrigerate\n @state.following.pop\n # at line 164:17: ( WS for_ WS num WS hours )?\n alt_18 = 2\n look_18_0 = @input.peek( 1 )\n\n if ( look_18_0 == WS )\n alt_18 = 1\n end\n case alt_18\n when 1\n # at line 164:18: WS for_ WS num WS hours\n match( WS, TOKENS_FOLLOWING_WS_IN_refrigerate_for_hours_586 )\n @state.following.push( TOKENS_FOLLOWING_for__IN_refrigerate_for_hours_588 )\n for_\n @state.following.pop\n match( WS, TOKENS_FOLLOWING_WS_IN_refrigerate_for_hours_590 )\n @state.following.push( TOKENS_FOLLOWING_num_IN_refrigerate_for_hours_592 )\n num24 = num\n @state.following.pop\n match( WS, TOKENS_FOLLOWING_WS_IN_refrigerate_for_hours_594 )\n @state.following.push( TOKENS_FOLLOWING_hours_IN_refrigerate_for_hours_596 )\n hours\n @state.following.pop\n\n end\n match( EOF, TOKENS_FOLLOWING_EOF_IN_refrigerate_for_hours_600 )\n # syntactic predicate action gate test\n if @state.backtracking == 0\n # --> action\n\n value = {\n :cmd => :refrigerate_for_hours,\n :args => {:hours => ( num24.nil? ? nil : num24.value ).to_i}\n }\n \n # <-- action\n end\n\n success = true\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 9 )\n memoize( __method__, refrigerate_for_hours_start_index, success ) if @state.backtracking > 0\n\n end\n \n return value\n end",
"def get_date(day, hours)\n current_time = Time.new #(2015,7,26) Preset date for testing. Should be current time\n if day.to_i > current_time.day\n month = current_time.month\n year = current_time.year\n else\n if current_time.month + 1 > 12\n month = 1\n year = current_time.year + 1\n else\n month = current_time.month + 1\n year = current_time.year\n end\n end\n year = year.to_i\n month = month.to_i\n day = day.to_i\n hours = hours.split('-')\n hours.map { |str| str.gsub!(/\\s+/, \"\") } #removes all white space\n hours[0] = ((hours[0].to_i != 12 && hours[0].to_i > 6) ? hours[0] + \"am\" : hours[0] + \"pm\") #adjusts hours to a 24 hour clock. Pivots at 6\n hours[1] = (hours[1].downcase.include?(\"close\") ? \"8pm\" : hours[1] + \"pm\") #sets \"close\" to be 8pm\n hours.map! { |time| DateTime.parse(time).strftime(\"%H:%M:%S\") }\n start_time = DateTime.parse(\"#{year}-\" + sprintf(\"%02d\", month) + \"-\" + sprintf(\"%02d\", day) + \"T#{hours[0]}\" + \"-0700\")\n end_time = DateTime.parse(\"#{year}-\" + sprintf(\"%02d\", month) + \"-\" + sprintf(\"%02d\", day) + \"T#{hours[1]}\" + \"-0700\")\n return { :start => start_time, :end => end_time }\nend",
"def reduce_schedule(day_sch, red_mult, start_red_hr, start_red_min, end_red_hr, end_red_min)\n start_time = OpenStudio::Time.new(0, start_red_hr, start_red_min, 0)\n end_time = OpenStudio::Time.new(0, end_red_hr, end_red_min, 0)\n\n # Get the original values at the desired start and end times\n # and put points into the schedule at those times.\n day_sch.addValue(start_time, day_sch.getValue(start_time))\n day_sch.addValue(end_time, day_sch.getValue(end_time))\n \n # Store the original time/values then clear the schedule\n times = day_sch.times\n values = day_sch.values\n day_sch.clearValues\n\n # Modify the time/values and add back to the schedule\n for i in 0..(values.length - 1)\n if times[i] > start_time and times[i] <= end_time # Inside range\n day_sch.addValue(times[i], values[i] * red_mult)\n else\n day_sch.addValue(times[i], values[i])\n end\n end\n\n end",
"def create60ggWins(contest,cp)\n beginning_date = contest.start_date.to_date\n day_range = (contest.end_date.to_date - contest.start_date.to_date).to_i\n total_prizes = 10\n winner_inserted = 0\n \n while winner_inserted < total_prizes\n offest_day_win = (0..day_range).to_a.sample\n winday = beginning_date + offest_day_win\n winhour = \"#{(0..23).to_a.sample}:#{(0..59).to_a.sample}:#{(0..59).to_a.sample} Rome\"\n wintime = Time.parse(winday.strftime(\"%Y-%m-%d\") +\" \"+ winhour)\n \n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n while Instantwin.where(\"unique_id=?\",unique_id).present?\n @hash_counter += 1\n unique_id = Digest::MD5.hexdigest(\"#{@hash_counter}\")\n end\n \n iw = Instantwin.new\n iw.contest_periodicity_id = cp.id\n iw.title = \"Random\"\n iw.time_to_win_start = wintime\n iw.unique_id = unique_id\n iw.save\n winner_inserted += 1\n @hash_counter += 1\n end\n end",
"def issue_hours_per_day(estimated_hours, start_date, end_date)\n (estimated_hours || 0.0) / (end_date - start_date + 1)\n end",
"def generate_assistances_with_one_day_difference\n (0..2).each do |extra_day|\n create(:good_entry_assistance, \n happening_at: base_date + extra_day.days,\n employee: employee) \n end\n end",
"def each_hours(n=1, offset=0, dur=1)\n each_seconds(n*60*60, offset*60*60, dur*60*60)\n end",
"def initialize(hours)\n @hatched = hours\n end",
"def occurrence_hash(default_duration) #:nodoc:\n date_time = self.to_ri_cal_date_time_value\n {:start => date_time,\n :end => date_time.advance(:hours => 24, :seconds => -1)}\n end",
"def rational_hour(seconds); end",
"def schedule_repetition\n self.due = Date.today + interval\n self.studied_at = Date.today\n end",
"def reduce_schedule(day_sch, before_hour, before_min, before_value, after_hour, after_min, after_value)\n before_time = OpenStudio::Time.new(0, before_hour, before_min, 0)\n after_time = OpenStudio::Time.new(0, after_hour, after_min, 0)\n day_end_time = OpenStudio::Time.new(0, 24, 0, 0)\n \n # Special situation for when start time and end time are equal,\n # meaning that a 24hr reduction is desired\n if before_time == after_time\n day_sch.clearValues\n day_sch.addValue(day_end_time, after_value)\n return\n end\n\n original_value_at_after_time = day_sch.getValue(after_time)\n day_sch.addValue(before_time,before_value)\n day_sch.addValue(after_time, original_value_at_after_time)\n times = day_sch.times\n values = day_sch.values\n day_sch.clearValues\n\n new_times = []\n new_values = []\n for i in 0..(values.length - 1)\n if times[i] >= before_time and times[i] <= after_time\n new_times << times[i]\n new_values << values[i]\n end\n end\n\n #add the value for the time period from after time to end of the day\n new_times << day_end_time\n new_values << after_value\n\n for i in 0..(new_values.length - 1)\n day_sch.addValue(new_times[i], new_values[i])\n end\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def add_time(hour: nil, proj: nil, date: nil, custom_num: nil, fill_value: nil, note: nil, costcodes: nil)\n # check if day already found\n day = self.days.where(:date => date).first\n if day\n result = day.add_time(hour: hour, proj: proj, date: date, custom_num: custom_num, fill_value: fill_value, note: note, cost_codes: costcodes)\n else\n day = Day.new\n result = day.add_time(hour: hour, proj: proj, date: date, custom_num: custom_num, fill_value: fill_value, note: note, cost_codes: costcodes)\n self.days << result[:day]\n end\n refresh_project_total(result: result, proj: proj)\n save\n publish(:add_time_successful, result)\n end",
"def insert_course(schedule, days, start_time, end_time)\n \n days.each do |day|\n for time in start_time...end_time\n # don't try to schedule class times past 5:15pm (for now)\n # puts \"%i %i \" % [time, schedule.length]\n if time < schedule.length\n schedule[time][day] = 1\n end\n end\n end\n \n return schedule\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def hours\n\n today = Date.today\n hours = {}\n #if @traveler.is_visitor? or @traveler.is_api_guest? #Return a wide range of hours\n if not @traveler or not @traveler.registered?\n (0..30).each do |n|\n hours[(today + n).to_s] = {open: \"07:00\", close: \"22:00\"}\n end\n\n else # This is not a guest, check to see if the traveler is registered with a service\n\n # NOTE(wilsonj806) For now this implementation does not let registered users\n #...book trips on weekends. Eventually we want to change that so they can do so\n\n if @traveler.booking_profiles.count > 0 #This user is registered with a service\n booking_profile = @traveler.booking_profiles.first\n service = booking_profile.service\n\n min_notice_days = (service.booking_details[:min_days] || 2).to_i\n max_notice_days = (service.booking_details[:max_days] || 14).to_i\n\n \n if service.booking_details[:trusted_users] and booking_profile.external_user_id.in? service.booking_details.try(:[], :trusted_users).split(',').map{ |x| x.strip }\n (1..21).each do |n|\n hours[(today + n).to_s] = {open: \"00:00\", close: \"23:59\"}\n end\n elsif service.schedules.count > 0 #This user's service has listed hours. This is the most common case.\n \n #Find out if we are past the cutoff for today. If so, start counting from tomorrow\n if service.booking_details[:cutoff_time] and (Time.now.in_time_zone.seconds_since_midnight > service.booking_details[:cutoff_time].to_i)\n day = Time.now + 1.days \n else\n day = Time.now\n end\n \n biz_days_count = 0\n (0..max_notice_days).each do |n|\n if service.open_on_day? day\n if biz_days_count >= min_notice_days\n schedule = service.schedules.where(day: day.wday).first\n if schedule\n hours[day.strftime('%Y-%m-%d')] = {open: schedule.schedule_time_to_military_string(schedule.start_time), \n close: schedule.schedule_time_to_military_string(schedule.end_time)}\n end\n end\n biz_days_count += 1\n end\n day = day + 1.days \n end\n\n else #This user is registered with a service, but that service has not entered any hours\n\n (min_notice_days..max_notice_days).each do |n|\n unless (today + n).saturday? or (today + n).sunday?\n hours[(today + n).to_s] = {open: \"08:00\", close: \"17:00\"}\n end\n end\n\n end\n\n else #This user is logged in but isn't registered with a service\n\n (1..14).each do |n|\n unless (today + n).saturday? or (today + n).sunday?\n hours[(today + n).to_s] = {open: \"08:00\", close: \"17:00\"}\n end\n end\n\n end # if #traveler.user_profile.user_services.count > 0\n end # if @travler.is_visitor\n\n render status: 200, json: hours\n\n end",
"def daily_midnight\n logger.info \" daily_midnight\"\n PersistStatsJob.create({})\n Gift.send_expiration_reminders(5)\n Gift.send_expiration_reminders(3)\n Gift.send_expiration_reminders(1)\n end",
"def weekly_time_generator(args = {:start_time => Time.now, :end_time => nil, :cron => ''})\n begin\n return [] if args[:cron].blank?\n\n # get cron as hash\n cron = cron_date args[:cron]\n\n # get the first value of the cron which is an integer and the pevious index\n # ex: cron = '41 * * * *' - we want to know that it starts every hour (prev index before the number) in the 41-st minute\n for k, v in cron do\n at = v\n break if v.class == 'Fixnum'\n # break in ruby continues the last iteration..\n every = k if v == '*'\n end\n\n changed_time = start_time = cron_generate_date args[:cron], args[:start_time]\n end_time = args[:end_time]\n\n # end_time is nil?\n end_time = Time.now.end_of_week if !end_time.respond_to? :year\n # end_time should not be longer than the end of this week\n end_time = end_time > start_time.end_of_week ? start_time.end_of_week : end_time\n\n all = []\n while changed_time <= end_time\n all << changed_time #changed_time.strftime(\"%d.%m.%Y %H:%M\")\n changed_time += 1.send(every)\n end\n\n all\n\n rescue => ex\n send_mail \"#{ex.class}: #{ex.message}. args: #{args}\" \n end\n\n end",
"def hour() end",
"def get_worked_hours_hash hours_array, hash\n first_hour_pos = 0\n hours_array.each do |hour|\n if is_different_day? hour.day, hours_array[first_hour_pos].day\n current_day = hours_array[first_hour_pos]\n first_hour_pos = hours_array.index(hour)\n worked_hours = get_worked_hours(current_day, hours_array[first_hour_pos - 1])\n hash = build_hash hash, current_day, worked_hours, hours_array[first_hour_pos - 1]\n elsif hours_array.index(hour) == hours_array.size - 1\n worked_hours = get_worked_hours(hours_array[first_hour_pos], hours_array[hours_array.size - 1])\n hash = build_hash hash, hours_array[first_hour_pos], worked_hours, hours_array[hours_array.size - 1]\n end\n end\n return hash\n end",
"def make_constant_schedule(name, temperature)\n s = OpenStudio::Model::ScheduleRuleset.new(@model)\n s.setName(name)\n s.defaultDaySchedule.addValue(OpenStudio::Time.new(\"24:00:00\"), OpenStudio::convert(temperature, \"F\", \"C\").get)\n\ts\n end",
"def generate_schedule(courses)\n num_days = 5\n num_time_slots = 111 # num of 5 minute intervals from 8:00am - 5:15pm\n schedule = Array.new(num_time_slots) { Array.new(num_days, 0)} # important !!!!!\n \n courses.each do |course|\n if course.meetingtime_start.nil? or course.meetingtime_end.nil? or \n course.meeting_days.nil?\n next\n end\n \n start_time = parse_time(course.meetingtime_start)\n end_time = parse_time(course.meetingtime_end)\n days = parse_day(course.meeting_days)\n schedule = insert_course(schedule, days, start_time, end_time)\n end\n \n # print_schedule(schedule)\n \n return schedule\n end",
"def generate_daytime_distribution \n \n end",
"def schedule_updates\n schedule_updates_in(24.hours, 48.hours)\n end",
"def advance_hours(hours)\n self + (hours * 60 * 60)\n end",
"def save_hours\n @day = Schedule.find(params[:monthday])\n\n @pitch.schedule.h0 = hours[0]\n @pitch.schedule.h1 = hours[1]\n @pitch.schedule.h2 = hours[2]\n @pitch.schedule.h3 = hours[3]\n @pitch.schedule.h4 = hours[4]\n @pitch.schedule.h5 = hours[5]\n @pitch.schedule.h6 = hours[6]\n @pitch.schedule.h7 = hours[7]\n @pitch.schedule.h8 = hours[8]\n @pitch.schedule.h9 = hours[9]\n @pitch.schedule.h10 = hours[10]\n @pitch.schedule.h11 = hours[11]\n @pitch.schedule.h12 = hours[12]\n @pitch.schedule.h13 = hours[13]\n @pitch.schedule.h14 = hours[14]\n @pitch.schedule.h15 = hours[15]\n @pitch.schedule.h16 = hours[16]\n @pitch.schedule.h17 = hours[17]\n @pitch.schedule.h18 = hours[18]\n @pitch.schedule.h19 = hours[19]\n @pitch.schedule.h20 = hours[20]\n @pitch.schedule.h21 = hours[21]\n @pitch.schedule.h22 = hours[22]\n @pitch.schedule.h23 = hours[23]\n @pitch.schedule.h24 = hours[24]\n @pitch.schedule.h25 = hours[25]\n @pitch.schedule.h26 = hours[26]\n @pitch.schedule.h27 = hours[27]\n @pitch.schedule.h28 = hours[28]\n @pitch.schedule.h29 = hours[29]\n @pitch.schedule.h30 = hours[30]\n @pitch.schedule.h31 = hours[31]\n @pitch.schedule.h32 = hours[32]\n @pitch.schedule.h33 = hours[33]\n @pitch.schedule.h34 = hours[34]\n @pitch.schedule.h35 = hours[35]\n @pitch.schedule.h36 = hours[36]\n @pitch.schedule.h37 = hours[37]\n @pitch.schedule.h38 = hours[38]\n @pitch.schedule.h39 = hours[39]\n @pitch.schedule.h40 = hours[40]\n @pitch.schedule.h41 = hours[41]\n @pitch.schedule.h42 = hours[42]\n @pitch.schedule.h43 = hours[43]\n @pitch.schedule.h44 = hours[44]\n @pitch.schedule.h45 = hours[45]\n @pitch.schedule.h46 = hours[46]\n @pitch.schedule.h47 = hours[47]\n\n return hours\n end",
"def days() 24 * hours end",
"def grandfather_clock &block\n hour = (Time.new.hour + 11)%12 + 1\n\n hour.times(&block)\nend",
"def hourly(options = {})\n branch options.merge(every: :hour)\n end",
"def hourly(options = {})\n branch options.merge(every: :hour)\n end",
"def hours\n \n end",
"def get_next_date(date, available_hours)\n # available_hours, ex : [(start_morning, end_morning), (start_afternoon, end_afternoon)]\n # 48 times because we want to try until the next day, same hour:\n # we add 0.5 hour each time so we have to add\n next_date = date + 30.minutes\n 48.times do\n available_hours.each do |interval|\n if (next_date.hour >= interval[0]) && (next_date.hour < interval[1])\n return next_date\n end\n end\n next_date += 30.minutes\n end\nend",
"def each_tuesday( n=1, offset=0, dur=1); each_wdays(self.Tue,n,offset,dur); end",
"def grandfather_clock &block\r\n hour = (Time.new.hour + 11)%12 + 1\r\n\r\n hour.times(&block)\r\nend",
"def each_saturday( n=1, offset=0, dur=1); each_wdays(self.Sat,n,offset,dur); end",
"def gen_reps(start_date = Date.current,\n end_date = Date.current.advance(:weeks => 1), period = 1)\n\n # must be the rep_parent\n if !self.rep_parent.nil?\n self.rep_parent.gen_reps(start_date, end_date, period)\n return\n end\n\n # check dates are dates\n if !start_date.is_a?(Date) or !end_date.is_a?(Date)\n puts \"start_date and end_date must be dates\"\n return\n end\n\n # make sure start before end\n if start_date > end_date\n puts \"start_date after end_date\"\n return\n end\n\n #check each day in date range\n date_range = start_date..end_date\n date_range.each do |date|\n if is_repeated_day(date)\n new_act = self.dup\n new_act.show_date = date\n if period != NO_EXPIRATION\n new_act.expiration_date = \n date.advance(:days => period)\n end\n new_act.parent_id = nil\n new_act.save!\n self.repititions << new_act\n end\n end\n end",
"def each_thursday( n=1, offset=0, dur=1); each_wdays(self.Thu,n,offset,dur); end",
"def seed_app_dining_periods\n start_hash = { 'Breakfast' => 8, 'Lunch' => 11, 'Dinner' => 16, 'Brunch' => 9, 'Late Night' => 20 }\n\n DiningOpportunity.all.each { |opp|\n DiningPlace.all.each { |dp|\n (0..6).each { |dow|\n start_hour = start_hash[opp.dining_opportunity_type]\n unless start_hour.blank?\n DiningPeriod.current_or_create_new(start_time: Time.now.change(hour: start_hour, min: rand(60)), end_time: Time.now.change(hour: start_hour + 3, min: rand(60)), day_of_week: dow, dining_opportunity_id: opp.id, dining_place_id: dp.id, institution_id: 1)\n end\n }\n }\n }\nend",
"def initialize(person, date)\n @person = person\n if (date.class == \"string\".class )\n\n @key_day = Date.strptime(date)\n else\n @key_day = date\n end\n week_begin = @key_day - @key_day.wday + 1\n week_end = @key_day - @key_day.wday + 7\n\n @items = {}\n tsi = TimesheetItem.find(:all, :conditions => [ \"hr_person_id = ? AND TO_DAYS(date) >= TO_DAYS(?) AND TO_DAYS(date) <= TO_DAYS(?)\", \n person, week_begin.strftime(\"%Y-%m-%d\"), week_end.strftime(\"%Y-%m-%d\") ])\n# raise week_begin.strftime + \"...\" + week_end.strftime\n\n @hours = 0\n tsi.each do | item |\n wday = item.date.wday() - 1\n if (wday == -1) then wday = 6 end\n if (@items [ wday ].nil?)\n @items[ wday ] = []\n end\n @items[ wday ].push(item)\n @hours = @hours + ((item.end - item.begin) / 3600)\n end\n end",
"def recurring; end",
"def populateWeek(timeS, course, duration, days, id, type)\n\n duration = duration*2 -1\n timeS = ((timeToDecimal(timeS)-8)*2).round\n\n if course !=''\n if type=='course'\n name = (course.faculty).to_s.upcase + (course.number).to_s\n elsif type == 'tutorial'\n name = (course.tutname).to_s.upcase\n else\n name = 'Course'\n end\n else\n name = 'NoName'\n end\n\n if days.include? \"Mo\"\n for i in 0..duration\n if @@mon[timeS + i][1] == false\n @@mon[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@mon[timeS + i][0])\n end\n end\n end\n if days.include? \"Tu\"\n for i in 0..duration\n if @@tue[timeS + i][1] == false\n @@tue[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@tue[timeS + i][0])\n end\n end\n end\n if days.include? \"We\"\n for i in 0..duration\n if @@wed[timeS + i][1] == false\n @@wed[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@wed[timeS + i][0])\n end\n end\n end\n if days.include? \"Th\"\n for i in 0..duration\n if @@thu[timeS + i][1] == false\n @@thu[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@thu[timeS + i][0])\n end\n end\n end\n if days.include? \"Fr\"\n for i in 0..duration\n if @@fri[timeS + i][1] == false\n @@fri[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@fri[timeS + i][0])\n end\n end\n end\n if days.include? \"Sa\"\n for i in 0..duration\n if @@sat[timeS + i][1] == false\n @@sat[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@sat[timeS + i][0])\n end\n end\n end\n if days.include? \"Su\"\n for i in 0..duration\n if @@sun[timeS + i][1] == false\n @@sun[timeS + i] = [name, true, id, type]\n else\n errorMessageSchedule(1, name, @@sun[timeS + i][0])\n end\n end\n end\n end",
"def hourly\n (0..23).collect { |h| redis.get(\"#{prefix_hourly}:#{Time.now.year}:#{Time.now.month}:#{Time.now.day}:#{h}\").to_i }\n end",
"def eac(hours = 1)\n eac = today_ac(hours) + etc(hours)\n eac.round(1)\n end",
"def price_rules \n # puts \"The start datetime: #{start_datetime}\"\n \n local_datetime = start_datetime.in_time_zone(\"Jakarta\") \n server_datetime = start_datetime\n # puts \"Jakarta_datetime: #{local_datetime} \"\n result_array = []\n current_calendar_id = self.calendar_id\n \n # how can we get the available price rules?\n # 1. get all \n \n # for each booked hour, get the associated price rule \n (1..number_of_hours).each do |x|\n datetime = local_datetime + (x-1).hours \n actual_booking_datetime = start_datetime + (x-1).hours \n server_booking_datetime = server_datetime + (x-1).hours\n \n book_hour_start = datetime.hour\n booking_creation_datetime = self.created_at \n \n \n current_calendar_id = self.calendar_id \n \n \n holiday_price_rule = PriceRule.where{\n # to ensure that we are using the old price at the time of creation\n (\n calendar_id.eq current_calendar_id\n ) & \n (\n is_holiday.eq true \n ) & \n (\n # is still active, and created before the booking creation \n (\n ( is_active.eq true) & \n (created_at.lte booking_creation_datetime)\n ) | \n # is not active, and created before the booking creation\n # and deactivated after the booking creation => \n # Hence, the rule is still in place\n (\n ( is_active.eq false) & \n ( created_at.lte booking_creation_datetime) & \n ( deactivated_at.gt booking_creation_datetime)\n )\n ) & \n\n # 0 - 23 \n (\n ( holiday_date.lte server_booking_datetime ) & \n ( finish_holiday_date.gt (server_booking_datetime + 1.hours - 1.seconds) )\n )\n }.order(\" id DESC\").first\n \n \n \n if not holiday_price_rule.nil?\n result_array << holiday_price_rule.id\n else\n \n price_rules = PriceRule.where{\n # to ensure that we are using the old price at the time of creation\n (\n calendar_id.eq current_calendar_id\n ) & \n\n\n (\n # is still active, and created before the booking creation \n (\n ( is_active.eq true) & \n (created_at.lte booking_creation_datetime)\n ) | \n # is not active, and created before the booking creation\n # and deactivated after the booking creation => \n # Hence, the rule is still in place\n (\n ( is_active.eq false) & \n ( created_at.lte booking_creation_datetime) & \n ( deactivated_at.gt booking_creation_datetime)\n )\n ) & \n\n # 0 - 23 \n (\n ( hour_start.lte datetime.hour ) & \n ( hour_end.gte datetime.hour )\n )\n }.order(\"id ASC, rule_case DESC\") # rule_case 2 == holiday, 1== specific, rule case 0= catch_all\n\n # puts \"Total price rule: #{price_rule.count}\"\n\n final_price_rule = []\n\n\n price_rules.each do |x|\n if x.is_sunday? and datetime.sunday?\n final_price_rule << x \n elsif x.is_monday? and datetime.monday?\n final_price_rule << x \n elsif x.is_tuesday? and datetime.tuesday?\n final_price_rule << x \n elsif x.is_wednesday? and datetime.wednesday?\n final_price_rule << x \n elsif x.is_thursday? and datetime.thursday?\n final_price_rule << x \n elsif x.is_friday? and datetime.friday?\n final_price_rule << x \n elsif x.is_saturday? and datetime.saturday? \n final_price_rule << x \n end\n end\n\n\n price_rule = final_price_rule.sort_by {|x| x.id }.last\n\n result_array << price_rule.id\n\n # corner case:\n # rule 1 : 1300-1300\n # rule 2 : 1300-1400 \n # booking time: 13.30 .. which rule will be selected? \n # we have the ordering by id, ASC\n # in this case: rule2 is created later.. rule2 will be selected. \n\n # corner case\n # rule1 : 2300-2300 \n # it means it will only affect the time from 2300-2400 \n\n\n \n end\n \n\n end\n \n return result_array\n end",
"def grandfather_clock &block\n hour = Time.new.hour\n if hour >= 13\n hour = hour - 12\n end\n if hour == 0\n hour = 12\n end\n hour.times do\n block.call\n end\nend",
"def time_slots\n collection=[]\n start_time=Time.now.beginning_of_hour\n end_time=Time.now.tomorrow.midnight-1.hour\n time=start_time\n\n while time < end_time\n collection<<[time.beginning_of_hour.hour, time.beginning_of_hour]\n time=time+1.hour\n end\n\n collection\n end",
"def sequential_day\n ActionPlan.sequential_day_for(week,day)\n end",
"def each_friday( n=1, offset=0, dur=1); each_wdays(self.Fri,n,offset,dur); end",
"def hour()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Hour::HourRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def lunch(day)\n\nend",
"def create\n today = Date.today # Today's date %>\n days_from_this_week = (today.at_beginning_of_week..today.at_end_of_week).map\n\n employee = Employee.where(:id => params[\"work_duration\"][\"eid\"]).first\n\n # First iterate over all the vendors this employee has\n for vendor in employee.vendors\n # Project is the relationship between employee and vendor, also workDuration record is attached to this relationship so we need to fetch it first\n project = employee.projects.where(:vendor_id => vendor.id).first\n\n # Next iterate over all the hours each day has\n (today.at_beginning_of_week..today.at_end_of_week).map.each_with_index do |day, index|\n\n # extract the number of hours for each \n hours_worked = params[\"work_duration\"][[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\"][index]+vendor.id.to_s]\n\n\n # Try to fetch the work duration object for the day that we are iterating over\n @work_duration = project.work_durations.where(work_day:day).first\n\n # if we did not find a pre existing work duration create new one else update oldone\n if @work_duration == nil\n @work_duration = project.work_durations.create(hours:hours_worked, work_day:day)\n else\n @work_duration.update_attributes(:hours => hours_worked)\n end\n end\n end\n #@work_duration = WorkDuration.new(work_duration_params)\n\n respond_to do |format|\n if @work_duration.save\n format.html { redirect_to employee, notice: 'Work duration was successfully created.' }\n format.json { render :show, status: :created, location: @work_duration }\n else\n format.html { render :new }\n format.json { render json: @work_duration.errors, status: :unprocessable_entity }\n end\n end\n end",
"def recurrence\n unless read_attribute(:recurrence).empty?\n IceCube::Rule.from_hash(read_attribute(:recurrence))\n end\n end",
"def remaining_hours_by_day\n values_by_day(0, true) { |x| model.remaining_hours_for_day_number(x) }\n end",
"def generate_schedule\r\n match_list = make_match_list\r\n schedule = make_empty_schedule\r\n # pp match_list\r\n # pp match_list.size\r\n\r\n scheduled_matches = []\r\n referee_count = 0\r\n move_to_next_slot = false\r\n\r\n schedule.each do |day|\r\n # puts \"#{day[:day]}\"\r\n day[:slots].each do |slots|\r\n # puts \" #{slots[:time]}\"\r\n\r\n match_count = -1\r\n move_to_next_slot = false\r\n match_to_validate = {}\r\n\r\n slots[:matches].each do |match|\r\n # puts \" scheduled (#{scheduled_matches.size})\"; pp scheduled_matches\r\n # puts \"match list (#{match_list.size})\"; pp match_list\r\n # puts \" to_val: \"; pp scheduled_matches\r\n while(!validate_rest_time(match_to_validate, scheduled_matches))\r\n match_count += 1 #next match on match_list\r\n # puts \" CLASH: mc=#{match_count} \"\r\n match_to_validate = {:teams=>match_list[match_count],:day => day[:day], :time => slots[:time]}\r\n\r\n if(match_list.size == match_count)\r\n # puts \"----> Move to next slot\"\r\n move_to_next_slot=true\r\n break\r\n end\r\n end\r\n\r\n # puts \"move_to_next_slot: #{move_to_next_slot}\"\r\n \r\n unless(move_to_next_slot)\r\n scheduled_matches << match_to_validate\r\n match[:referees] = REFEREES[referee_count%REFEREES.size]\r\n match[:score] = [0,0]\r\n match[:teams] = match_list.delete_at(match_count)\r\n # print \"Adding match: \"; pp match\r\n # puts \"-\"*34\r\n referee_count += 1\r\n match_count = 0\r\n match_to_validate = {:teams=>match_list[match_count], :day => match[:day], :time => match[:time]}\r\n else\r\n break\r\n end\r\n\r\n end\r\n\r\n end\r\n end\r\n\r\n schedule\r\n end",
"def hours_to_days(hours)\n hours / 24\nend",
"def time_sums(n)\n times = []\n hr = 0\n until hr == 24\n min = 0\n until min == 60\n min_sum = min.to_s.split('').map(&:to_i).reduce(&:+)\n hr_sum = hr.to_s.split('').map(&:to_i).reduce(&:+)\n sum = min_sum + hr_sum\n\n minString = min.to_s.split('')\n hrString = hr.to_s.split('')\n\n minString.unshift('0') until minString.length == 2\n hrString.unshift('0') until hrString.length == 2\n\n times << hrString.join('') + \":\" + minString.join('') if sum == n\n\n min += 1\n end\n hr += 1\n end\n times\nend",
"def create\n @schedule = Schedule.new(schedule_params)\n puts 'yoooo'\n rangeStart = Date.strptime(\"#{schedule_params['start(2i)']}/#{schedule_params['start(3i)']}/#{schedule_params['start(1i)']}\", \"%m/%d/%Y\")\n rangeEnd = Date.strptime(\"#{schedule_params['end(2i)']}/#{schedule_params['end(3i)']}/#{schedule_params['end(1i)']}\", \"%m/%d/%Y\")\n\n @shifts = Shift.all\n @employees = Employee.all\n\n days = %w(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)\n\n availability = [\n :mon_start,\n :mon_end,\n :tues_start,\n :tues_end,\n :wed_start,\n :wed_end,\n :thurs_start,\n :thurs_end,\n :fri_start,\n :fri_end,\n :sat_start,\n :sat_end,\n :sun_start,\n :sun_end\n ]\n\n @recent_schedule = Schedule.order(\"created_at\").last\n\n if @recent_schedule.blank?\n new_schedule_id = 1\n else\n new_schedule_id = @recent_schedule.schedule_id + 1\n end\n\n days.each_with_index do |dayName, dayOfTheWeek|\n @shifts.each do |s|\n\n s.active_days.split(\",\")\n\n if( s.active_days.include? days[dayOfTheWeek] )\n startTime = time_to_int(s.start)\n endTime = time_to_int(s.end)\n\n @employees.each do |e|\n employee_start_time = time_to_int(e[availability[dayOfTheWeek]])\n employee_end_time = time_to_int(e[availability[dayOfTheWeek + 1]])\n\n if employee_start_time.blank? == false && employee_end_time.blank? == false\n if(startTime >= employee_start_time && endTime <= employee_end_time)\n @schedule = Schedule.create(:schedule_id => new_schedule_id, :shift_id => s.id, :employee => e.name, :date => Time.now, :start => rangeStart, :end => rangeEnd)\n end\n end\n\n end\n end\n end\n end\n\n respond_to do |format|\n if @schedule.save\n format.html { redirect_to :action => \"show\", :id => new_schedule_id}\n format.json { render :show, status: :created, location: @schedule }\n else\n format.html { render :new }\n format.json { render json: @schedule.errors, status: :unprocessable_entity }\n end\n end\n end",
"def addDayOfWeekSpecification(time, dows)\n\t\tcurrentDow = time.wday\n\t\tnextDow = nil\n\t\tdows.each { |d|\n\t\t\tif d < currentDow\n\t\t\t\tdd = d + 7\n\t\t\telse\n\t\t\t\tdd = d\n\t\t\tend\n\t\t\tif nextDow.nil? or (dd < nextDow)\n\t\t\t\tnextDow = dd\n\t\t\tend\n\t\t}\n\t\tif nextDow\n\t\t\treturn time + (nextDow - currentDow) * 24 * 60 * 60\n\t\tend\n\t\treturn time\n\tend",
"def weekly_pay(rate, hours = 40)\n hours * rate\nend",
"def times_for_schedule_update_requests(start_time, end_time)\n times = []\n\n task_time = start_time.beginning_of_day + 15.hours\n task_time += 1.day if task_time < start_time\n\n while task_time < end_time\n times << task_time\n task_time += 1.day\n end\n\n times\n end",
"def hours\n fail \"A value is required for #{__method__}\" unless @value\n fail 'A value cannot be > 24' if @value > 24\n fail 'A value cannot be <= 0' if @value <= 0\n return 'daily' if @value == 24\n\n \"0/#{@value}:0:0\"\n end",
"def makeRecurr\n if repeats\n if recurrence.present?\n if recurrence.events.count == 1\n #We are the only event yet, HOOORAY\n dates = recurrence.getDatesAllInOne\n dates.each do |date|\n date = DateTime.parse(date.to_time.to_s)\n date = date.to_date\n if date != start.to_date\n\n #We do not want to override ourselve\n if !date.past?\n #We do not want to add past events\n time = start.to_time\n newStart = start\n newStart= newStart.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newEnd = self.end\n newEnd = newEnd.to_time.change(day: date.to_time.day, year: date.to_time.year, month: date.to_time.month)\n newStart = DateTime.parse(newStart.to_s)\n newEnd = DateTime.parse(newEnd.to_s)\n\n newEvent= Event.new(title: self.title, description: self.description,\n event_category: self.event_category, ort: self.ort, role_ids: self.role_ids, url: self.url,\n imageURL: self.imageURL, start: newStart, end: newEnd, repeats: false,\n priority: self.priority, flag: self.flag, author: self.author, manager: self.manager, admin: self.admin, state: self.state, recurrence: self.recurrence)\n newEvent.save!(:validate => false)\n end\n end\n end\n end\n end\n end\n end",
"def add_vals_to_sch(day_sch, sch_type, values)\n if sch_type == \"Constant\"\n day_sch.addValue(OpenStudio::Time.new(0, 24, 0, 0), values[0])\n elsif sch_type == \"Hourly\"\n for i in 0..23\n next if values[i] == values[i + 1]\n day_sch.addValue(OpenStudio::Time.new(0, i + 1, 0, 0), values[i]) \n end \n else\n #OpenStudio::logFree(OpenStudio::Info, \"Adding space type: #{template}-#{clim}-#{building_type}-#{spc_type}\")\n end\n end",
"def hours_for(hours)\n return 'closed' if hours.blank?\n\n hours.reduce '' do |memo, time_range|\n midnight = Time.current.midnight\n start_time = midnight.since(time_range.begin).strftime(TIME_FORMAT).strip\n end_time = midnight.since(time_range.end).strftime(TIME_FORMAT).strip\n\n memo + \"#{memo.empty? ? '' : ', '}#{start_time} to #{end_time}\"\n end\n end",
"def calculate(frequency, frequency_integer, start_date, end_date)\n first_due_date = @calendar.roll_forward(start_date)\n base_dates = [first_due_date]\n return [base_dates, base_dates] if frequency == 'Once'\n\n frequency_symbol = get_frequency_symbol(frequency)\n grace_dates = [first_due_date.advance(frequency_symbol => frequency_integer)]\n\n base_date = start_date\n end_date = calculate_end_date(start_date, end_date)\n\n while base_date < end_date\n grace_date = base_date.advance(frequency_symbol => frequency_integer*2)\n base_date = base_date.advance(frequency_symbol => frequency_integer)\n base_dates << @calendar.roll_forward(base_date)\n grace_dates << @calendar.roll_forward(grace_date)\n end\n\n [base_dates, grace_dates]\n end",
"def calculate!\n # When expanding the application to support multi-week pay periods, this code must be modified\n minutes_this_week = []\n daily_limit = 8 * 60 # in minutes\n weekly_limit = 40 * 60 # in minutes\n\n entries = employee_entries.reload # TODO: sort logic here \n \n entries.each do |e|\n duration = e.duration || 0\n date = e.payroll_worked_date = e.ticket.first_employee_entry\n \n minutes_this_week[e.employee_id] ||= { total: 0 }\n minutes_this_week[e.employee_id][date] ||= 0\n minutes_this_week[e.employee_id][date] += duration\n minutes_this_week[e.employee_id][:total] += duration\n \n overtime_today = minutes_this_week[e.employee_id][date] - daily_limit\n overtime_this_week = minutes_this_week[e.employee_id][:total] - weekly_limit\n overtime_max = [overtime_today, overtime_this_week, 0].max\n \n e.payroll_duration_standard = duration - overtime_max\n e.payroll_duration_standard = 0 if e.payroll_duration_standard < 0\n e.payroll_duration_overtime = duration - e.payroll_duration_standard\n \n e.payroll_bill_to = e.ticket.bill_to\n e.payroll_job_id = e.ticket.job_id\n e.payroll_status = if e.on_the_job? and e.payroll_job_id\n :bill_to_job\n else\n :overhead\n end\n e.payroll_pay_rate = if e.ticket.job\n e.ticket.pay_rate\n else\n :day_pay\n end\n \n e.payroll_category_string = \"#{e.employee_id} - #{e.payroll_bill_to} - #{e.payroll_job_id} - #{e.payroll_pay_rate} - #{e.payroll_status}\"\n \n e.save!\n end\n end",
"def search\n '''\n param: date - string\n param: start - string\n param: capacity - string\n param: length - string\n\n '''\n\n avail_rooms_id = []\n i = 1\n start_date_time = Time.parse(params[:date] + \" \" + params[:start])\n end_date_time = start_date_time + (60 * 60 * Integer(params[:length]))\n curr_date_time = start_date_time + (60 * 60)\n meal_room_cap = Integer(params[:capacity]) * 6/10\n comp_room_cap = Integer(params[:capacity]) * 1/10\n\n # Finds and adds conference to desired schedule id's\n conf_room = Schedule.where(\"cap > ? and time = ? and date = ? and avail = true\", \n params[:capacity], \n params[:start], \n params[:date]\n ).ids.first\n\n avail_rooms_id << conf_room\n\n while(curr_date_time != end_date_time - (60 * 60)) do\n \n curr_hour = curr_date_time.strftime('%I:%M %p')\n curr_date = curr_date_time.strftime('%F')\n \n # If i % 6, find room to eat with 60% of participants \n if i % 6 == 0\n\n meal_room = Schedule.where(\"cap > ? and time = ? and date = ? and food = true and avail = true\",\n meal_room_cap,\n curr_hour,\n curr_date\n ).ids.first\n\n avail_rooms_id << meal_room\n\n # else find room with computers to support 10% of participants\n else\n\n comp_room = Schedule.where(\"cap > ? and time = ? and date = ? and comp_avail = true and avail = true\",\n comp_room_cap,\n curr_hour,\n curr_date\n ).ids.first\n \n avail_rooms_id << comp_room\n \n end\n \n # Increments iteration, date, and time\n i += 1\n curr_date_time += (60 * 60)\n end\n\n # Finds and adds final room to desired schedule id's\n final_room = Schedule.where(\"cap > ? and time = ? and date = ?\",\n params[:capacity],\n end_date_time.strftime('%I:00 %p'),\n end_date_time.strftime('%F')\n ).ids.first\n \n avail_rooms_id << final_room\n\n # Checks if rooms were found and assigns them to instance variable\n if avail_rooms_id.empty? == false\n @avail_rooms = Schedule.find(avail_rooms_id)\n end\n end",
"def add_to_schedule(string)\n string = correct_format(string)\n parts = string.split(\"-\")\n hour1 = Integer(parts[0].split(\":\")[0])\n hour2 = Integer(parts[1].split(\":\")[0])\n if hour2 == hour1 + 1\n @schedule[parts[2]][\"#{parts[0]} - #{parts[1]}\"] = \"#{@rails_id}\" #\"1\" #schedule[parts[2]].push(\"#{parts[0]}-#{parts[1]}\")\n else \n while hour1 != hour2\n @schedule[parts[2]][\"#{hour1}:30 - #{hour1+1}:30\"] = \"#{@rails_id}\" #\"1\"\n hour1 = hour1+1\n end\n end\n return parts\n end",
"def hours_for_week(date)\n start_date = date.monday - 1.week - 1.day\n end_date = (date - 1.week).sunday - 1.day\n users_shifts = WorkshiftAssignment.where(workshifter_id: id,\n date: start_date..end_date)\n hours = 0\n users_shifts.each do |shift|\n hours += shift.hours * shift.hours_multiplier\n end\n hours - required_hours\n end",
"def create_by_raw(employee, date)\n \n return false if !employee.timeshift?\n\n ts = find_or_initialize_by(employee: employee, date: date)\n ts.timeblocks.clear\n\n # get rawdata of date\n raws = Rawdatum.timed(employee.enroll_number, date)\n # get dayoff of employee,date\n dayoff = Dayoff.by_date(date)\n\n # get employee timeshift\n shift = employee.timeshift.by_date(date)\n\n # dayoff is holiday if no timesheet\n if dayoff && raws.blank? then\n ts.timeblocks << Timeblock.new_block(dayoff.type, shift[:begin], shift[:end])\n ts.timeblocks << Timeblock.new_block(\"break\", shift[:break_begin], shift[:break_end])\n end\n\n case employee.timeshift.type\n when :auto then\n # in/out is 2 time event together\n raws.each_cons(2) do |slice|\n end\n when :filo then\n # if enough in/out for filo\n if raws.count > 1\n # get OT before working\n \n rfirst = raws.first.time\n rlast = raws.last.time\n otb_dur = UtilityHelper.duration(rfirst, shift[:begin])\n #w_dur = UtilityHelper.duration(rfirst, rlast)\n break_dur = UtilityHelper.duration(shift[:break_begin], shift[:break_end])\n ota_dur = UtilityHelper.duration(shift[:end], rlast)\n work_in = rfirst\n work_out = rlast\n\n if otb_dur > employee.timeshift.time_block\n #w_dur = UtilityHelper.duration(shift[:begin], rlast)\n work_in = shift[:begin]\n ts.timeblocks << Timeblock.new_block(\"otb\", rfirst, shift[:begin])\n end\n\n if ota_dur > employee.timeshift.time_block\n #w_dur = UtilityHelper.duration(shift[:begin], shift[:end])\n work_out = shift[:end]\n ts.timeblocks << Timeblock.new_block(\"ota\", shift[:end], rlast)\n end\n\n if break_dur > 0 && rfirst < shift[:break_begin]\n ts.timeblocks << Timeblock.new_block(\"break\", shift[:break_begin], shift[:break_end])\n end\n \n # get block FILO in working time first in/last out\n ts.timeblocks << Timeblock.new_block(\"working\", work_in, work_out)\n elsif raws.count == 1\n ts.timeblocks << Timeblock.new_block(\"filo\", raws.first.time, raws.first.time)\n else\n false\n end\n when :machine then\n # depend on inout_mode of rawdata to get timeblock\n end\n\n ts.save\n end",
"def each_wednesday(n=1, offset=0, dur=1); each_wdays(self.Wed,n,offset,dur); end",
"def hourly_totals(emoji)\n hour_zero = self.last_hour.where(emoji: emoji).pluck(:created_at).size\n hour_one = self.last_hour_plus_one.where(emoji: emoji).pluck(:created_at).size\n hour_two = self.last_hour_plus_two.where(emoji: emoji).pluck(:created_at).size\n hour_three = self.last_hour_plus_three.where(emoji: emoji).pluck(:created_at).size\n hour_four = self.last_hour_plus_four.where(emoji: emoji).pluck(:created_at).size\n some_days = [hour_zero, hour_one, hour_two, hour_three, hour_four]\n end",
"def grandfather_clock &block\n hours_passed = Time.new.hour%12\n hours_passed.times do\n block.call\n end\nend",
"def hours; self * HOUR; end",
"def hours; self * HOUR; end",
"def sequential_day\n puts \"AI.sequential_day = #{action_plan.sequential_day} + #{day-1}\"\n action_plan.sequential_day + day-1\n end"
] |
[
"0.66313756",
"0.63422376",
"0.6170693",
"0.6160254",
"0.61066705",
"0.600784",
"0.59787303",
"0.5962829",
"0.59465677",
"0.58838624",
"0.58235955",
"0.5812365",
"0.57726127",
"0.5766004",
"0.5765195",
"0.57523894",
"0.5750591",
"0.571505",
"0.5705398",
"0.5690481",
"0.56896913",
"0.5649943",
"0.56234556",
"0.5620843",
"0.5595064",
"0.55922633",
"0.55811894",
"0.5571526",
"0.5567334",
"0.5554913",
"0.555121",
"0.5538293",
"0.553758",
"0.5533811",
"0.55190814",
"0.5518147",
"0.5511365",
"0.5511188",
"0.55106014",
"0.5508855",
"0.55080676",
"0.54828215",
"0.5441943",
"0.54374677",
"0.54313886",
"0.5430096",
"0.5427404",
"0.540485",
"0.5395035",
"0.5393669",
"0.5390852",
"0.53755754",
"0.5369702",
"0.5369702",
"0.53572696",
"0.5347762",
"0.53446895",
"0.53393745",
"0.5339281",
"0.5337771",
"0.5316128",
"0.53152084",
"0.5306512",
"0.5306031",
"0.5300946",
"0.5287018",
"0.5285871",
"0.5282452",
"0.52771276",
"0.52767205",
"0.5266609",
"0.52605736",
"0.52590877",
"0.52572274",
"0.525702",
"0.5256409",
"0.5253461",
"0.5250672",
"0.5246406",
"0.52443",
"0.52363366",
"0.5232852",
"0.52232325",
"0.5221787",
"0.5216002",
"0.52159804",
"0.52152455",
"0.5213",
"0.52053803",
"0.52011746",
"0.51906806",
"0.51906604",
"0.51817614",
"0.5180493",
"0.51703066",
"0.51697975",
"0.5169305",
"0.5165992",
"0.5165431",
"0.51606786"
] |
0.57158464
|
17
|
Create a recurrence for given months of year
|
def month_of_year(months, *extras)
merge(month: months.array_concat(extras))
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def each_april( n=1); each_monthnum(self.Apr,n); end",
"def each_july( n=1); each_monthnum(self.Jul,n); end",
"def calculate_month_and_next_month(year, month)\n check_date = Time.new(year, month)\n {:actual => check_date, :next => check_date.next_month}\n end",
"def each_march( n=1); each_monthnum(self.Mar,n); end",
"def months_in_year\n 12\nend",
"def test_yearly_by_month_loop\n parse(\n 'FREQ=YEARLY;INTERVAL=1;UNTIL=20120203T225959Z;BYMONTH=2;BYSETPOS=1;BYDAY=SU,MO,TU,WE,TH,FR,SA',\n '2012-01-01 15:45:00',\n [\n '2012-02-01 15:45:00'\n ],\n '2012-01-29 23:00:00'\n )\n end",
"def each_may( n=1); each_monthnum(self.May,n); end",
"def period\n case self.recurring_month\n when 12\n 1.year # 1.year != 12.months\n else\n self.recurring_month.months\n end\n end",
"def fixed_monthly_payment(amount, months, ir )\n amount*( ir * ( 1 + ir ) **months )/(( 1 + ir )**months - 1 )\nend",
"def each_january( n=1); each_monthnum(self.Jan,n); end",
"def each_february( n=1); each_monthnum(self.Feb,n); end",
"def setup_months(start_month, end_month)\n @months = []\n while start_month <= end_month\n @months << start_month\n start_month += 1\n end\n end",
"def each_october( n=1); each_monthnum(self.Oct,n); end",
"def months() 30 * days end",
"def nwrug_meet_for year, month\n beginning_of_month = Date.civil(year, month, 1)\n nwrug = beginning_of_month + (18 - beginning_of_month.wday)\n nwrug += 7 if beginning_of_month.wday > 4\n\n # Make sure we skip to the next month if we've gone past this month's meet\n if nwrug < Date.today\n if month == 12\n month = 1\n year += 1\n else\n month += 1\n end\n nwrug = nwrug_meet_for year, month\n end\n\n nwrug\nend",
"def months ; self * 30.days ; end",
"def associated_months\n result = [] # expect no months if no dates\n years = associated_years\n \n\t start_date = event_start\n\t start_date = entry_deadline if is_opportunity?\n\t \t \n start_month_year = Time.parse(\"01/#{start_date}.month/#{start_date}.year\") if !start_date.blank?\n finish_month_year = Time.parse(\"01/#{event_finish}.month/#{event_finish}.year\") if !event_finish.blank?\n \n #this is the case when we only have a start month\n if !start_month_year.blank? and finish_month_year.blank?\n result << start_date.month\n #this is the tricky one...\n elsif !start_month_year.blank? and !finish_month_year.blank?\n delta_year = event_finish.year - start_date.year # year\n \n #if the range spans an entire year we have all the months\n if (delta_year) > 1\n result = [1,2,3,4,5,6,7,8,9,10,11,12]\n #this is the case of months being in the same year\n elsif delta_year == 0\n puts start_month_year.month\n puts finish_month_year.month\n for m in start_month_year.month..finish_month_year.month\n result << m\n end\n \n #this is the annoying one, going over new year\n elsif delta_year == 1\n #add months to year end\n for month in start_month_year.month..12\n result << month\n end\n \n #add months from start of year\n for month in 1.. finish_month_year.month\n result << month\n end \n end\n result\n end\n \n \n \n \n result\n end",
"def end_of_month\n self.class.new year, month + 1, 0\n end",
"def months; self * MONTH; end",
"def each_june( n=1); each_monthnum(self.Jun,n); end",
"def each_august( n=1); each_monthnum(self.Aug,n); end",
"def >>(months)\n y, m = (@year * 12 + (@month - 1) + months).divmod(12)\n m, = (m + 1) .divmod(1)\n d = @day\n d -= 1 until self.class.valid?(y, m, d)\n self.class.new(y,m,d)\n end",
"def each_december( n=1); each_monthnum(self.Dec,n); end",
"def month\n running_days = 0\n DAYS_IN_MONTH.each_with_index do |days, idx|\n running_days += days\n return idx + 1 if self.day_of_year <= running_days\n end\n end",
"def fridays_in_year(year)\n current_week = 1\n current_day = 5\n current_date = DateTime.commercial(year, current_week, current_day)\n fridays_per_month = Array.new(12,0)\n while current_date.year == year\n fridays_per_month[current_date.month - 1] += 1\n current_date += 7\n end\n fridays_per_month\nend",
"def next_month(months = 1)\n advance(months: months)\n end",
"def maximum_number_of_months_to_recur\n self.period.length_in_months -\n self.period.month_for_date(date)\n end",
"def each_months(n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt.to_date >> offset }\n s.increment { |dt,i| dt.to_date >> i }\n s.span { |dt| dt.to_date >> dur }\n end\n end",
"def increment_by_days count\n new_day = @day\n new_month = @month\n new_year = @year \n \n while count > 0\n days_to_next_month = days_in_month(new_month, new_year) - new_day + 1\n \n if (days_to_next_month > count)\n new_day = new_day + count\n count = 0 \n else\n new_day = 1\n new_month = new_month + 1\n if (new_month > 12)\n new_month = 1\n new_year = new_year + 1\n end\n \n count = count - days_to_next_month \n end\n end\n \n return MyDate.new new_day, new_month, new_year\n end",
"def each_november( n=1); each_monthnum(self.Nov,n); end",
"def next_month(month, year)\n if month == 12\n [1, year + 1]\n else\n [month + 1, year]\n end\nend",
"def monthly\n end",
"def no_repeat_years(first_year, last_year)\nend",
"def add_months(months = 1)\n months = months.to_i\n cur_month = @t_month\n cur_day = @t_day\n next_month = cur_month + months.to_i\n \n #Check if we have to alter the amount of years based on the month-change.\n if next_month > 12 or next_month <= 0\n years = (next_month.to_f / 12.0).floor\n \n newmonth = next_month - (years * 12)\n if newmonth == 0\n newmonth = 12\n years -= 1\n end\n \n self.month = newmonth\n self.add_years(years) if years != 0\n else\n raise \"Invalid month: '#{next_month}'.\" if next_month <= 0 or next_month > 12\n @t_month = next_month\n @t_day = 1\n end\n \n \n #If the month changed, and the day was the last day of the previous month, and there isnt that many days in the new month, set the day to the last day of the current month.\n dim = self.days_in_month\n \n if dim < cur_day\n @t_day = dim\n else\n @t_day = cur_day\n end\n \n return self\n end",
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def month() end",
"def make_year_stats(months)\n rows = months.map{|month|\n items = Item.all(:conditions => {\n :date => month_range(month),\n :type => [\"Expense\", \"Income\"]\n }).group_by(&:category)\n\n make_row(month, items)\n }\n\n return rows.push make_sum_row(rows)\n end",
"def month_of_year(*months)\n merge(month: months)\n end",
"def create_date_value\n \n 1.upto(months.length) do |month|\n 1.upto(month) do |day|\n arr << [\"2015#{day}#{month}\", day_of_week]\n end\n end\nend",
"def each_monthnum(nmonth,n=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt >> (nmonth - dt.month)%12 }\n s.increment { |dt,i| dt.to_date >> i*12 } \n s.span { |dt| dt.to_date >> 1 }\n end\n end",
"def get_months(years, months)\n if years > 0\n (years * 12) + months\n elsif years > 0 && months == 0\n years * 12\n else\n months\n end\nend",
"def year_month_ranges year\n\t\t\tfrom = Date.new(year, Time.now.month, Time.now.beginning_of_month.day) - 1.year\n\t\t\tto = Date.new(year, Time.now.month, Time.now.end_of_month.day)\n\t\t\t(from..to).group_by(&:month).map { |n,v| v.first.beginning_of_month.to_s..(v.first.end_of_month + 1.day).midnight.to_s }\n\t\tend",
"def term\n return nil unless start_time\n case start_time.mon\n when 1..3 # Lent term\n return month_range( start_time.year, 1, 3 )\n when 4..6 # Easter term\n return month_range( start_time.year, 4, 6 )\n when 7..9 # Long vac.\n return month_range( start_time.year, 7, 9 )\n when 10..12 # Michaelmas term\n return month_range( start_time.year, 10, 12 )\n end\n end",
"def years_to_months(years)\n #some code here\nend",
"def find_months_to_generate\n @dates_of_each_month = []\n @dates = Event.all.pluck(:date)\n @dates.each do |date|\n @dates_of_each_month << date.beginning_of_month\n end\n @dates_of_each_month.uniq!\n end",
"def month_range(month, year)\n next_month = month == 12 ? 1 : month + 1\n next_year = month == 12 ? year + 1 : year\n Date.new(year, month, 1)..Date.new(next_year, next_month, 1)\n end",
"def initial_window_months(order)\n order.total > 0 ? 1 : 12\n end",
"def monthly(options = {})\n branch options.merge(every: :month)\n end",
"def monthly(options = {})\n branch options.merge(every: :month)\n end",
"def totals_by_month_year\n revenue = Hash.new { |hash, key| hash[key] = {} }\n leases_by_year.each do |lease|\n lease.each do |year, months|\n months.each do |month, rent|\n revenue[year][month] ? revenue[year][month] += rent : revenue[year][month] = rent\n end\n end\n end\n revenue\n end",
"def advance_months(months)\n advance_to_date(to_date >> months)\n end",
"def months ; Duration[self * 30 * 86400] ; end",
"def day_number_of_the_year day, month, hash \n if month > 1\n for i in 1...month\n day += hash[i]\n end\n end\n day\nend",
"def years_to_month(years)\n years * 12.0\nend",
"def create_expenses\n expense_id = nil\n @expense = @account.expenses.create(expense_params)\n step = params[:expense_form][:recurrence].to_i\n\n if @expense.valid? && step != 0\n @expense.month_id = @expense.due_date.mon\n @expense.save \n start_month = @expense.due_date.mon + step\n number_of_months = step\n (start_month..12).step(step).each do |month|\n @expense = @account.expenses.new(expense_params)\n @expense.month_id = month\n @expense.due_date = @expense.due_date.to_date >> number_of_months\n number_of_months += step\n @expense.related_to = expense_id || @expense.id\n @expense.save\n expense_id ||= @expense.id\n end\n elsif @expense.valid?\n @expense.month_id = @expense.due_date.mon\n @expense.save\n end\n @expense.valid?\n end",
"def period_in_words\n case recurring_month\n when 12\n 'yearly'\n when 1\n 'monthly'\n when 0\n \"once\"\n else\n \"every #{recurring_month} months\"\n end\n end",
"def months\n @years * 12\n end",
"def mortal_fibonacci_rabbits(months, lived_months)\r\n pairs = [1, 1]\r\n x = 2\r\n while x < months\r\n total = 0\r\n if lived_months > x\r\n pairs.push( (pairs[x-1]) + (pairs[(x-2)]) )\r\n else\r\n for n in (2..lived_months)\r\n total += pairs[x - n]\r\n end\r\n pairs.push(total)\r\n end\r\n x += 1\r\n end\r\n return pairs[months - 1]\r\nend",
"def add_month(age) \n GenFactor::sanitize_age((age + (1.0/12.0)))\n end",
"def frm(r, n, po)\n\t## \n\t# interest rate is converted to fraction and made a monthly\n\tr = r.to_f/100/12\n\t##\n\t#number of years is converted to number of months\n\tn = n * 12\n\t##\n\t#monthly payment is calculated\n\tc = (r / (1 - (1+r) ** -n) ) * po\n\treturn c\nend",
"def generate_month_expenses\n Expense.all.each do |expense|\n MonthExpense.create(month_id: self.id, expense_id: expense.id)\n end\n end",
"def after_n_months(year, month)\n\tif year == nil\n\t\t\"year missing\"\n\telsif month == nil\n\t\t\"month missing\"\n\telse\n\t\t(year + month/12).to_i\n\tend\nend",
"def no_repeat_years(first_yr, last_yr)\n result = []\n (first_yr..last_yr).each do |num|\n if not_repeat_year?(num)\n result << num\n end\n end\n result\nend",
"def get_monthly_payments(loan, interest, months)\n loan * (interest / (1 - (1 + interest)**(-months)))\nend",
"def each_years(n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| Date.civil(dt.year + offset, dt.month, dt.day) }\n s.increment { |dt,i| Date.civil(dt.year + i, dt.month, dt.day) }\n s.span { |dt| Date.civil(dt.year + dur, dt.month, dt.day) }\n end \n end",
"def calculate_n_months(loan_duration)\n 12 * loan_duration\nend",
"def calc_days_in_month month, year\n months_with_30 = [4, 6, 9, 11]\n months_with_31 = [1, 3, 5, 7, 8, 10, 12]\n if months_with_30.include? month\n 30\n elsif months_with_31.include? month\n 31\n elsif (year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0)\n 29\n else\n 28\n end\n end",
"def beginning_of_month\n self.class.new year, month, 1\n end",
"def month; end",
"def month; end",
"def increment_month!\n if month != 12\n # just bump up a number\n self.date = ZDate.format_date(year_str, month + 1)\n else\n self.date = ZDate.format_date(year + 1)\n end\n end",
"def year_to_month_rate_convert(apr_in_decimals, loan_duration)\n ((1 + (apr_in_decimals / loan_duration))**loan_duration) - 1\nend",
"def set_variables(month, year)\n @month = month\n @year = year\n\n @start_of_month = Date.parse(\"#{year}-#{month}-1\")\n @days_in_month = Time.days_in_month(@month, @year)\n\n @dates = [[]]\n\n # Add blank dates before 1st of month\n blank_spaces_at_start_of_cal(@start_of_month.wday).times { @dates[0] << nil }\n\n # Loop over days in given month\n @days_in_month.times do |date_in_month|\n date_in_month = date_in_month + 1\n\n row = (date_in_month + day_of_week(@start_of_month.wday) - 1) / 7\n row -= 1 if day_of_week(@start_of_month.wday) == 7 && (date_in_month + 6) % 7 == 0\n\n @dates[row] = [] unless @dates[row]\n @dates[row] << date_in_month\n end\n\n # Fill remaining array with nil values after the last day of the month\n # to keep aesthetic consistency\n if @dates.last.length < 7\n (7 - @dates.last.length).times do |n|\n @dates.last << nil\n end\n end\n\n @active_employees = Employee.all.where(active: true)\n end",
"def effective_months\n return 0 if start_date > end_date\n y = (end_date.year - start_date.year) * 12\n m = (end_date.mon - start_date.mon)\n last_month_days = ((end_date.day - end_date.beginning_of_month.day) + 1).to_f / end_date.end_of_month.day\n first_month_days = ((start_date.end_of_month.day - start_date.day) + 1).to_f / start_date.end_of_month.day\n first_and_last = start_date.day - 1 == end_date.day ? 1 : last_month_days + first_month_days\n (y + m + first_and_last) - 1\n end",
"def future(year, month, day)\n years = (10 ** 9) / 60 / 60 / 24 / 365\n days = (10 ** 9) / 60 / 60 / 24 % 365\n\n year = year + years\n \n\nend",
"def months\n Thread.current[:datet_mode] = :months\n return self\n end",
"def iterate(m)\n i = 0\n 6.times do\n print_year_body(m, i)\n i += 1\n end\n end",
"def get_monthly_rate(apr)\n (apr / 100) / 12\nend",
"def prorated_price_for(year,month)\n m_days = amount_of_days_reserved_in(year,month)\n \n return 0 if m_days == 0\n \n if m_days == days_in(month)\n @monthly_price\n elsif m_days == days_in(month).round(-1) / 2\n @monthly_price / 2 # put this in here just to get line 2 of notes to pass ;)\n else\n (@monthly_price / days_in(month)) * m_days\n end\n end",
"def referrals_needed_per_month\n 5 * monthly_transaction_goal\n end",
"def set_year(m)\n if set_month(m) > 2 and set_month(m) < 13\n @year.to_i\n else\n @year.to_i - 1\n end\n end",
"def each_month\n @all_expenses ||= Expense.find(:all, :order => 'date')\n return if @all_expenses.empty?\n date = @all_expenses.first.date.beginning_of_month\n end_date = @all_expenses.last.date\n while date <= end_date\n yield date\n date += 1.month\n end\n end",
"def initialize(first_year, first_month, last_year, last_month)\n @first_year = first_year\n @first_month = first_month\n @last_year = last_year\n @last_month = last_month\n @months = (Month.new(first_year, first_month)..Month.new(last_year, last_month)).to_a\n end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).reduce([]) do |output, el|\n if not_repeat_year?(el)\n output << el\n else\n output\n end\n end\nend",
"def set_boundaries\n months = calculate_month_and_next_month(@values[:year],\n @values[:time_frame])\n set_values(months)\n return \"Calculated interval for month from input:\" \\\n \" #{months[:actual]} - #{months[:next]}\"\n end",
"def month=(_arg0); end",
"def no_repeat_years(first_yr, last_yr)\n (first_yr..last_yr).reduce([]) do |arr, year|\n if not_repeat_year?(year)\n arr << year\n else\n arr\n end\n end\nend",
"def month_calculations\n\t\t@prev_beg_range = @beg_range.to_date.beginning_of_month.prev_month\n\t\t@prev_end_range = @beg_range.to_date.beginning_of_month-1.day\n\t\t@next_beg_range = @beg_range.to_date.next_month.beginning_of_month\n\t\t@next_end_range = @beg_range.to_date.next_month.end_of_month\n\tend",
"def yearly(options = {})\n branch options.merge(every: :year)\n end",
"def yearly(options = {})\n branch options.merge(every: :year)\n end",
"def calculate_years(principal, interest, tax, desired)\n# principal amount\n year = 0\n while principal < desired\n year += 1\n income = principal * interest\n principal += income - income * tax\n end\n year\nend",
"def year_month_int_to_year_and_month(year_month)\n [year_month / 12, (year_month % 12) + 1]\n end",
"def each_september(n=1); each_monthnum(self.Sep,n); end",
"def monthly_payment(salary_per_annum)\n return salary_per_annum / 12\nend",
"def year_calculations\n\t\t@prev_beg_range = @beg_range.to_date.beginning_of_year.prev_year\n\t\t@prev_end_range = @beg_range.to_date.beginning_of_year-1.day\n\t\t@next_beg_range = @beg_range.to_date.next_year.beginning_of_year\n\t\t@next_end_range = @beg_range.to_date.next_year.end_of_year\n\tend",
"def roll_period_for_date(date)\n if date < start_date_of_roll_period(date.year, date.month)\n previous_month, year_of_previous_month = *previous_month(date.month, date.year)\n roll_period_starting_with_month(previous_month, year_of_previous_month)\n else\n roll_period_starting_with_month(date.month, date.year)\n end\nend",
"def fix_frequency\n return unless frequency.duration > 1.month\n if frequency.duration < 12.months\n if intervals.all? { |i| i.first_datetime.day == i.last_datetime.day }\n frequency.duration = frequency.units[:months].months\n end\n else\n if intervals.all? { |i| i.first_datetime.month == i.last_datetime.month && i.first_datetime.day == i.last_datetime.day }\n frequency.duration = (frequency.duration / 12.months).floor.years\n end\n end\n end",
"def fibonacci_rabbits(months, offspring, sequence = false)\r\n pairs = [1, 1]\r\n x = 2\r\n while x < months\r\n pairs.push( (pairs[x-1]) + (pairs[(x-2)]*offspring) )\r\n x += 1\r\n end\r\n if sequence\r\n return pairs\r\n end\r\n return pairs[months - 1]\r\nend",
"def count_of_days_in(month)\n 28 + (month + (month / 8)) % 2 + 2 % month + 2 * (1 / month)\nend",
"def get_number_of_month\n (1..is_leap?[adjust_set_month]).to_a\n end"
] |
[
"0.6542906",
"0.65370196",
"0.63910246",
"0.63830227",
"0.6307242",
"0.6290549",
"0.6285185",
"0.62744427",
"0.6267703",
"0.6240375",
"0.62143344",
"0.6159275",
"0.61251575",
"0.6118346",
"0.6113192",
"0.6103073",
"0.6101565",
"0.60980743",
"0.6083123",
"0.60818",
"0.6059043",
"0.6055971",
"0.6044512",
"0.6026451",
"0.60200703",
"0.6017649",
"0.6015288",
"0.5981923",
"0.59753674",
"0.5958679",
"0.5940321",
"0.59116936",
"0.59084046",
"0.5878144",
"0.5872648",
"0.58692163",
"0.58669525",
"0.5862756",
"0.5853601",
"0.58519137",
"0.5847231",
"0.5845558",
"0.57884747",
"0.5769579",
"0.5758785",
"0.5743038",
"0.57413214",
"0.57353747",
"0.57353747",
"0.572762",
"0.5708901",
"0.56977516",
"0.5697727",
"0.5692543",
"0.5692069",
"0.568765",
"0.5675383",
"0.56645733",
"0.5661107",
"0.5644882",
"0.5640095",
"0.5603597",
"0.55869234",
"0.5580617",
"0.5578417",
"0.5569765",
"0.5557636",
"0.55294985",
"0.55283207",
"0.55283207",
"0.5527187",
"0.55159175",
"0.551591",
"0.5515199",
"0.55099726",
"0.5502497",
"0.549087",
"0.5481222",
"0.5479735",
"0.5476161",
"0.5475045",
"0.5473183",
"0.54694206",
"0.5462874",
"0.5457102",
"0.54375046",
"0.54304856",
"0.5423383",
"0.5421556",
"0.5421556",
"0.5419986",
"0.54143876",
"0.54113805",
"0.54108435",
"0.5401849",
"0.5390024",
"0.53893083",
"0.53864026",
"0.5381132",
"0.5379253"
] |
0.5870216
|
35
|
Create a recurrence for given weeks of year
|
def week_of_year(weeks, *extras)
merge(week: weeks.array_concat(extras))
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def week_pattern\n year_weeks == 53 ? [5,4,5]+[4,4,5]*3 : [4,4,5]*4\n end",
"def weeks() 7 * days end",
"def weeks_in_year(year)\n date_calc.weeks_in_year(year)\n end",
"def year_week\n @year_week ||= (((date-start_of_year)+1)/7.0).ceil\n end",
"def week_of_year(*weeks)\n merge(week: weeks)\n end",
"def weeks ; self * 7.days ; end",
"def weeks\n result = end_week - start_week + 1\n weeks = Date.new(start_date.year, 12, 31).strftime('%W').to_i\n result < 0 ? result + weeks : result\n end",
"def next_week_in weeks\n Week.find_by(initial_day: initial_day+( weeks * 7.days))\n end",
"def weeks_in_year\n return (self-(self.yday-1)).wday == 6 && self.leap? ? 54 : 53\n end",
"def weeks_with_year\n rows = []\n rows << \"Su Mo Tu We Th Fr Sa\" + \" \"\n days = format_dates\n (0..7).each {|num|\n fields = days[num * 7, 7]\n rows << fields.join(\" \") + \" \" if fields\n }\n\n if rows.last.length < 22\n rows.last << \" \" * (22 - rows.last.length)\n end\n\n until rows.length == 7\n rows << \" \" * 22\n end\n rows\n end",
"def fridays_in_year(year)\n current_week = 1\n current_day = 5\n current_date = DateTime.commercial(year, current_week, current_day)\n fridays_per_month = Array.new(12,0)\n while current_date.year == year\n fridays_per_month[current_date.month - 1] += 1\n current_date += 7\n end\n fridays_per_month\nend",
"def weeks ; Duration[self * 604800] ; end",
"def setup_weeks(week_start)\n a_date = self.first\n the_last = self.last\n @weeks = []\n\n while (a_date < the_last)\n @weeks << Koyomi::Week.new(a_date, week_start)\n a_date += WEEK_DAYS\n end\n @weeks\n end",
"def weeks; self * WEEK; end",
"def weeks; self * WEEK; end",
"def weeks\n self.to_i * 604_800\n end",
"def week\n cweek = self.cweek\n year = self.year\n month = self.month\n\n next_year = year + 1\n previous_year = year - 1\n\n days = Date.new(year)\n .step(Date.new(year, -1, -1))\n .select{ |d| d.cweek == cweek }\n\n if cweek == 1 && month == 12 ||\n cweek == 1 && month == 1 ||\n cweek >= 52 && month == 12 ||\n cweek >= 52 && month == 1\n\n days.keep_if{ |d| d.year == year && d.month == month }\n end\n\n if days.count < 7\n rest = 7 - days.count\n\n rest_days = nil\n if month == 1\n rest_days = Date.new(previous_year, 12, 31 - rest + 1).step(Date.new(previous_year, 12, 31))\n elsif month == 12\n rest_days = Date.new(next_year).step(Date.new(next_year, 1, rest))\n end\n\n if !rest_days.nil?\n days += rest_days.to_a\n end\n end\n\n days.sort[0, 7]\n end",
"def iso_weeks_in_year(wkst)\n iso_year, week_one_start = *iso_year_and_week_one_start(wkst)\n probe_date = week_one_start + (7*52)\n if probe_date.iso_year(wkst) == iso_year\n 53\n else\n 52\n end\n end",
"def ops_calendar\n # setup calendar cells\n @today = Date.today - 3\n if @today.strftime(\"%a\") == \"Mon\"\n @start_date = @today\n else\n @start_date = @today\n until @start_date.strftime(\"%a\") == \"Mon\"\n @start_date -= 1\n end\n end\n @end_date = @start_date+21\n @date_range = (@start_date..@end_date)\n @weeks = @date_range.to_a.in_groups_of(3)\n\n\n end",
"def next_week(x = 1)\n\t\tself + (604800 * x)\n\tend",
"def apply_function_week_of_year(scope, ast)\n scope, date = apply_ast(scope, ast.children.first)\n return scope, \"(date_part('week', #{date})::integer)\"\n end",
"def dates_for_week(year, week_num)\n calendar_year_start = dates_for(1, year).first\n calendar_year_end = dates_for(12, year).last\n calendar_range = calendar_year_start..calendar_year_end\n\n dates = calendar_range.each_slice(7).take(week_num).last\n dates.first..dates.last\n end",
"def week_fields_for(date)\n week_data_cache[date] ||= begin\n eyear = date.year\n day_of_week = date.wday + 1\n day_of_year = date.yday\n\n # this should come from the CLDR's supplemental data set, but we\n # don't have access to it right now\n first_day_of_week = 1 # assume sunday\n minimal_days_in_first_week = 1 # assume US\n\n # WEEK_OF_YEAR start\n # Compute the week of the year. For the Gregorian calendar, valid week\n # numbers run from 1 to 52 or 53, depending on the year, the first day\n # of the week, and the minimal days in the first week. For other\n # calendars, the valid range may be different -- it depends on the year\n # length. Days at the start of the year may fall into the last week of\n # the previous year; days at the end of the year may fall into the\n # first week of the next year. ASSUME that the year length is less than\n # 7000 days.\n year_of_week_of_year = eyear\n rel_dow = (day_of_week + 7 - first_day_of_week) % 7 # 0..6\n rel_dow_jan1 = (day_of_week - day_of_year + 7001 - first_day_of_week) % 7 # 0..6\n woy = (day_of_year - 1 + rel_dow_jan1) / 7 # 0..53\n\n if (7 - rel_dow_jan1) >= minimal_days_in_first_week\n woy += 1\n end\n\n # Adjust for weeks at the year end that overlap into the previous or\n # next calendar year.\n if woy == 0\n # We are the last week of the previous year.\n # Check to see if we are in the last week; if so, we need\n # to handle the case in which we are the first week of the\n # next year.\n\n year_length = (Date.new(eyear, 1, 1) - Date.new(eyear - 1, 1, 1)).to_i\n\n prev_doy = day_of_year + year_length\n woy = week_number(prev_doy, day_of_week)\n year_of_week_of_year -= 1\n else\n last_doy = (Date.new(eyear + 1, 1, 1) - Date.new(eyear, 1, 1)).to_i\n # Fast check: For it to be week 1 of the next year, the DOY\n # must be on or after L-5, where L is yearLength(), then it\n # cannot possibly be week 1 of the next year:\n # L-5 L\n # doy: 359 360 361 362 363 364 365 001\n # dow: 1 2 3 4 5 6 7\n if day_of_year >= (last_doy - 5)\n last_rel_dow = (rel_dow + last_doy - day_of_year) % 7\n\n if (last_rel_dow < 0)\n last_rel_dow += 7\n end\n\n if ((6 - last_rel_dow) >= minimal_days_in_first_week) && ((day_of_year + 7 - rel_dow) > last_doy)\n woy = 1;\n year_of_week_of_year += 1\n end\n end\n end\n\n {\n week_of_year: woy,\n year_woy: year_of_week_of_year,\n week_of_month: week_number(date.mday, day_of_week),\n day_of_week_in_month: (date.mday - 1) / 7 + 1\n }\n end\n end",
"def get_week_report(week, year)\n\n week_start = Date.commercial(year, week)\n\n time_entries(week_start, week_start + 7).group_by { |e| e[:start].wday }.map do |_, date_entries|\n\n date = date_entries.first[:start]\n durations = date_entries.group_by { |e| e[:description] }\n .map { |desc, entries| [desc, entries.map { |e| e[:duration] }.reduce(&:+)] }\n total_duration = durations.map { |_, d| d }.reduce(&:+)\n\n {\n date: date,\n total_duration: total_duration,\n durations: durations\n }\n end\n end",
"def week\n working_date = DateTime.new(self.year, 1, 1)\n working_date.week_day_start = self.week_day_start\n working_date = (working_date-working_date.send(\"wday_offset\"))\n week_num = 0\n working_date.step(self) { |a_day| \n if a_day.wday == _week_day_numbers.first\n week_num += 1\n end\n }\n week_num\n end",
"def by_week(value, options = {})\n year = work_out_year(options[:year] || Time.now.year)\n # Dodgy!\n # Surely there's a method in Rails to do this.\n start_time = if value.class == Time || value.class == Date\n (value.strftime(\"%U\").to_i - 1).weeks\n year = value.year\n elsif value.to_i.class == Fixnum && value < 52\n Time.utc(year, 1, 1) + (value.to_i - 1).weeks\n else\n raise ParseError, \"by_week takes only a Time object, or a Fixnum (less than 52).\"\n end\n end_time = start_time + 1.week\n \n by_star(start_time, end_time, options)\n end",
"def add_recurrence_from_params\n on = recurrence_on.map(&:to_sym)\n at = transform_string_to_times(recurrence_at)\n clear_schedule\n add_recurrence(type: :week, on: on, at: at)\n end",
"def week; end",
"def each_weeks(n=1, offset=0, dur=1)\n each_days(n*7, offset*7, dur*7)\n end",
"def registration_weeks\n result = 0\n weeks = 0\n if registration_start_date && registration_end_date\n weeks = Date.new(registration_start_date.year, 12, 31).\n strftime('%W').to_i\n\n result = get_registration_end_week - get_registration_start_week + 1\n end\n result < 0 ? result + weeks : result\n end",
"def week\n @week ||= (((date-start_of_month)+1)/7.0).ceil\n end",
"def weeks\n\t\tk = offset( first_day.cwday )\n\n [ first_week( k ) ] + middle_weeks( DPW - k )\n end",
"def get_week(year, month, day)\n weeks = [\"月\",\"火\",\"水\",\"木\",\"金\",\"土\",\"日\"]\n\n days = 0\n month_index = month - 1\n while month_index > 0 do\n month_days = get_days(year, month_index)\n days = days + month_days\n month_index = month_index - 1\n end\n\n year_days = 0\n year_index = year -1\n # while year_index > 0 do\n # year_days = get_year_days(year_index)\n # days = days + year_days\n # year_index = year_index - 1\n # end\n while year_index > 0 do\n if get_days(year_index, 2) == 29\n days = days + 366\n else\n days = days + 365\n end\n year_index = year_index - 1\n end\n \n days = days + day\n\n return weeks[(days-1) % 7]\nend",
"def weeks\n days_in_month = Time.days_in_month(month, year)\n starting_day = date.beginning_of_week() -1.day + beginning_of_week.days\n ending_day = (date + days_in_month).end_of_week() -1.day + beginning_of_week.days\n (starting_day..ending_day).to_a.in_groups_of(7).collect { |week| Week.new(week, events) }\n end",
"def move_to_week_and_year!(week, year)\n wday = cwday\n wday = 7 if wday == 0 # sunday. bloody sunday\n\n *saved_hours = start_hour, end_hour\n *saved_minutes = start_minute, end_minute\n\n @date = Date.commercial(year, week, wday).in_time_zone.beginning_of_day\n self.starts_at = self.ends_at = self.week = self.year = nil\n self.start_hour, self.end_hour = *saved_hours\n self.start_minute, self.end_minute = *saved_minutes\n save!\n self\n end",
"def iso_year_and_week_one_start(wkst)\n iso_year = self.year\n date = ::Date.new(self.year, self.month, self.mday)\n if (date >= ::Date.new(iso_year, 12, 29))\n week_one_start = Calculations.iso_week_one(iso_year + 1, wkst)\n if date < week_one_start\n week_one_start = Calculations.iso_week_one(iso_year, wkst)\n else\n iso_year += 1\n end\n else\n week_one_start = Calculations.iso_week_one(iso_year, wkst)\n if (date < week_one_start)\n iso_year -= 1\n week_one_start = Calculations.iso_week_one(iso_year, wkst)\n end\n end\n [iso_year, week_one_start]\n end",
"def week\n stamp = params[:stamp].to_i\n interval = (params[:interval] || 10).to_i\n plus_weeks = (params[:plus_weeks] || 0).to_i\n context = (params[:context] || 0).to_i == 1 ? true : false\n time = Time.at(stamp).utc\n\n # Calculate monday from given date\n wday = time.wday\n # Adjust for sunday when we want to start on a monday\n wday = 7 if wday == 0\n\n date = time - (wday.days - 1.days)\n\n date = date + plus_weeks.weeks\n\n # Number of days in week range if we add context, we add the surrounding weeks as well\n days = context ? (7 * 3) - 1 : 6\n\n # If context we'll start at the monday before\n if context\n date -= 7.days\n end\n\n\n\n week_data = []\n week_dates = []\n\n buckets = 0.step((60 * 24) - 1, interval).to_a\n\n (0..days).each do |day|\n interval_data = Hash.new { |h, k| h[k] = [] }\n\n data = GlucoseSensorData.by_day(date.to_date, :field => :timestamp)\n\n data.each do |datum|\n minutes = datum.timestamp.min + (datum.timestamp.hour * 60)\n # At first seems like a no op but this actually buckets minutes into intervals\n bucket = (minutes / interval) * interval\n\n interval_data[bucket] << datum\n end\n\n week_context = nil\n\n if context\n week_number = day / 7\n if week_number == 0\n week_context = \"before\"\n elsif week_number == 1\n week_context = \"current\"\n else\n week_context = \"after\"\n end\n else\n week_context = \"current\"\n end\n\n buckets.each do |bucket|\n datum = {}\n\n datums = interval_data[bucket]\n # Averages glucose values if there are more than one datum for that bucket\n if datums.length > 0\n datum[:glucose] = datums.inject(0.0) { |sum, d| sum + d.glucose } / datums.size\n #datum[:timestamp] = datums[0].timestamp.to_i\n end\n datum[:timestamp] = (date + bucket.minutes).to_i\n datum[:week_context] = week_context\n\n\n datum[:time] = bucket\n datum[:day] = date.strftime(\"%A\").downcase\n datum[:date] = date.to_i\n week_data << datum\n end\n\n week_dates.push({ :week_context => week_context, :day => date.strftime(\"%A\").downcase, :date => date.to_i })\n date += 1.days\n end\n\n render :json => { :data => week_data, :interval => interval, :week_dates => week_dates }\n end",
"def find_week_count(count_date)\n week_of_year = count_date.strftime('%V').to_i\n week_count = week_of_year.modulo(4) + 1\n\n week_count\n end",
"def create_date_value\n \n 1.upto(months.length) do |month|\n 1.upto(month) do |day|\n arr << [\"2015#{day}#{month}\", day_of_week]\n end\n end\nend",
"def week\n @year = params[:year].to_i\n @month = params[:month].to_i\n @day = params[:day].to_i\n @date = Date.new(@year, @month, @day)\n @work_times = WorkTime.find_by_start_date(@date)\n end",
"def week_date_ranges\n (1..ReportWeeks).map do |week|\n begin_date = @start_date + (7*(week-1))\n begin_date .. (begin_date + 6)\n end\n end",
"def each_wdays(wd,n=1,offset=0,dur=1)\n build_subrange do |s|\n s.step = n\n s.adjust_range { |r| day_range(r) }\n s.offset { |dt| dt.to_date + (wd - dt.to_date.wday)%7 + offset*7 }\n s.increment { |dt,i| dt.to_date + i*7 }\n s.span { |dt| dt.to_date + dur }\n end\n end",
"def fortnights ; self * 2.weeks ; end",
"def week_of_year date\n \tdate.strftime('%U').to_i\n end",
"def weeks\n\t\treturn self * 7.days\n\tend",
"def weeks\n\t\treturn self * 7.days\n\tend",
"def get_registrations_per_week\n result = []\n\n if registrations &&\n registration_start_date &&\n registration_end_date\n\n reg = registrations.group(\"strftime('%W', created_at)\").count\n start_week = get_registration_start_week\n weeks = registration_weeks\n result = calculate_items_per_week(start_week, weeks, reg)\n end\n result\n end",
"def dayOfWeek\n days = 0;\n tempYear = MIN_YEAR\n while tempYear < @year\n days += SimpleDate.daysInYear(tempYear).to_i\n tempYear+=1\n end\n\n days = days + ordinalDate\n #puts \"days #{days}\"\n days = days % 7\n\n end",
"def date_of_next_week_count(find_week)\n current = Time.current\n week_count = find_week_count(current)\n while week_count != 1\n current += 1.week\n week_count = find_week_count(current)\n end\n\n while week_count != find_week\n current += 1.week\n week_count = find_week_count(current)\n end\n\n current.strftime('%Y-%V')\n end",
"def cfp_weeks\n result = 0\n if call_for_papers\n result = call_for_papers.weeks\n end\n result\n end",
"def week_num()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::WeekNum::WeekNumRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def mweek; (5 - wday + day) / 7 end",
"def week\n first_day_of_week = @date.monday\n \n days_of_week = []\n 7.times do |time|\n days_of_week << day_and_types(first_day_of_week + time.days)\n end \n \n days_of_week\n end",
"def total_weeks\n ((self.deadline - self.start_date) / 7).to_i\n end",
"def week_calculations\n\t\t@first_of_month = @beg_range.to_date.beginning_of_month \n\t\t@last_of_month = @beg_range.to_date.beginning_of_month.next_month-1 \n\t\tif (@end_range+7).between?(@first_of_month, @last_of_month) \n\t\t\tif @beg_range.between?(@beg_range.prev_month.end_of_month, @beg_range.beginning_of_month+1) \n\t\t\t\t# <!--1st Week-->\n\t\t\t\t @prev_beg_range = @beg_range.prev_month.beginning_of_month + 4.weeks \n\t\t\t\t @prev_end_range = @end_range.prev_month.end_of_month \n\t\t\t\t\n\t\t\t\t @next_beg_range = @beg_range+7.days \n\t\t\t\t @next_end_range = @end_range+7.days \n\t\t\telse \n\t\t\t\t# <!--Middle Weeks-->\n\t\t\t\t @prev_beg_range = @beg_range-7.days \n\t\t\t\t @prev_end_range = @end_range-7.days \n\t\t\t\t\n\t\t\t\t @next_beg_range = @beg_range+7.days \n\t\t\t\t @next_end_range = @end_range+7.days \n\t\t\tend \n\t\telsif \n\t\t\tif @beg_range.next_week.beginning_of_week.between?(@first_of_month, @last_of_month) \n\t\t\t\t# <!--4th Week-->\n\t\t\t\t @prev_beg_range = @beg_range-7.days \n\t\t\t\t @prev_end_range = @end_range-7.days \n\t\t\t\t\n\t\t\t\t @next_beg_range = @beg_range+7.days \n\t\t\t\t @next_end_range = @end_range.end_of_month \t\t\n\t\t\telse \n\t\t\t\t# <!--5th Week-->\n\t\t\t\t @prev_beg_range = @beg_range-7.days \n\t\t\t\t @prev_end_range = @end_range-2.days \n\t\t\t\t\n\t\t\t\t @next_beg_range = @beg_range.next_month.beginning_of_month \n\t\t\t\t @next_end_range = @end_range.next_week.beginning_of_month+6.days \n\t\t\tend \n\t\tend \n\tend",
"def weekly(options = {})\n branch options.merge(every: :week)\n end",
"def weekly(options = {})\n branch options.merge(every: :week)\n end",
"def discover_week( nextweek )\n year = self.year\n owner = self.user_id\n\n if ( nextweek )\n inc = 1\n week = self.week_number + 1\n limit = Timesheet.get_last_week_number( year ) + 1\n\n return if ( week >= limit )\n else\n inc = -1\n week = self.week_number - 1\n limit = 0\n\n return if ( week <= limit )\n end\n\n while ( week != limit )\n timesheet = Timesheet.find_by_user_id_and_year_and_week_number(\n owner, year, week\n )\n\n if ( yield( timesheet ) )\n return { :week_number => week, :timesheet => timesheet }\n end\n\n week += inc\n end\n\n return nil\n end",
"def by_week(time=Time.zone.now, options = {}, &block)\n time = parse(time)\n\n # If options[:year] is passed in, use that year regardless.\n year = work_out_year(options.delete(:year)) if options[:year]\n # If the first argument is a date or time, ask it for the year\n year ||= time.year unless time.is_a?(Numeric)\n # If the first argument is a fixnum, assume this year.\n year ||= Time.zone.now.year\n\n # Dodgy!\n # Surely there's a method in Rails to do this.\n start_time = if valid_time_or_date?(time)\n weeks = time.strftime(\"%U\").to_i\n Time.zone.now.beginning_of_year\n elsif time.is_a?(Numeric) && time < 53\n weeks = time.to_i\n Time.utc(year, 1, 1)\n else\n raise ParseError, \"by_week takes only a Time or Date object, a Fixnum (less than or equal to 53) or a Chronicable string.\"\n end\n # Make the start of the week predictably Sunday.\n start_time.strftime(\"%w\").to_i != 0 ? start_time - (7 - start_time.strftime(\"%w\").to_i).days : start_time\n start_time += weeks.weeks\n end_time = start_time + 1.week\n by_star(start_time, end_time, options, &block)\n end",
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def weeks\n lines[2..-1]\n end",
"def bbc_week\n adjustment = 3 - ((self.wday + 1) % 7)\n tuesday = self + adjustment\n [tuesday.year, ((tuesday.yday - 1) / 7) + 1, 4 - adjustment]\n end",
"def calculate_timeline_week_count\n ((@course.timeline_end.to_date - @beginning_of_first_week).to_f / 7).ceil\n end",
"def nwrug_meet_for year, month\n beginning_of_month = Date.civil(year, month, 1)\n nwrug = beginning_of_month + (18 - beginning_of_month.wday)\n nwrug += 7 if beginning_of_month.wday > 4\n\n # Make sure we skip to the next month if we've gone past this month's meet\n if nwrug < Date.today\n if month == 12\n month = 1\n year += 1\n else\n month += 1\n end\n nwrug = nwrug_meet_for year, month\n end\n\n nwrug\nend",
"def calculate_open_weeks\n @timeline_week_count - blackout_weeks_count - @course.weeks.count\n end",
"def aging_weeks__c\n if %w(1 true).include?(is_closed.to_s.downcase)\n (last_modified_date.to_i-created_date.to_i)/(60*60*24*7)\n else\n (Time.now.to_i - created_date.to_i)/(60*60*24*7)\n end\n end",
"def week_to_date_map\n week_of_year = Time.new.strftime(\"%V\").to_i\n week_count = week_of_year.modulo(4) + 1\n\n mapping = {}\n for i in 0..3 do\n date = Date.today.beginning_of_week(:monday)\n date += 1 + ((3-date.wday) % 7)\n date += i.week\n mapping[week_count] = date\n week_count += 1\n week_count = 1 if week_count > 4\n end\n\n mapping[0] = 'On Hold'\n mapping[99] = 'Not Yet Set'\n mapping\n end",
"def create_occurrences\n if (from_date && to_date)\n current_date = from_date\n #this does not include the final date, could change so it does\n while (current_date < to_date)\n\n occurrence_end = current_date + event_length\n\n if(current_date.wday == recurring_day) #in case start date is not the right day of week\n occurrence_date.create( {start: current_date, end: occurrence_end})\n end\n\n case frequency\n when \"weekly\"\n current_date = current_date + 7.days\n if (recurring_day)\n current_date = current_date.beginning_of_week + recurring_day\n end\n when \"monthly\" ## need option to select which month month\n current_date = current_date + 1.month\n if(recurring_day && recurring_day_order)\n beginning_of_month= current_date.beginning_of_month\n current_date = week_day_of_month(beginning_of_month, recurring_day, recurring_day_order)\n end\n when \"daily\"\n current_date = current_date.next_day\n else\n console.log(\"not a valid frequency\")\n end\n end\n end\n end",
"def number_of_weeks\n @number_of_weeks ||= cell_row(last_of_month) + 1\n end",
"def calculate_week_power_for\n dates, totals = consolidate_week\n\n weekPowerCount = 0\n\n totals.each do |index, total|\n weekPowerCount+=total\n end\n\n weekPowerCount\n end",
"def cweek\n end",
"def weekly(range)\n data = range(range, :skip_bitmap_count => true)\n\n data = data.group_by { |date, value| date.beginning_of_week }\n case self.type\n when :counter\n sum_up_grouped_data(data)\n when :bitmap\n bitmap_or_grouped_data(data)\n end\n end",
"def weeks\n rows = []\n rows << name_of_month.center(20) + \" \"\n rows << \"Su Mo Tu We Th Fr Sa\" + \" \"\n days = format_dates\n (0..7).each {|num|\n fields = days[num * 7, 7]\n rows << fields.join(\" \") + \" \" if fields\n }\n if rows.last.length < 22\n rows.last << \" \" * (22 - rows.last.length)\n end\n until rows.length == 8\n rows << \" \" * 22\n end\n rows\n end",
"def set_boundaries\n days = calculate_start_and_end_day(@values[:year], @values[:time_frame])\n set_values(days)\n return \"Calculated interval for week from input:\" \\\n \" #{days[:actual]} - #{days[:next]}\"\n end",
"def reportable_weeks(options = {})\n week = options[:from] ? from_time(options[:from]) : earliest_week\n last_in_sequence = current\n [week].tap do |weeks|\n while week != last_in_sequence\n week = week.next\n weeks << week\n end\n end\n end",
"def year\n if @date.cweek == 1 && @date.month == 12\n @date.year + 1\n elsif @date.cweek == 52 && @date.month == 1\n @date.year - 1\n else\n @date.year\n end\n end",
"def start_of_week_with_wkst(wkst)\n wkst ||= 1\n date = ::Date.civil(self.year, self.month, self.day)\n date -= 1 while date.wday != wkst\n date\n end",
"def no_repeat_years(first_year, last_year)\nend",
"def weeks_since(weeks)\n advance(weeks: weeks)\n end",
"def find_next_week\n if @schedule.days == 0\n date = @date + ((@schedule.start_date.wday - @date.wday) % 7) + (7 * ((@schedule.start_date - @date) % @schedule.period_num))\n return date\n else\n date = @date + find_next_in_bitmask(@schedule.days, @date.wday, 7)\n\n if @date.wday >= bitmask(@schedule.days).length\n date += periods_to_add * 7\n end\n\n return date\n end\n end",
"def create_invoices_for_week\n InvoiceGenerator.create_invoices_for_week(self)\n end",
"def week\n self.range('week')\n end",
"def get_current_week_from_weeks(weeks)\n now = DateTime.now\n weeks.each { |week|\n if now < week.start_time\n return (week.number - 1)\n end\n }\n return weeks.last.number\n end",
"def w_year; end",
"def next\n if index < 52\n self.class.new(year, index + 1)\n elsif year.week_count == 53 and index == 52\n self.class.new(year, index + 1)\n else\n self.class.new(year.next, 1)\n end\n end",
"def week_no(args = nil)\n week_no = (self.day_of_year.to_f / 7).to_i + 1\n \n if args and args[:mfirst] and self.day_in_week == 1\n week_no -= 1\n end\n \n return week_no\n end",
"def solver(from_date, to_date, weekday)\n result = 0\n days_to_sunday = 7 - weekday\n new_date = from_date.increment_by_days days_to_sunday\n if (new_date.day == 1)\n result = result + 1\n end\n while new_date <= to_date\n if (new_date.day == 1)\n result = result + 1\n end\n new_date = new_date.increment_by_days 7\n end\n return result\nend",
"def iso_week_num()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::IsoWeekNum::IsoWeekNumRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def weeks\n @month.weeks.map { |w|\n w.map { |d| \n {\n\t\t\t\t date: d,\n\t\t\t\t\titems: !d.nil? ? items.where( trx_date: d ) : []\n\t\t\t\t}\n }\n }\n end",
"def iso_week_num(wkst)\n iso_year_and_week_num(wkst)[1]\n end",
"def beginning_of_week; end",
"def beginning_of_week; end",
"def calculate_items_per_week(start_week, weeks, items)\n sum = 0\n result = []\n last_key = start_week - 1\n\n if !items.empty? && start_week > items.keys[0].to_i\n start_week = items.keys[0].to_i\n weeks += start_week - items.keys[0].to_i + 1\n end\n\n items.each do |key, value|\n # Padding\n if last_key < (key.to_i - 1)\n result += Array.new(key.to_i - last_key - 1, sum)\n end\n\n sum += value\n result.push(sum)\n last_key = key.to_i\n end\n\n # Padding right\n if result.length < weeks\n result += Array.new(weeks - result.length, sum)\n end\n\n result\n end",
"def calc_weeks_till\n (calc_days_till / 7.0).round(2)\n end",
"def next_week\n if self.class == Date\n self + 7\n elsif self.class == Time\n self + (60 * 60 * 24 * 7)\n end\n end",
"def next_week\n if self.class == Date\n self + 7\n elsif self.class == Time\n self + (60 * 60 * 24 * 7)\n end\n end",
"def each_july( n=1); each_monthnum(self.Jul,n); end",
"def weekly_pay(rate, hours = 40)\n hours * rate\nend",
"def compute_actual_days_worked(year, start_date, end_date)\n working_days_in_year = Float(52*5)\n\n if Date.new(year, 1, 1) < start_date\n start_date_to_consider = start_date\n else\n start_date_to_consider = Date.new(year, 1, 1)\n end\n\n if Date.new(year, 1, 1).end_of_year < end_date\n end_date_to_consider = Date.new(year, 1, 1).end_of_year\n else\n end_date_to_consider = end_date\n end\n\n # we have to add one to include last day of work. We multiply by working_days_in_year/365 to remove weekends.\n ((end_date_to_consider - start_date_to_consider + 1).to_i * (working_days_in_year/365)).to_i #actual days worked in 'year'\n end",
"def odd_week?; (to_i / 7.days).odd? end"
] |
[
"0.70631766",
"0.6972198",
"0.6892188",
"0.6822872",
"0.6808188",
"0.6724527",
"0.6658759",
"0.64955956",
"0.6405919",
"0.6402313",
"0.6290028",
"0.6271715",
"0.6264065",
"0.6254238",
"0.6254238",
"0.6236377",
"0.62134016",
"0.62010384",
"0.61955124",
"0.6183571",
"0.6181045",
"0.6180545",
"0.61780965",
"0.6164767",
"0.6152461",
"0.61191803",
"0.6085117",
"0.6075277",
"0.60302126",
"0.60273355",
"0.6019984",
"0.5993442",
"0.5958384",
"0.59442914",
"0.5943564",
"0.5929661",
"0.5908076",
"0.58751786",
"0.58604485",
"0.5832752",
"0.58095855",
"0.5804342",
"0.5792774",
"0.57719874",
"0.57684004",
"0.57684004",
"0.5763318",
"0.5756608",
"0.57521975",
"0.573508",
"0.57343334",
"0.57187986",
"0.57156366",
"0.57116723",
"0.57017535",
"0.5696118",
"0.5696118",
"0.5693144",
"0.5676912",
"0.56245947",
"0.5622146",
"0.56046873",
"0.5585297",
"0.55775976",
"0.5575036",
"0.5574466",
"0.55684686",
"0.55450857",
"0.55447125",
"0.55290765",
"0.5525851",
"0.5523419",
"0.55188173",
"0.55054975",
"0.5497882",
"0.5482633",
"0.5472888",
"0.5468327",
"0.54499704",
"0.54436886",
"0.5421021",
"0.54163754",
"0.5406399",
"0.5397091",
"0.53950995",
"0.5389593",
"0.53890526",
"0.53814393",
"0.5347385",
"0.53454703",
"0.53402615",
"0.53402615",
"0.53385144",
"0.53271985",
"0.5319488",
"0.5319488",
"0.5306825",
"0.53062916",
"0.53049076",
"0.5297764"
] |
0.673022
|
5
|
Create a recurrence that ends after given number of occurrences
|
def total(total)
merge(total: total)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def fill_recurrence(number)\n if old_num == number\n self.recc += 1\n else\n apply_recurrence\n self.old_num = number\n self.recc = 1\n end\n end",
"def pattern_repeat(n)\n last = [1, 1]\n counter = 0\n loop do\n last = [last.last, (last.first + last.last) % 10]\n break p \"#{counter}\" if last == [1, 1]\n counter += 1\n end\nend",
"def next_n_occurrences(n, from_date)\n first_next_occurrence = next_occurrence(from_date)\n blk = proc { |i| move_by first_next_occurrence, interval * i }\n range = 0.upto(n - 1)\n range = range.lazy if n > 1000\n range.map &blk\n end",
"def bounded(n)\n RepeatCount.bounded(n)\n end",
"def next_occurrences\n result = []\n\n occurrences = Invoice.belonging_to(id).count\n next_date = next_invoice_date\n max_date = [Date.current, finishing_date.blank? ? Date.current + 1 : finishing_date].min\n\n while next_date <= max_date and (max_occurrences.nil? or occurrences < max_occurrences) do\n result.append(next_date)\n occurrences += 1\n next_date += period.send period_type\n end\n\n result\n end",
"def recurrence\n nil\n end",
"def next_occurrences(limit = 1, after = Time.now.utc)\n occurrence_solver.next_occurrences(limit, after)\n end",
"def generate_recurrences\n # remove all already scheduled occurrences in the future\n Occurrence.where('event_id = ? AND date >= ?', self.id, Date.current).delete_all\n \n if read_attribute(:recurrence).empty?\n Occurrence.create(event: self, date: self.date)\n else\n # schedule events for the next month\n # TODO: make instance variable with schedule instance to avoid repeat instantiation\n schedule = IceCube::Schedule.new\n schedule.add_recurrence_rule(self.recurrence)\n schedule.occurrences(Time.current + 1.month).each do |o|\n Occurrence.create(event: self, date: o.to_date)\n end\n end\n end",
"def ncr(n, r)\n n.downto(n-r+1).inject(:*) / fct(r)\n # ((n-r+1)..n).inject(:*) / (1..r).inject(:*)\nend",
"def number_counting_seq(n)\r\n\r\nend",
"def update_interval\n self.interval =\n case repetitions\n when 1 then 1\n when 2 then 6\n else\n (repetitions - 1) * easiness_factor\n end\n end",
"def recurrence\n { ATTR_RECURRENCE[@attribute] => 1 }\n end",
"def set_next_repetition\n if repetitions.order(\"id ASC\").last.successful\n self.consecutive_successful_repetitions += 1\n next_planned_interval = rand((repetitions.last_planned_interval * 2)..(repetitions.last_planned_interval * 3))\n else\n self.consecutive_successful_repetitions = 0\n next_planned_interval = rand(1..3)\n end\n save\n if consecutive_successful_repetitions < WhRails::Application.config.max_consecutive_successful_repetitions\n # repetitions.last.actual_date is always the current date.\n next_repetition_date = repetitions.order(\"id ASC\").last.actual_date + next_planned_interval.days\n repetitions.create planned_date: next_repetition_date, actual_date: next_repetition_date\n else\n self.learned_on = Date.today\n save\n end\n end",
"def sequence_to(limit, sequence = [0, 1])\n loop do\n # Push the sum of the last two elements onto the array.\n sequence.push(sequence.last(2).inject(:+))\n # Once the last element has exceeded the limit, pop it and exit the loop.\n break if sequence.last.abs > limit && sequence.pop.abs\n end\n sequence\nend",
"def monkey_count(n)\n [*1..n]\nend",
"def recurrence=(value)\n @recurrence = value\n end",
"def recurrence=(value)\n @recurrence = value\n end",
"def r(i)\n raise unless 1 <= i\n raise unless i <= n\n index = n - i\n @reps[index]\n end",
"def create_scheduled_notifications\n t = Time.now.utc\n x = self.notifications_created_since_recurrence_last_updated_count\n \n while (d = recurrence[x]) && t >= d\n create_notification_for_date(d)\n \n self.notifications_created_since_recurrence_last_updated_count += 1\n self.save!\n \n x += 1\n end \n end",
"def occurrences(params={count: MAX_OCCURRENCE_COUNT})\n if(recurs?)\n if(params[:after])\n search_offset = params[:after].localtime.utc_offset - schedule.start_time.localtime.utc_offset\n elsif(params[:until])\n search_offset = params[:until].localtime.utc_offset - schedule.start_time.localtime.utc_offset\n end\n \n #reset schedule to utc\n schedule.start_time.utc\n schedule.end_time.utc\n \n schedules = if(params[:until])\n if(params[:after])\n schedule.occurrences_between(params[:after] - self.schedule.duration + search_offset, params[:until] + search_offset)\n else\n schedule.occurrences(params[:until] + search_offset)\n end\n elsif params[:count]\n if params[:after]\n schedule.next_occurrences(params[:count], params[:after] - self.schedule.duration + search_offset)\n else\n schedule.next_occurrences(params[:count], Time.zone.now - self.schedule.duration)\n end \n end\n \n if(schedules)\n \n #turn schedules [Time] into self.classes\n schedules.map { |time| duplicate(time - schedule.start_time + (self.start.localtime.utc_offset - time.localtime.utc_offset)) }\n else\n []\n end\n else\n [self]\n end\n end",
"def calculate_sequence\n old_sequence.split('')[1..-1].each(&method(:fill_recurrence))\n\n apply_recurrence\n\n recurrences.flatten.join\n end",
"def fibs_rec(n)\n n <= 1 ? n : fibs_rec(n - 1) + fibs_rec(n - 2)\nend",
"def factorials_rec(n)\n return [1] if n <= 1\n\n facts = factorials_rec(n-1)\n facts << facts.last * (n-1)\nend",
"def build_reminders\n\t\treminds = self.reminders.last(10).to_a\t\t\n\t\t(10 - self.reminders.count).times do\n\t\t\treminds << self.reminders.build\n\t\tend\n\t\treminds\n\tend",
"def build_fib_seq(n)\n fib = [1, 1]\n count = 2\n until count >= n\n fib << fib[-1] + fib[-2]\n count += 1\n end\n\n fib\nend",
"def fibs_rec(n)\n n == 0 || n == 1 ? n : fibs_rec(n-1) + fibs_rec(n-2)\n fibs(n)\nend",
"def next_occurrences(options = {})\n begin_datetime = start_datetime_for_collection(options)\n final_datetime = final_datetime_for_collection(options)\n limit = options.fetch(:limit, 100)\n [].tap do |occurences|\n occurrences_between(begin_datetime, final_datetime).each do |time|\n occurences << { event: self, time: time }\n return occurences if occurences.count >= limit\n end\n end\n end",
"def fibonacci_last_instant(nth)\n fibonacci_last(nth % 60)\nend",
"def fibs_rec(n, sequence = [0, 1])\n\tif n == 0\n\t\treturn 0\n\telsif n == 1\n\t\treturn 1\n\telse\n\t\tnew_num = sequence[-2] + sequence[-1]\n\t\tsequence << new_num\n\t\tfibs_rec(n-1, sequence)\n\tend\n\tsequence\nend",
"def repeats(n)\n # Check that the number is in the correct range.\n if n > 0 && n <= 50\n @metadata[:repeats] = n\n else\n raise \"The number of repeats must be between 1 and 50.\"\n end\n return self\n end",
"def find_repetition_interval(repetition, e_factor)\n return 6 if repetition == 1\n (repetition * e_factor).round\n end",
"def update_occurrences\n occurrences.destroy_all\n if recurrence_rules.any?\n recurrence_horizon = Time.now + (Radiant::Config['event_calendar.recurrence_horizon'] || 10).to_i.years\n to_ri_cal.occurrences(:before => recurrence_horizon).each do |occ|\n occurrences.create!(self.attributes.merge(:start_date => occ.dtstart, :end_date => occ.dtend, :uuid => nil)) unless occ.dtstart == self.start_date\n end\n end\n end",
"def fibs_rec(count)\n return [0,1,1].take(count) if count < 3\n prev_fibs = fibs_rec(count - 1)\n prev_fibs + [prev_fibs[-2] + prev_fibs[-1]]\nend",
"def countdown_r( n )\n\n # define a base case\n # (condition under which function STOPS calling itself)\n if n < 0\n puts \"Blast off!\"\n else\n # recursive case\n # the function calls itself, but in a way that always\n # brings us a step closer to the terminating base case\n puts n\n sleep 0.3\n countdown_r( n - 1 )\n end\n puts \"backing out of recursrion: n=#{n}\"\nend",
"def start_to_end(m, n)\n combinatorics(m+n, [m,n].max)\n end",
"def next_occurrence(after = Time.now.utc)\n occurrence_solver.next_occurrence(after)\n end",
"def fib_rec(n)\n return n if n <= 3\n\n return fib_rec(n-1) + fib_rec(n-2)\nend",
"def f(n)\n sum = (\"1\"*n).to_i # the last number of the sequence is n 1's\n # start with single digit if possible\n sum += n if n.to_s.length == 1\n # 2 digits next\n x = 2\n puts terms_of_n_with_length_x(n,x).inspect\n puts \"got here\"\n puts n-1\n (1..(n-1)).to_a.reverse.each do |x|\n puts x\n puts eat_2s(x)\n end\n return sum\nend",
"def repeat(n)\n Functors.repeat(n, &self)\n end",
"def increase_busy_counter\n @recurrence.increment! :busy_count\n end",
"def fibs_rec(n)\n return n if n <= 1\n return fibs_rec(n-2) + fibs_rec(n-1)\nend",
"def series_up(n) # Got help again. My first code couldn't adapt at all. This one has a reset limit, meaning it loops the amount of times it needs to for each interger. Still not perfect, but almost there. \n list = [1]\n i = 1\n length = n*(n+1)/2\n reset = 3\n list.push i\n i += 1\n if i == reset\n reset += 1\n end\n return list\nend",
"def series_up(n) # given n, return a list that goes [1,1,2,1,2,3... n]\n n_list = []\n (n+1).times do |m|\n m.times do |val|\n n_list.push(val+1)\n end\n end\n return n_list\nend",
"def tribonacci(signature, n)\n #your code here\n (n - 3).times do\n signature << signature.last(3).sum\n end\n signature.first(n)\nend",
"def gen(i, n, stopval)\r\n m = n + i + 1\r\n if (factor2(m) < stopval)\r\n gen(i+1, m, stopval)\r\n else\r\n print(\"i: \",i,\" m: \",m,\" stop: \",stopval)\r\n end\r\n \r\nend",
"def recurring; end",
"def fibonacci_sequence(limit)\n fib_seq = [1,2]\n i = 1\n until fib_seq[i] + fib_seq[i-1] > limit\n fib_seq.push(fib_seq[i] + fib_seq[i-1])\n i += 1\n end\n\n return fib_seq\nend",
"def fibs_rec(i, j, cnt, n)\n if(cnt > n)\n return i\n else\n k = i + j\n print i, \", \"\n i = j\n j = k\n fibs_rec(i, j, cnt += 1, n)\n end\nend",
"def countdown_recursive(n=10)\n if n < 0\n puts 'Blast Off!!'\n else\n puts n\n sleep 1\n countdown_recursive(n-1)\n end\nend",
"def sequence(count, start)\n final_arr = []\n 1.upto(count) do |num|\n final_arr << num * start\n end\n final_arr\nend",
"def seq(n)\n return n if n <= 1\n seq(n-1) + seq(n-2)\nend",
"def bottles(n)\n if n.zero?\n puts \"no more bottles of beer on the wall\"\n return\n end\n\n puts \"#{n} bottles of beer on the wall\"\n\n bottles(n - 1)\nend",
"def tail_rec_factorial(n)\n return tail_rec_factorial_(n, 1)\nend",
"def even_fibonacci(limit)\r\n start = [1, 2]\r\n\r\n start << start.last(2).inject(:+) while start[-1] < limit\r\n\r\n start.select { |number| number.even? }.inject(:+)\r\nend",
"def fibonacci_last(nth)\n nth = nth % 60\n last_2 = [1, 1]\n 3.upto(nth) do\n last_2 = [last_2.last, (last_2.first + last_2.last) % 10]\n end\n\n last_2.last\nend",
"def fibonacci_last(n)\n return 1 if n.between?(1, 2)\n prev_last_digits = [1, 1]\n \n 3.upto(n) do |_|\n prev_last_digits << prev_last_digits.sum % 10\n prev_last_digits.shift\n end\n \n prev_last_digits.last\nend",
"def fibs_rec n\n (n < 3) ? [1]*n : fibs_rec(n - 1) << fibs_rec(n - 1)[-1] + fibs_rec(n - 1)[-2]\nend",
"def series_up(n)\n new_list=[] # to push into a new list\n (n + 1).times do |index| #You need the nested loop index.times to run at least once. Since Index starts at 0, you need to add 1 so that it runs at least once\n index.times do |value| # this runs the loop each time until it reaches the number needed\n new_list.push(value + 1) #Same as the loop above. Since the value starts at 0, you need to start at 1 bc that's what the challenge wants you to do. the .push pushes it into the new list \n end \n end \n return new_list # this makes the function print the newly created list\nend",
"def next_occurrence(after = Time.now.utc)\n return nil unless recurrence\n\n occurrence = after.change(next_values)\n # TODO: add support for year multiples (eg., every other year, every 10th year)\n if @attribute == :year and @value < after.year\n nil # years are anchored, they don't recur (on the Gregorian calendar)\n elsif after < occurrence\n occurrence\n else\n begin\n occurrence = occurrence.advance(recurrence)\n end until @predicate === occurrence\n occurrence\n end\n end",
"def maximum_number_of_months_to_recur\n self.period.length_in_months -\n self.period.month_for_date(date)\n end",
"def fibs_rec(n)\n\treturn n if n <= 1\n\tfibs_rec(n-1) + fibs_rec(n-2)\nend",
"def number_of_ways_to_score_n_runs(n)\n return score_n_runs_rec(n)\nend",
"def fib_rec(n)\n return (0..n).reduce([]) { |a, v| a << v } if n < 2\n prev = fib_rec(n - 1)\n prev << prev[-2] + prev[-1]\nend",
"def next_occurrence_after(date)\n first_occurrence_on_or_after(date + 1)\n end",
"def fibonacci_last(nth)\n last_2 = [1, 1]\n 3.upto(nth) do\n last_2 = [last_2.last, (last_2.first + last_2.last) % 10]\n end\n last_2.last\nend",
"def bottles(n)\n if n == 0\n puts 'no more bottles of beer on the wall'\n else\n puts \"#{n} bottles of beer on the wall\"\n bottles(n - 1)\n end\nend",
"def fibonacci_last(nth)\n last_2 = [1, 1]\n 3.upto(nth) do\n last_2 = [last_2.last, (last_2.first + last_2.last) % 10]\n end\n\n last_2.last\nend",
"def fibonacci_last(nth)\n last_2 = [1, 1]\n 3.upto(nth) do\n last_2 = [last_2.last, (last_2.first + last_2.last) % 10]\n end\n\n last_2.last\nend",
"def fibonacci_last(nth)\n last_2 = [1, 1]\n 3.upto(nth) do\n last_2 = [last_2.last, (last_2.first + last_2.last) % 10]\n end\n\n last_2.last\nend",
"def fibonacci_last(nth)\n last_2 = [1, 1]\n 3.upto(nth) do\n last_2 = [last_2.last, (last_2.first + last_2.last) % 10]\n end\n\n last_2.last\nend",
"def series_up(num)\n series = 0\n list = [] #starts as empty\n #puts \"running code\"\n num.times do |pattern|\n n = 0#original num\n num.times do |num|\n list[n + series] = n + 1\n n += 1\n end \n series += pattern + 1 \n #makes it grow exponentially\n end\n return list \nend",
"def fibonacci(n_terms)\n def insert_next_term_in(fib_seq) fib_seq << fib_seq[-2] + fib_seq[-1] end\n\n (0..n_terms).inject([1,1]) { |fib_seq| insert_next_term_in(fib_seq) }[0,n_terms]\nend",
"def fibo_rec(n)\n return n <= 1 ? n : fibo(n - 1) + fibo(n - 2)\nend",
"def fib_rec(n)\n return 0 if n == 1\n return 1 if n == 2\n fib_rec(n - 1) + fib_rec(n - 2)\nend",
"def recurrence_to_events!(now = Time.now.utc)\n return unless recurrence\n pid = parent_id || id # if parent_id is nil then we're generating from the parent\n duration = (self.end - self.start).to_i\n t_start = end_of_chain.start.midnight.tomorrow # Every day after the current day\n recurrence.in_range(t_start, now).each do |t|\n self.class.create(:start => t, :end => t + duration, :parent_id => pid)\n end\n end",
"def find_fibonacci_index_by_length(int)\nlimit = (10**int)/10\nindex = 2\nx = 1\ny = 1\n loop do\n z = x + y\n x = y\n y = z\n index += 1\n break if z > limit \n end\n index\nend",
"def sequence(n)\n results = []\n 1.upto(n) {|num| results << num}\n results\nend",
"def adjust_occurrence(occurrence)\n occurrence.dup.tap { |o| o.instance_variable_set(:@pos, o.pos + o.line_num - 1) }\n end",
"def seqlength(n)\n seen = []\n m = 1\n\n 1.upto(n) do |i|\n rem = m % n\n return i if seen.include?(rem)\n seen.<< rem\n m = 10 * rem\n end\nend",
"def sequence(count, start_number)\n array = []\n count.times { |i| array << (start_number * (i + 1)) }\n array\nend",
"def bottles(n)\n if n == 0 \n puts 'no more bottles of beer on the wall'\n else\n puts \"#{n} bottles of beer on the wall \"\n bottles(n-1)\n end\nend",
"def series_up (n)\n length = n*(n + 1)/2 # this is the mathematical equation for the length of a series\n time = 1 # this variable counts how many times the loop runs but it needs to be reset after it is run three times so that it starts over at 1 again\n reset = 3 # this counts the number of resets\n list = [1]\n (length - 1).times do\n list = [list, time]\n time += 1\n if time == reset # refer to line 50 comment\n time =1\n reset+= 1 # after the first reset the reset needs increase each time so because the last number of the list is getting bigger and without the reset it will not print\n end\n end\n print list\nend",
"def fibs_rec(n, result = [0, 1])\n if n > 1\n result << result[-2] + result[-1]\n fibs_rec(n-1, result)\n end\n result\nend",
"def fibonacci(n)\n fib = [1, 1]\n while fib.size < n\n fib << fib[-1] + fib[-2]\n end\n fib.last % 10\nend",
"def fibs_rec(i)\n return i if i <= 1\n fibs_rec(i-2) + fibs_rec(i-1)\nend",
"def factorials_rec(num)\n return [1,1].take(num) if num < 2\n facts = factorials_rec(num - 1)\n facts + [facts.last * (num - 1)]\nend",
"def factorials_rec(num)\n return 1 if num == 0 \n return [1] if num == 1\n fact = [1]\n\n fact << [(fact[-1] * factorials_rec(num-1))]\n# (2) \n# 4 * fact_rc(3) 2\n# 3 * fact_rc(2) 6\n# 2 * fact_rc(1) 2\n# 1 * fact(rc 0 )\nend",
"def doubler(start)\n puts start\n if start < 10\n doubler(start * 2) #this starts our method over until start is more than 10\n end\nend",
"def fib_sequence(limit)\n seq = [1,2]\n while seq[-1] + seq[-2] < limit do\n seq << seq[-1] + seq[-2]\n end\n\n return seq\nend",
"def repeat_freq(nums, initial_val)\n sum = initial_val\n past_freqs = Set[initial_val]\n index = 0\n # This is an infinite loop so assumes that the problem has a solution\n while true\n sum += nums[index]\n return sum if past_freqs.add?(sum).nil?\n index += 1\n # Reset the index if it needs to loop\n index = 0 if index == nums.length\n end\nend",
"def to count\n take count + 1\n end",
"def factorials_rec(num)\n return [1] if num == 1\n\n facts = factorials_rec(num-1)\n\n facts << facts.last * (num - 1)\n\n facts\nend",
"def bottle_song_lyrics(n)\n bottle_counter = n\n bottles_remaining = n-1\n song = \"\"\n while bottle_counter >= 1\n if bottle_counter > 1\n song << \"#{bottle_counter} bottle of beer on the wall, #{bottle_counter} bottle of beer. Take one down, pass it around, #{bottles_remaining} bottle of beer on the wall! \"\n else\n song << \"1 bottle of beer on the wall, 1 bottle of beer. Take one down, pass it around, no more bottles of beer on the wall!\"\n end\n bottle_counter -= 1\n bottles_remaining -=1\n end\n song\nend",
"def rep(rule, min=1, max=Infinity, &block)\n ext(Repeat.new(min, max, rule), block)\n end",
"def xbonacci(starting_sequence, number_of_xbonacci_numbers_to_return)\n # create a loop that will run until N is reached\n # loop should take the length of the starting sequence\n # multiple the length by -1\n # add elements from end of array to the length * -1\n\n num_elements_to_sum = starting_sequence.length * - 1\n\n while starting_sequence.length != number_of_xbonacci_numbers_to_return\n starting_sequence << starting_sequence[num_elements_to_sum..-1].reduce(:+)\n end\n\n starting_sequence\n\n\nend",
"def series_up(n)\n list = []\n (n+1).times do |a|\n a.times do |b|\n list.push(b+1)\n end \n end\n return list\nend",
"def terminate_after(value)\n fresh.tap do |criteria|\n criteria.terminate_after_value = value\n end\n end",
"def ten_recipes_after number\n first_elf_position = 0\n second_elf_position = 1\n scoreboard = Array.new(number+10) # Pre-create array to avoid the cost of growing it\n scoreboard[first_elf_position] = 3\n scoreboard[second_elf_position] = 7\n scoreboard_size = 2\n while scoreboard_size < number + 10\n next_recipe_scores = (scoreboard[first_elf_position] + scoreboard[second_elf_position]).to_s.split('').map(&:to_i)\n next_recipe_scores.each do |new_score|\n scoreboard[scoreboard_size] = new_score\n scoreboard_size += 1\n end\n first_elf_delta = scoreboard[first_elf_position] + 1\n second_elf_delta = scoreboard[second_elf_position] + 1\n first_elf_position = normalize_elf_position(first_elf_position + first_elf_delta, scoreboard_size)\n second_elf_position = normalize_elf_position(second_elf_position + second_elf_delta, scoreboard_size)\n # print_scoreboard first_elf_position, second_elf_position, scoreboard\n # puts scoreboard_size\n end\n scoreboard[number..(number+10-1)].join('')\nend",
"def create_fibonacci(max)\n fibonacci = [1,2]\n until fibonacci[-1] > max\n fibonacci << fibonacci[-1] + fibonacci[-2]\n end\n fibonacci\nend",
"def sequence(count, start)\n seq = []\n count.times { |i| seq << start * (i + 1) }\n seq\nend",
"def fibonacci_last(nth) \n first_60 = [0, 1]\n\n 3.upto(60) do \n first_60 << (first_60[-2] + first_60.last) % 10\n end\n\n first_60[nth % 60]\nend"
] |
[
"0.61601716",
"0.6080025",
"0.59530854",
"0.5885252",
"0.5822106",
"0.5789838",
"0.57532483",
"0.57367927",
"0.5723179",
"0.56007063",
"0.55828875",
"0.5572156",
"0.55542475",
"0.54669666",
"0.5391866",
"0.53671384",
"0.53671384",
"0.53411204",
"0.5340492",
"0.5318625",
"0.53121424",
"0.52927",
"0.52926475",
"0.5289235",
"0.52778995",
"0.5264743",
"0.52629983",
"0.5262782",
"0.52466327",
"0.52337646",
"0.5219453",
"0.52173877",
"0.5207706",
"0.5201883",
"0.5200769",
"0.5185179",
"0.5179397",
"0.51773757",
"0.51739985",
"0.5157103",
"0.5156146",
"0.5154768",
"0.5144919",
"0.5143833",
"0.51437896",
"0.51436037",
"0.51424116",
"0.51315325",
"0.51280177",
"0.5126961",
"0.5126768",
"0.5122944",
"0.51172584",
"0.5111133",
"0.5109708",
"0.51065695",
"0.5100225",
"0.5093305",
"0.5084086",
"0.50816417",
"0.5080313",
"0.50802124",
"0.50697845",
"0.5060724",
"0.50581664",
"0.504554",
"0.5045151",
"0.5045151",
"0.5045151",
"0.5045151",
"0.5042822",
"0.503651",
"0.50356215",
"0.502729",
"0.5026371",
"0.5017612",
"0.50170386",
"0.5015066",
"0.501456",
"0.50125045",
"0.500772",
"0.5007489",
"0.50073636",
"0.50058496",
"0.5001689",
"0.5000756",
"0.5000513",
"0.49957",
"0.49946707",
"0.49887767",
"0.49856535",
"0.4985096",
"0.49696535",
"0.4962744",
"0.49600935",
"0.49582437",
"0.49464995",
"0.49461612",
"0.4944686",
"0.49427187",
"0.49422818"
] |
0.0
|
-1
|
Create a new recurrence combining options of self and other. The value of entries with duplicate keys will be those of other
|
def merge(other = {})
branch default_options.merge(other)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def merge!(other)\n\t\tALL.each do |key|\n\t\t\tincrement(key, other.get(key))\n\t\tend\n\t\tself\n\tend",
"def join(other)\n new(entries.merge(other.entries) { |_name, old, new| old + new })\n end",
"def merge_info(parent, child, opt1, opt2)\n result = TemporalConstraintSet.new\n if opt1.intervals.size > opt2.intervals.size\n result.intervals.concat(opt1.intervals)\n for i in opt2.intervals\n result.add(*i)\n end\n else\n result.intervals.concat(opt2.intervals)\n for i in opt1.intervals\n result.add(*i)\n end\n end\n\n result.occurence_constraints.merge!(opt1.occurence_constraints)\n opt2.occurence_constraints.each do |recurrent, spec|\n result.add_occurence_constraint(spec[0], spec[1], recurrent)\n end\n\n result\n end",
"def merge_by_values(relation, other)\n other.cte.with_values.each do |name, expression|\n relation = if other.cte.materialized_key?(name)\n relation.with!.materialized(name => expression)\n elsif other.cte.not_materialized_key?(name)\n relation.with!.not_materialized(name => expression)\n else\n relation.with!(name => expression)\n end\n end\n\n relation\n end",
"def merge!(other)\n operands[0] += other.operands[0]\n self\n end",
"def +(other)\n FrequencyMap.new(@map.merge(other.map){|key, first, second| first + second })\n end",
"def or other_hash\n return self if other_hash.nil?\n result = {}\n new_keys = self.keys | other_hash.keys\n new_keys.each do |key|\n value1 = self[key]\n value2 = other_hash[key]\n if block_given?\n result[key] = yield value1, value2\n elsif value1.nil? and not value2.nil?\n result[key] = value2\n elsif (not value1.nil?) and value2.nil?\n result[key] = value1\n elsif value1 == value2 or value1.eql?(value2)\n result[key] = value1 \n elsif value1.class == value2.class && value1.respond_to?(:|)\n result[key] = (value1 | value2)\n else # Hash#merge behavior\n result[key] = value2\n end\n end\n result\n end",
"def update_conditions!(other)\n\n # build an index of conditions by the clause and operator to\n # avoid nested looping\n conditions_index = Hash.new { |h,k| h[k] = {} }\n @conditions.each do |condition|\n next unless condition.size == 3 # only process triplets\n operator, clause = *condition\n conditions_index[clause][operator] = condition\n end\n\n # loop over each of the other's conditions, and overwrite the\n # conditions when in conflict\n other.conditions.each do |other_condition|\n if other_condition.size == 3 # only process triplets\n other_operator, other_clause, other_value = *other_condition\n\n if condition = conditions_index[other_clause][other_operator]\n operator, clause, value = *condition\n\n # TODO: do not overwrite the value. Instead splice the\n # condition from @conditions, and then push onto conditions.\n # that way each condition can become a real immutable Tuple\n\n # overwrite the value in the existing condition\n condition[2] = case operator\n when :eql, :like : other_value\n when :gt, :gte : [ value, other_value ].min\n when :lt, :lte : [ value, other_value ].max\n when :not, :in : Array(value) | Array(other_value)\n end\n\n next # process the next other condition\n end\n end\n\n # otherwise append the other condition\n @conditions << other_condition.dup\n end\n end",
"def combine(other)\n other.each { |key, value| setting(key).combine!(value) } if other.is_a?(Hash)\n end",
"def combine_options(o1, o2) # rubocop:disable Naming/MethodParameterName\n # $stderr.print \"Combining '#{o1}' with '#{o2}'\\n\"\n return unless @_option_value.key?(o1) && @_option_value.key?(o2)\n\n if !@_option_value.key?(o1)\n @_option_value[o1] = []\n elsif !@_option_value.key?(o2)\n @_option_value[o2] = []\n end\n\n tmp = @_option_value[o1] | @_option_value[o2]\n\n @_option_value[o1] = tmp\n @_option_value[o2] = tmp\n @_count[o1] = tmp.size\n @_count[o2] = tmp.size\n end",
"def merge!(other_context)\n \n other_context.each_pair() do | key, value |\n if(value == nil)\n set_key(key, nil)\n elsif(get_key(key).respond_to?(:merge) and value.respond_to?(:merge))\n set_key(key, get_key(key).merge(value))\n else\n v = value.dup() rescue value\n set_key(key, v)\n end\n\n end\n \n return self\n end",
"def merge!(other)\n other.each_pair do |key, value|\n value = yield(convert_key(key), self[key], convert_value(value)) if block_given? && self[key]\n self[key] = value\n end\n self\n end",
"def merge(other)\n # By default just take the other change if applicable\n other.instance_of?(self.class) && other.key == key ? other : self\n end",
"def deep_merge(other, &bloc)\n other.keys.inject(dup) do |result, key|\n begin\n case result[key]\n when Hash\n if other[key].is_a?(Hash)\n result[key] = result[key].deep_merge(other[key], &bloc)\n result\n else\n raise MergeConflict\n end\n when nil then result.merge key => other[key]\n else\n raise MergeConflict\n end\n rescue MergeConflict\n if bloc.nil?\n result[key] = other[key]\n else\n result[key] = bloc.call(result, other, key) \n end\n result\n end\n end\n \n end",
"def rmerge!(other)\n if other.is_a?(Array)\n other.each { |v| self << v.rdup unless include?(v) }\n elsif other\n self << other.rdup unless include?(other)\n end\n self\n end",
"def deep_merge!(other_hash, &block)\n other_hash.each_pair do |current_key, other_value|\n this_value = self[current_key]\n\n self[current_key] = if this_value.is_a?(Hash) && other_value.is_a?(Hash)\n this_value.deep_merge(other_value, &block)\n else\n if block_given? && key?(current_key)\n block.call(current_key, this_value, other_value)\n else\n other_value\n end\n end\n end\n\n self\n end",
"def join(other)\n return nil unless self.frequency == other.frequency\n\n expanded_datetimes = self.datetimes.map { |datetimes_within_an_interval|\n back_one = datetimes_within_an_interval.first - frequency.duration\n forward_one = datetimes_within_an_interval.last + frequency.duration\n\n [back_one] + datetimes_within_an_interval + [forward_one]\n }\n\n joint_ranges = []\n\n # Look for overlaps, where an overlap may be 'off by 1' -- hence the 'expanded_datetimes'\n # ...but start with other and join to each of it's intervals.\n #\n # Remember that 'pattern.datetimes' returns a list of datetimes per interval\n other.datetimes.each do |other_datetimes_within_an_interval|\n\n joinable_datetimes = expanded_datetimes.find { |expanded_datetimes_within_an_interval|\n other_datetimes_within_an_interval.any? { |d|\n expanded_datetimes_within_an_interval.include?(d)\n }\n }\n break unless joinable_datetimes\n\n # Joint ranges should be those that overlap\n #\n # This is buggy, because joinable_datetimes is a list of datetimes per interval that overlap\n # Excluding the first doesn't make sense\n #\n # Instead, we should exclude the first AND last for each element within joinable_datetimes \n joint_datetimes = (other_datetimes_within_an_interval + joinable_datetimes[1...-1]).sort\n joint_ranges << (joint_datetimes.first..joint_datetimes.last)\n end\n\n # This seems to be trying to say \"Only join when we got one for each interval of self\"\n # ...it also seems too restrictive...\n #\n # What if other includes multiple intervals of self?\n # Then we don't need same number of intervals\n #\n # Also might be wrong in other ways, it's tricky to tell\n if joint_ranges.size == self.intervals.size\n Pattern.new(joint_ranges, frequency.duration)\n end\n end",
"def merge!(other)\n other.each do |k, v|\n if v.is_a?(Array)\n v.each do |value|\n send(k) << value.dup unless send(\"named_#{k[0..-2]}\", value.name)\n end\n elsif send(k).nil?\n send(\"#{k}=\", v)\n end\n end\n\n self\n end",
"def +(other)\n Key.new( [to_s, other.to_s].join(SEPARATOR) )\n end",
"def +(other)\n result = self\n number = other.to_i\n\n number.abs.times do\n if number < 0\n result = result.previous\n else\n result = result.next\n end\n end\n\n result\n end",
"def **(other)\n self + other\n end",
"def |(other)\r\n Choice[(children + [other])]\r\n end",
"def add_alternation\n if nested_child?\n @options.last.last.add_alternation\n else\n @options << []\n end\n end",
"def deep_merge!(second)\n return nil unless second\n type_assert(second, Array)\n changed = nil\n second.each_index do |k|\n if self[k].is_a?(Array) and second[k].is_a?(Array)\n changed |= true if self[k].deep_merge!(second[k])\n elsif self[k].is_a?(Hash) and second[k].is_a?(Hash)\n changed |= true if self[k].deep_merge!(second[k])\n elsif exclude?(second[k])\n self << second[k]\n changed |= true\n end\n end\n return nil unless changed\n self\n end",
"def direction_intersect(other)\n self.class.new.tap do |memo|\n unless other.keys.empty?\n a(memo, other)\n b(memo, other)\n end\n c(memo)\n d(memo, other)\n end\n end",
"def a(memo, other)\n if keys == other.keys.take(keys.size)\n keys.each do |order|\n if other.keys.include?(order)\n memo << [order, flip_direction(other.assoc(order).last)]\n end\n end\n else\n keys.each do |order|\n if other.keys.include?(order)\n memo << other.assoc(order)\n end\n end\n end\n end",
"def deep_merge!(other_hash)\n other_hash.each_pair do |k,v|\n tv = self[k]\n self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v\n end\n self\n end",
"def deep_merge!(other_hash)\n other_hash.each_pair do |k,v|\n tv = self[k]\n self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v\n end\n self\n end",
"def deep_merge!(other_hash)\n other_hash.each_pair do |k,v|\n tv = self[k]\n self[k] = tv.is_a?(::Hash) && v.is_a?(::Hash) ? tv.deep_merge(v) : v\n end\n self\n end",
"def deep_merge!(other_hash, append: :auto, &block)\n\t\t\t\treturn self unless other_hash\n\t\t\t\tother_hash.each_pair do |k,v|\n\t\t\t\t\ttv = self[k]\n\t\t\t\t\tcase\n\t\t\t\t\twhen tv.is_a?(Hash) && v.is_a?(Hash)\n\t\t\t\t\t\tself[k] = tv.deep_merge(v, &block)\n\t\t\t\t\twhen tv.is_a?(Array) && v.is_a?(Array)\n\t\t\t\t\t\tif append==:auto and v.length > 0 && v.first.nil? then\n\t\t\t\t\t\t\t#hack: if the array begins with nil, we append the new\n\t\t\t\t\t\t\t#value rather than overwrite it\n\t\t\t\t\t\t\tv.shift\n\t\t\t\t\t\t\tself[k] += v\n\t\t\t\t\t\telsif append && append != :auto\n\t\t\t\t\t\t\tself[k] += v\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tself[k] = block && tv ? block.call(k, tv, v) : v\n\t\t\t\t\t\tend\n\t\t\t\t\twhen tv.nil? && v.is_a?(Array)\n\t\t\t\t\t\t#here we still need to remove nil (see above)\n\t\t\t\t\t\tif append==:auto and v.length > 0 && v.first.nil? then\n\t\t\t\t\t\t\tv.shift\n\t\t\t\t\t\t\tself[k]=v\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tself[k] = block && tv ? block.call(k, tv, v) : v\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\tself[k] = block && tv ? block.call(k, tv, v) : v\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tself\n\t\t\tend",
"def +(other)\n self.class.new(values: (to_a + other.to_a))\n end",
"def deep_merge other_in, options_in = {}\n return self if other_in.nil? or other_in.blank?\n\n options = { mode: :append }.merge(options_in)\n\n other =\n if other_in.is_a?(OpenStruct)\n other_in.dup\n elsif other_in.is_a?(Hash)\n other_in.to_os\n else\n OpenStruct.new(nil => other_in)\n end\n\n self.reduce(other) do |res, key, value|\n res[key] =\n if res.table.keys.include?(key)\n case value\n when Hash, OpenStruct\n value.deep_merge(res[key], options)\n when Array\n value.concat([res[key]].compact.flatten(1))\n when NilClass\n res[key]\n else\n value_out =\n if options[:mode] == :append\n [res[key], value].compact.flatten(1)\n elsif options[:mode] == :prepend\n [value, res[key]].compact.flatten(1)\n else\n value\n end\n\n if value_out.is_a?(Array) && options[:dedup]\n value_out.uniq\n else\n value_out\n end\n end\n else\n value\n end\n\n res\n end\n end",
"def additive_changeset(node)\n {\n 'children_attribs' => [{\n 'id' => node.c[0].id,\n 'option_attribs' => { 'id' => node.c[0].option_id, 'name_translations' => {'en' => 'Animal'} },\n 'children_attribs' => [\n {\n 'id' => node.c[0].c[0].id,\n 'option_attribs' => { 'id' => node.c[0].c[0].option_id, 'name_translations' => {'en' => 'Cat'} },\n 'children_attribs' => 'NONE'\n },\n {\n 'id' => node.c[0].c[1].id,\n 'option_attribs' => { 'id' => node.c[0].c[1].option_id, 'name_translations' => {'en' => 'Dog'} },\n 'children_attribs' => 'NONE'\n },\n {\n 'option_attribs' => { 'name_translations' => {'en' => 'Ocelot'} },\n 'children_attribs' => 'NONE'\n }\n ]\n }, {\n 'id' => node.c[1].id,\n 'option_attribs' => { 'id' => node.c[1].option_id, 'name_translations' => {'en' => 'Plant'} },\n 'children_attribs' => [\n {\n 'id' => node.c[1].c[0].id,\n 'option_attribs' => { 'id' => node.c[1].c[0].option_id, 'name_translations' => {'en' => 'Tulip'} },\n 'children_attribs' => 'NONE'\n },\n {\n 'id' => node.c[1].c[1].id,\n 'option_attribs' => { 'id' => node.c[1].c[1].option_id, 'name_translations' => {'en' => 'Oak'} },\n 'children_attribs' => 'NONE'\n }\n ]\n }]\n }\n end",
"def deep_merge!(other)\n merger = proc do |key, v1, v2|\n Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2\n end\n self.merge! other, &merger\n end",
"def merge!(other)\n other.config.each do |key, value|\n case key\n when 'clusters', 'contexts', 'users'\n value.each do |other_value|\n own_value = config[key].find { |c| c['name'] == other_value['name'] }\n config[key].delete(own_value) if own_value\n config[key] << other_value\n end\n when 'current-context', 'preferences'\n config[key] = value\n else\n config[key] ||= value\n end\n end\n\n self\n end",
"def duplicate_conditions(duplicator, other)\n conditions_to_duplicate = other.conditions.to_a.select do |condition|\n dependent_object = condition.actable.dependent_object\n duplicated = duplicator.duplicated?(condition.actable.dependent_object)\n duplicator.mode == :course ? (dependent_object.nil? || duplicated) : duplicated\n end.map(&:actable)\n conditions << duplicator.duplicate(conditions_to_duplicate).map(&:acting_as)\n end",
"def +(other)\n if !@con.nil?\n other.each do |k, v|\n # add it to con\n @con[k] = v\n\n # add it as a method\n (class << self; self; end).class_eval { define_method(k) { v }}\n\n #add it to the @specialmethods array\n @specialmethods.push k\n end\n end\n self\n end",
"def merge!(other)\n o = dup\n other.each do |k,v|\n o.store!(k,v)\n end\n o\n end",
"def merge!(other)\n if other.lower_bound > @lower_bound\n @lower_bound = other.lower_bound\n @include[:lower_bound] = other.include_lower_bound?\n end\n if other.upper_bound\n if @upper_bound.nil? || other.upper_bound < @upper_bound\n @upper_bound = other.upper_bound\n @include[:upper_bound] = other.include_upper_bound?\n end\n end\n self\n end",
"def from_self\n fs = {}\n @opts.keys.each{|k| fs[k] = nil} \n fs[:from] = [self]\n clone(fs)\n end",
"def merge other_hash\n self.class.new nested_class, to_h.merge((other_hash if other_hash.is_a? Hash) || other_hash.to_h)\n end",
"def ^(other)\n results = {}\n\n self_attributes, other_attributes = attributes, other.attributes\n\n self_attributes.each_pair do |k,v|\n other_value = other_attributes[k]\n unless v == other_value\n results[k] = [v, other_value]\n end\n end\n\n results\n end",
"def deep_merge!(other_hash, &block); end",
"def merge(other)\n other = other.criteria\n\n fresh.tap do |criteria|\n [\n :profile_value, :failsafe_value, :terminate_after_value, :timeout_value, :offset_value,\n :limit_value, :scroll_args, :source_value, :preference_value, :search_type_value,\n :routing_value, :track_total_hits_value, :explain_value, :http_timeout_value\n ].each do |name|\n criteria.send(:\"#{name}=\", other.send(name)) unless other.send(name).nil?\n end\n\n [\n :sort_values, :includes_values, :preload_values, :eager_load_values, :must_values,\n :must_not_values, :filter_values, :post_must_values, :post_must_not_values,\n :post_filter_values\n ].each do |name|\n criteria.send(:\"#{name}=\", (criteria.send(name) || []) + other.send(name)) if other.send(name)\n end\n\n [:highlight_values, :suggest_values, :custom_value, :aggregation_values].each do |name|\n criteria.send(:\"#{name}=\", (criteria.send(name) || {}).merge(other.send(name))) if other.send(name)\n end\n end\n end",
"def cogroup(*others)\n unioned = self\n others.each do |other|\n unioned = unioned.union(other)\n end\n\n unioned.group_by_key\n end",
"def &(other)\n (to_set - other.to_set).inject(clone) do |copy, e|\n copy.delete e\n copy\n end\n end",
"def or other_result\n result = dup\n result.matched = hash_union(matched, other_result.matched)\n result.not_matched = hash_union(not_matched, other_result.not_matched)\n result\n end",
"def concat(other)\n other.rule_sets.each do |context_name, rule_set|\n context(context_name).concat(rule_set)\n end\n self\n end",
"def deepDiff(other)\n (keys + other.keys).uniq.each_with_object({}) do |key, diff|\n selfKey = self[key]\n otherKey = other[key]\n next if selfKey == otherKey\n if selfKey.respond_to?(:deepDiff) && otherKey.respond_to?(:deepDiff)\n diff[key] = selfKey.deepDiff(otherKey)\n else\n diff[key] = [selfKey, otherKey]\n end\n diff\n end\n end",
"def merge(other)\n other.each { |entry| self << entry }\n self\n end",
"def merge_from(other)\n @title = other.title unless other.title.to_s.empty?\n @descriptions[:default] = other.descriptions[:default] unless other.descriptions[:default].to_s.empty?\n @impact = other.impact unless other.impact.nil?\n other.tags.each do |ot|\n tag = @tags.detect { |t| t.key == ot.key }\n tag ? tag.value = ot.value : @tags.push(ot)\n end\n self\n end",
"def merge!(rel)\n return self if rel.nil?\n\n MULTI_VALUE_METHODS.each do |method|\n (@values[method] ||= []).concat(rel.values[method]).uniq! unless rel.values[method].nil?\n end\n\n MULTI_KEY_METHODS.each do |method|\n (@values[method] ||= {}).merge!(rel.values[method]) unless rel.values[method].nil?\n end\n\n SINGLE_VALUE_METHODS.each do |method|\n @values[method] = rel.values[method] unless rel.values[method].nil?\n end\n\n self\n end",
"def deep_merge!(other_hash, &block)\n other_hash.each_pair do |k,v|\n tv = self[k]\n if tv.is_a?(Hash) && v.is_a?(Hash)\n self[k] = tv.deep_merge(v, &block)\n else\n self[k] = block && tv ? block.call(k, tv, v) : v\n end\n end\n self\n end",
"def +(other)\n SearchAtom.new(@records.clone.merge!(other.records) { |key, _old, _new|\n _old + _new\n })\n end",
"def accumulate(r0, labels, rs)\n source = r0.source\n start = r0.stop_index\n stop = rs.empty? ? start : rs[-1].stop_index\n if labels\n labels.each_with_index do |label, i|\n rs[i].key_in_parent = label if label\n end\n end\n factor_result(source, start, stop, rs)\n end",
"def merge!(other)\n raise ArgumentError, ('Argument other should be Edge object (was %s)' % other.class) unless other.is_a?(Edge)\n\n if EDGE_TYPES.dig(other.edge_type) > EDGE_TYPES.dig(edge_type)\n @edge_type = other.edge_type\n end\n\n # puts(\"EDGE REDUCTION: #{@reduction.class} -- #{other.class} // #{other.reduction.class}\")\n @reduction = ChaosDetector::GraphTheory::Reduction.combine(@reduction, other.reduction)\n self\n end",
"def merge!(other)\n @options[:last_received_time] = other.last_received_time\n @options[:idle] = other.idle\n @options[:next_directive] = other.next_directive\n @options[:next_method] = other.next_method\n @options[:data] = other.data\n @options[:parse_next] = other.parse_next\n end",
"def other\n other = Relation.create(\n relation.klass,\n table: relation.table,\n predicate_builder: relation.predicate_builder\n )\n hash.each do |k, v|\n k = :_select if k == :select\n if Array === v\n other.public_send(\"#{k}!\", *v)\n else\n other.public_send(\"#{k}!\", v)\n end\n end\n other\n end",
"def dup *args\n x = super()\n x.deepen_dup!\n unless args.empty?\n x._options= *args\n end\n x\n end",
"def deep_merge!(other_hash)\n other_hash.each do |k,v|\n (class << (tv = self[k]); self; end).send :include, Hashie::Extensions::DeepMerge\n self[k] = tv.is_a?(::Hash) && v.is_a?(::Hash) ? tv.deep_merge(v) : v\n end\n self\n end",
"def deep_merge!(second)\n second.each_pair do |k,v|\n if self[k].is_a?(Hash) and second[k].is_a?(Hash)\n self[k].deep_merge!(second[k])\n else\n self[k] = second[k]\n end\n end\n end",
"def merge(other)\n conflict_proc = proc { |key, my_val, other_val| my_val + other_val }\n AbilityMap.new(@map.merge(other.map, &conflict_proc))\n end",
"def reverse_merge!(other_hash)\n super(self.class.new(other_hash))\n end",
"def merge!(other)\n\t\tsuper(keys_to_symbols(other))\n\tend",
"def deep_merge!(hash_or_config)\n return self if hash_or_config.nil?\n other_config = convert hash_or_config\n other_config.each do |key, other_value|\n value = has_key?(key) && self[key]\n self[key] = if ConfigNode === value && ConfigNode === other_value\n value.deep_merge!(other_value)\n elsif ConfigNode === value && other_value.nil?\n self[key]\n else\n other_value\n end\n end\n self\n end",
"def <<(other)\n c = Connection.new\n c.end = other\n other.edges << self unless other.edges.include? self\n self.connections << c\n self\n end",
"def make_new_matching_options(round_number)\n matching_option = Hash.new\n matching_option[:matching_option_round_number] = matching_option\n matching_option\nend",
"def dup\n\n # duplicate self\n rta = super\n\n # iterate through array and dup each hash\n rta.each_with_index do |w_hash, index|\n\n # dup the hash at this index\n rta[index] = w_hash.dup\n\n # to be complete, also dup the key/values in the hash, in case another hash/array is nested\n w_hash.each_pair do |k, v|\n rta[index][k] = v.dup if v.is_a? Hash\n end\n end\n\n # now everything should have new object_id's\n rta\n end",
"def merge_no(no1, no2)\n esquerda = no1.frequencia > no2.frequencia ? no2 : no1\n direita = esquerda == no1 ? no2 : no1\n no = No.new(:frequencia => esquerda.frequencia + direita.frequencia, :esquerda => esquerda, :direita => direita)\n esquerda.pai = direita.pai = no # Define o pai dos nos direita e esquerda\n no\n end",
"def concat(other)\n #raise TypeError unless other.kind_of?(self.class)\n _clear_cache\n other.each_node do |node|\n self.add_node(node)\n end\n other.each_edge do |node1, node2, edge|\n self.add_edge(node1, node2, edge)\n end\n self\n end",
"def merge(other)\n\t\tsuper(keys_to_symbols(other))\n\tend",
"def union(other)\n set_operation(other, :+,\n distinct: true,\n add_boundaries: true)\n end",
"def merge(other_entry)\n @references += other_entry.references\n self\n end",
"def deep_update(other_hash)\n other_hash.each_pair do |k,v|\n key = convert_key(k)\n regular_writer(key, convert_value(v, true))\n end\n self\n end",
"def merge(other)\n if self.overlaps?(other)\n [self | other]\n else\n [self, other]\n end\n end",
"def diff(other, options={})\n Differences::Entry.compute(self, other, diff_criteria(options), options)\n end",
"def merge!(another)\n configs = self.configs\n another.each_pair do |key, value|\n if config = configs[key]\n config.set(receiver, value)\n else\n store[key] = value\n end\n end\n self\n end",
"def combine(other, conn=:and)\n return other.clone if self.empty?\n\n if other.empty?\n return self.clone\n elsif self.filters[0].member?(conn)\n f = self.clone\n f.filters[0][conn] += other.filters\n elsif other.filters[0].member?(conn)\n f = other.clone\n f.filters[0][conn] += self.filters\n else\n f = initialize(self.clone.filters + other.filters, conn)\n end\n\n return f\n end",
"def combine!(other)\n return self if other == self\n\n @transaction_count += other.transaction_count\n @call_count += other.call_count\n @rows_returned += other.rows_returned\n @call_time += other.call_time\n\n @min_call_time = other.min_call_time if @min_call_time.zero? or other.min_call_time < @min_call_time\n @max_call_time = other.max_call_time if other.max_call_time > @max_call_time\n\n @min_rows_returned = other.min_rows_returned if @min_rows_returned.zero? or other.min_rows_returned < @min_rows_returned\n @max_rows_returned = other.max_rows_returned if other.max_rows_returned > @max_rows_returned\n\n @histogram.combine!(other.histogram)\n self\n end",
"def merge!(other)\n update!(other.value)\n end",
"def reverse_merge!(other_hash)\n @parameters.merge!(other_hash.to_h) { |key, left, right| left }\n self\n end",
"def reverse_merge(other_hash); end",
"def reverse_merge(other_hash); end",
"def add_common_node_option_if_needed(options, node_opts, key)\n return options if options[key].nil? && node_opts.first[key].nil?\n\n options[key] ||= node_opts.first[key]\n end",
"def merge(other)\n other.items.each do |item, record|\n @items[item] ||= {observed: [], removed: []}\n @items[item][:observed] |= record[:observed]\n @items[item][:removed] |= record[:removed]\n @items[item][:observed] -= @items[item][:removed]\n end\n end",
"def deep_merge!(second)\n return nil unless second\n second.each_pair do |k,v|\n if self[k].is_a?(Array) and second[k].is_a?(Array)\n self[k].deep_merge!(second[k])\n elsif self[k].is_a?(Hash) and second[k].is_a?(Hash)\n self[k].deep_merge!(second[k])\n else\n self[k] = second[k]\n end\n end\n end",
"def reverse_merge!(other_hash); end",
"def union!(other)\n redis.sunionstore key, key, other.key\n ensure\n notify_changed\n end",
"def +(other)\n return dup.add(other)\n end",
"def initialize_duplicate_conditions(duplicator, other)\n duplicate_conditions(duplicator, other)\n video_conditions << other.video_conditions.\n select { |condition| duplicator.duplicated?(condition.conditional) }.\n map { |condition| duplicator.duplicate(condition) }\n end",
"def reduce_twice(_production, _range, _tokens, _children)\n multiplicity(2, 2)\n end",
"def concat_merge original\n {}.tap do |result|\n original.each do |element|\n element.each_pair do |key, value|\n if value.is_a?(Array)\n result[key] ||= []\n result[key].concat value\n merge_if_equals(result[key])\n else\n result[key] = value\n end\n end\n end\n end\n end",
"def deep_merge(other_hash)\n dup.deep_merge!(other_hash)\n end",
"def concat(other)\n other.each do |obj|\n add obj\n end\n self\n end",
"def +(other)\n self if other.length == 0\n union = Grammar.new(to_hash)\n other.each do |r|\n union.push(r)\n end\n\n union\n end",
"def |(other)\n self.class.new(values: (to_a | other.to_a))\n end",
"def deep_merge!(other_hash)\n replace(deep_merge(other_hash))\n end",
"def deep_merge!(other_hash)\n replace(deep_merge(other_hash))\n end",
"def b(memo, other)\n other.keys.each do |sort|\n if keys.include?(sort) && !memo.keys.include?(sort)\n memo << other.assoc(sort)\n end\n end\n end",
"def +(other)\n other.each do |dep|\n add dep\n end\n self\n end",
"def prepare_reuse_validation_diff(other)\n original = self.reload!.comparable\n reference = other.reload!.comparable\n unique_identifiers.each { |id| reference[id] = original[id] }\n [original, reference]\n end"
] |
[
"0.56236005",
"0.55999064",
"0.55021197",
"0.5483281",
"0.53406495",
"0.53396297",
"0.5334312",
"0.5278847",
"0.5250876",
"0.5205176",
"0.5188635",
"0.517613",
"0.51285815",
"0.5121691",
"0.5067655",
"0.5063546",
"0.5050378",
"0.50281185",
"0.5025045",
"0.50207466",
"0.5010415",
"0.5007892",
"0.4995203",
"0.4990813",
"0.49847314",
"0.49777836",
"0.4960078",
"0.4960078",
"0.49471223",
"0.49426395",
"0.4942624",
"0.4942207",
"0.49406272",
"0.49332377",
"0.49239093",
"0.4911818",
"0.4903728",
"0.48967955",
"0.48933554",
"0.48894867",
"0.4881722",
"0.48763448",
"0.4866466",
"0.48539305",
"0.4852518",
"0.4852136",
"0.48519632",
"0.48459122",
"0.48429653",
"0.4834408",
"0.48279938",
"0.48229766",
"0.48223567",
"0.48107162",
"0.48092532",
"0.48072493",
"0.48017928",
"0.4783345",
"0.47824535",
"0.4773801",
"0.47737283",
"0.47700396",
"0.47667193",
"0.47663757",
"0.47635615",
"0.4761012",
"0.4749711",
"0.4744976",
"0.47431016",
"0.4740415",
"0.4734894",
"0.47328043",
"0.47326177",
"0.47271785",
"0.47238332",
"0.47216088",
"0.47191596",
"0.47182643",
"0.471726",
"0.47166622",
"0.47161517",
"0.47134468",
"0.47134468",
"0.4708746",
"0.47084093",
"0.4708274",
"0.47081932",
"0.4705496",
"0.4705328",
"0.46997437",
"0.4689106",
"0.46865934",
"0.46848246",
"0.46846193",
"0.46800727",
"0.46759802",
"0.46688935",
"0.46681315",
"0.46662945",
"0.46656004",
"0.46655"
] |
0.0
|
-1
|
Takes an array of three integers to add to VERSION and three integers to multiply to VERSION
|
def bump(by,reset)
version_triplet.zip(by, reset).collect{|x,y,z| (x+y)*z}.join(".")
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def test_bump_numeric\n value_ = ::Versionomy.create([1, 9, 2, 'a2'], :semver)\n value_ = value_.bump(:patch)\n assert_equal([1, 9, 3, ''], value_.values_array)\n end",
"def custom_multiply(array, number)\n result = []\n number.times { array.each { |element| result << element}}\n result\nend",
"def custom_multiply(array,number)\n new_array = []\n number.times {new_array+=array}\n return new_array\nend",
"def custom_multiply(array, number)\n # Return a new array with the array that's passed in\n # as an argument multiplied by the number argument\n result = []\n number.times { array.each { |elem| result << elem } }\n result\nend",
"def multiplies (*args)\n multi=1\n args.each do |item|\n multi *=item\n end\n multi\nend",
"def custom_multiply(array, number)\n count = 0\n final =[]\n while count < number\n final = array + final\n count +=1\n end\n final\nend",
"def mult(*args)\n\tprod = 1\n\targs.each do |arg|\n\t\tprod *= arg\n\tend\n\tprod\nend",
"def test_bump_numeric\n value_ = ::Versionomy.create([1, 9, 2, 'a', 2], :rubygems)\n value_ = value_.bump(:field2)\n assert_equal([1, 9, 3, 0, 0, 0, 0, 0], value_.values_array)\n end",
"def multiply(array, num_two)\n array * num_two\nend",
"def product(numbers)\n result = 1\n numbers.each do |number|\n result *= number\n end\n result\nend",
"def increase_version version\n puts 'increased'\n new_version = \"#{version[1]}.#{version[2]}.#{version[3]}.\" +\n \"#{version[4].to_i + 1}\"\n end",
"def multiply_list(array1, array2)\n results = []\n n = 0\n\n array1.size.times do |num|\n results << array1[n]*array2[n]\n n += 1\n end\n\n results\nend",
"def multiply_list(arr1, arr2)\r\nresult = []\r\ncounter = 0\r\n\r\narr1.length.times do |num|\r\n result << arr1[counter] * arr2[counter]\r\n counter += 1\r\nend\r\np result\r\nend",
"def multiply_list(numbers1, numbers2)\n products = []\n numbers1.each_with_index do |num, ind|\n products << num * numbers2[ind]\n end\n products\nend",
"def test_bump_alias\n value_ = ::Versionomy.create([1, 9, 2, 'a', 2], :rubygems)\n value_ = value_.bump(:minor)\n assert_equal([1, 10, 0, 0, 0, 0, 0, 0], value_.values_array)\n end",
"def multiply_me(array, int)\r\n\r\n arr = [] # empty array created\r\n\r\n i = 0 # iteration starts to multiply each item\r\n while i < array.length\r\n arr << array[i] * int # products collected\r\n i += 1\r\n end\r\n\r\n arr # result\r\nend",
"def multiply_by(array)\n return array.map { |el| el * 3}\nend",
"def multiply (array)\n\tarray.inject(1) do |result, element|\n\t\tresult * element\n\tend\nend",
"def multiply_list(array_1, array_2)\n result = []\n array_1.size.times do |index|\n result << array_1[index] * array_2[index]\n end\n result\nend",
"def multiply(numbers)\n numbers.inject { |sum, n| sum * n }\n end",
"def pair_product(arr, num) \n\nend",
"def get_product_integers(array_of_integers)\n\n results = []\n array_of_integers.each_with_index do |num1,index1|\n product = 1\n array_of_integers.each_with_index do |num2,index2|\n next if index1 == index2\n product *= num2\n end\n results << product\n end\n p results\n\n end",
"def arrMultiply(arr)\n (arr[0].to_i * arr[1].to_i).to_s\nend",
"def multiply a, b, *array\n\ttotal = a * b\n\tremaining = array.length\n\ti = 0\n\twhile i < remaining\n\t\ttotal = total * array[i]\n\t\ti = i + 1\n\tend\n\ttotal\nend",
"def multiply(*numbers)\n numbers.reduce(1, :*)\n end",
"def multiply(array)\n array.inject(:*)\nend",
"def multiply(number_1, number_2, number_3)\n output = number_1 * number_2 * number_3\n return output\nend",
"def multiply(nums)\r\n nums.reduce(:*)\r\nend",
"def multiply_els(array)\n\tarray.inject(1) { |num, item| num * item }\n\nend",
"def test_change_alias\n value_ = ::Versionomy.create([1, 8, 7, 'a', 2], :rubygems)\n value_ = value_.change(:minor => 9)\n assert_equal([1, 9, 7, 'a', 2, 0, 0, 0], value_.values_array)\n end",
"def add_perversion(value, unique_id, event_id, map_id)\n container = (@perversion[[unique_id, event_id, map_id]] ||= [])\n if event_id != 0 && unique_id != 0\n mod_value = value.abs / (container.length + 1)\n else\n mod_value = value.abs\n end\n mod_value = [1, mod_value].max\n if value < 0\n mod_value = -mod_value\n end\n container << mod_value\n if $game_player.battler == self\n $game_variables[Perversion::VARIABLE] += mod_value\n end\n end",
"def product_thirteen(array, index)\n\tprod = 1\n\ti = index\n\twhile i < index+13\n\t\tprod *= array[i]\n\t\ti+=1\n\tend\n\tputs prod\n\treturn prod\nend",
"def multiply_list(arr1, arr2)\n new_arr = []\n arr1.size.times do |ind|\n new_arr << arr1[ind] * arr2[ind]\n end\n new_arr\nend",
"def multiply(*arr)\n\tproduct, i = 1, 0\n\n while i < arr.length\n \tproduct *= arr[i]\n \ti += 1\n end\n\n # could also just use reduce, just keeping fundamentals sharp\n product\nend",
"def output(prefix_products, suffix_products, nums)\n result = []\n\n nums.count.times do |index|\n result << if index == 0\n suffix_products[index + 1]\n elsif index == nums.count - 1\n prefix_products[index - 1]\n else\n (prefix_products[index - 1] * suffix_products[index + 1])\n end\n end\n\n result\nend",
"def multiply_list(array1, array2)\n result = []\n array1.each_with_index do |num, index|\n result.push(num * array2[index])\n end\n \nresult\n \n \n \nend",
"def index_multiplier_method\n #@multiplied_integer_array = []\n @reversed_array.each_with_index do |value, index|\n if index.odd? == true\n value = value * 2\n @multiplied_integer_array << value\n else\n value = value\n @multiplied_integer_array << value\n end\n end\n return @multiplied_integer_array\n end",
"def multiply(*args) # multiple arguments\n array = args.to_a #convert to array\n array.reduce(:*)\nend",
"def multisum(number)\n\n mult_array = (1..number).select { |n| n % 3 == 0 || n % 5 == 0 }\n p mult_array\n sum = mult_array.inject(0,:+)\n p sum\nend",
"def productify(array)\n prods = [1] * array.length\n current = array[0]\n (1...array.length).each do |i|\n prods[i] *= current\n current *= array[i]\n end\n current = array[-1]\n (array.length - 2).downto(0).each do |i|\n prods[i] *= current\n current *= array[i]\n end\n\n prods\nend",
"def product(numbers)\n if numbers.length > 0\n # inject pushes a character into every position of an\n # array, in this case multiplying each integer by the next\n numbers.inject(:*)\nelse\n return 1\nend\nend",
"def product(arr)\n product = 1\n for i in 0...arr.length\n product *= arr[i]\n end\n product\nend",
"def multiply_list(array1, array2)\n result = []\n array1.each_index { |index| result << array1[index] * array2[index]}\n result\nend",
"def multiply *array\n puts array.inspect\n array.flatten.inject(:*)\n end",
"def multiply_sum_by_3rd_argument\n\n end",
"def times_three(nums)\n answer = []\n nums.each do |num|\n answer << num * 3\n end\n return answer\nend",
"def highest_product_of_3(array_of_ints)\n raise ArgumentError, \"Less than 3 numbers given\" if array_of_ints.length < 3\n\n highest = array_of_ints.first(2).max # of 1st 3 ints\n lowest = array_of_ints.first(2).min\n highest_product_of_2 = array_of_ints[0] * array_of_ints[1]\n lowest_product_of_2 = array_of_ints[0] * array_of_ints[1]\n highest_product_of_3 = array_of_ints[0] * array_of_ints[1] * array_of_ints[2]\n\n # Walk through items, starting at index 2\n # (we could slice the array but that would use n space).\n array_of_ints.each_with_index do |current, index|\n next if index < 2\n\n # Do we have a new highest product of 3?\n # It's either the current highest,\n # or the current times the highest product of two,\n # or the current times the lowest product of two.\n highest_product_of_3 = [\n highest_product_of_3,\n current * highest_product_of_2,\n current * lowest_product_of_2\n ].max\n\n # Do we have a new highest product of two?\n highest_product_of_2 = [\n highest_product_of_2,\n current * highest,\n current * lowest\n ].max\n\n # Do we have a new lowest product of two?\n lowest_product_of_2 = [\n lowest_product_of_2,\n current * highest,\n current * lowest\n ].min\n\n # Do we have a new highest?\n highest = [highest, current].max\n\n # Do we have a new lowest?\n lowest = [lowest, current].min\n end\n\n highest_product_of_3\nend",
"def multiply_list(array1, array2)\n new_array = []\n array1.count.times do \n new_array << (array1.pop) * (array2.pop)\n end\n new_array.reverse\nend",
"def multiply_machine(number_1, number_2, number_3)\n output = number_1 * number_2 * number_3\n return output\nend",
"def integer_products integers\n\t# use each with index to loop through integers and find product of all other integers\n\t# better solution:\n\t# create an array that corresponds to the product of each integer before each index, and an array of the product of each integer after each index\n\tproduct_so_far = 1\n\tproducts_before_index = []\n\tintegers.each_with_index do |int, index|\n\t\tproducts_before_index[index] = product_so_far\n\t\tproduct_so_far*= integers[index]\n\tend\n\n\tproducts_after_index = []\n\tproduct_so_far = 1\n\ti = integers.length - 1\n\twhile i >= 0\n\t\tproducts_after_index[i] = product_so_far\n\t\tproduct_so_far*= integers[i]\n\t\ti-= 1\n\tend\n\n\treturn [products_before_index, products_after_index]\n\nend",
"def element_times_index(numbers)\n\tfor i in 0..numbers.length-1\n numbers[i] *= i\n end\n return numbers\nend",
"def multiply_list(array_1, array_2)\n results = []\n array_1.each_with_index {|num,idx| results << (num * array_2[idx])}\n results\nend",
"def vvec( version_string )\n\t\t\treturn version_string.split( '.' ).\n\t\t\t\tcollect {|num| num.to_i }.pack( 'N*' )\n\t\tend",
"def multiply!(numbers, multiplier)\n counter = 0\n\n loop do\n break if counter == numbers.size\n \n numbers[counter] *= multiplier\n\n counter += 1\n end\n\n numbers\nend",
"def versions vs\n raise ArgumentError, \"Invalid versions. Must be a positive integer.\" unless vs.is_a?(Fixnum) && vs > 0\n spawn :@versions, vs\n end",
"def mul(a, b)\n res = []\n res << a[0]*b[0] + a[1]*b[2]\n res << a[0]*b[1] + a[1]*b[3]\n res << a[2]*b[0] + a[3]*b[2]\n res << a[2]*b[1] + a[3]*b[3]\n res\nend",
"def multiply(*nums)\n return nums.reduce(:*)\nend",
"def nextVersion(version)\n\n current_version = version.split('.').reverse;\n new_version = [];\n\n if version.split('.').length == 1\n (version.to_i + 1).to_s\n else\n current_version.map.with_index do |n,i|\n if i == 0\n new_n = (n.to_i + 1).to_s\n if new_n == '10'\n new_version.push('0')\n current_version[i+1] = (current_version[i+1].to_i + 1).to_s\n else\n new_version.push(new_n)\n end\n else\n if n == '10'\n if i == (current_version.length - 1)\n new_version.push(n)\n else\n new_version.push('0')\n current_version[i+1] = (current_version[i+1].to_i + 1).to_s\n end\n else\n new_version.push(n)\n end\n end\n end\n new_version.reverse.join('.')\n end\n\nend",
"def multiply_by_two(array)\n # double_numbers = []\n # array.each do |number|\n # double_numbers << number * 2\n # end\n # double_numbers\n array.map { |number| number * 2 }\nend",
"def multiply_list(arry1, arry2)\n index = 0\n arry3 = []\n\n while index < arry1.length\n arry3 << arry1[index] * arry2[index]\n index += 1\n end\n arry3\nend",
"def multiply_list(array_1, array_2)\n result = []\n\n array_1.each_with_index do |num, index|\n result << num * array_2[index]\n end\n result\nend",
"def multiply(nums)\n\treturn 0 if nums == []\n\tnums.reduce(:*)\nend",
"def multiply_list(arr1, arr2)\n products_arr = []\n idx = 0\n until idx >= arr1.length\n products_arr << arr1[idx] * arr2[idx]\n idx += 1\n end\n products_arr\nend",
"def target_version_array\n @target_version_array ||=\n begin\n target_version_array = []\n each_package do |package_name, new_version, current_version, candidate_version, magic_version|\n case action\n when :upgrade\n if version_equals?(current_version, new_version)\n # This is a short-circuit (mostly for the rubygems provider) to avoid needing to\n # expensively query the candidate_version which must come later. This only checks\n # exact matching, the check for fuzzy matching is later.\n logger.trace(\"#{new_resource} #{package_name} #{new_version} is already installed\")\n target_version_array.push(nil)\n elsif current_version.nil?\n # This is a simple check to see if we have any currently installed version at all, this is\n # safe to do before the allow_downgrade check so we check this before.\n logger.trace(\"#{new_resource} has no existing installed version. Installing install #{candidate_version}\")\n target_version_array.push(candidate_version)\n elsif !allow_downgrade && version_compare(current_version, candidate_version) == 1\n # This check for downgrading when allow_downgrade is false uses the current_version rather\n # than the magic_version since we never want to downgrade even if the constraints are not met\n # if the version is higher. This check does use the candidate_version and unlazies this so\n # there will a perf hit on idempotent use when allow_downgrade is false which is unavoidable.\n logger.trace(\"#{new_resource} #{package_name} has installed version #{current_version}, which is newer than available version #{candidate_version}. Skipping...)\")\n target_version_array.push(nil)\n elsif magic_version.nil?\n # This is the check for fuzzy matching of the installed_version, where if the installed version\n # does not match the desired version constraints (but is not an exact match) then we need to\n # install the candidate_version (this must come after the allow_downgrade check)\n logger.trace(\"#{new_resource} has an installed version that does not match the version constraint. Installing install #{candidate_version}\")\n target_version_array.push(candidate_version)\n elsif candidate_version.nil?\n # This check necessarily unlazies the candidate_version and may be expensive (connecting to\n # rubygems.org or whatever). It comes as late as possible.\n logger.trace(\"#{new_resource} #{package_name} has no candidate_version to upgrade to\")\n target_version_array.push(nil)\n elsif version_equals?(current_version, candidate_version)\n # This check sees if the candidate_version is already installed or if we should upgrade/update the\n # package. This is the normal idempotent behavior of :upgrade and is inherently expensive due to\n # unlazying the candidate_version. To prevent the perf hit the version may be specified with a full\n # version constraint. Then the cookbook can roll the version forward and use :upgrade to force version\n # pinning.\n logger.trace(\"#{new_resource} #{package_name} #{candidate_version} is already installed\")\n target_version_array.push(nil)\n else\n logger.trace(\"#{new_resource} #{package_name} is out of date, will update to #{candidate_version}\")\n target_version_array.push(candidate_version)\n end\n\n when :install\n if current_version && new_version && !allow_downgrade && version_compare(current_version, new_version) == 1\n # This is the idempotency guard for downgrades when downgrades are not allowed. This should perhaps raise\n # an exception since we were told to install an exact package version but we are silently refusing to do so\n # because a higher version is already installed. Maybe we need a flag for users to apply their preferred\n # declarative philosophy? This has to come early and outside of the two code paths below.\n logger.warn(\"#{new_resource} #{package_name} has installed version #{current_version}, which is newer than available version #{new_version}. Skipping...)\")\n target_version_array.push(nil)\n elsif new_version && !use_magic_version?\n # This is for \"non magic version using\" subclasses to do comparisons between the current_version and the\n # desired new_version. XXX: If we converted this to current_version_requirement_satisfied? and made it specific\n # to the current version check and then eliminated the magic_version, we might be able to eliminate separate codepaths\n # here, and eliminate the semantic confusion around the magic_version?\n if version_requirement_satisfied?(current_version, new_version)\n logger.trace(\"#{new_resource} #{package_name} #{current_version} satisfies #{new_version} requirement\")\n target_version_array.push(nil)\n else\n # XXX: some subclasses seem to depend on this behavior where the new_version can be different from the\n # candidate_version and we install the new_version, it seems like the candidate_version should be fixed to\n # be resolved correctly to the new_version for those providers. although it may just be unit test bugs.\n # it would be more correct to use the candidate_version here, but then it needs to be the correctly resolved\n # candidate_version against the new_version constraint.\n logger.trace(\"#{new_resource} #{package_name} #{current_version} needs updating to #{new_version}\")\n target_version_array.push(new_version)\n end\n elsif magic_version.nil?\n # This is for when we have a \"magic version using\" subclass and where the installed version does not match the\n # constraint specified in the new_version, so we need to upgrade to the candidate_version. This is the only\n # codepath in the :install branch which references the candidate_version so it is slow, but it is the path where\n # we need to do work anyway. XXX: should we check for candidate_version.nil? somewhere around here?\n logger.trace(\"#{new_resource} #{package_name} not installed, installing #{candidate_version}\")\n target_version_array.push(candidate_version)\n else\n logger.trace(\"#{new_resource} #{package_name} #{current_version} already installed\")\n target_version_array.push(nil)\n end\n\n else\n # in specs please test the public interface provider.run_action(:install) instead of provider.action_install\n raise \"internal error - target_version_array in package provider does not understand this action\"\n end\n end\n\n target_version_array\n end\n end",
"def doubler(numbers)\n # Write your code here\n array=[]\n numbers.each do |num|\n array << num *= 2\n end\n array\nend",
"def productify(array)\n\nend",
"def multiply_by_any_number(numbers, multiplier)\n multiplied_numbers = []\n counter = 0\n\n loop do\n break if counter == numbers.size\n\n multiplied_numbers << numbers[counter] * multiplier\n counter += 1\n end\n\n multiplied_numbers\nend",
"def product_inject(numbers_array)\n numbers_array.inject {|accumulator, element| accumulator *= element}\nend",
"def product(numbers)\n numbers.reduce(1) { |acc, x| acc * x }\nend",
"def calculate_versions\n tags = `git for-each-ref --sort='*authordate' --format='%(refname:short)' refs/tags/`.split(\"\\n\")\n @last = tags.select {|l| l =~ /(^#{@prefix}-|\\.0$)/ }.last.gsub(/^#{@prefix}-/, '')\n @current = @last\n\n pemajor, major, minor = @last.split('.')\n minor = minor.to_i + 1\n quarter = major.to_i + 1\n @next = \"#{pemajor}.#{major}.#{minor}\"\n @quarter = \"#{pemajor}.#{quarter}.0\"\nend",
"def product(numbers)\n product = 1;\n numbers.each do |x|\n product = product * x;\n end\n product\nend",
"def double_numbers(array)\n new_array = []\n\n array.each do |number|\n new_array << number *= 2\n end\n return new_array\nend",
"def multiply_num(arr) # The round brakets gives the starting value\n arr.inject(1) do |quot, num| #quot survive, num gets multiplied on\n quot * num\n end\nend",
"def multiply_all_by(array, num)\n\n result = []\n array.each do |elem|\n result << elem * num\n end\n result\nend",
"def index_multiplier_method(reverse_integer_array)\n multiplied_integer_array = []\n reverse_integer_array.each_with_index do |value, index|\n if index.odd? == true\n value = value * 2\n multiplied_integer_array << value\n else\n value = value\n multiplied_integer_array << value\n end\n end\nreturn multiplied_integer_array\nend",
"def multiply(numbers, factor)\n multiplied_numbers = []\n counter = 0\n\n loop do\n break if counter == numbers.size\n multiplied_numbers << (numbers[counter] * factor)\n counter += 1\n end\n\n multiplied_numbers\nend",
"def multiply_arrnums_by_index(numbers) # array of ints\n new_array = [] # empty array\n i = 0 # start at indice 0\n while i < numbers.length\n new_array << numbers[i] * i # shovel value of int val of the indice * the indice\n # numb_to_mult = numbers[i]\n # numb_multd = numbers[i] * numb_to_mult\n # new_array << numb_multd\n i += 1 # next iteration\n end\n return new_array\nend",
"def multiple(num1,num2)\n\tnum1 * num2\nend",
"def product(array)\n products = []\n current = 0\n while (current < array.length)\n i = 0\n product = 1\n\n while (i < array.length)\n if i != current\n product *= array[i]\n end\n i += 1\n end\n\n products << product\n current += 1\n end\n\n products\nend",
"def multiply_list(arr1, arr2)\n result = []\n arr1.each_with_index { |num, idx| result << num * arr2[idx] }\n result\nend",
"def product(numbers)\n numbers.inject(1) { |result, num| num.is_a?(Numeric) ? result * num : result }\n end",
"def element_times_index(numbers)\n\tmulti = []\n \n\ti = 0\n\twhile i < numbers.length\n\t\titem = numbers[i]*i\n\t\tmulti << item\n\t\ti += 1\n end\n\n\treturn multi\nend",
"def productify(arr)\n\n up_product = 1\n up_array = []\n arr.length.times do |idx|\n up_product *= arr[idx]\n up_array << up_product\n end\n\n down_product = 1\n down_array = Array.new(arr.length)\n (arr.length - 1).downto(0) do |idx|\n down_product *= arr[idx]\n down_array[idx] = down_product\n end\n\n result = []\n arr.length.times do |idx|\n product = 1\n up_idx = idx - 1\n down_idx = idx + 1\n if up_idx >= 0\n product *= up_array[up_idx]\n end\n if down_idx < arr.length\n product *= down_array[down_idx]\n end\n result[idx] = product\n end\n\n result\n\nend",
"def multiply(array,mult)\n array.map{|num| num*mult}\nend",
"def multiply_list(arr1, arr2)\n new_arr = []\n arr1.each_with_index do |num, index| \n new_arr << num * arr2[index] \n end\n p new_arr\nend",
"def my_product(array)\n return nil if array.length == 0\n\n product = 1\n array.each do |elem|\n product = product * elem\n end\n product\nend",
"def *(multiplier)\n return map {|currency, money| money * multiplier}\n end",
"def multiply(*input)\n\t\tinput.flatten.inject(:*)\n\tend",
"def my_function4(arr)\n products_arr = []\n products_so_far = 1\n i = 0\n while i < arr.length\n products_arr[i] = products_so_far\n products_so_far *= arr[i]\n i += 1\n end\n\n products_so_far = 1\n i = arr.length - 1\n while i >= 0\n products_arr[i] *= products_so_far\n products_so_far *= arr[i]\n i -= 1\n end\n\n return \"Products: #{products_arr}\"\nend",
"def multiply_by(number, array)\n product_array = []\n array.map do |item|\n product_array.push(item * number)\n end\n puts product_array\nend",
"def build_prefix_products(nums)\n prefix_products = []\n\n nums.each do |num|\n prefix_products << if prefix_products.count > 0\n prefix_products.last * num\n else\n num\n end\n end\n\n prefix_products\nend",
"def multiply_list(array1, array2)\n array1.each_with_index.map do |current_integer, index|\n current_integer * array2[index]\n end\nend",
"def products(arr)\n\tproducts = []\n\tproduct = 1\n\tfor i in 0..arr.length-1\n\t\tproducts[i] = product\n\t\tproduct = product * arr[i]\n\tend\n\ti = arr.length - 1\n\tproduct = 1\n\twhile i >= 0\n\t\tproducts[i] = products[i] * product\n\t\tproduct = arr[i] * product\n\t\ti -= 1\n\tend\n\tproducts\nend",
"def product_machine(array_input)\nindex = 0\nproduct = 1\nnumber_of_loops = array_input.length\n\nnumber_of_loops.times do\n product = product * array_input[index]\n index = index + 1\nend\noutput = product\nreturn output\nend",
"def multiply(arr)\n\tans=1\n\tarr.each{|i|ans=ans*i}\n\treturn ans\nend",
"def look_up_version_numbers(selectors, options)\n selectors.collect do | selector |\n if selector[:tag] && selector[:latest]\n version = version_repository.find_by_pacticipant_name_and_latest_tag(selector[:pacticipant_name], selector[:tag])\n raise Error.new(\"No version of #{selector[:pacticipant_name]} found with tag #{selector[:tag]}\") unless version\n # validation in resource should ensure we always have a version\n {\n pacticipant_name: selector[:pacticipant_name],\n pacticipant_version_number: version.number\n }\n elsif selector[:latest]\n version = version_repository.find_latest_by_pacticpant_name(selector[:pacticipant_name])\n raise Error.new(\"No version of #{selector[:pacticipant_name]} found\") unless version\n {\n pacticipant_name: selector[:pacticipant_name],\n pacticipant_version_number: version.number\n }\n elsif selector[:tag]\n # validation in resource should ensure we always have at least one version\n versions = version_repository.find_by_pacticipant_name_and_tag(selector[:pacticipant_name], selector[:tag])\n raise Error.new(\"No version of #{selector[:pacticipant_name]} found with tag #{selector[:tag]}\") unless versions.any?\n versions.collect do | version |\n {\n pacticipant_name: selector[:pacticipant_name],\n pacticipant_version_number: version.number\n }\n end\n else\n selector.dup\n end\n end.flatten.compact.collect do | selector |\n add_ids(selector)\n end\n end",
"def sum_mix3(x)\n x.map(&:to_i).inject(:+)\nend",
"def multiply(*nums)\n nums.reduce(1, :*)\nend",
"def triple(nums)\n nums.map {|num| num * 3}\nend",
"def multiply_list(arr1, arr2)\n products = []\n counter = 0\n\n loop do\n products << (arr1[counter] * arr2[counter])\n\n counter += 1\n break if counter == arr1.length\n end\n\n products\nend"
] |
[
"0.60821146",
"0.6035046",
"0.5951242",
"0.5840144",
"0.58135456",
"0.5794542",
"0.5758383",
"0.57424957",
"0.5730996",
"0.5718913",
"0.5711211",
"0.57071185",
"0.5693568",
"0.56609046",
"0.56587124",
"0.5647613",
"0.5642471",
"0.56391037",
"0.5638697",
"0.5625911",
"0.5599047",
"0.55907273",
"0.5566693",
"0.55576587",
"0.5552242",
"0.55156714",
"0.5511959",
"0.5509587",
"0.5507963",
"0.55036455",
"0.55024666",
"0.54904723",
"0.5482101",
"0.54790694",
"0.54733944",
"0.54623634",
"0.54436195",
"0.5443055",
"0.54425293",
"0.5441926",
"0.5438484",
"0.54335946",
"0.5428092",
"0.5427407",
"0.5423262",
"0.5420927",
"0.5420484",
"0.54112273",
"0.5402597",
"0.5400304",
"0.53998005",
"0.5397824",
"0.53810513",
"0.5379441",
"0.53780293",
"0.5376599",
"0.53751177",
"0.5363736",
"0.5360539",
"0.53535783",
"0.53484285",
"0.5346756",
"0.53325623",
"0.5330791",
"0.5327562",
"0.53215325",
"0.53211457",
"0.5320695",
"0.532024",
"0.5319389",
"0.5313059",
"0.53070563",
"0.5305044",
"0.5304732",
"0.53008246",
"0.53004855",
"0.52985364",
"0.52796686",
"0.5271989",
"0.5269917",
"0.52690727",
"0.52687335",
"0.52682143",
"0.5265177",
"0.52640194",
"0.52633804",
"0.52613443",
"0.52611333",
"0.5259041",
"0.52551633",
"0.5242095",
"0.5238284",
"0.5231684",
"0.52304757",
"0.5227988",
"0.52153754",
"0.5213775",
"0.5206483",
"0.5201596",
"0.5199658"
] |
0.6652467
|
0
|
Returns a partial SPARQL grammar for this operator.
|
def to_sparql(**options)
"isNumeric(" + operands.first.to_sparql(**options) + ")"
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def to_sparql(**options)\n \"(!\" + operands.first.to_sparql(**options) + \")\"\n end",
"def to_sparql(**options)\n '(' + operands.to_sparql(delimiter: '/', **options) + ')'\n end",
"def to_sparql(**options)\n operands.first.to_sparql(reduced: true, **options)\n end",
"def to_sparql(**options)\n \"(#{operands.first.to_sparql(**options)} / #{operands.last.to_sparql(**options)})\"\n end",
"def to_sparql(**options)\n raise NotImplementedError, \"SPARQL::Algebra '#{first}' operator not implemented\"\n end",
"def to_sparql(**options)\n \"(#{operands.first.to_sparql(**options)} #{self.class.const_get(:NAME)} #{operands.last.to_sparql(**options)})\"\n end",
"def to_grammar\n raise NotImplementedError\n end",
"def to_sparql(**options)\n \"langMatches(\" +\n operands.first.to_sparql(**options) +\n \", \" +\n operands.last.to_sparql(**options) +\n \")\"\n end",
"def to_sparql(**options)\n \"STRSTARTS(\" + operands.to_sparql(delimiter: ', ', **options) + \")\"\n end",
"def to_sparql(**options)\n \"(#{operands.first.to_sparql(**options)} && #{operands.last.to_sparql(**options)})\"\n end",
"def to_sparql(**options)\n \"isLiteral(\" + operands.first.to_sparql(**options) + \")\"\n end",
"def to_sparql(**options)\n prefixes = {}\n str = operands.first.map do |(pfx, sfx)|\n pfx = pfx.to_s.chomp(':').to_sym\n prefixes[pfx] = sfx\n \"PREFIX #{pfx}: #{sfx.to_sparql}\\n\"\n end.join(\"\")\n\n str << operands.last.to_sparql(prefixes: prefixes, **options)\n end",
"def to_sparql(**options)\n \"STRLANG(\" + operands.to_sparql(delimiter: ', ', **options) + \")\"\n end",
"def to_sparql(**options)\n extensions = operands.first.inject({}) do |memo, (as, expression)|\n # Use string/name of variable \"as\" to aid in later matching\n memo.merge(as.to_s => expression)\n end\n\n # Merge any inherited extensions from options\n extensions = options.delete(:extensions).merge(extensions) if options.key?(:extensions)\n operands.last.to_sparql(extensions: extensions, **options)\n end",
"def to_sparql(**options)\n \"TRIPLE(#{operands.to_sparql(delimiter: ', ', **options)})\"\n end",
"def query\n <<-SPARQL\n SELECT DISTINCT ?item WHERE {\n {\n ?item p:P31 ?statement0.\n ?statement0 (ps:P31/(wdt:P279*)) wd:Q7889.\n }\n UNION\n {\n ?item p:P31 ?statement1.\n ?statement1 (ps:P31) wd:Q16070115.\n }\n UNION\n {\n ?item p:P31 ?statement2.\n ?statement2 (ps:P31/(wdt:P279*)) wd:Q865493.\n }\n UNION\n {\n ?item p:P31 ?statement3.\n ?statement3 (ps:P31) wd:Q209163.\n }\n }\n SPARQL\nend",
"def to_sparql(**options)\n \"STRENDS(\" + operands.to_sparql(delimiter: ', ', **options) + \")\"\n end",
"def to_rdf()\n rdf = \"<rdf:Statement>\"\n rdf << write_subject()\n rdf << \" <rdf:predicate rdf:resource=\\\"#{@predicate}\\\"/>\"\n rdf << write_object()\n rdf << \"</rdf:Statement>\"\n return rdf \n end",
"def to_sparql(**options)\n \"sameTerm(#{operands.to_sparql(delimiter: ', ', **options)})\"\n end",
"def root\n a = zero_or_more { or_clause }\n space\n\n if a.empty?\n AST.all\n elsif a.size == 1\n a.first\n else\n AST.new(:and, a)\n end\n end",
"def to_sparql(**options)\n \"STRUUID(\" + operands.to_sparql(delimiter: ', ', **options) + \")\"\n end",
"def to_sparql(**options)\n operands.last.to_sparql(datasets: operands.first, **options)\n end",
"def to_sparql(**options)\n to_sxp(**options)\n end",
"def to_sparql(**options)\n to_sxp(**options)\n end",
"def to_sparql(**options)\n iri, args = operands\n iri.to_sparql(**options) +\n '(' +\n args.to_sparql(delimiter: ', ', **options) +\n ')'\n end",
"def to_sparql(**options)\n str = to_triple.map {|term| term.to_sparql(**options)}.join(\" \")\n quoted? ? ('<<' + str + '>>') : str\n end",
"def to_sparql(**options)\n self.distinguished? ? super : \"_:_nd#{self.name}\"\n end",
"def to_sparql(**options)\n \"isTRIPLE(\" + operands.first.to_sparql(**options) + \")\"\n end",
"def doProduction(lhs)\n if lhs == BNF.void\n progress(\"\\nvoid\")\n return\n end\n if lhs == BNF.eof\n progress( \"\\nEOF\")\n return\n end\n if lhs.is_a?(RDF::Literal)\n literalTerminals[lhs.value()] = 1\n return\n end\n\n branchDict = {}\n\n rhs = graph.first_object(:subject => lhs, :predicate => BNF.matches)\n if rhs\n chatty(\"\\nToken #{lhs} matches regexp #{rhs}\")\n tokenRegexps[lhs] = rhs.value\n\n cc = graph.query(:subject => lhs, :predicate => BNF.canStartWith)\n progress(recordError(\"No record of what token #{lhs} can start with\")) if cc.empty?\n cc.each {|statement| chatty(\" Can start with: #{statement.object}\")}\n return\n end\n \n rhs = graph.first_object(:subject => lhs, :predicate => BNF.mustBeOneSequence)\n unless rhs\n progress(recordError(\"No definition of #{lhs}\"))\n # raise RuntimeError(\"No definition of %s in\\n %s\" %(`lhs`, `g`))\n return\n end\n\n options = rhs\n progress(\"\\nProduction #{lhs} :: #{options}\")\n graph.query(:subject => lhs, :predicate => BNF.canPrecede) do |statement|\n chatty(\" Can precede '#{statement.object}'\")\n end\n\n graph.query(:subject => lhs, :predicate => BNF.branch) do |statement|\n branch = statement.object\n sequence = graph.first_object(:subject => statement.object, :predicate => BNF.sequence)\n option = RDF::List.new(sequence, graph).to_a\n progress(\" option: #{option}\")\n \n option.each do |part|\n agenda << part unless already.include?(part) || agenda.include?(part)\n end\n \n conditions = graph.query(:subject => branch, :predicate => BNF.condition).map(&:object)\n if conditions.empty?\n progress(recordError(\"NO SELECTOR for #{lhs} option #{option}\"))\n if option.empty?\n # Void case - the tricky one\n graph.pattern(:subject => lhs, :predicate => BNF.canPrecede) do |st|\n progress(\" Can precede #{st.object}\")\n end\n end\n end\n \n progress(\" Conditions: #{conditions.to_a.map(&:to_s)}\")\n conditions.each do |str1|\n if branchDict.has_key?(str1)\n progress(\n \"Conflict: #{str1} is also the condition for #{branchDict[str1]}\")\n end\n branchDict[str1] = option\n end\n end\n \n branchDict.keys.each do |str1|\n branchDict.keys.each do |str2|\n s1, s2 = str1.to_s, str2.to_s\n if (s1.index(s2) == 0 || s2.index(s1) == 0) && branchDict[str1] != branchDict[str2]\n progress(\"WARNING: for #{lhs}, #{str1} indicates #{branchDict[str1]}, but #{str2} indicates #{branchDict[str2]}\")\n end\n end\n end\n \n branchTable[lhs] = branchDict\n end",
"def to_sparql(**options)\n \"ASC(#{operands.last.to_sparql(**options)})\"\n end",
"def to_sparql(**options)\n *args, last = operands.dup\n args += [:TO, last]\n \n \"ADD \" + args.to_sparql(**options)\n end",
"def to_sparql(**options)\n \"DELETE {\\n\" +\n operands.first.to_sparql(delimiter: \" .\\n\", **options) +\n \"\\n}\"\n end",
"def query_string\n ast.to_query_string\n end",
"def to_gql\n result = ' ' * __depth + __name\n result += __params_to_s(__params, true) unless __params.empty?\n unless __nodes.empty?\n result += \" {\\n\"\n result += __nodes.map(&:to_gql).join(\"\\n\")\n result += \"\\n#{' ' * __depth}}\"\n end\n\n result\n end",
"def to_s\n PgQuery::Deparse.from ast\n end",
"def to_sparql(**options)\n \"DELETE DATA {\\n\" +\n operands.first.to_sparql(top_level: false, delimiter: \". \\n\", **options) +\n \"\\n}\"\n end",
"def to_rdf\n self\n end",
"def to_sparql(**options)\n \"DESC(#{operands.last.to_sparql(**options)})\"\n end",
"def to_sparql(**options)\n distinct = operands.first == :distinct\n args = distinct ? operands[1..-1] : operands\n \"MIN(#{'DISTINCT ' if distinct}#{args.to_sparql(**options)})\"\n end",
"def grammar_def\n # -> uncomment the next line to manually enable rule tracing\n # trace_in(__method__, 1)\n return_value = GrammarDefReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n root_0 = nil\n g = nil\n __DOC_COMMENT1__ = nil\n string_literal2 = nil\n string_literal3 = nil\n string_literal4 = nil\n char_literal6 = nil\n __EOF12__ = nil\n id5 = nil\n options_spec7 = nil\n tokens_spec8 = nil\n attr_scope9 = nil\n action10 = nil\n rule11 = nil\n\n tree_for_g = nil\n tree_for_DOC_COMMENT1 = nil\n tree_for_string_literal2 = nil\n tree_for_string_literal3 = nil\n tree_for_string_literal4 = nil\n tree_for_char_literal6 = nil\n tree_for_EOF12 = nil\n stream_T__68 = ANTLR3::AST::RewriteRuleTokenStream.new(@adaptor, \"token T__68\")\n stream_DOC_COMMENT = ANTLR3::AST::RewriteRuleTokenStream.new(@adaptor, \"token DOC_COMMENT\")\n stream_T__69 = ANTLR3::AST::RewriteRuleTokenStream.new(@adaptor, \"token T__69\")\n stream_T__67 = ANTLR3::AST::RewriteRuleTokenStream.new(@adaptor, \"token T__67\")\n stream_T__71 = ANTLR3::AST::RewriteRuleTokenStream.new(@adaptor, \"token T__71\")\n stream_T__70 = ANTLR3::AST::RewriteRuleTokenStream.new(@adaptor, \"token T__70\")\n stream_EOF = ANTLR3::AST::RewriteRuleTokenStream.new(@adaptor, \"token EOF\")\n stream_id = ANTLR3::AST::RewriteRuleSubtreeStream.new(@adaptor, \"rule id\")\n stream_tokens_spec = ANTLR3::AST::RewriteRuleSubtreeStream.new(@adaptor, \"rule tokens_spec\")\n stream_rule = ANTLR3::AST::RewriteRuleSubtreeStream.new(@adaptor, \"rule rule\")\n stream_options_spec = ANTLR3::AST::RewriteRuleSubtreeStream.new(@adaptor, \"rule options_spec\")\n stream_action = ANTLR3::AST::RewriteRuleSubtreeStream.new(@adaptor, \"rule action\")\n stream_attr_scope = ANTLR3::AST::RewriteRuleSubtreeStream.new(@adaptor, \"rule attr_scope\")\n begin\n # at line 95:9: ( DOC_COMMENT )? ( 'lexer' | 'parser' | 'tree' | ) g= 'grammar' id ';' ( options_spec )? ( tokens_spec )? ( attr_scope )* ( action )* ( rule )+ EOF\n # at line 95:9: ( DOC_COMMENT )?\n alt_1 = 2\n look_1_0 = @input.peek(1)\n\n if (look_1_0 == DOC_COMMENT) \n alt_1 = 1\n end\n case alt_1\n when 1\n # at line 95:9: DOC_COMMENT\n __DOC_COMMENT1__ = match(DOC_COMMENT, TOKENS_FOLLOWING_DOC_COMMENT_IN_grammar_def_295) \n if @state.backtracking == 0\n stream_DOC_COMMENT.add(__DOC_COMMENT1__)\n end\n\n end\n # at line 96:6: ( 'lexer' | 'parser' | 'tree' | )\n alt_2 = 4\n case look_2 = @input.peek(1)\n when T__67 then alt_2 = 1\n when T__68 then alt_2 = 2\n when T__69 then alt_2 = 3\n when T__70 then alt_2 = 4\n else\n @state.backtracking > 0 and raise(ANTLR3::Error::BacktrackingFailed)\n\n nvae = NoViableAlternative(\"\", 2, 0)\n raise nvae\n end\n case alt_2\n when 1\n # at line 96:8: 'lexer'\n string_literal2 = match(T__67, TOKENS_FOLLOWING_T__67_IN_grammar_def_305) \n if @state.backtracking == 0\n stream_T__67.add(string_literal2)\n end\n # syntactic predicate action gate test\n if @state.backtracking == 0\n # --> action\n @grammar_type = LEXER_GRAMMAR \n # <-- action\n end\n\n when 2\n # at line 97:8: 'parser'\n string_literal3 = match(T__68, TOKENS_FOLLOWING_T__68_IN_grammar_def_321) \n if @state.backtracking == 0\n stream_T__68.add(string_literal3)\n end\n # syntactic predicate action gate test\n if @state.backtracking == 0\n # --> action\n @grammar_type = PARSER_GRAMMAR \n # <-- action\n end\n\n when 3\n # at line 98:8: 'tree'\n string_literal4 = match(T__69, TOKENS_FOLLOWING_T__69_IN_grammar_def_333) \n if @state.backtracking == 0\n stream_T__69.add(string_literal4)\n end\n # syntactic predicate action gate test\n if @state.backtracking == 0\n # --> action\n @grammar_type = TREE_GRAMMAR \n # <-- action\n end\n\n when 4\n # at line 99:16: \n # syntactic predicate action gate test\n if @state.backtracking == 0\n # --> action\n @grammar_type = COMBINED_GRAMMAR \n # <-- action\n end\n\n end\n g = match(T__70, TOKENS_FOLLOWING_T__70_IN_grammar_def_375) \n if @state.backtracking == 0\n stream_T__70.add(g)\n end\n @state.following.push(TOKENS_FOLLOWING_id_IN_grammar_def_377)\n id5 = id\n @state.following.pop\n if @state.backtracking == 0\n stream_id.add(id5.tree)\n end\n char_literal6 = match(T__71, TOKENS_FOLLOWING_T__71_IN_grammar_def_379) \n if @state.backtracking == 0\n stream_T__71.add(char_literal6)\n end\n # at line 101:25: ( options_spec )?\n alt_3 = 2\n look_3_0 = @input.peek(1)\n\n if (look_3_0 == OPTIONS) \n alt_3 = 1\n end\n case alt_3\n when 1\n # at line 101:25: options_spec\n @state.following.push(TOKENS_FOLLOWING_options_spec_IN_grammar_def_381)\n options_spec7 = options_spec\n @state.following.pop\n if @state.backtracking == 0\n stream_options_spec.add(options_spec7.tree)\n end\n\n end\n # at line 101:39: ( tokens_spec )?\n alt_4 = 2\n look_4_0 = @input.peek(1)\n\n if (look_4_0 == TOKENS) \n alt_4 = 1\n end\n case alt_4\n when 1\n # at line 101:39: tokens_spec\n @state.following.push(TOKENS_FOLLOWING_tokens_spec_IN_grammar_def_384)\n tokens_spec8 = tokens_spec\n @state.following.pop\n if @state.backtracking == 0\n stream_tokens_spec.add(tokens_spec8.tree)\n end\n\n end\n # at line 101:52: ( attr_scope )*\n loop do #loop 5\n alt_5 = 2\n look_5_0 = @input.peek(1)\n\n if (look_5_0 == SCOPE) \n alt_5 = 1\n\n end\n case alt_5\n when 1\n # at line 101:52: attr_scope\n @state.following.push(TOKENS_FOLLOWING_attr_scope_IN_grammar_def_387)\n attr_scope9 = attr_scope\n @state.following.pop\n if @state.backtracking == 0\n stream_attr_scope.add(attr_scope9.tree)\n end\n\n else\n break #loop 5\n end\n end\n # at line 101:64: ( action )*\n loop do #loop 6\n alt_6 = 2\n look_6_0 = @input.peek(1)\n\n if (look_6_0 == AT) \n alt_6 = 1\n\n end\n case alt_6\n when 1\n # at line 101:64: action\n @state.following.push(TOKENS_FOLLOWING_action_IN_grammar_def_390)\n action10 = action\n @state.following.pop\n if @state.backtracking == 0\n stream_action.add(action10.tree)\n end\n\n else\n break #loop 6\n end\n end\n # at file 102:6: ( rule )+\n match_count_7 = 0\n loop do\n alt_7 = 2\n look_7_0 = @input.peek(1)\n\n if (look_7_0 == DOC_COMMENT || look_7_0 == FRAGMENT || look_7_0 == TOKEN_REF || look_7_0 == RULE_REF || look_7_0.between?(T__75, T__77)) \n alt_7 = 1\n\n end\n case alt_7\n when 1\n # at line 102:6: rule\n @state.following.push(TOKENS_FOLLOWING_rule_IN_grammar_def_398)\n rule11 = rule\n @state.following.pop\n if @state.backtracking == 0\n stream_rule.add(rule11.tree)\n end\n\n else\n match_count_7 > 0 and break\n @state.backtracking > 0 and raise(ANTLR3::Error::BacktrackingFailed)\n\n eee = EarlyExit(7)\n\n\n raise eee\n end\n match_count_7 += 1\n end\n\n __EOF12__ = match(EOF, TOKENS_FOLLOWING_EOF_IN_grammar_def_406) \n if @state.backtracking == 0\n stream_EOF.add(__EOF12__)\n end\n # AST Rewrite\n # elements: attr_scope, id, tokens_spec, action, options_spec, rule, DOC_COMMENT\n # token labels: \n # rule labels: return_value\n # token list labels: \n # rule list labels: \n # wildcard labels: \n if @state.backtracking == 0\n\n return_value.tree = root_0\n stream_return_value = return_value ? subtree_stream(\"rule return_value\", return_value.tree) : subtree_stream(\"token return_value\")\n\n root_0 = @adaptor.create_flat_list!\n # 104:6: -> ^( id ( DOC_COMMENT )? ( options_spec )? ( tokens_spec )? ( attr_scope )* ( action )* ( rule )+ )\n # at line 104:9: ^( id ( DOC_COMMENT )? ( options_spec )? ( tokens_spec )? ( attr_scope )* ( action )* ( rule )+ )\n root_1 = @adaptor.create_flat_list!\n root_1 = @adaptor.become_root(@adaptor.create!(@grammar_type, g) , root_1)\n\n @adaptor.add_child(root_1, stream_id.next_tree)\n # at line 105:12: ( DOC_COMMENT )?\n if stream_DOC_COMMENT.has_next?\n @adaptor.add_child(root_1, stream_DOC_COMMENT.next_node)\n\n end\n\n stream_DOC_COMMENT.reset();\n # at line 105:25: ( options_spec )?\n if stream_options_spec.has_next?\n @adaptor.add_child(root_1, stream_options_spec.next_tree)\n\n end\n\n stream_options_spec.reset();\n # at line 105:39: ( tokens_spec )?\n if stream_tokens_spec.has_next?\n @adaptor.add_child(root_1, stream_tokens_spec.next_tree)\n\n end\n\n stream_tokens_spec.reset();\n # at line 105:52: ( attr_scope )*\n while stream_attr_scope.has_next?\n @adaptor.add_child(root_1, stream_attr_scope.next_tree)\n\n end\n\n stream_attr_scope.reset();\n # at line 105:64: ( action )*\n while stream_action.has_next?\n @adaptor.add_child(root_1, stream_action.next_tree)\n\n end\n\n stream_action.reset();\n # at line 105:72: ( rule )+\n unless stream_rule.has_next?\n raise ANTLR3::RewriteEarlyExit\n end\n\n while stream_rule.has_next?\n @adaptor.add_child(root_1, stream_rule.next_tree)\n\n end\n\n stream_rule.reset\n\n @adaptor.add_child(root_0, root_1)\n\n\n\n return_value.tree = root_0\n\n end# - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look(-1)\n\n if @state.backtracking == 0\n\n return_value.tree = @adaptor.rule_post_processing(root_0)\n @adaptor.set_token_boundaries(return_value.tree, return_value.start, return_value.stop)\n\n end\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n return_value.tree = @adaptor.create_error_node!(@input, return_value.start, @input.look(-1), re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out(__method__, 1)\n\n end\n \n return return_value\n end",
"def grammar_def\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 1 )\n return_value = GrammarDefReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n root_0 = nil\n g = nil\n __DOC_COMMENT1__ = nil\n string_literal2 = nil\n string_literal3 = nil\n string_literal4 = nil\n char_literal6 = nil\n __EOF12__ = nil\n id5 = nil\n options_spec7 = nil\n tokens_spec8 = nil\n attr_scope9 = nil\n action10 = nil\n rule11 = nil\n\n tree_for_g = nil\n tree_for_DOC_COMMENT1 = nil\n tree_for_string_literal2 = nil\n tree_for_string_literal3 = nil\n tree_for_string_literal4 = nil\n tree_for_char_literal6 = nil\n tree_for_EOF12 = nil\n stream_T__68 = ANTLR3::AST::RewriteRuleTokenStream.new( @adaptor, \"token T__68\" )\n stream_DOC_COMMENT = ANTLR3::AST::RewriteRuleTokenStream.new( @adaptor, \"token DOC_COMMENT\" )\n stream_T__69 = ANTLR3::AST::RewriteRuleTokenStream.new( @adaptor, \"token T__69\" )\n stream_T__67 = ANTLR3::AST::RewriteRuleTokenStream.new( @adaptor, \"token T__67\" )\n stream_T__71 = ANTLR3::AST::RewriteRuleTokenStream.new( @adaptor, \"token T__71\" )\n stream_T__70 = ANTLR3::AST::RewriteRuleTokenStream.new( @adaptor, \"token T__70\" )\n stream_EOF = ANTLR3::AST::RewriteRuleTokenStream.new( @adaptor, \"token EOF\" )\n stream_id = ANTLR3::AST::RewriteRuleSubtreeStream.new( @adaptor, \"rule id\" )\n stream_tokens_spec = ANTLR3::AST::RewriteRuleSubtreeStream.new( @adaptor, \"rule tokens_spec\" )\n stream_rule = ANTLR3::AST::RewriteRuleSubtreeStream.new( @adaptor, \"rule rule\" )\n stream_options_spec = ANTLR3::AST::RewriteRuleSubtreeStream.new( @adaptor, \"rule options_spec\" )\n stream_action = ANTLR3::AST::RewriteRuleSubtreeStream.new( @adaptor, \"rule action\" )\n stream_attr_scope = ANTLR3::AST::RewriteRuleSubtreeStream.new( @adaptor, \"rule attr_scope\" )\n begin\n # at line 86:9: ( DOC_COMMENT )? ( 'lexer' | 'parser' | 'tree' | ) g= 'grammar' id ';' ( options_spec )? ( tokens_spec )? ( attr_scope )* ( action )* ( rule )+ EOF\n # at line 86:9: ( DOC_COMMENT )?\n alt_1 = 2\n look_1_0 = @input.peek( 1 )\n\n if ( look_1_0 == DOC_COMMENT )\n alt_1 = 1\n end\n case alt_1\n when 1\n # at line 86:9: DOC_COMMENT\n __DOC_COMMENT1__ = match( DOC_COMMENT, TOKENS_FOLLOWING_DOC_COMMENT_IN_grammar_def_290 )\n if @state.backtracking == 0\n stream_DOC_COMMENT.add( __DOC_COMMENT1__ )\n end\n\n end\n # at line 87:6: ( 'lexer' | 'parser' | 'tree' | )\n alt_2 = 4\n case look_2 = @input.peek( 1 )\n when T__67 then alt_2 = 1\n when T__68 then alt_2 = 2\n when T__69 then alt_2 = 3\n when T__70 then alt_2 = 4\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n raise NoViableAlternative( \"\", 2, 0 )\n end\n case alt_2\n when 1\n # at line 87:8: 'lexer'\n string_literal2 = match( T__67, TOKENS_FOLLOWING_T__67_IN_grammar_def_300 )\n if @state.backtracking == 0\n stream_T__67.add( string_literal2 )\n end\n # syntactic predicate action gate test\n if @state.backtracking == 0\n # --> action\n @grammar_type = LEXER_GRAMMAR \n # <-- action\n end\n\n when 2\n # at line 88:8: 'parser'\n string_literal3 = match( T__68, TOKENS_FOLLOWING_T__68_IN_grammar_def_316 )\n if @state.backtracking == 0\n stream_T__68.add( string_literal3 )\n end\n # syntactic predicate action gate test\n if @state.backtracking == 0\n # --> action\n @grammar_type = PARSER_GRAMMAR \n # <-- action\n end\n\n when 3\n # at line 89:8: 'tree'\n string_literal4 = match( T__69, TOKENS_FOLLOWING_T__69_IN_grammar_def_328 )\n if @state.backtracking == 0\n stream_T__69.add( string_literal4 )\n end\n # syntactic predicate action gate test\n if @state.backtracking == 0\n # --> action\n @grammar_type = TREE_GRAMMAR \n # <-- action\n end\n\n when 4\n # at line 90:16: \n # syntactic predicate action gate test\n if @state.backtracking == 0\n # --> action\n @grammar_type = COMBINED_GRAMMAR \n # <-- action\n end\n\n end\n g = match( T__70, TOKENS_FOLLOWING_T__70_IN_grammar_def_370 )\n if @state.backtracking == 0\n stream_T__70.add( g )\n end\n @state.following.push( TOKENS_FOLLOWING_id_IN_grammar_def_372 )\n id5 = id\n @state.following.pop\n if @state.backtracking == 0\n stream_id.add( id5.tree )\n end\n char_literal6 = match( T__71, TOKENS_FOLLOWING_T__71_IN_grammar_def_374 )\n if @state.backtracking == 0\n stream_T__71.add( char_literal6 )\n end\n # at line 92:25: ( options_spec )?\n alt_3 = 2\n look_3_0 = @input.peek( 1 )\n\n if ( look_3_0 == OPTIONS )\n alt_3 = 1\n end\n case alt_3\n when 1\n # at line 92:25: options_spec\n @state.following.push( TOKENS_FOLLOWING_options_spec_IN_grammar_def_376 )\n options_spec7 = options_spec\n @state.following.pop\n if @state.backtracking == 0\n stream_options_spec.add( options_spec7.tree )\n end\n\n end\n # at line 92:39: ( tokens_spec )?\n alt_4 = 2\n look_4_0 = @input.peek( 1 )\n\n if ( look_4_0 == TOKENS )\n alt_4 = 1\n end\n case alt_4\n when 1\n # at line 92:39: tokens_spec\n @state.following.push( TOKENS_FOLLOWING_tokens_spec_IN_grammar_def_379 )\n tokens_spec8 = tokens_spec\n @state.following.pop\n if @state.backtracking == 0\n stream_tokens_spec.add( tokens_spec8.tree )\n end\n\n end\n # at line 92:52: ( attr_scope )*\n while true # decision 5\n alt_5 = 2\n look_5_0 = @input.peek( 1 )\n\n if ( look_5_0 == SCOPE )\n alt_5 = 1\n\n end\n case alt_5\n when 1\n # at line 92:52: attr_scope\n @state.following.push( TOKENS_FOLLOWING_attr_scope_IN_grammar_def_382 )\n attr_scope9 = attr_scope\n @state.following.pop\n if @state.backtracking == 0\n stream_attr_scope.add( attr_scope9.tree )\n end\n\n else\n break # out of loop for decision 5\n end\n end # loop for decision 5\n # at line 92:64: ( action )*\n while true # decision 6\n alt_6 = 2\n look_6_0 = @input.peek( 1 )\n\n if ( look_6_0 == AT )\n alt_6 = 1\n\n end\n case alt_6\n when 1\n # at line 92:64: action\n @state.following.push( TOKENS_FOLLOWING_action_IN_grammar_def_385 )\n action10 = action\n @state.following.pop\n if @state.backtracking == 0\n stream_action.add( action10.tree )\n end\n\n else\n break # out of loop for decision 6\n end\n end # loop for decision 6\n # at file 93:6: ( rule )+\n match_count_7 = 0\n while true\n alt_7 = 2\n look_7_0 = @input.peek( 1 )\n\n if ( look_7_0 == DOC_COMMENT || look_7_0 == FRAGMENT || look_7_0 == TOKEN_REF || look_7_0 == RULE_REF || look_7_0.between?( T__75, T__77 ) )\n alt_7 = 1\n\n end\n case alt_7\n when 1\n # at line 93:6: rule\n @state.following.push( TOKENS_FOLLOWING_rule_IN_grammar_def_393 )\n rule11 = rule\n @state.following.pop\n if @state.backtracking == 0\n stream_rule.add( rule11.tree )\n end\n\n else\n match_count_7 > 0 and break\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n eee = EarlyExit(7)\n\n\n raise eee\n end\n match_count_7 += 1\n end\n\n __EOF12__ = match( EOF, TOKENS_FOLLOWING_EOF_IN_grammar_def_401 )\n if @state.backtracking == 0\n stream_EOF.add( __EOF12__ )\n end\n # AST Rewrite\n # elements: id, rule, options_spec, DOC_COMMENT, action, attr_scope, tokens_spec\n # token labels: \n # rule labels: return_value\n # token list labels: \n # rule list labels: \n # wildcard labels: \n if @state.backtracking == 0\n\n return_value.tree = root_0\n stream_return_value = return_value ? subtree_stream( \"rule return_value\", return_value.tree ) : subtree_stream( \"token return_value\" )\n\n root_0 = @adaptor.create_flat_list\n # 95:6: -> ^( id ( DOC_COMMENT )? ( options_spec )? ( tokens_spec )? ( attr_scope )* ( action )* ( rule )+ )\n # at line 95:9: ^( id ( DOC_COMMENT )? ( options_spec )? ( tokens_spec )? ( attr_scope )* ( action )* ( rule )+ )\n root_1 = @adaptor.create_flat_list\n root_1 = @adaptor.become_root( ( @adaptor.create(@grammar_type, g) ), root_1 )\n\n @adaptor.add_child( root_1, stream_id.next_tree )\n # at line 96:12: ( DOC_COMMENT )?\n if stream_DOC_COMMENT.has_next?\n @adaptor.add_child( root_1, stream_DOC_COMMENT.next_node )\n\n end\n\n stream_DOC_COMMENT.reset();\n # at line 96:25: ( options_spec )?\n if stream_options_spec.has_next?\n @adaptor.add_child( root_1, stream_options_spec.next_tree )\n\n end\n\n stream_options_spec.reset();\n # at line 96:39: ( tokens_spec )?\n if stream_tokens_spec.has_next?\n @adaptor.add_child( root_1, stream_tokens_spec.next_tree )\n\n end\n\n stream_tokens_spec.reset();\n # at line 96:52: ( attr_scope )*\n while stream_attr_scope.has_next?\n @adaptor.add_child( root_1, stream_attr_scope.next_tree )\n\n end\n\n stream_attr_scope.reset();\n # at line 96:64: ( action )*\n while stream_action.has_next?\n @adaptor.add_child( root_1, stream_action.next_tree )\n\n end\n\n stream_action.reset();\n # at line 96:72: ( rule )+\n stream_rule.has_next? or raise ANTLR3::RewriteEarlyExit\n\n while stream_rule.has_next?\n @adaptor.add_child( root_1, stream_rule.next_tree )\n\n end\n stream_rule.reset\n\n @adaptor.add_child( root_0, root_1 )\n\n\n\n return_value.tree = root_0\n\n end# - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n if @state.backtracking == 0\n\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n @adaptor.set_token_boundaries( return_value.tree, return_value.start, return_value.stop )\n\n end\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n return_value.tree = @adaptor.create_error_node( @input, return_value.start, @input.look(-1), re )\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 1 )\n\n end\n \n return return_value\n end",
"def to_sql\n @sql ||= case @kind\n when :target, :comp_op, :bin_bool_op, :term\n child(0).to_sql\n when :target_set\n # array of fragments, one per target\n [child(0).to_sql] + (child(1) ? child(2).to_sql : [])\n when :qual_term\n # child(2) will be an array (target_set)\n \"(\" + child(2).to_sql.collect{|sql| comparison(child(0), child(1).child(0), sql)}.join(\" OR \") + \")\"\n when :unqual_term\n \"(\" + default_quals.collect{|q| comparison(q, EQUAL_TOKEN, child(0).to_sql)}.join(\" OR \") + \")\"\n when :query\n # first form\n if child(0).is?(:lparen)\n @children.collect{|c| c.to_sql}.join\n # second form\n elsif child(1) && child(1).is?(:bin_bool_op)\n @children.collect{|c| c.to_sql}.join(\" \")\n # third form\n elsif child(1) && child(1).is?(:query)\n child(0).to_sql + \" AND \" + child(1).to_sql\n # fourth form\n else\n child(0).to_sql\n end\n end\n end",
"def sparql_query\n return <<-SPARQL\n SELECT ?item ?itemLabel ?steamAppId WHERE {\n ?item wdt:P31 wd:Q7889; # instance of video game\n wdt:P1733 ?steamAppId. # items with a Steam App ID.\n FILTER NOT EXISTS { ?item wdt:P5794 ?igdbId. } # with no IGDB ID\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"en,en\". }\n }\n SPARQL\nend",
"def to_sparql(**options)\n \"UCASE(\" + operands.last.to_sparql(**options) + \")\"\n end",
"def ast\n disjunction\n end",
"def initialize(grammar)\n tokens = grammar.split(/[ \\t]+/)\n has_comments = tokens.index('#')\n if has_comments\n # remove all elements after comments position\n tokens = tokens.each_with_index.each_with_object([]) do |(value, index), result|\n result << value if index < has_comments\n result\n end\n end\n # we should have a well formed grammar\n self.tree = GrammarTree.new(tokens)\n end",
"def grammar\n @grammar ||= %w[\n ^(help)(\\s+setup|\\s+start|\\s+stop|\\s+abort|\\s+terminate|\\s+results|\\s+purge|\\s+show|\\s+status)?$\n ^(setup)(\\s+force|\\s+help)?$\n ^(start)(\\s+redeploy|\\s+help)?$\n ^(stop)(\\s+suspend|\\s+wait|\\s+suspend\\s+wait|\\s+wait\\s+suspend|\\s+help)?$\n ^(abort)(\\s+suspend|\\s+help)?$\n ^(results)(\\s+show|\\s+exclude|\\s+include|\\s+report|\\s+export|\\s+import|\\s+help)?(\\s+[\\d\\-:]+|\\s+last)?(.*)$\n ^(purge)(\\s+tests|\\s+clusters|\\s+all|\\s+help)?$\n ^(show)(\\s+jmeter|\\s+cluster|\\s+monitor|\\s+help|\\s+active)?(|\\s+all)?$\n ^(terminate)(\\s+help)?$\n ^(status)(\\s+help)?$\n ].collect { |p| Regexp.compile(p) }\n end",
"def scope\n scope!(operator) if @scopes.empty?\n scope!(\"AND\") if @scopes.last.is_a?(NestedScope)\n @scopes.last\n end",
"def to_sparql(**options)\n \"CEIL(#{operands.to_sparql(**options)})\"\n end",
"def query\n case query_type_str\n when 'empty'\n return\n when 'iso'\n return iso_query_builder\n when 'multi'\n return multi_query_builder\n end\n end",
"def to_sparql(**options)\n \"COALESCE(#{operands.to_sparql(delimiter: ', ', **options)})\"\n end",
"def complete_operator(node)\n definition.operator_by_field_name(node.value).map { |o| o.end_with?(' ') ? o : \"#{o} \" }\n end",
"def build_query\n GraphQL.parse(BASE_QUERY).tap do |d_ast|\n selections = d_ast.definitions.first.selections.first.selections\n\n node_types.each do |type|\n selections << inline_fragment_ast(type) if include?(type)\n end\n\n selections.compact!\n end\n end",
"def parse_prefix_comparison\n return ScopedSearch::QueryLanguage::AST::OperatorNode.new(next_token, [parse_value])\n end",
"def to_sparql(**options)\n ops = operands.last.to_s.empty? ? operands[0..-2] : operands\n \"REPLACE(\" + ops.to_sparql(delimiter: ', ', **options) + \")\"\n end",
"def deep_copy\n copy = Grammar.new( nil, @start_symbol )\n each_pair {|symb, alt| copy[symb] = alt.deep_copy }\n copy \n end",
"def query\n <<-SPARQL\n SELECT DISTINCT ?item ?vglistId WHERE {\n ?item wdt:P8351 ?vglistId.\n }\n SPARQL\nend",
"def next_condition_as_sql\n case @next_condition\n when CONDITION::NONE\n return \"\"\n when CONDITION::AND\n return \"AND\"\n when CONDITION::OR\n return \"OR\"\n end\n end",
"def games_query\n sparql = <<-SPARQL\n SELECT ?item WHERE {\n ?item wdt:P31 wd:Q7889; # Instances of video games.\n rdfs:label ?label filter(lang(?label) = \"en\"). # with a label\n }\n SPARQL\n\n return sparql\n end",
"def raw_query\n <<~GQL\n mutation dispatchWorkflow($input: DispatchWorkflowInput!) {\n dispatchWorkflow(input: $input) {\n workflow {\n id\n }\n }\n }\n GQL\n end",
"def query\n return <<-SPARQL\n SELECT ?item ?itemLabel ?igdbId ?numericId WHERE {\n OPTIONAL {\n ?item p:#{IGDB_GAME_PID} ?statement. # Get the statement of the IGDB ID\n ?statement ps:#{IGDB_GAME_PID} ?igdbId. # Get the actual ID\n FILTER(NOT EXISTS { ?statement pq:#{IGDB_NUMERIC_GAME_PID} ?numericId. }) # Get rid of anything with a numeric IGDB ID qualifier.\n }\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"en,en\". }\n }\n SPARQL\nend",
"def to_sparql(**options)\n distinct = operands.first == :distinct\n args = distinct ? operands[1..-1] : operands\n \"SAMPLE(#{'DISTINCT ' if distinct}#{args.to_sparql(**options)})\"\n end",
"def to_PLParser(startSym)\n\n thePLP = TextRect.new\n\n @ntIndex.each do |nt, s|\n\n theNT = TextRect.new(\"#{nt.name} ::= \")\n before = ' '\n\n s[:rules].each do |i|\n rhs = @ruleTable[i][:rule].rhs\n rhs.each { |sym| before << sym.name << ' ' }\n theNT.below!(before)\n before = ' | '\n end\n\n theNT.below!(' ;')\n thePLP.below!(theNT)\n\n end\n\n thePLP.below!('&G')\n\n end",
"def query\n @query ||= Waves::Request::Query.new( \n Waves::Request::Utilities.destructure( request.query ) )\n end",
"def to_sparql(**options)\n distinct = operands.first == :distinct\n args = distinct ? operands[1..-1] : operands\n \"SUM(#{'DISTINCT ' if distinct}#{args.to_sparql(**options)})\"\n end",
"def to_peg\n new_rules = []\n\n # Look for rules containing sub-sequences\n if expr.any? {|e| e.is_a?(Array) && e.first.is_a?(Symbol)}\n # duplicate ourselves for rewriting\n this = dup\n new_rules << this\n\n expr.each_with_index do |e, index|\n next unless e.is_a?(Array) && e.first.is_a?(Symbol)\n new_rule = build(e)\n this.expr[index] = new_rule.sym\n new_rules << new_rule\n end\n\n # Return new rules after recursively applying #to_bnf\n new_rules = new_rules.map {|r| r.to_peg}.flatten\n elsif expr.first == :diff && !terminal?\n this = dup\n new_rule = build([:not, expr[2]])\n this.expr = [:seq, new_rule.sym, expr[1]]\n new_rules << this\n new_rules << new_rule\n elsif [:hex, :istr, :range].include?(expr.first)\n # This rules are fine, they just need to be terminals\n raise \"Encountered #{expr.first.inspect}, which is a #{self.kind}, not :terminal\" unless self.terminal?\n new_rules << self\n else\n new_rules << self\n end\n \n return new_rules.map {|r| r.extend(EBNF::PEG::Rule)}\n end",
"def query_mode\n node_text(node_tagged(:querymode, :exclude => :subquery))\n end",
"def query_mode\n node_text(node_tagged(:querymode, :exclude => :subquery))\n end",
"def generate_grammar(grammar)\n plist.dict do\n if options.rules_to_generate.present?\n append_array('patterns', extract_patterns(grammar.repository))\n append_dictionary('repository', grammar.repository)\n else\n append_single('comment', grammar.comment)\n append_array('fileTypes', grammar.file_types)\n append_single('firstLineMatch', grammar.first_line_match)\n append_single('keyEquivalent', grammar.key_equivalent)\n append_single('name', grammar.name)\n append_array('patterns', grammar.patterns)\n append_dictionary('repository', grammar.repository)\n append_single('foldingStartMarker', grammar.folding_start_marker)\n append_single('foldingStopMarker', grammar.folding_stop_marker)\n end\n\n append_single('scopeName', grammar.scope_name)\n append_single('uuid', grammar.uuid)\n end\n end",
"def __name__() @__grammar__.name end",
"def expand(grammar, non_term=\"<start>\")\n sentence = \"\"\n\n if non_term.kind_of? Array\n for item in non_term\n sentence += expand(grammar, item)\n end\n return sentence\n end\n\n non_term = non_term.downcase\n if not is_non_terminal? non_term\n if non_term == \".\" or non_term == \"?\" or non_term == \"!\" or non_term == \",\" or non_term == \":\" or non_term == \"-\"\n return non_term\n end\n return \" \" + non_term\n\n elsif non_term == \"<start>\"\n list = grammar[non_term]\n for item in list\n for item2 in item\n sentence += expand(grammar, item2)\n end\n end\n return sentence\n\n else\n list = grammar[non_term]\n\n # Handles nonterminals that aren't defined\n if list==nil\n raise(Exception,\"Non-terminal #{non_term} is not defined\")\n end\n\n len = list.length\n rand_item_index = rand(len)\n return expand(grammar,list[rand_item_index])\n end\n end",
"def raw_query\n <<~GQL\n query ($workflowName: String, $customId: ID, $environmentName: String, $programmingLanguage: String) {\n findWorkflow(environmentName: $environmentName, programmingLanguage: $programmingLanguage, customId: $customId, name: $workflowName) {\n name\n properties\n }\n }\n GQL\n end",
"def as_query(opts={})\n Tripod.logger.debug(\"TRIPOD: building select query for criteria...\")\n\n return_graph = opts.has_key?(:return_graph) ? opts[:return_graph] : true\n\n Tripod.logger.debug(\"TRIPOD: with return_graph: #{return_graph.inspect}\")\n\n select_query = \"SELECT DISTINCT ?uri \"\n\n if graph_lambdas.empty?\n\n if return_graph\n # if we are returning the graph, select it as a variable, and include either the <graph> or ?graph in the where clause\n if graph_uri\n select_query += \"(<#{graph_uri}> as ?graph) WHERE { GRAPH <#{graph_uri}> { \"\n else\n select_query += \"?graph WHERE { GRAPH ?graph { \"\n end\n else\n select_query += \"WHERE { \"\n # if we're not returning the graph, only restrict by the <graph> if there's one set at class level\n select_query += \"GRAPH <#{graph_uri}> { \" if graph_uri\n end\n\n select_query += self.query_where_clauses.join(\" . \")\n select_query += \" } \"\n select_query += \"} \" if return_graph || graph_uri # close the graph clause\n\n else\n # whip through the graph lambdas and add into the query\n # we have multiple graphs so the above does not apply\n select_query += \"WHERE { \"\n\n graph_lambdas.each do |lambda_item|\n select_query += \"GRAPH ?g { \"\n select_query += lambda_item.call\n select_query += \" } \"\n end\n\n select_query += self.query_where_clauses.join(\" . \")\n select_query += \" } \"\n end\n\n select_query += self.extra_clauses.join(\" \")\n\n select_query += [order_clause, limit_clause, offset_clause].join(\" \")\n\n select_query.strip\n end",
"def generate_syntax_tree\n build_ast(@parse_tree).first\n end",
"def query_def; mrna.definition; end",
"def query\n unless @query\n parse_query()\n end\n @query\n end",
"def to_sql(builder, definition, &block)\n if operator == :not && children.length == 1\n builder.to_not_sql(rhs, definition, &block)\n elsif [:null, :notnull].include?(operator)\n to_null_sql(builder, definition, &block)\n elsif children.length == 1\n to_default_fields_sql(builder, definition, &block)\n elsif children.length == 2\n to_single_field_sql(builder, definition, &block)\n else\n raise ScopedSearch::QueryNotSupported, \"Don't know how to handle this operator node: #{operator.inspect} with #{children.inspect}!\"\n end\n end",
"def to_s\n rule.embed + operator\n end",
"def primary\n return Ringo::Literal.new(false) if match?(:false)\n return Ringo::Literal.new(true) if match?(:true)\n return Ringo::Literal.new(nil) if match?(:nil)\n return Ringo::Literal.new(previous.literal) if match?(:number, :string)\n return Ringo::This.new(previous) if match?(:this)\n return Ringo::Variable.new(previous) if match?(:identifier)\n\n if match?(:super)\n keyword = previous\n consume(:dot, \"Expect '.' after 'super'.\")\n method = consume(:identifier, \"Expect superclass method name.\")\n return Ringo::Super.new(keyword, method)\n end\n\n if match?(:lparen)\n expr = expression\n consume(:rparen, 'Expect ) after expression.')\n return Ringo::Grouping.new(expr)\n end\n\n raise error(peek(), 'Expecting expression.')\n end",
"def pp(indent = \"\")\n newindent = indent + \" \"\n \"#{indent}(#{@operator}\\n#{@node.pp(newindent)})\"\n end",
"def parse_unary\n if consume(:bang)\n Node.new(:unary, op: :not, lhs: parse_unary)\n elsif consume(:plus)\n Node.new(:unary, op: :plus, lhs: parse_term)\n elsif consume(:minus)\n Node.new(:unary, op: :minus, lhs: parse_term)\n else\n parse_term\n end\n end",
"def build_parsing_tree\n buffer = [] #[[op, rExpr, lExpr], ...]\n @postfix_buffer.each{|s| buffer << (s.class == Array ? s : [s, buffer.pop, buffer.pop]) }\n return buffer.first\n end",
"def sparql_up\n begin\n direct_query \"ASK { ?s ?p ?o }\"\n rescue\n false\n end\nend",
"def symbol()\n node = factor()\n\n if @look.kind.eql?(Token::STAR) then\n match(Token::STAR)\n node = Star.new(node)\n elsif @look.kind.eql?(Token::QUESTION) then\n match(Token::QUESTION)\n node = Question.new(node)\n end\n\n return node\n end",
"def subexpression()\n node = nil\n\n if current(:operator_less_than) || current(:operator_less_than_equal) ||\n current(:operator_greater_than) || current(:operator_greater_than_equal)\n\n node = operator()\n node.child = browser()\n elsif current(:boolean_true) || current(:boolean_false)\n node = boolean()\n else\n #No comparison operator is assuming equals\n node = Nodes::Equal.new()\n node.child = browser()\n end\n\n node\n end",
"def to_rdf\n rdf = \"<rdf:RDF xmlns:frm=\\\"#{Pho::Namespaces::FRAME}\\\" \"\n rdf << \" xmlns:rdf=\\\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\\\" \"\n rdf << \" xmlns:rdfs=\\\"http://www.w3.org/2000/01/rdf-schema#\\\" \"\n rdf << \" xmlns:bf=\\\"#{Pho::Namespaces::CONFIG}\\\" > \" \n \n rdf << \" <rdf:Description rdf:about=\\\"#{@uri}\\\"> \"\n \n rdf << \" <rdf:type rdf:resource=\\\"#{Pho::Namespaces::CONFIG}QueryProfile\\\"/> \"\n rdf << \" <rdfs:label>#{@label}</rdfs:label> \"\n \n @field_weights.each do |property|\n rdf << \" <bf:fieldWeight rdf:resource=\\\"#{property.uri}\\\"/> \"\n end\n \n rdf << \" </rdf:Description>\"\n \n @field_weights.each do |property|\n rdf << property.to_rdf(false)\n end\n \n rdf << \"</rdf:RDF>\"\n end",
"def to_sparql(**options)\n \"MD5(\" + operands.to_sparql(**options) + \")\"\n end",
"def whereise query_str\n <<-SPARQL.strip_heredoc\n WHERE {\n #{query_str}\n }\n SPARQL\n end",
"def query\n sparql = <<-SPARQL\n SELECT ?item ?itemLabel ?steamAppId {\n ?item wdt:P31 wd:Q7889; # instance of video game\n wdt:P1733 ?steamAppId. # items with a Steam App ID.\n FILTER NOT EXISTS { ?item wdt:P404 ?gameMode . } # with no game mode\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"en\". }\n }\n SPARQL\n\n sparql\nend",
"def query\n q = @root.clone\n\n # Navigation paths come first in the query\n q << \"/#{@navigation_paths.join(\"/\")}\" unless @navigation_paths.empty?\n\n # Handle links queries, this isn't just a standard query option\n q << \"/$links/#{@links_navigation_property}\" if @links_navigation_property\n\n # Handle count queries, this isn't just a standard query option\n q << \"/$count\" if @count\n query_options = generate_query_options\n\n q << \"?#{query_options.join('&')}\" if !query_options.empty?\n q\n end",
"def initialize(paren_start, element = nil, paren_end = nil)\n @options = @@parse_options\n @paren_type = paren_start[0]\n @offset = paren_start[1]\n if paren_end\n @length = (paren_end[1] - paren_start[1]) + paren_end[2]\n else\n @length = paren_start[2]\n end\n \n # delete head '(', '?', and tail \")\"\n @prefix = @paren_type.sub(/^\\(\\??/, \"\")\n if @prefix.index(\"(\") != 0\n @prefix.sub!(/\\)$/, \"\")\n end\n \n @name = get_name(@prefix)\n @condition = nil # set at generating json\n @refer_name = nil\n if element\n TstLog(\"Parenthesis: name:#{@name}, offset:#{@offset}, element:#{element}\")\n @element = element\n @type_name = \"LEX_PAREN\"\n else\n TstLog(\"Parenthesis: name:#{@name}, offset:#{@offset}, element: \\\"\\\"\")\n @element = TEmpty.new\n @type_name = \"LEX_OPTION_PAREN\" # (?x-i) etc.\n end\n @generated_string = []\n @nest = 0\n end",
"def sql\n @parser.sql\n end",
"def sql\n @parser.sql\n end",
"def grammar_hash\n @grammar_hash ||= ::RelatonIec.grammar_hash\n end",
"def to_sparql(**options)\n \"TZ(\" + operands.to_sparql(**options) + \")\"\n end",
"def query\n return <<-SPARQL\n SELECT ?item ?itemLabel ?igdbId WHERE {\n ?item wdt:P31 wd:Q7889; # instance of video game\n wdt:#{IGDB_GAME_PID} ?igdbId. # items with an IGDB ID.\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"en,en\". }\n }\n SPARQL\nend",
"def ruby_bnf_grammar_parser\r\n parser = nil\r\n time_and_puts(\"Generating parser for Ruby BNF grammar\") do\r\n begin\r\n parser = Parse.generate_parser <<-'EOG'\r\nGrammar BnfGrammars\r\n Tokens\r\n Blank = /\\s+/ [:Skip]\r\n EpsilonComment = /\\/\\* none \\*\\//\r\n Nonterm = /[a-z][a-z_\\d]*/ \r\n Keyword = /k\\w+/\r\n Token = /t[A-Z_\\d]+/\r\n String = /'[^']*'/\r\n Productions\r\n BnfGrammar -> Prod+ [: productions]\r\n Prod -> Nonterm ':' list(Alt, '|') [: nonterm,_,alts]\r\n Alt -> Element* [: elements]\r\n Element -> (Nonterm | Keyword | Token | \r\n String | EpsilonComment) [^]\r\nEOG\r\n rescue Exception => e\r\n puts e.inspect\r\n exit -1\r\n end\r\n end\r\n parser\r\nend",
"def add_sample_grammar(anEngine)\n anEngine.build_grammar do\n add_terminals('a', 'b', 'c')\n add_production('S' => 'A')\n add_production('A' => 'a A c')\n add_production('A' => 'b')\n end\n end",
"def sql_string\n StringExpression.new(:NOOP, self)\n end",
"def sql_string\n StringExpression.new(:NOOP, self)\n end",
"def to_sexp\n case self\n in [:all]\n \"all\"\n in [:none]\n \"none\"\n in [:tag, name]\n name\n in [:metatag, name, value, quoted]\n \"#{name}:#{quoted_value}\"\n in [:wildcard, name]\n \"(wildcard #{name})\"\n in [type, *args]\n \"(#{type} #{args.map(&:to_sexp).join(\" \")})\"\n end\n end"
] |
[
"0.64040565",
"0.6321709",
"0.631144",
"0.6310281",
"0.62468004",
"0.6241794",
"0.6177385",
"0.5945824",
"0.5944844",
"0.59406114",
"0.5841583",
"0.57748723",
"0.5691575",
"0.5639666",
"0.55992645",
"0.5555632",
"0.5552082",
"0.55493504",
"0.5544813",
"0.5524246",
"0.55005145",
"0.5481131",
"0.54789907",
"0.54789907",
"0.5473085",
"0.54257494",
"0.5388528",
"0.53794044",
"0.53158885",
"0.52918106",
"0.5263909",
"0.52611953",
"0.5259746",
"0.52508134",
"0.5236677",
"0.52288866",
"0.519887",
"0.5187193",
"0.5180824",
"0.5178272",
"0.51750934",
"0.5140401",
"0.51316804",
"0.506324",
"0.50449157",
"0.5025831",
"0.50245297",
"0.5002202",
"0.49919412",
"0.49794847",
"0.4958179",
"0.49518096",
"0.4938425",
"0.48990288",
"0.48967928",
"0.48894727",
"0.48835984",
"0.48616114",
"0.4841433",
"0.48280168",
"0.48069483",
"0.48019588",
"0.47909644",
"0.47791564",
"0.47728485",
"0.47718078",
"0.47567016",
"0.47567016",
"0.47534162",
"0.47530836",
"0.4749654",
"0.47488376",
"0.4742664",
"0.4741476",
"0.47364327",
"0.4731737",
"0.47195974",
"0.47140446",
"0.47137988",
"0.469863",
"0.46902764",
"0.46721774",
"0.46669018",
"0.4664335",
"0.46599182",
"0.46445006",
"0.46432602",
"0.46365315",
"0.4629454",
"0.46156162",
"0.46144578",
"0.4613249",
"0.4613249",
"0.46077293",
"0.45974138",
"0.45961535",
"0.45858765",
"0.45752266",
"0.45719203",
"0.45719203",
"0.4566118"
] |
0.0
|
-1
|
Add data on spreadsheet
|
def data_to_excel(data_hash, worksheet_hash, row_max)
ws = init_spreadsheet(worksheet_hash)
(row_max..data_hash[data_hash.keys[0]].length + row_max).each_with_index do |col, index|
worksheet_hash['titles'].length.times do |i|
ws[col, i + 1] = data_hash[data_hash.keys[i]][index]
end
end
save_excel(ws)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def add_new_record(h, ws)\n row_array = []\n @excel_row.each do |a|\n row_array.push(h[a])\n end\n ws.add_row row_array\nend",
"def add_as_sheet(book:)\n\n sheet = book.create_worksheet\n\n sheet.name = \"#{name} #{date.strftime('%F')}\"\n row = sheet.row(1)\n row.push \"Event: \"\n row.push name + \" \" + date.strftime('%F')\n row = sheet.row(2)\n row.push \"Uttag datum:\"\n row.push DateTime.now.strftime('%FT%R')\n row = sheet.row(3)\n row.push \"Bokningar:\"\n row = sheet.row(4)\n row.push \"Id\", \"Biljetter\", \"Namn\", \"Bokades\", \"Epost\", \"Telefon\", \"Kontaktperson\", \"Betalat\", \"Meddelande\", \"Notering\", \"Rabatt\", \"Rabattmeddelande\", \"Paket\"\n bookings.each_with_index do |booking, index|\n row = sheet.row(5+index)\n row.push booking.id, booking.tickets, booking.name, booking.created_at.strftime('%FT%R'), booking.email, booking.phone_nr, booking.contact_person, booking.paid, booking.message, booking.memo, booking.discount, booking.discount_message, booking.order_rows_string\n end\n\n return book\n end",
"def add_data(dataset, worksheet, columns)\r\n dataset.rows.each_with_index do |row, rindex|\r\n columns.each_with_index do |col, cindex|\r\n # set column formatting\r\n f = nil\r\n cell_value = nil\r\n col_length = row[col].to_s.length < 20 ? 20 : row[col].to_s.length\r\n if row[col].kind_of? Fixnum or row[col].kind_of? Float\r\n f = @formats[:number_column]\r\n cell_value = [row[col]]\r\n else\r\n f = @formats[:column_format] \r\n cell_value = row[col].to_s\r\n end\r\n \r\n worksheet.write(rindex + STARTING_DATA_ROW, cindex, cell_value, @formats[:column_format])\r\n worksheet.format_column(cindex, col_length, f)\r\n end\r\n end\r\n end",
"def postToolsGooglesheetAdd_row( spreadsheet_key, worksheet_key, data)\n params = Hash.new\n params['spreadsheet_key'] = spreadsheet_key\n params['worksheet_key'] = worksheet_key\n params['data'] = data\n return doCurl(\"post\",\"/tools/googlesheet/add_row\",params)\n end",
"def add_rows(sheet)\n # Do nothing\n end",
"def update_spreadsheet\n\t\tconnection = GoogleDrive.login(ENV[\"GMAIL_USERNAME\"], ENV[\"GMAIL_PASSWORD\"])\n\t\tss = connection.spreadsheet_by_title('Learn-Rails-Example')\n\t\tif ss.nil?\n\t\t\tss = connection.create_spreadsheet('Learn-Rails-Example')\n\t\tend\n\t\tws = ss.worksheets[0]\n\t\tlast_empty_row = 1 + ws.num_rows\n\t\tws[last_empty_row, 1] = Time.new\n\t\tws[last_empty_row, 2] = self.name\n\t\tws[last_empty_row, 3] = self.email\n\t\tws[last_empty_row, 4] = self.content\n\t\tws.save\n\tend",
"def worksheet\n @worksheet ||= workbook.add_worksheet(:name => name) do |sheet|\n sheet.add_row header.map(&:value)\n\n rows.each do |row|\n values = row.map(&:value)\n types = row.map(&:type)\n\n sheet.add_row values, :types => types\n end\n end\n end",
"def add_item(worksheet, card)\n users = []\n card.members.each { |member| users << member.full_name }\n last = (worksheet.num_rows + 1)\n worksheet[last, 1] = card.name\n worksheet[last, 2] = list_name(card)\n worksheet[last, 3] = users.join(\"\\n\")\n worksheet[last, 4] = card.description.strip!\n worksheet[last, 5] = card.short_id\n card.close!\n worksheet.save\nend",
"def add_worksheet worksheet\n worksheet.workbook = self\n @worksheets.push worksheet\n worksheet\n end",
"def stock_in_google_spreadsheet\n\n # On appelle l'URL comprenant les informations et on y stocke les URL trouvées dans notre hash\n hash = get_all_the_urls_of_val_doise_townhalls('http://www.annuaire-des-mairies.com/val-d-oise.html')\n\n # On se sert d'each_with_index pour récupérer un index incrementé\n # et faire passer chaque clef et valeur associée dans le spreadsheet\n # en faisant démarrer les deux depuis la ligne 2\n hash.each_with_index do |(key, value), index |\n $ws[index+2, 1] = key\n $ws[index+2, 2] = value\n end\n $ws.save\nend",
"def newSheet(table, taskName, id=nil)\n # open the Google Sheet service\n service = Google::Apis::SheetsV4::SheetsService.new\n service.client_options.application_name = APPLICATION_NAME\n service.authorization = authorize\n\n # open the Google Drive service\n drive = Google::Apis::DriveV3::DriveService.new\n drive.client_options.application_name = APPLICATION_NAME\n drive.authorization = authorize\n puts \"id in export sheet\"\n puts id\n\n #create a new sheet\n if id == nil\n\n spreadsheet = {\n properties: {\n title: taskName\n }\n }\n spreadsheet = service.create_spreadsheet(spreadsheet,\n fields: 'spreadsheetId')\n puts \"Spreadsheet ID: #{spreadsheet.spreadsheet_id}\"\n #fill the sheet with the data 'table'\n data = [\n {\n range: 'A:Z',\n majorDimension: \"ROWS\",\n values: table,\n }\n ]\n value_range_object = Google::Apis::SheetsV4::ValueRange.new(range: 'A:Z',\n majorDimension: \"ROWS\",\n values: table)\n result = service.update_spreadsheet_value(spreadsheet.spreadsheet_id,\n 'A:Z',\n value_range_object,\n value_input_option: 'RAW')\n puts = \"#{result.updated_cells} cells updated.\"\n file = drive.get_file(spreadsheet.spreadsheet_id)\n puts \"Create this file name: #{file.name}\"\n id = spreadsheet.spreadsheet_id\n\n ##\n # change the permision of the created file\n # line in google-api-ruby-client/lib/google/apis/core/api_command.rb return {} and make and error.\n # self.body = request_representation.new(request_object).to_json(user_options: { skip_undefined: true })\n #\n data = \n {\n \"role\" => \"writer\",\n \"type\" => \"anyone\"\n }\n # byebug\n permision = drive.create_permission(id, data.to_json,\n options: {skip_serialization: true})\n \n link = \"https://docs.google.com/spreadsheets/d/#{file.id}\"\n puts \"use this link: #{link}\"\n \n return link\n ##\n # Updating the file with new information\n else\n id = id.split('/')[5]\n file = drive.get_file(id)\n #geting the info of the sheet\n get_celds = service.get_spreadsheet_values(id, 'A:C')\n #byebug\n puts get_celds.values.length\n n = get_celds.values.length + 1\n range = \"A#{n}:B#{n}\"\n #write!\n value_range_object = Google::Apis::SheetsV4::ValueRange.new(range: range,\n values: table)\n result = service.update_spreadsheet_value(id,\n range,\n value_range_object,\n value_input_option: 'RAW')\n puts \"Updating this: #{file.name}\"\n link = \"https://docs.google.com/spreadsheets/d/#{file.id}\"\n puts \"use this link: #{link}\"\n return link\n end\nend",
"def import_data_to_workbook\n file_name = \"Sample_Test_Book.xls\"\n upload_file(file_name)\n\n import_option = ImportDataImportOption.new\n import_option.destination_worksheet = \"Sheet3\"\n import_option.is_insert = true\n response = @cells_api.post_import_data(file_name, import_option)\n end",
"def process_data()\n \tSpreadsheet.client_encoding='UTF-8'\n\tbook=Spreadsheet::Workbook.new\n\tsheet = book.create_worksheet\n\tsheet.row(0).push 'Link Text','Link Url','Description' #For including headers to the spreadsheet.\n\n\tmain_content=Array.new\n\ts=''\n\ts1=''\n\tvalue=0\n\trow_count=1\n\titerate=@range1.to_i\n\twhile iterate <= @range2.to_i\n \t\tif iterate==1\n \t\t\turl='http://www.google.co.in/search?q='+@query_string.to_s\n \t\t\tlink_count=11\n \t\telsif iterate>1\n \t\t\tvalue=(iterate-1)*10\n \t\t\tlink_count=10\n \t\t\turl='http://www.google.co.in/search?q='+@query_string.to_s+'&start='+value.to_s\n \t\tend\n \t\tdoc = Pismo::Document.new(url)\n \t\tcontent=doc.body.to_s\n \t\tmain_content=content.split('*',11)\n \t\ttmp=1\n \t\twhile tmp <= link_count\n \t\t\ts=main_content[tmp]\n \t\t\ts1=s.lines.map(&:chomp) #s1=s.split(/[\\n]+/)\n \t\t\t#print \"Link #{j} : \" + s1[1].to_s + \"\\nUrl #{j} : \" + s1[2].to_s + \"\\nDesc #{j} : \" + s1[3].to_s + \"\\n\"\n \t\t\tsheet.row(row_count).push s1[1].to_s,s1[2].to_s,s1[3].to_s\n \t\t\tbook.write('/home/chandrasekar/training-ruby/shekar/18_September/website_link.xls')\n \t\t\trow_count+=1\n \t\t\ttmp+=1\n \t\tend\n \t\titerate+=1\n\tend\n end",
"def add(row)\n @data << row\n end",
"def export_my_absence\n workbook = Spreadsheet::Workbook.new\n data_sheet = workbook.create_worksheet :name => \"absensi harian #{@current_person.full_name}\"\n format = Spreadsheet::Format.new :weight => :bold\n data_sheet.row(0).default_format = format\n data_sheet.row(0).replace ['Jam Masuk','Jam Keluar','Lama Kerja']\n data_sheet = set_data_export_my_absence(data_sheet)\n spreadsheet = StringIO.new\n workbook.write spreadsheet\n send_data spreadsheet.string, :filename => \"absent_harian_#{@current_person.full_name}.xls\", :type => \"application/vnd.ms-excel\"\n end",
"def save_as_spreadsheet\n session = GoogleDrive::Session.from_config(\"../../config.json\")\n spreadsheet = session.spreadsheet_by_name(\"testcreatefile\").worksheets[0] # on dit a l'api que l'on souhaite modifier le spreadsheet qui porte X nom et la feuille numero 0 de ce meme spreadsheet\n @@name_and_email.map.with_index do |hash, index| # on parcour le tableau qui contion les nom et les emails de chasque ville\n name = hash.keys # je met la key du hash dans une variable, cette variable corespond au nom de la ville\n name = name[0] # je transforme ma variable en string (sans cette ligne cette variable est de type array)\n email = hash.values # je met la value du hash dans une variable, cette variable corespond a l'email de la ville\n email = email[0] # je transforme ma variable en string (sans cette ligne cette variable est de type array)\n spreadsheet[index + 1, 1] = name # le programme envoi le nom de la ville sur le spreadsheet\n spreadsheet[index + 1, 2] = email # le programme envoi l'email de la ville sur le spreadsheet\n end\n spreadsheet.save # le programme sauvegarde les modifications sur le spreadsheet qu'il a modifier\n end",
"def create_games_excel\r\n\r\n if (params[:msg].nil?)\r\n\r\n @student_group = StudentGroup.find(params[:id])\r\n #@book = Spreadsheet.open 'C:/Users/Rushabh Hathi/Desktop/Dialogue1.0/public/Files/abc.txt'\r\n @book = Spreadsheet::Workbook.new\r\n sheet1 = @book.create_worksheet\r\n @rolelist=Role.all(:conditions=>['case_study_id=?', @student_group.case_study_id])\r\n i=1\r\n\r\n# #here role name is added for the list to be populated\r\n# @rolelist.each do |r|\r\n# sheet1[0, i]=r.name\r\n# i=i+1\r\n# end\r\n\r\n @studentgroupuserlist=StudentGroupUser.all(:conditions=>['student_group_id=?', params[:id]])\r\n @studentlist= Array.new\r\n @unallocated_student= Array.new\r\n @studentgroupuserlist.each do |s|\r\n @studentlist << User.find(s.user_id)\r\n end\r\n\r\n #here the dynamic data from student group gets populated\r\n i=1\r\n sheet1[0, 0]=\"Student ID\"\r\n sheet1[0, 1]=\"Student Name\"\r\n sheet1[0, 2]=\"Role Name\"\r\n\r\n\r\n @studentlist.each do |s|\r\n\r\n sheet1[i, 0]=s.id\r\n sheet1[i, 1]=s.first_name+s.last_name\r\n sheet1[i, 2]= \" \"\r\n i=i+1\r\n @book.write \"#{Rails.root}/public/Files/Game_Creation.xls\"\r\n\r\n\r\n end\r\n\r\n end\r\n end",
"def add_key(key)\n numkeys = @worksheet_obj.list.keys.length\n @worksheet_obj[1, numkeys+1] = key\n @worksheet_obj.save\n end",
"def save_as_spreadsheet\n\t\tsession = GoogleDrive::Session.from_config(\"config.json\")\n\t\tws = session.spreadsheet_by_key(\"1UAtn3oB21_a_gUM5TL8OK6Ud7zp6Z7z6c8tGYV6J4HA\").worksheets[0]\n\n\t\ti = 2\n\t\tws[1,1]= \"Ville\"\n\t\tws[1,2] = \"Contact\"\n\t\t@email_town.each_pair do |key, value| #/ on aurait pû utiliser each mais each_pair est plus conseillé lorsqu'il y a deux éléments \n\t\t\tws[i,1] = key\n\t\t\tws[i,2] = value\n\t\t\ti += 1\n\t\tend\n\t\tws.save \n\t\tws.reload\n\tend",
"def write_to_sheet(worksheet, api_data, format)\n col = row = 0\n # puts \"api_data #{api_data.size}\"\n for row in 0...api_data.size\n contents = api_data[row]\n # puts \"contents : #{contents.size}\"\n for col in 0...contents.length\n # puts \"contents[col #{contents[col]}\"\n worksheet.write(row, col, contents[col], format)\n end\n end\nend",
"def vision_sheet_input\n @vision_sheet = @xlsx.sheet('Vision').parse(header_search: [])\n @vision_sheet.drop(1).each do |row|\n @vision = Vision.create!(blurb: row['blurb'])\n end\n end",
"def save_from_on_GoogleDrive\n session = GoogleDrive::Session.from_config(\"config.json\")\n# ws = session.spreadsheet_by_key(\"1PzbUao-3UscYOWh48FL061r5yYcH2TBl1oWXtmaW1cw\").worksheets[0] #cle a changer en fonction du lien url du fichier google drive\n ws = session.spreadsheet_by_key(\"1PzbUao-3UscYOWh48FL061r5yYcH2TBl1oWXtmaW1cw\").worksheets[1] #cle a changer en fonction du lien url du fichier google drive\n table_of_mails=[]\n # for i in 1..table_data.length\n # ws[i, 1] = table_data[i-1][:nom]\n # ws[i, 2] = table_data[i-1][:url]\n # ws[i, 3] = table_data[i-1][:email]\n # end\n puts ws.num_rows\n (1..(ws.num_rows + 1)).each do |row|\n puts ws[row + 1, 2]\n table_of_mails << ws[row + 1, 2]\n end\n Operation_on_gmail(table_of_mails)\n ws.save\n ws.reload\nend",
"def write_to_sheet(worksheet, api_data, format)\n\tcol = row = 0\n\t# puts \"api_data #{api_data.size}\"\n\tfor row in 0...api_data.size\n\t\tcontents = api_data[row]\n\t\t# puts \"contents : #{contents.size}\"\n\t\tfor col in 0..2\n\t\t\t# puts \"contents[col #{contents[col]}\"\n\t\t\tworksheet.write(row, col, contents[col], format)\n\t\tend\n\tend\nend",
"def write_to_sheet(worksheet, api_data, format)\n\tcol = row = 0\n\t# puts \"api_data #{api_data.size}\"\n\tfor row in 0...api_data.size\n\t\tcontents = api_data[row]\n\t\t# puts \"contents : #{contents.size}\"\n\t\tfor col in 0..2\n\t\t\t# puts \"contents[col #{contents[col]}\"\n\t\t\tworksheet.write(row, col, contents[col], format)\n\t\tend\n\tend\nend",
"def create_games_excel\n\n\tif (params[:msg].nil?)\n\n\t @student_group = StudentGroup.find(params[:id])\n\t #@book = Spreadsheet.open 'C:/Users/Rushabh Hathi/Desktop/Dialogue1.0/public/Files/abc.txt'\n\t @book = Spreadsheet::Workbook.new\n\t sheet1 = @book.create_worksheet\n\t @rolelist=Role.all(:conditions=>['case_study_id=?', @student_group.case_study_id])\n\t i=1\n\n# #here role name is added for the list to be populated\n# @rolelist.each do |r|\n# sheet1[0, i]=r.name\n# i=i+1\n# end\n\n\t @studentgroupuserlist=StudentGroupUser.all(:conditions=>['student_group_id=?', params[:id]])\n\t @studentlist= Array.new\n\t @unallocated_student= Array.new\n\t @studentgroupuserlist.each do |s|\n\t\t@studentlist << User.find(s.user_id)\n\t end\n\n\t #here the dynamic data from student group gets populated\n\t i=1\n\t sheet1[0, 0]=\"Student ID\"\n\t sheet1[0, 1]=\"Student Name\"\n\t sheet1[0, 2]=\"Role Name\"\n\n\n\t @studentlist.each do |s|\n\n\t\tsheet1[i, 0]=s.id\n\t\tsheet1[i, 1]=s.first_name+s.last_name\n\t\tsheet1[i, 2]= \" \"\n\t\ti=i+1\n\t\t@book.write \"#{Rails.root}/public/Files/Game_Creation.xls\"\n\n\n\t end\n\n\tend\n end",
"def add_cells (row_key, cells)\r\n cells.each{|item|\r\n @table.put(row_key, {(item[\"col_family\"]+':'+item[\"col_name\"]) => item[\"value\"]})\r\n } \r\n end",
"def write_worksheet_data(worksheet, header)\n worksheet.write('A1', 'Region', header)\n worksheet.write('B1', 'Sales Rep', header)\n worksheet.write('C1', 'Product', header)\n worksheet.write('D1', 'Units', header)\n\n data = [\n ['East', 'Tom', 'Apple', 6380],\n ['West', 'Fred', 'Grape', 5619],\n ['North', 'Amy', 'Pear', 4565],\n ['South', 'Sal', 'Banana', 5323],\n ['East', 'Fritz', 'Apple', 4394],\n ['West', 'Sravan', 'Grape', 7195],\n ['North', 'Xi', 'Pear', 5231],\n ['South', 'Hector', 'Banana', 2427],\n ['East', 'Tom', 'Banana', 4213],\n ['West', 'Fred', 'Pear', 3239],\n ['North', 'Amy', 'Grape', 6520],\n ['South', 'Sal', 'Apple', 1310],\n ['East', 'Fritz', 'Banana', 6274],\n ['West', 'Sravan', 'Pear', 4894],\n ['North', 'Xi', 'Grape', 7580],\n ['South', 'Hector', 'Apple', 9814]\n ]\n\n row_num = 1\n data.each do |row_data|\n worksheet.write_row(row_num, 0, row_data)\n row_num += 1\n end\n end",
"def create_new_sheet(date, new_spreadsheet_id)\n #make copy of template sheet to new spreadsheet\n new_sheet_id = copy_sheet(new_spreadsheet_id)\n \n #set the name of that sheet\n set_name_of_sheet(date.day.to_s, new_sheet_id, new_spreadsheet_id)\n \n #set the date on the sheet\n set_date_of_sheet(date, new_spreadsheet_id)\nend",
"def save_as_spreadsheet\n session = GoogleDrive::Session.from_config(\"../config.json\")\n ws = session.spreadsheet_by_key(ENV['SPREADSHEET_KEY']).worksheets[0]\n ws.reload\n i = 0\n n = get_townhall_urls.count\n while i <= 4\n ws[i+1, 1] = @emails[i]\n ws[i+1, 2] = @names_of_town[i]\n i +=1\n end\n ws.save\n end",
"def create_spreadsheet(title = \"Untitled\")\n file = self.drive.files.insert.request_schema.new({\n \"title\" => title,\n \"mimeType\" => \"application/vnd.google-apps.spreadsheet\",\n })\n api_result = execute!(\n :api_method => self.drive.files.insert,\n :body_object => file)\n return wrap_api_file(api_result.data)\n end",
"def addRow\n\t\tnew_row = @vars.values\n\t\tcsvrow = new_row.to_csv\n\t\t@arrayOfRows.push(csvrow)\n\tend",
"def create_row(params)\n # add the keys if they don't exist\n params.each do | key, value |\n if(!@worksheet_obj.list.keys.include?(key))\n add_key(key)\n end\n end\n # save key changes\n if(@worksheet_obj.dirty?)\n @worksheet_obj.synchronize\n end\n #push the new row\n @worksheet_obj.list.push(params)\n @worksheet_obj.save\n end",
"def add_chart(chartType, upperLeftRow, upperLeftColumn, lowerRightRow, lowerRightColumn)\n begin\n if(@filename=='')\n raise \"Base file not specified\"\n end\n if(@worksheetname=='')\n raise \"Worksheet is not specified\"\n end\n str_uri = $productURI + \"/cells/\" + @filename + \"/worksheets/\" + @worksheetname + \"/charts?chartType=\" +\n chartType.to_s + \"&upperLeftRow=\" + upperLeftRow.to_s + \"&upperLeftColumn=\" +\n upperLeftColumn.to_s + \"&lowerRightRow=\" + lowerRightRow.to_s + \n \"&lowerRightColumn=\" + lowerRightColumn.to_s\n signed_uri = Common::Utils.sign(str_uri)\n \n response = RestClient.put signed_uri,'', {:accept => 'application/json'}\n v_output = Common::Utils.validate_output(response)\n if(v_output==nil || v_output=='')\n folder = SaasposeStorage::Folder.new\n outputstream = folder.getfile(@filename)\n outputstream\n outputpath = $OutPutLocation + @filename\n Common::Utils.saveFile(outputstream, outputpath)\n return \"Chart added\"\n else\n return v_output\n end\n rescue Exception=>e\n print e\n end\n end",
"def str1_upload_xls\n @title=\"Import Users\"\n Spreadsheet.client_encoding='UTF-8'\n if params[:file].present?\n book=Spreadsheet.open params[:file].tempfile\n sheet1=book.worksheet 0\n sheet1.each 1 do |row|\n @store = Businessnew.new(:address=>row[3], :category=>row[10], :city=>row[4], :id=>row[0],\n :latitude=>row[9], :longitude=>row[8], :name=>row[1], :phone=>row[7],\n :postal_code=>row[6].split(\" \").join(''), :state=>row[5], :url=>row[2])\n if @store.present?\n @store.save\n end\n end\n end\n redirect_to '/'\n end",
"def import_data\r\n # generate data column instances\r\n columnheaders_raw.each do |columnheader|\r\n\r\n data_column_information = initialize_data_column_information(columnheader)\r\n data_column_new = Datacolumn.create!(data_column_information)\r\n all_cells_for_one_column = data_for_columnheader(columnheader)[:data]\r\n datatype = Datatypehelper.find_by_name(data_column_information[:import_data_type])\r\n\r\n unless all_cells_for_one_column.blank?\r\n save_all_cells_to_database(data_column_new, datatype, all_cells_for_one_column)\r\n add_any_sheet_categories_included_for_this_column(columnheader, data_column_new)\r\n add_acknowledged_people(columnheader, data_column_new)\r\n end\r\n data_column_new.finished = true\r\n end\r\n end",
"def new_data_entry\n # subject_event_id = params[:sheet][:subject_event_id] if params[:sheet] && params[:sheet].key?(:subject_event_id)\n # @sheet = @subject.sheets.new(project_id: @project.id, design_id: @design.id, subject_event_id: subject_event_id)\n @sheet = @subject.sheets\n .where(\n project_id: @project.id,\n design_id: @design.id,\n adverse_event_id: params[:adverse_event_id],\n ae_adverse_event_id: params[:ae_adverse_event_id]\n )\n .new(sheet_params)\n render \"sheets/new\"\n end",
"def add_rows(sheet, mode_tos)\n\n infrastructures = @ntd_report.ntd_infrastructures.where(fta_mode: mode_tos[0], fta_service_type: mode_tos[1])\n\n (FtaTrackType.pluck(:name, :sort_order) + FtaGuidewayType.pluck(:name,:sort_order) + FtaPowerSignalType.pluck(:name, :sort_order)).sort_by{|x| x[1]}.map{|y| \"#{y[1]}. #{y[0]}\"}.each do |guideway_element|\n row_data = []\n guideway_element_str = guideway_element.split('.').last.strip\n infrastructure = infrastructures.find_by(fta_type: guideway_element_str)\n if infrastructure\n row_data << infrastructure.fta_mode #A\n row_data << infrastructure.fta_service_type #B\n row_data << guideway_element #C\n row_data << '' #D\n row_data << infrastructure.size #E\n row_data << infrastructure.track_miles #F\n row_data << infrastructure.expected_service_life #G\n row_data << infrastructure.pcnt_capital_responsibility #H\n row_data << infrastructure.shared_capital_responsibility_organization #I\n row_data << infrastructure.description #J\n row_data << infrastructure.notes #K\n row_data << infrastructure.allocation_unit #L\n row_data << infrastructure.pre_nineteen_thirty #M\n row_data << infrastructure.nineteen_thirty #N\n row_data << infrastructure.nineteen_forty #O\n row_data << infrastructure.nineteen_fifty #P\n row_data << infrastructure.nineteen_sixty #Q\n row_data << infrastructure.nineteen_seventy #R\n row_data << infrastructure.nineteen_eighty #S\n row_data << infrastructure.nineteen_ninety #T\n row_data << infrastructure.two_thousand #U\n row_data << infrastructure.two_thousand_ten #V\n row_data << infrastructure.two_thousand_twenty #W\n row_data << '' #X Placeholder for Tracks Miles Under Performance Restriction\n else\n row_data << [mode_tos[0], mode_tos[1], guideway_element, 'NA'] + ['']*19\n end\n sheet.add_row row_data.flatten.map{|x| x.to_s}, types: [:string]*5 + [:float]*2 + [:string]*16\n end\n\n add_performance_restrictions_row(sheet, mode_tos)\n\n end",
"def add_worksheet(name = nil)\n if name.nil? then\n n = 0\n\n begin\n name = SHEET_NAME_TEMPLATE % (n += 1)\n end until self[name].nil?\n end\n\n new_worksheet = Worksheet.new(:workbook => self, :sheet_name => name)\n worksheets << new_worksheet\n new_worksheet\n end",
"def add_worksheet(name = nil)\n if name.nil? then\n n = 0\n\n begin\n name = SHEET_NAME_TEMPLATE % (n += 1)\n end until self[name].nil?\n end\n\n new_worksheet = Worksheet.new(:workbook => self, :sheet_name => name)\n worksheets << new_worksheet\n new_worksheet\n end",
"def add_worksheet(name = nil)\n if name.nil? then\n n = 0\n\n begin\n name = SHEET_NAME_TEMPLATE % (n += 1)\n end until self[name].nil?\n end\n\n new_worksheet = Worksheet.new(:workbook => self, :sheet_name => name)\n worksheets << new_worksheet\n new_worksheet\n end",
"def add( ref = false )\n case ref\n when false ; s = Sheet.new( 'Sheet' + ( @sheets.count + 1 ).to_s, self )\n when Sheet ; ( s = ref ).workbook = self\n when String ; s = Sheet.new( ref, self )\n else ; fail TypeError, \"Unsupported Type: #{ ref.class }\"\n end\n @sheets << s\n s\n end",
"def add_entry entry\n @data << entry\n end",
"def save_as_spreadsheet\n session = GoogleDrive::Session.from_config('./config.json')\n key = '1cAn303rPBOi1d2O0j4tQuGi5FZksD2yVAzNQd57cDns'\n ws = session.spreadsheet_by_key(key).worksheets[0]\n i = 1\n get_townhall_url.sto_a.each do |x|\n ws[i, 1] = x[0]\n ws[i, 2] = x[1]\n i += 1\n end\n ws.save\n puts \"\\nTon fichier google est prêt\\n\\n\"\n Index.new.index\n end",
"def add_service_details_sheet(package)\n service_descriptions_sheet = Roo::Spreadsheet.open(Rails.root.join('app', 'assets', 'files', 'FMServiceDescriptions.xlsx'), extension: :xlsx)\n service_descriptions = service_descriptions_sheet.sheet('Service Descriptions')\n\n package.workbook.add_worksheet(name: 'Service Information') do |sheet|\n (service_descriptions.first_row..service_descriptions.last_row).each do |row_number|\n sanitized_row = service_descriptions.row(row_number).map { |cell| strip_tags(cell) }\n sheet.add_row sanitized_row, widths: [nil, 20, 200]\n end\n\n apply_service_information_sheet_styling(sheet)\n end\n end",
"def create_row(params)\n\t\tself.google_doc.restart_session_if_necessary\n\t\treset_worksheet_obj if @worksheet_obj == nil\n\t\t# add the keys if they don't exist\n\t\tparams.each do | key, value |\n\t\t\tif(!@worksheet_obj.list.keys.include?(key))\n\t\t\t\tadd_column_key(key)\n\t\t\tend\n\t\tend\n\t\t# save key changes\n\t\tif(@worksheet_obj.dirty?)\n\t\t\t@worksheet_obj.synchronize\n\t\tend\n\t\t#push the new row\n\t\tnew_row = @worksheet_obj.list.push(params)\n\t\t@worksheet_obj.save\n\t\treturn new_row\n\tend",
"def report \n @cars = Car.all\n\n book = Spreadsheet::Workbook.new \nsheet = book.create_worksheet :name => 'Test' \nmerge = Spreadsheet::Format.new :horizontal_align => :merge \nsheet.row(0).set_format(1, merge) \nsheet.row(0).set_format(2, merge) \nsheet.row(0).set_format(3, merge) \nsheet.row(0).set_format(4, merge) \n @cars.each_with_index do |car, i|\n sheet[i, 1] = car.title\n sheet[i, 5] = car.price\n car.parameters.each do |p| \n\tsheet[i, 2] = p.value if !(p.name !~ /发动机排量/)\n\tsheet[i, 3] = p.value if !(p.name !~ /生产厂家/) \n\tsheet[i, 4] = p.value if !(p.name !~ /生产状态/)\n end\n \n \n end\nbook.write '/home/ruby/mycar/fruits.xls' \n redirect_to :action => 'download' \nend",
"def add(data)\n if (@data_array.size >= @bulk_limit)\n bulk_insert(@data_array)\n @data_array.clear\n end\n\n health = [\n 'baby_hatch',\n 'clinic',\n 'dentist',\n 'doctors',\n 'hospital',\n 'nursing_home',\n 'pharmacy',\n 'social_facility',\n ]\n\n education = [\n 'college',\n 'kindergarten',\n 'library',\n 'public_bookcase',\n 'music_school',\n 'music_school',\n 'driving_school',\n 'language_school',\n 'university',\n ]\n\n finance = [\n 'atm',\n 'bank',\n 'bureau_de_change',\n ]\n\n food_amenity = [\n 'convenience',\n 'mall',\n 'supermarket',\n ]\n food_shop = [\n 'cafe',\n 'drinking_water',\n 'fast_food',\n 'food_court',\n 'ice_cream',\n 'pub',\n 'restaurant',\n ]\n\n entertainment = [\n 'arts_centre',\n 'casino',\n 'cinema',\n 'community_centre',\n 'fountain',\n 'gambling',\n 'nightclub',\n 'planetarium',\n 'social_centre',\n 'stripclub',\n 'studio',\n 'theatre',\n ]\n\n services_amenity = [\n 'social_facility',\n ]\n services_office = [\n 'accountant',\n 'advertising_agency',\n 'adoption_agency',\n 'architect',\n 'lawyer',\n 'estate_agent',\n 'copyshop',\n 'funeral_directors',\n ]\n\n\n\n if data[\"tags\"] != nil\n data[\"loc\"] = {\n type: \"Point\",\n coordinates: [data[\"lon\"].to_f, data[\"lat\"].to_f]\n }\n if health.include? data[\"tags\"][\"amenity\"]\n data[\"type\"] = 'health'\n @data_array.push(data)\n end\n if education.include? data[\"tags\"][\"amenity\"]\n data[\"type\"] = 'education'\n @data_array.push(data)\n end\n if finance.include? data[\"tags\"][\"amenity\"]\n data[\"type\"] = 'finance'\n @data_array.push(data)\n end\n if food_amenity.include?(data[\"tags\"][\"amenity\"]) || food_shop.include?(data[\"tags\"][\"shop\"])\n data[\"type\"] = 'food'\n @data_array.push(data)\n end\n\n if entertainment.include? data[\"tags\"][\"amenity\"]\n data[\"type\"] = 'entertainment'\n @data_array.push(data)\n end\n\n if services_amenity.include?(data[\"tags\"][\"amenity\"]) || services_office.include?(data[\"tags\"][\"office\"])\n data[\"type\"] = 'service'\n @data_array.push(data)\n end\n end\n #@data_array.push(data)\n end",
"def save_as_spreadsheet\n i = 1\n\n # Creates a session. This will prompt the credential via command line for the\n # first time and save it to config.json file for later usages.\n session = GoogleDrive::Session.from_config(\"../../config.json\")\n\n # Put the key from the google spreadsheet you whant to use\n ws = session.spreadsheet_by_key(\"14NaBtVAdrbCF6CSlLhrBM0Ob9nE96zvyrwKNkSF3oIY\").worksheets[0]\n\n # Puts cities and cities emails in 2 colones\n for y in 0...@ville_name_array.length\n ws[i, 1] = @ville_name_array[y]\n ws[i, 2] = @ville_email_array[y]\n i += 1\n end\n ws.save\n\n # Reloads the worksheet to get changes by other clients.\n ws.reload\n end",
"def save_as_spreedsheet(array)\n\n session = GoogleDrive::Session.from_config(\"config.json\")\n ws = session.spreadsheet_by_key(\"1jCyeGCeITqEWCu5r4NaTE8TxD0WHa9PNwuY93XP_Y2w\").worksheets[0]\n\n final_array = array\n\n ws[1, 1] = \"Nom des Villes\"\n ws[1, 2] = \"Emails des Villes\"\n\n row = 3\n final_array.each do |x|\n ws[row, 1] = x.keys.join\n ws[row, 2] = x.values.join\n row += 1\n end\n\n # Cannot load change without it\n ws.save\n ws.reload\n end",
"def add_worksheet(name)\n Worksheet.new(@wb.addWorksheet(name))\n end",
"def set_date_of_sheet(date, spreadsheet_id)\n day = date.day\n month = date.month\n year = date.year\n weekday = date.strftime('%A')\n formatted_date = \"#{month}/#{day}/#{year} #{weekday}\"\n range = \"#{day}!A2\" #sheet_name = date\n write_sheet_values(range, [[formatted_date]], date)\nend",
"def create\n # Create the spreadsheet file in /tmp and write the file's contents to it\n filename = \"#{DateTime.now.strftime(\"%Y%m%d%H%M%S\")}_sheet.xls\"\n data = params[:file].read\n spreadsheet_file = File.new(\"#{RAILS_ROOT}/tmp/#{filename}\", 'w+')\n spreadsheet_file.write(data)\n spreadsheet_file.close\n \n begin\n # Create a new instance of DatabaseUpdate for this spreadsheet. \n # NOTE: All the work of running the update on the database is handled\n # inside the DatabaseUpdate class on its first instantiation. i.e., upon create.\n @dbup = DatabaseUpdate.create(:spreadsheet_path => spreadsheet_file.path)\n redirect_to @dbup\n rescue CallLogExceptions::InvalidSpreadsheetError\n # DatabaseUpdate has thrown an error related to the format of the spreadsheet. Alert the user.\n flash[:error] = \"<strong>The spreadsheet you provided is not in the anticipated format.</strong><br/>Please correct the sheet and try again.\"\n redirect_to home_url(Person.find(session[:user_id]))\n end\n end",
"def googleroster\n returned_authorisation = googleauthorisation(request)\n if returned_authorisation[\"authorizationurl\"]\n redirect_to returned_authorisation[\"authorizationurl\"] and return\n end\n service = returned_authorisation[\"service\"]\n#-----------------------------------------------------------------\n# Create a new spreadsheet -works and tested\n #request_body = Google::Apis::SheetsV4::Spreadsheet.new\n #response = service.create_spreadsheet(request_body)\n #ss = response\n #spreadsheet_id = ss.spreadsheet_id\n#-----------------------------------------------------------------\n\n#-----------------------------------------------------------------\n# Use an existing previously created spreadsheet\n# Only need the id to make use of this.\n #spreadsheet_id = '1VHNfTl0Qxok1ZgBD2Rwby-dqxihgSspA0InqS5dTXNI'\n spreadsheet_id = '1mfS0V2IRS1x18otIta1kOdfFvRMu6NltEe-edn7MZMc'\n#-----------------------------------------------------------------\n\n#-----------------------------------------------------------------\n# Use the spreadsheet configured in user profiles\n# = Roster Google Spreadsheet URL \n spreadsheet_id = current_user[:rosterssurl].match(/spreadsheets\\/d\\/(.*?)\\//)[1]\n\n # Get URL of spreadsheet\n response = service.get_spreadsheet(spreadsheet_id)\n @spreadsheet_url = response.spreadsheet_url\n\n # Sheet we are working on.\n sheet_name = \"Sheet1\"\n sheet_id = 0\n\n #this function converts spreadsheet indices to column name\n # examples: e[0] => A; e[30] => AE \n e =->n{a=?A;n.times{a.next!};a} \n\n# ************ update spreadsheet title ************************\n# https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate\n spreadsheet_title = \"Google Roster\" \n request_body = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new\n myussp = {\"properties\": {\"title\": spreadsheet_title}, \"fields\": \"*\" }\n request_body.requests = [{\"update_spreadsheet_properties\": myussp }]\n result = service.batch_update_spreadsheet(spreadsheet_id, request_body, {})\n\n# ************ add sheet ************************\n googleAddSheet = lambda{ |mytitle, mysheetproperties|\n request_body = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new\n myas = {\"properties\": {\"title\": mytitle}}\n request_body.requests = [{\"add_sheet\": myas }]\n result = service.batch_update_spreadsheet(spreadsheet_id, request_body, {})\n mysheetproperties.push({'index' => result.replies[0].add_sheet.properties.index,\n 'sheet_id' => result.replies[0].add_sheet.properties.sheet_id,\n 'title' => result.replies[0].add_sheet.properties.title})\n }\n \n# ************ delete sheets ************************\n googleSheetDelete = lambda{\n result = service.get_spreadsheet(spreadsheet_id)\n mysheets = result.sheets\n request_body = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new\n mysheets.each_with_index do |o, i|\n next if i == 0\n request_body.requests == nil ?\n request_body.requests = [{\"delete_sheet\": {\"sheet_id\": o.properties.sheet_id}}] :\n request_body.requests.push({\"delete_sheet\": {\"sheet_id\": o.properties.sheet_id}})\n end\n unless request_body.requests == nil\n result = service.batch_update_spreadsheet(spreadsheet_id, request_body, {})\n end\n }\n\n# ************ get spreadsheet properties ************************\n googleSheetProperties = lambda{\n result = service.get_spreadsheet(spreadsheet_id)\n mysheets = result.sheets\n mysheetproperties = mysheets.map{|p| {'index' => p.properties.index, \n 'sheet_id' => p.properties.sheet_id,\n 'title' => p.properties.title } }\n \n }\n\n# ************ update sheet title ************************\n# https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate\n googleSetSheetTitle = lambda{ |mytitle|\n request_body = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new\n myusp = {\"properties\": {\"title\": mytitle }, \"fields\": \"title\" }\n request_body.requests = [{\"update_sheet_properties\": myusp }]\n result = service.batch_update_spreadsheet(spreadsheet_id, request_body, {})\n }\n\n# ************ delete all cells (rows) in a sheet ****************************\n# https://www.rubydoc.info/github/google/google-api-ruby-client/Google/Apis/SheetsV4/Request#delete_range-instance_method \n googleClearSheet = lambda{|passed_sheet_id|\n requests = [{ delete_range:{\n range: {sheet_id: passed_sheet_id, start_row_index: 0, start_column_index: 0 },\n shift_dimension: \"ROWS\"}}]\n body = {requests: requests}\n result = service.batch_update_spreadsheet(spreadsheet_id, body, {})\n }\n \n\n# ******** set vertical alignment using batch_update_spreadsheet ********\n # googleVertAlignAll.call(palign \"TOP | MIDDLE | BOTTOM\")\n googleVertAlignAll = lambda{ |passed_sheet_id, palign|\n requests = [{repeat_cell: {\n \t range: {sheet_id: passed_sheet_id,\n \t start_row_index: 0,\n \t start_column_index: 0\n \t },\n cell: {user_entered_format: {vertical_alignment: palign} },\n fields: \"user_entered_format(vertical_alignment)\"\n }\n }]\n body = {requests: requests}\n result = service.batch_update_spreadsheet(spreadsheet_id, body, {})\n }\n\n# ****************** calls batch_update_spreadsheet ******************\n # googlebatchdataitem.call(passed_items [googlebackgroundcolouritem, ...])\n googleBatchUpdate = lambda{|passeditems|\n if passeditems.count > 0\n body = {requests: passeditems}\n result = service.batch_update_spreadsheet(spreadsheet_id, body, {})\n end\n }\n\n# ******** update background colours using batch_update_spreadsheet ********\n # googleBGColourItem.call(rowStart, colStart, numberOfRows, numberOfCols,\n # colour[red_value, geen_value, blue_value])\n googleBGColourItem = lambda{|passed_sheet_id, rs, cs, nr, nc, pcolour|\n {repeat_cell: {\n \t range: {sheet_id: passed_sheet_id,\n \t start_row_index: rs - 1,\n \t end_row_index: rs - 1 + nr,\n \t start_column_index: cs - 1,\n \t end_column_index: cs - 1 + nc},\n cell:{user_entered_format:\n \t {background_color: {red: pcolour[0], green: pcolour[1], blue: pcolour[2]}}},\n fields: \"user_entered_format(background_color)\"}}}\n \n# ******** set vertical alignment using batch_update_spreadsheet ********\n # googleVertAlign.call(rowStart, colStart, numberOfRows, numberOfCols,\n # palign \"TOP | MIDDLE | BOTTOM\")\n googleVertAlign = lambda{|passed_sheet_id, rs, cs, nr, nc, palign|\n pad = 5\n result = {repeat_cell: {\n \t range: {sheet_id: passed_sheet_id,\n \t start_row_index: rs - 1,\n \t start_column_index: cs - 1 },\n cell:{user_entered_format: {vertical_alignment: palign,\n padding: {\n top: pad,\n right: pad,\n bottom: pad,\n left: pad\n }\n } \n },\n fields: \"user_entered_format(vertical_alignment,padding)\"\n }\n }\n if nr != nil then\n result[:repeat_cell][:range][:end_row_index] = rs - 1 + nr \n end\n if nc != nil then\n result[:repeat_cell][:range][:end_column_index] = cs - 1 + nc \n end\n return result\n }\n\n# ******** set wrap text using batch_update_spreadsheet ********\n # googleWrapText.call(rowStart, colStart, numberOfRows, numberOfCols,\n # wrap \"OVERFLOW_CELL | LEGACY_WRAP | CLIP | WRAP\")\n googleWrapText = lambda{|passed_sheet_id, rs, cs, nr, nc, pwrap|\n result = {repeat_cell: {\n \t range: {sheet_id: passed_sheet_id,\n \t start_row_index: rs - 1,\n \t start_column_index: cs - 1 },\n cell:{user_entered_format: {wrap_strategy: pwrap} },\n fields: \"user_entered_format(wrap_strategy)\"\n }\n }\n if nr != nil then\n result[:repeat_cell][:range][:end_row_index] = rs - 1 + nr \n end\n if nc != nil then\n result[:repeat_cell][:range][:end_column_index] = cs - 1 + nc \n end\n return result\n }\n\n# ******** update borders using batch_update_spreadsheet ********\n# https://developers.google.com/sheets/api/samples/formatting\n # googleBorder.call(sheet_id, rowStart, colStart, numberOfRows, numberOfCols,\n # {left: color, right: .., top: .., bottom: ..}, width)\n googleBorder = lambda{|passed_sheet_id, rs, cs, nr, nc, pcolour, passedStyle |\n {\n update_borders: {\n \t range: { sheet_id: passed_sheet_id,\n \t start_row_index: rs - 1,\n \t end_row_index: rs - 1 + nr,\n \t start_column_index: cs - 1,\n \t end_column_index: cs - 1 + nc },\n top: { style: passedStyle,\n \t color: {red: pcolour[0], green: pcolour[1], blue: pcolour[2]}},\n left: { style: passedStyle,\n \t color: {red: pcolour[0], green: pcolour[1], blue: pcolour[2]}},\n right: { style: passedStyle,\n \t color: {red: pcolour[0], green: pcolour[1], blue: pcolour[2]}},\n bottom: { style: passedStyle,\n \t color: {red: pcolour[0], green: pcolour[1], blue: pcolour[2]}},\n }\n }\n }\n\n# ******** update borders using batch_update_spreadsheet ********\n# https://developers.google.com/sheets/api/samples/formatting\n # googleBorder.call(sheet_id, rowStart, colStart, numberOfRows, numberOfCols,\n # {left: color, right: .., top: .., bottom: ..}, width)\n googleRightBorder = lambda{|passed_sheet_id, rs, cs, nr, nc, pcolour, passedStyle |\n {\n update_borders: {\n \t range: { sheet_id: passed_sheet_id,\n \t start_row_index: rs - 1,\n \t end_row_index: rs - 1 + nr,\n \t start_column_index: cs - 1,\n \t end_column_index: cs - 1 + nc },\n right: { style: passedStyle,\n \t color: {red: pcolour[0], green: pcolour[1], blue: pcolour[2]}}\n }\n }\n }\n\n# ******** adjust columns width using batch_update_spreadsheet ********\n# https://developers.google.com/sheets/api/samples/rowcolumn \n\n # googlecolwidthitem.call(colStart, numberOfCols,\n # width_pixels)\n googleColWidthItem = lambda{|passed_sheet_id, cs, nc, passedpw|\n {\n update_dimension_properties: {\n range: { dimension: \"COLUMNS\",\n \t sheet_id: passed_sheet_id,\n \t start_index: cs - 1,\n end_index: cs - 1 + nc },\n \t properties: { pixel_size: passedpw },\n \t fields: \"pixelSize\"\n }\n }\n }\n\n# ******** autoresize columns using batch_update_spreadsheet ********\n# https://developers.google.com/sheets/api/samples/rowcolumn \n\n # googlecolautowidthitem.call(passed_sheet_id, colStart, numberOfCols)\n googleColAutowidthItem = lambda{|passed_sheet_id, cs, nc|\n {\n auto_resize_dimensions: { dimensions: { dimension: \"COLUMNS\",\n \t sheet_id: passed_sheet_id,\n \t start_index: cs - 1,\n end_index: cs - 1 + nc }\n }\n }\n }\n \n# ******** merge cells using batch_update_spreadsheet ********\n# https://developers.google.com/sheets/api/samples/formatting \n # googleMergeCells.call(passed_sheet_id, rowStart, numOfRows, colStart, numberOfCols)\n googleMergeCells = lambda{|passed_sheet_id, rs, nr, cs, nc|\n {\n merge_cells: { range: { sheet_id: passed_sheet_id,\n start_row_index: rs - 1,\n end_row_index: rs - 1 + nr,\n start_column_index: cs - 1,\n end_column_index: cs - 1 + nc },\n merge_type: \"MERGE_ALL\"\n }\n }\n }\n\n# ******** format header cells using batch_update_spreadsheet ********\n# https://developers.google.com/sheets/api/samples/formatting \n # googlefomratCells.call(passed_sheet_id, rowStart, numOfRows, colStart, numberOfCols, fontSize)\n googleFormatCells = lambda{|passed_sheet_id, rs, nr, cs, nc, fs|\n {\n repeat_cell: { range: { sheet_id: passed_sheet_id,\n start_row_index: rs - 1,\n end_row_index: rs - 1 + nr,\n start_column_index: cs - 1,\n end_column_index: cs - 1 + nc },\n cell: { user_entered_format: {\n horizontal_alignment: \"CENTER\",\n text_format: {\n font_size: fs,\n bold: true\n }\n }\n },\n fields: \"userEnteredFormat(textFormat, horizontalAlignment)\"\n }\n }\n }\n\n# ************ update values using update_spreadsheet_value ****************************\n# doco: https://www.rubydoc.info/github/google/google-api-ruby-client/Google%2FApis%2FSheetsV4%2FSheetsService%3Aupdate_spreadsheet_value \n# call using\n\n# googlevalues.call(rowStartIndex, columnStartIndex, numberOfRows, numberOfColumns, values[[]])\n# Indexes start at 1 for both rows and columns\n googleValues = lambda{|rs, cs, nr, nc, values| \n range = \"#{sheet_name}!\" + e[cs - 1] + rs.to_s + \":\" +\n e[cs + nc - 1] + (rs + nr).to_s\n request_body = Google::Apis::SheetsV4::ValueRange.new\n request_body.values = values\n request_body.major_dimension = \"ROWS\"\n service.update_spreadsheet_value(spreadsheet_id, range, request_body, \n {value_input_option: 'USER_ENTERED'})\n }\n \n# ************ update values using batch_update_values ****************************\n # googlebatchdataitem.call(rowStart, colStart, numberOfRows, numberOfCols,\n # values[[]])\n googleBatchDataItem = lambda{|passed_sheet_name, rs, cs, nr, nc, values|\n range = \"#{passed_sheet_name}!\" + e[cs - 1] + rs.to_s + \":\" +\n e[cs + nc - 1] + (rs + nr).to_s\n {\n range: range,\n majorDimension: 'ROWS',\n values: values\n }\n }\n\n# ************ execute batch update of values - [data items] ****************************\n # googlebatchdataitem.call(spreadsheet_id, \n # passed in batch data [gppg;ebatcjdataote, ...])\n googleBatchDataUpdate = lambda{|ss_id, dataitems |\n if dataitems.count > 0\n request_body = Google::Apis::SheetsV4::BatchUpdateValuesRequest.new\n request_body.value_input_option = 'USER_ENTERED'\n request_body.data = dataitems\n service.batch_update_values(ss_id, request_body, {})\n end\n }\n\n# ************ text format run using batch_update_values ****************************\n # googlebatchTextFormatRunItem.call(rowStart, colStart, \n # text, breakPointToChangeFormat[])\n googleTextFormatRun = lambda{|passed_sheet_id, rs, cs, myText, myBreaks|\n result = \n {\n update_cells: {\n \t start: {sheet_id: passed_sheet_id,\n \t row_index: rs - 1,\n \t column_index: cs - 1\n \t },\n rows: [ \n { values: [ \n {\n user_entered_value: {\n string_value: myText\n },\n user_entered_format: {\n text_format: {\n fontFamily: \"Arial\"\n }\n },\n text_format_runs: [\n {\n start_index: myBreaks[0],\n format: {\n bold: true,\n font_size: 10\n }\n }\n ]\n }\n ]\n }\n \n ],\n fields: \"userEnteredValue, userEnteredFormat.textFormat.bold, textFormatRuns.format.(bold, fontSize, fontFamily)\"\n }\n }\n if myBreaks[1] < myText.length then\n secondRun = {\n start_index: myBreaks[1],\n format: {\n bold: false,\n font_size: 10\n }\n }\n result[:update_cells][:rows][0][:values][0][:text_format_runs].push(secondRun)\n end\n return result\n }\n \n \n# ************ batch update of data items ****************************\n # googlebatchdataitem.call(spreadsheet_id, \n # passed in batch data [gppg;ebatcjdataote, ...])\n googleBatchDataUpdate = lambda{|ss_id, dataitems |\n if dataitems.count > 0\n request_body = Google::Apis::SheetsV4::BatchUpdateValuesRequest.new\n request_body.value_input_option = 'USER_ENTERED'\n request_body.data = dataitems\n service.batch_update_values(ss_id, request_body, {})\n end\n }\n\n#-------- To test or not to test ------------------------------\ntesting = false # true or false\nif testing then\n\n#--------------------- Test Data -------------------------------\n# Clear the sheet\n googleClearSheet.call(sheet_id)\n \n# Some test formatting\n batchitems = []\n\n batchitems.push(googleBGColourItem.call(sheet_id, 1,1,1,2,[0,1,0]))\n batchitems.push(googleBGColourItem.call(sheet_id, 6,1,1,2,[1,0,0]))\n batchitems.push(googleBGColourItem.call(sheet_id, 7,1,1,2,[0,0,1]))\n\n batchitems.push(googleBorder.call(sheet_id, 2,1,2,2, [0,0,0], \"SOLID_MEDIUM\"))\n \n batchitems.push(googleVertAlign.call(sheet_id,2,1,2,2, \"TOP\"))\n\n batchitems.push(googleWrapText.call(sheet_id, 2,1,2,2, \"WRAP\"))\n\n batchitems.push(googleColWidthItem.call(sheet_id, 1,3,160))\n \n googleBatchUpdate.call(batchitems) \n\n# Some test cellvalues - individual update\n myvalues = [[\"update_spreadsheet_value\",\"test data - this row will get a background colour\"]]\n googleValues.call(1, 1, 1, 2, myvalues)\n\n# Some test value data - batch update\n mydata = []\n mydata.push(googleBatchDataItem.call(sheet_name,2,1,2,2,\n [\n [\"spreadsheet_values_batchUpdate\", \"test data\"],\n [\"spreadsheet_values_batchUpdate\", \"third row\"]\n ])\n )\n mydata.push(googleBatchDataItem.call(sheet_name,6,1,2,2,\n [\n [\"spreadsheet_values_batchUpdate2\", \"test data\"],\n [\"spreadsheet_values_batchUpdate2\", \"seventh row\"]\n ])\n )\n googleBatchDataUpdate.call(spreadsheet_id, mydata)\n\n #Note: need to do values first so autoformat works.\n batchitems = [] # reset\n batchitems.push(googleColAutowidthItem.call(sheet_id, 1, 1))\n googleBatchUpdate.call(batchitems) \n \n logger.debug \"about to try out googleTextFormatRun\"\n batchitems = []\n batchitems.push(googleTextFormatRun.call(sheet_id, 10,2, \"123456789\\n1234567890123456789\", [0,10]))\n googleBatchUpdate.call(batchitems) \n logger.debug \"done googleTextFormatRun\"\n\nelse # Not to test.\n\n# let does some processing - writing rosters to google sheets.\n #@sf = 5 # number of significant figures in dom ids for lesson,tutor, etc.\n\n #mystartdate = current_user.daystart\n #myenddate = current_user.daystart + current_user.daydur.days\n @options = Hash.new\n #@options[:startdate] = current_user.daystart\n #@options[:enddate] = current_user.daystart + current_user.daydur.days\n @options[:startdate] = current_user.rosterstart\n @options[:enddate] = current_user.rosterstart + current_user.rosterdays.days\n \n #*****************************************************************\n # Set these to control what is displayed in the roster\n \n @tutorstatusforroster = [\"scheduled\", \"dealt\", \"confirmed\", \"attended\"]\n @studentstatusforroster = [\"scheduled\", \"dealt\", \"attended\"]\n \n #*****************************************************************\n \n # call the library in controllers/concerns/calendarutilities.rb\n #@cal = calendar_read_display2(@sf, mystartdate, myenddate)\n #calendar_read_display1f(sf, mystartdate, myenddate, options)\n \n # @tutors and @students are used by the cal\n @tutors = Tutor\n .where.not(status: \"inactive\")\n .order('pname')\n @students = Student\n .where.not(status: \"inactive\")\n .order('pname')\n \n #@cal = calendar_read_display1f(@sf, mystartdate, myenddate, {})\n #@cal = calendar_read_display1f(@sf, @options)\n @cal = calendar_read_display1f(@options)\n # Clear the first sheet - the rest are deleted.\n googleClearSheet.call(sheet_id)\n #googleVertAlignAll.call(\"TOP\")\n\n # kinds will govern the background colours for tutors and students.\n kindcolours = Hash.new\n=begin\n kindcolours = {\n 'tutor-kind-training' => [244, 164, 96],\n 'tutor-kind-called' => [135, 206, 250],\n 'tutor-kind-standard' => [0, 250, 154],\n 'tutor-kind-relief' => [245, 222, 179],\n 'tutor-kind-BFL' => [255, 255, 0],\n 'tutor-kind-onCall' => [0, 255, 255],\n 'tutor-kind-onSetup' => [234, 209, 220],\n 'student-kind-free' => [0, 255, 0],\n 'student-kind-first' => [182, 215, 168],\n 'student-kind-catchup' => [173, 216, 230],\n 'student-kind-fortnightly' => [70, 130, 180], \n 'student-kind-onetoone' => [250, 128, 114],\n 'student-kind-standard' => [0, 250, 154],\n 'tutor-kind-' => [255, 255, 255],\n 'tutor-student-' => [255, 255, 255]\n }\n=end\n kindcolours.default = [255, 255, 255] # result if called with missing key\n \n # clear unused sheets & get sheet properties\n googleSheetDelete.call\n # sets mysheetproperties = [{'index', 'sheet_id', 'title'}, ..]\n mysheetproperties = googleSheetProperties.call \n\n # will increment to 1 on stepping into loops => 1..n\n # Note: both rows and column indexes spreadsheets start at 1\n # Following counters used to track loactions in the spreadsheet\n timeData = ''\n baseSiteRow = 1 \n baseSlotRowInSite = 1\n baseLessonRowInSlot = 0\n currentTutorRowInLesson = 0\n currentStudentRowInLesson = 0\n currentStudentInLesson = 0\n maxPersonRowInAnySlot = 0\n maxPersonRowInAnySlot = 0\n currentCol = 1\n currentRow = 1\n baseSiteRow = 1 # first site \n baseSiteRowAll = 1 # for the 'all' tab \n locationindex = 0 # index into the sites\n \n # to compress or not - remove unused days\n @compress = false # can be true or false\n\n # have an all tab in google sheets to show all sites in that page\n # this is for tutors to seach for their name across all sites.\n # We still have a separate tab for each site\n googleSetSheetTitle.call(\"All\")\n mysheetproperties[locationindex]['title'] = \"All\"\n sheet_name_all = mysheetproperties[locationindex]['title']\n sheet_id_all = mysheetproperties[locationindex]['sheet_id']\n ###----------------------------------------------------------------------\n ###------------------- step through the sites ---------------------------\n ###----------------------------------------------------------------------\n @cal.each do |location, calLocation| # step through sites\n if @compress # remove days with no valid slot for this site\n usedColumns = calLocation[0][0][\"days\"].keys\n usedColumnsIndex = [0]\n for i in 1..(calLocation[0].length-1)\n if usedColumns.include?(calLocation[0][i][\"value\"]) then\n usedColumnsIndex.push(i)\n end\n end \n end\n\n mydata = [] # google batch data writter at end of processing a site\n myformat = []\n\n # make separate sheet entry for each site\n baseSiteRow = 1 # reset when new sheet for each site.\n # baseSiteRowAll continues across all sites.\n if locationindex == 0 # set up the all tab - contains all sites\n # googleSetSheetTitle.call(location)\n # mysheetproperties[locationindex]['title'] = location\n # General formatting for the 'all' sheet - done once\n myformat.push(googleVertAlign.call(sheet_id_all, 1, 1, nil, nil, \"TOP\"))\n myformat.push(googleWrapText.call(sheet_id_all, 1, 1, nil, nil, \"WRAP\"))\n myformat.push(googleColWidthItem.call(sheet_id_all, 1,100,200))\n myformat.push(googleColWidthItem.call(sheet_id_all, 1,1,0))\n end\n # now have a sheet for each site.\n mysheetproperties = googleAddSheet.call(location, mysheetproperties) # add a sheet\n # mysheets = result.sheets\n # mysheetproperties = mysheets.map{|o| {'index' => o.properties.index, \n # 'sheet_id' => o.properties.sheet_id,\n # 'title' => o.properties.title } }\n locationindex += 1\n sheet_name = mysheetproperties[locationindex]['title']\n sheet_id = mysheetproperties[locationindex]['sheet_id']\n\n # This function formats a lesson row\n # myformal and mydata are global to this google roster function\n # we are passing in values to ensure they are in the correct context.\n formatLesson = lambda { |baseLessonRowInSlot, baseSlotRowInSite, baseSiteRow, baseSiteRowAll, currentCol, maxPersonRowInLesson|\n borderRowStart = baseLessonRowInSlot + baseSlotRowInSite + baseSiteRow\n borderRowStartAll = baseLessonRowInSlot + baseSlotRowInSite + baseSiteRowAll\n borderColStart = currentCol\n borderRows = maxPersonRowInLesson\n borderCols = 4 # one tutor col and 2 student cols + lesson commment col.\n # merge the cells within the comment section of a single session\n # googleMergeCells.call(passed_sheet_id, rowStart, numOfRows, colStart, numberOfCols)\n myformat.push(googleMergeCells.call(sheet_id, borderRowStart, borderRows,\n borderColStart + borderCols - 1, 1))\n myformat.push(googleMergeCells.call(sheet_id_all, borderRowStartAll, borderRows,\n borderColStart + borderCols - 1, 1))\n myformat.push(googleBorder.call(sheet_id, borderRowStart, borderColStart, borderRows, borderCols, [0, 0, 0], \"SOLID_MEDIUM\"))\n myformat.push(googleBorder.call(sheet_id_all, borderRowStartAll, borderColStart, borderRows, borderCols, [0, 0, 0], \"SOLID_MEDIUM\"))\n myformat.push(googleRightBorder.call(sheet_id, borderRowStart, borderColStart, borderRows, 1, [0, 0, 0], \"SOLID\"))\n myformat.push(googleRightBorder.call(sheet_id_all, borderRowStartAll, borderColStart, borderRows, 1, [0, 0, 0], \"SOLID\"))\n myformat.push(googleRightBorder.call(sheet_id, borderRowStart, borderColStart+2, borderRows, 1, [0, 0, 0], \"SOLID\"))\n myformat.push(googleRightBorder.call(sheet_id_all, borderRowStartAll, borderColStart+2, borderRows, 1, [0, 0, 0], \"SOLID\"))\n myformat.push(googleWrapText.call(sheet_id, borderRowStart, borderColStart, borderRows, borderCols, \"WRAP\"))\n myformat.push(googleWrapText.call(sheet_id_all, borderRowStartAll, borderColStart, borderRows, borderCols, \"WRAP\"))\n # want to put timeslot time (timeData) in first column of each lesson row.\n for i in borderRowStart..borderRowStart+borderRows-1 do\n mydata.push(googleBatchDataItem.call(sheet_name, i,1,1,1,[[timeData]]))\n end\n for i in borderRowStartAll..borderRowStartAll+borderRows-1 do\n mydata.push(googleBatchDataItem.call(sheet_name_all,i,1,1,1,[[timeData]]))\n end\n }\n #------------- end of lambda function: formatLesson ---------\n\n ### correction ###render flexibledisplay\n \n # General formatting for each site sheet\n myformat.push(googleVertAlign.call(sheet_id, 1, 1, nil, nil, \"TOP\"))\n myformat.push(googleWrapText.call(sheet_id, 1, 1, nil, nil, \"WRAP\"))\n myformat.push(googleColWidthItem.call(sheet_id, 1,100,350))\n myformat.push(googleColWidthItem.call(sheet_id, 1,1,0))\n\n #<table id=site-<%= location %> >\n baseSlotRowInSite = 0 # first slot\n currentRow = baseSlotRowInSite + baseSiteRow\n currentRowAll = baseSlotRowInSite + baseSiteRowAll\n ###----------------------------------------------------------------------\n ###-- step through each time period for this site e.g. 3:30, 4:30, etc. - \n ###-- (entry 0 = title info: 1. site 2. populated days by date) \n ###----------------------------------------------------------------------\n calLocation.each do |rows| # step through slots containing multiple days (fist row is actually a header row!)\n timeData = rows[0][\"value\"] \n #<tr>\n maxPersonRowInAnySlot = 0 # initialised to 1 to step a row even if no tutor or student found.\n currentCol = 1\n ###--------------------------------------------------------------------\n ###------- step through each day for this time period -----------------\n ### (entry 0 = time of lesson)\n ###--------------------------------------------------------------------\n rows.each_with_index do |cells, cellIndex| # step through each day (first column is head column - for time slots!)\n if @compress \n unless usedColumnsIndex.include?(cellIndex) then\n next\n end \n end\n awaystudents = \"\"\n ###-------------------------------------------------------------------------------------------\n ###------------------- step through each lesson in this slot ---------------------------------\n ###-------------------------------------------------------------------------------------------\n if cells.key?(\"values\") then # lessons for this day in this slot \n if cells[\"values\"].respond_to?(:each) then # check we have lessons?\n # This is a slot with lessons, do I need to output a title.\n #byebug\n # First column for each day needs to have the width set\n # googlecolwidthitem.call(sheet_id, colStart, numberOfCols, width_pixels)\n myformat.push(googleColWidthItem.call(sheet_id, currentCol, 1, 130))\n myformat.push(googleColWidthItem.call(sheet_id_all, currentCol, 1, 130))\n myformat.push(googleColWidthItem.call(sheet_id, currentCol+3, 1, 200))\n myformat.push(googleColWidthItem.call(sheet_id_all, currentCol+3, 1, 200))\n title = calLocation[0][0]['value'] + # site name\n calLocation[0][cellIndex]['datetime'].strftime(\" %A %e/%-m/%y \") + # date\n rows[0]['value'] # sesson time \n mydata.push(googleBatchDataItem.call(sheet_name,\n baseSiteRow + baseSlotRowInSite - 1, \n currentCol,1,1,[[title]]))\n mydata.push(googleBatchDataItem.call(sheet_name_all,\n baseSiteRowAll + baseSlotRowInSite - 1,\n currentCol,1,1,[[title]]))\n # googleMergeCells.call(passed_sheet_id, rowStart, numOfRows, colStart, numberOfCols)\n myformat.push(googleMergeCells.call(sheet_id, baseSiteRow + baseSlotRowInSite - 1, 1,\n currentCol, 4))\n myformat.push(googleMergeCells.call(sheet_id_all, baseSiteRowAll + baseSlotRowInSite - 1, 1,\n currentCol, 4))\n # Format the header line (merged cells)\n # googlefomratCells.call(passed_sheet_id, rowStart, numOfRows, colStart, numberOfCols, fontSize)\n myformat.push(googleFormatCells.call(sheet_id, baseSiteRow + baseSlotRowInSite - 1, 1,\n currentCol, 4, 16))\n myformat.push(googleFormatCells.call(sheet_id_all, baseSiteRowAll + baseSlotRowInSite - 1, 1,\n currentCol, 4, 16))\n baseLessonRowInSlot = 0 # index of first lesson in this slot for this day\n cells[\"values\"].sort_by {|obj| [valueOrderStatus(obj),valueOrder(obj)] }.each do |entry| # step thru sorted lessons\n next if (entry.status != nil && [\"global\", \"park\"].include?(entry.status))\n currentTutorRowInLesson = 0\n if entry.tutors.respond_to?(:each) then\n entry.tutors.sort_by {|obj| obj.pname }.each do |tutor|\n if tutor then\n thistutrole = tutor.tutroles.where(lesson_id: entry.id).first\n if @tutorstatusforroster.include?(thistutrole.status) then # tutors of interest\n currentRow = currentTutorRowInLesson + baseLessonRowInSlot + baseSlotRowInSite + baseSiteRow\n currentRowAll = currentTutorRowInLesson + baseLessonRowInSlot + baseSlotRowInSite + baseSiteRowAll\n #<div class=\"tutorname tutorinline <%= set_class_status(tutor, entry) %>\">tutor: <%= tutor.pname %></div>\n tutorData = tutor.pname\n tutorDataAll = tutor.pname\n formatBreakPoints = []\n formatBreakPointsAll = []\n formatBreakPoints.push(0)\n formatBreakPointsAll.push(0)\n formatBreakPoints.push(tutor.pname.length)\n formatBreakPointsAll.push(tutor.pname.length)\n # tutor.subjects\n mysubjects = tutor.subjects\n mysubjects = mysubjects ? mysubjects : \"\"\n # thistutrole.comment\n # tutor.comment\n # Status: thistutrole.status Kind: thistutrole.kind\n mykind = thistutrole.kind\n mykind = mykind ? mykind : \"\"\n # don't diaplay subjects or kind for tutors on setup\n unless (entry.status == 'onSetup' && mykind == 'onSetup') ||\n (entry.status == 'onCall' && mykind == 'onCall')\n tutorData += ((mysubjects == \"\") ? \"\" : (\"\\n\" + mysubjects)) \n tutorData += ((mykind == \"\") ? \"\" : (\"\\n\" + mykind)) unless [\"standard\"].include?(mykind)\n tutorDataAll += ((mykind == \"\") ? \"\" : (\"\\n\" + mykind)) unless [\"standard\"].include?(mykind)\n end\n if thistutrole.comment != nil && thistutrole.comment != \"\"\n tutorData += \"\\n\" + thistutrole.comment\n end\n mycolour = kindcolours['tutor-kind-' + mykind]\n mycolour = mycolour.map {|p| p/255.0} \n myformat.push(googleTextFormatRun.call(sheet_id, currentRow, currentCol,\n tutorData, formatBreakPoints))\n myformat.push(googleTextFormatRun.call(sheet_id_all, currentRowAll, currentCol,\n tutorDataAll, formatBreakPointsAll))\n ###myformat.push(googleBGColourItem.call(sheet_id, currentRow, currentCol, 1, 1, mycolour))\n ###myformat.push(googleBGColourItem.call(sheet_id_all, currentRowAll, currentCol, 1, 1, mycolour))\n currentTutorRowInLesson += 1\n end # tutors of interest\n end\n #break\n end\n # keep track of the largest count of tutors or students in lesson.\n maxPersonRowInAnySlot = maxPersonRowInAnySlot > currentTutorRowInLesson + baseLessonRowInSlot ?\n maxPersonRowInAnySlot : currentTutorRowInLesson + baseLessonRowInSlot\n end\n currentStudentRowInLesson = 0\n currentStudentInLesson = 0\n studentLessonComments = \"\"\n if entry.students.respond_to?(:each) then\n entry.students.each do |student|\n if student then\n logger.debug \"student: \" + student.pname\n thisrole = student.roles.where(lesson_id: entry.id).first\n #logger.debug \"thisrole: \" + thisrole.inspect\n if ['away', 'awaycourtesy', 'bye', 'absent'].include?(thisrole.status) then \n displayname = student.pname + \" (\" + thisrole.status + \")\"\n awaystudents += awaystudents.length > 0 ? \"\\n\" + displayname : displayname\n end\n if @studentstatusforroster.include?(thisrole.status) then # students of interest\n #logger.debug \"*************processing student: \" + student.pname\n #logger.debug \"currentStudentInLesson: \" + currentStudentInLesson.inspect\n #logger.debug \"currentStudentRowInLesson + baseLessonRowInSlot + baseSlotRowInSite: \" +\n # currentStudentRowInLesson.to_s + \", \" + baseLessonRowInSlot.to_s + \", \" + baseSlotRowInSite.to_s\n currentRow = currentStudentRowInLesson + baseLessonRowInSlot + baseSlotRowInSite + baseSiteRow\n currentRowAll = currentStudentRowInLesson + baseLessonRowInSlot + baseSlotRowInSite + baseSiteRowAll\n #<div class=\"studentname studentinline <%= set_class_status(student, entry) %>\">student: <%= student.pname %></div>\n #logger.debug \"DataItem parameters: \" + currentRow.to_s + \", \" + currentCol.to_s + \", 1, 1, \" + student.pname \n formatBreakPoints = []\n formatBreakPoints.push(0)\n studentData = student.pname\n studentSex = student.sex == nil ? \"\" :\n (student.sex.downcase.include?(\"female\") ? \"(F) \" : (student.sex.downcase.include?(\"male\") ? \"(M) \" : \"\"))\n studentData += \" \" + studentSex\n #logger.debug \"student.pname: \" + student.pname \n #logger.debug \"lesson_id: \" + entry.id.to_s\n #formatBreakPoints.push(student.pname.length)\n #studentSubjects = \" Yr: \" + (student.year == nil ? \" \" : student.year.rjust(3)) +\n # \" | \" + (student.study == nil ? \"\" : student.study)\n #studentYear = \" Yr:\" + (student.year == nil ? student.year.rjust(3))\n studentYear = \" Yr:\" + (student.year == nil ? \"\" : student.year)\n studentSubjects = student.study == nil ? \"\" : student.study\n studentData += studentYear\n studentDataAll = studentData\n formatBreakPointsAll = formatBreakPoints\n studentData += \"\\n\" + studentSubjects\n formatBreakPoints.push(studentData.length)\n # thisrole.comment\n # student.comment\n # Status: thisrole.status Kind: thisrole.kind\n mykind = thisrole.kind\n mykind = mykind ? mykind : \"\"\n studentData += \" (\" + mykind + \")\" unless [\"standard\"].include?(mykind)\n if thisrole.comment != nil && thisrole.comment != \"\"\n studentLessonComments += student.pname + \":\\n\" + thisrole.comment + \"\\n\"\n #studentData += \"\\n\" + thisrole.comment\n end\n if student.comment != nil && student.comment != \"\"\n studentData += \"\\n\" + student.comment\n end\n mycolour = kindcolours['student-kind-' + mykind]\n mycolour = mycolour.map {|p| p/255.0}\n #myformat.push(googleTextFormatRun.call(sheet_id, currentRow, currentCol + 1,\n # studentData, formatBreakPoints))\n colOffset = 1 + (currentStudentInLesson % 2)\n myformat.push(googleTextFormatRun.call(sheet_id, currentRow, currentCol + colOffset,\n studentData, formatBreakPoints))\n myformat.push(googleTextFormatRun.call(sheet_id_all, currentRowAll, currentCol + colOffset,\n studentDataAll, formatBreakPointsAll))\n ###myformat.push(googleBGColourItem.call(sheet_id, currentRow, currentCol + colOffset, 1, 1, mycolour))\n ###myformat.push(googleBGColourItem.call(sheet_id_all, currentRowAll, currentCol + colOffset, 1, 1, mycolour))\n \n #byebug \n currentStudentRowInLesson += 1 if (currentStudentInLesson % 2) == 1 # odd\n currentStudentInLesson += 1\n end # students of interest\n end\n end\n # Need to get correct count of rows (rounding up is necessary)\n # derive currentStudentRowInLesson from the currentStudentInLesson\n currentStudentRowInLesson = (currentStudentInLesson % 2) == 0 ? \n currentStudentInLesson / 2 : (currentStudentInLesson / 2) + 1 \n \n # keep track of the largest count of tutors or students in lesson.\n maxPersonRowInAnySlot = maxPersonRowInAnySlot > currentStudentRowInLesson + baseLessonRowInSlot ?\n maxPersonRowInAnySlot : currentStudentRowInLesson + baseLessonRowInSlot\n end\n maxPersonRowInLesson = currentTutorRowInLesson > currentStudentRowInLesson ? \n currentTutorRowInLesson : currentStudentRowInLesson \n # put a border around this lesson if there were lessons with people\n if maxPersonRowInLesson > 0 then\n # put in lesson comments if there were tutors or students.\n #<div class=\"lessoncommenttext\"><% if entry.comments != nil && entry.comments != \"\" %><%= entry.comments %><% end %></div>\n #<div class=\"lessonstatusinfo\"><% if entry.status != nil && entry.status != \"\" %>Status: <%= entry.status %> <% end %></div>\n mylessoncomment = ''\n if entry.status != nil && entry.status != ''\n unless [\"standard\", \"routine\", \"flexible\"].include?(entry.status) # if this is a standard lesson \n mylessoncomment = entry.status + \"\\n\" # don't show the lesson status (kind)\n end\n end\n mylessoncommentAll = mylessoncomment\n if entry.comments != nil && entry.comments != \"\"\n mylessoncomment += entry.comments\n end\n mylessoncomment += studentLessonComments\n if mylessoncomment.length > 0\n mylessoncomment = mylessoncomment.sub(/\\n$/, '') # remove trailing new line\n mydata.push(googleBatchDataItem.call(sheet_name, currentRow, currentCol+3,1,1,[[mylessoncomment]]))\n mydata.push(googleBatchDataItem.call(sheet_name_all,currentRowAll,currentCol+3,1,1,[[mylessoncommentAll]]))\n end\n # ----- formatting of the lesson row within the slot ---------\n formatLesson.call(baseLessonRowInSlot, baseSlotRowInSite, baseSiteRow, baseSiteRowAll, currentCol, maxPersonRowInLesson)\n end\n ###baseLessonRowInSlot += maxPersonRowInLesson\n baseLessonRowInSlot += maxPersonRowInLesson\n #currentRow = maxPersonRowInAnySlot + baseLessonRowInSlot + baseSlotRowInSite + baseSiteRow # next empty row \n end # end looping sorted lessons within a day/slot\n end # responds to cell[\"values\"]\n elsif cells.key?(\"value\") then # just holds cell info (not lessons) to be shown\n currentRow = baseSlotRowInSite + baseSiteRow\n currentRowAll = baseSlotRowInSite + baseSiteRowAll\n #timeData = cells[\"value\"].to_s #if currentCol == 1 &&\n # cells[\"value\"] != nil # pick up the time\n #mydata.push(googleBatchDataItem.call(sheet_name, currentRow, currentCol,1,1,[[cells[\"value\"].to_s]]))\n #mydata.push(googleBatchDataItem.call(sheet_name_all,currentRowAll,currentCol,1,1,[[cells[\"value\"].to_s]]))\n end\n # Now add a dummy row at end of slot to show students who are away\n if awaystudents.length > 0\n currentRow = baseLessonRowInSlot + baseSlotRowInSite + baseSiteRow\n currentRowAll = baseLessonRowInSlot + baseSlotRowInSite + baseSiteRowAll\n mydata.push(googleBatchDataItem.call(sheet_name, currentRow, currentCol,1,1,[[\"Students Away\"]]))\n mydata.push(googleBatchDataItem.call(sheet_name_all, currentRowAll, currentCol,1,1,[[\"Students Away\"]]))\n myformat.push(googleFormatCells.call(sheet_id, currentRow, 1, currentCol, 1, 10))\n myformat.push(googleFormatCells.call(sheet_id_all, currentRowAll, 1, currentCol, 1, 10))\n mydata.push(googleBatchDataItem.call(sheet_name, currentRow, currentCol + 1,1,1,[[awaystudents]]))\n mydata.push(googleBatchDataItem.call(sheet_name_all, currentRowAll, currentCol + 1,1,1,[[awaystudents]]))\n maxPersonRowInLesson = 1\n formatLesson.call(baseLessonRowInSlot, baseSlotRowInSite, baseSiteRow,\n baseSiteRowAll, currentCol, maxPersonRowInLesson) # apply the standard formatting\n baseLessonRowInSlot += 1 # add another row for this\n # update tracking of the largest count of tutors or students in lesson.\n maxPersonRowInAnySlot = maxPersonRowInAnySlot > currentStudentRowInLesson + baseLessonRowInSlot ?\n maxPersonRowInAnySlot : currentStudentRowInLesson + baseLessonRowInSlot\n maxPersonRowInAnySlot = maxPersonRowInAnySlot > currentTutorRowInLesson + baseLessonRowInSlot ?\n maxPersonRowInAnySlot : currentTutorRowInLesson + baseLessonRowInSlot\n end\n #</td>\n currentCol += currentCol == 1 ? 1 : 4 # first column is title, rest have adjacent tutors & students.\n end # end looping days within slots\n #</tr>\n #byebug\n baseSlotRowInSite += maxPersonRowInAnySlot # set ready for next slot (row of days)\n if baseLessonRowInSlot == 0 && maxPersonRowInAnySlot == 0 then\n baseSlotRowInSite += 1 # cater for when no lessons with tutors or students of interest\n end\n # Add an extra row between slots - except the first title slot\n # Jasmine wanted no rows between slots so reduced from 2 to 1.\n baseSlotRowInSite += 1 unless baseSlotRowInSite == 1\n end # end looping slots\n holdRailsLoggerLevel = Rails.logger.level\n Rails.logger.level = 1 \n googleBatchDataUpdate.call(spreadsheet_id, mydata)\n googleBatchUpdate.call(myformat) \n Rails.logger.level = holdRailsLoggerLevel\n\n #</table>\n baseSiteRow += baseSlotRowInSite + 1 # +1 adds blank row between sites\n baseSiteRowAll += baseSlotRowInSite + 1 # +1 adds blank row between sites\n #<br>\n end # end looping sites\nend # end of testing option.\n ### correction ###return # return without rendering.\n end",
"def add_cell(cell)\n # If there is no row yet, create a blank array for it.\n @current_row ||= []\n # Add the cell to the end of the row.\n @current_row << cell\n end",
"def add_code(cheatsheet_db, language, type, code, comment)\n cheatsheet_db.execute(\"INSERT INTO #{language} (type, code, comment) VALUES (?, ?, ?)\", [type, code, comment])\nend",
"def insert_row(row_index=0)\n validate_workbook\n validate_nonnegative(row_index)\n\n increase_rows(row_index)\n\n @sheet_data.insert(row_index,Array.new(@sheet_data[row_index].size))\n\n row_num = row_index+1\n\n #copy cell styles from row above, (or below if first row)\n @sheet_data[row_index].each_index do |i|\n if row_index > 0\n old_cell = @sheet_data[row_index-1][i]\n else\n old_cell = @sheet_data[row_index+1][i]\n end\n\n unless old_cell.nil?\n #only add cell if style exists, not copying content\n\n if @row_styles[(row_num+1).to_s].nil?\n @row_styles[(row_num+1).to_s] = {:style=>0}\n end\n if old_cell.style_index != 0 && old_cell.style_index.to_s != @row_styles[(row_num+1).to_s][:style].to_s\n c = Cell.new(self,row_index,i)\n c.style_index = old_cell.style_index\n @sheet_data[row_index][i] = c\n end\n end\n end\n\n #copy row styles from row above, (or below if first row)\n (@row_styles.size+1).downto(row_num+1) do |i|\n @row_styles[i.to_s] = @row_styles[(i-1).to_s]\n end\n if row_index > 0\n @row_styles[row_num.to_s] = @row_styles[(row_num-1).to_s]\n else\n @row_styles[row_num.to_s] = nil#@row_styles[(row_num+1).to_s]\n end\n\n #update row value for all rows below\n (row_index+1).upto(@sheet_data.size-1) do |i|\n row = @sheet_data[i]\n row.each do |c|\n unless c.nil?\n c.row += 1\n end\n end\n end\n\n return @sheet_data[row_index]\n end",
"def raw_data_sheet\r\n @book.worksheet(WBF[:data_sheet])\r\n end",
"def data_responsible_person_sheet\r\n @book.worksheet(WBF[:people_sheet])\r\n end",
"def data_description_sheet \r\n @book.worksheet(WBF[:columns_sheet])\r\n end",
"def addWorksheetFromActiveRecord(sheetname, objectType, objects)\r\n\t \r\n\t objects = [objects] unless objects.class == Array\r\n\t \r\n\t item = [sheetname.to_s, objectType.to_s, objects]\r\n\t @worksheets += [item]\r\n\t end",
"def add_worksheet(name = '')\n name = check_sheetname(name)\n worksheet = Worksheet.new(self, @worksheets.size, name)\n @worksheets << worksheet\n worksheet\n end",
"def manual_add_entry\n address_book.add_entry(enter_name, enter_phone, enter_email)\n end",
"def write_tasks_to_spreadsheet(tasks, output_filename)\n # Initialize\n book = Spreadsheet::Workbook.new\n sheet = book.create_worksheet\n sheet.row(0).concat %w{Title Category Minimum Maximum Average}\n\n puts tasks\n\n tasks.each_with_index do |task, i|\n sheet.row(i + 1).push(task.title)\n sheet.row(i + 1).push(task.category)\n sheet.row(i + 1).push(task.min_price)\n sheet.row(i + 1).push(task.max_price)\n sheet.row(i + 1).push(task.avg_price)\n end\n\n # Format\n sheet.row(0).height = 14\n\n format = Spreadsheet::Format.new :color => :blue,\n :weight => :bold,\n :size => 14\n sheet.row(0).default_format = format\n\n # Write to file\n book.write output_filename\nend",
"def create!(name:)\n @sheet = Sheet.new(name)\n\n @sheet.save\n end",
"def create_cells\n sheet.row_ids.each {|i| cell_for_row(i) }\n end",
"def save_as_spreadsheet\n\nsession = GoogleDrive::Session.from_config(\"config.json\")\n# First worksheet of\n# https://docs.google.com/spreadsheets/d/19fXbxVaXn9knKHPAQMuuMsiKH_Q50cN5jlj6K3H8VQc/edit#gid=0\nws = session.spreadsheet_by_key(\"19fXbxVaXn9knKHPAQMuuMsiKH_Q50cN5jlj6K3H8VQc\").worksheets[0]\n\n# Gets content of A2 cell.\n#p ws[2, 1] #==> \"hoge\"\n\n# Changes content of cells.\n# Changes are not sent to the server until you call ws.save().\n\nx = 1\n$my_hash.each do |key, value|\n\tws[x, 1] = key\n\tws[x, 2] = value\n\tx +=1\nend\nws.save\n\n# Dumps all cells.\n(1..ws.num_rows).each do |row|\n (1..ws.num_cols).each do |col|\n p ws[row, col]\n end\nend\n\n# Yet another way to do so.\np ws.rows #==> [[\"fuga\", \"\"], [\"foo\", \"bar]]\n\n# Reloads the worksheet to get changes by other clients.\nws.reload\nend",
"def add_recipe(new_recipe)\n @recipearray << new_recipe\n update_csv\n end",
"def add(data)\n create(data)\n end",
"def add(data)\n create(data)\n end",
"def add_recipe(recipe)\n @recipes << recipe\n\n save_csv\n end",
"def create_spreadsheet\n @package = Axlsx::Package.new\n @workbook = @package.workbook\n\n selected_buildings = @report.user_buildings\n\n services_selected = selected_buildings.collect { |b| b.building_json['services'] }.flatten # s.collect { |s| s['code'].gsub('-', '.') }\n services_selected.uniq!\n\n @workbook.add_worksheet(name: 'Building Information') do |sheet|\n # sheet.add_row ['Buildings information']\n i = 0\n [['Buildings information', nil],\n ['Building Type', 'eg. General office - customer facing, non customer facing, call centre operations.'],\n ['Address', ''],\n [nil, nil], [nil, nil], [nil, nil],\n ['GIA', 'Gross Internal Area: Square Metre (GIA) per annum']].each do |label|\n vals = []\n vals << label[0] << label[1] << row(selected_buildings, i)\n vals.flatten!\n sheet.add_row vals\n i += 1\n end\n end\n\n # selected_services = services_selected.map { |s| s['code'].gsub('-', '.') }\n services = @report.list_of_services # @report.selected_services(selected_services)\n uom_values_for_selected_buildings = @report.uom_values(selected_buildings)\n\n uoms = CCS::FM::UnitsOfMeasurement.all.group_by(&:service_usage)\n uom2 = {}\n uoms.map { |u| u[0].each { |k| uom2[k] = u[1] } }\n\n @workbook.add_worksheet(name: 'Service Matrix') do |sheet|\n i = 1\n vals = ['Work Package', 'Service Reference', 'Service Name', 'Unit of Measure']\n selected_buildings.each do |building|\n vals << 'Building ' + i.to_s + ' - ' + building.building_json['name']\n i += 1\n end\n sheet.add_row vals\n\n work_package = ''\n services.sort_by { |s| [s.work_package_code, s.code[s.code.index('.') + 1..-1].to_i] }.each do |s|\n if work_package == s.work_package_code\n label = nil\n else\n label = 'Work Package ' + s.work_package_code + ' - ' + s.work_package.name\n end\n\n work_package = s.work_package_code\n\n vals = [label, s.code, s.name]\n\n vals_v = []\n vals_h = nil\n uom_labels_2d = []\n selected_buildings.each do |building|\n id = building.building_json['id']\n suv = uom_values_for_selected_buildings.select { |v| v['building_id'] == id && v['service_code'] == s.code }\n\n any_suv = uom_values_for_selected_buildings.select { |v| v['service_code'] == s.code }\n\n vals_h = []\n uom_labels = []\n if suv.empty?\n if uom2[s.code]\n uom_labels << uom2[s.code].last.spreadsheet_label\n elsif s.work_package_code == 'A' || s.work_package_code == 'B'\n uom_labels << nil\n elsif s.work_package_code == 'M' || s.work_package_code == 'N'\n uom_labels << 'Percentage of Year 1 Deliverables Value (excluding Management and Corporate Overhead, and Profit) at call-off'\n elsif any_suv.empty?\n uom_labels << 'service (per annum)'\n end\n\n vals_h << nil\n else\n suv.each do |v|\n if v['spreadsheet_label']\n uom_labels << v['spreadsheet_label']\n elsif uom2[s.code]\n uom_labels << uom2[s.code].last.spreadsheet_label\n end\n\n vals_h << v['uom_value']\n end\n end\n vals_v << vals_h\n uom_labels_2d << uom_labels\n rescue StandardError\n vals << '=NA()'\n end\n\n uom_labels_max = uom_labels_2d.max\n\n max_j = vals_v.map(&:length).max\n if max_j\n (0..max_j - 1).each do |j|\n vals << uom_labels_max[j]\n\n (0..vals_v.count - 1).each do |k|\n vals << vals_v[k][j]\n end\n sheet.add_row vals\n\n vals = [nil, s.code, s.name]\n end\n end\n # end\n work_package = s.work_package_code\n end\n end\n\n @workbook.add_worksheet(name: 'Procurement summary') do |sheet|\n date = sheet.styles.add_style(format_code: 'dd mmm yyyy', border: Axlsx::STYLE_THIN_BORDER)\n left_align = sheet.styles.add_style(alignment: { horizontal: :left })\n ccy = sheet.styles.add_style(format_code: '£#,##0')\n\n sheet.add_row ['CCS reference number & date/time of production of this document']\n sheet.add_row\n sheet.add_row ['1. Customer details']\n sheet.add_row ['Name']\n sheet.add_row ['Organisation']\n sheet.add_row ['Position']\n sheet.add_row ['Contact details']\n sheet.add_row\n sheet.add_row ['2. Contract requirements']\n sheet.add_row ['Initial Contract length', @report.contract_length_years, 'years'], style: [nil, nil, left_align]\n sheet.add_row ['Extensions']\n sheet.add_row\n sheet.add_row ['Tupe involvement', @report.tupe_flag]\n sheet.add_row\n sheet.add_row ['Contract start date', @report.start_date&.to_date], style: [nil, date]\n sheet.add_row\n sheet.add_row ['3. Price and sub-lot recommendation']\n sheet.add_row ['Assessed Value', @report.assessed_value], style: [nil, ccy]\n sheet.add_row ['Assessed value estimated accuracy'], style: [nil, ccy]\n sheet.add_row\n sheet.add_row ['Lot recommendation', @report.current_lot]\n sheet.add_row ['Direct award option']\n sheet.add_row\n # sheet.add_row ['4. Supplier Shortlist']\n label = '4. Supplier Shortlist'\n @report.selected_suppliers(@current_lot).each do |supplier|\n sheet.add_row [label, supplier.data['supplier_name']]\n label = nil\n end\n sheet.add_row\n\n # sheet.add_row ['5. Regions summary']\n label = '5. Regions summary'\n FacilitiesManagement::Region.all.select { |region| @data[:posted_locations].include? region.code }.each do |region|\n sheet.add_row [label, region.name]\n label = nil\n end\n sheet.add_row\n\n # sheet.add_row ['6 Services summary']\n # services = FacilitiesManagement::Service.where(code: @data['posted_services'])\n services = @report.list_of_services\n services.sort_by!(&:name)\n label = '6 Services summary'\n services.each do |s|\n sheet.add_row [label, s.name]\n label = nil\n end\n sheet.add_row\n end\n end",
"def descargar_calificaciones\n sitio_web = SitioWeb.sitio_actual(params[:asignatura_nombre],params[:semestre])\n\n if __es_del_grupo_docente\n\n Spreadsheet.client_encoding = 'UTF-8'\n book = Spreadsheet::Workbook.new\n\n bold = Spreadsheet::Format.new :weight => :bold\n \n sheets = []\n \n hoja = 0\n fila = 0\n col = 0\n\n tipos = [\"Teoría\",\"Práctica\",\"Laboratorio\",\"Otro\"]\n\n sitio_web.seccion_sitio_web.each_with_index do |seccion_sitio_web, index|\n sheet = book.create_worksheet :name => seccion_sitio_web.seccion.nombre.to_s\n fila = 0\n col = 0\n sheet[fila,col] = \"Sección: \"+seccion_sitio_web.seccion.nombre\n\n sheet.row(fila).set_format(col, bold)\n\n fila = 1\n sheet[fila,col] = \"Cédula\"\n sheet.row(fila).set_format(col, bold)\n col = 1\n\n sheet[fila,col] = \"Estudiante\"\n sheet.row(fila).set_format(col, bold)\n col = 2\n \n\n\n tipos.each do |tipo|\n if Evaluacion.where(:sitio_web_id => sitio_web.id, :tipo => tipo).size > 0\n Evaluacion.where(:sitio_web_id => sitio_web.id, :tipo => tipo).each do |evaluacion|\n sheet[fila,col] = evaluacion.nombre\n sheet.row(fila).set_format(col, bold)\n col += 1\n end\n sheet[fila,col] = \"Total \" + tipo\n sheet.row(fila).set_format(col, bold)\n col += 1\n end\n end\n\n sheet[fila,col] = \"Total\"\n sheet.row(fila).set_format(col, bold)\n\n \n\n fila += 1\n col = 0\n\n Usuario.order(:apellido, :nombre).where(:id => EstudianteSeccionSitioWeb.where(\n :seccion_sitio_web_id => seccion_sitio_web.id).collect{|x| x.estudiante_id}).each do |usuario|\n col = 0\n sheet[fila,col] = usuario.cedula\n col = 1\n sheet[fila,col] = (usuario.apellido + \" \" + usuario.nombre)\n col = 2\n\n total = 0\n suma = 0\n\n porcentaje = Evaluacion.where(:sitio_web_id => sitio_web.id).sum(\"valor\")\n\n tipos.each_with_index do |tipo|\n if Evaluacion.where(:sitio_web_id => sitio_web.id, :tipo => tipo).size > 0\n suma = 0\n Evaluacion.where(:sitio_web_id => sitio_web.id, :tipo => tipo).each do |evaluacion|\n if calificacion = Calificacion.where(:evaluacion_id => evaluacion.id, :estudiante_id => usuario.id).first\n if calificacion.calificacion\n sheet[fila,col] = calificacion.calificacion\n suma += (evaluacion.valor.to_f*calificacion.calificacion.to_f)\n end\n end\n col += 1\n end\n sheet[fila,col] = (suma/porcentaje).round(2)\n total += suma\n col += 1\n end\n end\n\n sheet[fila,col] = (total/porcentaje).round(2)\n sheet.row(fila).set_format(col, bold)\n fila += 1\n end\n\n sheets[hoja] = sheet\n end\n\n\n\n ruta = (\"#{Rails.root}/doc/calificaciones/calificaciones.xls\").to_s\n\n book.write ruta\n\n send_file ruta, :filename => \"Calificaciones de \"+sitio_web.asignatura.nombre + \" \" + sitio_web.periodo + \".xls\"\n\n return\n end\n\n flash[:error] = \"Parece que no se puede realizar la descarga en este momento. Inténtelo nuevamente.\"\n redirect_to :back\n end",
"def add_recipe(recipe)\n @recipes << recipe\n save_csv\n end",
"def write_excel\n #get param\n @user = index\n @hashtags= @user.hashtags\n #generate new Excel file\n workbook = RubyXL::Workbook.new\n worksheet=workbook[0]\n #save information for all post\n worksheet.add_cell(0, 1, \"ID\")\n worksheet.add_cell(0, 2, \"FOLLOWERS\")\n worksheet.add_cell(0, 3, \"LEVEL\")\n worksheet.add_cell(0, 4, \"SCORE\")\n worksheet.add_cell(0, 5, \"SUM\")\n worksheet.add_cell(1, 1, @user.username)\n worksheet.add_cell(1, 2, @user.followers)\n worksheet.add_cell(1, 3, @user.level)\n worksheet.add_cell(1, 4, @user.score)\n worksheet.add_cell(1, 5, @user.sum)\n #write hashtags\n worksheet.add_cell(3, 0, \"RANK\")\n worksheet.add_cell(3, 1, \"HASHTAG\")\n worksheet.add_cell(3, 2, \"TIMES\")\n worksheet.add_cell(3, 3, \"GLOBAL TIMES\")\n worksheet.add_cell(3, 4, \"VALUE\")\n worksheet.add_cell(3, 5, \"AVAILABILITY\")\n i=0\n for hashtag in @hashtags\n worksheet.add_cell(i+4, 0, i+1)\n worksheet.add_cell(i+4, 1, hashtag.hashtags)\n worksheet.add_cell(i+4, 2, hashtag.use_by_user)\n worksheet.add_cell(i+4, 3, hashtag.use_by_global)\n worksheet.add_cell(i+4, 4, hashtag.avai == \"0\" ? hashtag.use_by_global*hashtag.use_by_user : 0 )\n worksheet.add_cell(i+4, 5, hashtag.avai) \n i=i+1 \n end\n #send\n send_data( workbook.stream.string, :filename => \"#{@user.username}-#{@percentage}%-hashtags.xlsx\" ) \n end",
"def set_value(row,col,value,sheet=nil)\n sheet = @default_sheet unless sheet\n raise RangeError, \"sheet not set\" unless sheet\n #@@ Set and pass sheet_no\n begin\n sheet_no = sheets.index(sheet)+1\n rescue\n raise RangeError, \"invalid sheet '\"+sheet.to_s+\"'\"\n end\n row,col = normalize(row,col)\n @gs.add_to_cell_roo(row,col,value,sheet_no)\n # re-read the portion of the document that has changed\n if @cells_read[sheet]\n key = \"#{row},#{col}\"\n (value, value_type) = determine_datatype(value.to_s)\n @cell[sheet][key] = value \n @cell_type[sheet][key] = value_type \n end\n end",
"def data_sheet\n attachments.for('data_sheet')\n end",
"def batch_update(batch_data, cellfeed_uri)\n batch_uri = cellfeed_uri + '/batch'\n\n batch_request = <<FEED\n<?xml version=\"1.0\" encoding=\"utf-8\"?> \\\n <feed xmlns=\"http://www.w3.org/2005/Atom\" \\\n xmlns:batch=\"http://schemas.google.com/gdata/batch\" \\\n xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\" \\\n xmlns:gd=\"http://schemas.google.com/g/2005\">\n <id>#{cellfeed_uri}</id>\nFEED\n\n batch_data.each do |batch_request_data|\n version_string = get_version_string(cellfeed_uri + '/' +\n batch_request_data[:cell_id])\n data = batch_request_data[:data]\n batch_id = batch_request_data[:batch_id]\n cell_id = batch_request_data[:cell_id]\n row = batch_request_data[:cell_id][1,1]\n column = batch_request_data[:cell_id][3,1]\n edit_link = cellfeed_uri + '/' + cell_id + '/' + version_string\n \n batch_request<< <<ENTRY\n <entry>\n <gs:cell col=\"#{column}\" inputValue=\"#{data}\" row=\"#{row}\"/>\n <batch:id>#{batch_id}</batch:id>\n <batch:operation type=\"update\" />\n <id>#{cellfeed_uri}/#{cell_id}</id>\n <link href=\"#{edit_link}\" rel=\"edit\" type=\"application/atom+xml\" />\n </entry>\nENTRY\n end\n \n batch_request << '</feed>'\n return post(batch_uri, batch_request)\n end",
"def insert_row(row_index = 0)\n validate_workbook\n ensure_cell_exists(row_index)\n\n old_row = new_cells = nil\n\n if row_index > 0 then\n old_row = sheet_data.rows[row_index - 1]\n if old_row then\n new_cells = old_row.cells.collect { |c|\n if c.nil? then nil\n else nc = RubyXL::Cell.new(:style_index => c.style_index)\n nc.worksheet = self\n nc\n end\n }\n end\n end\n\n row0 = sheet_data.rows[0]\n new_cells ||= Array.new((row0 && row0.cells.size) || 0)\n\n sheet_data.rows.insert(row_index, nil)\n new_row = add_row(row_index, :cells => new_cells, :style_index => old_row && old_row.style_index)\n\n # Update row values for all rows below\n row_index.upto(sheet_data.rows.size - 1) { |i|\n row = sheet_data.rows[i]\n next if row.nil?\n row.cells.each { |c| c.row = i unless c.nil? }\n }\n\n return new_row\n end",
"def todas_personas\n down = \"/public/reportes/\"\n reportes = RAILS_ROOT + down\n tiempo = Time.zone.now.to_s(:number)\n @personas = Persona.find :all, \n :select=>\"id, nombre, apepat, apemat, familia_id, sexo, nacimiento\",\n :include=>[\"familia\", \"relacions\"]\n #creo la hoja en excell\n book = Spreadsheet::Workbook.new\n sh1 = book.create_worksheet :name => \"Personas\"\n #relleno la hoja\n sh1.row(0).concat( [\"Ficha persona\",\"nombre\",\"apepat\",\"apemat\",\"sexo\",\"nacimiento\",\"Ficha familia\"] +\n [\"p apepat\",\"p nombre\",\"m apepat\",\"m nombre\"] + \n [\"telefonos\",\"direccion1\",\"distrito\",\"ciudad\", \"region\",\"pais\"] + \n [\"Ficha inst\",\"institucion\"]\n )\n #rellenando las filas con los datos\n i = 0\n @personas.each do |p|\n i=i+1\n #guardo el link a la ficha de la persona\n sh1.row(i).push Spreadsheet::Link.new(url_for(p),p.id.to_s)\n sh1.row(i).push p.nombre, p.apepat, p.apemat, p.sexo, p.nacimiento\n #la familia\n #guardo el link a la familia\n if p.familia_id? \n sh1.row(i).push Spreadsheet::Link.new(url_for(p.familia),p.familia_id.to_s)\n else\n sh1.row(i).push \"-sin familia-\"\n end\n padre = nil\n madre = nil\n padre = p.familia.padre if p.familia_id and p.familia\n padre ||= Persona.new(:nombre=>\"-sin padre-\")\n madre = p.familia.madre if p.familia_id and p.familia\n madre ||= Persona.new(:nombre=>\"-sin madre-\")\n sh1.row(i).push(padre.apepat, padre.nombre)\n sh1.row(i).push(madre.apepat, madre.nombre)\n #direccion\n d = p.direccion\n sh1.row(i).push d.telefonos,d.street_1,d.street_2,d.city,d.region_name,d.country_with_region_check\n #institucion\n ins = p.institucions.first \n unless ins == nil\n sh1.row(i).push Spreadsheet::Link.new(url_for(ins),ins.id.to_s), ins\n else\n sh1.row(i).push \"\", \"-sin institución-\"\n end\n\n end\n #guardo\n book.write reportes + \"#{tiempo}.xls\"\n @download = \"/reportes/#{tiempo}.xls\"\n\n end",
"def loadtest2\n returned_authorisation = googleauthorisation(request)\n if returned_authorisation[\"authorizationurl\"]\n redirect_to returned_authorisation[\"authorizationurl\"] and return\n end\n service = returned_authorisation[\"service\"]\n#-----------------------------------------------------------------\n# Create a new spreadsheet -works and tested\n #request_body = Google::Apis::SheetsV4::Spreadsheet.new\n #response = service.create_spreadsheet(request_body)\n #ss = response\n #spreadsheet_id = ss.spreadsheet_id\n#-----------------------------------------------------------------\n\n\n#-----------------------------------------------------------------\n# Use an existing previously created spreadsheet\n# Only need the id to make use of this.\n spreadsheet_id = '1VHNfTl0Qxok1ZgBD2Rwby-dqxihgSspA0InqS5dTXNI'\n#-----------------------------------------------------------------\n sheet_name = \"Sheet1\"\n\n# ************ update spreadsheet title ************************\n# https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate \n spreadsheet_title = \"Testing Updates from BIT Server\"\n request_body = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new\n myussp = {\"properties\": {\"title\": spreadsheet_title}, \"fields\": \"*\" }\n request_body.requests = [{\"update_spreadsheet_properties\": myussp }]\n result = service.batch_update_spreadsheet(spreadsheet_id, request_body, {})\n\n\n\n\n# ************ delete all cells (rows) in a sheet ****************************\n# https://www.rubydoc.info/github/google/google-api-ruby-client/Google/Apis/SheetsV4/Request#delete_range-instance_method \n \tgridrange = {\n \t sheet_id: 0,\n \t start_row_index: 0,\n# \t end_row_index: 1,\n \t start_column_index: 0,\n# \t end_column_index: 2\n \t }\n requests = []\n requests.push(\n {\n delete_range:{\n range: gridrange,\n shift_dimension: \"ROWS\"\n }\n }\n )\n body = {requests: requests}\n result = service.batch_update_spreadsheet(spreadsheet_id, body, {})\n\n# ************ update values using update_spreadsheet_value ****************************\n# doco: https://www.rubydoc.info/github/google/google-api-ruby-client/Google%2FApis%2FSheetsV4%2FSheetsService%3Aupdate_spreadsheet_value \n range = \"#{sheet_name}!A1:B1\"\n request_body = Google::Apis::SheetsV4::ValueRange.new\n request_body.values = [[\"update_spreadsheet_value\",\"test data - this row will get a background colour\"]]\n request_body.major_dimension = \"ROWS\"\n result = service.update_spreadsheet_value(spreadsheet_id, range, request_body, \n {value_input_option: 'USER_ENTERED'})\n logger.debug \"update_spreadsheet_value completed\"\n\n# ************ update values using update_spreadsheet_value ****************************\n range = \"#{sheet_name}!A2:B3\"\n mydata = [\n {\n range: range,\n majorDimension: 'ROWS',\n values: [\n [\"spreadsheet_values_batchUpdate\", \"test data\"],\n [\"spreadsheet_values_batchUpdate\", \"third row\"]\n ]\n }\n ]\n request_body = Google::Apis::SheetsV4::BatchUpdateValuesRequest.new\n request_body.value_input_option = 'USER_ENTERED'\n request_body.data = mydata\n result = service.batch_update_values(spreadsheet_id, request_body, {})\n\n# ******** update background colours using batch_update_spreadsheet ********\n \tgridrange = {\n \t sheet_id: 0,\n \t start_row_index: 0,\n \t end_row_index: 1,\n \t start_column_index: 0,\n \t end_column_index: 2\n \t }\n requests = []\n requests.push(\n {\n repeat_cell: {\n \t range: gridrange,\n cell:\n {\n \t user_entered_format:\n \t {\n \t\t text_format: {bold: true},\n \t\t background_color:\n \t\t {\n \t\t\t red: 0.0,\n \t\t\t green: 1.0,\n \t\t\t blue: 0.0\n \t\t }\n \t }\n \t },\n fields: \"user_entered_format(background_color, text_format.bold)\"\n }\n }\n )\n body = {requests: requests}\n result = service.batch_update_spreadsheet(spreadsheet_id, body, {})\n\n# ******** autorezise columns using batch_update_spreadsheet ********\n# https://developers.google.com/sheets/api/samples/rowcolumn \n requests = []\n requests.push(\n {\n auto_resize_dimensions: {\n dimensions:\n {\n \t dimension: \"COLUMNS\",\n \t sheet_id: 0,\n end_index: 2,\n \t start_index: 0\n \t },\n }\n }\n )\n body = {requests: requests}\n result = service.batch_update_spreadsheet(spreadsheet_id, body, {})\n\n# ******** adjust columns width using batch_update_spreadsheet ********\n# https://developers.google.com/sheets/api/samples/rowcolumn \n requests = []\n requests.push(\n {\n update_dimension_properties: {\n range:\n {\n \t dimension: \"COLUMNS\",\n \t sheet_id: 0,\n end_index: 2,\n \t start_index: 0\n \t },\n \t properties: {\n \t pixel_size: 160\n \t },\n \t fields: \"pixelSize\"\n }\n }\n )\n body = {requests: requests}\n result = service.batch_update_spreadsheet(spreadsheet_id, body, {})\n\n end",
"def add_data_elements\n \n end",
"def addrow(data, opts=DEF_ADD_ROW_OPTS)\n\t\t#opts=DEF_ADD_ROW_OPTS.merge(opts)\n\t\tvalidate_row(data)\n\t\t@rows << data\n\tend",
"def add_dat\n add_daily_attendance(:dat)\n end",
"def parse_xlsx\n 2.upto(@spreadsheet.last_row).each do |row_index|\n row = info_hash(row_index)\n \n unless row.nil?\n @data[row[:name]] ||= {\n code: row[:code],\n worlds: [],\n areas: [],\n positions: []\n }\n\n @data[row[:name]][:worlds] << row[:world] if !row[:world].blank? && !@data[row[:name]][:worlds].include?(row[:world])\n @data[row[:name]][:areas] << row[:area] if !row[:area].blank? && !@data[row[:name]][:areas].include?(row[:area])\n @data[row[:name]][:positions] << row[:position] if !row[:position].blank? && !@data[row[:name]][:positions].include?(row[:position])\n end\n end\n end",
"def outputRow (sid, type) \n\n $sumSheet.add_row [ sid, type, \"1\", \"2\", \"3\", \"4\", \"5\" ], :style => $black_cell \n\n if sid.odd?\n link = \"A#{$curRow}\" \n puts \"outputRow: sid: #{sid}, link: #{link}\" \n # Setting the style for the link will apply the xf that we created in the Main Program block\n $sumSheet[link].style = $blue_link\n $sumSheet.add_hyperlink :location => \"'Log'!A#{$curRow}\", :target => :sheet, :ref => link \n end\n $curRow += 1 \nend",
"def add_cell(value=\"\", options={})\n c = Cell.new(self, value, options)\n update_auto_fit_data\n c\n end",
"def generate_excel(collections, heading, options={})\n message = \"\"\n xls_file = Spreadsheet::Workbook.new\n sheet = xls_file.create_worksheet :name => \"Sheet 1\"\n red = Spreadsheet::Format.new :color => 'black', :size => 10, :align => 'center', :pattern_fg_color => :red, :pattern => 1\n begin\n collections.each_with_index do |err, index|\n err.each do |r|\n #next unless r.present?\n sheet.row(index).push r\n end\n end\n rescue Exception => e\n message = e.message\n end\n blob = StringIO.new(\"\")\n #blob = message if !message.present?\n xls_file.write blob\n blob.string\n end",
"def increase_rows(row)\n @sheet_data.size.upto(row) do\n @sheet_data << Array.new(@sheet_data[0].size)\n end\n end",
"def get_the_name_and_email_and_put_it_in_spreadsheet(session, excel, tab)\n\n\t\t#on recupere le fichier mairie de notre drive\n\t\ttownhall_file = session.spreadsheet_by_title(excel)\n\n\t\t#je me positionne dans le 1er onglet de mon fichier spreadsheet drive (excel drive)\n\t\tonglet1 = townhall_file.worksheets[0]\n\n\t\t# on demarre\n\t\t# i à 2 car la 1ere ligne est la ligne qui contient les noms de colonne , i va de 2 à taille du tableau de hash soit 185+2=187\n\t\t# le hash est sous cette forme {nom_mairie:email_mairie}\n\t\ti=2\n\t\t#binding.pry\n\t\ttab.each do |element_du_tab_est_hash|\n\t\t\telement_du_tab_est_hash.each do |k,v|\n\t\t\t\tonglet1[i,1] = k\n\t\t\t\tonglet1[i,2] = v\n\t\t\tend\n\t\t\t#incrementation des lignes \"i\" en dehors des boucles d'insertion des valeurs\n\t\t\ti += 1\n\t\tend\n\t\t#on envoie les donnees au sheet drive :\n\t\tonglet1.save\n\t\treturn onglet1\n\tend",
"def add_cell(value = '', options = {})\n c = Cell.new(self, value, options)\n self << c\n worksheet.send(:update_column_info, self, [])\n c\n end",
"def goal_sheet_input\n goal_ranges.each do |range|\n @range = range\n @goal_sheet = @xlsx.sheet(@range).parse(header_search: [])\n create_goals\n end\n end",
"def insert_row(row_index = 0)\n validate_workbook\n ensure_cell_exists(row_index)\n\n old_row = new_cells = nil\n\n if row_index > 0 then\n old_row = sheet_data.rows[row_index - 1]\n if old_row then\n new_cells = old_row.cells.collect { |c|\n if c.nil? then nil\n else nc = RubyXL::Cell.new(:style_index => c.style_index)\n nc.worksheet = self\n nc\n end\n }\n end\n end\n\n row0 = sheet_data.rows[0]\n new_cells ||= Array.new((row0 && row0.cells.size) || 0)\n\n sheet_data.rows.insert(row_index, nil)\n new_row = add_row(row_index, :cells => new_cells, :style_index => old_row && old_row.style_index)\n\n # Update row values for all rows below\n row_index.upto(sheet_data.rows.size - 1) { |r|\n row = sheet_data.rows[r]\n next if row.nil?\n row.cells.each_with_index { |cell, c|\n next if cell.nil?\n cell.r = RubyXL::Reference.new(r, c)\n }\n }\n\n return new_row\n end",
"def dup\n Data.new( sheet, @data.map(&:dup) )\n end",
"def change_contents(data, formula=nil)\n validate_worksheet\n @datatype='str'\n if data.is_a?(Date) || data.is_a?(DateTime)\n data = @workbook.date_to_num(data)\n end\n if (data.is_a?Integer) || (data.is_a?Float)\n @datatype = ''\n end\n @value=data\n @formula=formula\n end",
"def add(type, *data)\n df = DataFrame.new({x: data[0], y: data[1], z: data[2]})\n return add_with_df(df, type, :x, :y, :z)\n end",
"def excel_parse\n excel = Spreadsheet.open \"clientes.xls\"\n hoja = excel.worksheet 0\n\n# @filas = []\n hoja.each 1 do |fila|\n #solo añadimos aquellos clientes que no existan, comprobamos que el codigo no exista\n #\n ficha = Cliente.find_by_codigo( fila[4])\n if not ficha then\n ficha = Cliente.new\n ficha.user_id = 1 #usuario de test, para cuando sea MMO\n ficha.codigo = fila[4]\n ficha.nombre = fila[3]\n ficha.provincia = fila[25]\n ficha.direccion = fila[26]\n ficha.ciudad = fila[27]\n ficha.cp = fila[28]\n ficha.telefono = fila[29]\n ficha.grupo_id = fila[1]\n ficha.notas = \"\"\n ficha.save!\n# @filas << ficha\n end\n\n #parseamos la marca a la que pertenece la venta\n m = Marca.find_by_codigo( fila[10])\n if not m then\n m = Marca.new\n m.codigo = fila[10]\n m.user = 0\n m.save!\n end\n\n #parseamos las ventas de esa fila suponiendo que el cliente existe\n vdata = Venta.new do |v|\n v.user= 1\n v.cliente= ficha.id\n #v.marca = Marca.find_by_codigo(fila[10]).id\n v.marca = m.id\n v.piezas_12m = fila[23]\n v.piezas_fact_last_mes = fila[12]\n v.piezas_last_pedido = fila[18]\n v.piezas_pendientes = fila[11]\n end\n vdata.save!\n end\n end",
"def add_row(obj)\n obj = DataRow.new(obj) unless obj.is_a?(DataRow)\n raise(StandardError, \"wrong row size #{obj.cells_count}, should be #{columns_count})\") if obj.cells_count != columns_count\n obj.close\n @rows << obj\n self\n end",
"def add_work_item(data)\n name = @table_name.to_s\n sql = @model.from(name.to_sym).insert_sql(\n description: data[:description],\n guide: data[:guide],\n status: data[:status],\n username: data[:name],\n archived: 0\n )\n sql = _format_sql(sql)\n @logger.info(\"Prepared POST query: #{sql}\")\n response = run_statement(sql, \"post\")\n id = response[0][:long_value]\n @logger.info(\"Successfully created work_item_id: #{id}\")\n id\n end",
"def update\n fname = @import.filename\n bs, _, ext = fname.rpartition(\".\")\n outfname = \"#{bs}-out.#{ext}\"\n\n book = RubyXL::Parser.parse(fname)\n master = book[\"Master\"]\n\n # Write out the meeting names unconditionally into Excel row 2 of the Master tab\n meetnamerow = master[1]\n col = 6\n Meeting.order(:date).each do |mtg|\n if master[2].nil? || master[2][col].nil? || master[2][col].value.blank?\n flash[:error] =\n \"Missing prepared column in Master sheet, row 3, column #{col + 1}\"\n end\n # Overwrite existing information with the information from the database\n fmt = if mtg.date.day == 1\n \"%B %Y \"\n else\n \"%-d %B %Y \"\n end\n master.add_or_chg(1, col, \"#{mtg.date.strftime(fmt)}#{mtg.meetingtype} Meeting\")\n meetnamerow[col].style_index = meetnamerow[col - 1].style_index if col > 6 # copy previous cell's style\n col += 1\n end\n\n # Go through the database Items in numerical order:\n # 1. In a row on the Master sheet, write out the item's properties and then its per-meeting statuses.\n # Handle missing meeting statuses including at the end of the line.\n # NOTE: With the current release of RubyXL (3.3.12), there's nothing we can do about the hyperlinks.\n # They are properties of the sheet, not the cell.\n # RubyXL::Reference.ref2ind(master.hyperlinks.first.ref.to_s)\n # master.relationship_container.find_by_rid(master.hyperlinks.first.r_id)\n # 2. Write three rows on the Minutes sheet.\n rowno = 2\n Item.order(:number).each do |item|\n # Change_contents spoils the shared string thing, so don't write unless you have to.\n # Anyhow, when writing, rows and columns might not exist.\n master.add_or_chg(rowno, 0, item.number.to_s) # Use this method to ensure that the row exists\n master.add_or_chg(rowno, 1, item.date.strftime(\"%d-%b-%Y\"))\n master.add_or_chg(rowno, 2, item.standard)\n master.add_or_chg(rowno, 3, item.clause)\n master.add_or_chg(rowno, 4, item.subject)\n master.add_or_chg(rowno, 5, item.draft)\n # There may not be a minutes entry corresponding to each meeting (=column), so keep a track of the item's current\n # status and use that where no minutes entry exists.\n current_sts = \"-\"\n colno = 6\n Meeting.order(:date).each do |mtg|\n min = item.minutes.where(\"minutes.meeting_id = ?\", mtg.id).first\n current_sts = min.minst.code if min&.minst\n if master[rowno][colno].nil? || master[rowno][colno].blank?\n flash[:error] =\n \"Missing prepared column in Master sheet, row #{rowno + 1}, column #{colno + 1}\"\n end\n master.add_or_chg(rowno, colno, current_sts)\n colno += 1\n end\n # Write hash signs on the remaining cells in the row, adding new cells to the right if necessary.\n # Issue #29: master[rowno].cells.count comes out as a big number (16384) for unused rows.\n # Calculate the last column number instead.\n # Also, if there are more meetings than the input spreadsheet allowed for, there won't be cells for each meeting.\n lastcolno = Meeting.count + 6\n (colno..lastcolno).each do |colcolno|\n if master[rowno][colcolno].nil?\n master.add_cell(rowno, colcolno, \"#\")\n else\n master[rowno][colcolno].chg_cell(\"#\")\n end\n end\n # Add a hash at the end of the row if there isn't one\n unless master[rowno][lastcolno + 1] && master[rowno][lastcolno + 1].value == \"#\"\n master.add_cell(rowno, lastcolno + 1, \"#\")\n end\n rowno += 1\n end\n # Fill the rest of the rows with hash signs. Make sure there's at least one row of hashes.\n make_master_hash_row(master, rowno) unless master[rowno] && master[rowno][1] && master[rowno][1].value == \"#\"\n ((rowno + 1)..(master.count - 1)).each do |r|\n make_master_hash_row(master, r)\n end\n\n minutes = book[\"Minutes\"]\n rowno = 1\n Item.order(:number).each do |item|\n minutes.add_or_chg(rowno, 1, item.number.to_s)\n colno = 3\n Meeting.order(:date).each do |mtg|\n min = item.minutes.where(\"minutes.meeting_id = ?\", mtg.id).first\n if min && !min.date.blank?\n datestr = min.date.strftime(\"%-d-%b-%Y\")\n minutes.add_or_chg(rowno, colno, datestr)\n else\n minutes.delete_cell(rowno, colno)\n end\n if min && !min.text.blank?\n minutes.add_or_chg(rowno + 1, colno, min.text)\n else\n minutes.delete_cell(rowno + 1, colno)\n end\n if min && (!min.date.blank? || !min.text.blank?)\n minutes.add_or_chg(rowno + 2, colno, \"#\")\n else\n minutes.delete_cell(rowno + 2, colno)\n end\n colno += 1\n end\n rowno += 3\n end\n # Delete the rest of the rows, making sure the last row has a single '#' in the number column.\n # Note that delete_row pushes cells up, so we delete the same numbered row repeatedly.\n (rowno..(minutes.count - 1)).each { |_r| minutes.delete_row(rowno) }\n minutes.add_cell(rowno, 0, \"\")\n minutes.add_cell(rowno, 1, \"#\")\n\n book.write(outfname)\n\n respond_to do |format|\n format.html do\n response.headers[\"Content-Length\"] = File.size(outfname).to_s\n send_file(outfname, type: @import.content_type, x_sendfile: true)\n return\n end\n format.json { render :show, status: :ok, location: @import }\n end\n end",
"def index\n #@spreadsheet = Spreadsheet.new()\n #@spreadsheets = Spreadsheet.all\n end"
] |
[
"0.7351838",
"0.6927981",
"0.6913316",
"0.6859386",
"0.68364173",
"0.6580632",
"0.636083",
"0.6313194",
"0.6261162",
"0.61709356",
"0.61571294",
"0.61534846",
"0.61332995",
"0.6123624",
"0.6101902",
"0.602228",
"0.60148335",
"0.5997898",
"0.5995702",
"0.59706223",
"0.59587747",
"0.59422034",
"0.59213716",
"0.59213716",
"0.5911223",
"0.58950925",
"0.585428",
"0.58533466",
"0.5851086",
"0.5838603",
"0.58296883",
"0.5820754",
"0.5806856",
"0.5802485",
"0.5801636",
"0.5789431",
"0.5783248",
"0.577822",
"0.577822",
"0.577822",
"0.5778092",
"0.57313585",
"0.5729397",
"0.57189035",
"0.5713243",
"0.5709498",
"0.570053",
"0.5684397",
"0.56826496",
"0.5663838",
"0.5647598",
"0.5624263",
"0.5609112",
"0.56083107",
"0.56024355",
"0.56007665",
"0.5597671",
"0.55966365",
"0.5594453",
"0.558331",
"0.558113",
"0.5574733",
"0.5549661",
"0.5541924",
"0.5540405",
"0.5535953",
"0.55192465",
"0.5512404",
"0.5512404",
"0.5505065",
"0.54911333",
"0.5490403",
"0.54902387",
"0.54901946",
"0.54826665",
"0.54773694",
"0.5470692",
"0.54702765",
"0.54626125",
"0.5460478",
"0.5448171",
"0.54462546",
"0.54419833",
"0.5437986",
"0.5436936",
"0.5428376",
"0.54241496",
"0.5423129",
"0.54213375",
"0.5412574",
"0.54030657",
"0.5394979",
"0.53871197",
"0.53686875",
"0.53669286",
"0.5366687",
"0.53566754",
"0.53562987",
"0.53512394",
"0.5350683"
] |
0.539653
|
91
|
Returns a key that will be used to group ids into batches.
|
def group_key(id)
nil
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def to_key\n [id.to_s]\n end",
"def to_key\n [id]\n end",
"def to_key\n key = id\n [key] if key\n end",
"def batch_key(_record)\n raise \"Implement in child\"\n end",
"def redis_key_for(id)\n \"#{redis_prefix}:#{Array(id).join(':')}\"\n end",
"def to_key\n [object_id]\n end",
"def key_name\n \"#{prefix}:#{@id}\"\n end",
"def batch_key\n case self.scope\n when 'outgoing'\n key = \"outgoing-\"\n key += self.recipient_domain.to_s\n when 'incoming'\n key = \"incoming-\"\n key += \"rt:#{self.route_id}-ep:#{self.endpoint_id}-#{self.endpoint_type}\"\n else\n key = nil\n end\n key\n end",
"def to_key\n new? ? [] : [id]\n end",
"def key\n 'groupid'\n end",
"def to_key\n new? ? [] : [id]\n end",
"def key(list_id)\n key_format % list_id\n end",
"def build_key(last_part)\n [scope[:id], super].compact.join(\"_\")\n end",
"def to_key # :nodoc:\n id\n end",
"def redis_id_seq_key(id = [])\n postfix = Array(id).join(':')\n \"#{redis_prefix}_id_seq#{\":#{postfix}\" if postfix.present?}\"\n end",
"def to_key\n persisted? ? [id] : nil\n end",
"def to_key\n persisted? ? [id] : nil\n end",
"def key\n @registry.send :_key, @worker_group, @registry.localize(ppid)\n end",
"def to_key\n _persisted_obj ? [id] : nil\n end",
"def cache_key(*ids)\n ids.join(':')\n end",
"def gid\n self.class.key(id)\n end",
"def gid\n self.class.key(id)\n end",
"def id_key_for(model_class)\n get_key('ID_KEY', model_class) + '_id'\n end",
"def key_id; end",
"def counter_key\n @counter_key ||= [*name.downcase.split(\"::\"), :idcnt].join(\":\")\n end",
"def generate_key; end",
"def _hashback_id_key\n self.__send__(self.class.__send__(:class_variable_get, :@@_key_method_sym))\n end",
"def key\n raise MissingID if not defined?(@id)\n model.key[id]\n end",
"def to_key\n persisted? ? id.to_s : nil\n end",
"def create_last_message_key(user, group)\n user.id.to_s + group.uuid\n end",
"def multi_id_key\n key = :id\n if parent?\n key = resources_configuration[symbols_for_association_chain[-1]][:param]\n end\n key\n end",
"def to_key\n []\n end",
"def key(name = nil)\n \"#{@id}:#{name}\"\n end",
"def cache_key(pk)\n \"#{self}:#{Array(pk).join(',')}\"\n end",
"def key(msg_id, suffix)\n \"#{msg_id}:#{suffix}\"\n end",
"def key\n add_spaces(@key, chars_per_group)\n end",
"def to_key; end",
"def key\n @key ||= [model_name, operation, scope]\n end",
"def key\n to_a[0..(num_key_fields-1)].join(\"-\")\n end",
"def batch_key\n key = \"validation-\"\n key += \"rt:#{self.route_id}-ep:#{self.endpoint_id}-#{self.endpoint_type}\"\n key\n end",
"def key_id\n return @key_id\n end",
"def key_id\n return @key_id\n end",
"def key_id\n return @key_id\n end",
"def group_through_identifier\n \"#{name.downcase}_groups\".to_sym\n end",
"def cache_key(pk)\n raise(Error, 'no primary key for this record') unless pk.is_a?(Array) ? pk.all? : pk\n \"#{cache_key_prefix}:#{Array(pk).join(',')}\"\n end",
"def key\n id\n end",
"def key\n @key ||= name.to_s\n end",
"def cache_key(id); end",
"def key\n self.id\n end",
"def key\n self.id\n end",
"def key\n self.id\n end",
"def enriched_key\n \"backend.#{backend.id}.#{id}\"\n end",
"def gen_node_key(num)\n \"node#{num}\".to_sym\nend",
"def build_item_key(item)\n if options[:id_namespace]\n \"#{options[:id_namespace]}_#{item.key}\"\n else\n item.key\n end\n end",
"def build_item_key(item)\n if options[:id_namespace]\n \"#{options[:id_namespace]}_#{item.key}\"\n else\n item.key\n end\n end",
"def generate_key\n proposed_key = nil\n\n loop do\n num_part = rand(10**7).to_s.rjust(7, \"0\")\n proposed_key = \"#{IDB_CONFIG[:key_prefix]}-#{num_part}\"\n break unless self.class.find_by(key: proposed_key)\n end\n proposed_key\n end",
"def key_for(node)\n \"#{id}-#{node.id}\"\n end",
"def dataset_key\n :id\n end",
"def _find_valid_key\n _key = name.underscore.parameterize\n index = 0\n while true\n break unless UserGroup.where(key: _key).where.not(id: id).any?\n _key = \"#{name.underscore.parameterize}-#{index}\"\n index += 1\n end\n _key\n end",
"def key(name)\n @unique_key = name\n end",
"def default_key\n :\"#{self[:name]}_id\"\n end",
"def gen_key(record)\n return Digest::SHA2.hexdigest(record.to_s)\n end",
"def get_cache_key(id)\n memcache_key_object.key_template % @options.merge(id: id)\n end",
"def get_cache_key(id)\n memcache_key_object.key_template % @options.merge(id: id)\n end",
"def key\n self.class._key\n end",
"def group_by_key(num_partitions=nil)\n create_combiner = 'lambda{|item| [item]}'\n merge_value = 'lambda{|combiner, item| combiner << item; combiner}'\n merge_combiners = 'lambda{|combiner_1, combiner_2| combiner_1 += combiner_2; combiner_1}'\n\n combine_by_key(create_combiner, merge_value, merge_combiners, num_partitions)\n end",
"def index_key\n GlobalIndex.index_key_for_chunk(self)\n end",
"def key_for(id)\n lamb = @key_lambda || lambda { |id| \"deferred-job:#{id}\" }\n lamb.call id\n end",
"def key_partition\n Dynamoid::Config.partitioning? ? \".#{Random.rand(Dynamoid::Config.partition_size)}\" : ''\n end",
"def to_bson_key\n to_s.to_bson_key\n end",
"def id_from_key(key)\n @key_to_id[key]\n end",
"def prefix_key(key)\n if self.instance_id\n [KEY_PREFIX, self.instance_id, key].join('/')\n else\n raise RuntimeError.new(\"Attempted to generate a key name without an instance id.\")\n end\n end",
"def key_id\n GlobalConstant::Aws::Kms.get_key_id_for(@purpose)\n end",
"def key_id\n GlobalConstant::Aws::Kms.get_key_id_for(@purpose)\n end",
"def id\n key\n end",
"def default_key\n :\"#{self[:name]}_id\"\n end",
"def get_key record\n record\n end",
"def key_id\n metadata[\"keyid\"]\n end",
"def get_request_counter_key(type, name)\n generate_store_key(\"#{type}-r:#{name}\")\n end",
"def gid\n \"##{id}\"\n end",
"def key\n @key.id2name\n end",
"def enriched_key\n \"product.#{service.id}.#{id}\"\n end",
"def key_for(ip)\n [prefix, ip].join\n end",
"def key_generator; end",
"def key_generator; end",
"def prefix_key(key)\n if self.instance_id\n [self.path, self.instance_id, key].join('/')\n else\n raise RuntimeError.new(\"Attempted to generate a key name without an instance id.\")\n end\n end",
"def simple_cache_key\n \"#{self.class.name.underscore}/#{id}\"\n end",
"def key_id=(value)\n @key_id = value\n end",
"def key_id=(value)\n @key_id = value\n end",
"def key_id=(value)\n @key_id = value\n end",
"def group_key\n columns = []\n\n @columns.each do |column|\n columns.push(column) if column.group\n end\n\n columns\n end",
"def key_for_series(bucketable, series_name, bucket_name)\n \"bucket_maker:#{bucketable.class.to_s.underscore}_#{bucketable.id}:#{series_name.to_s}:#{bucket_name.to_s}\" if bucketable && bucketable.id rescue nil\n end",
"def _key\n @_key || self.class.key.(self)\n end",
"def key\n @entity.key\n end",
"def reids_key(event_id)\n \"#{redis_prefix}-event-#{event_id}\"\n end",
"def key_builder()\n Transformer::KeyBuilder.new(@db_id, @coll_id, @doc_id)\n end",
"def build_key(instance)\n @key_processor.call(instance)\n end",
"def key(id=nil)\n postfix = id ? \"-#{id}\" : \"\"\n \"cb2-#{service}#{postfix}\"\n end",
"def key_id(comment)\n \"OPENSHIFT-#{@container.uuid}-#{comment}\"\n end",
"def next_group_id\n if @groups.empty?\n # Start each time from 1 to make sure groups get the same id's for the\n # same input data\n 1\n else\n id = @groups.last.id\n loop do\n id += 1\n break id if @groups.find { |g| g.id == id }.nil?\n end\n end\n end"
] |
[
"0.6898292",
"0.68468094",
"0.6801638",
"0.6737686",
"0.65537804",
"0.6535845",
"0.649238",
"0.64242184",
"0.63658416",
"0.635251",
"0.6320878",
"0.63197047",
"0.6316198",
"0.626829",
"0.6267376",
"0.6253607",
"0.6253607",
"0.62518734",
"0.6230364",
"0.62069833",
"0.61809623",
"0.61809623",
"0.6150968",
"0.6123141",
"0.6105549",
"0.6105012",
"0.6075244",
"0.60669136",
"0.6028502",
"0.60080576",
"0.60004526",
"0.59825265",
"0.5981534",
"0.59799397",
"0.5967965",
"0.5967214",
"0.59603876",
"0.5959334",
"0.5935341",
"0.59245646",
"0.59216744",
"0.59216744",
"0.59216744",
"0.59025866",
"0.5900386",
"0.5898878",
"0.5881631",
"0.5880836",
"0.5875137",
"0.5875137",
"0.5875137",
"0.58626026",
"0.584838",
"0.5844025",
"0.5844025",
"0.5833436",
"0.5829939",
"0.58019274",
"0.57749915",
"0.57571197",
"0.57561696",
"0.57557046",
"0.5740882",
"0.5740882",
"0.5738288",
"0.5738098",
"0.5724786",
"0.5722479",
"0.5720844",
"0.57206017",
"0.5720153",
"0.5715831",
"0.5714913",
"0.5714913",
"0.5710077",
"0.5702122",
"0.57011026",
"0.56974506",
"0.5695516",
"0.56767434",
"0.56741893",
"0.5672898",
"0.5665635",
"0.56652045",
"0.56652045",
"0.56625885",
"0.5658548",
"0.56567734",
"0.56567734",
"0.56567734",
"0.565519",
"0.5650049",
"0.5644914",
"0.5623844",
"0.56183046",
"0.5605697",
"0.560534",
"0.5604305",
"0.5600489",
"0.559037"
] |
0.6976525
|
0
|
Returns a new enumerable collection than responds to :<<. Deferred values will be aggregated into these collections by group key.
|
def new_group(key)
[]
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def collect!\n block_given? or return enum_for(__method__)\n set = self.class.new\n each { |o| set << yield(o) }\n replace(set)\n end",
"def push_all(enumerable)\n enumerable.each do |item|\n push(item)\n end\n self\n end",
"def mappend\n result = []\n self.each { |a| b = yield(a); b.each { |c| result << c } if b }\n result\n end",
"def groups(recursive = false)\n Set.new() << self\n end",
"def collect\n nha = self.class.new\n (0...self.length).each { |i| nha << yield(self.fetch(i)) }\n nha\n end",
"def aggregate\n []\n end",
"def each\n group.each\n end",
"def to_list\n\t\t# Binder.collection.group(key: :owner, cond: {}, initial: {count: 0}, reduce: \"function(doc,prev) {prev.count += +1;}\")\n\t\t# <query>.selector inserted into conditions field\n\t\trange = Range.new(grouphash['range'].first.to_i,grouphash['range'].last.to_i)\n\t\traw = kollection.titleize.constantize.collection.group(\t:key => grouphash['groupvals']['key'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t:cond => grouphash['groupvals']['cond'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t:initial => grouphash['groupvals']['initial'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t:reduce => grouphash['groupvals']['reduce'])\n\t\traw = raw.map{ |f| { f['owner'] => f['count'].to_i } }\n\t\traw = raw.reject{ |f| range.cover?(f.first[1]) }\n\t\traw.map{ |f| f.first[0] }\n\tend",
"def map\n reset_iteration\n return enum_for(:collect) unless block_given?\n [].tap { |ret| loop { ret << yield(self.next) } }\n end",
"def collect; end",
"def collect!\n block_given? or return enum_for(__method__) { size }\n set = self.class.new\n each { |o| set << yield(o) }\n replace(set)\n end",
"def group\n contents = []\n doc = Group.new(0, contents: contents)\n\n groups << doc\n target << doc\n\n with_target(contents) { yield }\n groups.pop\n doc\n end",
"def group\n klass.collection.group(\n :key => field_list,\n :cond => selector,\n :initial => { :group => [] },\n :reduce => Javascript.group\n ).collect do |docs|\n docs[\"group\"] = docs[\"group\"].collect do |attrs|\n Mongoid::Factory.from_db(klass, attrs)\n end\n docs\n end\n end",
"def to_expanded_set\r\n (target.map { |x| x.to_i } << to_i).to_set # include the group value as well\r\n end",
"def aggregate\n klass.collection.group(\n :key => field_list,\n :cond => selector,\n :initial => { :count => 0 },\n :reduce => Javascript.aggregate\n )\n end",
"def group\n return if record.respond_to?(:where)\n record.group\n end",
"def group_feed(group_id, limit)\n Enumerator.new do |y|\n processed = 0\n current_page = group_raw_feed(group_id, @page_size)\n\n until current_page.empty? || (processed >= limit)\n current_page.each do |element|\n y << element\n processed = processed + 1\n end\n current_page = current_page.next_page\n end\n end\n end",
"def each(&block)\n group.each_value(&block)\n end",
"def flat_map\n self\n end",
"def groups\n return [] if new_record?\n cached_groups do\n fetch_groups!\n end\n end",
"def group_with_map_reduce(coll, limit = 0)\n puts \"Grouping by 'Make' (map/reduce)\"\n opts = {\n :limit => limit.to_i,\n :out => {:inline => true},\n :raw => true\n }\n coll.map_reduce(@map, @reduce, opts)\nend",
"def group_by(*args)\n @group_keys = args\n\n @group_by = Proc.new do |allocations|\n getters = attribute_getters(@group_keys)\n\n allocations.group_by do |allocation|\n getters.map { |getter| getter.call(allocation) }\n end\n end\n\n self\n end",
"def group_with_builtin(coll)\n puts \"Grouping by 'Make' (built-in)\"\n coll.group({\n :key => [:Make],\n :initial => {:crashes => 0},\n :reduce => 'function(doc, prev) {prev.crashes += 1;}'\n })\nend",
"def map! &block\n mapped = enumerable_map(&block)\n clear\n merge mapped\n end",
"def collect\n end",
"def replace_aggregate!(&block)\n map! do |op|\n case\n when op.respond_to?(:aggregate?) && op.aggregate?\n yield op\n when op.respond_to?(:replace_aggregate!)\n op.replace_aggregate!(&block) \n else\n op\n end\n end\n self\n end",
"def to_a\n resolve\n @items\n end",
"def each\n @mset.each_pair do |key, group| \n group.to_a.each do |value|\n yield [key, value]\n end\n end \n end",
"def accumulate_instances\n self.repository = Hash.new { |h,k| h[k] = new(*k) }\n\n begin\n yield\n return repository.values\n ensure\n self.repository = nil\n end\n end",
"def merge(enum)\n enum.each do |val|\n self << val\n end\n self\n end",
"def each_aggregate(&block)\n if block_given?\n @aggregates.each_function(&block)\n self\n else\n @aggregates.functions\n end\n end",
"def each(&block)\n @grouped_collection.each { |gc| block.call(gc) }\n end",
"def group(*values)\n values.inject(self) { |res, val| res._group(val) or fail ArgumentError, \"Unknown value for group: #{val}\" }\n end",
"def my_map\n array = []\n self.my_each do |item|\n array << (yield item)\n end\n array\n end",
"def batch_badge_creator(attendee)\n # the below code would work more effectively but since I found it somewhere else I decided to use another method to prove to myself I could do it on my own. Since the collect method saves the results automatically to a new array, it doesnt require the extra step I needed to do with the .each method.\n # attendee.collect do |i|\n # badge_maker(i)\n # end\n\n badges =[]\n attendee.each {|i| badges.push badge_maker(i)}\n return badges\nend",
"def enq(group)\n depth = group.depth\n @queue << [] until depth < @queue.length\n @queue[depth] << group\n end",
"def group\n records.group_by{|r| r[:date]}\n end",
"def group_by(collection, grouping_key)\n [].tap do |providers| #building the returned Array\n extract_uniq_values_for_key(collection, grouping_key).each do |provider_name|\n current_provider_array, collection = collection.partition{|h| h[grouping_key] == provider_name} #reducing the collection\n providers << current_provider_array\n end\n end\nend",
"def all\n end_time = (Time.now - (30 * 60 * 60 * 24)).to_i\n all_items = Array.new\n cur_items = self\n begin\n all_items += cur_items.items\n cur_items = cur_items.next(:count => 200, :start_time => end_time)\n end until cur_items.nil?\n all_items\n end",
"def objects\n @objects ||= population_group_members.collect(&:objects).flatten.uniq\n end",
"def collecting(accessor, *params)\n self.inject([]) { |all, child| all + child.send(accessor, *params) } || []\n end",
"def merge(enum)\n enum.each { |x| self << x }\n self\n end",
"def each_group\n @groups.each_value do | group |\n yield( group )\n end\n end",
"def flatten(array, opts)\n keys = opts[:keys].dup\n\n # this must be an interval period : find the mean, sum, max, whatever\n opts[:list_operator] ||= :mean\n\n collection = self.new( :data => {} )\n\n keys.each_with_index do |key, idx|\n if key == :date\n collection.created_at = array.first.created_at\n next\n end\n\n collection_key = key.to_s.gsub(/[\\s*\\/:x+-]+/, '_')\n keys[idx] = collection_key if collection_key != key\n\n array.each do |item|\n collection.data[collection_key] ||= []\n collection.data[collection_key] << (item.fetch(key) || 0)\n end\n\n # turn the collection into a single value\n value = if opts[:list_operator] == :delta\n collection.data[collection_key].max -\n collection.data[collection_key].min\n\n else\n collection.data[collection_key].send(opts[:list_operator])\n\n end\n\n collection.data[collection_key] = value\n end\n\n collection\n collection.readonly! if collection.respond_to?(:readonly!)\n\n return [keys, collection]\n end",
"def get_everything!\n self.update!\n\n prev = @prev\n while prev\n prev.update!\n\n self.merge_entries! prev\n prev = prev.prev\n end\n\n nxt = @next\n while nxt\n nxt.update!\n\n self.merge_entries! nxt\n nxt = nxt.next\n end\n\n self\n end",
"def group(*) end",
"def emit_ungrouped_questions\n ungrouped_question_sets = quiz.ungrouped_questions.group_by(&:points)\n ungrouped_question_sets.each_pair do |points,questions|\n start_new_group(:name => \"Group:unpooled:#{points}\", :pick_count => questions.length, :question_points => points)\n questions.each do |q|\n canvas_question = render_multiple_choice(q)\n add_question_to_current_group(canvas_question)\n end\n end\n end",
"def map\n out = []\n\n each { |e| out << yield(e) }\n\n out\n end",
"def to_a\n resolve\n @items\n end",
"def groups_of(num)\n collection.each_slice(num).to_a\n end",
"def group_by(collection, grouping_value)\n collection.reduce({}) do |acc, item| #we build a dictionary (or hashmap)\n acc.tap do |acc| #because I love old fashioned functional style\n acc[item[grouping_value]] ||= [] #because a new value\n acc[item[grouping_value]] << item\n end\n end.map do |key, value| #transform the hash to an array\n value\n end\nend",
"def aggregations\n @aggregations ||= AggregationSet.new\n end",
"def with_collection_lock\n @lock.synchronize do\n return yield\n end\n end",
"def closure item_set\n\t\tresult = item_set\n\t\ttemp = nil\n\t\t#continue adding to closure set until it doesn't change\n\t\tuntil temp == result\n\t\t\t#create deep copy of temp\n\t\t\ttemp = Marshal.load(Marshal.dump(result))\n\t\t\ttemp.keys.each do |lhs|\n\t\t\t\ttemp[lhs].each do |rhs|\n\t\t\t\t\tif rhs.index(@marker)\n\t\t\t\t\t\tnext_val = rhs[rhs.index(@marker)+1]\n\t\t\t\t\t\tif non_terminals.include?(next_val)\n\t\t\t\t\t\t\t@production_rules[next_val].each do |rhs|\n\t\t\t\t\t\t\t\t#create temporary rhs so we don't modify the production rules with unshift\n\t\t\t\t\t\t\t\tt_rhs = rhs.clone\n\t\t\t\t\t\t\t\tt_rhs = t_rhs.unshift(@marker)\n\t\t\t\t\t\t\t\tif result[next_val]\n\t\t\t\t\t\t\t\t\tdup = false\n\t\t\t\t\t\t\t\t\tresult[next_val].each do |r|\n\t\t\t\t\t\t\t\t\t\tif r.eql?(t_rhs)\n\t\t\t\t\t\t\t\t\t\t\tdup = true\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\tif !dup\n\t\t\t\t\t\t\t\t\t\tresult[next_val].push(t_rhs)\n\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tresult[next_val] = [t_rhs]\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\treturn result\n\tend",
"def aggregate(accessor, *params)\n self.inject([]) { |all, child| all << child.send(accessor, *params) }.flatten || []\n end",
"def thread_collect\n collection = Array.new\n thread_each do |e|\n collection << yield(e)\n end\n collection\n end",
"def collect_groups\n @groups.inject(name => self) do |acc, g|\n acc.merge(g.collect_groups)\n end\n end",
"def collect\n base_finder = @base_class.includes(@dependency_tree)\n # If there are dependencies to load, we reduce the the batch size to compensate for\n # the increased memory of loading all the associations at the same time.\n batch_size = @dependency_tree.blank? ? DEFAULT_BATCH_SIZE : DEFAULT_BATCH_SIZE / 10\n enumerable = Enumerator.new do |yielder|\n @ids.each_slice(batch_size).with_index do |batch_of_ids, batch_index|\n with_sql_subscription do\n base_finder.where(@base_class.primary_key => batch_of_ids).load\n end\n # Expose this batch of SELECTs to the enumerator\n yielder.yield(@selects)\n # Reset the accumulator for the next batch (don't hog memory!)\n @selects.clear\n end\n end\n # By using a lazy enumerator, we make it possible to garbage collect records\n # as we process a batch, so long as the end user accesses the data via #each\n # and does not maintain references to previous rows. Example:\n # Polo.explore(klass, ids, associations).each { |row| file.puts(row) }\n enumerable.to_enum.lazy\n end",
"def map(collection)\n result = []\n collection.each { |el| result << yield(el)}\n result\nend",
"def grouped_duplicates(collection); end",
"def collect(*args, &block)\n all.collect(*args, &block)\n end",
"def decorated_collection\n @collection.map do |element|\n Resource.new(element, @controller)\n end\n end",
"def children\n (items + collections)\n end",
"def collection\n @collection ||= collection_values\n end",
"def my_map\n arr = []\n self.my_each {|x| arr << yield(x)}\n arr\n end",
"def each\n return enum_for(:each) unless block_given?\n\n @data.collection.each { |item| yield item }\n end",
"def to_a\n results = @allocations\n\n @wheres.each do |where|\n results = where.call(results)\n end\n\n # First apply group_by\n results = @group_by.call(results) if @group_by\n\n # Apply each mapper\n @mappers.each do |mapper|\n results = mapper.call(results)\n end\n\n results\n end",
"def collection\n iterator.next\n end",
"def each()\n yield izq\n yield der\n end",
"def date_group_items\n @date_group_items ||= []\n end",
"def generate_groups(groups, type)\r\n [].tap do |results|\r\n groups.each do |n, obj|\r\n group = {}\r\n group[\"name\"] = obj['name']\r\n group[\"code\"] = n\r\n group[\"risk_category\"] = \"AUTO\"\r\n group[type] = obj[type]\r\n results << group\r\n end\r\n end\r\nend",
"def flat_map\n yield(value)\n end",
"def group\n raise \"View#reduce must have been set before grouping is permitted\" unless query[:reduce]\n update_query(:group => true)\n end",
"def group\n raise \"View#reduce must have been set before grouping is permitted\" unless query[:reduce]\n update_query(:group => true)\n end",
"def group_builder; end",
"def collect!(&block)\n unless block_given?\n return ArrayEnumerator.new(self, :collect! ) # for 1.8.7\n end\n i = 0\n sz = self.__size\n enum_res = self.each { | elem | # use self.each to handle break in block\n self.__at_put(i, block.call( elem ) )\n i += 1\n }\n if i < sz\n return enum_res\n end\n self\n end",
"def my_collect(array)\n i = 0\n collection = []\n while i < array.size\n collection << yield(array[i])\n i += 1\n end\n collection\nend",
"def each\n return enum_for(:each) unless block_given?\n results.each(&Proc.new)\n self\n end",
"def map &block\n self.class.from_a enumerable_map(&block)\n end",
"def all\r\n copy_and_return(@records)\r\n end",
"def map\n cur = self\n while cur\n yield(cur)\n cur = cur.next\n end\n self\n end",
"def groups\n @groups ||= Groups.call(self)\n end",
"def groups\r\n @groups ||= fetch_groups\r\n end",
"def my_collect(array)\n collection = []\n index = 0\n while index < array.size\n collection << yield(array[index])\n index += 1\n end\n collection\nend",
"def to_ary\n resolve\n @items\n end",
"def merge(enum)\n if enum.is_a?(Set)\n @hash.update(enum.instance_eval { @hash })\n else\n enum.is_a?(Enumerable) or raise ArgumentError, \"value must be enumerable\"\n enum.each { |o| add(o) }\n end\n\n self\n end",
"def collection\n apply_scopes(super).order(:date).includes{[person, shift.shift_group, shift.county]}.uniq\n end",
"def <<(id)\n group << id\n end",
"def all\n response = run\n\n while continue?(response)\n @options[:exclusive_start_key] = response.last_evaluated_key\n response = run(response)\n end\n\n @collection.deserialize(response.entities)\n end",
"def <<(group) \n @groups[group.name] = group\n end",
"def each(&block)\n to_set.each(&block)\n end",
"def process_group\n slice_size = 0.step(@ids.size - 1, @process_group_chunk).size\n\n @ids.each_slice(slice_size).lazy\n # => [[1, 2, 3, ...], [10, 11, 12, ...], ...]\n end",
"def all\n @all ||= raw.map { |item| new(item) }\n end",
"def group(entry)\n push(\"$group\" => evolve(entry.__expand_complex__))\n end",
"def all\n\n @all ||= dataset.map { |item| self.new item }\n\n end",
"def read_many(query)\n Collection.new(query) do |set|\n read(query, set, true)\n end\n end",
"def group_by\n end",
"def collect_join_chain\n [self]\n end",
"def groups\n find(:group).map { |g| g.content }\n end",
"def _reduce_7(val, _values)\n Group.new(val[1])\nend"
] |
[
"0.55238044",
"0.5398791",
"0.5371102",
"0.5361916",
"0.5331594",
"0.5328977",
"0.5316539",
"0.5292373",
"0.5287342",
"0.5193399",
"0.518639",
"0.5137206",
"0.51040167",
"0.5054244",
"0.5030129",
"0.5020475",
"0.5019767",
"0.5018616",
"0.50144035",
"0.49533525",
"0.4927352",
"0.48895574",
"0.48433352",
"0.48408246",
"0.48393613",
"0.48387656",
"0.48330668",
"0.48330393",
"0.48250136",
"0.47900987",
"0.4787145",
"0.4786733",
"0.4785283",
"0.47834352",
"0.47782192",
"0.47755358",
"0.47652197",
"0.47640842",
"0.47597384",
"0.474706",
"0.47398472",
"0.47370917",
"0.4729892",
"0.47250047",
"0.47245058",
"0.47152016",
"0.47117326",
"0.47075716",
"0.470573",
"0.47016406",
"0.4701271",
"0.46925008",
"0.46919993",
"0.46872547",
"0.46840167",
"0.46698794",
"0.46534035",
"0.46525624",
"0.46523073",
"0.4646476",
"0.46415454",
"0.46399403",
"0.46368852",
"0.46359164",
"0.46339792",
"0.46188647",
"0.4618166",
"0.4606177",
"0.46029893",
"0.45982006",
"0.45959315",
"0.45942554",
"0.45939457",
"0.45879498",
"0.45865783",
"0.45770305",
"0.4575749",
"0.45741168",
"0.45649502",
"0.45645475",
"0.45591378",
"0.4556718",
"0.4555262",
"0.45528254",
"0.45526728",
"0.45523182",
"0.45487943",
"0.4548613",
"0.45480472",
"0.4546878",
"0.454461",
"0.45425868",
"0.45343068",
"0.4530874",
"0.45283225",
"0.4527107",
"0.45269874",
"0.4523913",
"0.45223993",
"0.45220822"
] |
0.4782574
|
34
|
Indicates whether its possible to capture the payment
|
def can_capture?(payment)
['checkout', 'pending'].include?(payment.state)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def can_capture?(payment)\n payment.pending? || payment.checkout?\n end",
"def can_capture?(payment)\n payment.pending? || payment.checkout?\n end",
"def can_capture?(payment)\n payment.pending? || payment.checkout?\n end",
"def can_capture?(payment)\n payment.pending? || payment.checkout?\n end",
"def can_capture?(payment)\n payment.pending? || payment.checkout?\n end",
"def can_capture?(payment)\n payment.state == 'pending' || payment.state == 'checkout'\n end",
"def can_capture?(payment)\n ['pending'].include?(payment.state)\n end",
"def can_capture?(payment)\n ['pending'].include?(payment.state)\n end",
"def can_capture?(payment)\n payment.checkout?\n end",
"def can_capture?(payment)\n (payment.pending? || payment.checkout?) && !payment.response_code.blank?\n end",
"def can_capture?(payment)\n (payment.pending? || payment.checkout?) && !payment.response_code.blank?\n end",
"def can_capture?(payment)\n logger.debug \"\\n----------- #{self.invoice_number} -----------\\n\"\n ['checkout', 'pending', 'processing'].include?(payment.state) && !self.invoice_number.blank?\n end",
"def can_capture?(payment)\n ['checkout', 'pending'].include?(payment.state)\n end",
"def can_capture?(payment)\n ['checkout', 'pending', 'processing'].include?(payment.state)\n end",
"def collect_payment?\n true\n end",
"def can_supply?\n payment_received? || payment_on_account?\n end",
"def can_credit?(payment)\n payment.completed? && payment.credit_allowed > 0\n end",
"def can_credit?(payment)\n payment.completed? && payment.credit_allowed > 0\n end",
"def can_activate?\n self.authorize_payment\n end",
"def can_void?(payment)\n !payment.failed? && !payment.void?\n end",
"def can_void?(payment)\n !payment.failed? && !payment.void?\n end",
"def can_void?(payment)\n !payment.void?\n end",
"def can_void?(payment)\n !payment.void?\n end",
"def can_finish?\n self.payment_status == PTE::PaymentStatus.processing\n end",
"def payment_success?\n @fields['decision'] == 'ACCEPT'\n end",
"def in_payment?\n @in_payment\n end",
"def is_manual?\n payment_kind == 'manual'\n end",
"def can_credit?(payment)\n return false unless payment.state == 'completed'\n return false unless payment.order.payment_state == 'credit_owed'\n payment.credit_allowed > 0\n end",
"def capture_pending_payments\n success = true\n order.payments.pending.each do |payment|\n unless payment.capture!\n copy_errors(payment)\n success = false\n end\n end\n success\n end",
"def guard_process_payment_from_created; true; end",
"def guard_process_payment_from_created; true; end",
"def can_void?(payment)\n payment.state != 'void'\n end",
"def can_void?(payment)\n payment.state != 'void'\n end",
"def can_credit?(payment)\n return false unless payment.completed?\n return false unless payment.order.payment_state == 'credit_owed'\n payment.credit_allowed > 0\n end",
"def can_credit?(payment)\n return false unless payment.completed?\n return false unless payment.order.payment_state == 'credit_owed'\n payment.credit_allowed > 0\n end",
"def can_void?(payment)\n !%w(void failure invalid).include?(payment.state)\n end",
"def can_void?(payment)\n payment.state != 'void'\n end",
"def can_void?(payment)\n payment.state != 'void'\n end",
"def can_void?(payment)\n payment.state != 'void'\n end",
"def can_void?(payment)\n payment.state != 'void'\n end",
"def can_void?(payment)\n payment.state != 'void'\n end",
"def can_void?(payment)\n payment.state != 'void'\n end",
"def can_void?(payment)\n payment.state != 'void'\n end",
"def can_void?(payment)\n !payment.state.in?(['void', 'invalid', 'failed'])\n end",
"def can_void?(payment)\n !payment.void? && payment.pending? && !payment.response_code.blank?\n end",
"def can_void?(payment)\n !payment.void? && payment.pending? && !payment.response_code.blank?\n end",
"def can_cash?\n self.capture_and_cash\n end",
"def payment_cadence_allowed?\n begin\n config_payment_cadence = SystemConfiguration::Variable.get_value('booking.payment_cadence').to_i\n _date_from_str = \"#{self.date_from.strftime('%Y-%m-%d')}T#{self.time_from}:00#{self.date_from.strftime(\"%:z\")}\"\n _date_from = DateTime.strptime(_date_from_str,'%Y-%m-%dT%H:%M:%S%:z')\n diff_in_hours = ((_date_from.to_time - self.creation_date.to_time).to_f * 24).to_i\n allowed = diff_in_hours > 0 && (diff_in_hours >= config_payment_cadence)\n allowed || force_allow_payment\n rescue => error\n p \"Error #{id} #{date_from} #{time_from} #{date_to} #{time_to} #{driver_date_of_birth} #{driver_driving_license_date}\"\n return false\n end\n end",
"def should_request_capture?(response, requires_approval)\n !capture_requested?(response) && requires_approval != false\n end",
"def store_credit_card?\n paid?\n end",
"def payment_api_return?\n\t\ttrue\n\tend",
"def payment_received?\n payment_state == PAYMENT_RECEIVED\n end",
"def payed?\n !payment_entry.nil?\n end",
"def credit_card_needed?\n credit_card_required?\n end",
"def paid_with_card?\n payment_type == \"card\"\n end",
"def authorize_payment\n if !self.pending_purchase_order && self.payment_object\n order, payment = self.purchase_and_authorize\n if payment && payment.success?\n# self.payment_object = nil # remove payment object so we can re-validate\n self.purchase_orders.reload\n return payment.success?\n end\n end\n false\n end",
"def credit?\n (payment_method == CREDIT)\n end",
"def capture_payment(options = {})\n # transaction do\n capture = OrderTransaction.capture(amount, authorization_reference, options)\n self.save!\n self.order_transactions << capture\n\n if capture.success?\n self.payment_captured!\n else\n self.transaction_declined!\n end\n\n capture\n # end\n end",
"def succeeded?\n authorized? || paid?\n end",
"def authorize_and_capture\n \n resp = StdClass.new \n if self.financial_status == Invoice::FINANCIAL_STATUS_CAPTURED\n resp.error = \"Funds for this invoice have already been captured.\"\n else\n \n sc = self.site.store_config \n case sc.pp_name \n when StoreConfig::PAYMENT_PROCESSOR_STRIPE\n \n Stripe.api_key = sc.stripe_secret_key.strip\n bt = nil\n begin\n c = Stripe::Charge.create(\n :amount => (self.total * 100).to_i,\n :currency => 'usd',\n :customer => self.customer.stripe_customer_id,\n :capture => true,\n :metadata => { :invoice_id => self.id },\n :statement_descriptor => \"#{self.site.description.truncate(22)}\"\n ) \n rescue Exception => ex\n resp.error = \"Error during capture process\\n#{ex.message}\" \n end \n if resp.error.nil?\n InvoiceTransaction.create(\n :invoice_id => self.id,\n :transaction_id => c.id,\n :transaction_type => InvoiceTransaction::TYPE_AUTHCAP,\n :payment_processor => sc.pp_name,\n :amount => c.amount / 100.0,\n :captured => true,\n :date_processed => DateTime.now.utc,\n :success => c.status == 'succeeded'\n )\n if c.status == 'succeeded'\n self.financial_status = Invoice::FINANCIAL_STATUS_CAPTURED\n self.save\n resp.success = true\n else\n resp.error = \"Error capturing funds.\"\n end\n end\n \n end \n end \n return resp\n end",
"def authorizable_cc_payment?\n adyen_cc_payment? && amount != 0\n end",
"def payment_pending?\n payment_state == PAYMENT_PENDING\n end",
"def payment_in_progress?\n\t\t\t\t\treturn !self.payment_id.nil?\n\t\t\t\tend",
"def paid_with_card?\n order.payment_method == 'credit_card'\n end",
"def capture!\n if hpp_payment? || adyen_cc_payment?\n amount = money.money.cents\n process do\n payment_method.send(\n :capture, amount, response_code, gateway_options)\n end\n else\n super\n end\n end",
"def payment_confirmation_required?\n true\n end",
"def payment_authorized?(payment_id)\n check_payment = get_payment_intent_info(payment_id)\n status = check_payment['status']\n puts \"Current Payment Status: #{status}\"\n case status\n when 'Authorized', 'Card Verified'\n puts 'Payment has been authorized'\n return true\n # when 'Declined'\n # puts \"Reason for Decline: #{check_payment['response_summary']}\"\n # abort 'Payment has been declined so exiting this program'\n end\n puts \"3DS Flow hasn't been completed\"\n false\n end",
"def payment_profiles_supported?\n false\n end",
"def payments_in_use?\n payment_gateway.present? && payment_gateway.configured?\n end",
"def purchase!\n if ratepay?\n capture!\n elsif adyen_cc_payment?\n authorize!\n capture!\n else\n super\n end\n end",
"def requires_manual_payment?\n Paykido::Application.config.always_pay_manually or\n !self.payer.registered?\n end",
"def charge_is_allowed?\n\t\tif not customer_has_authorized_payment?\n\t\t\terrors.add :base, I18n.t('views.customer_file.new_charge.you_are_not_authorized')\n\t\t\tfalse\n\t\telsif valid? and charge_amount.present? and authorized_amount and charge_amount.to_i <= authorized_amount\n\t\t\ttrue\n\t\telse\n\t\t\terrors.add :charge_amount, I18n.t('views.customer_file.new_charge.invalid', amount: charge_amount_usd) if errors.empty?\n\t\t\tfalse\n\t\tend\n\tend",
"def check(payment)\n retval\n end",
"def payment_received?\n status == Enums::PaymentStatus::PAYMENT_RECEIVED\n end",
"def claim_amount_required?\n @full_repayment_of_ads != 'Y'\n end",
"def capture!(capture_amount = nil)\n if hpp_payment? || adyen_cc_payment? || ratepay?\n amount = money.money.cents\n process do\n payment_method.send(\n :capture, amount, response_code, gateway_options)\n end\n else\n super\n end\n end",
"def payment_failed?\n cancel_reason == PAYMENT_FAILED\n end",
"def require_one_click_payment?(source, shopper)\n false\n end",
"def settled_payment?\n SUCCESSFUL_PAYMENT.include?(response['payment_state'])\n end",
"def credit_card?\n (payment_method == CREDIT_CARD)\n end",
"def cc_pay?\n plan&.direct_pay && id != 3744\n end",
"def capture\n begin \n Order.transaction do\n # lock order\n Order.find_by_id(self.id, :lock => true)\n # go through all order_payments\n order_payments = self.order_payments\n if order_payments.size == 0\n p \"No order_payments to process.\"\n raise PaymentError, \"No order_payments to process.\"\n end\n for order_payment in order_payments\n order_payment.capture!\n end\n self.upgrade_coupons!\n # update order\n self.update_attributes!(:state => Order::PAID, :paid_at => Time.zone.now)\n end\n # send confirmation email\n user = User.find_by_id(self.user_id)\n if user and user.send_confirmation(self.deal_id)\n return true\n else\n logger.error \"Order.capture: Confirmation email failed to send: #{self.inspect}\"\n return false\n end\n rescue PaymentError => pe\n p \"Order.capture: Failed for Order #{self.inspect} #{pe}\"\n logger.error \"Order.capture: Failed for Order #{self.inspect} #{pe}\"\n rescue ActiveRecord::RecordInvalid => invalid\n p \"Order.capture: Failed for Order #{self.inspect} #{invalid}\"\n logger.error \"Order.capture: Failed for Order #{self.inspect} #{invalid}\"\n end\n return false\n end",
"def payment_possible_for?(listing)\n listing.price && listing.price > 0 && stripe_in_use?\n end",
"def success?\n @result[:payment] === true\n end",
"def verify!\n raise \"Payment details not active anymore\" if active == false\n end",
"def payments_in_use?\n active_payment_types.present?\n end",
"def valid?\n p = build_payment\n p.valid?\n end",
"def process_with_active_merchant\n options = populate_options\n auth = authorize_payment(options)\n save!\n if APP_CONFIG['pre_and_post_authorization'] == true\n if auth.success == true\n capture_payment(options)\n save!\n end\n end\n end",
"def customer_has_authorized_payment?\n\t\tauthorized and authorized_amount.try(:>, 0) and has_customer_account?\n\tend",
"def charge?\n false\n end",
"def recording_consent_required?\n @settings.get_value(\"Require Recording Consent\") == \"true\"\n end",
"def can_request_purchase?\n true # TODO: Should this be !virginia_borrower? ?\n end",
"def trial?\n price_is_zero = price_amount_micros == 0\n price_is_zero && payment_received?\n end",
"def payment_possible_for?(listing)\n listing.price && listing.price > 0 && payments_in_use?\n end",
"def pending?\n payment_status == 'Pending'\n end",
"def paid_in_full?\n !payment_outstanding?\n end",
"def allow_paypal_payments?\n paypal_credentials.present? || paypal_email.present?\n end",
"def can_pay?\n\n can_pay_deposit? or can_pay_pending? or can_pay_total?\n\n end",
"def accounts_receivable?\n type == 'ACCRECCREDIT'\n end"
] |
[
"0.8574391",
"0.8574391",
"0.8574391",
"0.8574391",
"0.8574391",
"0.8421634",
"0.840692",
"0.83986884",
"0.8374448",
"0.83426374",
"0.83426374",
"0.8285566",
"0.82840663",
"0.8245142",
"0.76958513",
"0.72335327",
"0.71325046",
"0.71325046",
"0.71179265",
"0.7106526",
"0.7106526",
"0.7004219",
"0.7004219",
"0.69761574",
"0.69729304",
"0.6920117",
"0.6905132",
"0.68792975",
"0.6878423",
"0.6878125",
"0.6878125",
"0.68705887",
"0.68705887",
"0.6854525",
"0.6854525",
"0.6840233",
"0.68260354",
"0.68260354",
"0.68260354",
"0.68260354",
"0.68260354",
"0.68260354",
"0.68260354",
"0.6804581",
"0.67943954",
"0.67943954",
"0.6789482",
"0.6763707",
"0.6741932",
"0.6704732",
"0.66913325",
"0.66803646",
"0.6655936",
"0.66481507",
"0.66368896",
"0.659922",
"0.659313",
"0.6559455",
"0.6553428",
"0.6528682",
"0.6496032",
"0.64757854",
"0.646828",
"0.64674497",
"0.6459903",
"0.64376986",
"0.6432658",
"0.6422796",
"0.64100313",
"0.6405559",
"0.63914835",
"0.6388284",
"0.6388221",
"0.6387437",
"0.63678837",
"0.636496",
"0.6363913",
"0.6352809",
"0.63392484",
"0.63217205",
"0.6303929",
"0.62953824",
"0.62766343",
"0.6271231",
"0.6267796",
"0.62561107",
"0.62546706",
"0.62528485",
"0.62410927",
"0.6227802",
"0.6182079",
"0.6174833",
"0.61711377",
"0.6171051",
"0.6159654",
"0.61500674",
"0.61407906",
"0.61360097",
"0.61227816"
] |
0.83002377
|
11
|
Indicates whether its possible to void the payment.
|
def can_void?(payment)
payment.state != 'void'
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def can_void?(payment)\n !payment.void?\n end",
"def can_void?(payment)\n !payment.void?\n end",
"def can_void?(payment)\n !payment.failed? && !payment.void?\n end",
"def can_void?(payment)\n !payment.failed? && !payment.void?\n end",
"def can_void?(payment)\n !payment.state.in?(['void', 'invalid', 'failed'])\n end",
"def can_void?(payment)\n payment.state != 'void'\n end",
"def can_void?(payment)\n payment.state != 'void'\n end",
"def can_void?(payment)\n !%w(void failure invalid).include?(payment.state)\n end",
"def can_void?(payment)\n !payment.void? && payment.pending? && !payment.response_code.blank?\n end",
"def can_void?(payment)\n !payment.void? && payment.pending? && !payment.response_code.blank?\n end",
"def can_finish?\n self.payment_status == PTE::PaymentStatus.processing\n end",
"def try_void(payment)\n transaction = braintree.transaction.find(payment.response_code)\n if transaction.status.in? SolidusBraintree::Gateway::VOIDABLE_STATUSES\n # Sometimes Braintree returns a voidable status although it is not voidable anymore.\n # When we try to void that transaction we receive an error and need to return false\n # so Solidus can create a refund instead.\n begin\n void(payment.response_code, nil, {})\n rescue ActiveMerchant::ConnectionError => e\n e.message.match(NON_VOIDABLE_STATUS_ERROR_REGEXP) ? false : raise(e)\n end\n else\n false\n end\n end",
"def payed?\n !payment_entry.nil?\n end",
"def payment_failed?\n cancel_reason == PAYMENT_FAILED\n end",
"def payment_pending?\n payment_state == PAYMENT_PENDING\n end",
"def cancel_payment\n\n\t\t\t\t\t# Delete payment id\n\t\t\t\t\tself.payment_id = nil\n\t\t\t\t\t\n\t\t\t\t\t# Save\n\t\t\t\t\tself.override_accept_terms\n\t\t\t\t\tif !self.save\n\t\t\t\t\t\treturn false\n\t\t\t\t\tend\n\n\t\t\t\t\treturn true\n\t\t\t\tend",
"def void_payment(event)\n payment = extract_payment_from_event(event)\n reason = event.data.object.cancellation_reason\n\n payment.with_lock do\n break if payment.void?\n\n payment.void!.tap do\n SolidusStripe::LogEntries.payment_log(\n payment,\n success: true,\n message: \"Payment was voided after payment_intent.voided webhook (#{reason})\"\n )\n end\n end\n end",
"def void_transaction!(authorization)\n response = provider_payment_gateway.void(authorization)\n log_gateway_response(response, \"void [transaction: #{authorization}]\")\n response.success?\n end",
"def paid_in_full?\n !payment_outstanding?\n end",
"def can_supply?\n payment_received? || payment_on_account?\n end",
"def void\n @order.void_payment\n render 'status'\n end",
"def can_capture?(payment)\n payment.pending? || payment.checkout?\n end",
"def can_capture?(payment)\n payment.pending? || payment.checkout?\n end",
"def can_capture?(payment)\n payment.pending? || payment.checkout?\n end",
"def can_capture?(payment)\n payment.pending? || payment.checkout?\n end",
"def can_capture?(payment)\n payment.pending? || payment.checkout?\n end",
"def paid_up?\n if payment_item.is_a? GeneralPaymentItem\n outstanding_amount <= 0.0\n else\n nil\n end\n end",
"def settled_payment?\n SUCCESSFUL_PAYMENT.include?(response['payment_state'])\n end",
"def payment_in_progress?\n\t\t\t\t\treturn !self.payment_id.nil?\n\t\t\t\tend",
"def collect_payment?\n true\n end",
"def pending?\n payment_status == 'Pending'\n end",
"def in_payment?\n @in_payment\n end",
"def incomplete_payment?\n past_due || incomplete\n end",
"def donor_can_cancel?\n !received?\n end",
"def can_capture?(payment)\n payment.state == 'pending' || payment.state == 'checkout'\n end",
"def can_capture?(payment)\n ['pending'].include?(payment.state)\n end",
"def prepaid?\n not postpaid?\n end",
"def payment_possible_for?(listing)\n listing.price && listing.price > 0 && payments_in_use?\n end",
"def can_credit?(payment)\n payment.completed? && payment.credit_allowed > 0\n end",
"def can_credit?(payment)\n payment.completed? && payment.credit_allowed > 0\n end",
"def trial?\n price_is_zero = price_amount_micros == 0\n price_is_zero && payment_received?\n end",
"def can_capture?(payment)\n ['pending'].include?(payment.state)\n end",
"def charge?\n false\n end",
"def payment_possible_for?(listing)\n listing.price && listing.price > 0 && stripe_in_use?\n end",
"def can_capture?(payment)\n (payment.pending? || payment.checkout?) && !payment.response_code.blank?\n end",
"def can_capture?(payment)\n (payment.pending? || payment.checkout?) && !payment.response_code.blank?\n end",
"def payment_intent_cancelled?\n status == 'Payment Intent Cancelled'\n end",
"def unredeemable?\n payment_owed? && !(ProductStrategy === self.order.promotion.strategy) \n end",
"def payment_success?\n @fields['decision'] == 'ACCEPT'\n end",
"def succeeded?\n authorized? || paid?\n end",
"def can_capture?(payment)\n ['checkout', 'pending'].include?(payment.state)\n end",
"def can_capture?(payment)\n ['checkout', 'pending'].include?(payment.state)\n end",
"def can_capture?(payment)\n ['checkout', 'pending', 'processing'].include?(payment.state)\n end",
"def can_capture?(payment)\n logger.debug \"\\n----------- #{self.invoice_number} -----------\\n\"\n ['checkout', 'pending', 'processing'].include?(payment.state) && !self.invoice_number.blank?\n end",
"def payment_api_return?\n\t\ttrue\n\tend",
"def can_credit?(payment)\n return false unless payment.state == 'completed'\n return false unless payment.order.payment_state == 'credit_owed'\n payment.credit_allowed > 0\n end",
"def can_capture?(payment)\n ['checkout', 'pending'].include?(payment.state)\n end",
"def is_deletable\n not is_default_cash_gift\n end",
"def payment_authorized?(payment_id)\n check_payment = get_payment_intent_info(payment_id)\n status = check_payment['status']\n puts \"Current Payment Status: #{status}\"\n case status\n when 'Authorized', 'Card Verified'\n puts 'Payment has been authorized'\n return true\n # when 'Declined'\n # puts \"Reason for Decline: #{check_payment['response_summary']}\"\n # abort 'Payment has been declined so exiting this program'\n end\n puts \"3DS Flow hasn't been completed\"\n false\n end",
"def delete_permitted(mem)\n unless mem.suspended? || mem.mem_state.strip == StateNameTable::WaitPayment\n error \"Only TeamPaks awaiting payment can be deleted\"\n return false\n end\n\n @orders = Order.list_for_membership(mem.mem_id)\n\n @orders.each do |order|\n pays = Pays.for_order(order)\n unless pays.empty?\n error \"Cannot delete a TeamPak after orders associated with it have been paid\"\n return false\n end\n LineItem.items_for_order(order.order_id) do |li|\n if li.li_date_shipped\n error \"Cannot delete: '#{li.li_desc}' has been shipped\"\n return false\n end\n end\n end\n true\n end",
"def can_credit?(payment)\n return false unless payment.completed?\n return false unless payment.order.payment_state == 'credit_owed'\n payment.credit_allowed > 0\n end",
"def can_credit?(payment)\n return false unless payment.completed?\n return false unless payment.order.payment_state == 'credit_owed'\n payment.credit_allowed > 0\n end",
"def user_must_pay?\n !journal_will_pay? &&\n !institution_will_pay? &&\n (!submitter_affiliation.present? || !submitter_affiliation.fee_waivered?)\n end",
"def test_credit_card_purchase_and_void_amount_not_specified\n assert purchase = @gateway.purchase(@amount, @credit_card, @options)\n assert_success purchase\n assert_equal 'Approved', purchase.message\n assert void = @gateway.void(nil, purchase.authorization, @credit_card, @options)\n assert_failure void\n assert_equal 'TRANSACTION AMOUNT IS REQUIRED', void.message\n end",
"def awaiting_disbursement?\n financial_aid_approved? && !disbursed?\n end",
"def user_must_pay?\n !journal&.will_pay? && !institution_will_pay? && !funder_will_pay?\n end",
"def descriptively_ok?\n acceptance & DESCRIPTIVE == DESCRIPTIVE\n end",
"def process_cancellation!\n if payment.settled?\n # If we have the money, refund it.\n if payment.refund!\n return_stock\n IslayShop::OrderMailer.cancelled(self).deliver\n next!(\"Credited #{formatted_total}\")\n else\n fail!(\"Could not refund payment due to a problem with the payment provider\")\n end\n else\n # If the payment provider supports voiding, void\n if payment.can_void?\n if payment.void!\n return_stock\n IslayShop::OrderMailer.cancelled(self).deliver\n next!(\"Payment has been voided\")\n else\n fail!(\"Could not void payment due to a problem with the payment provider\")\n end\n else\n # Let the authorization expire:\n return_stock\n IslayShop::OrderMailer.cancelled(self).deliver\n next!(\"Payment can't be voided: the authorization will expire, usually within 7 days.\")\n end\n end\n end",
"def may_purchase?(_company)\n false\n end",
"def payment_received?\n payment_state == PAYMENT_RECEIVED\n end",
"def void(unique_id)\n request('payment/void', :void => {:unique_id => unique_id} )\n end",
"def can_submit?\n # First check the state machine to see if it is Ok to submit based on the\n # current state\n b = super()\n if b\n # Now check that the CP has funding\n b = false unless total_cost > 0\n #b = false unless funding_difference <= 0\n end\n b\n end",
"def deal_with_payment\n if human_amount_due <= 0\n update_attributes!(active: false)\n lease.mark_next_active_from_date(self.due_date)\n else\n true\n end\n end",
"def destroy\n if delete_payment_profile and super\n return true\n else\n return false\n end\n end",
"def approved?\n !self.pending\n end",
"def test_authorization_and_void\n return if Base.mode == :test # only tests in production mode\n assert_equal Base.mode, :production\n assert authorization = @gateway.authorize(@amount, @credit_card, @options)\n assert_success authorization\n \n assert void = @gateway.void(authorization.authorization)\n assert_success void\n assert_match(/This transaction has been approved/, void.message)\n end",
"def pending?\n payment_at.nil?\n end",
"def can_reject?\n !accepted? && !rejected? && !withdrawn?\n end",
"def reject!\n return false if self.approved == true\n self.destroy\n end",
"def can_pay_pending?\n conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool\n conf_payment_deposit = (['deposit','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit')))\n conf_payment_pending = SystemConfiguration::Variable.get_value('booking.allow_pending_payment', 'false').to_bool\n if (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and conf_payment_pending and self.status != :cancelled\n self.total_paid > 0\n else\n return false\n end\n end",
"def authorizable_cc_payment?\n adyen_cc_payment? && amount != 0\n end",
"def cc_pay?\n plan&.direct_pay && id != 3744\n end",
"def pending?\n !self.canceled?\n end",
"def technically_paid?\n unconfirmed_value_paid >= value_needed\n end",
"def can_capture?(payment)\n payment.checkout?\n end",
"def is_manual?\n payment_kind == 'manual'\n end",
"def verify!\n raise \"Payment details not active anymore\" if active == false\n end",
"def paid?\n current_transaction\n end",
"def approved?\n !pending\n end",
"def free?\n cost == 0.0 || payment_not_required\n end",
"def pending_deletable?\n !pending_delete_prohibited?\n end",
"def credit_unlimited?\n #if prepaid?\n # raise \"Prepaid users do not have credit\"\n credit == -1\n end",
"def require_one_click_payment?(source, shopper)\n false\n end",
"def canceled_by_user?\n cancel_reason == PAYMENT_CANCELED\n end"
] |
[
"0.8414637",
"0.8414637",
"0.83615565",
"0.83615565",
"0.8343824",
"0.83381695",
"0.83381695",
"0.8314558",
"0.82425183",
"0.82425183",
"0.7034634",
"0.67792964",
"0.6753569",
"0.66845626",
"0.6645172",
"0.655368",
"0.6535386",
"0.6432738",
"0.6413752",
"0.6403974",
"0.6372271",
"0.6345093",
"0.6345093",
"0.6345093",
"0.6345093",
"0.6345093",
"0.62849617",
"0.6275267",
"0.62740374",
"0.6247822",
"0.6243406",
"0.62250245",
"0.62244344",
"0.6211772",
"0.62077403",
"0.6204708",
"0.6200113",
"0.6193152",
"0.61879605",
"0.61879605",
"0.61803544",
"0.6160425",
"0.61593497",
"0.61517215",
"0.6149852",
"0.6149852",
"0.6140135",
"0.6123242",
"0.6090431",
"0.6086983",
"0.6083711",
"0.6083711",
"0.60602254",
"0.60448337",
"0.6035236",
"0.60326016",
"0.60308975",
"0.60161155",
"0.600306",
"0.59985423",
"0.599123",
"0.599123",
"0.5986141",
"0.5981576",
"0.59602255",
"0.5958762",
"0.5958155",
"0.5950703",
"0.5949185",
"0.59418577",
"0.594106",
"0.5934158",
"0.5928771",
"0.59253037",
"0.5919024",
"0.5916805",
"0.59145993",
"0.5911992",
"0.5880878",
"0.5859505",
"0.5856417",
"0.5855412",
"0.58510274",
"0.5847799",
"0.5844867",
"0.5844511",
"0.5842209",
"0.58274215",
"0.5824397",
"0.58237207",
"0.58166313",
"0.58160883",
"0.581278",
"0.58058405"
] |
0.8435381
|
6
|
this is smelly. IMO there's a 'bug' in spree in the admin payment view. Whey are we asking about sources with profile I filed:
|
def sources_with_profile(order)
nil
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def associate_payment_profile\n order = Spree::Order.where(\"email = ?\", @user.email).order(\"created_at\").last\n if order.try(:payments).present?\n payment_source = order.payments.last.source\n payment_source.update_attributes(user_id: @user.id)\n end\n end",
"def payment_source_class\n ::Spree::PaymentSource::PAYONE::PayoneEWalletPaymentSource\n end",
"def before_payment\n if try_spree_current_user && try_spree_current_user.respond_to?(:payment_sources)\n @payment_sources = try_spree_current_user.payment_sources\n end\n end",
"def payment_source_class\n ::Spree::PaymentSource::PAYONE::PayoneCashInAdvancePaymentSource\n end",
"def supports_saved_payment_source\n true\n end",
"def payment_profiles_supported?\n false\n end",
"def guard_process_payment_from_created; true; end",
"def guard_process_payment_from_created; true; end",
"def payee\n profile\n end",
"def show\n @order = Spree::Order.find(params[:order_id])\n @gateway = @order.available_payment_methods.find{|x| x.id == params[:gateway_id].to_i }\n\n if @order.blank? || @gateway.blank?\n flash[:error] = I18n.t(\"invalid_arguments\")\n redirect_to :back\n else\n\t\t\t@pay_type = @gateway.options[:pay_type]\n\t\t\t@price = sprintf(\"%.2f\",@order.total.to_f).to_f\n\t\t\t@currency = @gateway.options[:currency]\n\t\t\t@convert_currency = @gateway.options[:convert_currency] ? 'yes':'no'\n\t\t\t@price_final = @gateway.options[:price_final] ? 'yes':'no'\n\t\t\t@user_email = @order.email\n\t\t\t@md5 = Digest::MD5.hexdigest([@gateway.options[:pay_type],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsprintf(\"%.1f\",@order.total.to_f).to_f,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t@currency,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t@order.id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t@convert_currency,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t@gateway.options[:priv_code]].join(';'))\n\n render :action => :show\n end\n end",
"def pre_pay_offered\n end",
"def payment_instruction\n end",
"def payment_type\n :credit_card\n end",
"def wallet_payment_sources\n user.wallet_payment_sources.to_a\n end",
"def payment_source_class\n nil\n end",
"def service_payment_info_loop\n end",
"def provider_class\n ::Spree::PAYONE::Provider::Payment::EWallet\n end",
"def payment_term; end",
"def before_payment\n #remove any payments if you are updatind\n # current_order.payments.destroy_all if request.put?\n if current_user\n @order.bill_address ||= Address.default\n @order.bill_address.user = current_user\n else\n @order.bill_address ||= Address.default\n end\n end",
"def verify_payment_profile(user) \n resp = self.gateway.get_customer_profile({ :customer_profile_id => user.authnet_customer_profile_id }) \n if resp.success?\n arr = resp.params['profile']['payment_profiles'] \n arr = [arr] if arr && arr.is_a?(Hash)\n if arr.nil? || arr.count == 0\n self.create_empty_payment_profile(user)\n user.valid_authnet_payment_profile_id = false \n else \n h = arr[0]\n user.authnet_payment_profile_id = h['customer_payment_profile_id'] \n user.valid_authnet_payment_profile_id = h['bill_to'] && h['bill_to']['address'] && h['bill_to']['address'].strip.length > 0 \n user.save\n end\n end \n end",
"def profile_state\n\t\tresponse=Partay.get('http://shoponline.tescolotus.com/api/v1/Customer/',:headers => {'Content-Type' => 'application/json', 'language' => 'en-GB', 'region' => 'TH', 'userId' => access_token })\n\t\tputs response\n\t\tself.profile(JSON(response)[\"InAmendOrderMode\"])\n\tend",
"def collect_payment?\n true\n end",
"def payment_profile_options(user, params)\n bt_address = \"#{params[:billing][:address]}\"\n bt_address << \", #{params[:billing][:address2]}\" if params[:billing][:address2] && params[:billing][:address2].strip.length > 0 \n \n return { \n :customer_profile_id => user.authnet_customer_profile_id.to_i, \n :payment_profile => {\n :bill_to => {\n :first_name => params[:billing][:first_name],\n :last_name => params[:billing][:last_name],\n :address => bt_address,\n :city => params[:billing][:city],\n :state => params[:billing][:state],\n :zip => params[:billing][:zip],\n :phone_number => user.phone,\n :email => user.email\n }, \n :payment => {\n :credit_card => Caboose::StdClass.new({\n :number => params[:credit_card][:number],\n :month => params[:credit_card][:expiration_month].to_i,\n :year => \"20#{params[:credit_card][:expiration_year].to_i}\",\n :first_name => params[:billing][:first_name],\n :last_name => params[:billing][:last_name]\n })\n }\n },\n :validation_mode => :live\n }\n end",
"def franchisee_royalty_pay_slip\n \n end",
"def show\n #allowing a \"buyer\" to purchase \n if params[:checkout] == \"success\"\n #update buyer - creating a new buyer and linking that to the profile table before updating the buyer and saving \n Buyer.create(profile_id: current_user.profile.id)\n @listing.buyer_id = current_user.profile.buyer.id\n @listing.save\n end\n end",
"def navigate_to_payment(skip_authentication = false)\n # set valid Cielo config\n Spree::CieloConfig.test_mode = true\n Spree::CieloConfig.afiliation_key = '12345'\n Spree::CieloConfig.token = 'abc1234'\n Spree::CieloConfig.credit_cards = {'visa' => 10}\n Spree::CieloConfig.minimum_value = '5.0'\n\n # add mug to cart\n visit spree.root_path\n click_link mug.name\n click_button 'add-to-cart-button'\n click_button 'Checkout'\n\n if !skip_authentication\n fill_in 'spree_user_email', with: 'test@example.com'\n fill_in 'spree_user_password', with: 'spree123'\n fill_in 'spree_user_password_confirmation', with: 'spree123'\n click_on 'Create'\n end\n\n # set address\n address = 'order_bill_address_attributes'\n fill_in \"#{address}_firstname\", with: 'Ryan'\n fill_in \"#{address}_lastname\", with: 'Bigg'\n fill_in \"#{address}_address1\", with: '143 Swan Street'\n fill_in \"#{address}_city\", with: 'Richmond'\n select 'United States of America', from: \"#{address}_country_id\"\n select 'Alabama', from: \"#{address}_state_id\"\n fill_in \"#{address}_zipcode\", with: '12345'\n fill_in \"#{address}_phone\", with: '(555) 555-5555'\n # confirm address\n click_button 'Save and Continue'\n\n # confirm shipping method\n click_button 'Save and Continue'\nend",
"def purchase_sub_existing_choose\n @plan = params[:sec][:plan] #now this is an integer, my_plan_id\n @planobject = Plan.find_by_my_plan_id(@plan)\n @events_number = @planobject.events_number \n # if user is a stripe customer (even though no acticve sub), want to allow him to use existing card\n if !current_user.customer_id.blank? \n c = Stripe::Customer.retrieve(current_user.customer_id)\n @last4 = c.cards.data.first.last4\n @cardtype = c.cards.data.first.type\n end \n\nend",
"def atest_ID_25845_edit_profile_edit_profile_details\n # Need clarification\n end",
"def billingCycle profile_name\n end",
"def payment_gateway_profile_attributes\n PaymentGatewayProfile.card_virtual_attributes.inject({ }) { |acc, e| acc[e] = \"\"; acc }\n end",
"def changesub_existinguser\n @plan = params[:sub][:plan] # this is an integer corresponding to my_plan_id\n @planobject = Plan.find_by_my_plan_id(@plan)\n @events_number = @planobject.events_number \n @code = params[:sub][:code]\n\n if is_valid_sub_coupon(@code) && !@planobject.nil?\n @coupon = Coupon.find_by_name(@code)\n @new_price = @planobject.monthly_cost_cents * (100 - @coupon.percent_off)/100\n flash.now[:success] = \"Your promo code has been applied!\"\n else #could not find that coupon\n @code = nil \n @coupon = nil \n @new_price = nil\n end\n\n if !current_user.customer_id.blank?\n c = Stripe::Customer.retrieve(current_user.customer_id)\n @last4 = c.cards.data.first.last4\n @cardtype = c.cards.data.first.type\n end \n\n render action: 'purchase_sub_existing_choose'\n\nend",
"def index\n @profile = current_user.payment_profile || Payments::Profile.new(email: current_user.login)\n end",
"def premium_paid\n wizard_step(returns_lbtt_tax_npv_url) { { after_merge: :update_npv_calculation, cache_index: LbttController } }\n end",
"def show\n @payment = Payment.new\n @creditcard = ActiveMerchant::Billing::CreditCard.new\n \n end",
"def show\n @order = Order.find(params[:order_id])\n @gateway = @order.available_payment_methods.find{|x| x.id == params[:gateway_id].to_i }\n @order.payments.destroy_all\n @hash = Digest::MD5.hexdigest(@gateway.preferred_secret_key+\"|\"+@gateway.preferred_account_id+\"|\"+@order.total.to_s+\"|\"+@order.number+\"|\"+[gateway_ebsin_comeback_url(@order),'DR={DR}'].join('?')+\"|\"+@gateway.preferred_mode)\n payment = @order.payments.create!(:amount => 0, :payment_method_id => @gateway.id)\n\n if @order.blank? || @gateway.blank?\n flash[:error] = I18n.t(\"invalid_arguments\")\n redirect_to :back\n else\n @bill_address, @ship_address = @order.bill_address, (@order.ship_address || @order.bill_address)\n render :action => :show\n end\n end",
"def payment_description\n\t\t\t\t\treturn nil\n\t\t\t\tend",
"def accounts_with_usage; end",
"def _spent_on\n return payment\n end",
"def update_params_payment_source\n if has_checkout_step?(\"payment\") && self.payment?\n if @updating_params[:payment_source].present?\n source_params = @updating_params.delete(:payment_source)[non_wallet_payment_method]\n\n if source_params\n non_wallet_payment_attributes(@updating_params[:order][:payments_attributes]).first[:source_attributes] = source_params\n end\n end\n\n if (@updating_params[:order][:payments_attributes])\n user = user_or_by_email\n # This method is overrided because spree add all order total in first payment, now after wallet we can have multiple payments.\n if user && available_wallet_payment_method\n wallet_payments = wallet_payment_attributes(@updating_params[:order][:payments_attributes])\n wallet_payments.first[:amount] = [remaining_total, user.store_credits_total].min if wallet_payments.present?\n @updating_params[:order][:payments_attributes] = wallet_payments if remaining_order_total_after_wallet(wallet_payments) <= 0\n non_wallet_payment_attributes(@updating_params[:order][:payments_attributes]).first[:amount] = remaining_order_total_after_wallet(wallet_payments) if non_wallet_payment_attributes(@updating_params[:order][:payments_attributes]).present?\n else\n @updating_params[:order][:payments_attributes].first[:amount] = remaining_total\n end\n end\n end\n @updating_params[:order]\n end",
"def full_details\n @account = Account.find(params[:account_id])\n @subscription = @account.subscriptions.find(params[:id])\n @order = Order.find(@subscription.order_id)\n\n if @order.user_id\n @user = User.find(@order.user_id)\n end\n\n if @order.by_agent\n @agent = User.find(@order.by_agent)\n end\n\n if @order.price_plan_id\n @price_plan = Country.where(:\"price_plans._id\" => @order.price_plan_id).first.price_plans.find(@order.price_plan_id)\n end\n\n respond_to do |format|\n format.html {render(layout: 'management')}\n end\n end",
"def pay_status_paypal\n\n end",
"def provider_class\n ActiveMerchant::Billing::Integrations::Europabank\n end",
"def wizard_new\n \n @subtype=params[:sub_type]\n @package = \"\"\n @image = \"\"\n if @subtype == \"1\"\n @package = \"Basic Snack Pack\"\n @image = \"/../assets/new-design/img1-mem.jpg\"\n elsif @subtype == \"2\"\n @package = \"Double Snack Pack\"\n @image = \"/../assets/new-design/img1-mem.jpg\"\n else\n @package = \"Family Snack Pack\"\n @image = \"/../assets/new-design/img1-mem.jpg\"\n end\n @subscription = Subscription.find_by_id @subtype\n unless @subscription.blank?\n if request.env['omniauth.auth'].present?\n params = request.env[\"omniauth.params\"]\n\n @fb_data = fetch_facebook_params\n @user = Spree::User.where(email: @fb_data[:email]).first\n\n\n if (@user.blank? && params[\"login\"].present?) || (@user.present? && is_ordinary_user?(@user.facebook_token) && params[\"login\"].present?)\n\n #here need to check if it's a fb registered user + in params we must receive login\n #if !is_ordinary_user?(@user.facebook_token) && params[\"login\"].present?\n #use the @not_yet_fb_signed_up to notify the message at the top.\n\n @not_yet_fb_signed_up = true\n @user = Spree::User.new\n @user.addresses.build\n @user.creditcards.build\n\n #user does not registered yet & coming for signup(or login params is blank.)\n elsif @user.blank? && params[\"login\"].blank?\n @user = Spree::User.new(email: @fb_data[:email], facebook_token: @fb_data[:fb_token], image: @fb_data[:image])\n @user.addresses.build\n @user.creditcards.build\n @user.addresses.first.firstname = @fb_data[:firstname]\n @user.addresses.first.lastname = @fb_data[:lastname]\n\n #user is registered & still trying for signup via facebook\n elsif @user.present? && params[\"login\"].blank?\n @registered_email = @user.email\n @user = Spree::User.new\n @user.addresses.build\n @user.creditcards.build\n else\n #update the token if @user_founds token is not same as the @fb_token\n @user.update_attributes(facebook_token: @fb_data[:fb_token], image: @fb_data[:image]) if @user.facebook_token != @fb_data[:fb_token]\n sign_in(:spree_user, @user)\n redirect_to spree.snack_queue_orders_path\n end\n\n else\n @user = Spree::User.new\n @user.addresses.build\n @user.creditcards.build\n\n end\n \nelse\n redirect_to root_path\nend\n \n end",
"def test_switch_taxes_off_in_profile_and_check_new_invoice_has_taxes_disabled\r\n $test_ui.agree('continue?', true) if @debug\r\n update_profile_taxes(\r\n :tax_enabled => false)\r\n\r\n \r\n deny @profile.tax_enabled, \"after setting tax_enabled to false on profile page, profile.tax_enabled was not false\"\r\n goto_new_invoice_url \r\n\r\n $test_ui.agree('continue?', true) if @debug\r\n\r\n deny_tax_enabled_name_and_rate_exist(\r\n \"after disabling taxes in profile settings and creating a new invoice\",\r\n :tax_1_enabled => @profile.tax_1_enabled,\r\n :tax_1_name => @profile.tax_1_name,\r\n :tax_1_rate => @profile.tax_1_rate, \r\n :tax_2_enabled => @profile.tax_1_enabled,\r\n :tax_2_name => @profile.tax_2_name,\r\n :tax_2_rate => @profile.tax_2_rate)\r\n @debug = false\r\n end",
"def default_wallet_payment_source\n user.wallet_payment_sources.find_by(default: true)\n end",
"def profile; end",
"def profile; end",
"def payer_first_name\n user_payment_method.first_name\n end",
"def cms_voucher_request?\n false\n end",
"def activate\n\n # load two modified/updated files for active merchant\n require File.join(Protx3dsGatewayExtension.root, \"lib\", \"active_merchant\", \"billing\", \"gateways\", \"protx.rb\")\n require File.join(Protx3dsGatewayExtension.root, \"lib\", \"active_merchant\", \"billing\", \"gateways\", \"protx3ds.rb\")\n\n # NOTE: monkey patch the extended gateway interface into place\n Creditcard.class_eval do\n # add gateway methods to the creditcard so we can authorize, capture, etc.\n # this needs to be loaded after the standard gateway\n include Spree::PaymentGatewayForProtx3ds\n\n # request that a card payment to use 3ds\n attr_accessor :use_3ds\n end\n\n # can't do auto captures here, since payment mech isn't necess simple - rethink\n unless Spree::Config[].nil?\n Spree::Config.set(:auto_capture => false)\n end\n\n Checkout.class_eval do\n # can't do auto captures here, since payment mech isn't necess simple - rethink\n # monkey-patched in directly, since there's an issue with including a private mthd via module ...\n private\n def authorize_creditcard\n # not doing any card authorization\n end\n end\n\n # add in the actions for the 3ds particulars\n CheckoutsController.class_eval do \n # import the new operations\n include Spree::UpdateMethod\n include Spree::Protx3dsController\n ssl_required :enter_3dsecure, :complete_3dsecure, :callback_3dsecure\n protect_from_forgery :except => :callback_3dsecure\n end\n\n # NOTE: monkey patch until spree master catches up\n Order.class_eval do \n # need this to allow updates later on\n attr_protected :vtx_code\n\n # register a new creditcard payment sequence, returning the actual transaction added\n def new_payment(card, taken_amount, auth_amount, auth_code, txn_type)\n payment = creditcard_payments.create(:amount => taken_amount, :creditcard => card)\n # create a transaction to reflect the authorization\n transaction = CreditcardTxn.new( :amount => auth_amount,\n :response_code => auth_code,\n :txn_type => txn_type )\n payment.creditcard_txns << transaction\n transaction\n end\n end\n end",
"def require_one_click_payment?(source, shopper)\n false\n end",
"def change_address_payment_page_link\n $tracer.trace(__method__)\n #unit_test_no_generate: change_address_payment_page_link, a.className(create_ats_regex_string(\"ats-editbillingaddr\"))\n return ToolTag.new(a.className(create_ats_regex_string(\"ats-editbillingaddr\")), __method__, self)\n end",
"def preview\n @referral = ReferralCategory.order(\"id ASC\")\n @title_page = \"More Info\"\n if order.items.select{|i| i.premium? }.blank?\n redirect_to premium_manage_orders_path\n elsif order.total.to_i < 1\n redirect_to dashboard_path\n end\n\n if current_user && order\n customer_profile = order.orderable ? order.orderable.profile : nil\n if customer_profile\n customer_profile.referal_id = current_user.code \n customer_profile.referal = current_user.referral_category.name if current_user.referral_category\n else\n redirect_to new_customer_manage_orders_path\n end\n end\n end",
"def payment_method\n self.payments.last.andand.payment_method || \"none\"\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def in_payment?\n @in_payment\n end",
"def activate \n # credit card numbers should always be stored in the case of offline processing (no other option makes sense)\n #Spree::Config.set(:store_cc => true) \n \n Creditcard.class_eval do \n require 'openssl'\n require 'base64'\n \n # overrides filter_sensitive to make sure the stored values are encrypted.\n private\n def filter_sensitive \n # don't encrypt again, this way we can clone an order and its creditcard and keep text encrypted\n return unless encrypted_text.blank?\n gnupg = GnuPG.new :recipient => Spree::Pgp::Config[:email]\n public_key_text = Rails.cache.fetch('public_key') do\n File.read(\"#{RAILS_ROOT}/#{Spree::Pgp::Config[:public_key]}\")\n end\n gnupg.load_public_key public_key_text \n text = \"Number: #{number} Code: #{verification_value}\"\n self[:encrypted_text] = gnupg.encrypt(text)\n self[:number] = \"\"\n self[:verification_value] = \"\"\n end\n end\n \n # register Creditcards tab\n Admin::BaseController.class_eval do\n before_filter :add_creditcard_tab\n\n private\n def add_creditcard_tab\n @order_admin_tabs ||= []\n @order_admin_tabs << {:name => t('credit_cards'), :url => \"admin_order_creditcards_url\"} \n end\n end \n \n end",
"def payments?\n user_record? || payment_admin? || super_admin?\n end",
"def collect_billing_info\n return if self.class.to_s.match(/^Devise/) # Don't prevent logins, etc.\n return if request.path.match(/^\\/saas_admin/) # Admins don't need to pay\n return unless account = current_account # Nothing to do if there is no account\n return if !(sub = account.subscription) || sub.state.nil?\n return if sub.state == 'active' && sub.current? && !sub.needs_payment_info?\n return if sub.state == 'trial' && (!Saas::Config.require_payment_info_for_trials || !sub.needs_payment_info?)\n redirect_to billing_account_path\n end",
"def managed?; stripe_account_type == 'managed'; end",
"def managed?; stripe_account_type == 'managed'; end",
"def payout\n\t\t# if !current_user.merchant_id.blank?\n # \t\t\taccount = Stripe::Account.retrieve(current_user.merchant_id)\n # \t\t\t@login_link = account.login_links.create()\n\t\t# end\n end",
"def build\n credit_card = order.user.try!(:default_credit_card)\n\n if credit_card.try!(:valid?) && order.payments.from_credit_card.count == 0\n Spree::Payment.new(\n payment_method_id: credit_card.payment_method_id,\n source: credit_card,\n )\n end\n end",
"def dod_paygrade; end",
"def account_src\n account_src_id\n end",
"def create_empty_payment_profile(user) \n options = {\n :customer_profile_id => user.authnet_customer_profile_id.to_i, \n :payment_profile => {\n :bill_to => { :first_name => user.first_name, :last_name => user.last_name, :address => '', :city => '', :state => '', :zip => '', :phone_number => '', :email => user.email }, \n :payment => { :credit_card => Caboose::StdClass.new({ :number => '4111111111111111', :month => 1, :year => 2020, :first_name => user.first_name, :last_name => user.last_name }) }\n }\n #, :validation_mode => :live\n } \n resp = self.gateway.create_customer_payment_profile(options) \n if resp.success? \n user.authnet_payment_profile_id = resp.params['customer_payment_profile_id'] \n user.save\n else\n puts \"==================================================================\" \n puts resp.message\n puts \"\"\n puts resp.inspect\n puts \"==================================================================\"\n end\n end",
"def payment_price_shipping\n\t\t\t\t\treturn nil\n\t\t\t\tend",
"def payment_type\n :credit_card\n end",
"def show\n @current_locale = current_locale\n @order = Order.find(params[:id])\n redirect_to :action => \"index\" and return if current_admin.limited_sales_rep && !current_admin.users.include?(@order.user)\n new_payment(@order.user) if @order.can_be_paid?\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @order }\n end\n end",
"def update\n @user = current_user\n @order = Order.find(params[:id])\n @price_plan = Country.get_price_plan_by_country_and_id(current_user.account.country_short, @order.price_plan_id)\n\n if @order.save\n if @order.purchase\n\n @order.update_attributes(kind: 'paypal', state: 'success', completed_at: Time.now.utc)\n @price_plan.mark_promotion_code_for_usage(@order)\n subscription = @user.account.add_subscription(@price_plan, @order)\n subscription.activate\n @user.account.finish_registration()\n\n redirect_to( action: 'success', id: @order )\n else\n redirect_to( action: 'failure', id: @order )\n end\n else\n render action: 'edit'\n end\n end",
"def test_a_user_can_create_company_billing_profile_witout_vat_code\n visit new_billing_profile_path\n fill_in_address\n\n fill_in('billing_profile[name]', with: 'ACME corporation')\n\n assert_changes('BillingProfile.count') do\n click_link_or_button('Submit')\n end\n\n assert(@user.billing_profiles\n .where(name: 'ACME corporation')\n .where('vat_code IS NULL'))\n\n assert(page.has_css?('div.notice', text: 'Created successfully.'))\n end",
"def show\n # fix login bug that redirects to accounts/1\n @account = Account.find(params[:id]) \n\n # if current_user && current_user.email.present? && current_user.email.ends_with?('_admin@leadplace.com')\n # current_user.update_attribute :admin, true\n # end\n\n @buying = session[:feewise_inproc_buying]\n @purchase_preference = current_user.purchase_preference if !current_user.blank?\n\n begin\n # Rails.env.production? || Rails.env.staging? do\n#### logger.warn \"Sending email to: #{current_user.email} subject: #{current_user.full_name} has signed up\"\n#### UserMailer.welcome_email(current_user).deliver if current_user\n # end\n rescue Exception => e\n note = \"Attempted to notify feewise that there is a paying customer but email failed for #{current_user.full_name} #{current_user.email}\"\n logger.error note\n Bulletin.create! :body => note, :kind => 'error'\n errors.add :base, \"There was a problem notifying Feewise of your request. Your request will be resent until it is acknowledged. Thank you! Feel free to contact us by phone. We want you to have the most timely service \"\n end\n redirect_to PurchaseFlow.step_path(2, @purchase_preference) and return if @buying && current_user\n\n if !@buying && current_user\n render :show and return\n else\n redirect_to admin_root_path\n end\n\n end",
"def chargeable_profiles\n profile ? [profile] : []\n end",
"def assign_default_credit_card\n true\n end",
"def profile\n\n end",
"def create_first_payment\n make_payment\n end",
"def variant_full_price(variant)\nproduct = variant.product\nunless product.variants.active(current_currency).all? { |v| v.price == product.price }\nSpree::Money.new(variant.price, { currency: current_currency }).to_html\nend\nend",
"def contact_us_to_complete_payment\n # Horrible hack: when the user triggers a £40 edit charge, chooses a payment\n # method but then navigates backward, we get into a state where we can no\n # longer compare the \"old\" and \"new\" carrier types (because we no longer\n # know what the \"old\" type was as its now been overwritten in Mongo). This\n # means the new charge determination will output no charge, potentially\n # making the change of carrier type free.\n setup_registration('payment', true)\n render_not_found and return unless @registration\n end",
"def store_credit_card?\n paid?\n end",
"def profile\n super\n end",
"def profile\n super\n end",
"def auto_dispute_order_details\n nil\n end",
"def payment_type\n self.transcation_payment_type\n end",
"def credit_card_type; end",
"def billing_info_edit\n result = ChargeBee::Customer.retrieve(@customer_id)\n @customer = result.customer\n @billing_address = result.customer.billing_address\n @country_codes = get_country_codes\n end",
"def prepare_subscription\n @subscriptions = Subscription.all\n @my_subscription = current_user.user_subscriptions.includes(:subscription).where(\"user_subscriptions.id = ? and user_subscriptions.status = ?\", params[:id], \"active\").first\n\n if @my_subscription.blank?\n flash[:error] = \"Sorry, You are not authorized for this subscription.\"\n redirect_to main_app.profile_users_path and return\n else\n #@order = @my_subscription.orders.where(state: :confirm).first\n @order= @my_subscription.orders.where('state = ? and delivery_date > ?',\n 'confirm', (ORDER_UPDATE_LIMIT+1).days.from_now.to_date).first\n\n @cart = Cart.get_cart(current_user.id)\n @cart.prepare_cart(current_user.id, @order.subscription_id)\n order_subscription_token = @cart.copy_order_to_cart(@order.id)\n\n @current_cart_items = @cart.get_cart_items\n @subscription_offers = Subscription.get_subscription_list\n @total_space = @cart.max_cart_items\n @snacks = Spree::Product.select('id, name')\n @my_subscription_id = @my_subscription.subscription.id\n @my_subscription_type = @my_subscription.subscription.subscription_type\n end\n end",
"def payment\n @payment ||= user.try(:payment_method).try(:to_payment)\n end",
"def payment_type_t\n self.payment_type_s.t\n end",
"def display_resource(single_payment)\n single_payment.name\n end",
"def test_success_cc_payment_page\r\n @u = users(:user_without_sps_gateway_settting)\r\n @user = watir_session.with(:user_without_sps_gateway_settting)\r\n @user.logs_in\r\n\r\n @invoice = invoices(:invoice_moneris_payment_cc)\r\n \r\n \r\n b = @user.b\r\n add_sps_cc_profile(:user_without_sps_gateway_settting)\r\n @url = send_invoice(@invoice.id, true, true, true)\r\n \r\n total = b.span(:id, \"invoice_total\").text\r\n assert_equal \"10.00 CAD\", total\r\n\r\n link = b.link(:text, \"Pay Invoice\")\r\n link.click\r\n b.wait\r\n \r\n b.button(:value, \"Pay Now\").click\r\n b.wait\r\n assert b.html.include?(\"12 errors\"), \"cannot find validation error message\"\r\n \r\n pay = Payment.find(:first, :conditions => {:pay_type => 'moneris' })\r\n assert_equal 'created', pay.status\r\n\r\n b.text_field(:id, 'card_number').value=('4242424242424242')\r\n b.text_field(:id, 'card_first_name').value=('Payer First')\r\n b.text_field(:id, 'card_last_name').value=('Payer Last')\r\n b.select_list(:id, 'card_year').option(:text, '2012').select\r\n b.text_field(:id, 'card_verification_value').value=('123')\r\n \r\n\r\n b.text_field(:id, 'billing_address_name').value=('Payer Name')\r\n b.text_field(:id, 'billing_address_address1').value=('Payer Address1')\r\n b.text_field(:id, 'billing_address_city').value=('Payer City')\r\n b.select_list(:id, 'billing_address_state').select('BC - British Columbia')\r\n b.text_field(:id, 'billing_address_zip').value=('12345')\r\n b.text_field(:id, 'billing_address_phone').value=('123-456-7890')\r\n b.text_field(:id, 'billing_address_email').value=('test@test.com')\r\n \r\n b.button(:value, \"Pay Now\").click\r\n b.wait\r\n assert b.html.include?(\"successfully recorded\")\r\n pay = Payment.find(:first, :conditions => {:pay_type => 'moneris' })\r\n assert_equal 'cleared', pay.status\r\n \r\n @user.goto(@url)\r\n b.wait\r\n sleep 3\r\n #verify pay invoice link does not exist\r\n assert !b.html.include?(\"Pay Invoice\") , \"Paid invoice link found for fully paid invoice.\"\r\n inv = Invoice.find(@invoice.id)\r\n assert_equal \"paid\", inv.status\r\n assert_equal 0.0, inv.owing_amount\r\n assert_equal inv.total_amount, inv.paid_amount\r\n \r\n \r\n @u = nil\r\n @user.teardown \r\n end",
"def tax_profile_amount\n return self.tax_profile.value\n end",
"def real_payment_method_name\n client_payments.last.payment_method.to_label rescue ''\n end",
"def need_details?\r\n admin? || purchasing? || popv_admin?\r\n end",
"def name\n object.merchant.name\n end",
"def merchant_defined_data1\n @user\n end",
"def paid_with_card?\n payment_type == \"card\"\n end"
] |
[
"0.6521839",
"0.63903046",
"0.6331863",
"0.632724",
"0.62157273",
"0.60296845",
"0.60243315",
"0.60243315",
"0.5974015",
"0.5944873",
"0.5898278",
"0.58730257",
"0.5835857",
"0.5832085",
"0.5814041",
"0.57760257",
"0.57676846",
"0.5728966",
"0.5662179",
"0.5631374",
"0.56198317",
"0.56156045",
"0.56152445",
"0.5602241",
"0.56012017",
"0.55635965",
"0.55575716",
"0.5530754",
"0.5525111",
"0.5517515",
"0.54834205",
"0.54832697",
"0.5470755",
"0.5470551",
"0.5469763",
"0.5468449",
"0.54633",
"0.54605365",
"0.54579294",
"0.5456889",
"0.5453737",
"0.54430234",
"0.5434719",
"0.54038244",
"0.54007137",
"0.53979",
"0.53979",
"0.53930116",
"0.53857136",
"0.5379581",
"0.53754956",
"0.5369222",
"0.5365624",
"0.53629035",
"0.5359802",
"0.5359802",
"0.5359802",
"0.5359802",
"0.5359802",
"0.5359802",
"0.5358948",
"0.53573775",
"0.5353137",
"0.53362834",
"0.53337926",
"0.53337926",
"0.5332307",
"0.5330784",
"0.5327751",
"0.5326318",
"0.5320092",
"0.5317955",
"0.53134793",
"0.53093743",
"0.5306265",
"0.52974176",
"0.52931327",
"0.5292405",
"0.5292369",
"0.5284204",
"0.5282582",
"0.52806365",
"0.528052",
"0.526659",
"0.5261084",
"0.5261084",
"0.5257724",
"0.52574974",
"0.52552265",
"0.5247208",
"0.52466166",
"0.5244741",
"0.52438945",
"0.5243745",
"0.52328426",
"0.5232506",
"0.52304786",
"0.52283895",
"0.5228185",
"0.5226993",
"0.5219019"
] |
0.0
|
-1
|
Public: Creates a new Group. name The name of the group as a Symbol. plugin The FeverFacade::Manager to which the group belongs. Returns a Group.
|
def initialize(name, plugin)
@name = name
@context = Context.new(plugin, plugin.graph)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def new_group(name, sub_group_path = nil)\n group = project.new(PBXGroup)\n group.name = name\n\n target = find_subpath(sub_group_path, true)\n target.children << group\n group\n end",
"def new_group(name, sub_group_path = nil)\n group = project.new(PBXGroup)\n group.name = name\n\n target = find_subpath(sub_group_path, true)\n target.children << group\n group\n end",
"def create_group(name, options={})\n body = {:name => name}.merge(options)\n post(\"/groups\", :body => body)\n end",
"def group(name)\n return false unless present?(name)\n\n model.group = name\n\n Vedeu.groups.by_name(name).add(model.name)\n end",
"def group(name)\n return false unless present?(name)\n\n model.group = name\n\n Vedeu.groups.by_name(name).add(model.name)\n end",
"def group_new(name, client_id = nil)\n args = { :user => self, :name => name }\n args[:client_id] = client_id unless client_id.nil?\n return CakeMail::Group.create(args)\n end",
"def group(name = nil)\n if name\n @groups << name\n self.class.groups[name] ||= []\n self.class.groups[name] << self\n else\n @groups\n end\n end",
"def create_group(groupname)\n current_path = '/api/v1/groups'\n payload = { 'group_name' => groupname }.to_json\n @conn.post(current_path, payload)\n end",
"def add_group(name)\n unless group_exists?(name)\n self.groups.create(:name => name)\n else\n raise GroupAlreadyExists, \"The group '\" + name + \"' already exists.\"\n end\n end",
"def create_group(group_name, path = '/')\n request(\n 'Action' => 'CreateGroup',\n 'GroupName' => group_name,\n 'Path' => path,\n :parser => Fog::Parsers::AWS::IAM::CreateGroup.new\n )\n end",
"def group(path, name)\n RubyAem::Resources::Group.new(@client, path, name)\n end",
"def create_pop_group( name ) \n return \"Group #{name} already exists.\" if NodeGroup.find_by_name( name )\n \n unless File.exists?( SpkDashboard::DATA_PATH + \"/data_#{name}\" )\n return \"No params file found to create group #{name}. FILE: #{SpkDashboard::DATA_PATH + \"/data_#{name}\"}\"\n end\n \n params = self.read_group_params( name )\n \n nodegroup = NodeGroup.new(\n :name => name,\n :node_group_names => [ \"spk_base\" ],\n :parameter_attributes => params )\n \n if nodegroup.save \n return \"Successfully created group #{name}\"\n else\n return \"Failed to create group #{pop}\"\n end\n \n end",
"def new\n @group = Group.new\n end",
"def add_pod_group(name)\n pods.groups.new('name' => name)\n end",
"def group(name)\n @_group = name\n end",
"def get_group( name )\n if ( !@groups.has_key?( name ) )\n @groups[name] = Group.new( name )\n end\n return @groups[name]\n end",
"def create_group(group_node)\n name_ru = group_node.text.delete(\"0-9\")\n Group.create(name_ru: name_ru)\n end",
"def create_group( group_name )\n check_user_pass\n # First we need to clean the group_name since jangosmtp only allows alphanumeric characters\n group_name.tr!('^A-Za-z0-9 ', '')\n options = {\n 'Username' => @username,\n 'Password' => @password,\n 'GroupName' => group_name\n }\n\n response = post_with_attempts( 'AddTransactionalGroup', options )\n if response != false\n new_group_id = Nokogiri::XML.parse(response.body).xpath(\"*\").first.content.split(\"\\n\")[2]\n end\n return new_group_id\n end",
"def createGroup\n call :createGroup\n end",
"def group(name, &blk)\n add_child(:groups, Hubcap::Group.new(self, name, &blk))\n end",
"def group_create(group_name:, trace: false)\n group_query = \"{\\\"group_name\\\":\\\"#{group_name}\\\",\\\"group_external_id\\\":\\\"#{group_name}\\\",\\\"group_management_type\\\":{\\\".tag\\\":\\\"company_managed\\\"}}\"\n dropbox_query(query: '2/team/groups/create', query_data: group_query, trace: trace)\n end",
"def new\n @group = Group.new\n end",
"def new\n @group = Group.new\n end",
"def new\n @group = Group.new\n end",
"def new\n @group = Group.new\n end",
"def new\n @group = Group.new\n end",
"def create\n new_group = Group.new(name: params[:name])\n\n if new_group.save\n render json: { \"notice\"=>\"new group #{params[:name]} successfully created\" }\n else\n render json: { \"alert\"=>\"group creation failed. check params.\" }\n end\n end",
"def create(id, user_id, name)\n user = get_user(user_id)\n group = Group.new(id, user.id, name)\n @@group[id] = group\n group.add(user.id)\n return \"Group Created\"\n end",
"def find_group(name)\n NetCDF::Group.new(@netcdf_elmt.findGroup(name))\n end",
"def group(name = nil, &block)\n make_child(name, nil, &block)\n end",
"def create\n name = params[:name]\n @group = Group.new(name: name)\n @group.creator_id = @current_user.id\n if @group.save\n @current_user.creator_join!(@group)\n respond_with(@group, only: [:id, :name, :creator_id, :admin_id])\n else\n render_error(404, request.path, 20101, @group.errors.as_json)\n end\n end",
"def new\n \t@group = Group.new\n end",
"def create(name, options = {})\n last_slash = name.rindex(\"/\")\n category = name[0 ... last_slash]\n plugin = name[last_slash .. -1]\n\n map = @plugins[category]\n if not map\n raise \"Plugin category #{category} does not exist\"\n elsif not map.has_key? plugin\n raise \"Plugin #{plugin} does not exist in category #{category}\"\n else\n map[plugin].new(options)\n end\n end",
"def add_group(name)\n return nil unless @document\n group = Xcodeproj::Workspace::GroupReference.new(name)\n elem = @document.root.add_element(group.to_node)\n yield group, elem if block_given?\n group\n end",
"def group(name)\n group = name if name.kind_of? Salticid::Group\n group ||= @salticid.group name\n group.hosts |= [self]\n @groups |= [group]\n group\n end",
"def create_group(name, description, visible, owner_id=nil)\n url = \"/groups/#{name}\"\n body = {\n description: description,\n visible_to_all: visible,\n }\n body[:owner_id] = owner_id unless owner_id.nil? || owner_id.empty?\n put(url, body)\n end",
"def groups_create(params = {})\n fail ArgumentError, \"Required arguments 'name' missing\" if params['name'].nil?\n response = @session.do_post \"#{SCOPE}.create\", params\n Slack.parse_response(response)\n end",
"def group(name)\n groups.detect { |group| group.name == name } ||\n raise(\"No such Fever group: #{name.inspect}\")\n end",
"def group(name, &block)\n # Get group\n group = name if name.kind_of? Salticid::Group \n name = name.to_s\n group ||= @groups.find{|g| g.name == name}\n group ||= Salticid::Group.new(name, :salticid => self)\n\n # Store\n @groups |= [group]\n\n # Run block\n if block_given?\n group.instance_exec &block\n end\n\n group\n end",
"def add(name_, opts_={})\n @group._add(name_, opts_)\n end",
"def new\n @group = Group.new \n end",
"def get_create_group( group_name )\n check_user_pass\n existing_group_id = get_group_id( group_name )\n if existing_group_id == nil\n new_group_id = create_group( group_name )\n return new_group_id\n end\n return existing_group_id\n end",
"def create_pseudo_group(groupname, title, description)\n params = { \":name\" => groupname } \n params[\"sakai:pseudoGroup\"] = true\n params[\"sakai:excludeSearch\"] = true\n params[\"sakai:group-description\"] = description || \"\"\n params[\"sakai:group-id\"] = groupname\n params[\"sakai:group-title\"] = title\n response = @sling.execute_post(@sling.url_for($GROUP_URI), params)\n @log.info(\"create_pseudo_group() for #{groupname} POST response code: #{response.code}\")\n @log.debug(\"create_pseudo_group() for #{groupname} POST response body: #{response.body}\")\n @file_log.info(\"create_pseudo_group() for #{groupname} POST response code: #{response.code}\") if (@file_log)\n @file_log.debug(\"create_pseudo_group() for #{groupname} POST response body: #{response.body}\") if (@file_log)\n if (response.code.to_i > 299)\n @log.warn(\"create_pseudo_group() returned #{response.code} group may already exist?\")\n @file_log.warn(\"create_pseudo_group() returned #{response.code} group may already exist?\") if (@file_log)\n end\n end",
"def createGroup(groupName, gid)\r\n uri = sprintf(\"/api/v1/group_categories/%d/groups\", gid) \r\n \r\n dbg(\"POST #{uri}\")\r\n dbg(\"name=#{groupName}\")\r\n newGroup = $canvas.post(uri, {'name' => groupName})\r\n dbg(newGroup)\r\n return newGroup\r\nend",
"def createGroup(groupName, gid)\r\n uri = sprintf(\"/api/v1/group_categories/%d/groups\", gid) \r\n \r\n dbg(\"POST #{uri}\")\r\n dbg(\"name=#{groupName}\")\r\n newGroup = $canvas.post(uri, {'name' => groupName})\r\n dbg(newGroup)\r\n return newGroup\r\nend",
"def group name, opts={}, &block\n opts.reverse_merge! :access => true, :priv => false\n @groups[name] ||= MockLdapGroup.new(self)\n\n if opts[:access]\n @access_groups.push name\n end\n\n if opts[:priv]\n @priv_groups.push name\n end\n\n @groups[name].instance_eval &block\n end",
"def create_group(path, name)\n puts \"creating #{name} on path #{path}\"\n \n ret = RestClient.post \"#{@url}/groups\", \n { path: path, name: name }, \n { \"Private-Token\": @token } \n json = JSON.parse(ret.body)\n\n json['id']\n end",
"def add_group( group )\n type_check( group, Elements::Group )\n assert( !name_defined?(name), \"name [#{name}] is already in use\" )\n \n @groups[group.name] = group\n end",
"def create #:nodoc:\n @group = Group.new(params[:group])\n\n respond_to do |format|\n if @group.save\n flash[:notice] = I18n.t(\"{{value}} was successfully created.\", :default => \"{{value}} was successfully created.\", :value => I18n.t(\"Group\", :default => \"Group\"))\n if params[:create_and_new_button]\n format.html { redirect_to new_group_url }\n else\n format.html { redirect_to groups_url }\n # format.xml { render :xml => @group, :status => :created, :location => @group }\n end\n else\n format.html { render :action => \"new\" }\n # format.xml { render :xml => @group.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n create_params = params_for_create\n\n if group_exists?(create_params[:name])\n render_error_with_message(t('controllers.api.v1.groups.group_found'), :bad_request)\n return\n end\n\n group = @project.groups.new(name: create_params[:name])\n errors = update_article_groups(group, create_params)\n if errors\n render_errors(errors)\n return\n end\n\n respond_with @project do |format|\n format.json { render json: decorate_group(group) }\n end\n end",
"def create_target_group(groupname, title, description)\n params = { \":name\" => groupname }\n params[\"sakai:category\"] = \"group\"\n params[\"sakai:group-description\"] = description || \"\"\n params[\"sakai:group-id\"] = groupname\n params[\"sakai:group-title\"] = title || \"\"\n params[\"sakai:joinRole\"] = \"member\"\n params[\"sakai:roles\"] = '[{\"id\":\"member\",\"title\":\"Member\",\"allowManage\":false},{\"id\":\"manager\",\"title\":\"Manager\",\"allowManage\":true}]'\n params[\"sakai:templateid\"] = \"simplegroup\"\n response = @sling.execute_post(@sling.url_for($GROUP_URI), params)\n @log.info(\"create_target_group() for #{groupname} POST response code: #{response.code}\")\n @log.debug(\"create_target_group() for #{groupname} POST response body: #{response.body}\")\n @file_log.info(\"create_target_group() for #{groupname} POST response code: #{response.code}\") if (@file_log)\n @file_log.debug(\"create_target_group() for #{groupname} POST response body: #{response.body}\") if (@file_log)\n if (response.code.to_i > 299)\n @log.warn(\"create_target_group() returned #{response.code} group may already exist?\")\n @file_log.warn(\"create_target_group() returned #{response.code} group may already exist?\") if (@file_log)\n end\n group = Group.new(groupname)\n return group\n end",
"def group\n @group ||= Group.new @instance, group_id\n end",
"def add_to_group plugin, group:\n group_sym = group.to_sym\n @groups[group_sym] ||= {}\n @groups[group_sym][plugin.to_s] = plugin\n end",
"def create_contact_group(project_name, optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'POST'\n\t\targs[:path]['ProjectName'] = project_name\n\t\targs[:pattern] = '/projects/[ProjectName]/groups'\n\t\targs[:query]['Action'] = 'CreateContactGroup'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :contact_group\n\t\t\targs[:body]['ContactGroup'] = optional[:contact_group]\n\t\tend\n\t\tself.run(args)\n\tend",
"def create\n params[:group].delete(:domain) unless current_group.shapado_version.has_custom_domain?\n @group = Group.new\n if params[:group][:languages]\n params[:group][:languages].reject! { |lang| lang.blank? }\n end\n @group.safe_update(%w[languages name legend description default_tags subdomain logo forum enable_mathjax enable_latex custom_favicon language theme signup_type custom_css wysiwyg_editor], params[:group])\n\n @group.safe_update(%w[isolate domain private], params[:group]) if current_user.admin?\n\n @group.owner = current_user\n @group.state = \"active\"\n\n respond_to do |format|\n if @group.save\n @group.create_default_widgets\n\n Jobs::Images.async.generate_group_thumbnails(@group.id)\n @group.add_member(current_user, \"owner\")\n flash[:notice] = I18n.t(\"groups.create.flash_notice\")\n format.html { redirect_to(domain_url(:custom => @group.domain, :controller => \"admin/manage\", :action => \"properties\")) }\n format.json { render :json => @group.to_json, :status => :created, :location => @group }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @group.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create(name)\n self.new(name)\n end",
"def get_group_by_name(name)\n @groups.each do |group|\n if group[0][\"name\"].downcase == name.downcase\n return group\n end\n end\n end",
"def group(name, &block)\n namespace = Namespace.new(name, &block)\n @blocks << namespace\n namespace\n end",
"def get_or_create_group\n name = metadata['group']\n\n db = DB::Groups.find(name, pool)\n grp = load_group\n\n if db.nil?\n # The group does not exist, create it\n Commands::Group::Create.run!(\n pool: pool.name,\n name: grp.name\n )\n\n return DB::Groups.find(name, pool) || (fail 'expected group')\n end\n\n db\n end",
"def create\n @group = Group.new(group_params)\n unless @group.save\n render :new and return\n end\n msg = [\"Created group.\", rebuild_configs].join(\" \")\n redirect_to groups_url, notice: msg\n end",
"def create_group(attributes)\n BrickFTP::API::Group.create(attributes)\n end",
"def create_group(attributes)\n BrickFTP::API::Group.create(attributes)\n end",
"def create_group\n group new_resource.group do\n gid new_resource.gid\n system true\n end\n end",
"def group(name)\n RouteLookup.new.group(name)\n end",
"def add_to_group(group_path, group_name)\n group = RubyAem::Resources::Group.new(@client, group_path, group_name)\n group.add_member(@call_params[:name])\n end",
"def create\n @group = Group.new(params[:group])\n\n respond_to do |format|\n if @group.save\n format.html { redirect_to(view_group_path(@group.label), :notice => 'Group was successfully created.') }\n format.xml { render :xml => @group, :status => :created, :location => @group }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @group.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @group = LunchGroup.new\n end",
"def im_group_create(body, opts = {})\n im_group_create_with_http_info(body, opts)\n nil\n end",
"def create_by_name(name)\n self.new.tap do |o|\n o.name = name # ambos sirven\n end\n end",
"def new #:nodoc:\n @group = Group.new\n\n respond_to do |format|\n format.html # new.html.haml\n # format.xml { render :xml => @group }\n end\n end",
"def group(name=nil)\n @group ||= if name\n name\n else\n case Pry::Method(block).source_file\n when %r{/pry/.*_commands/(.*).rb}\n $1.capitalize.gsub(/_/, \" \")\n when %r{(pry-\\w+)-([\\d\\.]+([\\w\\d\\.]+)?)}\n name, version = $1, $2\n \"#{name.to_s} (v#{version.to_s})\"\n when /pryrc/\n \"~/.pryrc\"\n else\n \"(other)\"\n end\n end\n end",
"def group name, &block\n Tagz.tag :div, { :class => \"group-#{name}\" }, &block\n end",
"def initialize( name, group=nil )\n @name = name\n @group = group\n\n @count = nil\n end",
"def add_group(groupname, gid=nil)\n\t\t\t\tCfruby.controller.attempt(\"Adding group \\\"#{groupname}\\\"\", 'destructive') {\n\t\t\t\t\t`/usr/bin/niutil -create . /groups/#{groupname}`\n\n\t\t\t\t\tnewgroupid = gid\n\t\t\t\t\tif(newgroupid == nil)\n\t\t\t\t\t\tlastgid = `/usr/bin/nidump group . | /usr/bin/cut -d: -f3 | /usr/bin/sort -n | /usr/bin/tail -n 1`\n\t\t\t\t\t\tnewgroupid = lastgid.to_i() + 1\n\t\t\t\t\tend\t\t\t\t\n\n\t\t\t\t\t`/usr/bin/niutil -createprop . /groups/#{groupname} gid #{newgroupid}`\n\t\t\t\t\t`/usr/bin/niutil -createprop . /groups/#{groupname} users`\n\t\t\t\t}\n\t\t\tend",
"def create(name:, type: 'spread', labels: {})\n if type.to_s != 'spread'\n raise Hcloud::Error::InvalidInput, \"invalid type #{type.inspect}, only 'spread' is allowed\"\n end\n raise Hcloud::Error::InvalidInput, 'no name given' if name.blank?\n\n prepare_request(\n 'placement_groups', j: COLLECT_ARGS.call(__method__, binding),\n expected_code: 201\n ) do |response|\n PlacementGroup.new(client, response.parsed_json[:placement_group])\n end\n end",
"def group(gname)\n jiak.group = gname\n jiak.bucket.name = gname\n end",
"def createGroup _args\n \"createGroup _args;\" \n end",
"def create_group(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'CreateGroup'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'https'\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :comments\n\t\t\targs[:query]['Comments'] = optional[:comments]\n\t\tend\n\t\tif optional.key? :group_name\n\t\t\targs[:query]['GroupName'] = optional[:group_name]\n\t\tend\n\t\tself.run(args)\n\tend",
"def set_group(group_name, hash)\n if @groups.key?(group_name)\n raise DuplicateGroup, \"#{group_name} has already been defined\"\n end\n @groups[group_name] = Group.new(hash)\n end",
"def new_group(group_data)\n [:id, :name].each { |attr| raise(ArgumentError, \"Missing or Invalid Parameter(s)\") unless group_data.key?(attr) }\n set_values group_data\n end",
"def plugin(name, options={})\n ops = resolve_defaults(options)\n GemPlugin::Manager.instance.create(name, ops)\n end",
"def create\n @group = Group.new(group_params)\n\n respond_to do |format|\n if @group.save\n format.json { render json: @group, status: :created }\n else\n format.json { render json: @group.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n save_navi_state(['groups_title', 'new_group'])\n @group = Group.new\n end",
"def create\n group = params[:group] || {}\n group.delete(:locales)\n group.delete(:domains)\n @group = GROUP.new(group)\n @group.current_user = current_user\n\n respond_to do |format|\n if @group.save\n flash[:notice] = 'Group was successfully created.'\n format.html { redirect_to(group_url(@group.id)) }\n format.xml { render :xml => @group, :status => :created, :location => group_url(@group.id) + \".xml\" }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @group.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create!\n misc = GroupCategory.find_by(slug: 'misc').id\n GROUP_NAMES.each do |name|\n # Make the group\n group = Group.where(\n name: name\n ).first_or_create(category_id: misc)\n # Set up an initial owner\n GroupMember.create!(user: owner, group: group, rank: :admin)\n end\n\n # Build up neighborhood, so the aozora groups have each other as neighbors\n GROUP_NAMES.permutation(2) do |from, to|\n src = Group.find_by(name: from)\n dst = Group.find_by(name: to)\n GroupNeighbor.create!(source: src, destination: dst)\n end\n end",
"def create\n if(params[:group][:name].nil?) or (params[:group][:name] == \"\")\n flash[:notice] = \"Group must have a name and description\"\n redirect_to new_group_path\n else\n \n #create a new group\n @group = Group.new(group_params)\n user = User.find(session[:user_id]) \n respond_to do |format|\n if @group.save\n #generate a code for the group\n o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten\n new_code = (0...8).map { o[rand(o.length)] }.join\n @group.update(code: new_code)\n #after group is created add creator to group as leader\n Membership.create!(user_id: session[:user_id], group_id: @group.id, member_type: 'leader', username: user.username)\n format.html {redirect_to @group, notice: \"Group was successfully created.\"}\n format.json {render :show, status: :created, location: @group}\n else\n format.html {render :new, status: :unprocessable_entity}\n format.json {render json: @group.errors, status: :unprocessable_entity}\n end\n end\n end\n end",
"def <<(group) \n @groups[group.name] = group\n end",
"def create\n\t\t@group = Group.new(params[:group])\n\t\trespond_to do |format|\n\t\t\tif fonct_new_dup?\n\t\t\t\tobject_orig=Group.find(params[:object_orig_id])\n\t\t\tst = @group.create_duplicate(object_orig)\n\t\t\telse\n\t\t\tst = @group.save\n\t\t\tend\n\t\t\tif st\n\t\t\t\tflash[:notice] = t(:ctrl_object_created, :typeobj => t(:ctrl_group), :ident => @group.name)\n\t\t\t\tparams[:id]=@group.id\n\t\t\t\tshow_\n\t\t\t\tformat.html { render :action => \"show\" }\n\t\t\t\tformat.xml { render :xml => @group, :status => :created, :location => @group }\n\t\t\telse\n\t\t\t\tflash[:error] = t(:ctrl_object_not_created, :typeobj => t(:ctrl_group), :msg => nil)\n\t\t\t\tformat.html { render :action => \"new\" }\n\t\t\t\tformat.xml { render :xml => @group.errors, :status => :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend",
"def group_present(name)\n group_exists = false\n execute(\"dscacheutil -q group -a name #{name}\") do |result|\n group_exists = result.stdout.start_with?(\"name: #{name}\")\n end\n\n return if group_exists\n\n gid = gid_next\n create_cmd = \"dscl . create /Groups/#{name}\"\n create_cmd << \" && dscl . create /Groups/#{name} PrimaryGroupID #{gid}\"\n execute(create_cmd)\n end",
"def add_group(group_name, filter_argument = nil)\n groups[group_name] = filter_argument\n end",
"def create\n \n @group = Group.new(params[:group])\n\n respond_to do |format|\n if @group.save\n flash[:notice] = 'Group was successfully created.'\n format.html { redirect_to(@group) }\n format.xml { render :xml => @group, :status => :created, :location => @group }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @group.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @group = Group.new(params[:group])\n\n if @group.save\n flash[:notice] = t('flash_msg46')\n @groups = Group.all\n else\n @error = true\n end\n end",
"def create\n @group = Group.new(params[:group])\n\n respond_to do |format|\n if @group.save\n flash[:success] = \"Группа успешно добавлена.\"\n format.html { redirect_to @group }\n format.json { render json: @group, status: :created, location: @group }\n else\n flash.now[:error] = \"Группа с таким названием не может быть добавлена!\"\n format.html { render action: \"new\" }\n format.json { render json: @group.errors, status: :unprocessable_entity }\n end\n end\n end",
"def group?(name)\n name = name.to_s\n @groups.find{ |g| g.name == name } || false\n end",
"def aws_create_security_group( name, opts = {} )\n opts = deep_merge_hashes( @aws_default_sg_options, opts )\n region = opts.delete( :region )\n ec2 = AWS::EC2.new.regions[ region ]\n unless ec2.security_groups.find { |sg| sg.name == name }\n ec2.security_groups.create( name, opts )\n end\n end",
"def CreateGroup params = {}\n \n APICall(path: 'groups.json',method: 'POST',payload: params.to_json)\n \n end",
"def group\n @group ||= Interface::Group.new(self)\n end",
"def create_or_find_group(name, parent)\n conds = [\"name = ? AND path = ?::ltree || ?\", name, parent.path, parent.id.to_s]\n AssetGroup.where(conds).first || AssetGroup.create(:name => name, :parent => parent)\n end",
"def create_security_group(name, description)\n action = 'CreateSecurityGroup'\n params = {\n 'Action' => action,\n 'GroupName' => name,\n 'GroupDescription' => description\n }\n\n response = send_query_request(params)\n response.is_a?(Net::HTTPSuccess)\n end",
"def new\n @host_group = Hostgroup.new\n end",
"def create\n @group = Group.new(new_group_params)\n if @group.save\n redirect_to groups_url\n else\n render :template => \"groups/new\"\n end\n end"
] |
[
"0.71094185",
"0.71094185",
"0.7012829",
"0.686723",
"0.686723",
"0.6831943",
"0.6715615",
"0.66910833",
"0.66452456",
"0.6613371",
"0.6594258",
"0.65823054",
"0.6572937",
"0.6572216",
"0.65611136",
"0.6554566",
"0.65385073",
"0.65264416",
"0.65257215",
"0.65136707",
"0.6471836",
"0.6449201",
"0.6449201",
"0.6449201",
"0.6449201",
"0.6449201",
"0.6432503",
"0.640066",
"0.63941616",
"0.63652474",
"0.6345093",
"0.63177204",
"0.6294785",
"0.6288355",
"0.62717646",
"0.6270629",
"0.6258995",
"0.62407637",
"0.6228703",
"0.62228274",
"0.61801535",
"0.61726856",
"0.61453986",
"0.6087587",
"0.6087587",
"0.6084442",
"0.5989159",
"0.5977344",
"0.5961422",
"0.5896701",
"0.58816206",
"0.58807874",
"0.58755255",
"0.58351827",
"0.58339703",
"0.580508",
"0.5798127",
"0.5778533",
"0.57744485",
"0.575471",
"0.5747258",
"0.57468367",
"0.5743286",
"0.5741682",
"0.57395464",
"0.5734765",
"0.5728454",
"0.57190573",
"0.5709515",
"0.57049763",
"0.56744623",
"0.56708795",
"0.5664022",
"0.5654626",
"0.5647617",
"0.56459355",
"0.564537",
"0.563965",
"0.56344825",
"0.5633256",
"0.5625509",
"0.56207806",
"0.5617746",
"0.5612245",
"0.5610434",
"0.5604874",
"0.5564528",
"0.55547655",
"0.5551706",
"0.5535841",
"0.55256814",
"0.55201876",
"0.5516393",
"0.5514659",
"0.55138755",
"0.55113727",
"0.5508657",
"0.55035055",
"0.55024856",
"0.5502028",
"0.5500651"
] |
0.0
|
-1
|
Public: The Fever calculation which will compute the group.
|
def calculator
@calculator ||= Fever::Calculator.new(consumer, activities)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def group_fines\n []\n end",
"def evaluate_group(grp)\n true\n end",
"def calc_group\n GROUP_MAPPINGS.keys.each do |group_id|\n # return the details, and include the id for reference\n return group_details(group_id) if self.in_group?(group_id)\n end\n # default: return 'other'\n return group_details('other')\n end",
"def cost_per_person\n self.total_cost / @group\n end",
"def _reduce_7(val, _values)\n Group.new(val[1])\nend",
"def calculate_frame(frame)\n @groups.each { |calc| calc.calculate_frame(frame) }\n end",
"def score_for_group group\r\n score = 0\r\n group.seminarians.each do |sem|\r\n # Exponential penalty\r\n if self.times_with_seminarian(sem) == 0\r\n score += 0\r\n else\r\n score += self.schedule_dataset.seminarians_per_group ** (self.times_with_seminarian(sem) - 1)\r\n end\r\n end\r\n \r\n return score\r\n end",
"def group_demand_for_electricity(group)\n graph\n .group_nodes(group)\n .map { |conv| conv.node_api.input_of_electricity }\n .compact.sum\n end",
"def group; end",
"def calculate(calculate_display_order)\n engine :group_table do |e|\n GroupTableRulebook.new(e).rules\n\n @group.matches.each{|group_match| e.assert group_match}\n @group.table_positions.each{|table_position| e.assert table_position}\n\n e.match\n end\n\n @group.sort_group_table(calculate_display_order)\n @group\n end",
"def group_size_factor_for(plan)\n return 1.0 if use_simple_employer_calculation_model?\n\n factor_carrier_id = plan.carrier_profile_id\n @gsf_cache ||= Hash.new do |h, k|\n h[k] = lookup_cached_gsf_for(k)\n end\n @gsf_cache[factor_carrier_id]\n end",
"def calculated; end",
"def calculate_group_points\n attributes_groups.each do |group|\n if group.group_points_formula.present?\n character_group = self.find_attributes_group(group.name)\n character_group.points = self.calculator.evaluate(group.group_points_formula)\n end\n end\n end",
"def sumOfGroup(k)\n return k**3\n \n#Given the fact that Sn=(A1+An)*n/2\n#Given the fact that An= A1+(n-1)d\n#Given the problme that A1 = n(n-1) +1 \n#Then Sn = n*n*n\n\nend",
"def calc_contribution(f)\n each_class do |k|\n a, b, c, d = get_A(f, k), get_B(f, k), get_C(f, k), get_D(f, k)\n n = a+b+c+d\n \n s = 0.0\n if not n.zero?\n s = (a+d) / n\n end\n \n set_feature_score(f, k, s)\n end\n end",
"def calculate(t, fraud, type)\r\n#\t\tpp \"1\"\r\n\t\treturn 0.0 if type == 'billable' && self.bid_fee #if this fee is a bid fee and we are not looking at the bid fees then return 0, else continue on\r\n\t#\tpp \"2\"\r\n \t\r\n \tfee = self.fixed if self.price_type == 'F'\r\n \r\n fee = (self.fixed + (t.amount * self.percent) + (fraud == '1' ? self.fraud : 0)).at_least(self.min).at_most(self.max) if self.price_type == 'V' #calculate the fee\r\n \r\n return fee if self.sign == '>=' && self.threshold == 0 #if there is no threshold to worry about get out quick...this is what happens the majority of the time\r\n\t\r\n\t\t#if we get here we know we are dealing with a variable fee\r\n\t\t#puts (self.fixed + (t.amount * self.percent) + (fraud == '1' ? self.fraud : 0)).at_least(self.min)\r\n\t#\tfee = (self.fixed + (t.amount * self.percent) + (fraud == '1' ? self.fraud : 0)).at_least(self.min).at_most(self.max) #calculate the fee\r\n\t#\tpp fee\r\n\t#\tpp \"3\"\r\n\t#\treturn fee if self.sign == '>=' && self.threshold == 0 #if there is no threshold to worry about get out quick...this is what happens the majority of the time\r\n\t\t\r\n\t\t#otherwise we need to determine the sign and threshold before we can return\r\n\t\tcase self.sign\r\n\t\t\twhen '>'\r\n\t\t\t #pp \">\"\r\n\t\t\t\treturn fee if t.amount > self.threshold\r\n\t\t\twhen '>='\r\n\t\t\t #pp \">=\"\r\n\t\t\t\treturn fee if t.amount >= self.threshold\r\n\t\t\twhen '<'\r\n\t\t\t #pp \"<\"\r\n\t\t\t\treturn fee if t.amount < self.threshold\r\n\t\t\twhen '<='\r\n\t\t\t #pp \"<=\"\r\n\t\t\t\treturn fee if t.amount <= self.threshold\r\n\t\t\telse\r\n\t\t\t #pp \"4\"\r\n\t\t\t\treturn 0.0\r\n\t\tend\r\n\t\t\r\n\t\t#if we get here then we have no idea what to do so just return 0\r\n\t\treturn 0.0\r\n\tend",
"def calc_contribution(f) \n each_class do |k|\n a, b, c, d = get_A(f, k), get_B(f, k), get_C(f, k), get_D(f, k)\n \n # note: intentionally negated it\n R.eval \"rv <- fisher.test(matrix(c(#{a}, #{b}, #{c}, #{d}), nrow=2))$p.value\"\n s = -1.0 * R.rv\n \n set_feature_score(f, k, s)\n end\n end",
"def group(entry)\n push(\"$group\" => evolve(entry.__expand_complex__))\n end",
"def calc_contribution(f)\n each_class do |k|\n b, d = get_B(f, k), get_D(f, k)\n \n s = 0.0\n x = b+d\n \n s = d/x if not x.zero?\n \n set_feature_score(f, k, s)\n end\n end",
"def calc_of_parent_one(field_set)\n unless @@result_group[self.id].blank?\n @@result_group[self.id].map{|x| x.calc_of_parent_one(field_set)}\n sum_value = total_calc(@@result_group[self.id],field_set[0]) \n @@result_group[self.parent_id].map{|x| x.id == self.id && x[field_set[0]] = sum_value}\n end \n end",
"def calc_contribution(f)\n each_class do |k|\n a, b, c, d = get_A(f, k), get_B(f, k), get_C(f, k), get_D(f, k)\n n = a+b+c+d\n \n s = 0.0\n x = (a+b)*(a+c)\n \n s = Math.log2(a*n/x) if not x.zero?\n \n set_feature_score(f, k, s)\n end\n end",
"def calc_contribution(f)\n each_class do |k|\n a, b, c, d = get_A(f, k), get_B(f, k), get_C(f, k), get_D(f, k)\n \n s = 0.0\n x = b*c\n \n s = (a*d) / x if not x.zero?\n \n set_feature_score(f, k, s)\n end\n end",
"def check_split\n (meal + ((meal * tip) / 100)) / group\n end",
"def ifft\r\n inverse_strategy.new(data).calculate\r\n end",
"def calc_contribution(f)\n each_class do |k|\n a, b, c, d = get_A(f, k), get_B(f, k), get_C(f, k), get_D(f, k)\n \n s = 0.0\n x = (a+b)*(a+c)*(b+d)*(c+d)\n \n s = (a*d-b*c) / Math.sqrt(x) if not x.zero?\n \n set_feature_score(f, k, s)\n end\n end",
"def calc_contribution(f)\n each_class do |k|\n a, b, c, d = get_A(f, k), get_B(f, k), get_C(f, k), get_D(f, k)\n \n s = 0.0\n x, y = b+d, a+c\n \n s = (d/x)**(@k) - (c/y)**(@k) if not x.zero? and not y.zero?\n \n set_feature_score(f, k, s)\n end\n end",
"def fees\n total_input - total_output\n end",
"def calc_contribution(f)\n each_class do |k|\n a, c = get_A(f, k), get_C(f, k)\n \n s =0.0\n x = a+c\n \n s = a/x if not x.zero?\n \n set_feature_score(f, k, s)\n end\n end",
"def F_score(gold)\n\t\tClustering.F_score(gold,self)\n\tend",
"def calc_contribution(f)\n each_class do |k|\n set_feature_score(f, k, rand)\n end\n end",
"def calcElectCost( calcType )\n balancekWh = 0\n # Subtract old electricity cost from total before recalculating electricity cost\n $gResults[$outputHCode][\"avgFuelCostsTotal$\"] -= $gResults[$outputHCode][\"avgFuelCostsElec$\"]\n if ( calcType == \"annualMin\" )\n $gElecRate[\"avgFuelCostsElec$\"] = $gElecRate[\"ElecMthMinCharge$\"] * 12\n else\n if ( $gResults[$outputHCode][\"avgFueluseEleckWh\"] > $gElecRate[\"ElecBlck1Units\"] )\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] = $gElecRate[\"ElecBlck1Units\"] * $gElecRate[\"ElecBlck1CostPerUnit\"]\n balancekWh = $gResults[$outputHCode][\"avgFueluseEleckWh\"] - $gElecRate[\"ElecBlck1Units\"]\n if ( balancekWh > $gElecRate[\"ElecBlck2Units\"] )\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] += $gElecRate[\"ElecBlck2Units\"] * $gElecRate[\"ElecBlck2CostPerUnit\"]\n balancekWh -= $gElecRate[\"ElecBlck2Units\"]\n if ( balancekWh > $gElecRate[\"ElecBlck3Units\"] )\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] += $gElecRate[\"ElecBlck3Units\"] * $gElecRate[\"ElecBlck3CostPerUnit\"]\n balancekWh -= $gElecRate[\"ElecBlck3Units\"]\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] += balancekWh * $gElecRate[\"ElecBlck4CostPerUnit\"]\n else\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] += balancekWh * $gElecRate[\"ElecBlck3CostPerUnit\"]\n end\n else\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] += balancekWh * $gElecRate[\"ElecBlck2CostPerUnit\"]\n end\n else\n $gResults[$outputHCode][\"avgFuelCostsElec$\"] = $gResults[$outputHCode][\"avgFueluseEleckWh\"] * $gElecRate[\"ElecBlck1CostPerUnit\"]\n end\n end\n # Update total fuel cost variable\n $gResults[$outputHCode][\"avgFuelCostsTotal$\"] += $gResults[$outputHCode][\"avgFuelCostsElec$\"]\nend",
"def calc_draft_probs_fo(fo,n_teams = 30)\n ###fo means finishing order\n ###pick means draft order\n\n probs_fo = {}\n probs_pick = {}\n (1..n_teams).each{|fo| probs_fo[fo] = 0;probs_pick[fo] = 0}\n probs_fo[fo] = 1\n\n fn_fo = TF1.new(\"fn_fo\",\"gaus\")\n\n if (fo <= 14)\n (1..14).each{|pick| probs_pick[pick] += (probs_fo[fo]*$lottery_odds[fo][pick-1])}\n elsif fo > 14\n probs_pick[fo] = probs_fo[fo]#.to_N(5)\n end\n\n return probs_pick\nend",
"def total_amount_passed_to_field_worker\n # it is assumed that the setup fee is deducted from loan disbursement \n total_amount_passed = BigDecimal(\"0\")\n self.membership_to_receive_loan_disbursement.each do |glm|\n glp = glm.group_loan_product \n total_amount_passed += glp.loan_amount - glp.setup_payment_amount\n end\n \n return total_amount_passed\n end",
"def group(*) end",
"def calculation\n end",
"def post_divide; end",
"def compute_actual\n line[1] = @ho_form.line['sqft']\n line[2] = @ho_form.line['total_sqft']\n line[3] = (line[1] * 100.0 / line[2]).round(2)\n\n line['4/gross_inc'] = gross_income\n\n # We make a simplifying assumption that (1) every Home Office Expense\n # applies to every Home Office form, and (2) all expenses are indirect.\n categorize_records('Home Office Expense')\n #\n # We assume that the home office using the actual method is being rented and\n # thus there are no mortgage payments or such on it.\n #\n #fill_for_categories(self, '5b', 'Casualty_Losses')\n #fill_for_categories(self, '6b', 'Mortgage_Interest')\n #fill_for_categories(self, '7b', 'Real_Estate_Taxes')\n\n line['8b'] = sum_lines('5b', '6b', '7b')\n line[9] = (line['8b'] * line[3] / 100.0).round\n line[10] = line[9]\n\n line[11] = other_business_expenses\n\n line[12] = sum_lines(10, 11)\n line['13/ho_max_ded'] = line[4] - line[12]\n\n fill_for_categories(self, '16b', 'Insurance')\n fill_for_categories(self, '17b', 'Rent')\n fill_for_categories(self, '18b', 'Repairs')\n fill_for_categories(self, '19b', 'Utilities')\n fill_other_categories(\n self, '20b', continuation: 'Other Home Office Expenses'\n )\n line['21b'] = sum_lines(*%w(14b 15b 16b 17b 18b 19b 20b))\n line[22] = (line['21b'] * line[3] / 100.0).round\n\n # Assume no carryover for line 23\n line['24/ho_ded'] = sum_lines('21a', 22, 23)\n line[25] = [ line[13], line[24] ].min\n line[26] = line[13] - line[25]\n\n # Assume no casualty losses or depreciation for lines 27-29 and 33\n line[30] = sum_lines(27, 28, 29)\n line[31] = [ line[26], line[30] ].min\n line[32] = sum_lines(10, 25, 31)\n\n line[33] = BlankZero\n line['34/ho_expenses'] = line[32] - line[33]\n\n end",
"def calc_amounts(total_amount_required,do_not_commit = nil)\n calc_amounts = nil\n self.total_req_amount = total_amount_required\n @ratios.each do |ratio|\n ratio_num = ratio[:ratio]\n req_amount = ((ratio_num)* total_amount_required).round\n \n if !do_not_commit\n @puc_groups[ratio[:puc_group]][:req_amount] = req_amount\n else\n calc_amounts = Hash.new if !calc_amounts\n calc_amounts.store(ratio[:puc_group],req_amount)\n end\n end\n return calc_amounts\n end",
"def compute_fuel(element)\n (element/3).floor - 2\n end",
"def uberX_fare_calculator\nend",
"def most_specific_subdivision; end",
"def schedule_fcfs(data)\n time = data.first[:arrival]\n waiting_sum = turnaround_sum = 0\n\n data.each do |obj| \n # Waiting time is current time - arrival time\n waiting_sum += time - obj[:arrival]\n # Turnaround is completion - arrival\n time += obj[:cpu_cycles]\n turnaround_sum += time - obj[:arrival]\n end\n \n avg_waiting = waiting_sum.to_f / data.length\n avg_turnaround = turnaround_sum.to_f / data.length\n { :policy => 'FCFS', \n :waiting_avg => avg_waiting.round_to(2), \n :turnaround_avg => avg_turnaround.round_to(2) }\nend",
"def full_recalc\r\n # # # # # # # # # \r\n print \"(FULL RECALC)\\n\"\r\n @hub_diam = bearing_outside_diam + (wall_thick * 0.8)\r\n \r\n @amount_lopside = wheel_diam * lopside_percent\r\n @floor_thick = @wall_thick * 1 \r\n @mount_bolt_thread_diam = @mount_bolts_diam * 0.85\r\n @mount_bolt_length = @stock_z_len + 0.05\r\n @cut_off_allowance = @mill.bit_diam\r\n print \"(hub_diam=\", @hub_diam, \")\\n\"\r\n recalc()\r\n end",
"def calc_fitness\n self.join.to_i(2)\n end",
"def update_ship_group(group_array, user)\n if ( user == @attacker )\n array = @attacker_level\n else\n array = @defender_level\n end\n if group_array[-2] < 0\n group_array[-2] = 0\n end\n #Falls Einheit\n if (group_array[6])\n hp_one = Unit.find(group_array[0]).shell * @shell_mult * (1 + (0.1 * array[0])).to_i\n damage_one = Unit.find(group_array[0]).damage * @damage_mult * (1 + (0.1 * mult_weapon_level(group_array[3], user))) \n # Falls Anlage \n else\n hp_one = Facility.find(group_array[0]).shell * @shell_mult * (1 + (0.1 * array[0])).to_i\n damage_one = Facility.find(group_array[0]).damage * @damage_mult * (1 + (0.1 * mult_weapon_level(group_array[3], user)))\n end\n if group_array[1] > 0 \n amount_before = group_array[1]\n group_array[1] = (group_array[-2] / hp_one).ceil\n group_array[2] = group_array[1] * damage_one\n group_array[4] = amount_before - group_array[1]\n end \n if group_array[1] < 0\n group_array[1] = 0\n end\n if group_array[-2] < 0\n group_array[-2] = 0\n end\n end",
"def f(i, k)\n if i == 1\n k < 7 ? 0.16666666666666667 : 0 #Uniform distribution of probability for one die\n elsif @cached_f[i] && @cached_f[i][k]\n @cached_f[i][k] #Using cached value if it exists\n else\n # Using exponentiation by squaring algorithm for determining probability\n sum = 0\n range = i < 3 ? ([k-6,1].max..[k-1,6].min) : ([k-6,1].max..k-1) \n range.each do |value|\n sum = sum + 0.16666666666666667*f(i-1,value)\n end\n # Storing the calculated value in cache\n @cached_f[i] ||= {}\n @cached_f[i][k] = sum \n end\n end",
"def example_group_memoized_helpers; end",
"def group\n raise \"View#reduce must have been set before grouping is permitted\" unless query[:reduce]\n update_query(:group => true)\n end",
"def pre_divide; end",
"def efp\n top_players.inject(0) { |sum, player| player.efp + sum }\n end",
"def prec_f() end",
"def update_ship_group(group)\n if group[-2] < 0\n group[-2] = 0\n end\n amount_before = group[1]\n hp_one = Unit.find(group[0]).shell\n damage_one = Unit.find(group[0]).damage\n group[1] = (group[-2] / hp_one).ceil\n group[2] = group[1] * damage_one\n group[4] = amount_before - group[1]\n if group[1] < 0\n group[1] = 0\n end\n end",
"def calculate_group_distance\n sum = 0.0\n @patterns.each { |pattern|\n sum += calculate_distance(pattern.features, @center.features)\n }\n sum\n end",
"def calculate_fcost(p)\n\t\t@hcosts[p] + @gcosts[p]\n\tend",
"def get_sum_defender_units\n all_units = 0\n @defender_fleet.ship_groups.each do |group|\n all_units = all_units + group.number\n end\n return all_units\n end",
"def step_divisor\n 10 + features_sum(:anger_mantain)\n end",
"def calculate_result\n process_events(@events)\n\n elements = {}\n i = 0\n @images.each do |image|\n element_list = image['elements'].split(',')\n rank_multiplier = 5 - @final_rank[i]\n element_list.each do |element_name|\n # \"cf:\" is a legacy prefix, if it exists remove it.\n element_name = element_name[3..-1] if element_name[0..2] == 'cf:'\n elements[element_name] ||= 0\n elements[element_name] += rank_multiplier\n end\n i += 1\n end\n\n elements\n end",
"def fulfillment_fee\n begin\n if variant.product_costs.where(:retailer_id => self.order.retailer_id).first.fulfillment_fee > 0\n variant.product_costs.where(:retailer_id => self.order.retailer_id).first.fulfillment_fee * quantity\n else\n self.order.retailer.fulfillment_fee * quantity\n end\n rescue\n begin\n self.order.retailer.fulfillment_fee * quantity\n rescue\n 0.0\n end\n end\n end",
"def group\n raise \"View#reduce must have been set before grouping is permitted\" unless query[:reduce]\n update_query(:group => true)\n end",
"def cal_group_val(val_arr)\n\t\tval = 0\n\t\tval_arr.each_with_index do |v, ind|\n\t\t\tval += v.to_i * 2**ind\n\t\tend\n\t\treturn val\n\tend",
"def calc(n, k)\n fac(n) / (fac(k) * fac(n - k)) * ((1.0/6.0)**k * (5.0/6.0)**(n-k)) * 100\n end",
"def ego_group(actor, depth, generator, group)\n functor('ego-group', actor, PrologLiteral.new(depth),\n generator, group)\n end",
"def icc_2_1_fs(pp,alpha=0.05)\n fj=jms.quo(ems)\n per=1-(0.5*alpha)\n vn=(k-1)*(n-1)*((k*pp*fj+n*(1+(k-1)*pp)-k*pp)**2)\n vd=(n-1)*(k**2)*(pp**2)*(fj**2)+((n*(1+(k-1)*pp)-k*pp)**2)\n v=vn.quo(vd)\n f1=Distribution::F.p_value(per, n-1,v)\n f2=Distribution::F.p_value(per, v, n-1)\n [f1,f2]\n end",
"def run_aggregation\n GRADES.each_with_index do |grade, idx|\n classifier[grade].each_pair do |metric, values|\n all_values = values\n all_values += classifier[GRADES[idx + 1]][metric] if (idx + 1) < GRADES.count\n\n classifier[grade][metric] =\n if all_values.count <= 2\n values.max || 0\n else\n (all_values.sum / all_values.count).round(2)\n end\n end\n end\n end",
"def prediction_payment\n group.ffs_payment * 3\n end",
"def feruchemist; end",
"def aggregate_after_grouping?; @aggregate_after_grouping; end",
"def calc_contribution(f)\n if not get_classes.size == 2\n abort \"[#{__FILE__}@#{__LINE__}]: \\n\"+\n \" Relief applicable only to two-class problems without missing data\"\n end\n \n ## use all samples if @m not provided\n #@m = get_sample_size if not @m\n \n k1, k2 = get_classes\n score = 0.0\n \n @m.times do \n # pick a sample at random\n rs, rk = pick_a_sample_at_random\n \n # find the nearest neighbor for each class\n nbrs = find_nearest_nb(rs, rk)\n \n # calc contribution from neighbors\n score += calc_score(f, rs, rk, nbrs)\n end\n \n s = score / @m\n \n set_feature_score(f, :BEST, s)\n end",
"def calculate\n\t\taverage_rank\n\t\tfound_percent\n\tend",
"def recalculate\n\tend",
"def fare\n return PENALTY_FARE if penalty?\n return MINIMUM_FARE\n end",
"def efg\n return 0.0 if fg.zero? || fga.zero?\n\n ((fg.to_f + 0.5 * three_p.to_f)/fga).round(3)\n end",
"def calc_koef(f, fs)\r\n 2 * Math.cos(2 * Math::PI * f / fs)\r\n end",
"def update_group(increment)\n end",
"def age_group\n # NOTE: This method may be called before saving, so database queries are a no-no!\n\n season = self.performance.contest.season\n\n if self.solo? || (self.accompaniment? && !self.performance.category.popular?)\n # Soloists and non-popular accompanists have their own age group\n calculate_age_group(self.participant.birthdate, season)\n elsif self.ensemble?\n # Ensemble players share an age group\n ensemble_appearances = self.performance.appearances.select(&:ensemble?)\n calculate_age_group(ensemble_appearances.map { |a| a.participant.birthdate }, season)\n else\n # Pop accompanists share an age group (excluding the soloist)\n accompanist_appearances = self.performance.appearances.select(&:accompaniment?)\n calculate_age_group(accompanist_appearances.map { |a| a.participant.birthdate }, season)\n end\n end",
"def group_fitness\n unless @all_persons.empty?\n @all_persons.each do |person|\n puts \"#{person}: #{person.get_energy_level}\"\n end\n end\n end",
"def fvan(i, n, pmt)\n return pmt * (((1 + i) ** n) - 1) / i \n end",
"def compute(fdata)\n #print \"Jdu spocitat: \" + @calculate.to_s + \"\\n\"\n @calculator.evaluate(@calculate)\n end",
"def ii_groups; end",
"def grasa\n\t\t1.2*imc+0.23*@edad-10.8*@sexo-5.4\n\tend",
"def recalculate\n end",
"def total_fee\n fee + fee2 + fee3 + fee4\n end",
"def rule\n @rule || @distribution.inject([]){|result, elm| result << [(result.empty? ? 0.0 : result.last[0]) + elm[0], elm[1]]}\\\n .tap{|array| array.last[0] = 1.0 } # make sure the last element's cdf is 1.0\n end",
"def compute_average_grade\n total = 0.0\n self.fcqs.compact.each {|x| next if x.avg_grd == nil; total += x.avg_grd}\n count = courses_taught\n if count == 0\n return 1.0 \n else\n return (total.to_f / count.to_f)\n end\n end",
"def peer_group\n employee_total = @company_info.global_employee_total.to_i\n EpliGroup.peer_group(state_group, industry_group, employee_total)\n end",
"def f\n F_COND()\n end",
"def calculate_fee\n cost = (shooter.current_member? or join_psac) ? 15 : 20\n has_shooter = persisted? ? match.has_more_than_one_shooter?(shooter) : match.has_shooter?(shooter)\n if has_shooter\n cost = 3\n self.squad = 5\n end\n if join_psac\n cost += 30\n end\n self.fee = cost\n end",
"def rev_by_fee_type_medium\n @contingency_expected = Graph.revenue_by_fee_type_estimated(current_user,\"Contingency\",'estimated_conclusion_expected','medium_estimate')\n @mixed_expected = Graph.revenue_by_fee_type_estimated(current_user,\"Mixed\",'estimated_conclusion_expected','medium_estimate')\n @fixed_fee_expected = Graph.revenue_by_fee_type_estimated(current_user,\"Fixed Fee\",'estimated_conclusion_expected','medium_estimate')\n @hourly_expected = Graph.revenue_by_fee_type_estimated(current_user,\"Hourly\",'estimated_conclusion_expected','medium_estimate')\n\n @contingency_fast = Graph.revenue_by_fee_type_estimated(current_user,\"Contingency\",'estimated_conclusion_fast','medium_estimate')\n @mixed_fast = Graph.revenue_by_fee_type_estimated(current_user,\"Mixed\",'estimated_conclusion_fast','medium_estimate')\n @fixed_fee_fast = Graph.revenue_by_fee_type_estimated(current_user,\"Fixed Fee\",'estimated_conclusion_fast','medium_estimate')\n @hourly_fast = Graph.revenue_by_fee_type_estimated(current_user,\"Hourly\",'estimated_conclusion_fast','medium_estimate')\n\n @contingency_slow = Graph.revenue_by_fee_type_estimated(current_user,\"Contingency\",'estimated_conclusion_slow','medium_estimate')\n @mixed_slow = Graph.revenue_by_fee_type_estimated(current_user,\"Mixed\",'estimated_conclusion_slow','medium_estimate')\n @fixed_fee_slow = Graph.revenue_by_fee_type_estimated(current_user,\"Fixed Fee\",'estimated_conclusion_slow','medium_estimate')\n @hourly_slow = Graph.revenue_by_fee_type_estimated(current_user,\"Hourly\",'estimated_conclusion_slow','medium_estimate')\n end",
"def fees\n @fees ||= {\n \"insurance_fee\" => (commission * ASSURANCE_SHARE).round(0),\n \"assistance_fee\" => (ASSISTANCE_COST * rental.duration).round(0)\n }.tap { |fees| fees[\"drivy_fee\"] = commission - fees.values.inject(:+) }\n end",
"def hard(input)\n group_weight = input.sum / 4\n count = 2\n groups = []\n loop do\n groups = input.combination(count).select { |c| c.sum == group_weight }\n break unless groups.empty?\n count += 1\n end\n group = groups.sort_by { |g| quantum_entanglement(g) }.first\n quantum_entanglement(group)\nend",
"def group_by_exp(input, variable, expression); end",
"def calculate_fee\n Application::courses_fee(course_selections_count > 1 ? :multiple : :single)\n end",
"def calcNormEffort\r\n\tws = $ws1\r\n\trowMax = $validRow\r\n\t#do for all the CSCRMs\r\n\trowMax.times do |row|\r\n\t\trow = row + 2\r\n\t\t#default factor to multiply\r\n\t\tfactor = 1\r\n\t\teffort = ws.cells(row, $columnNumbers1[\"Effort\"]).value\r\n\t\tdeveloper = ws.cells(row, $columnNumbers1[\"Developer\"]).value\r\n\t\tcomponent = ws.cells(row, $columnNumbers1[\"Module\"]).value\r\n\t\t\r\n\t\t#all of these should be defined\r\n\t\tif developer && component\r\n\t\t\tif $productivity.has_key?(developer) && $productivity[developer].has_key?(component)\r\n\t\t\t\tfactor = $productivity[developer][component]\r\n\t\t\tend\r\n\t\tend\r\n\t\t\r\n\t\t#Task specific productivity overrides the regular productivity\r\n\t\ttaskFactor = ws.cells(row, $columnNumbers1[\"TaskProductivity\"]).value if $columnNumbers1[\"TaskProductivity\"] != -1\r\n\t\t\r\n\t\tif taskFactor\r\n\t\t\tfactor = taskFactor\r\n\t\tend\r\n\t\t\r\n\t\tif effort\r\n\t\t\tws.cells(row,$columnNumbers1[\"Normalised Effort\"]).value = effort * factor\r\n\t\tend\r\n\tend\r\nend",
"def running_average; end",
"def group\n @group ||= Innsights::Fetchers::Group.new(@group_object) if @group_object\n end",
"def effective_group(store)\n group(store) || store.default_group\n end",
"def stat_ftc\n percentage(self.heifers_first, self.heifers_first_calved)\n end",
"def calc_carbon_savings_from_upg_diesel(val1= calc_upg_mwh_ch4, val2= 0.2938, val3= 0.78)\n\t\t(val1 * val2 * val3).round 2\n\tend",
"def i_groups; end",
"def cf\n\t\tself.buy ? (-self.amount-self.fee) : (self.amount - self.fee)\n\tend",
"def cf_mortgage_basic\n sum_cash_flows(self.cf_down_payment, self.cf_repayment, self.cf_settlement, self.cf_selling_price)\n end"
] |
[
"0.57707494",
"0.5635831",
"0.55958277",
"0.55887777",
"0.55579996",
"0.5512065",
"0.5482379",
"0.5464107",
"0.54468966",
"0.5434748",
"0.5386438",
"0.5375116",
"0.5367701",
"0.53619194",
"0.53467554",
"0.5342817",
"0.5340674",
"0.53394413",
"0.53033537",
"0.52810824",
"0.5261671",
"0.5255629",
"0.52503395",
"0.5245376",
"0.5223386",
"0.5215732",
"0.5204128",
"0.51961315",
"0.51720166",
"0.51644534",
"0.5155961",
"0.51542073",
"0.51537824",
"0.5136508",
"0.5095604",
"0.5084417",
"0.5073846",
"0.50676864",
"0.5061259",
"0.50491077",
"0.5032058",
"0.502114",
"0.50101584",
"0.50093687",
"0.50057423",
"0.499139",
"0.4990725",
"0.49734432",
"0.49725252",
"0.49678984",
"0.49570498",
"0.49547893",
"0.49516502",
"0.49469954",
"0.49403536",
"0.49296582",
"0.49249044",
"0.4923896",
"0.49181008",
"0.49151188",
"0.49130064",
"0.49061525",
"0.48999497",
"0.48984262",
"0.4894847",
"0.48899508",
"0.4875876",
"0.48733908",
"0.48695046",
"0.48509467",
"0.48497412",
"0.48446622",
"0.48443958",
"0.4839783",
"0.48392552",
"0.4837054",
"0.48283428",
"0.4828104",
"0.4825082",
"0.482172",
"0.4817946",
"0.48138922",
"0.48131546",
"0.4809491",
"0.48093084",
"0.48036408",
"0.4795447",
"0.47943482",
"0.4793336",
"0.47891364",
"0.4783703",
"0.47782138",
"0.47643468",
"0.47625995",
"0.47600663",
"0.4753961",
"0.47455397",
"0.47438338",
"0.47429335",
"0.47429293",
"0.4742168"
] |
0.0
|
-1
|
Public: Returns a curve which describes the demand for electricity caused by the activities within the calculator.
|
def elec_demand_curve
@elec_demand_curve ||= ElectricityDemandCurve.from_adapters(adapters)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def demand_curve\n load_curve('demand.csv')\n end",
"def demand_curve\n @demand_curve ||= begin\n unlimited_carrier_curve.map do |value|\n value < @carrier_capacity ? value : @carrier_capacity\n end\n end\n end",
"def calculate_carrier_demand\n demand_curve.sum * 3600\n end",
"def fever_demand_curve(name)\n @household_heat.curve(name)\n end",
"def demand_curve\n @demand_curve ||= CurveTools.add_curves(\n participants.users.reject(&:provides_price?).map(&:load_curve)\n )\n end",
"def demand_value(curve_name)\n if curve_name == :ev\n @graph.query.group_demand_for_electricity(:merit_ev_demand)\n else\n @household_heat.demand_value(curve_name)\n end\n end",
"def curve\n end",
"def curve\n end",
"def calculator\n @calculator ||= Calculator.new(\n Helper.total_demand_curve(self),\n Helper.total_supply_curve(self)\n )\n end",
"def curtailment_curve(demand)\n return zeroed_profile if @curtailment.zero?\n\n useable_profile.map.with_index do |curtailed_factor, frame|\n uncurtailed = demand * @profile[frame]\n uncurtailed - (demand * curtailed_factor)\n end\n end",
"def consumption_curve\n consumption = @adapters\n .select { |a| a.config.type == :consumer && a.config.subtype != :pseudo }\n .map { |c| c.participant.load_curve }\n\n Merit::CurveTools.add_curves(consumption) || EMPTY_CURVE\n end",
"def unlimited_carrier_curve\n demand_profile * max_carrier_production\n end",
"def total_demand_for_electricity\n final_demand_for_electricity +\n non_final_demand_for_electricity +\n electricity_losses_if_export_is_zero\n end",
"def energy_sector_own_use_electricity\n graph.node(:energy_power_sector_own_use_electricity).demand\n end",
"def revenue_curve\n @revenue_curve ||= load_curve * order.price_curve\n end",
"def exp_rate; CPanel::EXPRATE; end",
"def explode_curve\n end",
"def explode_curve\n end",
"def load_curve\n curve = Curve.new([], Merit::POINTS)\n\n Merit::POINTS.times do |point|\n if cheaper_locally?(point)\n curve.set(point, [\n available_capacity(point),\n foreign_demand(point),\n @capacity.get(point)\n ].min)\n else\n curve.set(point, 0.0)\n end\n end\n\n curve\n end",
"def temperature_curve\n @context.curves.curve('weather/air_temperature', @node)\n end",
"def get_cost_of_equity\n @cost_of_equity = (self.class.risk_free_rate + self.get_beta * (self.class.market_growth_rate - self.class.risk_free_rate)).round(2)\n end",
"def ramping_curve\n Curve.new(load_curve.each_cons(2).map { |a, b| (b - a).abs })\n end",
"def producer_for_electricity_demand\n producer_for_carrier(:electricity)\n end",
"def curve(name, node)\n carrier, direction =\n Qernel::Causality::SelfDemandProfile\n .decode_name(name)\n .values_at(:carrier, :direction)\n\n case carrier\n when :electricity\n electricity_merit_self_curve(node, carrier, direction)\n when :steam_hot_water\n heat_network_merit_self_curve(node, carrier, direction)\n when :useable_heat, :heat\n fever_self_curve(node, carrier, direction)\n else\n raise %(Unsupported curve: \"self: #{name}\" on #{node.key})\n end\n end",
"def theCost\n # calculate the energy in kWh used in 24 hours at this power level\n # using (24x60x60 secs/day)/(1000x60x60 J/kWh) = 0.024 (kWh/day)/W\n kWh_per_day = 0.024*power\n # convert to an equivalent cost in cents\n return kWh_per_day*ATHOME['energy_cost']\n end",
"def caloric_requirement\n age = current_age\n bmr = basal_metabolic_rate(age)\n if strength == 1\n caloric_requirement_st1(age, bmr).to_i\n elsif strength == 2\n caloric_requirement_st2(age, bmr).to_i\n else\n caloric_requirement_st3(age, bmr).to_i\n end\n end",
"def get_earnings\n get_historic_eps(1)\n end",
"def compute_actual\n line[1] = @ho_form.line['sqft']\n line[2] = @ho_form.line['total_sqft']\n line[3] = (line[1] * 100.0 / line[2]).round(2)\n\n line['4/gross_inc'] = gross_income\n\n # We make a simplifying assumption that (1) every Home Office Expense\n # applies to every Home Office form, and (2) all expenses are indirect.\n categorize_records('Home Office Expense')\n #\n # We assume that the home office using the actual method is being rented and\n # thus there are no mortgage payments or such on it.\n #\n #fill_for_categories(self, '5b', 'Casualty_Losses')\n #fill_for_categories(self, '6b', 'Mortgage_Interest')\n #fill_for_categories(self, '7b', 'Real_Estate_Taxes')\n\n line['8b'] = sum_lines('5b', '6b', '7b')\n line[9] = (line['8b'] * line[3] / 100.0).round\n line[10] = line[9]\n\n line[11] = other_business_expenses\n\n line[12] = sum_lines(10, 11)\n line['13/ho_max_ded'] = line[4] - line[12]\n\n fill_for_categories(self, '16b', 'Insurance')\n fill_for_categories(self, '17b', 'Rent')\n fill_for_categories(self, '18b', 'Repairs')\n fill_for_categories(self, '19b', 'Utilities')\n fill_other_categories(\n self, '20b', continuation: 'Other Home Office Expenses'\n )\n line['21b'] = sum_lines(*%w(14b 15b 16b 17b 18b 19b 20b))\n line[22] = (line['21b'] * line[3] / 100.0).round\n\n # Assume no carryover for line 23\n line['24/ho_ded'] = sum_lines('21a', 22, 23)\n line[25] = [ line[13], line[24] ].min\n line[26] = line[13] - line[25]\n\n # Assume no casualty losses or depreciation for lines 27-29 and 33\n line[30] = sum_lines(27, 28, 29)\n line[31] = [ line[26], line[30] ].min\n line[32] = sum_lines(10, 25, 31)\n\n line[33] = BlankZero\n line['34/ho_expenses'] = line[32] - line[33]\n\n end",
"def cost\n start_value\n end",
"def demand_at(order, point)\n order.demand_calculator.demand_at(point)\n end",
"def final_demand_for_electricity\n group_demand_for_electricity(:final_demand_group)\n end",
"def learning_curve factor\n @learning_curve = []\n current_week_data = current_user.reports.where(exam_date:(Time.now.all_week())).map {|x| x.send(:\"#{factor}\")}\n prev_week_data = current_user.reports.where(exam_date:((Time.now-1.week).all_week())).map {|x| x.send(:\"#{factor}\")}\n @learning_curve << (average(current_week_data) - average(prev_week_data)).round(2)\n current_month_data = current_user.reports.where(exam_date:(Time.now.all_month())).map {|x| x.send(:\"#{factor}\")}\n prev_month_data = current_user.reports.where(exam_date:((Time.now-1.month).all_month())).map {|x| x.send(:\"#{factor}\")}\n @learning_curve << (average(current_month_data) - average(prev_month_data)).round(2)\n @learning_curve = [0,0] if @learning_curve.empty?\n end",
"def depreciation_costs\n fetch(:depreciation_costs) do\n if technical_lifetime.zero?\n raise IllegalZeroError.new(self, :technical_lifetime)\n end\n\n investment = total_investment_over_lifetime\n\n if investment && investment < 0\n raise IllegalNegativeError.new(\n self, :total_investment_over_lifetime, investment\n )\n end\n\n investment / technical_lifetime\n end\n end",
"def input_efficiency\n @input_efficiency ||=\n begin\n base_cop = @config.base_cop\n per_degree = @config.cop_per_degree\n\n temperature_curve.map do |val|\n cop = base_cop + per_degree * val\n\n # Coefficient of performance must not drop below 1.0 (where there\n # is no \"balanced_with\" energy, and only \"based_on\" energy is\n # used).\n cop < 1.0 ? 1.0 : cop\n end\n end\n end",
"def energyEfficiency()\n\t\t\t\t\"Carbs \" + carbsPercent().round(2).to_s + \"%,\\nProteins \" + proteinsPercent().round(2).to_s + \"%\\nLipids \" + lipidsPercent().round(2).to_s + \"%\\n\"\n\t\t\tend",
"def price_curve\n load_curve('price.csv')\n end",
"def curve(base)\n if base.respond_to?(:to_curve) && base.length == Fever::FRAMES\n return base.to_curve\n end\n\n case base\n when Numeric then curve_from_numeric(base)\n when Enumerable then curve_from_enum(base)\n else raise(ArgumentError, \"cannot create a curve from #{ base.inspect }\")\n end\n end",
"def foreign_demand(point)\n local_price = @local.price_curve.get(point)\n producers = foreign_producers(point, local_price)\n\n producers.reduce(0.0) do |sum, prod|\n amount = prod.load_curve.get(point) -\n Convergence.competitive_load(prod, point, local_price)\n\n sum + amount\n end\n end",
"def modeler_description\n return 'This measure uses the EnergyPlus Energy Management System to log and report emissions based on user-provided future and historical years as well as future, historical hourly, and historical annual subregions.'\n end",
"def production_curve\n production = @adapters\n .select { |a| a.config.type == :producer && PRODUCTION_TYPES.include?(a.config.subtype) }\n .map { |c| c.participant.load_curve }\n\n (Merit::CurveTools.add_curves(production) || EMPTY_CURVE).map(&:-@)\n end",
"def cost\n deductible * RATE\n end",
"def exp_rate(otherElo)\n \t1.0/(1+10**((otherElo - self.elo)/400.0))\n end",
"def spare_load_curve\n max_load_curve - load_curve\n end",
"def curve(curve_name)\n self.curves[curve_name]\n end",
"def mana_curve\n curve = []\n num_cards = packs.map { |pack| pack.number }.sum\n cost = 0\n while curve.sum != num_cards\n packs = packs_with_cmc(cost)\n curve[cost] = packs.map { |pack| pack.number }.sum\n cost += 1\n end\n curve\n end",
"def capacity_to_demand_multiplier\n 8760.0\n end",
"def effective_rate; end",
"def curve(name, node)\n name = name.to_s\n\n # Fever and self curves come from Fever or another Merit instance and\n # are already rotated.\n if prefix?(name, 'fever-electricity-demand')\n fever_demand_curve(name[25..-1].strip.to_sym)\n elsif prefix?(name, 'self')\n self_curve(name[5..-1].strip.to_sym, node)\n else\n super\n end\n end",
"def get_energia\n\t\t\t\t@lipidos * 9 + @proteins * 4 + @carbs * 4\n\t\t\tend",
"def gfp_standard_curve(coordinates)\n # Calculating Std Curve for GFP\n num_of_pts = 0\n a = 0\n x_sum = 0\n y_sum = 0\n x_sq_sum = 0\n x_arr = []\n y_arr = []\n coordinates.each do |x, y|\n if x < 25 # Above 25uM is out of linear range of our instrument\n a += (x * y)\n x_sum += x\n x_sq_sum += (x**2)\n y_sum += y\n x_arr.push(x)\n y_arr.push(y)\n num_of_pts += 1\n end\n end\n a *= num_of_pts\n b = x_sum * y_sum\n c = num_of_pts * x_sq_sum\n d = x_sum**2\n slope = (a - b)/(c - d)\n f = slope * (x_sum)\n yint = (y_sum - f)/num_of_pts\n # show{note \"y = #{(slope).round(2)}x + #{(yint).round(2)}\"}\n return (slope).round(3), (yint).round(3), x_arr, y_arr\n end",
"def modeler_description\r\n return \"E+ measure to popolate the Kiva settings values\"\r\n end",
"def inidicator_energia()\n\t\t\t\te = get_energia()\n\n\t\t\t\tif e < 670\n\t\t\t\t\treturn 1.0\n\t\t\t\telsif e <= 830\n\t\t\t\t\treturn 2.0\n\t\t\t\telse\n\t\t\t\t\treturn 3.0\n\t\t\t\tend\n\t\t\tend",
"def marginal_costs\n fetch(:marginal_costs, false) do\n if output(:electricity).nil?\n nil\n elsif electricity_output_conversion.zero?\n 0.0\n else\n variable_costs_per_typical_input(include_waste: false) *\n SECS_PER_HOUR / # Highlighting\n electricity_output_conversion\n end\n end\n end",
"def expression_value\n return @expression_value if defined?(@expression_value)\n\n subexpr_value =\n (1 + periodic_interest_rate) ** total_number_of_payments\n @expression_value =\n (periodic_interest_rate * subexpr_value) / (subexpr_value - 1)\n end",
"def exposure\n market_value\n end",
"def fuel_efficiency\n ((mileage - predecessor.mileage) / liter).round(1) if predecessor\n end",
"def ener_kcal \n\t\t@ener_kcal = @saturadas * 9 + @monoinsaturadas * 9 + @polinsaturadas * 9 + @azucares * 4 + @polialcoles * 2.4 + @almidon * 4 + @fibra * 2 + @proteinas * 4 + @sal * 6\n\t\treturn @ener_kcal\n\tend",
"def curve(x0, y0, x1, y1, x2, y2, x3, y3)\n cur_page.curve(x0, y0, x1, y1, x2, y2, x3, y3)\n end",
"def calculation_methods\n out = {\n :demand => {\n :demand => {},\n :preset_demand => {},\n :demand_of_sustainable => {},\n :weighted_carrier_cost_per_mj => {},\n :weighted_carrier_co2_per_mj => {},\n :sustainability_share => {},\n :final_demand => {},\n :primary_demand => {},\n :primary_demand_of_fossil => {},\n :primary_demand_of_sustainable => {}\n },\n :technical => {\n :input_capacity => {},\n :electric_based_input_capacity => {label: '', unit: 'MWinput'},\n :heat_based_input_capacity => {label: '', unit: 'MWinput'},\n :cooling_based_input_capacity => {label: '', unit: 'MWinput'},\n :number_of_units => {}\n },\n :costs_per_plant => {\n 'total_costs_per(:plant)' => {label: 'Total costs per plant', unit: 'euro / plant'},\n 'fixed_costs_per(:plant)' => {},\n 'cost_of_capital_per(:plant)' => {},\n 'depreciation_costs_per(:plant)' => {},\n 'variable_costs_per(:plant)' => {},\n 'fuel_costs_per(:plant)' => {},\n 'co2_emissions_costs_per(:plant)' => {},\n 'fixed_operation_and_maintenance_costs_per(:plant)' => {},\n 'variable_operation_and_maintenance_costs_per(:plant)' => {},\n 'total_initial_investment_per(:plant)' => {},\n },\n :costs_per_node => {\n 'total_costs_per(:node)' => {},\n 'fixed_costs_per(:node)' => {},\n 'cost_of_capital_per(:node)' => {},\n 'depreciation_costs_per(:node)' => {},\n 'variable_costs_per(:node)' => {},\n 'fuel_costs_per(:node)' => {},\n 'co2_emissions_costs_per(:node)' => {},\n 'fixed_operation_and_maintenance_costs_per(:node)' => {},\n 'variable_operation_and_maintenance_costs_per(:node)' => {},\n 'total_initial_investment_per(:node)' => {},\n },\n :costs_per_mw_electricity => {\n 'total_costs_per(:mw_electricity)' => {},\n 'fixed_costs_per(:mw_electricity)' => {},\n 'cost_of_capital_per(:mw_electricity)' => {},\n 'depreciation_costs_per(:mw_electricity)' => {},\n 'variable_costs_per(:mw_electricity)' => {},\n 'fuel_costs_per(:mw_electricity)' => {},\n 'co2_emissions_costs_per(:mw_electricity)' => {},\n 'fixed_operation_and_maintenance_costs_per(:mw_electricity)' => {},\n 'variable_operation_and_maintenance_costs_per(:mw_electricity)' => {},\n 'total_initial_investment_per(:mw_electricity)' => {},\n },\n :costs_per_mwh_electricity => {\n 'total_costs_per(:mwh_electricity)' => {},\n 'fixed_costs_per(:mwh_electricity)' => {},\n 'cost_of_capital_per(:mwh_electricity)' => {},\n 'depreciation_costs_per(:mwh_electricity)' => {},\n 'variable_costs_per(:mwh_electricity)' => {},\n 'fuel_costs_per(:mwh_electricity)' => {},\n 'co2_emissions_costs_per(:mwh_electricity)' => {},\n 'fixed_operation_and_maintenance_costs_per(:mwh_electricity)' => {},\n 'variable_operation_and_maintenance_costs_per(:mwh_electricity)' => {},\n 'total_initial_investment_per(:mwh_electricity)' => {},\n },\n :costs_per_mw_heat => {\n 'total_costs_per(:mw_heat)' => {},\n 'fixed_costs_per(:mw_heat)' => {},\n 'cost_of_capital_per(:mw_heat)' => {},\n 'depreciation_costs_per(:mw_heat)' => {},\n 'variable_costs_per(:mw_heat)' => {},\n 'fuel_costs_per(:mw_heat)' => {},\n 'co2_emissions_costs_per(:mw_heat)' => {},\n 'fixed_operation_and_maintenance_costs_per(:mw_heat)' => {},\n 'variable_operation_and_maintenance_costs_per(:mw_heat)' => {},\n 'total_initial_investment_per(:mw_heat)' => {},\n },\n :costs_per_mwh_heat => {\n 'total_costs_per(:mwh_heat)' => {},\n 'fixed_costs_per(:mwh_heat)' => {},\n 'cost_of_capital_per(:mwh_heat)' => {},\n 'depreciation_costs_per(:mwh_heat)' => {},\n 'variable_costs_per(:mwh_heat)' => {},\n 'fuel_costs_per(:mwh_heat)' => {},\n 'co2_emissions_costs_per(:mwh_heat)' => {},\n 'fixed_operation_and_maintenance_costs_per(:mwh_heat)' => {},\n 'variable_operation_and_maintenance_costs_per(:mwh_heat)' => {},\n 'total_initial_investment_per(:mwh_heat)' => {},\n }\n }\n graph.carriers.each do |c|\n method_name = \"primary_demand_of_#{c.key}\".to_sym\n out[:demand][method_name] = {hide_if_zero: true}\n end\n out\n end",
"def electricity_network\n fetch(:electricity_network) do\n curve_helper = graph.plugin(:merit).curves\n\n Closud::Queryable.new(\n Closud.build(graph),\n ->(curve) { curve_helper.derotate(curve) }\n )\n end\n end",
"def profit_per_mwh_electricity\n production_mwh = production(:mwh)\n return nil if production_mwh.zero?\n\n profit / production_mwh\n end",
"def capacity_to_demand_multiplier\n 1.0\n end",
"def modeler_description\n return \"This measure will demonstrate how an OpenStudio measure calling EMS functions can be used to model the performance of HVAC equipment that cannot be represented well by using single “standard” performance curve objects (cubic, quadratic, biquadratic, etc.) For example, properly characterizing some HVAC equipment objects requires using different performance curves that cover operation of different parts of the performance regime. This measure will alter (overwrite) the Coil Cooling DX Single Speed Cooling Capacity as a function of temperature performance curve object and attributes used by the simulation if the outdoor air temperature falls below a user defined threshold. This measure allows the user to define the biquadratic curve coefficients associated with the Coil Cooling DX Single Speed Cooling Capacity.\"\n end",
"def modeler_description\n return 'Cooling Setpoints Hourly Adjusted by Degrees. Determines optimal cooling temperature ranges for load shaping of baseline load to meet the demand response of the target load'\n end",
"def quadratic_curve(x1, y1, x2, y2)\n [x1.value, y1.value, x2.value, y2.value]\n end",
"def electricity_price\n csv_serializer = CarrierPriceCSVSerializer.new(\n @scenario.gql.future_graph.carrier(:electricity),\n @scenario.gql.future_graph.year\n )\n\n respond_to do |format|\n format.csv { render_serializer csv_serializer }\n format.json { render json: csv_serializer }\n end\n end",
"def legendary_value(options)\n (5.00/25.00)\n end",
"def init_demand\n\t\t\n\t\t# building the sum of the demand values\n\t\tsum_values = 0\n\t\t(0..(@nbTSInOneDay - 1)).each do |ts|\n\t\t\tsum_values += getDemandAt(ts)\n\t\tend\n\t\t\n\t\t# cululated sum + normalization \n\t\tdemand = {}\n\t\t(0..(@nbTSInOneDay - 1)).each do |ts|\n\t\t\tdemand[ts] =\n\t\t\tif ts != 0\n\t\t\t\tdemand[ts - 1] + (getDemandAt(ts).to_f / sum_values)\n\t\t\telse\n\t\t\t\tgetDemandAt(ts).to_f / sum_values\n\t\t\tend\n\t\tend\n\t\t\n\t\treturn demand\n\tend",
"def emission_estimate(options = {})\n @emission_estimate ||= ::Carbon::EmissionEstimate.new self\n @emission_estimate.take_options options\n @emission_estimate\n end",
"def estimated_supply\n values = {}\n\n # Pi\n values[:absorbed_nitrogen_at_opening] = estimate_absorbed_nitrogen_at_opening\n\n # Ri\n values[:mineral_nitrogen_at_opening] = estimate_mineral_nitrogen_at_opening\n\n # Mh\n values[:humus_mineralization] = estimate_humus_mineralization\n\n # Mhp\n values[:meadow_humus_mineralization] = estimate_meadow_humus_mineralization\n\n # Mr\n values[:previous_cultivation_residue_mineralization] = estimate_previous_cultivation_residue_mineralization\n\n # Mrci\n values[:intermediate_cultivation_residue_mineralization] = estimate_intermediate_cultivation_residue_mineralization\n\n # Nirr\n values[:irrigation_water_nitrogen] = estimate_irrigation_water_nitrogen\n\n # Xa\n values[:organic_fertilizer_mineral_fraction] = estimate_organic_fertilizer_mineral_fraction\n\n # Rf\n values[:nitrogen_at_closing] = estimate_nitrogen_at_closing\n\n # Po\n values[:soil_production] = estimate_soil_production\n\n # Xmax\n values[:maximum_nitrogen_input] = estimate_maximum_nitrogen_input\n\n values\n end",
"def modeler_description\n return \"This energy efficiency measure (EEM) loops through all Controller:OutdoorAir objects and adds sensor faults to economizer sensor nodes. As appropriate, sensor drifts for return and outside air temperature and enthalpy are added to the model, based on the 'Economizer Control Type' setting. If the Economizer Control Type is set to 'No Economizer', no actions are taken. Drift limits are hard coded to reasonable values for sensor quality based on published ASHRAE documentation.\"\n end",
"def calculator\n @calculator ||= Fever::Calculator.new(consumer, activities)\n end",
"def get_eficiencia_diaria\n\t\tcalculate_eficiencia_diaria\n\tend",
"def cost\n 0.89\n end",
"def fuel_costs\n fetch(:fuel_costs) do\n if typical_input && typical_input < 0\n raise IllegalNegativeError.new(self, :typical_input, typical_input)\n end\n\n typical_input * weighted_carrier_cost_per_mj\n end\n end",
"def estimated_consumption(cr)\n total = 0\n # If real consumption equals zero, try to estimate\n if cr == 0\n # Only estimates if there is an incidence that requires estimating\n if ReadingIncidence.reading_should_be_estimated(self.id)\n # 1. Consumption invoiced in the same period of last year (reading_2)\n total = consumption_invoiced(reading_2)\n if total == 0\n # 2. Consumption invoiced in the last period (reading_1)\n total = consumption_invoiced(reading_1)\n if total == 0\n # 3. Average consumption of...\n invoice_date = billing_period.try(:prebilling_starting_date) || Date.today\n # 3.1. ...the last 36 months of reading\n from_date = invoice_date - 36.months\n total = consumption_previous_readings(from_date, invoice_date)\n if total == 0\n # 3.2. ...the last 12 months of reading\n from_date = invoice_date - 12.months\n total = consumption_previous_readings(from_date, invoice_date)\n if total == 0\n # 4. Nominal capacity of the meter x 15 hs x quantity of months\n nominal_flow = meter.caliber.nominal_flow rescue 1.5\n nominal_flow = 1.5 if nominal_flow.blank?\n total = (nominal_flow * 15) * billing_frequency.total_months\n end # 3.2\n end # 3.1\n end # 2\n end # 1\n end # ReadingIncidence.reading_should_be_estimated(self.id)\n else # If real consumption not equals zero, try to compensate\n total = estimated_consumption_with_cr(cr)\n end # cr == 0\n total || 0\n end",
"def non_final_demand_for_electricity\n group_demand_for_electricity(:non_final_electricity_demand_nodes)\n end",
"def preset_demand_by_electricity_production=(value)\n set_preset_demand_by_carrier_production(value, :electricity)\n end",
"def capacity_to_demand_multiplier\n 3600.0\n end",
"def get_cost_for_duration(resource, duration) ; 1.0 end",
"def load_curve\n if always_on?\n max_load_curve\n else\n @load_curve\n end\n end",
"def price_curve\n @price_curve ||= PriceCurve.new(self, fallback_price)\n end",
"def total_demand\n info[:total_demand]\n end",
"def co2_emissions_costs\n fetch(:co2_emissions_costs) do\n typical_input * co2_emissions_costs_per_typical_input\n end\n end",
"def co2_emissions_costs_per_typical_input\n 0.0\n end",
"def max_load_curve\n @max_load_curve ||= Curve.new(\n if @load_profile\n @load_profile.values.map { |v| v * max_production }\n else\n Array.new(Merit::POINTS, available_output_capacity)\n end\n )\n end",
"def CPI\n if self.spent_hours>0 and self.estimated_hours>0\n earned_value= (self.completed_percent * self.estimated_hours)/100\n actual_cost=self.spent_hours\n return (earned_value/actual_cost)\n else\n return 0\n end\n\n rescue\n return 0\n end",
"def estimated_charges\n @os_cloudwatch.estimated_charges\n end",
"def estimated_profit\n day_rate = avg_rate_card_amount_cents.round(2)\n mins_tracked = Timing.minute_duration_submitted_for_client(id)\n days_tracked = (mins_tracked.to_s.to_d / account.account_setting.working_day_duration_minutes).round(2)\n\n task_estimate_mins = Task.total_estimated_minutes_for_client(id)\n task_estimate_days = (task_estimate_mins.to_s.to_d / account.account_setting.working_day_duration_minutes).round(2)\n\n ((task_estimate_days * day_rate.to_s.to_d) - (days_tracked * day_rate.to_s.to_d)).round(2)\n end",
"def estimated_consumption_with_cr(cr)\n total = 0\n # if real consumption greater than zero, must compensate estimation balance\n if cr > 0\n total = cr < current_estimation_balance ? cr * (-1) : current_estimation_balance * (-1)\n end # cr > 0\n total || 0\n end",
"def modeler_description\n return 'This measure will clone all of the schedules that are used as electric equipment power setting for each zone. Then the schedules are adjusted by a specified percentage during a specified time period. If the measure is applied throughout the entire building, the reduction value can be separately defined based on whether this space type is occupied or not.'\n end",
"def nominal_due_given_efective(effective_rate, periods)\n\t\t\t((((1 + (effective_rate.to_f/100))**(1/periods.to_f)-1)*periods.to_f)*100).round(4)\n end",
"def price_coefficient_rate\n hash[\"PriceCoefficientRate\"]\n end",
"def initialize(curve_expression)\n raise InvalidCurveError, \"A curve expression should have :c as it's first symbol\" unless curve_expression[0] == :c\n raise InvalidCurveError, \"Curve expression contained no values\" unless curve_expression[2]\n \n # Nuke7 sometimes produces curves where the command is a string literal \n # within quotes, and it contains a trailing space\n cmd = curve_expression[1].to_s.strip\n raise InvalidCurveError, \"Curve expression should start with a 'curve' command\" unless cmd =~ /^curve/\n \n # Compute the curve increment or decrement. It looks like a modifier:\n # \"curve+5\" means we have to add 5 to every value on the curve\n xformer = lambda { |v| v} # Identity\n if cmd =~ /^(curve)([+-])([\\d\\.]+)$/\n operator = $2[0..1] # Ensure only one character gets through\n modifier = $3.to_f\n xformer = lambda{|v| v.send(operator, modifier) }\n end\n \n expand_curve(curve_expression, &xformer)\n end",
"def learning_curve_strategy\n @learning_curve = []\n current_week_data = strategy_stats (Time.now.all_week())\n prev_week_data = strategy_stats ((Time.now-1.week).all_week())\n prev_month_data = strategy_stats ((Time.now-1.month).all_month())\n current_month_data = strategy_stats (Time.now.all_month())\n @learning_curve << (average(current_week_data) - average(prev_week_data)).round(2)\n @learning_curve << (average(current_month_data) - average(prev_month_data)).round(2)\n end",
"def operating_costs\n fixed_om_costs + variable_costs\n end",
"def modeler_description\n return \"Reduces runtime fraction of lights by user-specified amount during the user-specified time period (typically daytime). This is an attempt to represent the impact of using the light collected on the roof instead of electric lighting. This modeling approach does not capture the impact of using a PV cell to turn the IR spectrum of the captured light into electricity.\"\n end",
"def curve(x1, y1, x2, y2, x3, y3)\n [x1.value, y1.value, x2.value, y2.value, x3.value, y3.value]\n end",
"def energy\n return @data.inject(0.0){|sum,x| sum + (x * x)}\n end",
"def demands\n demands_array.map do |name, constraint|\n Demand.new(self, name, constraint)\n end\n end"
] |
[
"0.7033966",
"0.70048326",
"0.6853632",
"0.67025465",
"0.65962905",
"0.6502511",
"0.6428135",
"0.6428135",
"0.6353733",
"0.6330756",
"0.6001785",
"0.59905463",
"0.59339285",
"0.57778776",
"0.5752317",
"0.5727273",
"0.55787647",
"0.55787647",
"0.5575891",
"0.5567091",
"0.55669624",
"0.551567",
"0.5465861",
"0.54058385",
"0.53998226",
"0.53900456",
"0.532687",
"0.53225416",
"0.5316469",
"0.5286483",
"0.52835435",
"0.525203",
"0.5250168",
"0.52485305",
"0.52472925",
"0.52440965",
"0.52417743",
"0.52387697",
"0.5209866",
"0.5187866",
"0.5174819",
"0.5159467",
"0.51551175",
"0.5140817",
"0.51316077",
"0.51305187",
"0.51258844",
"0.51207346",
"0.510734",
"0.50756615",
"0.5069429",
"0.5067261",
"0.50497186",
"0.50392336",
"0.5032625",
"0.50289804",
"0.5023933",
"0.50197005",
"0.5018175",
"0.5017387",
"0.50156206",
"0.50146514",
"0.5000128",
"0.49942935",
"0.49922767",
"0.49895436",
"0.49879366",
"0.49879342",
"0.49875668",
"0.49861917",
"0.4976694",
"0.49746615",
"0.49672782",
"0.49629933",
"0.49599338",
"0.4951739",
"0.49483016",
"0.49446782",
"0.4938224",
"0.4925926",
"0.49249086",
"0.49230963",
"0.4920357",
"0.4910961",
"0.4898731",
"0.48861554",
"0.48837295",
"0.48816195",
"0.48654085",
"0.48648968",
"0.48579794",
"0.4856453",
"0.48499203",
"0.48385063",
"0.48379984",
"0.4835287",
"0.4835032",
"0.48341691",
"0.48278847",
"0.48273182"
] |
0.73674726
|
0
|
Public: Returns the adapter for the node matching `key` or nil if the node is not a participant in the group.
|
def adapter(key)
if (config = @context.graph.node(key).fever)
adapters_by_type[config.type].find { |a| a.node.key == key }
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def [](key)\n @adapter[key.to_s]\n end",
"def get_node(key); end",
"def [](key)\n\t\t\treturn dial!(key)\n\t\tend",
"def fetch_node(key)\n node = fetch_node_nt(key)\n raise unless node\n node\n end",
"def node_for(path_or_key)\n key = PathEx::Key.new(path_or_key)\n return nil if key.blank?\n\n child = self.children.find { |c| c.name == key.head }\n child.nil? ? nil : key.has_tail? ? child.node_for(key.tail) : child\n end",
"def get_connection_by_key(key)\n if n = @slots[keyslot(key)]\n @connections[n[:name]] ||= get_redis_link(n[:host], n[:port])\n else\n # If we don't know what the mapping is, return a random node.\n get_random_connection\n end\n end",
"def [](key)\n if key == \"provider\"\n return @provider\n end\n @hash[key]\n end",
"def find_helper(current_node, key)\n return nil if current_node.nil?\n return current_node.value if current_node.key == key\n\n if key < current_node.key\n current_node = find_helper(current_node.left, key)\n else\n current_node = find_helper(current_node.right, key)\n end\n end",
"def find(key)\n find_node(checked_get_node(key))\n end",
"def get(key)\n node = node_for_key(key)\n node.read(&@block)\n end",
"def find_node(key)\n return nil if @root == nil\n node = @root.find_vertical(key)\n (node.nil? || node.value.nil? ? nil : node)\n end",
"def get(key)\n node_for(key).get(key)\n end",
"def search_key key\n node = self.head\n while node\n return node if node.key == key\n nc = node.child \n while nc\n return nc if nc.key == key\n ncs = nc.sibling\n while ncs \n return ncs if ncs.key == key\n ncs = ncs.sibling\n end\n nc = nc.child\n end\n node = node.sibling\n end\n end",
"def find(key)\n node = find_node(key)\n (node == nil ? nil : node.value)\n end",
"def [](key)\n\t\tcdat = gen_child_data(key)\n\t\tBLEU.new(nil, cdat)\n\tend",
"def get(key)\n node = get_rec(@root, key, 0)\n return nil if node.nil?\n return node.value\n end",
"def find_by_key(key)\n find_by_id(key) # backlog method looks exactly the same except for the parameter type\n end",
"def find_helper(node, key)\n if node.nil?\n return nil\n elsif node.key == key\n return node.value\n elsif key < node.key\n return find_helper(node.left, key)\n elsif key > node.key\n return find_helper(node.right, key)\n end\nend",
"def find(key)\n current_node = @root \n return find_helper(current_node, key)\n end",
"def peers_for( key, from_peer = nil )\n @peers.touch from_peer if from_peer\n key = Key.new(key) unless Key === key\n peers.nearest_to( key )\n end",
"def find(key)\n return self if @name == key\n @children.each do |child|\n next unless child.respond_to?(:find)\n match = child.find(key)\n return match unless match.nil?\n end\n nil\n end",
"def find_nearest_node(key) #:nodoc:\n x = anchor\n level = node_level(x)\n while level > 0\n level -= 1\n xnext = node_next(x, level)\n while node_compare(xnext, key) <= 0\n x = xnext\n xnext = node_next(x, level)\n end\n end\n x\n end",
"def [](key)\n index = self.index(key, @items.length)\n if !@items[index].nil?\n current = @items[index].head\n until current.nil?\n if current.key === key\n return current.value\n else\n current = current.next\n end\n end\n end\n end",
"def find_helper(current_node, key)\n return nil if current_node.nil?\n return current_node if current_node.value == key\n\n if key < current_node.value\n return find_helper(current_node.left_node, key)\n else\n return find_helper(current_node.right_node, key)\n end\n end",
"def get_node(string_key)\n pos = self.get_node_pos(string_key)\n return nil if pos.nil?\n\n return @ring[@_sorted_keys[pos]]\n end",
"def find_by_key(key)\n result = assert_connected(table)[key]\n return nil if result.nil?\n return new(result.merge(:pk => key))\n end",
"def adapter_key\n @key ||= Key.new(@feature.name, key)\n end",
"def find(key)\n return nil if @root.nil?\n return find_helper(@root, key)\n end",
"def retrieve key\n\t\tnode = traverse @root, key\n\t\tnode.key\n\tend",
"def find_helper(current_node, key)\n return if current_node.nil?\n \n if key < current_node.key\n current_node.left = find_helper(current_node.left, key)\n elsif key > current_node.key\n current_node.right = find_helper(current_node.right, key)\n else\n return current_node.value\n end\n \n end",
"def find_nearest_node(key) #:nodoc:\n x = node_first\n level = node_level(x)\n while level > 0\n level -= 1\n xnext = node_next(x, level)\n while node_compare(xnext, key) <= 0\n x = xnext\n xnext = node_next(x, level)\n end\n end\n x\n end",
"def find(key)\n x = find_nearest_node(key)\n return node_value(x) if node_compare(x, key) == 0\n nil # nothing found\n end",
"def find(key)\n x = find_nearest_node(key)\n return node_value(x) if node_compare(x, key) == 0\n nil # nothing found\n end",
"def get_room\n @key = @a_keys.shift\n find_room(@key)\n end",
"def peek_item(key)\n leaf = find_key(key)\n return nil unless leaf\n leaf.peek_item\n end",
"def node(key)\n @network.node(@values[key])\n end",
"def [](key)\n if !@con.nil?\n return @con[key]\n end\n\n nil\n end",
"def register_adapter(key, klass)\n adapters[key] = klass\n end",
"def find(key, node = root)\n return nil if node.nil?\n if key == node.data\n return node\n else\n find(key, left_right(key, node))\n end\n end",
"def get(key, &block)\n res = nil\n do_with_logging(:get, key) do\n retryable(:on => ArgumentError) do\n begin\n res = adapter.get(key.to_s)\n if res.nil?\n res = yield key if block_given?\n else\n res = unmarshall(res)\n end\n res\n rescue ArgumentError => e\n m = e.message.match(/class\\/module .*/)\n if m\n m = m.to_s\n m.gsub!(\"class/module\", '')\n m.gsub!(\"(ArgumentError)\", '')\n require m.strip.underscore\n raise e\n end\n rescue Exception => e\n raise e\n end\n end\n end\n res\n end",
"def find(key)\n if root.nil?\n return nil\n else\n root.find(key)\n end\n end",
"def [] (key)\n # Check if the handset actually has the key\n if @capabilityhash.key?(key)\n return @capabilityhash[key]\n else\n # The handset does not so check if the fallback handset does\n # Note: that this is actually a recursive call.\n if @fallback != nil\n return @fallback[key]\n end\n end\n # if it gets this far then no one has the key\n return nil\n end",
"def find(key)\n return find_helper(@root, key)\n end",
"def find(key)\n return find_helper(@root, key)\n end",
"def find(key)\n return find_helper(@root, key)\n end",
"def find(key)\n return find_helper(@root, key)\n end",
"def find(key)\n return find_helper(@root, key)\n end",
"def [](key)\n entry = find_entry(key)\n return(entry.nil? ? nil : entry[1])\n end",
"def find_key(key)\n leaf, stack = walk_towards_key(key)\n return nil if leaf && leaf.peek_item.key != key\n leaf\n end",
"def get(key)\n node = _get(@root, key)\n return nil unless node\n node.value\n end",
"def connection(key = :default)\n raise ArgumentError, \"Connection #{key} is not defined\" unless connections.key?(key)\n connections[key]\n end",
"def find(key)\n root = root? key.slice(0)\n [].tap { |a| root and probe(0, root, key[1..-1], a) }\n # generate_result([], key) { |rkey, r| r.first.prepend(rkey) }\n end",
"def [](key)\n if @items[index(key,size)] != nil\n current = @items[index(key, size)].head #chooses head node\n while current != nil\n if current.key == key\n return current.value\n else\n current = current.next\n end\n end\n end\n end",
"def connection(key)\n @connections[key]\n end",
"def connection(key)\n @connections[key]\n end",
"def find(key)\n current_and_parent_pair = find_current_and_parent_nodes(key)\n if current_and_parent_pair[:current] \n return current_and_parent_pair[:current].value\n else\n return nil\n end\n end",
"def find_by_key(key)\n by_key[key]\n end",
"def find_by_key(key)\n by_key[key]\n end",
"def get(key)\n key = to_key key\n return @group[key] if @group.key? key\n create key\n end",
"def get key\n deserialize backend.get key.to_s rescue nil\n end",
"def [](key)\n value = doozer_pool.with_connection do |doozer|\n doozer[full_key(key)]\n end\n @deserializer.deserialize(value)\n end",
"def find_node(calling_node, key)\n @router.touch(calling_node)\n return @router.get_closest_nodes(key)\n end",
"def find(key)\n if @root.nil?\n return nil\n elsif @root.key == key\n return @root.value\n else\n find_helper(@root, key)\n end\n end",
"def find_by_key(key)\n find_by('key', key)\n end",
"def safely_get_drentry_for_key(key)\n if ( self.dr[key]==nil)\n return \"\"\n end\n\n return dr[key][0][0]\n end",
"def get(key)\n return nil if @root.nil?\n \n splay(key)\n (@root.key <=> key) == 0 ? @root.value : nil\n end",
"def adapter\n return @adapter if @adapter\n self.use self.default_adapter\n @adapter\n end",
"def adapter\n return @adapter if @adapter\n self.use self.default_adapter\n @adapter\n end",
"def get(node, key)\n return nil unless map.key?(key)\n\n map[key].map do |matcher|\n return matcher[:klass] if node_matches?(node, matcher)\n end\n nil\n end",
"def get_node_ip(key)\n return @iplist[get_hash(key, @iplist.size)]\n end",
"def find(key)\n # TODO(himanshujaju) - possible improvement by not checking for contains.\n if contains?(key)\n return @key_data[key].value\n end\n\n return nil\n end",
"def find(key)\n current = @root\n\n while current != nil\n if current.key > key\n current = current.left\n elsif current.key < key\n current = current.right\n else\n return current.value\n end\n end\n return nil\n end",
"def find(key)\n if @root == nil\n return nil\n elsif @root.key == key\n return @root.value\n else\n current_node = @root\n while current_node != nil\n if key == current_node.key\n return current_node.value\n elsif key <= current_node.key\n current_node = current_node.left\n else\n current_node = current_node.right\n end\n end\n end \n end",
"def get(key)\n node = @node_map[key]\n if node\n # clip us out of the chain\n clip_node_from_list(node)\n insert_node_at_head(node)\n node.val\n else\n -1\n end\n end",
"def k8s_node(key)\n k8s_node_sub(@_k8s_node, key, key)\n end",
"def find(key)\r\n \t\t\t# Start at beginning of the List\r\n \t\t\tcurrent = @head\r\n \t\t\t# Go through list until nil\r\n\t\t\twhile current\r\n\t\t\t\t# If matching key is found return value at node\r\n\t\t\t\tif current.key == key\r\n\t\t\t\t\treturn current.value\r\n\t\t\t\tend\r\n\t\t\t\t# Go to next node\r\n\t\t\t\tcurrent = current.next\r\n\t\t\tend\r\n \t\tend",
"def bag_or_node(key, bag=nil)\n bag ||= retrieve_data_bag\n val = bag[key.to_s] if bag\n val || node[node_key][key]\n end",
"def get(key)\n data = request_data(:get, key_uri(key))\n return nil unless data\n if nodes = data[S_NODE][S_NODES]\n nodes.each_with_object({}) do |node, acc|\n acc[node[S_KEY]] = node[S_VALUE]\n end\n else\n data[S_NODE][S_VALUE]\n end\n end",
"def find(key)\n helper_find(@root, key)\n end",
"def find_by_key(key, options = {})\n record = find_record_by_key(key, options)\n resource_for(record, options[:context])\n end",
"def find_by_key(key)\n type, trail = decode_key(key)\n case type[0]\n when ?S\n ActiveSP::Site.new(self, trail[0] == \"\" ? @root_url : ::File.join(@root_url, trail[0]), trail[1].to_i)\n when ?L\n ActiveSP::List.new(find_by_key(trail[0]), trail[1])\n when ?U\n ActiveSP::User.new(root, trail[0])\n when ?G\n ActiveSP::Group.new(root, trail[0])\n when ?R\n ActiveSP::Role.new(root, trail[0])\n when ?A\n find_by_key(trail[0]).field(trail[1])\n when ?P\n ActiveSP::PermissionSet.new(find_by_key(trail[0]))\n when ?F\n list = find_by_key(trail[0])\n ActiveSP::Folder.new(list, trail[1])\n when ?I\n list = find_by_key(trail[0])\n ActiveSP::Item.new(list, trail[1])\n when ?T\n parent = find_by_key(trail[0])\n if ActiveSP::List === parent\n ActiveSP::ContentType.new(parent.site, parent, trail[1])\n else\n ActiveSP::ContentType.new(parent, nil, trail[1])\n end\n else\n raise \"not yet #{key.inspect}\"\n end\n end",
"def find(key)\n find_helper(@root, key)\n end",
"def find(key)\n find_helper(@root, key)\n end",
"def [](key)\n current_node = @buckets[index(key, size)].head\n if !current_node\n #raise InvalidKeyError \"Cannot retrieve that item - not instantiated\"\n return nil\n end\n while current_node.key != key\n current_node = current_node.next\n break unless current_node\n end\n\n if !current_node\n #raise InvalidKeyError \"Cannot retrieve that item - not instantiated\"\n return nil\n end\n\n return current_node.value\n end",
"def get(key)\n\t\t\t@@driver.get(key.to_s, (key.is_a? Array) ? true : false)\n\t\tend",
"def try_get(key)\n curr = self\n found = false\n val = nil\n while (not found) and (not curr.nil?)\n found, val = curr.query(key)\n curr = curr.parent\n end\n return [ found, val ]\n end",
"def extension(key)\r\n return nil unless @extensions.has_key?(key)\r\n return @extensions[key]\r\n end",
"def [](key)\n return @discovery_document[key]\n end",
"def get_value_and_owner(key)\n return @capabilityhash[key],@wurfl_id if @capabilityhash.key?(key)\n return @fallback.get_value_and_owner(key) if @fallback != nil\n return nil,nil\n end",
"def get(key)\n get_recursive(@root, key)\n end",
"def [](key)\n selected_child = children.select {|child| child.name == key }\n selected_child.size.eql?(1) ? selected_child.first : selected_child\n end",
"def find(key)\n if empty?\n nil\n else\n if @val[0] == key\n @val\n elsif @val[0] < key && @right!=nil\n @right.find(key)\n elsif @left!=nil\n @left.find(key)\n else\n nil\n end\n end\n end",
"def [](key)\n return nil unless @data.is_a?(Hash)\n\n @data[compatible_key(key)]\n end",
"def get_account_by_key(opts = {})\n data, _status_code, _headers = get_account_by_key_with_http_info(opts)\n return data\n end",
"def find(key, node=@root)\n return nil if @root.nil?\n\n if key < node.key\n find(key, node.left)\n elsif key > node.key\n find(key, node.right)\n else\n return node.value\n end\n end",
"def get key\n\t\t\tif @my_hash.has_key? key\n\t\t\t\tnode = @my_hash[key]\n\t\t\t\t@my_list.promote_node node\n\t\t\t\tnode.value\n\t\t\telse\n\t\t\t\tnil\n\t\t\tend\n\t\tend",
"def find(key)\n return nil if @root.nil?\n\n current = @root\n while current\n if key > current.key\n current = current.right\n elsif key < current.key\n current = current.left\n else\n return current.value\n end\n end\n\n return nil\n end",
"def [](key)\n node = root_node\n ba_key = Bitarray.new(key)\n\n # descend to the node or bail with null value hash\n 1.upto(KEY_SIZE) do |depth|\n bit = ba_key[depth - 1]\n node = (bit == 0) ? node.left : node.right\n return self.class.null_value_hash unless node\n end\n node.value\n end",
"def get_encrypted_data(item, key)\n datum = nil\n begin\n # load the encrypted data bag item, using a secret if specified\n data = Chef::EncryptedDataBagItem.load(@bag, item, secret)\n # now, let's look for the data\n datum = data[key]\n rescue\n Chef::Log.info(\"Unable to load data for #{key}, #{item}.\")\n end\n datum\n end",
"def get_druther(key)\n druthers_cache.fetch(key) do\n val = where(key: key).pluck(:value).to_a\n val.present? ? val.first : send_druthers_event(:default, key)\n end\n end"
] |
[
"0.55878437",
"0.55456716",
"0.5412625",
"0.5281771",
"0.52773225",
"0.5255326",
"0.5246342",
"0.5224118",
"0.5180288",
"0.5157669",
"0.51574326",
"0.5157236",
"0.5137",
"0.5110948",
"0.5108243",
"0.50745267",
"0.503432",
"0.5034296",
"0.5025054",
"0.50127786",
"0.50102276",
"0.49973878",
"0.499458",
"0.49863142",
"0.49827302",
"0.49813244",
"0.49729165",
"0.496333",
"0.4952545",
"0.49383792",
"0.4920082",
"0.49020877",
"0.49020877",
"0.4901106",
"0.489586",
"0.48834005",
"0.48724303",
"0.48675418",
"0.4842352",
"0.4842156",
"0.48417196",
"0.48089585",
"0.479586",
"0.479586",
"0.479586",
"0.479586",
"0.479586",
"0.4786276",
"0.47782916",
"0.47773412",
"0.4776251",
"0.47717136",
"0.47712103",
"0.4760543",
"0.4760543",
"0.47599372",
"0.47584257",
"0.47584257",
"0.47405455",
"0.4724554",
"0.47140512",
"0.47045982",
"0.470229",
"0.47012234",
"0.47002244",
"0.46932948",
"0.46809343",
"0.4680763",
"0.4680043",
"0.46726963",
"0.46713582",
"0.4650438",
"0.4645991",
"0.46449485",
"0.4638729",
"0.46304286",
"0.4629089",
"0.4617653",
"0.4617132",
"0.46167877",
"0.46163645",
"0.45993763",
"0.45993763",
"0.4598985",
"0.45892492",
"0.4586811",
"0.4585163",
"0.457847",
"0.45742753",
"0.45733917",
"0.45647168",
"0.45569876",
"0.45494702",
"0.45418915",
"0.45335892",
"0.4522962",
"0.45179743",
"0.45172358",
"0.45126367",
"0.45109305"
] |
0.71893305
|
0
|
Internal: The adapters which map nodes from the graph to activities within Fever.
|
def adapters
adapters_by_type.values.flatten
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def adapters\n @adapters ||=\n @nodes.transform_values do |convs|\n convs.map { |conv| Adapter.adapter_for(conv, @context) }\n end\n end",
"def activity\n @root.xpath('Events/Event').map do |act|\n Activity.new(act)\n end\n end",
"def to_directed_graph(adapters)\n node_paths = {}\n adapters.each do |node|\n node_paths[node] = adapters.select{|other_node| other_node.between?(node+1, node+3)}\n end\n node_paths\nend",
"def get_field_deserializers()\n return {\n \"activities\" => lambda {|n| @activities = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::ExternalConnectorsExternalActivity.create_from_discriminator_value(pn) }) },\n }\n end",
"def activity\n @root.xpath('TrackSummary').map do |act|\n Activity.new(act)\n end +\n @root.xpath('TrackDetail').map do |act|\n Activity.new(act)\n end\n end",
"def activity\n @root.xpath('TrackSummary').map do |act|\n Activity.new(act)\n end +\n @root.xpath('TrackDetail').map do |act|\n Activity.new(act)\n end\n end",
"def adapters_by_type\n return @adapters if @adapters\n\n @adapters =\n Manager::TYPES.each_with_object({}) do |type, data|\n data[type] =\n Etsource::Fever.group(@name).keys(type).map do |node_key|\n Adapter.adapter_for(\n @context.graph.node(node_key), @context\n )\n end\n end\n end",
"def wrap(activities)\n activities.map do |act|\n if act['activities']\n # Feed::ActivityGroup automatically converts activites in it\n Feed::ActivityGroup.new(opts[:feed], act)\n else\n Feed::Activity.new(opts[:feed], act)\n end\n end\n end",
"def adapter(key)\n if (config = @context.graph.node(key).fever)\n adapters_by_type[config.type].find { |a| a.node.key == key }\n end\n end",
"def activities\n\t activity_feed.activities\n\tend",
"def activities\n children('activities')\n end",
"def map_nodes!(bijection)\n self.each do |solution|\n solution.each_binding do |name, value|\n solution[name] = bijection.fetch(value, value)\n end\n end\n end",
"def get_edges\n getEdges.to_route(:graph => self, :element_type => :edge)\n end",
"def get_edges\n getEdges.to_route(:graph => self, :element_type => :edge)\n end",
"def get_edges\n getEdges.iterator.to_route(:graph => self, :element_type => :edge)\n end",
"def to_nodes(event)\n nodes = []\n event.transitions.each do |transition|\n if transition.multiple_from?\n temp_nodes = transition.from.map{ |from| Jsm::Drawer::Node.new(from: from, to: transition.to, label: event.name) }\n else\n from = transition.from[0] # even only one it is still in array e.g: [:confirmed]\n temp_nodes = [Jsm::Drawer::Node.new(from: from, to: transition.to, label: event.name)]\n end\n nodes += temp_nodes\n end\n nodes\n end",
"def add_activities!(activities)\n activities.each do |activity|\n activity.slot.series.each do |time|\n activity.courts.each do |court|\n grid.fill(time, court.id, Table::Cell::Activity.new(activity,time))\n end\n end\n end\n end",
"def communicationgraph_old(filter=@filter, &block) # :nodoc:\n us = users(filter)\n if block\n g = DotGraph.new(us, :directed => true, &block)\n else\n g = DotGraph.new(us, :directed => true) { |n| n.name }\n end\n pages(filter).each do |p| \n p.revisions(filter).inject do |a,b|\n g.link(b.user,a.user)\n b\n end\n end\n g\n end",
"def activities\n add_to_query restrict_kind: 'activity'\n end",
"def activity_complements\n\n context.render_entity_aspects(activity, :activity)\n\n end",
"def build_activities(id=nil)\n @doc.xpath('//xmlns:Activity', namespaces).map do |activity_node|\n # Assuming only 1 activity in a file for now. This will need to be fixed.\n @activities_obj = build_activity(activity_node)\n end\n end",
"def initialize(mappers = Mapper::Relation.descendants, edge_builder = RelationRegistry::Builder, mapper_builder = Mapper::Builder)\n @mappers = mappers\n @mapper_registry = Mapper.mapper_registry\n @edge_builder = edge_builder\n @mapper_builder = mapper_builder\n end",
"def edges_from(node)\n self[node].map { |n| [node, n] }\n end",
"def attach_graph(attach_point, fsm)\r\n node_count = get_node_count\r\n raise \"#{attach_point} out of graph bounds.\" if attach_point >= node_count\r\n raise \"going to break everything by attaching to myself!\" if fsm == self\r\n #dfa = fsm.subsetify #.subsetify\r\n dfa = fsm # Before, we were subsetifying\r\n dfa.increment_node_labels(node_count)\r\n #@graph_hash[attach_point] = {LAMBDA => dfa.origin} # THIS IS OUR CULPRIT!\r\n #puts \"before #{@graph_hash[attach_point]}\"\r\n \r\n #if (@graph_hash[attach_point]!=nil)\r\n # lambdas = [@graph_hash[attach_point][LAMBDA]] || [] # this is an array!\r\n # lambdas << dfa.origin\r\n # lambdas = lambdas.flatten.find{|entry| !entry.nil?}\r\n # @graph_hash[attach_point][LAMBDA] = lambdas\r\n #else\r\n # @graph_hash[attach_point] = {LAMBDA => dfa.origin}\r\n #end\r\n\r\n # if attach point was on the graph w/o outgoing edges\r\n @graph_hash[attach_point] = Hash.new if @graph_hash[attach_point].nil?\r\n \r\n if @graph_hash[attach_point][LAMBDA].nil?\r\n @graph_hash[attach_point][LAMBDA] = [dfa.origin]\r\n else # attach point already has outgoing lambda edges\r\n @graph_hash[attach_point][LAMBDA] << dfa.origin\r\n end\r\n \r\n #@graph_hash[attach_point][\"foo\"] = lambdas\r\n #puts \"after #{@graph_hash[attach_point]}\"\r\n #puts \"@gh = #{graph_hash}\\ndfah = #{dfa.graph_hash}\"\r\n #puts \"merged: #{@graph_hash.merge(dfa.graph_hash)}\"\r\n @graph_hash.merge!(dfa.graph_hash)\r\n #@graph_hash.merge!({4=>{\"L\"=>21}})\r\n @accept_states.merge!(dfa.accept_states)\r\n #subsetify!\r\n get_node_count\r\n end",
"def init_with_args(type, from_node, to_node)\n @_java_node = Neo4j.create_rel(type, from_node, to_node)\n @_java_node._wrapper = self\n @_java_node[:_classname] = self.class.to_s\n Neo4j.event_handler.relationship_created(self)\n self.class.indexer.on_relationship_created(@_wrapper, type) \n end",
"def edges\n\t\t\tself.node_maps.select { |i| !i.marked_for_destruction? }.select { |i|\n\t\t\t\ti.node && i.parent\n\t\t\t}.collect { |i|\n\t\t\t\t{\n\t\t\t\t\t:source => i.parent.node.id,\n\t\t\t\t\t:target => i.node.id,\n\t\t\t\t}\n\t\t\t}.uniq\n\t\tend",
"def expand\n @state.neighbors.map{|n|\n AStarNode.new(n, self)\n }\n end",
"def initialize\n @forward_edges_with_info = IdentityHash.new\n @backward_edges = IdentityHash.new\n end",
"def initialize(nodes, edges)\n super()\n self.nodes = nodes\n self.edges = edges.map { |e| Edge.new(e[0], e[1], e[2]) }\n\n self.build\n end",
"def feed node\n return unless node.respond_to? :attributes\n value = Hash[node.attributes.map{|k,v|[k, typecasted(v.value) ]}] \n if @state_assigned\n feed_value value\n else\n assign_state value\n end \n end",
"def update_tree_activities(activity, title, start_time, end_time)\n\n #First update itself.\n #\n #\n activity.name = title\n activity.start_time = start_time\n activity.end_time = end_time\n activity.save\n\n #Activity Root Node just update all children.\n #\n #\n if (activity.reference_activity == nil)\n\n ref_activities = Activity.where('reference_activity_id = ?', \"#{ activity.id }\")\n\n ref_activities.each do |ref_item|\n ref_cal = Google::Calendar.new(:username => ref_item.user.email,\n :password => ref_item.user.email_password,\n :app_name => 'firmy')\n\n if (ref_cal != nil)\n ref_event = ref_cal.find_event_by_id(ref_item.reference)\n ref_event.title = title\n ref_event.start_time = start_time\n ref_event.end_time = end_time\n ref_cal.save_event(ref_event)\n end\n\n ref_item.name = title\n ref_item.start_time = start_time\n ref_item.end_time = end_time\n ref_item.save\n end\n\n #Activity Child Node need to find root node and then update all children.\n #\n #\n else\n root_activity = Activity.where('id = ?', \"#{ activity.reference_activity.id }\").first\n\n root_cal = Google::Calendar.new(:username => root_activity.user.email,\n :password => root_activity.user.email_password,\n :app_name => 'firmy')\n\n if (root_cal != nil)\n root_event = root_cal.find_event_by_id(root_activity.reference)\n root_event.title = title\n root_event.start_time = start_time\n root_event.end_time = end_time\n root_cal.save_event(root_event)\n end\n\n root_activity.name = title\n root_activity.start_time = start_time\n root_activity.end_time = end_time\n root_activity.save\n\n update_tree_activities(root_activity, title, start_time, end_time)\n end\n\n end",
"def activity_worker\n worker = AWS::Flow::ActivityWorker.new(@domain.client, @domain, ACTIVITY_TASKLIST)\n worker.add_implementation(SwfActivityOne.new)\n worker.add_implementation(SwfActivityTwo.new)\n worker.add_implementation(SwfActivityThree.new)\n worker\n end",
"def initialize\n @nodes = {}\n @edges = {}\n @back_edges = {}\n end",
"def node_ids() ; ext_info[:nodes] ; end",
"def apply_maps(activities, maps)\n return activities if maps.empty?\n activities.map do |act|\n if act['activities'] # Recurse into activity groups\n act['activities'] = apply_maps(act['activities'], maps)\n act\n else\n maps.reduce(act) { |acc, elem| elem.call(acc) }\n end\n end\n end",
"def neighbor_vertices\n @meeting_edges.map &:to\n end",
"def node_to_map\r\n if map.nil?\r\n @map = Map.new @node.expand_to_map(gdata: self)\r\n else\r\n new_map = @node.expand_to_map(existing: map, gdata: self)\r\n if new_map.size > 1 # TODO Detect trivial integrations in node.rb, not here\r\n new_map.each { |loc| map.push loc }\r\n end\r\n end\r\n end",
"def set_activities_for_pagination\n \n end",
"def map_nodes_for_events(events_diff, handlers)\n nodes_events = {}\n events_diff.each do |object, events|\n events.each do |event, nodes|\n handlers.keys.each do |ip|\n if nodes.include?(ip)\n nodes_events[ip] ||= {}\n nodes_events[ip][object] ||= []\n nodes_events[ip][object].push(event)\n break\n end\n end\n end\n end\n nodes_events\n end",
"def initialize activity\n @activity = activity\n end",
"def relations\n Relations::RelationTraverser.new(@internal_node)\n end",
"def build_activity_oid_map()\n activity_object_ids = {}\n activities = @primavera.get_activities(P6_PROJECT_ID)\n activities.each do |activity|\n activity_object_ids[activity[:id]] = activity[:object_id]\n end\n activity_object_ids\nend",
"def nodes; end",
"def nodes; end",
"def nodes; end",
"def refinery_graph\n @refinery ||= begin\n catalysts.reduce(graph) do |result, catalyst|\n catalyst.call(result)\n end\n end\n end",
"def nodes\n @object.edge_nodes\n end",
"def internal_connections\n stroke(200, 0, 0, 80)\n nodes[0..nodes.size - 1].each_with_index do |pi, i|\n nodes[i + 1..nodes.size - 1].each do |pj|\n line(pi.x, pi.y, pj.x, pj.y)\n end\n end\n end",
"def nested_graph\n @nested_graph ||= ModelConverter.new(resource: Valkyrie::Types::Anything[value.value], adapter: value.adapter, subject_uri: subject_uri).convert.graph\n end",
"def anything\n EDGE_LIST.each do |record|\n from, to, weight = record\n @adj_matrix[from.id][to.id] = weight\n @adj_matrix[to.id][from.id] = weight\n end\n end",
"def activity\n end",
"def relations_for(node) #:nodoc:\n Enumerator.new do |yielder|\n @description.relations.each do |relation_accessor|\n begin\n relations = relation_accessor[node]\n enumerable = relations.is_a?(Enumerable) ? relations : [relations].compact\n\n enumerable.each { |e| yielder << e unless visited?(e) }\n rescue NoMethodError\n # ignore errors on relation_accessor[node]\n end\n end\n end\n end",
"def map_nodes!(&ruby_block)\n # Nothing to do.\n end",
"def to_edges\n @value.collect do |reference|\n reference.catalog = resource.catalog\n\n # Either of the two retrieval attempts could have returned\n # nil.\n unless related_resource = reference.resolve\n self.fail \"Could not retrieve dependency '#{reference}' of #{@resource.ref}\"\n end\n\n # Are we requiring them, or vice versa? See the method docs\n # for futher info on this.\n if self.class.direction == :in\n source = related_resource\n target = @resource\n else\n source = @resource\n target = related_resource\n end\n\n if method = self.class.callback\n subargs = {\n :event => self.class.events,\n :callback => method\n }\n self.debug(\"subscribes to #{related_resource.ref}\")\n else\n # If there's no callback, there's no point in even adding\n # a label.\n subargs = nil\n self.debug(\"requires #{related_resource.ref}\")\n end\n\n rel = Puppet::Relationship.new(source, target, subargs)\n end\n end",
"def detect_cycle_in_graph(edges)\nend",
"def add_edges_to(label, to_vertices, props = {})\n case to_vertices\n when Pacer::Core::Route, Enumerable, java.util.Iterator\n else\n to_vertices = [to_vertices].compact\n end\n graph = self.graph\n unless graph\n v = (detect { |v| v.graph } || to_vertices.detect { |v| v.graph })\n graph = v.graph if v\n unless graph\n Pacer.debug_info << { :error => 'No graph found', :from => self, :to => to_vertices, :graph => graph }\n raise \"No graph found\"\n end\n end\n has_props = !props.empty?\n first_edge_id = last_edge_id = nil\n counter = 0\n graph.managed_transactions do\n graph.managed_transaction do\n each do |from_v|\n to_vertices.to_route.each do |to_v|\n counter += 1\n graph.managed_checkpoint if counter % graph.bulk_job_size == 0\n begin\n edge = graph.create_edge(nil, from_v, to_v, label.to_s, props)\n first_edge_id ||= edge.element_id\n last_edge_id = edge.element_id\n end\n end\n end\n end\n end\n if first_edge_id\n if last_edge_id != first_edge_id\n (first_edge_id..last_edge_id)\n else\n first_edge_id\n end\n end\n end",
"def each_annotated_port(&block)\n if !block_given?\n return enum_for(:each_annotated_port)\n end\n frame_associations.each(&block)\n supercall(nil, :each_annotated_port, &block)\n end",
"def to_node_maps(nodes, config)\n config.map { |from, to| get_node_map(nodes, from, to) }\n end",
"def map_nodes!(&ruby_block)\n @index = ruby_block.call(@index)\n @index.parent = self unless @index.parent\n @ref = ruby_block.call(@ref)\n @ref.parent = self unless @ref.parent\n end",
"def collect_node_nei_hashes\n @log.info(\"#{__method__.to_s} started[#{self.class.to_s}]\")\n\n node_nei_hash = @redis_connector.fetch_relations\n end",
"def connectable_nodes_from(nodes)\n @calls << [:connectable_nodes_from, nodes]\n nodes & @accept_nodes\n end",
"def feed( params={} )\n feed = get_connections(\"feed\", params)\n return map_connections feed, :to => Facebook::Graph::Generic\n end",
"def feed( params={} )\n feed = get_connections(\"feed\", params)\n return map_connections feed, :to => Facebook::Graph::Generic\n end",
"def adapters\n @adapters ||= {}\n end",
"def connections_to(node)\n node = get_index_from_node(node)\n @adj_mat.map {|row| row[node] }.map.with_index do|el, row_num| \n el == 0 ? nil : @nodes[row_num]\n end.select{ |el| el } \n end",
"def connections_to(node)\n node = get_index_from_node(node)\n @adj_mat.map {|row| row[node] }.map.with_index do|el, row_num| \n el == 0 ? nil : @nodes[row_num]\n end.select{ |el| el } \n end",
"def bridge_all_traffic_state\n super\n end",
"def neighbors\n NodeWrapper.new @links.map(&:to)\n end",
"def __connect__(node)\n raise \"Cannot connect to a node which is not on the same graph!\" if node.graph != @this.graph\n node.in.instance_exec(@this) { |n| @others << n }\n @graph.instance_eval { @changed = true }\n end",
"def to_adj\n full_jsivt= []\n @nodes.each do |id, node_data|\n name = node_data[@name_key]\n data = node_data[:data]\n adjacencies = node_data[@children_key]\n jsivt = {}\n jsivt[\"id\"] = id\n jsivt[\"name\"] = name || \"id: #{id}\" #if no name show id\n jsivt[\"data\"] = data\n jsivt[\"adjacencies\"] = adjacencies\n full_jsivt << jsivt\n end \n full_jsivt.to_json \n end",
"def construct_adj_list(edges)\n map = Hash.new\n edges.each do |edge|\n from = edge[0]\n to = edge[1]\n if map[to].nil?\n map[to] = []\n end\n if map[from].nil?\n map[from] = []\n end\n map[from].push(to)\n end\n map\nend",
"def convert_class_list_to_graph()\n class_list.each do |c|\n node = graph_add_or_find_node(c)\n ancestors = generate_ancestor_list(c)\n process_ancestor_list(ancestors, node)\n end\n end",
"def establish_edges!\n @edges.sort_by(&:key).each do |edge|\n next if edge.carrier == :coupling_carrier\n\n self.class.establish_edge(edge, @graph, @nodes)\n end\n end",
"def adapters\n @adapters ||= {}\n end",
"def nodes\n @pathway.graph.keys\n end",
"def activities()\n sql = \"SELECT a.* FROM activities a INNER JOIN bookings b ON b.activities_id = a.id WHERE b.members_id =$1\"\n values = [@id]\n result = SqlRunner.run(sql, values)\n return result.map { |session| Activity.new( session) }\n end",
"def initialize(dataset)\n opts = dataset.opts\n eager_graph = opts[:eager_graph]\n @master = eager_graph[:master]\n requirements = eager_graph[:requirements]\n reflection_map = @reflection_map = eager_graph[:reflections]\n reciprocal_map = @reciprocal_map = eager_graph[:reciprocals]\n limit_map = @limit_map = eager_graph[:limits]\n @unique = eager_graph[:cartesian_product_number] > 1\n \n alias_map = @alias_map = {}\n type_map = @type_map = {}\n after_load_map = @after_load_map = {}\n reflection_map.each do |k, v|\n alias_map[k] = v[:name]\n after_load_map[k] = v[:after_load] unless v[:after_load].empty?\n type_map[k] = if v.returns_array?\n true\n elsif (limit_and_offset = limit_map[k]) && !limit_and_offset.last.nil?\n :offset\n end\n end\n\n # Make dependency map hash out of requirements array for each association.\n # This builds a tree of dependencies that will be used for recursion\n # to ensure that all parts of the object graph are loaded into the\n # appropriate subordinate association.\n @dependency_map = {}\n # Sort the associations by requirements length, so that\n # requirements are added to the dependency hash before their\n # dependencies.\n requirements.sort_by{|a| a[1].length}.each do |ta, deps|\n if deps.empty?\n dependency_map[ta] = {}\n else\n deps = deps.dup\n hash = dependency_map[deps.shift]\n deps.each do |dep|\n hash = hash[dep]\n end\n hash[ta] = {}\n end\n end\n \n # This mapping is used to make sure that duplicate entries in the\n # result set are mapped to a single record. For example, using a\n # single one_to_many association with 10 associated records,\n # the main object column values appear in the object graph 10 times.\n # We map by primary key, if available, or by the object's entire values,\n # if not. The mapping must be per table, so create sub maps for each table\n # alias.\n records_map = {@master=>{}}\n alias_map.keys.each{|ta| records_map[ta] = {}}\n @records_map = records_map\n\n datasets = opts[:graph][:table_aliases].to_a.reject{|ta,ds| ds.nil?}\n column_aliases = opts[:graph_aliases] || opts[:graph][:column_aliases] # SEQUEL5: Remove :graph_aliases support\n primary_keys = {}\n column_maps = {}\n models = {}\n row_procs = {}\n datasets.each do |ta, ds|\n models[ta] = ds.model\n primary_keys[ta] = []\n column_maps[ta] = {}\n row_procs[ta] = ds.row_proc\n end\n column_aliases.each do |col_alias, tc|\n ta, column = tc\n column_maps[ta][col_alias] = column\n end\n column_maps.each do |ta, h|\n pk = models[ta].primary_key\n if pk.is_a?(Array)\n primary_keys[ta] = []\n h.select{|ca, c| primary_keys[ta] << ca if pk.include?(c)}\n else\n h.select{|ca, c| primary_keys[ta] = ca if pk == c}\n end\n end\n @column_maps = column_maps\n @primary_keys = primary_keys\n @row_procs = row_procs\n\n # For performance, create two special maps for the master table,\n # so you can skip a hash lookup.\n @master_column_map = column_maps[master]\n @master_primary_keys = primary_keys[master]\n\n # Add a special hash mapping table alias symbols to 5 element arrays that just\n # contain the data in other data structures for that table alias. This is\n # used for performance, to get all values in one hash lookup instead of\n # separate hash lookups for each data structure.\n ta_map = {}\n alias_map.keys.each do |ta|\n ta_map[ta] = [records_map[ta], row_procs[ta], alias_map[ta], type_map[ta], reciprocal_map[ta]]\n end\n @ta_map = ta_map\n end",
"def performance_graph_list\n super\n end",
"def inject_graph_values!\n end",
"def map_nodes!(&ruby_block)\n # By default, nothing to do.\n end",
"def edges\n @pathway.relations.collect do |rel|\n [ rel.node[0], rel.node[1], rel.relation ]\n end\n end",
"def kind\n :activity\n end",
"def res_node_for_child_2(ch_nodes)\n res = []\n\n if ch_nodes\n ch_nodes.each do |child|\n node_type = child.type\n res2 = {\n 'nodeinfo' => child,\n 'name' => child.get_name,\n 'instructor_id' => child.get_instructor_id, # add instructor id to the payload to make it available in the frontend\n 'key' => params[:reactParams2][:key],\n 'type' => node_type,\n 'private' => child.get_private,\n 'creation_date' => child.get_creation_date,\n 'updated_date' => child.get_modified_date\n }\n coursenode_assignmentnode(res2, child) if %w[CourseNode AssignmentNode].include? node_type\n res << res2\n end\n end\n res\n end",
"def entry_edges\n ensure_network\n self.network.entry_edges\n end",
"def activities_for(filter: nil, type: _feed_type)\n Feed::ActivityList.new(self).filter(filter).with_type(type)\n end",
"def each\n @nodes.values.each do |node|\n yield node, node.adjacency_list\n end\n end",
"def nodes\n @from | @to\n end",
"def data\n @map = Map.find(params[:map_id])\n @categories = @map.categories\n p \"--------- @map ---------\"\n p @map.nodes.to_json\n response = { nodes: [], edges: []}\n @map.nodes.each do |n|\n response[:nodes] << {id: n.id, name: n.name, description: n.description}\n n.rels.each do |rel|\n start = idIndex(@map.nodes, rel.start_node.id)\n stop = idIndex(@map.nodes, rel.end_node.id)\n if !start.nil? && !stop.nil?\n response[:edges] << {source: start, target: stop, type: rel.rel_type }\n end\n end\n end\n index_offset = @map.nodes.count \n @categories.each do |n|\n response[:nodes] << {id: n.id, name: n.name}\n n.rels.each do |rel|\n start = idIndex(@map.nodes, rel.start_node.id)\n stop = idIndex(@categories, rel.end_node.id, index_offset)\n if !start.nil? && !stop.nil?\n response[:edges] << {source: start, target: stop, type: rel.rel_type }\n end\n end\n end\n p \"------------ response -----------\"\n puts response.to_json\n respond_to do |format|\n format.html { render 'graph/show'}\n format.json { render json: response}\n end\nend",
"def for_node; end",
"def establish_edges!\n @edges.sort_by(&:key).each do |edge|\n next if edge.carrier == :coupling_carrier\n\n self.class.establish_edge(edge, @graph)\n end\n end",
"def activities\n Activity.\n includes(:activity_objects => self.class.to_s.underscore).\n where(\"#{ self.class.quoted_table_name }.id\" => self.id)\n end",
"def activities\n get_call(\"1/activities.json\")\n end",
"def infer_relations_relations\n datasets.each do |gateway, schema|\n schema.each do |name|\n if infer_relation?(gateway, name)\n klass = Relation.build_class(name, adapter: adapter_for(gateway))\n klass.gateway(gateway)\n klass.dataset(name)\n else\n next\n end\n end\n end\n end",
"def transfer_node_attributes(nodes, attributes); end",
"def find_activities\n #This needs to be updated to handle the Ring Model\n #Unit Test is in activity_test.rb\n activities = Array.new\n for friend in mutual_friends\n for activity in friend.activities\n #Does the user have permission to view the activity?\n #The friend must have the user in a ring of equal distance or closer than the content created.\n #However, Comments don't have a ring number, so their respective posts must be referred to.\n if activity.entity_type == 'Comment'\n #The user must be close enough to his/her friend \n if activity.entity.post.ring >= friend.which_ring(self)\n activities << activity\n end\n elsif activity.entity.ring >= friend.which_ring(self)\n if activity.entity_type == 'Friendship'\n #A mutual friendship creates two activities--one for each friendship.\n #This makes sure that only one activity is seen in the list.\n activities.include?(activity.entity.mutual_friendship.activity) ? nil : activities << activity\n else \n activities << activity\n end\n end\n end\n end\n #Sort the activity chronologically\n activities.sort!{|a, b| b.updated_at<=>a.updated_at}\n return activities\n end",
"def loadGraph \n \n @airports = \n $adameus.airports.split(/\\n/).map do |airport|\n Airport.new(airport[0,3])\n end\n @airports.each do |airport|\n loadAirport(airport,$adameus.destinations(airport.code))\n end\n end",
"def build_post_activity\n Activity.new :channel => channel!,\n :relation_ids => Array(_relation_ids)\n end",
"def activities_setup\n @activities = Activity.all\n end",
"def map_entity_relations\n assignments = @db_base.query_assignments\n results = Hash.new()\n assignments.each { |result|\n results[result[\"P_Id\"]] = result[\"T_Id\"]\n }\n return results\n end",
"def graph\n @graph ||= Codependency::Graph.new\n end"
] |
[
"0.61826605",
"0.57532585",
"0.55151004",
"0.5497104",
"0.527428",
"0.527428",
"0.51466423",
"0.5059942",
"0.5015169",
"0.49789783",
"0.49622956",
"0.4945211",
"0.4930157",
"0.4930157",
"0.490244",
"0.48882315",
"0.48597562",
"0.48274285",
"0.4813186",
"0.4805733",
"0.48018613",
"0.47980163",
"0.47930497",
"0.47765526",
"0.47731325",
"0.4770534",
"0.47623253",
"0.4761653",
"0.4758615",
"0.47554177",
"0.47398445",
"0.47390065",
"0.47347638",
"0.4729507",
"0.4720403",
"0.47072765",
"0.46959454",
"0.46935606",
"0.468568",
"0.46853846",
"0.46720853",
"0.4668311",
"0.46660924",
"0.46660924",
"0.46660924",
"0.4658114",
"0.46541968",
"0.46540263",
"0.46463257",
"0.46448737",
"0.46403715",
"0.46396375",
"0.46163395",
"0.46124867",
"0.4608053",
"0.4602162",
"0.45988092",
"0.4585319",
"0.45715123",
"0.45702732",
"0.45575556",
"0.45562243",
"0.45562243",
"0.4552048",
"0.45460472",
"0.45460472",
"0.45458072",
"0.45443055",
"0.45117605",
"0.45098245",
"0.45076197",
"0.45065695",
"0.45013532",
"0.4499193",
"0.44981253",
"0.44975507",
"0.44910446",
"0.44880563",
"0.44848776",
"0.44831914",
"0.44800434",
"0.44796398",
"0.44783977",
"0.44675198",
"0.44626585",
"0.44579947",
"0.44573814",
"0.4454852",
"0.4454568",
"0.445428",
"0.44471973",
"0.44464383",
"0.44402742",
"0.4421735",
"0.44211623",
"0.44166908",
"0.44097477",
"0.44088838",
"0.4408214",
"0.44077668"
] |
0.44988528
|
74
|
Internal: Maps Fever types (:consumer, :storage, etc) to adapters.
|
def adapters_by_type
return @adapters if @adapters
@adapters =
Manager::TYPES.each_with_object({}) do |type, data|
data[type] =
Etsource::Fever.group(@name).keys(type).map do |node_key|
Adapter.adapter_for(
@context.graph.node(node_key), @context
)
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def adapters\n adapters_by_type.values.flatten\n end",
"def adapters\n @adapters ||= {}\n end",
"def adapters\n @adapters ||= {}\n end",
"def register_adapter(type, adapter); end",
"def adapters\n @adapters ||=\n @nodes.transform_values do |convs|\n convs.map { |conv| Adapter.adapter_for(conv, @context) }\n end\n end",
"def adapters\n @__adapters__ ||= {}\n end",
"def adapter(key)\n if (config = @context.graph.node(key).fever)\n adapters_by_type[config.type].find { |a| a.node.key == key }\n end\n end",
"def type_map\n @type_map ||= TypeMap.new(adapter.class.type_map)\n end",
"def type_map\n @type_map ||= TypeMap.new(adapter.class.type_map)\n end",
"def adaptors\n @adaptors ||= []\n end",
"def register_adapter name, klass\n (@@adapters ||= {})[name] = klass\n end",
"def adapters(interface)\n mod_hash = interfaces[name_to_key(interface)] || {}\n mod_hash[:adapters] ? mod_hash[:adapters].keys : []\n end",
"def register_adapter(key, klass)\n adapters[key] = klass\n end",
"def drivers\n send :adapters\n end",
"def register_adapter( a )\n aname = a.name.split('::').last.downcase\n @@adapters[aname] = a\n end",
"def init_adapter\n self.adapter = adapter_string.constantize.new\n end",
"def each_adapter\n return enum_for(:each_adapter) unless block_given?\n\n adapters.values.flatten.each { |adapter| yield(adapter) }\n end",
"def provider_map\n @provider_map ||= provider_list.inject({}) do |map, klass|\n map[klass.provider_id] = klass unless klass.nil?\n map\n end\n end",
"def typify(api_map); end",
"def each_adapter(options)\n Sms::Adapters::Factory.products(options).each do |klass|\n yield(klass.new)\n end\n end",
"def search_adaptors(type = 'all')\n @adaptors[type] ||= search_adaptor_files(type).collect do |file|\n file['adaptor_class_name'].constantize.new(file)\n end\n end",
"def adapter_class\n case Utilities.adapter\n when \"mysql2\"\n Adapters::Mysql2Adapter\n when \"postgresql\"\n Adapters::PostgreSQLAdapter\n when \"sqlite3\"\n Adapters::SQLite3Adapter\n when \"sqlserver\"\n Adapters::SQLServerAdapter\n end\n end",
"def adapter_class\n @@adapters[configuration[:adapter]]\n end",
"def load!\n adapter_registry.build(mapper)\n mapper.adapters = adapters\n mapper.load!\n end",
"def map_resource_type(resource_types, node)\n if resource_types.empty?\n if node.is_a?(IFile)\n return {\n 'string' => 'File',\n 'icon' => 'file'\n }\n else\n return {\n 'string' => 'Unknown',\n 'icon' => 'cog'\n }\n end\n end\n\n types = {\n '{http://calendarserver.org/ns/}calendar-proxy-write' => {\n 'string' => 'Proxy-Write',\n 'icon' => 'people'\n },\n '{http://calendarserver.org/ns/}calendar-proxy-read' => {\n 'string' => 'Proxy-Read',\n 'icon' => 'people'\n },\n '{urn:ietf:params:xml:ns:caldav}schedule-outbox' => {\n 'string' => 'Outbox',\n 'icon' => 'inbox'\n },\n '{urn:ietf:params:xml:ns:caldav}schedule-inbox' => {\n 'string' => 'Inbox',\n 'icon' => 'inbox'\n },\n '{urn:ietf:params:xml:ns:caldav}calendar' => {\n 'string' => 'Calendar',\n 'icon' => 'calendar'\n },\n '{http://calendarserver.org/ns/}shared-owner' => {\n 'string' => 'Shared',\n 'icon' => 'calendar'\n },\n '{http://calendarserver.org/ns/}subscribed' => {\n 'string' => 'Subscription',\n 'icon' => 'calendar'\n },\n '{urn:ietf:params:xml:ns:carddav}directory' => {\n 'string' => 'Directory',\n 'icon' => 'globe'\n },\n '{urn:ietf:params:xml:ns:carddav}addressbook' => {\n 'string' => 'Address book',\n 'icon' => 'book'\n },\n '{DAV:}principal' => {\n 'string' => 'Principal',\n 'icon' => 'person'\n },\n '{DAV:}collection' => {\n 'string' => 'Collection',\n 'icon' => 'folder'\n }\n }\n\n info = {\n 'string' => [],\n 'icon' => 'cog'\n }\n\n resource_types.each do |resource_type|\n if types.key?(resource_type)\n info['string'] << types[resource_type]['string']\n else\n info['string'] << resource_type\n end\n end\n\n types.each do |key, resource_info|\n if resource_types.include?(key)\n info['icon'] = resource_info['icon']\n break\n end\n end\n\n info['string'] = info['string'].join(', ')\n\n info\n end",
"def __adapter_for_klass(klass)\n Adapter.adapters.select { |name, checker| checker.call(klass) }.keys.first\n end",
"def adapters\n Ribbit::Adapters.adapters\n end",
"def register_mime_types(types)\n cr = Fl::Framework::Attachment::ClassRegistry.registry\n\n types.each do |tk, tv|\n av = (tv.is_a?(Array)) ? tv : [ tv ]\n av.each do |orm|\n cr.register(tk, self, orm)\n end\n end\n end",
"def adapter(name, type, uri = nil, default: false)\n adapter_registry.register(name, type, uri, default: default)\n end",
"def handlers\n {\n Api::Type::Boolean => ->(v) { v ? 'true' : 'false' },\n Api::Type::Constant => ->(v) { quote_string(v.upcase) },\n Api::Type::Double => ->(v) { v },\n Api::Type::Enum =>\n ->(v) { quote_string(v.is_a?(Symbol) ? v.id2name : v.to_s) },\n Api::Type::Integer => ->(v) { v },\n Api::Type::String => ->(v) { quote_string(v) },\n Api::Type::Time => ->(v) { quote_string(v.iso8601) },\n Api::Type::Array => ->(v) { format_values('[', v, ']') },\n Api::Type::NestedObject => ->(v) { format_values('{', v, '}') },\n Api::Type::NameValues => ->(v) { format_values('{', v, '}') },\n Api::Type::ResourceRef => ->(v) { quote_string(v) },\n Api::Type::Array::STRING_ARRAY_TYPE =>\n ->(v) { ['[', v.map { |e| quote_string(e) }.join(', '), ']'].join },\n Api::Type::Array::RREF_ARRAY_TYPE =>\n ->(v) { ['[', v.call(exported_values: false).join(', '), ']'].join }\n }.freeze\n end",
"def serverBehaviorMappings()\n {\n connections: ServerCallbacks::Connections::f,\n orders: ServerCallbacks::Orders::f,\n services: ServerCallbacks::Services::f\n # decision_engine: ServerCallbacks::DecisionEngine::f\n # rules_engine: ServerCallbacks::RulesEngine::f\n # advanced_strategies: ServerCallbacks::AdvancedStrategies::f\n }\nend",
"def registered_types\n end",
"def handlers\n {\n Api::Type::Boolean => ->(v) { v ? 'true' : 'false' },\n Api::Type::Constant => ->(v) { quote_string(v.upcase) },\n Api::Type::Double => ->(v) { v },\n Api::Type::Enum =>\n ->(v) { quote_string(v.is_a?(Symbol) ? v.id2name : v.to_s) },\n Api::Type::Integer => ->(v) { v },\n Api::Type::String => ->(v) { quote_string(v) },\n Api::Type::Time => ->(v) { quote_string(v.iso8601) },\n Api::Type::Array => ->(v) { format_values('[', v, ']') },\n Api::Type::NestedObject => ->(v) { format_values('{', v, '}') },\n Api::Type::ResourceRef => ->(v) { quote_string(v) },\n Api::Type::Array::STRING_ARRAY_TYPE =>\n ->(v) { ['[', v.map { |e| quote_string(e) }.join(', '), ']'].join },\n Api::Type::Array::RREF_ARRAY_TYPE =>\n ->(v) { ['[', v.call(exported_values: false).join(', '), ']'].join },\n Api::Type::NameValues => ->(v) { format_values('{', v, '}') }\n }.freeze\n end",
"def initialize\n provider_builders = read_provider_builders\n @providers = Hash[provider_builders.map do |name, package_hash|\n packages = Hash[package_hash.map do |size, price|\n [size, Package.new(size, price)]\n end]\n [name, Provider.new(name, packages)]\n end]\n end",
"def get_field_deserializers()\n return {\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"supportsDeviceLicensing\" => lambda {|n| @supports_device_licensing = n.get_boolean_value() },\n \"supportsUserLicensing\" => lambda {|n| @supports_user_licensing = n.get_boolean_value() },\n }\n end",
"def get_field_deserializers()\n return super.merge({\n \"capability\" => lambda {|n| @capability = n.get_string_value() },\n \"providerId\" => lambda {|n| @provider_id = n.get_string_value() },\n \"providerName\" => lambda {|n| @provider_name = n.get_string_value() },\n \"providerResourceId\" => lambda {|n| @provider_resource_id = n.get_string_value() },\n \"uri\" => lambda {|n| @uri = n.get_string_value() },\n })\n end",
"def register\n ModelAdapter.adapters ||= []\n ModelAdapter.adapters << Kernel.const_get(self.to_s)\n end",
"def item_type_mapping\n Rails.cache.fetch(['item_type_map', __method__], expires_in: 60.minutes) do\n client = SymphonyClient.new\n item_type_map = client.get_item_type_map.to_json\n JSON.parse(item_type_map)\n end\n end",
"def get_field_deserializers()\n return {\n \"configurationManagerDataConnectorConfigured\" => lambda {|n| @configuration_manager_data_connector_configured = n.get_boolean_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n }\n end",
"def boot_types\n @types = {}\n type_names.each do |name , ivars |\n @types[name] = type_for( name , ivars)\n end\n type_type = @types[:Type]\n @types.each do |name , type |\n type.set_type(type_type)\n end\n end",
"def ambition_adapter=(klass)\n @@ambition_adapter ||= {}\n # should this be doing the same check for respond_to?(:name) like above?\n @@ambition_adapter[name] = klass\n end",
"def polymorphic_mappings; end",
"def installed_adapters_of_type(type)\n (adapters[type] || []).select { |a| a.carrier_demand.positive? }\n end",
"def get_field_deserializers()\n return {\n \"ipAddressOrFQDN\" => lambda {|n| @ip_address_or_f_q_d_n = n.get_string_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"proxy\" => lambda {|n| @proxy = n.get_string_value() },\n }\n end",
"def init_adapters(adapter_manager)\n end",
"def register(mime, klass, orm = ORM_ACTIVERECORD)\n k = @map[mime]\n if k\n k[orm] = klass\n else\n @map[mime] = { orm => klass }\n end\n end",
"def type_name_resolver; end",
"def register converter, *backends\n backends.each {|backend| backend == '*' ? (registry.default = converter) : (registry[backend] = converter) }\n end",
"def add_type_converter(type, r2c, c2r)\n warn \"WAR\\NING: overridding #{type} on #{caller[0]}\" if @@type_map.has_key? type\n @@type_map[type] = [r2c, c2r]\n end",
"def map name, &block\n mapped_name, mapped_class = name.first\n mappings[mapped_name] =\n HotCocoa::Mappings::Mapper.map_instances_of mapped_class, mapped_name, &block\n end",
"def get_field_deserializers()\n return {\n \"detectionType\" => lambda {|n| @detection_type = n.get_string_value() },\n \"method\" => lambda {|n| @method = n.get_string_value() },\n \"name\" => lambda {|n| @name = n.get_string_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n }\n end",
"def _mapper(offer)\n mapped_keys = {\n 'link-id' => 'id', \n 'description' => 'description', \n 'link-name' => 'title', \n 'destination' => 'url', \n 'promotion-end-date'=> 'expires_at',\n 'advertiser-id' => 'merchant_id'\n }\n\n result = {}\n mapped_keys.each do |k,el|\n result[el] = offer[k]\n end\n result\nend",
"def adapter(name, options = {}, &block)\n use(Adapters.const_get(name), options, &block)\n end",
"def initialize_adapter\n case procedure.adapter_name.to_sym\n when :mongo then Backup::Adapters::MongoDB.new trigger, procedure\n when :mysql then Backup::Adapters::MySQL.new trigger, procedure\n when :sqlite then Backup::Adapters::SQLite.new trigger, procedure\n when :postgresql then Backup::Adapters::PostgreSQL.new trigger, procedure\n when :archive then Backup::Adapters::Archive.new trigger, procedure\n when :custom then Backup::Adapters::Custom.new trigger, procedure\n else\n puts \"Unknown Adapter: \\\"#{procedure.adapter_name}\\\".\"\n exit\n end\n end",
"def map_config_extensions\n @extensions = Hash.new\n @config[\"types\"].each do |k,v|\n puts \"#{k} => #{v}\"\n v.each do |ext|\n @extensions[ext] = k\n end\n end\n return @extensions\n end",
"def __auto_detect_adapter\n case\n when defined?(::Patron)\n :patron\n when defined?(::Typhoeus)\n :typhoeus\n when defined?(::HTTPClient)\n :httpclient\n when defined?(::Net::HTTP::Persistent)\n :net_http_persistent\n else\n ::Faraday.default_adapter\n end\n end",
"def get_field_deserializers()\n return {\n \"appConfigKey\" => lambda {|n| @app_config_key = n.get_string_value() },\n \"appConfigKeyType\" => lambda {|n| @app_config_key_type = n.get_enum_value(MicrosoftGraph::Models::MdmAppConfigKeyType) },\n \"appConfigKeyValue\" => lambda {|n| @app_config_key_value = n.get_string_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n }\n end",
"def initialize_adapters\n adapters\n nil\n end",
"def get_field_deserializers()\n return {\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"resourceId\" => lambda {|n| @resource_id = n.get_string_value() },\n \"uri\" => lambda {|n| @uri = n.get_string_value() },\n }\n end",
"def network_adapter(slot, type, *args)\n @network_adapters[slot] = [type, args]\n end",
"def get_field_deserializers()\n return {\n \"deviceCount\" => lambda {|n| @device_count = n.get_number_value() },\n \"lastUpdateDateTime\" => lambda {|n| @last_update_date_time = n.get_date_time_value() },\n \"malwareIdentifier\" => lambda {|n| @malware_identifier = n.get_string_value() },\n \"name\" => lambda {|n| @name = n.get_string_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n }\n end",
"def set_adapter_scheme(scheme)\n @scheme = scheme\n @@adapters[scheme.to_sym] = self\n end",
"def device_typemap # :nodoc:\n @device_typemap ||= DEVICE_TYPEMAP.dup\n end",
"def get_field_deserializers()\n return {\n \"connectingIP\" => lambda {|n| @connecting_i_p = n.get_string_value() },\n \"deliveryAction\" => lambda {|n| @delivery_action = n.get_string_value() },\n \"deliveryLocation\" => lambda {|n| @delivery_location = n.get_string_value() },\n \"directionality\" => lambda {|n| @directionality = n.get_string_value() },\n \"internetMessageId\" => lambda {|n| @internet_message_id = n.get_string_value() },\n \"messageFingerprint\" => lambda {|n| @message_fingerprint = n.get_string_value() },\n \"messageReceivedDateTime\" => lambda {|n| @message_received_date_time = n.get_date_time_value() },\n \"messageSubject\" => lambda {|n| @message_subject = n.get_string_value() },\n \"networkMessageId\" => lambda {|n| @network_message_id = n.get_string_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n }\n end",
"def cast_types; end",
"def connector_types\n [connector_type_1, connector_type_2]\n end",
"def unsupported_adapters\n []\n end",
"def initialize_exchange_rate_adapters\n @exchange_rate_adapters ||= []\n if self.exchange_rate_adapter_names.kind_of?(Array) && self.exchange_rate_adapter_names\n self.exchange_rate_adapter_names.each do |adapter|\n begin\n @exchange_rate_adapters << Straight::ExchangeRate.const_get(\"#{adapter}Adapter\").instance\n rescue NameError\n StraightServer.logger.warn \"No exchange rate adapter with the name #{adapter} was found!\"\n end\n end\n end\n end",
"def configured_adapters\n # Get our adapters as above.\n adapters = ADAPTERS.dup\n\n # Get all configured custom adapters and iterate over them.\n QuirkyApi.adapters.all.each do |configured_adapter|\n # Get the index of the adapter that will be used to determine\n # placement on the custom adapter.\n index = adapters.index(configured_adapter[:adapter])\n\n # Get the pre-existing adapter at that index.\n old_adapter = adapters[index]\n\n # Determine the placement of the new adapter by the 'placement'\n # specified when you configured it (based upon insert_before/after).\n # '+1' here means the new adapter should go after the old one, '-1'\n # means it should go before the old one.\n case configured_adapter[:placement]\n # Append\n when '+1'\n # Put the new adapter immediately after the old adapter.\n adapters[index, 1] = [old_adapter, configured_adapter[:new_adapter]]\n # Prepend\n when '-1'\n # Put the ne wadapter immediately before the old adapter.\n adapters[index, 1] = [configured_adapter[:new_adapter], old_adapter]\n end\n end\n\n # Return all adapters such as they are.\n adapters\n end",
"def types\n @callers.keys\n end",
"def adapter_class\n ADAPTERS[Utilities.adapter]\n end",
"def find_adapters_from_path\n @@supported_files.each do |file|\n path = File.expand_path(\"#{self.path}/#{file}\")\n if File.exists?(path)\n adapter = Adapter.new(path, self)\n self.adapters << adapter if adapter.valid?\n end\n end\n \n self.adapters\n end",
"def add_pg_decoders\n if @config[:use_follower_reads_for_type_introspection]\n @default_timezone = nil\n @timestamp_decoder = nil\n\n coders_by_name = {\n \"int2\" => PG::TextDecoder::Integer,\n \"int4\" => PG::TextDecoder::Integer,\n \"int8\" => PG::TextDecoder::Integer,\n \"oid\" => PG::TextDecoder::Integer,\n \"float4\" => PG::TextDecoder::Float,\n \"float8\" => PG::TextDecoder::Float,\n \"numeric\" => PG::TextDecoder::Numeric,\n \"bool\" => PG::TextDecoder::Boolean,\n \"timestamp\" => PG::TextDecoder::TimestampUtc,\n \"timestamptz\" => PG::TextDecoder::TimestampWithTimeZone,\n }\n\n known_coder_types = coders_by_name.keys.map { |n| quote(n) }\n query = <<~SQL % known_coder_types.join(\", \")\n SELECT t.oid, t.typname\n FROM pg_type as t AS OF SYSTEM TIME '-10s'\n WHERE t.typname IN (%s)\n SQL\n\n coders = execute_and_clear(query, \"SCHEMA\", []) do |result|\n result\n .map { |row| construct_coder(row, coders_by_name[row[\"typname\"]]) }\n .compact\n end\n\n map = PG::TypeMapByOid.new\n coders.each { |coder| map.add_coder(coder) }\n @connection.type_map_for_results = map\n\n @type_map_for_results = PG::TypeMapByOid.new\n @type_map_for_results.default_type_map = map\n @type_map_for_results.add_coder(PG::TextDecoder::Bytea.new(oid: 17, name: \"bytea\"))\n @type_map_for_results.add_coder(MoneyDecoder.new(oid: 790, name: \"money\"))\n\n # extract timestamp decoder for use in update_typemap_for_default_timezone\n @timestamp_decoder = coders.find { |coder| coder.name == \"timestamp\" }\n update_typemap_for_default_timezone\n else\n super\n end\n rescue ActiveRecord::StatementInvalid => e\n raise e unless e.cause.is_a? PG::InvalidCatalogName\n # use original if database is younger than 10s\n super\n end",
"def types(types); end",
"def get_field_deserializers()\n return {\n \"allowedDeviceCount\" => lambda {|n| @allowed_device_count = n.get_number_value() },\n \"blockedDeviceCount\" => lambda {|n| @blocked_device_count = n.get_number_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"quarantinedDeviceCount\" => lambda {|n| @quarantined_device_count = n.get_number_value() },\n \"unavailableDeviceCount\" => lambda {|n| @unavailable_device_count = n.get_number_value() },\n \"unknownDeviceCount\" => lambda {|n| @unknown_device_count = n.get_number_value() },\n }\n end",
"def converters\n registry.merge\n end",
"def initialize_type_map(m = type_map)\n super\n m.register_type 'box', OID::Box.new\n m.register_type 'circle', OID::Circle.new\n m.register_type 'interval', OID::Interval.new\n m.register_type 'line', OID::Line.new\n m.register_type 'segment', OID::Segment.new\n end",
"def get_field_deserializers()\n return {\n \"hashes\" => lambda {|n| @hashes = n.get_object_value(lambda {|pn| MicrosoftGraph::Models::Hashes.create_from_discriminator_value(pn) }) },\n \"mimeType\" => lambda {|n| @mime_type = n.get_string_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"processingMetadata\" => lambda {|n| @processing_metadata = n.get_boolean_value() },\n }\n end",
"def get_field_deserializers()\n return {\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"resourceAccess\" => lambda {|n| @resource_access = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::ResourceAccess.create_from_discriminator_value(pn) }) },\n \"resourceAppId\" => lambda {|n| @resource_app_id = n.get_string_value() },\n }\n end",
"def get_field_deserializers()\n return {\n \"denied\" => lambda {|n| @denied = n.get_boolean_value() },\n \"description\" => lambda {|n| @description = n.get_string_value() },\n \"displayName\" => lambda {|n| @display_name = n.get_string_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"productName\" => lambda {|n| @product_name = n.get_string_value() },\n \"publisherName\" => lambda {|n| @publisher_name = n.get_string_value() },\n }\n end",
"def get_field_deserializers()\n return {\n \"accessContainerId\" => lambda {|n| @access_container_id = n.get_string_value() },\n \"accessContainerType\" => lambda {|n| @access_container_type = n.get_enum_value(MicrosoftGraph::Models::DelegatedAdminAccessContainerType) },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n }\n end",
"def get_field_deserializers()\n return {\n \"displayName\" => lambda {|n| @display_name = n.get_string_value() },\n \"locale\" => lambda {|n| @locale = n.get_string_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n }\n end",
"def get_field_deserializers()\n return {\n \"compliancePolicy\" => lambda {|n| @compliance_policy = n.get_boolean_value() },\n \"deviceConfiguration\" => lambda {|n| @device_configuration = n.get_boolean_value() },\n \"inventory\" => lambda {|n| @inventory = n.get_boolean_value() },\n \"modernApps\" => lambda {|n| @modern_apps = n.get_boolean_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"resourceAccess\" => lambda {|n| @resource_access = n.get_boolean_value() },\n \"windowsUpdateForBusiness\" => lambda {|n| @windows_update_for_business = n.get_boolean_value() },\n }\n end",
"def handle(*types); end",
"def get_field_deserializers()\n return {\n \"description\" => lambda {|n| @description = n.get_string_value() },\n \"displayName\" => lambda {|n| @display_name = n.get_string_value() },\n \"id\" => lambda {|n| @id = n.get_guid_value() },\n \"isEnabled\" => lambda {|n| @is_enabled = n.get_boolean_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"value\" => lambda {|n| @value = n.get_string_value() },\n }\n end",
"def get_field_deserializers()\n return {\n \"deviceComplianceCheckinThresholdDays\" => lambda {|n| @device_compliance_checkin_threshold_days = n.get_number_value() },\n \"isScheduledActionEnabled\" => lambda {|n| @is_scheduled_action_enabled = n.get_boolean_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"secureByDefault\" => lambda {|n| @secure_by_default = n.get_boolean_value() },\n }\n end",
"def get_field_deserializers()\n return {\n \"cellularDataBlockWhenRoaming\" => lambda {|n| @cellular_data_block_when_roaming = n.get_boolean_value() },\n \"cellularDataBlocked\" => lambda {|n| @cellular_data_blocked = n.get_boolean_value() },\n \"managedApps\" => lambda {|n| @managed_apps = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::AppListItem.create_from_discriminator_value(pn) }) },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n }\n end",
"def get_field_deserializers()\n return {\n \"address\" => lambda {|n| @address = n.get_string_value() },\n \"itemId\" => lambda {|n| @item_id = n.get_string_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"relevanceScore\" => lambda {|n| @relevance_score = n.get_object_value(lambda {|pn| Double.create_from_discriminator_value(pn) }) },\n \"selectionLikelihood\" => lambda {|n| @selection_likelihood = n.get_enum_value(MicrosoftGraph::Models::SelectionLikelihoodInfo) },\n }\n end",
"def get_field_deserializers()\n return {\n \"appliesTo\" => lambda {|n| @applies_to = n.get_string_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"provisioningStatus\" => lambda {|n| @provisioning_status = n.get_string_value() },\n \"servicePlanId\" => lambda {|n| @service_plan_id = n.get_guid_value() },\n \"servicePlanName\" => lambda {|n| @service_plan_name = n.get_string_value() },\n }\n end",
"def aliases(media_type)\n registered_aliases.map { |a| media_type.type(a).to_s }\n end",
"def get_field_deserializers()\n return {\n \"address\" => lambda {|n| @address = n.get_string_value() },\n \"exceptions\" => lambda {|n| @exceptions = n.get_collection_of_primitive_values(String) },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"useForLocalAddresses\" => lambda {|n| @use_for_local_addresses = n.get_boolean_value() },\n }\n end",
"def initialize(**options)\n @type = options[:type]\n @uri = options[:uri]\n @class_name ||= Lotus::Utils::String.new(\"#{@type}_adapter\").classify\n end",
"def get_field_deserializers()\n return {\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n \"query\" => lambda {|n| @query = n.get_string_value() },\n \"queryRoot\" => lambda {|n| @query_root = n.get_string_value() },\n \"queryType\" => lambda {|n| @query_type = n.get_string_value() },\n }\n end",
"def get_adapter_class(name)\n begin\n \"#{name.to_s.camelize}Adapter\".constantize\n rescue NameError => e\n nil\n end\n end",
"def interfaces(direction, collections)\n mode = case direction\n when :input then true\n when :output then false\n else\n raise Bud::CompileError, \"unrecognized interface type #{direction}\"\n end\n collections.each do |tab|\n t_provides << [tab.to_s, mode]\n end \n end",
"def get_field_deserializers()\n return {\n \"activities\" => lambda {|n| @activities = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::ExternalConnectorsExternalActivity.create_from_discriminator_value(pn) }) },\n }\n end",
"def load_adaptors(*args)\n adaptors.map do |adaptor_klass|\n next unless adaptor_supports?(adaptor_klass, args)\n instantiate_adaptor(adaptor_klass, args)\n end.compact\n end",
"def adapter\n unless @_adapter && @_adapter.valid?\n @_adapter = Cachetastic::Adapters.build(cache_klass)\n end\n @_adapter\n end",
"def init_adapter_from(context)\n self.adapter = adapter_class.new(context)\n end",
"def get_field_deserializers()\n return {\n \"extensionAttribute1\" => lambda {|n| @extension_attribute1 = n.get_string_value() },\n \"extensionAttribute10\" => lambda {|n| @extension_attribute10 = n.get_string_value() },\n \"extensionAttribute11\" => lambda {|n| @extension_attribute11 = n.get_string_value() },\n \"extensionAttribute12\" => lambda {|n| @extension_attribute12 = n.get_string_value() },\n \"extensionAttribute13\" => lambda {|n| @extension_attribute13 = n.get_string_value() },\n \"extensionAttribute14\" => lambda {|n| @extension_attribute14 = n.get_string_value() },\n \"extensionAttribute15\" => lambda {|n| @extension_attribute15 = n.get_string_value() },\n \"extensionAttribute2\" => lambda {|n| @extension_attribute2 = n.get_string_value() },\n \"extensionAttribute3\" => lambda {|n| @extension_attribute3 = n.get_string_value() },\n \"extensionAttribute4\" => lambda {|n| @extension_attribute4 = n.get_string_value() },\n \"extensionAttribute5\" => lambda {|n| @extension_attribute5 = n.get_string_value() },\n \"extensionAttribute6\" => lambda {|n| @extension_attribute6 = n.get_string_value() },\n \"extensionAttribute7\" => lambda {|n| @extension_attribute7 = n.get_string_value() },\n \"extensionAttribute8\" => lambda {|n| @extension_attribute8 = n.get_string_value() },\n \"extensionAttribute9\" => lambda {|n| @extension_attribute9 = n.get_string_value() },\n \"@odata.type\" => lambda {|n| @odata_type = n.get_string_value() },\n }\n end"
] |
[
"0.6957223",
"0.64922756",
"0.6475926",
"0.615097",
"0.6124453",
"0.60587054",
"0.590596",
"0.5777547",
"0.5777547",
"0.56655526",
"0.55141914",
"0.54472643",
"0.54305834",
"0.53451043",
"0.53404623",
"0.53288406",
"0.52990973",
"0.5272447",
"0.5253847",
"0.5224774",
"0.5213625",
"0.51540047",
"0.5140517",
"0.5131286",
"0.51281583",
"0.5098901",
"0.50820196",
"0.5058785",
"0.5056611",
"0.5050342",
"0.50501716",
"0.5013603",
"0.5004285",
"0.499935",
"0.4994481",
"0.4975042",
"0.4967697",
"0.4955446",
"0.49503",
"0.49499235",
"0.49461812",
"0.49371085",
"0.49334577",
"0.49323308",
"0.49187222",
"0.49053016",
"0.49023673",
"0.4898259",
"0.48967743",
"0.48896533",
"0.48890147",
"0.48887485",
"0.4879418",
"0.48719198",
"0.48714915",
"0.48687765",
"0.48678163",
"0.4864019",
"0.48509613",
"0.48438525",
"0.4832894",
"0.48320222",
"0.48316497",
"0.4828641",
"0.48213735",
"0.48197004",
"0.47998652",
"0.47969663",
"0.4776707",
"0.47613674",
"0.47585955",
"0.47388718",
"0.47368383",
"0.47334808",
"0.47225288",
"0.47214565",
"0.4718224",
"0.47114053",
"0.47080004",
"0.47072452",
"0.47033274",
"0.4698069",
"0.46971792",
"0.46962062",
"0.46957266",
"0.4695352",
"0.46930546",
"0.46920216",
"0.46888894",
"0.4688178",
"0.4683783",
"0.46836278",
"0.468127",
"0.468063",
"0.4678171",
"0.4674409",
"0.4672746",
"0.46716458",
"0.46712112",
"0.46670213"
] |
0.72373736
|
0
|
The resource method returns the instance of a resource based upon the route path. For example, the route /learning_paths/:learning_path_id/custom_content would return the LearningPath instance with an id of :learning_path_id
|
def resource
klass, param = resource_class
klass&.find(params[param.to_sym])
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def resource(path)\n Resource.new(self, path)\n end",
"def resource(path, params={})\n r = Resource.process_detailed(self, *do_get(path, params))\n\n # note that process_detailed will make a best-effort to return an already\n # detailed resource or array of detailed resources but there may still be\n # legacy cases where #show is still needed. calling #show on an already\n # detailed resource is a no-op.\n r.respond_to?(:show) ? r.show : r\n end",
"def find_resource\n get params[:resource_path]\n end",
"def resource(name, path, *args, &block)\n controller name, path, *args do\n expand_within(:resource, &block)\n end\n end",
"def resource(*args)\n defaults = args.pop\n options = extract_options_from_args!(args) || {}\n key = []\n params = []\n \n args.each do |arg|\n if arg.is_a?(Symbol) || arg.is_a?(String)\n key << arg.to_s\n else\n key << arg.class.to_s\n params << arg\n end\n end\n \n unless route = Merb::Router.resource_routes[key]\n raise Merb::Router::GenerationError, \"Resource route not found: #{args.inspect}\"\n end\n\n params << options\n \n route.generate(params, defaults, true)\n end",
"def resource\n resource_model.find(params[:id])\n end",
"def get_resource\n execute(resource_path, method: :get)\n end",
"def resource(*args)\n args << @request_params || {}\n Merb::Router.resource(*args)\n end",
"def resource(path, &block)\n raise \"Resource path cannot be nil\" if path.nil?\n (@path_parts ||= []) << path\n block.call\n @path_parts.pop\n end",
"def resource\n\n end",
"def resource(options = {})\n options = { :path => options } if options.is_a? String\n raise ArgumentError unless options[:path]\n options = { :client => self }.merge(options)\n query_string = Resource.query_string(options[:filter] || {})\n (@resources ||= {})[options[:path] + query_string] ||= Resource.new(options)\n end",
"def resources(type, path)\n Resources.new(self, path, type)\n end",
"def resource\n @resource\n end",
"def resource\n @resource\n end",
"def resource_path(*args)\n resource.path(*args)\n end",
"def resource\n self.class.resource\n end",
"def requested_resource(request_path)\n parts = request_path.split('/')\n raw_resource(parts)\n end",
"def get(path)\n self.class.get(path)\n end",
"def path\n name = @resource.value(:name)\n if (attrs = self.class.all[name])\n attrs[:path]\n end\n end",
"def resource_path(resource = self.resource, **options)\n controller_path(action: :show, id: resource, **options)\n end",
"def resource\n @resource\n end",
"def get_resource(resource_path)\n \n return self if path == resource_path\n\n @children.each do |c|\n resource = c.get_resource(resource_path)\n return resource if resource\n end if @children\n\n return nil\n end",
"def resource path\n File.expand_path \"resources/#{path}\", __dir__\n end",
"def resource\n @resource ||= Resource.new(uri, graph: graph)\n end",
"def path\n name = @resource.value(:name)\n # rubocop:disable Style/GuardClause\n if (attrs = self.class.all[name])\n # rubocop:enable Style/GuardClause\n attrs[:path]\n end\n end",
"def resource\n @resource ||= begin\n resource_constant.new(attributes)\n end\n end",
"def resource\n instance_variable_get(resource_name) || params[:id] && set_resource(controller_model.find(params[:id]))\n end",
"def resource\n @resource ||= Resource.new(self)\n end",
"def routes\n Resources::Routes.new(self)\n end",
"def path\n @path ||= polymorphic_path @resources\n end",
"def path(path = nil)\n if resource\n resource.path = path if path\n resource.path\n else\n @path = path if path\n @path || resource_name\n end\n end",
"def resource\n @resource ||= resource_set.createResource(uri)\n end",
"def resource_for_path(path, options = {}, debug = true)\n RestClient.log = Logger.new(STDOUT) if debug\n RestClient.proxy = credentials[:proxy] if credentials[:proxy]\n url = ['https://', credentials[:domain], path].join\n RestClient::Resource.new url, options.merge(default_options)\n end",
"def resource\n return @resource\n end",
"def resource\n return @resource\n end",
"def resource\n return @resource\n end",
"def resource\n return @resource\n end",
"def resource\n return @resource\n end",
"def resource\n return @resource\n end",
"def route\n @route ||= Role.available_routes.find {|r| r.conditions[:path_info].to_s == path_info && r.conditions[:request_method].to_s == request_method}\n end",
"def show\n @resource = Resource.find(params[:id])\n end",
"def resource\n instance_variable_get(\"@#{resource_name}\")\n end",
"def new_resource_path\n send route_prefix_to_method_name(\"new_#{class_name.model_name.singular_route_key}_path\")\n end",
"def show\n @resource = @lode.resource\n end",
"def resource(set_name, path, &block)\n self.class.resource(set_name, path, &block)\n end",
"def resource\n @resource ||= resource_klass.new object\n end",
"def show\n @resource = find_resource\n end",
"def resource\n self\n end",
"def resource(path)\n argtype(:path) { Pathname }\n Java::gv.codegen.Codegen.resource(path.to_s)\n &.to_io\n end",
"def path(resource, &block)\n if block\n path_object = Skeleton::Path.new\n yield(path_object)\n paths[resource] = path_object\n else\n paths[resource]\n end\n end",
"def resource_path(*args)\n options = args.extract_options!\n super_path(with_chain(args.first || resource), options)\n end",
"def resource\n get_resource_ivar || set_resource_ivar(end_of_association_chain.send(method_for_find, params[:id]))\n end",
"def load_resource\n query = eager_load(resource_class)\n if resource_class.respond_to? :friendly_id\n query.friendly.find params[:id]\n else\n query.find params[:id]\n end\n end",
"def path(name, data = nil)\n RouteLookup.new.path(name, data)\n end",
"def find_by_path(resource_path)\n idents = resource_path.split(/#/).delete_if {|x| x.blank? }\n return unless ident.eql?(idents.shift)\n return self if idents.empty?\n child = children.select{|r| r.ident == idents.first}.first\n child and child.find_by_path(idents * '#')\n end",
"def find_resource\n @resource = resource_class.find(params[:id])\n end",
"def resource_api_path(path=nil)\n @resource_api_path = path if path\n @resource_api_path || \"1.0/#{self.path}\"\n end",
"def resource_for(*paths)\n @authz_client.resource(*paths)\n end",
"def get_route(path, options = nil)\n conditions = options && options.delete(:conditions) || nil\n requirements = options && options.delete(:requirements) || nil\n default_values = options && options.delete(:default_values) || nil\n generate_with = options && options.delete(:generate_with) || nil\n priority = options && options.delete(:priority) || nil\n if options\n options.delete_if do |k, v|\n if v.is_a?(Regexp) || v.is_a?(Proc)\n (requirements ||= {})[k] = v\n true\n end\n end\n end\n\n if conditions && !conditions.empty?\n conditions.keys.all?{|k| request_methods.include?(k)} or raise(\"You are trying to use request methods that don't exist in the request_methods supplied #{conditions.keys.join(', ')} -> #{(conditions.keys - request_methods).join(\", \")}\")\n end\n\n if priority\n enable_priority_lookups!\n end\n\n route = parser.generate_route(path, conditions, requirements, default_values, generate_with, priority)\n raise(MultipleParameterException.new) if !allow_identical_variable_names? and route.paths.first.dynamic? and route.paths.first.dynamic_keys.uniq.size != route.paths.first.dynamic_keys.size\n route.to(options) if options && !options.empty?\n route\n end",
"def resource\n @project ||= Project.find_by_slug!(params[:id])\n end",
"def resource\n @resource ||= begin\n resource_query\n .new(relation: resource_scope)\n .find_for_show(find_by_conditions: find_by_conditions)\n end\n end",
"def route_path(path)\n AutoRouter::Router.map_controller(self, path: path)\n end",
"def get_resource(id)\n raise 'To be implemented in child classes'\n end",
"def get_resource\n instance_variable_get(\"@#{resource_name}\")\n end",
"def get_resource\n instance_variable_get(\"@#{resource_name}\")\n end",
"def get_resource\n instance_variable_get(\"@#{resource_name}\")\n end",
"def load_resource(path, args=nil)\n service.get(path, args)\n end",
"def get_resource\n instance_variable_get(\"@#{resource_name}\")\n end",
"def get_resource\n instance_variable_get(\"@#{resource_name}\")\n end",
"def path\n Rails.application.routes.url_helpers.send(self.class.to_s.underscore.concat('_path'), id)\n end",
"def path\n ensure_valid\n @path\n end",
"def route\n @route\n end",
"def current_resource\n return nil unless current_path\n sitemap.find_resource_by_destination_path(current_path)\n end",
"def resource_model\n resource = \"#{resource_param}\".constantize\n end",
"def get_resource_to_use\n return @resources.first\n end",
"def path\n return get_path self\n end",
"def resource\n @halibut\n end",
"def resource\n instance_variable_get(:\"@#{resource_name}\")\n end",
"def resource\n instance_variable_get(:\"@#{resource_name}\")\n end",
"def current_hammock_resource\n nesting_resources = params.keys.select {|k| /_id$/ =~ k }.map {|k| k.gsub(/_id$/, '').pluralize }\n ActionController::Routing::Routes.route_map.base_for nesting_resources.push(mdl.resource_name).map(&:to_sym)\n end",
"def get(path, id)\n path = \"#{API_PATH}#{path}\"\n return super(path, id, headers: admin_headers(path, '', 'GET', resource_id: id))\n end",
"def get_resource\n instance_variable_get(\"@#{resource_name}\")\n end",
"def load_ratable\n\t\tresource, id = request.path.split('/')[1, 2]\n\t\t@ratable = resource.singularize.classify.constantize.find(id)\n\tend",
"def method_missing(id, *args, &block)\n # Figure out what kind of resource we're trying to get.\n klass = Scrumy::Models.const_get(id.to_s.capitalize.singularize)\n # Special case for handling id=:current - this really only applies to Sprint resources\n # but if other resources specified the `current` sub-resources then it should still work.\n if klass.current_url and args.first==:current\n @url = format(klass.current_url, :current)\n else\n # TODO\n # Figure out a better way of determining if the resource is singular or plural\n \n # The only argument that resources ever take is an ID, so pass the first arg as the ID.\n @url = format((id.to_s =~ /s$/ ? klass.list_url : klass.show_url), args.first)\n end\n\n # Here we request the resource using the singular of the resource name as the root\n # to extract from the returned JSON hash.\n response = get(@url, id.to_s.singularize)\n \n # Responses are of two types, either arrays of hashes or a single hash\n if response.kind_of? Array\n # If it's array collect a new array by constructing objects based on the resource\n # name capitalized and singularized.\n response.collect do |obj| \n klass.new(obj, self)\n end\n else\n # Otherwise create a single new object of the correct type.\n klass.new(response, self)\n end\n end",
"def show\n respond_with resource\n end",
"def resource\n (@nested_resource || @root_resource)\n end",
"def read_resource(resource)\n resource\n end",
"def read_resource(resource)\n resource\n end",
"def resource\n resource_klass.new(attributes.symbolize_keys.merge(new_record: false))\n end",
"def resource(object, options = {})\n respond_with_object_and_type object, options, :resource, true\n end",
"def resource\n @index.project.resource( @id )\n end",
"def resource\n return Object unless resource_type\n return resource_type.constantize unless resource_id\n return _resource\n end",
"def resource_path\n return super unless resource.is_a?(Decidim::Component)\n\n @resource_path ||= main_component_path(resource)\n end",
"def path\n CGI::unescape @resource\n end",
"def resource; end",
"def routes\r\n RoutesController.instance\r\n end",
"def get(path_or_id, *args)\n if path_or_id.is_a?(String)\n get_by_path(path_or_id)\n else\n super\n end\n end",
"def path\n return @path unless @path.nil?\n\n substitute_keys_with(@route_params)\n substitute_keys_with(known_params)\n @path = @route\n end",
"def load_resource\n if action_name.in? %w(edit update destroy)\n resource_name = controller_name.singularize\n model_class = resource_name.capitalize.constantize\n resource = model_class.find(params[:id])\n instance_variable_set \"@#{resource_name}\", resource\n end\n end",
"def rest_resource(path, options={}, &blk)\n rest_get path, options, &blk\n rest_edit path, options, &blk\n rest_delete path, options, &blk\n end"
] |
[
"0.72713137",
"0.69367135",
"0.6685142",
"0.6670331",
"0.6457288",
"0.64116126",
"0.635408",
"0.6289022",
"0.62704146",
"0.6264048",
"0.6199893",
"0.6184447",
"0.6167844",
"0.6167844",
"0.6159838",
"0.6128533",
"0.60493964",
"0.6038231",
"0.60155505",
"0.6000513",
"0.59613323",
"0.5941334",
"0.59351027",
"0.59313136",
"0.5889557",
"0.58802396",
"0.5870686",
"0.5802188",
"0.5786825",
"0.57830936",
"0.57500297",
"0.5746311",
"0.5733522",
"0.57320064",
"0.57320064",
"0.57320064",
"0.57320064",
"0.57320064",
"0.57320064",
"0.5724652",
"0.57175577",
"0.57075334",
"0.5700638",
"0.5666884",
"0.56625074",
"0.56508636",
"0.5646039",
"0.5645492",
"0.5645109",
"0.5632077",
"0.5621",
"0.561836",
"0.5578545",
"0.55782443",
"0.5576785",
"0.55761886",
"0.5552462",
"0.55519587",
"0.5527681",
"0.55257285",
"0.55135447",
"0.5504569",
"0.54971683",
"0.54943454",
"0.54943454",
"0.54943454",
"0.5491801",
"0.54666144",
"0.54666144",
"0.5460043",
"0.54523647",
"0.5451593",
"0.54464346",
"0.5440379",
"0.5436601",
"0.5435689",
"0.5429984",
"0.54257864",
"0.54257864",
"0.54230416",
"0.542083",
"0.54138684",
"0.5402257",
"0.5401756",
"0.5394997",
"0.53791714",
"0.53671974",
"0.53671974",
"0.5365273",
"0.536153",
"0.5351492",
"0.5341648",
"0.5341176",
"0.533949",
"0.5336238",
"0.53316057",
"0.532899",
"0.53216267",
"0.53098625",
"0.53091943"
] |
0.6229239
|
10
|
This method looks at the params hash. Its looking for a param that ends in '_id'. Once found it removes the id and then returns the class and the id to look up. For example in the route /learning_paths/:learning_path_id/custom_content the method would find `learning_path_id` and then return the class LearningPath and learning_path_id
|
def resource_class
params.each do |name, _value|
if /(.+)_id$/.match?(name)
model = name.match(%r{([^\/.]*)_id$})
return model[1].classify.constantize, name
end
end
nil
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def parse_klass_and_id\n klass = params[:commentable].constantize\n commentable_id = \"#{klass}_id\".downcase.to_sym\n return klass, commentable_id\n end",
"def get_id(path, user, classname)\n begin \n if classname == \"person\"\n return People.all.first.to_param\n end\n \n object = case classname\n when \"user\"\n user || User.first\n when \"pseud\"\n user.try(:default_pseud) || Pseud.first\n when \"medium\"\n Media.first\n when \"collection\"\n user.owned_collections.first\n when \"restricted_work\"\n Work.where(:restricted => true).in_collection(Collection.find(@last_id)).first\n when \"tag_wrangler\"\n if permit?(\"tag_wrangler\")\n user\n else\n Role.find_by_name(\"tag_wrangler\").users.first\n end\n when \"nomination\"\n TagSetNomination.for_tag_set(OwnedTagSet.find(@last_id)).owned_by(user).first\n when \"setting\"\n AdminSetting.first\n when \"assignment\", \"claim\", \"signup\"\n klass = \"challenge_#{classname}\".classify.constantize\n query = classname == \"assignment\" ? klass.by_offering_user(user) :\n (classname == \"signup\" ? klass.by_user(user) : \n (classname == \"claim\" ? klass.by_claiming_user(user) : nil))\n if path.match('collection')\n query = query.in_collection(Collection.find(@last_id))\n end\n query.first\n when \"item\", \"participant\"\n \"collection_#{classname}\".classify.constantize.where(:collection_id => @last_id).first\n when \"tag_wrangling\", \"user_creation\", \"translator\", \"translation\"\n # not real objects\n nil\n else\n klass = classname.classify.constantize\n if klass.column_names.include?(\"user_id\")\n klass.where(:user_id => user.id).first\n elsif klass.column_names.include?(\"pseud_id\")\n klass.where(:pseud_id => user.default_pseud.id).first\n else\n classname.classify.constantize.first\n end\n end\n\n # return the id\n object.try(:id)\n rescue\n @errors << \"NOT SURE HOW TO FIND #{classname}\"\n nil\n end \n end",
"def find_by_id(class_name)\n class_name.find_by(id: params[:id])\n end",
"def id\n \n id = path_info.split(\"/\")[1]\n\n # Fix for /path/id.with.dot like /person/full.name - where format is \"json\" (derived from either Accept or Content-Type)\n if [\"html\", \"json\", \"xml\"].include? format\n if not id.nil? # for POST id is null\n id = id.gsub(/\\.(html|json|xml)$/, \"\")\n end\n \n else\n \n # Otherwise, remove trailing .json or .xml\n if id =~ /[.]/\n id = id.split(\".\")\n id.pop\n id = id.join(\".\")\n end\n \n end\n \n if id == [] or id.nil?\n id == \"\"\n end\n \n id\n \n end",
"def children_params\n klass_id = self.class.name.split('::').last.downcase + '_id'\n route_params.merge(klass_id.to_sym => id).reject { |k, v| k == :id }\n end",
"def find_likable\n params.each do |name, value|\n if name =~ /(.+)_id$/\n return $1.classify.constantize.find(value)\n end\n end\n end",
"def get_param_by_id(id)\n param = nil\n @params.each do |p|\n if p['id'] == id\n param = p\n end\n end\n return param\n end",
"def get_param_by_id(id)\n param = nil\n @params.each do |p|\n if p['id'] == id\n param = p\n end\n end\n return param\n end",
"def id\n [\"#{name}_id\", \"#{model_name}_id\", 'id'].uniq.\n map { |id| controller.params[id] }.find(&:present?)\n end",
"def id_or_param(id)\n id = id.to_param if id.respond_to?(:to_param)\n id\nend",
"def find_params_id(model)\n model.find(params[:id])\n rescue Exception => e\n redirect_with_flash(e.message) and return nil\n end",
"def id\n @id || self.class.name.underscore.split('/').last #gsub('/', '_')\n end",
"def parent_params\n request.path_parameters.keys.select { |k| k.end_with?('_id') }\n end",
"def process_params(path)\n # find symbols: \"users/show/:id/:name\" will give us [\"users/show\", \"id\", \"name\"]\n params = path.split(/\\/:/)\n # first element is path \"users/show\"\n params.shift\n # return params\n params\n end",
"def find_imageable\n params.each do |name, value|\n if name =~ /(.+)_id$/\n klass = $1.classify.constantize\n return klass.find(value)\n end\n end\n nil\n end",
"def params_key(k)\n key = k.to_s.camelize\n key.gsub('Id', 'ID')\n end",
"def id_param\n params[:id]\n end",
"def find_by_id_or_name(error_handler=nil)\n error_handler ||= lambda do |msg|\n logger.error \"find_by_id_or_name #{msg}\"\n return redirect_to_error!(msg)\n end\n\n unless params[:id] || params[:name]\n return error_handler.call(\"No id or name parameter given\")\n end\n\n classname = params[:controller].camelize.singularize\n id = params[:id]\n id ||= params[:name]\n method = :find\n\n if id.blank?\n return error_handler.call(\"Empty id or name parameter given\")\n end\n\n begin\n klass = Kernel.const_get(classname)\n if !id.match(/^[0-9]+$/)\n method = :find_by_name!\n end\n\n unless klass.respond_to?(method)\n return error_handler.call(\"#{classname} does not respond to #{method}\")\n end\n rescue => e\n return error_handler.call(\"No such class name #{classname}\")\n end\n\n begin\n obj = klass.send(method, id)\n rescue => e\n return error_handler.call(e.message)\n end\n\n instance_variable_set(\"@#{params[:controller].singularize}\", obj)\n true\n end",
"def get_id\n params[:id]\n end",
"def route_params\n params = { id: id }\n\n self.class.routes.values.each do |route|\n route.gsub(/:(\\w+)/) do |m|\n m = m.delete(':').to_sym\n params[m] = self.send(m)\n end\n end\n\n params\n end",
"def find_votable\n params.each do |name, value|\n if name =~ /(.+)_id$/\n return $1.classify.constantize.find(value)\n end\n end \n return nil\n end",
"def find(id, params = {})\n from_base id, params\n end",
"def find_commentable\n params.each do |name, value|\n if name =~ /(.+)_id$/\n return $1.classify.constantize.find(value) \n end\n end\n nil\n end",
"def identifier_from_path\n @identifier_from_path ||= request.path_info.each_with_object({}) do | (key, value), hash|\n case value\n when String, Symbol, Numeric\n hash[key] = value\n end\n end\n end",
"def entity_by_id(model_class)\n halt 400 unless (params[:id].to_i.to_s == params[:id])\n model_class[params[:id]] || (halt 404)\n end",
"def id\n @params[\"id\"]\n end",
"def get_param(name_or_id, by_name_or_id)\n param = nil\n @params.each do |p|\n if (by_name_or_id == :by_id and p['id'] == name_or_id)\n param = p\n end\n if (by_name_or_id == :by_name and p['name'] == name_or_id)\n param = p\n end\n end\n return param\n end",
"def get_param(name_or_id, by_name_or_id)\n param = nil\n @params.each do |p|\n if (by_name_or_id == :by_id and p['id'] == name_or_id)\n param = p\n end\n if (by_name_or_id == :by_name and p['name'] == name_or_id)\n param = p\n end\n end\n return param\n end",
"def find_commentable\n params.each do |name, value|\n if name =~ /(.+)_id$/\n return $1.classify.constantize.find(value)\n end\n end\n nil\n end",
"def process_path_for_parent_params(path, parent_params)\n parent_prefix = parent_params.flatten.compact.uniq.map do |param|\n map = (param.respond_to?(:map) && param.map ? param.map : param.to_s)\n part = \"#{map}/:#{Inflections.singularize(param)}_id/\"\n part = \"(#{part})?\" if param.respond_to?(:optional) && param.optional?\n part\n end\n\n [parent_prefix, path].flatten.join(\"\")\n end",
"def normalize_params(h = nil)\n h = params unless h.is_a?(Hash)\n hn = {}\n re = /.+_id$/i\n \n h.each do |hk, hv|\n case hv\n when ActionController::Parameters\n hv = normalize_params(hv.to_h)\n when Hash\n hv = normalize_params(hv)\n end\n\n hn[hk.to_sym] = hv\n shk = hk.to_s\n hn[\"_#{shk}\".to_sym] = (hv.is_a?(String) ? hv.dup : hv) if (shk == 'id') || (shk =~ re)\n end\n\n hn\n end",
"def load_param(p)\r\n if params.has_key?(p + '_id')\r\n #logger.info(\"*** looking to load: #{p + '_id'}\")\r\n begin\r\n instance_variable_set(('@' + p).to_sym, p.camelize.constantize.find(params[p + '_id']))\r\n #logger.info(\"**** autoloaded an instance of #{p.camelize} with an id of #{params[p + '_id']} ****\")\r\n rescue\r\n logger.info(\"**** Couldn't find an instance of #{p.camelize} with an id of #{params[p + '_id']} ****\")\r\n end\r\n end\r\n end",
"def extract_resource_context(params)\n (Conf.contributor_models + Conf.contributable_models).each do |model_name|\n id_param = \"#{model_name.underscore}_id\"\n return Object.const_get(model_name).find_by_id(params[id_param]) if params[id_param]\n end\n\n nil\n end",
"def get_id\n allowed_params = params.permit(:id, :ref, :path)\n\n id = [allowed_params[:id] || allowed_params[:ref]]\n id << \"/\" + allowed_params[:path] unless allowed_params[:path].blank?\n id.join\n end",
"def find_documentable\n params.each do |name, value|\n if name =~ /(.+)_id$/\n klass = $1.classify.constantize\n return klass.find(value)\n end\n end\n nil\n end",
"def id\n params[:id] \n end",
"def find_opinionable\n params.each do |name, value|\n if name =~ /(.+)_id$/\n return $1.classify.constantize.find(value)\n end\n end\n nil\n end",
"def extract_id(self_link, type)\n link = self_link.match(/#{type}\\/(?<id>\\d+)/)\n id = link['id']\nend",
"def parse_params(options, klass)\n options = symbolize_keys(options)\n id = extract_id(options, klass)\n params = id ? { id: id } : parse_associated_params(options, klass)\n validate_params(params, klass)\n end",
"def actual_id\n args = params[:id].split('-')\n args[0]\n end",
"def id\n params[:id]\n end",
"def extract_resource_context(params)\n (Conf.contributor_models + Conf.contributable_models).each do |model_name|\n id_param = \"#{Conf.to_visible(model_name.underscore)}_id\"\n return Object.const_get(model_name).find_by_id(params[id_param]) if params[id_param]\n end\n\n nil\n end",
"def find_commentable\n \tparams.each do |name, value|\n \t\tif name =~ /(.+)_id$/\n \t\t\treturn $1.classify.constantize.find(value)\n \tend\n end\n nil\n end",
"def extract_id(object)\n case object\n when ::Integer\n object\n when ::String\n object.split('/').last.to_i\n when URI, Addressable::URI\n object.path.split('/').last.to_i\n when Teamsupport::Identity\n object.ID\n end\n end",
"def parse_id(id)\n id.split('/')\n end",
"def get_from_param\n instance_variable_set(\"@#{self.controller_name.singularize}\", self.controller_name.classify.constantize.from_param(params[:id]))\n end",
"def record\n @record ||= if request.path_parameters[:id]\n controller_name.classify.constantize.find_by(id: request.path_parameters[:id])\n end\n end",
"def get!(id)\n klass.find(:all, params: { id: wrap_key(id) })\n end",
"def get_full_path_id\n full_path_id = self.id[0..1] + '/' + self.id[2..3] + '/' + self.id[4..5] + '/' + self.id[6..7] + '/' + self.id\n end",
"def model_from(path)\n extract_from path, /\\/(\\w+)\\/(\\d+)/\n end",
"def find_by_id(id)\n resp = get(\"/#{exposed_as}/#{id}\")\n case resp.response.code.to_i\n when 200\n result = MultiJson.load resp.parsed_response\n new(result)\n when 404\n nil\n else\n raise \"#{self.class.name}#try_find with ID #{id.inspect} returned unexpected response: #{resp.inspect}\"\n end\n end",
"def identifier\n match_path(3..-1)\n end",
"def find_by_id(clazz, id)\n clazz.find(id)\n end",
"def paramsid\n @order = Order.find_by(params[:id])\n params[:id]= @order.id\n end",
"def id_finder\n @id_finder ||= extract_id ? :all_of : :where\n end",
"def param_by_classname(string)\n key = string.underscore.to_sym\n if @config_params.key?(key)\n @config_params.fetch(key)\n end\n end",
"def find_by_friendly_id(id); end",
"def process_path_for_parent_params(path, parent_params)\n parent_prefix = parent_params.uniq.collect { |param| \"#{param}/:#{param}_id\" }.join(\"/\")\n File.join(parent_prefix, path)\n end",
"def extract_id\n selector[:_id]\n end",
"def get_object_by_id(class_name, id)\n obj = nil\n get_objects_of_class(class_name).each do |o|\n if o.id == id\n obj = o\n break\n end\n end\n obj\n end",
"def get_parent_resource\n parent_id_param = request.path_parameters.keys.detect { |k| k.to_s.end_with?('_id') }\n if parent_id_param\n parent_type = parent_id_param.to_s.chomp('_id')\n parent_class = safe_class_lookup(parent_type.camelize)\n if parent_class\n @parent_resource = parent_class.find(params[parent_id_param])\n end\n end\n end",
"def id\n \"#{controller.url}/#{name}\"[1..-1].gsub('/', '_')\n end",
"def find_object\n @object = @model_class.find_by_id(params[:id].to_i)\n end",
"def extract_encoded_object(param)\n return nil unless param\n s = SimpleScramble.unscramble(CGI.unescape(param)) \n (obj_class,obj_id) = s.split('-') unless ( s.blank? )\n obj_class && obj_id ? obj_class.constantize.find_by_id(obj_id) : nil\n end",
"def to_param\n # We can't use alias_method here, because method 'id' optimizes itself on the fly.\n id&.to_s # Be sure to stringify the id for routes\n end",
"def params_for_get\n \"params[:id]\"\n end",
"def build_request_path(path = nil, parameters = {})\n parameters = parameters.try(:with_indifferent_access)\n\n unless path.is_a?(String)\n parameters = path.try(:with_indifferent_access) || parameters\n path =\n if parameters.include?(primary_key) && parameters[primary_key] && !parameters[primary_key].kind_of?(Array)\n element_path.dup\n else\n collection_path.dup\n end\n\n owner_path = parameters.delete(:_owner_path)\n path = \"#{owner_path}/#{path}\" unless owner_path.nil?\n\n # Replace :id with our actual primary key\n path.gsub!(/(\\A|\\/):id(\\Z|\\/)/, \"\\\\1:#{primary_key}\\\\2\")\n end\n\n path.gsub(/:([\\w_]+)/) do\n # Look for :key or :_key, otherwise raise an exception\n value = $1.to_sym\n parameters.delete(value) ||\n parameters.delete(:\"_#{value}\") ||\n raise(ActiveService::Errors::PathError.new(\"Missing :_#{$1} parameter to build the request path. Path is `#{path}`. Parameters are `#{parameters.symbolize_keys.inspect}`.\", $1))\n end\n end",
"def to_param\n id\n end",
"def id_path\n full_path.collect(&:id).join(\":\")\n end",
"def get(path_or_id, *args)\n if path_or_id.is_a?(String)\n get_by_path(path_or_id)\n else\n super\n end\n end",
"def [](id)\n begin\n @params[id]\n rescue NameError => e\n Utils_errors::critical_error(\"Params module #{@db_name}'s getter was called with a bad argument : '#{id}' ( there is no such id )\", e)\n end\n end",
"def nested_models\n @controller.params.map {|key, value| [key.to_s.gsub('_id','').camelize, value] if key.to_s =~ /_id$/}.compact\n end",
"def parent_type_from_params\n [*belongs_to].find { |parent| !params[\"#{parent}_id\".to_sym].nil? }\n end",
"def _get_from_params(key)\n if @params.respond_to?(:dig)\n @params.dig(*key.to_s.split(GET_SEPARATOR).map!(&:to_sym))\n else\n @params.get(key)\n end\n end",
"def self_param_id\n \"#{name.underscore}_id\".to_sym\n end",
"def self_param_id\n \"#{name.underscore}_id\".to_sym\n end",
"def self_param_id\n \"#{name.underscore}_id\".to_sym\n end",
"def extract_id(args)\n args.each { |arg| return arg.fetch('id') if arg.is_a? Hash }\n nil\n end",
"def to_param\n id\n end",
"def get_id(what, item)\n case what.keys[0]\n when :study\n /^study_(?<s_id>\\d+)_manage_link$/.match(item['id'])[:s_id]\n when :study_group\n /^study_group_(?<sg_id>\\d+)_manage_link$/.match(item['id'])[:sg_id]\n when :site\n raise \"don't know how to search for site id\"\n when :team\n raise \"don't know how to search for team id\"\n else\n nil\n end\n end",
"def parent_type_from_params\n [*belongs_to].find { |parent| !params[\"#{parent}_id\".to_sym].nil? }\n end",
"def id_class\n @id_class ? @id_class : nil\n end",
"def folder_id\n case params[:controller] + '/' + params[:action]\n when 'folder/index', 'folder/list', 'folder/new', 'folder/create', 'folder/update_permissions', 'folder/feed', 'file/upload', 'file/validate_filename'\n current_folder_id = 1 unless current_folder_id = params[:id]\n when 'file/do_the_upload'\n # This prevents a URL like 0.0.0.0/file/do_the_upload/12,\n # which breaks the upload progress. The URL now looks like this:\n # 0.0.0.0/file/do_the_upload/?folder_id=12\n current_folder_id = 1 unless current_folder_id = params[:folder_id]\n when 'folder/rename', 'folder/update', 'folder/destroy'\n current_folder_id = @folder.parent_id if @folder\n when 'file/download', 'file/rename', 'file/update', 'file/destroy', 'file/preview'\n current_folder_id = @myfile.folder.id\n when 'inbox/do_the_upload', 'inbox/index'\n unless params[:user_id].nil?\n current_folder_id = Folder.fetch_user_inbox(params[:user_id]).id \n else\n current_folder_id = Folder.fetch_user_inbox(@logged_in_user.id).id \n end\n end\n\n case params[:controller]\n when 'claims'\n current_folder_id = 2\n end\n\n return current_folder_id\n end",
"def to_param\n # We can't use alias_method here, because method 'id' optimizes itself on the fly.\n id && id.to_s # Be sure to stringify the id for routes\n end",
"def find(id); end",
"def find(id); end",
"def object_for(object_or_id, klass)\n case object_or_id\n when klass then object_or_id\n when Integer\n klass.find_by(id: object_or_id)\n else\n raise ArgumentError,\n \"must provide a #{ klass } or a valid #{ klass } id\"\n end\n end",
"def player_class_id(c)\n PlayerClass.find_by(name: c['playerClass']).id\nrescue NoMethodError\n PlayerClass.find_by(name: 'Neutral').id\nend",
"def find_by_path_or_id(path, id)\n Categories::Finder.by_path_or_id(path, id)\n end",
"def parent_param\n params[\"#{parent_type}_id\".to_sym]\n end",
"def to_param_from_slug\n slug? ? slug.to_friendly_id : id.to_s\n end",
"def to_param_from_slug\n slug? ? slug.to_friendly_id : id.to_s\n end",
"def to_param_from_slug\n slug? ? slug.to_friendly_id : id.to_s\n end",
"def get_id(id)\n return unless id\n id = id['id'] || id[:id] if id.is_a?(Hash)\n id\n end",
"def find_model_class_by(params)\n model_class = Map.model_class_map params[:resources]\n return model_class unless MODEL_ACTIONS.include? params[:action].to_sym\n raise ModelNotFound, params[:resources] unless model_class\n unless Map.mode_map[model_class]\n raise UnprocessableEntity, Locale.t('errors.unprocessable_entity.model', model: model_class)\n end\n\n model_class\n end",
"def path\n Rails.application.routes.url_helpers.send(self.class.to_s.underscore.concat('_path'), id)\n end",
"def find_by_path_or_id!(path, id)\n category = find_by_path_or_id(path, id)\n\n raise ActiveRecord::RecordNotFound unless category\n\n category\n end",
"def find_by_path_or_id!(path, id)\n category = find_by_path_or_id(path, id)\n\n raise ActiveRecord::RecordNotFound unless category\n\n category\n end",
"def to_param\n \"#{self.id}-#{self.match.try(:name)}\".parameterize\n end",
"def polymorphic_id_param\n \"#{key}_id\".to_sym\n end"
] |
[
"0.6184204",
"0.5998596",
"0.59538954",
"0.5832948",
"0.5788657",
"0.57686955",
"0.5625831",
"0.5625831",
"0.56169355",
"0.55943364",
"0.5585347",
"0.549406",
"0.54765767",
"0.54430145",
"0.54159385",
"0.5381057",
"0.53735405",
"0.5333437",
"0.5329433",
"0.52723914",
"0.52720195",
"0.5264187",
"0.52249646",
"0.5223735",
"0.52147746",
"0.52103573",
"0.5206027",
"0.5206027",
"0.5204313",
"0.5201641",
"0.51541877",
"0.51471543",
"0.51373404",
"0.5125267",
"0.51244444",
"0.510607",
"0.5083271",
"0.5076615",
"0.50534743",
"0.50491995",
"0.503791",
"0.5033748",
"0.503284",
"0.5023895",
"0.5020329",
"0.50138426",
"0.50063944",
"0.4970179",
"0.49700907",
"0.4951824",
"0.49148446",
"0.4914386",
"0.48949262",
"0.4893483",
"0.48928148",
"0.489214",
"0.4890157",
"0.48840412",
"0.4877974",
"0.48676616",
"0.48596466",
"0.48593757",
"0.48363397",
"0.48345652",
"0.4830697",
"0.48251048",
"0.48017237",
"0.47980633",
"0.4778214",
"0.47701156",
"0.4768897",
"0.4765776",
"0.47505108",
"0.474095",
"0.4739794",
"0.4739794",
"0.4739794",
"0.4728695",
"0.471821",
"0.4716244",
"0.4714747",
"0.47129002",
"0.4710414",
"0.47062704",
"0.4697708",
"0.4697708",
"0.46949407",
"0.46942347",
"0.46891707",
"0.46888155",
"0.46884462",
"0.46884462",
"0.46884462",
"0.46879315",
"0.46815053",
"0.46789768",
"0.46725896",
"0.46725896",
"0.46712688",
"0.46539357"
] |
0.60759187
|
1
|
Adds +action_names+ to the list of valid actions for this resource. Does not include superclass's action list when appending.
|
def actions(*action_names)
action_names = action_names.flatten
if !action_names.empty? && !@allowed_actions
self.allowed_actions = ([ :nothing ] + action_names).uniq
else
allowed_actions(*action_names)
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def add_actions(actions)\n # Remove the empty action (dead pokemon)\n actions.delete_if(&:empty?)\n # Merge the actions\n @actions.concat(actions)\n end",
"def include_actions(*actions)\n self.actions ||= []\n self.actions.push(*actions)\n end",
"def add_action(action)\n if !@actions.include?(action)\n @actions << action\n @actions.flatten!\n end\n end",
"def add_actions(*args)\n @actions.concat(args)\n end",
"def actions\n @actions ||= self.class.registered_actions.inject({}){ |res, name| res.merge(name.to_sym => normalize_action_config(send(ACTION_METHOD_NAME % name))) }\n end",
"def append_action actions\n params = {}\n instance_variables.each do | each |\n params[ each.to_s.sub( '@', '' ).to_sym ] = instance_variable_get( each )\n end\n method = \"append_#{ self.class.name.demodulize.underscore }\"\n __send__ method, actions, params\n end",
"def action_methods\n @action_methods ||= Set.new(super.reject { |name| hidden_actions.include?(name) }).freeze\n end",
"def action_strs=(actions)\n @action_strs = actions\n if !@action_strs.is_a?(Array)\n @action_strs = [@action_strs]\n end\n end",
"def set_actions\n @actions = []\n end",
"def setup_actions(actions)\n keep_actions = actions\n\n if actions.include?(:all)\n keep_actions = ACTIONS\n end\n\n options = actions.extract_options!\n except_actions = options[:except] || []\n keep_actions -= except_actions\n\n (ACTIONS - keep_actions).uniq.each do |action|\n undef_method action.to_sym, \"#{action.to_sym}!\"\n end\n end",
"def add_action(action)\n unless action && kind.actions.include?(action)\n raise Occi::Core::Errors::MandatoryArgumentError, 'Cannot add an action that is empty or not defined on kind'\n end\n actions << action\n end",
"def add_action(new_action)\n if action(new_action.name)\n raise DuplicateAction, \"Action '#{new_action.name}' already defined on service '#{_attributes_[:name]}'\"\n end\n\n actions << new_action\n end",
"def upmin_actions(*actions)\n if actions.any?\n # set the actions\n @upmin_actions = actions.map{|a| a.to_sym}\n end\n @upmin_actions ||= []\n return @upmin_actions\n end",
"def actions\n @actions ||= []\n end",
"def add_actions(action_map)\n authority_action_map.merge!(action_map)\n end",
"def resource_actions params={}\n except = params.delete(:except).arrayize.compact\n only = params.delete(:only).arrayize.compact\n\n params[:format] = params.has_key?(:format) ? params[:format].arrayize : [:html,:xml]\n\n # Logic to see if we should add an action\n # It should either be in :only, or :except isn't empty and it's not in :except\n should_add = lambda do |action|\n # Only isn't empty and our action is contained within\n if !only.empty?\n break only.include?(action)\n end\n # Except isn't empty and our action isn't contained therein\n if !except.empty?\n break !except.include?(action)\n end\n # Just add it\n true\n end\n\n # Add each action, if we should\n add :index, params if should_add[:index]\n add :new, params if should_add[:new]\n add :create, params if should_add[:create]\n add :edit, {:id => \"some_id\"}.merge(params) if should_add[:edit]\n add :show, {:id => \"some_id\"}.merge(params) if should_add[:show]\n add :update, {:id => \"some_id\"}.merge(params) if should_add[:update]\n add :destroy, {:id => \"some_id\"}.merge(params) if should_add[:destroy]\n end",
"def actions=(action)\n @actions << action \n end",
"def resources_actions\n @resources_actions ||= []\n end",
"def actions\n @actions ||= []\n end",
"def exclude_actions(*actions)\n self.excluded_actions ||= []\n self.excluded_actions.push(*actions)\n end",
"def actions=(value)\n @actions = value\n end",
"def actions\n if !@actions\n # make sure we've loaded all the actions we know about\n Dir.glob(File.join(File.dirname(__FILE__), 'ec2-discovery', 'actions', '*.rb')).each do |file|\n req_name = \"ec2-discovery/actions/#{File.basename(file).gsub(/\\.rb^/, '')}\"\n info \"Requiring #{req_name}\"\n require req_name\n end\n\n @actions = []\n action_strs.each do |action_str|\n begin\n action = eval(action_str)\n if action.is_a?(ReframeIt::EC2::Action)\n @actions << action\n info { \"Loaded action #{action.inspect}\" }\n else\n error \"Actions must inherit from ReframeIt::EC2::Action, but #{action.inspect} does not!\"\n end\n rescue Exception => ex\n error \"Error trying to eval #{action_str}\", ex\n end\n end\n end\n\n @actions\n end",
"def _actions(action = nil)\n @_actions ||= Mash.new{|h,k| h[k] = ActionManager.new}\n action.nil? ? @_actions : @_actions[action]\n end",
"def actions\n @actions || []\n end",
"def add_default_action(action)\n ORIGINAL_ACTIONS << action\n end",
"def add_default_action(action)\n ORIGINAL_ACTIONS << action\n end",
"def for_actions(*actions)\n self.working_actions = actions\n self\n end",
"def default_actions\n @actions = []\n @actions << 'add_trace' if logged_in?\n @actions << 'search' if logged_in?\n end",
"def authority_actions(action_map)\n forced_action = action_map.delete(:all_actions)\n add_actions(action_map)\n force_action(forced_action) if forced_action\n end",
"def actions *actions\n options = actions.extract_options!\n return if actions.blank?\n actions = [:show, :edit, :destroy] if actions == [:all]\n actions.each do |action|\n action_link(action.to_sym, options)\n end\n nil\n end",
"def define_actions_from_routes\n (effective_resource.member_actions - effective_resource.crud_actions).each do |action|\n define_method(action) { member_action(action) }\n end\n\n (effective_resource.collection_actions - effective_resource.crud_actions).each do |action|\n define_method(action) { collection_action(action) }\n end\n end",
"def resource_actions=(value)\n @resource_actions = value\n end",
"def resource_actions=(value)\n @resource_actions = value\n end",
"def resource_actions\n @resource_actions ||= []\n end",
"def initialize\n @actions = []\n end",
"def add_action(action)\n types = [\"Sieve::Action\", \"Sieve::Vacation\"]\n raise \"the param is not a Action\" unless types.index(action.class.to_s)\n @actions << action\n end",
"def allowed_resource_actions=(value)\n @allowed_resource_actions = value\n end",
"def addAction(action)\n @index += 1\n @actions -= @actions.drop(@index)\n @actions.push(action)\n end",
"def actions\n return self.class.actions_pool if self.params[\"screen\"].blank?\n self.class.actions_pool.select {|action| valid_action?(action)}.uniq {|action| action[:name]}\n end",
"def initialize_actions(actions)\n @loading = true unless @strict\n\n filtered_actions, active_undos = self.class.filtered_actions(actions)\n @undo_possible = false\n # replay all actions with a copy\n filtered_actions.each.with_index do |action, index|\n if !action.nil?\n action = action.copy(self) if action.is_a?(Action::Base)\n process_action(action)\n else\n # Restore the original action to the list to ensure action ids remain consistent but don't apply them\n @actions << actions[index]\n end\n end\n @redo_possible = active_undos.any?\n @loading = false\n end",
"def mount_default_actions(actions)\n raise TypeError, \"wrong argument type #{actions.class.name} (expected Array)\" unless actions.is_a?(Array)\n\n actions.each do |action|\n create_route_for(action)\n end\n end",
"def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end",
"def action_strs\n @action_strs ||= user_data_as_array('action')\n @action_strs\n end",
"def expand_actions(actions)\n actions.map do |action|\n aliased_actions[action] ? [action, *expand_actions(aliased_actions[action])] : action\n end.flatten\n end",
"def add_actions(actions)\n @search_options.add_actions(actions, @info)\n search()\n end",
"def actions\n @actions ||= {}\n result = @actions.keys\n\n if self.is_a?(Class) and superclass.respond_to?(:actions)\n result += superclass.actions\n elsif self.class.respond_to?(:actions)\n result += self.class.actions\n end\n # We need to uniq the result, because we duplicate actions when they are\n # fetched to ensure that they have the correct bindings; they shadow the\n # parent, and uniq implements that. --daniel 2011-06-01\n (result - @deactivated_actions.to_a).uniq.sort\n end",
"def hide_action(*names)\n self._hidden_actions = self._hidden_actions | names.map { |n| n.to_s }\n end",
"def set_resource_actions\n self.actions[:index] = Action.new(self.entity, :index, :collection, :resource => true)\n self.actions[:new] = Action.new(self.entity, :new, :collection, :resource => true)\n self.actions[:edit] = Action.new(self.entity, :edit, :member, :resource => true)\n self.actions[:show] = Action.new(self.entity, :show, :member, :resource => true)\n self.actions[:create] = Action.new(self.entity, :create, :collection, :method => :post, :resource => true)\n self.actions[:update] = Action.new(self.entity, :update, :member, :method => :put, :resource => true)\n self.actions[:delete] = Action.new(self.entity, :delete, :member, :method => :delete, :resource => true)\n end",
"def actions\n @actions ||= enabled_actions.split(',')\n end",
"def actions=(new_actions)\n raise 'Actions must be an array!' unless new_actions.is_a?(Array)\n raise 'Actions must be up to 10 items!' unless new_actions.size < 10\n raise 'Action length must not be over 50 characters!' unless new_actions.select { |v| v.length > 50 }.empty?\n\n @actions = new_actions unless new_actions.empty?\n end",
"def inherit_actions(actions = superclass.actions, exclude: [])\n\t\t\t\t(actions - exclude).each do |public_method|\n\t\t\t\t\tum = superclass.public_instance_method(public_method)\n\t\t\t\t\tdefine_method public_method, um\n\t\t\t\tend\n\t\t\tend",
"def create\n @actions = [] unless defined?(@actions)\n @actions << :create\n end",
"def actions\n []\n end",
"def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end",
"def hide_action(*names)\n write_inheritable_attribute(:hidden_actions, hidden_actions | names.collect { |n| n.to_s })\n end",
"def add_actions; end",
"def add_actions(count)\n update_attributes(actions: actions + count)\n end",
"def available_actions\n @available_search_criteria.deep_find_results('AddAction')\n end",
"def register_actions_by_item_and_action_name(item_actions)\n item_actions.each do |item_name, act_hash|\n if @item_actions[item_name]\n act_hash.each do |action_name, opts|\n existing = @item_actions[item_name][action_name]\n if existing\n ActionItem::ACTION_LEGAL_KEYS.each do |key|\n if existing[key] && opts[key] && existing[key] != opts[key]\n raise \"Can't register action #{action_name.inspect} for item #{item_name.inspect}, conflict for key #{key.inspect}!\"\n end\n end\n existing.merge!(opts)\n else\n @item_actions[item_name][action_name] = opts\n end\n end\n else\n @item_actions[item_name] = act_hash\n end\n end\n end",
"def valid_action?(name, resource = resource_class)\n disabled_actions.exclude?(name.to_s) && super\n end",
"def actions\n actions = ((self.instance_methods(false) - ::Object.methods) + (@action_aliases||{}).keys).\n reject { |a| a.to_s =~ /__appetite__/ }.\n map { |a| a.to_sym }\n return actions if actions.size > 0\n\n define_method :index do |*|\n 'Get rid of this placeholder by defining %s#index' % self.class\n end\n\n [:index]\n end",
"def define_methods_from_actions(action_list)\n log \"<#{self.class}> Defining methods; action list: #{action_list}\"\n\n if action_list.is_a? Hash\n @action_list << action_list\n define_method_from_action(action_list[:name].to_sym,\n action_list[:argumentList][:argument])\n elsif action_list.is_a? Array\n action_list.each do |action|\n=begin\n in_args_count = action[:argumentList][:argument].find_all do |arg|\n arg[:direction] == 'in'\n end.size\n=end\n @action_list << action\n args = action[:argumentList] ? action[:argumentList][:argument] : {}\n define_method_from_action(action[:name].to_sym, args)\n end\n else\n log \"<#{self.class}> Got actionList that's not an Array or Hash.\"\n end\n end",
"def actions\n actions = []\n @model.with_each_action_for(self) do |action|\n actions << action\n end\n actions\n end",
"def actions\n [only].flatten.map(&:to_sym) - [except].flatten.map(&:to_sym)\n end",
"def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end",
"def actions\n ['index', 'show', 'new', 'create', 'edit', 'update', 'destroy']\n end",
"def add(file); @actions << Action::AddAction.new(file); end",
"def allow(actions, resources)\n add_rule(true, actions, resources)\n end",
"def default_actions\n [\n Constants.TASK_ACTIONS.ADD_ADMIN_ACTION.to_h,\n Constants.TASK_ACTIONS.CANCEL_AND_RETURN_TASK.to_h\n ]\n end",
"def set_actions\n @actions = []\n\n unless params[:show_actions] == 'false' || @node.blank?\n role = current_user.role_on(@node)\n\n if role && @node.content_type_configuration[:allowed_roles_for_update].include?(role.name)\n @actions << { url: { action: :edit }, text: I18n.t('admin.edit'), method: :get }\n end\n end\n end",
"def defined_actions\n\n controller.instance_methods.map(&:to_sym) & ResourceController::ACTIVE_ADMIN_ACTIONS\n\n end",
"def register_actions(action_hash)\n @engine.register_actions_by_item_and_action_name(@name => action_hash)\n end",
"def initialize_actions(actions, at_action: nil)\n @loading = true unless @strict\n filtered_actions, active_undos = self.class.filtered_actions(actions)\n\n # Store all actions for history navigation\n @raw_all_actions = actions\n filtered_actions.each.with_index { |action, index| @raw_all_actions[index]['skip'] = true unless action }\n\n @undo_possible = false\n # replay all actions with a copy\n filtered_actions.each.with_index do |action, index|\n next if @exception\n break if at_action && action && action['id'] > at_action\n\n if action\n action = action.copy(self) if action.is_a?(Action::Base)\n\n process_action(action)\n else\n # Restore the original action to the list to ensure action ids remain consistent but don't apply them\n @raw_actions << actions[index]\n end\n end\n @redo_possible = active_undos.any?\n @loading = false\n end",
"def insert_action?(new_action, action_list, opts = {})\n insert_action_helper = InsertActionHelper.create(new_action, action_list, opts)\n insert_action_helper.insert_action?(self)\n end",
"def parse_actions(action_list)\n @actions = {}\n\n if action_list == nil\n return\n end\n action_list.css('action').each do |action|\n name = action.at('name').text.strip\n\n raise Error, \"insecure action name #{name}\" unless name =~ /\\A\\w*\\z/\n\n\n @actions[name] = parse_action_arguments action.at('argumentList')\n end\n end",
"def available_actions\n fail NotImplementedError\n end",
"def flash_addItemWithActions(list_name, message, actions)\n if flash[list_name].nil?\n flash[list_name] = Array.new\n end\n flash_string = \"<p>#{message}</p><div class=\\\"alert-actions\\\">\"\n\n actions.each do |action|\n if action[:type] == :link\n flash_string = flash_string + \"<a class=\\\"btn small\\\" href=\\\"#{action[:action]}\\\">#{action[:name]}</a>\"\n end\n end\n\n flash_string = flash_string +\"</div>\"\n flash[list_name].push(flash_string)\n end",
"def validate_resource_actions(resource_file_path, action_script_names)\n defined_actions = load_resource_actions(resource_file_path) if File.exists?(resource_file_path)\n unless defined_actions.nil? || defined_actions.empty?\n missing_action_definitions = []\n defined_actions.each { |action_name| missing_action_definitions << action_name unless action_script_names.include?(action_name) }\n if missing_action_definitions.size == 1\n Log.info(\"[chef] Warning! no powershell script exists for the action: #{missing_action_definitions.first}\")\n elsif missing_action_definitions.size > 1\n Log.info(\"[chef] Warning! no powershell scripts exist for the following actions: #{missing_action_definitions.join(\", \")}\")\n end\n end\n\n true\n end",
"def global_actions\n if self == Base\n own_global_actions\n else\n superclass.global_actions + own_global_actions\n end\n end",
"def _hidden_actions\n actions = read_inheritable_attribute(:_hidden_actions)\n actions ? actions : write_inheritable_attribute(:_hidden_actions, [])\n end",
"def set_actions\n actions :all\n end",
"def method_added(name)\n super\n clear_action_methods!\n end",
"def valid_action?(value)\n action_names.include?(value)\n end",
"def actions\n return self.class.actions_pool if self.params[\"screen\"].blank?\n self.class.actions_pool.select {|action| valid_action?(action, self.params[\"screen\"]) } \n end",
"def action_list(action_id, fields = \"all\")\n action_resource action_id, \"list\", fields: fields\n end",
"def upmin_action(action)\n @upmin_actions ||= []\n\n action = action.to_sym\n @upmin_actions << action unless @upmin_actions.include?(action)\n end",
"def excluded_resource_actions=(value)\n @excluded_resource_actions = value\n end",
"def allow_all_actions(path)\n @allowed << { :controller => recognize_path(path)[:controller] }\n end",
"def add_permissions(resource, actions)\n raise ArgumentError, 'invalid resource' unless resource\n raise ArgumentError, 'invalid actions' unless actions\n\n acts = actions.is_a?(Array) ? actions : [actions]\n @permissions << { resource: resource, actions: acts }\n end",
"def add_action(a)\n $LOG.debug(\"Adding action #{a.type} to #{seq_name}\")\n \n @actions.push a\n \n a.apply_to(self)\n \n return a\n \n end",
"def actions(*actions_to_keep)\n raise ArgumentError, 'Wrong number of arguments. You have to provide which actions you want to keep.' if actions_to_keep.empty?\n\n options = actions_to_keep.extract_options!\n actions_to_remove = Array(options[:except])\n actions_to_remove += ACTIONS - actions_to_keep.map { |a| a.to_sym } unless actions_to_keep.first == :all\n actions_to_remove.map! { |a| a.to_sym }.uniq!\n (instance_methods.map { |m| m.to_sym } & actions_to_remove).each do |action|\n undef_method action, \"#{action}!\"\n end\n end",
"def addAction(verb, target, result, usableItems)\n verbSymbol = verb.to_sym\n a = self[verbSymbol]\n newA = false\n if a.nil?\n a = Action.new(verbSymbol) if a.nil?\n newA = true\n end\n \n newItems = usableItems.to_a # Allows single strings to be passed\n symbolItems = []\n usableItems.each do |x|\n symbolItems << x.to_sym\n end\n\n a.addTarget(target.to_sym, result.to_sym, symbolItems)\n @actions << a if newA\n sortActions if newA\n a # return the Action\n end",
"def store_action_items\n return unless self.all_action_items\n\n self.all_action_items.delete :retrieved_file\n\n if self.class.columns_hash[item_actions_field].type == :string\n send \"#{item_actions_field}=\", self.all_action_items.to_json\n else\n send \"#{item_actions_field}=\", self.all_action_items\n end\n end",
"def permissions(*actions, &block)\n # Store the permissions block so we can run it in validations\n self.__permissions__ ||= {}\n\n # if no action was specified, assume all actions\n actions += [:create, :read, :update, :delete] if actions.size == 0\n\n actions.each do |action|\n # Add to an array of proc's for each action\n (self.__permissions__[action] ||= []) << block\n end\n\n validate do\n action = new? ? :create : :update\n run_permissions(action)\n end\n end",
"def collection_action(name, method, request_type)\n self.actions[name.to_sym] = Action.new(self.entity, name.to_sym, :collection, :method => method, :request_type => request_type)\n end",
"def actions(allow_private = false)\n actions = {}\n \n actions.update(self.class.superclass.actions(allow_private)) if (klass = self.class.superclass).respond_to? :actions\n \n actions.update(self.class.actions(allow_private))\n \n actions\n end",
"def _valid_action_name?(action_name); end",
"def collect\n raise Errors::ActionMethodNotImplemented.new 'Collect actions must overwrite the collect method.'\n end",
"def action\n case attributes['action']\n when 'modify' then :modify\n when 'delete' then :delete\n else :add\n end\n end",
"def actionlist_params\n params.require(:actionlist).permit(:name)\n end"
] |
[
"0.6996415",
"0.6754788",
"0.6661041",
"0.6623624",
"0.65538853",
"0.63702375",
"0.6365066",
"0.63529104",
"0.6340668",
"0.6312769",
"0.62622046",
"0.6175846",
"0.61708295",
"0.6154739",
"0.61301893",
"0.6121649",
"0.61059654",
"0.6072857",
"0.603807",
"0.6031886",
"0.60253346",
"0.60159576",
"0.601049",
"0.5970578",
"0.5961836",
"0.5961836",
"0.5957197",
"0.5949741",
"0.5897102",
"0.5885555",
"0.5871312",
"0.5810215",
"0.5810215",
"0.5809418",
"0.58011734",
"0.57721436",
"0.5752229",
"0.5741781",
"0.5716412",
"0.57155174",
"0.5714951",
"0.5696455",
"0.5693179",
"0.5692445",
"0.5690753",
"0.56835335",
"0.5678463",
"0.5678398",
"0.5676463",
"0.56734926",
"0.56722933",
"0.5660835",
"0.5650866",
"0.5650611",
"0.56355786",
"0.5620969",
"0.55808634",
"0.55532616",
"0.55250496",
"0.55227304",
"0.5501847",
"0.5485914",
"0.54701483",
"0.54690474",
"0.5456805",
"0.5451522",
"0.54496104",
"0.54271996",
"0.54231924",
"0.5423",
"0.54217345",
"0.5421657",
"0.54214334",
"0.54113716",
"0.54095405",
"0.5400278",
"0.53977257",
"0.5367286",
"0.53634316",
"0.5363176",
"0.5350596",
"0.53474957",
"0.5335767",
"0.53073937",
"0.53069514",
"0.5288743",
"0.527749",
"0.52755505",
"0.52663976",
"0.52565944",
"0.52504176",
"0.52251714",
"0.5223113",
"0.5204343",
"0.519433",
"0.5193961",
"0.5181913",
"0.5174124",
"0.51679546",
"0.51666605"
] |
0.7872911
|
0
|
a book title. First word in a title should always be capitalized. Do not capitalize words like 'a', 'and', 'of', 'over' or 'the'.
|
def titleize(title)
#test
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def title=(book_title)\n little_words = %w{a an and the in of for}\n title = book_title.split.map do |word|\n if little_words.include? word\n word\n else\n word = word[0].upcase + word[1..-1]\n end\n end.join(' ')\n\n if title[0] == title[0].downcase\n title = title[0].upcase + title[1..-1]\n end\n @title = title\n end",
"def title\n\t\tlowers = %w(a an and but in of the)\n\t\ttitle_array = @title.split\n\t\ttitle_array.each do |word|\n\t\t\tif lowers.include?(title_array[0])\n\t\t\t\tword.capitalize!\n\t\t\telsif lowers.include?(word)\n\t\t\t\tword\n\t\t\telse\n\t\t\t\tword.capitalize!\n\t\t\tend\n\t\tend\n\t\ttitle_array.join(\" \")\n\tend",
"def titleize(title)\n\tbook = Book.new\n\tbook.title = title\n\treturn book.title\nend",
"def title=(book_title)\n # words to ignore when capitalizing\n conjunctions = %w(and in the of a an)\n\n # put input title into an array\n titles = book_title.split(' ')\n\n # store capitalized words\n captialized_titles = []\n\n # iterate through each word in a given title\n # and if the word is not one of the conjuction\n # words, then capitalize it\n titles.each do |title|\n if conjunctions.include? title\n captialized_titles << title\n else\n temp_title = title.capitalize\n captialized_titles << temp_title\n end\n end\n\n # always capitalize the first character of the first word\n # for example the word 'the' is one of the conjuction word\n # but if its the first word n the title, make sure to capitalize it\n captialized_titles[0] = captialized_titles[0].capitalize\n\n # finally return the final capitalized title\n @title = captialized_titles.join(' ')\n end",
"def capitalize_title\n \t\tself.title = self.title.split(/\\s+/).map(&:downcase).\n map(&:capitalize).join(' ')\n end",
"def titlecase\n title_case = []\n # titleize first word in title separately \n #(might contain exception words)\n title_case.push titleize_word @title.split[0], true \n\n @title.split.drop(1).each do |word|\n title_case.push titleize_word(word)\n end \n\n title_case.join(\" \")\n end",
"def titleize(title)\n\ttitle_split = title.split(\" \")\n\ttitle_split.map do |word|\n\t\tif word == \"over\"\n\t\t\t#word = word\n\t\t\treturn word\n\t\telsif word == \"and\"\n\t\t\t#word = word\n\t\t\treturn word\n\t\telsif word == \"the\" && title_split[0] != word\n\t\t\t#word = word\n\t\t\treturn word\n\t\telse\n\t\t\treturn word.capitalize\n\t\tend\n\tend\nend",
"def title=(title)\n\t little_words = %w{a an and if in or of over the}\n\t split_str = title.split(\" \")\n\t#shortcut for creating arrays found in beginningruby\n\tsplit_str.map! do |x|\n\t\tif x == split_str.first\n\t\t\tx.capitalize\n\t\t\telsif little_words.include?(x)\n\t\t\t\tx\n\t\t\t\telse\n\t\t\t\t\tx.capitalize\n\t\t\t\tend\n\t\t\tend\n\t\t\t@title = split_str.join(\" \")\n\t\tend",
"def titleize(title)\n # split title into words\n\n little_words = %w[a and of over the]\n\n words = title.split.map.with_index do |word, idx|\n if !little_words.include?(word.downcase) || idx == 0\n word.capitalize\n else\n word.downcase\n end\n end\n\n words.join(' ')\nend",
"def cleanTitle(str)\n str.nil? and return str\n r = Sanitize.clean(str).strip\n str.empty? and return str\n r = (r[0].match(/[^\\w]/)) ? r[1..-1].strip : r\n r.sub(/^(The|A|An) /i, '').capitalize\nend",
"def title\n title_raw.downcase\n end",
"def titleize(s)\n\ttitle = s.capitalize\n\ttitle = title.split.map {|x| ((x != \"the\") && (x != \"and\") && (x != \"over\")) ?\n\t\t\tx.capitalize : x}.join(\" \")\nend",
"def title(title_input)\n words_no_cap = [\"and\", \"or\", \"the\", \"over\", \"to\", \"the\", \"a\", \"but\", \"is\", \"in\"]\n post_title = title_input.split(\" \").map {|word|\n if words_no_cap.include?(word)\n word\n else\n word.capitalize!\n end\n }\n post_title[0] = post_title[0].capitalize\n post_title.join(\" \")\n end",
"def title_case(title, minor_words = '')\n splitTitle = title.capitalize.split\n \n i = 1\n while i < splitTitle.length do\n word = splitTitle[i]\n\n if !minor_words.downcase.split.include?(word.downcase)\n splitTitle[i] = word.capitalize\n end\n \n i += 1\n end\n \n splitTitle.join(\" \")\n end",
"def titlecase_title\n self.title = self.title.titlecase\n end",
"def titlecase_title\n self.title=(title().titlecase())\n end",
"def title=(title)\n\t\twords = title.split(\" \")\n\t\t\n\t\t@title = words.map.with_index {|word, idx|\n\t\t\tif cap?(word) || idx == 0\n\t\t\t\t# If a word isn't in the don't cap list, we capitalize it, but first we need to see if it has a hyphen and test the sub-words in the hypenated word. It will also capitalize any hyphenated word if that word is at the beginning of the title\n\t\t\t\t#\n\t\t\t\tif word.include?(\"-\")\n\t\t\t\t\tword.split(\"-\").map!.with_index {|w, i| w.capitalize if cap?(word) || i == 0 }.join(\"-\")\n\t\t\t\telse\n\t\t\t\t\tword.capitalize\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tword\n\t\t\tend\n\t\t}.join(\" \")\n\tend",
"def titleize(title)\n sm_words = ['a', 'and', 'of', 'over', 'the']\n title.capitalize.split(\" \").map{ |wrd| sm_words.include?(wrd) ? wrd : wrd.capitalize }.join(\" \")\nend",
"def smart_titlecase\n small_re = %w( is a an and as at but by en for if in of on or the to v[.]? via vs[.]? ).join('|')\n\n # Original Perl version by: John Gruber (daringfireball.net) 2008-05-10\n # Adapted to Ruby by: Marshall Elfstrand (vengefulcow.com/ 2008-05-21\n # Improved and customized: Jacob Duffy (duffy.jp) 2011-01-25\n # License: http://www.opensource.org/licenses/mit-license.php\n\n # if source is all uppercase, use all lowercase instead. -- jpd\n string = (self.upcase == self)? self.downcase : self\n\n result = \"\"\n string.gsub('_', ' ').split(/( [:.;?!][ ] | (?:[ ]|^)[\"\"] )/x).each do |s|\n s.gsub!(/ \\b( [[:alpha:]] [[:lower:].'']* )\\b /x) do |w|\n # Skip words with inresult dots, e.g. \"del.icio.us\" or \"example.com\"\n (w =~ / [[:alpha:]] [.] [[:alpha:]] /x) ? w : w.capitalize\n end\n\n # Lowercase our list of small words:\n s.gsub!(/\\b(#{small_re})\\b/io) { |w| w.downcase }\n\n # If the first word in the title is a small word, then capitalize it:\n s.gsub!(/\\A([[:punct:]]*)(#{small_re})\\b/io) { |w| $1 + $2.capitalize }\n\n # If the last word in the title is a small word, then capitalize it:\n s.gsub!(/\\b(#{small_re})([[:punct:]]*)\\Z/io) { |w| $1.capitalize + $2 }\n\n # Append current substring to output\n result += s\n end #each\n\n # Special Cases:\n upcase_re = (Array(Duffy.configuration.upcase_custom) + Array(Duffy.configuration.upcase_default)).uniq.join(\"|\")\n\n # Names with apostrophes; O'Brian, De'Wayne. 3+ Skips \"I've\" \"Haven't\" etc.\n result.gsub!(/([A-Z][a-z]*)'([a-z]{3,})/) { \"#{$1}'#{$2.capitalize}\" }\n\n result.gsub!(/ V(s?)\\. /, ' v\\1. ') # \"v.\" and \"vs.\"\n\n result.gsub!(/([''])S\\b/, '\\1s') # 'S (otherwise you get \"the SEC'S decision\")\n\n result.gsub!(/\\b(#{upcase_re})\\b/i) { |w| w.upcase } unless upcase_re.blank?\n\n # Squash repeated whitespace characters\n result.gsub!(/\\s+/, ' ')\n\n # Strip leading / tailing whitespace and return\n result.strip\n end",
"def title_case(title, minor_words = nil)\n title = title.downcase.split(\" \")\n title.map! {|word| minor_words && minor_words.downcase.split(\" \").include?(word) ? word : word.capitalize}\n title[0] = title[0].capitalize if title[0]\n return title.join(\" \")\nend",
"def title\n name.capitalize.bold.sub('_', ' ')\n end",
"def citation_title(title_text)\n prepositions = [\"a\", \"about\", \"across\", \"an\", \"and\", \"before\", \"but\", \"by\", \"for\", \"it\", \"of\", \"the\", \"to\", \"with\", \"without\"]\n new_text = []\n title_text.split(\" \").each_with_index do |word, index|\n if (index == 0 and word != word.upcase) or (word.length > 1 and word != word.upcase and !prepositions.include?(word))\n # the split(\"-\") will handle the capitalization of hyphenated words\n new_text << word.split(\"-\").map! {|w| w.capitalize}.join(\"-\")\n else\n new_text << word\n end\n end\n new_text.join(\" \")\n end",
"def capitalize_title\n self.title.capitalize! if title\n end",
"def capitalize_title\n self.title = title.capitalize\n end",
"def titleize!(title)\n title.split.map { |word| word.gsub(word[0],word[0].upcase) }.join(' ')\nend",
"def title_case(title, *minor_words)\n minor_words = minor_words[0].split.map(&:capitalize) if minor_words[0]\n title.split.each_with_index do |word, ix| \n word.capitalize!\n word.downcase! if minor_words.include?(word) && ix != 0\n end.join(\" \")\nend",
"def titlecase\n first = true\n words = downcase.split(/(?<!\\w')\\b/)\n\n words.map.with_index do |word,i|\n if LOWERCASE_WORDS.include?(word) and i > 0 # leave LOWERCASE_WORDS lowercase, unless it's the first word.\n word\n else\n word.gsub(/^\\w/) { |c| c.upcase } # capitalize first letter\n end\n end.join('')\n end",
"def titlecase\n first = true\n words = downcase.split(/(?<!\\w')\\b/)\n\n words.map.with_index do |word,i|\n if LOWERCASE_WORDS.include?(word) and i > 0 # leave LOWERCASE_WORDS lowercase, unless it's the first word.\n word\n else\n word.gsub(/^\\w/) { |c| c.upcase } # capitalize first letter\n end\n end.join('')\n end",
"def titlecase()\r\n ignore_list = %w{of etc and by the for on is at to but nor or a via}\r\n capitalize_all_ex(ignore_list)\r\n end",
"def titleize(title)\n results = []\n #get all the words\n bad_words = ['a', 'and', 'or', 'of', 'over', 'the']\n words = title.split(' ')\n # iterate over words with INDEX\n words.each_with_index do |word, i|\n word.downcase!\n if i == 0\n results << word.capitalize\n elsif bad_words.include?(word)\n results << word\n else\n results << word.capitalize\n end\n end\n #capitalize if first word\n #capitalize unless the included in the bad list\n results.join(' ')\nend",
"def titleize\n self.underscore.humanize.gsub(/\\b(?<!['’`])[a-z]/) { $&.capitalize }\n end",
"def title_case(title, minor_words = '')\n # capitalize all words in the original title, split them up into\n # an array and check the elements against the minor_words array\n # if they match, return the word, otherwise capitalize them\n proper_title = title.capitalize.split.map do |word|\n minor_words.downcase.split.include?(word) ? word : word.capitalize\n end\n proper_title.join(' ') # join the elements of the array into a string\nend",
"def titleize(word)\n\tlittle_words = [\"a\", \"an\", \"the\", \"at\", \"by\", \"for\", \"in\", \"of\", \"on\",\"over\", \"to\", \"up\", \"and\", \"as\", \"but\", \"it\", \"or\", \"and\", \"nor\"]\n\ttitle =word.split.map {|w| little_words.include?(w)? w: w.capitalize!}\n\ttitle[0] = title[0].capitalize\n\ttitle.join(\" \")\nend",
"def capitalize_title\n self.title = title.capitalize if title.present?\n end",
"def title\n name.gsub(/_/, ' ')\n end",
"def titleize(word)\n humanize(underscore(word)).gsub(/\\b('?[a-z])/){ $1.capitalize }\n end",
"def titleize(a)\n\tword = a.split\n\tphrase = \"\"\n\tif word[1].empty?\n\t\treturn a.split[0]\n\telse \n\t\tword.each do |element|\n\t\t\tphrase = phrase + element.capitalize + \"\"\n\t\t\treturn phrase\n\t\tend\n\telse\n\tend\nend",
"def title_case(title)\n new_array = []\n split_sentence= title.split\n split_sentence.each do |word|\n # word.capitalize()\n new_array.push(word.capitalize)\n end\n new_array.join(\" \")\n end",
"def full_title(page_title)\n base_title = \"Scirate\"\n if page_title.empty?\n base_title\n else\n sanitize(\"#{base_title} | #{page_title}\")\n end\n end",
"def regulate_title\n self.title = self.title.strip\n self.title.downcase!\n end",
"def title\n Sanitize.clean(name).strip\n end",
"def titleize(title) \r\n title.en.titlecase\r\nend",
"def titleize(word)\n humanize(underscore(word)).gsub(/\\b('?[a-z])/) { $1.capitalize }\n end",
"def titleize(word)\n humanize(underscore(word)).gsub(/\\b('?[a-z])/) { $1.capitalize }\n end",
"def capitalize_title\n self.title.capitalize!\n end",
"def titleize(word)\n #humanize(underscore(word)).gsub(/\\b(?<!['`])[a-z]/) { $&.capitalize }\n humanize(underscore(word)).gsub(/\\b[\"'`]?[a-z]/) { $&.capitalize }\n end",
"def upcased_title\n title.upcase\n end",
"def upcased_title\n title.upcase\n end",
"def title=(new_title)\n new_title.capitalize!\n arr = ['over', 'the', 'and', 'in', 'of', 'a', 'an']\n @title = new_title.split(' ').map! { |word| arr.include?(word) ? word : word.capitalize }.join(' ')\n end",
"def titlecase\n\t\tsplit(/(\\W)/).map(&:capitalize).join\n\tend",
"def book_title\n self.part_of_title_by_type('Book')\n end",
"def normalized_title\n normalized(full_title)\n end",
"def title_case(title, minor_words = '')\n minor_words_arr = minor_words.downcase.split\n title_words = title.split\n title_words.each_with_index do |title_word, index|\n if index == 0 || !minor_words_arr.include?(title_word.downcase)\n title_words[index] = title_words[index].capitalize\n else\n title_words[index] = title_words[index].downcase\n end\n end\n title_words.join(' ')\nend",
"def title_case(title, minor_words='')\n\ttitle_array = title.downcase.split(' ')\n\tminor_words_array = minor_words.downcase.split(' ')\n\ttitle_array.map!{|e|\n\t\tif minor_words_array.include?(e) == false || title_array[0] == e\n\t\t\te.capitalize\n\t\telse \n\t\t\te\n\t\tend \n\t} \n\ttitle_array.join(' ')\nend",
"def titleize line\n \n separate_words = line.split\n \n # if there is only one word in the title\n # return title cased word \n if separate_words.count == 1\n return separate_words[0][0].upcase + separate_words[0].chars.drop(1).join\n end\n \n # for more than one word\n # convert first word into title case\n # irrespective of what the word is e.g., the, and over \n first_word = separate_words[0]\n separate_words[0].replace(first_word[0].upcase + first_word.chars.drop(1).join) \n\n separate_words.each do |word|\n if word != \"and\" and word != \"the\" and word != \"over\" # do not title case these words \n word.replace(word[0].upcase + word[1..word.size])\n end \n end\n separate_words.join(\" \")\nend",
"def title_case(title, minor_words = '')\n return '' if title.empty?\n \n title.downcase.split(' ').map.with_index do |word, idx|\n minor_words.downcase.split(' ').include?(word) && idx != 0 ? word : word.capitalize\n end.join(' ')\nend",
"def titleize str\n\t\treturn str\n\tend",
"def title=(new_title)\n @title= Book.titleize(new_title)\n end",
"def titleize(title)\n\n result = []\n\n excluded = ['a', 'and', 'of', 'over', 'the']\n arr = title.split\n\n arr.each_index {|i|\n if excluded.include?(arr[i]) && i != 0\n result << arr[i]\n else\n result << arr[i].capitalize\n end\n }\n\n result.join(\" \")\nend",
"def title_case\n\t\tself.split.collect{ |s| s.capitalize_first }.join(\" \")\n\tend",
"def titleize(str)\n str.capitalize!\n dont_capitalize = [\"and\", \"over\", \"the\", \"from\"]\n str.split(\" \").collect {|word| dont_capitalize.include?(word) ? word : word.capitalize}.join(\" \")\nend",
"def is_title_case\n if title.split.any?{|w|w[0].upcase != w[0]}\n errors.add(:title, \"Title must be in title case\")\n end\n end",
"def titleize(sentence)\n\tret = \"\"\n\twords = sentence.split(\" \")\n\n\t#These are the words NOT to be capitalized if they are not the first word\n\t#The test case includes over as a little_word\n\tlittle_words = [\"a\", \"an\", \"and\", \"the\", \"over\"]\n\n\twords.each_with_index do |word, i|\n\t\tif(i > 0)\n\t\t\tif(little_words.include?(word))\n\t\t\t\tret << word + \" \"\n\t\t\telse\n\t\t\t\tret << word.capitalize + \" \"\n\t\t\tend\n\t\telse\n\t\t\t#capitalize the first word, regardless of if it is a little_word\n\t\t\tret << word.capitalize + \" \"\n\t\tend\n\tend\n\n\tret[0..-2]\nend",
"def title_of(post_name)\n post_name[9..-1].gsub('_',' ').titleize\n end",
"def full_title(page_title)\n\t\tbase_title=\"StemLoops\"\n\t\tif page_title.empty?\n\t\t\tbase_title\n\t\telse\n\t\t\tbase_title+\" | \"+page_title\n\t\tend\n\tend",
"def titleize(word)\n\tparse = \"\"\n\tlittle = ['the', 'and', 'over']\n\t\n\t#Seems inefficient but breaks up and capitalizes and sets the words in a string\n\tword.split.each do |i|\n\t\tif little.include?(i)\n\t\t\tparse += i.downcase + \" \"\n\t\telse\n\t\t\tparse += i.capitalize + \" \"\n\t\tend\n\tend\n\n\tparse[0] = parse[0].upcase #Manually upcases the 1st char\n\treturn parse[0...-1]\nend",
"def normalize_title(title)\n title.gsub(/_/, ' ')\n end",
"def full_title(page_title)\n\t\tbase_title = \"dreamly\"\n\t\tif page_title.empty?\n\t\t\tbase_title\n\t\telse\n\t\t\t\"#{base_title} | #{page_title}\"\n\t\tend\n\tend",
"def title\n base_title = \"Bibliocloud\"\n if @title.nil?\n base_title\n else\n \"#{base_title} | #{@title}\"\n end\n end",
"def title\n\t\tbase_title = \"Black Market Books\"\n\t\tif @title.nil?\n\t\t\tbase_title\n\t\telse\n\t\t\t\"#{base_title} | #{@title}\"\n\t\tend\n\tend",
"def titleize(title)\n\n word = title.split(\" \")\n\n cap = []\n\n word.each do |letters|\n\n #checking for specific words/conditions\n #simplest/most readable means to implement\n #could also have each word in an array and check against the array\n if letters == \"i\"\n cap << letters.capitalize\n elsif letters == \"day\"\n cap << letters.capitalize\n elsif letters == \"eat\"\n cap << letters.capitalize\n elsif letters == \"man\"\n cap << letters.capitalize\n elsif letters.length >= 4 and word.index != 0\n cap << letters.capitalize\n else\n cap << letters\n end\n\n end\n\n\n#making sure that every first word is capitalized\n cap[0] = cap[0].capitalize\n\n#making sure that \"Over\" is not capitalized\n#this is not optimal nor dyanmic, and needs to\n#be improved upon\n\n if cap[2] == \"Over\"\n cap[2] = \"over\"\n end\n\n#putting everything back together for the return\n cap = cap.join(' ')\n cap = cap.to_s\n return cap\n end",
"def title_case title, minors=\"\"\n sentence = title.downcase.split()\n minor_words = minors.downcase.split()\n\n sentence.map.with_index do |word,i|\n minor_words.include?(word) && i!= 0 ? word : word.capitalize\n end.join(' ')\nend",
"def titleize_a_string(string)\nend",
"def titleize_a_string(string)\nend",
"def full_title(page_title = '')\n base_title = \"WriteIt\"\n if page_title.empty?\n base_title\n else\n page_title + \" | \" + base_title\n end\n end",
"def title_brief\n return '' unless @marc_record && @marc_record['245']\n subfieldA = @marc_record['245']['a'] || ''\n title = subfieldA.strip\n # return the cleaned up title\n trim_punctuation(title)\n end",
"def quick_title(song)\n File.basename(song, File.extname(song)).gsub(/^[^A-Za-z]+\\s+(\\w)/, \"\\\\1\")\n end",
"def titleize(name)\n lowercase_words = %w{a an the and but or for nor of over}\n name.split.each_with_index.map{|x, index| lowercase_words.include?(x) && index > 0 ? x : x.capitalize }.join(\" \")\nend",
"def titleize(word)\n words = word.split(\" \")\n little_words = [\"and\", \"or\", \"the\", \"but\", \"over\"]\n first_word = words.first\n\n words.each do |word|\n banned_word = false\n\n # Check if the word is a little word \n little_words.each do |banned|\n if(banned == word)\n banned_word = true\n end\n end\n\n # If its the first word of the title or not a banned word it can be capitalized\n if((first_word == word) || (banned_word == false))\n word.capitalize!\n end\n end\n words.join(\" \")\nend",
"def normalized_title\n t = self.title.presence || default_title\n t.gsub('.', '').strip\n end",
"def full_title(page_title)\n base_title = \"WebSchool\"\n if page_title.empty?\n base_title\n else\n \"#{page_title} - #{base_title}\"\n end\n end",
"def titleize\n self.gsub(/\\s/, \"_\").split('_').map(&:capitalize).join(' ')\n end",
"def full_title(page_title)\n base_title = \"ARealtor\"\n if page_title.empty?\n base_title\n else\n \"#{base_title} | #{page_title}\"\n end\n end",
"def titleize(sentence)\n\tsentence = sentence.split.map.with_index do|word,i| \n\t\tif i == 0\n\t\t\tword = word.capitalize\n\t\telsif word != \"and\" && word != \"the\"\t\n\t\t\tword = word.capitalize\n\t\telse \n\t\t\tword\n\t\tend\n\tend\n\treturn sentence.join(\" \")\nend",
"def titleize(title)\n title_array = title.split(\" \")\n for word in title_array\n if word == title_array[0]\n word = word.capitalize!\n elsif word.downcase == \"and\" or word.downcase == \"over\" or word.downcase == \"of\" or word.downcase == \"the\" or word.downcase == \"an\" or word.downcase == \"for\" or word.downcase == \"nor\" or word.downcase ==\"but\" or word.downcase ==\"or\" or word.downcase ==\"yet\" or word.downcase == \"so\" \n word = word.downcase!\n else word = word.capitalize!\n end\n end\n print title_array.join(\" \")\nend",
"def full_title(page_title)\n base_title = \"Anand Sampat\"\n if page_title.empty?\n base_title\n else\n \"#{base_title} | #{page_title}\"\n end\n end",
"def title_case(title, minor_words = '')\n title.capitalize.split().map{|a| minor_words.downcase.split().include?(a) ? a : a.capitalize}.join(' ')\nend",
"def full_title(page_title)\n base_title = \"Adit\"\n if page_title.empty?\n base_title\n else\n \"#{base_title} | #{page_title}\"\n end\n end",
"def smart_titlecase\n small_words = %w(a an and as at but by en for if in of on or the to v v. via vs vs. von)\n\n x = split(\" \").map do |word|\n # note: word could contain non-word characters!\n # downcase all small_words, capitalize the rest\n small_words.include?(word.gsub(/\\W/, \"\").downcase) ? word.downcase! : word.smart_capitalize!\n word\n end\n # capitalize first and last words\n x.first.smart_capitalize!\n x.last.smart_capitalize!\n # small words after colons are capitalized\n x.join(\" \").gsub(/:\\s?(\\W*#{small_words.join(\"|\")}\\W*)\\s/) { \": #{$1.smart_capitalize} \" }\n end",
"def title\n @title ||= Utilities.longest_common_substring_in_array(titles.values) \n @title = titles[:og_title] unless title_ok?\n @title = titles[:html_title] unless title_ok?\n @title = titles[:from_doc] unless title_ok?\n\n @title\n end",
"def titleize(s)\n my_words = s.split(\" \")\n cap_sentence = \"\"\n my_words.each {|w| cap_sentence << w.capitalize << \" \"} \n cap_sentence.chop\n\nend",
"def full_title(page_title)\n title = base_title\n\n Array(page_title).each do |var|\n title << (' | ' + var) unless var.empty? \n end\n\n title\n end",
"def titleize(string)\n\tlittle_words = [\"and\", \"over\", \"the\"]\n\n\teach_word = string.split(\" \")\n\teach_word.each { |word|\n\t\tword.capitalize! unless little_words.include?(word)\n\t}\n\t# capitalizes the first word regardless if it is a little_word or not\n\teach_word[0].capitalize!\n\teach_word.join(\" \")\nend",
"def full_title(page_title)\n page_title.blank? ? \"My Defi Pie\" : \"My Defi Pie | #{page_title}\"\n end",
"def titleize\n#\t\thumanize(underscore(self)).gsub(/\\b('?[a-z])/) { $1.capitalize }\n#\t\thumanize(self.underscore).gsub(/\\b('?[a-z])/) { $1.capitalize }\n\t\tself.underscore.humanize.gsub(/\\b('?[a-z])/) { $1.capitalize }\n\tend",
"def full_title(page_title)\n base_title = 'Vietnam Beauty Spots'\n if page_title.empty?\n base_title\n else\n \"#{base_title} | #{page_title}\"\n end\n end",
"def titleize\n arr = %w(a an the by to)\n upcase_arr = %w(DX EDA AEDG LPD COP)\n r = gsub('_', ' ').gsub(/\\w+/) do |match|\n match_result = match\n if upcase_arr.include?(match.upcase)\n match_result = upcase_arr[upcase_arr.index(match.upcase)]\n elsif arr.include?(match)\n match_result = match\n else\n match_result = match.capitalize\n end\n match_result\n end\n\n r\n end",
"def full_title(page_title)\n base_title = \"BH Herbarium\"\n if page_title.empty?\n base_title\n else\n \"#{base_title} | #{page_title}\"\n end\n end",
"def titleize(string)\n string.gsub(/[-_-]/, ' ').split(' ').map(&:capitalize).join(' ')\n end",
"def full_title(page_title)\n\t\tbase_title = \"Hybrid Edu\"\n\t\tif page_title.empty?\n\t\t\tbase_title\n\t\telse\n\t\t\t\"#{base_title} | #{page_title}\"\n\t\tend\n\tend",
"def title_folded_to_filename\n self[:title].gsub(/[^a-z0-9-]/) do |c|\n case c\n when /\\s+|\\./ then '-'\n when /[A-Z]+/ then c.downcase\n else ''\n end\n end.gsub(/\\-+/,'-')\n end"
] |
[
"0.8359545",
"0.8349746",
"0.83100075",
"0.80901784",
"0.7852844",
"0.77563936",
"0.7745889",
"0.7630952",
"0.7600611",
"0.7583136",
"0.753964",
"0.75297165",
"0.751997",
"0.7509409",
"0.7508735",
"0.74927",
"0.7492536",
"0.7445897",
"0.74411136",
"0.7408913",
"0.7407508",
"0.7397438",
"0.73731685",
"0.7372233",
"0.7353607",
"0.73341894",
"0.7326457",
"0.7326457",
"0.7317533",
"0.7317235",
"0.73151046",
"0.7304445",
"0.730047",
"0.7289584",
"0.7280402",
"0.7272265",
"0.7271632",
"0.72659904",
"0.72611576",
"0.7249614",
"0.7249354",
"0.72391796",
"0.7235801",
"0.7235801",
"0.72314817",
"0.7231274",
"0.72125995",
"0.72125995",
"0.72098917",
"0.7204267",
"0.71985584",
"0.719449",
"0.71839654",
"0.7181458",
"0.71779543",
"0.7168429",
"0.71661353",
"0.7159053",
"0.7157739",
"0.7125726",
"0.7121767",
"0.71188474",
"0.7107652",
"0.7105329",
"0.7092657",
"0.7092003",
"0.7071488",
"0.7064048",
"0.7059121",
"0.7055504",
"0.7049912",
"0.70497674",
"0.7034038",
"0.7034038",
"0.7033621",
"0.70311004",
"0.7027442",
"0.70182216",
"0.70147574",
"0.7011432",
"0.7011051",
"0.7009883",
"0.7002742",
"0.69991034",
"0.6997885",
"0.6996347",
"0.699587",
"0.69934326",
"0.6988297",
"0.6987235",
"0.698624",
"0.69817406",
"0.698152",
"0.69783634",
"0.6976555",
"0.69729835",
"0.6971132",
"0.69622433",
"0.69423234",
"0.6941959",
"0.6937291"
] |
0.0
|
-1
|
A palindrome is a word or sequence of words that reads the same backwards as forwards. Write a method that returns the length of the longest palindrome in a given string. If there is no palindrome longer than two letters, return false.
|
def longest_palindrome(string)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def longest_palindrome(string)\n string.length.downto(3) do |length|\n string.chars.each_cons(length) do |substr_arr|\n return substr_arr.length if palindrome?(substr_arr.join)\n end\n end\n false\nend",
"def longest_palindrome(string)\n\tcurrent_longest = \"\"\n\tif string.length < 3\n\t\treturn false\n\tend\n\t#This represents the overarching iteration through the string. \n\t#As a string must be at least length 3 to be a palindrome, no search is necessary\n\t#for the last 2 letters of the string\n\tfor x in 0...string.length-2 do\n\t\t#Note: Need to ensure that every matching letter is checked\n\t\t#First part of conditional removes spaces from consideration for palindrome-ness\n\t\tif string[x] != \" \" && string.slice(x+1...(string.length)).include?(string[x])\n\t\t\tsubstring = string.slice(x..(string.rindex(string[x])))\n\t\t\tif Palindrome?(substring) && substring.length > current_longest.length\n\t\t\t\tcurrent_longest = substring\n\t\t\t\t#If the longest palindrome is the entire string itself, return it\n\t\t\t\tif current_longest.length == string.length\n\t\t\t\t\treturn current_longest\n\t\t\t\tend\n\t\t\tend\n\t\t\t#Check the substring, without the last matched letter for palindrome\n\t\t\t#This is to account for second matched letters, but wastes runtime on\n\t\t\t#Some unnecessary operations\n\t\t\tsub_test = longest_palindrome(string.slice(x...(string.rindex(string[x]))))\n\t\t\tif sub_test && sub_test.length > current_longest.length\n\t\t\t\tcurrent_longest = sub_test\n\t\t\tend\n\t\tend\n\tend\n\treturn current_longest.length > 0 ? current_longest : false\nend",
"def longest_palindrome(string)\n longest = ''\n i = 0\n while i < string.length\n j = 1\n while (i + j) <= string.length\n x = string.slice(i, j)\n if (x == x.reverse) && (x.length > longest.length)\n longest = x\n end\n j += 1\n end\n i += 1\n end\n if longest.length == 1\n return false\n end\n longest.length\n\nend",
"def longest_palindrome(string)\n \nend",
"def longest_palindrome(string)\n string_arr = string.split(\"\")\n longest = 0\n substring = \"\"\n\n while string_arr.length > 0\n string_arr.each do |char|\n substring << char\n palindrome?(substring) && substring.length > longest ? longest = substring.length : next\n end\n\n string_arr.shift\n substring = \"\"\n end\n \n longest\nend",
"def longest_palindrome(string)\n pal_arr = get_palindromes(string)\n return false if pal_arr.empty?\n sorted_arr = pal_arr.sort_by {|el| el.length}\n \n sorted_arr[-1].length\n \n \nend",
"def longest_palindrome(string)\n\ti = 0\n\tlongest = \"\"\n\twhile i < string.length\n\t\tcurrent_palindrome = \"\"\n\t\tj = 1\n\t\twhile j <= string.length\n\t\t\tif palindrome?(string.slice(i,j))\n\t\t\t\tcurrent_palindrome = string.slice(i,j)\n\t\t\tend\n\n\t\t\tif longest == \"\" || current_palindrome.length > longest.length\n\t\t\t\tlongest = current_palindrome\n\t\t\tend\t\n\t\t\tj += 1\n\t\tend\n\t\ti += 1\n\tend\n\tlongest\nend",
"def longest_palindrome(string)\n longest_palindrome = false\n i = 0\n\n while i < string.length - 1\n j = i + 1\n\n while j < string.length\n curr_string = string[i..j]\n len = curr_string.length\n\n if is_palindrome?(curr_string)\n longest_palindrome = len if !longest_palindrome || len > longest_palindrome\n end\n\n j += 1\n end\n\n i += 1\n end\n\n longest_palindrome\nend",
"def longest_palindrome(string)\n longest_palindrome = false\n i = 0\n\n while i < string.length - 1\n j = i + 1\n\n while j < string.length\n curr_string = string[i..j]\n len = curr_string.length\n\n if is_palindrome?(curr_string)\n longest_palindrome = len if !longest_palindrome || len > longest_palindrome\n end\n\n j += 1\n end\n\n i += 1\n end\n\n longest_palindrome\nend",
"def longest_palindrome(string)\nend",
"def longest_palindrome(str)\n \nend",
"def longest_palindrome(str)\r\n pal = \"\"\r\n (0..str.size).each do |x|\r\n i = 1\r\n while (i < (str.size-x)) do\r\n\t if str[x,i].reverse == str[x,i]\r\n\t pal = str[x,i] if pal.size < str[x,i].size\r\n\t end\r\n\t i+= 1\r\n\tend\r\n end\r\n pal\r\nend",
"def longest_palindrome(string)\n for substring_length in string.length...3\n for check in 0..(string.length - sub_string)\n possible_palindrome = string[check...check+substring_length]\n if palindrome(possible_palindrome)\n return possible_palindrome\n end\n end\n end\n return false \nend",
"def longest_palindrome(s)\n result = ''\n \n for i in (0..s.length-1) do\n for j in (i..s.length-1) do \n result = s[i..j] if s[i..j].length > result.length && s[i..j] == s[i..j].reverse\n end\n end\n \n result\nend",
"def longest_palindrome s\n return 0 if s.empty?\n (s.length).downto(1).each do | i |\n s.split(\"\").each_cons(i).map do |c|\n return c.count if c == c.reverse\n end\n end\nend",
"def find_longest_palindrome(string)\n l = string.size\n l.downto(0) { |i|\n 0.upto(l) { |j|\n s = string.slice(j,i)\n return s if s == s.reverse && s.size > 1\n }\n }\nend",
"def longest_palindrome(s)\n max = \"\"\n 0.upto(s.size - 1).each { |i|\n odd = palindrome(s, i, i)\n even = palindrome(s, i, i + 1)\n \n return s if odd.size == s.size || even.size == s.size\n max = odd if odd.size > max.size\n max = even if even.size > max.size\n }\n\n max \nend",
"def longest_palindrome(str)\n\nend",
"def longest_palindrome(string)\n longest = \"\"\n i = 0\n j = 0\n\n while i < string.length\n while j < string.length\n if is_palindrome?(string[i..j]) && string[i..j].length > longest.length\n longest = string[i..j]\n end\n j += 1\n end\n i += 1\n j = i + 1\n end\n\n longest\nend",
"def longest_palindrome(string)\n best_palindrome_start = 0\n best_palindrome_len = 0\n\n 0.upto(string.length - 1).each do |start|\n # micro-optimization: don't look at substrings shorter than best\n # palindrome.\n len = best_palindrome_len + 1\n while start + len <= string.length\n if is_palindrome?(string, start, len)\n best_palindrome_start, best_palindrome_len = start, len\n end\n\n len += 1\n end\n end\n\n [best_palindrome_start, best_palindrome_start + best_palindrome_len - 1]\nend",
"def longest_palindrome(string)\n if string.length <= 1\n return string\n end\n\n i = 0\n string.length.downto(1).each do |length|\n # .. is inclusive\n (0..i).each do |start_index|\n if palindrome?(string.slice(start_index, length))\n return string.slice(start_index, length)\n end\n end\n\n i += 1\n end\n\n string[0]\nend",
"def largest_palindrome(string)\n palindromes(string).max {|a, b| a.size <=> b.size }\nend",
"def naive_longest_palindrome(s)\n longest = s[0]\n s.each_char.with_index do |ch_i, i|\n s.each_char.with_index do |ch_j, j|\n next if j < i\n possible_pal = s[i..j]\n if is_palindrome?(possible_pal)\n longest = possible_pal.length > longest.length ? possible_pal : longest\n end\n end\n end\n longest\nend",
"def longest_palindrome(s)\n return '' if s == ''\n arr = s.chars\n\n s.length.downto(1) do |char|\n palindrome = arr.each_cons(char).find { |tested| tested == tested.reverse }\n return palindrome.join if palindrome\n end\nend",
"def longest_palindrome(string)\n # Create a variable to store our results to be returned\n best_palindrome = nil\n \n # Loop through our string\n i = 0\n while i < string.length # to go through each letter in the string\n # create local variable\n length = 1 # assign first length to 1\n \n # Create second loop\n while (i + length) <= string.length # to slice out out the substring 0 + 1 <= 5\n # local variable\n substring = string.slice(i, length) # to define the substring string.slice(0, 1) => ab\n \n if palindrome?(substring) && (best_palindrome == nil || substring.length > best_palindrome.length)\n best_palindrome = substring\n end\n # substring becomes new best_palindrome if it meets 2 requirements:\n # 1. it is a palindrome\n # 2. it's (nil = to the first substring as best_palindrome) OR new substring is longer than current logest substring.\n \n length += 1 # increment length of substring at each starting index. (i.e. a, ab, abc, abcd, etc...)\n end\n \n i += 1 # then increment i to set each letter as startign index. (i.e. abcd, bcbd, cbd, etc...)\n end\n \n return best_palindrome\n end",
"def longest_palindrome(string)\n\n palindromes = []\n\n (0...string.length).each do |i|\n (i+1...string.length).each do |j|\n sub = string[i..j]\n palindromes << sub if sub == sub.reverse\n end\n end\n\n palindromes.sort_by(&:length).last \n\nend",
"def longest_palindrome(string)\n largest = ''\n (0...string.length).each do |i|\n (i + 1...string.length).each do |j|\n sub_str = string[i..j]\n if sub_str == sub_str.reverse\n if sub_str.length > largest.length\n largest = sub_str\n end\n end\n end\n end \n largest\nend",
"def longest_palindrome(string)\n longest = \"\"\n len = 2\n \n while len < string.length\n i = 0\n while i+len <= string.length\n if is_palindrome?(string[i...i+len])\n longest = [i, i+len-1]\n end\n i += 1\n end\n len += 1\n end\n\n longest\nend",
"def longest_palindrome(str)\n return 0 if str.empty?\n\n arr = str.chars\n substrings = []\n length = 1\n loop do\n arr.each_cons(length) { |set| substrings << set }\n length += 1\n break if length > arr.length\n end\n substrings.select { |set| set == set.reverse }.max_by(&:length).length\n p substrings\nend",
"def palindrome(string)\n (string.length <= 1) || ((string[0, 1] == string[-1, 1]) && palindrome(string[1..-2]))\nend",
"def palindrome?(string)\n if string.size <= 1\n true\n else\n string[0] == string[-1] && palindrome?(string[1..-2])\n end\nend",
"def palindrome?(string)\n return true if string.length == 1\n return true if string.length == 2 && string[0] == string[1]\n return true if string[0] == string[string.length-1] && palindrome?(string[1...-1])\n false\nend",
"def is_palindrome(s)\n return is_palindrome(s, 0, s.length - 1 )\nend",
"def longest_palindrom(str)\n return str if str.length <= 1\n\n result = ''\n (0...str.length - 1).each do |i|\n ((i + 1)...str.length).each do |j|\n substr = str[i, j]\n result = substr if is_palindrom?(substr) && (result.length < substr.length)\n end\n end\n result\nend",
"def palindrome?(str)\n n = str.size / 2\n (0..n).all? do |i|\n str[i] == str[str.size-1-i]\n end\nend",
"def palindrome?(str)\n matches = []\n str.size.times { |index| matches << (str[index] == str[-(index+1)]) }\n matches.all?(true) && matches.size > 1\nend",
"def is_palindrome?(string)\n (0...((string.length) / 2)).each do |left|\n return false unless string[left] == string[-(left + 1)]\n end\n return true\nend",
"def longest_palindrome(str)\n result = [0, \"\"]\n for i in (0..str.length - 1)\n p1 = expand(str, i, i) \n result = result[0] > p1.length ? result : [p1.length, p1]\n p2 = expand(str, i, i + 1) \n result = result[0] > p2.length ? result : [p2.length, p2]\n end\n result[1]\nend",
"def palindrome?(word)\n array_of_letters = word.downcase.split(\"\")\n count_front = 0\n count_back = word.length - 1\n # Match the first letter with the last, if they are the same then step through the word\n while count_front < count_back\n if array_of_letters[count_front] == array_of_letters[count_back]\n count_front += 1\n count_back -= 1\n else\n return false\n end\n end\n return true\nend",
"def check_palindrome(s)\n for i in 0...(s.length/2).floor\n if s[i] != s[s.length-i-1]\n return false\n end\n end\n return true\nend",
"def longest_palindrome(string)\n length = string.length\n while true\n (0..(string.length - length)).each do |i|\n word = string[i...(i + length)]\n return [i, (i + length - 1)] if is_palindrome?(word)\n end\n length -= 1\n end\nend",
"def palindrome (word)\n if word.length == 1 || word.length == 0 #baseline, where it ends\n true\n else\n if word[0] == word[-1]\n palindrome(word[1..-2])\n else\n false\n end\n end\nend",
"def palindrome?(str)\n (str.length - 1).downto(0).map { |i| str[i] }.zip(str.chars).all? { |a, b| a == b }\nend",
"def longest_palindrome(s)\n left = 0\n right = 0\n for i in 0...s.length do\n odd = length_from_center(s, i, i)\n even = length_from_center(s, i, i + 1)\n longest = [odd, even].max\n if longest > right - left\n left = i - (longest - 1) / 2\n right = i + longest / 2\n end\n end\n return s[left..right]\n end",
"def is_palindrome(s)\n if s.length < 2\n return true\n elsif s[0] != s[-1]\n return false\n else\n return is_palindrome(s[1..-2])\n end\nend",
"def palindrome (word)\n word.length.times do |n|\n if (word[n] != word[word.length - n - 1]) \n return false\n end\n end\n return true\nend",
"def is_palindrome(s)\n return true if s.length <= 1\n return pal(s, 0, (s.length - 1))\nend",
"def is_palindrome?(string)\n counter = 0\n \n if string.length == 0 || string.length == 1\n return counter\n elsif string[0]==string[-1]\n is_palindrome?(string[1..-2])\n counter += 1\n\n elsif string[0]!=string[-1]\n is_palindrome?(string[1..-1]) \n\n else\n false\n end \nend",
"def valid_palindrome(str)\n l_ndx = 0\n r_ndx = str.size - 1\n while l_ndx < r_ndx\n unless str[l_ndx] == str[r_ndx]\n return palindromic?(str, l_ndx, r_ndx - 1) || palindromic?(str, l_ndx + 1, r_ndx)\n end\n\n l_ndx += 1\n r_ndx -= 1\n end\n\n true\nend",
"def is_palindrome(s)\n if s.length <= 1\n return true\n end\n\n if s[0] != s[-1]\n return false\n end\n return is_palindrome(s[1...-1])\nend",
"def is_palindrome?(string)\n if string.length == 1 || string.length == 0\n true\n else\n if string[0] == string[-1]\n is_palindrome?(string[1..-2])\n else\n false\n end\n end\nend",
"def is_palindrome(s)\n if s.length < 2\n return true\n elsif s[0] != s[-1]\n return false\n else\n return is_palindrome(s[1..-2])\n end\nend",
"def is_palindrome(word)\n forward = 0\n backword = word.length - 1\n while forward <= backword\n if word[forward] != word[backword]\n return false\n end\n forward += 1\n backword -= 1\n end\n return true\nend",
"def almost_palindrome_checker(string)\n p1 = 0\n p2 = string.length - 1\n array = string.split('')\n\n while p1 < p2\n return palindrome_checker(array, p1, p2 - 1) || palindrome_checker(array, p1 + 1, p2) if array[p1] != array[p2]\n\n p1 += 1\n p2 -= 1\n end\n\n true\nend",
"def palindrome? x\n # convert into string\n y = x.to_s\n look = y.length / 2\n y[0..(look-1)] == y[-look..-1].reverse\nend",
"def palindrome?(str)\n length = str.length\n half1 = str.slice(0, length/2)\n if length.odd?\n half2 = str.slice(length/2 + 1, length)\n else\n half2 = str.slice(length/2, length)\n end\n half1 === half2.reverse\nend",
"def palindrome_r(word)\n if word.length == 1 or word.length == 0\n true\n else\n if word[0] == word[-1]\n palindrome_r(word[1..-2])\n else\n false\n end\n end\nend",
"def palidrome?(word)\n j = word.length - 1\n half_length = word.length / 2\n\n half_length.times do |i|\n if word[i] != word[j]\n return false\n end\n j -= 1\n end\n\n return true\nend",
"def is_palindrome(str)\n return false if str.empty?\n 0.upto(str.size / 2) do |i|\n return false if str[i] != str[-i - 1]\n end\n return true\nend",
"def is_palindrome(s)\n if s.length == 0 || s.length == 1\n return true\n else\n first_and_last_match = (s[0] == s[-1])\n s[0] = ''\n s[-1] = ''\n return first_and_last_match && is_palindrome(s)\n end\nend",
"def is_palindrome(s)\n return true if s.length <= 1\n return s[0] == s[-1] && is_palindrome(s[1,s.length - 2])\nend",
"def palyndrome?(str)\n (0..( (str.size - 1) / 2 )).each do |i|\n return false if str[i] != str[ str.size - 1 - i ]\n end\n true\n end",
"def palindrome?(string)\n\n idx1 = 0\n idx2 = -1\n\n while idx1 < string.length\n if string[idx1] != string[idx2] \n return false\n end\n\n idx1 += 1\n idx2 -= 1\n end\n\n return true\nend",
"def is_palindrome(s)\n return true if s.length <= 1\n return false if s[0] != s[-1]\n return is_palindrome(s[1...-1])\nend",
"def is_palindrome(s)\n return true if s.length <= 1\n return false if s[0] != s[-1]\n return is_palindrome(s[1...-1])\nend",
"def palindrome?(string)\n first = 0\n last = string.length - 1\n \n while first < last do\n return false if string[first] != string[last]\n first += 1\n last -= 1\n end\n true\nend",
"def is_palindrome(s)\n return true if s.empty?\n return false if s[0] != s[-1]\n return is_palindrome(s[1...-1])\n \n # To do this without creating new strings, make a helper method\n # that accepts additional parameters for left_char and right_char and increments\n # them inward each time, like I did for reverse_in_place with helper_reverse\nend",
"def is_palindrome(s)\n return true if s.length == 0\n return palindrome_helper(s, 0, s.length - 1)\nend",
"def palindrome(string)\n if string.length == 1 || string.length == 0\n true\n elsif string[0] == string[-1]\n palindrome(string[1..-2])\n else\n false\n end\nend",
"def is_palindrome(s) \n return true if s.length < 2\n return false if s[0] != s[-1]\n\n return is_palindrome(s[1..-2])\nend",
"def palindrome?(str)\n i = 0\n while i < str.length/2\n if str[i] != str[str.length - i - 1]\n return false\n end\n i = i + 1\n end\n return true\nend",
"def is_palindrome(s)\n if s.length < 2 \n return true \n elsif s[0] != s[-1]\n return false\n else \n return is_palindrome(s[1..-2])\n end\nend",
"def longest_palindrome(s)\n return s if s.length == 1\n previous = s[0]\n\n all_same = true\n z = 0\n counter = 0\n while z < s.length\n if s[z] == previous\n counter += 1\n else\n tmp_longest = previous * counter\n longest = tmp_longest if tmp_longest.length > longest.length\n previous = s[z]\n counter = 1\n break if counter > s.length / 2\n end\n z += 1\n end\n return previous * counter if all_same || counter > s.length / 2\n\n longest = ''\n i = 0\n while i < s.length\n starting_letter = s[i]\n matching_hash = {}\n matching_hash[i] = starting_letter\n\n j = i + 1\n while j < s.length\n if s[j] == starting_letter\n matching_hash[j] = s[j]\n end\n j += 1\n end\n\n i += 1\n\n indices = matching_hash.keys\n next if indices.length == 1\n next if (indices[-1] - indices[0]) < longest.length\n\n first_index = matching_hash.first[0]\n\n k = 0\n valid_sequence = true\n while k < (indices.length / 2 - 1)\n first_dist = indices[k + 1] - indices[k]\n second_dist = indices[indices.length - 1 - k] - indices[indices.length - 2 - k]\n if first_dist != second_dist\n valid_sequence = false\n break\n end\n k += 1\n end\n\n next if !valid_sequence\n\n matching_hash.delete_if {|key,v| (key != first_index) && (key - first_index < longest.length)}\n indices = matching_hash.keys\n\n n = 1\n last_index = indices[-1]\n running_str = ''\n while first_index + n < ((last_index - first_index) / 2)\n matching_hash.each do |key, v|\n if key == first_index\n running_str = matching_hash[key] << s[key + n]\n else\n checking_str = matching_hash[key] << s[key - n]\n matching_hash.delete(key) if checking_str != running_str\n end\n end\n n +=1\n end\n\n matching_hash.values.each do |value|\n longest = value if value.length > longest.length\n end\n end\n puts \"longest: #{longest}\"\n return longest\nend",
"def palindrome?\n str = self.to_s\n len = str.size\n\n if len.odd?\n str[0, len/2] == str[len/2 + 1, len/2].reverse\n else\n str[0, len/2] == str[len/2, len/2].reverse\n end\n end",
"def is_palindrome(s)\n\tl = 0\n\tr = s.length - 1\n\treturn pal_helper(s, l, r)\nend",
"def palindrome1?(str)\n if str.size <= 1\n true\n else\n str[0] == str[-1] ? palindrome1?(str[1..-2]) : false\n end\nend",
"def is_palindrome(s)\n if s.length == 0\n return true\n else \n if s[0] == s[-1]\n return is_palindrome(s[1..-2])\n else\n return false\n end\n end\nend",
"def palindrome(string)\n return true if string.length <= 1\n\n if string[0] == string[-1]\n palindrome(string[1..-2])\n else\n false\n end\nend",
"def is_palindrome(string)\n joined_str = string.gsub(/[^0-9a-z]/i, '').downcase\n reverse_str = reverser(joined_str.clone)\n difference_count = 0\n joined_str.length.times do |i|\n difference_count += 1 if joined_str[i] != reverse_str[i]\n end\n\n if difference_count != 0\n return false\n else\n return true\n end\n\nend",
"def palindrome?(pal_str)\n char_list = pal_str.split\n reverse_list = Array.new\n char_list.length.times do\n reverse_list.push(char_list.pop) unless char_list == []\n end\n reversed_string = reverse_list.join('')\n true if pal_str == reversed_string\nend",
"def palindrome(str)\n if str.length == 1 || str.length.zero?\n true\n elsif str[0] == str[-1]\n palindrome(str[1..-2])\n else\n false\n end\nend",
"def word_palindrome(word)\n\n index = 0\n end_point = -1\n\n while index < word.length/2\n return false if word[index] != word[end_point-index]\n index+=1\n end\n return true\n\nend",
"def palindrome?(substr)\n substr == substr.reverse && substr.length > 1\nend",
"def is_palindrome(s)\n if s == \"\"\n return true\n end\n if s[0] != s[-1]\n return false\n end\n return is_palindrome(s[1...-1])\nend",
"def is_palindrome(s)\n if s.length <= 1\n return true\n elsif s[0] != s[-1] \n return false\n else \n return is_palindrome(s[1..-2])\n end \nend",
"def palindrome(str)\n return true if str.size == 1 || str.size == 0 # base case\n if str[0] == str[-1]\n palindrome(str[1..-2]) # getting closer to base case\n else\n false\n end\nend",
"def is_palindrome?(string)\n i = 0\n\n while i < string.length / 2\n if string[i] != string[string.length - 1 - i]\n return false\n end\n i += 1\n end\n\n return true\nend",
"def is_palindrome(s)\n return true if s.length <= 1\n if s[0] == s[-1]\n return is_palindrome(s[1...-1])\n else\n return false\n end\n end",
"def is_palindrome(s)\n return true if s.empty?\n\n if s[0] == s[-1]\n return is_palindrome(s[1..-2]) \n else \n return false\n end \nend",
"def is_palindrome(s)\n return true if s.empty? || s.length == 1\n return is_palindrome(s[1..-2])if s[0] == s[-1]\n return false\nend",
"def palindrome?(string)\n \n begin_index = 0\n end_index = string.length - 1\n \n if string.length == 1\n return true\n end\n \n while begin_index < end_index || begin_index != end_index\n if string[begin_index] == string[end_index]\n begin_index += 1\n end_index -= 1\n palindrome = true\n else\n begin_index = end_index\n palindrome = false\n end\n end\n return palindrome\n \nend",
"def is_palindrome(string)\n return true if string.empty? || string.length == 1\n\n front = 0\n back = string.length - 1\n\n while back > front\n return false if string[front] != string[back]\n front += 1\n back -= 1 \n end\n return true\nend",
"def longest_palindrome(s)\n string_hash = Hash.new(0)\n \n s.each_char do |char|\n string_hash[char] += 1\n end\n \n beginning_count = 0\n middle_count = 0\n \n string_hash.keys.each do |key|\n if string_hash[key] % 2 == 1\n middle_count = 1\n end\n \n beginning_count += string_hash[key] / 2\n end\n \n beginning_count * 2 + middle_count\nend",
"def palindrome?(str)\n str = str.downcase\n\n if str.length == 0 || str.length == 1\n true\n elsif str[0] == str[-1]\n palindrome?(str[1..-2])\n true\n else\n false\n end\nend",
"def is_palindrome(s)\n if s == \"\" || s.length == 1\n return true\n elsif s[0] != s[-1]\n return false\n else\n return is_palindrome(s[1..-2])\n end\nend",
"def is_palindrome(string) # a b c d c b a, m u m s, e a a e\n left = 0\n right = string.length - 1\n\n while left <= right # 0 != 6, 1 != 5, 2 != 4, 3 != 3\n return false if string[left] != string[right]\n if string[left] == string[right]\n left += 1\n right -= 1\n end\n end\n\n return true if left > right\n false\nend",
"def palindrome(string)\n word_array = string.split(\"\")\n\n word_array.each_with_index do |letter,index|\n if letter[index] == letter[-index]\n return true\n end\n end\n end",
"def palindrome?(string)\n new_string = \"\"\n i = 1\n string.length.times do\n new_string << string[-i]\n i += 1\n end\n string == new_string\nend"
] |
[
"0.8752934",
"0.8530597",
"0.8502323",
"0.8410809",
"0.8396968",
"0.83964324",
"0.83857787",
"0.83709925",
"0.83709925",
"0.83675176",
"0.8297208",
"0.8292763",
"0.82502997",
"0.82332367",
"0.8233189",
"0.8228377",
"0.8207186",
"0.8176335",
"0.81715465",
"0.8167062",
"0.81586546",
"0.8130788",
"0.8109412",
"0.8010037",
"0.79882944",
"0.79662913",
"0.7892889",
"0.78873086",
"0.78431976",
"0.7828388",
"0.7802447",
"0.7801656",
"0.7798914",
"0.779514",
"0.7783596",
"0.7775102",
"0.77750325",
"0.7772122",
"0.7768677",
"0.77611583",
"0.77605486",
"0.775927",
"0.77486277",
"0.7737335",
"0.7722441",
"0.7710621",
"0.770985",
"0.7696086",
"0.76890033",
"0.76864237",
"0.7684334",
"0.76793164",
"0.76788616",
"0.7676491",
"0.76681703",
"0.7667145",
"0.76652867",
"0.7657843",
"0.76561886",
"0.7651859",
"0.765142",
"0.7637589",
"0.7635939",
"0.76344615",
"0.76344615",
"0.76311713",
"0.76304775",
"0.7627777",
"0.7625434",
"0.76247305",
"0.7621903",
"0.76184005",
"0.76154953",
"0.760732",
"0.760582",
"0.7602094",
"0.7602059",
"0.75876707",
"0.7584196",
"0.75812155",
"0.75737184",
"0.75578445",
"0.75565773",
"0.7550979",
"0.7546632",
"0.7546456",
"0.75344217",
"0.7520937",
"0.75199836",
"0.7507461",
"0.7497141",
"0.7496718",
"0.74943936",
"0.74907005",
"0.7485878",
"0.7484661",
"0.7481549",
"0.74790555"
] |
0.8286128
|
14
|
Write a function `anagrams(str1, str2)` that takes in two words and returns a boolean indicating whether or not the words are anagrams. Anagrams are words that contain the same characters but not necessarily in the same order. Solve this without using `Arraysort` or `Arraysort_by`.
|
def anagrams(str1, str2)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def anagrams?(str1, str2)\n return false unless str1.length == str2.length\n\n str1.each_char do |chr|\n return false unless str2.count(chr) == str1.count(chr)\n end\n\n true\nend",
"def are_anagrams?(str1, str2)\n # if different length, then can't possibly match\n return false if str1.length != str2.length\n\n str1_arr = str1.split('').sort\n str2_arr = str2.split('').sort\n 0.upto(str1_arr.length-1) do |i|\n return false if str1_arr[i] != str2_arr[i]\n end\n true\nend",
"def anagrams_maybe_better(string1, string2)\n return true if string1.chars.sort == string2.chars.sort\n false\nend",
"def anagrams?(word1, word2)\n if word1.length != word2.length\n return false\n end\n word1.each_char do |ele|\n if !word2.include?(ele)\n return false\n end\n end\n return true\nend",
"def anagrams?(s1, s2)\n return false if s1.downcase == s2.downcase\n \n a1 = s1.downcase.delete(' ').chars.sort\n a2 = s2.downcase.delete(' ').chars.sort\n\n a1 == a2\nend",
"def anagrams?(str1, str2)\n make_tally(str1) == make_tally(str2)\nend",
"def anagrams?(word1, word2)\n\tarr1 = word1.split(\"\")\n \tarr2 = word2.split(\"\")\n\n count = Hash.new(0)\n \tcount2 = Hash.new(0)\n\n \tarr1.each {|word| count[word] += 1}\n \tarr2.each {|word| count2[word] += 1}\n\n if count == count2\n return true\n else\n return false\n end\nend",
"def anagrams?(word1, word2)\n w1 = Hash.new(0)\n word1.each_char do |char|\n w1[char] += 1\n end\n w2 = Hash.new(0)\n word2.each_char do |char|\n w2[char] += 1\n end\n return w1 == w2\nend",
"def are_anagrams_v2?(str1, str2)\n return false if str1.length != str2.length\n str1_char_count = Array.new(256, 0)\n str2_char_count = Array.new(256, 0)\n str1.each_byte do |c|\n str1_char_count[c] += 1\n end\n\n str2.each_byte do |c|\n str2_char_count[c] += 1\n end\n\n 0.upto(str1_char_count.length-1) do |i|\n return false if str1_char_count[i] != str2_char_count[i]\n end\n true\nend",
"def anagrams(str1, str2)\n letters = Hash.new(0)\n\n str1.split('').each do |char|\n letters[char] += 1\n end\n\n str2.split('').each do |char|\n letters[char] -= 1\n end\n\n letters.all? { |_, v| v.zero? }\nend",
"def check_anagrams(s1, s2)\n return false if s1.length != s2.length\n s1.chars.sort == s2.chars.sort\nend",
"def are_anagrams(firstword, secondword)\n firstword.downcase.split(\"\").sort.join == secondword.downcase.split(\"\").sort.join\nend",
"def anagrams(word1, word2)\n length = word1.length\n if word1.length == word2.length\n array = []\n while length>=0\n array.push(word1[length-1])\n length -= 1\n end\n length2 = word2.length\n while length2 >= 0\n if array.include?(word2[length2 - 1])\n length2 -= 1\n else\n return false\n end\n end\n return true\n else\n return false\n end\nend",
"def anagrams?(a_string, another_string)\n # TODO: implement the obvious method to test if two words are anagrams\n puts a_string_sorted = clean(a_string.downcase.chars.sort.join)\n puts another_string_sorted = clean(another_string.downcase.chars.sort.join)\n a_string_sorted == another_string_sorted\nend",
"def anagrams?(word1, word2)\n return char_count(word1) == char_count(word2)\nend",
"def anagrams?(word1, word2)\n return char_count(word1) == char_count(word2)\nend",
"def anagrams?(word1, word2)\n\treturn hashLetters(word1) == hashLetters(word2)\nend",
"def anagrams?(word1, word2)\r\n return charCount(word1) == charCount(word2)\r\nend",
"def anagrams?(word1, word2)\n return char_count(word1) == char_count(word2)\nend",
"def anagrams?(word1, word2)\n return char_count(word1) == char_count(word2)\nend",
"def anagrams?(word1, word2)\n return char_count(word1) == char_count(word2)\nend",
"def anagrams?(word1, word2)\n\n # let's use hash count \n counter1 = Hash.new(0)\n\n word1.each_char do |char|\n counter1[char] += 1\n end \n \n counter2 = Hash.new(0)\n word2.each_char do |char|\n counter2[char] += 1\n end \n\n if counter1 == counter2\n return true \n end \n\n return false\nend",
"def are_anagrams?( s1, s2 )\r\n\ttransformS1 = s1.downcase.split('').sort.join('')\r\n\ttransformS2 = s2.downcase.split('').sort.join('')\r\n\treturn transformS1 == transformS2\r\nend",
"def are_anagrams?(word1, word2)\n #si las palabras son anagramas regresa true de lo contrario regresa false\n if canonical(word1) == canonical(word2) then true else false end\nend",
"def is_anagram(w1, w2)\n\tw1.downcase.split(\"\").sort.join == w2.downcase.split(\"\").sort.join\nend",
"def str_anagram(str1, str2)\n if str1.chars.sort.join.downcase == str2.chars.sort.join.downcase\n puts true\n else\n puts false\n end\n end",
"def check_anagrams(first_words, second_words)\n first_words.each_with_index do |word, index|\n if word.split('').sort == second_words[index].split('').sort\n puts true\n else\n puts false\n end\n end\nend",
"def anagrams?(word1, word2)\n\treturn char_count(word1) == char_count(word2)\n \nend",
"def is_anagram(w1, w2)\n\tif w1.split(//).sort == w2.split(//).sort\n\t\treturn true\n\tend\n\treturn false\nend",
"def anagrams(stringA, stringB)\n compare_strA = stringA.downcase\n .gsub(/[^\\w]/, '')\n .split('')\n .sort { |a, b| a <=> b}\n .join('')\n \n compare_strB = stringB.downcase\n .gsub(/[^\\w]/, '')\n .split('')\n .sort { |a, b| a <=> b}\n .join('')\n \n compare_strA == compare_strB\nend",
"def is_anagram(s1, s2)\n\ts1 = s1.downcase.split('').sort\n\ts2 = s2.downcase.split('').sort\n\ts1 == s2 ? true : false \t \nend",
"def anagrams(str1, str2)\n hash_1 = Hash.new(0)\n hash_2 = Hash.new(0)\n str1.each_char { |char| hash_1[char] += 1 }\n str2.each_char { |char| hash_2[char] += 1 }\n hash_1 == hash_2\nend",
"def string_anagrams(str1, str2)\n return false if str1 == nil || str2 == nil\n return false if str1.length != str2.length\n\n ascii_options = Array.new(256)\n 256.times do |i|\n ascii_options[i] = 0\n end\n\n str1.length.times do |i|\n ascii_options[str1[i].ord] += 1\n end\n\n str2.length.times do |i|\n ascii_options[str2[i].ord] -= 1\n return false if ascii_options[str2[i].ord] < 0\n end\n\n return true\nend",
"def anagrams2(str1, str2)\n arr1 = str1.split(\"\")\n arr2 = str2.split(\"\")\n arr1.each do |el|\n i = arr2.index(el)\n return false if i.nil?\n arr2.delete_at(i)\n end\n arr2.empty?\nend",
"def valid_anagram(str1, str2)\n str1 = str1.split('').sort\n str2 = str2.split('').sort\n if str1 == '' && str2 == ''\n true\n else\n str1 == str2\n end\nend",
"def anagram str1, str2\n str1.downcase.chars.sort.join == str2.downcase.chars.sort.join\nend",
"def is_anagram word1, word2\n \tpermute = permute_word(word1)\n \tpermute.each do |w|\n \t puts w.join\n \t if w.join.eql?(word2)\n \t \treturn true\n \t end\n \tend\n \treturn false\n end",
"def anagrams?(str_sym_or_int_1, str_sym_or_int_2)\n str_sym_or_int_1.to_s.downcase.delete(' ').split('').sort.join == str_sym_or_int_2.to_s.downcase.delete(' ').split('').sort.join\nend",
"def anagram?(s1,s2)\n\ts1.chars.sort == s2.chars.sort\nend",
"def anagramI?(str1, str2)\n anagrams = str1.split(\"\").permutation.to_a.map { |anagram| anagram.join(\"\") }\n anagrams.include?(str2)\nend",
"def anagrams_one_hash?(str1, str2)\n letter_count = Hash.new(0)\n str1.each_char { |char| letter_count[char] += 1 }\n str2.each_char { |char| letter_count[char] -= 1 }\n\n letter_count.each_value.all? { |val| val == 0 }\nend",
"def first_anagrams_2(str_1, str_2)\n string_1 = str_1.split('')\n string_2 = str_2.split('')\n\n return false if str_1.length != str_2.length\n\n string_1.each do |char|\n idx = string_2.find_index(char)\n if idx == nil\n return false\n else\n string_2.delete_at(idx)\n end\n end\n\n return true if string_2.empty?\nend",
"def anagrams_better(string1, string2)\n string2 = string2.chars\n return false if string1.length != string2.length\n string1.chars.each do |ch|\n idx = string2.index(ch)\n unless idx.nil?\n string2.delete_at(idx)\n end\n end\n return true if string2.empty?\n false\nend",
"def anagram3(str1, str2)\n str1 = str1.downcase.chars.sort.join\n str2 = str2.downcase.chars.sort.join\n\n return str1 == str2\nend",
"def anagrams(str1, str2)\n hash1 = Hash.new(0) \n hash2 = Hash.new(0) \n\n str1.each_char do |el|\n hash1[el] += 1\n end\n\n str2.each_char do |el|\n hash2[el] += 1\n end\n\n hash1 == hash2\nend",
"def anagram(string1, string2)\n puts \"Are #{string1} and #{string2} anagrams?\"\n if string1.length != string2.length\n return false\n else\n string1.length.times do |i|\n if !string2.include? string1[i] \n return false\n end\n end\n return true\n end\nend",
"def first_anagram?(str1, str2)\n all_anagrams1 = str1.split(\"\").permutation.to_a.map(&:join)\n # (n) + (n!) + (n!) + (n!*n) => reduces down to O(n *n!) \n # ^\n #bottleneck\n all_anagrams1.include?(str2) # O(n!*n) \nend",
"def anagram?(s1, s2)\n\ts1_array = s1.split(\"\")\n\ts2_array = s2.split(\"\")\n\tif s1_array.sort == s2_array.sort\n\t\treturn true\n\telse\n\t\treturn false\n\tend\nend",
"def anagram?(a, b)\n a.chars.sort == b.chars.sort\nend",
"def anagram?(x, y)\n x.chars.sort == y.chars.sort\nend",
"def second_anagram?(str1, str2)\n str1_chars = str1.chars\n str2_chars = str2.chars\n\n str1.chars.each do |ch1|\n str1_chars.delete_if { str2.include?(ch1) }\n end\n\n str2.chars.each do |ch1|\n str2_chars.delete_if { str1.include?(ch1) }\n end\n\n str1_chars == str2_chars\nend",
"def first_anagram?(str1, str2)\n anagrams = str1.split(\"\").permutation.to_a \n anagrams.include?(str2.split(\"\"))\nend",
"def anagram3(str1, str2) #O(nlogn)\n split1 = str1.split(\"\").sort #O(n) + O(nlogn) = O(nlogn)\n split2 = str2.split(\"\").sort #O(n) + O(nlogn) = O(nlogn)\n\n split1 == split2 #O(n)\nend",
"def anagrams?(word1, word2)\n\nend",
"def anagrams?(word1, word2)\n\nend",
"def anagram3(string, string2)\n(string.chars.sort.join == string2.chars.sort.join) ? true : false\nend",
"def anagram?(phrase_one, phrase_two)\n phrase_one.split('').sort == phrase_two.split('').sort\n end",
"def anagram (str1, str2)\n # to downcase and remove non alphanumeric characters \n str1_hash = str_to_hash(str1.downcase.gsub(/(\\W)/, \"\"))\n str2_hash = str_to_hash(str2.downcase.gsub(/(\\W)/, \"\"))\n\n if str1_hash == str2_hash\n return true\n else\n return false\n end\n\nend",
"def first_anagram?(str1, str2)\n all_anagrams(str1).include?(str2)\nend",
"def third_anagrams?(str1,str2)\n str1.split(\"\").sort.join(\"\") == str2.split(\"\").sort.join(\"\")\nend",
"def anagram?(a, b)\n return false unless a.length == b.length\n a.chars.sort == b.chars.sort\nend",
"def anagramIII?(str1, str2)\n str1_arr = str1.split(\"\")\n str2_arr = st2.split(\"\")\n str1_arr.sort == str2_arr.sort\nend",
"def not_better_by_much_anagram(string1, string2)\n hsh1 = Hash.new(0)\n hsh2 = Hash.new(0)\n\n string1.chars.each do |ch|\n hsh1[ch] +=1\n end\n\n string2.chars.each do |ch|\n hsh2[ch] +=1\n end\n\n return true if hsh1 == hsh2\n false\nend",
"def second_anagram?(string1, string2)\n s1char_arr = string1.chars\n s2char_arr = string2.chars\n return false if s1char_arr.length != s2char_arr.length\n s1char_arr.dup.each_with_index do |ch1, ind1|\n s2char_arr.dup.each_with_index do |ch2, ind2|\n if s1char_arr.include?(ch2)\n string1.delete!(ch2)\n string2.delete!(ch2)\n p string1\n p string2\n end\n end\n end\n\n string1.empty? && string2.empty?\nend",
"def anagram_3?(str1,str2)\n str1.chars.sort == str2.chars.sort\nend",
"def second_anagram?(str1, str2)\n str1.chars.each do |char1|\n str2.chars.each do |char2|\n if char1 == char2\n str1.delete!(char1)\n str2.delete!(char2)\n end\n end\n end\n return true if str1.empty?\n false\nend",
"def anagram_3?(word1, word2)\n return false if word1.length != word2.length\n arr1, arr2 = word1.split(\"\").sort, word2.split(\"\").sort\n (0...word1.length).all? { |idx| arr1[idx] == arr2[idx] }\nend",
"def anagram?\n chars1 = @input1.downcase.gsub(/[!@#$%^&*()-=_+|;':\",.<>?']/, '').split(\"\").sort\n chars2 = @input2.downcase.gsub(/[!@#$%^&*()-=_+|;':\",.<>?']/, '').split(\"\").sort\n if\n self.allwords?\n if\n chars1 == chars2\n return \"These words are anagrams!\"\n elsif\n self.antigrams?\n return \"These words are not anagrams but they are antigrams!\"\n elsif self.antigrams? == false\n return \"These words are neither anagrams nor antigrams!\"\n end\n else\n return \"You need to input actual words!\"\n end\n end",
"def third_anagram?(str1, str2)\n letters1 = str1.chars\n letters1.sort!\n letters2 = str2.chars\n letters2.sort!\n \n letters1 == letters2\nend",
"def anagram?(str1,str2)\r\n count = Hash.new(0)\r\n str1.each_char {|char| count[char] +=1}\r\n str2.each_char {|char| count[char] -=1}\r\n count.values.all?(0)\r\nend",
"def fith_anagram?(str1, str2)\n hash = Hash.new(0)\n \n str1.each_char { |char| hash[char] += 1 }\n str2.each_char { |char| hash[char] += 1 }\n \n hash.values.all? { |v| v > 1 }\nend",
"def second_anagram?(str1, str2)\n str1.chars.each do |el|\n if str2.include?(el)\n str1 = str1.sub(el, \"\")\n str2 = str2.sub(el, \"\")\n end\n end\n\n str1.empty? && str2.empty?\nend",
"def second_anagram?(word1, word2)\n return false if word1.length != word2.length\n word1.chars.each do |char1|\n word2.chars.each do |char2|\n if char1 == char2\n word1 = delete_char(word1, char1)\n word2 = delete_char(word2, char1)\n end\n end\n end\n\n word1.empty? && word2.empty?\nend",
"def third_anagram?(word1, word2)\n split1= word1.chars.sort\n split2 = word2.chars.sort\n split1 == split2\nend",
"def bonus_anagram?(str1, str2)\n counts = Hash.new(0)\n\n str1.chars.each { |letter| counts[letter] += 1 }\n str2.chars.each { |letter| counts[letter] -= 1 }\n\n counts.values.all? { |value| value == 0 }\nend",
"def second_anagram?(str_1, str_2)\n words = str_2.chars\n str.each_char.with_index do |char, i|\nend\n\n# def first_anagram?(str_1, str_2)\n# hash_1 = Hash.new(0)\n# hash_2 = Hash.new(0)\n\n# str_1.each_char { |char| hash_1[char] += 1}\n# str_2.each_char { |char| hash_2[char] += 1}\n\n# hash_1 == hash_2\n# end\n\n# p first_anagram?(\"gizmo\", \"sally\") #=> false\n# p first_anagram?(\"elvis\", \"lives\") #=> true",
"def third_anagram?(first_word, second_word)\n first_word.chars.sort == second_word.chars.sort\nend",
"def third_anagram?(word1, word2)\n first = word1.chars.sort.join(\"\")\n second = word2.chars.sort.join(\"\")\n\n p first == second \nend",
"def second_anagram?(str1, str2)\n return false if str1.length != str2.length\n str1_copy = str1.dup\n str2_copy = str2.dup\n\n (0...str1.length).each do |i|\n if str2.include?(str1[i])\n str1_copy.delete!(str1[i])\n end\n end\n\n (0...str2.length).each do |i|\n if str1.include?(str2[i])\n str2_copy.delete!(str2[i])\n end\n end\n\n\n return true if str1_copy.empty? && str2_copy.empty?\n false\nend",
"def third_anagram?(str1, str2)\n\n str1.chars.sort == str2.chars.sort\n #sort1 #sort2\nend",
"def slightly_better_by_much_anagram(string1, string2)\n hsh1 = Hash.new(0)\n\n string1.chars.each do |ch|\n hsh1[ch] += 1\n end\n\n string2.chars.each do |ch|\n hsh1[ch] -= 1\n end\n\n return true if hsh1.values.all? {|el| el == 0}\n false\nend",
"def anagram_bruteforce? (s1,s2)\n sp = StringPermutator.new\n return true if sp.permutations(s1).include? s2\n false\n end",
"def third_anagram?(word_1, word_2)\n word_1.chars.sort == word_2.chars.sort\nend",
"def second_anagram?(str1, str2)\n return false unless str1.length == str2.length\n str2_arr = str2.chars\n str1_copy = str1.dup.chars\n str1.chars.each_with_index do |letter, idx|\n return false unless str2_arr.include?(letter)\n str2_arr.delete_at(str2_arr.index(letter)) if str2_arr.include?(letter)\n end\n true\nend",
"def third_anagram?(string1, string2)\n arr1 = string1.chars.sort\n arr2 = string2.chars.sort\n\n arr1 == arr2\nend",
"def second_anagram?(str1, str2)\n first = str1.chars\n second = str2.chars\n\n first_dup = first.dup\n second_dup = second.dup\n\n first.each_with_index do |char, idx|\n second.each_with_index do |char2, idx2|\n if char == char2\n first_dup[idx] = \"\"\n second_dup[idx2] = \"\"\n end\n end\n end\n\n first_dup == second_dup\nend",
"def second_anagram?(string1,string2)\n # byebug\n return false unless string1.length == string2.length\n\n chars1 = string1.chars\n chars2 = string2.chars\n\n chars1.each do |char|\n if chars2.include?(char)\n chars2.delete(char)\n end\n end\n\n return true if chars2.empty?\n\n false\nend",
"def second_anagram?(word1, word2)\n split1, split2 = word1.chars, word2.chars\n\n idx = 0\n while idx < split1.length\n split2.each_with_index do |el2, idx2|\n if el2 == split1[idx]\n split1.delete_at(idx)\n split2.delete_at(idx2)\n idx = -1\n break\n end\n end\n idx += 1\n end\n return false unless split1.empty? && split2.empty?\n true\nend",
"def second_anagram?(str_1, str_2)\n str_1.each_char do |char|\n return false unless str_1.include?(str_2[0])\n str_2.chars.delete_at(str_2.index(char))\n end\n true\nend",
"def third_anagram?(str1, str2)\n s1 = str1.split('').sort\n s2 = str2.split('').sort\n\n s1 == s2\nend",
"def third_anagram?(str_1, str_2)\n sorted_str_1 = str_1.chars.sort.join\n sorted_str_2 = str_2.chars.sort.join\n sorted_str_1 == sorted_str_2\nend",
"def first_anagram?(string1, string2)\n all_anagrams(string1).include?(string2)\nend",
"def third_anagram?(str1,str2) #O(nlogn)\n str1_a = str1.split('').sort\n str2_a = str2.split('').sort\n\n str1_a == str2_a \nend",
"def third_anagram(str1, str2) \n sorted_str1 = str1.split(\"\").sort\n sorted_str2 = str2.split(\"\").sort\n\n sorted_str1 == sorted_str2\nend",
"def second_anagram?(str1, str2)\n letters1 = str1.chars\n letters2 = str2.chars\n\n str1.chars.each do |c|\n match1 = letters1.index(c)\n match2 = letters2.index(c)\n\n return false unless match1 && match2\n\n letters1.delete_at(match1)\n letters2.delete_at(match2)\n end\n\n letters1.empty? && letters2.empty?\nend",
"def third_anagram?(str1, str2)\n\n str1.split(\"\").sort == str2.split(\"\").sort\n\nend",
"def third_anagram?(word1, word2)\n a, b = word1.split(''), word2.split('')\n\n a.sort == b.sort\nend",
"def third_anagram?(first_str, second_str)\n first_sorted = first_str.chars.sort # n + nlogn\n second_sorted = second_str.chars.sort # m + mlogm\n first_sorted == second_sorted\nend",
"def third_anagram?(string1, string2)\n chars1 = string1.chars.sort\n chars2 = string2.chars.sort\n\n chars1 == chars2\nend",
"def third_anagram?(str1, str2)\n sorted1 = str1.split(\"\").sort.join #O(n + nlogn + n) => O(nlogn)\n sorted2 = str2.split(\"\").sort.join #O(n + nlogn + n) => O(nlogn)\n\n sorted1 == sorted2 #O(1)\nend"
] |
[
"0.9070155",
"0.9026226",
"0.9014158",
"0.8991528",
"0.89730996",
"0.8948751",
"0.8903333",
"0.8874652",
"0.88339776",
"0.8830037",
"0.88141763",
"0.8813923",
"0.88133454",
"0.8797188",
"0.87943155",
"0.87943155",
"0.87934756",
"0.8783717",
"0.87818086",
"0.87818086",
"0.87818086",
"0.87682086",
"0.87634605",
"0.87472",
"0.873102",
"0.86777437",
"0.8676096",
"0.8675599",
"0.86708844",
"0.86659706",
"0.86568403",
"0.86564064",
"0.8653576",
"0.858261",
"0.856829",
"0.85664004",
"0.8520176",
"0.8492825",
"0.84630334",
"0.8460048",
"0.84542805",
"0.84345293",
"0.84284186",
"0.83986545",
"0.83977485",
"0.8390519",
"0.83865917",
"0.8370432",
"0.83581257",
"0.8356732",
"0.8333733",
"0.83315706",
"0.8330714",
"0.83120704",
"0.83120704",
"0.8298925",
"0.8295548",
"0.8259088",
"0.8254871",
"0.82519054",
"0.82476354",
"0.82457536",
"0.822506",
"0.8219281",
"0.8190066",
"0.81851506",
"0.81759024",
"0.817415",
"0.81659687",
"0.8161655",
"0.81516236",
"0.8150171",
"0.8127249",
"0.81212723",
"0.8111243",
"0.8110991",
"0.81028926",
"0.8097656",
"0.80867463",
"0.80865026",
"0.8084192",
"0.80827147",
"0.80811477",
"0.80777097",
"0.8075108",
"0.80735016",
"0.8072328",
"0.8069127",
"0.8063677",
"0.80528146",
"0.8045846",
"0.8045707",
"0.80431455",
"0.80341125",
"0.8031986",
"0.80291504",
"0.8016171",
"0.80144155",
"0.80124915",
"0.8007577"
] |
0.8277312
|
57
|
Define a recursive method `permutations(array)` that returns all of the permutations of an array example => permutations([1,2,3]) should return => [ [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1] ] You CANNOT use call Ruby's builtin `Arraypermutation` method.
|
def permutations(array)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def permutations(array)\n\treturn array.permutation\nend",
"def permutations(array)\n return [array] if array.length == 1\n\n perms = []\n array.each do |el|\n dupped = array.dup\n dupped.delete(el)\n permutations(dupped).each { |perm| perms << [el] + perm }\n end\n\n perms\nend",
"def permutations(array)\n return [array] if array.length <= 1\n\n # Similar to the subsets problem, we observe that to get the permutations of \n # [1, 2, 3] we can look at the permutations of [1, 2] which are [1, 2] and \n # [2, 1] and add the last element to every possible index getting [3, 1, 2], \n # [1, 3, 2], [1, 2, 3], [3, 2, 1], [2, 3, 1], [2, 1, 3]\n\n # pop off the last element\n first = array.shift\n\n # make the recursive call\n perms = permutations(array)\n\n # we will need an array to store all our different permutations\n total_permutations = []\n\n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).to_a.each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n\n total_permutations\nend",
"def permutations(array)\n debugger\n return [array] if array.length <= 1\n # pop off the last element\n first = array.shift\n # make the recursive call\n perms = permutations(array)\n # we will need an array to store all our different permutations\n total_permutations = []\n\n\n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0 ... i] + [first] + perm[i .. -1]\n end\n end\n total_permutations\nend",
"def permutations(array)\n if array[0].is_a?(Array)\n permutation_num = factorial(array[0].length)\n return array if array.length == permutation_num\n current = array[-1]\n prev_array = [current[-1]] + current[0..-2]\n next_array = [current[-1]] + current[0..-2].reverse\n result = array + [next_array , prev_array]\n permutations(result)\n else\n permutation_num = factorial(array.length)\n return array if array.length == permutation_num\n next_array = [array[0]] + array[1..-1].reverse\n result = [array] + [next_array]\n permutations(result)\n end\n end",
"def permutations(array)\n return [array] if array.length <= 1\n\n\n # Similar to the subsets problem, we observe that to get the permutations\n # of [1, 2, 3] we can look at the permutations of [1, 2] which are\n # [1, 2] and [2, 1] and add the last element to every possible index getting\n # [3, 1, 2], [1, 3, 2], [1, 2, 3], [3, 2, 1], [2, 3, 1]\n\n # pop off the last element\n first = array.shift\n # make the recursive call\n perms = permutations(array)\n # we will need an array to store all our different permutations\n total_permutations = []\n\n\n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n total_permutations\nend",
"def permutations(array)\n \nend",
"def permutations(array)\n results = []\n results[0] = [[array.first]]\n (1..array.length - 1).each do |i|\n new_perms = []\n old_perms = results[i-1].deep_dup\n old_perms.each do |perm|\n perm.each_with_index do |value, index|\n new_perms << perm.splice(index, i + 1)\n end\n new_perms << perm.push(i + 1)\n end\n results[i] = new_perms\n end\n results[array.length - 1]\nend",
"def permutations(array)\n return [[]] if array.empty?\n return [array] if array.length == 1\n new_arr = []\n\n first_el = array.shift\n array_perms = permutations(array)\n array_perms.each do |perm|\n (0..perm.length).each do |idx|\n new_arr << perm[0...idx] + [first_el] + perm[idx..-1]\n end\n end\n return new_arr\nend",
"def permutations(array)\n return [array] if array.length <= 1\n\n first = array.shift\n perms = permutations(array)\n total_permutations = []\n\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm.take(i) + [first] + perm.drop(i)\n end\n end\n total_permutations\nend",
"def permutations(array)\n return [array] if array.length <= 1\n\n first = array.shift\n perms = permutations(array)\n\n total_permutations = []\n\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n\n total_permutations\nend",
"def permutations(array)\n\n ret = []\n return [array] if array.length < 2\n sub = permutations(array[1..-1])\n sub.each do |sub_array|\n (0..sub_array.length).each do |idx|\n ret << sub_array[0...idx] + [array.first] + sub_array[idx..-1]\n end\n end\n ret\nend",
"def permutations(array)\n return [array] if array.length == 1\n\n first = array.shift\n\n perms = permutations(array)\n total_permutations = []\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n\n end\n total_permutations\nend",
"def permutations(array)\n return [array] if array.length <= 1\n total_permutations = []\n last = array[-1]\n perms = permutations(array[0...-1])\n\n perms.each do |perm|\n 0.upto(perm.length) do |index|\n total_permutations << perm[0...index] + [last] + perm[index..-1]\n end\n end\n\n total_permutations\nend",
"def permutations(array)\n if array.empty?\n return [[]]\n end\n if array.count == 1\n return [array.clone]\n end\n arr = []\n array.each_with_index do |ele, idx|\n cpy = array.clone\n cpy.delete_at(idx)\n permutations(cpy).each do |perm|\n arr << [ele] + perm\n end\n end\n return arr\nend",
"def permutations(array)\n return [array] if array.length <= 1\n start = array.shift\n perm = permutations(array)\n total_perms = []\n perm.each do |perms|\n (0..perm.length).each do |i|\n total_perms << perms[0...i] + [start] + perms[i..-1]\n end\n end\n total_perms\nend",
"def permutations(array)\n return [array] if array.length <= 1\n \n \n # Similar to the subsets problem, we observe that to get the permutations\n # of [1, 2, 3] we can look at the permutations of [1, 2] which are\n # [1, 2] and [2, 1] and add the last element to every possible index getting\n # [3, 1, 2], [1, 3, 2], [1, 2, 3], [3, 2, 1], [2, 3, 1]\n \n # pop off the last element\n first = array.shift\n # make the recursive call\n perms = permutations(array)\n # we will need an array to store all our different permutations\n total_permutations = []\n \n \n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n total_permutations\nend",
"def permute(arr)\n return [array] if array.length <= 1\n\n first = array.shift\n perms = permute(array)\n total_permutations = []\n \n \n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n total_permutations\nend",
"def permute(arr)\n permutations = []\n for i in (0 .. arr.size - 1)\n for j in (i + 1 .. arr.size - 1)\n permutations.push([arr[i],arr[j]])\n end\n end\n permutations\n end",
"def permutations(array)\n #base case\n return [[]] if array.empty?\n\n results = []\n prev_perm = permutations(array[0...-1]) # permutations([1,2]) == [[1, 2], [2, 1]]\n last_ele = array[-1] # 3\n prev_perm.each do |sub_arr|\n (0...array.length).each do |idx|\n # temp = Array.new(array.length) [nil, nil, nil]\n # temp = sub_arr[0...idx] + [last_ele] + sub_arr[idx..-1]\n results << temp\n end\n end\n results\nend",
"def permutations(arr)\n return [arr] if arr.length == 1\n results = []\n arr.each_with_index do |num, idx|\n rest_of_arr = arr[0...idx] + arr[(idx + 1)..-1]\n permutations(rest_of_arr).each do |permutation|\n results << [num] + permutation\n end\n end\n results\nend",
"def permutations(array)\n return [array] if array.length == 1\n\n results = []\n\n array.each_with_index do |item, i|\n permutations(array[0..i-1] + array[i+1..-1]).each do |perm|\n results << perm.unshift(item)\n end\n end\n\n results\nend",
"def permutation(array)\n answer_arr = []\n return array if array.length == 1\n array.each_index do |i|\n perm = permutation(array - [array[i]])\n perm.each do |el|\n answer_arr << ([array[i]] + [el]).flatten\n end\n perm.each do |el|\n answer_arr << ([el] + [array[i]]).flatten\n end\n end\n answer_arr.uniq\nend",
"def permutations(arr)\n # will have to iterate\n # will have logic similar to subsets\n\n # [1], hits base case and we're done\n\n return [arr] if arr.length <= 1\n\n result = []\n last_ele = arr.pop\n sub_perms = permutations(arr)\n\n sub_perms.each do |sub|\n (0..sub.length) do |i| # index will vary, we to include sub.length as an index, otherwise we will never be able to shove into the last/back spot\n result << sub[0...i] + [last_ele] + sub[i..-1]\n # since the i will vary as we iterate through, ^^ will shift the last_ele around\n end\n end",
"def permutations(arr)\n arr = arr.dup\n return [arr] if arr.length == 1\n\n last_el = arr.pop\n base = permutations(arr) # [[1]]\n\n results = []\n base.each do |perm|\n (perm.length + 1).times do |i|\n result = perm[0...i] + [last_el] + perm[i..-1]\n results << result\n end\n end\n\n results\nend",
"def permutations array\n if array.size < 2\n yield array\n else\n array.each do |element|\n permutations(array.select() {|n| n != element}) \\\n {|val| yield([element].concat val)}\n end\n end\nend",
"def permutations(array)\n return array if array.length <= 1\n\n if array.length == 2\n return [array, array.reverse]\n end\n\n final_array = []\n\n array.length.times do\n set = array.take(array.length - 1)\n\n final_array += permutations(set).map do |item|\n item += [array.last]\n end\n\n next_item = array.shift\n array.push(next_item)\n end\n\n final_array\nend",
"def array_permutation(array)\n return array[0] if array.size == 1\n first = array.shift\n return first.product( array_permutation(array) )\nend",
"def permutations(array)\n return [array] if array.length < 2\n\n result = []\n prev = permutations(array[0..-2])\n prev.each do |perm|\n (0..perm.size).each do |idx|\n result << perm.dup.insert(idx, array.last)\n end\n end \n \n result\nend",
"def permutations(arr)\n return [arr] if arr.length <= 1\n\n prev_perms = permutations(arr[0..-2])\n total_perms = []\n\n prev_perms.each do |sub_perm|\n (0..sub_perm.length).each do |idx|\n total_perms << sub_perm[0...idx] + [arr.last] + sub_perm[idx..-1]\n end\n end\n\n total_perms\nend",
"def permutations(arr)\n return [arr] if arr.length <= 1\n\n first = arr.shift\n perms = permutations(arr)\n total_perms = []\n\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_perms << perm[0...i] + [first] + perm[i..-1]\n end\n end\n\n total_perms.sort\nend",
"def permutations(array)\n # debugger\n return [array] if array.length == 1\n perms = permutations(array[0..-2])\n other_perms = []\n perms.each do |perm|\n other_perms += (0..perm.length).map do |idx|\n temp = perm.dup\n temp.insert(idx, array[-1])\n end\n end \n other_perms\nend",
"def permutations(arr)\n return [arr] if arr.length <= 1\n\n [arr.last] + permutations(arr[0...-1])\nend",
"def permutations(arr)\n return arr if arr.length <= 1\n perm = [arr]\n sub_perm = permutations(arr[1..-1])\n curr_el = arr[0]\n p sub_perm\n p \" sub_perm #{sub_perm} \"\n if sub_perm.length > 1\n\n sub_perm.each do |subArr|\n temp = []\n (0...subArr.length).each do |i|\n temp = subArr[0..i] + [curr_el] + subArr[i + 1..-1]\n end\n perm << temp\n end\n end\n # puts \" sub_perm #{sub_perm} \"\n # sub_perm.each do |subArr|\n # subArr << curr_el\n # perm << subArr\n # end\n # sub_perm << curr_el\n # perm << sub_perm\nend",
"def permutations(arr)\n # return nil if arr.empty?\n return [arr] if arr.length == 1\n # grab first element to append to all perms of smaller array\n first_el = arr.shift\n # get permutations of shrunken array\n subset_perms = permutations(arr)\n total_permutations = []\n # iterate through all smaller perms\n subset_perms.each do |sub|\n # add first element to all possible indices of perms array\n # and add to total_perms array\n (0..sub.length).each do |i|\n subset = sub[0...i] + [first_el] + sub[i..-1]\n total_permutations << subset\n end\n end\n total_permutations\nend",
"def permutations(array)\n #[1,2]\nreturn [array] if array==[1]\n\n\n\n\nprevious=permutations(array[0...-1])\nlast = array.last\nresult=[]\nprevious.each do |ele|\n (0...array.length-1).each do |i|\n result << ele[0..i]+[last]+ele[i+1..-1]\n \n \n end\n result << [last]+ele\n\n end\n result\nend",
"def permutations(arr)\n return arr if arr.length <= 1\n return [arr, arr.reverse] if arr.length == 2\n last_el = arr.pop\n old_arr = arr.deep_dup\n arr = []\n permutations(old_arr).each do |el|\n (0..el.length).each do |pos|\n base_el = el.deep_dup\n arr += [base_el.insert(pos, last_el)]\n end\n end\n arr\nend",
"def perms(arr)\n result = []\n all_perms(arr, 0, result)\nend",
"def print_permutations_of(array) \n array.permutation.to_a.each do |element|\n puts element.join(\", \")\n end\n end",
"def permutations(elements)\n return [elements] if elements.size <= 1\n result = []\n elements.uniq.each do |p|\n _elements = elements.dup\n _elements.delete_at(elements.index(p))\n permutations(_elements).each do |perm|\n result << (perm << p)\n end\n end\n result\nend",
"def get_permutations(arr)\n\t# byebug\n\treturn [arr] if arr.count <= 1\n\n\tarray_except_last = arr[0..arr.count - 2]\n\tlast_one = [arr.last]\n\n\tpermutations_of_array_except_last = get_permutations(array_except_last)\n\n\tpermutations = []\n\tpermutations_of_array_except_last.each do |permutation_of_array_except_last|\n\t\t(0..permutation_of_array_except_last.count).each do |position|\n\t\t\tif position == 0\n\t\t\t\tp = last_one + permutation_of_array_except_last\n\t\t\telsif position == array_except_last.count\n\t\t\t\tp = permutation_of_array_except_last + last_one\n\t\t\telse\n\t\t\t\tp = permutation_of_array_except_last[0...position] + last_one + permutation_of_array_except_last[position..permutation_of_array_except_last.count - 1]\n\t\t\tend\n\t\t\tpermutations << p\n\t\tend\n\tend\n\tpermutations\nend",
"def array_permutations(arr)\n return [arr] if arr.length <= 1\n removed = arr.last\n sliced_arr = arr.slice(0...-1)\n new_arrays = array_permutations(sliced_arr)\n res = []\n new_arrays.each{|new_array|res += insert_num(new_array, removed)}\n res\nend",
"def permutation (array)\n# yields permutation set WITH duplicates\nend",
"def permutations(arr)\n return [[]] if arr.empty? \n \n #last element arr\n #putting before and after every index of a perm\n #permuatations(arr[0..-2])\n #last = arr[-1]\n \n last = arr[-1]\n perms = permutations(arr[0..-2])\n result = [] \n perms.each do |sub_arr| #[a,b]\n current_perms = []\n (0..sub_arr.length).each do |i|\n dup = sub_arr.dup \n current_perms << dup.insert(i,last) # dup = ['b','a']\n end \n result += current_perms\n end \n\n result \nend",
"def permutation(array)\n return array if array.length == 1\n\n smaller = permutation(array[0...-1])\n combination_array = []\n (smaller.length + 1).times do |index|\n combination_array += smaller.dup.insert(index, array[-1])\n # debugger\n end\n combination_array\nend",
"def permutations_of_array(a, k)\n a.permutation(k).to_a\nend",
"def get_permutations(n)\r\n return (1..n).to_a.permutation.to_a\r\nend",
"def permutations(input)\n return [] if input.empty?\n [permute(0,input)].flatten\n end",
"def permutations_lazy_iter(arr)\n new_arr = [arr]\n num_perms = factorial(arr.length)\n\n until new_arr.length == num_perms\n new_arr << arr.shuffle\n new_arr = new_arr.uniq\n end\n\n new_arr\nend",
"def permute(list)\n if (list.length <= 1)\n return [list]\n end\n permutations = []\n count = 1\n list.each do |item|\n sublist_permutations = permute(list - [item])\n sublist_permutations.each do |permutation|\n permutation.unshift(item)\n permutations << permutation\n #puts \"Permutations : #{permutations.join(', ')}\"\n #puts \"permutation lists: #{permutations.each {permutation.join(', ')}}\"\n end\n end\n return permutations\nend",
"def permutations\n return [self] if length == 1\n\n orders = []\n positions = (0...length).to_a\n\n # Finding the permutations with a basic array of digits\n positions.each do |position|\n (positions - [position]).permutations.each do |permutation|\n orders << permutation.unshift(position)\n end\n end\n\n # We subsitute in our original elements. This prevents duplicate\n # elements from causing problems, and allows the [3,3] example to work.\n orders.map { |order| order.map { |index| self[index] } }\n end",
"def all_permutations\n perms = permutations\n perms = perms.shuffle.take(1) if @single_perm || ENV['FAST_TESTS']\n\n perms.each do |p|\n yield(p)\n WebMock.reset!\n end\n end",
"def permutations(array)\n results = []\n\n 1000.times do \n premutation = array.shuffle\n results << array << premutation\n end\n\n results.uniq.sort\nend",
"def permutations(string)\n permute(string, 0, string.length)\nend",
"def permutations(arrays, i)\n if i == arrays.length then return [[]] end\n\n res_next = permutations(arrays, i + 1)\n res = []\n arrays[i].each do |x|\n res_next.each do |y|\n res << ([x] + y)\n end\n end\n return res\nend",
"def permute(items, perms=[], res=[])\n unless items.length > 0\n res << perms\n else\n for i in items\n newitems = items.dup\n newperms = perms.dup\n newperms.unshift(newitems.delete(i))\n permute(newitems, newperms,res)\n end\n end\n return res\nend",
"def permutations(string)\n string.chars.permutation(string.length).to_a.map { |arr| arr.join }.uniq\nend",
"def permutations(sequence)\n return sequence if sequence.empty?\n\n ch = sequence.delete_at(0)\n underlying = Set.new([ch])\n sequence.each do |ch|\n new_set = Set.new\n underlying.each do |permutation|\n (0..permutation.length).each do |idx|\n new_set.add(permutation.dup.insert(idx, ch))\n end\n end\n underlying = new_set\n end\n underlying.each\nend",
"def permutations(string)\n string.chars.permutation(string.length).map(&:join).uniq\nend",
"def permutations(sequence)\n return sequence if sequence.empty?\n ch = sequence.delete_at(0)\n underlying = Set.new([ch])\n sequence.each do |ch|\n new_set = Set.new\n underlying.each do |permutation|\n (0..permutation.length).each do |idx|\n new_set.add(permutation.dup.insert(idx, ch))\n end\n end\n underlying = new_set\n end\n underlying.each\n end",
"def lexicographic_permutations\n a=Array.new\n (1..self.length.factorial).each { |i| a << self.lexicographic_permutation(i) }\n a\n end",
"def perm(arr)\n return [arr] if arr.length <= 1\n result = []\n arr.each_index do |idx|\n temp = perm(arr[0...idx] + arr[idx+1..-1])\n subset = temp.map { |sub| [arr[idx]] + sub }\n result += subset\n end\n\n result\n\n\n\n\n # return [arr] if arr.length <= 1\n # result = []\n #\n # arr.each_index do |idx|\n #\n # other_perm = perm(arr[0...idx] + arr[idx+1..-1])\n # row = other_perm.map { |subarr| [arr[idx]] + subarr }\n # result += row\n # end\n #\n # result\nend",
"def permutations(base, result = [])\n base = base.dup\n base.empty? ? [result] : base.shift.map { |value| permutations(base, result + [value]) }.flatten(1)\n end",
"def permutations(string)\n perms = []\n combos = string.split('').permutation.to_a.map { |combo| combo.join('') }\n combos.each { |combo| perms << combo if !perms.include?(combo) }\n perms\nend",
"def permutations(str)\n permutation(str.chars)\nend",
"def permutations(string)\n string.chars.permutation.to_a.map(&:join).uniq\nend",
"def permutations(string)\nend",
"def permutations(str)\nend",
"def permute(nums)\n result = []\n permute_helper(nums, [], result)\n result\nend",
"def permutations(a, i)\n if i == a.size \n puts to_decimal(a)\n gets\n return\n end\n\n for j in i..a.size-1\n a[j], a[i] = a[i], a[j]\n permutations(a, i + 1)\n a[j], a[i] = a[i], a[j]\n end\nend",
"def permute(level, input)\n return [input] if level == input.length - 1\n\n results = []\n for i in level..(input.length-1)\n foo = permute(level+1, swap(input, level, i))\n results << foo\n end\n results\n end",
"def permutation(string)\n return [string] if string.size < 2\n char = string[0]\n total_perms = []\n perms = permutation(string[1..-1])\n\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_perms << perm[0...i] + char + perm[i..-1]\n end\n end\n\n total_perms\nend",
"def permute(nums)\n result = []\n permute_helper(nums, [], result)\n result\nend",
"def permutations(p)\r\n p.to_s.scan(/\\d/).permutation.map{|e| e.join}.sort\r\nend",
"def permutation(length = size, &block)\n return enum_for(:permutation, length) if not block_given?\n if length == 0\n yield EmptyList\n elsif length == 1\n each { |obj| yield Cons.new(obj, EmptyList) }\n elsif not empty?\n if length < size\n tail.permutation(length, &block)\n end\n\n tail.permutation(length-1) do |p|\n 0.upto(length-1) do |i|\n left,right = p.split_at(i)\n yield left.append(right.cons(head))\n end\n end\n end\n self\n end",
"def q(a);a.permutation;end",
"def permutation(string)\n return [string] if string.size < 2\n char = string[0]\n perms = permutation(string[1..-1])\n result = []\n perms.each do |perm|\n result << char + perm\n (1..perm.length-1).each do |i|\n result << perm[0..i-1] + char + perm[i..-1]\n end\n result << perm + char\n end\n result.uniq\nend",
"def getPermutations3(s,perm=[])\n subresult = getPermutations2(s[1..3])\n subresult.each do |item|\n perm.push(item.insert(0,s[0]))\n end\n if perm.length >= factorial(s.length)\n return perm\n else\n s = rotateChar(s)\n getPermutations3(s,perm)\n end\nend",
"def permutations(paths)\n permutations = paths.map(&:downcase).map(&:all_permutations)\n permutations = permutations.flatten.sort_by(&:length).reverse\n permutations\nend",
"def permute(nums, solution = [], results = []\n return results << solution.clone if solution.size == nums.size\n\n nums.each do |num|\n next if solution.include?(num)\n\n solution << num\n permute(nums, solution, results)\n solution.pop\n end\n results\nend",
"def string_permutations(str) \n return [] if !str || str.length == 0\n \n perms = []\n helper(rest: str, perms: perms)\n perms \nend",
"def test_permutations\n find = Finder.new\n arr = [\"CAKE\", \"ANT\", \"TRY\"]\n word_list = [\"CAKE\", \"NAT\"]\n result = find.permutations(arr, word_list)\n expected = [\"CAKE\", \"NAT\"]\n assert_equal expected, result\n end",
"def permutations(perms, digits)\n\tcounts = Array.new(digits.size, 0)\n\t\nend",
"def number_permutations(number)\n permutations = []\n\n [3, 4, 5, 6, 7, 10].each do |pattern|\n permutations << split_in_two(number, pattern)\n end\n [[3, 3], [3, 4], [4, 3]].each do |pattern|\n permutations << split_in_three(number, pattern.first, pattern.last)\n end\n\n permutations\n end",
"def nth_permutation(number_of_permutations)\n\t\tpermutation_array = []\n\t\tnumber_of_permutations -= 1 # assuming we start from the first permutation rather than the zeroth\n\t\twhile lexographic_array.length > 0\n\t\t\tindex = number_of_permutations / (lexographic_array.length - 1).factorial\n\t\t\tnumber_of_permutations %= (lexographic_array.length - 1).factorial\n\t\t\tpermutation_array.push(lexographic_array.delete_at(index))\n\t\tend\n\t\tpermutation_array\n\tend",
"def permute(words)\n return nil if words.nil?\n return [] if words.empty?\n\n pwords = []\n words.each do |w|\n list = w.chars.to_a.permutation.map(&:join)\n pwords.concat list\n end\n pwords\n end",
"def permutations(string)\n # base case\n if string.length == 0\n return string\n end\n\n results = []\n\n i = 0\n while i < string.length\n first_letter = string[i]\n rest = string[i+1..-1]\n permutes = permutations(rest)\n \n permutes.each do |permuties|\n results.push(first_letter += permuties)\n end\n end\n\n return results\n\nend",
"def permutate(word)\n max_size = word.size\n perms_arr = word.chars.permutation.map(&:join)\n perms_arr.each do |perm|\n @perms << perm if perm.size == max_size\n end\n end",
"def getPermutations(s)\n result = []\n for i in 0..2\n substring = s[1..2]\n result.push(s[0] + substring)\n result.push(s[0] + substring.reverse)\n s = rotateChar(s)\n end\n\n return result\nend",
"def permute_string(perm_string)\n char_array = perm_string.chars\n permute_rec(char_array,0,char_array.size - 1, [])\nend",
"def permute(&block)\n case size\n when 0 then yield []\n when 1 then yield self\n when 2\n yield self\n yield self.reverse\n else\n 0.upto(size-1) do |i|\n a = dup\n c = a.slice!(i)\n a.permute do |p|\n yield p.dup.unshift(c)\n end\n end\n end\n end",
"def getPermutations2(s,perm=[])\n substring = s[1..2]\n perm.push(s[0] + substring)\n perm.push(s[0] + substring.reverse)\n if perm.length >= factorial(s.length)\n return perm\n else\n s = rotateChar(s)\n getPermutations2(s,perm)\n end\nend",
"def permsol(str)\n str.chars.permutation.to_a.map(&:join).uniq \nend",
"def mixup_shuffle arr\n recursive_shuffle(arr, [])\nend",
"def perm(nums, i, result)\n return result << nums.dup if i == nums.size\n\n (i...nums.size).each do |j|\n nums[i], nums[j] = nums[j], nums[i]\n perm(nums, i + 1, result)\n nums[i], nums[j] = nums[j], nums[i]\n end\nend",
"def shuffle(array)\n recursive_shuffle array, []\nend",
"def pbEachCombination(array,num)\n return if array.length<num || num<=0\n if array.length==num\n yield array\n return\n elsif num==1\n for x in array\n yield [x]\n end\n return\n end\n currentComb=[]\n arr=[]\n for i in 0...num\n currentComb[i]=i\n end\n begin\n for i in 0...num\n arr[i]=array[currentComb[i]]\n end\n yield arr\n end while _pbNextComb(currentComb,array.length)\nend"
] |
[
"0.8647117",
"0.8589345",
"0.8478354",
"0.84593046",
"0.8430611",
"0.8413266",
"0.8404853",
"0.8382999",
"0.83511484",
"0.8347155",
"0.83425707",
"0.830749",
"0.83056116",
"0.82848465",
"0.817577",
"0.8171826",
"0.81556547",
"0.81370294",
"0.8060257",
"0.80356085",
"0.7976874",
"0.79487705",
"0.791343",
"0.7874373",
"0.7856687",
"0.7854395",
"0.77813774",
"0.77553874",
"0.77502996",
"0.7748855",
"0.77447367",
"0.7706563",
"0.75697696",
"0.75653297",
"0.7518014",
"0.75147665",
"0.7473544",
"0.7454595",
"0.7388736",
"0.73660797",
"0.7347778",
"0.72568077",
"0.72338456",
"0.7227139",
"0.7196823",
"0.7193763",
"0.71028394",
"0.70993733",
"0.7043999",
"0.6935092",
"0.6917164",
"0.69136226",
"0.69080204",
"0.68624675",
"0.68463725",
"0.6819358",
"0.67958516",
"0.67567956",
"0.67422146",
"0.6737583",
"0.67309314",
"0.6718357",
"0.67100346",
"0.66924715",
"0.66546303",
"0.6637396",
"0.6636267",
"0.6594915",
"0.65511066",
"0.65473205",
"0.6547271",
"0.6523631",
"0.65227044",
"0.6497849",
"0.6427131",
"0.6405446",
"0.6391677",
"0.63804203",
"0.6353048",
"0.6306573",
"0.63018006",
"0.62887347",
"0.6271444",
"0.6221264",
"0.61723125",
"0.6107731",
"0.6081634",
"0.60815287",
"0.6039838",
"0.603017",
"0.600324",
"0.59947956",
"0.59150004",
"0.58903325",
"0.58872455",
"0.58669245",
"0.5816109"
] |
0.84100753
|
9
|
Back in the good old days, you used to be able to write a darn near uncrackable code by simply taking each letter of a message and incrementing it by a fixed number, so "abc" by 2 would look like "cde", wrapping around back to "a" when you pass "z". Write a function, `caesar_cipher(str, shift)` which will take a message and an increment amount and outputs the encoded message. Assume lowercase and no punctuation. Preserve spaces. To get an array of letters "a" to "z", you may use `("a".."z").to_a`. To find the position of a letter in the array, you may use `Arrayfind_index`.
|
def caesar_cipher(str, shift)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def caesar_cipher(string, shift_factor)\n\n\n upc_alphabet_arr = ('A'..'Z').to_a\n downc_alphabet_arr = ('a'..'z').to_a\n\n\n string_chars_arr = string.chars\n\n new_chars_arr = []\n\n string_chars_arr.each do |char|\n if upc_alphabet_arr.include?(char)\n new_index = (upc_alphabet_arr.index(char) + shift_factor)%26\n new_char = upc_alphabet_arr[new_index]\n\n new_chars_arr << new_char\n\n elsif downc_alphabet_arr.include?(char)\n new_index = (downc_alphabet_arr.index(char) + shift_factor)%26\n new_char = downc_alphabet_arr[new_index]\n\n new_chars_arr << new_char\n\n else \n new_chars_arr << char\n end\n end\n\n new_string = new_chars_arr.join(\"\")\n puts new_string\nend",
"def caesar_cipher(string, shift)\n shifted = \"\"\n letters = (\"a\"..\"z\").to_a\n string.each_char do |char|\n old_idx = letters.find_index(char)\n if old_idx\n shifted << letters[(old_idx + shift) % 26]\n else\n shifted << \" \"\n end\n end\n\n shifted\nend",
"def caesar_cipher(str, shift)\n results = []\n #get all chars\n chars = str.split('')\n # if its a char included in alpha then get index num of low case\n alphabet = ('a'..'z').to_a\n chars.each do |char|\n if alphabet.include?(char.downcase)\n index = alphabet.index(char.downcase)\n results << alphabet[(index+shift)%26]\n else\n results << char\n end\n end\n # add the shift to index and get the modulo and get the letter indexd there\n # else pass the char to results because not a letter\n\n results.join('')\n\nend",
"def caesar_cipher(str, shift)\n letters = (\"a\"..\"z\").to_a\n\n encoded_str = \"\"\n str.split('').each do |char|\n if char == \" \"\n encoded_str << \" \"\n next\n end\n\n old_idx = letters.find_index(char)\n new_idx = (old_idx + shift) % letters.count\n\n encoded_str << letters[new_idx]\n end\n\n encoded_str\nend",
"def caesar_cipher(str, shift)\n letters = (\"a\"..\"z\").to_a\n\n encoded_str = \"\"\n str.each_char do |char|\n if char == \" \"\n encoded_str < \" \"\n next\n end\n old_idx = letters.find_index(char)\n new_idx = (old_idx + shift) % letters.count\n encoded_str << letters[new_idx]\n end\n encoded_str\nend",
"def caesar_cipher(string, shift)\n\n while shift > 26 #prevents users from accessing a value beyond the letters of ASCII table\n puts 'Sorry choose a number equal to or lower than 26'\n shift.gets.chomp.to_i\n end \n \nstring.chars.map {|char| #.chars seperates each symbol of the string (including spaces) into an array; .map 'maps' each element in the block with |char| representing the variable being targeted\n if char =~ (/\\w/) && char == char.upcase #the =~ is a 'match operator' used to match current char with \\w (any alphanumeric character) AND checks to see if char is uppercase\n char = char.ord + shift # .ord gives the ASCII value of the char + given shift num \n if char > 90 #if char is greater than 90, substract the total letters of alphabet to link char with appropriately shifted posotion \n char = (char - 26).chr #use chr to return it back to letter form \n else\n char.chr #if not greater than 90 (all char greater than 90 fall into lowercase category), simply return the .chr \n end\n elsif char =~ (/\\w/) && char == char.downcase #elsif char matches alphanumeric character AND downcase....\n char = char.ord + shift #.ord value +shift \n if char > 122 #if greater than lowercase z in ASCII table...\n char = (char - 26).chr \n else\n char.chr\n end\n else #if its not a letter just char it up some \n char\n \n end}.join #rejoin the .chars array as shifted string \n \nend",
"def caesar_cipher(str, shift)\n letters = (\"a\"..\"z\").to_a\n\n encoded_str = \"\"\n str.each_char do |char|\n if char == \" \"\n encoded_str << \" \"\n next\n end\n\n old_idx = letters.find_index(char)\n new_idx = (old_idx + shift) % letters.count\n\n encoded_str << letters[new_idx]\n end\n\n encoded_str\nend",
"def caesar_cipher(string, shift)\n lower = ('a'..'z')\n caesar_string = ''\n\n string.each_char do |char|\n shift.times { char = char.next } if lower.include?(char.downcase) # identify letters only\n caesar_string << char[-1]\n end\n caesar_string\nend",
"def caesar_cipher(str, shift)\n letters = (\"a\"..\"z\").to_a\n new_string = \"\"\n str.chars.each do |char|\n if letters.include?(char)\n shift_position = (letters.index(char) + shift) % 26\n new_string += letters[shift_position]\n else\n new_string += char\n end\n end\n new_string\nend",
"def caesar_cipher(string, shift_factor)\n alphabet = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]\n return string.split(//).map { |el|\n el.gsub(/\\w/, \"#{ind = alphabet.index(el).to_i + shift_factor\n until alphabet.index(el).to_i > 25 && ind < 52 || alphabet.index(el).to_i < 26 && ind < 26\n ind -= 26\n end\n alphabet[ind]}\")\n }.join\nend",
"def caesar_cipher(str, shift)\n alpha = (\"a\"..\"z\").to_a\n new_str = \"\"\n \n str.each_char do |char|\n if alpha.index(char)\n old_idx = alpha.index(char)\n new_str += alpha[(old_idx + shift) % 26]\n else\n new_str += char\n end\n end\n\n new_str\nend",
"def caesar_cipher(offset, string)\n\n result = \"\"\n\n array = string.split(\"\")\n\n i = 0\n\n while array.length > i\n\n ascii = array[i].ord\n p ascii\n\n if( array[i] != \" \") # keep space the same, do not add offset\n ascii += offset\n end\n\n if ascii >= 122 # IMPORTANT\n\n # look at note2self\n #\n back_round_from_a = ( ascii - \"a\".ord ) % 26\n #\n # look at note2self\n\n ascii = back_round_from_a + \"a\".ord\n # if x, i.e. x = 199 & offset = 3 so, total 122, then back_round_from_a = 0\n # Therefor, back_round_from_a + \"a\".ord === 0 + 97 => a\n\n end\n\n letter = ascii.chr\n p letter\n\n result += letter\n\n i += 1\n end # while\n\n p result\n\n return result\n\nend",
"def caesar_cipher(input_string, shift_factor)\r\n positions = input_string.unpack('C*')\r\n shifted_positions = positions.map do |pos|\r\n case pos\r\n when (65..90), (97..122)\r\n shifted = pos + (shift_factor % 26) # use % 26 to account for shift factors over 26\r\n if (shifted > 90 && shifted < 97) || (shifted > 122) # loop around\r\n shifted = shifted - 26\r\n end\r\n pos = shifted\r\n else\r\n pos # ignore non-alphabet chars\r\n end\r\n end\r\n result_string = shifted_positions.pack('C*')\r\n puts result_string\r\nend",
"def caesar_cipher(caesar_string, shift_factor) \n alphabet = (\"a\"..\"z\").to_a\n new_string = \"\"\n\n caesar_string.each_char do |input|\n if input == \" \"\n new_string += \" \"\n else \n old_index = alphabet.find_index(input)\n new_index = (old_index + shift_factor) % alphabet.count\n new_string += alphabet[new_index]\n end\n end\n\nputs new_string.chomp\n\nend",
"def caesar_cipher(str, shift)\n alph = (\"a\"..\"z\").to_a\n\n decode = \"\"\n\n str.chars.each do |letter|\n if letter == \" \"\n decode << letter\n end\n\n num = alph.find_index(letter)\n decode << alph[(num + shift) % 26]\n end\n\n decode\nend",
"def caesar_cipher(str, shift)\n dictionary = (\"a\"..\"z\").to_a\n new_array = []\n str.split(\"\").each do |letter|\n index_letter = dictionary.find_index(letter)\n if index_letter.nil?\n new_array << letter\n else\n new_index = (index_letter + shift) % 26\n\n new_array << dictionary[new_index]\n end\n end\n new_array.join\nend",
"def caesar_cipher(str, shift)\n alphabet ||= ('a'..'z').to_a\n res = \"\"\n str.chars.each do |letter|\n if letter == \" \"\n res += letter\n else\n old_idx = alphabet.index(letter)\n new_idx = old_idx*shift % 26\n res += alphabet[new_idx]\n end\n end\n res\nend",
"def caesar_cipher(str, shift)\n letters = (\"a\"..\"z\").to_a\n\n encoded_str = \"\"\n str.chars.each do |char|\n if char == \" \"\n encoded_str += \" \"\n next\n end\n\n old_idx = letters.index(char)\n new_idx = (old_idx + shift) % letters.length\n encoded_str << letters[new_idx]\n end\n\n encoded_str\nend",
"def caesar_cipher(str, shift)\n alpha = ('a'..'z').to_a\n\n str.split(' ').map do |word|\n word.chars.map { |x| alpha[(alpha.index(x) + shift) % 26] }.join\n end.join(' ')\nend",
"def caesar_cipher(str, shift)\n alphabet = ('a'..'z').to_a\n arr = []\n words = str.split\n words.each do |word|\n newword = ''\n word.each_char do |chr|\n idx = alphabet.index(chr) + shift\n newword += alphabet[idx % alphabet.length]\n end\n arr << newword\nend\n arr.join(' ')\nend",
"def caesar_cipher(string, shift)\n alphabet = (\"a\"..\"z\").to_a\n\n result = \"\"\n string.each_char do |char|\n if char == \" \"\n result += \" \"\n else\n result += alphabet[(alphabet.index(char) + shift) % 26]\n end\n end\n\n return result\nend",
"def caesar_cipher(string, shift = DateTime.now.day) # I set shift to be the current day if I do not include a parameter for it\n string.tr Alphabet.join, Alphabet.map{ |array| array.rotate shift }.join # This looks at every single character in the string and uses .map to rotate the array to bascially let it shift how ever many times within the array to assign the new character to the string variable\nend",
"def caesar_cipher(string, shift)\nend",
"def caesar_cipher(str, shift)\n cipher = (\"a\"..\"z\").to_a\n\n result = \"\"\n str.chars.each do |char|\n if char == \" \"\n result << char\n else\n shifted_idx = cipher.index(char) * shift % cipher.length\n result << cipher[shifted_idx]\n end\n end\n result\nend",
"def caesar_cipher(string, shift)\n begin\n shift = shift % 26\n new_string = \"\"\n letters = string.split('')\n letters.each do |i|\n if i >='a' && i <= 'z'\n encrypted = i.ord + shift\n if encrypted > 122 # ASCII for 'z'; wraps around to 'a'\n encrypted = encrypted - 26\n end\n elsif i >='A' && i <= 'Z'\n encrypted = i.ord + shift\n if encrypted > 90 # ASCII for 'Z'; wraps around to 'A'\n encrypted = encrypted - 26\n end\n else\n encrypted = i\n end\n new_string << encrypted.chr\n end\n return new_string\n rescue TypeError\n return \"Invalid shift factor. Please enter a number.\"\n end\nend",
"def caesar(string, shift)\n letters = string.chars\n code_word = []\n letters.each do |letter|\n if /[a-zA-Z]/ !~ letter\n code_word << letter\n else\n new_ord = letter.ord + shift\n if letter.ord > 90\n first_letter = 97\n else\n first_letter = 65\n end\n code_word << (((new_ord % first_letter) % 26) + first_letter).chr\n end\n end\n code_word.join\nend",
"def caesar(str, shift)\n\n alpha = ('a'..'z').to_a\n cipher = []\n\n str.split(\"\").map do |char|\n\n if alpha.include? char\n\n char_index = (alpha.index(char) + shift) % 26\n\n cipher << alpha[char_index]\n\n elsif alpha.include? char.downcase\n\n char_index = (alpha.index(char.downcase) + shift) % 26\n\n cipher << alpha[char_index].upcase\n\n\n else\n\n cipher << char\n\n end\n\n end\n\n cipher.join\n\nend",
"def caesar_cipher(message, shift_key)\n result = \" \"\n message.each_char do |letter|\n if letter.ord.between?(65,90) || letter.ord.between?(97, 122)\n final_code = letter.ord + shift_key\n\n final_code -= 26 if (final_code > 91 && letter.ord < 91) || final_code > 122\n result += final_code.chr\n else\n result += letter\n end\n end\n return result\nend",
"def Caesar_cipher(input_string,input_shift)\n\n alphabet = ('a'..'z').to_a\n alphabetUpCase = ('A'..'Z').to_a\n\n input_string.each_char {|letter| \n if letter =~ /[A-Z]/\n new_letter_index = alphabetUpCase.index(letter) + input_shift\n if new_letter_index > 25\n new_letter_index -= 26\n puts alphabetUpCase[new_letter_index]\n else\n puts alphabetUpCase[new_letter_index]\n end\n elsif letter =~ /[a-z]/\n new_letter_index = alphabet.index(letter) + input_shift\n if new_letter_index > 25\n new_letter_index -= 25\n puts alphabet[new_letter_index]\n else\n puts alphabet[new_letter_index]\n end\n else\n puts letter\n end\n }\nend",
"def caesar_cipher(string, shift_factor)\n output = \"\"\n string.scan (/./) do |i|\n if (\"a\"..\"z\").include? (i.downcase)\n shift_factor.times {i = i.next}\n end\n output << i[-1]\n end\n return output\nend",
"def caesar_cipher(string, shift)\n\tstring = string.to_s\n\tshift = shift.to_i\n\tnew_string = \"\"\n\n\tstring.each_byte do |i|\n\t\tif (i > 64 && i < 91) #A-Z\n\t\t\tif (i+shift) > 90\n\t\t\t\tnew_string << (i+shift - 26).chr \n\t\t\telse\n\t\t\t\tnew_string << (i+shift).chr\n\t\t\tend\n\t\telsif (i > 96 && i < 123) #a-z\n\t\t\tif (i+shift) > 122\n\t\t\t\tnew_string << (i+shift - 26).chr\n\t\t\telse\n\t\t\t\tnew_string << (i+shift).chr\n\t\t\tend\n\t\telse\n\t\t\tnew_string << i.chr\n\t\tend\n\tend\n\n\tputs new_string\nend",
"def caesar_cipher(str, num)\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n\n str.each_char.with_index do |char, i|\n shift = alphabet.index(char) + num # shifting num chars in the alphabet\n if shift > 26 # restart at 0 after index 26\n shift -= 26\n end\n str[i] = alphabet[shift]\n end\n\n str\nend",
"def caesar_cipher(word, shift)\n letters = ('a'..'z').to_a.concat(('A'..'Z').to_a)\n cipher = \"\"\n\n #only shift alpha characters\n word.each_char do |c|\n cipher += letters.include?(c) ? letters[(letters.index(c) + shift) % 52] : c\n end\n\n cipher\nend",
"def caesars_cipher(str, shift = 1)\n encrypted = ''\n\n ascii_nums = str.bytes\n ascii_nums.each do |i|\n encrypted << case i\n when 65..90\n ((i + shift - 65) % 26 + 65).chr\n when 97..122\n ((i + shift - 97) % 26 + 97).chr\n else\n i.chr\n end\n end\n encrypted\nend",
"def caesar_cipher(string, shift)\n alphabet = Array('a'..'z')\n encrypter = Hash[alphabet.zip(alphabet.rotate(shift))]\n string.chars.map { |c| encrypter.fetch(c, \" \") }\nend",
"def caesar_cipher(string_to_cipher, shift)\n shifted_string = \"\"\n string_to_cipher.chars.map do |char|\n ascii = char.ord\n if ((65..90) === ascii || (97..122) === ascii) then \n ascii += shift \n if (ascii > 90 && ascii < 97) || (ascii > 122) then\n ascii -= 26\n end\n end\n shifted_string += ascii.chr\n\n end\n shifted_string\nend",
"def caesar_cipher(string, shift_factor = 0)\n result = ''\n string.each_char do |char|\n # use cipher only if char is an uppercase or lowercase letter\n if char.ord.between?(65, 90) || char.ord.between?(97, 122)\n new_code = char.ord + shift_factor\n\n #ensure wrapping from Z to A or z to a\n new_code -= 26 if (new_code > 91 && char.ord < 91) || new_code > 122\n result += new_code.chr\n else\n result += char\n end\n end\n result\nend",
"def caesar_cipher text, shift = 5 #shifts letters by 5 - by default\nletters = text.split(//)\nncrypted_string = \"\"\nletters.each do |x|\nif (x =~ /\\w/) && (x =~ /\\D/) && (x != \"_\") ##Checks with RegEx's whether the current array index' value is a word character + a non-digit character + not an underscore '_', so only a-z & A-Z letters pass the test and are affected by the following code.\nif x == x.upcase ##<-I do this so I can wrap back to A when Z's #ord index is exceeded. \"A\".ord == 65, \"Z\".ord == 90\nx = x.ord + shift\nif x > 90\nx -= 90\nx += 64\nend\nelsif x == x.downcase ##Same is done here for downcases as is done above for upcases. \"a\".ord == 97, \"z\".ord == 122\nx = x.ord + shift\nif x > 122\nx -= 122\nx += 96\nend\nend\nx.chr\nend\nncrypted_string << x\nend\nputs ncrypted_string\nend",
"def caesar_cipher(offset, string)\n\talph = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]\n\ti = 0\n\tnew_string = \"\"\n\tind = 0\n\n\tputs string.length \n\n\twhile i < string.length\n\t\t\n\t\t\n\t\t\n\t\tif string[i] == \" \"\n\t\t\tnew_string = new_string + \" \"\n\t\t\t\n\t\telse \n\t\t\tind = alph.index(string[i])\n\t\t\t\n\t\t\tif (ind + offset) > 25\n\t\t\t\tind = (ind + offset) - 26 \n\t\t\t\t\n\t\t\t\tnew_string = new_string + alph[(ind)]\n\t\t\t\t\n\t\t\telse \n\t\t\t\tnew_string = new_string + alph[(ind + offset)]\n\t\t\t\t\n\t\t\tend\n\t\tend\n\t\ti +=1\n\tend\n\n\treturn new_string\n\nend",
"def ceasar_cipher(phrase, shift)\n phrase.downcase!\n words = phrase.split(\" \")\n words.each do |word| #for each word in the sentence\n word.split(\"\").each_with_index do |letter, index| #for each letter in the word\n asciiValue = letter.ord\n if(asciiValue >= 97 && asciiValue <= 122) #if the value is a letter and not a character or digit\n\n newValue = asciiValue + shift\n \n if newValue > 122 #if it goes beyond z, loop around back to a\n difference = newValue - 122\n offset = 96+difference\n letter = offset.chr\n word[index] = letter\n else\n letter = newValue.chr \n word[index] = letter\n end\n end \n end\n end\n puts words.join(\" \")\nend",
"def caesar_cipher(str, shift)\n result = \"\"\n str.each_char do |char|\n if char == \" \"\n result += \" \"\n next\n else\n shift.times { char == \"z\" ? char = 'a' : char = char.next }\n result += (char)\n end\n end\n result\nend",
"def caesar_cipher(word, shift) \n\n #Checks if 'word' is a String \n unless word.is_a? String\n return \"Input was not text\"\n end\n\n #Initializes a temp word\n new_word = \"\"\n\n #Creates an array of ascii numbers for each letter in 'word'\n word_array = word.codepoints.to_a\n\n #Loops over each letter in 'word' and manipulates\n for i in 0..word_array.length-1\n\n #Keeps track of the letter casing\n lowercase = false\n if word_array[i] >= 97 && word_array[i] <= 122\n lowercase = true\n else\n lowercase = false\n end\n\n #Adds the shift to the letter (checks if the character is a letter and not a symbol or space)\n if word_array[i] >= 65 && word_array[i] <= 122\n word_array[i] += shift\n end\n\n # Checks character ascii values\n if word_array[i] > 122 && lowercase == true\n word_array[i] -= 26\n elsif word_array[i] > 90 && lowercase == false\n word_array[i] -= 26\n end\n new_word += word_array[i].chr\n end\n return new_word\nend",
"def caesar_cipher(phrase, shift)\n shifted_array = phrase.chars.map {|char| shift_letter(char, shift)}\n new_phrase = shifted_array.join\nend",
"def caesar_cipher(text, shift)\n upper = ('A'..'Z').to_a\n lower = ('a'..'z').to_a\n shifted = text.split('').map do |character|\n case character\n when /[[:upper:]]/ then \n (upper.rotate(shift))[upper.index(character)]\n when /[[:lower:]]/ then \n (lower.rotate(shift))[lower.index(character)]\n else character\n end\n end\n shifted.join\nend",
"def caesar_cipher(shift, string)\n alphabet = (\"a\"..\"z\").to_a\n blank = string.each_char.map do |letter| alphabet.include?(letter) ? alphabet[(alphabet.index(letter) + shift) % alphabet.length] : letter\n end\n return blank.join #must use return not puts, otherwise tests will not pass! Also no (\" \") needed because mapping adds a \" \"\n #in between every letter and a \"nil\" + \" \" in between every word, and join deletes the spaces in between the letters\n #and deletes the nil in between words, leaving one space in between words.\nend",
"def caesar_cipher(word, shift)\n ascii_shift = 97\n word.each_codepoint.map do |num|\n num = num - ascii_shift + shift\n num = (num % 26) + ascii_shift\n end\n .inject('', :<<)\nend",
"def caesar_cipher(offset, string)\n words = string.split(\" \")\n\n word_idx = 0\n while word_idx < words.length\n word = words[word_idx]\n\n letter_idx = 0\n while letter_idx < word.length\n char_i = word[letter_idx].ord - \"a\".ord\n\n new_char_i = (char_i + offset) % 26\n word[letter_idx] = (\"a\".ord + new_char_i).chr\n\n letter_idx += 1\n end\n\n word_idx += 1\n end\n\n return words.join(\" \")\nend",
"def Caesar_Cypher(string, shift_factor)\n coded_array = []\n arr = string.split(\"\")\n\n arr.each do |letter|\n ascii_letter = letter.ord\n\n if ascii_letter.between?(65, 90)\n ascii_letter += shift_factor\n if ascii_letter > 90\n ascii_letter -= 26\n end\n elsif ascii_letter.between?(97, 122)\n ascii_letter += shift_factor\n if ascii_letter > 122\n ascii_letter -= 26\n end\n end\n\n coded_array.push(ascii_letter.chr)\n end\n\n cypher = coded_array.join(\"\")\n p cypher\nend",
"def caesar_cipher phrase, shift\n\tphrase.split('').map { |char| \n\t\tif (char.match(/[a-z]/))\n\t\t\t((((char.ord - 97) + shift) % 26) + 97).chr\n\t\telsif (char.match(/[A-Z]/))\n\t\t\t((((char.ord - 65) + shift) % 26) + 65).chr\n\t\telse\n\t\t\tchar\n\t\tend\n\t}.join\nend",
"def caesar_cipher(text, shift=0)\n return text if shift == 0 || text == \"\" || shift.nil? || text.nil?\n standard_key_caps = (\"A\"..\"Z\").to_a\n standard_key_lower = (\"a\"..\"z\").to_a\n\n while shift < 0 do\n shift += 26\n end\n\n i = shift % 26\n\n\n shift_key_caps = []\n range = ('A'..'Z').to_a\n range.each do |x|\n shift_key_caps[i] = x\n i+=1\n i=0 if i >= 26\n end\n\n i=shift\n shift_key_lower = []\n range = ('a'..'z').to_a\n range.each do |x|\n shift_key_lower[i] = x\n i+=1\n i=0 if i >= 26\n end\n\n text_mod = \"\"\n text.each_char do |x|\n character = x\n if standard_key_caps.include?(x)\n offset = shift_key_caps.index(x)\n character = standard_key_caps[offset]\n elsif standard_key_lower.include?(x)\n offset = shift_key_lower.index(x)\n character = standard_key_lower[offset]\n end\n text_mod = text_mod + character\n end\n text_mod\nend",
"def caesar_cipher(str, shift)\n shifted = \"\"\n words = str.split(\" \")\n words.each do |word|\n word.each_char do |char|\n shifted += shift_char(char, shift)\n end\n shifted += \" \"\n end\n shifted[0...-1]\nend",
"def caesar_cipher2(message, offset)\n\n\toffset %= 26\n\tcipher = ''\n\n\t# Direction is relevant\n\tincrement = true if offset > 0\n\n\tif increment\n\t\tmessage.each_char do |c|\n\t\t\toffset.times do\n\t\t\t\tif c.match(/[A-Ya-y]/)\n\t\t\t\t\tc.next! # No wrap required on these letters, increment\n\t\t\t\telse\n\t\t\t\t\tif c.match(/Z/) #Wrap required\n\t\t\t\t\t\tc = 'A'; end\n\t\t\t\t\tif c.match(/z/)\n\t\t\t\t\t\tc = 'a'; end; end; end\n\t\t\tcipher << c # Insert scrambled character to output string\n\t\tend\n\telse # decrement\n\t\tmessage.each_char do |c|\n\t\t\toffset.abs.times do # Use absolute value, can't do a loop negative times!\n\t\t\t\tif c.match(/[B-Zb-z]/)\n\t\t\t\t\tc = (c.ord - 1).chr # Quick shuffling using ASCII value\n\t\t\t\telse\n\t\t\t\t\tif c.match(/A/) # Reverse wrap required\n\t\t\t\t\t\tc = 'Z'; end\n\t\t\t\t\tif c.match(/a/) \n\t\t\t\t\t\tc = 'z'; end; end; end\n\t\t\tcipher << c # Insert scrambled character to output string\n\t\tend\n\tend\n\n\treturn cipher\nend",
"def caesar_cipher(input, shift)\n\toutput = \"\"\n\t\n\tinput.each_byte do |ascii|\n\t\t# Take each character's ASCII code\n\t\tif ascii >= 65 && ascii <= 90\n\t\t\t# If character is uppercase letter:\n\t\t\tascii -= 65 \t\t\t\t\t# Subtract to A=0, Z=25\n\t\t\tascii = (ascii + shift) % 26 \t# Shift with wrapping Z-to-A\n\t\t\tascii += 65\t\t\t\t\t\t# Add back to new ASCII code\n\t\t\toutput += ascii.chr\t\t\t\t# Add ASCII character to output\n\t\telsif ascii >= 97 && ascii <= 122\n\t\t\t# If character is lowercase letter:\n\t\t\tascii -= 97 \t\t\t\t\t# Subtract to a=0, z=25\n\t\t\tascii = (ascii + shift) % 26 \t# Shift with wrapping z-to-a\n\t\t\tascii += 97\t\t\t\t\t\t# Add back to new ASCII code\n\t\t\toutput += ascii.chr\t\t\t\t# Add ASCII character to output\n\t\telse\n\t\t\toutput += ascii.chr\t\t\t\t# Else just add character to output\n\t\tend\n\tend\n\toutput\nend",
"def caesar_cipher(str, num)\n new_str = \"\"\n str.each_char { |c| new_str += shift_char(c, num) }\n new_str\nend",
"def solve_cipher (message, shift:-3)\n \n #Iterate over message\n message.each_char do |c|\n\n\n \t#Calculate the integer ordinal of the char\n \tindex = c.ord\n\n \t\n \t#If lower case\n \tif (97..122) === index\n\t \t#Positive shift\n\t \tif shift > 0\n\t \t\t#If it's a \"special\" letter apply the \"special\" cipher , if not apply the \"normal cipher\" \n\t \t\tif index+shift>122\n\t \t\t\tprint (97+(index+shift-123)).chr \t\t\n\t \t\telse \n\t \t\t\tprint (index+shift).chr\n\t \t\tend\n\t \t#Negative shift\n\t \telsif shift < 0 \n\t \t\t#If it's a \"special\" letter apply the \"special\" cipher , if not apply the \"normal cipher\" \n\t \t\tif index+shift<97\n\t \t\t\tprint (123-(97-index)+shift).chr \t\t\n\t \t\telse \n\t \t\t\tprint (index+shift).chr\n\t \t\tend\n\n\t \telse\n\t \t\tprint index.chr \t\t\n\t \tend\n\t#If upper case\n\telsif (65..90) === index\n\t \t#Positive shift\n\t \tif shift > 0 \n\t \t\t#If it's a \"special\" letter apply the \"special\" cipher , if not apply the \"normal cipher\"\n\t \t\tif index+shift>90\n\t \t\t\tprint (65+(index+shift-91)).chr \t\t\n\t \t\telse \n\t \t\t\tprint (index+shift).chr\n\t \t\tend\n\t \t#Negative shift\n\t \telsif shift < 0 \n\t \t\t#If it's a \"special\" letter apply the \"special\" cipher , if not apply the \"normal cipher\" \n\t \t\tif index+shift<65\n\t \t\t\tprint (91-(65-index)+shift).chr \t\t\n\t \t\telse \n\t \t\t\tprint (index+shift).chr\n\t \t\tend\n\n\t \telse\n\t \t\tprint index.chr \t\t\n\t \tend\n\t#If other character\n\telse\t\t\n\t \t\tprint index.chr \n\tend\n\t\t\n \t\t\n end\nend",
"def caesar_cipher(userWord, userShift)\n userWordArray = userWord.split(\"\") #Makes an array of characters\n shift = userShift%26\n c = []\n userWordArray.each do |letter|\n if letter.ord == 32\n c.push(letter)\n elsif letter.ord < 122\n b = letter.ord + shift\n c.push(b.chr)\n else\n b = letter.ord \n diff= (b-122) + shift\n b = 96+diff\n c.push(b.chr)\n end\n end\n c = c.join\nend",
"def caesar_cipher(string, shift)\n result = \"\"\n string.each_char do |ch|\n result += ch == \" \" ? ch : shift(ch, shift)\n end\n result\nend",
"def vigenere_cipher(str, arr)\n alpha = ('a'..'z').to_a\n new_msg = ''\n\n str.each_char.with_index do |char,idx|\n old_pos = alpha.index(char)\n new_pos = old_pos + arr[idx % arr.length]\n new_msg += alpha[new_pos % 26]\n end\n new_msg\nend",
"def cipher(string, shift)\n message = (string.chars.map do |char|\n shift.times { char.next! } if /[A-Za-z]/.match(char)\n char[0]\n end).join\n puts message\nend",
"def caesar_cipher(word, shift)\n\tletters = ('a'..'z').to_a.concat(('A'..'Z').to_a) # create array of all possible chars\n\tdecoded = \"\"\n\n\tword.each_char do |c| \n\t\tif letters.include?(c)\t\n\t\t\tdecoded += letters[letters.index(c) - shift]\n\t\telse\n\t\t\tdecoded += c # adds non-alpha char to the decoded string\n\t\tend\n\tend\n\t decoded\nend",
"def caesar_cipher(word, shift)\n\tletters = ('a'..'z').to_a.concat(('A'..'Z').to_a) # create array of all possible chars\n\tdecoded = \"\"\n\n\tword.each_char do |c| \n\t\tif letters.include?(c)\t\n\t\t\tdecoded += letters[letters.index(c) - shift]\n\t\telse\n\t\t\tdecoded += c # adds non-alpha char to the decoded string\n\t\tend\n\tend\n\t decoded\nend",
"def vigenere_cipher(message, keys)\n alphabet = (\"a\"..\"z\").to_a\n indices = message.split(\"\").map {|char| alphabet.index(char)}\n \n ciphered_message = \"\"\n indices.each_with_index do |n, i|\n shift_amount = keys[i % keys.length]\n new_index = (n + shift_amount) % alphabet.length\n ciphered_message += alphabet[new_index]\n end\n\n ciphered_message\nend",
"def caesar_cipher(string, shift = 1)\n alphabet = Array('a'..'z')\n non_caps = Hash[alphabet.zip(alphabet.rotate(shift))]\n \n alphabet = Array('A'..'Z')\n caps = Hash[alphabet.zip(alphabet.rotate(shift))]\n \n encrypter = non_caps.merge(caps)\n \n string.chars.map { |c| encrypter.fetch(c, c) }\nend",
"def caesar_cypher(string, shift)\n string.split('').map do |char|\n if char == ' '\n char\n elsif char.ord + shift > 'z'.ord\n (char.ord + shift - 26).chr\n else\n (char.ord + shift).chr\n end\n end.join('')\nend",
"def caesar_cipher(str, num)\n alphabet = \"abcdefghijklmnopqrstuvxyz\"\n new_str = \"\"\n \n str.each_char do |char|\n old_idx = alphabet.index(char) # each items index on the alphabet\n\tnew_idx = old_idx + num\n\tnew_char = alphabet[new_idx % 26] # to ensure that results is always less than 26 e.g. 'z' + 4 will fail without this, will now return to 'a' + 4 = 'd'.\n\tnew_str += new_char\n\tend\n \n return new_str\n\nend",
"def solve_cipher(input, shift=nil)\n\n# Setting -3 as defautl shift\n\tif shift.nil? \n\t\tshift = -3\n\tend\n\n\n# Positive numbers shift right and negative numbers shift left \n\tif shift < 0\n\t\tshift = -shift\n\tend\n\n\toutput = \"\"\n\t(input.split\"\").each do |letra|\n\n\t\t# Spaces remain as spaces\n\t\tif letra == \" \"\n\t\t\toutput << \" \"\n\n\t\t# a will be z in case of shift = 1\n\t\telsif letra == 'a'\n\t\t\tindice = 122 + shift\n\n\t\telse\n\t\t\tindice = letra.ord - shift\n\n\t\toutput << indice.chr\n\t\tend\n\tend\n\tputs output\nend",
"def caesar_cipher(string,num)\n alpha = (\"a\"..\"z\").to_a \n string_array = \"\"\n string.each_char do |char|\n if alpha.include?(char)\n old_index = alpha.index(char)\n new_index = old_index + num \n string_array += alpha[new_index % 26]\n else\n string_array += char \n end\n\n end\n return string_array\nend",
"def caeser_cipher(message, inc)\n message.downcase!\n alphabet = (\"a\"..\"z\").to_a\n message_array = message.split(//)\n puts(message_array)\n\n message_index_array = message_array.map do |e|\n alphabet.index(e)\n end\n\n puts(message_index_array)\n rotated = alphabet.rotate(inc)\n puts(rotated)\n\n crypted_array = message_index_array.map do |e|\n if e == nil\n \" \"\n else\n rotated[e]\n end \n end\n\n crypted_array.join\n #it iterates through the message array, and finds the index of each character within the alphabet\n #the alphabet array shifts based on inc\n #each chacter in the message array is swapped out for it's indexed counterpart. \nend",
"def caesar_cipher(str, num)\n new_str = \"\"\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n str.each_char do |char|\n old_index = alphabet.index(char)\n new_index = old_index + num\n new_char = alphabet[new_index % 26] # MOST IMPORTANT STEP!!!!! THIS WILL ALSO TAKE CARE OF new_index > 26\n new_str += new_char\n end\n return new_str\nend",
"def vigenere_cipher(msg, arr)\n alphabet = (\"a\"..\"z\").to_a\n new_msg = \"\"\n msg.each_char.with_index do |char, i|\n pos= alphabet.index(char)\n key = arr[i % arr.length]\n new_pos = (pos + key) % alphabet.length\n new_msg += alphabet[new_pos]\n end\n new_msg\nend",
"def caesar_cipher(str, num)\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n new_str = \"\"\n \n\tstr.each_char do |char|\n old_idx = alphabet.index(char)\n new_idx = old_idx + num\n new_char = alphabet[new_idx % 26]\n new_str += new_char\n\n end\n return new_str\n\nend",
"def caesar(str,shift)\n str_split = str.split(\"\")\n str_shift = str_split.map{|char| char_shift(char, shift)}\n str_final = str_shift.join(\"\")\n end",
"def caesar_cipher(str, shift)\n res = [] \n str.split(\" \").each do |word|\n res << encode_word(word, shift)\n end\n res.join(' ')\nend",
"def caesar_cipher(str, num)\r\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\r\n new_str = \"\"\r\n\r\n str.each_char do |char|\r\n old_idx = alphabet.index(char)\r\n new_idx = old_idx + num\r\n new_char = alphabet[new_idx % 26]\r\n new_str += new_char\r\n end\r\n\r\n return new_str\r\nend",
"def decrypt_caesar_cipher(string, shift = -@offset_value.to_i)\n alphabet = Array('a'..'z')\n encrypter = Hash[alphabet.zip(alphabet.rotate(shift))]\n string.chars.map { |c| encrypter.fetch(c, \" \") }\nend",
"def caesar_cipher(string, shift = 1)\n alphabet = Array('a'..'z')\n non_caps = Hash[alphabet.zip(alphabet.rotate(shift))]\n \n alphabet = Array('A'..'Z')\n caps = Hash[alphabet.zip(alphabet.rotate(shift))]\n \n encrypter = non_caps.merge(caps)\n \n string.chars.map { |c| encrypter.fetch(c, c) }\n end",
"def caesar_cipher(str, num)\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n new_str = \"\"\n\n str.each_char do |char|\n old_idx = alphabet.index(char)\n new_idx = old_idx + num\n new_char = alphabet[new_idx % 26]\n new_str += new_char\n end\n\n return new_str\nend",
"def caesar_cipher(str, num)\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n new_str = \"\"\n\n str.each_char do |char|\n old_idx = alphabet.index(char)\n new_idx = old_idx + num\n new_char = alphabet[new_idx % 26]\n new_str += new_char\n end\n\n return new_str\nend",
"def solve_cipher(input_array,shift)\n\toutput_array = []\n\tinput_array.each do |char|\n\t\tpos1 = char.ord\n\t\tpos2 = pos1 + shift\n\t\tif pos2 < 97\n\t\t\tpos3 = 123 - (97 - pos2) \n\t\t\toutput_array << pos3.chr\n\t\telsif pos2 > 122\n\t\t\tpos3 = 96 + (pos2 - 122) \n\t\t\toutput_array << pos3.chr\n\t\telse\n\t\t\toutput_array << pos2.chr\n\t\tend\n\tend\n\toutput_array\nend",
"def caesar_cipher(str, shift)\n word = str.split(\" \")\n ans = \"\"\n word.each do |var|\n if var == word.last\n ans << caeser_helper(var, shift)\n else\n ans << caeser_helper(var, shift) + \" \"\n end\n end\n \n ans\nend",
"def caesar_cypher (text, shift)\n\tupper = (\"A\"..\"Z\").to_a\n\tlower = (\"a\"..\"z\").to_a\n\ttext_a = text.chars\n\tfinished = \"\"\n\ttext_a.each do |char|\n\t\t# Check if the character is uppercase\n\t\tif upper.include?(char)\n\t\t\tindex = upper.index(char)\n\t\t\tindex += shift\n\t\t\twhile index >= upper.length\n\t\t\t\tindex -= upper.length\n\t\t\tend\n\t\t\tfinished << upper[index]\n\t\t# Check if it's lowercase\n\t\telsif lower.include?(char)\n\t\t\tindex = lower.index(char)\n\t\t\tindex += shift\n\t\t\twhile index >= lower.length\n\t\t\t\tindex -= lower.length\n\t\t\tend\n\t\t\tfinished << lower[index]\n\t\t# Append all miscellaneous characters that don't match\n\t\telse\n\t\t\tfinished << char\n\t\tend\n\tend\n\tfinished\nend",
"def encipher(char, shift) \n if char >= 65 && char <= 90 \n index = char - 65\n shifted_char = (index + shift) % 26\n if shifted_char < 0 \n shifted_char += 26\n enciphered_char = shifted_char + 65\n else\n enciphered_char = shifted_char + 65\n end\n elsif char >= 97 && char <= 122\n index = char - 97\n shifted_char = (index + shift) % 26\n if shifted_char < 0\n shifted_char += 26\n enchiphered_char = shifted_char + 97\n else \n enciphered_char = shifted_char + 97\n end\n else\n char = char \n end\nend",
"def caesar_cipher(sentence, raw_offset)\r\n offset = raw_offset % 26\r\n sentence.gsub(/([a-zA-Z])/){|char| shift_the_letter(char.ord, offset).chr}\r\nend",
"def caesar_cipher(str, shift)\n new_str = []\n str = str.split('')\n str.each do |x| \n new_str << letter_cipher(x, shift) \n end\n new_str = new_str.join\n puts new_str\n return new_str\nend",
"def caesar_cipher(str, num)\n \tnew_str = \"\"\n\n \tstr.each_char do |c|\n new_letter = c.ord + num\n if new_letter > 122\n shift = ((new_letter - 96) % 26) + 96\n new_str += shift.chr\n else\n new_str += new_letter.chr\n end\n end\n return new_str\nend",
"def vigenere_cipher(str, arr)\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n results = \"\"\n str.each_char.with_index do |char, i|\n ind = (alphabet.index(char) + arr[0]) % 26\n results += alphabet[ind]\n arr.rotate!\n end\n results\nend",
"def caesar_cipher(str, num)\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n cipher = ''\n\n (0...str.length).each do |i|\n char = str[i]\n index = alphabet.index(char) + num\n cipher += alphabet[index % 26]\n end\n return cipher\nend",
"def solve_cipher(input, shift)\n words = input.split(\"\")\n \n string_container = \"\" \n words.each do | letter|\n \tif letter == \" \"\n \t\tstring_container += \" \"\n\n \telse\n \tstring_container += (letter.ord + shift).chr\n\tend\n end\n\tstring_container\n\t#your code goes here\nend",
"def caesar_cipher(text_to_cipher, key)\n # ensure key is a value between 0 and 25\n key = key % 26\n\n text_to_cipher.split(\"\").map do |character|\n if letter?(character)\n shift(character, key)\n else\n character\n end\n end.join(\"\")\n\nend",
"def caesar_cipher(message, offset)\n\t\n\tchars\t= \t[]\n\tnums \t= \t[]\n\t\n\tif offset > -1\n\t\toffset = offset % 26\n\telse\n\t\toffset = -offset % 26\n\t\toffset = -offset; end\n\n\twords = message.split(\" \") # Make an array of words from the input, strip spaces\n\twords.each do |word| # From each word....\n\t\tchars.push(word.split(\"\")); end # Construct a sub-array of its characters\n\t\n\tchars.each do |char| # On each character....\n\t\tnums.push(char.map(&:ord)); end # Send the ASCII integer value to a new array\n\n\tfor i in 0...nums.length do # Step through each word\n\t\tfor j in 0...nums[i].length do # And each character\n\t\t\tnums[i][j] += offset # Alter the ASCII value by the offset\n\t\t\tnums[i][j] = nums[i][j].chr; end; end # Translate back, ASCII->String\n\n\treturn nums\nend",
"def caesar_cipher(str, num)\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n new_str = \"\"\n \n str.each_char do |char|\n old_idx = alphabet.index(char)\n new_idx = old_idx + num\n new_char = alphabet[new_idx % 26]\n new_str += new_char\n end\n\n return new_str\nend",
"def caesar_cipher(str, num)\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n new_str = \"\"\n \n str.each_char do |char|\n old_idx = alphabet.index(char)\n new_idx = old_idx + num\n new_char = alphabet[new_idx % 26]\n new_str += new_char\n end\n \n return new_str\nend",
"def vigenere_cipher(message, keys)\n alphabet = (\"a\"..\"z\").to_a\n encrypted = \"\"\n\n message.each_char.with_index do |char, idx|\n shift = keys[idx % keys.length]\n encrypted += alphabet[(alphabet.index(char) + shift) % 26]\n end\n\n encrypted\nend",
"def vigenere_cipher(message, keys)\n alpha = (\"a\"..\"z\").to_a\n count = 0\n message.each_char.with_index do |char, idx|\n pos = alpha.index(char)\n #rather than count we can do key alpha[(pos + key[idx % key.length] )% 26]\n message[idx] = alpha[(pos + keys[count]) % alpha.length]\n count += 1\n count = 0 if count == keys.length\n end\n message\nend",
"def cipher(sentence, shift)\n # Funtion to cipher the word given a specific shift value to change the letter\n lowercase = 'abcdefghijklmnopqrstuvwxyz'\n uppercase = lowercase.upcase\n\n ciphered_word = []\n\n sentence.each_char.with_index do |char, idx|\n\n if lowercase.include?(char)\n index = lowercase.index(char)\n ciphered_word << lowercase[(index + shift) % 26]\n elsif uppercase.include?(char)\n index = uppercase.index(char)\n ciphered_word << uppercase[(index + shift) % 26]\n else\n ciphered_word << char\n end\n end\n\n return ciphered_word.join('')\n\nend",
"def cipher(str, shift)\n alphabet = (\"a\"..\"z\").to_a\n \n i = 0\n while i < str.length \n if str[i] == \" \"\n i += 1\n next\n end \n char = str[i]\n prevIdx = alphabet.index(char)\n newIdx = (prevIdx + shift) % 26\n str[i] = alphabet[newIdx]\n i += 1\n end \n str\nend",
"def caesar_cipher(str, num)\n \talphabet = \"abcdefghijklmnopqrstuvwxyz\"\n \tcipher = \"\"\n\n\tstr.each_char do |char|\n \tletterPos = alphabet.index(char)\n \tnewPos = letterPos + num\n \tcipher += alphabet[newPos % 26] # mod so wraps arround\n end\n \n \treturn cipher\nend",
"def letter_cipher(letter, shift)\n if not letter?(letter)\n return letter\n end\n cap_start = 'A'.ord\n low_start = 'a'.ord\n if is_upper(letter)\n start = cap_start\n else\n start = low_start\n end\n mod_letter = (letter.ord + shift - start)\n if mod_letter >= 26\n if is_upper(letter)\n start = low_start\n else\n start = cap_start\n end\n end\n mod_letter = start + mod_letter % 26\n return mod_letter.chr\nend",
"def vigenere_cipher(message, keys)\n alpha = (\"a\"..\"z\").to_a\n new_string = \"\"\n message.each_char.with_index do |char, i|\n old_i = alpha.index(char)\n new_i = (old_i + keys[i % keys.length]) % 26\n new_string += alpha[new_i]\n end\n new_string\nend",
"def vigenere_cipher(message, keys)\n alphabet = (\"a\"..\"z\").to_a\n new_msg = \"\"\n\n message.each_char.with_index do |char|\n old_pos = alphabet.index(char)\n new_pos = old_pos + keys[idx % keys.length]\n new_msg += alphabet[new_pos % alphabet.length]\n end\n\n new_msg\nend"
] |
[
"0.8599134",
"0.8594511",
"0.85886806",
"0.8567948",
"0.856101",
"0.8551369",
"0.85338473",
"0.85260546",
"0.85254586",
"0.85237694",
"0.85232854",
"0.85210884",
"0.8505192",
"0.8492382",
"0.8481106",
"0.84583384",
"0.8453188",
"0.84526193",
"0.84524393",
"0.84277356",
"0.84205496",
"0.84076977",
"0.840097",
"0.8380515",
"0.83795345",
"0.8361592",
"0.8338148",
"0.83324057",
"0.8330208",
"0.83223045",
"0.8298412",
"0.82956916",
"0.82921624",
"0.8271665",
"0.8257094",
"0.8253757",
"0.82530516",
"0.82492554",
"0.82315946",
"0.82019246",
"0.8197925",
"0.8194209",
"0.81918776",
"0.8177468",
"0.8151156",
"0.81496835",
"0.8123785",
"0.81151927",
"0.808733",
"0.8081223",
"0.807814",
"0.8049239",
"0.80396986",
"0.8024585",
"0.8022605",
"0.8021422",
"0.80162567",
"0.8014931",
"0.79732925",
"0.7961071",
"0.7961071",
"0.7959046",
"0.7959003",
"0.7956293",
"0.795229",
"0.7931297",
"0.79188937",
"0.78956807",
"0.7890587",
"0.7866824",
"0.7866051",
"0.7840811",
"0.78333557",
"0.7826793",
"0.78071284",
"0.7797653",
"0.7791424",
"0.77826697",
"0.77763665",
"0.77759063",
"0.7768814",
"0.77685535",
"0.7764233",
"0.77627736",
"0.77598125",
"0.77526355",
"0.77440894",
"0.77338064",
"0.7731096",
"0.77266467",
"0.77206874",
"0.7713767",
"0.7705032",
"0.76834047",
"0.7682327",
"0.7666581",
"0.7647607",
"0.7647089",
"0.7626238",
"0.7615621"
] |
0.8459711
|
15
|
Write a recursive method that takes in a base 10 number n and converts it to a base b number. Return the new number as a string E.g. base_converter(5, 2) == "101" base_converter(31, 16) == "1f"
|
def base_converter(num, b)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def base_converter(num, b)\n\n return num.to_s if [0, 1].include?(num)\n\n digits = %w(0123456789abcdef)\n base_converter(num/b, b) + digits[num % b]\n\nend",
"def base_converter(num, b)\n return \"\" if num == 0\n digits = %w(0 1 2 3 4 5 6 7 8 9 a b c d e f)\n\n base_converter(num/b, b) + digits[num%b]\n end",
"def base_converter(num, b)\n return num.to_s if [0,1].include?(num)\n\n digits = %w(0 1 2 3 4 5 6 7 8 9 a b c d e f)\n base_converter(num/b, b) + digits[num % b]\nend",
"def toBase(n, base)\n return n.to_s(base) if base > 0\n return '0' if n.zero?\n\n digits = []\n while n != 0\n n, remainder = n.divmod(base)\n if remainder < 0\n n += 1\n remainder -= base\n end\n digits << remainder\n end\n digits.join.reverse\nend",
"def num_to_s(num, base)\n raise \"Please give a base greater than 1 and less than 16\" if base <= 1 || base > 16\n\n number_string_hash = {0 =>\"0\", 1 =>\"1\", 2 =>\"2\", 3 =>\"3\", 4 =>\"4\", 5 =>\"5\", 6 =>\"6\",\n 7 =>\"7\", 8 =>\"8\", 9 =>\"9\" }\n \n if base > 10\n num = num.to_i(base)\n base = 10\n end\n \n num_string = \"\"\n num_place = 0\n while num > 0\n current_digit = (num / base**num_place) % base\n num = num - (current_digit * (base**num_place))\n num_string.prepend(number_string_hash[current_digit])\n num_place += 1\n end\n num_string\nend",
"def convert( number, base )\n if(number < base)\n return @digits[number]\n else\n return convert( number / base, base ) + @digits[ number % base ]\n end\n end",
"def binarify(base_ten_num)\n raise 'input must be an integer' if base_ten_num.is_a?(String)\n base_ten_num.to_s(2)\nend",
"def convert_to_base_8(n)\n n.to_s(8).to_i # replace these two method calls\nend",
"def convert_base(base, integer, target_base)\n x = 0\n result = ''\n\n start_pos = (integer[0] == '-') ? 1 : 0\n\n for i in start_pos..(integer.length - 1)\n x *= base\n x += (integer[i].ord - '0'.ord < 10) ? integer[i].ord - '0'.ord : integer[i].ord - 'A'.ord + 10\n end\n x\n\n\n while (x > 0)\n remainder = x % target_base\n result.prepend (remainder < 10) ? remainder.to_s : ((remainder - 10) + 'A'.ord).chr\n x /= target_base\n end\n\n\n if start_pos == 1\n result.prepend '-'\n end\n\n result\nend",
"def convert(digits, from_base:, to_base:)\n if from_base > MAX || to_base > MAX || from_base < MIN || to_base < MIN\n raise InvalidRadix,\n \"cannot convert #{digits} from base #{from_base} to base #{to_base}\"\n end\n\n if from_base < 37 && to_base < 37\n return digits.to_s.to_i(from_base).to_s(to_base)\n end\n\n represent(value_of(digits.to_s, in_base: from_base), in_base: to_base)\n end",
"def convert_to_base_8(n)\n n.to_s(8).to_i\nend",
"def convert_to_base_8(n)\n n.to_s(8).to_i\nend",
"def convert_to_base_8(n)\r\n #n.method_name.method_name # replace these two method calls\r\n n.to_s(8).to_i\r\nend",
"def to_s(base = 2)\n case base \n when 2\n inject(\"\") { |a, b| a + \"%0#{@bits}b \" % b }.strip\n when 10\n self.inject(\"\") { |a, b| a + \"%1d \" % b }.strip\n else\n raise(ArgumentError, \"unsupported base\")\n end\n end",
"def base10_to_base2(num)\n base2_ary = []\n\n MAX_POWER_OF_TWO.downto(0).each do |pow|\n if 2 ** pow <= num\n base2_ary << num / 2 ** pow\n num = num % 2 ** pow\n else\n base2_ary << 0\n end\n end\n\n base2_ary.join('').to_i\nend",
"def decimal_base(n)\n 10**(n-1)\nend",
"def binary_to_base_n(binaryarr, base)\n val = 0\n pow = 0\n while !binaryarr.empty?\n val += binaryarr.pop * 2**pow\n pow += 1\n end\n t = []\n num_to_digit_array(val, base).each do |dig|\n if dig > 9\n t << (('a'..'z').to_a[dig-10])\n else\n t << (dig)\n end\n end\n t.join\nend",
"def represent(number, in_base:)\n digits = \"\"\n\n while number > 0\n digits = CHARS[number % in_base] + digits\n number = number / in_base\n end\n\n digits\n end",
"def base2to10(binary)\n base_ten = 0\n binary.split(\"\").reverse.map {|digit| digit.to_i}.each_with_index {|digit, index| base_ten += digit * (2**index)}\n return base_ten\nend",
"def from_base(base=10)\n n = 0\n chars.reverse_each.with_index do |c, power|\n value = BASE_DIGITS[c]\n n += (base**power) * value\n end\n n\n end",
"def base_two(num)\n result = ''\n\n until num.zero?\n rem = num % 2\n num /= 2\n result += rem.to_s\n end\n\n result.reverse\nend",
"def convertCodeGolf(inStr, inBase, outBase)\n number = inStr.chars.reverse.map.with_index{ |c,i|\n inBase**i*$digits.index(c) }.reduce &:+\n intToStr(number, outBase)\nend",
"def base2to10(str_num)\n str = str_num.dup.reverse\n total = 0\n\n str.each_char.with_index do |char, idx|\n total += (char.to_i * (2 ** idx))\n end\n total\nend",
"def to_s(base=2)\n n = Bits.power_of_two(base)\n if n\n digits = (size+n-1)/n\n #{ }\"%0#{digits}d\" % @v.to_s(base)\n Numerals::Format[:fix, base: base].set_leading_zeros(digits).write(@v)\n else\n @v.to_s(base)\n end\n end",
"def to_bcd(n)\n n.to_s.gsub(/\\d/) {|d| \"%04b \" % d}.strip\nend",
"def to_s(base=nil)\n base.nil? ? super() : super().to_i(Gibbler.default_base).to_s(base)\n end",
"def integer_to_string(number)\n result = ''\n loop do\n number, remainder = number.divmod(10)\n # binding.pry\n result.prepend(DIGITS[remainder])\n break if number == 0\n end\n result\nend",
"def base2to10(binary)\n\tresult = 0\n digits = binary.chars.reverse\n\n digits.each_with_index do |bit, idx|\n result += bit.to_i * (2**idx)\n end\n\n result\nend",
"def integer_to_string(number)\n\n\tconversion = {0 => '0', 1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5',\n\t\t\t\t 6 => '6', 7 => '7', 8 => '8', 9 => '9' }\n\n\tnumber.digits.reverse.map do |num|\n\t\tconversion[num]\n\tend.join\n\nend",
"def toBinary (x)\n if (x>1)\n toBinary(x/2) + (x%2).to_s\n elsif x==1\n return x.to_s\n end\nend",
"def to_bits(base10_num)\n bits = @bit_vals.map do |b|\n if base10_num >= b\n base10_num -= b\n '1'\n else\n '0'\n end\n end\n bits.join\n end",
"def reverse(number)\n return number if number.to_s.length == 1 #1 is the last number to go\n number_array = number.to_s.split(\"\")\n first_element = number_array.pop #ie 2 (from base)\n new_number = number_array.join(\"\").to_i\n recursive_call = first_element.to_s + reverse(new_number).to_s #take advantage of string concat\n\n output_string = \"\"\n number = output_string + recursive_call\n number.to_i\nend",
"def super_digit(n)\n # base case\n return n if n/10 == 0\n \n # recursive case\n return super_digit(n/10 + n%10)\nend",
"def stringy number, count = 1\n binary_string = ''\n\n if count == 1\n (number / 2).times {binary_string << '10'}\n binary_string << '1' if number % 2 == 1\n elsif count == 0\n (number / 2).times {binary_string << '01'}\n binary_string << '0' if number % 2 == 1\n end\n\n binary_string\n end",
"def super_digit(n)\n s = n.to_s \n if s.length <= 1 # basecase here\n return n\n end\n \n sum = 0 \n s.split(\"\").each do |d|\n sum += d.to_i \n end\n \n return super_digit(sum)\nend",
"def int_to_binary_string(number)\n number.to_s(2)\nend",
"def decimal_to_binary(number)\n if number == 0\n 0\n else\n number % 2 + 10 * decimal_to_binary(number/2)\n end \nend",
"def super_digit(n)\n new_num = 0\n numbers = n.to_s.split(\"\")\n if numbers.length <= 1\n return n\n end\n numbers.each do |i|\n new_num += i.to_i\n end\n return super_digit(new_num)\nend",
"def to_s(base=nil, divider=nil)\n divider = divider.to_s if divider\n if base\n convert(base).to_s(nil, divider)\n else\n if code\n digits_encoded.join(divider)\n else\n if @base > 10\n digits.join(divider || DIVIDER)\n else\n digits.join(divider)\n end\n end\n end\n end",
"def integer_to_string(num)\n\tlookup_table = {0 => '0', 1 => '1', 2 => '2', 3 => '3', 4 => '4', \n\t\t\t\t\t5 => '5', 6 =>'6', 7 => '7', 8 => '8', 9 => '9'}\n \n result = ''\n\n if num.is_a? Integer\n num.digits.reverse.each do |number|\n result += lookup_table[number]\n end\n result\n else\n puts \"Invalid entry!\"\n end\nend",
"def super_digit(n)\n n < 10 ? n : super_digit(n / 10 + n % 10)\nend",
"def number_to_english(n)\n\n numbers_to_name = {\n 1000 => \"thousand\",\n 100 => \"hundred\",\n 90 => \"ninety\",\n 80 => \"eighty\",\n 70 => \"seventy\",\n 60 => \"sixty\",\n 50 => \"fifty\",\n 40 => \"forty\",\n 30 => \"thirty\",\n 20 => \"twenty\",\n 19=>\"nineteen\",\n 18=>\"eighteen\",\n 17=>\"seventeen\",\n 16=>\"sixteen\",\n 15=>\"fifteen\",\n 14=>\"fourteen\",\n 13=>\"thirteen\",\n 12=>\"twelve\",\n 11 => \"eleven\",\n 10 => \"ten\",\n 9 => \"nine\",\n 8 => \"eight\",\n 7 => \"seven\",\n 6 => \"six\",\n 5 => \"five\",\n 4 => \"four\",\n 3 => \"three\",\n 2 => \"two\",\n 1 => \"one\",\n 0 => \"zero\"\n }\n\n\n str = \"\"\n numbers_to_name.each do |num, name|\n\n if n == 0\n return str\n\n elsif n > 99999\n return str\n\n elsif n.to_s.length == 1 && n/num > 0\n return \"#{name}\"\n\n elsif n < 100 && n/num > 0\n\n return \"#{name}\" if n%num == 0\n return \"#{name} \" + number_to_english(n%num)\n\n elsif n/num > 0\n return number_to_english(n/num) + \" #{name} \" + number_to_english(n%num)\n\n end\n\n end\nend",
"def recursiveBaseExpansionOf(base, n, a)\n if n != 0\n q = (n/base).floor\n recursiveBaseExpansionOf(base, q, a << n - (q * base))\n else \n return a\n end\n end",
"def refined_super_digit(n, k)\n refined = \"\"\n\n k.times do \n refined += n.to_s \n end \n refined = refined.to_i\n\n super_digit(refined)\n\nend",
"def print_binary(n)\n puts \"print binary (#{n})\"\n if n < 0 \n print \"-\"\n print_binary(-n)\n \n elsif n < 2\n print n\n \n else\n last_digit = n % 2\n rest_of_digit = n / 2\n print_binary(rest_of_digit)\n print_binary(last_digit)\n end\nend",
"def super_digit(n)\n if 10 > n\n return n\n end\n\n last_digit = n % 10\n sum = n / 10 + last_digit \n \n return super_digit(sum)\nend",
"def super_digit(n)\n while n >= 10\n n = n % 10 + super_digit(n / 10)\n end\n return n\nend",
"def integer_to_string(number)\n hash_of_integers = { 0 => '0', 1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9'}\n \n string =''\n loop do\n\n number, digit = number.divmod(10)\n \n string.prepend(hash_of_integers[digit])\n break if number == 0\n end\n string\nend",
"def display_binary(n)\n if (n <= 0)\n return\n end\n display_string = binary_to_int(n).to_s\n display_string.tr!(\"[], \", \"\")\n display_string.reverse!\n puts \"#{n} in binary is: #{display_string}\"\n return display_string\nend",
"def super_digit(n)\n string_n = n.to_s\n return n if string_n.size == 1\n\n i = 1\n sum = string_n[0].to_i\n while i < string_n.size\n sum += string_n[i].to_i\n i += 1\n end\n return super_digit(sum)\nend",
"def super_digit(n)\n while n > 9\n n = n % 10 + super_digit(n / 10)\n end\n return n\nend",
"def super_digit(n)\n string_n = n.to_s\n return n if string_n.size == 1\n\n i = 1\n sum = string_n[0].to_i\n while i < string_n.size\n sum += string_n[i].to_i\n i += 1\n end\n return super_digit(sum)\n end",
"def super_digit(n)\n sum = 0\n while n >= 10 do\n sum += n % 10\n n /= 10\n end\n sum += n\n return sum < 10 ? sum : super_digit(sum)\nend",
"def super_digit(n)\n return n if n < 10 \n return super_digit(n.to_s.chars.map(&:to_i).sum)\nend",
"def integer_to_string(num)\n num.digits.map { |x| INT_CONVERT[x] }.reverse.join\nend",
"def super_digit(n)\n sum = 0\n\n if n < 10\n return sum + n\n else\n until n < 10\n sum += (n % 10)\n n /= 10\n end\n\n sum += n\n end\n\n return super_digit(n = sum)\nend",
"def super_digit(n)\n return n if n < 10\n sum = n.to_s.chars.map(&:to_i).sum\n return super_digit(sum)\nend",
"def super_digit(n)\n return n if n / 10 == 0\n return super_digit(digit_helper(n))\nend",
"def super_digit(n)\n return n if n / 10 < 1\n \n string = n.to_s.split(\"\")\n sum = 0\n \n string.each do |num|\n sum += num.to_i\n end\n \n return super_digit(sum)\nend",
"def num_into_string(number)\n puts number.ordinalize\nend",
"def num_to_string(number)\n case number\n when '1'\n \"one \"\n when '2'\n \"two \"\n when '3'\n \"three \"\n when '4'\n \"four \"\n when '5'\n \"five \"\n when '6'\n \"six \"\n when '7'\n \"seven \"\n when '8'\n \"eight \"\n when '9'\n \"nine \"\n when '10'\n \"ten \"\n when '11'\n \"eleven \"\n when '12'\n \"twelve \"\n when '13'\n \"thirteen \"\n when '14'\n \"fourteen \"\n when '15'\n \"fifteen \"\n when '16'\n \"sixteen \"\n when '17'\n \"seventeen \"\n when '18'\n \"eighteen \"\n when '19'\n 'nineteen '\n when '20'\n \"twenty \"\n when '30'\n \"thirty \"\n when '40'\n \"fourty \"\n when '50'\n \"fifty \"\n when '60'\n \"sixty \"\n when '70'\n \"seventy \"\n when '80'\n \"eighty \"\n when '90'\n \"ninty \"\n else\n \"\"\n end\nend",
"def convert_base(number, base)\n \n exponents = []\n n = 0 # Exponent / number position\n\n # Find the appropriate exponent size larger than the number \n while number != 0\n # puts \"Current top number: #{number}\"\n # puts \"Current exponent value: #{n}\"\n running_total = 0\n if number < base ** n\n # puts \"Base ** n: #{base ** n}\" \n # puts \"If loop current number: #{number}\"\n running_total += base ** (n-1)\n # puts \"If loop running_total: #{running_total}\"\n number = number - running_total\n # puts \"If loop number after subtraction: #{number}\"\n if exponents[n-1].nil? then exponents[n-1] = 1 else exponents[n-1] += 1 end\n n = 0\n else\n n += 1\n end\n end\n\n exponents.inspect\n\nend",
"def to_2digit(number)\n if number < 9\n number=\"0\"+number.to_s\n else\n number=number.to_s\n end\n return number\nend",
"def convert(num)\n return num.to_s\nend",
"def super_digit(n)\n return n if n < 10\n\n sum = 0 \n\n while n > 0\n digit = n % 10\n n /= 10\n sum += digit\n end\n\n super_digit(sum)\n\nend",
"def super_digit(n)\n return n if n.to_s.length == 1 \n\n return super_digit(digit_helper(n))\nend",
"def super_digit(n)\n return n if n < 10\n\n sum_digits = 0\n until n == 0\n sum_digits += n % 10\n n /= 10\n end\n\n super_digit(sum_digits)\nend",
"def integer_to_string(int)\n int.digits.map { |num| NUMBERS[num] }.join.reverse\nend",
"def integer_to_string(int)\n num_digits = 1\n loop do\n quotient = int / 10**num_digits\n break if quotient == 0\n num_digits += 1\n end\n \n digits_arr = []\n for i in (1..num_digits)\n digits_arr.unshift(int % 10**i/ 10**(i-1))\n end \n \n digits_arr.each_with_index do |digit, index| \n if digit == 0\n digits_arr[index] = '0'\n elsif digit == 1\n digits_arr[index] = '1'\n elsif digit == 2\n digits_arr[index] = '2'\n elsif digit == 3\n digits_arr[index] = '3' \n elsif digit == 4\n digits_arr[index] = '4' \n elsif digit == 5\n digits_arr[index] = '5'\n elsif digit == 6\n digits_arr[index] = '6'\n elsif digit == 7\n digits_arr[index] = '7'\n elsif digit == 8\n digits_arr[index] = '8'\n elsif digit == 9\n digits_arr[index] = '9'\n end\n end \n \n string_version = digits_arr.join('')\n # p string_version\nend",
"def to_i(base=10) end",
"def convertToTwoDigitString inInt\n if inInt < 10 \n return \"0\" + inInt.to_s;\n end\n inInt.to_s\n end",
"def do_digit(chr, base)\n result = \"\"\n num = chr.to_i\n case num\n when (1..3)\n 1.upto(num) { result << ROMANS[base] }\n when 4 \n result << 'IV' if base == 1 #=> 4\n result << 'IL' if base == 10 #=> 40\n result << 'ID' if base == 100 #=> 400\n # no 4000+ in roman number, max roman number is 3000\n when 5\n result << 'V' if base == 1 #=> 5\n result << 'L' if base == 10 #=> 50\n result << 'D' if base == 100 #=> 500\n # no 5000 in roman number, max roman number is 3000\n when (6..8)\n result << 'V' if base == 1 #=> 6+\n result << 'L' if base == 10 #=> 60+\n result << 'D' if base == 100 #=> 600+\n 1.upto(num-5) { result << ROMANS[1] } # add extra 'III'\n # no 6000+ in roman number, max roman number is 3000\n when 9\n result << 'IX' if base == 1 #=> 9\n result << 'XC' if base == 10 #=> 90\n result << 'CM' if base == 100 #=> 900\n # no 9000 in roman number, max roman number is 3000\n end \n result\n end",
"def base2to10(binary)\n #split to single digits\n digits = binary.split('').map{|str| str.to_i}.reverse\n #loop through multiply by 2 raised to index and add to result\n result = 0\n digits.each_with_index do |num, i|\n result += (num *(2**i))\n end\n result\nend",
"def super_digit(n)\n return n if n/10 == 0\n \n sum = n % 10\n while n/10 != 0\n n = n/10\n sum += n % 10\n end\n return super_digit(sum)\nend",
"def super_digit(n)\n return n if n < 10\n sum = super_digit_helper(n, 0)\n super_digit(sum)\nend",
"def handle_hundred (num)\n num2str=''\n if (num%100==0)\n num2str+=NUM_MAP[num/100]+ ' '+ NUM_MAP[100]\n elsif (num%100>=10 && num%100 <= 99)\n num2str+=NUM_MAP[num/100]+ ' '+ NUM_MAP[100]+ ' ' +handle_ten(num%100)\n elsif (num%100>=1 && num%100 <= 9)\n num2str+=NUM_MAP[num/100]+ ' '+ NUM_MAP[100]+ ' ' +handle_bit(num%100)\n end\n return num2str\nend",
"def dec_to_base7(decimal)\r\n result = []\r\n until decimal == 0\r\n result.push(decimal % 7)\r\n decimal = decimal / 7\r\n end\r\n return result.reverse.join.to_i\r\nend",
"def to_bin(number)\n number = Integer(number);\n if(number == 0)\n return 0;\n end\n ret_bin = \"\";\n ## Untill val is zero, convert it into binary format\n while(number != 0)\n ret_bin = String(number % 2) + ret_bin;\n number = number / 2;\n end\n return ret_bin;\n end",
"def base_conversion(value, base)\n #if value < 0\n # @negative, value = true, value.abs\n #end\n i = value.abs\n\n a = []\n while i > 0\n i, r = i.divmod(base)\n a << r\n end\n\n a << 0 if a.empty?\n\n a.reverse\n end",
"def do_digit(chr, base)\n result = \"\"\n num = chr.to_i\n case num\n when (1..3)\n 1.upto(num) { result << ROMANS[base] }\n when 4 \n result << 'IV' if base == 1 #=> 4\n result << 'XL' if base == 10 #=> 40\n result << 'CD' if base == 100 #=> 400\n # no 4000+ in roman number, max roman number is 3000\n when 5\n result << 'V' if base == 1 #=> 5\n result << 'L' if base == 10 #=> 50\n result << 'D' if base == 100 #=> 500\n # no 5000 in roman number, max roman number is 3000\n when (6..8)\n result << 'VI' if base == 1 #=> 6+\n result << 'LX' if base == 10 #=> 60+\n result << 'DC' if base == 100 #=> 600+\n # add extra C, X or I\n 1.upto(num-6) { result << ROMANS[base] } \n # no 6000+ in roman number, max roman number is 3000\n when 9\n result << 'IX' if base == 1 #=> 9\n result << 'XC' if base == 10 #=> 90\n result << 'CM' if base == 100 #=> 900\n # no 9000 in roman number, max roman number is 3000\n end \n result\n end",
"def number_to_string (num) \n p num.to_s\nend",
"def handle_ten (num)\n num2str=''\n if (num%10==0)\n num2str+=NUM_MAP[num]\n elsif (num>10 && num<20)\n num2str+=NUM_MAP[num]\n else\n num2str+=NUM_MAP[num/10*10]+'-'+NUM_MAP[num%10]\n end\n return num2str\nend",
"def integer_to_string(number)\n string = number.digits.reverse.join\nend",
"def integer_to_string(number)\n string = number.digits.reverse.join\nend",
"def integer_to_string(num)\n num.digits.reverse.join\nend",
"def dec2bin(n)\n case n\n when 0 then '0000'\n when 1 then '0001'\n when 2 then '0010'\n when 3 then '0011'\n when 4 then '0100'\n when 5 then '0101'\n when 6 then '0110'\n when 7 then '0111'\n when 8 then '1000'\n when 9 then '1001'\n when 10 then '1010'\n when 11 then '1011'\n when 12 then '1100'\n when 13 then '1101'\n else nil\n end\n end",
"def number_to_english(n)\n return \"\" unless n.integer? && n >= 0\n\n numbers_to_name = {\n 1000000 => \"million\",\n 1000 => \"thousand\",\n 100 => \"hundred\",\n 90 => \"ninety\",\n 80 => \"eighty\",\n 70 => \"seventy\",\n 60 => \"sixty\",\n 50 => \"fifty\",\n 40 => \"forty\",\n 30 => \"thirty\",\n 20 => \"twenty\",\n 19=>\"nineteen\",\n 18=>\"eighteen\",\n 17=>\"seventeen\",\n 16=>\"sixteen\",\n 15=>\"fifteen\",\n 14=>\"fourteen\",\n 13=>\"thirteen\",\n 12=>\"twelve\",\n 11 => \"eleven\",\n 10 => \"ten\",\n 9 => \"nine\",\n 8 => \"eight\",\n 7 => \"seven\",\n 6 => \"six\",\n 5 => \"five\",\n 4 => \"four\",\n 3 => \"three\",\n 2 => \"two\",\n 1 => \"one\",\n 0 => \"zero\"\n }\n\n if n < 10\n numbers_to_name[n]\n elsif n < 100\n if n % 10 == 0 || n < 20\n numbers_to_name[n]\n else\n numbers_to_name[(n / 10) * 10] + ' ' + numbers_to_name[(n % 10)]\n end\n elsif n < 1000\n if n % 100 == 0\n numbers_to_name[(n / 100)] + ' ' + numbers_to_name[100]\n else\n numbers_to_name[(n / 100)] + ' ' + numbers_to_name[100] + ' ' + number_to_english(n % 100)\n end\n elsif n <= 99999\n number_to_english(n / 1000) + ' ' + numbers_to_name[1000] + ' ' + number_to_english(n % 1000)\n else\n \"\"\n end\n\nend",
"def integer_to_string(int)\n int_str = ''\n\n loop do\n int, remainder = int.divmod(10)\n int_str.prepend(DIGITS[remainder])\n\n break if int == 0\n end\n\n int_str\nend",
"def do_digit(chr, base)\n # max roman number is 3000\n # 1 = base 1 char, 10 = base 2 chars, 100 = base 3 chars, 1000 = base 4 chars\n romans = { 1 => 'I', 5 => 'V', 10 => 'X', 50 => 'L', 100 => 'C', 500 => 'D', 1000 => 'M' }\n\n result = ''\n num = chr.to_i\n case num\n when (1..3)\n 1.upto(num) { result << romans[base] }\n when 4\n result << 'IV' if base == 1\n result << 'XL' if base == 10\n result << 'CD' if base == 100\n when 5\n result << 'V' if base == 1\n result << 'L' if base == 10\n result << 'D' if base == 100\n when (6..8)\n result << 'VI' if base == 1\n result << 'LX' if base == 10\n result << 'DC' if base == 100\n # add extra C, X or I\n 1.upto(num - 6) { result << romans[base] }\n when 9\n result << 'IX' if base == 1\n result << 'XC' if base == 10\n result << 'CM' if base == 100\n else\n # zero will go here, don't need to do anything about it\n end\n result\n end",
"def integer_to_string(int)\n string_chars = {\n 0 => '0', 1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5',\n 6 => '6', 7 => '7', 8 => '8', 9 => '9'\n }\n\n string = ''\n int.digits.reverse.each {|digit| string << string_chars[digit]}\n string\nend",
"def number_to_string(num)\n num.to_s\nend",
"def refined_super_digit(n, k)\n s = \"\"\n k.times do\n s += n.to_s\n end\n return super_digit(s.to_i)\nend",
"def to_string(number)\n str_array = []\n loop do\n str_array.unshift(number % 10)\n number /= 10\n break if number == 0\n end\n str_array.join\nend",
"def super_digit(n)\n #has to be a single digit \n if n < 10 \n return n\n else \n return super_digit(n.digits.sum)\n end \n \n \nend",
"def super_digit(n)\n return n.abs if n.abs < 10\n\n sum = recursive_digit_helper(n)\n\n return super_digit(sum)\nend",
"def integer_to_string(int)\n convert = %w(0 1 2 3 4 5 6 7 8 9)\n string = ''\n int.digits.each { |digit| string += convert[digit] }\n string.reverse\nend",
"def integer_to_string(int)\n convert = %w(0 1 2 3 4 5 6 7 8 9)\n string = ''\n int.digits.each { |digit| string += convert[digit] }\n string.reverse\nend",
"def to_bin(num_string)\n digits = convert_to_base10(num_string)\n digits.map!{|char| to_bits(char)}\n digits.join\n end",
"def super_digit(n)\n return n if n < 10\n count = add_digits(n)\n return super_digit(count)\n\nend",
"def add_binary(a,b)\n #your code here\n binary = a + b\n binary.to_s(2) # Convert um inteiro para string na base 2(base binária)\nend"
] |
[
"0.83575493",
"0.8238559",
"0.8166278",
"0.79266685",
"0.752838",
"0.74049246",
"0.73185587",
"0.72491074",
"0.70962274",
"0.70758754",
"0.70092463",
"0.70092463",
"0.6985597",
"0.6976186",
"0.69758296",
"0.695093",
"0.69158375",
"0.6788643",
"0.6671125",
"0.6626104",
"0.66150534",
"0.6578407",
"0.65590936",
"0.6475228",
"0.6405016",
"0.6404934",
"0.6375617",
"0.6366004",
"0.6349669",
"0.6348202",
"0.6344747",
"0.6343767",
"0.63292485",
"0.63258404",
"0.63189405",
"0.63130283",
"0.6308948",
"0.630574",
"0.6300407",
"0.6292503",
"0.62845516",
"0.62644064",
"0.6259544",
"0.6236631",
"0.6226497",
"0.62248904",
"0.6216308",
"0.6206238",
"0.61971426",
"0.61960685",
"0.6195087",
"0.6190215",
"0.6188481",
"0.61869174",
"0.6182953",
"0.61806273",
"0.61753494",
"0.616995",
"0.616597",
"0.61658984",
"0.61647445",
"0.615697",
"0.61533934",
"0.61500823",
"0.6135261",
"0.6133326",
"0.6121537",
"0.6114966",
"0.6112563",
"0.6094511",
"0.6088315",
"0.6085896",
"0.6082736",
"0.6068891",
"0.6066242",
"0.6062001",
"0.60523504",
"0.6049526",
"0.6048927",
"0.604712",
"0.6035635",
"0.6035403",
"0.6025714",
"0.6025714",
"0.6023536",
"0.60214144",
"0.60198236",
"0.6017207",
"0.60037994",
"0.600032",
"0.59988046",
"0.5995331",
"0.59922373",
"0.59846807",
"0.5981541",
"0.59770465",
"0.59767175",
"0.597139",
"0.5964493",
"0.5960516"
] |
0.74677706
|
5
|
Write a recursive method `subsets(array)` that returns all of the subsets of an array example => subsets([1,2,3]) should return => [ [], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3] ]
|
def subsets(array)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def subsets(array)\n if array.length <= 1\n return array\n end\n subset_array = []\n (0..array.length - 1).each do |i|\n subset_array << subsets(array[0...i]) << subsets(array[0...i]).concat([array[-1]])\n end\n return subset_array\nend",
"def subsets(arr)\n return [arr] if arr.empty?\nsubsets(arr[])\nend",
"def subsets(array)\n return [[]] if array.empty?\n number = array.pop\n prev_subsets = subsets(array)\n new_subsets = []\n prev_subsets.each do |subset|\n new_subsets << ([number] + subset)\n end\n prev_subsets + new_subsets\nend",
"def subsets(array)\n if array.empty?\n return [[]]\n end\n\n el = array.shift[0]\n old_subsets = subsets(array)\n new_subsets = old_subsets.map { |old_subset| [el] + old_subset }\n new_subsets + old_subsets\nend",
"def subsets(arr)\n return [arr] unless arr.is_a?(Array)\n return [arr] if arr.empty?\n\n # return [arr] if arr.length == 1\n # first = arr.shift\n # all_subsets << subsets(first)\n # all_subsets << subsets(arr)\n\n # [[],[1]] << [2],[1,2] [each, last] << [last] [each,last]\n # subsets(arr-1) << subsets(arr)[-1]\n all_subsets = [[]]\n\n arr.each { |ele| all_subsets << [ele] }\n\n (0...(arr.length - 1)).each do |idx1|\n # all_subsets << [arr[idx1]] unless all_subsets.include?(arr[idx1])\n (1...arr.length).each do |idx2|\n if idx2 > idx1 && !all_subsets.include?(arr[idx2])\n # all_subsets << [arr[idx2]]\n all_subsets << arr[idx1..idx2]\n end\n end\n end\n\n all_subsets\nend",
"def subsets(array)\n return [[]] if array.empty?\n\n dupped = array.dup\n last = dupped.pop\n sets = subsets(dupped)\n\n subsets(dupped).each do |set|\n sets << (set << last)\n end\n\n sets\nend",
"def array_subsets(arr)\n return arr if arr.length == 0 || arr.length == 1\n new_arr = []\n new_arr << [arr[0]] + array_subsets(arr[1..-1])\n \n # length = 1\n # new_arr = [[]]\n # while length <= arr.length\n # arr.each do |el|\n # new_arr << Array.new(length) { el }\n # end\n # length += 1\n # end\nend",
"def subsets(arr)\n return [arr] if arr.empty?\n # p arr\n # if arr.length == 1\n # return subsets(arr[0...0]) + [arr]\n # end\n\n arr.each {|ele| subsets(arr -[ele]) } + [arr]\nend",
"def subsets(array)\n return [[]] if array.empty?\n subs = array[0...-1]\n smaller_subs = subsets(subs)\n bigger_subs = []\n smaller_subs.each do |sub|\n bigger_subs << sub + [array[-1]]\n end\n smaller_subs + bigger_subs\nend",
"def subsets_of(array)\n 0.upto(array.length).flat_map { |n| array.combination(n).to_a }\n end",
"def subsets(arr)\r\n comb = [] #set up return array\r\n\r\n for x in 0..arr.length do # gives a value from 0 to arr.length to pass below\r\n arr.combination(x) {|y| comb << y} # pushes to the return all of the possible combinations of the array\r\n end # the x insures that all possible lengths of combinations are returned.\r\n\r\n comb # returns all combinations\r\nend",
"def subsets(array)\n return [[]] if array.empty?\n\n val = array[0]\n subs = subsets(array.drop(1))\n new_subs = subs.map { |sub| sub + [val] }\n\n subs + new_subs\nend",
"def subsets(array) # [1, 2], [1]\n return [[]] if array.length == 0\n # return [[], array ] if array.length == 1\n\n except_last = subsets(array[0...-1]) #subsets([1]), subsets([])\n combination = except_last.map { |ele| ele += [array[-1]]} #map subsets([1]) + [2], \n\n except_last + combination\nend",
"def subsets(arr)\n return [ [] ] if arr.empty?\n subs = subsets(arr.drop(1)) # [ [] ]\n return subs.concat(subs.map { |sub| [arr.first].concat(sub) })\nend",
"def array_subsets(array)\n return [array] if array.empty?\n \nend",
"def subsets (arr)\n return [[]] if arr.length == 0\n\n interim = subsets(arr[0...-1])\n interim + interim.map do |el|\n el + [arr[-1]]\n end\nend",
"def subsets(array)\n\n return [[]] if array == []\n all_but_last = subsets(array[0...array.length - 1].dup)\n last = array.last\n all_but_last.map { |el| el.dup } + all_but_last.map { |el| el << last }\nend",
"def subsets(array)\n return [[]] if array == []\n\n sets = subsets(array[0...-1])\n sets + sets.map { |el| el += [array.last] }\nend",
"def subsets(arr)\n return [arr] if arr.empty?\n out = []\n subsets(arr[1..-1]).each do |s|\n out << s\n out << [arr[0]] + s\n end\n out\nend",
"def subsets(array)\n return [[]] if array.empty?\n\n subs = subsets(array[0..-2])\n subs.concat(subs.map{|el| el += [array.last]})\nend",
"def subsets(array)\n return [[]] if array.empty?\n\n subs = subsets(array[0..-2])\n subs.concat(subs.map{|el| el += [array.last]})\nend",
"def subsets(arr)\n return [[]] if arr.empty?\n subsets_arr = []\n cur_el = arr[0]\n prior_subs = subsets(arr[1..-1])\n prior_subs.each do |subset|\n subsets_arr << subset.dup.push(cur_el)\n end\n subsets_arr + prior_subs\nend",
"def subsets(arr)\n return [[]] if arr.empty?\n s = subsets(arr - [arr.last])\n s + s.map { |el| el + [arr.last] }\nend",
"def subsets(array)\n return [[]] if array.empty?\n subs = subsets(array[0..-2])\n subs += subs.map { |el| el += [array.last] }\n end",
"def powerset(array)\n subsets = [[]]\n\n array.each do |elem|\n (1..subsets.length - 1).each do |i|\n current_subset = subsets[i]\n subsets.append(current_subset + [elem])\n end\n end\n\n return subsets\nend",
"def subsets(set)\n return [[]] if set == []\n \n res= [[]]\n \n 0.upto set.length-1 do |i|\n subsets(set[(i+1)..-1]).each do |subsubset|\n res << [set[i]] + subsubset\n end\n end\n \n res\nend",
"def powerset(array)\n subsets = [[]]\n array.each { |element|\n for i in 0..subsets.length - 1\n current_subset = subsets[i]\n subsets << (current_subset + [element])\n end\n }\n return subsets\nend",
"def find_subsets(nums)\n\tsorted_nums = nums.sort()\n\n\tsubsets = []\n\tsubsets.append([])\n\n\tstart_index, end_index = 0, 0\n\n\tfor i in 0..(nums.length - 1)\n\t\tstart_index = 0\n\t\t0\n\t\t0\n\t\tif i > 0 and nums[i] == nums[i - 1]\n\t\t\tstart_index = end_index + 1\n\t\tend\n\n\t\tend_index = subsets.length - 1\n\t\t0\n\t\t1\n\t\tfor j in start_index..end_index\n\t\t\tsubset1 = Array.new(subsets[j])\n\t\t\t[]\n\t\t\t[]\n\t\t\tsubset1.append(nums[i])\n\t\t\t[1]\n\t\t[3]\n\t\t\tsubsets.append(subset1)\n\t\t\t[[],[1],[3]]\n\t\tend\n\tend\n\n\treturn subsets\nend",
"def subsets(arr)\n return [[]] if arr == [] \n\n new_arr = []\n last = arr[-1]\n subset = subsets(arr[0..-2])\n\n subset.each do |suba|\n new_arr << suba + [last]\n end\n \n subset + new_arr\n\nend",
"def subsets(nums)\n result = []\n subsets_helper(nums, [], result, 0)\n result\nend",
"def subsets(arr)\n return [arr] if arr.empty?\n prev = subsets(arr[0..-2]) \n next_one = []\n prev.each { |sub| next_one << sub + [arr[-1]] }\n return prev + next_one\nend",
"def subsets(arr)\n subsets_helper(result = [], temp = [], arr, 0)\nend",
"def subsets(arr)\n return [[]] if arr.length == 0\n #return [arr] if arr.length == 1\n\n prev_set = subsets(arr[0..-2])\n new_subset = prev_set.map { |subarr| subarr + [arr[-1]] }\n\n prev_set + new_subset\nend",
"def subsets(arr)\n return [[]] if arr.empty?\n\n val = arr[0]\n subs = subsets(arr.drop(1))\n new_subs = subs.map{ |sub| sub + val }\n\n subs + new_subs\nend",
"def subsets(arr)\n ans = [[]]\n arr.length.times do |id|\n id2 = id + 1\n ans << [arr[id]]\n while id2 < arr.length\n ans << arr[id..id2]\n id2 += 1\n end\n end\n ans\nend",
"def subsets(arr)\n res = [] \n if arr.length == 1 \n res << [] \n res << [arr[0]]\n return res \n elsif arr.empty?\n return [[]]\n end\n \n last = arr.pop \n old_set = subsets(arr)\n res = old_set\n \n res += old_set.map{ |i| i + [last] }\nend",
"def subsets(arr)\n #base case(s)\n p arr\n return [arr] if arr.empty?\n # return [[], arr] if arr.length == 1\n #inductive step\n remaining_arr = subsets(arr[0...-1])\n remaining_arr + remaining_arr.map { |ele| ele + [arr.last] }\n # subsets(arr) + subsets(arr[0...-1])\nend",
"def subsets(arr)\n return [[]] if arr.empty?\n\n last_el = arr.last\n results = []\n\n\n subsets(arr[0..-2]).each do |el|\n sub_arr = el << last_el\n results << sub_arr\n end\n\n subsets(arr[0..-2]) + results\nend",
"def recursive_subsets(arr)\n return [[]] if arr.empty?\n last_el = arr.pop\n p sub_arr = recursive_subsets(arr)\n p last_el\n sub_arr += sub_arr.map { |el| el + [last_el] }\nend",
"def subsets(set)\n return [[]] if set.empty?\n smaller_set = set.take(set.count-1)\n smaller_subsets = subsets(smaller_set)\n bigger_subsets = []\n smaller_subsets.each do |smaller_subset|\n bigger_subsets << smaller_subset + [set.last]\n end\n\n smaller_subsets + bigger_subsets\nend",
"def subsets(nums)\n return [[]] if nums.empty?\n return [[],[nums.first]] if nums.size == 1\n [[], (0...nums.size).map {|x|\n [[nums[x]], subsets(nums[x + 1..-1]).map { |y| [nums[x]] + y }]\n }.flatten]\nend",
"def subsets(nums)\n return [[]] if nums.empty?\n first = nums[0]\n prev_subs = subsets(nums[1..-1])\n new_subs = prev_subs.map do |sub|\n sub + [first]\n end \n prev_subs + new_subs\nend",
"def subsets(ary)\n # base case\n return [[]] if ary.empty?\n\n # create subsets without the last element (smaller array)\n subs = subsets(ary.take(ary.length - 1))\n\n # adds the subs with the last element that was omitted.\n subs.concat( subs.map { |sub| sub + [ary.last] })\n\nend",
"def subsets(arr)\n # return an empty array (tech a subset of an empty array) - base case\n return [[]] if arr.empty?\n # take out the last el\n last = arr[-1]\n # take all the other els\n # find all subsets don't have the last element\n subsets_without_last = subsets(arr[0...-1])\n # create an array with a combo of s (the el) & the last ele in arr\n # find all subsets that have the last element\n subsets_with_last = subsets_without_last.map { |s| s.dup << last }\n # merge with prior subsets\n # all subsets of arr either have the last element, or they don't.\n subsets_without_last + subsets_with_last\nend",
"def subsets(arr)\n return [self] if arr.length == 1\n\n subs + subsets()\nend",
"def array_subsets(arr)\n return [[]] if arr.empty?\n partial_subset = array_subsets(arr[0..-2])\n addition = partial_subset.map {|ele| ele + [arr[-1]]}\n partial_subset + addition\nend",
"def powerset(array, idx = nil)\n if (idx == nil)\n idx = array.length - 1\n end\n if (idx < 0)\n return [[]]\n end\n element = array[idx]\n subsets = powerset(array, idx - 1)\n for i in 0..subsets.length - 1\n current_subset = subsets[i]\n subsets << current_subset + ([element])\n end\n return subsets\nend",
"def powerset(array, index = nil)\n if index.nil?\n index = array.length - 1\n elsif index < 0\n return [[]]\n end\n\n ele = array[index]\n subsets = power(array, index - 1)\n (0..subsets.length - 1).each do |i|\n current_subset = subsets[i]\n subsets.append(current_subset + [ele])\n end\n\n subsets\nend",
"def subsets_iter(arr)\n new_arr = [[]]\n # byebug\n i = 0\n while i < arr.length\n# byebug\n ele1 = arr[i]\n new_arr << [ele1]\n\n if arr.length > 2\n sub_arr = [ele1]\n j = i + 1\n while j < arr.length\n # byebug\n ele2 = arr[j]\n sub_arr << ele2\n new_arr << sub_arr.dup\n sub_arr.pop\n j += 1\n end\n end\n i += 1\n end\n# byebug\n new_arr << arr unless arr.length < 2\n\n new_arr\nend",
"def subsets(arr)\n return [[]] if arr.empty?\n # debugger\n # take - return first n elements\n\n subArr = arr.take(arr.count - 1)\n\n subs = subsets(subArr)\n\n # concat Appends the elements of other_ary to self.\n # tyle co +\n subArrays = subs.map { |sub| sub + [arr.last] }\n subs.concat(subArrays)\nend",
"def subsets(arr)\n return [[]] if arr.empty?\n\n # new_series = subsets(arr[0..-2]).each do |subarr|\n # subarr << arr[-1]\n # end\n # subsets(arr[0..-2]) + new_series\n\n prev = subsets(arr[0..-2])\n prev.concat( prev.map { |subarr| subarr + [arr.last] } )\n\nend",
"def subsets(arr)\n # byebug\n return [arr] if arr.empty?\n\n if arr.length.odd?\n mid_idx = arr.length / 2\n else\n mid_idx = arr.length / 2 - 1\n end\n# byebug\n with_last = subsets(arr[1..-1])\n # byebug\n without_last = subsets(arr[0...-1])\n # byebug\n combined1 = subsets(arr[0...mid_idx] + arr[mid_idx + 1..-1])\n # combined2 = subsets(arr[0..mid_idx] + arr[mid_idx + 2..-1]) # this didn't work. still missing [1, 2, 4] with [1, 2, 3, 4] original input\n# byebug\n output = without_last + combined1 + with_last + [arr] # combined2\n output.uniq\nend",
"def subsets(arr)\n return [[]] if arr.empty?\n sub = subsets(arr[0...-1])\n newsub = sub.map { |ele| ele + [arr.last] } \n sub + newsub\n\n\n# sub + arr[-1]\nend",
"def each_subset(array)\n subsets_of(array).each {|subset| yield(subset)}\n end",
"def permutations(array)\n return [array] if array.length <= 1\n\n\n # Similar to the subsets problem, we observe that to get the permutations\n # of [1, 2, 3] we can look at the permutations of [1, 2] which are\n # [1, 2] and [2, 1] and add the last element to every possible index getting\n # [3, 1, 2], [1, 3, 2], [1, 2, 3], [3, 2, 1], [2, 3, 1]\n\n # pop off the last element\n first = array.shift\n # make the recursive call\n perms = permutations(array)\n # we will need an array to store all our different permutations\n total_permutations = []\n\n\n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n total_permutations\nend",
"def permutations(array)\n return [array] if array.length <= 1\n\n # Similar to the subsets problem, we observe that to get the permutations of \n # [1, 2, 3] we can look at the permutations of [1, 2] which are [1, 2] and \n # [2, 1] and add the last element to every possible index getting [3, 1, 2], \n # [1, 3, 2], [1, 2, 3], [3, 2, 1], [2, 3, 1], [2, 1, 3]\n\n # pop off the last element\n first = array.shift\n\n # make the recursive call\n perms = permutations(array)\n\n # we will need an array to store all our different permutations\n total_permutations = []\n\n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).to_a.each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n\n total_permutations\nend",
"def find_subsets(arr, target_value)\n rec(arr, target_value, arr.length - 1)\nend",
"def permutations(array)\n return [array] if array.length <= 1\n \n \n # Similar to the subsets problem, we observe that to get the permutations\n # of [1, 2, 3] we can look at the permutations of [1, 2] which are\n # [1, 2] and [2, 1] and add the last element to every possible index getting\n # [3, 1, 2], [1, 3, 2], [1, 2, 3], [3, 2, 1], [2, 3, 1]\n \n # pop off the last element\n first = array.shift\n # make the recursive call\n perms = permutations(array)\n # we will need an array to store all our different permutations\n total_permutations = []\n \n \n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n total_permutations\nend",
"def subsets_2(nums, results = [], solution = [], current_idx = 0)\n results << solution.clone\n return if current_idx >= nums.length\n\n current_idx.upto(nums.length - 1) do |i|\n solution << nums[i]\n subsets(nums, results, solution, i + 1)\n solution.pop\n end\n\n results\nend",
"def subsets_with_dup(nums)\n result = []\n nums.sort!\n subsets_helper(nums, [], result, 0, {})\n result\nend",
"def subsets_3(nums, results = [], solution = [], current_idx = 0)\n results << solution.clone\n return if current_idx == nums.length\n\n nums[current_idx..-1].each_with_index do |num, i|\n solution << num\n subsets(nums, results, solution, current_idx + i + 1)\n solution.pop\n end\n\n results\nend",
"def subsets(arr, n = arr.size-1)\n #Heaps permutations\n @sol = [] if n == arr.size - 1\n\n if n == 0\n p arr\n @sol << arr\n return arr\n else\n (n+1).times do |i|\n p i\n subsets(arr,n-1)\n if( (n - 1) % 2 == 1)\n arr[1],arr[n] = arr[n],arr[1]\n else\n arr[i],arr[n] = arr[n],arr[i]\n end\n end\n end\nend",
"def generate_n_sets(array, number_of_sets)\n\nend",
"def powerset(arr)\n arr.inject([Set.new].to_set) do |powerset, el|\n new_powerset = Set.new\n powerset.each do |subset|\n new_powerset << subset\n new_powerset << subset + [el]\n end\n new_powerset\n end\n end",
"def common_subsets(array_one, array_two)\n\nend",
"def recompute_recursive_subsets\n @recursive_subsets = subsets.inject(ValueSet.new) do |set, child|\n set.merge(child.recursive_subsets)\n end\n if parent\n parent.recompute_recursive_subsets\n end\n end",
"def get_power_set_2(set)\n\treturn [[]] if set.empty?\n\n\tnum = set.pop\n\tprevious_subsets = get_power_set_2(set)\n\n\tprevious_subsets.map do |subset|\n\t\t[subset.dup.push(num), subset]\n\tend.flatten(1)\n\nend",
"def subset_in_array?(array, value)\n result = 1.upto(array.length).flat_map do |n|\n array.combination(n).to_a\n end\n result.include?(value)\nend",
"def common_subsets(arr1, arr2)\n subsets(intersection3(arr1, arr2))\nend",
"def find_subsets_of_points(options={})\n puts \"Calculating subsets\"\n puts \"Set of #{@points_amount} points: 2^#{@points_amount} subsets = #{2**@points_amount} different subsets\"\n @points_subsets = Array.new(@points_amount) { Array.new }\n # amount of all subsets of a set 2^n-1 (-1, as we're excluding the empty set {})\n (1..2**@points.length-1).each { |i|\n p i if i%100000 == 0\n subset_size = subset_size(i)\n if (options[:with_first_point_only] != true) || (options[:with_first_point_only] == true and i % 2 == 1)\n @points_subsets[subset_size-1] << i\n end\n }\n\n (2..@points_amount).each do |subset_size|\n subsets = @points_subsets[subset_size-1]\n puts \"Subset size: \" + subset_size.to_s + \"; Subsets total: \" + subsets.size.to_s\n end\n\n puts \"Done calculating subsets\"\n end",
"def permutations(array)\n\n ret = []\n return [array] if array.length < 2\n sub = permutations(array[1..-1])\n sub.each do |sub_array|\n (0..sub_array.length).each do |idx|\n ret << sub_array[0...idx] + [array.first] + sub_array[idx..-1]\n end\n end\n ret\nend",
"def sub_arrays(arr)\n sub_arr = []\n i_arr = []\n arr.length.times do |x|\n arr.map do |ele1|\n i_arr += [ele1]\n sub_arr << i_arr\n end\n i_arr = []\n arr.shift\n end\n sub_arr\nend",
"def common_subsets(array_one, array_two)\n common_array = fast_intersection(array_one, array_two)\n subsets(common_array)\nend",
"def common_subsets(array_one, array_two)\n subsets(fast_intersection(array_one, array_two))\nend",
"def get_power_set_1(set)\n\t(0..set.length).map {|i| set.combination(i).to_a}.flatten(1)\nend",
"def permutations(array)\n debugger\n return [array] if array.length <= 1\n # pop off the last element\n first = array.shift\n # make the recursive call\n perms = permutations(array)\n # we will need an array to store all our different permutations\n total_permutations = []\n\n\n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0 ... i] + [first] + perm[i .. -1]\n end\n end\n total_permutations\nend",
"def sub_arrays\n result = []\n self.each_index do |i|\n self.each_index do |j|\n result << self[i..j] if j >= i\n end\n end\n result\n end",
"def permutations(array)\n if array.empty?\n return [[]]\n end\n if array.count == 1\n return [array.clone]\n end\n arr = []\n array.each_with_index do |ele, idx|\n cpy = array.clone\n cpy.delete_at(idx)\n permutations(cpy).each do |perm|\n arr << [ele] + perm\n end\n end\n return arr\nend",
"def permute(arr)\n return [array] if array.length <= 1\n\n first = array.shift\n perms = permute(array)\n total_permutations = []\n \n \n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n total_permutations\nend",
"def sub(array)\n arr = []\n array.each_index do |i|\n (i...array.length).each do |j|\n arr << array[i..j]\n end\n end\n arr \nend",
"def select(array, path=[], solutions=[])\n if path.size == 5 #|| array.size == 0\n solutions << path\n return solutions \n end\n\n 0.upto(array.size-1).each do |num|\n arr = array[num]\n if arr[0].is_a?(Array)\n arr.each do |a|\n select(array[(num+1..-1)], path + [a],solutions)\n end\n else\n select(array[(num+1..-1)], path + [arr], solutions)\n end\n end\n\n return solutions\nend",
"def permutations(arr)\n # return nil if arr.empty?\n return [arr] if arr.length == 1\n # grab first element to append to all perms of smaller array\n first_el = arr.shift\n # get permutations of shrunken array\n subset_perms = permutations(arr)\n total_permutations = []\n # iterate through all smaller perms\n subset_perms.each do |sub|\n # add first element to all possible indices of perms array\n # and add to total_perms array\n (0..sub.length).each do |i|\n subset = sub[0...i] + [first_el] + sub[i..-1]\n total_permutations << subset\n end\n end\n total_permutations\nend",
"def permutations array\n if array.size < 2\n yield array\n else\n array.each do |element|\n permutations(array.select() {|n| n != element}) \\\n {|val| yield([element].concat val)}\n end\n end\nend",
"def find_subarrays(nums_ary)\n subarrays = []\n last_index = nums_ary.size - 1\n 0.upto(last_index) do |start_index|\n start_index.upto(last_index) do |end_index|\n subarrays << nums_ary[start_index..end_index]\n end\n end\n subarrays.push([])\nend",
"def permutation(array)\n answer_arr = []\n return array if array.length == 1\n array.each_index do |i|\n perm = permutation(array - [array[i]])\n perm.each do |el|\n answer_arr << ([array[i]] + [el]).flatten\n end\n perm.each do |el|\n answer_arr << ([el] + [array[i]]).flatten\n end\n end\n answer_arr.uniq\nend",
"def permutation (array)\n# yields permutation set WITH duplicates\nend",
"def largest_sub_sum(array)\n subsets = []\n i = 0\n while i < array.length\n j = i\n while j < array.length\n subsets << array[i..j]\n j += 1\n end\n i += 1\n end\n result = nil\n subsets.map {|subset| subset.inject(:+)}.each do |sum|\n result = sum if result.nil? || result < sum\n end\n result\nend",
"def permutations(arr)\n # will have to iterate\n # will have logic similar to subsets\n\n # [1], hits base case and we're done\n\n return [arr] if arr.length <= 1\n\n result = []\n last_ele = arr.pop\n sub_perms = permutations(arr)\n\n sub_perms.each do |sub|\n (0..sub.length) do |i| # index will vary, we to include sub.length as an index, otherwise we will never be able to shove into the last/back spot\n result << sub[0...i] + [last_ele] + sub[i..-1]\n # since the i will vary as we iterate through, ^^ will shift the last_ele around\n end\n end",
"def PowerSetCount(arr)\n combinations = []\n (0..arr.size).each { |combo| combinations += arr.combination(combo).to_a }\n combinations.size\nend",
"def getLineSubset( arr, len )\n return [] if (arr.empty? || (x = arr[0]) > len)\n return [[x]] if x == len\n ar = arr.drop(1)\n getLineSubset( ar, len-x )\n .each{ |a| a.unshift x }\n .concat getLineSubset( ar, len )\nend",
"def permutations(array)\n #base case\n return [[]] if array.empty?\n\n results = []\n prev_perm = permutations(array[0...-1]) # permutations([1,2]) == [[1, 2], [2, 1]]\n last_ele = array[-1] # 3\n prev_perm.each do |sub_arr|\n (0...array.length).each do |idx|\n # temp = Array.new(array.length) [nil, nil, nil]\n # temp = sub_arr[0...idx] + [last_ele] + sub_arr[idx..-1]\n results << temp\n end\n end\n results\nend",
"def permutations(array)\n return [array] if array.length == 1\n\n perms = []\n array.each do |el|\n dupped = array.dup\n dupped.delete(el)\n permutations(dupped).each { |perm| perms << [el] + perm }\n end\n\n perms\nend",
"def largest_contiguous_subsum(arr)\n subsets = []\n\n (0...arr.length).each do |idx1|\n (idx1...arr.length).each do |idx2|\n subsets << arr[idx1..idx2]\n end\n end \n\n largest_sum = subsets.first.sum\n\n subsets.each do |subset|\n if subset.sum > largest_sum\n largest_sum = subset.sum\n end\n end\n\n print subsets\nend",
"def permutations(array)\n return [array] if array.length <= 1\n start = array.shift\n perm = permutations(array)\n total_perms = []\n perm.each do |perms|\n (0..perm.length).each do |i|\n total_perms << perms[0...i] + [start] + perms[i..-1]\n end\n end\n total_perms\nend",
"def unique_combinations(array, aggregate, all=Set.new, current=[], start=0, &aggregator)\n return all if array.length == start\n (1..array.length-start).flat_map do |offset|\n index = start + offset\n element = array[index-1]\n nextaggregate, prune = aggregator.call(aggregate, element)\n break if prune\n combination = [*current, element]\n unless all.include? combination\n all << combination\n unique_combinations(array, nextaggregate, all, combination, index, &aggregator)\n end\n end\n all\nend",
"def variations(a)\n if !a.empty?\n first = a.first \n if a.length==1 then\n first\n else\n rest = variations(a[1..-1])\n first.map{ |x| rest.map{ |y| \"#{x} #{y}\" } }.flatten\n end\n else\n # \"array is empty\"\n a\n end\n \nend",
"def permutations(array)\n return [array] if array.length <= 1\n\n first = array.shift\n perms = permutations(array)\n total_permutations = []\n\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm.take(i) + [first] + perm.drop(i)\n end\n end\n total_permutations\nend",
"def permutations(array)\n return [[]] if array.empty?\n return [array] if array.length == 1\n new_arr = []\n\n first_el = array.shift\n array_perms = permutations(array)\n array_perms.each do |perm|\n (0..perm.length).each do |idx|\n new_arr << perm[0...idx] + [first_el] + perm[idx..-1]\n end\n end\n return new_arr\nend"
] |
[
"0.87269956",
"0.8644677",
"0.864104",
"0.86296016",
"0.8595369",
"0.85549206",
"0.84374523",
"0.8425629",
"0.8392272",
"0.8386299",
"0.836957",
"0.827848",
"0.82594174",
"0.82570493",
"0.82448715",
"0.82265544",
"0.82134014",
"0.8204193",
"0.8200897",
"0.81033313",
"0.81033313",
"0.8099804",
"0.8084958",
"0.80836385",
"0.8049307",
"0.80170035",
"0.7990716",
"0.7922044",
"0.79105955",
"0.79079837",
"0.79007",
"0.7882964",
"0.78624165",
"0.7762367",
"0.77440685",
"0.77347744",
"0.7732936",
"0.77226746",
"0.77026343",
"0.7694053",
"0.76869977",
"0.765078",
"0.76414585",
"0.76320803",
"0.7630518",
"0.75746274",
"0.7547676",
"0.74759763",
"0.7435801",
"0.7434728",
"0.7395936",
"0.71594036",
"0.70471954",
"0.7042727",
"0.70382404",
"0.7016585",
"0.7013272",
"0.6990418",
"0.68370366",
"0.6818968",
"0.68174934",
"0.664613",
"0.6603069",
"0.6560876",
"0.6386097",
"0.6384403",
"0.6153333",
"0.6138898",
"0.6137815",
"0.60789996",
"0.6055556",
"0.60529935",
"0.6003027",
"0.59839433",
"0.59393394",
"0.592958",
"0.5909066",
"0.5857007",
"0.5774927",
"0.5737284",
"0.5716894",
"0.57166743",
"0.57113594",
"0.5705417",
"0.57013977",
"0.5652793",
"0.56294274",
"0.56223315",
"0.55846673",
"0.5563993",
"0.5563785",
"0.5560452",
"0.55462754",
"0.55455035",
"0.5545337",
"0.55344325",
"0.55320674",
"0.5524339"
] |
0.81932193
|
20
|
See question here: Write a recursive method to solve `make_better_change`. HINT: To make_better_change, we only take one coin at a time and never rule out denominations that we've already used. This allows each coin to be available each time we get a new remainder. By iterating over the denominations and continuing to search for the best change, we assure that we test for 'nongreedy' uses of each denomination. `make_better_change(24, [10,7,1])` should return [10,7,7]
|
def make_better_change(value, coins)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def make_better_change(amount, coin_denoms)\n return [amount] if coin_denoms.include?(amount)\n return [] if amount <= 0\n\n coin_denoms.sort.reverse!\n all_possible_arr = []\n\n coin_denoms.each do |value|\n change_arr = []\n change_arr << value\n change_arr.concat(make_better_change(amount - value, coin_denoms))\n all_possible_arr << change_arr if change_arr.inject(:+) == amount\n end\n\n all_possible_arr.min_by { |arr| arr.length }\n\nend",
"def make_better_change(change, coins)\n # base case would be if the change exactly matched one of the coins\n # it would simple return the coin and it would be the least amount of coins\n return [change] if coins.include?(change)\n\n # filter out any coins that are greater than the change\n # we also need an array to compare possible solutions\n usable_coins = coins.select { |coin| coin <= change }\n possible_solutions = []\n \n # loop through the usable coins and make possible combinations\n usable_coins.each do |coin|\n remainder_coins = usable_coins.select { |i| i <= coin }\n remainder_change = change - coin\n\n # rescuing exception\n begin\n # make_better_change will return nil if there is no possible solution\n # so it would be nil + [coin], which would result in NoMethodError\t\n possible_solution = make_better_change(remainder_change, remainder_coins) + [coin]\n rescue NoMethodError\n return nil\n end\n\n possible_solutions << possible_solution\n end\n\n possible_solutions.sort_by(&:length).first\nend",
"def make_change(target, coins = [25, 10, 5, 1])\n # Don't need any coins to make 0 cents change\n return [] if target == 0\n # Can't make change if all the coins are too big. This is in case\n # the coins are so weird that there isn't a 1 cent piece.\n return nil if coins.none? { |coin| coin <= target }\n\n # Optimization: make sure coins are always sorted descending in\n # size. We'll see why later.\n coins = coins.sort.reverse\n\n best_change = nil\n coins.each_with_index do |coin, index|\n # can't use this coin, it's too big\n next if coin > target\n\n # use this coin\n remainder = target - coin\n\n # Find the best way to make change with the remainder (recursive\n # call). Why `coins.drop(index)`? This is an optimization. Because\n # we want to avoid double counting; imagine two ways to make\n # change for 6 cents:\n # (1) first use a nickel, then a penny\n # (2) first use a penny, then a nickel\n # To avoid double counting, we should require that we use *larger\n # coins first*. This is what `coins.drop(index)` enforces; if we\n # use a smaller coin, we can never go back to using larger coins\n # later.\n best_remainder = make_change(remainder, coins.drop(index))\n\n # We may not be able to make the remaining amount of change (e.g.,\n # if coins doesn't have a 1cent piece), in which case we shouldn't\n # use this coin.\n next if best_remainder.nil?\n\n # Otherwise, the best way to make the change **using this coin**,\n # is the best way to make the remainder, plus this one coin.\n this_change = [coin] + best_remainder\n\n # Is this better than anything we've seen so far?\n if (best_change.nil? || (this_change.count < best_change.count))\n best_change = this_change\n end\n end\n\n best_change\nend",
"def make_change( amount, coins=[25,10,5,1], avoid_pennies=true, recursing=false )\n # Don't sort in place, in case the user wants to preserve the coin array\n coins = coins.sort_by{ |coin| -coin }\n owed = amount\n change = []\n coins.each{ |coin|\n while owed >= coin\n owed -= coin\n change << coin\n end\n }\n change = nil unless owed == 0\n\n if recursing\n change\n else\n answers = [ change ]\n while coins.shift\n answers << make_change( amount, coins, avoid_pennies, true )\n end\n answers.compact.sort_by{ |answer|\n [\n answer.length,\n -answer.send( avoid_pennies ? :last : :first )\n ]\n }.first\n end\nend",
"def make_better_change(total, coins = [1,5,10,25])\n # base case once total reaches 0\n return [] if total == 0\n\n # array to hold current best change\n best_change = nil\n\n # sort high to low, unnecessary for this function\n coins.sort!{|a,b| b <=> a}\n\n # since best change method unknown, we cycle through coins, grabbing\n # one of current coin and making best change with remainder.\n coins.each do |coin|\n next if coin > total # coin is unusable\n rest_of_change = make_better_change(total - coin, coins)\n change = [coin] + rest_of_change\n # if best change array empty or current change uses less coins, replace\n if best_change.nil? || change.count < best_change.count\n best_change = change\n end\n end\n best_change\nend",
"def make_change(amount, coins = [10, 7, 1])\n return [] if amount == 0\n return nil if coins.none? { |coin| coin <= amount }\n\n coins = coins.sort.reverse\n best_change = nil\n coins.each_with_index do |coin, index|\n next if coin > amount\n remainder = amount - coin\n \n best_remainder = make_change(remainder, coins.drop(index))\n \n next if best_remainder.nil?\n \n this_change = [coin] + best_remainder\n \n if best_change.nil? || (this_change.count < best_change.count)\n best_change = this_change\n end \n end\n \n best_change\nend",
"def make_better_change(total, coin_values)\n return [] if total == 0\n return nil if coin_values.none? { |coin| coin <= total }\n\n coins = coin_values.sort.reverse\n\n change_possibilities = []\n coins.each_with_index do |coin, index|\n next if coin > total\n\n remainder = total - coin\n best_remainder = make_better_change(remainder, coins.drop(index))\n next if best_remainder.nil?\n\n change_possibilities << [coin] + best_remainder\n end\n\n change_possibilities.min_by(&:length)\nend",
"def make_change(coins, target)\n return [] if target == 0\n coins.sort!{|a,b| b <=> a }\n best_change = []\n\n coins.each do |coin|\n solution = []\n (target / coin).times { solution << coin }\n\n solution += make_change(coins.drop(1), target % coin)\n\n if best_change.length > solution.length || best_change.empty?\n best_change = solution\n end\n end\n best_change\nend",
"def make_change(change, coins)\n return [] if change == 0\n return nil if coins.count == 0 && change != 0\n\n current_coin = coins.first\n if change / current_coin >= 1\n results = [current_coin] + make_change(change - current_coin, coins)\n next_results = make_change(change - current_coin, coins.shift)\n greedy_results = [current_coin] + next_results unless next_results == nil\n results = greedy_results if greedy_results.length < results.length \n else\n coins.shift\n results = make_change(change, coins)\n end\nend",
"def make_change(value,coins)\n return nil if value < coins.min\n best = nil\n coins.each do |coin|\n if value < coin\n next\n elsif value == coin\n return [coin]\n else\n # Try finding a combination of coins that will sum to value - coin.\n # Then you can get a combination of coins for value by adding the\n # current coin.\n candidate = [coin] + make_change(value - coin, coins)\n \n if candidate != nil && (best.nil? || candidate.size < best.size)\n best = [coin] + make_change(value - coin, coins)\n end\n end\n end\n best\nend",
"def greedy_make_change(amount, coins = [25, 10, 5, 1])\n return [] if amount == 0\n change = []\n sorted_coins = coins.sort\n largest_coin = sorted_coins.pop\n\n large_coins = amount / largest_coin\n large_coins.times {change << largest_coin}\n\n new_amount = amount - change.sum\n \n change += greedy_make_change(new_amount, sorted_coins)\n\n change\nend",
"def make_better_change(value, coins)\n return nil if coins.empty?\n return [] if value == 0\n\n change = []\n coins = coins.sort.reverse.select{|coin| coin <= value}\n coins.each do |coin|\n remainder = value - coin\n if remainder > 0\n best_remainder = make_better_change(remainder, coins)\n change << [coin] + best_remainder unless best_remainder.nil?\n else\n change << [coin]\n end\n end\n change.sort_by!{|arr| arr.size}.first\nend",
"def make_better_change(value, coins)\n return nil if coins.empty?\n return [] if value == 0\n\n change = []\n coins = coins.sort.reverse.select{|coin| coin <= value}\n coins.each do |coin|\n remainder = value - coin\n if remainder > 0\n best_remainder = make_better_change(remainder, coins)\n change << [coin] + best_remainder unless best_remainder.nil?\n else\n change << [coin]\n end\n end\n change.sort_by!{|arr| arr.size}.first\nend",
"def greedy_make_change(amount, coins = [25, 10, 5, 1])\n #debugger\n return [amount] if amount == 1\n return [] if coins.min > amount\n\n collected_coins = []\n\n coins.each do |coin|\n divided_amount = amount / coin\n\n if divided_amount > 0\n new_amount = amount - (coin * divided_amount)\n if new_amount == 0\n return collected_coins\n end\n\n divided_amount.times do\n collected_coins << coin\n end\n\n collected_coins += greedy_make_change(new_amount, coins)\n #elsif divided_amount ==\n\n end\n end\n\n collected_coins\nend",
"def make_change(amount, coins = [25, 10 ,5, 1])\n biggest_fit_coin = coins.detect { |val| amount >= val }\n\n if biggest_fit_coin == amount\n [biggest_fit_coin]\n else\n [biggest_fit_coin] + make_change(amount - biggest_fit_coin)\n end\nend",
"def make_greedy_change(amount, bank = [25,10,5,1])\n return [] if amount == 0\n\n bank.each_with_index do |coin, idx|\n next if coin > amount\n\n remainder = amount - coin\n return [coin] + make_greedy_change(remainder, bank)\n end\nend",
"def make_change(target, coins = [25, 10, 5, 1])\n return [] if target == 0\n return nil if coins.none? { |coin| coin <= target }\n\n coins = coins.sort.reverse\n best_change = nil\n\n coins.each_with_index do |coin, index|\n next if coin > target\n remainder = target - coin\n best_remainder = make_change(remainder, coins.drop(index))\n next if best_remainder.nil?\n this_change = [coin] + best_remainder\n if (best_change.nil? || (this_change.count < best_change.count))\n best_change = this_change\n end\n end\n\n return best_change if best_change.nil?\n best_change.count\nend",
"def greedy_make_change(total, coins)\n return [] if total == 0\n change = []\n # sort coins largest to smallest\n coins.sort!{|a,b| b <=> a}\n # remove first coin from array\n coin = coins.shift\n # calculate how many fit into total \n coin_count = total / coin\n # add coin to change as many times as calculated above\n coin_count.times { change << coin}\n # current coin change and recursive call to remaining total using remaining coins\n change + greedy_make_change(total-(coin * coin_count), coins)\nend",
"def make_better_change(amount, coins)\n stack = [amount]\n until stack.empty?\n coins.each do |coin|\n break if amount - coin == 0\n stack << amount - coin if amount >= coin\n make_better_change(amount-coin, coins)\n end\n end\nend",
"def recursive_greedy_make_change(amount, coins = [25, 10, 5, 1])\n return [] if amount == 0\n\n if amount >= coins.first\n new_amount = amount - coins.first\n return [coins.first] + recursive_greedy_make_change(new_amount, coins)\n else\n return recursive_greedy_make_change(amount, coins[1..-1])\n end\nend",
"def make_better_change(amount, denoms)\n return greedy_make_change(amount, denoms) if greedy_make_change(amount, denoms).length < greedy_make_change(amount, denoms[1..-1]).length\n make_better_change(amount, denoms[1..-1])\nend",
"def make_smart_change(change_amount, available_coins)\n possible_answers = []\n while available_coins.length > 1 do\n possible_answers << make_change(change_amount, available_coins)\n \n #compare best answer\n # this_answer = make_smart_change(x,y)\n # if best_ans.length > this_answer\n # best_ans = this_answer\n # end\n next if available_coins.length == 1\n available_coins = available_coins[1..-1]\n end\n \n #pick shortest length array within possible_answers\n possible_answers.sort_by(&:length)[0]\n \nend",
"def make_change(n)\n\tdef change(amount, denoms, index)\n\t\treturn 0 if amount == 0\n\t\treturn 1 if index >= denoms.length\n\t\tcurrent_denom = denoms[index]\n\t\tways = 0\n\t\ti = 0\n\t\twhile i * current_denom <= amount\n\t\t\tamount_remaining = amount - i * current_denom\n\t\t\tways += change(amount_remaining, denoms, index + 1)\n\t\t\ti += 1\n\t\tend\n\t\tways\n\tend\n\tdenoms = [100, 20, 10, 5, 2, 1]\n\tchange(n, denoms, 0)\nend",
"def greedy_make_change(value, coins)\n return [] if value == 0 || coins.empty?\n num_coin = value / coins.first\n remaining_value = value % coins.first\n [coins.first] * num_coin + greedy_make_change(remaining_value, coins.drop(1))\nend",
"def make_better_change(value, coins)\n check_coins = coins.select { |el| el <= value }\n return nil if check_coins.empty?\n\n solutions = []\n check_coins.sort.reverse.each do |coin|\n remain = value - coin\n\n if remain > 0\n remain = make_better_change(remain, coins)\n solutions << [coin] + remain unless remain.nil?\n else\n solutions << [coin]\n end\n end\n solutions.sort_by! { |arr| arr.length }.first\n\n end",
"def greedy_change(num, coins)\n return [] if num <= 0\n\n result = []\n new_coin = coins.select { |coin| num - coin >= 0 }.max\n #p new_coin\n result << new_coin\n #p result\n #p greedy_change(num - new_coin, coins)\n result + greedy_change(num - new_coin, coins)\nend",
"def greedy_make_change(total, coin_values)\n return [] if total == 0\n\n coin = coin_values.find { |cn| cn <= total }\n\n [coin] + greedy_make_change(total - coin, coin_values)\nend",
"def greedy_make_change(cents,coins = [25,10,5,1])\n return [cents] if coins.include?(cents)\n arr = Array.new\n coins.each do |coin|\n if coin < cents\n arr << coin\n break\n end\n end\n greedy_make_change(cents-arr.first,coins).each {|coin| arr << coin}\n return arr\nend",
"def make_better_change(amount, coins = [25, 10, 5, 1])\n\treturn [] if amount < 1\n\tsmallest_change = nil\n\n\tcoins.sort.reverse.each.with_index do |coin, i|\n\t\tunless coin > amount\n\t\t\tchange = [coin] + make_better_change(amount - coin, coins.drop(i))\n\t\t\tif smallest_change == nil || change.count < smallest_change.count\n\t\t\t\tsmallest_change = change\n\t\t\tend\n\t\tend\n\tend\n\n\tsmallest_change\nend",
"def greed_make_change(change, coin_arr)\n return [] if change <= coin_arr.min - 1\n changed = false\n i = 0\n change_arr = []\n until changed || i == coin_arr.length\n remainder = change - coin_arr[i]\n if remainder >= 0\n change_arr += [coin_arr[i]] + greed_make_change(remainder,coin_arr)\n change -= coin_arr[i]\n changed = true\n end\n i += 1\n end\n change_arr\nend",
"def make_change_it(amount, coins = [25, 10, 5, 1])\n #iterative version to make sure can get it \n change = []\n i = 0\n while amount > 0\n #as long as money is greater than zero there's a coin that we can give back\n while amount >= coins[i]\n #compare money that you have to the biggest coin\n amount -= coins[i]\n change << coins[i]\n p change\n end\n i += 1\n end\nend",
"def bestCoinsExchange(coins, change)\n\n #sums is in the format [[coin values], depth]\n #the coin values will be either a real coin\n #or the sum of other coins\n #depth is used to determine how deep in the calculation\n #loop we are. if we have a value for 757 that consists of\n #only 2 coins (depth 1), then we will favor that result\n #in our sums hash over some future result that may use more\n #than 2 coins to arrive at 757\n\n sums = {}\n for c in coins\n sums[c] = [[c],0]\n end\n\n depth = 1\n #keep looping till we have a combination of coins equaling\n #the total change\n while sums[change] == nil\n prod = coins.product(sums.keys)\n prod.each{|p|\n sum = p[0] + p[1]\n l = sums[sum]\n #when putting the combination of coins as the answer\n #for a collection of summed values, we will favor\n #the shallower depth (fewer coins) and the larger coin\n #if the depths are equal\n if l == nil || (p[0] > l[0][0] && l[1] >= depth)\n #dont bother storing the sum if it is larger\n #than what we are looking for\n sums[sum] = [p,depth] if sum <= change\n end\n }\n depth += 1\n end\n\n a = sums[change][0]\n counts = {}\n getCounts(coins, sums, a, counts)\n counts.collect{|k,v| [k,v]}.sort_by{|a| a[0]}.reverse\nend",
"def make_change(change_needed, register)\n return [] if change_needed == 0\n\n biggest_coin = register.max\n if biggest_coin <= change_needed\n biggest_coin_amount = 1\n change = [biggest_coin]\n change_remaining = change_needed - biggest_coin\n new_register = register\n else\n new_register = register.dup.sort[0...-1]\n change = []\n change_remaining = change_needed\n end\n\n return change + make_change(change_remaining, new_register)\nend",
"def change1(total, denominations)\n breakdowns = []\n\n denominations.each_with_index do |coin, index|\n next if total/coin == 0\n\n subtotal = total\n set = []\n count = subtotal / coin\n\n if count > 0\n count.times { set << coin }\n subtotal -= (coin * count)\n end\n\n if subtotal > 0\n set += change1(subtotal, denominations[index+1..-1])\n end\n breakdowns << set.flatten\n end\n breakdowns\nend",
"def make_change(coins, money, index)\n return 1 if money == 0\n return 0 if index >= coins.size\n\n amount_with_coin = 0\n ways = 0\n\n while amount_with_coin <= money\n remaining = money - amount_with_coin\n ways += make_change(coins, remaining, index + 1)\n amount_with_coin += coins[index]\n end\n\n ways\nend",
"def greedy_change(amount, coins)\n return {} if amount <= 0\n coins_count = {}\n coins_count[coins.max] = amount / coins.max\n remainder = amount % coins.max\n coins.delete(coins.max)\n coins_count.merge(greedy_change(remainder, coins))\nend",
"def greedy_make_change(target, coins=[25,10,5,1])\nend",
"def make_change(amt, coins, coin_cache = {0 => 0})\n ### THIS FAILS SPECS BECAUSE NIL.nan? IS NOT A METHOD ###\n return coin_cache[amt] if coin_cache.key?(amt)\n return nil if amt < coins.first\n\n best_change = amt\n coins.each do |coin|\n next if amt < coin\n prev_change = make_change(amt - coin, coins, coin_cache)\n if prev_change.nil?\n coin_cache[amt] = nil\n else\n best_change = [best_change, prev_change + 1].min\n coin_cache[amt] = best_change\n end\n end\n\n best_change == amt ? nil : best_change\n end",
"def make_change(amt, coins, coin_cache = {0 => 0})\n return coin_cache[amt] if coin_cache[amt]\n return 0.0/0.0 if amt < coins[0]\n\n min_change = amt\n way_found = false\n idx = 0\n while idx < coins.length && coins[idx] <= amt\n num_change = 1 + make_change(amt - coins[idx], coins, coin_cache)\n if num_change.is_a?(Integer)\n way_found = true\n min_change = num_change if num_change < min_change\n end\n idx += 1\n end\n\n if way_found\n coin_cache[amt] = min_change\n else\n coin_cache[amt] = 0.0/0.0\n end\n end",
"def make_change_iterative(amount, coins = [25, 10, 5, 1])\n change = []\n coins.each do |coin|\n count = amount / coin # how many of that coin I can use\n count.times { change << coin }\n amount -= count * coin\n end\n \n change\nend",
"def calculate_change(candidate, bills, remaining)\n (0..4).each do |level|\n # Try giving out change at every bills level, skipping denominations that\n # don't have any bills or are bigger than the current change amount.\n next if bills[level] == 0\n next if VALUES[level] > remaining\n # If the denomination is equal to the change remaining, add this bill to\n # change and return the change amount.\n if remaining == VALUES[level]\n candidate[level] += 1\n return candidate\n else\n # Otherwise, recursively try adding the bill to the change amount. If\n # this branch is successful, it will be returned; otherwise, we'll skip\n # to the next denomination\n trial_candidate = candidate.dup\n trial_bills = bills.dup\n trial_remaining = remaining\n trial_candidate[level] += 1\n trial_bills[level] -= 1\n trial_remaining -= VALUES[level]\n trial = calculate_change(trial_candidate, trial_bills, trial_remaining)\n return trial if trial\n end\n end\n false\n end",
"def make_change(coins, target_change)\n sorted_in_descending = coins.sort { |a, b| b <=> a }\n change = []\n i = 0\n while i < coins.length\n current_coin = sorted_in_descending[i]\n p current_coin\n if target_change >= current_coin\n target_change -= current_coin\n change << current_coin\n else\n i += 1\n end\n end\n change.length\nend",
"def make_change(total, denominations)\n ways = {}\n start_point = 1\n while start_point <= total\n sub_answer = 0\n denominations.each do |coin|\n if coin == start_point\n sub_answer += 1\n elsif coin < start_point\n next if (denominations.include?(start_point - coin) && coin < (start_point - coin))\n sub_answer += ways[start_point - coin]\n end\n end\n ways[start_point] = sub_answer\n start_point += 1\n end\n puts ways\nend",
"def change(amount, coins)\n return 0 if coins.empty?\n\n # TO make zero, there is one way. Dont give anything.\n ways = Array.new(amount + 1, 0)\n ways[0] = 1\n coins.each do |coin|\n (coin..amount).each do |amt|\n ways[amt] += ways[amt - coin]\n end\n end\n ways[-1]\nend",
"def make_change(amt, coins, coin_cache = {0 => 0})\n return coin_cache[amt] if coin_cache[amt]\n return 0.0/0.0 if amt < coins[0]\n\n min = amt\n change_possible = false\n coins.each do |coin|\n next if coin > amt\n\n test_change = make_change(amt - coin, coins, coin_cache) + 1\n if test_change.integer? && test_change < min\n change_possible = true\n min = test_change\n end\n end\n\n min = 0.0/0.0 unless change_possible\n coin_cache[amt] = min\n\n min\n end",
"def make_greedy_coin(remainder,arr=[50,25,10,5,1])\ni=0\nresult=[]\nwhile i < arr.length\nif remainder - arr[i]<0\ni+=1\nelse\n result << arr[i]\n return result+make_greedy_coin(remainder-arr[i])\nend\n\nend\nreturn result\nend",
"def make_change(amt, coins, coin_cache = { 0 => 0 })\n return coin_cache[amt] if coin_cache[amt]\n return 0.0 / 0.0 if amt < coins[0]\n\n ans = 0.0 / 0.0\n coins.each do |coin|\n break if coin > amt\n num_coins = 1 + make_change(amt - coin, coins, coin_cache)\n ans = num_coins unless ans.is_a?(Integer) && num_coins > ans\n end\n\n coin_cache[amt] = ans.is_a?(Integer) ? ans : 0.0 / 0.0\n end",
"def nonConstructibleChange(coins)\n min_change = 0\n coins.sort!\n\n coins.each do |coin|\n if coin > (min_change + 1)\n return (min_change + 1)\n else\n min_change += coin\n end\n end\n return (min_change + 1)\nend",
"def given(array = [])\n i = cur_val = 0\n until array[i].nil?\n cur_val += array[i] * VALS[i]\n i += 1 \n end\n return [array] if cur_val == GOAL_VAL\n combos = []\n if VALS[i] > 1\n (0..((GOAL_VAL - cur_val) / VALS[i])).each do |num_coins|\n combos += given( array + [num_coins] )\n end\n return combos\n else\n return [array + [GOAL_VAL - cur_val] ]\n end\nend",
"def coin_change2(coins, amount)\n coins_needed = Hash.new do |hash, key|\n coins_needed_after_one = coins.select {|coin_value| coin_value <= key}.map {|coin_value| hash[key-coin_value]}\n .reject {|coins_needed| coins_needed == -1}.min\n hash[key] = if coins_needed_after_one == nil then -1 else 1 + coins_needed_after_one end\n end.update(0 => 0)\n \n #This is just to prevent stack overflow. If you tried to directly calculate amount you might have too many calls down.\n (1..amount).each {|current| coins_needed[current]}\n \n coins_needed[amount]\nend",
"def coin_change(coins, amount)\n coins = coins.sort\n\n return -1 if coins.empty?\n return -1 if coins[0] > amount\n\n current_coin = coins.pop\n change = []\n sum = 0\n\n loop_coins(coins, amount ,current_coin, change, sum)\nend",
"def change2(amount, denominations)\n denomination_breakdown = Array.new(amount + 1, 0)\n denomination_breakdown[0] = 1\n\n denominations.each do |denomination|\n (denomination..amount).each do |higher_amount|\n remainder = higher_amount - denomination\n denomination_breakdown[higher_amount] += denomination_breakdown[remainder]\n end\n end\n\n denomination_breakdown[amount]\nend",
"def make_change(amt, coins)\n return Float::INFINITY if amt < 0\n return @change_hash[amt] if @change_hash[amt]\n min_so_far = Float::INFINITY\n coins.each do |coin|\n num_coins = make_change(amt - coin, coins) + 1\n min_so_far = num_coins if num_coins < min_so_far\n end\n @change_hash[amt] = min_so_far\n min_so_far\n end",
"def change(amount, arr)\n changes = [[]] + Array.new(amount, Array.new(amount))\n\n 1.upto(amount) do |i|\n arr.each do |coin|\n next if coin > i\n\n changes[i] = changes[i - coin] + [coin] if changes[i].size > (changes[i - coin] + [coin]).size\n end\n end\n\n changes[amount]\nend",
"def change(amount, coins)\n dp = Array.new(amount + 1,0)\n dp[0] = 1\n (1..coins.size).each do |i|\n (1..amount).each do |j|\n if coins[i - 1] <= j\n dp[j] = dp[j] + dp[j - coins[i-1]]\n end\n end\n end\n dp[amount]\nend",
"def change(amount, arr)\n arr.reverse.each_with_object([]) do |coin, change|\n until coin > amount\n amount -= coin\n change << coin\n end\n end\nend",
"def make_change(a, list = [25, 10, 5, 1])\n return [] if a < 0\n return [] if a != a.floor\n\n parents = Array.new(a + 1)\n parents[0] = 0\n worklist = [[0, 0]]\n while parents[a].nil? && !worklist.empty? do\n base, starting_index = worklist.shift\n starting_index.upto(list.size - 1) do |index|\n denomination = list[index]\n tot = base + denomination\n if tot <= a && parents[tot].nil?\n parents[tot] = base\n worklist << [tot, index]\n end\n end\n end\n\n return [] if parents[a].nil?\n result = []\n while a > 0 do\n parent = parents[a]\n result << a - parent\n a = parent\n end\n result.sort!.reverse!\n end",
"def make_largest_change(amount, coins)\n orig_amount, change = amount, []\n coins.size.times {|index| change[index], amount = amount / coins[index], amount % coins[index] }\n amount > 0 ? make_largest_change(orig_amount + 1, coins) : change # err in favor of larger amount returned\n end",
"def make_change(amt, coins)\n return Float::INFINITY if amt < 0\n @cache[0] = 0\n\n return @cache[amt] if @cache[amt]\n minimum = Float::INFINITY\n\n coins.each do |coin|\n attempt = make_change(amt - coin, coins) + 1\n minimum = attempt unless minimum.is_a?(Integer)\n minimum = attempt if attempt < minimum\n end\n\n @cache[amt] = minimum\n end",
"def GetChangeCombos(n, c)\n ways = Array.new(n+1,0)\n ways[0] = 1\n c.select!{|c| c<n}\n return 0 if (c.empty?)\n for coin in c\n for amount in coin..n\n ways[amount] =ways[amount] + ways[amount - coin]\n end \n end\n ways[n]\nend",
"def make_change(money, change)\n return [] if money == 0\n if change.first > money\n make_change(money, change.drop(1))\n else\n make_change(money - change.first, change).unshift(change.first)\n end\nend",
"def changer(amount)\n\n coins = []\n\n [25, 10, 5, 1].each do |denomination|\n coins = amount / denomination\n returned_coins += [denomination] * coins\n amount -= coins * denomination\n end\n returned_coins\nend",
"def make_change(amount, denominations = DENOMINATIONS)\n change = {} \n denominations.each{|coin, value|\n num, amount = amount.divmod(value)\n change[coin] = num if num > 0\n }\n # print \" \"\n change\nend",
"def dp_change(money, coins) \n <<-DOC\n Input: An integer money and an array Coins = (coin1, ..., coind).\n Output: The minimum number of coins with denominations Coins that changes money.\n \n DPCHANGE(money, Coins)\n MinNumCoins(0) ← 0\n for m ← 1 to money\n MinNumCoins(m) ← ∞\n for i ← 1 to |Coins|\n if m ≥ coini\n if MinNumCoins(m - coini) + 1 < MinNumCoins(m)\n MinNumCoins(m) ← MinNumCoins(m - coini) + 1\n output MinNumCoins(money) \n \n DOC\n\n # Since we can't assign infinity, lets assign the max possible coins + 1 as inifinity\n # Get the least value coin and divide our money with that \n infinity = (money/coins[-1]) + 1\n min_num_coins = {}\n min_num_coins[0] = 0\n (1..money).each do |m|\n min_num_coins[m] = infinity\n coins.each do |coin|\n if (m >= coin)\n if (min_num_coins[m-coin] + 1) < min_num_coins[m]\n min_num_coins[m] = min_num_coins[m-coin] + 1\n end\n end\n end\n end\n return min_num_coins[money]\n end",
"def change_possibilities(amount, array_length, target)\n # If the target is 0 there is only one solution\n return 1 if (target == 0)\n \n # If the target is less than 0 there are no solutions\n return 0 if (target < 0)\n \n # If there are no more integers i the array and\n # the target is greater than 0, then no\n # solution exist\n return 0 if (array_length <=0 and target >= 1)\n \n return change_possibilities(amount, array_length-1, target) + change_possibilities(amount, array_length, target-amount[array_length-1] )\nend",
"def change(amount, coin_arr, index)\n\tif amount == 0\n\t\treturn 1\n\tend\n\tif index >= coin_arr.length\n\t\treturn 0\n\tend\n\n\tamount_with_coin = 0\n\tways = 0\n\n\twhile amount_with_coin <= amount\n\t\tremainder = amount - amount_with_coin\n\t\tways += change(remainder, coin_arr, index+1)\n\t\tamount_with_coin += coin_arr[index]\n\tend\n\tways\nend",
"def change_possibilities_bottom_up(amount, denominations)\n ways_of_doing_n_cents = [0] * (amount + 1)\n ways_of_doing_n_cents[0] = 1\n\n denominations.each do |coin|\n (coin..amount).each do |higher_amount|\n higher_amount_remainder = higher_amount - coin \n ways_of_doing_n_cents[higher_amount] += ways_of_doing_n_cents[higher_amount_remainder]\n end\n end\n ways_of_doing_n_cents\nend",
"def determine_minimal_coins(num)\n count = 0\n coins = [11, 9, 7, 5, 3, 1]\n change = num\n coins.each do |coin|\n while change >= coin\n count += 1\n # why in this line, the change always minus 11? but not other coins?????????????\n change -= coin\n end\n end\n count\nend",
"def coin_combos(total)\n coins = [1, 5, 10, 25, 50, 100]\n counter ||= 0\n if total == 0\n counter += 1\n p \"#{counter} is counter\"\n return\n elsif total > 0\n coins.reverse.each do |integer|\n if integer < total\n coin_combos(total - integer)\n end\n end\n end\nend",
"def change_possibilities_bottom_up(amount, denominations)\n ways_of_doing_n_cents = [1] + Array.new(amount, 0)\n\n denominations.each do |coin| # 1\n (coin..amount).each do |higher_amount|\n higher_amount_remainder = higher_amount - coin\n ways_of_doing_n_cents[higher_amount] += ways_of_doing_n_cents[higher_amount_remainder]\n end\n end\n\n ways_of_doing_n_cents[amount]\nend",
"def make_change(amount)\n\tcoin_values = [25, 10, 5, 1]\n\tcoins = []\n\n\tcoin_values.each do |value|\n\t\twhile amount >= value\n\t\t\tcoins.push(value)\n\t\t\tamount -= value\n\t\tend\n\tend\n\n\t# while (amount - 25) >= 0\n\t# \tcoins.push(25)\n\t# \tamount -= 25\n\t# end\n\n\t# while (amount - 10) >= 0\n\t# \tcoins.push(10)\n\t# \tamount -= 10\n\t# end\n\n\n\t# while (amount - 5) >= 0\n\t# \tcoins.push(5)\n\t# \tamount -= 5\n\t# end\n\n\t# while (amount - 1) >= 0\n\t# \tcoins.push(1)\n\t# \tamount -= 1\n\t# end\n\tcoins\nend",
"def return_coins(remaining_coins,target_amount)\n # 1. loop through coins, if any one of it is == target_amount, return it.\n # 2. if coins < target_amount, minus the coin from target_amount and save it in a variable.\n return [] if remaining_coins.sum < target_amount\n return [1] if target_amount == 1\n return [] if remaining_coins == []\nfor i in remaining_coins\n return i if i == target_amount\n\n if i == target_amount/3 && !(i < target_amount) \n testcase10 = remaining_coins.select{|x|x==(target_amount/3)}\n return testcase10\n elsif i < target_amount \n save = i\n temporary = target_amount - save\n end\nend \n# remaining_coins.delete_at(remaining_coins.index(remaining_coins[-1]))\nremaining_coins.delete_at(remaining_coins.find_index(save))\nfinal = [save] + [return_coins(remaining_coins,temporary)]\nreturn final.flatten.sort\nend",
"def coin_change(coins, amount)\n make_change(coins, amount, 0, {})\nend",
"def make_change_for_amount(amount, check = false)\n remaining_returns = amount\n\n change = []\n\n @coins.each do |coin, count|\n num_coins = count\n\n while num_coins > 0 && ((remaining_returns - @@coin_value_by_details[coin]) >= 0)\n # remove amount we need less\n remaining_returns -= @@coin_value_by_details[coin]\n change << @@coin_value_by_details[coin]\n\n num_coins -= 1\n end\n\n @coins[coin] = num_coins unless check\n\n break if remaining_returns == 0\n end\n\n change\n end",
"def change_in_coins(change)\n return [] if change.zero?\n supported_nominals.reverse_each do |coin|\n next if (change - coin).negative? || !coin_available?(coin)\n remove_change_coin(coin)\n next unless (sum = change_in_coins(change - coin))\n return sum + [coin]\n end\n nil\n end",
"def make_change(amount, denominations)\n\nend",
"def calculate_change(amount, coin_array = nil)\n # ignore coins higher than the target amount\n @status = :no_change\n avail_coins = get_available_coins(coin_array, amount)\n return status unless avail_coins.any?\n required_quantity = amount / avail_coins[0].value\n return status unless coins_are_available(avail_coins, required_quantity)\n residual = amount % avail_coins[0].value\n return @status = :success if residual.zero?\n calculate_change(residual, avail_coins[1..-1])\n end",
"def coin_denominaitons(money, denom)\n\tcount = 0\n\tresult = []\n\t#M = money\n\t#D = denom.reverse\n\tdef denominate (mm, dd)\n\t\tsubresult = []\n\t\t#while m > 0\n\t\t\tdd.each do |d|\n\t\t\t\twhile mm >= d\n\t\t\t\t\tsubresult << \"#{d}c\"\n\t\t\t\t\tmm - d\n\t\t\t\tend\n\t\t\tend\n\t\t#end\n\t\tputs subresult\n\t\tresult << subresult\n\t\tcount += 1\n\t\tdd.shift\n\t\tdenominate(mm, dd)\n\tend\t\n\tdenominate(money,denom)\n\tputs \"Number of ways to make #{M}: #{count}\"\n\tputs result\nend",
"def change_for(total_change)\n raise NegativeTargetError if total_change < 0\n\n final_row = coins.reduce(\n [[]] + [nil] * total_change,\n &method(:apply_coin_to_row)\n )\n\n raise ImpossibleCombinationError if final_row[-1].nil?\n\n final_row[-1]\n end",
"def possibilities (target, coins)\n return 1 if target == 0\n return 0 if target < 0 || coins . length == 0\n\n sum = 0\n for i in 0 .. (target / coins [0]) . to_i do\n sum += possibilities(target - i * coins [0], coins [1 .. -1])\n end\n\n return sum\nend",
"def alternate_options(amount, coins)\n inner_options, high, head, tail = [], amount / coins[0], coins[0], coins[1..-1]\n high.times {|n| inner_options << make_largest_change((amount - ((high - n) * head)), tail).unshift(high - n)}\n inner_options\n end",
"def make_change( amount )\n #REMOVED IN REFACTOR: coins = changer( pull_cents( f ), COINS )\n #REMOVED IN REFACTOR: bills = changer( pull_bills( f ), BILLS )\n coins = changer( pull_currency( amount ){ | s, idx | currency = s[ idx + 1..-1 ] }, COINS )\n bills = changer( pull_currency( amount ){ | s, idx | currency = s[ 0...idx ] }, BILLS )\n [ bills, coins ]\n end",
"def make_change(num)\n\t\n\tarray = []\n\n\tamount = num\n\tquaters = amount/25\n\t# puts quaters \n\tamount_left= num - (quaters * 25 )\n\tdime = amount_left/10\n\t# puts dime\n\tamount_left2 = num - (quaters*25+dime*10)\n\tnickel = amount_left2/5\n\t# puts nickel\n\tamount_left3 = num - (quaters*25+dime*10+nickel*5)\n\tpenny = amount_left3/1\n\t# puts penny\n\tarray.push((quaters*25),(dime*10),(nickel*5),penny)\n\tarray\n\n\t# coins = []\n\n\t# while (amount-25) >= 0\n\t# \tcoins.push(25)\n\t# \tamount -=25\n\t# end\n\n\n\n\nend",
"def change (cost, quantity) \n\t@total_change = @total - (cost.to_i * quantity.to_i) #subtract cost*quantity to the total money\n\t@new_total = @total_change \n\t#looking for number of bills per denomination\n\tif @total_change >= 1000\n \t\tthousands_change = @total_change / 1000\n \t\t@total_change = @total_change % 1000\n \tend\n \t\n \tif @total_change >= 500\n \t\tfive_hundreds_change = @total_change / 500\n \t\t@total_change = @total_change % 500\n \tend\n \t\n \tif @total_change >= 100\n \t\thundreds_change = @total_change / 100\n \t\t@total_change = @total_change % 100\n \tend\n \t\n \tif @total_change >= 50\n \t\tfifties_change = @total_change / 50\n \t\t@total_change = @total_change % 50\n \tend\n \t\n \tif @total_change >= 20\n \t\ttwenties_change = @total_change / 20\n \t\t@total_change = @total_change % 20\n \tend\n \t\n \tif @total_change >= 10\n \t\ttens_change = @total_change / 10\n \t\t@total_change = @total_change % 10\n \tend\n \t\n \tif @total_change >= 5\n \t\tfives_change = @total_change / 5\n \t\t@total_change = @total_change % 5\n \tend\n \t\n \tif @total_change >= 1\n \t\tones_change = @total_change / 1\n \t\t@total_change = @total_change % 1\n \tend\n \t\n \tchange = {\n \t\t:ones => ones_change.to_i,\n \t\t:fives => fives_change.to_i,\n \t\t:tens => tens_change.to_i,\n \t\t:twenties => twenties_change.to_i,\n \t\t:fifties => fifties_change.to_i,\n \t\t:hundreds => hundreds_change.to_i,\n \t\t:five_hundreds => five_hundreds_change.to_i,\n \t\t:thousands => thousands_change.to_i\n \t}\n \t\n \t\"<br /> #{change[:ones]} Php 1\" \"<br />#{change[:fives]} Php 5\" \"<br />#{change[:tens]} Php 10,\" \"<br />#{change[:twenties]} Php 20\" \"<br />#{change[:fifties]} Php 50\" \"<br />#{change[:hundreds]} Php 100\" \"<br />#{change[:five_hundreds]} Php 500\" \"<br />#{change[:thousands]} Php 1000\"\n end",
"def min_change_sum(coins, total)\n totals = Array.new(total + 1, 1000000000000)\n totals[0] = 0\n\n (1..total).each do |i|\n coins.each do |coin|\n if coin <= i && (totals[i-coin] + 1 < totals[i])\n totals[i] = totals[i-coin] + 1\n end\n end\n end\n\n totals[total]\nend",
"def coins(n, demoninations = [1, 5, 10, 25])\n change_table = []\n\n \n\nend",
"def coin_combos(target_value, coin_values)\n coin_values.sort!\n _coin_combos(target_value, coin_values)\nend",
"def lemonade_change(bills)\n hash = {\n 5 => 0,\n 10 => 0,\n 20 => 0\n }\n \n bills.each do |bill|\n hash[bill] += 1\n if bill != 5\n change = bill - 5\n \n until change == 0\n if change >= 20\n if hash[20] > 0\n hash[20] -=1\n change -= 20\n elsif hash[10] > 0\n hash[10] -=1\n change -= 10\n elsif hash[5] > 0\n hash[5] -=1\n change -= 5\n else\n return false\n end\n elsif change >= 10\n if hash[10] > 0\n hash[10] -=1\n change -=10\n elsif hash[5] > 0\n hash[5] -=1\n change -= 5\n else\n return false\n end\n elsif change >= 5\n if hash[5] > 0\n hash[5] -=1\n change -= 5\n else\n return false\n end\n end\n end\n \n end\n end\n true\nend",
"def dispense_change(change_due, product)\n coins = @coins.map(&:value)\n change = coins.sort\n .reverse\n .map do |coin|\n number_of_coins = change_due / coin\n change_due %= coin\n Array.new(number_of_coins) { coin }\n end\n change.flatten.each do |ch|\n @coins.delete(@coins.find { |c| c.value == ch })\n end\n puts \"Here are the coins due to you: #{change.flatten} pennies\"\n dispense_product(product)\n change.flatten\n end",
"def wonky_coins(n)\n return 1 if n == 0\n\n # call wonky_coins from inside itself. This is called *recursion*.\n return wonky_coins(n / 2) + wonky_coins(n / 3) + wonky_coins(n / 4)\nend",
"def solution_proximity_heuristic(amount,comb,coins)\n (amount-comb.sum)*min_size_heuristic(amount,comb,coins)\nend",
"def find_solutions_dp\n solutions = Array.new(@amount+1).map {|i| 0 }\n solutions[0] = 1\n\n @coins.each do |coin|\n for i in coin..@amount\n solutions[i] = solutions[i] + solutions[i-coin]\n end\n end\n\n solutions[@amount]\n end",
"def arrange_coins(n)\n k = 0\n while (n -= k) > k\n k += 1\n end\n k\nend",
"def puppy_golden_age_brute_forced(gains)\n \n # brute force solution\n \n if gains.empty?\n return nil\n end\n \n golden_age_so_far= [0, 0]\n value_so_far= sum(gains[0..0])\n \n 0.upto (gains.length-1) do |i|\n i.upto (gains.length-1) do |j|\n if sum(gains[i..j]) > value_so_far\n value_so_far= sum(gains[i..j])\n golden_age_so_far= [i, j]\n end\n end\n end\n \n golden_age_so_far\nend",
"def recursive_solution\n\n end",
"def getWays(n, c)\n # i = n or change needed\n # j = enabled coins\n # dp[i][j] = dp[i - j's coin value][j] + dp[i][j - 1]\n store = [[1] * c.length]\n\n (1..n).each do |i|\n c.length.times do |j|\n sum_one = i - c[j] >= 0 ? store[i - c[j]][j] : 0\n sum_two = j - 1 >= 0 ? store[i][j - 1] : 0\n store[i] = [] unless store[i]\n store[i][j] = sum_one + sum_two\n end\n end\n\n store.last.last\nend",
"def solve112(target_proportion)\n bouncy_proportion = 0\n total_bouncy = 0\n num = 0\n while bouncy_proportion < target_proportion\n num += 1\n if bouncy?(num)\n total_bouncy += 1\n bouncy_proportion = 1.0*total_bouncy/num\n end\n end\n puts target_proportion, num\nend",
"def min_size_heuristic(amount,comb,coins)\n rem = amount-comb.sum\n return Infinity if rem < 0\n comb.size+rem.to_f/(coins.select{|c|c<=rem&&c<=comb.max}.max) rescue comb.size\nend"
] |
[
"0.8316564",
"0.8313527",
"0.8258674",
"0.82523847",
"0.82502264",
"0.82125086",
"0.817377",
"0.8012915",
"0.79881406",
"0.7953267",
"0.7931597",
"0.7929538",
"0.7929538",
"0.79112273",
"0.7862891",
"0.78613335",
"0.78555894",
"0.7845935",
"0.78330916",
"0.7801413",
"0.77469087",
"0.7690272",
"0.76799613",
"0.76530695",
"0.7632191",
"0.7585339",
"0.75795674",
"0.75146306",
"0.75082254",
"0.74876475",
"0.74463487",
"0.72353697",
"0.72229475",
"0.72128797",
"0.71605945",
"0.712456",
"0.70988816",
"0.701608",
"0.6992757",
"0.6980432",
"0.6884226",
"0.68101794",
"0.6802076",
"0.6791556",
"0.6777688",
"0.6753385",
"0.67243654",
"0.67122275",
"0.66722757",
"0.66633964",
"0.6654364",
"0.6630442",
"0.6628936",
"0.65990674",
"0.6580024",
"0.65644705",
"0.65385425",
"0.6530829",
"0.65087456",
"0.6494152",
"0.64928013",
"0.648065",
"0.646764",
"0.6463516",
"0.64452046",
"0.6412937",
"0.6372522",
"0.63599974",
"0.6317848",
"0.6317822",
"0.62733144",
"0.6226111",
"0.6137249",
"0.6124768",
"0.61115205",
"0.6100266",
"0.6091628",
"0.60676473",
"0.6056564",
"0.60334224",
"0.60084987",
"0.5981319",
"0.5976908",
"0.5947208",
"0.593874",
"0.5913616",
"0.58890134",
"0.5876288",
"0.58409077",
"0.58198184",
"0.5765441",
"0.57394993",
"0.5737566",
"0.57349235",
"0.5718905",
"0.5714095",
"0.5698123",
"0.5678575"
] |
0.64890194
|
63
|
THIS PROBLEM WILL NOT SHOW UP ON A REAL ASSESSMENT If you are a nonnative English speaker and find it difficult to understand this problem, do not spend too much time on it. Focus on other problems instead. Define a method `pig_latinify(sentence)` that translates a sentence into pig latin. You may want a helper method. Rules In the English language, vowels are the following letters: ['a', 'e', 'i', 'o', 'u'] Consonants are all other letters. Pig latin translation uses the following rules: 1. If the word begins with a vowel, simply append `ay` onto the end. ex. 'apple' => 'appleay' 2. If the word begins with a consonant, move the starting consonants to the end of the word and then append `ay` ex1. 'pearl' => 'earlpay' ex2. `school` => `oolschay` 3. Treat `qu` at the start of a word as a singular consonant. ex1. `queen` => `eenquay` ex2. `square` => `aresquay`
|
def pig_latinify(sentence)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def pig_latin_sentence(sentence)\n y = sentence\n x = sentence.split\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n t = \"t\"\n h = \"h\"\n qu = \"qu\"\n\n x.map do |word|\n first_letter = word[0]\n if vowels.include?(first_letter)\n word << \"way\"\n elsif word.include?(t && h)\n word << t\n word << h\n word.slice!(0..1)\n word << \"ay\"\n elsif word.include?(qu)\n word << qu\n word.slice!(0..1)\n word << \"ay\"\n else\n word << first_letter\n word.slice!(0)\n word << \"ay\"\n end\n x[0].capitalize!\n end\n\n x.join(\" \")\nend",
"def convert_pig_latin(sent)\n vowels = \"aeiou\"\n latin = []\n\n sent = sent.split(\" \")\n sent.each_with_index do |word,idx|\n uppercase = false\n if word.length < 3\n latin << word\n elsif vowels.include?(word[0].downcase)\n latin << (word + \"yay\")\n else\n temp_str = \"\"\n i = 0\n while i < word.length\n uppercase = true if i == 0 && word[i] == word[i].upcase\n if !vowels.include?(word[i].downcase)\n temp_str += word[i]\n else \n new_word = (word[i..-1] + temp_str.downcase + \"ay\")\n uppercase ? ( latin << (new_word[0].upcase + new_word[1..-1]) ) : ( latin << new_word )\n break\n end\n i += 1\n end\n end\n end\n latin.join(\" \")\nend",
"def piglatinize_word(word)\r\n # vowel at the start\r\n # 3 consonants\r\n # 2 consonants\r\n # 1 consonant\r\n # count consonants\r\n count = 0\r\n # check if word starts with a vowel\r\n if !consonant?(word[0])\r\n word += \"w\"\r\n else\r\n count += 1\r\n end\r\n \r\n # check if word starts with 3 consonants\r\n if count == 1 && consonant?(word[1]) && consonant?(word[2])\r\n count += 2\r\n word = word.slice(3..-1) + word.slice(0,3)\r\n # check if word starts with 2 consonants if it isn't 3\r\n elsif count == 1 && consonant?(word[1])\r\n word = word.slice(2..-1) + word.slice(0,2)\r\n # check if word starts with 1 consonant if it isn't 3 or 2\r\n elsif count == 1 \r\n word = word.slice(1..-1) + word.slice(0)\r\n end\r\n\r\n # finally add the \"ay\" using += or <<\r\n word+= \"ay\"\r\n end",
"def pig_latin(word)\n vowels = ['a', 'e', 'i', 'o', 'u']\n suffix = 'ay'\n position = 0\n word = word.split(//)\n\n word.any? do |character|\n if vowels.include?(character)\n position = word.find_index(character)\n end\n end\n\n word = word.join.downcase\n punctuation = punctuation?(word) ? word.chars.last : ''\n word_start = punctuation?(word) ? word[position..-2] : word[position..-1]\n\n if position > 0\n word = word_start + word[0...position] + suffix + punctuation \n return word\n end\n\n word = word + suffix\nend",
"def pig_latin_name(word)\n# and returns a new string (pig latinified)\n# need to define vowels (can be an array?)\n vowels_list = vowels\n# break word into letters\n letters = word.split(\"\")\n# iterate through each letter of the word\n# until we hit a vowel\n letters.each do |letter|\n\n # check if first letter is vowel or consonant\n if is_consonant?(letter)\n # move it to the end\n removed_consonant = letters.shift\n letters = letters + removed_consonant.split\n #\n else\n letters.push(\"ay\")\n return letters.join\n end\n\n # then add \"ay\" at the end and return\n end\n\nend",
"def piglatinize(word)\n vowels = ['a','e','o','u','i','A','E','O','U','I']\n split_word = word.split('')\n\n if vowels.include?(split_word[0])\n split_word << \"way\"\n else\n until vowels.include?(split_word[0])\n split_word.rotate!(1)\n end\n split_word << \"ay\"\n end\n split_word.join\n end",
"def piglatinize(words)\n \n # \"flat iron\"\n # change the words in to an arry of words\n # words = \"Flat iron\"\n # expecting \"atFlay ironway\"\n splited_words = words.split(\" \")\n # vowels = [\"a\", \"e\",\"i\",\"o\"]\n sentence = []\n splited_words.each do |word|\n # .map do |word|\n changed_word = []\n beginning =[]\n i = 0\n while i < word.length do\n if word[i].downcase != \"a\" && word[i].downcase != \"e\" && word[i].downcase != \"i\" && word[i].downcase != \"o\" && word[i].downcase != \"u\"\n \n changed_word << word[i] \n else\n break\n end\n i += 1\n end\n \n beginning << word[i, word.length]\n if word[0].downcase != \"a\" && word[0].downcase != \"e\" && word[0].downcase != \"i\" && word[0].downcase != \"o\" && word[0].downcase != \"u\"\n\n latinized = beginning.join + changed_word.join + \"ay\" \n sentence << latinized \n else\n latinized = beginning.join + changed_word.join + \"way\" \n sentence << latinized\n end\n end \n sentence.join(\" \")\n end",
"def convert_sentence_to_pig_latin(sentence)\n\tpig_sentence = ''\n\twords = sentence.split(/\\W+/)\n\trubbish = sentence.split(/\\w+/)\n\tfor i in (0..words.length)\n\t\tpig_sentence += rubbish[i].to_s + convert_word_to_pig_latin(words[i]) \n\t\t#put rubbish at first because it has empty string\n\tend\n\treturn pig_sentence\nend",
"def pig_latin word\n vowels = %w(a e i o u)\n if vowels.include? word[0]\n word + 'yay'\n else\n vw = nil\n word.chars.each_with_index do |x,xi|\n vw = xi and break if vowels.include? x\n end\n pre = word[0...vw]\n suf = word[vw..-1]\n suf + pre + 'ay'\n end\nend",
"def pig_latin(word)\n # Encrypts words into pig latin\n # if/else: catches the \"qu\" phoneme to treat it as a group\n # until: builds the word section to be shifted to the end\n i = 0\n shift = ''\n vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n if word.include?('qu') == true\n until \"u\".include? (word[i]) do\n shift += word[i]\n i += 1\n end\n shift += word[i]\n else \n until vowels.include? (word[i]) do \n shift += word[i]\n i += 1\n end\n end\n word.sub(shift, '') + shift.downcase + 'ay'\nend",
"def pig_latin(word)\n\nif word[0..0] =~ /[A-Z]/\n is_cap = true\nelse\n is_cap = false\nend\n\n if word.slice(0) == \"a\" ||\n word.slice(0) == \"e\" ||\n word.slice(0) == \"i\" ||\n word.slice(0) == \"o\" ||\n word.slice(0) == \"u\"\n word += \"way\"\n\n elsif word.slice(0..1) == \"qu\"\n word = word.slice(2..word.length) + word.slice(0..1) + \"ay\"\n\n elsif word.slice(1) == \"a\" ||\n word.slice(1) == \"e\" ||\n word.slice(1) == \"i\" ||\n word.slice(1) == \"o\" ||\n word.slice(1) == \"u\"\n word = word.slice(1..word.length) + word.slice(0) + \"ay\"\n\n elsif word.slice(2) == \"a\" ||\n word.slice(2) == \"e\" ||\n word.slice(2) == \"i\" ||\n word.slice(2) == \"o\" ||\n word.slice(2) == \"u\"\n word = word.slice(2..word.length) + word.slice(0..1) + \"ay\"\n\n elsif word.slice(3) == \"a\" ||\n word.slice(3) == \"e\" ||\n word.slice(3) == \"i\" ||\n word.slice(3) == \"o\" ||\n word.slice(3) == \"u\"\n word = word.slice(3..word.length) + word.slice(0..2) + \"ay\"\n\n end\n if is_cap == true\n return word.capitalize\n else\n return word\n end\nend",
"def pig_latinify(sentence)\n translated_words = sentence.split(\" \").map do |word|\n translate_word(word)\n end\n translated_words.join(\" \")\nend",
"def convert_pig_latin(sentence)\n translated = []\n\n sentence.split(' ').each do |word|\n if word.length > 2\n translated << pig_latin(word)\n else\n translated << word\n end\n end\n translated.join(' ')\nend",
"def piglatin(word)\n new_string = \"\"\n vowels = (\"aeiou\")\n word.split(\"\").each_with_index do |letter, index| \n if !vowels.include?(letter.downcase)\n next\n else\n if index == 0\n new_string += word + \"way\"\n return new_string\n else\n up_to_vowel = word.slice(0...index)\n after_vowel = word.slice(index..-1)\n new_string += after_vowel + up_to_vowel + \"ay\"\n return new_string\n end\n end\n end\n end",
"def pig_latin_sentence(sentence)\r\n\tnew_sentence = \"\"\r\n\tsentence.split.each do |word|\r\n\t\tif word[0].downcase =~ /[aeiou]/\r\n\t\t\tword << \"way\" \r\n\t\telse\r\n\t\t\tn = /[aeiou]/.match word.downcase\r\n\t\t\tword = n.to_s + n.post_match + n.pre_match + \"ay\"\r\n\t\tend\r\n\t\tnew_sentence << word\r\n\tend\r\n\tnew_sentence\r\nend",
"def pigatize\n # Declare the output string\n piglatin = ''\n # Split the input text into words and loop with .each,\n # and 'word' as the iterator variable.\n split(' ').each do |word|\n # Check to see if the first letter is a vowel, else it's a consonant.\n if starts_with_vowel(word[0])\n # Add onto the output string with += and add an extra space.\n piglatin += word + 'way'\n else\n piglatin += word[1..-1] + word[0] + 'ay' + ' '\n end\n end\n # Added a .chomp here to get rid of any trailing space.\n piglatin.chomp\n end",
"def sentence_to_pig_latin(sentence)\n sentence = sentence.split(' ')\n sentence.map! do |word|\n punctuation = get_punctuation(word)\n word = remove_punctuation(word.downcase)\n pig_latin(word) + punctuation\n end\n sentence.join(' ')\nend",
"def pig_latinify(sentence)\nend",
"def pig_latin(string)\n words_array = string.split(\" \")\n modified_words_array = \"\"\n words_array.map do |word|\n \n if word =~ /\\A[aeiou]/\n word += \"ay\"\n modified_words_array << word + \" \"\n \n # regex to grab three consonants took from http://stackoverflow.com/questions/18406509/using-regexp-to-check-whether-a-string-starts-with-a-consonant\n # word starts with three consonants or \"[const.]qu\" ie. \"square\", \"squat\"\n elsif ( word =~ /\\A(?i:(?![aeiou])[a-z]){3}/ ) || ( word =~ (/\\b[^aeiou]+qu/) ) # word =~ /\\A[^aeiou]+qu{3}/ )\n without_first_three = word[3..-1]\n without_first_three += word[0..2] + \"ay\"\n if word[0] == word[0].upcase\n without_first_three.capitalize!\n end\n modified_words_array << without_first_three + \" \"\n \n # word starts with two consonants or \"qu\" ie. \"quake\", \"quart\" \n elsif ( word =~ /\\A(?i:(?![aeiou])[a-z]){2}/ ) || ( word =~ /\\A[qu]{2}/ )\n without_first_two = word[2..-1]\n without_first_two += word[0..1] + \"ay\"\n if word[0] == word[0].upcase\n without_first_two.capitalize!\n end\n modified_words_array << without_first_two + \" \"\n \n # word starts with consonant \n elsif word =~ /\\A[^aeiou]/\n without_first = word[1..-1]\n without_first += word[0] + \"ay\"\n if word[0] == word[0].upcase\n without_first.capitalize!\n end\n modified_words_array << without_first + \" \"\n end\n \n end\n modified_words_array.chomp(\" \")\nend",
"def piglatinizer(str)\n plstr = \"\"\n arr = str.split\n\n arr.each do |pig|\n if (pig.size <= 2) && (pig.slice(0) =~ /[aeiou]/)\n plstr << pig\n plstr << \"ay \"\n else\n l = pig.slice!(0)\n plstr << pig\n plstr << l\n plstr << \"ay \"\n end\n end\n plstr.downcase.capitalize\nend",
"def pig_latin(word)\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n ind = word.index(/[aeiou]/)\n\n if vowels.include?(word[0])\n word.delete(\" \") << \"ay\"\n else\n if ind == nil\n word << \"ay\"\n else\n final_word = word.chars.drop(ind) << word.chars.slice(0..ind-1) << \"ay\"\n final_word.join\n end\n end\n end",
"def pig_latin(word)\n if word.slice(0..1) == \"qu\"\n word = word.slice(1..word.length) + word.slice(0) + \"ay\" \n elsif word.slice(0) == \"a\" ||\n word.slice(0) == \"e\" ||\n word.slice(0) == \"i\" ||\n word.slice(0) == \"o\" ||\n word.slice(0) == \"u\"\n word += \"way\"\n elsif word.slice(1) == \"a\" ||\n word.slice(1) == \"e\" ||\n word.slice(1) == \"i\" ||\n word.slice(1) == \"o\" ||\n word.slice(1) == \"u\"\n word = word.slice(1..word.length) + word.slice(0) + \"ay\"\n elsif word.slice(2) == \"a\" ||\n word.slice(2) == \"e\" ||\n word.slice(2) == \"i\" ||\n word.slice(2) == \"o\" ||\n word.slice(2) == \"u\"\n word = word.slice(2..word.length) + word.slice(0..1) + \"ay\"\n else word.slice(3) == \"a\" ||\n word.slice(3) == \"e\" ||\n word.slice(3) == \"i\" ||\n word.slice(3) == \"o\" ||\n word.slice(3) == \"u\"\n word = word.slice(3..word.length) + word.slice(0..2) + \"ay\"\n end\n return word\nend",
"def pig_latin_word(word)\n\tvowels = \"a,e,i,o,u\"\n \tif ( vowels.include?(word[0]) )\n return word + \"yay\"\n end\n \tfor i in (0...word.length)\n if (vowels.include?(word[i]))\n return word[i..-1] + word[0...i] + \"ay\"\n end\n end\nend",
"def pig_latin(word)\n check_vowel = %w(a e i o u).include?(word[0])\n if check_vowel == true\n word + 'way'\n else\n word_array = word.chars.to_a\n until word_array[0].to_s == \"a\" || word_array[0].to_s == \"e\" || word_array[0].to_s == \"i\" || word_array[0].to_s == \"o\" || word_array[0].to_s == \"u\"\n word_array << word_array[0]\n word_array.shift\n end\n word_array.join + 'ay'\n end\nend",
"def pig_latinify(sentence)\n sentence.split(\" \").map { |word| pig_process(word) }.join(\" \")\nend",
"def pig_latin_word(word)\n vowels = \"aeiou\" # vowel string to reference to contain all vowels\n \n # abcdefghijklmnopqrstuvwxyz\n\n # check if the word starts with a vowel, then add yay\n if vowels.include?(word[0]) # word is a string and check if starts with first position if its a vowel - check this character\n return word + \"yay\" # return + add string yay\n end \n\n # iterate through every letter of each word\n word.each_char.with_index do |char, idx| # iterate and grab every character\n if vowels.include?(char) # we know the behavior of each char is to iterate from left to right\n before_vowel = word[0...idx] # up to but not including vowel -- gives you `tr`\n after_vowel = word[idx..-1] # very last position, inclusive -- gives you `ash`\n return after_vowel + before_vowel + \"ay\"\n end\n end\n\nend",
"def pig_it text\n\n # split string into array of words\n text_array = text.split(\" \")\n \n #for each word take first character from index [0] and move to last character index [-1] + 'ay', remove first character\n latin_array = text_array.map do |word|\n new_word = word + word[0] + \"ay\" \n new_word[1..-1]\n end\n \n #join together to single string\n latin_string = latin_array.join(\" \")\n \n #delete 'ay' from endings of sentences with punctuation - kind of cheating \n latin_string.sub! '!ay', '!' \n latin_string.sub! '?ay', '?'\n\n latin_string\n\nend",
"def pig_latin_word(word)\n vowels = \"aeiou\"\n pigArr = []\n wordArr = word.split(\"\")\n \n if vowels.include?(word[0]) == true\n return word << \"yay\"\n else\n\n word.each_char.with_index do |ele, idx|\n\n if vowels.include?(ele) == true\n wordArr << pigArr\n return wordArr.join(\"\") + \"ay\"\n else\n wordArr[idx] = \"\"\n pigArr << ele\n end\n \n end\n\n end\nend",
"def pig_latinify(sentence)\n results = []\n sentence.split(' ').each do |word|\n results << pig_word(word)\n end\n results.join(' ')\nend",
"def pig_latin(sentence)\n sentence.split.map { |word| latinify(word) }.join(\" \")\nend",
"def pig_latin_word(word)\n vowels = ['a', 'e', 'i', 'o', 'u']\n new_word = \"\"\n if vowels.include?(word[0])\n return word + \"yay\"\n else\n word.each_char.with_index do |ch, i|\n if vowels.include?(ch)\n return word[i..-1] + word[0...i] + \"ay\"\n end\n end\n end\nend",
"def pig_latin_word(word)\n pigLatin = \"\"\n str1 = \"\"\n str2 = \"\"\n\n if is_vowel(word[0])\n pigLatin = word + \"yay\"\n return pigLatin\n end\n\n word.each_char.with_index do |char, i|\n if is_vowel(char)\n return word[i..-1] + word[0...i] + \"ay\"\n end\n end\nend",
"def piglatinize(string)\n string.split(\" \").each do |word|\n m = word.match(/^[^aeiou]+/i)\n if m\n word.delete_prefix!(m[0])\n word << m[0]\n word << \"ay\"\n else\n word << \"way\"\n end\n end.join(\" \")\n end",
"def pig_latin_word(word)\n vowels = \"aeiou\"\n\n if vowels.include?(word[0])\n return word + \"yay\"\n end\n\n word.each_char.with_index do |char, i|\n if vowels.include?(char)\n return word[i..-1] + word[0...i] + \"ay\"\n end\n end\nend",
"def pig_latin_word(word)\r\n latin = word\r\n word.each_char.with_index do |char,idx|\r\n if isVowel(char)\r\n if idx == 0\r\n return latin + 'yay'\r\n else\r\n return latin + 'ay'\r\n end\r\n else\r\n letter = latin[0]\r\n latin[0] = \"\"\r\n latin += letter\r\n end\r\n end\r\nend",
"def pig_latin(word)\n if word.chr =~ /[aeiou]/\n word + \"way\"\n\n else while word =~ /\\A[^aeiou]/\n word = \"#{word[1..-1]}#{word[0..0]}\"\n if word.chr =~ /[aeiou]/\n end\n end\n word + \"ay\"\nend\nend",
"def pig_latin_word(word)\n vowels = 'aeiou'\n\n if vowels.include?(word[0])\n return word + 'yay'\n end\n\n word.each_char.with_index do | char, i |\n if vowels.include?(char)\n return word[i..-1] + word[0...i] + 'ay'\n end\n end\nend",
"def pig_latin_word(word)\n word_array = word.split('')\n vowels = 'aeiou'\n if vowels.include?(word_array.first)\n return \"#{word_array.join}yay\"\n end\n\n until vowels.include?(word_array.first)\n char = word_array.shift\n word_array.push(char)\n end\n\n \"#{word_array.join}ay\"\nend",
"def piglatinize(phrase)\n return PigLatinizer.translate_text(phrase)\n end",
"def pig_latin(sentence)\n \n\nend",
"def pig_latin_sentence(sentence)\n words = sentence.split(\" \")\n new_words = []\n words.each do |word|\n new_words << pig_latin(word)\n end\n new_words.join(\" \")\nend",
"def pig_latin(sentence)\n\nend",
"def pig_latin(word)\n word_array = word.split(\"\")\n if word.start_with?(\"a\",\"e\",\"i\",\"o\",\"u\")\n return \"#{word}way\"\n else\n until word_array[0].start_with?(\"a\",\"e\",\"i\",\"o\",\"u\")\n word_array = word_array.rotate(1)\n end\n return \"#{word_array.join}ay\"\n end\nend",
"def to_pig_latin(words)\n words.split(\" \").collect{|word| piglatinize(word)}.join(\" \")\n\nend",
"def pig_latinify(wordstring)\n\t\tstr = wordstring.downcase.gsub(/\\s+/, \"\") #gsub.replaces\n\t\tif str.start_with?(\"a\") || str.start_with?(\"e\") || str.start_with?(\"i\") || str.start_with?(\"o\") || str.start_with?(\"u\")\n\t\t\treturn str + \"way\"\n\t\telsif str == \"shit\" || str == \"fuck\" || str == \"arse\" || str == \"munter\" || str == \"cock\" || str == \"pussy\" || str == \"asshole\" || str == \"motherfucker\" |\n\t\t\treturn str.gsub(\"a\", \"*\").gsub(\"e\", \"*\").gsub(\"i\", \"*\").gsub(\"o\", \"*\").gsub(\"u\", \"*\")\n\t\telse\n\t\t\tsuffix = str[0]\n\t\t\tstr[0] = \"\"\n\t\t\treturn str + suffix + \"ay\"\n\t\tend\n\tend",
"def pig_latin(sentence)\n \n words = sentence.split\n result = words.map do |word|\n \tlatinize(word)\n end\n result.join(\" \")\nend",
"def piglatinize(input)\n\t\t#splits the input to capture multiple words\n\t\tif input.split(\" \").length == 1\n\t\t\tpiglatinize_single_word(input)\n\t\telse piglatinize_sentence(input)\n end\n\tend",
"def pig(word, howmany = 0)\r\n chars = word.split(//)\r\n lastletter_index = word.rindex(/\\w/)\r\n puncs = {}\r\n \r\n #grab punctuation, store info in hash\r\n chars.each_index { |x| puncs[x] = chars.at(x) if chars.at(x) =~ /\\W/ }\r\n\r\n #delete punctuation so we only deal with letters, does nothing if no punc \r\n chars.delete_if {|x| puncs.values.include?(x)} \r\n\r\n #not the most elegant for dealing with starts-with-vowel words, but more modular this way\r\n #skip this swapping stuff if it's a vowel for first letter\r\n if(howmany > 0) \r\n first = chars.slice!(0, howmany) #grab the first n chars, delete grabbed\r\n\r\n if(first[0] == first[0].upcase) #word was capitalized, swap order\r\n chars[0].upcase!\r\n first[0].downcase!\r\n end\r\n\r\n chars += first\r\n end\r\n\r\n #add back punctuation if it existed, does nothing if no punc\r\n puncs.keys.each { |key| chars.insert(key, puncs[key]) }\r\n \r\n #length == 1 means we got a single vowel like \"I\"; different rule\r\n chars.length == 1 ? chars << \"way\" : chars.insert(lastletter_index + 1, \"ay\") \r\n return chars.join(\"\")\r\nend",
"def pig_latin(sentence)\nend",
"def pig_sentence(string)\n pig_latin = \"\"\n string.split().each do |word|\n pig_latin += pig_word(word).downcase + \" \"\n end\n pig_latin.strip!\nend",
"def to_pig_latin(phrase)\n\t\tphrase.split.collect{|word| piglatinize(word)}.join(\" \")\n\tend",
"def piglatin(data)\n if data\n # + means space\n words = data.split(\"+\")\n piglatin_words = []\n\n words.each do |word|\n # vowel?\n if word[0].match(/[a,e,i,o,u]/)\n word = word + \"way\"\n # 'qu' at front?\n elsif word[0,2] == \"qu\"\n word = word[2..-1] + \"quay\"\n # consonant?\n elsif word[0].match(/[^a,e,i,o,u,0-9]/)\n word = word[1..-1] + word[0] + \"ay\"\n end\n\n piglatin_words.push(word)\n end\n\n piglatin_words.join(\" \")\n else\n \"Error: need input\"\n end\n end",
"def pig_latin_sentence(sentence)\n word_array = sentence.split\n\n new_array = word_array.map {|each_word| pig_latin(each_word)}.join(\" \")\nend",
"def pig_latin (string)\n if string.chr == \"a\" || string.chr == \"e\" || string.chr == \"i\" || string.chr == \"o\" || string.chr == \"u\" \n string + \"way\"\n else \n arr=[]\n arr = string.split(//) << string.split(//)[0]\n arr.delete_at(0)\n arr.join + 'ay'\n end\nend",
"def pig_latin_word(word)\r\n\tif word[0].downcase =~ /[aeiou]/\r\n\t\tword << \"way\" \r\n\telse\r\n\t\tn = /[aeiou]/.match word.downcase\r\n\t\tn.to_s + n.post_match + n.pre_match + \"ay\"\r\n\tend\r\nend",
"def pig_latin word\n vowel = word =~ /[aeio]|(?<!q)u/\n word[vowel..-1]+word[0...vowel]+'ay'\nend",
"def pig_latin_word(english)\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n \n if vowels.include?(english[0].downcase)\n english\n else\n vowel_index = english.index(/[aeiouy]/)\n front_half = english.slice!(vowel_index..-1)\n back_half = english\n punct = front_half.slice!(/\\W$/)\n punct = \"\" if punct == nil\n pig_word = front_half + back_half + \"ay\" + punct\n end\nend",
"def translate(sentence)\r\n words = sentence.split(\" \")\r\n words.collect! do |a|\r\n if(a =~ /\\w\\.\\.\\.\\w/) #matching e.g \"yes...no\"\r\n morewords = a.split(\"...\")\r\n ##\r\n #alternative: allows for recursion, but loses accuracy since \"a...b\" becomes \"a ... b\"\r\n #probably some non-messy way to make it work, and be less redundant too\r\n #\r\n #morewords.insert(1, \"...\")\r\n #translate(morewords.join(\" \"))\r\n pig(morewords[0], 1) + \"...\" + pig(morewords[1], 1)\r\n elsif(a =~ /\\w\\W\\w/ and !(a =~ /'/)) #matching e.g. \"steins;gate\", \"ninety-nine\", but not \"it's\"\r\n nonletter = a.scan(/\\W/)[0]\r\n morewords = a.split(/\\W/)\r\n #morewords.insert(1, nonletter)\r\n #translate(morewords.join(\" \"))\r\n pig(morewords[0], 1) + nonletter + pig(morewords[1], 1)\r\n elsif(a[0..1].match(/qu/)) #quiet = ietquay\r\n pig(a, 2)\r\n elsif(a[0..2].match(/sch|.qu/)) #school = oolschay, square = aresquay\r\n pig(a, 3)\r\n else\r\n x = a.index(/[AaEeIiOoUu]/) #starts with other consonant(s) or a vowel; find the first vowel\r\n if(!(x.nil?)) #found at least one vowel\r\n pig(a, x) \r\n else #x is nil, no vowels found\r\n a.index(/[[:alpha:]]/) ? pig(a, 1) : a #if it contains letters, attempt to process; otherwise, do nothing\r\n end\r\n end\r\n end\r\n return words.join(\" \")\r\nend",
"def pig_latin_word(str)\n vowels = \"aeiou\"\n\n if vowels.include?(str[0])\n return str + \"yay\"\n else\n str.each_char.with_index do |char, index|\n if vowels.include?(char)\n return str[index..-1] + str[0...index] + \"ay\"\n end\n end\n end\nend",
"def pig_latin(str)\n new_str = str.downcase.scan(/\\w+/)\n output = []\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n new_str.each do |element|\n first = []\n last = []\n temp = element.split(\"\")\n temp.each_with_index do |letter, index|\n if vowels.include?(letter)\n last = temp[0...index]\n last.push(\"ay\");\n first = temp[index..-1]\n break\n end\n end\n output.push(first.join(\"\").concat(\"-\"+last.join(\"\")))\n end\n output.join(\" \")\nend",
"def pig_latin_word(string)\n array_of_char = string.downcase.split(//)\n\n if [\"a\",\"e\",\"i\",\"o\",\"u\",\"y\"].include?(array_of_char[0])\n array_of_char.push(\"ay\")\n elsif !([\"a\",\"e\",\"i\",\"o\",\"u\",\"y\"].include?(array_of_char[0]))\n consonant = array_of_char.delete_at(0)\n array_of_char.push(consonant, \"ay\")\n end\n\n return array_of_char.join\n\nend",
"def pig_latin_sentence_reverse(sentence)\n sentence.downcase!\n\n x = sentence.split\n\n t = \"t\"\n h = \"h\"\n q = \"q\"\n u = \"u\"\n\n # this removes the \"ay\"\n x.map do |word|\n word.slice!(\"way\")\n word.slice!(\"ay\")\n end\n\n # this removes the \"th\" and \"qu\" from the end of the words and add it to the front\n x.map do |word|\n last_letter = word[-1]\n if word.include?(t && h)\n word.insert(0, h)\n word.insert(0, t)\n word.chop!\n if last_letter == t || h\n word.chop!\n end\n end\n # else\n if word.include?(u && q)\n word.insert(0, u)\n word.insert(0, q)\n word.chop!\n if last_letter == u || q\n word.chop!\n end\n end\n end\n\n # this changes the selected elements\n [x[2], x[3], x[6], x[7]].map do |word|\n word.insert(0, word[-1])\n if word[0] == word[-1]\n word.chop!\n word == word[0..-2]\n end\n x[0].capitalize!\n end\n\n x.join(\" \")\nend",
"def pig_latin(string)\n # Your code goes here\n arr = string.split(\" \")\n\n pig_latin = []\n arr.map do |x|\n if arr.length == 1\n return x[0] + \"ay\"\n else\n \n word = x[1..-1] + x[0] + \"ay\"\n pig_latin.push(word)\n end\n \n end\n return pig_latin.join(\" \")\nend",
"def translate(phrase)\n #split phrase into words\n word_array = phrase.split ' '\n #to_pig each word\n answer_array = word_array.map {|word| to_pig(word)}\n #join words back together\n answer = answer_array.join ' '\nend",
"def pigLatin(sentence)\n\n #declare var to hold the split string\n splitSentence = sentence.split()\n #empty array to hold split strings\n result = \"\"\n #split the word into letters\n for word in splitSentence\n letters = word.split(//)\n first_letter = letters[0]\n letters.shift()\n letters.push(first_letter)\n letters.push(\"ay \")\n\n result += letters.join()\n\n end\n\n result.capitalize!.chop!()\n return result\nend",
"def pig_latin_sentence(string)\n array_of_word = string.split(\" \")\n new_array_of_word = []\n\n array_of_word.each do |word|\n new_array_of_word.push(pig_latin_word(word))\n end\n\n return new_array_of_word.join(\" \")\n\nend",
"def pig(word)\n letters = word.split(\"\")\n letters.keep_if {|letter| letter != \".\"}\n if letters.size == 1 || vowel?(letters[0])\n letters << \"way\"\n elsif letters.size > 1\n until vowel?(letters[0])\n letters << letters.shift\n end\n letters << \"ay\"\n end\n letters.join\n end",
"def pigatize(text)\n if starts_with_vowel?(text)\n text + \"way\"\n else\n text.chars.rotate.join + \"ay\"\n end\nend",
"def pig_latinize_string(text)\n a = text.split(' ')\n b= a.map {|word| pig_latinize_word(word)}\n b.join(' ')\n end",
"def pig_it(sentence)\n sentence.split.map do |word|\n if ('a'..'z').cover?(word.downcase)\n word[1..-1] + word[0] + 'ay'\n else\n word\n end\n end.join(' ')\nend",
"def to_pig_latin(text)\n\t\ttext.split(' ').map do |w|\n\t\t\tpiglatinize(w)\n\t\tend.join(' ')\n\tend",
"def convert (str)\r\n# REFERENCE : Using logic from this source https://stackoverflow.com/questions/13498688/pig-latin-method-translation\r\n alpha = ('a'..'z').to_a\r\n vowels = %w[a e i o u]\r\n consonants = alpha - vowels\r\n lstr = str.downcase\r\n if vowels.include?(lstr[0])\r\n str + 'way'\r\n elsif consonants.include?(lstr[0]) && consonants.include?(lstr[1]) && consonants.include?(lstr[2])\r\n str[3..-1] + str[0..2] + 'ay'\r\n elsif consonants.include?(lstr[0]) && consonants.include?(lstr[1])\r\n str[2..-1] + str[0..1] + 'ay'\r\n elsif consonants.include?(lstr[0])\r\n str[1..-1] + str[0] + 'ay'\r\n else\r\n str # return unchanged\r\n end\r\nend",
"def pig_it(string)\n words = string.split\n\n words.map do |word|\n if word.match(/[a-z]/i)\n word[1..word.size] << word[0] << 'ay'\n else\n word\n end\n end.join(' ')\nend",
"def translate(str)\n words = str.split\n pig_words = []\n words.each do |word|\n pig_words << latinize(word)\n end\n\n pig_words.join(\" \")\nend",
"def pig_it(str)\n \twords_from_sentence = str.split\n \twords_from_sentence.map! do |word|\n \t\tif word.length == 1\n \t\t\tif word.match? (/[^\\w]/)\n \t\t\t\tword\n \t\t\telse\n \t\t\t\tword << 'ay'\n \t\t\tend\n \t\telsif word[-1].match? (/[^\\w]/)\n \t\t\tlast_letter = word.slice!(-1)\n \t\t\tword << word.slice!(0) << 'ay' << last_letter\n \t\telse\n \t\t\tword << word.slice!(0) << 'ay'\n \t\tend\n \tend\n \twords_from_sentence.join(' ')\nend",
"def pig_it(str)\n words = str.split\n pigified = []\n words.each do |word|\n if word =~ /\\w/\n word += \"#{word.chr}ay\"\n word[0] = ''\n pigified << word\n else pigified << word\n end\n end\n pigified.join(' ')\nend",
"def pig_latin_chop(word)\n\t#split single word into characters\n\n\twordArray = word.split(\"\") \n\tvowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n\tuntil vowels.include?(wordArray[0])==true\n\t\tconsonant = wordArray.shift().downcase\n\t\twordArray = wordArray.push(consonant)\n\tend\n\tnewWord = wordArray.join()+ \"ay\"\nend",
"def pig_it text\n text.split(' ').map do |word|\n if word == \"?\" || word == \"!\" || word == \".\" || word == \",\"\n word\n else\n (word[1..(word.length-1)] + word[0] + \"ay\")\n end\n end.join(' ')\nend",
"def pig_it text\n answer = text.split(' ')\n answer.each_with_index do |str, index|\n if (!str.match(/[-!$%^&*()_+|~=`{}\\[\\]:\";'<>?,.\\/]/))\n firstLetter = str[0]\n str[0] = str[0].delete(str[0])\n answer[index] = str.concat(firstLetter) + \"ay\"\n end\n end \n answer.join(' ')\nend",
"def pig_it(string)\n arr = string.split(\" \")\n result = \"\"\n arr.each do |word|\n # Check if word is containing only letters and not special characters\n if word.match? /\\A[a-zA-Z']*\\z/\n result += (word[1..-1] + word[0] + \"ay \")\n else\n result += (word + \" \")\n end\n end\n result[0...-1]\nend",
"def pig_latin_txt(string)\n arr=[]\n arr = string.split.map!{|x| pig_latin(x)}\n arr.join(' ')\nend",
"def pig_it(str)\r\n str.split.map { |w| w =~ /[a-z]/i ? w[1..-1] + w[0] + 'ay' : w }.join(' ')\r\nend",
"def pig_latin_translate\n english_word_arr = []\n vowel_array = %w(a e i o u)\n \n print \"What word would you like to translate? \"\n input = gets.chomp!.downcase\n \n english_word_to_translate = input.split(/ /)\n \n english_word_to_translate.each do |word|\n english_word_arr = word.split(//)\n\n\n\n #split by words\n #split by character\n #Take first letter move to end\n #add 'Ay'\n #join and return word\n end\nend",
"def pig_it(string)\n string2 = string.split.map{|e|e == '!' || e == '?' ? e : e.to_s << (e[0]) }.join(' ')\n\n string3 = string2.split.map{|e|e == '!' || e == '?' ? e : e.to_s << 'ay'}.join(' ')\n\n string3.split.map{|e| e == '!' || e == '?' ? e : e = e[1..-1]}.join(' ')\nend",
"def pig_latin_name(word)\n \n letters = word.split(\"\")\n \n final_array = letters.clone\n letters.each do |letter| #[p, l, u, m]\n \n \n if is_consonants?(letter)\n final_array.rotate! \n # #puts \".........#{removed_consonant}\"\n # #letters.push(removed_consonant)\n # puts \".........#{final_array}..#{letters}\"\n else \n # puts \"*****#{final_array}.... #{letters}\"\n final_array.push(\"ay\")\n return final_array.join\n end\n end\nend",
"def translate\n words\n words_array = []\n pig_latin_words_array = []\n @words_array.each do |word|\n if starts_with_vowel?(word)\n word += 'way'\n elsif !starts_with_vowel?(word[1..-1])\n word = word[2..-1] + word[0] + word[1] + 'ay'\n else\n word = word[1..-1] + word[0] + 'ay'\n end\n pig_latin_words_array << word\n end\n return pig_latin_words_array\n end",
"def pig_it text\n arr = []\n text.split.map do |x|\n split_word = x.split('')\n unless /[[:punct:]]/.match(x)\n first_letter = split_word.first\n split_word.shift\n split_word << \"#{first_letter + 'ay'}\"\n end\n arr << split_word.join\n end\n arr.join(' ')\nend",
"def translate(string)\n newArr = []\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n \n # * Split it into words\n words = string.split()\n\n # * For every word in the sentence...\n words.each do |word|\n # * If the word has 'qu'\n if word[1..2].downcase == \"qu\"\n newArr << word[3..-1] + word[0..2] + \"ay\"\n\n elsif word[0..1].downcase == \"qu\"\n newArr << word[2..-1] + word[0..1] + \"ay\"\n\n # * If it starts with a vowel\n elsif vowels.include?(word[0].downcase)\n newArr << word + \"ay\"\n\n # * If the first three consonants aren't vowels\n elsif not vowels.include?(word[0].downcase) and not vowels.include?(word[1]) and not vowels.include?(word[2])\n newArr << word[3..-1] + word[0..2] + \"ay\" \n # * ...or if the first two consonants aren't vowels\n elsif not vowels.include?(word[0].downcase) and not vowels.include?(word[1])\n newArr << word[2..-1] + word[0..1] + \"ay\" \n \n # * After all that, if it starts with one consonant\n else\n newArr << word[1..-1] + word[0] + \"ay\"\n end\n end\n\n newArr.join(\" \")\nend",
"def translate word\n\n\tsplit = word.split(\" \")\n\tlatin = \"\"\n\tvowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n\t\n\n\n\tsplit.each do |string|\n\n\t\ta = 0\n\t\tconsts = 0\n\n\t\twhile vowels.include?(string[a]) === false\n\t\t\tconsts = consts + 1\n\t\t\ta = a + 1\n\t\tend\n\n\t\tif string[consts -1] === \"q\"\n\t\t\tif string[consts] === \"u\"\n\t\t\t\tconsts = consts + 1\n\t\t\tend\n\t\tend\n\n\t\tb = string[0, consts]\n\n\t\t\n\t\tif consts === 1\n\t\t\tlatin = latin + string[consts, string.length-1] + string[0] + \"ay\"\n\t\telsif\tconsts > 1\n\t\t\tlatin = latin + string[consts, string.length-1] + b + \"ay\"\n\t\telse\n\t\t\tlatin = latin + string + \"ay\"\n\t\tend\n\n\tlatin = latin + \" \"\n\n\tend\n\n\tlatin.strip\n\t\nend",
"def translate string\n\n\t#This splits the string into an array of words\n\twords = string.split(\" \")\n\t\n\t#Goes through each word in array words\n\tfor i in 0...words.length\n\n\t\t#This splits each word into an array of characters\n\t\tcharacters = words[i].chars\n\n\t\t#If a word begins with a vowel, add \"ay\" to the end of the word\n\t\tif isVowel characters[0]\n\n\t\t\tcharacters.push(\"a\", \"y\")\n\t\t\twords[i] = characters.join(\"\")\n\n\t\t#If a word does not begin with a vowel...\n\t\telse\n\n\t\t\t#While the first character is not a vowel, move it to the back of the word\n\t\t\twhile !(isVowel characters[0])\n\n\t\t\t\t#If the first character is a \"q,\"\n\t\t\t\tif characters[0] == \"q\"\n\n\t\t\t\t\t#and the next character is a \"u,\" push both the \"qu\" to the end\n\t\t\t\t\tif characters[1] == \"u\"\n\n\t\t\t\t\t\tconsonant = characters.shift\n\t\t\t\t\t\tcharacters.push(consonant)\n\t\t\t\t\t\tu = characters.shift\n\t\t\t\t\t\tcharacters.push(u)\n\n\t\t\t\t\tend\n\n\t\t\t\t#Otherwise, just push the first letter to the end\n\t\t\t\telse\n\n\t\t\t\t\tconsonant = characters.shift\n\t\t\t\t\tcharacters.push(consonant)\n\n\t\t\t\tend\n\n\t\t\tend\n\n\t\t\t#Then add \"ay\" to the end of the word\n\t\t\tcharacters.push(\"a\", \"y\")\n\t\t\twords[i] = characters.join(\"\")\n\n\t\tend\n\t\t\n\tend\n\n\t#Joins together all the words with a space in between them and returns the modified string as an answer\n\tanswer = words.join(\" \")\n\treturn answer\n\nend",
"def translate(str)\n\tvowel=%w[a e i o u]\n\tcons=[*'a'..'z']-vowel\n\n\ta_str=str.split(\" \")\n\n\tfor i in 0..a_str.length-1\n\t\tif vowel.include?a_str[i][0]\n\t\t\tpig_l = a_str[i] + \"ay\"\n\t\t\treturn pig_l.split(\",\").join(\"\")\n\t\telsif cons.include?a_str[i][0]\n\t\t\tif cons.include?a_str[i][1]\n\t\t\t\tz=a_str[i].slice!(0..1)\n\t\t\telse\n\t\t\t\tz=a_str[i].slice!(0)\n\t\t\tend\n\t\t\tpig_l=a_str[i] + z+ \"ay\"\n\t\t\treturn pig_l.split(\",\").join(\"\")\n\t\tend\n\tend\nend",
"def english_translate\n pig_latin_arr = []\n pig_latin = []\n print \"What word would you like to translate? \"\n input = gets.chomp!.downcase\n \n pig_latin_word_to_translate = input.split(/ /)\n\n pig_latin_word_to_translate.each do |word|\n pig_latin_arr = word.split(//)\n\n first_letter = pig_latin_word_to_translate.delete_at(0)\n new_letters = english_word_to_translate.join\n\n word = new_letters + first_letter + \"ay\"\n\n pig_latin << word\n end\n \n puts pig_latin.join(' ').capitalize\nend",
"def translate( word )\n #Practicing regular expressions. Main idea: If I can find the first vowel then take the index\n #where that vowel is and split the word. If word has no vowels or first letter is a vowel,\n #just put word in new_word variable.\n\n phrase = \"\"\n\n word.split.each do | word |\n\n #If first letter is a vowel or no vowels in the word, just give the word\n if ( /[aeiou]/ =~ word ) == 0 || ( /[aeiou]/ =~ word ) == nil\n new_word = word\n\n #If my word starts with a qu then we'll split the word with the qu together\n elsif word[ 0..1 ] == \"qu\"\n new_word = word[ 2..word.length ] + word[ 0..1 ]\n\n #Keeping below if I wanna find a word that has a vowel \n #if word.split.any? { |letter| /[aeiou]/ =~ letter }\n\n #If my word starts with an squ then we'll split this word with the squ together\n elsif word[ 0..2 ] == \"squ\"\n new_word = word[ 3..word.length ] + word[ 0..2 ]\n\n else\n new_word = word[ ( /[aeiou]/ =~ word )..word.length ] + word[ 0..( ( /[aeiou]/ =~ word ) - 1 ) ]\n end\n\n #Add ay if vowel is at the front of the new word\n new_word += \"ay\" if new_word.split.any? { | letter | /[aeiou]/ =~ letter }\n\n #Adding the words together to form the output with space\n phrase += \"#{ new_word } \"\n\n end\n\n puts phrase\n phrase.strip\n\nend",
"def pig_latin_str=(str)\r\n @pig_latin_str = str.split.map(&:to_s) # split the input to words arrays\r\n end",
"def pig_consonant\n pig_latin = @word\n\nend",
"def translate(word)\n split_words = word.split(' ')\n words = []\n vowels = %w[a e i o u]\n split_words.each do |word|\n word = qu_in_word(word)\n if vowels.include?(word[0])\n words.push(word + 'ay')\n else\n count = 0\n word.length.times do |number|\n vowels.include?(word[number]) ? break : count += 1\n end\n words.push(word[count..-1] + word[0..(count - 1)] + 'ay')\n end\n end\n words.join(' ')\nend",
"def translate(sentence)\n #we .split that sentence. Because we do not give a limit, the sentence is automaticly split along the spaces.\n #we .map the result of the .split to make every word in the array a variable= word.\n sentence.split.map do |word|\n #We define what the first vowel of the word is by a different method (first_vowel) and assign it as variable v\n v = first_vowel(word)\n # we slice of the first vowel and the letter preceding that. then we add the first letter of the word at the end, and add +ay\n word.slice(v..-1) + word[0,v] + \"ay\"\n #We end the function and join the retunring array with spaces in between.\n end.join(\" \")\n end",
"def translate(str)\n\n\n\n # Vowels to consider\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n \n # Special cases to consider\n two_letter_consonants = [\"ch\", \"sh\", \"qu\", \"th\", \"br\"]\n three_letter_consonants = [\"thr\", \"sch\", \"squ\"]\n\n words = str.split(\" \")\n result = []\n\n words.each do |word|\n if vowels.include?(word[0])\n result.push word << \"ay\"\n else \n if three_letter_consonants.include? (word[0] + word[1] + word[2])\n first_three_letters = word.slice!(0,3)\n \n # Add letters to end of word with 'ay'\n result.push word << first_three_letters << 'ay'\n elsif two_letter_consonants.include?(word[0] + word[1])\n first_two_letters = word.slice!(0,2)\n result.push word << first_two_letters << \"ay\"\n else \n first_letter = word.slice!(0)\n \n # Add first letter to end of word with 'ay'\n result.push word << first_letter << 'ay'\n end #End of special consonant check\n end \n end \n return result.join(\" \")\nend",
"def pig_it_ms_two(str)\n pig = []\n str.split.each do |w|\n pig << w.chars.rotate.join + \"ay\" if w =~ /\\w/\n pig << w if w =~ /\\W/\n end\n pig.join(\" \")\nend",
"def translate (sentence)\n\ttranslated = ''\n\twords = sentence.split(' ')\n\twords.each { |word|\n\t\tfound_vowels = word.scan(/^[aeiou]*/)\n\t\tfound_consonants = word.scan(/^[bcdfghjklmnpqrstvxzwy]*/)\n\t\tif !found_vowels[0].empty?\n\t\t\ttranslated << word << 'ay'\n\t\telsif !found_consonants[0].empty?\n\t\t\tword = word.tr(found_consonants[0], '')\n\t\t\ttranslated << word << found_consonants[0] << 'ay'\n\t\tend\n\t\tif words.length > 1\n\t\t\ttranslated << ' '\n\t\tend\n\t}\n\treturn translated.rstrip\nend"
] |
[
"0.8841267",
"0.87730575",
"0.867668",
"0.8656043",
"0.8618591",
"0.8613246",
"0.8606145",
"0.85803676",
"0.85799867",
"0.8579038",
"0.85786974",
"0.8566909",
"0.856355",
"0.8539216",
"0.8521281",
"0.84993243",
"0.84407496",
"0.8440136",
"0.8426666",
"0.8412286",
"0.8398716",
"0.8386795",
"0.8380882",
"0.83708334",
"0.83652127",
"0.8356386",
"0.83492297",
"0.8329493",
"0.8304657",
"0.82919663",
"0.82751846",
"0.8266383",
"0.82604384",
"0.8241824",
"0.82396394",
"0.8238167",
"0.823328",
"0.8229906",
"0.82288677",
"0.822492",
"0.82245064",
"0.82004863",
"0.8200009",
"0.81831485",
"0.81734866",
"0.8165184",
"0.8152321",
"0.8149299",
"0.8136318",
"0.81210846",
"0.81188315",
"0.8112504",
"0.8100839",
"0.80997944",
"0.80657524",
"0.8044816",
"0.80426574",
"0.8022503",
"0.8015499",
"0.7996872",
"0.79813856",
"0.796762",
"0.7942388",
"0.78854156",
"0.7877452",
"0.7828266",
"0.7768346",
"0.77451324",
"0.76969224",
"0.7694942",
"0.76067644",
"0.7597386",
"0.75914246",
"0.75887483",
"0.75573325",
"0.7544719",
"0.74955475",
"0.74196357",
"0.7417285",
"0.735384",
"0.73274577",
"0.7281285",
"0.7277977",
"0.72314245",
"0.7220537",
"0.72150946",
"0.71651673",
"0.71155614",
"0.7112818",
"0.71071124",
"0.70757496",
"0.7055341",
"0.70203334",
"0.7018367",
"0.69040906",
"0.6823686",
"0.6788778",
"0.67771304",
"0.67473096",
"0.67072666"
] |
0.84793234
|
16
|
It is sometimes necessary to be able to break down a number into its prime factors. The process is called prime factorization. We can use a factor tree to determine the prime factorization of a number: 12 / \ / \ 4 3 / \ 2 2 Define a method `prime_factorization(n)` that breaks a number down into it's prime factors. example: prime_factorization(12) => [2,2,3]
|
def prime_factorization(num)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def prime_factorization(num)\n if is_prime?(num)\n return [num]\n end\n factors = []\n (2..num).each do |factor|\n if num % factor == 0\n factors << factor\n factors << prime_factorization(num/factor)\n \n break\n end\n end\n factors.flatten\n\nend",
"def prime_factorization(num)\n return [] if num < 2\n\n # get all primes up to num recursively\n primes_factors = prime_factorization(num - 1)\n if prime?(num)\n primes_factors << num\n end\n\n primes_factors\nend",
"def prime_factorization(num)\n return [num] if is_prime?(num)\n\n prime_factors = []\n prime_factors << first_factor(num)\n next_num = num / first_factor(num)\n prime_factors << prime_factorization(next_num)\n prime_factors.flatten\nend",
"def prime_factorization(num)\n # Base case - 1 is not a prime so we return an empty array here\n return [] if num == 1\n \n # initialize i to 2, since it is the first prime #\n i = 2\n \n # increment i until we find a prime factor\n i += 1 until is_prime?(i) && num % i == 0 \n \n # Add i to prime factors and make recursive call to find rest\n [i] + prime_factorization(num / i)\nend",
"def prime_factorization(num)\n return [num] if is_prime?(num)\n prime_fact = []\n (2..num).each do |n|\n return [n] + prime_factorization(num / n) if num % n == 0\n end\n prime_fact\n end",
"def prime_factors(number)\n return [] if number < 2\n return [number] if number < 4\n factors = []\n\n factor = 2\n while factor < number\n break if number % factor == 0\n factor += 1\n end\n factors << factor\n factors.concat(prime_factors(number / factor))\n factors.sort\nend",
"def prime_factors(number)\n return [] if number < 2\n return [number] if number < 4\n factors = []\n\n factor = 2\n while factor < number\n break if number % factor == 0\n factor += 1\n end\n factors << factor\n factors.concat(prime_factors(number / factor))\n factors.sort\nend",
"def prime_factorization(num)\n if is_prime(num)\n return [num]\n else\n n = 2\n while (num % n) != 0\n n += 1\n end\n return [n] + prime_factorization(num / n)\n end\nend",
"def prime_factorization(num)\n return [num] if prime?(num)\n\n #otherwise break up into two factors, \n #and call prime_factorization on them both\n (2..num/2).each do |n| \n if num % n == 0\n return prime_factorization(n) + prime_factorization(num/n) \n end\n end\nend",
"def prime_factorization(n)\n return [n] if is_prime?(n)\n\n # factors(n).each do |factor|\n # return [prime_factorization(factor), prime_factorization(n/factor)].flatten\n # end\n factor = factors(n)[0]\n prime_factorization(factor) + prime_factorization(n/factor)\n \n \nend",
"def prime_factors(number)\n factors = []\n i = 0\n if prime?(number)\n return [number]\n else\n new_prime = @primes[-1] + 2\n while @primes[-1] * 2 <= number\n if prime?(new_prime)\n @primes << new_prime\n end\n new_prime += 2\n end\n while @primes[i] <= Math.sqrt(number)\n if number % @primes[i] == 0\n factors << @primes[i]\n number /= @primes[i]\n i = 0\n else\n i += 1\n end\n end\n factors << number\n end\n return factors\nend",
"def prime_factors(n)\n return [] if n == 1\n factor = (2..n).find {|x| n % x == 0}\n [factor] + prime_factors(n / factor)\nend",
"def prime_factorization(num)\n return [num] if prime?(num)\n [2,3,5].each do |factor|\n if num % factor == 0\n return [factor] + prime_factorization(num / factor)\n end\n end\nend",
"def prime_factors(number)\n primes = []\n return primes unless number >= 1\n return primes << number if is_prime?(number)\n # until is_prime?(number) do\n (2..(number / 2)).to_a.each do |num|\n if number % num == 0 # Divisor\n if is_prime?(num)\n primes << num\n number /= num\n return (primes << prime_factors(number)).flatten\n # break\n end\n end\n end\n # end\n # primes << number\nend",
"def factorize(test_number)\n return [] if test_number == 1\n prime_factor = (2..test_number).find {|divisor| test_number % divisor == 0}\n [prime_factor] + factorize(test_number / prime_factor)\nend",
"def prime_factorization(num)\n # return [num] if prime?(num)\n # first_prime = find_prime_factor(num)\n # return [first_prime] + prime_factorization(num/first_prime)\n (2...(num/2)).each do |n|\n if num % n == 0\n multiplier = num / n\n return prime_factorization(n) + prime_factorization(multiplier)\n end\n end\n [num]\nend",
"def prime_factors(number)\n fs = []\n f1 = factor(number)\n return [number] if f1 == 1\n f2 = number/f1\n fs.concat(prime_factors(f1))\n fs.concat(prime_factors(f2))\n return fs\n end",
"def prime_factors(num)\n factors = factors(num)\n result = []\n factors.each do |fac|\n if prime?(fac)\n result << fac\n end\n end\n result\nend",
"def prime_factors\n n = self\n factors = Hash.new(0)\n\n # Pull out twos manually\n while n % 2 == 0 do\n factors[2] += 1\n n /= 2\n end\n\n # Then use Fermat's method\n a = Math.sqrt(n).ceil\n b2 = a**2 - n\n until (b2**0.5).round**2 == b2 do\n a += 1\n b2 = a**2 - n\n end\n\n candidates = [(a - Math.sqrt(b2)).round, (a + Math.sqrt(b2)).round]\n candidates.each do |candidate|\n next if candidate == 1\n if candidate == n\n factors[n] += 1\n else\n candidate_factors = candidate.prime_factors\n if candidate_factors.length == 1\n factors[candidate_factors.first] += 1\n else\n candidates.concat candidate_factors\n end\n end\n end\n \n expanded = []\n factors.each do |prime, count|\n count.times { expanded << prime }\n end\n expanded.sort\n end",
"def factors(num)\n factors = Prime.prime_division(num)\n result = []\n factors.each { |factor, power| result += [factor] * power }\n result\nend",
"def prime_factorization(num)\n return [num] if is_prime?(num)\n\n (2..num).each do |fact|\n if num % fact == 0\n prime_factorization(fact)\n other_fact = num / fact\n prime_factorization(other_fact)\n end\n end\n\nend",
"def prime_factorization(num)\n (2...num).each do |fact|\n if (num % fact == 0)\n otherFact = num / fact\n return [ *prime_factorization(fact), *prime_factorization(otherFact) ]\n end\n end\n\n [num]\nend",
"def prime_factors(num)\n facs = factors(num)\n p_facs = []\n facs.each{|n| p_facs.push(n) if prime?(n)}\n p_facs\nend",
"def prime_factorization(num)\n\n return [num] if prime?(num)\n\n (2...num).each do |divisor|\n if num % divisor == 0\n next_factor = num / divisor\n return [divisor, *prime_factorization(next_factor)]\n end\n end\n\nend",
"def prime_factorization(num)\n\n (2...num).each do |factor|\n if num % factor == 0\n divisor = num / factor\n return prime_factorization(factor) + prime_factorization(divisor)\n end\n end\n [num]\nend",
"def prime_factors( n )\nend",
"def prime_factorization(num)\n return [num] if prime?(num)\n (2...num).each do |i|\n if prime?(i) && num % i == 0\n return [i].concat(prime_factorization(num / i))\n end\n end\nend",
"def prime_factorization(num)\n (2...num).each do |fact|\n if num % fact == 0\n other_fact = num / fact\n return [ *prime_factorization(fact), *prime_factorization(other_fact) ]\n end\n end\n [ num ]\nend",
"def prime_factors(num)\n\n if prime?(num)\n return [num]\n end\n\n primes = (2...num).to_a.select { |factor| prime?(factor) }\n\n \n \n factors = []\n\n while num > 1\n candidate = primes.shift\n\n if num % candidate == 0\n factors << candidate\n while num % candidate == 0\n num /= candidate\n end\n end\n end\n\n return factors\n \nend",
"def prime_factorization(num)\n (2...num).each do |fact|\n if num % fact == 0\n other_fact = num / fact\n return [*prime_factorization(fact), *prime_factorization(other_fact)]\n end\n end\n [num]\nend",
"def prime_factor(num)\n i = 2\n factors = []\n while i <= num\n if num % i == 0\n factors << i\n num = num / i\n else\n i += 1\n end\n end\n factors\nend",
"def prime_factorisation(n)\n Prime.prime_division(n).flat_map { |factor, power| [factor] * power }\n end",
"def factors(num)\n pn = num.prime_division\n ans = []\n pn.each_index do |i|\n ans << pn[i][0]\n end\n return ans\nend",
"def prime_factorization(num)\n (2...num).each do |fact|\n if num % fact == 0 \n fact_2 = num / fact\n return [ *prime_factorization(fact), *prime_factorization(fact_2) ]\n end\n end\n\n [ num ]\nend",
"def prime_factorization(num)\n (2...num).each do |factor|\n if num % factor == 0\n other = num / factor\n return prime_factorization(factor).concat(prime_factorization(other))\n end\n end\n\n [num]\nend",
"def all_factorizations(num)\n Prime.prime_division(num)\nend",
"def factor(n)\n return [] if n.zero?\n Prime.prime_division n\n end",
"def findPrimeFactorsofaNumber(number)\n listofprimefactors = []\n possiblePrime = 2\n while number > 1 \n if number % possiblePrime == 0\n number /= possiblePrime\n listofprimefactors.push possiblePrime\n elsif possiblePrime < 3\n possiblePrime += 1\n else\n possiblePrime += 2\n end\n end\n return listofprimefactors\n end",
"def prime_factorization(num)\n primes = [] \n i = 2 \n while num != 1\n while num % i == 0\n if is_prime?(i) \n num = num / i \n primes << i \n else\n i += 1 \n end \n end\n i += 1 \n end\n primes\nend",
"def prime_factorization(num)\nend",
"def prime_factors_helper(f, n)\n if f > n\n []\n elsif is_prime(f) && n % f == 0\n [f] + prime_factors_helper(f, n / f)\n else\n prime_factors_helper(f == 2 ? f + 1 : f + 2, n)\n end\nend",
"def prime_factors(num)\n arr = factors(num)\n new_arr = []\n arr.each do |n|\n new_arr << n if prime?(n)\n end\n new_arr\nend",
"def factors(num)\n factors = Prime.prime_division(num)\n result = []\n factors.each { |factor, power| result += [factor] * power }\n result\n end",
"def prime_factors(n)\n factors = []\n d = 2\n while n > 1\n while n % d == 0\n factors << d\n n /= d\n end\n d = d + 1\n if d*d > n\n if n > 1\n factors << n\n break\n end\n end\n end\n return factors\nend",
"def prime_factorization(n)\n (2...n).each do |num|\n if n % num == 0\n othernum = n / num\n return [*prime_factorization(num),*prime_factorization(othernum)]\n end\n end\n [n]\nend",
"def prime_factors num\n\tfactors = []\n\ttest_value = 2\n\twhile num > 1 do\n\t\twhile num % test_value == 0 do\n\t\t\tfactors.push num\n\t\t\tnum = num / test_value\n\t\tend\n\t\ttest_value += 1\n\tend\n\treturn factors\nend",
"def prime_factorization(num)\n (2...num).each do |fact|\n if num % fact == 0\n other_fact = num/fact\n return [*prime_factorization(fact),*prime_factorization(other_fact)]\n end\n end\n\n return [num]\nend",
"def prime_factorization(num)\n\n (2...num).each do |i|\n if num % i == 0\n i2 = num / i\n return [*prime_factorization(i), *prime_factorization(i2)]\n end \n end\n [num]\nend",
"def factors(number)\n divisors = []\n # 1 is always a divisor\n divisors << 1\n if number > 1\n # target number is also always a divisor\n divisors << number\n # start looking for other divisors from 2 on up.\n i = 2\n while (i <= Math.sqrt(number).to_i)\n # if number is evenly divisible by i, then retain i, and possibly also\n # the division of number/i.\n if (number % i == 0)\n divisors << i\n divisors << number/i if (i != number/i)\n end\n i += 1\n end\n divisors.sort!\n end\n divisors\nend",
"def prime_factors(num)\n require \"prime\"\n primes = []\n Prime.each{|prime| primes << prime if num % prime ==0 ; break if prime > num }\n primes\nend",
"def prime_factors(num)\n factors(num).select {|n| prime?(n)}\nend",
"def factors(number)\r\n divisor = number\r\n factors = []\r\n while divisor > 0 do \r\n factors << number / divisor if number % divisor == 0\r\n divisor -= 1\r\n end \r\n factors\r\nend",
"def prime_factors(number, array=[])\n 2.upto(number) do |factor|\n if number % factor == 0\n array << factor\n number /= factor\n prime_factors(number, array)\n break\n end\n end\n array\nend",
"def find_factors(number)\n\t# start with lowest prime number\n\tinteger = 2\n\n\t# make sure integer doesn't exceed the actual number\n\twhile integer <= number do\n\t\t# integer will be returned when if it is a factor of number\n\t\treturn integer if number % integer == 0\n\n\t\t# if integer is not a factor move to next integer\n\t\tinteger += 1\n\tend\nend",
"def prime_factors(num)\n factors(num).select { |factor| prime?(factor) }\nend",
"def prime_factors(number, array = [])\n return if number == 1\n 2.upto(number).each do |num|\n if number % num == 0\n number /= num\n array << num\n else\n end\n end\n prime_factors(number, array)\nend",
"def prime_factors(n)\n factors = []\n old_n = n\n @primes.each { |prime|\n if @factors_hash[n]\n factors += @factors_hash[n]\n factors.uniq!\n break\n end\n if n % prime == 0\n factors.push(prime)\n n /= prime\n end\n break if prime >= n\n # If the remainder is a prime, add and break\n if @prime_hash[n]\n factors.push(n)\n break\n end\n }\n @factors_hash[old_n] = factors\n return factors\nend",
"def factors(number)\n divisor = number\n factors = []\n #begin\n\twhile divisor > 0\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n #end until divisor == 1\n\tend\n factors\nend",
"def prime_factors(num)\r\n # your code goes here\r\n prime_factors = []\r\n for i in 1 .. num\r\n if num % i == 0 && prime?(i)\r\n prime_factors << i\r\n end\r\n end\r\n prime_factors\r\nend",
"def prime_factors(n)\n\tfps = []\n\t# check for even\n\tif n % 2 == 0\n\t\tfps.push(2)\n\t\tn = div_factor(n, 2)\n\tend\n\t# check odd factors\n\tfact = 3\n\tmaxFact = Math.sqrt(n)\n\twhile n > 1 && fact < maxFact\n\t\tif n % fact == 0\n\t\t\tfps.push(fact)\n\t\t\tn = div_factor(n, fact)\n\t\t\tmaxFact = Math.sqrt(n)\n\t\tend\n\t\tfact = fact + 2\n\tend\n\tif n > fps.last\n\t\tfps.push(n)\n\tend\n\tfps.sort!\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def prime_factors(num)\n\tfactors = []\n\tfactor = 2\n\tremainder = num\n\n\twhile (remainder > 1) && (factor <= num)\n\t\twhile (remainder % factor == 0)\n\t\t\tfactors << factor\n\t\t\tremainder /= factor\n\t\tend\n\n\t\tfactor += 1\n\tend\n\tfactors\nend",
"def prime_factors(number)\n divisors = []\n divisor = 2\n\n while number > 1\n if number % divisor == 0\n number /= divisor\n divisors << divisor\n else\n divisor += 1\n end\n end\n\n divisors.uniq\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(num)\n prime?(num) ? [1, num].uniq : [*1..num].select { |i| num % i == 0}\nend",
"def prime_factors(num)\n\tfactors(num).select { |n| prime?(n) }\nend",
"def prime_factors\n if prime?\n [self]\n else\n pair = factorize\n (pair[0].prime_factors + pair[1].prime_factors).sort.uniq\n end\n end",
"def factors_of(number)\n\t\tprimes, powers = number.prime_division.transpose\n\t\texponents = powers.map{|i| (0..i).to_a}\n\t\tdivisors = exponents.shift.product(*exponents).map do |powers|\n\t\t\tprimes.zip(powers).map{|prime, power| prime ** power}.inject(:*)\n\t\tend\n\t\tdivisors.sort.map{|div| [div, number / div]}\n\tend",
"def factors(number)\n divisor = number\n factors = []\n loop do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n break if divisor == 0\n end\n factors\n \nend",
"def old_factors(num)\n factors = []\n (1..num).each do |i|\n if num % i == 0\n factors << i\n end\n end\n factors\nend",
"def prime_factors(n)\n factors = []\n divisor = 2\n\n while n > 1\n if (n % divisor).zero?\n power = 0\n n /= divisor while (n % divisor).zero? && (power += 1)\n factors << \"(#{divisor}#{power > 1 ? \"**#{power}\" : ''})\"\n end\n divisor += 1\n end\n\n factors.join\nend",
"def factors(number)\n fs = [1,number]\n (2..Math.sqrt(number).to_i).each do |i|\n if number % i == 0\n fs << i\n fs << number/i unless number/i == i\n end\n end\n fs.sort\n end",
"def factors(num)\n factors = []\n (1..num/2).each {|n| factors << n if num % n == 0}\n factors << num\nend",
"def prime_factors(num)\n factors = []\n # Store all the factors in an array\n (2..num).each do |divisor|\n if num % divisor == 0\n factors << divisor\n end\n end\n\n # loop through factors array and return only the prime prime prime factors\n if factors.length > 0\n return factors.select { |factor| checkIfPrime(factor) }\n else\n return factors\n end\nend",
"def factors(number)\n divisor = number\n factors = []\n loop do\n break if divisor <= 0\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def find_prime_factors(numb)\n\tfactors = []\n\n\twhile numb > 1\n\t\ttest_num = 2\n\t\twhile true\n\t\t\tif is_factor?(numb,test_num)\n\t\t\t\tfactors << test_num\n\t\t\t\tbreak\n\t\t\tend\n\t\t\ttest_num += 1\n\t\tend\n\t\tnumb = numb/test_num\n\tend\n\n\treturn factors\nend",
"def prime_factorization_to_factors(factorization)\n\tif factorization.empty?\n\t\t[1]\n\telse\n\t\tprime_factor, multiplicity = factorization[0]\n\t\tfactors = prime_factorization_to_factors(factorization.drop(1))\n\t\tmultiplicity_array = Array.new(multiplicity + 1) { |i| prime_factor ** i }\n\t\tfactors.map { |factor| multiplicity_array.map { |multiple| multiple * factor } }.flatten\n\tend\nend",
"def factors(number)\n divisor = number\n factors = []\n begin\n # evaluate statement on right side of shovel operator and if\n # divisor evenly divides number then add into factors array \n factors << number / divisor if number % divisor == 0\n # decrement divisor by 1\n divisor -= 1\n # stops when divisor is 0\n end until divisor == 0\n \n # return all factors in an array that divides evenly with \n # the number passed in as an argument when calling the function\n factors\nend",
"def find_factors!\n (1..number).each do |n|\n break if @factors.include?(n)\n if number % n == 0\n @factors << n << (number / n)\n end\n end\n # handle any perfect squares\n\n @factors.uniq!\n end",
"def factors(number)\n divisor = number\n factors = []\n loop do\n if number == 0 || number < 0\n break\n else factors << number / divisor if number % divisor == 0\n divisor -= 1\n break if divisor == 0\n end\n end\n factors\n end",
"def prime_factor(n)\n factors = []\n p = 2\n\n\n while (p < n)\n\n return factors if ( factors.inject(:*).to_i >= n )\n\n if ( n % p == 0 )\n factors.push(p)\n end\n\n p += 1\n\n end\n\n\n return factors\nend",
"def factors(number)\n divisor = number\n factors = []\n loop do\n break if number <= 0\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n break if divisor == 0\n end \n factors\nend",
"def factors( n )\n p = Primer.ld( n )\n return n if p == n\n factors n.div( p )\nend",
"def find_factors(number)\n factors =[]\n for i in 1..number\n factors << i if number % i == 0\n end\n factors\nend",
"def prime_factors(num)\n prime_facts = []\n\n (1..num).each do |i|\n if num % i == 0 && prime?(i)\n prime_facts << i\n end\n end\n\n return prime_facts\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0\n factors << (number / divisor) if ((number % divisor) == 0)\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n dividend = 1\n divisors = []\n while dividend <= number\n divisors << dividend if number % dividend == 0\n dividend += 1\n end\n divisors\nend",
"def factors(num)\r\n factors = []\r\n sqrt = Math.sqrt(num)\r\n until num == 1\r\n\r\n factor_founded = false\r\n (2..sqrt).each do |i|\r\n if (num % i).zero?\r\n num /= i\r\n factors << i\r\n factor_founded = true\r\n break\r\n end\r\n end\r\n unless factor_founded\r\n factors << num\r\n num /= num\r\n end\r\n end\r\n return factors\r\nend",
"def find_factors(num)\n raise ArgumentError, \"num must be >= 0\" if num < 0\n return [n] if num <= 1\n result = []\n\n n = num\n if n.even?\n while n % 2 == 0\n result << 2\n n /= 2\n end\n end\n\n div = 3\n\n while (n > 1)\n while n % div == 0\n result << div\n n /= div\n end\n div += 2\n\n if (div * div > n)\n result << n\n break\n end\n end\n\n result\nend",
"def prime_factors_mult( n )\nend",
"def factors_of(num)\n factors = []\n \n i = 1\n while i <= num\n # if num is divided by i\n if num % i == 0\n factors << i\n end\n \n i += 1\n end\n \n return factors\n end",
"def prime_factors(n)\r\n num=Math.sqrt(n).round\r\n while num>0\r\n if n%num==0\r\n return num if prime?(num)\r\n end\r\n num-=1\r\n end\r\nend",
"def prime_factors(num)\n array = []\n (1..num).each do |number|\n array << number if prime?(number) && num % number == 0\n end\n array.sort!\nend"
] |
[
"0.8428887",
"0.82478887",
"0.8245271",
"0.8202063",
"0.81589955",
"0.81140804",
"0.81140804",
"0.81003475",
"0.80887234",
"0.80355823",
"0.8033517",
"0.80309725",
"0.80170643",
"0.7986394",
"0.7977813",
"0.7956462",
"0.79532456",
"0.79420835",
"0.79312116",
"0.7917168",
"0.790988",
"0.78837687",
"0.78791904",
"0.7871747",
"0.786847",
"0.7865806",
"0.7854556",
"0.78481776",
"0.7841444",
"0.78336406",
"0.78155965",
"0.78101",
"0.7802438",
"0.7790872",
"0.7788855",
"0.7772408",
"0.7762846",
"0.77446675",
"0.774393",
"0.7721916",
"0.7716746",
"0.7713309",
"0.7703966",
"0.7703407",
"0.77003044",
"0.76960003",
"0.76931036",
"0.769274",
"0.7690056",
"0.76526606",
"0.76447207",
"0.76436365",
"0.7628282",
"0.7627214",
"0.7623782",
"0.76172084",
"0.7614686",
"0.75990117",
"0.75931466",
"0.7579361",
"0.7577541",
"0.7577541",
"0.7577541",
"0.7577541",
"0.7577541",
"0.7577541",
"0.7577397",
"0.7575356",
"0.7565452",
"0.7560111",
"0.75516725",
"0.754878",
"0.75307685",
"0.7526319",
"0.7522296",
"0.75145084",
"0.7510467",
"0.75052494",
"0.74994516",
"0.7497986",
"0.74978113",
"0.7492252",
"0.7488592",
"0.7486926",
"0.7483574",
"0.74799174",
"0.747841",
"0.74783933",
"0.74768424",
"0.74738693",
"0.7462943",
"0.7452317",
"0.7449211",
"0.7449077",
"0.74434775",
"0.74376816",
"0.74372023",
"0.7434298"
] |
0.76571995
|
51
|
You are not required to implement this; it's here as a suggestion :)
|
def bubble_sort!(&prc)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def private; end",
"def probers; end",
"def custom; end",
"def custom; end",
"def specie; end",
"def specie; end",
"def specie; end",
"def specie; end",
"def anchored; end",
"def implementation; end",
"def implementation; end",
"def who_we_are\r\n end",
"def schubert; end",
"def internal; end",
"def intensifier; end",
"def formation; end",
"def isolated; end",
"def isolated; end",
"def extra; end",
"def original; end",
"def suivre; end",
"def same; end",
"def identify; end",
"def specialty; end",
"def overrides; end",
"def terpene; end",
"def weber; end",
"def ignores; end",
"def wrapper; end",
"def escaper; end",
"def as_you_like_it_quote; end",
"def macro; raise NotImplementedError; end",
"def macro; raise NotImplementedError; end",
"def macro; raise NotImplementedError; end",
"def overload; end",
"def offences_by; end",
"def used?; end",
"def implemented_in; end",
"def extended(*) end",
"def operations; end",
"def operations; end",
"def missing; end",
"def silly_adjective; end",
"def internal?; end",
"def expanded; end",
"def tiny; end",
"def celebration; end",
"def jack_handey; end",
"def final; end",
"def placebo?; false end",
"def refutal()\n end",
"def abstract?; end",
"def from; end",
"def from; end",
"def from; end",
"def from; end",
"def escaper=(_); end",
"def abstract!; end",
"def strategy; end",
"def returns; end",
"def loc; end",
"def loc; end",
"def loc; end",
"def original_result; end",
"def verdi; end",
"def internship_passed; end",
"def position; end",
"def position; end",
"def position; end",
"def position; end",
"def position; end",
"def position; end",
"def position; end",
"def position; end",
"def plain; end",
"def missing?; end",
"def required_positionals; end",
"def under_construction\n end",
"def pos; end",
"def pos; end",
"def pos; end",
"def pos; end",
"def pos; end",
"def pos; end",
"def villian; end",
"def origin; end",
"def origin; end",
"def origin; end",
"def trd; end",
"def isolated?; end",
"def isolated?; end",
"def code_of_conduct; end",
"def buzzword; end",
"def buzzword; end",
"def alt; end",
"def stderrs; end",
"def generic?; true; end",
"def explicit; end",
"def informational?; end",
"def public_method; end",
"def virtual; end"
] |
[
"0.7553544",
"0.6552228",
"0.6468686",
"0.6468686",
"0.6329687",
"0.6329687",
"0.6329687",
"0.6329687",
"0.6240793",
"0.62360597",
"0.62360597",
"0.6225513",
"0.6177131",
"0.6068755",
"0.60113126",
"0.59909743",
"0.59866005",
"0.59866005",
"0.5981032",
"0.5937013",
"0.5912015",
"0.59012103",
"0.5890042",
"0.5877088",
"0.5872261",
"0.58611554",
"0.58412397",
"0.57918996",
"0.5769689",
"0.5763334",
"0.57577765",
"0.57529145",
"0.57529145",
"0.57529145",
"0.5751227",
"0.5739019",
"0.57101685",
"0.5673916",
"0.5662733",
"0.5657311",
"0.5657311",
"0.5652275",
"0.564936",
"0.564721",
"0.56368005",
"0.56351924",
"0.56177354",
"0.5612311",
"0.5604098",
"0.55893016",
"0.5587457",
"0.55836314",
"0.55757374",
"0.55757374",
"0.55757374",
"0.55757374",
"0.55697864",
"0.55537164",
"0.5549931",
"0.5542717",
"0.55403507",
"0.55403507",
"0.55403507",
"0.5527882",
"0.55249506",
"0.55241454",
"0.5521253",
"0.5521253",
"0.5521253",
"0.5521253",
"0.5521253",
"0.5521253",
"0.5521253",
"0.5521253",
"0.5518786",
"0.55164236",
"0.5508646",
"0.55034703",
"0.55031884",
"0.55031884",
"0.55031884",
"0.55031884",
"0.55031884",
"0.55031884",
"0.5495477",
"0.54927623",
"0.54927623",
"0.54927623",
"0.54926",
"0.54915255",
"0.54915255",
"0.5482353",
"0.548095",
"0.548095",
"0.54762316",
"0.547281",
"0.5464949",
"0.5459907",
"0.542921",
"0.54250544",
"0.5418944"
] |
0.0
|
-1
|
Write a method that takes a string and an alphabet. It returns a copy of the string with the letters reordered according to their positions in the alphabet. If no alphabet is passed in, it defaults to normal alphabetical order (az). Do NOT use `Arraysort` or `Arraysort_by`. Example: `jumble_sort("hello")` => "ehllo" `jumble_sort("hello", ['o', 'l', 'h', 'e'])` => 'ollhe'
|
def jumble_sort(str, alphabet = nil)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def jumble_sort(str, alphabet = nil)\n alphabet ||= (\"a\"..\"z\").to_a\n\n new_string = str.split(\"\").sort do |letter_a, letter_b|\n alphabet.find_index(letter_a) <=> alphabet.find_index(letter_b)\n end\n new_string.join\nend",
"def jumble_sort(str, alphabet = nil)\n return str.split(\"\").sort.join if alphabet.nil?\n #not done yet\nend",
"def jumble_sort(str, alphabet = nil)\n alphabet ||= ('a'..'z').to_a\n sorted = \"\"\n alphabet.each do |c1|\n str.chars.each do |c2|\n sorted << c2 if c2 == c1\n end\n end\n sorted\nend",
"def jumble_sort(str, alphabet = (\"a\"..\"z\").to_a)\n str_arr = []\n temp = []\n str.chars.each do |char1|\n if str_arr.empty?\n str_arr << char1\n temp << char1\n else\n temp.each_index do |i|\n if alphabet.index(str_arr[i]) < alphabet.index(char1)\n str_arr << char1\n else\n str_arr.insert(i,char1)\n end\n end\n end\n end\n str_arr.join(\"\")\nend",
"def jumble_sort(str, alphabet = nil)\n return str.chars.sort.join(\"\") if alphabet.nil?\n new_string = \"\"\n alphabet.each do |letter|\n (str.count(letter)).times do\n new_string += letter\n end\n end\n new_string\nend",
"def jumble_sort(str, alphabet = nil)\n return str.split(//).sort.join if alphabet.nil?\n\n str.split(//).sort_by { |x| alphabet.index(x) }.join\nend",
"def jumble_sort(str, alphabet = nil)\n arr = str.split('')\n if alphabet.nil?\n arr.sort.join\n else\n arr.sort{|i, j| alphabet.index(i) <=> alphabet.index(j)}.join\n end\n\nend",
"def jumble_sort(str, alphabet = nil)\n alphabet = ('a'..'z').to_a\n\n sorted = false\n while sorted\n sorted = true\n\n str.length.times do |i|\n break if i <= (str.length)\n if alphabet.index(str[i]) > alphabet.index(str[i + 1])\n str[i], str[i + 1] = str[i + 1], str[i]\n sorted = false\n end\n end\n end\n\n str\nend",
"def jumble_sort(str, alphabet = nil)\n alphabet ||= ('a'..'z').to_a\n\n sorted = false\n until sorted\n sorted = true\n (0...str.length - 1).to_a.each do |i|\n if alphabet.index(str[i]) > alphabet.index(str[i + 1])\n str[i], str[i + 1] = str[i + 1], str[i]\n sorted = false\n end\n end\n end\n str\nend",
"def jumble_sort(str, alphabet = nil)\n alphabet ||= ('a'..'z').to_a\n #access each letter\n #call both letters and switch if the letters if the index of first is higher than the index of the second\n\n letters = str.split('')\n i = 0\n while i < letters.length\n j = i + 1\n while j < letters.length\n if alphabet.index(letters[i]) > alphabet.index(letters[j])\n letters[i], letters[j] = letters[j], letters[i]\n end\n j += 1\n end\n i += 1\n end\n\n letters.join('')\nend",
"def jumble_sort(str, alphabet = nil)\n alphabet ||= ('a'..'z').to_a\n arr = str.chars\n sorting = true\n while sorting\n sorting = false\n\n arr.each_with_index do |el, i|\n next if i == (arr.length - 1)\n if alphabet.index(el) > alphabet.index(arr[i+1])\n arr[i], arr[i + 1] = arr[i +1], arr[i]\n sorting = true\n end\n end\n\n end\n arr.join\nend",
"def jumble_sort(str, alphabet = nil)\n alphabet ||= ('a'..'z').to_a\n final_str = \"\"\n \n alphabet.each do |alpha_char|\n if str.include?(alpha_char)\n str.count(alpha_char).times do\n final_str += alpha_char\n end\n end\n end\n \n final_str\nend",
"def jumble_sort(str, alphabet = (\"a\"..\"z\"))\n char_count = Hash.new(0)\n str.each_char { |c| char_count[c] += 1 }\n jumbled_str = \"\"\n alphabet.each do |c|\n (0...char_count[c]).each { |n| jumbled_str << c }\n end\n jumbled_str\nend",
"def jumble_sort(str, alphabet = nil)\n return str.chars.sort.join if alphabet == nil\n\n arr = []\n cur_len = 0\n alphabet.each do |c|\n break if cur_len >= str.length\n\n if str.include?(c)\n num = str.count(c)\n arr.push(c * num)\n cur_len += num\n end\n end\n\n arr.join\nend",
"def alphabetized(string)\n string.delete(\"^A-Za-z\").chars.sort_by { |char| char.downcase}.join\nend",
"def alphabetize(arr, rev = false)\n arr.sort!\nend",
"def sort_letters(string)\n string.downcase.split('').sort.join('')\n end",
"def alphabetize(arr, rev = false)\nend",
"def alphabetized(str)\n alphabet = ('a'..'z').to_a + ('A'..'Z').to_a\n\n str.chars.delete_if { |char| alphabet.include?(char) == false }\n .sort_by { |letter| letter.downcase }.join('')\nend",
"def alphabet_soup(str)\n str.split('').sort.join\nend",
"def alphabetic(s)\n # pass\n s == s.split('').sort.join('')\nend",
"def letters_sorted(word)\n word.split(\"\").sort\nend",
"def alphabet_soup(str)\n p str.split(\"\").sort.join\nend",
"def alphabetize(arr, rev=false)\n arr.sort!\n if rev\n arr.reverse!\n else\n arr\n end\nend",
"def alphabetize(arr, rev = false)\n arr.sort!\n arr.reverse! if rev == true\nend",
"def alphabetize(arr, rev=false)\n if rev == false\n arr.reverse! #this method doesn't default to alphabetizing an array when\n #it doesn't receive a second parameter.\n else\n arr.sort!\n end\nend",
"def alphabetize(arr, rev=false)\n if rev\n arr.sort { |item1, item2| item2 <=> item1 }\n else\n arr.sort { |item1, item2| item1 <=> item2 }\n end\nend",
"def alphabetize(arr, rev=false)\n if rev\n arr.sort { |item1, item2| item2 <=> item1 }\n else\n arr.sort { |item1, item2| item1 <=> item2 }\n end\nend",
"def alphabetize(arr, rev=false)\n if rev\n arr.sort! {|first, second| second <=> first }\n else\n arr.sort! {|first, second| first <=> second }\n end\n return arr\nend",
"def alphabetize(arr, rev = false)\n arr.sort!\n if rev == true\n arr.reverse!\n else\n \tarr\n end\nend",
"def alphabetize(arr, rev = false)\n arr.sort!\n if rev == true\n arr.reverse!\n else\n \tarr\n end\nend",
"def alphabetize(array)\n esp=\"abcĉdefgĝhĥijĵklmnoprsŝtuŭvz\" #esperanto alphabet\n ascii = \"@-\\\\\" #\"@-\\\\\" = \"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\\"\n array.sort_by{|string| string.tr(esp, ascii)}\nend",
"def alphabetize!\n sort! { |a, b| grouped_compare(a, b) }\n end",
"def AlphabetSoup(str)\n str.chars.sort.to_s\nend",
"def AlphabetSoup(str)\n str.chars.sort.to_s\nend",
"def alphabetize(arr, rev = false)\n arr.sort!\n if rev == true\n arr.reverse\n else\n return arr\n\tend\nend",
"def alphabetize(arr)\n arr.sort_by do |word|\n word.chars.map { |letter| ESPERANTO_ALPHABET.index(letter) }\n end\nend",
"def alphabeticShift(inputString)\n alpha = (\"a\"..\"z\").to_a + [\"a\"]\n array = inputString.split(\"\")\n \n for i in 0..(array.count-1)\n array[i] = alpha[alpha.index(array[i])+1]\n end\n array.join(\"\")\nend",
"def alpha_sort(phrase)\n char_count = Hash.new(0)\n\n phrase.split(\"\").each { |char| char_count[char]+=1 }\n\n single_chars = char_count.keys\n single_chars.delete(\" \")\n\n idx = 0\n sort_done = false\n num_of_sorts = single_chars.length - 2\n\n \n until sort_done\n changes = 0\n 0.upto(num_of_sorts) do |i|\n if single_chars[i] > single_chars[i+1]\n single_chars[i], single_chars[i+1] = single_chars[i+1], single_chars[i]\n changes += 1\n end\n end\n sort_done = true if changes == 0\n end\n\n single_chars.join\nend",
"def AlphabetSoup(str)\n\t# splits str into an array of the characters making up str, sorts that arr, and then converts it to a single string\n\tstr.chars.sort.join('')\nend",
"def alphabetize(arr)\n esperanto_alphabet = \"abcĉdefgĝhĥijĵklmnoprsŝtuŭvz\"\n arr.sort_by do |phrase|\n phrase.chars.map do |char|\n esperanto_alphabet.index(char)\n end\n end\nend",
"def calculate_alphabet(str)\nend",
"def alphabetize1(arr, rev=false)\n if rev!=false\n arr.sort! do |a, b|\n b <=> a # REVERSE ALPHABETICAL ORDER\n end\n else\n arr.sort! do |a, b|\n a <=> b\n end\n end\nend",
"def alphabetize(arr, rev=false)\n\tif rev\n\t\tarr.sort { |item1, item2| item2 <=> item1 }\n\telse\n\t\tarr.sort { |item1, item2| item1 <=> item2 }\n\tend\nend",
"def AlphabetSoup(str)\n str = str.split(\"\")\n str.sort!\n return str.join\nend",
"def alphabetize (arr, rev=false)\n if rev==true\n arr.reverse!\n#{|firstItem, secondItem| secondItem <=> firstItem}\n else\n rev==false\n arr.sort!\n end\n end",
"def alphabetized(s)\n s.scan(/[a-z]/i).sort_by(&:downcase).join\nend",
"def AlphabetSoup(str)\n str.split(\"\").sort.join\nend",
"def alphabetize(arr, rev = false)\n arr.sort!\n \n if rev == true\n arr.reverse!\n else\n arr\n end\n return arr\n end",
"def alphabetized(str)\n array = str.chars\n array.delete_if { |x| x =~ /[\\W_]/ }\n array.sort { |a,b| a.downcase <=> b.downcase }.join\nend",
"def alphabetic(s)\n s.chars.sort.join == s\nend",
"def alphabetSoup(str)\n\treturn str.split('').sort().join('')\nend",
"def alphabetize(arr)\n\nesperanto_ALPHABET = \"abcĉdefgĝhĥijĵklmnoprsŝtuŭvz\"\n\n arr.sort_by do |sentence|\n sentence.chars.collect do |letter|\n # binding.pry\n esperanto_ALPHABET.index(letter)\n # binding.pry \n\n end\n end\n\nend",
"def alphabetic_number_sort(numbers)\n numbers.sort_by { |number| NUMBERS[number] }\nend",
"def ordered_letters\n @word.chars.sort.join\n end",
"def dealphabetize(\n alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n )\n str = to_s\n alphabet = alphabet.to_s\n len = alphabet.length\n str.chars.inject(0) do |num, char|\n i = alphabet.index(char)\n raise(\"Character not in alphabet: '#{char}'\") if i.nil?\n\n num * len + i\n end\n end",
"def letter_swap(str)\n\tcount = 0\n\tnew_str = \"\"\n\twhile count < str.length\n\t\tstr_to_int = (str[count].ord + 1)\n\t\tif str_to_int > 122\n\t\t\tstr_to_int = 97\n\t\tend\n\t\tnew_str += str_to_int.chr\n\t\tcount+=1\n\tend\n\treturn new_str\nend",
"def reverse_ordered_letters\n ordered_letters.reverse\n end",
"def check_input_vs_alphabet(string_array)\n braille_translated = []\n string_array.each do |letter|\n if letter == letter.upcase && letter != letter.downcase\n braille_translated << alpha.trans_braille[:shift]\n braille_translated << alpha.trans_braille[letter.downcase]\n else\n braille_translated << alpha.trans_braille[letter]\n end\n end\n sort_out(braille_translated)\n end",
"def alphabetize(arr, rev=false) # Default value will be false for SECOND\n # parameter if ONLY ONE argument is passed\n arr.sort!\n if rev!=false # Executes line below if TWO arguments are passed (passing TWO\n # arguments will sort the array in DESCENDING order).\n arr.reverse!\n else # Executes line below if ONE argument is passed (passing ONE argument\n # will sort the array in ASCENDING order)\n arr.sort!\n end\nend",
"def alphabetize\n\nend",
"def letter_reverse str\n str.reverse!\nend",
"def sort(word)\n\t# Downcase and converting string into array\n\tword = word.downcase().split(\"\")\n\tlen = word.length\n\n\t# Initializing loop variables\n\ti = 0\n\tj = 0\n\ttemp = 0\n\n\t# Sort the array\n\twhile i < len - 1\n\t\tj = i + 1\n\t\twhile j < len\n\t\t\tif word[i] > word[j]\n\t\t\t\t#swap characters in ascending order\n\t\t\t\ttemp = word[i]\n\t\t\t\tword[i] = word[j]\n\t\t\t\tword[j] = temp\n\t\t\tend\n\t\t\tj += 1\n\t\tend\n\t\ti += 1\n\tend\n\treturn word\nend",
"def letter_hash s\n s.each_char.to_a.sort.join('')\nend",
"def char_sorted(str) str.split('').sort.join end",
"def AlphabetSoup(str)\n\tstr = str.split(\"\").sort.join(\"\")\n\treturn str\n\nend",
"def sort3(strings, length)\n (length - 1).downto(0) do |i|\n buckets = Array.new(26) { [] }\n strings.each do |string|\n letter = string[i]\n buckets[letter.ord - \"a\".ord] << string\n end\n\n strings = []\n buckets.each do |bucket|\n bucket.each { |string| strings << string }\n end\n end\n\n strings\nend",
"def alphabet_sort(array)\n alphabet = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \n \t\"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]\n counter = 1\n until counter == 100\n\n \tnew_array = array.each do |letter|\n \t\n \t\ti = 1\n \t index_of_letter_in_array = array.index(letter)\n \t index_of_next_letter_in_array = index_of_letter_in_array + i \n \t value_of_next_item_in_array = array[index_of_next_letter_in_array]\n \t \n \t until i == array[index_of_letter_in_array..-1].length\n \t \t\t if \talphabet.index(letter) > alphabet.index(value_of_next_item_in_array)\n\t\n \t \t\t\t\tarray[index_of_letter_in_array], array[index_of_next_letter_in_array] =\n \t \t\t\t\t array[index_of_next_letter_in_array], array[index_of_letter_in_array]\n \t \t\t\tend #if\n \t \t\t\t\n \t \t\t\ti += 1 \n \t \tindex_of_next_letter_in_array = index_of_letter_in_array + i \n \t \tvalue_of_next_item_in_array = array[index_of_next_letter_in_array]\n \t \tend #until\n \t \t\n \tend #do\n\n counter += 1\n\tend #until\n\tp new_array\n\nend",
"def reverse_only_letters(s)\n letters = []\n alphabet = (\"a\"..\"z\").to_a\n \n s.each_char do |char|\n letters << char if alphabet.include?(char.downcase)\n end\n \n s.each_char.with_index do |char, idx|\n s[idx] = letters.pop if alphabet.include?(char.downcase)\n end\n s\nend",
"def my_array_sorting_method(source)\n source.sort { |a,b| a.to_s <=> b.to_s } # sort string within array alphabetically\nend",
"def alphabet\n 'abcdefghijklmnopqrstuvwxyz'\n end",
"def do_sorting\n char_list_length = char_list.length\n\n loop do\n swapped = false\n (char_list_length - 1).times do | i |\n if char_list[i] > char_list[i+1]\n char_list[i], char_list[i+1] = char_list[i+1], char_list[i]\n num_list[i], num_list[i+1] = num_list[i+1], num_list[i]\n\n swapped = true\n end\n end\n break if not swapped\n end\n end",
"def encrypt_letter alphabet, cipherbet, letter\n# default for things not found in alphabet is to just return as\n encrypted_letter = letter\n # look for letter using method from above, -1 means not found\n pos = get_position_in_list alphabet, letter\n if pos == -1\n return encrypted_letter\n else\n encrypted_letter = cipherbet[pos]\n if is_lowercase(letter) == true\n encrypted_letter = encrypted_letter.downcase\n end\n return encrypted_letter\n end\nend",
"def generate_alphabet\n (\"a\"..\"z\").to_a\nend",
"def alphabet\n ('a'..'z').to_a\n end",
"def depunctuate(a_string)\n alphabet = [*\"A\"..\"Z\"] + [*\"a\"..\"z\"]\n result = \"\"\n a_string.length.times do |i|\n if alphabet.include?(a_string[i])\n result << a_string[i]\n end\n end\n result\nend",
"def sortme(str)\n str.sort_by { |word| word.downcase }\nend",
"def letter_changes(str)\n str.each_char.with_index do |char, idx|\n if char =~ /[A-Za-z]/\n if char =~ /[Zz]/\n str[idx] = 'a'\n else\n str[idx] = (char.ord + 1).chr\n end\n end\n end\n str.each_char.with_index do |char, idx|\n str[idx] = char.upcase if char =~ /[aeiou]/\n end\n str\nend",
"def sorts(s)\n s = s.chars.sort.join\nend",
"def sortme(names)\n names.sort\nend",
"def alphabetic_number_sort2 num_arr\n num_arr.sort {|a, b| WORDS_ARR[a] <=> WORDS_ARR[b]}\nend",
"def encrypt(password)\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n index = 0\n while index < password.length\n letter = password[index]\n position = alphabet.index(letter) #magic\n\n if password[index] == \"z\"\n password[index] = \"a\"\n else\n password[index] = alphabet[position].next!\n end\n\n index += 1\n end\n return password\nend",
"def swap_letters(word)\n word[0], word[-1] = word[-1], word[0]\n word\nend",
"def letter_to_place(str)\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n arr = []\n str.each_char {|letter| arr << alphabet.index(letter) + 1}\n arr\nend",
"def string_sort(str_arr)\n (str_arr.first.length - 1).downto(0) do |d|\n str_arr = merge_sort(str_arr, d)\n end\n str_arr\nend",
"def my_array_sorting_method(source)\n sourceDup = source.dup\n # p sourceDup.sort_by{|word| word.to_s}\n\n return sourceDup.sort_by{|word| word.to_s}\nend",
"def alphabetic_number_sort2(nums)\n nums.sort { |num1, num2| ENGLISH_NUMBERS[num1] <=> ENGLISH_NUMBERS[num2] }\nend",
"def sortme( names )\n names.sort\nend",
"def sortme( names )\n names.sort\nend",
"def sortme( names )\n names.sort\nend",
"def scramble_words(words)\n first_word = words[0]\n last_word = words[-1]\n alphabetically = words[1, (words.size - 2)].chars.sort\n alphabetically.unshift(first_word).push(last_word).join\nend",
"def swap_letters(word)\n\n\tword[0], word[-1] = word[-1], word[0]\n\tword\n\t\nend",
"def alphabetic_number_sort(arr)\n arr.sort { |a, b| INT_NAMES[a] <=> INT_NAMES[b] }\nend",
"def reverse_letter(letter)\r\n alphabet = (\"a\"..\"z\").to_a\r\n index = alphabet.index(letter) \r\n alphabet[index-1]\r\nend",
"def letter_changes(string)\n array = (\"a\"..\"z\").to_a\n\n result_array = string.chars.map do |char|\n case\n when char.downcase == \"x\" then char == \"x\" ? \"a\" : \"A\"\n when char.downcase == \"y\" then char == \"y\" ? \"b\" : \"B\"\n when char.downcase == \"z\" then char == \"z\" ? \"c\" : \"C\"\n when char.match(/[a-z]/) then array[array.index(char.downcase) + 3]\n when char.match(/[A-Z]/) then array[array.index(char.downcase) + 3].upcase\n else char\n end\n end\n result_array.join\nend",
"def alphabetic_number_sort(numbers)\n result = []\n sorted_numbers = []\n\n numbers.each { |num| sorted_numbers << num}\n sorted_numbers.sort.each { |number| result << NUMBERS[number] }\n result\nend",
"def alphabet\n ('A'..'Z').to_a\n end",
"def alphabet\n ('A'..'Z').to_a\n end"
] |
[
"0.82605445",
"0.8129675",
"0.79923725",
"0.79903567",
"0.7891827",
"0.7886857",
"0.7872977",
"0.78611183",
"0.7830589",
"0.77589554",
"0.76950973",
"0.75813735",
"0.7578386",
"0.7437177",
"0.70201355",
"0.6944216",
"0.6866046",
"0.6866045",
"0.68637824",
"0.6863201",
"0.6724297",
"0.6585089",
"0.6584519",
"0.651759",
"0.6516811",
"0.64764124",
"0.6437627",
"0.6437627",
"0.64120275",
"0.64113975",
"0.64113975",
"0.6409372",
"0.6398548",
"0.6393995",
"0.6393995",
"0.63569665",
"0.6348509",
"0.6348168",
"0.6334537",
"0.6325383",
"0.63053066",
"0.62931454",
"0.62608564",
"0.6260088",
"0.62504923",
"0.62410474",
"0.62230545",
"0.6221803",
"0.6217361",
"0.6216428",
"0.61902666",
"0.6167452",
"0.61495155",
"0.61318445",
"0.61101687",
"0.6093333",
"0.6072532",
"0.6036092",
"0.5959637",
"0.59328735",
"0.593092",
"0.59278566",
"0.5907279",
"0.58881634",
"0.5884832",
"0.5859642",
"0.5852784",
"0.5840463",
"0.5799233",
"0.5790343",
"0.5787756",
"0.5780238",
"0.5777726",
"0.5771609",
"0.5765872",
"0.5763427",
"0.57492787",
"0.5742597",
"0.5735648",
"0.57194996",
"0.5711196",
"0.57110924",
"0.5708638",
"0.5694727",
"0.5690257",
"0.56873876",
"0.5685258",
"0.5680694",
"0.5667033",
"0.5667033",
"0.5664075",
"0.5656785",
"0.56561786",
"0.5654117",
"0.56488895",
"0.56476253",
"0.5645427",
"0.5645427"
] |
0.8202616
|
3
|
Define a method `rec_sum(nums)` that returns the sum of all elements in an array recursively
|
def rec_sum(nums)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def sum(nums)\n return 0 if nums.empty?\n nums[0] + sum_rec(nums[1..-1])\nend",
"def sum_rec(nums)\n return 0 if nums.empty?\n nums[0] + sum_rec(nums[1..-1])\nend",
"def sum_rec(nums)\n return 0 if nums.empty?\n nums[0] + sum_rec(nums.drop(1))\nend",
"def sum_rec(nums)\n return 0 if nums.length == 0\n sum_rec(nums[0...-1]) + nums[-1]\nend",
"def recursive_sum(nums)\n return 0 if nums.empty?\n\n return nums.pop + recursive_sum(nums)\nend",
"def rec_sum(nums)\n return 0 if nums.empty?\n \n nums[0] + rec_sum(nums.drop(1))\nend",
"def sum_array_rec(array_to_sum)\n if(array_to_sum.length > 0)\n sum = array_to_sum[0]\n sum += sum_array_rec(array_to_sum[1..-1])\n else\n 0\n end\nend",
"def sum_rec(num_array)\n return 0 if num_array.empty?\n\n num[0] + sum_rec(num_array.drop(1))\nend",
"def sum_rec(numbers)\n # base case\n return 0 if numbers.empty?\n # inductive step\n numbers[0] + sum_rec(numbers[1..-1])\nend",
"def sum_rec(numbers)\n return 0 if numbers.empty?\n num = numbers.pop\n num + sum_rec(numbers)\nend",
"def sum_rec(nums)\nreturn nums[0] if nums.size == 1\nreturn 0 if nums.size == 0\n nums[0] + sum_rec(nums[1..-1])\nend",
"def sum(nums)\n\treturn 0 if nums == []\n\tnums.reduce(:+)\nend",
"def sum_arr_rec(arr)\n return 0 if arr.length == 0\n return arr[0] if arr.length == 1\n arr[0] + sum_arr_rec(arr[1..-1])\nend",
"def sum_recur(array)\n #base case\n return 0 if array.empty?\n #iterative step\n array.first + sum_recur(array[1..-1])\nend",
"def sum_recur(array)\n return 0 if array.empty?\n array.pop + sum_recur(array)\nend",
"def sum_recursion(arr)\n return 0 if arr.empty?\n sum = arr.shift\n sum += sum_of_array(arr)\n # 2 + sum_of_array([3])\n #3 + sum_of_array([])\n\n\nend",
"def RecursiveSum(arrayofNumbers) \n \n # Base Case: If the array is empty, return 0. \n \n if arrayofNumbers? \n return 0\n \n # Recursive code: Adding each element to the variable by calling the method. \n \n else\n Sum = arrayofNumbers.pop \n return Sum + RecursiveSum(arrayofNumbers) \n end\nend",
"def sum_recur(array)\n return 0 if array.empty?\n array.first + sum_recur(array.drop(1))\nend",
"def sum_recur(array)\n return 0 if array.length <= 0\n array[0] + sum_recur(array[1..-1])\nend",
"def sum_recur(array)\n return 0 if array.empty?\n \n array[0] + sum_recur(array[1..-1])\nend",
"def sum_recur(array)\n return 0 if array.empty?\n array.first + sum_recur(array.drop(1))\nend",
"def recursive_sum(array)\n return array[0] if array.length == 1\n\n array[0] + recursive_sum(array[1..-1])\nend",
"def sum_recur(array)\n sum = 0\n if array.empty?\n 0\n else\n sum = array.first\n sum += sum_recur(array.drop(1))\n sum\n end\nend",
"def sum(nums)\n nums.reduce(&:+)\nend",
"def sum_rec(arr)\n return 0 if arr.empty?\n arr[0] += sum_rec(arr.drop(1))\nend",
"def sum_recur(array)\n#for array = []\n return 0 if array == []\n\n first_el = array.shift\n recursive_call = sum_recur(array)\n first_el + recursive_call\n\nend",
"def add_nums_iterative(arr)\n return nil if arr.length == 0\n total = 0\n arr.each do |num|\n total += num\n end\n total\nend",
"def recursive_sum(array)\n if array.length == 0\n return 0\n end\n recursive_sum(array[1..-1]) + array.first\nend",
"def iterative_sum(arr)\n total = 0\n arr.each {|num| total += num}\n return total\nend",
"def sum_recur(array)\n return 0 if array.empty?\n val = array.last\n val + sum_recur(array.take(array.length - 1))\nend",
"def add_numbers(nums_array)\n return nums_array.first if nums_array.length == 1 #=> base case if the array is length 1 then just return the first element\n return nil if nums_array.length < 1 #=> return nil if the array length is less than 1\n \n nums_array.pop + add_numbers(nums_array) #=> inductive/recursive case taking the sum of the array and #pop the the last ele each time\nend",
"def arr_sum(arr)\n return 0 if arr.empty?\n head = arr[0]\n tail = arr[1..-1]\n head.size + arr_sum(tail)\nend",
"def sum_recur(array)\n return 0 if array.empty?\n dup = array.dup\n return dup[0] if dup.length == 1\n sum = dup.pop + sum_recur(dup)\n\nend",
"def sum arr\n sum = arr.sum\n return sum\nend",
"def sum_recur(array)\n return array.first if array.length == 1\n array[0] + sum_recur(array[1..-1])\nend",
"def sum_rec(arr)\n return arr.first if arr.size <= 1\n arr.pop + sum_rec(arr)\nend",
"def sum arr\n sum = 0\n arr.each do |n|\n sum+= n\n end\n return sum\nend",
"def sum_array(numbers)\n return numbers.sum()\nend",
"def sum_recursive(num)\n # can also compute sum with symbol (1..5).inject(:+)\n (1..num).inject { |sum, n| sum + n }\nend",
"def add_numbers(num_array)\n return num_array[0] if num_array.length <= 1\n sum = num_array[0]\n sum += add_numbers(num_array[1..-1])\nend",
"def sum arr\n #this is slightly too easy...\n arr.sum\nend",
"def sum_recur(array)\n return array[0] if array.length == 1\n array[0] + sum_recur(array.drop(1))\nend",
"def sum_recur(array)\n return array[0] if array.length == 1\n array[0] + sum_recur(array.drop(1))\nend",
"def sum_recurse(num)\n return 0 if num == 0\n num[0] + sum_recurse(num.delete(1))\nend",
"def sum_recur(array)\n \n if array.empty?\n return 0\n elsif array.length == 1\n return array[0]\n end\n \n return sum_recur(array[0...-1]) + array[-1]\n \n\nend",
"def my_sum(arr)\n arr.inject(:+)\nend",
"def sum(nums)\n total = 0\n nums.each do |n|\n total+= n\n end\n return total\nend",
"def sum_array_recur(array)\n return nil if array.empty?\n return array[0] if array.length == 1\n\n array[0] + sum_array_recur(array[1..-1])\nend",
"def sum_of_sums(arr)\n sum = 0\n total = 0\n\n arr.each do |num|\n sum += num\n total += sum\n end\n total\nend",
"def sum_of_sums(arr)\n sum = 0\n total = 0\n\n arr.each do |num|\n sum += num\n total += sum\n end\n total\nend",
"def sum_of_sums(array)\r\nend",
"def arr_sum(array)\n sum = 0 # Declares initial value for variable 'sum' as 0\n array.each do |i| # Begin iterating each item of arr\n sum += i # add each number in array to the next item, continue until items exhausted\n end\n return sum # Returns new sum value\nend",
"def sum (arr)\n\treturn arr.inject(0, :+)\nend",
"def sum arr\n return 0 if arr.empty?\n arr.inject(:+)\nend",
"def array_sum(arr)\n return 0 if arr.empty?\n\n arr.reduce(&:+)\nend",
"def sum(arr)\n return 0 if arr.empty?\n el = arr.shift\n total = sum(arr)\n total + el\nend",
"def sum(array) \n if array == []\n 0\n else\n array[0] + sum(array[1..-1])\n end\nend",
"def iterative_sum(array)\n sum = 0\n array.each do |ele|\n sum += ele\n end\n sum\nend",
"def iterative_sum(array)\n sum = 0\n array.each do |ele|\n sum += ele\n end\n sum\nend",
"def sum(arr)\n arr.inject(:+)\nend",
"def sum(array)\n array.sum\nend",
"def sum(array_of_integers)\n # TODO\nend",
"def sum arr\n sum = 0\n arr.each do |i|\n sum = sum + i\n end\n return sum\nend",
"def sum_nums(num)\n (1..num).inject(&:+)\nend",
"def sum(arr)\n arr.reduce(0, :+)\nend",
"def add_numbers(nums_array)\n if nums_array.empty? \n 0\n else \n n = nums_array.pop\n return n + add_numbers(nums_array)\n end \nend",
"def add_nums(arr)\n return nil if arr.length == 0\n return arr[0] if arr.length == 1\n arr[0] + add_nums(arr[1..-1])\nend",
"def array_sum(arr)\n\n sum = 0\n arr.each {|n| sum += n}\n\n sum\nend",
"def sum_of_arr(arr)\n arr.inject(:+)\nend",
"def my_sum(array)\n sum = 0\n array.each do |num|\n sum += num\n end\n sum\nend",
"def sum_an_array(arr)\n p arr\n return 0 if arr.empty?\n return arr[0] if arr.length == 1\n # first = arr[0]\n # rest = sum_an_array(arr[1..-1])\n # total = first + rest\n left = arr[0...arr.length/2]\n right = arr[arr.length/2..-1]\n p left\n p right\n left_sum = sum_an_array(left)\n right_sum = sum_an_array(right)\n total = left_sum + right_sum\nend",
"def array_sum(arr)\n arr.reduce(:+)\nend",
"def array_sum(arr)\n arr.reduce(:+)\nend",
"def sum_array_iterative(arr)\n arr.inject(0) {|sum, el| sum + el}\nend",
"def sum_of_arr(arr)\n sum = 0\n arr.each do |i|\n sum = sum + i\n end\n sum\nend",
"def array_sum(arr)\n arr.reduce(:+)\n\nend",
"def sum arr\n sum = 0\n arr.each { |a| sum += a }\n return sum\nend",
"def sum(arr)\n return 0 if arr.empty?\n arr.reduce(:+)\nend",
"def sum(numbers)\n numbers.reduce(&:+)\n end",
"def sum arr\n rtn = 0\n arr.each { |n| rtn += n }\n return rtn\nend",
"def sum arr\n res = 0\n arr.each {|i| res+=i}\n return res\nend",
"def sum_array(array)\n array.sum\nend",
"def sum arr\n arr.reduce(0, :+)\nend",
"def sum arr\n arr.reduce(0, :+)\nend",
"def array_sum(arr)\n if arr.length == 0\n return 0\n end\n arr.reduce(:+)\nend",
"def sum(sums = Array[0])\n retVal = 0;\n sums.each do |i|\n retVal = (retVal + i.to_i);\n end\n retVal;\nend",
"def sum_array(array)\n array.sum\nend",
"def sum(arr)\n return 0 if arr.length.zero?\n\n arr.reduce(:+)\nend",
"def sum arr\n sum_array = 0 \n arr.each { |x| sum_array = sum_array + x } \n return sum_array\nend",
"def rec_sum(num)\n return num if num <= 1\n num + rec_sum(num - 1)\nend",
"def sum_numbers(root)\n return 0 if root.nil?\n nums = []\n inner_sum_numbers(root, 0, nums)\n nums.reduce(:+) #OR (&:+)\n#(5..10).reduce(:+) => 45\n# Same using a block and inject (5..10).inject { |sum, n| sum + n } => 45\n# Multiply some numbers(5..10).reduce(1, :*) => 151200\nend",
"def add_numbers(nums_array)\n return 0 if nums_array.length == 0\n\n first = nums_array.shift\n\n first + add_numbers(nums_array)\nend",
"def my_sum(array)\n return nil if array.length == 0\n\n sum = 0\n array.each do |elem|\n sum = sum + elem\n end\n sum\nend",
"def sum_of_sums(int_arr)\n sum = 0\n current_numbers = []\n int_arr.each { |int|\n current_numbers << int\n sum += current_numbers.sum\n }\n sum\nend",
"def array_sum(arr)\n return 0 if arr.empty?\n arr.reduce(:+)\nend",
"def array_sum(arr)\n return 0 if arr.empty?\n arr.reduce(:+)\nend",
"def sum_of_sums(arr)\n total_sum = 0\n dup_arr = arr.dup # make a copy to avoid mutating original array\n until dup_arr.empty?\n total_sum += dup_arr.reduce(:+)\n dup_arr.pop\n end\n total_sum\nend",
"def total(nums)\n sum = 0\n nums.each {|i| sum = (sum + i)}\nend",
"def arr_sum(arr)\r\n sum_arr = 0\r\n arr.each { |i| sum_arr+=i}\r\n sum_arr\r\nend"
] |
[
"0.83367825",
"0.82483006",
"0.8013581",
"0.79152244",
"0.79009026",
"0.78916806",
"0.782543",
"0.78227",
"0.78149915",
"0.77546424",
"0.769735",
"0.7678221",
"0.76095736",
"0.75948626",
"0.7591033",
"0.75586843",
"0.7542731",
"0.7514435",
"0.7514305",
"0.7504766",
"0.75002843",
"0.7491897",
"0.74723315",
"0.7465478",
"0.74412036",
"0.74364555",
"0.74283344",
"0.7413794",
"0.7384435",
"0.7341181",
"0.7314489",
"0.7268134",
"0.72517186",
"0.7230503",
"0.7207671",
"0.72001654",
"0.71985847",
"0.718353",
"0.718284",
"0.71631736",
"0.7156294",
"0.71467423",
"0.71467423",
"0.7141273",
"0.71350205",
"0.7134734",
"0.71267897",
"0.7122805",
"0.7118122",
"0.7118122",
"0.7109148",
"0.71048737",
"0.7103872",
"0.70945907",
"0.70920116",
"0.708668",
"0.70864725",
"0.70841944",
"0.70661306",
"0.7065291",
"0.70632666",
"0.70555764",
"0.7051562",
"0.7047408",
"0.70386386",
"0.7035732",
"0.70297605",
"0.7027923",
"0.7018233",
"0.70154256",
"0.7015359",
"0.7008496",
"0.7008496",
"0.70047814",
"0.6999012",
"0.69936866",
"0.6987105",
"0.69869834",
"0.6986571",
"0.69830745",
"0.698057",
"0.69787973",
"0.69715995",
"0.69711477",
"0.6969645",
"0.6961251",
"0.69603753",
"0.69548476",
"0.695363",
"0.69446373",
"0.6943698",
"0.6942091",
"0.69411093",
"0.6932603",
"0.69271386",
"0.69271386",
"0.69260013",
"0.69217926",
"0.69205475"
] |
0.83437324
|
1
|
Write a method that returns b^n recursively. Your solution should accept negative values for n.
|
def exponent(b, n)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def exponentiation(b, n)\n return 1 if n == 0\n\n return exponentiation(b, n - 1) * b\nend",
"def exponent(b, n)\n return 1 if n == 0\n if n > 0\n b * exponent(b, n - 1)\n else\n 1.0/b * exponent(b, n + 1)\n end\nend",
"def exponent(b, n)\n return 1 if n == 0\n if n > 0\n b * exponent(b, n - 1)\n else\n 1.0/b * exponent(b, n + 1)\n end\nend",
"def exponent(b, n)\n return 1 if n == 0\n\n if n > 0\n b * exponent(b, n - 1)\n else\n 1.0/b * exponent(b, n + 1)\n end\nend",
"def power(b, n)\n\n\t# b^n.to_i\n\n\tb ** n\n\nend",
"def my_pow(x, n)\n return x if n == 1\n return x * x if n == 2\n return x / x if n == -2\n\n if n > 0\n x * my_pow(x, n - 1)\n else\n my_pow(x, n + 1)\n end\nend",
"def exponentiation1(b,n)\n return 1 if n == 0 \n b * exponentiation1(b, n - 1)\nend",
"def exponentiation_1(b, n)\n return 1 if n == 0\n return b if n == 1\n b * exponentiation_1(b, n - 1)\nend",
"def exponent_v1(b, n)\n puts s += 1\n if n == 0\n return 1\n end\n b * exponent_v1(b, n-1)\nend",
"def exponent(b, n)\n return b if n == 1\n return 1 if n == 0\n if n >= 0\n exponent(b, n-1) * b\n else\n (1.0/b) * exponent(b, n+1)\n end\n end",
"def exponentiation_1(b, n)\n return 1 if n == 0\n return b if n == 1\n b*exponentiation_1(b, n-1)\nend",
"def power(x,n)\n n == 0 ? (return 1) : x*power(x,n-1)\n\nend",
"def power(num, n)\n return num if n == 1\n multiply(num, power(num, n - 1))\nend",
"def pow( x, n)\n if (n == 0)\n return (1)\n elsif (n % 2 == 0)\n value = pow(x, n / 2)\n return (value * value)\n else\n value = pow(x, n / 2)\n return (x * value * value)\n end\nend",
"def power_of_n(n, power)\n result = 1\n power.times {result = multiply(n, result)} # similar to recursion\n result\nend",
"def pow(x, n)\n if n == 0\n return 1\n elsif n % 2 == 0\n return pow(x, n/2) * pow(x, n/2)\n else\n return x*pow(x, n-1)\n end\nend",
"def exp(b,n)\n return 1 if n == 0\n b * exp(b,n-1)\nend",
"def exponentiation2(b, n)\n return 1 if n == 0\n return b if n == 1\n if n.even?\n exponentiation2(b, n / 2) ** 2\n else\n b * exponentiation2(b, (n - 1) / 2) ** 2\n end\nend",
"def power(num, n)\n if n == 0\n 1\n elsif n > 0\n multiply(power(num, n - 1), num)\n else\n 1 / power(num, -n).to_f\n end\nend",
"def perfect_power(n)\n\nend",
"def exponentiation_2(b, n)\n return 1 if n == 0\n return b if n == 1\n\n if n.even?\n exponentiation_2(b, n / 2) ** 2\n else\n b * (exponentiation_2(b, (n - 1) / 2) ** 2)\n end\nend",
"def exponent_v2(b, n)\n puts s += 1\n if n == 0 \n return 1\n elsif n == 1 \n return b\n elsif n.even?\n rec = exponent_v2(b, n / 2)\n rec * rec\n else \n rec = exponent_v2(b, (n - 1) / 2)\n b * rec * rec\n end\nend",
"def exp(b, n)\n return b if n <= 1\n b * exp(b, n-1)\nend",
"def exp(b,n) #First method\n return 1 if n == 0\n if n > 0\n b * exp(b,n - 1)\n else\n (1.0/b) * exp(b,n + 1) \n end\nend",
"def bunny(n)\n # base case\n return 0 if n == 0\n # recursive case\n return 2 + bunny(n - 1)\nend",
"def bunny(n)\n # base case\n return 0 if n == 0\n # recursive case\n return 2 + bunny(n-1)\nend",
"def exp(b,n)\n return 1 if n == 0\n return b if n == 1\n\n if n.even?\n num = exp(b, n / 2)\n num * num\n else\n num = exp(b, (n - 1) / 2)\n b * num * num\n end\nend",
"def exp(b, n)\n return b if n == 0 || n == 1\n \n if n.even?\n return exp(b, n / 2) ** 2\n else\n return b * exp(b, n - 1)\n end\nend",
"def exp(b, n)\n return b if n == 0 || n == 1\n \n return b * exp(b, n - 1)\nend",
"def power(n)\n n ** 2\nend",
"def exp(b, n) # option 2\n return 1 if n == 0\n result = nil\n\n if n.even?\n result = exp(b, n / 2) ** 2\n else\n result = b * (exp(b, (n - 1) / 2) ** 2)\n end\n\n result\nend",
"def power_of_n(num, exponent)\n num ** exponent\nend",
"def bunny(n)\n raise ArgumentError if n < 0\n if n == 0 # base case\n return 0\n else\n return bunny(n - 1) + 2\n end\nend",
"def bunny(n)\n if n < 0 \n raise ArgumentError, \"bunnies cannot be a negative number!\"\n elsif\n n == 0\n return n\n else\n return 2+ bunny(n-1)\n end\nend",
"def bunny(n)\n if n <= 0\n return 0\n else\n return 2 + bunny(n-1)\n end\nend",
"def general_power(n, x)\n multiply(n, 1)**(x)\nend",
"def bunny(n)\n if n == 0\n return 0\n else\n return 2 + bunny(n - 1)\n end\nend",
"def rpower(n) end",
"def bunny(n)\n if n == 0\n return 0\n else\n return 2 + bunny(n-1)\n end \nend",
"def potenz(x, n)\n check_pre((n.nat?))\n if (n == 1) then\n x\n elsif (n == 0) then\n 1\n else \n x*=potenz((x), n-1)\n end\n end",
"def solve( n = 100 )\n max = 0\n 1.upto( n - 1 ) do |a|\n 1.upto( n - 1 ) do |b|\n m = (a**b).sum_digits\n max = m if m > max\n end\n end\n \n max\n end",
"def bunny(n)\n if n < 1\n return 0\n else \n return 2 + bunny(n-1)\n end\nend",
"def bunny(n)\n if n == 0\n return n\n else\n return 2 + bunny(n - 1)\n end\nend",
"def modpow(a, b, n, m)\n if n == 0\n [1, 0]\n elsif n % 2 == 0\n modpow((a * a) % m, (a * b + b) % m, n / 2, m)\n else\n c, d = modpow(a, b, n - 1, m)\n [(a * c) % m, (a * d + b) % m]\n end\nend",
"def q(n)\n if n == 1\n return 1\n else q(n-1) + (n*n*n)\n end\nend",
"def jacobi(a, n)\n if a == 0\n n == 1 ? 1 : 0\n elsif a.odd?\n negpow((a-1)*(n-1)/4) * jacobi(n%a, a)\n else\n negpow((a**2-1)/8) * jacobi(a/2, n)\n end\nend",
"def bunny(n)\n # raise NotImplementedError, \"Method not implemented\"\n if n == 0\n return 0\n else\n return 2 + bunny(n - 1)\n end\nend",
"def bunny(n)\n if n === 0\n return 0\n end\n\n return 2 + bunny(n-1)\nend",
"def bunny(n)\n if n == 0\n return 0\n elsif n == 1\n return 2 \n else\n 2 + bunny(n - 1)\n end \nend",
"def bunny(n)\n if n == 0\n return n\n else\n return 2 + bunny(n-1)\n end\nend",
"def solve( n = 30 )\n term = nil\n\n (2..10).each do |e|\n (2..100).each do |sum|\n if (sum**e).sum_digits == sum\n term, n = sum**e, n - 1 \n end\n break if 0 == n\n end\n break if 0 == n\n end\n\n term\n end",
"def bunny(n)\n raise ArgumentError if !n\n \n return n if n <= 0 \n return 2 + bunny(n - 1)\nend",
"def bunny(n)\n return 0 if n == 0\n return 2 + bunny(n - 1)\nend",
"def bunny(n)\n return 0 if n == 0\n return 2 + bunny(n - 1)\nend",
"def exp_1(b, n)\n return 1 if n == 0\n b * exp_1(b, n - 1)\nend",
"def bunny(n)\n return 0 if n <= 0\n return 2 if n == 1\n return 2 + bunny(n-1)\nend",
"def bunny(n)\n return 0 if n == 0\n return 2 + bunny( n - 1 )\nend",
"def bunny(n)\n return 0 if n == 0\n return 2 + bunny(n-1)\nend",
"def bunny(n)\n return 0 if n == 0\n return 2 + bunny(n-1)\nend",
"def bunny(n) \n return 0 if n == 0\n return 2 + bunny(n - 1)\nend",
"def factorialB(n, total=1)\n raise ArgumentError.new(\"Not an integer\") if\n !(n.class==Integer)\n raise ArgumentError.new(\"Not a non-negative integer\") if n < 0\n\n if n==0\n return total\n else\n return factorialB(n-1, n * total)\n end\nend",
"def bunny(n)\n return 0 if n == 0\n return 2 + bunny(n-1)\nend",
"def bunny(n)\n return 0 if n == 0\n return 2 + bunny(n-1)\nend",
"def bunny(n)\n return 0 if n == 0\n return 2 + bunny(n-1)\nend",
"def pow2(x, n)\n if n == 0\n return 1\n end\n temp = pow2(x, n/2)\n if n % 2 == 0\n return temp * temp\n else\n return x*temp*temp\n end\nend",
"def exp1(b, n)\n return 1 if n == 0\n b * exp1(b, n - 1)\nend",
"def factorial_recursive(n)\n if n < 0\n \"Invalid input\"\n elsif n == 0\n 1\n else\n n *= factorial_recursive(n-1)\n end\nend",
"def bunny(n)\n return 0 if n == 0\n\n return 2 + bunny(n-1)\nend",
"def bunny(n)\n # raise NotImplementedError, \"Method not implemented\"\n return 0 if n == 0\n return 2 + bunny(n - 1)\n\nend",
"def bunny(n)\n return 0 if n == 0\n return 2 if n == 1\n return 2 + bunny(n - 1)\nend",
"def jacobi(a, n)\n if n == 1\n return 1\n elsif a.zero?\n return 0\n elsif a == 1\n return 1\n elsif a == 2\n if [3, 5].include?(n % 8)\n return -1\n elsif [1, 7].include?(n % 8)\n return 1\n end\n elsif a < 0\n return (-1)**((n - 1) / 2) * jacobi(-1 * a, n)\n end\n\n if a.even?\n return jacobi(2, n) * jacobi(a / 2, n)\n elsif a % n != a\n return jacobi(a % n, n)\n else\n if a % 4 == n % 4 && a % 4 == 3\n return -1 * jacobi(n, a)\n else\n return jacobi(n, a)\n end\n end\nend",
"def binomial_coefficient(n,k)\n return 1 if (k==0 or k==n)\n k=[k, n-k].min\n binding.pry\n permutations(n,k).quo(factorial(k))\n # The factorial way is\n # factorial(n).quo(factorial(k)*(factorial(n-k)))\n # The multiplicative way is\n # (1..k).inject(1) {|ac, i| (ac*(n-k+i).quo(i))}\n end",
"def bunny(n)\n # raise NotImplementedError, \"Method not implemented\"\n return 2 + bunny(n - 1) unless n.zero?\n return 0 if n.zero?\nend",
"def binomial_coefficient(n,k)\n return 1 if (k==0 or k==n)\n k=[k, n-k].min\n permutations(n,k).quo(factorial(k))\n # The factorial way is\n # factorial(n).quo(factorial(k)*(factorial(n-k)))\n # The multiplicative way is\n # (1..k).inject(1) {|ac, i| (ac*(n-k+i).quo(i))}\n end",
"def power_of_n(number, power)\n array = [number] * power\n base_number = 1\n array.each do |num|\n base_number = multiply(base_number, num)\n end\n base_number\nend",
"def bunny(n)\n return 0 if n == 0\n return 2 if n == 1\n return 2 + bunny(n-1)\nend",
"def bunny(n)\n return n if n == 0\n return 2 + bunny(n-1)\nend",
"def exp1(b, n)\n return 1 if n == 0\n p b * exp1(b, n - 1)\nend",
"def bunny(n)\n return 0 if n < 1\n return 2 if n < 2\n return 2 + bunny(n-1)\nend",
"def factorial_recursive(n)\n\tif (n==0)\n\t\treturn 1\n\telse\n\t\t\treturn n*factorial_recursive(n-1)\n\tend\nend",
"def factorial_recursive n\n return 1 if n == 0\n n * factorial_recursive(n-1)\nend",
"def power_to_the_n(number, power)\n return 1 if power == 0\n result = 1\n while power > 0\n result = multiply(result, number)\n power -= 1\n end\n result\nend",
"def wonky_coins(n)\n return 1 if n == 0\n\n # call wonky_coins from inside itself. This is called *recursion*.\n return wonky_coins(n / 2) + wonky_coins(n / 3) + wonky_coins(n / 4)\nend",
"def bunny(n)\n if n % 2 == 0\n return 0\n else\n return n + bunny(2-1)\n end\nend",
"def factorial(n)\n # Input validation\n raise ArgumentError if n < 0 \n # Base case\n return 1 if n == 0 \n # Recursive case\n return n * factorial(n-1)\nend",
"def binomial_coefficient(n, k)\n return 1 if n == k || k == 0\n return n if k == 1\n return -1 if n < k\n\n # calculate factorials\n fact_n = (2..n).inject(1) { |carry, i| carry * i }\n fact_k = (2..k).inject(1) { |carry, i| carry * i }\n fact_n_sub_k = (2..(n - k)).inject(1) { |carry, i| carry * i }\n\n fact_n / (fact_k * fact_n_sub_k)\n end",
"def bunny(n)\n return 0 if n == 0\n return 2 if n == 1\n return bunny(n - 1) + bunny(1)\n\nend",
"def exp2(b, n)\n return 1 if n == 0\n return b if n == 1\n if n.even?\n partial = exp2(b, n / 2)\n return partial * partial\n else\n partial = exp2(b, (n - 1) / 2)\n return b * (partial * partial)\n end\nend",
"def factorial(n)\n\n raise ArgumentError unless n >= 0 \n return 1 if n == 1 || n == 0\n\n n * factorial(n - 1)\n\nend",
"def power(nb1, nb2)\n return nb1 ** nb2\nend",
"def factorial(n)\n raise ArgumentError if n < 0\n return 1 if n == 1 || n == 0\n return n * factorial(n-1)\nend",
"def bunny(n)\n return n if n == 0\n return 2 + bunny(n-1)\n end",
"def exp(b,n)\n return 1 if n == 0\n return b if n == 1\n case \n when n > 0 && n.even?\n exp(b,n/2) ** 2\n when n > 0 && n.odd?\n b * exp(b,(n-1)/2)**2\n when n < 0 && n.even?\n exp(1.0/b,n/2) ** 2\n when n < 0 && n.odd?\n 1.0/b * exp(b,(n+1)/2) **2\n end\nend",
"def bunny(n)\n return 0 if n == 0\n\n return (2 + (2 * (n - 1)))\nend",
"def bunny(n)\n\n return 0 if n == 0\n return 2 if n == 1\n bunny(n - 1) + 2\n\nend",
"def binom(n, k)\n return 1 if k.zero? || (n - k).zero?\n return n if k == 1 || n - k == 1\n\n factorial(n) / (factorial(k) * factorial(n - k))\n end",
"def factorial(n)\n raise ArgumentError if n < 0\n return 1 if n == 0\n return n * factorial(n-1)\nend",
"def factorial(n)\n raise ArgumentError.new if n < 0 \n return 1 if n == 1 || n == 0 \n return n * factorial(n-1)\nend"
] |
[
"0.7867685",
"0.7718268",
"0.7718268",
"0.7708262",
"0.76860213",
"0.7595162",
"0.75813276",
"0.7523488",
"0.75191253",
"0.7430109",
"0.7412472",
"0.73890454",
"0.73381114",
"0.73173046",
"0.7310674",
"0.7285143",
"0.72811705",
"0.7151168",
"0.7126279",
"0.71241736",
"0.7120184",
"0.7104152",
"0.70747876",
"0.7070633",
"0.7029283",
"0.7022627",
"0.69739217",
"0.6971352",
"0.6966528",
"0.69608223",
"0.6943238",
"0.69344825",
"0.69276255",
"0.6914665",
"0.6904504",
"0.687875",
"0.6864744",
"0.6849425",
"0.68485373",
"0.68474334",
"0.6845072",
"0.6816591",
"0.6810241",
"0.6805615",
"0.6804493",
"0.6793833",
"0.678319",
"0.67808694",
"0.677773",
"0.6773843",
"0.6747774",
"0.6744259",
"0.674054",
"0.6735539",
"0.6734953",
"0.6732868",
"0.67268956",
"0.6723226",
"0.6723226",
"0.67229944",
"0.67218816",
"0.67200756",
"0.67200756",
"0.67200756",
"0.6690926",
"0.6688783",
"0.66883266",
"0.66772765",
"0.6674672",
"0.6672853",
"0.6670865",
"0.66654414",
"0.66621584",
"0.6662",
"0.6658771",
"0.66460824",
"0.66405237",
"0.66231006",
"0.66173434",
"0.661552",
"0.6609242",
"0.66043055",
"0.6597269",
"0.65860784",
"0.65851897",
"0.65825737",
"0.65754944",
"0.6573457",
"0.656905",
"0.65673834",
"0.65671486",
"0.6566661",
"0.6566122",
"0.6564069",
"0.65624774",
"0.6562078",
"0.6560448",
"0.6560065"
] |
0.73164076
|
16
|
Write a recursive method that returns the sum of the first n even numbers recursively. Assume n > 0.
|
def first_even_numbers_sum(n)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def first_even_numbers_sum(n)\n return 2 if n == 1\n 2 * n + first_even_numbers_sum(n-1)\n end",
"def first_even_numbers_sum(n)\n return 2 if n == 1\n 2 * n + first_even_numbers_sum(n-1)\nend",
"def recursion(n)\n if n % 2 ==0\n n\n else\n recursion(n + 1)\nend\nend",
"def even_num_rec(n)\n n = (0...n).to_a if n.is_a? Integer\n if n == []\n []\n else\n [n[0] * 2] + even_num_rec(n[1..-1])\n end\nend",
"def fib_even_sum(n)\n fib_arr = [1, 1]\n sum = 0\n\n until fib_arr[-1] >= n\n fib_arr << (fib_arr[-2] + fib_arr[-1])\n sum += fib_arr[-2] if fib_arr[-2].even?\n end\n\n sum\nend",
"def recursiveSumOfEvenNumbers array\n return 0 if array.empty?\n lastNumb = array.pop\n sum = recursiveSumOfEvenNumbers array\n if lastNumb % 2 == 0 then sum += lastNumb end\n return sum\nend",
"def sum(n)\n return 1 if n == 1\n\n n + sum(n - 1)\nend",
"def sum_even_fibonacci_numbers(num)\n even_fibonacci_numbers = fibonacci_numbers(num).select{|number| number.even?}\n even_fibonacci_numbers.inject(:+)\nend",
"def fibs_sum(n)\n return 1 if n == 1 || n == 2\n sum = 0\n sum += (fibs_sum(n - 1) + fibs_sum(n - 2))\n \n \nend",
"def rec_sum(n)\n if n == 0\n return 0\n else\n return n + rec_sum(n-1)\n end\nend",
"def even_fibs_recursive(num, term1 = 1, term2 = 2, sum = 2)\n \n next_term = term1 + term2\n return sum if next_term >= num\n\n sum += next_term if next_term % 2 == 0\n\n even_fibs_recursive(num, term2, next_term, sum)\n\nend",
"def sumOfEvenFibonacciNumbersUnderN(n)\n\n return 0 if n <= 2 \n \n fibonacci = [0,1]\n total = 0\n\n until fibonacci.last >= n\n \tfibonacci << fibonacci.last + fibonacci[-2]\n \ttotal += fibonacci[-1] if fibonacci[-1].even? \n end\n\n total \n\nend",
"def sum_to(n)\n # if n < 2\n # 1\n # else\n # n + sum_to(n-1)\n # end\n return 1 if n < 2\n n + sum_to(n - 1)\nend",
"def fibs_sum(n)\n return 0 if n == 0\n return 1 if n == 1\n\n fibs_sum(n - 1) + fibs_sum(n - 2) + 1\nend",
"def fibs_sum(n)\n return 0 if n == 0\n return 1 if n == 1\n\n fibs_sum(n-1) + fibs_sum(n-2) + 1\nend",
"def fibs_sum(n)\n return 0 if n == 0\n return 1 if n == 1\n\n fibs_sum(n-1) + fibs_sum(n-2) + 1\nend",
"def fibs_sum(n)\n return 0 if n == 0\n return 1 if n == 1\n\n fibs_sum(n-1) + fibs_sum(n-2) + 1\nend",
"def fibs_sum(n)\n return 0 if n == 0\n return 1 if n == 1\n\n fibs_sum(n-1) + fibs_sum(n-2) + 1\nend",
"def row_sum_odd_numbers(n)\n starting_odd = (n * (n - 1) / 2) * 2 + 1\n sum_of_odd = 0\n (n).times do\n sum_of_odd += starting_odd\n starting_odd += 2\n end\n sum_of_odd\nend",
"def even_fib_sum(n)\n f = ->(x){ x < 2 ? x : f[x-1] + f[x-2] }\n\n value =f[2]\n res = cnt = 0\n while value <= n\n res+=value if value.even?\n cnt+=1\n value=f[cnt]\n end\n res\nend",
"def sum_to(n)\n return nil if n<0\n return 1 if n==1\n sum_to(n-1) + n\nend",
"def row_sum_odd_numbers(n)\n b = (1..n).sum * 2 - 1\n a = b - 2 * (n - 1)\n (a..b).select{|i| i.odd?}.sum\n\n # # other solution:\n # n ** 3\nend",
"def f(n)\n return 1 if n < 2\n return 2 if n == 2\n\n if n % 2 == 1\n return f( (n-1) /2)\n else\n tmp = n / 2\n m = 1\n while tmp % 2 == 0\n m+=1\n tmp = tmp / 2\n end\n return f(tmp) + m* f(tmp-1)\n end\nend",
"def nth_even(n)\n (n * 2) - 2\nend",
"def nth_even(n)\n (n*2) - (2)\nend",
"def sum_even_odd(fake_num); end",
"def sum_to(n)\n return nil if n < 1\n return 1 if n == 1\n sum_to(n - 1) + n\nend",
"def sum_to(n)\n return nil if n < 1\n return 1 if n == 1\n\n n + sum_to(n - 1) \nend",
"def sum_to(n)\n return n if n == 1\n n + sum_to(n-1)\nend",
"def fib_sum(n)\n return n if ( 0..1 ).include? n\n ( fib_sum( n - 1 ) + fib_sum( n - 2 ) )\nend",
"def sum_to(n)\n return nil if n < 0\n return n if n == 1\n\n n + sum_to(n - 1)\nend",
"def f(n)\n return n if n.zero? || n == 1\n f(n - 1) + f(n - 2)\nend",
"def sum_to(n)\n\n if n < 1\n return nil\n elsif n == 1\n return 1\n end\n\n n + sum_to(n - 1)\nend",
"def sum_to(n)\n return 1 if n == 1\n return nil if n<1\n n + sum_to(n-1)\nend",
"def sum_to(n)\n if n == 1\n return 1\n elsif n < 1\n return nil\n end\n\n n + sum_to(n - 1)\nend",
"def sum_to(n)\n return n if n == 1 || n == 0\n return nil if n < 0\n n + sum_to(n - 1)\nend",
"def fibs_sum(n) # my version\n return 1 if n == 1\n return 2 if n == 2\n\n current = single_fib(n)\n current += fibs_sum(n - 1)\nend",
"def sum_even(nums)\n nums.select { |n| n.even? }.inject(&:+)\nend",
"def sum_to(n)\n return nil if n < 1\n return n if n == 1\n n + sum_to(n - 1)\nend",
"def sum_to(n)\n return nil if n < 1\n return n if n == 1\n \n n + sum_to(n - 1)\nend",
"def even_fibonacci_sum(limit)\n fib_seq = fibonacci_sequence(limit)\n sum = 0\n fib_seq.each{|fib_num| fib_num%2 == 0 ? (sum += fib_num) : ()}\n\n return sum\nend",
"def even_fibonacci_number(n)\n sum = 0\n fib1 = 0\n fib2 = 1\n while fib2 < n\n temp = fib1\n fib1 = fib2\n fib2+=temp\n sum += fib2 if fib2.even?\n end\n p sum\nend",
"def sum_to(n)\n return 1 if n == 1\n return nil if n <= 0\n n + sum_to(n-1)\nend",
"def even_fibonacci(n)\n\tif n == 0\n\t\treturn 0\n\telsif n == 1\n\t\treturn 2\n\telse\n\t\treturn 4*even_fibonacci(n-1)+even_fibonacci(n-2)\n\tend\nend",
"def sum_to(n)\n return nil if n < 0\n return 0 if n == 0\n n + sum_to(n-1)\nend",
"def sum_to(n)\n return nil if n < 0\n return n if n <= 1\n n + sum_to(n - 1) #if n > 0\nend",
"def sum_to(n)\n n > 1 ? n + sum_to(n - 1) : n < 1 ? [].first : 1\n end",
"def sum_of_even_fibonaccis2(n)\n\tfibs = []\n\tnth = 0\n\tfibs[nth] = fibonacci[nth]\nend",
"def row_sum_odd_numbers(n)\n row = 1\n num = 1\n sum = 0\n while row <= n\n row.times do\n if row == n\n sum += num\n end\n num += 2\n end\n row += 1\n end\n return sum\nend",
"def tail_sum(n, total = 0)\n return total if n == 0\n\n tail_sum(n - 1, total + n)\nend",
"def sum_to(n)\n return n if n == 0\n return nil if n < 0\n n + sum_to(n - 1)\nend",
"def fibsum(n)\n\tsum = 0\n\tfib = [1,2]\n\ttest = fib[-1]\n\twhile test <= n:\n\t\tsum += test if test % 2 == 0\n\t\tfib << test + fib[-2]\n\t\tfib.shift\n\t\ttest = fib[-1]\n\tend\n\tp sum\nend",
"def sumOfEvenFibonacci(n)\n\t# sum of f(2),f(5),f(8),f(11),f(14),etc is needed. f(5) is 8, f(6) is 13, f(7) is 21\n\tsum = 10\n\tfn2 = 8\n\tfn1 = 13\n\tfn = 21\n\ti = 8\n\twhile (fn < n)\n\t\tif i % 3 == 0 then sum = sum + fn end\n\t\tfn2 = fn1\n\t\tfn1 = fn\n\t\tfn = fn1 + fn2\n\t\ti += 1\n\tend\n\treturn sum\nend",
"def fiboEvenSum(number)\n\tsum = 0\n\tpreviousDigit = 1\n\tfiboDigit = 0;\n\n\twhile fiboDigit < number\n\t\ttemp = fiboDigit\n\t\tfiboDigit += previousDigit\n\t\tpreviousDigit = temp\n\t\tif fiboDigit % 2 == 0\n\t\t\tsum += fiboDigit \n\t\tend\n\tend \n\tsum\nend",
"def sum_to(n)\n return nil if n <= 0 #negatives and 0\n return 1 if n == 1 #base step\n #inclusive step 1 + sum_to(n)\n n + sum_to(n - 1)\nend",
"def sum_func(n)\n if n / 10 == 0\n return n\n else\n return n % 10 + sum_func(n/10)\n end\nend",
"def fibonacci_recursive n\n return n if n < 2\n fibonacci_recursive(n-1) + fibonacci_recursive(n-2)\nend",
"def sum_of_even(input_array)\n\teven_array = []\n\tinput_array.each do |number|\n\t\tif number%2 == 0\n\t\t\teven_array.push(number)\n\t\tend\n\tend\n\treturn even_array.inject(:+)\nend",
"def sum_to(n)\n return nil if n < 0\n return n if n == 0\n n += sum_to(n - 1)\nend",
"def sum_to(n)\n return 1 if n == 1\n return nil if n < 1\n n += sum_to(n - 1)\nend",
"def even_fibonacci(limit, current, prev, sum = 0)\n return sum if current >= limit\n\n sum += current if (current % 2).zero?\n current, prev = current + prev, current\n even_fibonacci(limit, current, prev, sum)\nend",
"def exponent_v2(b, n)\n puts s += 1\n if n == 0 \n return 1\n elsif n == 1 \n return b\n elsif n.even?\n rec = exponent_v2(b, n / 2)\n rec * rec\n else \n rec = exponent_v2(b, (n - 1) / 2)\n b * rec * rec\n end\nend",
"def even_fibs_sum(num)\n fibs = [0,1]\n \n while fibs.max < num\n nexty = fibs[-1] + fibs[-2]\n fibs << nexty\n end\n \n sum = 0\n fibs.map {|x| sum += x if x.even? }\n \n return sum\nend",
"def sum_of_even_digits(n) #adds every even digit\n n = n.to_s.split(//)\n reverse_cc = n.reverse.values_at(1,3,5,7,9,11,13,15).compact\n sum_evens = 0\n reverse_cc.each do |cc_number|\n doubled = cc_number.to_i * 2\n sum_evens += get_digit(doubled)\n end\n return sum_evens\nend",
"def evenLoop(n)\n i = 0\n while i < n*2 do\n return i\n i+=2\n end\nend",
"def sum(n)\n end",
"def sum(n, m)\n if n > m\n return 0\n else\n return sum(n+1, m) + n\n end\nend",
"def sum_to(n)\n (1..n).reduce(0) do |sum, value|\n sum + value\n end\nend",
"def fib2(n)\n if n < 2\n n\n else\n fib2(n - 1) + fib2(n - 2)\n end\nend",
"def oddCount n \r\n if (n % 2 == 0)\r\n return n / 2\r\n end\r\n return (n - 1) / 2\r\n end",
"def problem2(num)\n f = [1,2]\n f.push(f[-2..-1].reduce(:+)) until f[-1] >= num\n f.select{|n| n.even?}.reduce(:+)\nend",
"def fibonnaci_even(limit)\n fibonnacci = [1, 1]\n (1...limit).each { fibonnacci << fibonnacci.last(2).sum }\n fibo_even = fibonnacci.select { |num| num.even? }.sum\nend",
"def sum_of_n_consecutive_numbers (n)\n n*(n+1)/2\nend",
"def row_sum_odd_numbers(n)\n # (1..n).each_with_object([]) { |row, obj| obj << }\n # .at(n - 1)\n # arr = Array.new(n, 0)\n # num = 1\n # n.times do |x|\n \n # arr[x] += num\n # num += 2\n # end\n # arr\n min = n * (n - 1) + 1\n max = n * n + (n - 1)\n (min..max).reject(&:even?).inject(:+)\nend",
"def evenLoop(n)\n total = n * 2\n for x in 1..total\n if x % 2 == 0\n x\n end\n end\nend",
"def s1(n)\n if n.even? then 0\n else 1 end\nend",
"def odd_nums_r (bound=99, n=3)\n if n <= bound\n puts n\n odd_nums_r(bound, n + 1)\n end\nend",
"def even_valued_number(x)\n fib_array = [0,1]\n x.times do\n fib_array << fib_array[-1] + fib_array[-2]\n end\n fib_array.find_all{ |number| number % 2 == 0}.reduce(:+)\nend",
"def bunny(n)\n # base case\n return 0 if n == 0\n # recursive case\n return 2 + bunny(n-1)\nend",
"def fibs(n)\n return n if n <= 1\n fibs(n - 1) + fibs(n - 2)\nend",
"def exp_2(b, n)\n return 1 if n == 0\n return b if n == 1\n\n even_rec = exp_2(b, n / 2) # if n.even?\n odd_rec = exp_2(b, (n - 1) / 2) # if n.odd?\n\n if n.even?\n even_rec * even_rec\n # exp(2, 8)\n # => [ exp(2, 4) ] * [ exp(2, 4) ]\n # => [ exp(2, 2) * exp(2, 2) ] * [ exp(2, 2) * exp(2, 2) ]\n # => [ exp(2, 1) * exp(2, 1) * exp(2, 1) * exp(2, 1) ] *[ exp(2, 1) * exp(2, 1) * exp(2, 1) * exp(2, 1) ]\n # => [ b * b * b * b * b * b * b * b ]\n else # n == odd\n b * odd_rec * odd_rec\n # => exp(2, 7)\n # => b * [ exp(2, 3) ] * [ exp(2, 3) ]\n # => b * [ b * exp(2, 1) * exp(2, 1) ] * [ b * exp(2, 1) * exp(2, 1) ]\n # => b * [ b * b * b ] * [ b * b * b ]\n end\n\nend",
"def sum(n)\n result = 0\n n.each do |number|\n result = result + number\n end\n return result\n end",
"def bunny(n)\n # base case\n return 0 if n == 0\n # recursive case\n return 2 + bunny(n - 1)\nend",
"def fun1 n\n return 0 if n == 1\n return 1 + fun1(n/2)\nend",
"def sum_numbers(arr, n)\n sum = 0\n index = 0\n\n arr.each do |i|\n if index != n \n sum += i\n else\n return sum\n end\n\n index += 1\n end\nend",
"def sum_of_even_fibonaccis(limit)\n\n holder = [1,2]\n\n while ( holder[-1] + holder[-2] ) < limit\n holder << holder[-1] + holder[-2]\n end\n\n return holder.select { |n| n.even? }.reduce(:+)\n\nend",
"def nth(n)\n\tif n <= 0 \n\t\treturn 0 \n\tend \n\tif n == 1\n\t\treturn 17 \n\telse \n\t\treturn nth(n-1) + 5 \n\tend \nend",
"def square_sum_up_to n=100\r\n (n * (n + 1) / 2)**2\r\nend",
"def even(n)\n n % 2 == 0\nend",
"def even_fibonacci_sum(limit)\n array = [0, 1]\n array << (array[-1] + array[-2]) while (array[-1] + array[-2]) < limit\n array.select(&:even?).reduce(:+)\nend",
"def bunny(n)\n if n % 2 == 0\n return 0\n else\n return n + bunny(2-1)\n end\nend",
"def even_fibonacci(number)\n even_sum = 0\n fib1 = 1\n fib2 = 2\n fib_count = 0\n\n if number < 3\n even_sum = 0\n else\n while fib_count < number\n if fib2 % 2 === 0\n even_sum += fib2\n end\n fib_count = fib1 + fib2\n fib1 = fib2\n fib2 = fib_count\n end\n end\n\n puts even_sum\n return even_sum\nend",
"def fib(n)\n if n<2\n return n\n else\n return fib(n-2)+fib(n-1)\n end\nend",
"def fibonacci_recur(n)\n return 0 if n == 1\n return 1 if n == 2\n\n fibonacci_recur(n - 1) + fibonacci_recur(n - 2)\nend",
"def next_step(n)\n if n.even?\n n/2.to_i\n else\n 3*n+1\n end\nend",
"def square_of_sum(n)\n sum = 0\n (1..n).each {|i| sum = sum + i}\n sum * sum\n end",
"def exponentiation_2(b, n)\n return 1 if n == 0\n return b if n == 1\n\n if n.even?\n exponentiation_2(b, n / 2) ** 2\n else\n b * (exponentiation_2(b, (n - 1) / 2) ** 2)\n end\nend",
"def fib(n)\n\treturn n if (n < 2)\n\treturn fib(n - 1) + fib(n - 2)\nend",
"def row_sum_odd_numbers(n)\n\tn**3\nend"
] |
[
"0.88773525",
"0.88209176",
"0.7575595",
"0.7511886",
"0.7442943",
"0.7334038",
"0.73173136",
"0.7249176",
"0.72258985",
"0.72222763",
"0.72195196",
"0.71986216",
"0.7167344",
"0.71563643",
"0.71517795",
"0.71517795",
"0.71517795",
"0.71517795",
"0.7151437",
"0.7128636",
"0.71247786",
"0.7121537",
"0.71168274",
"0.71002984",
"0.71000046",
"0.70949805",
"0.7062453",
"0.7054256",
"0.7053261",
"0.7040451",
"0.7039255",
"0.70372057",
"0.70325744",
"0.7026855",
"0.7022136",
"0.7006043",
"0.7005452",
"0.6991958",
"0.69901",
"0.69779074",
"0.6974072",
"0.6971203",
"0.69682837",
"0.69649476",
"0.69111085",
"0.69088036",
"0.68669075",
"0.68487936",
"0.6848366",
"0.68473506",
"0.684624",
"0.6845727",
"0.684456",
"0.6804366",
"0.6795059",
"0.6794382",
"0.6791501",
"0.67809254",
"0.67671454",
"0.67667705",
"0.67528373",
"0.67500556",
"0.6713371",
"0.6704637",
"0.66989696",
"0.6696767",
"0.6693497",
"0.66880625",
"0.6687121",
"0.6683846",
"0.668195",
"0.666303",
"0.666002",
"0.66579854",
"0.6654384",
"0.66543204",
"0.66252124",
"0.6620089",
"0.66193044",
"0.6617569",
"0.66101855",
"0.6605983",
"0.6602134",
"0.6597752",
"0.6594727",
"0.6591929",
"0.65903735",
"0.65515167",
"0.6549388",
"0.6544647",
"0.65441424",
"0.6542762",
"0.6541645",
"0.65396345",
"0.65210074",
"0.65185946",
"0.6517671",
"0.6514964",
"0.6512657"
] |
0.8361318
|
3
|
Write a recursive method `string_include_key?(string, key)` that takes in a string to search and a key string. Return true if the string contains all of the characters in the key in the same order that they appear in the key. example_1: string_include_key?("cadbpc", "abc") => true example_2: string_include_key("cba", "abc") => false
|
def string_include_key?(string, key)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def string_include_key?(string, key)\n return true if key == \"\"\n string.each_char.with_index do |char, idx|\n if char == key[0]\n return string_include_key(string[(idx + 1)..-1], key[1..-1])\n end\n end\n\n false\nend",
"def string_include_key?(string, key)\n return true if key.length == 0\n return false if string.length == 0\n\n if string[0] == key[0]\n string_include_key?(string[1..-1], key[1..-1])\n else\n string_include_key?(string[1..-1], key)\n end\nend",
"def string_include_key?(string, key)\n str_arr = string.split(\"\")\n key_arr = key.split(\"\")\n return true if key.length == 1 && str_arr.include?(key_arr.first)\n str_arr.each_index do |i|\n if str_arr[i] == key_arr.first\n bool = string_include_key?(str_arr.drop(i+1).join(\"\"), key_arr.drop(1).join(\"\"))\n if bool\n return true\n end\n end\n end\n false\n end",
"def string_include_key?(string, key)\n return true if key.length == 0\n\n next_key_char = key.chars.first\n key_index = string.index(next_key_char)\n\n return false if key_index.nil?\n string_include_key?(string[key_index+1..-1], key[1..-1])\nend",
"def string_include_key?(string, key)\n return false if string.length < key.length\n key.each_char do |ele|\n return true if string.include?(ele)\n end\n\n \nend",
"def string_include_key?(string, key)\n return true if string == key\n l = string.length\n k_l = key.length\n i = 0\n while i < (l - k_l)\n # return true if string[i ... i + k_l] == key\n return true if string_include_key?(string[i ... i+k_l], key)\n # val = string_include_key?(string[0 ... i], key)\n i += 1\n end\n false\nend",
"def item_included?(str, hash)\n hash.each do |key, value|\n return true if key == str\n end\n false\nend",
"def include?(key)\n self.each_key.any? { |k|\n k.casecmp?(key)\n }\n end",
"def contains(string)\n node = self.root\n string.each_char { |letter|\n if !node.has_key?(letter)\n return false\n end\n node = node[letter]\n }\n\n return node.has_key?(end_symbol)\n \n end",
"def custom_include?(str, substr)\n # return true if substring is found anywhere\n # within the string. Return false otherwise.\n len = substr.length\n str.chars.each_with_index do |char, idx|\n return true if str[idx, len] == substr\n end\n false\nend",
"def include?(searchstring, substring)\n\nend",
"def in_all_strings?(long_strings, substring)\n long_strings.all?{ |el| el.include?(substring)}\nend",
"def in_all_strings?(long_strings, substring)\n long_strings.each do |string|\n return false unless string.include?(substring)\n end\n\n return true\nend",
"def find_match(key, value, key_str, search_str)\n \tif value.kind_of?(Array)\n \t\tvalue.each do |element_value|\n \t\t\t#puts \"key: \" + key + \", element_value: \" + element_value\n \t\t\tif (find_match(key, element_value, key_str, search_str))\n \t\t\t\treturn true\n \t\t\tend\n \t\tend\n\telsif value.kind_of?(Hash)\n\t\tvalue.each do |element_key, element_value|\n\t\t\tif (find_match(element_key, element_value, key_str, search_str))\n\t\t\t\treturn true\n\t\t\tend\n\t\tend\n\telse\n\t\tif (key == key_str && value.to_s == search_str)\n\t\t\treturn true\n\t\tend\n\tend\n\treturn false\n end",
"def in_all_strings?(long_strings, substring)\n long_strings.all?{|str|str.include?(substring)}\n\nend",
"def in_all_strings?(long_strings, substring)\n long_strings.all? { |string| string.include?(substring) }\nend",
"def in_all_strings?(long_strings, substring)\n long_strings.all? { |string| string.include?(substring) }\nend",
"def unlock(str)\n key = {\n 2 => ['a', 'b', 'c'],\n 3 => ['d', 'e', 'f'],\n 4 => ['g', 'h', 'i'],\n 5 => ['j', 'k', 'l'],\n 6 => ['m', 'n', 'o'],\n 7 => ['p', 'q','r', 's'],\n 8 => ['t', 'u', 'v'],\n 9 => ['w', 'x', 'y', 'z']\n }\n\n output = []\n str.downcase.chars.each {|x| key.any? {|k,v| output << k if v.include? x} }\n output.join\n\nend",
"def in_all_strings?(long_strings, substring)\n long_strings.all? {|x| x.include?(substring) }\nend",
"def in_all_strings?(long_strings, substring)\n long_strings.all? {|string| string.include?(substring)}\nend",
"def in_all_strings?(long_strings, substring)\n long_strings.all? {|word| word.include?(substring)}\nend",
"def in_all_strings?(long_strings, substring)\n new_arr = long_strings.select {|s| s.include?(substring)}\n return new_arr == long_strings\nend",
"def string_include?(val)\n return false if !val.is_a?(String)\n ret = false\n for a in self\n ret = true if a.is_a?(String) && val.include?(a)\n end\n return ret\n end",
"def include?(key); end",
"def include?(key); end",
"def wordInStrings(word, strings)\n for string in strings do\n\n if string.include? word\n return true\n end\n end\n\n return false\nend",
"def include_key?(key)\n\t\t\ttrue\n\t\tend",
"def sequence_search(seq, key)\n seq_array = seq.split(\"\")\n key_array = key.split(\"\")\n key_i = 0\n seq_array.length.times do |j|\n if seq_array[j] == key_array[key_i] \n key_i += 1\n if key_i == key_array.length \n return true\n end\n\n end\n end\n return false\nend",
"def check_str(str,s)\n if str.include?s\n puts \"true\"\n else\n puts \"false\"\n end\nend",
"def my_include?(dict, query)\n dict.each do |valid_word|\n if valid_word == query\n return true\n end\n end\n return false\nend",
"def found_match(str)\n\tif dictionary.include?(str) # returns true if found in the dictionary\n\t\treturn str # don't stop the recursion, but return the word ?\n\tend\n\tfalse\nend",
"def string_check(elem)\n (('a'..'z').to_a + ('A'..'Z').to_a).each { |k| return true if elem.include?(k) }\n false\n end",
"def in_all_strings?(long_strings, substring)\n long_strings.all? { |long_string| sub_string?(long_string, substring) }\nend",
"def in_all_strings?(long_strings, substring)\n long_strings.all? {|el| sub_string?(el, substring)}\nend",
"def key?(key)\n keys.include?(key) || keys.map(&:to_s).include?(key)\n end",
"def key?(key)\n keys.include?(key) || keys.map(&:to_s).include?(key)\n end",
"def str_includes(str1, str2)\n if str2.downcase.include?(str1.downcase)\n true\n else\n false\n end\nend",
"def contains?(string)\n node = @root\n string.each_char do |letter|\n return false unless node[letter]\n node = node[letter]\n end\n\n node[@end_symbol] ? true : false\n end",
"def include?(key)\n @hash.has_key?(key.to_s)\n end",
"def in_all_strings?(long_strings, substring)\n count = 0\n long_strings.each do |string|\n if sub_string?(string, substring)\n count += 1\n end\n end\n\n count == long_strings.length\nend",
"def item_include?(array, string)\n match = false\n array.each do |el|\n if el == string\n match = true\n end\n end\n match\nend",
"def matches?(config_array, content_string)\n config_array.each { |key| return true if /#{key}/.match(content_string) } unless config_array.nil?\n false\n end",
"def include?(key)\n Options.check_valid_key(key)\n @data.include?(key.to_sym)\n end",
"def in_all_strings?(long_strings, substring)\n long_strings.map do |str|\n str.split.any?(substring)\n end.all?(true)\nend",
"def in_all_strings?(long_strings, short_string)\n long_strings.all? do |long_string|\n long_string.include?(short_string)\n end\nend",
"def include?(key)\n has_key?(key)\n end",
"def include_str_ary?(instr_ary)\n last_match = 0\n found = 0\n instr_ary.each do |instr|\n self[last_match..-1].each_with_index do |g_ins, idx|\n if g_ins.to_s.index instr\n found += 1\n last_match += idx + 1\n break\n end\n end\n end\n found == instr_ary.size\n end",
"def include?(key)\n value.include?(key)\n end",
"def is_string_contains_another_string?(char_string, char_set)\n (char_string.sub(char_set, '**').index('**') ? true : false) if(valid_strings?(char_string, char_set))\nend",
"def match_string( tree, string )\n # puts \"Checking for `#{string}` in tree (#{tree}).\"\n\n if tree.empty?\n # puts \"Tree is empty, returning empty\"\n return [ ]\n\n elsif string.empty?\n # puts \"No search string, returning empty\"\n return [ ]\n\n else\n matches = [ ]\n\n tree.each do |key,val|\n # puts \"Checking for `#{string}` in `#{key}` branch.\"\n\n simdex = string.simdex(key)\n\n if 0 < simdex\n if string == key\n # puts \"Matched full word! #{string} is #{key}\"\n # matches = collect_keys(val, key).unshift(key)\n return collect_keys(val, key).unshift(key)\n # puts \"Got matches: #{matches}\"\n\n else\n leaf = string.leaf(simdex)\n # puts \"Got leaf #{leaf}\"\n\n check = match_string(val, leaf)\n # puts \"Got check: #{check}\"\n\n if !check.empty?\n # matches = (check.map { |m| key + m })\n return check.map { |m| key + m }\n # puts \"New matches: #{matches}\"\n end\n end\n\n # break\n\n else\n check = match_string(val, string)\n\n if !check.empty?\n matches += check\n end\n end\n end\n\n # if matches.empty?\n # # puts \"No matches (#{string})\"\n # else\n # # puts \"Returning matches (#{string}): #{matches}\"\n # end\n\n return matches\n end\n end",
"def in_all_strings?(long_strings, short_string)\nend",
"def item_included?(str, arr)\n arr.each do |item|\n return true if item == str\n end\n false\nend",
"def match?(string)\n bigrams = get_bigrams(string)\n while bigrams.length > 1\n pair = bigrams.shift\n return true if bigrams[1..-1].include?(pair)\n end\nend",
"def includes?(array, target)\n array.each do |k, v|\n if k == key\n return true\n elsif v.class.to_s == \"Array\"\n v.each do |inner_array|\n return has_key(inner_array, key)\n end\n else\n return false\n end\n end\n\nend",
"def validate_string(string)\n stack = []\n lookup = { '(' => ')', '[' => ']', '{' => '}', '<' => '>' }\n left = lookup.keys\n right = lookup.values\n\n string.each_char do |char|\n if left.include? char\n stack << char\n elsif right.include? char\n return false if stack.empty? || (lookup[stack.pop] != char)\n end\n end\n\n return stack.empty?\nend",
"def valid_key?(match_data)\n match_data[:key].to_i == (97 - match_data[1..-2].join.to_i) % 97\nend",
"def custom_includee(string, substring)\n string.split(substring).length != 1\nend",
"def permutations?(string1, string2) \n hash = {}\n if string1.length == string2.length\n string2.each_char do |char|\n if string1.include?(char)\n if hash[char] == true\n repeated = char+char\n hash[repeated] = true\n else \n hash[char] = true\n end\n else \n hash[char]= false\n end\n end\n else \n return false\n end\n\n occurences = 0\n hash.keys.each do |key|\n if hash[key] == true\n occurences +=1\n end\n end\n\n if occurences == string1.length\n return true\n else \n return false\n end\n\nend",
"def str_include?(str, target_str)\n tmp = target_str.downcase\n if !!str.match(/#{tmp}/i)\n return true\n else\n return false\n end\n end",
"def string_has_all_letters(str)\n result = {}\n str.each_char do |c|\n return true if result.length == 26\n if c == \" \"\n next\n elsif !result.include?(c)\n result[c] = c\n end\n end\n result.length == 26 ? true : false\nend",
"def include?(key)\n current = @head\n while current.next_node != nil\n return true if current.value == key\n current = current.next_node\n end\n\n return true if current.value == key\n\n false\n end",
"def repeating_letters?(str)\r\n # your code goes here\r\n str = str.downcase.split(\"\")\r\n temp = \"\"\r\n i = 0\r\n while i < str.length\r\n if temp.include?(str[i])\r\n return true\r\n else\r\n temp << str[i]\r\n end\r\n i += 1\r\n end\r\n false\r\nend",
"def contains_expected_keys?(data, *expected_keys)\n expected_keys.each do |expected_key|\n return false until data.keys.include? expected_key\n end\n return true\nend",
"def contains_string(given, string_array)\n is_present = false\n string_array.each do |file_name|\n is_present = true if given.downcase.include? file_name.downcase\n end\n\n is_present\nend",
"def is_substring?(string1, string2)\n return true if string2.empty?\n return false if string2.length > string1.length\n\n string2_matchings = 0\n\n string1.each_char do |string1_char|\n if string2_matchings.zero?\n if string1_char == string2[0]\n string2_matchings += 1\n end\n else\n if string1_char == string2[string2_matchings]\n string2_matchings += 1\n else\n string2_matchings = 0\n end\n\n if string2_matchings == string2.length\n return true\n end\n end\n end\n\n false\nend",
"def contains(input, substr)\n input.include?(substr) ? true : false\n end",
"def contain_substrings?(str, sub1, sub2)\n sub1_length = sub1.size\n sub2_length = sub2.size\n start_idx_sub1 = 0\n start_idx_sub2 = 0\n sub1_found_idxs = []\n sub2_found_idxs = []\n\n 0.upto(str.size - 1) do |current_idx|\n # Find all indexes of sub1 in str\n if str[start_idx_sub1..current_idx] == sub1\n sub1_found_idxs << start_idx_sub1\n start_idx_sub1 = current_idx + 1\n elsif current_idx - start_idx_sub1 >= sub1_length - 1\n start_idx_sub1 += 1\n end\n\n # Find all indexes of sub2 in str\n if str[start_idx_sub2..current_idx] == sub2\n sub2_found_idxs << start_idx_sub2\n start_idx_sub2 = current_idx + 1\n elsif current_idx - start_idx_sub2 >= sub2_length - 1\n start_idx_sub2 += 1\n end\n end\n\n result(sub1_found_idxs, sub1_length, sub2_found_idxs, sub2_length) ? 'YES' : 'NO'\nend",
"def is_in(char, a_str)\n\n a_str = a_str.chars.sort(&:casecmp).join\n length = a_str.length\n mid = length / 2\n if a_str == ''\n p false\n elsif a_str.length == 1\n a_str == char\n elsif char == a_str[mid]\n p true\n elsif char < a_str[mid]\n is_in(char, a_str[0..(mid-1)])\n else\n is_in(char, a_str[(mid+1)..-1])\n end\nend",
"def common_substrings(string1, string2)\n string2.downcase.chars.each do |char|\n return false if string2.count(char) > string1.downcase.count(char)\n end\n true\nend",
"def include?(key)\n return false unless @data.is_a?(Hash)\n\n @data.include?(compatible_key(key))\n end",
"def in?(key)\n start_slot = hasher(key, @keys.size)\n position = start_slot\n found = false\n\n while @keys[position] != nil and !found\n if @keys[position] == key\n found = true\n else\n position = rehash(position, @keys.size)\n break if position == start_slot\n end\n end\n\n found\n end",
"def is_a_partial_string?(containing_string, potentially_partial_string)\n return (containing_string.size > potentially_partial_string.size and containing_string.include?(potentially_partial_string) )\n end",
"def isRepeated? subString, str\n\n if str.length % subString.length != 0 then return false end\n\n n = subString.length\n max_repetitions = str.length / n\n (0...max_repetitions).each do |i|\n if str[n*i, n] != subString then return false end\n end\n return true\nend",
"def key_in_map?(arr,key)\n if arr.empty?\n return false\n else\n if arr[0][0] == key\n return true \n else\n key_in_map?(arr[1..-1], key)\n end\n end\n end",
"def permut_sub_strings(b, s)\n hash = {}\n permutations(s).each do |str|\n hash[str] = true\n end\n for i in 0..b.size-s.size\n if (hash.key?(b[i..i+s.size]))\n return true\n end\n end\nend",
"def substring_of_string(string, substring)\n sub_i = 0\n\n string.each_char.with_index do |char, i|\n if substring[sub_i] == char\n return true if sub_i == substring.length - 1\n sub_i += 1\n else\n if substring[0] == char\n sub_i = 1\n else\n sub_i = 0\n end\n end\n end\n\n false\nend",
"def custom_start_with?(string, substring)\n array_of_strings = string.split(\" \")\n array_of_strings.first == substring ? true : false\nend",
"def StringScramble(str1,str2)\n x = str1.chars\n y = str2.chars\n y.each do |s|\n \t# if i use return true if x.include?(s)\n \t# it doesn't work, why????????????????\n \t# since it will return true once if finds a match\n \t# then the function will stop running. \n \t return false if !x.include?(s) \n end\n return true \nend",
"def contains_char(string, char)\n i = 0\n while i < string.length\n if string[i] == char\n return true\n end\n i += 1\n end\n return false\nend",
"def first_anagram?(str1, str2)\r\n anagram_helper(str1).include?(str2) \r\n\r\nend",
"def find_perm(key_str)\n key_arr = key_str.chars\n sorted_arr = key_arr.sort\n permut = key_arr.size.times.to_a.permutation.select do |perm|\n sorted_arr.values_at(*perm) == key_arr\n end.flatten\nend",
"def substring_test(str1, str2)\n str1.chars.each_index do |i|\n (i + 1).upto(str1.length) do |n|\n return true if str2.downcase.include?(str1[i..n].downcase) && str1[i..n].length > 1\n end\n end\n false\nend",
"def has_key?( key )\n key = UniMap.str_to_key( key ) unless key.is_a?( Key )\n key && contains_key( key )\n end",
"def contain_substr(input, substr)\n input.include?(substr) ? true : false\n end",
"def closest_string_in_front(key_string, sub_string)\n\n\t\tpositions = []\n\t\tlast_pos = nil\n\t\tmy_string = \" \" + to_str\n\t\tkey_pos = my_string.index(key_string)\n\t\tif key_pos.nil?\n\t\t\t#puts \"WARNING: closest_string_in_front PASSED A string THAT DID NOT INCLUDE key_string\"\n\t\t\treturn nil\n\t\telse\n\t\t\tmy_string = my_string.slice(0..key_pos+1)\n\t\tend\n\n\t\twhile (last_pos = my_string.index(sub_string, (last_pos ? last_pos + 1 : 0)))\n\t\t\tpositions << last_pos\n\t\tend\n\n\t\tif positions != []\n\t\t\treturn_string = my_string[key_pos-positions.map{|p| (p-key_pos).abs}.min..key_pos-1]\n\t\t\treturn return_string.match(sub_string).to_s\n\t\telse\n\t\t\treturn nil\n\t\tend\n\tend",
"def check_inclusion(s1, s2)\n\treturn false if s1 == '' || s2 == ''\n\tk = s1.size\n\tn = s2.size\n h1 = {}\n # Store all elements of string p in hash h1.\n for i in 0..k-1 do\n \tif h1[s1[i]]\n \t\th1[s1[i]] = h1[s1[i]] + 1\n \telse\n \t\th1[s1[i]] = 1\n \tend\n end\n h2 = {}\n j = 0\n # Traverse each substring of length k.\n # Store elements of substring upto k length in hash h2.\n for i in 0..n-k do \t\n \twhile j < i+k do\n \t\tif h2[s2[j]]\n \t\t\th2[s2[j]] = h2[s2[j]]+1\n \t\telse\n \t\t\th2[s2[j]] = 1\t\n \t\tend\n \t\tj = j+1\n \tend\n \t# Return true if h1 equals to h2\n \treturn true if h1 == h2\n \t# After traversing, i will be i+1, so remove ith key from hash.\n \tif h2[s2[i]] > 1\n \t\th2[s2[i]] = h2[s2[i]] - 1\n \telse\n \t\th2.delete(s2[i])\n \tend\n end\n # Return false if all elements are traversed i.e permutation not found in string.\n return false\nend",
"def arr_in_phrase? (arr, string)\n\t#might be unefficient to recreate the reg each time, maybe better to return a regex?\n\treg = arr.map {|str| Regexp.escape(str)}\n\treg = /#{arr.join(\"|\")}/ \n\treturn reg === string\nend",
"def contains?(key)\n position = search(key)\n (key <=> @keys[position]) == 0\n end",
"def in_all_strings?(long_strings, short_string)\n # sliding window\n\n # check each long_string\n long_strings.each do |s|\n in_string = false\n n = s.length - short_string.length\n\n # check each substring of a long string\n # if equal to short string\n (0..n).each do |i|\n # if we encounter the shortstring in the substring\n # then we should move on to the next long string\n if s.slice(i, short_string.length) == short_string\n in_string = true\n break\n end\n end\n # if we didn't find a substring in this long string\n # then we know that not all substrings are in the long string\n if in_string == false\n return false\n end\n end\n\n true\nend",
"def contains_char(s1, s2)\n i = 0\n output = false\n while i < s1.length\n if s1[i] == s2\n output = true\n end\n i += 1\n end\n return output\nend",
"def key_word?(line)\n k_list = [\n /^Skills:.*/ ,\n /^Note:.*/ ,\n /^Talents:.*/ ,\n /^Trappings:.*/ ,\n /^Career Entries:.*/ ,\n /^Career Exits:.*/ ,\n /^Career.*/ ,\n /^\\*.*/ ,\n ]\n ret = false\n k_list.each do |reg|\n if (line =~ reg)\n ret = true\n end\n end\n return ret\nend",
"def include?(key)\n\t\tself.keywords.include?(key)\n\tend",
"def matches?(input_string)\n @word_list.include? input_string\n end",
"def contains?(key)\n @key_data.has_key?(key)\n end",
"def strCheck(arr, str)\n arr.each do |i|\n if str == i\n return true\n end\n end\n return false\nend",
"def solve(inp_str, bag_hash)\n\treturn bag_hash.select{ | k, v | v.include?(inp_str)}\nend",
"def hash_query(search_str, arr, search_key, return_key)\n\tif arr != nil\n\t\tarr.find {|hash| hash[search_key] == search_str}[return_key]\n\tend\nend",
"def include?(key)\n # Ensure a Ruby true is returned\n item_exists(key) == true\n end"
] |
[
"0.8987253",
"0.89137924",
"0.8889353",
"0.87755823",
"0.8721188",
"0.8523977",
"0.6659698",
"0.665448",
"0.63056636",
"0.627746",
"0.62403536",
"0.6211641",
"0.6196496",
"0.619202",
"0.6184977",
"0.61618227",
"0.61611706",
"0.6121738",
"0.6109552",
"0.6103083",
"0.6071483",
"0.60188514",
"0.5992428",
"0.5987991",
"0.5987991",
"0.5982328",
"0.5964703",
"0.59597427",
"0.5937266",
"0.5905885",
"0.5892524",
"0.58639663",
"0.5841143",
"0.5827178",
"0.580414",
"0.580414",
"0.58020014",
"0.57963747",
"0.5791033",
"0.5761014",
"0.5742591",
"0.5737938",
"0.570335",
"0.56855905",
"0.5679318",
"0.5663783",
"0.5653432",
"0.5653228",
"0.56409323",
"0.56216407",
"0.5620696",
"0.56156015",
"0.5587742",
"0.5574452",
"0.55666643",
"0.55597687",
"0.555916",
"0.55450463",
"0.5529957",
"0.5514562",
"0.55141044",
"0.55138075",
"0.55137235",
"0.5483263",
"0.5469395",
"0.5456595",
"0.5442454",
"0.544074",
"0.54396456",
"0.5434326",
"0.54302216",
"0.5420236",
"0.5419438",
"0.5406823",
"0.54066527",
"0.53980696",
"0.53965336",
"0.53946424",
"0.5394637",
"0.5392003",
"0.5379489",
"0.5372888",
"0.537036",
"0.5367675",
"0.5359877",
"0.53573817",
"0.5352962",
"0.5352927",
"0.5331451",
"0.5325817",
"0.5321797",
"0.53130156",
"0.5298509",
"0.52966833",
"0.5292305",
"0.52866167",
"0.5282966",
"0.5278961"
] |
0.8242099
|
8
|
Write a recursive method that returns the first "num" factorial numbers in ascending order. Note that the 1st factorial number is 0!, which equals 1. The 2nd factorial is 1!, the 3rd factorial is 2!, etc.
|
def factorials_rec(num)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def first_factorial(num)\n if num < 2\n return 1\n else\n return num * first_factorial(num - 1)\n end\nend",
"def FirstFactorial(num)\n if num > 1\n return num*(FirstFactorial(num-1)) \n end\n return num \nend",
"def factorialrecursion num\n\tif num < 0\n\t\tnil\n\tend\n\t\n\tif num <= 1\n\t\t1\n\t\telse\n\t\t\tnum * factorial(num - 1)\n\t\tend\n\tend",
"def factorial(num)\n\tif num <= 1\n\t\treturn 1\n\telse\n\t\tnum * factorial(num - 1)\n\tend\nend",
"def FirstFactorial(num, a = 1)\n if (num == 1)\n return a\n end\n\n return FirstFactorial(num-1, a*num)\n \nend",
"def FirstFactorial(num)\n result = 1\n \n while num > 1\n result *= num\n num -= 1\n end\n \n return result\nend",
"def getFactorial(num)\n if (num == 1)\n sum = 1\n else\n sum = getFactorial(num-1)*num\n end\n return sum\nend",
"def factorial(num)\n if num == 1\n 1\n else\n num * factorial(num - 1)\n end\nend",
"def factorial(num)\n if num <= 1\n 1\n else\n num * factorial(num-1)\n end\nend",
"def factorial(num)\n if num < 2 \n return 1\n end \n fac = num * factorial(num - 1)\nend",
"def factorial num\n\tfactorial = 1\n\twhile num > 0\n\t\tfactorial *= num\n\t\tnum -= 1\n\tend\n\treturn factorial\nend",
"def factorial_recursive(num)\n if num == 0\n 1\n else \n num * factorial_recursive(num-1)\n \n # 7 * 6 = 42\n # 42 * 5 = 210\n # 210 * 4 = 840\n # 840 * 3 = 2520\n # 2520 *2 = 5040\n # 5040* 1 = 5040\n end\nend",
"def FirstFactorial(num)\n product = 1\n for x in num..1\n product *= x\n end\n return product\nend",
"def factorial(num)\n\tfactor = 1\n\tfact = [0]\n\tif num == 0\n\t\tfactor\n\telse\n\t\tnum.times do |i|\n\t\t\tfact[i] = i+1\n\t\tend\n\t\tp fact\n\t\t(num-1).times do |i|\n\t\t\tfactor = factor * fact[i+1]\n\t\tend\n\t\tfactor\n\tend\nend",
"def factorial(num)\n if num == 0\n 1\n else\n num * factorial(num - 1)\n end\nend",
"def FirstFactorial(num)\n (1..num).reduce(:*) || 1\nend",
"def factorial(num)\n if num > 0\n #until num == 1\n return num * factorial(num - 1)\n else\n return 1\n end\nend",
"def first_factorial(num)\r\n (1..num).reduce(&:*)\r\nend",
"def factorials_rec(num)\n if num == 1\n [1]\n else\n facs = factorials_rec(num - 1)\n facs << facs.last * (num - 1)\n facs\n end\nend",
"def factorials_rec(num)\n if num == 1\n [1]\n else\n facs = factorials_rec(num - 1)\n facs << facs.last * (num - 1)\n facs\n end\nend",
"def factorials_rec(num)\n if num == 1\n [1]\n else\n facs = factorials_rec(num - 1)\n facs << facs.last * (num - 1)\n facs\n end\nend",
"def factorial(num)\n return 1 if num == 1\n num * factorial(num - 1)\nend",
"def factorial(num)\n\treturn nil if num < 0\n\treturn 1 if num.equal?(0)\n\ti = 1\n\ttotal = 1\n\tnum.times do\n\t\ttotal *= i\n\t\ti += 1\n\tend\n\treturn total\nend",
"def factorial(num)\n\tif num != 1\n\tputs num \n\n\tnum * factorial(num-1)\n\telse \n\treturn 1\n\tend\t\n\n\nend",
"def factorial_recursive(num = 0)\n # this is a guard clause\n return \"Can not calculate factorial of a negative number\" if num < 0\n\n if num <= 1\n 1 # this is our base case\n else\n num * factorial_recursive(num - 1) # this is where the recursion happens\n end\nend",
"def factorials_rec(num)\n if num == 1\n [1]\n else\n factorial = factorials_rec(num - 1)\n factorial << (num - 1) * factorial[-1]\n end\nend",
"def factorials_rec(num)\n if num == 1\n return [1]\n else\n facs = factorials_rec(num - 1)\n facs << facs.last * (num - 1)\n facs\n end\nend",
"def factorial(num)\n if num == 0\n return 1\n else\n value = num - 1\n until value == 0\n num *= value\n value -= 1\n end\n return num\n end\nend",
"def factorial(num)\n raise ArgumentError if num < 0\n if num == 1 || num == 0 # base case\n return 1\n else\n return num * factorial(num - 1)\n end\nend",
"def factorials_rec(num)\n return [1,1].take(num) if num < 2\n facts = factorials_rec(num - 1)\n facts + [facts.last * (num - 1)]\nend",
"def recursive_fac(num)\n return num if num == 1\n tail_rec(num - 1) * num\nend",
"def factorials_rec(num)\n return [1] if num <= 1\n fact = factorials_rec(num-1)\n fact << (num-1) * fact.last\nend",
"def factorial(num)\n if num == 0 || num == 1\n return 1\n else\n arr = []\n (1..num).each do |x|\n arr.push(x)\n end\n until arr.length == 2 do\n arr.push(arr[-1] * arr[-2])\n arr.delete_at(-2)\n arr.delete_at(-2)\n end\n return arr[1]\n end\nend",
"def factorials_rec(num)\n return [1] if num == 1\n prev = factorials_rec(num-1)\n prev + [prev.last * (num-1)]\nend",
"def factorials_rec(num)\n return [1] if num <= 1\n res = factorials_rec(num-1)\n res.concat([(num-1)*res[-1]])\nend",
"def factorials_rec(num)\n\n return [1] if num == 1\n\n prev_facs = factorials_rec(num - 1)\n prev_facs << (num - 1) * prev_facs[-1]\nend",
"def factorial(num)\n return 1 if num.zero?\n\n num * factorial(num - 1)\nend",
"def factorials_rec(num)\n return [1] if num == 1\n facs = factorials_rec(num - 1)\n facs << facs.last * (num - 1)\n facs\nend",
"def factorials_rec(num)\n return [1] if num == 1\n facs = factorials_rec(num - 1)\n facs << facs[-1] * (num - 1)\nend",
"def factorials_rec(num)\n return [1] if num == 1\n factorials_rec(num-1) + [(1...num).to_a.reduce(:*)]\nend",
"def factorials_rec(num)\n return [1] if num == 1\n previous_factorials = factorials_rec(num-1)\n next_factorial = [previous_factorials.last * (num-1)]\n previous_factorials + next_factorial\nend",
"def factorial(number)\n if number == 0 #(limit)\n 1\n else\n number * factorial(number-1) #first number * number - 1 but the factorial calls the same method on the number - 1\n end\nend",
"def factorials_rec(num)\n return [1] if num == 1\n\n facs = factorial_rec(num - 1)\n facs << facs.last * num\nend",
"def factorials_rec(num)\n return [] if num == 0\n return [1] if num == 1\n prev = factorials_rec(num - 1)\n prev + [prev.last * (num - 1)]\nend",
"def factorial(number)\n if number == 0\n return 1\n elsif number == 1\n return 1\n else\n number*factorial(number-1)\n end\nend",
"def factorials_rec(num)\n return [1] if num == 1\n\n facs = factorials_rec(num - 1)\n facs << facs.last * num\n\n facs\nend",
"def factorials_rec(num)\n return [1] if num == 1\n prev = factorials_rec(num - 1)\n prev << (num - 1) * prev[-1]\nend",
"def factorials_rec(num)\n return [1] if num == 1\n\n factorials_rec(num-1) << factorials_rec(num-1).last * (num - 1)\nend",
"def factorials_rec(num)\n if num == 1\n [num]\n else\n factorials = factorials_rec(num - 1)\n factorials << factorials.last * (num - 1)\n factorials\n end\nend",
"def factorials_rec(num)\n return [1] if num == 0\n num.times do |num|\n facs = factorials_rec(num-1)\n facs << num * facs.last\n facs\n end\nend",
"def factorial(num)\n\tproduct = 1\n\twhile num > 1\n\t\tproduct = product*num\n\t\tnum -= 1\n\tend\n\tproduct\nend",
"def factorials_rec(num)\n return [1] if num == 1\n fact = factorials_rec(num-1)\n fact << fact.length * fact[-1]\nend",
"def iterative_factorial(num)\n if num < 0 || !is_integer?(num)\n return Float::NAN\n elsif num == 0 || num==1\n 1\n else\n (1..num).inject(:*) || 1\n end\nend",
"def factorial(number)\n if number == 0\n \treturn 1\n elsif number == 1\n \treturn 1\n end\n i=number-1\n f=number*i\n while i > 1\n \ti=i-1\n \tf=f*i\n end\n return f\nend",
"def factorial(number)\n if number == 1\n return 1\n else\n return number * factorial(number - 1)\n end\nend",
"def factorials_rec(num)\n #6 == [0!, 1!, 2!, 3!, 4!, 5!]\n return [1] if num == 1\n\n factorials_rec(num-1) + [(num-1) * factorials_rec(num-1).last]\nend",
"def factorials_rec(num)\n if num == 1\n [1]\n else\n recs = factorials_rec(num - 1)\n recs << (num - 1) * recs.last\n end\nend",
"def factorial_rec(num)\n return [1] if num == 1\n res = factorial_rec(num - 1)\n res << (num - 1) * res[-1]\nend",
"def factorials_rec(num)\n return [1] if num <= 1\n\n result = factorials_rec(num-1)\n result << (num-1) * result[-1]\n\nend",
"def factorial(number)\n\treturn 1 if number == 1 \n\treturn number * factorial(number-1)\nend",
"def factorials_rec(num)\n return [1] if num == 0\n return [1] if num == 1\n \n prev = factorials_rec(num-1)\n prev << (num-1) * prev[-1]\nend",
"def factorials_rec(num)\n return [1] if num == 1\n prev = factorials_rec(num - 1)\n prev << prev[-1] * (num - 1)\n prev\nend",
"def FirstFactorial(num)\n arr = [*1..num]\n i = 0\n answer = 1\n while i < arr.length\n answer *= arr[i]\n i += 1\n end\nanswer\nend",
"def factorial(number)\n if number == 0 \n return 1\n elsif number > 1 \n return number * factorial(number - 1)\n else\n return number\n end\nend",
"def factorials_rec(num)\n return [1] if num==1\n return [1,1] if num==2\n factorials_rec(num-1) + [(num-1) * factorials_rec(num-1).last]\nend",
"def factorial(num)\n num == 1 ? num * 1 : num * factorial(num - 1)\nend",
"def iterative_factorial(num)\n\tif num < 0\n\t\treturn Float::NAN # a constant meaning \"Not a Number\"\n\tend\n\tmemo = 1\n\t(1..num).each do |i|\n\t\tmemo = memo*i\n\tend\n\tmemo\nend",
"def factorials_rec(num)\r\n return [1,1].take(num) if num < 3\r\n factorials = factorials_rec(num - 1)\r\n factorials << factorials.last * (num -1)\r\nend",
"def factorials_rec(num)\n return [1] if num == 1\n facs = factorials_rec(num - 1)\n facs << facs.last * num\nend",
"def factorials_rec(num)\n return [1] if num == 1\n\n facs = factorials_rec(num - 1)\n facs << facs.last * (num - 1)\n facs\n\n\nend",
"def recursive_factorial(n)\n return 1 if n < 1\n\n n * recursive_factorial(n - 1)\nend",
"def factorials_rec(num)\n return [1] if num == 1\n previous_factorial = factorials_rec(num - 1)\n last_fac = previous_factorial.last\n previous_factorial + [last_fac * (num - 1)]\nend",
"def factorial(number)\n if number < 0\n return nil\n elsif number <= 1\n 1\n else\n number * factorial(number-1)\n end\nend",
"def factorial(number)\n if number == 0\n return 1\n else\n number*factorial(number-1)\n end\n\nend",
"def getFactorial(number)\n factorial = 1\n if number > 0\n for i in 1..number\n factorial *= i\n end\n end\n return factorial\n end",
"def factorial_of num \n\t(2..num).inject(1) {|product, x| product * x }\nend",
"def iterative_factorial(num)\n return Float::NAN if !num.is_a?(Integer) || num < 0\n fact = 1\n (1..num).each {|i| fact *= i}\n fact\nend",
"def factorial(factor)\n return 1 if factor == 1\n factor*factorial(factor-1)\nend",
"def Factorial(num)\ncurrent = num\nproduct = 1\n\n\twhile current > 0\n\t\tproduct = product * current\n\t\tcurrent -= 1\n\tend\n\tproduct\nend",
"def factorial num\n if num < 0\n return 'You can\\'t take the factorial of a negative number!'\n end\n if num <= 1\n 1\n else\n num * factorial(num-1)\n end\nend",
"def factorials_rec(num)\n return [1] if num == 1\n\n facts = factorials_rec(num-1)\n\n facts << facts.last * (num - 1)\n\n facts\nend",
"def factorial(number)\n return 1 if number <= 1\n number * factorial(number - 1)\nend",
"def factorials_rec(num)\n return 1 if num == 0 \n return [1] if num == 1\n fact = [1]\n\n fact << [(fact[-1] * factorials_rec(num-1))]\n# (2) \n# 4 * fact_rc(3) 2\n# 3 * fact_rc(2) 6\n# 2 * fact_rc(1) 2\n# 1 * fact(rc 0 )\nend",
"def iterative_factorial(num)\n\tif num < 0 || !(is_integer?(num))\n\t\tFloat::NAN\n\telsif num == (0 || 1)\n\t\t1\n\telse\n\t\tnum.downto(1).reduce(:*)\n\tend\nend",
"def factorials_rec(num)\n return [] if num == 0\n factorials = []\n\n assessment_passer = factorials_rec(0)\n\n idx = 0\n while idx < num\n factorials << factorial_num(idx)\n idx += 1\n end\n\n factorials\nend",
"def factorials_rec(num)\n answer = []\n return [1] if num == 1\n return [1, 1] if num == 2\n next_num = (num - 1) * factorials_rec(num - 1)[-1]\n answer << next_num\n #answer\nend",
"def factorial(num)\n\tproduct = num\n \titer = num-1\n \twhile(iter>1)\n \tproduct *=iter\n \titer-= 1\n end\n return product\nend",
"def factorial(number)\n # Your code goes here\n if(number > 1)\n number * factorial(number-1)\n else\n 1\n end\nend",
"def factorial(num)\n if num < 0\n return \"You can't take the factorial of a negative number.\"\n end\n\n if num <= 1\n 1\n else\n num * factorial(num - 1)\n end\nend",
"def factorial( n )\n if (n <= 1)\n return 1\n else\n return n*factorial( n-1 ).to_i\n end\nend",
"def factorials_rec(num)\n return 'error' if num < 0\n return [1] if num == 1\n return [1, 1] if num == 2\n fac = factorials_rec(num - 1)\n fac << fac.last * (num - 1)\n fac\n\nend",
"def factorial_1(num)\n factorial_count = 1\n while num > 0\n factorial_count *= num\n num -= 1\n end\n factorial_count\nend",
"def factorial(number)\n if number == 0\n return 1\n else\n final_factorial = 1\n\n for x in 1..number\n final_factorial = final_factorial * x\n end\n\n return final_factorial\n end\nend",
"def factorials_rec(num)\n return [1,1] if num == 2\n return [1] if num == 1\n\n factorial_array = factorials_rec(num-1)\n factorials = factorial_array + [(num-1) * factorial_array.last]\n factorials\nend",
"def factorial((number))\nif number == 0\n return 1\n else\n result = 1\n while number > 1\n result = result * number\n number -= 1\n end\nend\n return result\nend",
"def factorial(number)\n\ttotal = 1\n\tif number == 0\n\t\treturn 1\n\telse\n\t\twhile number > 1\n\t\t\ttotal *= number\n\t\t\tnumber -= 1\n\t\tend\n\t\treturn total\n\tend\nend",
"def factorial(number)\n i = number\n total = number\n if number == 0 || number == 1\n return 1\n else\n while i > 1\n total=total * (i - 1)\n i -= 1\n end\n end\n return total\nend",
"def factorial(number)\n if number == 0\n return 1\n else\n i = number-1\n while i >= 1\n number = number * i\n i = i - 1\n end\n return number\n end\nend",
"def factorial(number)\n if number == 0\n return 1\n else\n i = number-1\n while i >= 1\n number = number * i\n i = i - 1\n end\n return number\n end\nend",
"def factorial(num)\n product = 1\n\n i = 2 # 1 * 2 = 2, so just start from 2 and skip 1 as it doesn't matter\n while i <= num\n product *= i\n\n i += 1\n end\n\n return product\nend",
"def factorial(number)\n if number <= 1\n return 1\n else\n result = 1\n (1..number).each {|x| result = result * x}\n return result\n end\nend"
] |
[
"0.8556982",
"0.8358095",
"0.81390655",
"0.8106482",
"0.80206656",
"0.7777546",
"0.776495",
"0.7758426",
"0.7750472",
"0.7726955",
"0.771697",
"0.77163166",
"0.7710064",
"0.77042234",
"0.77035886",
"0.769294",
"0.7690432",
"0.76596737",
"0.7648177",
"0.7648177",
"0.7648177",
"0.76325595",
"0.7626627",
"0.7625657",
"0.7619287",
"0.75824845",
"0.7579711",
"0.75371695",
"0.752104",
"0.7515669",
"0.75141215",
"0.7495317",
"0.74814105",
"0.74806863",
"0.747407",
"0.7472483",
"0.7469447",
"0.7459102",
"0.74578005",
"0.7457616",
"0.74481225",
"0.7444797",
"0.74395293",
"0.7423036",
"0.7422266",
"0.74177855",
"0.7417036",
"0.74072826",
"0.740432",
"0.73906523",
"0.73890495",
"0.738526",
"0.73832166",
"0.7382355",
"0.73780394",
"0.7371547",
"0.7369004",
"0.7368838",
"0.7364911",
"0.7354459",
"0.7353708",
"0.73496115",
"0.73469",
"0.73339844",
"0.73280394",
"0.7326564",
"0.7321405",
"0.73188674",
"0.73114616",
"0.7307825",
"0.7301019",
"0.7294575",
"0.7286531",
"0.7271784",
"0.7255031",
"0.72514236",
"0.72490674",
"0.72470444",
"0.7244832",
"0.72381234",
"0.7226827",
"0.7222548",
"0.72212166",
"0.72040176",
"0.7195626",
"0.71888626",
"0.7186546",
"0.71828896",
"0.7177757",
"0.71748185",
"0.71743804",
"0.71720374",
"0.7161997",
"0.71601564",
"0.7157197",
"0.71563643",
"0.71529794",
"0.7150835",
"0.7150835",
"0.7146986",
"0.7138756"
] |
0.0
|
-1
|
Write a method that finds the sum of the first n fibonacci numbers recursively. Assume n > 0.
|
def fibs_sum(n)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def fibs_sum(n)\n return 0 if n == 0\n return 1 if n == 1\n\n fibs_sum(n - 1) + fibs_sum(n - 2) + 1\nend",
"def fibs_sum(n)\n return 0 if n == 0\n return 1 if n == 1\n\n fibs_sum(n-1) + fibs_sum(n-2) + 1\nend",
"def fibs_sum(n)\n return 0 if n == 0\n return 1 if n == 1\n\n fibs_sum(n-1) + fibs_sum(n-2) + 1\nend",
"def fibs_sum(n)\n return 0 if n == 0\n return 1 if n == 1\n\n fibs_sum(n-1) + fibs_sum(n-2) + 1\nend",
"def fibs_sum(n)\n return 0 if n == 0\n return 1 if n == 1\n\n fibs_sum(n-1) + fibs_sum(n-2) + 1\nend",
"def fibs_sum(n)\n return 1 if n == 1 || n == 2\n sum = 0\n sum += (fibs_sum(n - 1) + fibs_sum(n - 2))\n \n \nend",
"def fib_sum(n)\n return n if ( 0..1 ).include? n\n ( fib_sum( n - 1 ) + fib_sum( n - 2 ) )\nend",
"def fibs_sum(n) # my version\n return 1 if n == 1\n return 2 if n == 2\n\n current = single_fib(n)\n current += fibs_sum(n - 1)\nend",
"def fibonacciRecursive(n)\n\tif n <= 1\n\t\treturn n\n\telse\n\t\treturn fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2)\n\tend\nend",
"def fibs(n)\n return n if n <= 1\n fibs(n - 1) + fibs(n - 2)\nend",
"def fibonacci_recursive(n)\n if n == 0 || n == 1\n return n\n end\n # ex n = 5: fib(4) + fib(3) ==> fib(3) + fib(2) ==> fib(2) + 1 =\n return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)\nend",
"def fib(n)\n if n == 0 || n == 1\n return n\n else\n fib(n - 1) + fib(n - 2)\n end\n end",
"def fibonacci_recursive n\n return n if n < 2\n fibonacci_recursive(n-1) + fibonacci_recursive(n-2)\nend",
"def sum_of_fib(n)\n return fib(n+2)-1;\nend",
"def fibo_finder(n)\n if n <= 1\n \tn\n else\n fibo_finder(n-1) + fibo_finder(n-2)\n end\nend",
"def fibo_finder(n) \n if n == 0\n return 0\n elsif n ==1\n return 1\n else\n return (fibo_finder(n - 1) + fibo_finder(n - 2))\n end\nend",
"def find_fib_nth(n)\n if n == 0\n 1\n elsif n == 1\n 1\n else\n return (find_fib_nth(n - 2) + find_fib_nth(n - 1))\n end\nend",
"def recursive_fib n\n return 1 if n == 1 || n == 2\n recursive_fib(n-1) + recursive_fib(n-2)\nend",
"def fibonacci(n)\n\tif n == 0 || n == 1\n\t\treturn 1\n\telse\n\t\treturn fibonacci(n-1) + fibonacci(n-2)\n\tend\nend",
"def recursive_fibonacci(n)\n if (n == 1)\n return 0\n elsif (n == 2 || n == 3)\n return 1\n end\n return recursive_fibonacci(n - 2) + recursive_fibonacci(n - 1)\n end",
"def fibs_rec(n)\n n == 0 || n == 1 ? n : fibs_rec(n-1) + fibs_rec(n-2)\n fibs(n)\nend",
"def fibonacci(n)\n\treturn 0 if n == 0\n\treturn 1 if n == 1\n\tfibonacci(n-1) + fibonacci(n-2)\nend",
"def fib(n)\n if n == 0 || n == 1\n return n\n else\n fib(n-1) + fib(n-2)\n end\nend",
"def fib(n)\n return 0 if n == 0\n return 1 if n == 1\n\n return fib(n-1) + fib(n-2)\nend",
"def fib(n)\n return 0 if n <= 0\n return 1 if n == 1\n\n fib(n - 1) + fib(n - 2)\nend",
"def nth_fibonacci(n) \n if n == 1\n return 0\n elsif n == 2\n return 1\n end\n return nth_fibonacci(n-1) + nth_fibonacci(n-2)\nend",
"def fibonacci(n)\n return 0 if n == 0\n return 1 if n == 1\n\n fibonacci(n - 1) + fibonacci(n - 2)\nend",
"def fibonacci(n)\n if n <= 1\n return n\n else\n return fibonacci(n - 1) + fibonacci(n - 2)\n end\nend",
"def fibonacci(n)\n return n if n == 1 || n == 0 \n fibonacci(n - 1) + fibonacci(n - 2)\nend",
"def fibonacci(n)\n return n if (0..1).include? n\n (fibonacci(n - 1) + fibonacci(n - 2))\nend",
"def fib(n)\n return 0 if n == 0\n return 1 if n == 1\n \n\n fib(n - 1) + fib(n - 2)\nend",
"def fib_sum(n)\n #generate up to n recursive\n fib = [0, 1]\n i = 2\n while i < n\n fib << fib[i - 2] + fib[i - 1]\n i += 1\n end\n p fib\n # sum = 0\n accumulator = fib.first\n while !fib.empty?\n accumulator += fib.pop\n end\n #iterate and sum through the stack\n return accumulator\nend",
"def fib(n)\n return n if (0..1).include? n\n fib(n-1) + fib(n-2)\nend",
"def fibonacci(n)\n return n unless n > 1\n fibonacci(n -1) + fibonacci(n -2)\nend",
"def fib_basic(n)\n if (0..1).include? n\n return n\n else\n (fib_basic(n - 1) + fib_basic(n - 2))\n end\nend",
"def fibs_rec(n)\n return n if n <= 1\n return fibs_rec(n-2) + fibs_rec(n-1)\nend",
"def fibonacci(n)\n if n == 0 or n == 1\n return n\n else\n return fibonacci(n - 1) + fibonacci(n - 2)\n end\nend",
"def fib(n)\n return 1 if n == 2\n return 0 if n == 1\n\n fib(n-1) + fib(n-2)\nend",
"def fibonacci(n)\r\n if n == 0\r\n return 0\r\n elsif n == 1\r\n return 1\r\n else\r\n return fibonacci(n-1) + fibonacci(n-2)\r\n end\r\nend",
"def fibonacci( n )\n return n if ( 0..1 ).include? n\n ( fibonacci( n - 1 ) + fibonacci( n - 2 ) )\nend",
"def fibonacci( n )\n return n if ( 0..1 ).include? n\n ( fibonacci( n - 1 ) + fibonacci( n - 2 ) )\nend",
"def fibonacci( n )\n return n if ( 0..1 ).include? n\n ( fibonacci( n - 1 ) + fibonacci( n - 2 ) )\nend",
"def fib(n)\n if n == 1 || n == 2\n return 1\n end\n return fib(n-1) + fib(n-2)\nend",
"def fib(n)\n if n == 1 || n == 2\n return 1\n end\n return fib(n-1) + fib(n-2)\nend",
"def fib(n)\n return 1 if n == 1 || n == 2\n fib(n-1) + fib(n-2)\nend",
"def fib(n)\n if n == 1 || n == 2\n return 1\n end\n return fib(n - 1) + fib(n - 2)\nend",
"def fib_rec(n)\n return 0 if n == 1\n return 1 if n == 2\n fib_rec(n - 1) + fib_rec(n - 2)\nend",
"def fibs_rec(n)\n\treturn n if n <= 1\n\tfibs_rec(n-1) + fibs_rec(n-2)\nend",
"def fibonacci(n)\n return 0 if n == 1\n return 1 if n == 2\n return fibonacci(n-1)+fibonacci(n-2)\nend",
"def fib(n)\n return n if n <= 1\n fib(n-1) + fib(n-2)\nend",
"def fibonacci(n)\n return 1 if n == 1\n return 1 if n == 2\n fibonacci(n - 1) + fibonacci(n - 2)\nend",
"def fibo_n n\n\treturn n if (0..1).include? n\n\tfibo_n(n-2) + fibo_n(n-1)\nend",
"def fib(n)\n return nil if n < 1\n return 1 if n == 1 || n == 2\n fib(n-1) + fib(n-2)\nend",
"def fibonacci(n)\n return 1 if n == 1 || n == 2\n fibonacci(n - 1) + fibonacci(n - 2)\nend",
"def fibonacci(n)\n return 1 if n == 1 || n == 2\n fibonacci(n - 1) + fibonacci(n - 2)\nend",
"def fib(n)\n if (n <= 1) \n return n;\n else\n return fib(n-1)+fib(n-2);\n end\nend",
"def fibonacciR( n )\r\n return n if n <= 1\r\n fibonacciR( n - 1) + fibonacciR( n - 2)\r\nend",
"def fibonacci(n)\n raise ArgumentError, \"n cannot be less than 0\" if n < 0\n return 0 if n == 0 \n\n old_sum, new_sum = 0, 1\n return fib_helper(old_sum, new_sum, n)\nend",
"def fibonacci(n)\n return 1 if n <= 2\n fibonacci(n - 2) + fibonacci(n - 1)\nend",
"def fibonacci(n)\n if n == 0\n 1\n elsif n == 1\n 1\n else\n fibonacci(n-2) + fibonacci(n-1)\n end\nend",
"def fibonnaci(n)\n if n == 1 || n == 2\n 1\n else\n fibonnaci(n - 1) + fibonnaci(n - 2)\n end\nend",
"def fibonacci(n)\n return 1 if n <= 2\n fibonacci(n - 1) + fibonacci(n - 2)\nend",
"def fibonacci(n)\n return 1 if n <= 2\n fibonacci(n - 1) + fibonacci(n - 2)\nend",
"def fibonacci(n)\n if n < 2\n return n\n else\n fibonacci(n-1) + fibonacci(n-2)\n end\nend",
"def recursive_fib(n)\n if n<2\n return n\n else\n return (recursive_fib(n-1)+recursive_fib(n-2))\n end \nend",
"def fib(n)\n return 1 if n <= 2\n fib(n-1) + fib(n-2)\nend",
"def fibonacci(n)\n return 1 if n == 1 || n == 2\n\n fibonacci(n - 1) + fibonacci(n - 2)\nend",
"def fibonacci(n)\n return 1 if n <= 2\n fibonacci(n - 1 ) + fibonacci(n - 2)\nend",
"def fibonacci(n)\n if n == nil || n < 0\n raise ArgumentError\n elsif n == 0\n return 0\n elsif n == 1\n return 1\n end\n\n first = 0\n second = 1\n\n index = 1\n while index < n\n holder = first + second\n first = second\n second = holder\n index += 1\n end\n return holder\nend",
"def fib(n)\n return 1 if n <= 2\n fib(n - 1) + fib(n - 2)\nend",
"def fibonacci_recur(n)\n return 0 if n == 1\n return 1 if n == 2\n\n fibonacci_recur(n - 1) + fibonacci_recur(n - 2)\nend",
"def fibonacci(n)\n \n return n if n == 1\n \n if n > 2 \n fibonacci(n-1) + fibonacci(n-2)\n else\n fibonacci(n-1)\n end\nend",
"def fib n\n if n == 0\n 0\n elsif n == 1\n 1\n else\n fib(n-2) + fib(n-1)\n end\nend",
"def fibonacci(n)\n if n < 2\n return n\n else\n return fibonacci(n-1) + fibonacci(n-2)\n end\nend",
"def fib(n)\n\n if n == 1 or n == 2\n return 1\n else\n return fib(n-1) + fib(n-2)\n end\n\nend",
"def fib(n) \n if n == 0\n return 0\n else\n\tfib_0 = 0\n\tfib_1 = 1\n\t(1..(n-1)).each do \n\t\ttemp = fib_0\n\t\tfib_0 = fib_1\n\t\tfib_1 = temp + fib_1\n\t\t\n\tend\n\treturn fib_1\n end\nend",
"def fibonacci( n )\n return n if n <= 1 \n fibonacci( n - 1 ) + fibonacci( n - 2 ) \nend",
"def fib(n)\n return 0 if n == 0\n return 1 if n == 1\n return 1 if n == 2\n # return 2 if n == 3\n fib(n - 1) + fib(n - 2)\nend",
"def fibonacci(n)\n if n <= 2\n 1\n else\n fibonacci(n - 1) + fibonacci(n - 2)\n end\nend",
"def fib(n)\n return 0 if n == 0\n return 1 if n == 1\n\n [fib(n-1),fib(n-2)].reduce(:+)\n\t\nend",
"def fibonacci(n)\n if n == 1 || n == 2\n 1\n else\n fibonacci(n-1) + fibonacci(n-2)\n end\nend",
"def get_nth_fib(n)\n if n == 2\n return 1\n elsif n == 1\n return 0\n else\n return get_nth_fib(n - 1) + get_nth_fib(n - 2)\n end\nend",
"def fib_rec( n )\n $call_count += 1\n # Define the base case\n if n < 2\n return 1\n else\n # do the recursive calculation:\n return fib_rec( n - 1 ) + fib_rec( n - 2 )\n end\n\nend",
"def fib(n)\n if n == 1 || n == 2\n n\n else\n fib(n-1) + fib(n-2)\n end\nend",
"def fibs_rec(n)\n n <= 1 ? n : fibs_rec(n - 1) + fibs_rec(n - 2)\nend",
"def fib(n)\n return 0 if n < 0\n return n if n < 2\n return fib(n-1) + fib(n-2)\nend",
"def fibonacci(n)\n return 1 if n <= 2\n \n fibonacci(n - 1) + fibonacci(n - 2)\nend",
"def fib(n)\n if n < 2\n 1\n else\n fib(n-2) + fib(n-1)\n end\nend",
"def fib(n)\n if n == 0\n 0\n elsif n == 1 || n == 2\n 1\n else fib(n - 2) + fib(n - 1)\n end\nend",
"def fibonacci(n)\n if n < 2\n n\n else\n fibonacci(n - 1) + fibonacci(n - 2)\n end\nend",
"def get_nth_fib(n)\n if n == 0 || n == 1\n return 0\n elsif n == 2\n return 1\n else\n return get_nth_fib(n-1) + get_nth_fib(n-2)\n end\n\nend",
"def fibonacci n\n return n if n < 2\n fibonacci(n - 1) + fibonacci(n - 2)\nend",
"def fibs (n) #Non-recursive\n\n\t# n = number of Fibonacci sequence members.\n\t# 0, 1, 1, 2, 3, 5, 8, 13, ..\t\n\tfib_seq = []\n\t(0..n).each do |i|\n\t\tif i == 0\n\t\t\tfib_seq << 0\n\t\telsif i == 1\n\t\t\tfib_seq << 1\n\t\telse\n\t\t\tfib_seq << fib_seq[i-2] + fib_seq[i-1]\n\t\tend\n\tend\n\tfib_seq\nend",
"def fib(n)\n # your implementation here\n if n==0 then\n 1\n elsif n==1 then\n 1\n else \n fib(n-2) + fib(n-1)\n end\nend",
"def fib(n)\n return n if n < 2\n fib(n-1) + fib(n-2)\nend",
"def fibonacci(n)\n if n == nil || n < 0\n raise ArgumentError\n end\n# base cases are 0 and 1 (0th place is 0, 1st place is 1)\n if n < 2\n return n\n end\n\n counter = 1\n left = 0\n right = 1\n\n while counter < n\n sum = left + right\n left = right\n right = sum\n counter += 1\n end\n return sum\nend"
] |
[
"0.8981103",
"0.897471",
"0.897471",
"0.897471",
"0.897471",
"0.87479585",
"0.87065566",
"0.86833096",
"0.86395675",
"0.8585491",
"0.8540424",
"0.85397935",
"0.85042083",
"0.8501192",
"0.8486396",
"0.8470936",
"0.84407544",
"0.84372413",
"0.8435925",
"0.8426029",
"0.8420815",
"0.84188473",
"0.8410866",
"0.84104073",
"0.84059334",
"0.8390522",
"0.83890265",
"0.8376364",
"0.8374238",
"0.8373865",
"0.83629453",
"0.83603555",
"0.83474684",
"0.83413446",
"0.8339897",
"0.8338685",
"0.8338054",
"0.8335896",
"0.83350813",
"0.83327377",
"0.83327377",
"0.83327377",
"0.83247066",
"0.83247066",
"0.8318469",
"0.83110607",
"0.8308924",
"0.83076173",
"0.8296932",
"0.82954174",
"0.82950294",
"0.82922685",
"0.82921493",
"0.8290572",
"0.8290572",
"0.8287636",
"0.82841414",
"0.828054",
"0.82804006",
"0.8271546",
"0.8269859",
"0.8268296",
"0.8268296",
"0.82567936",
"0.82537615",
"0.8252077",
"0.8248075",
"0.8247271",
"0.82359415",
"0.8234635",
"0.8229937",
"0.8225679",
"0.82165915",
"0.82159793",
"0.82106936",
"0.8207811",
"0.8206275",
"0.8203501",
"0.8191999",
"0.8186684",
"0.81851995",
"0.81811005",
"0.81807595",
"0.81799763",
"0.8175478",
"0.8171926",
"0.8171543",
"0.81706357",
"0.8165208",
"0.8160703",
"0.8159551",
"0.81568307",
"0.81503665",
"0.81467295",
"0.81445897",
"0.81418544"
] |
0.82296354
|
75
|
Using recursion and the `is_a?` method, write an `Arraydeep_dup` method that will perform a "deep" duplication of the interior arrays.
|
def deep_dup(arr)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recursive_deep_dup(arr)\n # # does arr contain anymore arrays?\n # if !(arr.is_a? Array)\n # arr\n # else\n # arr[recursive_deep_dup(arr)].dup\n # arr_copy = arr.dup\n arr_copy = []\n arr.each do |sub|\n if sub.is_a? Array\n # sub_copy = sub.dup\n # p sub_copy\n # recursive_deep_dup(sub_copy)\n arr_copy << recursive_deep_dup(sub)\n else\n arr_copy << sub\n end\n end\n arr_copy\n # end\nend",
"def deep_dup(arr)\n # new_array = []\n # arr.each do |el|\n # new_array << (el.is_a?(Array) ? deep_dup(el) : el)\n # end\n # new_array\nend",
"def deep_dup(arr)\n copy = arr.dup\n copy.each_with_index do |el, i|\n copy[i] = deep_dup(el) if el.is_a?(Array)\n end\nend",
"def deep_dup(arr)\n deep = []\n arr.each do |el|\n if el.is_a?(Array)\n deep << deep_dup(el)\n else\n deep << el\n end\n end\n deep\nend",
"def recursive_deep_dup(arr)\n return arr unless arr.is_a?(Array)\n \n new_arr = []\n arr.each { |ele| new_arr << recursive_deep_dup(ele) }\n new_arr\nend",
"def deep_dup(arr)\n return arr if !arr.kind_of?(Array)\n new_arr = []\n arr.each do |ele|\n new_arr << deep_dup(ele)\n end\n new_arr\nend",
"def deep_dup(arr)\n if !arr.is_a?(Array)\n return arr\n end\n\n duped_arr = []\n arr.each do |el|\n duped_arr << deep_dup(el)\n end\n\n return duped_arr\nend",
"def deep_dup(arr)\n ans = []\n arr.each do |elt| #can use map\n if elt.is_a?(Array)\n ans.concat([deep_dup(elt)])\n else\n ans << elt\n end\n end\n ans\nend",
"def deep_dup(array_to_dup)\n [].tap do |duplicated_array|\n\n array_to_dup.each do |item|\n\n puts \"item is #{item}\"\n\n if item.is_a?(Array)\n duplicated_array << deep_dup(item)\n else\n duplicated_array << item\n end\n end\n end\nend",
"def deep_dup(arr)\n return [arr] if !arr.is_a?(Array)\n res = []\n arr.each do |a|\n res += deep_dup(a)\n end \n res \nend",
"def deep_dup(arr)\n new_arr = []\n arr.each do |el|\n if el.is_a?(Array)\n new_arr << deep_dup(el)\n else\n new_arr << el\n end\n end\n new_arr\nend",
"def deep_dup(arr)\n return arr.dup if arr.none?{|ele| ele.is_a?(Array)}\n temp = arr[0]\n if temp.is_a?(Array)\n [arr[0].dup] + deep_dup(arr[1..-1])\n else\n [arr[0]] + deep_dup(arr[1..-1])\n end\nend",
"def deep_dup(array)\n arr = []\n return [] if array.empty?\n return array if array.length == 1 \n array.each do |ele|\n if ele.is_a? Array \n arr << deep_dup(ele)\n else \n arr << ele\n end \n end \n arr \nend",
"def deep_dup(arr)\n return [] if arr.length.zero?\n\n innerArr = []\n\n arr.each do |el|\n if el.is_a?(Array)\n innerArr << deep_dup(el)\n else\n innerArr << el\n end\n end\n\n innerArr\nend",
"def deep_dup; end",
"def deep_dup(arr)\n arr.map{ |el| el.is_a?(Array) ? deep_dup(el) : el }\nend",
"def deep_dup(arr)\n arr.map{ |el| el.is_a?(Array) ? deep_dup(el) : el }\nend",
"def deep_dup(arr)\n arr.map{ |el| el.is_a?(Array) ? deep_dup(el) : el }\nend",
"def deep_dup(arr)\n duper_arr = arr.dup.map { |item| item * 1 }\nend",
"def deep_dup\n map(&:deep_dup)\n end",
"def rec_deep_dup(input)\n if !input.is_a?(Array)\n input\n else\n result = []\n input.each do |element|\n result << rec_deep_dup(element)\n end\n end\nend",
"def deep_dup(array)\n return array if !array.is_a?(Array)\n array.map do |x|\n deep_dup(x)\n end\n end",
"def deep_dup(arr)\n new_arr = []\n return arr if !arr.is_a?(Array)\n # return arr.each if arr.is_a?\n\n if arr.is_a?(Array)\n arr.each do |value|\n new_arr << deep_dup(value)\n end\n end\n new_arr\nend",
"def deep_dup(array)\n\n final_array = []\n return final_array if array.empty?\n\n array.each do |item|\n if item.is_a?(Array)\n final_array << deep_dup(item)\n else\n final_array << item\n end\n end\n\n final_array\nend",
"def deep_dup\n dup\n end",
"def deep_dup\n # noinspection RubyMismatchedReturnType\n dup\n end",
"def deep_dup(outer)\n return outer if outer.empty?\n\n temp = []\n outer.each do |element|\n if element.is_a?(Array)\n temp << deep_dup(Array.new(element))\n else\n temp << element\n end\n end\n\n temp\nend",
"def deep_dup(ary)\n ary.map { |sub_ary| sub_ary.map { |el| el } }\nend",
"def deeper_dup(arr)\n duper_deeper_arr = arr.dup.map do |item|\n if item.kind_of?(Array)\n deeper_dup(item)\n else\n item = item * 1\n end\n end\n duper_deeper_arr \nend",
"def deep_dup\n @map.map { |e| e.is_a?(Array) ? deep_dup(e) : ele }\n end",
"def deep_dup\n duplicable? ? dup : self\n end",
"def deep_dup\n duplicable? ? dup : self\n end",
"def deep_dup\n puts \"warning: #{self.class}: deep_dup not implement\"\n end",
"def deep_copy\n answer = []\n %w[1 2 3 4 5 6].each do |elem|\n answer << elem.dup\n end\n answer\nend",
"def deep_duplicate(object)\n case object\n when Array\n object.map { |item| deep_duplicate(item) }\n when Hash\n hash = object.dup\n hash.each_pair { |key, value| hash[key] = deep_duplicate(value) }\n hash\n else\n object\n end\n end",
"def deep_dup\n duped_board = []\n @board.each_with_index do |row, row_ind|\n duped_board << []\n\n row.each_with_index do |piece, column_ind|\n if piece.nil?\n duped_board[row_ind][column_ind] = nil\n next\n end\n\n new_piece = piece.dup\n duped_board[row_ind][column_ind] = new_piece\n new_piece.position = new_piece.position.dup\n end\n end\n self.class.new(duped_board)\n end",
"def deep_clone; end",
"def deep_dup(obj)\n if obj.is_a?(Hash)\n result = {}\n obj.each { |k,v| result[k] = deep_dup(v) }\n result\n elsif obj.is_a?(Array)\n obj.map { |el| deep_dup(el) }\n else\n dup_or_self(obj)\n end\n end",
"def deep_dup\n Marshal.load(Marshal.dump(self))\n end",
"def deep_dup\n new_board = Board.new(false)\n self.grid.each.with_index do |row, idx1|\n row.each.with_index do |cell, idx2|\n if self.grid[idx1][idx2].nil?\n next\n else\n new_board.grid[idx1][idx2] = self.grid[idx1][idx2].dup\n new_board.grid[idx1][idx2].board = new_board\n end\n end\n end\n new_board\n end",
"def initialize_dup( hooked_array_dup )\n \n super\n \n hooked_array_dup.internal_array = hooked_array_dup.internal_array.dup\n\n end",
"def deep_dup\n inject(self.class.new) do |new_hash, (key, value)|\n key = key.respond_to?(:deep_dup) ? key.deep_dup : key.dup?\n value = value.respond_to?(:deep_dup) ? value.deep_dup : value.dup?\n new_hash[key] = value\n new_hash\n end\n end",
"def deep_copy\n deep_transform_values(&method(:_deep_copy))\n end",
"def duplicate(array)\n array.uniq!\nend",
"def dup\n\n # duplicate self\n rta = super\n\n # iterate through array and dup each hash\n rta.each_with_index do |w_hash, index|\n\n # dup the hash at this index\n rta[index] = w_hash.dup\n\n # to be complete, also dup the key/values in the hash, in case another hash/array is nested\n w_hash.each_pair do |k, v|\n rta[index][k] = v.dup if v.is_a? Hash\n end\n end\n\n # now everything should have new object_id's\n rta\n end",
"def deep_dup\n new_board = Board.new(false)\n\n grid.flatten.compact.each do |piece|\n new_board[piece.pos.dup] =\n Piece.new(piece.pos.dup, new_board, piece.color)\n end\n\n new_board\n end",
"def deep_dup()\n # avoid validation by using a empty Hash for the intial value.\n c = Data.new({})\n c.instance_variable_set(:@root, deep_dup_value(@root))\n c\n end",
"def copy array\n array.map(&:clone)\nend",
"def duplicate(stuff)\n duplicated_stuff = []\n stuff = [*stuff] unless stuff.is_a?(Enumerable)\n stuff.each do |obj|\n duplicated_stuff << duplicate_object(obj)\n end\n duplicated_stuff.length == 1 ? duplicated_stuff[0] : duplicated_stuff\n end",
"def create_deep_copy(object)\n if object.is_a?(Array)\n return object.map { |e| create_deep_copy e }\n elsif object.is_a?(Hash)\n return {}.tap { |out| object.each { |k, v| out[create_deep_copy(k)] = create_deep_copy(v) unless k == :Parent } }\n elsif object.is_a?(String)\n return object.dup\n else\n return object # objects that aren't Strings, Arrays or Hashes (such as Symbols and Integers) won't be edited inplace.\n end\n end",
"def __deep_copy__\n self.class.new(aliases) do |copy|\n each do |entry|\n copy.push(entry.__deep_copy__)\n end\n end\n end",
"def duplicate\n @copy = self.deep_clone :no_duplicates => true, :never_clone => [:uuid, :updated_at,:created_at]\n @copy.static_page = self.static_page.duplicate\n self.sub_pages.each do |page| \n copy_of_page = page.duplicate\n @copy.sub_pages << copy_of_page\n copy_of_page.save\n end\n @copy.save\n @copy\n end",
"def dup(array)\n output = []\n i = 0\n while i < array.length\n output << array[i]\n i += 1\n end\n return output\nend",
"def deep_copy(obj); end",
"def deep_dup(hash)\n hash.each_with_object({}) do |(key, value), dup|\n dup[key] = value.is_a?(Hash) ? deep_dup(value) : value\n end\n end",
"def deep_copy(obj)\n if obj.is_a?(Hash)\n obj.inject({}) { |h, kv| h.merge(kv[0] => deep_copy(kv[1])) }\n elsif obj.is_a?(Array)\n obj.map { |el| deep_copy(el) }\n else\n obj\n end\n end",
"def deep_clone\n cloned = self.clone\n cloned.initialize_from_copy(self)\n cloned\n end",
"def deep_dup(value)\n return value if value.is_a?(DelayedEvaluator)\n\n visitor = lambda do |obj|\n obj = obj.dup rescue obj\n case obj\n when Hash\n obj.each { |k, v| obj[k] = visitor.call(v) }\n when Array\n obj.each_with_index { |v, i| obj[i] = visitor.call(v) }\n end\n obj\n end\n visitor.call(value)\n end",
"def dup(n=1)\n n.times{dps.concat(dps)}\n self\nend",
"def deep_clone(value)\n case value\n when Hash\n value.inject({}) do |result, kv|\n result[kv[0]] = deep_clone(kv[1])\n result\n end\n when Array\n value.inject([]) do |result, item|\n result << deep_clone(item)\n end\n else\n begin\n value.clone\n rescue TypeError\n value\n end\n end\n end",
"def duplicate\n dup.tap do |c|\n c.page = nil\n columns.each do |column|\n c.columns << column.duplicate\n end\n pictures.each do |picture|\n c.pictures << picture.duplicate\n end\n end\n end",
"def push_dup; end",
"def deepen_copy! copier, src\n @a = @a.map { | x | copier[x] }\n end",
"def deep_dup\n self.class.new(@parameters.deep_dup, @logging_context).tap do |duplicate|\n duplicate.permitted = @permitted\n end\n end",
"def two_array_copy(a)\n new_a = Array.new(a.length)\n new_a.each.dup\n return new_a\n end",
"def deep_clone\n Marshal.load(Marshal.dump(self))\n end",
"def deep_copy\n copy = dup\n copy.values = {}\n @values.each { |k, v| copy.values[k] = v.clone }\n copy\n end",
"def dup\n clone\n end",
"def deep_clone\n Marshal::load(Marshal.dump(self))\n end",
"def deep_clone\n return @deep_cloning_obj if @deep_cloning\n @deep_cloning_obj = clone\n @deep_cloning_obj.instance_variables.each do |var|\n val = @deep_cloning_obj.instance_variable_get(var)\n begin\n @deep_cloning = true\n val = val.deep_clone\n rescue TypeError, NoMethodError\n next\n ensure\n @deep_cloning = false\n end\n @deep_cloning_obj.instance_variable_set(var, val)\n end\n deep_cloning_obj = @deep_cloning_obj\n @deep_cloning_obj = nil\n deep_cloning_obj\n end",
"def clone_args(arg)\n if arg.is_a?(Array)\n arg.map {|sub_arg| clone_args(sub_arg)}\n elsif arg.is_a?(Hash)\n Hash[arg.map {|k, v| [clone_args(k), clone_args(v)]}]\n else\n arg # Some objects (e.g. symbol) can't be dup'd.\n end\n end",
"def __deep_copy__\n map { |value| value.__deep_copy__ }\n end",
"def dup\n self.class.new(\n self.class.attributes.keys.each_with_object({}) do |k, result|\n val = send(k)\n next if val.nil? || (val.respond_to?(:empty?) && val.empty?)\n\n result[k] = val.is_a?(Array) ? val.map(&:dup) : val.dup\n end\n )\n end",
"def duplicates_subarray2(arr)\n arr_srt = arr.sort {|a, b| a.ord <=> b.ord}\n new_arr = [[arr_srt[0]]]\n arr_srt.each_with_index do |elm, idx|\n next if idx == 0\n if new_arr[-1].include? elm\n new_arr[-1] << elm\n else\n new_arr << [elm]\n end\n end\n new_arr\nend",
"def dup #$\n a = pop\n push a\n push a\n end",
"def dup_args_alt(arr)\n arr == arr.uniq ? false : true\nend",
"def deep_copy\n return Matrix.new(\n @matrix.map{|row| row.map{|e| e.dup}},\n @rownames.map{|e| e.dup},\n @colnames.map{|e| e.dup}\n )\n end",
"def double_array(array)\n array.concat(array)\nend",
"def duplicate_sub_arrays(array)\n array_hash = {}\n \n array.each do |sub_array|\n sorted_array = sub_array.sort\n \n if array_hash[sorted_array]\n return true\n else\n array_hash[sorted_array] = true\n end\n \n end\n \n return false\nend",
"def flatten\n dup\n end",
"def deep_dup\n #new_ops = operands.map(&:dup)\n new_ops = operands.map do |op|\n op.deep_dup\n end\n graph_name = RDF::Node.intern(new_ops.hash)\n log_debug(\"formula\") {\"dup: #{self.graph_name} to #{graph_name}\"}\n self.class.new(*new_ops, **@options.merge(graph_name: graph_name, formulae: formulae))\n end",
"def create_copy(arr)\n copy = []\n arr.each { |e| copy.unshift(e) }\n copy\nend",
"def deep_clone; Marshal::load(Marshal.dump(self)); end",
"def clone_sexp(node)\n node.map do |part|\n # guess: arrays most common, then un-dupables, then dup-ables (strings only)\n if Array === part\n clone_sexp(part)\n elsif [Symbol, Fixnum, TrueClass, FalseClass, NilClass].any? { |k| k === part }\n part\n else\n part.dup\n end\n end\n end",
"def deep_copy(config)\n config.each_with_object({}) do |(key, value), hash|\n hash[key] = if value.is_a?(Array)\n value.dup\n else\n value\n end\n end\n end",
"def deep_copy\n Expression.new(name.deep_copy, value && value.deep_copy)\n end",
"def dedup_array(obj)\n if obj.is_a?(Hash)\n obj.map { |k, v| [k, dedup_array(v)] }.to_h\n elsif obj.is_a?(Array)\n obj.reverse.uniq { |h| h.respond_to?(:first) ? h.first : h }.reverse\n else obj\n end\nend",
"def deep_dup(index = {})\n return index[object_id] if index.key? object_id\n\n deep_dup_enumerable(self, index) { |new, k, v| new[k] = v }\n end",
"def dup\n duped_board = Board.new(false)\n\n figures.each do |piece|\n duped_board[piece.position] = piece.class.new(duped_board, piece.color, piece.position.dup)\n end\n\n duped_board\n end",
"def pack_consecutive_duplicates\n self.inject([[]]) do |array, current|\n if array[-1][-1] == current or array[-1][-1].nil?\n array[-1] << current\n else\n array << [current]\n end\n array\n end\n \n end",
"def optimize(**options)\n self.deep_dup\n end",
"def array_copy(a)\n n = []\n a.each do |i|\n n.push(i)\n end\n n\nend",
"def pack(a)\n\treps = Hash.new(1)\n prev = nil\n \n # filter out repeats\n a.select! {|v| prev == v ? (reps[v] += 1; false) : prev = v}\n \n # replace with nested arrays\n reps.each {|k, v| a[a.index k] = Array.new(v, k)}\n \n a\nend",
"def deep_copy\n Marshal.load(Marshal.dump(self))\n end",
"def clone_for_recursion(child, association)\n self.class.new(\n # replication mode\n :mode => mode,\n\n # the new src_obj is of course the child\n :src_obj => child,\n\n # these stay the same\n :dest_mission => dest_mission,\n :deep_copy => deep_copy,\n :retain_link_on_promote => retain_link_on_promote,\n\n # this is always true since we go into a transaction first thing\n :in_transaction => true,\n\n # the current_assoc is the name of the association that is currently being replicated\n :current_assoc => association,\n\n # add the new copy to the list of copy parents\n :ancestors => ancestors + [dest_obj],\n\n # recursed always is true since we're recursing here\n :recursed => true\n )\n end",
"def pbt_deep_dup_build(item_to_duplicate, &block)\n self.class.pbt_deep_dup_build(self, item_to_duplicate, &block)\n end",
"def dup\n empty_board = Board.new(false)\n pieces.each do |piece|\n temp_color = (piece.color == :red) ? :red : :white\n temp_pos = [piece.pos[0], piece.pos[1]]\n temp_kinged = piece.kinged\n temp_piece = Piece.new(empty_board, temp_color, temp_pos, temp_kinged)\n\n # empty_board.add_piece(Piece.new(empty_board, temp_color, temp_pos, temp_kinged), temp_pos)\n end\n\n empty_board\n # duped_rows = rows.map(&:dup)\n #\n # duped_rows.each_with_index do |row, row_idx|\n # row.each_index do |col_idx|\n # next if duped_rows[row_idx].nil?\n # current_cell = duped_rows[row_idx][col_idx]\n #\n # next if current_cell.nil?\n # duped_rows[row_idx][col_idx] = current_cell.dup\n # end\n # end\n # duped_board = self.class.new(duped_rows, false)\n # duped_board.pieces.each do |piece|\n # piece.board = duped_board\n # end\n # duped_board\n\n end",
"def deep_equals?(arr1, arr2)\n return false if arr1.length != arr2.length\n\n arr1.each_with_index do |x, i|\n return false if x.instance_of?(Array) && !deep_equals?(x, arr2[i])\n return false if x != arr2[i]\n end\n\n true\nend"
] |
[
"0.8449243",
"0.8212479",
"0.8200234",
"0.8174518",
"0.814501",
"0.8058728",
"0.80546415",
"0.8049845",
"0.8030621",
"0.80120975",
"0.7983847",
"0.79547346",
"0.7933665",
"0.79264325",
"0.7919462",
"0.7916924",
"0.7916924",
"0.7916924",
"0.7900404",
"0.7895804",
"0.7887487",
"0.78688824",
"0.7809156",
"0.7767778",
"0.77168846",
"0.77139854",
"0.7688344",
"0.7643347",
"0.7389636",
"0.7378348",
"0.7331946",
"0.7331946",
"0.7304717",
"0.6945978",
"0.67592114",
"0.67265064",
"0.6685205",
"0.66444206",
"0.6597354",
"0.6459478",
"0.6436091",
"0.6394594",
"0.6287388",
"0.61695516",
"0.61314595",
"0.60991585",
"0.60683745",
"0.6061889",
"0.60608315",
"0.6018185",
"0.5996894",
"0.5987291",
"0.5980829",
"0.59516597",
"0.59133583",
"0.58959126",
"0.58900636",
"0.5843067",
"0.58333105",
"0.5803555",
"0.57948047",
"0.57782286",
"0.57675683",
"0.574451",
"0.57424605",
"0.5736293",
"0.5724335",
"0.5723541",
"0.57091516",
"0.5698784",
"0.56973565",
"0.5695337",
"0.5693572",
"0.5691369",
"0.56624866",
"0.564523",
"0.5640276",
"0.56313",
"0.5621993",
"0.559307",
"0.55824417",
"0.55633855",
"0.55216956",
"0.55138195",
"0.55119026",
"0.55087364",
"0.5508253",
"0.5491489",
"0.54885787",
"0.54877406",
"0.54803544",
"0.54706424",
"0.5466232",
"0.5448725",
"0.5408062",
"0.540425",
"0.5397152",
"0.53945667"
] |
0.85044515
|
2
|
Write a method, `digital_root(num)`. It should Sum the digits of a positive integer. If it is greater than 9 (i.e. more than one digit), sum the digits of the resulting number. Keep repeating until there is only one digit in the result, called the "digital root". Do NOT use the built in `Integerto_s` or `Integerdigits` methods in your implementation. You may wish to use a helper function, `digital_root_step(num)` which performs one step of the process.
|
def digital_root(num)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def digital_root(num)\n digits = []\n until num == 0\n digits << num % 10\n num /= 10\n end\n sum = digits.reduce(0, :+)\n sum < 10 ? sum : digital_root(sum)\nend",
"def digital_root(num)\n while num >= 10\n num = digit_sum(digits(num))\n end\n num\nend",
"def digital_root(num)\n return num if num < 10\n sum = 0\n sum += num % 10 + digital_root(num / 10)\n\n if sum > 10\n digital_root(sum)\n else\n sum\n end\n end",
"def digital_root(num)\n return num if num < 10\n res = 0\n while num > 0\n res += num % 10\n num /= 10\n end \n digital_root(res)\nend",
"def digital_root(num)\n return num if num < 10\n i = 1\n sum = 0\n while 10 ** (i - 1) <= num\n sum += num % (10 ** i) / (10 ** (i - 1))\n i += 1\n end\n\n return digital_root(sum)\nend",
"def digital_root(number)\n while number >= 10 do\n number = _digital_root_sum(number)\n end\n number\nend",
"def digital_root(num)\n while num > 9\n num = add_digits(num)\n end\n\n num\nend",
"def digital_root(num)\n return num if num < 10\n \n sum = digital_root(num/10) + (num % 10)\n \n if sum > 10\n sum = digital_root(sum)\n else\n sum\n end\nend",
"def digital_root(num)\n return num if num < 10\n digital_root((num % 10) + (num / 10))\nend",
"def digital_root(num)\n return num if num < 11\n n = num % 10\n k = num / 10\n ans = n + k\n digital_root(ans)\nend",
"def digital_root(num)\n array = []\n\n until num == 0\n array << num % 10\n num = num / 10\n end\n result = array.inject(:+)\n\n if result > 9\n digital_root(result)\n else\n result\n end\nend",
"def digital_root(num)\n# sum variable \n# while loop => num > 0 \n# mod 10 add that to the sum var \n# div num by ten and reassign to num \n# check if sum >= 10 => digital_root(newNum) => return this\n\n sum = 0\n while num > 0 \n sum += num % 10 \n num /= 10\n end\n\n if sum >= 10 \n digital_root(sum)\n else \n sum \n end \nend",
"def digital_root(num)\n return num if num < 10\n\n num = digital_root_step(num)\n\n (num > 10) ? digital_root(num) : num\nend",
"def digital_root(n)\r\n while n > 9\r\n n = n.digits.inject(:+)\r\n end\r\n n\r\nend",
"def digital_root(number)\n return number if number < 10\n\n digital_root((number / 10) + (number % 10))\nend",
"def digital_root(integer)\r\n integer = integer\r\n loop do\r\n integer = integer.digits.sum\r\n break if integer.digits.size == 1\r\n digital_root(integer)\r\n end\r\n integer\r\nend",
"def digital_root(num)\n until num < 10\n num = num.to_s.split(\"\")\n formatted = []\n num.each do |n|\n formatted << n.to_i\n end\n\n num = formatted.inject(:+)\n end\n num\nend",
"def digital_root(num)\n while num >= 10\n num = digital_root_step(num)\n end\n\n num\nend",
"def digital_root(num)\n while num >= 10\n num = digital_root_step(num)\n end\n\n num\nend",
"def digital_root(num)\n while num >= 10\n num = digital_root_step(num)\n end\n\n num\nend",
"def digital_root(num)\n\n while num > 10\n num = digital_root_step(num)\n end\n\n num\nend",
"def digital_root(n)\n n < 10 ? n : digital_root(n.digits.sum)\nend",
"def digital_root(num)\n\n total = digital_root_step(num)\n until total < 10\n total = digital_root_step(total)\n end\n total\nend",
"def digital_root(num)\n if num < 10\n return num\n end\n recursion = num.to_s.split(\"\").map { |n| n.to_i }.reduce(:+)\n digital_root(recursion)\nend",
"def digital_root1(number)\n return -1 if number < 0\n return number if number < 10\n\n sum = 0\n number.to_s.chars.map(&:to_i).each do |num|\n sum += num\n end\n\n if sum >= 10\n digital_root1(sum)\n else\n return sum\n end\nend",
"def digital_root(n)\r\n digits = n.digits\r\n \r\n counter = digits.length\r\n\r\nuntil counter.size == 1\r\np sum = digits.sum\r\np sum.digits.sum\r\np counter -= 1\r\n end \r\n\r\nend",
"def digital_root(num)\n until num < 10\n num = digital_root_step(num)\n end\n num\nend",
"def digital_root(num)\n reductions = []\n\n if num < 10\n return num\n elsif num < 19\n until num < 10 \n reductions << (num / 10)\n num -= 1\n end\n reduced = reductions.reduce(:+)\n else\n num = num / 10\n reductions = []\n digital_root(num)\n end\n\nend",
"def digital_root(n)\n # Return number if it can't be reduced further\n return n if n.size == 1\n # Evaluate the sum of digits use recursion on the sum\n digital_root(n.to_s.chars.inject {|sum, n| sum.to_i + n.to_i })\nend",
"def digital_root(n)\n return n < 1 ? 0 : (n - 1) % 9 + 1\nend",
"def digital_root(n)\n def sum_digits(n)\n digits = n.to_s.split(\"\") # This will be [\"1\", \"3\", \"2\", \"1\", \"8\", \"9\"]\n sum = 0\n digits.each do |number|\n sum += number.to_i\n end\n sum\n end\n value = sum_digits(n)\n loop do\n if value.to_s.length == 1\n return value\n else\n value = sum_digits(value)\n end\n end\nend",
"def digital_root(n)\n until n < 10 do\n j = n\n n = 0\n until j < 1 do\n n += j % 10\n j /= 10\n end\n end\n return n\nend",
"def digital_root(n)\n n < 10 ? n : digital_root(n / 10 + n % 10)\nend",
"def digital_root(n)\n return n if n < 10\n \n n_arr = n.to_s.chars\n num = n_arr.first.to_i\n new_num = n_arr[1..-1].join.to_i\n digital_root(num + digital_root(new_num))\nend",
"def digital_root(n)\n arr = n.to_s.split('')\n if arr.length != 1\n tot = arr.inject(0){|sum,x| sum.to_i + x.to_i }\n while (tot >= 10)\n tot = tot.to_s.split('').inject(0){|sum,x| sum.to_i + x.to_i }\n end\n else \n return arr[0].to_i\n end\n return tot\n end",
"def digital_root(int)\n\tif int.div(10) == 0\n\t\treturn int\n\telse\n\t\treturn digital_root(digital_sum(int))\n\tend\nend",
"def digital_root(n)\n p '--- Jan-09-2017 problem2 --- '\n n = n.to_s.chars.map(&:to_i).reduce(:+) until n < 10\n n\nend",
"def digital_root(n)\n num = 0\n n.to_s.split(\"\").each {|x| num += x.to_i}\n num.to_i > 9 ? digital_root(num.to_i) : num.to_i\nend",
"def digital_root(number)\r\n # Your code goes here\r\n\r\n # int to array of numbers\r\n # seperate into digits\r\n # iterate\r\n # add them\r\n # return them (into another array?)\r\n\r\n #guard clause to make sure it's an integer?\r\n\r\n# if number !>= 0 && number !>= 1\r\n# if number == 0..9 dont run?\r\n\r\ndigits_arr = []\r\ndigital_root = []\r\n\r\nif !number.negative? # if number is not negative then run loop\r\n\r\n digits_arr = number.digits.reverse #this method wont work?\r\n\r\n #use to chr\r\n\r\n digital_root = digits_arr.sum\r\n\r\n root_digits = digital_root.digits.reverse\r\n\r\n digital_root_sum = \r\n\r\n\r\n digits_arr.each do |digit|\r\n #use sum method\r\n # if sum of digits_arr is == number then return true\r\n digit(i) + digit(i+1) #loop through add to next one - index?\r\n end\r\n\r\nelse \r\n return (-1) #if any negative argument is provided\r\n\r\nend\r\n\r\n\r\n# (&:to_i)\r\n# thats a short hand for map{|num| num.to_i}",
"def digital_root(n)\n arr = n.to_s.split(\"\")\n total = []\n val, answer = 0, 0\n arr.each {|x| val += x.to_i}\n if val <= 9\n return val\n elsif val > 9\n total = val.to_s.split(\"\")\n total.each {|s| answer += s.to_i }\n return answer\n end\nend",
"def digital_root(number)\n # return -1 if any negative number is provided\n if number < 0\n return -1\n end\n\n # split number into array \n number_array = number.to_s.scan(/\\d/).map {|i| i.to_i}\n # calculate sum of array while array.length > 1\n y = number_array.sum\n while y.to_s.length > 1\n y = number.to_s.scan(/\\d/).map {|i| i.to_i}\n y.sum\n end\n \nend",
"def digital_root_alt(n)\n n < 10 ? n : digital_root(n.digits.sum)\nend",
"def digital_helper(num)\n result = 0\n while num >= 10\n result += num % 10\n num = num/10\n end\n result + num\nend",
"def digital_root(n)\n result = n.to_s.chars.map(&:to_i).inject(:+)\n return result if result.to_s.size == 1\n\n digital_root(result)\nend",
"def sumdigit_r(num)\n if num < 10\n num\n else\n sumdigit_r(num/10) + num % 10\n end\nend",
"def sumdig_r(num, result = 0)\n if num < 10\n result += num\n else\n result += num % 10\n result = sumdig_r(num / 10, result)\n end\n result\nend",
"def digit_sum(num, digits)\n if digits == 1\n num\n else\n num % 10 + digit_sum(num / 10, digits - 1)\n end\nend",
"def sum_digits(num)\n\nend",
"def digital_sum(int)\n\tif int.div(10) == 0\n\t\treturn int.modulo(10)\n\telse\n\t\treturn int.modulo(10) + digital_sum(int.div(10))\n\tend\nend",
"def super_digit(n)\n return n if n/10 == 0\n \n sum = n % 10\n while n/10 != 0\n n = n/10\n sum += n % 10\n end\n return super_digit(sum)\nend",
"def super_digit(n)\n return n if n <= 9\n \n until n < 10\n sum = 0\n sum += (n % 10)\n sum += (n / 10)\n n = sum\n end\n\n return sum\nend",
"def sumdig_r(n)\n return n if n < 10\n (n%10) + sumdig_r(n/10)\nend",
"def sum_digits(n)\n return n if n <= 9\n n % 10 + sum_digits(n / 10)\nend",
"def digit_sum (number)\n sum = 0\n base = 10\n while number > 0 do\n sum += number % base\n number /= base\n end\n return sum\nend",
"def sumdig_r(n)\n\n # puts \"#{n} and n /10 is #{n/10} and n%10 is #{n%10}\"\n\n if (n<10) \n return n\n else\n return n%10 + sumdig_r(n/10)\n end\nend",
"def super_digit(n)\n return n if n < 10\n\n sum = 0 \n\n while n > 0\n digit = n % 10\n n /= 10\n sum += digit\n end\n\n super_digit(sum)\n\nend",
"def super_digit(n)\n #has to be a single digit \n if n < 10 \n return n\n else \n return super_digit(n.digits.sum)\n end \n \n \nend",
"def super_digit(n, sum=0) \n return sum + n if n / 10 == 0\n return super_digit(super_digit(n/10, sum+(n%10)))\nend",
"def super_digit(n)\n sum = 0;\n\n while n > 0 || sum > 9\n if n == 0\n n = sum\n sum = 0\n end\n sum += n % 10\n n /= 10\n end\n return sum\nend",
"def super_digit(n)\n return n if n < 10 \n \n sum = 0\n until n == 0\n sum += n % 10\n n /= 10\n end\n \n return super_digit(sum) # I had n.digits.sum here earlier, but since #digits creates a new array, I thought this solution would be less expensive\nend",
"def super_digit(n)\n return n if n < 10\n\n sum_digits = 0\n until n == 0\n sum_digits += n % 10\n n /= 10\n end\n\n super_digit(sum_digits)\nend",
"def sum(num)\n digits = []\n sum = 0\n digits = num.digits\n sum = digits.sum\n return sum\nend",
"def sum(num)\n num.digits.sum\nend",
"def sum(num)\n num.digits.sum\nend",
"def sum(num)\n num.digits.sum\nend",
"def sum(num)\n num.digits.sum\nend",
"def digital_root_best(n)\r\n n < 10 ? n : digital_root_best(n/10 + n%10)\r\nend",
"def super_digit(n)\n return n.abs if n.abs < 10\n\n sum = recursive_digit_helper(n)\n\n return super_digit(sum)\nend",
"def super_digit(n)\n while n > 9\n n = n % 10 + super_digit(n / 10)\n end\n return n\nend",
"def super_digit(n)\n\n return n if n < 10\n super_digit(n.digits.sum)\n\nend",
"def super_digit(n)\n return n if n < 10\n sum = super_digit_helper(n, 0)\n super_digit(sum)\nend",
"def super_digit(n)\n return n if n < 10\n\n return super_digit(n.digits.sum)\nend",
"def super_digit(n)\n if n >= 0 && n < 10 \n return n\n end\n digits_of_n = n.digits\n sum_digits = digits_of_n.sum\n\n return super_digit(sum_digits)\nend",
"def sum(number)\r\n number.digits.sum\r\nend",
"def super_digit(n)\n while n >= 10\n n = n % 10 + super_digit(n / 10)\n end\n return n\nend",
"def sum_func(num)\n return num if num <= 1\n\n divided = num / 10\n moded = num % 10\n\n moded + sum_func(divided)\nend",
"def super_digit(n)\n # base case\n return n if n/10 == 0\n \n # recursive case\n return super_digit(n/10 + n%10)\nend",
"def super_digit(n)\n return n if n < 10\n super_digit(n.digits.sum)\nend",
"def super_digit(n)\n return n if n < 10\n super_digit(n.digits.sum)\nend",
"def super_digit(n)\n return n if n < 10\n return super_digit(n.digits.sum)\nend",
"def sum(number)\n number.digits.sum\nend",
"def sum(number)\n number.digits.sum\nend",
"def sum_to_one_digit(num)\n if num < 1 or not num.is_a? Integer\n puts \"Num must be positive integer\"\n return false;\n end\n\n get_sum = ->(intgr) {\n digit_sum = 0\n intgr = intgr.to_s.split('')\n intgr.each do |i|\n digit_sum += i.to_i\n end\n return digit_sum\n }\n\n sum = get_sum.call(num)\n while sum.to_s.length > 1 do\n sum = get_sum.call(sum)\n end\n\n puts sum\n return sum\nend",
"def super_digit(n)\n sum = 0\n\n if n < 10\n return sum + n\n else\n until n < 10\n sum += (n % 10)\n n /= 10\n end\n\n sum += n\n end\n\n return super_digit(n = sum)\nend",
"def super_digit(n)\n sum = 0\n while n >= 10 do\n sum += n % 10\n n /= 10\n end\n sum += n\n return sum < 10 ? sum : super_digit(sum)\nend",
"def digit_sum(int)\n return int.digits.sum\nend",
"def super_digit(n)\n return n if n < 10 \n return super_digit(n.to_s.chars.map(&:to_i).sum)\nend",
"def sum(num)\n\n\tarray_of_digits = num.digits\n\n\tarray_of_digits.sum\n\nend",
"def sum(n)\n n.digits.sum\nend",
"def super_digit(n)\n if 10 > n\n return n\n end\n\n last_digit = n % 10\n sum = n / 10 + last_digit \n \n return super_digit(sum)\nend",
"def add_digits(num)\n return 0 if num == 0\n (num - 1) % 9 + 1\nend",
"def sum(int)\n int.digits.sum\nend",
"def super_digit(n)\n return n if n < 10\n sum = n.to_s.chars.map(&:to_i).sum\n return super_digit(sum)\nend",
"def compute_number(digits)\n digits.length == 1 ? (digits.to_i) : (digits[-1].to_i + 10*compute_number(digits[0..-2]))\nend",
"def sum_square_digits(q)\n sum = 0\n return 1 if q == 0\n until q == 0\n q, r = q / 10, q % 10\n sum += r*r\n end\n sum\nend",
"def sum_of_digits(int)\n int.digits.sum\nend",
"def sum(integer)\n integer.digits.sum\nend",
"def super_digit(n)\n num_array = n.to_s.chars.map(&:to_i)\n sum = num_array.sum\n if sum <9\n return sum\n else \n return super_digit(sum)\n end\n \nend"
] |
[
"0.85687935",
"0.8507984",
"0.83947444",
"0.8332727",
"0.8288676",
"0.8264662",
"0.8260138",
"0.8258121",
"0.81567365",
"0.8051066",
"0.7998651",
"0.7973149",
"0.7963087",
"0.7932783",
"0.79193586",
"0.79143745",
"0.7882045",
"0.7866445",
"0.7866445",
"0.7866445",
"0.7777042",
"0.7772465",
"0.77597827",
"0.7749049",
"0.7734073",
"0.7718639",
"0.76457113",
"0.7627193",
"0.7618025",
"0.75828034",
"0.7570501",
"0.7554991",
"0.75357825",
"0.7515229",
"0.74526954",
"0.7420817",
"0.73782486",
"0.7348921",
"0.73031133",
"0.727585",
"0.72375625",
"0.7187639",
"0.71414846",
"0.69749284",
"0.6857887",
"0.67933095",
"0.6657511",
"0.66251063",
"0.6596542",
"0.64250046",
"0.64170116",
"0.64158124",
"0.63787127",
"0.6357344",
"0.6337282",
"0.63169765",
"0.6288897",
"0.6285723",
"0.6281973",
"0.62600994",
"0.62478817",
"0.6244725",
"0.62401927",
"0.62401927",
"0.62401927",
"0.62401927",
"0.62342846",
"0.61925584",
"0.6180602",
"0.6178613",
"0.61713016",
"0.6143606",
"0.61300045",
"0.6129875",
"0.6127568",
"0.6112801",
"0.6112548",
"0.61082155",
"0.61082155",
"0.61082125",
"0.6105865",
"0.6105865",
"0.6069587",
"0.60695386",
"0.6067941",
"0.6053091",
"0.6031285",
"0.60308176",
"0.6003403",
"0.5990575",
"0.5971773",
"0.5965998",
"0.5958015",
"0.5954607",
"0.5944525",
"0.59328747",
"0.59031",
"0.58856595"
] |
0.74865025
|
36
|
Write a method that doubles each element in an array. Assume all elements of the array are integers.
|
def doubler(array)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def calculate_doubles(arr)\n arr.map {|a|a*2}\n\nend",
"def calculate_doubles!(array)\n\t\n\tarray.map! { |num| num * 2}\nend",
"def calculate_doubles(arr)\n doubled_array = []\n arr.each {|int| doubled_array.push(int * 2)}\n doubled_array\nend",
"def calculate_doubles!(arr)\n arr.map! {|int| int * 2}\nend",
"def double_array(array)\n array*2\nend",
"def double_numbers(array)\n\tarray.map { |integer| integer * 2 }\t\nend",
"def double_all array\n array.map { |i| i*2 }\nend",
"def double_all(arr)\n doubles = []\n\n arr.each do |num|\n doubles.push(num * 2)\n end\n\n doubles\nend",
"def double_array(array)\n\tn = [1, 2, 3]\n\tn * 2\nend",
"def calculate_doubles(arr)\n array = []\n arr.each {|x| array << x + x}\n array\n\nend",
"def double_array(input_array)\n \n double_array = []\n \n input_array.each do |number|\n double_array << number *= 2\n end\n return double_array\n\nend",
"def calculate_doubles!(arr)\n\n arr.map! {|x| x + x}\n arr\n\nend",
"def double_numbers(array)\n doubled_numbers = []\n array.each do |number|\n doubled_numbers << number * 2\n end\n return doubled_numbers\nend",
"def double_array(arr)\n doubled_arr = arr.map do | element| \n element *2 \n end\n doubled_arr\nend",
"def map(arr)\n i = 0\n # Double each item in the array and replace values.\n arr.each do |item|\n arr[i] = double(item)\n i += 1\n end\n # Return the new doubled array.\n # This is the result of the map function.\n return arr\nend",
"def double_numbers(input_array)\n doubled_array =[]\n input_array.each {|num| doubled_array << num*2} \n doubled_array\nend",
"def map_to_double(array)\n new_array = array.map{|n| n*2}\n return new_array\nend",
"def map_to_double(source_array)\n \n i = 0\n new_array = []\n \n while i < source_array.length do\n new_array_value = source_array[i] * 2\n new_array << new_array_value\n \n i += 1\n end\n \n new_array\nend",
"def calculate_doubles(array)\n\tmapped_array = array.map { |num| num * 2 }\nend",
"def double_numbers(array)\n new_array = []\n\n array.each do |number|\n new_array << number *= 2\n end\n return new_array\nend",
"def double_array(array)\n output_array = []\n\n array.each do |thing|\n output_array << thing * 2\n end\n\n return output_array\nend",
"def double_eles(arr)\n arr.map do |ele|\n ele * 2\n end\nend",
"def double_numbers!(numbers)\n counter = 0\n\n loop do\n break if counter == numbers.size\n\n numbers[counter] *= 2\n\n counter += 1\n end\n numbers\nend",
"def double(*numbers)\n numbers.each do |x|\n puts x * 2\n end\nend",
"def double_it(numbers)\n numbers.map{|number| number * 2}\nend",
"def square_array(array)\n array.map do |element|\n element ** 2 \n end\nend",
"def multiply_element(array)\n array.each do |x|\n x=x*x\n end\n end",
"def square_array(array)\n array.collect {|num| num * num}\n \nend",
"def map_to_double(source_array)\n array = []\n index = 0 \n \n while index < source_array.size do \n array.push(source_array[index] * 2)\n index += 1 \n end\n return array\nend",
"def square_array(array)\n array.map! { |ele| ele ** 2 }\nend",
"def double_numbers!(numbers)\n\n counter = 0\n loop do\n break if counter >= numbers.length\n numbers[counter] *= 2\n counter += 1\n end\n numbers # not really necessary, but good to have\n end",
"def square_the_values(array_of_integers)\n # TODO\nend",
"def double_each\n numbers = [1,2,3,4,5]\n doubled = []\n numbers.each do |number|\n doubled << number * 2\n end\n doubled\nend",
"def double_it(numbers)\n numbers.map { |x| x * 2 }\nend",
"def double_array(array)\n # your code here\nend",
"def calculate_doubles!(arr)\n arr.map!{|a|a=a*2}\nend",
"def doubler(array)\n array.map do |num|\n num *= 2\n end\n\nend",
"def square_array(array)\n # Use an Enumerable to square every element in the passed in array\n # Return a new array of the results\n array.map do |n|\n n*n\nend\nend",
"def multiply_me(array, int)\r\n\r\n arr = [] # empty array created\r\n\r\n i = 0 # iteration starts to multiply each item\r\n while i < array.length\r\n arr << array[i] * int # products collected\r\n i += 1\r\n end\r\n\r\n arr # result\r\nend",
"def multiply(arr)\n arr.map { |i| i * 2 }\nend",
"def double_it(numbers)\n numbers.map do |x|\n x * 2\n end\nend",
"def doubler(array)\r\n res = []\r\n array.each do |ele|\r\n res << ele * 2\r\n end\r\n res\r\nend",
"def multiply(array,mult)\n array.map{|num| num*mult}\nend",
"def square_array(array)\n array.each_with_index do | num, index |\n array[index] = num * num\n end\nend",
"def square_array(array)\n new_array = []\n array.each { |e| new_array << e ** 2 }\n new_array\nend",
"def square_array(array)\n squared = []\n array.each { |element| squared << element ** 2 }\n squared\nend",
"def square_array(some_array)\n some_array.collect {|num| num*num} \nend",
"def multiply_by(array)\n return array.map { |el| el * 3}\nend",
"def square_array(array)\n numbers = []\n array.each do |number| numbers << number ** 2\n end\n numbers\nend",
"def doubler(array)\n array.map { |num| num * 2 }\nend",
"def doubler(array)\n array.map { |num| num * 2 }\nend",
"def square_array_2(array)\n array.collect { |i| i**2 }\n array\nend",
"def multiply_els(array)\n\tarray.inject(1) { |num, item| num * item }\n\nend",
"def square_array(some_array)\n some_array.map {|number| number ** 2}\nend",
"def multiply_by_two(array)\n # double_numbers = []\n # array.each do |number|\n # double_numbers << number * 2\n # end\n # double_numbers\n array.map { |number| number * 2 }\nend",
"def double_num(array)\n array.map do |num|\n if num % 2 == 0 then num*2\n else\n num\n end\n end\nend",
"def double_numbers!(numbers)\n counter = 0\n\n loop do\n break if counter == numbers.size\n\n current_number = numbers[counter]\n numbers[counter] = current_number * 2\n\n counter += 1\n end\n\n numbers\nend",
"def multiply_all_by(array, num)\n\n result = []\n array.each do |elem|\n result << elem * num\n end\n result\nend",
"def multiply (array)\n\tarray.inject(1) do |result, element|\n\t\tresult * element\n\tend\nend",
"def square_array(array)\narray.map { |to_square| to_square**2}\nend",
"def square_array(array)\n\tsquared_nums = []\n\n array.each do |number|\n squared_nums << (number * number)\n end\n squared_nums\nend",
"def square_array(array)\n new_array = []\n array.each{|a| new_array.push(a*a)}\n return new_array\nend",
"def basic_9 (array_iterate)\n square_array = array_iterate.collect { |n| n * n}\n return square_array\nend",
"def multiply_els(arr)\n\tarr.my_inject(1) do |res, i| \n\t\tres * i \n\tend\nend",
"def square_array(array)\n square = []\n \n array.each do |num|\n square << num * num\n end\n square\nend",
"def square_array(array)\n\n squared = []\n array.each do |num|\n squared.push(num * num)\n end\n\n squared\n \nend",
"def square_array(numbers)\n numbers.map { |e| e ** 2 }\nend",
"def custom_multiply(array, number)\n # Return a new array with the array that's passed in\n # as an argument multiplied by the number argument\n result = []\n number.times { array.each { |elem| result << elem } }\n result\nend",
"def square_array2(array)\n return array.collect { |num| num ** 2 }\nend",
"def multiply(array)\n array.inject(:*)\nend",
"def multiply *array\n puts array.inspect\n array.flatten.inject(:*)\n end",
"def multiply_by(num,arr)\n arr.map do |x|\n x * num\n end\nend",
"def arr_product(arr)\n product = arr.reduce(:*)\n arr.map { |el| product / el }\nend",
"def multiply_each (array, product=1)\n array.each do |x|\n product *= x\n end\n return product\nend",
"def custom_multiply(array, number)\n result = []\n number.times { array.each { |element| result << element}}\n result\nend",
"def element_times_index(numbers)\n\tfor i in 0..numbers.length-1\n numbers[i] *= i\n end\n return numbers\nend",
"def multiply_by_two(array)\n array.map { |n| n * 2 }\nend",
"def square_array_collect(array)\n array.collect{|num| num ** 2}\nend",
"def square_array (array)\n\nnewarray = []\n\narray.each do |element|\n newarray.push(element**2) \nend\n\nnewarray\n\nend",
"def compute_squares(array)\n arrayFinal = []\n array.each do |element|\n arrayFinal << element * element\n end\n return arrayFinal\nend",
"def square_array_with_collect(array)\n array.collect{|element| element**2}\nend",
"def squares(array)\n\t\n\tnew_array = array.map { |num| num * num}\n\tp new_array\nend",
"def square_array(array)\n squared_array = []\n \n array.each do |number| \n squared_array << number**2 \n end\n \n squared_array\nend",
"def doubler(numbers)\n\tdoubled_nums = [] # Creates empty array to store double nums\n\n\ti = 0\n\twhile i < numbers.length\n\t\told_elem = numbers[i] # Creates temporary variable to hold number for each iteration\n\t\tnew_elem = old_elem * 2 # Multiplies old element by two and saves to new variable\n\t\tdoubled_nums << new_elem\n\n\t\ti += 1 # Iterates upwards\n\tend\n\n\treturn doubled_nums\nend",
"def arrMultiply(arr)\n (arr[0].to_i * arr[1].to_i).to_s\nend",
"def square_array(array)\nnew_array = []\ncounter = 0\nwhile counter < array.length do\n new_array << array[counter] ** 2 #**squaring incrments\ncounter += 1 #increments plus 1 after squaring elements\nend\nreturn new_array #can also just write new_array without the retun before it \nend",
"def multiply_els(array)\n array.my_inject(1) { |product, i| product * i }\nend",
"def double_even_numbers(array)\n doubled_array = array.clone\n\n (array.length - 1).step(0, -2) do |i|\n doubled_array[i] += doubled_array[i]\n end\n\n doubled_array\n end",
"def array_times_two(array)\n new_array = array.map{ |el| el * 2}\n end",
"def map_to_square(source_array)\n \n i = 0\n new_array = []\n \n while i < source_array.length do\n new_array_value = source_array[i] ** 2\n new_array << new_array_value\n \n i += 1\n end\n \n new_array\nend",
"def square_array(array)\n new_array = []\n array.each { |n| new_array << n*n }\n new_array\nend",
"def square_array(array)\n squared = []\n count = 0\n while count < array.size do\n squared << (array[count] ** 2)\n count = count + 1\n end\n squared\nend",
"def square_array(array)\n squared = []\n count = 0\n while count < array.size do\n squared << (array[count] ** 2)\n count = count + 1\n end\n squared\nend",
"def square_array(array)\n counter = 0\n new_array = []\n while counter < array.length do\n new_array << array[counter] ** 2\n counter += 1\n end\n p new_array\nend",
"def double_to_single_method(multiplied_integer_array)\n single_digit_array = []\n multiplied_integer_array.each do |value|\n if value > 9\n value = value - 9\n single_digit_array << value\n else\n value = value\n single_digit_array << value\n end\n end\n return single_digit_array\nend",
"def mult5 array\n array.map do |value| \n value * 5 \n end\nend",
"def arr_square()\n [1, 1, 2, 3, 5,].each{|x| puts x * x}\nend",
"def square_array(some_array)\n array_squared = []\n some_array.each do |number|\n array_squared << number * number\n end \n return array_squared\nend",
"def square_array(some_array)\n array_squared = []\n some_array.each do |item|\n array_squared << item*item\nend\n return array_squared\nend",
"def doubler(arr)\n i = 0\n while i < arr.length\n arr[i] = arr[i] * 2\n i += 1\n end\n return arr\nend",
"def multiply(array, num_two)\n array * num_two\nend"
] |
[
"0.78334135",
"0.7793091",
"0.7789141",
"0.7783288",
"0.7671744",
"0.7598676",
"0.7593664",
"0.7563257",
"0.75166327",
"0.74786144",
"0.7310658",
"0.72904456",
"0.7279631",
"0.7252194",
"0.72190785",
"0.72157377",
"0.71854794",
"0.71812576",
"0.7177584",
"0.7171713",
"0.7161439",
"0.70582557",
"0.7018519",
"0.70092905",
"0.6957518",
"0.695108",
"0.6914689",
"0.69037",
"0.6898913",
"0.6872441",
"0.68639946",
"0.6862963",
"0.68308604",
"0.68259245",
"0.67874295",
"0.6763117",
"0.6751378",
"0.67402875",
"0.6740084",
"0.6729636",
"0.6698568",
"0.6676269",
"0.6675996",
"0.6656049",
"0.6643436",
"0.66370857",
"0.66335833",
"0.6626701",
"0.6614797",
"0.6613873",
"0.6613873",
"0.66105723",
"0.66042644",
"0.65984523",
"0.65730083",
"0.6568548",
"0.655322",
"0.65411705",
"0.65287614",
"0.6511058",
"0.64904785",
"0.6489439",
"0.6481743",
"0.6480622",
"0.64771795",
"0.645534",
"0.6439937",
"0.6433191",
"0.64063543",
"0.6399483",
"0.63836086",
"0.6375874",
"0.6364327",
"0.6353359",
"0.6352837",
"0.63521147",
"0.6350447",
"0.6327448",
"0.6326252",
"0.6319851",
"0.6315389",
"0.63042253",
"0.63030255",
"0.62941104",
"0.62909406",
"0.62841904",
"0.6282585",
"0.6275228",
"0.6269522",
"0.62689424",
"0.6262567",
"0.6257655",
"0.6257655",
"0.62453794",
"0.6240323",
"0.6218305",
"0.6215258",
"0.6203697",
"0.6201133",
"0.61928076",
"0.6182514"
] |
0.0
|
-1
|
Define a method `primes(num)` that returns an array of the first "num" primes. You may wish to use an `is_prime?` helper method.
|
def primes(num)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def primes(num)\n\twhole_array = (2..num).to_a\n\tprime_array = [whole_array.shift]\n\n\tuntil whole_array == []\n\t\twhole_array.delete_if { |x| x % prime_array.last == 0 }\n\t\tprime_array << whole_array.shift\n\tend\n\tprime_array\nend",
"def get_primes num\n primes = []\n for i in 0 ... num do\n if check_prime?(i) == true\n primes.push(i)\n end\n end\n p primes\nend",
"def first_n_primes(n)\n\t return \"n must be an integer.\" unless n.is_a? Integer\n\t return \"n must be greater than 0.\" if (n<=0)\n\n prime_array||=[]\n\tprime = Prime.new\n\tn.times {prime_array << prime.next } \n\tprime_array\nend",
"def primes_less_than(num)\n require 'prime'\n arr = []\n Prime.each(num) do |prime| arr.push(prime)\n end\n num.prime? ? arr.pop : arr\n return arr\n end",
"def primes_less_than(num)\n arr = []\n (2...num).each do |el|\n if is_prime?(el)\n arr << el\n end\n end\n arr\nend",
"def primes_less_than(num)\n res = []\n (2...num).each do |i|\n res.push(i) if is_prime?(i) == true\n end\n res\nend",
"def first_n_primes(n)\n\n #unless n.is_a? Integer\n # return \"n must be an integer.\"\n #end\n return \"n must be an integer.\" unless n.is_a? Integer\n\n #if n <= 0\n # return \"n must be greater than 0.\"\n #end\n return \"n must be greater than 0.\" if n <= 0\n \n #prime_array = [] if prime_array.nil?\n prime_array ||= []\n \n prime = Prime.new\n #for num in (1..n)\n # prime_array.push(prime.next)\n #end\n # n.times { prime_array.push(prime.next) }\n n.times { prime_array << prime.next }\n \n #return prime_array\n prime_array # implicit return!\n\nend",
"def first_n_primes(n)\n\n unless n.is_a? Integer\n return \"n must be an integer.\"\n end\n\n if n <= 0\n return \"n must be greater than 0.\"\n end\n \n prime_array = [] if prime_array.nil?\n \n prime = Prime.new\n for num in (1..n)\n prime_array.push(prime.next)\n end\n return prime_array\nend",
"def first_n_primes(n)\n\n \"n must be an integer.\" unless n.is_a? Integer\n\n \"n must be greater than 0.\" if n <= 0\n \n prime_array ||= []\n \n prime = Prime.new\n n.times { prime_array << prime.next }\nend",
"def first_n_primes(n)\n\n return \"n must be an integer.\" unless n.is_a? Integer\n return \"n must be greater than 0.\" if n <= 0\n \n prime_array ||= []\n \n prime = Prime.new\n n.times {\n prime_array << prime.next \n }\n prime_array\nend",
"def primes_less_than (num)\n arr=[]\n for n in 2..(num-1)\n if is_prime?(n)\n arr.push(n)\n end\n end\n p arr\n return arr\nend",
"def pick_primes(numbers)\n\tprimes = []\n \tnumbers.each do |num| \n \tif isPrime(num) \n \tprimes.push(num)\n end\n end\n \treturn primes\nend",
"def primes (number)\n primes_array = []\n Prime.each(number) do |p|\n primes_array.push(p)\n end\n\n primes_array\nend",
"def primes()\n return [] if @number < 2\n # build Boolean array to use for sieve with buffer to align indices\n sieve_array = Array.new(2, false) + Array.new(@number-1, true)\n # perform Sieve of Eratosthenes eliminations\n (2..Math.sqrt(@number).to_i).each do |i|\n (i**2..@number).step(i) {|j| sieve_array[j] = false} if sieve_array[i] == true\n end\n # return numbers by corresponding index that are still true\n (2..@number).collect {|index| index if sieve_array[index] == true}.compact\n end",
"def get_primes\n j = 0\n\n while j < @limit \n prime_number = is_prime\n if prime_number\n @prime_numbers.push(prime_number)\n j += 1\n end\n @count += 1\n end\n\n return @prime_numbers\n end",
"def primes\n\t\t# primes = []\n\t\t# primes << 2\n\t\tprimes = [2] # combined previous two lines\n\t\tx = 3\n\n\t\tloop do\n\t\t\tbreak if primes.length == @n_primes # End loop when desired number has been calculated\n\t\t# while primes.length < @n_primes # Alternative 1 to loop do, break\n\t\t# until primes.length == @n_primes # Alternative 2 to loop do, break\n\t\t\ty = 3\n\t\t\ty += 2 until x % y == 0 # Loop to test if x is divisible by any odd number below it, y\n\t\t\tprimes << x if x == y # If the (odd) number was not divisible by any (odd) below itself, it is a prime\n\t\t\tx += 2\n\t\tend\n\n\t\treturn primes\n\tend",
"def find_primes(num,prime_array=[])\n i = 2\n until num % i == 0 \n i += 1\n end\n prime_array << i\n return prime_array if num == i\n find_primes(num/i, prime_array) \nend",
"def prime(number)\n prime_numbers = []\n (2..number).each do |current_number|\n if is_prime? current_number\n prime_numbers << current_number\n end\n end\n return prime_numbers\nend",
"def all_primes(number)\n primes = []\n (2...number).each do |num|\n if prime?(num)\n primes << num \n end\n end\n primes\nend",
"def prime_numbers(num)\n all_factors = factors(num)\n only_prime = []\n i = 0\n while i < all_factors.length\n if prime?(all_factors[i])\n only_prime += all_factors[i]\n end\n i += 1\n end\n only_prime\n end",
"def primes\n return [] if self == 0\n return \"don't do that\" if self < 0\n list = [2]\n test = 3\n until list.length == self\n list << test if test.is_prime?\n test += 2\n end\n list\n end",
"def pretentious_primes(arr, num)\n new_arr = []\n if num > 0\n arr.each do |ele|\n i = ele + 1\n count = 0\n while true\n if is_prime?(i)\n count += 1\n end\n if count == num\n new_arr << i\n break\n end\n i += 1\n end\n end\n else\n num = -1 * num\n end\n new_arr\nend",
"def prime_list(number_of_primes)\n return [] if number_of_primes < 1\n prime_numbers = Array.new\n for num in 2..9999999 do\n if is_prime_num(num, prime_numbers)\n prime_numbers.push(num)\n break if prime_numbers.length == number_of_primes\n end\n end\n return prime_numbers\n end",
"def pick_primes(numbers)\n return numbers.select { |num| prime?(num)}\nend",
"def pretentious_primes(arr, num)\nend",
"def pick_primes(numbers)\r\n return numbers.select { |num| prime?(num)}\r\nend",
"def get_primes(limit)\n primes = []\n (2...limit).each do |number|\n primes << number if is_prime?(number)\n end\n primes\nend",
"def select_primes(array)\n array.select { |num| is_prime?(num) }\nend",
"def prime_factors(num)\n arr = []\n (1...num).each do |number|\n if is_prime(number) && num % number == 0\n arr << number\n end\n end\n return arr\nend",
"def pick_primes(numbers)\n numbers.select { |num| prime?(num) }\nend",
"def prime_factors(num)\n require \"prime\"\n primes = []\n Prime.each{|prime| primes << prime if num % prime ==0 ; break if prime > num }\n primes\nend",
"def prime_factors(num)\n arr = []\n\tPrime.each(num) { |prime| num % prime == 0 ? arr.push(prime) : false }\n return arr\nend",
"def primes\n return [] if max_prime < 2\n\n candidates.each do |prime,_|\n # skip numbers we already know NOT to be prime (from previous iterations)\n next if candidates[prime] != :prime\n\n # find the prime number candidates greater than the current prime number\n candidates.select { |n,_| candidates[n].eql?(:prime) && n > prime }\n .each do |num,_|\n # mark numbers evenly divisible by the current prime as NOT PRIME\n @candidates[num] = :not_prime if (num % prime) == 0\n end\n end\n\n # convert numbers still marked as prime to an array of numbers\n candidates.map { |num,value| num if value.eql? :prime }.compact\n end",
"def primes_less_than(num)\n\toutput = []\n\t(2...num).each do |n|\n\t\toutput << n if is_prime?(n)\n\tend\n\toutput\nend",
"def get_primes limit\n\tnums = (1...limit).select { |n| n.prime? }\n\n\tp nums\nend",
"def prime (n)\n\n\t#create an Array\n\tprime_num = []\n\n\tfor num in (2..n)\n\t\tis_prime = factors(num)\n\t\tif (is_prime.length ==2)\n\t\t\tprime_num.push(num)\n\t\tend\n\tend\n\treturn prime_num\nend",
"def primes(max)\n primes = []\n number = 2\n \n while number <= max\n primes << number if is_prime? number\n number += 1\n end\n primes\nend",
"def primes(max)\n primes = []\n number = 2\n \n while number <= max\n primes << number if is_prime? number\n number += 1\n end\n primes\nend",
"def get_primes(qyt)\n Prime.first qyt\nend",
"def primes (n)\n return (1..n).select { |x| x.prime? }\nend",
"def prime_factors(num)\n arr = (2..Math.sqrt(num).round).to_a\n primes = arr.each do |i|\n arr.select! {|j| j%i != 0 or j==i}\n end\n pfacts = primes.select {|i| num%i == 0}\n\n return [num] if pfacts.empty?\n return pfacts\nend",
"def prime_factors(num)\n\tprimeFactors = []\n \t\n \t(1..num).each do |i|\n \tif num % i == 0 && isPrime(i)\n \tprimeFactors.push(i)\n end\n end\n \n \treturn primeFactors\nend",
"def nth_Prime(num)\n\tprime_array = [2]\n\ti = 3\n\n\twhile prime_array.length < num\n\t\ti += 2\n\t\tif (i % 2 == 0)\n\t\t\tnext_num\n\t\tend\n\n\t\tprime = true\n\t\tprime_array.each do |j|\n\t\t\tif (i % j == 0)\n\t\t\t\tprime = false\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\n\t\tif prime\n\t\t\tprime_array << i\n\t\tend\n\tend\n\tprime_array.last\nend",
"def prime_factors(num)\n arr = factors(num)\n new_arr = []\n arr.each do |n|\n new_arr << n if prime?(n)\n end\n new_arr\nend",
"def pick_primes(numbers)\n numbers.select { | n | is_prime(n) }\nend",
"def prime_factors(num)\n arr = []\n (1..num).each { |n| arr << n if num%n==0 && prime?(n)}\n return arr\nend",
"def prime_factors(num)\n factors = []\n # Store all the factors in an array\n (2..num).each do |divisor|\n if num % divisor == 0\n factors << divisor\n end\n end\n\n # loop through factors array and return only the prime prime prime factors\n if factors.length > 0\n return factors.select { |factor| checkIfPrime(factor) }\n else\n return factors\n end\nend",
"def prime_factors(integer)\n primes = Prime.take(20)\n arr = []\n i = 0\n loop do \n if integer % primes[i] == 0\n integer = integer / primes[i]\n arr << primes[i]\n else\n i += 1\n end\n break if integer == 1\n end\n arr\nend",
"def primes (n)\r\n primes = Array.new(n) { |index| index+=1 }\r\n return primes.select { |x| factors(x).length == 2 }\r\nend",
"def prime_factors(num)\n factors = factors(num)\n result = []\n factors.each do |fac|\n if prime?(fac)\n result << fac\n end\n end\n result\nend",
"def prime_factors(num)\n array = []\n (1..num).each do |number|\n array << number if prime?(number) && num % number == 0\n end\n array.sort!\nend",
"def prime_factors(num)\n prime_facts = []\n \n (1..num).each do |i|\n if num % i == 0 && prime?(i)\n prime_facts << i\n end\n end\n \n return prime_facts\n end",
"def prime_numbers\n # start with the first prime number\n primes = [2]\n # find the rest of the prime numbers\n (2..1000).each do |i|\n add_next_prime_number(primes)\n end\n return primes\nend",
"def first_n_primes(n)\n return \"n must be an integer.\" unless n.is_a? Integer\n return \"n must be greater than 0.\" if n <= 0\n return Prime.first n\nend",
"def primes(max)\n array = []\n i = 2\n while i < max.abs\n if is_prime?(i)\n array << i\n end\n i += 1\n end\n array\nend",
"def find_prime_numbers(num)\n\tarr =[]\n (2..num).each{|x| arr.push(x)}\n\n i = 0\n p = arr[i]\n\n while p != arr[-1]\n\t arr.delete_if{|n| n%p == 0 && n != p}\n\t i+= 1\n\t p = arr[i]\n end\n return arr\nend",
"def prime_factors(num)\n\n if prime?(num)\n return [num]\n end\n\n primes = (2...num).to_a.select { |factor| prime?(factor) }\n\n \n \n factors = []\n\n while num > 1\n candidate = primes.shift\n\n if num % candidate == 0\n factors << candidate\n while num % candidate == 0\n num /= candidate\n end\n end\n end\n\n return factors\n \nend",
"def sieve(n)\n # initialize an empty array (this will store all primes between 2 and n)\n prime_array = []\n for i in 2..n\n if(is_prime(i))\n # if 'i' is a prime number, add it to the array\n prime_array.push(i)\n end\n end\n # finally, we'll return our array of prime numbers\n return prime_array\nend",
"def find_primes(number)\n\tprimes = []\n\ttry_num = 2\n\tx = 2\n\tfactors = []\n\t\n\twhile primes.length != number\n\t\t#puts \"primes : #{primes}\"\n\t\t#puts \"try_num : #{try_num}\"\n\t\t#puts \"x : #{x}\"\n\t\t#puts \"factors : #{factors}\"\n\t\t\n\t\tif factors.length >= 1 && factors[0] != try_num\n\t\t\t#puts \"#{try_num} is not prime\"\n\t\t\ttry_num += 1\n\t\t\tx = 2\n\t\t\tfactors = []\n\t\t \n\t\telsif try_num % x == 0 && x == try_num\n\t\t\t#puts \"#{try_num} is prime\"\n\t\t\tprimes << try_num\n\t\t\ttry_num += 1\n\t\t\tx = 1\n\t\t\n\t\telsif try_num % x == 0\n\t\t\t#puts \"#{x} is factor of #{try_num}\"\n\t\t\tfactors << x\n\t\telse\n\t\t\n\t\tend\n\t\t\n\t\tx += 1\n\tend\n\tputs primes\n\treturn primes\nend",
"def prime_factors(num)\n facs = factors(num)\n p_facs = []\n facs.each{|n| p_facs.push(n) if prime?(n)}\n p_facs\nend",
"def first_n_primes(n)\n return \"n must be an integer.\" unless n.is_a? Integer\n return \"n must be greater than 0.\" unless n > 0\n return Prime.first n\nend",
"def prime_factors(num)\n\tfactors(num).select { |n| prime?(n) }\nend",
"def first_n_primes(n)\n return \"n must be an integer.\" unless n.is_a? Integer\n return \"n must be greater than 0.\" if n <= 0\n Prime.first n\nend",
"def first_n_primes(n)\n return \"n must be an integer.\" unless n.is_a? Integer\n return \"n must be greater than 0.\" if n <= 0\n Prime.first n\nend",
"def print_prime\n @n_primes = get_n_primes\n return [] if @n_primes == 0\n p_arr_len = @prime_numbers.length\n return @prime_numbers[0..@n_primes] if p_arr_len >= @n_primes\n (p_arr_len > 1) ? (n = @prime_numbers.last) : (n = 3)\n until @prime_numbers.length == @n_primes do\n @prime_numbers.push(n) if @prime_cache[n]\n (@prime_numbers.push(n) && @prime_cache[n] = true) if is_prime(n)\n n += 1\n end\n @prime_numbers\n end",
"def first_n_primes(n)\n\n return \"n must be an integer.\" unless n.is_a? Integer\n\n return \"n must be greater than 0.\" if n <= 0\n\n return Prime.first n\n\nend",
"def select_primes(possible_primes)\n possible_primes.select { |num| is_prime?(num) }\nend",
"def prime_factors(num)\n prime_facts = []\n\n (1..num).each do |i|\n if num % i == 0 && prime?(i)\n prime_facts << i\n end\n end\n\n return prime_facts\nend",
"def prime_factors(num)\n #initialize an array\n primeFacts = []\n \n #iterate each number from 1 until num\n (1..num).each do |nums|\n #if the remainder is 0 and nums is prime push nums\n if num % nums == 0 && prime?(nums)\n primeFacts << nums\n end\n end\n return primeFacts\nend",
"def first_n_primes(n)\n\n # return \"n must be an integer.\" unless n.respond_to?(:next)\n return \"n must be an integer.\" unless n.is_a? Integer\n\n return \"n must be greater than 0.\" if n <= 0\n\n Prime.first n\nend",
"def primeArray(number)\n @sieve = Array.new(number)\n \n for count in 2..Math.sqrt(number)\n next if @sieve[count]\n \n for inner_count in 2..number/count\n @sieve[count * inner_count] = true\n end\n end\n @sieve\nend",
"def getPrimes()\n oldlimit = $primelimit + 1\n $primelimit *= 2\n\n for i in oldlimit...$primelimit\n isPrime = true\n $primes.each do |p|\n if i % p == 0\n isPrime = false\n break\n end\n end\n if isPrime\n $primes << i\n end\n end\n\nend",
"def prime?(num)\r\n # your code goes here\r\n prime = []\r\n\r\n for i in 1 .. num\r\n if num % i == 0\r\n prime << i\r\n end\r\n end\r\n prime.length == 2\r\nend",
"def specific_prime(n)\n\na = (2..n) # list of integers 2 through \nprimes = Array.new\n\nprimes = a.select { |x| (2..Math.sqrt(x)).none? { |d| (x % d).zero? }}\n\nputs primes[10000]\n# answer => 104,743\n\nend",
"def isPrime(number)\n\t\tdivisores=[]\n\t\t1.upto(number){|num| \n\t\t\tif (number % num == 0 )\n\t\t\t\tdivisores.push num\n\t\t\tend\t\t\n\t\t}\n\t\treturn divisores\n\tend",
"def largest_prime(num)\n\tresult = []\n\ti = 2\n\twhile i <= num\n\t\tif is_prime?(i)\n\t\t\tif num % i == 0 # Check for whole number if % by i \n\t\t\t\tnum = num / i # Update the num\n\t\t\t\tresult << i # Add i to the array\n\t\t\t\ti = 2 # Reset i to 2\t\n\t\t\tend\t\n\t\tend\n\t\ti += 1\t\n\tend\n\tresult\nend",
"def prime_factors(num)\n factors(num).select { |factor| prime?(factor) }\nend",
"def prime?(num)\n if num <= 1\n false\n elsif num == 2 || num == 3\n true\n elsif num > 3\n list_array = (2..num-1).to_a\n list_array.none? { |i| num % i == 0 }\n end\nend",
"def prime_number(n)\n res = []\n prime = Array.new(n + 1, true)\n (2..n).each do |x|\n num = x * x\n break if num > n\n\n if prime[x]\n (num..n).step(x).each do |multiples|\n prime[multiples] = false\n end\n end\n end\n \n (2..n).each do |primes|\n res << primes if prime[primes]\n end\n res\nend",
"def prime_factors(num)\n primes = (2..num).select { | n | isprime?(n) }\n primes.select { |prime| num % prime == 0 }\nend",
"def collect_primes(number)\n \n sieve = [nil, nil] + (2 .. number).to_a\n \n (2 .. Math.sqrt(number)).each do |n|\n next unless sieve[n]\n (n*n).step(number, n) do |num|\n sieve[num] = nil\n end\n end\n \n primes = []\n sieve.each do |x|\n if x != nil\n primes << x\n end\n end\n return primes\nend",
"def ruby_prime(n1, n2)\n prime_numbers = []\n (n1..n2).each do |num|\n if Prime.prime?(num)\n prime_numbers << num\n end\n end\n prime_numbers\nend",
"def prime_factors(num)\r\n # your code goes here\r\n prime_factors = []\r\n for i in 1 .. num\r\n if num % i == 0 && prime?(i)\r\n prime_factors << i\r\n end\r\n end\r\n prime_factors\r\nend",
"def next_prime(array)\r\n array.map {|num| prime?(num) ? next_prime(num) : num}\r\nend",
"def nth_prime(n)\n nums = (0..10000).to_a\n result = []\n\n nums.each do |i| \n if prime?(i) == true\n result.push(i)\n end\n end\n\n\n return result[n]\nend",
"def prime_factors(num)\n facs = (1..num).select {|x| num % x == 0 }\n facs.select {|x| prime?(x)}\nend",
"def primes(top)\n n = 2\n primes = []\n loop do\n primes << n if (2..Math.sqrt(n)).all? {|x| n % x != 0 }\n return primes.last if primes.count == top\n n += 1\n end\nend",
"def find_primes(int1, int2)\n nums = (int1..int2).to_a\n nums.select { |num| is_prime?(num) }\nend",
"def GetPrimes (maximum)\n\t# Clear the input vector in case there is existing data\n\tprimes = []\n\t\n\t# There are no primes less than 2\n\tif (maximum < 2)\n\t\treturn\n\tend\n\t\n\t# Construct and execute the Sieve\n\tsqrtMaximum = Math.sqrt(maximum).to_i\n\tprimeTracker = Array.new(maximum,true)\n\t\n\tfor i in 2...sqrtMaximum\n\t\tif (!primeTracker[i])\n\t\t\tnext\n\t\tend\n\t\t\n\t\tfor j in ((i+i)...maximum).step(i)\n\t\t\tif (j < 0) # Guard against integer overflow\n\t\t\t\tbreak\n\t\t\tend\n\t\t\t\n\t\t\tprimeTracker[j] = false\n\t\tend\n\tend\n\t\n\treturn primeTracker\nend",
"def prime_numbers\n s = (0..self).to_a\n s[0] = s[1] = nil\n s.each do |p|\n next unless p\n break if p * p > self\n (p*p).step(self, p) { |m| s[m] = nil }\n end\n s.compact\n end",
"def primes_array(options = {})\n limit = options[:limit] || ARRAY_DEFAULT_LIMIT\n field = Array.new(limit+1, true)\n # sieve the number field\n 3.step(field.size / 2, 2) do |k|\n (3 * k).step(field.size, 2 * k) do |n|\n field[n] = false\n end\n end\n \n # collect the field into an array, starting with 3\n primes = [ 2 ]\n 3.step(field.size, 2) do |n|\n primes << n if field[n] \n end\n primes\n end",
"def prime_factors(num)\n facts = []\n\n (1..num).each do |i|\n if num % i == 0 && prime?(i)\n facts << i\n end\n end\n \n return facts\nend",
"def find_primes_magic_value(magic_number)\n @primes = []\n number = 2\n while magic_number > 1\n if magic_number % number == 0\n magic_number /= number\n @primes << number\n end\n number += 1\n end\n\n end",
"def divisors(num)\n divisors_results = [] \n 2.upto(num - 1) do |n|\n divisors_results << n if num % n == 0\n end\n return \"#{num} is prime\" if divisors_results.empty?\n divisors_results\nend",
"def primes(n)\nend",
"def prime_factors(num)\n factors(num).select {|n| prime?(n)}\nend",
"def nth_prime(num)\n\ti = 2\n\tprime_numbers = []\n\twhile true\n\t\tif is_prime?(i)\n\t\t\tprime_numbers << i\n\t\tend\n\t\tif prime_numbers.length == num\n\t\t\treturn prime_numbers[num-1]\n\t\tend\n\t\ti +=1\n\tend\nend"
] |
[
"0.76440054",
"0.75346",
"0.74419427",
"0.74032646",
"0.73564935",
"0.73544806",
"0.7349326",
"0.73464507",
"0.7345914",
"0.73427826",
"0.72873807",
"0.7286154",
"0.7262145",
"0.7199959",
"0.7164529",
"0.71369815",
"0.7088585",
"0.7079181",
"0.70356137",
"0.70328826",
"0.70072365",
"0.6994593",
"0.69816136",
"0.6973887",
"0.6955597",
"0.69538057",
"0.69426095",
"0.6933341",
"0.69288313",
"0.6914023",
"0.6911092",
"0.69003266",
"0.689436",
"0.6893358",
"0.6867299",
"0.6860973",
"0.6859286",
"0.6859286",
"0.6853987",
"0.68200594",
"0.68130386",
"0.67895025",
"0.67708176",
"0.6756097",
"0.67416173",
"0.6704736",
"0.66648346",
"0.66555727",
"0.6631943",
"0.66232777",
"0.6619301",
"0.6613328",
"0.6593484",
"0.65820086",
"0.657748",
"0.6577013",
"0.6573454",
"0.65577936",
"0.65492105",
"0.6548191",
"0.6545664",
"0.65423155",
"0.6530002",
"0.6530002",
"0.651089",
"0.6508932",
"0.65046996",
"0.6498129",
"0.64970547",
"0.6490384",
"0.64818454",
"0.647215",
"0.64642",
"0.6461058",
"0.645447",
"0.6435875",
"0.64327264",
"0.6419679",
"0.64118135",
"0.64038867",
"0.64038837",
"0.6400354",
"0.6385938",
"0.6385356",
"0.6380323",
"0.6352771",
"0.6351539",
"0.633282",
"0.63215286",
"0.6319995",
"0.63091016",
"0.6306538",
"0.6306043",
"0.62979025",
"0.62798584",
"0.6274189",
"0.62637097"
] |
0.69505763
|
29
|
Write a method that returns the factors of a number in ascending order.
|
def factors(num)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def factors(num)\n\t((1..num).select {|n| num % n == 0 } ).sort\nend",
"def factors(num)\n factors = []\n for factor in 1..num\n factors << factor if num % factor == 0\n end\n factors.sort\nend",
"def factors(num)\n result = []\n for i in 1..num\n if num % i == 0\n result << i\n end\n end\n result.sort\nend",
"def factors(num)\n array = []\n (1..num).each do |number|\n array << number if num % number == 0\n end\n array.sort!\nend",
"def factors(number)\r\n divisor = number\r\n factors = []\r\n while divisor > 0 do \r\n factors << number / divisor if number % divisor == 0\r\n divisor -= 1\r\n end \r\n factors\r\nend",
"def factors(number)\n divisor = number\n factors = []\n #begin\n\twhile divisor > 0\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n #end until divisor == 1\n\tend\n factors\nend",
"def factors(num)\n factors = []\n (1..num).each do |factor|\n factors << factor if num % factor == 0\n end\n factors\nend",
"def factors(number)\n fs = [1,number]\n (2..Math.sqrt(number).to_i).each do |i|\n if number % i == 0\n fs << i\n fs << number/i unless number/i == i\n end\n end\n fs.sort\n end",
"def get_factors(num)\n factors = []\n (1..num).each do |i|\n factors << i if num % i == 0\n end\n factors\nend",
"def factors(number)\n dividend = 1\n divisors = []\n while dividend <= number\n divisors << dividend if number % dividend == 0\n dividend += 1\n end\n divisors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(num)\n factors = []\n (1..num).each do |n|\n factors << n if num % n == 0\n end\n factors\nend",
"def factors(num)\n factors = []\n (1..num/2).each {|n| factors << n if num % n == 0}\n factors << num\nend",
"def factors_of(num)\n factor_arr = []\n\n (1...num).reverse_each do |factor|\n if (num % factor).zero?\n factor_arr << factor\n end\n end\n\n factor_arr\nend",
"def factors(number)\n divisor = number\n factors = []\n loop do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n break if divisor == 0\n end\n factors\n \nend",
"def factors_of(num)\n # Write your code here\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0 do\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor > 0\n factors << (number / divisor) if ((number % divisor) == 0)\n divisor -= 1\n end\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n loop do\n if number == 0 || number < 0\n break\n else factors << number / divisor if number % divisor == 0\n divisor -= 1\n break if divisor == 0\n end\n end\n factors\n end",
"def factors_of(num)\n \n index = 1 \n \n factors = []\n \n while index <= num\n if num % index == 0 \n factors << index \n end \n \n index += 1 \n end \n \n return factors \n \nend",
"def find_factors(number)\n factors =[]\n for i in 1..number\n factors << i if number % i == 0\n end\n factors\nend",
"def factors( n )\n p = Primer.ld( n )\n return n if p == n\n factors n.div( p )\nend",
"def factors(num)\n 1.upto(num).select { |x| num % x == 0 }\nend",
"def factors(number)\n divisor = number\n factors = []\n loop do\n break if number <= 0\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n break if divisor == 0\n end \n factors\nend",
"def factors_of(num)\n factors = []\n \n i = 1\n while i <= num\n # if num is divided by i\n if num % i == 0\n factors << i\n end\n \n i += 1\n end\n \n return factors\n end",
"def factors(number)\n divisor = number\n factors = []\n loop do\n break if divisor <= 0\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end\n factors\nend",
"def factors(num)\n output_arr = []\n\n (1..num).each do |el|\n if num % el == 0\n output_arr << el\n end\n end\n\n output_arr.sort\nend",
"def factors(num)\r\n # your code goes here\r\n\r\n factors = []\r\n for i in 1 .. num\r\n if num % i == 0\r\n factors << i\r\n end\r\n end\r\n factors\r\nend",
"def factors(number)\n divisor = number\n factors = []\n begin\n # evaluate statement on right side of shovel operator and if\n # divisor evenly divides number then add into factors array \n factors << number / divisor if number % divisor == 0\n # decrement divisor by 1\n divisor -= 1\n # stops when divisor is 0\n end until divisor == 0\n \n # return all factors in an array that divides evenly with \n # the number passed in as an argument when calling the function\n factors\nend",
"def factors(number)\n divisors = []\n # 1 is always a divisor\n divisors << 1\n if number > 1\n # target number is also always a divisor\n divisors << number\n # start looking for other divisors from 2 on up.\n i = 2\n while (i <= Math.sqrt(number).to_i)\n # if number is evenly divisible by i, then retain i, and possibly also\n # the division of number/i.\n if (number % i == 0)\n divisors << i\n divisors << number/i if (i != number/i)\n end\n i += 1\n end\n divisors.sort!\n end\n divisors\nend",
"def factors(num)\n arr = [1]\n i = 1\n while i <= num\n arr << i if (num % i).zero?\n i += 1\n end\n arr.uniq.sort\nend",
"def factors n\n 1.upto(Math.sqrt(n)).select{ |x| (n % x).zero?}.inject([]) do |arr,x|\n arr << x\n arr << n/x unless x == n/x\n arr.sort\n end\nend",
"def factors(number)\n divisor = number\n factors = []\n begin\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end until divisor == 0\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n begin\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end until divisor == 0\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n begin\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end until divisor == 0\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n begin\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end until divisor == 0\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n begin\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end until divisor == 0\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n begin\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end until divisor == 0\n factors\nend",
"def factors(number)\n divisor = number\n factors = []\n while divisor != 0\n # not the cleanest way to do it, will return the same results\n # if we take the abs value of the number, removing the ternary operator\n factors << number / divisor if number % divisor == 0\n divisor > 0 ? divisor -= 1 : divisor += 1\n end\n factors\nend",
"def factors(num)\n factors = []\n (1..num).each do |i| \n factors << i if num % i === 0\n end\n factors\nend",
"def factors(number)\n dividend = number\n divisors = []\n number.times do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while number >= 1\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n break if dividend == 0\n end\n divisors\nend",
"def factors(num)\r\n factors = []\r\n sqrt = Math.sqrt(num)\r\n until num == 1\r\n\r\n factor_founded = false\r\n (2..sqrt).each do |i|\r\n if (num % i).zero?\r\n num /= i\r\n factors << i\r\n factor_founded = true\r\n break\r\n end\r\n end\r\n unless factor_founded\r\n factors << num\r\n num /= num\r\n end\r\n end\r\n return factors\r\nend",
"def old_factors(num)\n factors = []\n (1..num).each do |i|\n if num % i == 0\n factors << i\n end\n end\n factors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while number > 0\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(num)\n factors = Prime.prime_division(num)\n result = []\n factors.each { |factor, power| result += [factor] * power }\n result\nend",
"def factors(number)\n factors = []\n divisor = number\n while divisor > 0 do\n factors << (number / divisor) if number % divisor == 0\n divisor -= 1\n end\n if divisor <= 0\n puts \"Invalid number: no 0's or negatives!\"\n else\n end\n factors\n end",
"def factors_of(num)\n divide_by = []\n \n i = 1\n while i <= num\n if num % i == 0\n divide_by << i\n end\n \n i += 1\n end\n \n return divide_by\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n divisors = []\n if number > 0 \n dividend = number\n begin\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end until dividend == 0\n divisors\n end\n divisors\nend",
"def factors(num)\n\n factors = []\n # iterate through all nums from 1 to num\n # add to factors if evenly divisible\n # return factors\n\n i = 1\n while i <= num\n factors << i if num % i == 0\n i += 1\n end\n\n factors\n\nend",
"def factors(num)\n facs = [1]\n (2..num/2).each{|n| facs.push(n) if num % n == 0 }\n facs.push(num)\nend",
"def factors num\n f = Array.new # creates a new array to store factors\n 1.upto(num) do |i|\n f << i if num%i == 0\n end\n f # returns factors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end \n divisors\nend",
"def factors num\n if num != 1\n #Start with 1 and num as the first factors\n c = 2\n 2.upto(num/2) { |f|\n if num % f == 0\n c += 1\n end\n }\n else\n c = 1\n end\n\n c\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def factors(num)\n result = [1]\n\n (2..num).each do |el|\n result << el if num % el == 0\n end\n result\nend",
"def factor(num)\n\tcurrent_factor = num/2\n\tfactors = []\n\tfactors << num\n\twhile current_factor > 0\n\t\tif num%current_factor == 0\n\t\t\tfactors << current_factor\n\t\t\tcurrent_factor -= 1\n\t\telse\n\t\t\tcurrent_factor -= 1\n\t\tend\n\tend\n\t\n\treturn factors\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend",
"def find_factors(num)\n raise ArgumentError, \"num must be >= 0\" if num < 0\n return [n] if num <= 1\n result = []\n\n n = num\n if n.even?\n while n % 2 == 0\n result << 2\n n /= 2\n end\n end\n\n div = 3\n\n while (n > 1)\n while n % div == 0\n result << div\n n /= div\n end\n div += 2\n\n if (div * div > n)\n result << n\n break\n end\n end\n\n result\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\nend",
"def factors(num)\n (1..num).select { |el| num % el == 0 }\nend",
"def factors_of(num)\n\tnums = []\n \n\ti = 1\n\twhile i <= num\n\t\tif num % i == 0\n\t\t\tnums << i\n end\n\t\ti += 1\n end\n \n\treturn nums\nend",
"def factors(num)\n factors = []\n (1..num).each do |i|\n factors << i if num % i == 0\n end\n \n factors\nend",
"def factors(number)\n dividend = number\n divisors = []\n begin\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end until dividend == 0\n divisors\nend",
"def factors(number)\n dividend = number\n divisors = []\n begin\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end until dividend == 0\n divisors\nend",
"def factors(num)\n (1..num).select{|i| num % i == 0 }\nend",
"def factors(number)\r\n divisor = number\r\n factors = []\r\n while divisor > 0 do \r\n factors << number / divisor if number % divisor == 0 #Allows you to determine if the result of the division is an integer number (no remainder).\r\n divisor -= 1\r\n end \r\n factors #with no return statement, the last line is returned - in this case we want to return 'factors'\r\nend",
"def find_factors(number)\n\t# start with lowest prime number\n\tinteger = 2\n\n\t# make sure integer doesn't exceed the actual number\n\twhile integer <= number do\n\t\t# integer will be returned when if it is a factor of number\n\t\treturn integer if number % integer == 0\n\n\t\t# if integer is not a factor move to next integer\n\t\tinteger += 1\n\tend\nend",
"def factors(num)\n facs = []\n i = 1\n while i <= num\n if num % i == 0\n facs << i\n end\n i += 1\n end\n facs\nend",
"def factors(num)\n return nil if num <= 0\n return [1] if num == 0\n (1..num).select { |i| (num % i) == 0 }\nend",
"def factors(number)\n dividend = number\n divisors = []\n while dividend > 0\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end \n divisors\nend",
"def factors(num)\n (1..num).select { |n| num%n == 0}\nend",
"def factors_of(num)\n (1..num).select{|ele| num % ele == 0}\nend",
"def factors(number)\n return \"number must be greatr than zero\" if (number == 0 || number < 0 )\n \n divisor = number\n factors = []\n begin\n factors << number / divisor if number % divisor == 0\n divisor -= 1\n end until divisor == 0\n factors\nend",
"def factors(num)\n arr = []\n for i in 1..num\n if num%i == 0\n arr << i\n end\n end\n arr\nend",
"def factors(num)\n arr = []\n (2..num).each do |ele|\n if (num % ele == 0)\n arr << ele\n end\n end\n return arr\nend",
"def proper_factors(n)\n f = []\n 1.step((n/2).to_i, 1).each do |x|\n if n % x == 0\n f.push(x)\n end\n end\n f.sort\nend",
"def factors(number)\n dividend = number\n divisors = []\n begin\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end until dividend == 0\ndivisors\nend",
"def factors(num)\n return nil if num < 0\n return 1 if num == 1\n (1..num).select { |n| num % n == 0}\n\n\nend",
"def factors(num)\n (1..num).select {|x| num % x == 0 }\nend"
] |
[
"0.8575256",
"0.8532261",
"0.8478011",
"0.8477378",
"0.83777696",
"0.83758056",
"0.83459604",
"0.8343072",
"0.83401227",
"0.83394605",
"0.8335541",
"0.8334777",
"0.83283925",
"0.831717",
"0.8308934",
"0.8308751",
"0.8306715",
"0.8306715",
"0.8306715",
"0.8306715",
"0.8306715",
"0.8306715",
"0.8306223",
"0.8293108",
"0.828284",
"0.8263457",
"0.8262555",
"0.82589656",
"0.8257303",
"0.825384",
"0.8241848",
"0.82366407",
"0.8234455",
"0.8232248",
"0.8232091",
"0.82254106",
"0.82225275",
"0.8222441",
"0.8222441",
"0.8222441",
"0.8222441",
"0.8221817",
"0.8220656",
"0.821778",
"0.8206889",
"0.8205384",
"0.8205122",
"0.8184918",
"0.81831837",
"0.8167484",
"0.81657904",
"0.8163399",
"0.8161173",
"0.81599754",
"0.81599754",
"0.81599754",
"0.81599754",
"0.81599754",
"0.8159557",
"0.8157975",
"0.8153991",
"0.8147879",
"0.8139062",
"0.8130481",
"0.8128632",
"0.8128632",
"0.8128632",
"0.8128632",
"0.8128632",
"0.8128632",
"0.8128632",
"0.8128632",
"0.8128632",
"0.8127093",
"0.8126653",
"0.8125773",
"0.81210506",
"0.8118973",
"0.81023043",
"0.8101314",
"0.80968803",
"0.80957204",
"0.80957204",
"0.8090223",
"0.80869526",
"0.8085958",
"0.80847776",
"0.8082092",
"0.80817866",
"0.8081428",
"0.8076611",
"0.80744064",
"0.80637985",
"0.8060301",
"0.8059127",
"0.8046761",
"0.8043816",
"0.8040869"
] |
0.84801
|
4
|
Write an `Arraymy_controlled_flatten(n)` method that only flattens n levels of an array. For example, if you have an array with 3 levels of nested arrays, and run `arr.my_flatten(1)`, you should return an array with 1 level of nested arrays flattened. Example: `[1,[2,3], [4,[5]]].my_controlled_flatten(1)` => [1,2,3,4,[5]]
|
def my_controlled_flatten(n)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def my_controlled_flatten(n)\n flattened = []\n self.my_each do |el|\n if n > 0 && el.is_a?(Array)\n flattened += el.my_controlled_flatten(n - 1)\n else\n flattened << el\n end\n end\n flattened\n end",
"def my_controlled_flatten(n)\n flattened = []\n\n self.each do |el|\n depth = 0\n if el.is_a?(Array)\n depth += 1\n flattened += el.my_flatten\n else\n flattened << el\n end\n end\n flattened\n end",
"def my_controlled_flatten(n)\n return self if n < 1\n new_arr = []\n my_each {|el| new_arr += (el.is_a?(Array) ? el.my_controlled_flatten(n-1) : [el])}\n new_arr\n end",
"def my_controlled_flatten(n)\n return self if n == 0\n new_arr = []\n self.each do |el|\n if el.is_a? (Array)\n new_arr += el.my_controlled_flatten(n-1)\n else\n new_arr << el\n end\n end\n new_arr\n end",
"def my_controlled_flatten(n)\n return self if n == 0\n result = []\n self.each do |el|\n result << el unless el.is_a? Array\n result += el.my_controlled_flatten(n - 1) if el.is_a? Array\n end\n result\n end",
"def my_controlled_flatten(n)\n return self if n == 0\n result = []\n self.each do |el|\n result << el unless el.is_a? Array\n result += el.my_controlled_flatten(n - 1) if el.is_a? Array\n end\n result\n end",
"def my_controlled_flatten(n)\n return self if n == 0\n flattened = []\n\n self.each do |el|\n if el.is_a? Array\n next_val = n.nil? nil : n - 1\n flattened += el.my_controlled_flatten(next_val)\n else\n flattened += el\n end\n end\n\n flattened\n end",
"def my_controlled_flatten(n=1)\n #here\n return self if n < 1\n\n results = []\n self.each do |el|\n if el.class == Array\n #here\n results += el.my_controlled_flatten(n-1)\n else\n results << el\n end\n end\n\n results\n\n end",
"def my_controlled_flatten(level = nil)\n flattened = []\n\n self.each do |ele|\n if ele.is_a?(Array) && level != 0\n flattened += (level.nil? ? ele.my_controlled_flatten : ele.my_controlled_flatten(level - 1))\n else\n flattened << ele\n end\n end\n\n flattened\n end",
"def my_controlled_flatten(level = nil)\n flattened = []\n\n self.each do |ele|\n if ele.is_a?(Array) && level != 0\n flattened += (level.nil? ? ele.my_controlled_flatten : ele.my_controlled_flatten(level - 1))\n else\n flattened << ele\n end\n end\n\n flattened\n end",
"def using_flatten(array)\n array.flatten()\nend",
"def using_flatten(array)\n array.flatten\nend",
"def using_flatten(array)\n array.flatten\nend",
"def using_flatten(arr)\n arr.flatten\nend",
"def using_flatten(array)\n array.flatten\nend",
"def using_flatten(array)\n array.flatten\nend",
"def using_flatten(array)\n array.flatten\nend",
"def using_flatten(array)\n array.flatten\nend",
"def using_flatten(array)\n array.flatten\nend",
"def using_flatten(array)\n array.flatten\nend",
"def my_flatten(arr, flattened_arr = [])\nend",
"def my_flatten\n flattened_array = []\n each do |item|\n if item.class != Array\n flattened_array << item\n else\n #recursevly call my flatten\n item.my_flatten.each { |sub_item| flattened_array << sub_item }\n end\n end\n flattened_array\n end",
"def using_flatten(array)\n \n array.flatten\n \nend",
"def using_flatten(array)\n array.flatten\n \nend",
"def using_flatten (array)\n return array.flatten!\nend",
"def using_flatten(array)\n array.flatten\n end",
"def my_flatten\n arr = []\n i = 0\n while i < self.length\n if self[i].is_a? Array\n arr += self[i].my_flatten\n else\n arr << self[i]\n end\n i += 1\n end\n return arr\n end",
"def flatten(array)\n array.flatten(1)\nend",
"def flatten(array)\n array.flatten(1)\nend",
"def my_flatten\n flattened = []\n self.my_each do |el|\n el.is_a?(Array) ? flattened += el.my_flatten : flattened << el\n end\n flattened\n end",
"def my_flatten\n flattened = []\n self.my_each do |el|\n if el.is_a? Array\n flattened += el.my_flatten\n else\n flattened << el\n end\n end\n flattened\n end",
"def my_flatten(array)\n print array.flatten\n end",
"def my_flatten\n flattened = []\n self.my_each do |el|\n el.is_a?(Array) ? flattened.concat(el.my_flatten) : flattened << el\n end\n flattened\n end",
"def my_flatten_recursive \n results = []\n self.my_each do |ele|\n if ele.is_a? Array \n results.concat(ele.my_flatten_recursive)\n else \n results<< ele\n end\n end\n results\n\n end",
"def my_flatten\n # return self unless self.is_a?(Array)\n new_arr = []\n self.each do |el|\n if el.is_a?(Array)\n new_arr += el.my_flatten\n else\n new_arr << el\n end\n end\n new_arr\n end",
"def my_flatten!\n self.replace(my_flatten)\n end",
"def recursively_flatten_finite(array, out, level)\n ret = nil\n if level <= 0\n out.concat(array)\n else\n array.each do |o|\n if ary = Backports.is_array?(o)\n recursively_flatten_finite(ary, out, level - 1)\n ret = self\n else\n out << o\n end\n end\n end\n ret\n end",
"def recursively_flatten_finite(array, out, level)\n ret = nil\n if level <= 0\n out.concat(array)\n else\n array.each do |o|\n if ary = Backports.is_array?(o)\n recursively_flatten_finite(ary, out, level - 1)\n ret = self\n else\n out << o\n end\n end\n end\n ret\n end",
"def convert_1_level_deep(arr, result=[])\n arr.flatten.each_slice(3) { |ele| result.push(ele)}\n result\nend",
"def flatten(data, level = 0)\n return [data] unless data.is_a?(Array) \n flat = []\n data.each do |ele|\n if ele.is_a?(Array)\n flat += flatten(ele, level + 1)\n else\n flat << ele\n end\n end\n flat\nend",
"def flatten_array(arr)\n arr.flatten\nend",
"def recursive_flatten(incoming_array, new_flattened_array = [])\n incoming_array.each do |item|\n if item.class == Array\n # Recursion\n recursive_flatten(item, new_flattened_array)\n else\n new_flattened_array << item\n end\n end\n new_flattened_array\n end",
"def one_line_flatten(array, ret = [])\n array.each { |x| x.is_a?(Array) ? one_line_flatten(x, ret) : ret << x }; ret\nend",
"def applying_flatten array_value\n return array_value.flatten!\n end",
"def flatten\n\t\tmake_flat(@array)\n\tend",
"def flatten_with_optional_argument!(level=-1)\n level = Backports.coerce_to_int(level)\n return flatten_without_optional_argument! if level < 0\n\n out = []\n ret = recursively_flatten_finite(self, out, level)\n replace(out) if ret\n ret\n end",
"def flatten!() end",
"def arr\n a = [1,2,[3,4,[5]]]\n return a.flatten\nend",
"def flatten(a, flat=[])\n if a.class != Array\n # base case\n flat << a\n else\n a.each {|v| flatten(v, flat)}\n end\n flat\nend",
"def flatten(depth = -1)\n to_a.flatten(depth)\n end",
"def unflatten(flat_array)\n result = []\n x = 0\n\n while x < flat_array.length do \n if flat_array[x] < 3 \n result.push flat_array[x]\n x += 1\n else\n temp = [*flat_array[x...x + flat_array[x]]]\n result.push temp \n x += flat_array[x]\n end\n end\n result \nend",
"def flatten() end",
"def flatten_with_optional_argument!(level=-1)\n level = Backports.coerce_to_int(level)\n return flatten_without_optional_argument! unless level >= 0\n\n ret, out = nil, []\n ret = recursively_flatten_finite(self, out, level)\n replace(out) if ret\n ret\n end",
"def flatten(array)\n a = []\n array.each do |n|\n if n.is_a? Array\n b = flatten(n)\n b.each { |x| a << x }\n else\n a << n\n end\n end\n a\nend",
"def flatten_deeper(array)\n array.collect { |element| element.respond_to?(:flatten) ? element.flatten : element }.flatten\n end",
"def my_flatten(final_arr = []) \n self.my_each do |el|\n debugger\n if el.class == Integer\n final_arr << el\n else\n el.my_flatten(final_arr)\n end\n end\n result\n end",
"def flatt(arr, flat_arr = [])\n arr.each do |element|\n if element.is_a?(Array)\n flatt(element, flat_arr)\n else\n flat_arr << element\n end\n end\n flat_arr\nend",
"def flatten!\n\t\t@array = make_flat(@array)\n\tend",
"def flatten(array)\n return [] if array.empty?\n\n res = []\n array.each do |el|\n if el.is_a? Array\n res += flatten(el)\n else\n res << el\n end\n end\n res\nend",
"def flatten(list)\n list.flatten\nend",
"def flatten!\n self.replace(flatten)\n end",
"def flatten(nested_array, result = [])\n nested_array.each do |integer|\n if integer.class == Array\n flatten(integer, result)\n else\n result << integer\n end\n end\n result\nend",
"def flatten!\n # buggerit\n raise NotImplementedError\n end",
"def flatten(array, result = [])\n array.each do |element|\n if element.is_a?(Array)\n flatten(element, result)\n else\n result << element\n end\n end\n result\nend",
"def flatten(array)\n raise NonArrayError, 'argument must be an array' unless array.is_a? Array\n\n array.each_with_object([]) do |element, memo|\n if element.is_a?(Array)\n memo.push(*flatten(element))\n else\n memo.push(element)\n end\n end\nend",
"def flatten!\n nil\n end",
"def test_fix_nested_array\n array = [1, [2], [3, [4,[5]]], 6]\n array = array.flatten\n assert_equal [1,2,3,4,5,6], array\n end",
"def flatten_aoi_recursive(array)\n return nil if array.nil?\n result = []\n array.each do |element|\n if element.is_a?(Array)\n f_array = flatten_aoi_recursive(element)\n f_array.each do |f_element|\n result << f_element\n end\n else\n result << element\n end\n end\n result\nend",
"def flatten_deeper(array)\n array.collect do |element|\n (element.respond_to?(:flatten) && !element.is_a?(Hash)) ? element.flatten : element\n end.flatten\n end",
"def flatten_array(array, result = [])\n array.each do |element|\n if element.is_a? Array\n flatten_array(element, result)\n else\n result << element\n end\n end\n result\nend",
"def flatten(array)\n new_array = []\n array.each do |x|\n if x.class == Array\n x.each {|y| new_array.push(y)}\n else\n new_array.push(x)\n end\n end\n new_array\nend",
"def flatten(array)\n return [] if array.empty? \n list = []\n head = array[0]\n rest = array[1..-1]\n if head.is_a? Array \n flatten(head) + flatten(rest)\n else \n list += [head] + flatten(rest)\n end \nend",
"def _recursively_flatten_to!(array, out)\n array.each do |o|\n if NodeList === o\n _recursively_flatten_to!(o.nodes, out)\n elsif o.respond_to?(:to_ary)\n ary = Array === o ? o : o.to_ary\n _recursively_flatten_to!(ary, out)\n else\n out << o\n end\n end\n end",
"def flatten\n map {|item| item.respond_to?(:flatten) ? item.flatten : item }.flatten\n end",
"def flat(a)\n\tnew_arr = []\n\ta.each do |el|\n\t\tif el.is_a? Array\n\t\t\tel.each do |n|\n\t\t\t\tif el.is_a? Array\n\t\t\t\t\ta << n\n\t\t\t\telse\n\t\t\t\t\tnew_arr << n\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\tnew_arr << el\t\n\t\tend\n\tend\n\tp new_arr\nend",
"def flatten\n a=[]\n self.deep_each {|f| a << f}\n a\n end",
"def flatten_array(arr)\n arr.each_with_object([]) do |item, flat|\n if item.is_a? Integer\n flat << item\n else\n flatten_array(item).each do |num|\n flat << num\n end\n end\n end\nend",
"def flatten(array)\n container = []\n\n array.each do |element|\n if element.is_a?(Array)\n container += element\n else\n container << element\n end\n end\n\n container\nend",
"def flat_map(n = 1, &f)\n _flat_map do |elem|\n if n.eql? 1\n yield elem\n else\n elem.flat_map n - 1, &f\n end\n end\n end",
"def multi_dimensional_sum(array)\n\n puts \"With the built-in flatten method:\"\n puts array.flatten.inject { |acc, num| acc + num }\n\n puts \"With my flatten method:\"\n puts my_flatten(array).inject { |acc, num| acc + num}\n\n return \"----\"\n\nend",
"def flatten_without_hooks!\n\n @without_hooks = true\n\n return_value = flatten!\n \n @without_hooks = false\n\n return return_value\n\n end",
"def array_subsets(arr)\n return arr if arr.length == 0 || arr.length == 1\n new_arr = []\n new_arr << [arr[0]] + array_subsets(arr[1..-1])\n \n # length = 1\n # new_arr = [[]]\n # while length <= arr.length\n # arr.each do |el|\n # new_arr << Array.new(length) { el }\n # end\n # length += 1\n # end\nend",
"def flatten(*args)\n new_array = []\n self.each do |v|\n if v.is_a?(Array)\n new_array.push( *(v.flatten(*args)) )\n else\n new_array << v\n end\n end\n new_array\n end",
"def ensure_flat_array_value(value)\n if value.kind_of?(Array)\n value.flatten!\n else\n value = [value]\n end\n value\n end",
"def flatten\n dup\n end",
"def inject_deep_flat(list, remaining_path, multiplicity)\n return inject_deep(list, remaining_path) if multiplicity == 0\n\n flat_input = list.flat_map { |v| v.nil? ? [] : v }\n flat_output = inject_deep_flat(flat_input, remaining_path, multiplicity - 1)\n item_index = -1\n list.map { |v| v&.map { flat_output[item_index += 1] } }\n end",
"def flatten(arr)\n\n flat = []\n\n arr.each do |el|\n if el.class != Array\n flat << el \n else\n #flatten(el).each {|char| flat << char}\n flat.push(*flatten(el))\n end\n end\n flat \nend",
"def flatten\n self.class.new.flatten_merge(self)\n end",
"def flatten\n self.class.new.flatten_merge(self)\n end",
"def test_flatten_once\n ary = [1, [2, [3, 4]], [5]]\n flatter_ary = [1, 2, [3, 4], 5]\n assert_equal flatter_ary, OneLiner.flatten_once(ary)\n end",
"def test_flatten_once\n ary = [1, [2, [3, 4]]]\n flatter_ary = [1, 2, [3, 4]]\n assert_equal flatter_ary, OneLiner.flatten_once(ary)\n end",
"def subsets(arr)\n return [[]] if arr.empty?\n # debugger\n # take - return first n elements\n\n subArr = arr.take(arr.count - 1)\n\n subs = subsets(subArr)\n\n # concat Appends the elements of other_ary to self.\n # tyle co +\n subArrays = subs.map { |sub| sub + [arr.last] }\n subs.concat(subArrays)\nend",
"def flat(arr1=[],arr2=[],i=0)\n if i >= arr1.length\n return arr2\n else\n if arr1[i].kind_of?(Array)\n flat(arr1[i],arr2) \n else\n arr2.push(arr1[i])\n end\n return flat(arr1,arr2,i+1)\n end\nend",
"def flatten(value, named=false) # :nodoc:\n # Passes through everything that isn't an array of things\n return value unless value.instance_of? Array\n\n # Extracts the s-expression tag\n tag, *tail = value\n\n # Merges arrays:\n result = tail.\n map { |e| flatten(e) } # first flatten each element\n \n case tag\n when :sequence\n return flatten_sequence(result)\n when :maybe\n return named ? result.first : result.first || ''\n when :repetition\n return flatten_repetition(result, named)\n end\n \n fail \"BUG: Unknown tag #{tag.inspect}.\"\n end",
"def flatten_object something\r\n if something.is_a? Hash\r\n super_flatten_hash(something)\r\n elsif something.is_a? Array\r\n super_flatten_array(something)\r\n else\r\n something\r\n end\r\nend",
"def multi_dimensional_sum(array)\n array.flatten\nend",
"def flatten\n # if any item is a Set or Java Collection, then convert those into arrays before recursively flattening the list\n if any? { |item| Set === item or Java::JavaUtil::Collection === item } then\n return map { |item| (Set === item or Java::JavaUtil::Collection === item) ? item.to_a : item }.flatten\n end\n base__flatten\n end",
"def flatten_repetition(list, named) # :nodoc:\n if list.any? { |e| e.instance_of?(Hash) }\n # If keyed subtrees are in the array, we'll want to discard all \n # strings inbetween. To keep them, name them. \n return list.select { |e| e.instance_of?(Hash) }\n end\n\n if list.any? { |e| e.instance_of?(Array) }\n # If any arrays are nested in this array, flatten all arrays to this\n # level. \n return list.\n select { |e| e.instance_of?(Array) }.\n flatten(1)\n end\n \n # Consistent handling of empty lists, when we act on a named result \n return [] if named && list.empty?\n \n # If there are only strings, concatenate them and return that. \n foldl(list) { |s,e| s+e }\n end",
"def flatten( level = 1 )\n\n load_parent_state\n \n return super\n\n end"
] |
[
"0.8790983",
"0.8764352",
"0.87516683",
"0.8651184",
"0.8626679",
"0.8626679",
"0.86212575",
"0.7940102",
"0.7869281",
"0.7869235",
"0.70922625",
"0.6985684",
"0.6985684",
"0.69841427",
"0.69667184",
"0.69667184",
"0.69667184",
"0.69667184",
"0.69667184",
"0.69667184",
"0.6950921",
"0.6922009",
"0.6882481",
"0.68739396",
"0.68562365",
"0.67931867",
"0.67908686",
"0.67167175",
"0.67167175",
"0.6701296",
"0.6694228",
"0.6669934",
"0.6634364",
"0.654137",
"0.6487084",
"0.64744604",
"0.6463511",
"0.6463511",
"0.6357012",
"0.6356825",
"0.635198",
"0.63456947",
"0.63147146",
"0.62739396",
"0.6270234",
"0.62133306",
"0.6208957",
"0.6206176",
"0.6145087",
"0.6137024",
"0.61186516",
"0.6107367",
"0.6095146",
"0.6084945",
"0.60770047",
"0.6029273",
"0.5990396",
"0.598951",
"0.59485376",
"0.5920666",
"0.5918217",
"0.59020805",
"0.5892663",
"0.5869255",
"0.58621126",
"0.58497465",
"0.57784915",
"0.57476676",
"0.5718837",
"0.5715353",
"0.56905097",
"0.56631166",
"0.5661154",
"0.55996263",
"0.55913156",
"0.55781335",
"0.5568419",
"0.55664855",
"0.5523912",
"0.55119133",
"0.5497235",
"0.5438686",
"0.5434262",
"0.543059",
"0.5380431",
"0.5377793",
"0.5340968",
"0.5312594",
"0.5312594",
"0.5270327",
"0.5253385",
"0.51445836",
"0.51332235",
"0.5058778",
"0.50565815",
"0.5046382",
"0.50395226",
"0.50305134",
"0.50255114"
] |
0.83443964
|
8
|
GET /certifieds GET /certifieds.json
|
def index
@certifieds = Certified.where(user: self.current_user)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def index\n @certifications = Certification.all\n end",
"def certs\n request :get, '/certs'\n end",
"def set_certified\n @certified = Certified.find(params[:id])\n end",
"def index\n @certifications = @certifications.sort_by(&:name)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @certifications }\n end\n end",
"def index\n @certs = Cert.all\n end",
"def index\n @certs = Cert.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @certs }\n end\n end",
"def show\n @certification_users = []\n\n #TODO: make a better SQL query for this\n @certification.users.sort_by(&:name).each do |user|\n @certification_users.push user if can? :read, user\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @certification }\n end\n end",
"def show\n @concerts = Concert.find(params[:id])\n end",
"def index\n @certainties = Certainty.all\n end",
"def index\n @certifications = Certification.visible :view_certifications\n end",
"def cert_chain\n service = Service.find(params[:id])\n response = service.certificate.full_chain(true)\n render json: response\n end",
"def index\n if params[:s]\n @certs = Cert.where('name = ?', params[:s])\n else\n @certs = Cert.all\n end\n end",
"def index\n @concerts = Concert.all\n end",
"def index\n @concerts = Concert.all\n end",
"def index\n @concerts = Concert.all\n end",
"def index\n @concerts = Concert.all\n end",
"def certified_employees(company_id=nil)\n if company_id.nil?\n get(\"employees/wotc/certified\")\n else\n get(\"employees/wotc/certified?company_id=#{company_id}\")\n end\n end",
"def destroy\n @certified.destroy\n respond_to do |format|\n format.html { redirect_to certifieds_url }\n format.json { head :no_content }\n end\n end",
"def create\n @certified = Certified.new(certified_params)\n @certified.events = events\n @certified.attendees = attendees\n @certified.slug = generate_token\n @certified.user = self.current_user\n\n flash[:notice] = \"Certificado criado com sucesso.\" if @certified.save\n\n respond_with(@certified) do |format|\n format.html { redirect_to @certified }\n end\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @certification }\n end\n end",
"def index\n @certificate_authorities = CertificateAuthority.all\n @certificate_authorities.each { |ca| ca.collect_certificates }\n end",
"def create\n respond_to do |format|\n if @certification.save\n format.html { redirect_to Certification, :notice => 'Certification was successfully created.' }\n format.json { render :json => @certification, :status => :created, :location => @certification }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @certification.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def certificates\n http_path = \"http://localhost:8081/auth/realms/master/protocol/openid-connect/certs\"\n url = URI(http_path)\n http = Net::HTTP.new(url.host, url.port)\n # request = Net::HTTP::Post.new(url.to_s)\n request = Net::HTTP::Get.new(url.to_s)\n #request[\"authorization\"] = 'bearer ' + token\n #request[\"content-type\"] = 'application/json'\n #body = {}\n\n #request.body = body.to_json\n response = http.request(request)\n puts \"RESPONSE\", response.read_body\n response_json = parse_json(response.read_body)[0]\nend",
"def keycerts; end",
"def index\n @certificates = Certificate.all\n end",
"def index\n @certificates = Certificate.all\n end",
"def index\n professors = Professor.includes(:courses).all\n\n render json: professors.to_json(include: :courses)\n end",
"def list\n cert_list(certstore_handler)\n end",
"def index\n @certtests = Certtest.all\n end",
"def new\n # get the authority\n @authority = Certify::Authority.find(params[:certify_authority_id])\n\n # generate a new one\n @certificate = Certify::Certificate.new()\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @certificate }\n end\n end",
"def index\n @certificate_requests = CertificateRequest.all\n end",
"def index\n courses = Course.includes(:professors).includes(:ratings).all\n\n render json: courses.to_json(include: [:professors, :ratings])\n end",
"def create\n @certification = Certification.new(certification_params)\n\n respond_to do |format|\n if @certification.save\n format.html { redirect_to @certification, notice: 'Certification was successfully created.' }\n format.json { render :show, status: :created, location: @certification }\n else\n format.html { render :new }\n format.json { render json: @certification.errors, status: :unprocessable_entity }\n end\n end\n end",
"def show\n @certified_repository = CertifiedRepository.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @certified_repository }\n end\n end",
"def index\n @classifieds = Classified.all\n end",
"def create\n @cert = Cert.new(cert_params)\n\n respond_to do |format|\n if @cert.save\n format.html { redirect_to @cert, notice: 'Cert was successfully created.' }\n format.json { render action: 'show', status: :created, location: @cert }\n else\n format.html { render action: 'new' }\n format.json { render json: @cert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def get_students\n @course = Course.find(params[:course_id])\n\n render json: @course.students\n end",
"def distrust_certs()\n process_certs(\"Explicitly distrusting certs\", CertTools.distrusted_certs_dir)\n end",
"def create\n @cert = Cert.new(cert_params)\n\n respond_to do |format|\n if @cert.save\n format.html { redirect_to @cert, notice: 'Cert was successfully created.' }\n format.json { render :show, status: :created, location: @cert }\n else\n format.html { render :new }\n format.json { render json: @cert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @careers = Career.all\n json_response(@careers)\n end",
"def show\n render json: @citation\n end",
"def show\n render json: @citation\n end",
"def index\n @citations = Citation.all\n\n render json: @citations\n end",
"def cert_content; end",
"def make_certificates\n # @contest is fetched by CanCan\n\n # Define params for PDF output\n prawnto filename: \"urkunden#{random_number}\", prawn: { page_size: 'A4', skip_page_creation: true }\n @performances = apply_scopes(Performance)\n .joins(:contest_category)\n .where(\"contest_categories.contest_id = ?\", @contest.id)\n .accessible_by(current_ability)\n .order(:stage_time)\n .paginate(page: params[:page], per_page: 15)\n end",
"def index\n @critical_factors = CriticalFactor.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @critical_factors }\n end\n end",
"def index\n @expertises = Expertise.all\n\n render json: @expertises\n end",
"def certificate_list\n return @cert_list unless @cert_list.nil?\n cmd = <<-EOF\n $certs_list = Get-Item '#{resource[:cert_dir]}\\\\*' | Where-object { $_.FriendlyName -eq '#{resource[:cert_name]}' }\n if ($certs_list) {\n $data = @()\n foreach ($cert in $certs_list) {\n # don't put this in one big expression, this way powershell throws an error on the specific\n # line that is having a problem, not the beginning of the expression\n $data += @{\n 'not_after'= $cert.NotAfter.ToString(\"o\"); # Convert to ISO format\n 'not_before' = $cert.NotBefore.ToString(\"o\");\n 'serial_number' = $cert.SerialNumber;\n 'thumbprint' = $cert.Thumbprint;\n }\n }\n # powershell is dumb and will \"unbox\" a single-element array and return just the elemtn\n # we really want an array though... thanks PowerShell...\n ConvertTo-Json @($data)\n }\n EOF\n res = ps(cmd)\n Puppet.debug('parsing cert json')\n Puppet.debug(\"got output: #{res}\")\n # add to check for truthy stdout because, if the cert doesn't exist the output\n # could be nil / empty string\n @cert_list = if res[:exitcode].zero? && res[:stdout]\n JSON.parse(res[:stdout])\n else\n false\n end\n Puppet.debug(\"finished getting cert list: #{@cert_list}\")\n @cert_list\n end",
"def index\n @consents = Consent.all\n render json: @consents\n end",
"def index\n @course_certificates = CourseCertificate.all\n end",
"def show\n render json: @course, status: :found\n end",
"def create\n @certification = Certification.new(certification_params)\n\n respond_to do |format|\n if @certification.save\n format.html { redirect_to certifications_url, notice: 'Certification was successfully created.' }\n else\n format.html { render :new }\n end\n end\n end",
"def create\n @certification = Certification.new(certification_params)\n\n respond_to do |format|\n if @certification.save\n format.html { redirect_to certifications_url, notice: 'Certification was successfully created.' }\n else\n format.html { render :new }\n end\n end\n end",
"def create\n @concert = Concert.new(concert_params)\n\n respond_to do |format|\n if @concert.save\n format.html { redirect_to @concert, notice: 'Concert was successfully created.' }\n format.json { render :show, status: :created, location: @concert }\n else\n format.html { render :new }\n format.json { render json: @concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @concert = Concert.new(concert_params)\n\n respond_to do |format|\n if @concert.save\n format.html { redirect_to @concert, notice: 'Concert was successfully created.' }\n format.json { render :show, status: :created, location: @concert }\n else\n format.html { render :new }\n format.json { render json: @concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n if params[:s]\n @certificates = Certificate.where('number = ?', params[:s])\n else\n @certificates = Certificate.all\n end\n end",
"def index\n @certifications_members = CertificationsMember.all\n end",
"def show\n @competency_pertenece_evaluation = CompetencyPerteneceEvaluation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @competency_pertenece_evaluation }\n end\n end",
"def index\n respond_to do |format|\n format.html {\n @disabilities = Disability.sorted.is_active\n @categories = QuestionCategory.all_main\n }\n format.json { render json: QuestionPairingDisabilitiesDatatable.new(view_context, params[:is_certified], params[:type], params[:category]) }\n end\n end",
"def index\n @collection = current_user.collections.find(params[:collection_id]) \n @recommenders = @collection.recommenders.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @recommenders }\n end\n end",
"def certificates(options = {})\n headers = extract_headers!(options)\n json = client.list(\"/v1/auth/cert/certs\", options, headers)\n return Secret.decode(json).data[:keys] || []\n rescue HTTPError => e\n return [] if e.code == 404\n raise\n end",
"def index\n @assessment_courses = AssessmentCourse.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @assessment_courses }\n end\n end",
"def index\n @disciplines = Discipline.all\n\n render json: @disciplines\n end",
"def index\n @collections = current_user.collections.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @collections }\n end\n end",
"def set_certification\n @certification = Certification.find(params[:id])\n end",
"def set_certification\n @certification = Certification.find(params[:id])\n end",
"def index\n lat = request.headers['lat'].to_f\n long = request.headers['long'].to_f\n\n @user = User.find(current_user)\n @concerts = @user.artists.map do |a|\n a.concerts.select{|c| Date.parse(c.date) > Date.today && Date.parse(c.date) < (Date.today + 7)}\n end\n @concerts = @concerts.flatten.sort do |concert1, concert2|\n order = Date.parse(concert1.date) <=> Date.parse(concert2.date)\n if order != 0\n order\n else\n concert1.distance(lat, long) <=> concert2.distance(lat, long)\n end\n end\n render json: {concerts: @concerts}\n end",
"def show\n @concert = Concert.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @concert }\n end\n end",
"def classifications(classification)\n params = {\n classification: classification\n }.compact\n\n _get(\"/account/classifications\", params) { |json| json }\n end",
"def certificate_list\n certificates = self.certs #[0].certificate.name\n list = certificates.collect! {|x| x.certificate.name + \"; \" }\n list.join()\n end",
"def index\n @proposals = Proposal.all\n\n render json: @proposals\n end",
"def index\n @courses = Course.all\n render json: @courses, status: :ok\n end",
"def index\n\n @critical_success_factors = CriticalSuccessFactor.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @critical_success_factors }\n end\n end",
"def destroy\n @certification.destroy\n\n respond_to do |format|\n format.html { redirect_to certifications_url }\n format.json { head :no_content }\n end\n end",
"def certified_params\n params.require(:certified).permit( :background_url, :event_id, :name_color)\n end",
"def index\n @enrolleds = Enrolled.all\n @courses = Course.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @enrolleds }\n end\n end",
"def list_tenants_for_circles(args = {}) \n get(\"/tenants.json/circles\", args)\nend",
"def index\n @disciplines = Discipline.all\n #respond_to do |format|\n # format.json { render json: @disciplines, status: :ok }\n #end\n #render json: @disciplines, status: :ok\n respond_with @disciplines\n end",
"def get_subjects\n if params[:c].present?\n sc_id = params[:c].to_i\n subjects = Subject.joins(:school_cycle_has_subjects).where(\"school_cycle_id = ?\", sc_id)\n msg = { \"success\": \"true\", \"subjects\": subjects }\n else\n msg = { \"success\": false, \"subjects\": 0 }\n end\n\n render json: msg\n end",
"def index\n authorize(@project, policy_class: CitationPolicy)\n @citations = CitationSupplyingService.new.find_by_project_id(@project.id)\n respond_to do |format|\n format.fhir_xml { render xml: @citations }\n format.fhir_json { render json: @citations }\n format.html { render json: @citations }\n format.json { render json: @citations }\n format.xml { render xml: @citations }\n format.all { render text: 'Only HTML, JSON and XML are currently supported', status: 406 }\n end\n end",
"def index\n @notifies = Notify.where(:course_id => @course.id).order('created_at DESC').page(params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @course.notifies }\n end\n end",
"def can_certify\n authorize! :certify, @registration\n end",
"def show\n @clinicalsection = Clinicalsection.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @clinicalsection }\n end\n end",
"def certified?\n @data['certifiedDev']\n end",
"def show\n render json: @course\n end",
"def show\n @submissions = Contests.get_contest_submissions(params[:id])\n unless @submissions.nil?\n render json: @submissions\n return\n end\n end",
"def show\n render json: course\n end",
"def destroy\n @cert.destroy\n respond_to do |format|\n format.html { redirect_to certs_url }\n format.json { head :no_content }\n end\n end",
"def retrieve_attempted\n\t\trender json: @@contests_attempted_shared\n\tend",
"def index\n @citizenship_classes = @grantee.citizenship_classes.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @citizenship_classes }\n end\n end",
"def certification\n return @certification\n end",
"def show\n @critical_factor = CriticalFactor.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @critical_factor }\n end\n end",
"def index\n @certification_schemes = CertificationScheme.order(:code)\n end",
"def ssl_certs\n requires :identity\n\n service.ssl_certs.all(identity)\n end",
"def get_gift_certificates_by_email_with_http_info(email, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: GiftCertificateApi.get_gift_certificates_by_email ...'\n end\n # verify the required parameter 'email' is set\n if @api_client.config.client_side_validation && email.nil?\n fail ArgumentError, \"Missing the required parameter 'email' when calling GiftCertificateApi.get_gift_certificates_by_email\"\n end\n # resource path\n local_var_path = '/gift_certificate/gift_certificates/by_email/{email}'.sub('{' + 'email' + '}', email.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n header_params['X-UltraCart-Api-Version'] = @api_client.select_header_api_version()\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 = nil\n auth_names = ['ultraCartOauth', 'ultraCartSimpleApiKey']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'GiftCertificatesResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: GiftCertificateApi#get_gift_certificates_by_email\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def show\n @evaluable_competency = EvaluableCompetency.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @evaluable_competency }\n end\n end",
"def index\n @aws_certificates = AwsCertificate.all\n end",
"def get(certificate_thumbprint)\n cert_get(certificate_thumbprint)\n end",
"def identified\n if CommodityType.aliases.keys.include?(params[:commodity])\n commodity = CommodityType.aliases[params[:commodity]]\n else\n commodity = CommodityType.where(:convertedcommod=>params[:commodity]).pluck(:commodid)\n end\n\n if params[:year]\n year = params[:year].to_i\n else\n year=Date.today.year.to_i\n end\n\n scope = Resource.mineral(commodity).year(year).nonzero\n\n if params[:recoverability] == 'recoverable'\n scope=scope.recoverable \n elsif params[:recoverability] == 'insitu' \n scope=scope.insitu \n end\n\n if !params[:state].blank? || !params[:status].blank?\n scope = scope.includes(:deposit_status)\n scope=scope.merge(DepositStatus.state(@state)) unless @state.blank?\n scope=scope.merge(DepositStatus.status(@status)) unless @status.blank?\n end\n\n resources = scope.all\n\n @identified_resources = IdentifiedResourceSet.new(resources)\n\n respond_to do |format|\n format.json #{ render :json => @grades.to_json }# grade.html.erb\n end\n end",
"def index\n @consignees = Consignee.all\n end"
] |
[
"0.64023674",
"0.64013535",
"0.62414056",
"0.6160832",
"0.6140631",
"0.59337527",
"0.5896812",
"0.58808196",
"0.57871866",
"0.5755358",
"0.5751683",
"0.57469463",
"0.57280207",
"0.57280207",
"0.57280207",
"0.57280207",
"0.5726518",
"0.5675416",
"0.5665637",
"0.56452423",
"0.5565023",
"0.55561227",
"0.54966074",
"0.54821783",
"0.54742897",
"0.54742897",
"0.54429924",
"0.54323566",
"0.5401708",
"0.5378391",
"0.5373959",
"0.53731704",
"0.5368845",
"0.5366078",
"0.53434235",
"0.53353405",
"0.5331308",
"0.53153044",
"0.5296813",
"0.5292655",
"0.5280096",
"0.5280096",
"0.52792114",
"0.52465063",
"0.524473",
"0.5232008",
"0.52242845",
"0.52157676",
"0.5180939",
"0.51609695",
"0.5159344",
"0.5155139",
"0.5155139",
"0.51309854",
"0.51309854",
"0.51169676",
"0.5098901",
"0.5095695",
"0.5083108",
"0.50773937",
"0.5066497",
"0.50614446",
"0.50567716",
"0.505593",
"0.50532585",
"0.50532585",
"0.505306",
"0.5051513",
"0.50512904",
"0.5041101",
"0.5040522",
"0.503139",
"0.5027466",
"0.50271195",
"0.50265825",
"0.5026255",
"0.5018343",
"0.50108045",
"0.50073117",
"0.5007176",
"0.5002948",
"0.49989542",
"0.49937254",
"0.4992567",
"0.49906883",
"0.4990031",
"0.49883074",
"0.49842176",
"0.49661723",
"0.49604684",
"0.49570143",
"0.49525002",
"0.49478763",
"0.49455744",
"0.4943332",
"0.4943203",
"0.49414665",
"0.49356338",
"0.4933807",
"0.49302918"
] |
0.6654699
|
0
|
GET /certifieds/1 GET /certifieds/1.json
|
def show
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def index\n @certifieds = Certified.where(user: self.current_user)\n end",
"def index\n @certifications = Certification.all\n end",
"def set_certified\n @certified = Certified.find(params[:id])\n end",
"def index\n @certs = Cert.all\n end",
"def show\n @concerts = Concert.find(params[:id])\n end",
"def certs\n request :get, '/certs'\n end",
"def index\n @certifications = @certifications.sort_by(&:name)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @certifications }\n end\n end",
"def new\n # get the authority\n @authority = Certify::Authority.find(params[:certify_authority_id])\n\n # generate a new one\n @certificate = Certify::Certificate.new()\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @certificate }\n end\n end",
"def cert_chain\n service = Service.find(params[:id])\n response = service.certificate.full_chain(true)\n render json: response\n end",
"def index\n @certs = Cert.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @certs }\n end\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @certification }\n end\n end",
"def index\n if params[:s]\n @certs = Cert.where('name = ?', params[:s])\n else\n @certs = Cert.all\n end\n end",
"def index\n @concerts = Concert.all\n end",
"def index\n @concerts = Concert.all\n end",
"def index\n @concerts = Concert.all\n end",
"def index\n @concerts = Concert.all\n end",
"def create\n @cert = Cert.new(cert_params)\n\n respond_to do |format|\n if @cert.save\n format.html { redirect_to @cert, notice: 'Cert was successfully created.' }\n format.json { render action: 'show', status: :created, location: @cert }\n else\n format.html { render action: 'new' }\n format.json { render json: @cert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def show\n @certification_users = []\n\n #TODO: make a better SQL query for this\n @certification.users.sort_by(&:name).each do |user|\n @certification_users.push user if can? :read, user\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @certification }\n end\n end",
"def create\n @cert = Cert.new(cert_params)\n\n respond_to do |format|\n if @cert.save\n format.html { redirect_to @cert, notice: 'Cert was successfully created.' }\n format.json { render :show, status: :created, location: @cert }\n else\n format.html { render :new }\n format.json { render json: @cert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @certified.destroy\n respond_to do |format|\n format.html { redirect_to certifieds_url }\n format.json { head :no_content }\n end\n end",
"def create\n respond_to do |format|\n if @certification.save\n format.html { redirect_to Certification, :notice => 'Certification was successfully created.' }\n format.json { render :json => @certification, :status => :created, :location => @certification }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @certification.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def certificates\n http_path = \"http://localhost:8081/auth/realms/master/protocol/openid-connect/certs\"\n url = URI(http_path)\n http = Net::HTTP.new(url.host, url.port)\n # request = Net::HTTP::Post.new(url.to_s)\n request = Net::HTTP::Get.new(url.to_s)\n #request[\"authorization\"] = 'bearer ' + token\n #request[\"content-type\"] = 'application/json'\n #body = {}\n\n #request.body = body.to_json\n response = http.request(request)\n puts \"RESPONSE\", response.read_body\n response_json = parse_json(response.read_body)[0]\nend",
"def index\n @certificates = Certificate.all\n end",
"def index\n @certificates = Certificate.all\n end",
"def index\n @certainties = Certainty.all\n end",
"def show\n @certified_repository = CertifiedRepository.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @certified_repository }\n end\n end",
"def create\n @certification = Certification.new(certification_params)\n\n respond_to do |format|\n if @certification.save\n format.html { redirect_to @certification, notice: 'Certification was successfully created.' }\n format.json { render :show, status: :created, location: @certification }\n else\n format.html { render :new }\n format.json { render json: @certification.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @certifications = Certification.visible :view_certifications\n end",
"def index\n @certificate_requests = CertificateRequest.all\n end",
"def info id\n get(\"ssl/v1/#{id}\")\n end",
"def index\n if params[:s]\n @certificates = Certificate.where('number = ?', params[:s])\n else\n @certificates = Certificate.all\n end\n end",
"def show\n @concert = Concert.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @concert }\n end\n end",
"def show\n @certificate = Certificate.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @certificate }\n end\n end",
"def create\n @certified = Certified.new(certified_params)\n @certified.events = events\n @certified.attendees = attendees\n @certified.slug = generate_token\n @certified.user = self.current_user\n\n flash[:notice] = \"Certificado criado com sucesso.\" if @certified.save\n\n respond_with(@certified) do |format|\n format.html { redirect_to @certified }\n end\n end",
"def show\n @issuer = Issuer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @issuer }\n end\n end",
"def get(certificate_thumbprint)\n cert_get(certificate_thumbprint)\n end",
"def set_certification\n @certification = Certification.find(params[:id])\n end",
"def set_certification\n @certification = Certification.find(params[:id])\n end",
"def create\n @concert = Concert.new(concert_params)\n\n respond_to do |format|\n if @concert.save\n format.html { redirect_to @concert, notice: 'Concert was successfully created.' }\n format.json { render :show, status: :created, location: @concert }\n else\n format.html { render :new }\n format.json { render json: @concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @concert = Concert.new(concert_params)\n\n respond_to do |format|\n if @concert.save\n format.html { redirect_to @concert, notice: 'Concert was successfully created.' }\n format.json { render :show, status: :created, location: @concert }\n else\n format.html { render :new }\n format.json { render json: @concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def show\n render json: @citation\n end",
"def show\n render json: @citation\n end",
"def index\n @certtests = Certtest.all\n end",
"def index\n @certificate_authorities = CertificateAuthority.all\n @certificate_authorities.each { |ca| ca.collect_certificates }\n end",
"def show\n @critical_factor = CriticalFactor.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @critical_factor }\n end\n end",
"def destroy\n @cert.destroy\n respond_to do |format|\n format.html { redirect_to certs_url }\n format.json { head :no_content }\n end\n end",
"def cert_content; end",
"def show\n render json: @course, status: :found\n end",
"def show\n @compromise = Compromise.find(params[:id])\n\n render json: @compromise\n end",
"def show\n @clinical_course = ClinicalCourse.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @clinical_course }\n end\n end",
"def certificate\n @user = User.find(params[:id])\n end",
"def new\n # get the authority\n @authority = Certify::Authority.find(params[:certify_authority_id])\n @keypair = @authority.key_pairs.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @keypair }\n end\n end",
"def create\n @certification = Certification.new(certification_params)\n\n respond_to do |format|\n if @certification.save\n format.html { redirect_to certifications_url, notice: 'Certification was successfully created.' }\n else\n format.html { render :new }\n end\n end\n end",
"def create\n @certification = Certification.new(certification_params)\n\n respond_to do |format|\n if @certification.save\n format.html { redirect_to certifications_url, notice: 'Certification was successfully created.' }\n else\n format.html { render :new }\n end\n end\n end",
"def index\n @course_certificates = CourseCertificate.all\n end",
"def set_certification\n @certification = Certification.find(params[:id])\n rescue ActiveRecord::RecordNotFound\n render_404\n end",
"def index\n @careers = Career.all\n json_response(@careers)\n end",
"def show\n @compromise = Compromise.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @compromise }\n end\n end",
"def show\n @competency_pertenece_evaluation = CompetencyPerteneceEvaluation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @competency_pertenece_evaluation }\n end\n end",
"def certificate_list\n return @cert_list unless @cert_list.nil?\n cmd = <<-EOF\n $certs_list = Get-Item '#{resource[:cert_dir]}\\\\*' | Where-object { $_.FriendlyName -eq '#{resource[:cert_name]}' }\n if ($certs_list) {\n $data = @()\n foreach ($cert in $certs_list) {\n # don't put this in one big expression, this way powershell throws an error on the specific\n # line that is having a problem, not the beginning of the expression\n $data += @{\n 'not_after'= $cert.NotAfter.ToString(\"o\"); # Convert to ISO format\n 'not_before' = $cert.NotBefore.ToString(\"o\");\n 'serial_number' = $cert.SerialNumber;\n 'thumbprint' = $cert.Thumbprint;\n }\n }\n # powershell is dumb and will \"unbox\" a single-element array and return just the elemtn\n # we really want an array though... thanks PowerShell...\n ConvertTo-Json @($data)\n }\n EOF\n res = ps(cmd)\n Puppet.debug('parsing cert json')\n Puppet.debug(\"got output: #{res}\")\n # add to check for truthy stdout because, if the cert doesn't exist the output\n # could be nil / empty string\n @cert_list = if res[:exitcode].zero? && res[:stdout]\n JSON.parse(res[:stdout])\n else\n false\n end\n Puppet.debug(\"finished getting cert list: #{@cert_list}\")\n @cert_list\n end",
"def index\n @citations = Citation.all\n\n render json: @citations\n end",
"def show\n @concour = Concour.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @concour }\n end\n end",
"def show\n @corpus_positive = CorpusPositive.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @corpus_positive }\n end\n end",
"def keycerts; end",
"def show\n @excercise = Excercise.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @excercise }\n end\n end",
"def destroy\n @certification.destroy\n\n respond_to do |format|\n format.html { redirect_to certifications_url }\n format.json { head :no_content }\n end\n end",
"def certified_employees(company_id=nil)\n if company_id.nil?\n get(\"employees/wotc/certified\")\n else\n get(\"employees/wotc/certified?company_id=#{company_id}\")\n end\n end",
"def set_cert\n @cert = Cert.find(params[:id]) \n end",
"def show\n @court = Court.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @court }\n end\n end",
"def show\n @assessment_course = AssessmentCourse.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @assessment_course }\n end\n end",
"def show\n @cerc = Cerc.find(params[:id])\n\n render json: @cerc\n end",
"def show\n @clinicalsection = Clinicalsection.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @clinicalsection }\n end\n end",
"def show\n render json: course\n end",
"def show\n @chiropractic_assessment = ChiropracticAssessment.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @chiropractic_assessment }\n end\n end",
"def show\n @organic_certifier = OrganicCertifier.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @organic_certifier }\n end\n end",
"def show\n @proficiency = Proficiency.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @proficiency }\n end\n end",
"def get_students\n @course = Course.find(params[:course_id])\n\n render json: @course.students\n end",
"def list\n cert_list(certstore_handler)\n end",
"def index\n @consents = Consent.all\n render json: @consents\n end",
"def new\n @certified_repository = CertifiedRepository.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @certified_repository }\n end\n end",
"def index\n @critical_factors = CriticalFactor.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @critical_factors }\n end\n end",
"def index\n @expertises = Expertise.all\n\n render json: @expertises\n end",
"def show\n @secry = Secry.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @secry }\n end\n end",
"def show\n @critical_success_factor = CriticalSuccessFactor.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @critical_success_factor }\n end\n end",
"def show\n @critical_question = CriticalQuestion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @critical_question }\n end\n end",
"def certificate_details\n data[:certificate_details]\n end",
"def show\n @evaluable_competency = EvaluableCompetency.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @evaluable_competency }\n end\n end",
"def show\n render json: @course\n end",
"def show\n @id_proof = IdProof.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @id_proof }\n end\n end",
"def certificate(name)\n json = client.get(\"/v1/auth/cert/certs/#{encode_path(name)}\")\n return Secret.decode(json)\n rescue HTTPError => e\n return nil if e.code == 404\n raise\n end",
"def destroy\n @cert.destroy\n respond_to do |format|\n format.html { redirect_to certs_url, notice: 'Cert was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def index\n @aws_certificates = AwsCertificate.all\n end",
"def show\n @certificate_type = CertificateType.find(params[:id])\n end",
"def show\n @proof_cost = ProofCost.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @proof_cost }\n end\n end",
"def index\n @disciplines = Discipline.all\n\n render json: @disciplines\n end",
"def show\n respond_to do |format|\n format.html\n format.json { render json: @assertion }\n end\n end",
"def show\n @cadet = Cadet.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cadet }\n end\n end",
"def fetch\n\t\t\tbegin\t\t\t\n\t\t\t\tdatatofetch = Datastore.new\t\t\t\n\t\t\t\t@json = datatofetch.fetch(params[:key])\n\t\t\t\trender :status => 200,\n\t \t\t:json => { :response => \"success\",\n\t \t :status => 200,\n\t \t :info => \"Successfully fetched\", \n\t \t :data => @json }\n\t\t\trescue Exception => e\n\t\t\t\trender :status => :unprocessable_entity,\n\t \t :json => { :response => \"fail\",\n\t \t :status => 401,\n\t :info => e.message }\n\t\t\tend\n\t\tend",
"def show\n @chiropractic_compliance = ChiropracticCompliance.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @chiropractic_compliance }\n end\n end",
"def destroy\n @certification.destroy\n respond_to do |format|\n format.html { redirect_to certifications_url, notice: 'Certification was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certification.destroy\n respond_to do |format|\n format.html { redirect_to certifications_url, notice: 'Certification was successfully destroyed.' }\n format.json { head :no_content }\n end\n end"
] |
[
"0.6450775",
"0.64422876",
"0.63641644",
"0.63593847",
"0.63547647",
"0.6341853",
"0.6232498",
"0.6190968",
"0.61797994",
"0.61444694",
"0.6120884",
"0.6018219",
"0.5944131",
"0.5944131",
"0.5944131",
"0.5944131",
"0.58838",
"0.5850074",
"0.5836835",
"0.58322656",
"0.5832056",
"0.5829236",
"0.582396",
"0.582396",
"0.57854354",
"0.5782576",
"0.56652963",
"0.5641703",
"0.5630194",
"0.56291217",
"0.5616285",
"0.561212",
"0.5592442",
"0.55780184",
"0.55670047",
"0.55540466",
"0.55386966",
"0.55386966",
"0.5525279",
"0.5525279",
"0.551914",
"0.551914",
"0.55084896",
"0.5505617",
"0.5462849",
"0.5456099",
"0.5450329",
"0.5437578",
"0.5433714",
"0.5433145",
"0.5414474",
"0.54116017",
"0.54011744",
"0.54011744",
"0.5400796",
"0.5398054",
"0.5397624",
"0.53948045",
"0.53931475",
"0.53846425",
"0.53792197",
"0.53777915",
"0.5374262",
"0.5367137",
"0.5361266",
"0.53606874",
"0.535685",
"0.5356828",
"0.53544664",
"0.5342448",
"0.53397775",
"0.5339419",
"0.5335923",
"0.533193",
"0.53318405",
"0.53171146",
"0.5313707",
"0.5311133",
"0.5304419",
"0.5296149",
"0.529584",
"0.52883303",
"0.5284147",
"0.52837384",
"0.5281672",
"0.5277934",
"0.52725303",
"0.5270668",
"0.5267258",
"0.5267183",
"0.5265479",
"0.52561533",
"0.52517396",
"0.5246669",
"0.5233507",
"0.52284676",
"0.5227507",
"0.5223102",
"0.5218397",
"0.5213783",
"0.5213783"
] |
0.0
|
-1
|
POST /certifieds POST /certifieds.json
|
def create
@certified = Certified.new(certified_params)
@certified.events = events
@certified.attendees = attendees
@certified.slug = generate_token
@certified.user = self.current_user
flash[:notice] = "Certificado criado com sucesso." if @certified.save
respond_with(@certified) do |format|
format.html { redirect_to @certified }
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def create\n respond_to do |format|\n if @certification.save\n format.html { redirect_to Certification, :notice => 'Certification was successfully created.' }\n format.json { render :json => @certification, :status => :created, :location => @certification }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @certification.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @certification = Certification.new(certification_params)\n\n respond_to do |format|\n if @certification.save\n format.html { redirect_to @certification, notice: 'Certification was successfully created.' }\n format.json { render :show, status: :created, location: @certification }\n else\n format.html { render :new }\n format.json { render json: @certification.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @cert = Cert.new(cert_params)\n\n respond_to do |format|\n if @cert.save\n format.html { redirect_to @cert, notice: 'Cert was successfully created.' }\n format.json { render :show, status: :created, location: @cert }\n else\n format.html { render :new }\n format.json { render json: @cert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @cert = Cert.new(cert_params)\n\n respond_to do |format|\n if @cert.save\n format.html { redirect_to @cert, notice: 'Cert was successfully created.' }\n format.json { render action: 'show', status: :created, location: @cert }\n else\n format.html { render action: 'new' }\n format.json { render json: @cert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def certified_params\n params.require(:certified).permit( :background_url, :event_id, :name_color)\n end",
"def create\n @certification = Certification.new(certification_params)\n\n respond_to do |format|\n if @certification.save\n format.html { redirect_to certifications_url, notice: 'Certification was successfully created.' }\n else\n format.html { render :new }\n end\n end\n end",
"def create\n @certification = Certification.new(certification_params)\n\n respond_to do |format|\n if @certification.save\n format.html { redirect_to certifications_url, notice: 'Certification was successfully created.' }\n else\n format.html { render :new }\n end\n end\n end",
"def set_certified\n @certified = Certified.find(params[:id])\n end",
"def certify_event_attendence_post\n #create approval if create approval selected\n @event = Event.find_by_id(params[:event_id])\n if @event != nil && !@event.submitted_for_certification && !@event.certified && @event.event_certification_request == nil\n # check to make sure debriefing is submitted\n # TODO: ^^ This\n # update the event first\n if @event.update(event_certify_params)\n #create certification request\n ecr = EventCertificationRequest.new(event_id: @event.id)\n #create approval\n ecr.approval_id = new_approval(6)\n ecr.user_id = current_user.id\n if ecr.save\n @event.submitted_for_certification = true\n @event.event_certification_request_id = ecr.id\n if @event.save\n render status: 200, json: @event\n else\n render status: 500, json: { message: 'Error Occured. Event could not be submitted for certification' }\n end\n else\n @event.submitted_for_certification = false\n if @event.save\n render status: 500, json: { message: 'ERROR: ECR could not be saved. Event reverted so certification could be made.' }\n else\n render status: 500, json: { message: 'ERROR: ECR could not be saved and the event could not be updated. Data wise this is probably really messed up you will need to contact Rindzer.' }\n end\n end\n else\n render status: 500, json: { message: \"An error occured and the event could not be updated.\" }\n end\n else\n render status: 404, json: { message: 'Either this event was not found or has already been submitted for certification.' }\n end\n end",
"def create\n @concert = Concert.new(concert_params)\n\n respond_to do |format|\n if @concert.save\n format.html { redirect_to @concert, notice: 'Concert was successfully created.' }\n format.json { render :show, status: :created, location: @concert }\n else\n format.html { render :new }\n format.json { render json: @concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @concert = Concert.new(concert_params)\n\n respond_to do |format|\n if @concert.save\n format.html { redirect_to @concert, notice: 'Concert was successfully created.' }\n format.json { render :show, status: :created, location: @concert }\n else\n format.html { render :new }\n format.json { render json: @concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n params[:certification][:course_id].each do |i|\n begin\n cert = @person.certifications.build(course_id: i, year_id: params[:certification][:year_id])\n cert.save\n rescue\n end\n end\n @certification = @person.certifications.build(certification_params)\n respond_to do |format|\n format.html { redirect_to @person, notice: 'Certification was successfully created.' }\n end\n end",
"def create\n @certtest = Certtest.new(certtest_params)\n\n respond_to do |format|\n if @certtest.save\n format.html { redirect_to @certtest, notice: 'Certtest was successfully created.' }\n format.json { render :show, status: :created, location: @certtest }\n else\n format.html { render :new }\n format.json { render json: @certtest.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n # get the ca\n @authority = Certify::Authority.find(params[:certify_authority_id])\n\n # generate a new one\n @certificate = Certify::Certificate.new(params[:certificate])\n\n # generate the csr\n if (params[:csr] && params[:csr] != \"\")\n csr = Certify::Csr.new :data => params[:csr]\n else\n kp = Certify::KeyPair.find(params[:keypair][:id])\n csr = kp.generate_csr('CN=ca/DC=example')\n end\n\n # sign the csr\n @certificate = @authority.sign_csr(csr)\n\n # format\n respond_to do |format|\n if @certificate && @certificate.valid?\n format.html { redirect_to certify_authority_path(@authority), notice: 'Certificate was successfully created.' }\n format.json { render json: @certificate, status: :created, location: @certificate }\n else\n format.html { render action: \"new\" }\n format.json { render json: @certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def certification_params\n params.require(:certification).permit(Certification.safe_attributes)\n end",
"def create\n @certainty = Certainty.new(certainty_params)\n\n respond_to do |format|\n if @certainty.save\n format.html { redirect_to @certainty, notice: 'Certainty was successfully created.' }\n format.json { render :show, status: :created, location: @certainty }\n else\n format.html { render :new }\n format.json { render json: @certainty.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n # TODO 既存 team を含めて保存する場合は認証に対応させる\n @concert = Concert.new(concert_savable_params)\n\n if @concert.save\n render :show, status: :created\n else\n render json: @concert.errors, status: :unprocessable_entity\n end\n end",
"def certification_params\n params.require(:certification).permit(:name)\n end",
"def certification_params\n params.require(:certification).permit(Certification.safe_attributes)\n end",
"def create\n @classified = Classified.new(classified_params)\n respond_to do |format|\n if @classified.save\n format.html { redirect_to @classified, notice: 'Classified was successfully created.' }\n format.json { render :show, status: :created, location: @classified }\n else\n format.html { render :new }\n format.json { render json: @classified.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @certified.destroy\n respond_to do |format|\n format.html { redirect_to certifieds_url }\n format.json { head :no_content }\n end\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\n respond_to do |format|\n if @medical_certificate.save\n format.html { redirect_to student_medical_certificates_path(@student), notice: 'Medical certificate was successfully created.'}\n format.json { render :show, status: :created, location: @medical_certificate }\n else\n format.html { render :new }\n format.json { render json: @medical_certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def certification_params\n params.require(:certification).permit(:course_id, :year_id, :person_id)\n end",
"def create\n @concert = Concert.new(concert_params)\n\n respond_to do |format|\n if @concert.save\n format.html { redirect_to(@concert, :notice => 'Concert was successfully created.') }\n format.xml { render :xml => @concert, :status => :created, :location => @concert }\n else\n format.html { render :action => 'new' }\n format.xml { render :xml => @concert.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n course = Course.includes(:professors).new(course_params)\n course.professor_ids=(params[:professors])\n\n if course.save\n render json: course.to_json(include: :professors)\n else\n render :json => { :errors => course.errors }, :status => 422\n end\n end",
"def do_coaps_posted_02\n # get the Base64 of the incoming signed request\n body = IO.read(\"spec/files/vr_00-D0-E5-F2-00-02.vrq\")\n\n env = Hash.new\n env[\"SSL_CLIENT_CERT\"] = cbor_clientcert_02\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 new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @certification }\n end\n end",
"def register_cert(cert)\n request :post, '/certs', cert\n end",
"def create\n #@classified = Classified.new(classified_params)\n @classified = current_user.classifieds.new(classified_params)\n\n respond_to do |format|\n if @classified.save\n format.html { redirect_to @classified, notice: 'Classified was successfully created.' }\n format.json { render :show, status: :created, location: @classified }\n else\n format.html { render :new }\n format.json { render json: @classified.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @certificado = Certificado.new(certificado_params)\n\n respond_to do |format|\n if @certificado.save!\n format.html { redirect_to @certificado, notice: 'Certificado was successfully created.' }\n format.json { render :show, status: :created, location: @certificado }\n else\n format.html { render :new }\n format.json { render json: @certificado.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @small_concert = SmallConcert.new(small_concert_params)\n\n respond_to do |format|\n if @small_concert.save\n format.html { redirect_to '/admin/small_concerts', notice: 'Small concert was successfully created.' }\n format.json { render action: 'show', status: :created, location: @small_concert }\n else\n format.html { render action: 'new' }\n format.json { render json: @small_concert.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 @incident_proof = IncidentProof.new(incident_proof_params)\n\n respond_to do |format|\n if @incident_proof.save\n format.html { redirect_to @incident_proof, notice: 'Incident proof was successfully created.' }\n format.json { render :show, status: :created, location: @incident_proof }\n else\n format.html { render :new }\n format.json { render json: @incident_proof.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @certificate = Certificate.new(certificate_params)\n respond_to do |format|\n if @certificate.save\n format.html { redirect_to root_path, notice: 'Certificate was successfully created.' }\n format.json { render :show, status: :created, location: @certificate }\n else\n format.html { render :new }\n format.json { render json: @certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n # get the authority\n @authority = Certify::Authority.find(params[:certify_authority_id])\n\n # generate a new one\n @certificate = Certify::Certificate.new()\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @certificate }\n end\n end",
"def create\n @organic_certifier = OrganicCertifier.new(params[:organic_certifier])\n\n respond_to do |format|\n if @organic_certifier.save\n format.html { redirect_to(@organic_certifier, :notice => 'OrganicCertifier was successfully created.') }\n format.xml { render :xml => @organic_certifier, :status => :created, :location => @organic_certifier }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @organic_certifier.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def certifying_body_params\n params.require(:certifying_body).permit(:name, :mission, :url)\n end",
"def create\n @concert = Concert.new(concert_params)\n\n respond_to do |format|\n if @concert.save\n @concert.create_activity :create, owner: current_user\n format.html { redirect_to @concert, notice: 'Concert was successfully created.' }\n format.json { render :show, status: :created, location: @concert }\n else\n format.html { render :new }\n format.json { render json: @concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @certification_scheme = CertificationScheme.new(certification_scheme_params)\n\n respond_to do |format|\n if @certification_scheme.save\n format.html { redirect_to @certification_scheme, notice: 'Certification scheme was successfully created.' }\n format.json { render :show, status: :created, location: @certification_scheme }\n else\n format.html { render :new }\n format.json { render json: @certification_scheme.errors, status: :unprocessable_entity }\n end\n end\n end",
"def certainty_params\n params.require(:certainty).permit(:name)\n end",
"def make_certificates\n # @contest is fetched by CanCan\n\n # Define params for PDF output\n prawnto filename: \"urkunden#{random_number}\", prawn: { page_size: 'A4', skip_page_creation: true }\n @performances = apply_scopes(Performance)\n .joins(:contest_category)\n .where(\"contest_categories.contest_id = ?\", @contest.id)\n .accessible_by(current_ability)\n .order(:stage_time)\n .paginate(page: params[:page], per_page: 15)\n end",
"def create\n @collection = Collection.new(collection_params)\n build_kiosks(params)\n respond_to do |format|\n if @collection.save\n format.html { redirect_to @collection, notice: 'Collection was successfully created.' }\n format.json { render :show, status: :created, location: @collection }\n else\n format.html { render :new }\n format.json { render json: @collection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @certifications_member = CertificationsMember.new(certifications_member_params)\n\n respond_to do |format|\n if @certifications_member.save\n format.html { redirect_to @certifications_member, notice: 'Certifications member was successfully created.' }\n format.json { render :show, status: :created, location: @certifications_member }\n else\n format.html { render :new }\n format.json { render json: @certifications_member.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\t\t@gift_cert = GiftCert.new(params[:gift_cert])\n \t@gift_cert.status = \"Not activiated\" \n\n if allowSendEmail \n # notify stevek that a new student account was created \n MsMailer.giftCert( \"stevek91411@yahoo.com\", @gift_cert.purchaser_name, @gift_cert.activiation_code, \n @gift_cert.status, \"New Gift certificate:\" ).deliver\n MsMailer.giftCert( \"8182617590@txt.att.net\", @gift_cert.purchaser_name, @gift_cert.activiation_code, \n @gift_cert.status, \"New Gift certificate: step1\" ).deliver \n end\n \n \trespond_to do |format|\n \t\tif @gift_cert.save\n \t\tformat.xml { render :xml => @gift_cert }\n \t\telse\n \t\tformat.xml { render :xml => log_DB_errors( \"GiftCert\", @gift_cert.errors ) }\n \t\tend\n \tend\n end",
"def create\n @inspection = Inspection.new(inspection_params)\n @clients = @inspection.try(:appointment).try(:insp_request).try(:property).try(:clients)\n create_documents\n respond_to do |format|\n if @inspection.save\n format.html { redirect_to @inspection, notice: 'Inspection was successfully created.' }\n format.json { render json: @inspection }\n else\n format.html { render :new }\n format.json { render json: @inspection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def submit_report(json, cookbookname)\n data = File.read(json)\n uri = URI.parse($SPEC_ENDPOINT)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = uri.scheme == \"https\"\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Post.new(\"/api/reports\")\n request.add_field('Content-Type', 'application/json')\n request.body = {\n :spec_result => data,\n :hostname => `hostname`.chomp,\n :cookbook_name => cookbookname\n }.to_json\n response = http.request(request)\n end",
"def create\n @concert = @theater.concerts.new(concert_params)\n\n respond_to do |format|\n if @concert.save\n format.html { redirect_to @concert, notice: 'Concert was successfully created.' }\n #TODO localise the previous string\n format.json { render :show, status: :created, location: @concert }\n else\n format.html { render :new }\n format.json { render json: @concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def can_certify\n authorize! :certify, @registration\n end",
"def create\n # Revoke the old cert before creating a new one\n revoke_cert if certificate && private_key && check_cert_exists\n new_cert = create_cert\n client_cert_save(new_cert)\n end",
"def create\n # get the ca\n @authority = Certify::Authority.find(params[:certify_authority_id])\n\n @keypair = Certify::KeyPair.new(params[:keypair])\n @keypair.authority = @authority\n\n respond_to do |format|\n if @keypair.save\n format.html { redirect_to certify_authority_path(@authority), notice: 'Private key was successfully created.' }\n format.json { render json: @keypair, status: :created, location: @keypair }\n else\n format.html { render action: \"new\" }\n format.json { render json: @keypair.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n professor = Professor.new(professor_params)\n \n if professor.save\n render json: professor.to_json(include: :courses)\n else\n render :json => { :errors => professor.errors }, :status => 422\n end\n end",
"def create\n @user = User.new\n\n @certificate = Certificate.new(certificate_params)\n respond_to do |format|\n if @certificate.save\n format.html { redirect_to @certificate, notice: 'Certificado criado com sucesso.' }\n format.json { render :show, status: :created, location: @certificate }\n else\n format.html { render :new }\n format.json { render json: @certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @evaluation = Evaluation.new(evaluation_params)\n @evaluation.collection = evaluation_params[:collection]\n \n\n respond_to do |format|\n if @evaluation.save\n format.html { redirect_to @evaluation, notice: \"Evaluation was successfully created.\" }\n format.json { render :show, status: :created, location: @evaluation }\n else\n format.html { render :new }\n format.json { render json: @evaluation.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @agreement = Agreement.new(agreement_params)\n\n respond_to do |format|\n if @agreement.save\n format.html { redirect_to @agreement, notice: 'Certificado criado com sucesso.' }\n format.json { render :show, status: :created, location: @agreement }\n else\n format.html { render :new }\n format.json { render json: @agreement.errors, status: :unprocessable_entity }\n end\n end\n end",
"def certs\n request :get, '/certs'\n end",
"def create\n @certificate_request = CertificateRequest.new(certificate_request_params)\n\n respond_to do |format|\n if @certificate_request.save\n format.html { redirect_to @certificate_request, notice: 'Certificate request was successfully created.' }\n format.json { render action: 'show', status: :created, location: @certificate_request }\n else\n format.html { render action: 'new' }\n format.json { render json: @certificate_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @careers = Career.create!(career_params)\n json_response(@careers, :created)\n end",
"def certificate_params\n params.require(:certificate).permit(:name, :email, :description, :text_id)\n end",
"def index\n @certifications = Certification.all\n end",
"def create\n\n \t\t\t@penalty = Penalty.new penalty_params\n\n \t\t\tif @penalty.save\n\n \t\t\t\trender json: @penalty,status: :created\n\n \t\t\telse\n\n \t\t\t\trender json: {error: true,errors: @penalty.errors},status: :unprocessable_entity\n\n \t\t\tend\n\n \t\tend",
"def create\n @category_classified = CategoryClassified.new(category_classified_params)\n\n respond_to do |format|\n if @category_classified.save\n format.html { redirect_to @category_classified, notice: 'Category classified was successfully created.' }\n format.json { render :show, status: :created, location: @category_classified }\n else\n format.html { render :new }\n format.json { render json: @category_classified.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\n @certificate_types = CertificateType.all\n @certificate_type = CertificateType.create(certificate_type_params)\n\n=begin\n @certificate_type = CertificateType.new(certificate_type_params)\n\n respond_to do |format|\n if @certificate_type.save\n format.html { redirect_to @certificate_type, notice: 'Certificate type was successfully created.' }\n format.json { render :show, status: :created, location: @certificate_type }\n else\n format.html { render :new }\n format.json { render json: @certificate_type.errors, status: :unprocessable_entity }\n end\n end\n=end\n end",
"def destroy\n @certification.destroy\n\n respond_to do |format|\n format.html { redirect_to certifications_url }\n format.json { head :no_content }\n end\n end",
"def create\n @fullassessment = Fullassessment.new(fullassessment_params)\n respond_to do |format|\n if @fullassessment.save\n format.json { render json: @fullassessment }\n else\n format.html { render :new }\n format.json { render json: @fullassessment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @course_id = params[:course_id]\n @user_id = params[:user_id]\n @course_certificate = CourseCertificate.new(user_id: @user_id, course_id: @course_id)\n\n respond_to do |format|\n if @course_certificate.save && !already_created?\n format.html { redirect_to @course_certificate, notice: \"Course certificate was successfully created.\" }\n format.json { render :show, status: :created, location: @course_certificate }\n else\n format.html { render :show, status: :unprocessable_entity, location: @course_certificates }\n format.json { render json: @course_certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\t@safety_check = current_user.safety_checks.new(safety_check_params)\n\n\trespond_to do |format|\n\t if @safety_check.save\n\t\tformat.html { redirect_to :back, notice: 'Safety check was successfully created.' }\n\t\tformat.json { render :back, status: :created, location: @safety_check }\n\t else\n\t\tformat.html { render :back, notice: \"Error in sending safety check\" }\n\t\tformat.json { render json: @safety_check.errors, status: :unprocessable_entity }\n\t end\n\tend\n end",
"def new\n # get the authority\n @authority = Certify::Authority.find(params[:certify_authority_id])\n @keypair = @authority.key_pairs.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @keypair }\n end\n end",
"def create\n @expertise = Expertise.new(expertise_params)\n\n if @expertise.save\n render json: @expertise, status: :created, location: @expertise\n else\n render json: @expertise.errors, status: :unprocessable_entity\n end\n end",
"def create\n @competency_pertenece_evaluation = CompetencyPerteneceEvaluation.new(params[:competency_pertenece_evaluation])\n\n respond_to do |format|\n if @competency_pertenece_evaluation.save\n format.html { redirect_to @competency_pertenece_evaluation, notice: 'Competency pertenece evaluation was successfully created.' }\n format.json { render json: @competency_pertenece_evaluation, status: :created, location: @competency_pertenece_evaluation }\n else\n format.html { render action: \"new\" }\n format.json { render json: @competency_pertenece_evaluation.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n submission = Submission.new(submission_params)\n unless submission.save\n render json: {errors: submmission.errors.full_messages}, status: :bad_request\n return\n end\n\n claim = Claim.new(\n insured_id: submission.insured_id,\n provider_id: submission.provider_id\n )\n unless claim.save\n submission.delete\n render json: {errors: claim.errors.full_messages}, status: :bad_request\n return\n end\n\n submission.claim = claim\n unless submission.save\n submisson.delete\n claim.delete\n render json: {errors: submmission.errors.full_messages}, status: :bad_request\n return\n end\n\n render json: {submission: submission.id, claim: claim.id}\n end",
"def create_certificate\n create_app_cert(params['app_identifier'], params['cert'], params['pkey'])\n redirect_to \"/\", flash: { error_message: @error_message }\n end",
"def index\n @certifieds = Certified.where(user: self.current_user)\n end",
"def create\n @assertion = Assertion.new(assertion_params)\n @assertion[:verify] = { type: \"hosted\", url: \"http://frozen-dawn-78535.herokuapp.com/assertions/#{@assertion.id}\" }\n\n respond_to do |format|\n if @assertion.save\n format.html { redirect_to assertions_path, notice: 'Assertion was successfully created.' }\n format.json { render :show, status: :created, location: @assertion }\n else\n format.html { render :new }\n format.json { render json: @assertion.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @contestant = Contestant.new(contestant_params)\n\n \n if @contestant.save\n render json: @contestant\n else\n render json: @contestant.errors\n end\n \n end",
"def create\n @cadet = Cadet.new(params[:cadet])\n\n respond_to do |format|\n if @cadet.save\n format.html { redirect_to @cadet, notice: 'Cadet was successfully created.' }\n format.json { render json: @cadet, status: :created, location: @cadet }\n else\n format.html { render action: \"new\" }\n format.json { render json: @cadet.errors, status: :unprocessable_entity }\n end\n end\n end",
"def distrust_certs()\n process_certs(\"Explicitly distrusting certs\", CertTools.distrusted_certs_dir)\n end",
"def create\n @certified_repository = CertifiedRepository.new(params[:certified_repository])\n\n respond_to do |format|\n if @certified_repository.save\n flash[:notice] = 'CertifiedRepository was successfully created.'\n format.html { redirect_to(@certified_repository) }\n format.xml { render :xml => @certified_repository, :status => :created, :location => @certified_repository }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @certified_repository.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def destroy\n @certification.destroy\n respond_to do |format|\n format.html { redirect_to certifications_url, notice: 'Certification was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certification.destroy\n respond_to do |format|\n format.html { redirect_to certifications_url, notice: 'Certification was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def submit_form_2122\n validate_json_schema\n\n power_of_attorney = ClaimsApi::PowerOfAttorney.find_using_identifier_and_source(header_md5: header_md5,\n source_name: source_name)\n unless power_of_attorney&.status&.in?(%w[submitted pending])\n power_of_attorney = ClaimsApi::PowerOfAttorney.create(\n status: ClaimsApi::PowerOfAttorney::PENDING,\n auth_headers: auth_headers,\n form_data: form_attributes,\n source_data: source_data,\n header_md5: header_md5\n )\n\n unless power_of_attorney.persisted?\n power_of_attorney = ClaimsApi::PowerOfAttorney.find_by(md5: power_of_attorney.md5)\n end\n\n power_of_attorney.save!\n end\n\n ClaimsApi::PoaUpdater.perform_async(power_of_attorney.id)\n\n render json: power_of_attorney, serializer: ClaimsApi::PowerOfAttorneySerializer\n end",
"def create\n #@incident = @quote.incidents.new(incident_params)\n logger.info params[:incident]\n params[:incident].each do |incident|\n @incident = @quote.incidents.new(incident)\n @incident.save\n end\n respond_to do |format|\n format.json { render :json => { :code => \"201\", :description => \"Created incidents\"} }\n end\n end",
"def create\n @jewelrycollection = Jewelrycollection.new(jewelrycollection_params)\n\n respond_to do |format|\n if @jewelrycollection.save\n format.html { redirect_to @jewelrycollection, notice: 'Jewelrycollection was successfully created.' }\n format.json { render :show, status: :created, location: @jewelrycollection }\n else\n format.html { render :new }\n format.json { render json: @jewelrycollection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @stage_certainty_factor = StageCertaintyFactor.new(stage_certainty_factor_params)\n\n respond_to do |format|\n if @stage_certainty_factor.save\n format.html { redirect_to @stage_certainty_factor, notice: 'Stage certainty factor was successfully created.' }\n format.json { render :show, status: :created, location: @stage_certainty_factor }\n else\n format.html { render :new }\n format.json { render json: @stage_certainty_factor.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n @certified.background_url = params[:background_url]\n\n if @certified.update(certified_params)\n format.html { redirect_to @certified, notice: 'Certified was successfully updated.' }\n format.json { head :no_content }\n else\n format.html {\n render action: 'edit', alert: @certified.errors.to_a\n }\n format.json { render json: @certified.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n if signed_in?\n @classified = current_user.classifieds.build(params[:classified])\n else\n if user_present?(params[:email]) # checks whether user is already present ...and if present assigns it to @user\n redirect_to signin_path, notice: 'This account is already in use.Please sign in to use it'\n return\n else\n create_impulse_signup params[:email]\n end\n @classified = @user.classifieds.build(params[:classified])\n end\n respond_to do |format|\n if @classified.save\n if signed_in?\n format.html { redirect_to @classified, notice: 'Classified was successfully created.' }\n else\n format.html { redirect_to @classified, notice: 'Classified was successfully created..Please confirm your email account by clicking on the link we sent you' }\n end\n format.json { render json: @classified, status: :created, location: @classified }\n else\n format.html { render action: 'new' }\n format.json { render json: @classified.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @classifier = Classifier.new(classifier_params)\n\n respond_to do |format|\n if @classifier.save\n format.html { redirect_to @classifier, notice: 'Classifier was successfully created.' }\n format.json { render :show, status: :created, location: @classifier }\n else\n format.html { render :new }\n format.json { render json: @classifier.errors, status: :unprocessable_entity }\n end\n end\n end",
"def certification_scheme_params\n params.fetch(:certification_scheme, {}).permit(:code, :name, :scheme_type, :certification_fee, :description)\n end",
"def set_certification\n @certification = Certification.find(params[:id])\n end",
"def set_certification\n @certification = Certification.find(params[:id])\n end",
"def create\n Rails.logger.debug \"[ClassificationsController.create] params.class: #{params.class}, params: #{params}\"\n @classifaction = Classification.new transaction_data: params\n @classifaction.classifiers << StatusCodeClassifier.classify( @classifaction.transaction_data )\n @classifaction.classify\n\n if @classifaction.save\n render json: @classifaction.as_jsonapi, status: :created\n else\n render json: { error: 'oops' }, status: 500\n end\n end",
"def grade!\n uri = URI.parse problem.endpoint.url\n response = Net::HTTP.post_form uri, task: problem.task_name, code: code\n verdict = Verdict.from_endpoint_response response, self\n verdict.save!\n end",
"def post_check(excon, body)\n excon.request(\n method: :post,\n path: '/check',\n headers: { 'Content-Type' => 'application/json' },\n body: body\n )\nend",
"def create_assignment(name)\n @url = \"http://#{$canvas_host}/api/v1/courses/#{$canvas_course_id}/assignments\"\n puts \"@url is #{@url}\"\n\n @payload={'assignment': { \n 'name': name,\n 'points_possible': '0',\n 'grading_type': 'pass_fail',\n 'published': 'true',\n 'submission_types': [ \"none\" ]\n }\n }\n\n @postResponse = HTTParty.post(@url, :body => @payload.to_json, :headers => $header )\n puts(\" POST to create assignment has Response.code #{@postResponse.code} and postResponse is #{@postRepsone}\")\nend",
"def certification=(value)\n @certification = value\n end",
"def create\n @attorney = Attorney.new(attorney_params)\n authorize @attorney\n respond_to do |format|\n if @attorney.save\n format.html { redirect_to (params[:save_and_new].present? ? new_attorney_path : @attorney), success: I18n.t('notices.created', entity: Attorney.model_name.human, id: @attorney.id) }\n format.json { render :show, status: :created, location: @attorney }\n else\n format.html { render :new }\n format.json { render json: @attorney.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @id_proof = IdProof.new(params[:id_proof])\n\n respond_to do |format|\n if @id_proof.save\n format.html { redirect_to @id_proof, notice: 'Id proof was successfully created.' }\n format.json { render json: @id_proof, status: :created, location: @id_proof }\n else\n format.html { render action: \"new\" }\n format.json { render json: @id_proof.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @certificate = Certificate.new\n @certificate.user_id = current_user.id\n @certificate.type_certificate_id = params[:type_certificate_id]\n @certificate.type_status_certificate_id = \"1\"\n respond_to do |format|\n if @certificate.save\n format.html { redirect_to certificates_path }\n format.json { render :show, status: :created, location: @certificate }\n else\n @type_certificates = TypeCertificate.all\n format.html { render :new }\n format.json { render json: @certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def cert_params\n params.require(:cert).permit(:memo, :get_at, :expire_at, :pin, :pin_get_at, :user_id, :cert_state_id, :cert_type_id, :purpose_type)\n end",
"def certificate_params\n params.fetch(:certificate).permit(:patient_id, :doctor_id, :income_date, :discharge_date)\n end"
] |
[
"0.6489707",
"0.6436034",
"0.6311841",
"0.6270349",
"0.6267243",
"0.6254824",
"0.6254824",
"0.6172796",
"0.60597944",
"0.6047397",
"0.6047397",
"0.6040358",
"0.6034543",
"0.5952242",
"0.59151787",
"0.5858251",
"0.58091444",
"0.57874733",
"0.57859355",
"0.5741499",
"0.57053375",
"0.5637504",
"0.55714935",
"0.55659586",
"0.5559497",
"0.55515873",
"0.5546615",
"0.5516656",
"0.55144596",
"0.551175",
"0.5491677",
"0.54774946",
"0.54454875",
"0.5444507",
"0.5435346",
"0.53963304",
"0.536313",
"0.5357421",
"0.53477013",
"0.5343936",
"0.5298393",
"0.528261",
"0.5279999",
"0.5247078",
"0.522386",
"0.5201025",
"0.5197593",
"0.51964784",
"0.5191165",
"0.51844496",
"0.5181781",
"0.5180026",
"0.5172774",
"0.51702166",
"0.5169158",
"0.51449126",
"0.51385456",
"0.5138298",
"0.5134805",
"0.5128773",
"0.512311",
"0.51150006",
"0.51045656",
"0.50985",
"0.5097131",
"0.5094465",
"0.5086369",
"0.50863236",
"0.50840485",
"0.50788236",
"0.50746",
"0.50691617",
"0.5060704",
"0.5040356",
"0.5038936",
"0.50299954",
"0.5016818",
"0.50166726",
"0.5008404",
"0.5008404",
"0.50075555",
"0.5005555",
"0.50037473",
"0.4997011",
"0.49780965",
"0.49779034",
"0.49739107",
"0.49730715",
"0.49725026",
"0.49725026",
"0.4968582",
"0.49677384",
"0.4967423",
"0.49617678",
"0.49474448",
"0.49428013",
"0.49358276",
"0.49304143",
"0.49295324",
"0.4925243"
] |
0.69736564
|
0
|
PATCH/PUT /certifieds/1 PATCH/PUT /certifieds/1.json
|
def update
respond_to do |format|
@certified.background_url = params[:background_url]
if @certified.update(certified_params)
format.html { redirect_to @certified, notice: 'Certified was successfully updated.' }
format.json { head :no_content }
else
format.html {
render action: 'edit', alert: @certified.errors.to_a
}
format.json { render json: @certified.errors, status: :unprocessable_entity }
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def update\n respond_to do |format|\n if @cert.update(cert_params)\n format.html { redirect_to @cert, notice: 'Cert was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @cert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @cert.update(cert_params)\n format.html { redirect_to @cert, notice: 'Cert was successfully updated.' }\n format.json { render :show, status: :ok, location: @cert }\n else\n format.html { render :edit }\n format.json { render json: @cert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @certification.update_attributes(params[:certification])\n format.html { redirect_to Certification, :notice => 'Certification was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @certification.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @certification.update(certification_params)\n format.html { redirect_to @certification, notice: 'Certification was successfully updated.' }\n format.json { render :show, status: :ok, location: @certification }\n else\n format.html { render :edit }\n format.json { render json: @certification.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @certificate_request.update(certificate_request_params)\n format.html { redirect_to @certificate_request, notice: 'Certificate request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @certificate_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch!\n request! :patch\n end",
"def patch\n headers = {\"If-Match\" => @version}\n response = @context.request :patch, \"#{@path}/#{@id}\", @data.to_json, headers\n @version += 1\n response\n # 'X-HTTP-Method-Override' => 'PATCH'\n end",
"def update\n respond_to do |format|\n if @certtest.update(certtest_params)\n format.html { redirect_to @certtest, notice: 'Certtest was successfully updated.' }\n format.json { render :show, status: :ok, location: @certtest }\n else\n format.html { render :edit }\n format.json { render json: @certtest.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @certificate.update(certificate_params)\n format.html { redirect_to root_path, notice: 'Certificate was successfully updated.' }\n format.json { render root_path, status: :ok, location: @certificate }\n else\n format.html { render :edit }\n format.json { render json: @certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @small_concert.update(small_concert_params)\n format.html { redirect_to '/admin/small_concerts', notice: 'Small concert was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @small_concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @certification.update(certification_params)\n format.html { redirect_to @person, notice: 'Certification was successfully updated.' }\n else\n format.html { render :edit }\n end\n end\n end",
"def set_certified\n @certified = Certified.find(params[:id])\n end",
"def update\n respond_to do |format|\n if @certification.update(certification_params)\n format.html { redirect_to certifications_url, notice: 'Certification was successfully updated.' }\n\n else\n format.html { render :edit }\n end\n end\n end",
"def update\n respond_to do |format|\n if @certification.update(certification_params)\n format.html { redirect_to certifications_url, notice: 'Certification was successfully updated.' }\n\n else\n format.html { render :edit }\n end\n end\n end",
"def update\n respond_to do |format|\n if @concert.update(concert_params)\n format.html { redirect_to @concert, notice: 'Concert was successfully updated.' }\n format.json { render :show, status: :ok, location: @concert }\n else\n format.html { render :edit }\n format.json { render json: @concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @concert.update(concert_params)\n format.html { redirect_to @concert, notice: 'Concert was successfully updated.' }\n format.json { render :show, status: :ok, location: @concert }\n else\n format.html { render :edit }\n format.json { render json: @concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, data)\n request 'PATCH', path, body: data.to_json\n end",
"def update\n respond_to do |format|\n if @certificate.update(certificate_params)\n format.html { redirect_to certificates_url, notice: 'Довідка редагована.' }\n format.json { render :show, status: :ok, location: @certificate }\n else\n format.html { render :edit }\n format.json { render json: @certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @certificate.update(certificate_params)\n format.html { redirect_to @certificate, notice: 'Certificado modificado com sucesso.' }\n format.json { render :show, status: :ok, location: @certificate }\n else\n format.html { render :edit }\n format.json { render json: @certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(id:, private_key: nil, certificate: nil, bundle_method: nil)\n id_check('id', id)\n id_check('private_key must be provided') if private_key.nil?\n bundle_method_check(bundle_method)\n data = {private_key: private_key, certificate: certificate, bundle_method: bundle_method}\n cf_patch(path: \"/zones/#{zone_id}/custom_certificates/#{id}\", data: data)\n end",
"def update\n @concert = Concert.find(params[:id])\n\n respond_to do |format|\n if @concert.update_attributes(concert_params)\n format.html { redirect_to(@concert, :notice => 'Concert was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => 'edit' }\n format.xml { render :xml => @concert.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @certificateinfo.update(certificateinfo_params)\n format.html { redirect_to @certificateinfo, notice: 'Certificateinfo was successfully updated.' }\n format.json { render :show, status: :ok, location: @certificateinfo }\n else\n format.html { render :edit }\n format.json { render json: @certificateinfo.errors, status: :unprocessable_entity }\n end\n end\n end",
"def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end",
"def patch_resource(payload)\n execute(resource_path, method: :patch, payload: payload.to_json)\n end",
"def update\n @certified_repository = CertifiedRepository.find(params[:id])\n\n respond_to do |format|\n if @certified_repository.update_attributes(params[:certified_repository])\n flash[:notice] = 'CertifiedRepository was successfully updated.'\n format.html { redirect_to(@certified_repository) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @certified_repository.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def patch(url, payload, headers={})\n RestClient.patch url, payload, headers\n end",
"def update!(**args)\n @certificate = args[:certificate] if args.key?(:certificate)\n @format = args[:format] if args.key?(:format)\n @x509_details = args[:x509_details] if args.key?(:x509_details)\n end",
"def update!(**args)\n @certificate = args[:certificate] if args.key?(:certificate)\n @format = args[:format] if args.key?(:format)\n @x509_details = args[:x509_details] if args.key?(:x509_details)\n end",
"def update\n respond_to :json\n\n if @expense_claim.update(expense_claim_params)\n head :ok\n else\n render partial: 'expense_claim_key_data', layout: false, status: :ok, locals: { expense_claim: @expense_claim }\n end\n end",
"def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end",
"def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def update\n respond_to do |format|\n if @incident_proof.update(incident_proof_params)\n format.html { redirect_to @incident_proof, notice: 'Incident proof was successfully updated.' }\n format.json { render :show, status: :ok, location: @incident_proof }\n else\n format.html { render :edit }\n format.json { render json: @incident_proof.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n\n @certificate_types = CertificateType.all\n @certificate_type = CertificateType.find(params[:id])\n\n @certificate_type.update_attributes(certificate_type_params)\n\n=begin\n respond_to do |format|\n if @certificate_type.update(certificate_type_params)\n format.html { redirect_to @certificate_type, notice: 'Certificate type was successfully updated.' }\n format.json { render :show, status: :ok, location: @certificate_type }\n else\n format.html { render :edit }\n format.json { render json: @certificate_type.errors, status: :unprocessable_entity }\n end\n end\n=end\n end",
"def update\n @classified = @user.classifieds.find(params[:id])\n\n respond_to do |format|\n if @classified.update_attributes(params[:classified])\n format.html { redirect_to @classified, notice: 'Classified was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @classified.errors, status: :unprocessable_entity }\n end\n end\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 patch(path, opts = {})\n request(:patch, path, opts).body\n end",
"def put!\n request! :put\n end",
"def update\n # { clinic: {id: references, \"license_id\"=>nil, \"name\"=>string } }\n \n if @clinic.update_attributes(params[:clinic].except(:api_license_id))\n head :no_content\n else\n render json: clinic.errors.full_messages, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @certification_scheme.update(certification_scheme_params)\n format.html { redirect_to @certification_scheme, notice: 'Certification scheme was successfully updated.' }\n format.json { render :show, status: :ok, location: @certification_scheme }\n else\n format.html { render :edit }\n format.json { render json: @certification_scheme.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @claim.update(claim_params)\n format.html { redirect_to @claim, notice: 'Claim was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @claim.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n course = Course.includes(:professors).find(params[:id])\n course.update!(course_params)\n \n course.professor_ids=(params[:professors])\n\n render json: course.to_json(include: :professors)\n end",
"def update\n respond_to do |format|\n if @certainty.update(certainty_params)\n format.html { redirect_to @certainty, notice: 'Certainty was successfully updated.' }\n format.json { render :show, status: :ok, location: @certainty }\n else\n format.html { render :edit }\n format.json { render json: @certainty.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, params = {})\n request(:patch, path, params)\n end",
"def patch(path, params = {})\n request(:patch, path, params)\n end",
"def patch(payload)\n post_like payload, Net::HTTP::Patch.new(@uri.path)\n end",
"def update # PATCH\n raise NotImplementedError\n end",
"def update\n @organic_certifier = OrganicCertifier.find(params[:id])\n\n respond_to do |format|\n if @organic_certifier.update_attributes(params[:organic_certifier])\n format.html { redirect_to(@organic_certifier, :notice => 'OrganicCertifier was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @organic_certifier.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @course_certificate.update(course_certificate_params)\n format.html { redirect_to @course_certificate, notice: \"Course certificate was successfully updated.\" }\n format.json { render :show, status: :ok, location: @course_certificate }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @course_certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch_tls_certificate_0_with_http_info(certificate_id, tls_trust_data, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PolicyInfraCertificatesCertificatesApi.patch_tls_certificate_0 ...'\n end\n # verify the required parameter 'certificate_id' is set\n if @api_client.config.client_side_validation && certificate_id.nil?\n fail ArgumentError, \"Missing the required parameter 'certificate_id' when calling PolicyInfraCertificatesCertificatesApi.patch_tls_certificate_0\"\n end\n # verify the required parameter 'tls_trust_data' is set\n if @api_client.config.client_side_validation && tls_trust_data.nil?\n fail ArgumentError, \"Missing the required parameter 'tls_trust_data' when calling PolicyInfraCertificatesCertificatesApi.patch_tls_certificate_0\"\n end\n # resource path\n local_var_path = '/global-infra/certificates/{certificate-id}'.sub('{' + 'certificate-id' + '}', certificate_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(tls_trust_data)\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: PolicyInfraCertificatesCertificatesApi#patch_tls_certificate_0\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def update\n respond_to do |format|\n if @catched.update(catched_params)\n format.html { redirect_to @catched, notice: 'Catched was successfully updated.' }\n format.json { render :show, status: :ok, location: @catched }\n else\n format.html { render :edit }\n format.json { render json: @catched.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, data, options = {})\n uri = build_uri(path, options)\n\n request = Net::HTTP::Patch.new(uri.request_uri)\n set_authorisation_header(request)\n request.set_form_data(data)\n\n response = https_client(uri).request(request)\n end",
"def update\n respond_to do |format|\n if @aws_certificate.update(aws_certificate_params)\n format.html { redirect_to @aws_certificate, notice: 'Aws certificate was successfully updated.' }\n format.json { render :show, status: :ok, location: @aws_certificate }\n else\n format.html { render :edit }\n format.json { render json: @aws_certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @medical_certificate.update(medical_certificate_params)\n format.html { redirect_to student_medical_certificates_path(@student), notice: 'Medical certificate was successfully updated.'}\n format.json { render :show, status: :ok, location: @medical_certificate }\n else\n format.html { render :edit }\n format.json { render json: @medical_certificate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, **args); end",
"def update\n respond_to do |format|\n if @incident.update(incident_params)\n format.json { head :no_content }\n else\n format.json { render json: @incident.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @collection_overrides = args[:collection_overrides] if args.key?(:collection_overrides)\n @credential = args[:credential] if args.key?(:credential)\n @custom_certificate_authority_roots = args[:custom_certificate_authority_roots] if args.key?(:custom_certificate_authority_roots)\n @description = args[:description] if args.key?(:description)\n @descriptor_url = args[:descriptor_url] if args.key?(:descriptor_url)\n @id = args[:id] if args.key?(:id)\n @insert_time = args[:insert_time] if args.key?(:insert_time)\n @labels = args[:labels] if args.key?(:labels)\n @name = args[:name] if args.key?(:name)\n @operation = args[:operation] if args.key?(:operation)\n @options = args[:options] if args.key?(:options)\n @self_link = args[:self_link] if args.key?(:self_link)\n end",
"def update\n respond_to do |format|\n if @certificado.update(certificado_params)\n format.html { redirect_to @certificado, notice: 'Certificado was successfully updated.' }\n format.json { render :show, status: :ok, location: @certificado }\n else\n format.html { render :edit }\n format.json { render json: @certificado.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @compromise = Compromise.find(params[:id])\n\n if @compromise.update(compromise_params)\n Notification.delete_all([\"compromise_id = ?\", @compromise.id])\n create_for_each_notification_type(@compromise)\n head :no_content\n else\n render json: @compromise.errors, status: :unprocessable_entity\n end\n end",
"def update\n @shop_claim = ShopClaim.find(params[:id])\n\n if @shop_claim.update(shop_claim_params)\n head :no_content\n else\n render json: @shop_claim.errors, status: :unprocessable_entity\n end\n end",
"def update\n @issuer = Issuer.find(params[:id])\n\n respond_to do |format|\n if @issuer.update_attributes(params[:issuer])\n format.html { redirect_to issuers_path, notice: 'Issuer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @issuer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @concert.update(concert_params)\n format.html { redirect_to @concert, notice: 'Concert was successfully updated.' }\n #TODO: localise the previous string\n format.json { render :show, status: :ok, location: @concert }\n else\n format.html { render :edit }\n format.json { render json: @concert.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(type, info)\n path, info = type_info(type, :path), force_case(info)\n ida = type == :client ? 'client_id' : 'id'\n raise ArgumentError, \"info must include #{ida}\" unless id = info[ida]\n hdrs = headers\n if info && info['meta'] && (etag = info['meta']['version'])\n hdrs.merge!('if-match' => etag)\n end\n reply = json_parse_reply(@key_style,\n *json_patch(@target, \"#{path}/#{Addressable::URI.encode(id)}\", info, hdrs))\n\n # hide client endpoints that are not quite scim compatible\n type == :client && !reply ? get(type, info['client_id']): reply\n end",
"def update\n respond_to do |format|\n if @couch.update(couch_params)\n format.html { redirect_to @couch, notice: 'Couch was successfully updated.' }\n format.json { render :show, status: :ok, location: @couch }\n else\n format.html { render :edit }\n format.json { render json: @couch.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @complaint = Complaint.find(params[:id])\n\n if @complaint.update_attributes(params[:complaint])\n head :no_content\n else\n render json: @complaint.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @certifications_member.update(certifications_member_params)\n format.html { redirect_to @certifications_member, notice: 'Certifications member was successfully updated.' }\n format.json { render :show, status: :ok, location: @certifications_member }\n else\n format.html { render :edit }\n format.json { render json: @certifications_member.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @patch.update(patch_params)\n format.html { redirect_to @patch, notice: 'Patch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @patch.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @cerc = Cerc.find(params[:id])\n\n if @cerc.update_attributes(params[:cerc])\n head :no_content\n else\n render json: @cerc.errors, status: :unprocessable_entity\n end\n end",
"def update\n @patch = Patch.find(params[:id])\n\n respond_to do |format|\n if @patch.update_attributes(params[:patch])\n format.html { redirect_to @patch, notice: 'Patch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @patch.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @ca_certificate = args[:ca_certificate] if args.key?(:ca_certificate)\n @ca_certificate_set = args[:ca_certificate_set] if args.key?(:ca_certificate_set)\n @client_certificate = args[:client_certificate] if args.key?(:client_certificate)\n @client_certificate_set = args[:client_certificate_set] if args.key?(:client_certificate_set)\n @client_key = args[:client_key] if args.key?(:client_key)\n @client_key_set = args[:client_key_set] if args.key?(:client_key_set)\n end",
"def update\n @event_subscription.update(event_subscription_params)\n @event_subscription.save\n\n file_params.each do |requirement|\n if(requirement[\"doc\"])\n requirement.symbolize_keys\n requirement[:doc].symbolize_keys\n path = \"data:#{requirement[:doc][:filetype]};base64, #{requirement[:doc][:base64]}\"\n Document.update(id: requirement[:doc][:id],\n user_id: @event_subscription.user_id,\n requirement_id: requirement[:id],\n state: \"pending_review\",\n path: path\n )\n end\n end\n render json: @event_subscription, status: :updated\n end",
"def patch(path, data, params = {}, request_options = {})\n request(:patch, path, data, params)\n end",
"def update\n @compromise = Compromise.find(params[:id])\n\n respond_to do |format|\n if @compromise.update_attributes(params[:compromise])\n format.html { redirect_to @compromise, notice: 'Compromise was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @compromise.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @certificate = Certificate.find(params[:id])\n\n respond_to do |format|\n if @certificate.update_attributes(params[:certificate])\n flash[:notice] = 'Certificate was successfully updated.'\n format.html { redirect_to(@certificate) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @certificate.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def put(id, json)\n with_endpoint do |endpoint|\n url = [endpoint, @resource_name, id].compact.join('/')\n url += \"/\" \n return HTTParty.put(url, :body => json, :timeout => 4, :headers => { 'Content-Type' => 'application/json' })\n end\n end",
"def update\n respond_to do |format|\n if @critical.update(critical_params)\n format.html { redirect_to @critical, notice: 'Critical was successfully updated.' }\n format.json { render :show, status: :ok, location: @critical }\n else\n format.html { render :edit }\n format.json { render json: @critical.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_key_cert\n converge_by(\"Update #{new_resource} cert key method\") do\n\t kid = new_resource.keyid\n\t cid = new_resource.certid\n caid = new_resource.cacertid if !new_resource.cacertid.nil?\n\t todel='-alt'\n\t if @current_resource.exists\n\t if !load_balancer.client['LocalLB.ProfileClientSSL'].get_key_file([\"/Common/#{new_resource.sslprofile_name}\"])[0].value.include?(\"#{new_resource.sslprofile_name}-alt\")\n\t\tkid = new_resource.sslprofile_name+'-alt.key'\n\t\tcid = new_resource.sslprofile_name+'-alt.crt'\n\t\tcaid = new_resource.sslprofile_name+'-alt.crt' if !new_resource.cacertid.nil?\n\t\ttodel = ''\n\t end\n\t end\n Chef::Log.info \"Update #{new_resource} cert key method with PASSPHRASE #{new_resource.passphrase}\"\n load_balancer.client['LocalLB.ProfileClientSSL'].set_key_certificate_file([new_resource.sslprofile_name], [{\"value\" => \"/Common/#{kid}\", \"default_flag\" => \"false\"}] , [{\"value\" => \"/Common/#{cid}\", \"default_flag\" => \"false\"}])\n load_balancer.client['LocalLB.ProfileClientSSL'].set_passphrase([\"/Common/#{new_resource.sslprofile_name}\"], [{\"value\" => \"#{new_resource.passphrase}\", \"default_flag\" => \"false\" }]) if !new_resource.passphrase.nil?\n load_balancer.client['LocalLB.ProfileClientSSL'].set_chain_file_v2([\"/Common/#{new_resource.sslprofile_name}\"], [{\"value\" => \"/Common/#{caid}\", \"default_flag\" => \"false\" }]) if !new_resource.cacertid.nil?\n\t \n\t ssl_d = load_balancer.ltm.ssls(\"MANAGEMENT_MODE_DEFAULT\").find { |p| p =~ /(^|\\/)#{new_resource.sslprofile_name}#{todel}$/ } \n\t if !ssl_d.nil?\n\t \tload_balancer.client['Management.KeyCertificate'].key_delete(\"MANAGEMENT_MODE_DEFAULT\", [\"/Common/#{new_resource.sslprofile_name}#{todel}\"])\n\t \tload_balancer.client['Management.KeyCertificate'].certificate_delete(\"MANAGEMENT_MODE_DEFAULT\", [\"/Common/#{new_resource.sslprofile_name}#{todel}\"])\n\t end\n current_resource.keyid(new_resource.keyid)\n current_resource.certid(new_resource.certid)\n current_resource.passphrase(new_resource.passphrase)\n current_resource.cacertid(new_resource.cacertid)\n\n new_resource.updated_by_last_action(true)\n end\n end",
"def patch options\n rest_request({ method: :patch }.merge(options))\n end",
"def patch options\n rest_request({ method: :patch }.merge(options))\n end",
"def patch_tls_certificate_with_http_info(certificate_id, tls_trust_data, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PolicyInfraCertificatesCertificatesApi.patch_tls_certificate ...'\n end\n # verify the required parameter 'certificate_id' is set\n if @api_client.config.client_side_validation && certificate_id.nil?\n fail ArgumentError, \"Missing the required parameter 'certificate_id' when calling PolicyInfraCertificatesCertificatesApi.patch_tls_certificate\"\n end\n # verify the required parameter 'tls_trust_data' is set\n if @api_client.config.client_side_validation && tls_trust_data.nil?\n fail ArgumentError, \"Missing the required parameter 'tls_trust_data' when calling PolicyInfraCertificatesCertificatesApi.patch_tls_certificate\"\n end\n # resource path\n local_var_path = '/infra/certificates/{certificate-id}'.sub('{' + 'certificate-id' + '}', certificate_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(tls_trust_data)\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: PolicyInfraCertificatesCertificatesApi#patch_tls_certificate\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def put payload, path = \"\"\n make_request(path, \"put\", payload)\n end",
"def update(url, data)\n RestClient.put url, data, :content_type => :json\nend",
"def update\n authorize @attorney\n respond_to do |format|\n if @attorney.update(attorney_params)\n format.html { redirect_to @attorney, success: I18n.t('notices.updated', entity: Attorney.model_name.human, title: @attorney.name) }\n format.json { render :show, status: :ok, location: @attorney }\n else\n format.html { render :edit }\n format.json { render json: @attorney.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @x509_certificate = args[:x509_certificate] if args.key?(:x509_certificate)\n end",
"def UpdateTicket params = {}\n \n APICall(path: 'tickets.json',method: 'PUT',payload: params.to_json)\n \n end",
"def patch\n end",
"def test_update_object_by_id\r\n\t VCR.use_cassette('edit_object') do\r\n\t\t cred=JSON.parse(YAML::load_file('test/fixtures/credential.yml').to_json)\r\n\t\t json = JSON.parse(File.read(\"test/fixtures/edit_specimen.json\"))\r\n\t\t id = json[\"id\"]\r\n\t\t json[\"id\"] = \"\" #id cannot be updated\r\n\t\t result=CordraRestClient::DigitalObject.update(API_URL, id, json, cred[\"uc_1\"])\r\n\r\n\t\t #check that the result is saved\r\n\t\t assert_equal 200, result[:code]\r\n\t\t assert_equal \"OK\", result[\"message\"]\r\n\t\tend\r\n\t end",
"def update\n respond_to do |format|\n if @special_collection_request.update(special_collection_request_params)\n format.html { redirect_to @special_collection_request, notice: 'Special collection request was successfully updated.' }\n format.json { render :show, status: :ok, location: @special_collection_request }\n else\n format.html { render :edit }\n format.json { render json: @special_collection_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @couch.update(couch_params)\n format.html { redirect_to @couch, notice: 'Couche was successfully updated.' }\n format.json { render :show, status: :ok, location: @couch }\n else\n format.html { render :edit }\n format.json { render json: @couch.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_gift_certificate_with_http_info(gift_certificate_oid, gift_certificate, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: GiftCertificateApi.update_gift_certificate ...'\n end\n # verify the required parameter 'gift_certificate_oid' is set\n if @api_client.config.client_side_validation && gift_certificate_oid.nil?\n fail ArgumentError, \"Missing the required parameter 'gift_certificate_oid' when calling GiftCertificateApi.update_gift_certificate\"\n end\n # verify the required parameter 'gift_certificate' is set\n if @api_client.config.client_side_validation && gift_certificate.nil?\n fail ArgumentError, \"Missing the required parameter 'gift_certificate' when calling GiftCertificateApi.update_gift_certificate\"\n end\n # resource path\n local_var_path = '/gift_certificate/gift_certificates/{gift_certificate_oid}'.sub('{' + 'gift_certificate_oid' + '}', gift_certificate_oid.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n header_params['X-UltraCart-Api-Version'] = @api_client.select_header_api_version()\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(gift_certificate)\n auth_names = ['ultraCartOauth', 'ultraCartSimpleApiKey']\n data, status_code, headers = @api_client.call_api(:PUT, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'GiftCertificateResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: GiftCertificateApi#update_gift_certificate\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def contact_updated(freshdesk_data,contact_id)\n\t\t#Rails.logger.info \"Update method id and data\"\n\t\t#Rails.logger.debug \"#{@api_domain}-#{contact_id}-#{@api_key}\"\n\t\t#Rails.logger.debug \"#{freshdesk_data.to_json}\"\n\t response = HTTParty.put(\n\t \"#{@api_domain}contacts/#{contact_id}\", \n\t\t basic_auth: { username: @api_key, password: \"password\" },\n\t\t headers: { 'Content-Type' => 'application/json' },\n\t\t body: freshdesk_data.to_json\n\t )\n\tend",
"def update\n respond_to do |format|\n if @instrument_patch.update(instrument_patch_params)\n format.html { redirect_to @instrument_patch, notice: 'Instrument patch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @instrument_patch.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @cadet.update(cadet_params)\n format.html { redirect_to @cadet, notice: 'Cadet was successfully updated.' }\n format.json { render :show, status: :ok, location: @cadet }\n else\n format.html { render :edit }\n format.json { render json: @cadet.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @classified.update(classified_params)\n format.html { redirect_to @classified, notice: 'Classified was successfully updated.' }\n format.json { render :show, status: :ok, location: @classified }\n else\n format.html { render :edit }\n format.json { render json: @classified.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @classified.update(classified_params)\n format.html { redirect_to @classified, notice: 'Classified was successfully updated.' }\n format.json { render :show, status: :ok, location: @classified }\n else\n format.html { render :edit }\n format.json { render json: @classified.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, params)\n time(\"PATCH #{path}\") { Cloudflarer.new.patch(path, params) }\n end",
"def rest_patch(base_uri,json_payload,params)\n begin\n @response = RestClient.patch(base_uri,json_payload,params)\n rescue => e\n puts @response.code\n end\n return @response\n end",
"def update\n # TODO エラーハンドリングを共通化する\n if @current_team&.id != @concert.team.id\n render json: false, status: :unauthorized\n elsif @concert.update(concert_savable_params)\n render :show, status: :ok\n else\n render json: @concert.errors, status: :unprocessable_entity\n end\n end",
"def update\n @id_proof = IdProof.find(params[:id])\n\n respond_to do |format|\n if @id_proof.update_attributes(params[:id_proof])\n format.html { redirect_to @id_proof, notice: 'Id proof was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @id_proof.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @incident = Incident.find(params[:id])\n\n if @incident.update(incident_params)\n head :no_content\n else\n render json: @incident.errors, status: :unprocessable_entity\n end\n end",
"def patch(url, data, headers = {})\n request(:patch, url, headers, :data => data)\n end"
] |
[
"0.67089456",
"0.6598706",
"0.6578622",
"0.6372914",
"0.6175863",
"0.6173402",
"0.61700946",
"0.60551465",
"0.6050975",
"0.6028821",
"0.60144734",
"0.599366",
"0.59705466",
"0.59705466",
"0.591571",
"0.591571",
"0.5899892",
"0.588313",
"0.58670896",
"0.5841749",
"0.5785926",
"0.5766992",
"0.57650346",
"0.57545376",
"0.57505953",
"0.572612",
"0.5719443",
"0.5719443",
"0.5708291",
"0.5697536",
"0.56806844",
"0.56531996",
"0.5645067",
"0.5633962",
"0.5625368",
"0.56215835",
"0.56118333",
"0.56038165",
"0.5603751",
"0.56027865",
"0.55960685",
"0.558704",
"0.55703515",
"0.55703515",
"0.55669826",
"0.55553496",
"0.5554088",
"0.5548781",
"0.5548165",
"0.5546572",
"0.5545994",
"0.553709",
"0.5528244",
"0.5527424",
"0.55251396",
"0.5521519",
"0.5517432",
"0.55157644",
"0.551306",
"0.55122274",
"0.5493974",
"0.54911935",
"0.54880863",
"0.5481989",
"0.5477792",
"0.5473331",
"0.5472287",
"0.54678184",
"0.5467661",
"0.5452531",
"0.5445624",
"0.54440325",
"0.5431885",
"0.5431118",
"0.5417354",
"0.54167753",
"0.54120183",
"0.54120183",
"0.5409904",
"0.5406323",
"0.54051006",
"0.5401261",
"0.5399691",
"0.53986675",
"0.5393072",
"0.53916514",
"0.53884673",
"0.5388301",
"0.53806037",
"0.5378935",
"0.5378233",
"0.53731334",
"0.53717417",
"0.53717417",
"0.5369221",
"0.5360475",
"0.53559077",
"0.53542215",
"0.53523767",
"0.5348116"
] |
0.628047
|
4
|
DELETE /certifieds/1 DELETE /certifieds/1.json
|
def destroy
@certified.destroy
respond_to do |format|
format.html { redirect_to certifieds_url }
format.json { head :no_content }
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def destroy\n @cert.destroy\n respond_to do |format|\n format.html { redirect_to certs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cert.destroy\n respond_to do |format|\n format.html { redirect_to certs_url, notice: 'Cert was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certification.destroy\n\n respond_to do |format|\n format.html { redirect_to certifications_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certtest.destroy\n respond_to do |format|\n format.html { redirect_to certtests_url, notice: 'Certtest was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certification.destroy\n respond_to do |format|\n format.html { redirect_to certifications_url, notice: 'Certification was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certification.destroy\n respond_to do |format|\n format.html { redirect_to certifications_url, notice: 'Certification was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certificate.destroy\n respond_to do |format|\n format.html { redirect_to certificates_path}\n format.json { head :no_content }\n end\n end",
"def destroy\n @certificate_request.destroy\n respond_to do |format|\n format.html { redirect_to certificate_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @small_concert.destroy\n respond_to do |format|\n format.html { redirect_to '/admin/small_concerts' }\n format.json { head :no_content }\n end\n end",
"def destroy\n # get the ca\n @authority = Certify::Authority.find(params[:certify_authority_id])\n\n # get the certificate\n @certificate = Certify::Certificate.find(params[:id])\n @certificate.destroy\n\n respond_to do |format|\n format.html { redirect_to certify_authority_path(@authority), notice: 'Certificate removed' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certainty.destroy\n respond_to do |format|\n format.html { redirect_to certainties_url, notice: 'Certainty was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certificate.destroy\n respond_to do |format|\n format.html { redirect_to certificates_url, notice: 'Certificate was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @concert.destroy\n respond_to do |format|\n format.html { redirect_to concerts_url, notice: 'Concert was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @concert.destroy\n respond_to do |format|\n format.html { redirect_to concerts_url, notice: 'Concert was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @concert.destroy\n respond_to do |format|\n format.html { redirect_to concerts_url, notice: 'Concert was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certificate.destroy\n respond_to do |format|\n format.html { redirect_to certificates_url, notice: 'Довідка видалена.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @concert = Concert.find(params[:id])\n @concert.destroy\n\n respond_to do |format|\n format.html { redirect_to(concerts_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @concert = Concert.find(params[:id])\n @concert.destroy\n\n respond_to do |format|\n format.html { redirect_to(concerts_url, :notice=> 'Concert was deleted.') }\n format.xml { head :ok }\n end\n end",
"def remove_cert(cert={})\n request :delete, '/certs', cert\n end",
"def destroy\n @gift_cert = GiftCert.find(params[:id])\n @gift_cert.destroy\n\n respond_to do |format|\n format.html { redirect_to(gift_certs_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @certificate = Certificate.find(params[:id])\n @certificate.destroy\n\n respond_to do |format|\n format.html { redirect_to(certificates_url) }\n format.xml { head :ok }\n end\n end",
"def delete\n res = HTTParty.get URL, headers: HEADERS\n message = JSON.parse res.body, symbolize_names: true\n if res.code == 200\n numSubs = message[:data].count\n if numSubs > 0\n message[:data].each do |sub|\n id = sub[:id]\n delRes = HTTParty.delete \"#{URL}/#{id}\", headers: HEADERS\n #TODO handle status codes\n end\n end\n end\n end",
"def destroy\n @aws_certificate.destroy\n respond_to do |format|\n format.html { redirect_to aws_certificates_url, notice: 'Aws certificate was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certification.destroy\n respond_to do |format|\n format.html { redirect_to @person, notice: 'Certification was successfully destroyed.' }\n end\n end",
"def destroy\n @certificateinfo.destroy\n respond_to do |format|\n format.html { redirect_to certificateinfos_url, notice: 'Certificateinfo was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certificado.destroy\n respond_to do |format|\n format.html { redirect_to certificados_url,\n notice: 'El certificado fue eliminado exitosamente.'}\n format.json { head :no_content }\n end\n end",
"def destroy\n @medical_certificate.destroy\n respond_to do |format|\n format.html { redirect_to student_medical_certificates_path(@student), notice: 'Medical certificate was successfully destroyed.'}\n format.json { head :no_content }\n end\n end",
"def destroy\n @certificadoriesgo.destroy\n respond_to do |format|\n format.html { redirect_to certificadoriesgos_url, notice: 'Certificadoriesgo was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @claim.destroy\n respond_to do |format|\n format.html { redirect_to claims_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certifications_member.destroy\n respond_to do |format|\n format.html { redirect_to certifications_members_url, notice: 'Certifications member was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @incident_proof.destroy\n respond_to do |format|\n format.html { redirect_to incident_proofs_url, notice: 'Incident proof was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @conciert = Conciert.find(params[:id])\n @conciert.destroy\n respond_to do |format|\n format.html { redirect_to group_concierts_url, notice: \"Conciert was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def delete\n client.delete(\"/#{id}\")\n end",
"def destroy\n @assertion.destroy\n respond_to do |format|\n format.html { redirect_to assertions_url, notice: 'Assertion was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete path\n make_request(path, \"delete\", {})\n end",
"def destroy\n @concert.destroy\n respond_to do |format|\n format.html { redirect_to concerts_url, notice: 'Concert was successfully destroyed.' }\n format.js {flash[:notice] = 'Concert was succesfully destroyed.'}\n format.json { head :no_content }\n end\n end",
"def delete\n request(:delete)\n end",
"def destroy\n @consensu = Consensu.find(params[:id])\n @consensu.destroy\n\n respond_to do |format|\n format.html { redirect_to consensus_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certified_repository = CertifiedRepository.find(params[:id])\n @certified_repository.destroy\n\n respond_to do |format|\n format.html { redirect_to(certified_repositories_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @organic_certifier = OrganicCertifier.find(params[:id])\n @organic_certifier.destroy\n\n respond_to do |format|\n format.html { redirect_to(organic_certifiers_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @course_certificate.destroy\n respond_to do |format|\n format.html { redirect_to course_certificates_url, notice: \"Course certificate was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def destroy\n @couch.destroy\n respond_to do |format|\n format.html { redirect_to couches_url, notice: 'Couch was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.new\n authorize @user\n\n @certificate.destroy\n respond_to do |format|\n format.html { redirect_to certificates_url, notice: 'Certificado excluído com sucesso.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certificado = Certificado.find(params[:id])\n @certificado.destroy\n\n respond_to do |format|\n format.html { redirect_to(certificados_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @enrollment.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def delete endpoint\n do_request :delete, endpoint\n end",
"def incident_delete(statuspage_id, incident_id)\n data = {}\n data['statuspage_id'] = statuspage_id\n data['incident_id'] = incident_id\n\n request :method => :post,\n :url => @url + 'incident/delete',\n :payload => data\n end",
"def destroy\n @certification_scheme.destroy\n respond_to do |format|\n format.html { redirect_to certification_schemes_url, notice: 'Certification scheme was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @certidao = Certidao.find(params[:id])\n @certidao.destroy\n\n respond_to do |format|\n format.html { redirect_to(certidaos_url) }\n format.xml { head :ok }\n end\n end",
"def delete(certificate_thumbprint)\n cert_delete(certstore_handler, certificate_thumbprint)\n end",
"def destroy\n\n @certificate_types = CertificateType.all\n @certificate_type = CertificateType.find(params[:id])\n @certificate_type.destroy\n\n=begin\n @certificate_type.destroy\n respond_to do |format|\n format.html { redirect_to certificate_types_url, notice: 'Certificate type was successfully destroyed.' }\n format.json { head :no_content }\n end\n=end\n end",
"def destroy\n @envelope.destroy\n\n respond_to do |format|\n format.html { redirect_to :root }\n format.json { head :ok }\n end\n end",
"def destroy\n @contestant = Contestant.find(params[:id])\n @contestant.destroy\n\n respond_to do |format|\n format.html { redirect_to contestants_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @shop_claim.destroy\n\n head :no_content\n end",
"def destroy\n @claim.destroy\n respond_to do |format|\n format.html { redirect_to insurer_claims_url, notice: 'Claim was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @critical.destroy\n respond_to do |format|\n format.html { redirect_to criticals_url, notice: 'Critical was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete!\n request! :delete\n end",
"def delete\n response = WebPay.client.delete(path)\n response['deleted']\n end",
"def destroy\n @distinctive_sign.destroy\n respond_to do |format|\n format.html { redirect_to distinctive_signs_url, notice: 'Distinctive sign was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @claim_datum.destroy\n respond_to do |format|\n format.html { redirect_to claim_data_url, notice: 'Claim datum was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @courier_request.destroy\n respond_to do |format|\n format.html { redirect_to courier_requests_url, notice: \"Courier request was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def delete\n url = prefix + \"delete\"\n return response(url)\n end",
"def delete\n url = prefix + \"delete\"\n return response(url)\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 @signed_lease.destroy\n respond_to do |format|\n format.html { redirect_to signed_leases_url, notice: 'Signed lease was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @couch.destroy\n respond_to do |format|\n format.html { redirect_to couches_url, notice: 'Couche was successfully destroyed.' }\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 @competency_unit.destroy\n respond_to do |format|\n format.html { redirect_to certification_scheme_path(@competency_unit.certification_scheme), notice: 'Competency unit was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n authorize! :manage, @vspec\n metric = @vspec.metric\n @vspec.destroy\n respond_to do |format|\n format.html { redirect_to [metric.service, metric] }\n format.json { head :no_content }\n end\n end",
"def delete(payload = {})\n request! do\n options = {payload: to_payload(payload)}\n api(options)[url.path].delete(API_HEADERS)\n end\n end",
"def destroy\n @newsletter.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n @cerveja = Cerveja.find(params[:id])\n @cerveja.destroy\n\n respond_to do |format|\n format.html { redirect_to cervejas_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @agreement.destroy\n respond_to do |format|\n format.html { redirect_to agreements_url, notice: 'Agreement was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @claimant = Claimant.find(params[:id])\n @claimant.destroy\n\n respond_to do |format|\n format.html { redirect_to claimants_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @fullassessment.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n @hold_request.destroy\n respond_to do |format|\n format.html { redirect_to student_requests_path, notice: 'Hold request was deleted.' }\n format.json { head :no_content }\n end\n end",
"def delete\n client.delete(url)\n @deleted = true\nend",
"def cancelReservation(lease_uuid)\n broker_url = APP_CONFIG['broker_ip'] + ':' + APP_CONFIG['broker_port'].to_s \n cert_path = APP_CONFIG['cert_path']\n \n header = {\"Content-Type\" => \"application/json\"}\n options = {uuid: lease_uuid}\n\n #puts options.to_json \n uri = URI.parse(broker_url+\"/resources/leases\")\n pem = File.read(cert_path)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n http.cert = OpenSSL::X509::Certificate.new(pem)\n http.key = OpenSSL::PKey::RSA.new(pem)\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Delete.new(uri.request_uri, header)\n request.body = options.to_json\n\n response = http.request(request)\n puts response\n if response.header.code != '200'\n puts \"Something went wrong\"\n puts response\n end\n end",
"def test_del\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n id = last_response.body\n\n delete \"/traces/#{id}\"\n assert last_response.ok?\n\n get \"/traces/#{id}\"\n\n contents = JSON.parse last_response.body\n assert_kind_of(Hash, contents, 'Response contents is not a hash')\n assert contents.key? 'description'\n assert(!last_response.ok?)\n end",
"def destroy\n if current_user.has_role? :admin\n @concert.destroy\n respond_to do |format|\n format.html { redirect_to concerts_url, notice: 'Concert was successfully destroyed.' }\n format.json { head :no_content }\n end\n end\n end",
"def delete!( opts = {} )\n http_action :delete, nil, opts\n end",
"def destroy\n @confection.destroy\n respond_to do |format|\n format.html { redirect_to confections_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cict.destroy\n respond_to do |format|\n format.html { redirect_to cicts_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @chiropractic_assessment = ChiropracticAssessment.find(params[:id])\n @chiropractic_assessment.destroy\n\n respond_to do |format|\n format.html { redirect_to chiropractic_assessments_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @cadet = Cadet.find(params[:id])\n @cadet.destroy\n\n respond_to do |format|\n format.html { redirect_to cadets_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @id_proof = IdProof.find(params[:id])\n @id_proof.destroy\n\n respond_to do |format|\n format.html { redirect_to id_proofs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @treq = Treq.find(params[:id])\n @treq.destroy\n\n respond_to do |format|\n format.html { redirect_to treqs_url }\n format.json { head :no_content }\n end\n end",
"def delete(id:)\n id_check('id', id)\n cf_delete(path: \"/zones/#{zone_id}/custom_certificates/#{id}\")\n end",
"def destroy\n @clientcase = Clientcase.find(params[:id])\n @clientcase.destroy\n\n respond_to do |format|\n format.html { redirect_to clientcases_url }\n format.json { head :ok }\n end\n end",
"def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end",
"def destroy\n @classified = Classified.find(params[:id])\n @classified.destroy\n\n respond_to do |format|\n format.html { redirect_to(classifieds_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @consignee.destroy\n respond_to do |format|\n format.html { redirect_to consignees_url, notice: 'Consignee was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @verification = Verification.find(params[:id])\n @verification.destroy\n\n respond_to do |format|\n format.html { redirect_to verifications_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @verification = Verification.find(params[:id])\n @verification.destroy\n\n respond_to do |format|\n format.html { redirect_to verifications_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @expectation = Expectation.find(params[:id])\n @expectation.destroy\n\n respond_to do |format|\n format.html { redirect_to expectations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @associated_trial.destroy\n respond_to do |format|\n format.html { redirect_to associated_trials_url, notice: 'Associated trial was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @dataload_email = DataloadEmail.find(params[:id])\n @dataload_email.destroy\n\n respond_to do |format|\n format.html { redirect_to dataload_emails_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @classified = @user.classifieds.find(params[:id])\n @classified.destroy\n\n respond_to do |format|\n format.html { redirect_to classifieds_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @authority = Certify::Authority.find(params[:certify_authority_id])\n @keypair = @authority.key_pairs.find(params[:id])\n @keypair.destroy\n\n respond_to do |format|\n format.html { redirect_to certify_authority_path(@authority), notice: 'Private key was successfully removed.' }\n format.json { head :no_content }\n end\n end"
] |
[
"0.7595877",
"0.741068",
"0.73887163",
"0.7270093",
"0.7259015",
"0.7259015",
"0.71330494",
"0.7105309",
"0.7025883",
"0.7000783",
"0.6947421",
"0.6929092",
"0.6903883",
"0.6903883",
"0.6903883",
"0.68865",
"0.6877033",
"0.6791788",
"0.67452013",
"0.6692637",
"0.6690766",
"0.66841173",
"0.66698104",
"0.66488326",
"0.66393214",
"0.66392714",
"0.66191924",
"0.6616606",
"0.6613355",
"0.66039747",
"0.6602588",
"0.6595772",
"0.6586381",
"0.65492517",
"0.6548813",
"0.65455145",
"0.6542091",
"0.6534737",
"0.6530547",
"0.6520341",
"0.651638",
"0.6509561",
"0.6495789",
"0.64750636",
"0.64583296",
"0.6457292",
"0.64542407",
"0.6446537",
"0.6439128",
"0.641802",
"0.63887227",
"0.63881844",
"0.6381144",
"0.6379558",
"0.6379486",
"0.6376056",
"0.63727",
"0.63671976",
"0.63563436",
"0.6356054",
"0.63533384",
"0.63482916",
"0.63469416",
"0.63469416",
"0.63427603",
"0.6337216",
"0.63362557",
"0.6332755",
"0.63311785",
"0.6322743",
"0.6318904",
"0.63180864",
"0.631265",
"0.6307211",
"0.63036954",
"0.6296238",
"0.6289117",
"0.6283098",
"0.6282098",
"0.62820333",
"0.6281673",
"0.62811446",
"0.6280293",
"0.6278217",
"0.62779397",
"0.6277852",
"0.62659144",
"0.62657654",
"0.6262622",
"0.6259049",
"0.6256688",
"0.6256533",
"0.62564844",
"0.62563294",
"0.62563294",
"0.62493163",
"0.6247872",
"0.6247478",
"0.62457347",
"0.62393814"
] |
0.79015255
|
0
|
Use callbacks to share common setup or constraints between actions.
|
def set_certified
@certified = Certified.find(params[:id])
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def set_required_actions\n # TODO: check what fields change to asign required fields\n end",
"def action_hook; end",
"def run_actions; end",
"def define_action_hook; end",
"def actions; end",
"def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end",
"def add_actions; end",
"def callbacks; end",
"def callbacks; end",
"def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end",
"def define_action_helpers; end",
"def post_setup\n end",
"def action_methods; end",
"def action_methods; end",
"def action_methods; end",
"def before_setup; end",
"def action_run\n end",
"def execute(setup)\n @action.call(setup)\n end",
"def define_action_helpers?; end",
"def set_actions\n actions :all\n end",
"def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end",
"def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end",
"def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end",
"def before_actions(*logic)\n self.before_actions = logic\n end",
"def setup_handler\n end",
"def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end",
"def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def workflow\n end",
"def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end",
"def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end",
"def before(action)\n invoke_callbacks *self.class.send(action).before\n end",
"def process_action(...)\n send_action(...)\n end",
"def before_dispatch(env); end",
"def after_actions(*logic)\n self.after_actions = logic\n end",
"def setup\n # override and do something appropriate\n end",
"def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end",
"def setup(_context)\n end",
"def setup(resources) ; end",
"def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end",
"def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end",
"def determine_valid_action\n\n end",
"def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end",
"def startcompany(action)\n @done = true\n action.setup\n end",
"def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end",
"def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end",
"def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end",
"def define_tasks\n define_weave_task\n connect_common_tasks\n end",
"def setup(&block)\n define_method(:setup, &block)\n end",
"def setup\n transition_to(:setup)\n end",
"def setup\n transition_to(:setup)\n end",
"def action\n end",
"def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend",
"def config(action, *args); end",
"def setup\n @setup_proc.call(self) if @setup_proc\n end",
"def before_action \n end",
"def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end",
"def action\n end",
"def matt_custom_action_begin(label); end",
"def setup\n # override this if needed\n end",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end",
"def after(action)\n invoke_callbacks *options_for(action).after\n end",
"def pre_task\n end",
"def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end",
"def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end",
"def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end",
"def setup_signals; end",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end",
"def initialize(*args)\n super\n @action = :set\nend",
"def after_set_callback; end",
"def setup\n #implement in subclass;\n end",
"def lookup_action; end",
"def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end",
"def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end",
"def release_actions; end",
"def around_hooks; end",
"def save_action; end",
"def setup(easy)\n super\n easy.customrequest = @verb\n end",
"def action_target()\n \n end",
"def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end",
"def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end",
"def before_setup\n # do nothing by default\n end",
"def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end",
"def default_action; end",
"def setup(&blk)\n @setup_block = blk\n end",
"def callback_phase\n super\n end",
"def advice\n end",
"def _handle_action_missing(*args); end",
"def duas1(action)\n action.call\n action.call\nend",
"def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end",
"def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end",
"def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend"
] |
[
"0.6163163",
"0.6045976",
"0.5946146",
"0.591683",
"0.5890051",
"0.58349305",
"0.5776858",
"0.5703237",
"0.5703237",
"0.5652805",
"0.5621621",
"0.54210985",
"0.5411113",
"0.5411113",
"0.5411113",
"0.5391541",
"0.53794575",
"0.5357573",
"0.53402257",
"0.53394014",
"0.53321576",
"0.53124547",
"0.529654",
"0.5296262",
"0.52952296",
"0.52600986",
"0.52442724",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.5232394",
"0.523231",
"0.5227454",
"0.52226824",
"0.52201617",
"0.5212327",
"0.52079266",
"0.52050185",
"0.51754695",
"0.51726824",
"0.51710224",
"0.5166172",
"0.5159343",
"0.51578903",
"0.51522785",
"0.5152022",
"0.51518047",
"0.51456624",
"0.51398855",
"0.5133759",
"0.5112076",
"0.5111866",
"0.5111866",
"0.5110294",
"0.5106169",
"0.509231",
"0.50873137",
"0.5081088",
"0.508059",
"0.50677156",
"0.50562143",
"0.5050554",
"0.50474834",
"0.50474834",
"0.5036181",
"0.5026331",
"0.5022976",
"0.5015441",
"0.50121695",
"0.5000944",
"0.5000019",
"0.4996878",
"0.4989888",
"0.4989888",
"0.49864885",
"0.49797225",
"0.49785787",
"0.4976161",
"0.49683493",
"0.4965126",
"0.4958034",
"0.49559742",
"0.4954353",
"0.49535993",
"0.4952725",
"0.49467874",
"0.49423352",
"0.49325448",
"0.49282882",
"0.49269363",
"0.49269104",
"0.49252945",
"0.4923091",
"0.49194667",
"0.49174926",
"0.49173003",
"0.49171105",
"0.4915879",
"0.49155936"
] |
0.0
|
-1
|
Never trust parameters from the scary internet, only allow the white list through.
|
def certified_params
params.require(:certified).permit( :background_url, :event_id, :name_color)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def strong_params\n params.require(:user).permit(param_whitelist)\n end",
"def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end",
"def allow_params_authentication!; end",
"def allowed_params\n ALLOWED_PARAMS\n end",
"def default_param_whitelist\n [\"mode\"]\n end",
"def param_whitelist\n [:role, :title]\n end",
"def expected_permitted_parameter_names; end",
"def safe_params\n params.except(:host, :port, :protocol).permit!\n end",
"def strong_params\n params.require(:team_member).permit(param_whitelist)\n end",
"def permitir_parametros\n \t\tparams.permit!\n \tend",
"def strong_params\n params.require(:community).permit(param_whitelist)\n end",
"def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end",
"def strong_params\n params.require(:education).permit(param_whitelist)\n end",
"def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end",
"def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end",
"def param_whitelist\n [:rating, :review]\n end",
"def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end",
"def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end",
"def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end",
"def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end",
"def valid_params_request?; end",
"def strong_params\n params.require(:experience).permit(param_whitelist)\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end",
"def allowed_params\n params.require(:allowed).permit(:email)\n end",
"def permitted_params\n []\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end",
"def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend",
"def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end",
"def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end",
"def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end",
"def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end",
"def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end",
"def safe_params\n params.require(:user).permit(:name)\n end",
"def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend",
"def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end",
"def check_params; true; end",
"def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end",
"def quote_params\n params.permit!\n end",
"def valid_params?; end",
"def paramunold_params\n params.require(:paramunold).permit!\n end",
"def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend",
"def filtered_parameters; end",
"def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end",
"def filtering_params\n params.permit(:email, :name)\n end",
"def check_params\n true\n end",
"def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend",
"def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend",
"def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end",
"def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end",
"def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end",
"def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend",
"def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end",
"def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end",
"def active_code_params\n params[:active_code].permit\n end",
"def filtering_params\n params.permit(:email)\n end",
"def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end",
"def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end",
"def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end",
"def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end",
"def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end",
"def list_params\n params.permit(:name)\n end",
"def filter_parameters; end",
"def filter_parameters; end",
"def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end",
"def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end",
"def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end",
"def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end",
"def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end",
"def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end",
"def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end",
"def url_whitelist; end",
"def admin_social_network_params\n params.require(:social_network).permit!\n end",
"def filter_params\n params.require(:filters).permit(:letters)\n end",
"def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end",
"def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end",
"def sensitive_params=(params)\n @sensitive_params = params\n end",
"def permit_request_params\n params.permit(:address)\n end",
"def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end",
"def secure_params\n params.require(:location).permit(:name)\n end",
"def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end",
"def question_params\n params.require(:survey_question).permit(question_whitelist)\n end",
"def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end",
"def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end",
"def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end",
"def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end",
"def url_params\n params[:url].permit(:full)\n end",
"def backend_user_params\n params.permit!\n end",
"def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend",
"def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end",
"def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end",
"def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end",
"def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end",
"def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end",
"def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end",
"def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end",
"def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end"
] |
[
"0.69792545",
"0.6781151",
"0.67419964",
"0.674013",
"0.6734356",
"0.6591046",
"0.6502396",
"0.6496313",
"0.6480641",
"0.6477825",
"0.64565",
"0.6438387",
"0.63791263",
"0.63740575",
"0.6364131",
"0.63192815",
"0.62991166",
"0.62978333",
"0.6292148",
"0.6290449",
"0.6290076",
"0.62894756",
"0.6283177",
"0.6242471",
"0.62382483",
"0.6217549",
"0.6214457",
"0.6209053",
"0.6193042",
"0.6177802",
"0.6174604",
"0.61714715",
"0.6161512",
"0.6151757",
"0.6150663",
"0.61461",
"0.61213595",
"0.611406",
"0.6106206",
"0.6105114",
"0.6089039",
"0.6081015",
"0.6071004",
"0.60620916",
"0.6019971",
"0.601788",
"0.6011056",
"0.6010898",
"0.6005122",
"0.6005122",
"0.6001556",
"0.6001049",
"0.59943926",
"0.5992201",
"0.59909594",
"0.5990628",
"0.5980841",
"0.59669393",
"0.59589154",
"0.5958826",
"0.5957911",
"0.5957385",
"0.5953072",
"0.59526145",
"0.5943361",
"0.59386164",
"0.59375334",
"0.59375334",
"0.5933856",
"0.59292704",
"0.59254247",
"0.5924164",
"0.59167904",
"0.59088355",
"0.5907542",
"0.59064597",
"0.5906243",
"0.5898226",
"0.589687",
"0.5896091",
"0.5894501",
"0.5894289",
"0.5891739",
"0.58860534",
"0.5882406",
"0.587974",
"0.58738774",
"0.5869024",
"0.58679986",
"0.5867561",
"0.5865932",
"0.5864461",
"0.58639693",
"0.58617616",
"0.5861436",
"0.5860451",
"0.58602303",
"0.5854586",
"0.58537364",
"0.5850427",
"0.5850199"
] |
0.0
|
-1
|
convert.exe before.jpg region "230x140+60+130" ^ fill black ^ fuzz 25%% ^ opaque rgb("192","00","10")
|
def apply(image)
image.view(0,0,image.columns,image.rows) do |view|
eyes.each { |eye| do_redeye(eye,view) }
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def main()\n img = ImageList.new($input)\n convert = ImageList.new\n page = Magick::Rectangle.new(0,0,0,0)\n $total_ops = (img.rows * img.columns).to_f\n\n for i in 0..img.rows\n for j in 0..img.columns\n pixel = generate_hex_pixel(rgb_to_hex(img.pixel_color(j,i)))\n convert << pixel\n page.x = j * pixel.columns\n page.y = i * pixel.rows\n pixel.page = page\n progress()\n end\n end\n\n puts 'Writing image, this could take a while...'\n convert.mosaic.write($output)\nend",
"def setup\n size 200, 200 \n no_stroke\n background 0 \n c = load_image \"cait.jpg\" \n xoff, yoff = 0, 0\n p = 2\n pix = p * 3 \n (c.width * c.height).times do |i| \n pixel = c.pixels[i] \n fill red( pixel ), 0, 0\n rect xoff, yoff, p, pix \n fill 0, green( pixel ), 0\n rect xoff+p, yoff, p, pix \n fill 0, 0, blue( pixel )\n rect xoff+p*2, yoff, p, pix \n xoff += pix\n if xoff >= (width-pix)\n xoff = 0\n yoff += pix\n end\n end \nend",
"def process_small_image\n small_image.encode!(:png).convert!('-resize 50x50 -gravity center -background none -extent 50x50')\n end",
"def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend",
"def generate_test_image(file, params = {})\n # Set default size for sample test image.\n line_size = 1\n box_size = 6\n width = (box_size * 6) + (line_size * 7)\n height = (box_size * 5) + (line_size * 6)\n\n # Set parameters for image creation options.\n image_type = params[:image_type] || File.extname(file)\n bands = params[:bands] || 3\n color = params[:color] || 'rgb'\n depth = params[:depth] || 8\n cg_type = params[:cg_type] || 'adobe_rgb'\n compression = params[:compression]\n profile = params[:profile]\n\n temp_array = color_gauge_values(cg_type)\n temp_image = Vips::Image.black(width, height, bands: temp_array.first.size)\n 5.times do |i|\n b = (box_size * i) + (line_size * (i + 1))\n # d = b + box_size - line_size\n 6.times do |j|\n a = (box_size * j) + (line_size * (j + 1))\n # c = a + box_size - line_size\n colors = temp_array.shift\n temp_image = temp_image.draw_rect(colors, a, b, box_size, box_size, fill: true)\n end\n end\n\n temp_image = color.eql?('cmyk') ? temp_image.copy(interpretation: :cmyk) : temp_image.copy(interpretation: :srgb)\n\n temp_image = if color.eql?('grey') && bands == 3\n mean = temp_image.bandmean\n Vips::Image.bandjoin([mean, mean, mean])\n elsif color.eql?('grey') && bands == 1\n temp_image.bandmean\n elsif color.eql?('bin') && bands == 3\n mean = temp_image.bandmean < 128\n Vips::Image.bandjoin([mean, mean, mean])\n elsif color.eql?('bin') && bands == 1\n temp_image.bandmean < 128\n else\n temp_image\n end\n\n options = {}\n unless profile.nil?\n profile_file = File.join(Assembly::PATH_TO_IMAGE_GEM, 'profiles', \"#{profile}.icc\")\n options.merge!(profile: profile_file)\n end\n\n case image_type\n when '.tiff', '.tif'\n options.merge!(compression: compression) unless compression.nil?\n options.merge!(squash: true) if depth.eql?(1)\n temp_image.tiffsave(file, **options)\n when '.jpeg', '.jpg'\n temp_image.jpegsave(file, **options)\n else\n raise \"unknown type: #{image_type}\"\n end\nend",
"def black_and_white\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.quantize(256, Magick::GRAYColorspace)\n img.write('public' + @photo.attachment_url)\n end",
"def process(raw)\n # set up some temp filenames\n rgb = raw.gsub \"raw\", \"rgb\"\n tif = raw.gsub \"raw\", \"tif\"\n\n # calculate the strip size\n bytes = File.size raw\n bytes -= 16 # remove the header bytes from the calculation\n size = { width: bytes / 6 / HEIGHT, height: HEIGHT }\n\n puts \"Processing #{raw} as #{size[:width]}x#{size[:height]}px..\"\n\n # rename to rgb\n `mv #{raw} #{rgb}`\n\n # convert to tiff and normalize channels while at it, then crop into equal tiles\n `convert -size #{size[:width]}x#{size[:height]} -depth 16 -interlace plane -channel ALL -normalize -contrast-stretch 1.5x0.03% -crop #{size[:width] / WIDTH }x1@ +repage #{rgb} %d_#{tif}`\n\n # rename to raw\n `mv #{rgb} #{raw}`\nend",
"def main\n ImageManip::inspect_image(@image_path)\n dimensions = ImageManip::get_dimensions(@image_path)\n sharp_pixels = get_accidental_pixels(@sharp_path)\n flat_pixels = get_accidental_pixels(@flat_path)\n edits = Hash.new\n edits[:lower_left] = [dimensions[0] / 2, dimensions[1] / 2]\n edits[:rgb_array] = sharp_pixels\n ImageManip::draw_2D_object(@image_path, './new_staff.gif', edits)\n edits[:lower_left] = [dimensions[0] / 3, dimensions[1] / 3]\n edits[:rgb_array] = flat_pixels\n ImageManip::draw_2D_object('./new_staff.gif', './new_staff.gif', edits)\n end",
"def map_transparent_pixels(img_path)\n print_status(\"Mapping transparent pixels for #{img_path}\")\n img = ChunkyPNG::Image.from_file(img_path)\n\n found_indexes = []\n index = 0\n img.pixels.each do |p|\n found_indexes << index if ChunkyPNG::Color.fully_transparent?(p)\n index += 1\n end\n\n found_indexes\nend",
"def image_colors(input_image)\n image = ImageList.new(input_image)\n\n q = image.resize_to_fit(75, 75).quantize(8, Magick::RGBColorspace)\n\n palette = q.color_histogram.sort {|a, b| b[1] <=> a[1]}\n\n # width in px times height in px\n total_depth = image.columns * image.rows\n\n results = []\n\n palette.count.times do |i|\n p = palette[i]\n\n r1 = p[0].red / 256\n g1 = p[0].green / 256\n b1 = p[0].blue / 256\n\n r2 = r1.to_s(16).rjust(2, \"0\")\n g2 = g1.to_s(16).rjust(2, \"0\")\n b2 = b1.to_s(16).rjust(2, \"0\")\n\n # r2 += r2 unless r2.length == 2\n # g2 += g2 unless g2.length == 2\n # b2 += b2 unless b2.length == 2\n\n rgb = \"#{r1},#{g1},#{b1}\"\n hex = \"#{r2}#{g2}#{b2}\"\n depth = p[1]\n\n results << {\n rgb: rgb,\n hex: hex,\n percent: ((depth.to_f / total_depth.to_f) * 100).round(2)\n }\n end\n\n # q.write('../../assets/img/test/new_' + File.basename(input_image))\n\n # puts results\n\n results\nend",
"def interlace\n manipulate! do |img|\n img.strip\n img.combine_options do |c|\n c.quality \"80\"\n c.depth \"8\"\n c.interlace \"plane\"\n end\n img\n end\n end",
"def redify(file, range, off)\n \n Magick::Image.read(file)[0].each_pixel do |pixel|\n pixel.each do |r,g,b|\n ary.bsearch {|x| block } → elem # find matching X in array, apply block...\n \n end\n end \nend",
"def convert_image_resource(path)\n puts(\"Updating and trimming image file '#{path}'\")\n image = MiniMagick::Image.open(path)\n image.combine_options do |co|\n co.fuzz(\"90%\") # color disimilarity threshold to get all shadows, see https://github.com/fastlane/fastlane/pull/14199\n co.trim(\"+repage\") # `+repage` removes meta-data\n end\n image.write(path)\nend",
"def mask(image, before, after, bg = WHITE, tolerance = 0.5)\n new_image = ChunkyPNG::Image.new(image.width, image.height, TRANSPARENT)\n image.width.times{ |x|\n image.height.times{ |y|\n score = euclidean_distance_rgba(image[x,y], before).to_f / MAX_EUCLIDEAN_DISTANCE_RGBA\n if score < tolerance then new_image[x,y] = ChunkyPNG::Color.compose(after, bg) end\n }\n }\n new_image\nend",
"def convert_image_resource(path)\n puts(\"Updating and trimming image file '#{path}'\")\n image = MiniMagick::Image.open(path)\n image.combine_options do |co|\n co.fuzz(\"90%\") # color dissimilarity threshold to get all shadows, see https://github.com/fastlane/fastlane/pull/14199\n co.trim(\"+repage\") # `+repage` removes meta-data\n end\n image.write(path)\nend",
"def test_add_transparency_chunk\n img = Imgrb::Image.new(41,41,0)\n transparency_chunk = Imgrb::Chunks::ChunktRNS.assemble(0,:indexed)\n img.add_chunk(transparency_chunk)\n\n png_str = save_png_to_string(img, 1)\n img_saved = Imgrb::Image.new(png_str, :from_string)\n\n assert img_saved.has_alpha?\n end",
"def preprocess_image(path)\n MiniMagick::Tool::Convert.new.yield_self do |convert|\n convert << path\n\n if config.localization_preprocessing != :none\n # general preprocessing\n convert.colorspace \"Gray\"\n convert.normalize\n\n if config.localization_preprocessing == :full\n # try to reduce shadows (based on https://legacy.imagemagick.org/Usage/compose/#divide)\n convert.stack do |stack|\n convert.clone 0\n convert.sample \"25%\"\n convert.blur \"30x10\"\n convert.resize \"400%\"\n end\n convert.compose \"DivideSrc\"\n convert.composite\n\n # remove short vertical features\n convert.morphology \"Close\", \"3x6: 1,-,1 1,-,1 1,-,1 1,-,1 1,-,1 1,-,1\"\n # remove small features and flaws\n convert.morphology \"Close:3\", \"Square:1\"\n end\n\n convert.threshold \"50%\"\n end\n\n convert.depth 8\n convert << \"gray:-\"\n\n MiniMagick::Shell.new.run(convert.command)\n end.first\n end",
"def test_load_8bit_interlaced_grayscale_alpha\n img = Imgrb::Image.new(\"test/png_test_suite/basi4a08.png\")\n assert GRAYSCALE_ALPHA_8BIT_GRAY_ROWS == img.get_channel(0).rows\n assert GRAYSCALE_ALPHA_8BIT_ALPHA_ROWS == img.get_channel(1).rows\n end",
"def enhance_image(image)\n colors = image.get_pixels.flatten\n colors.map! { |color| color**2 / 255 }\n blob = colors.pack('C*') # Recreate the original image, credit to stackoverflow.com/questions/53764046\n image = MiniMagick::Image.import_pixels(blob, image.width, image.height, 8, 'rgb')\n image.statistic('mean', '6x6')\n image.threshold(threshold_percent)\n image.statistic('median', '9x9') # Replace with object discard below set size\n end",
"def imagemagick?; end",
"def test_load_8bit_interlaced_paletted\n img = Imgrb::Image.new(\"test/png_test_suite/basi3p08.png\")\n assert INDEXED_8BIT_DEPALETTED_R_ROWS == img.get_channel(0).rows\n assert INDEXED_8BIT_DEPALETTED_G_ROWS == img.get_channel(1).rows\n assert INDEXED_8BIT_DEPALETTED_B_ROWS == img.get_channel(2).rows\n end",
"def build(filename, frames)\n frames = normalize_depth frames, to: 3 # frames are rows of pixels\n pixel_args = frames.flat_map.with_index do |rows, z|\n width, height = frames.first.first.length, frames.first.length\n [ '(',\n '-size', \"#{width}x#{height}\", 'xc:none',\n '-frame', z.to_s,\n *rows.flat_map.with_index { |pixels, y|\n pixels.flat_map.with_index do |pixel, x|\n color = if pixel[:transparent]\n ['-alpha', 'Transparent']\n else\n [\"-fill\", \"RGB(#{pixel.fetch :red},#{pixel.fetch :green},#{pixel.fetch :blue})\",\n \"-draw\", \"point #{x},#{y}\"\n ]\n end\n end\n },\n ')',\n ]\n end\n\n if File.exist? filename\n puts \"skipping #{filename}\"\n else\n program = 'convert', '-coalesce', *pixel_args, filename\n puts program.join ' '\n system *program\n end\nend",
"def conform( image )\n @logger.info( \"T #{Thread.current[:id]}: Conform image: #{ image }\" )\n return @asset_functions.create_asset( image, @output_format ) {|a| @output_type_obj.convert_resize_extent_color_specs( image, a )}\n end",
"def convert_to_images(arr,rows,cols)\n canvas = ChunkyPNG::Canvas.new(28, 28, ChunkyPNG::Color::TRANSPARENT)\n canvas.grayscale!\n \n for i in 0..arr.length-1 do\n for j in 0..rows-1 do\n for k in 0..cols-1 do\n canvas[j,k] = arr[i][((cols+1)*j)+k]\n end\n end\n canvas.save(\"F:\\\\Projects\\\\YetAnotherAnn\\\\filename#{i}.png\", :interlace => true)\n end\nend",
"def setup\n size 200, 200\n @a = load_image 'construct.jpg'\n @b = load_image 'wash.jpg'\n @offset = 0.0\nend",
"def test_load_8bit_interlaced_rgba\n img = Imgrb::Image.new(\"test/png_test_suite/basi6a08.png\")\n assert RGBA_R_8BIT_ROWS == img.get_channel(0).rows\n assert RGBA_G_8BIT_ROWS == img.get_channel(1).rows\n assert RGBA_B_8BIT_ROWS == img.get_channel(2).rows\n assert RGBA_A_8BIT_ROWS == img.get_channel(3).rows\n end",
"def depolarize\n @image.run_command(\"convert\", @image.path, \"-virtual-pixel Black -distort DePolar 0\", @image.path)\n end",
"def imagemagick7?; end",
"def test_load_8bit_interlaced_rgb\n img = Imgrb::Image.new(\"test/png_test_suite/basi2c08.png\")\n assert RGB_R_8BIT_ROWS == img.get_channel(0).rows\n assert RGB_G_8BIT_ROWS == img.get_channel(1).rows\n assert RGB_B_8BIT_ROWS == img.get_channel(2).rows\n end",
"def customQRcode(inputStr) \n qrcode = RQRCode::QRCode.new(inputStr).as_png(fill: 'white', color: 'black', file: 'abc.png')\n avatar = ChunkyPNG::Image.from_file('abc.png')\n\n # alogo.png being the logo file\n badge = ChunkyPNG::Image.from_file('alogo.png')\n\n print(\"height of backgound:\")\n print(avatar.height)\n print(\"height of logo:\")\n print(badge.height)\n\n #Alpha Blending\n avatar.compose!(badge, avatar.height/2 - badge.height/2, avatar.height/2 - badge.height/2)\n avatar.save('composited.png', :fast_rgba)\nend",
"def test_progressive_dct_based_jpeg_image\n testname = '35w x 35h progressive jpeg image.'\n data = %w(\n FF D8 FF E0 00 10 4A 46 49 46 00 01 02 01 00 96\n 00 96 00 00 FF E1 04 E7 45 78 69 66 00 00 4D 4D\n 00 2A 00 00 00 08 00 07 01 12 00 03 00 00 00 01\n 00 01 00 00 01 1A 00 05 00 00 00 01 00 00 00 62\n 01 1B 00 05 00 00 00 01 00 00 00 6A 01 28 00 03\n 00 00 00 01 00 02 00 00 01 31 00 02 00 00 00 14\n 00 00 00 72 01 32 00 02 00 00 00 14 00 00 00 86\n 87 69 00 04 00 00 00 01 00 00 00 9C 00 00 00 C8\n 00 00 00 96 00 00 00 01 00 00 00 96 00 00 00 01\n 41 64 6F 62 65 20 50 68 6F 74 6F 73 68 6F 70 20\n 37 2E 30 00 32 30 30 38 3A 30 39 3A 30 39 20 32\n 32 3A 32 33 3A 31 32 00 00 00 00 03 A0 01 00 03\n 00 00 00 01 FF FF 00 00 A0 02 00 04 00 00 00 01\n 00 00 00 23 A0 03 00 04 00 00 00 01 00 00 00 23\n 00 00 00 00 00 00 00 06 01 03 00 03 00 00 00 01\n 00 06 00 00 01 1A 00 05 00 00 00 01 00 00 01 16\n 01 1B 00 05 00 00 00 01 00 00 01 1E 01 28 00 03\n 00 00 00 01 00 02 00 00 02 01 00 04 00 00 00 01\n 00 00 01 26 02 02 00 04 00 00 00 01 00 00 03 B9\n 00 00 00 00 00 00 00 48 00 00 00 01 00 00 00 48\n 00 00 00 01 FF D8 FF E0 00 10 4A 46 49 46 00 01\n 02 01 00 48 00 48 00 00 FF ED 00 0C 41 64 6F 62\n 65 5F 43 4D 00 02 FF EE 00 0E 41 64 6F 62 65 00\n 64 80 00 00 00 01 FF DB 00 84 00 0C 08 08 08 09\n 08 0C 09 09 0C 11 0B 0A 0B 11 15 0F 0C 0C 0F 15\n 18 13 13 15 13 13 18 11 0C 0C 0C 0C 0C 0C 11 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 01 0D 0B 0B 0D\n 0E 0D 10 0E 0E 10 14 0E 0E 0E 14 14 0E 0E 0E 0E\n 14 11 0C 0C 0C 0C 0C 11 11 0C 0C 0C 0C 0C 0C 11\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C FF C0 00 11\n 08 00 23 00 23 03 01 22 00 02 11 01 03 11 01 FF\n DD 00 04 00 03 FF C4 01 3F 00 00 01 05 01 01 01\n 01 01 01 00 00 00 00 00 00 00 03 00 01 02 04 05\n 06 07 08 09 0A 0B 01 00 01 05 01 01 01 01 01 01\n 00 00 00 00 00 00 00 01 00 02 03 04 05 06 07 08\n 09 0A 0B 10 00 01 04 01 03 02 04 02 05 07 06 08\n 05 03 0C 33 01 00 02 11 03 04 21 12 31 05 41 51\n 61 13 22 71 81 32 06 14 91 A1 B1 42 23 24 15 52\n C1 62 33 34 72 82 D1 43 07 25 92 53 F0 E1 F1 63\n 73 35 16 A2 B2 83 26 44 93 54 64 45 C2 A3 74 36\n 17 D2 55 E2 65 F2 B3 84 C3 D3 75 E3 F3 46 27 94\n A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56 66\n 76 86 96 A6 B6 C6 D6 E6 F6 37 47 57 67 77 87 97\n A7 B7 C7 D7 E7 F7 11 00 02 02 01 02 04 04 03 04\n 05 06 07 07 06 05 35 01 00 02 11 03 21 31 12 04\n 41 51 61 71 22 13 05 32 81 91 14 A1 B1 42 23 C1\n 52 D1 F0 33 24 62 E1 72 82 92 43 53 15 63 73 34\n F1 25 06 16 A2 B2 83 07 26 35 C2 D2 44 93 54 A3\n 17 64 45 55 36 74 65 E2 F2 B3 84 C3 D3 75 E3 F3\n 46 94 A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5\n 56 66 76 86 96 A6 B6 C6 D6 E6 F6 27 37 47 57 67\n 77 87 97 A7 B7 C7 FF DA 00 0C 03 01 00 02 11 03\n 11 00 3F 00 F5 54 0B 33 71 AB 79 AC BF 75 83 53\n 5B 01 7B 84 F1 B9 95 EE 73 54 F2 1C E6 D1 63 9B\n F4 9A C7 16 FC 40 5C F7 49 B7 1A FA 19 51 BF 23\n 1B 2C B4 3A EC 7B 2D 65 76 6E 23 DC FD 06 FB 58\n FF 00 A4 CB 92 53 1E B9 F5 9B 3E 96 DB 8D 83 D3\n B2 85 A7 DB 56 53 D8 1B 5C E9 EE 0F 7E E6 37 FE\n B8 AF FD 5B FD AA 71 9E EE A2 CB 6A 26 36 D7 7B\n C5 8F 07 5D EE DE 27 F4 7F 43 E9 21 E5 D5 85 8D\n 59 39 B9 04 56 EE 45 D9 6F F7 79 7A 6D 1E FF 00\n EA AB 9D 0A C3 67 4D AC 9A AC C7 01 CF 0C A6 D2\n 4B DA D0 E7 7A 61 FE A4 BF E8 7E FA 4A 74 12 49\n 24 94 FF 00 FF D0 F5 2B DA 5D 4D 8D 1C B9 A4 7D\n E1 66 F4 FB BA 7F 50 C3 C7 17 D4 CF 59 B5 33 F4\n 57 06 97 00 47 2D 9F CC 74 7D 26 2D 55 CC 7D 61\n CD 7F 40 38 66 BA 99 76 16 4D CE AD EC B8 4B 69\n 2E 06 C6 7A 76 0F 73 37 D9 EC D8 EF EC 24 A7 61\n 95 74 7C 70 6F 6B 28 AF 61 FE 72 1B 20 8F DD 77\n D2 44 E9 97 8C 8C 63 7B 5A E6 36 CB 2C 21 AE D1\n D0 1E EA F5 1F D8 58 1F 57 FA 95 DD 6B 23 25 B5\n D5 5E 23 31 F6 13 63 1A 1E F9 70 73 76 56 F7 7B\n 6A FE 6F 7F D0 FC F5 D3 63 D1 56 3D 2C A6 A6 ED\n AD 82 1A 12 52 44 92 49 25 3F FF D1 F5 55 47 AD\n C7 EC AC AD DE 84 7A 6E 9F B5 4F A3 11 FE 1B 67\n BF 67 F5 17 CC 69 24 A7 E9 6F AB BB 7F 66 55 B7\n EC BB 60 47 D8 B7 7A 5C 7F C2 7E 93 FC F5 A8 BE\n 55 49 25 3F 55 24 BE 55 49 25 3F FF D9 FF ED 09\n 94 50 68 6F 74 6F 73 68 6F 70 20 33 2E 30 00 38\n 42 49 4D 04 25 00 00 00 00 00 10 00 00 00 00 00\n 00 00 00 00 00 00 00 00 00 00 00 38 42 49 4D 03\n ED 00 00 00 00 00 10 00 96 00 00 00 01 00 01 00\n 96 00 00 00 01 00 01 38 42 49 4D 04 26 00 00 00\n 00 00 0E 00 00 00 00 00 00 00 00 00 00 3F 80 00\n 00 38 42 49 4D 04 0D 00 00 00 00 00 04 00 00 00\n 1E 38 42 49 4D 04 19 00 00 00 00 00 04 00 00 00\n 1E 38 42 49 4D 03 F3 00 00 00 00 00 09 00 00 00\n 00 00 00 00 00 01 00 38 42 49 4D 04 0A 00 00 00\n 00 00 01 00 00 38 42 49 4D 27 10 00 00 00 00 00\n 0A 00 01 00 00 00 00 00 00 00 01 38 42 49 4D 03\n F5 00 00 00 00 00 48 00 2F 66 66 00 01 00 6C 66\n 66 00 06 00 00 00 00 00 01 00 2F 66 66 00 01 00\n A1 99 9A 00 06 00 00 00 00 00 01 00 32 00 00 00\n 01 00 5A 00 00 00 06 00 00 00 00 00 01 00 35 00\n 00 00 01 00 2D 00 00 00 06 00 00 00 00 00 01 38\n 42 49 4D 03 F8 00 00 00 00 00 70 00 00 FF FF FF\n FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF\n FF FF FF 03 E8 00 00 00 00 FF FF FF FF FF FF FF\n FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 03\n E8 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF\n FF FF FF FF FF FF FF FF FF FF FF 03 E8 00 00 00\n 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF\n FF FF FF FF FF FF FF 03 E8 00 00 38 42 49 4D 04\n 08 00 00 00 00 00 10 00 00 00 01 00 00 02 40 00\n 00 02 40 00 00 00 00 38 42 49 4D 04 1E 00 00 00\n 00 00 04 00 00 00 00 38 42 49 4D 04 1A 00 00 00\n 00 03 59 00 00 00 06 00 00 00 00 00 00 00 00 00\n 00 00 23 00 00 00 23 00 00 00 12 00 54 00 43 00\n 50 00 5F 00 43 00 69 00 72 00 63 00 6C 00 65 00\n 5F 00 42 00 61 00 6C 00 6C 00 61 00 73 00 74 00\n 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00\n 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00\n 00 00 23 00 00 00 23 00 00 00 00 00 00 00 00 00\n 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00\n 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 01\n 00 00 00 00 00 00 6E 75 6C 6C 00 00 00 02 00 00\n 00 06 62 6F 75 6E 64 73 4F 62 6A 63 00 00 00 01\n 00 00 00 00 00 00 52 63 74 31 00 00 00 04 00 00\n 00 00 54 6F 70 20 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 4C 65 66 74 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 42 74 6F 6D 6C 6F 6E 67 00 00 00 23 00 00\n 00 00 52 67 68 74 6C 6F 6E 67 00 00 00 23 00 00\n 00 06 73 6C 69 63 65 73 56 6C 4C 73 00 00 00 01\n 4F 62 6A 63 00 00 00 01 00 00 00 00 00 05 73 6C\n 69 63 65 00 00 00 12 00 00 00 07 73 6C 69 63 65\n 49 44 6C 6F 6E 67 00 00 00 00 00 00 00 07 67 72\n 6F 75 70 49 44 6C 6F 6E 67 00 00 00 00 00 00 00\n 06 6F 72 69 67 69 6E 65 6E 75 6D 00 00 00 0C 45\n 53 6C 69 63 65 4F 72 69 67 69 6E 00 00 00 0D 61\n 75 74 6F 47 65 6E 65 72 61 74 65 64 00 00 00 00\n 54 79 70 65 65 6E 75 6D 00 00 00 0A 45 53 6C 69\n 63 65 54 79 70 65 00 00 00 00 49 6D 67 20 00 00\n 00 06 62 6F 75 6E 64 73 4F 62 6A 63 00 00 00 01\n 00 00 00 00 00 00 52 63 74 31 00 00 00 04 00 00\n 00 00 54 6F 70 20 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 4C 65 66 74 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 42 74 6F 6D 6C 6F 6E 67 00 00 00 23 00 00\n 00 00 52 67 68 74 6C 6F 6E 67 00 00 00 23 00 00\n 00 03 75 72 6C 54 45 58 54 00 00 00 01 00 00 00\n 00 00 00 6E 75 6C 6C 54 45 58 54 00 00 00 01 00\n 00 00 00 00 00 4D 73 67 65 54 45 58 54 00 00 00\n 01 00 00 00 00 00 06 61 6C 74 54 61 67 54 45 58\n 54 00 00 00 01 00 00 00 00 00 0E 63 65 6C 6C 54\n 65 78 74 49 73 48 54 4D 4C 62 6F 6F 6C 01 00 00\n 00 08 63 65 6C 6C 54 65 78 74 54 45 58 54 00 00\n 00 01 00 00 00 00 00 09 68 6F 72 7A 41 6C 69 67\n 6E 65 6E 75 6D 00 00 00 0F 45 53 6C 69 63 65 48\n 6F 72 7A 41 6C 69 67 6E 00 00 00 07 64 65 66 61\n 75 6C 74 00 00 00 09 76 65 72 74 41 6C 69 67 6E\n 65 6E 75 6D 00 00 00 0F 45 53 6C 69 63 65 56 65\n 72 74 41 6C 69 67 6E 00 00 00 07 64 65 66 61 75\n 6C 74 00 00 00 0B 62 67 43 6F 6C 6F 72 54 79 70\n 65 65 6E 75 6D 00 00 00 11 45 53 6C 69 63 65 42\n 47 43 6F 6C 6F 72 54 79 70 65 00 00 00 00 4E 6F\n 6E 65 00 00 00 09 74 6F 70 4F 75 74 73 65 74 6C\n 6F 6E 67 00 00 00 00 00 00 00 0A 6C 65 66 74 4F\n 75 74 73 65 74 6C 6F 6E 67 00 00 00 00 00 00 00\n 0C 62 6F 74 74 6F 6D 4F 75 74 73 65 74 6C 6F 6E\n 67 00 00 00 00 00 00 00 0B 72 69 67 68 74 4F 75\n 74 73 65 74 6C 6F 6E 67 00 00 00 00 00 38 42 49\n 4D 04 11 00 00 00 00 00 01 01 00 38 42 49 4D 04\n 14 00 00 00 00 00 04 00 00 00 01 38 42 49 4D 04\n 0C 00 00 00 00 03 D5 00 00 00 01 00 00 00 23 00\n 00 00 23 00 00 00 6C 00 00 0E C4 00 00 03 B9 00\n 18 00 01 FF D8 FF E0 00 10 4A 46 49 46 00 01 02\n 01 00 48 00 48 00 00 FF ED 00 0C 41 64 6F 62 65\n 5F 43 4D 00 02 FF EE 00 0E 41 64 6F 62 65 00 64\n 80 00 00 00 01 FF DB 00 84 00 0C 08 08 08 09 08\n 0C 09 09 0C 11 0B 0A 0B 11 15 0F 0C 0C 0F 15 18\n 13 13 15 13 13 18 11 0C 0C 0C 0C 0C 0C 11 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 01 0D 0B 0B 0D 0E\n 0D 10 0E 0E 10 14 0E 0E 0E 14 14 0E 0E 0E 0E 14\n 11 0C 0C 0C 0C 0C 11 11 0C 0C 0C 0C 0C 0C 11 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C FF C0 00 11 08\n 00 23 00 23 03 01 22 00 02 11 01 03 11 01 FF DD\n 00 04 00 03 FF C4 01 3F 00 00 01 05 01 01 01 01\n 01 01 00 00 00 00 00 00 00 03 00 01 02 04 05 06\n 07 08 09 0A 0B 01 00 01 05 01 01 01 01 01 01 00\n 00 00 00 00 00 00 01 00 02 03 04 05 06 07 08 09\n 0A 0B 10 00 01 04 01 03 02 04 02 05 07 06 08 05\n 03 0C 33 01 00 02 11 03 04 21 12 31 05 41 51 61\n 13 22 71 81 32 06 14 91 A1 B1 42 23 24 15 52 C1\n 62 33 34 72 82 D1 43 07 25 92 53 F0 E1 F1 63 73\n 35 16 A2 B2 83 26 44 93 54 64 45 C2 A3 74 36 17\n D2 55 E2 65 F2 B3 84 C3 D3 75 E3 F3 46 27 94 A4\n 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56 66 76\n 86 96 A6 B6 C6 D6 E6 F6 37 47 57 67 77 87 97 A7\n B7 C7 D7 E7 F7 11 00 02 02 01 02 04 04 03 04 05\n 06 07 07 06 05 35 01 00 02 11 03 21 31 12 04 41\n 51 61 71 22 13 05 32 81 91 14 A1 B1 42 23 C1 52\n D1 F0 33 24 62 E1 72 82 92 43 53 15 63 73 34 F1\n 25 06 16 A2 B2 83 07 26 35 C2 D2 44 93 54 A3 17\n 64 45 55 36 74 65 E2 F2 B3 84 C3 D3 75 E3 F3 46\n 94 A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56\n 66 76 86 96 A6 B6 C6 D6 E6 F6 27 37 47 57 67 77\n 87 97 A7 B7 C7 FF DA 00 0C 03 01 00 02 11 03 11\n 00 3F 00 F5 54 0B 33 71 AB 79 AC BF 75 83 53 5B\n 01 7B 84 F1 B9 95 EE 73 54 F2 1C E6 D1 63 9B F4\n 9A C7 16 FC 40 5C F7 49 B7 1A FA 19 51 BF 23 1B\n 2C B4 3A EC 7B 2D 65 76 6E 23 DC FD 06 FB 58 FF\n 00 A4 CB 92 53 1E B9 F5 9B 3E 96 DB 8D 83 D3 B2\n 85 A7 DB 56 53 D8 1B 5C E9 EE 0F 7E E6 37 FE B8\n AF FD 5B FD AA 71 9E EE A2 CB 6A 26 36 D7 7B C5\n 8F 07 5D EE DE 27 F4 7F 43 E9 21 E5 D5 85 8D 59\n 39 B9 04 56 EE 45 D9 6F F7 79 7A 6D 1E FF 00 EA\n AB 9D 0A C3 67 4D AC 9A AC C7 01 CF 0C A6 D2 4B\n DA D0 E7 7A 61 FE A4 BF E8 7E FA 4A 74 12 49 24\n 94 FF 00 FF D0 F5 2B DA 5D 4D 8D 1C B9 A4 7D E1\n 66 F4 FB BA 7F 50 C3 C7 17 D4 CF 59 B5 33 F4 57\n 06 97 00 47 2D 9F CC 74 7D 26 2D 55 CC 7D 61 CD\n 7F 40 38 66 BA 99 76 16 4D CE AD EC B8 4B 69 2E\n 06 C6 7A 76 0F 73 37 D9 EC D8 EF EC 24 A7 61 95\n 74 7C 70 6F 6B 28 AF 61 FE 72 1B 20 8F DD 77 D2\n 44 E9 97 8C 8C 63 7B 5A E6 36 CB 2C 21 AE D1 D0\n 1E EA F5 1F D8 58 1F 57 FA 95 DD 6B 23 25 B5 D5\n 5E 23 31 F6 13 63 1A 1E F9 70 73 76 56 F7 7B 6A\n FE 6F 7F D0 FC F5 D3 63 D1 56 3D 2C A6 A6 ED AD\n 82 1A 12 52 44 92 49 25 3F FF D1 F5 55 47 AD C7\n EC AC AD DE 84 7A 6E 9F B5 4F A3 11 FE 1B 67 BF\n 67 F5 17 CC 69 24 A7 E9 6F AB BB 7F 66 55 B7 EC\n BB 60 47 D8 B7 7A 5C 7F C2 7E 93 FC F5 A8 BE 55\n 49 25 3F 55 24 BE 55 49 25 3F FF D9 00 38 42 49\n 4D 04 21 00 00 00 00 00 55 00 00 00 01 01 00 00\n 00 0F 00 41 00 64 00 6F 00 62 00 65 00 20 00 50\n 00 68 00 6F 00 74 00 6F 00 73 00 68 00 6F 00 70\n 00 00 00 13 00 41 00 64 00 6F 00 62 00 65 00 20\n 00 50 00 68 00 6F 00 74 00 6F 00 73 00 68 00 6F\n 00 70 00 20 00 37 00 2E 00 30 00 00 00 01 00 38\n 42 49 4D 04 06 00 00 00 00 00 07 00 08 01 01 00\n 01 01 00 FF E1 12 48 68 74 74 70 3A 2F 2F 6E 73\n 2E 61 64 6F 62 65 2E 63 6F 6D 2F 78 61 70 2F 31\n 2E 30 2F 00 3C 3F 78 70 61 63 6B 65 74 20 62 65\n 67 69 6E 3D 27 EF BB BF 27 20 69 64 3D 27 57 35\n 4D 30 4D 70 43 65 68 69 48 7A 72 65 53 7A 4E 54\n 63 7A 6B 63 39 64 27 3F 3E 0A 3C 3F 61 64 6F 62\n 65 2D 78 61 70 2D 66 69 6C 74 65 72 73 20 65 73\n 63 3D 22 43 52 22 3F 3E 0A 3C 78 3A 78 61 70 6D\n 65 74 61 20 78 6D 6C 6E 73 3A 78 3D 27 61 64 6F\n 62 65 3A 6E 73 3A 6D 65 74 61 2F 27 20 78 3A 78\n 61 70 74 6B 3D 27 58 4D 50 20 74 6F 6F 6C 6B 69\n 74 20 32 2E 38 2E 32 2D 33 33 2C 20 66 72 61 6D\n 65 77 6F 72 6B 20 31 2E 35 27 3E 0A 3C 72 64 66\n 3A 52 44 46 20 78 6D 6C 6E 73 3A 72 64 66 3D 27\n 68 74 74 70 3A 2F 2F 77 77 77 2E 77 33 2E 6F 72\n 67 2F 31 39 39 39 2F 30 32 2F 32 32 2D 72 64 66\n 2D 73 79 6E 74 61 78 2D 6E 73 23 27 20 78 6D 6C\n 6E 73 3A 69 58 3D 27 68 74 74 70 3A 2F 2F 6E 73\n 2E 61 64 6F 62 65 2E 63 6F 6D 2F 69 58 2F 31 2E\n 30 2F 27 3E 0A 0A 20 3C 72 64 66 3A 44 65 73 63\n 72 69 70 74 69 6F 6E 20 61 62 6F 75 74 3D 27 75\n 75 69 64 3A 34 37 38 34 61 35 39 66 2D 37 65 64\n 66 2D 31 31 64 64 2D 39 61 37 39 2D 61 31 62 66\n 63 38 33 61 61 63 63 36 27 0A 20 20 78 6D 6C 6E\n 73 3A 78 61 70 4D 4D 3D 27 68 74 74 70 3A 2F 2F\n 6E 73 2E 61 64 6F 62 65 2E 63 6F 6D 2F 78 61 70\n 2F 31 2E 30 2F 6D 6D 2F 27 3E 0A 20 20 3C 78 61\n 70 4D 4D 3A 44 6F 63 75 6D 65 6E 74 49 44 3E 61\n 64 6F 62 65 3A 64 6F 63 69 64 3A 70 68 6F 74 6F\n 73 68 6F 70 3A 34 37 38 34 61 35 39 64 2D 37 65\n 64 66 2D 31 31 64 64 2D 39 61 37 39 2D 61 31 62\n 66 63 38 33 61 61 63 63 36 3C 2F 78 61 70 4D 4D\n 3A 44 6F 63 75 6D 65 6E 74 49 44 3E 0A 20 3C 2F\n 72 64 66 3A 44 65 73 63 72 69 70 74 69 6F 6E 3E\n 0A 0A 3C 2F 72 64 66 3A 52 44 46 3E 0A 3C 2F 78\n 3A 78 61 70 6D 65 74 61 3E 0A 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 0A 3C 3F 78 70 61 63\n 6B 65 74 20 65 6E 64 3D 27 77 27 3F 3E FF EE 00\n 21 41 64 6F 62 65 00 64 40 00 00 00 01 03 00 10\n 03 02 03 06 00 00 00 00 00 00 00 00 00 00 00 00\n FF DB 00 84 00 01 01 01 01 01 01 01 01 01 01 01\n 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01\n 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01\n 02 02 02 02 02 02 02 02 02 02 02 03 03 03 03 03\n 03 03 03 03 03 01 01 01 01 01 01 01 01 01 01 01\n 02 02 01 02 02 03 03 03 03 03 03 03 03 03 03 03\n 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03\n 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03\n 03 03 03 03 03 03 FF C2 00 11 08 00 23 00 23 03\n )\n @image.__send__(\"process_jpg\", [data.join('')].pack('H*'))\n assert_equal(@type, @image.type)\n assert_equal(35, @image.width)\n assert_equal(35, @image.height)\n end",
"def optimized_image(image,x,y)\n return image.variant(resize_to_fill: [x,y]).processed\n end",
"def convert_standalone_image(el, _opts, img); end",
"def rawimage_to_gif(rawimage, width, height, palette, image_path)\n image = Image.new width, height\n draw = Draw.new\n ii = 0\n (0...height).each do |yy|\n (0...width).step(2).each do |xx|\n c0 = PixelColor.from_coco3(palette[(rawimage[ii].ord & 0xf0) >> 4])\n draw.fill(c0.to_s())\n draw.point(xx, yy)\n c1 = PixelColor.from_coco3(palette[rawimage[ii].ord & 0xf])\n draw.fill(c1.to_s())\n draw.point(xx + 1, yy)\n ii = ii + 1\n end\n end\n draw.draw image\n image.write image_path\nend",
"def show_image(buffer)\n # We need to squish 8 pixels (3 bytes each) into 2 images of 1 byte.\n # (i.e. a black-and-white image of 8 pixels needs to turn from \n # [[0xFF, 0xFF, 0xFF], [0x00, 0x00, 0x00], [0xFF, 0xFF, 0xFF], [0x00, 0x00, 0x00], [0xFF, 0xFF, 0xFF], [0x00, 0x00, 0x00], [0xFF, 0xFF, 0xFF], [0x00, 0x00, 0x00]]\n # to 0b10101010 (one bit per pixel, instead of 3 bytes). \n # Red pixels will be saved off as a separate image.\n black_image, red_image = [], []\n buffer.each_byte.each_slice(3).each_slice(8) do |chunk|\n black_image_chunk = 0\n red_image_chunk = 0\n # for each chunk of 8 pixels, construct a 8-bit number from each of the pixels.\n chunk.each_with_index do |pixel, i|\n # Write from left to right.\n index_to_write = 7 - i\n # if the pixel is white, write a 1 on the black image, and a 0 on the red image\n if pixel.all?(0xff)\n black_image_chunk |= 1 << index_to_write\n red_image_chunk |= 0 << index_to_write\n # if the pixel is black, write a 0 on the black image and the red image\n elsif pixel.all?(0x00)\n black_image_chunk |= 0 << index_to_write\n red_image_chunk |= 0 << index_to_write\n # any other color will be interpreted as red; write a 1 on the black image and the red image\n else\n black_image_chunk |= 1 << index_to_write\n red_image_chunk |= 1 << index_to_write\n end\n end\n black_image << black_image_chunk\n red_image << red_image_chunk\n end\n p \"Shoving #{black_image.length} bytes down the pipe\"\n show_image_buffer(black_image, red_image)\n end",
"def monochrome! \n\t\treturn @image = @image.quantize(2, Magick::GRAYColorspace) \n\tend",
"def clipart\n output = get_working_image(@session_id)\n unless File.exist?(output)\n FileUtils.cp(\"#{Rails.root}/public/#{params[:src]}\", output)\n img = Image.read(output).first\n img = img.scale(params[:rs].to_f) unless params[:rs].blank?\n img = img.level_colors(params[:b] || \"\", params[:w] || \"\", true) if params[:b] || params[:w]\n img.background_color = \"none\"\n img.rotate!(params[:r].to_f) unless params[:r].blank?\n\n #For embroidery\n if params[:emb] == 'true'\n img = img.ordered_dither\n end\n #FLIP/FLOP/Transpose/Transverse\n if params[:ff] == 'flip'\n img.flip!\n elsif params[:ff] == 'flop'\n img.flop!\n elsif params[:ff] == 'transpose'\n img.transpose!\n elsif params[:ff] == 'transverse'\n img.transverse!\n end\n #Extracts a channel\n if params[:ec] == 'R'\n img = img.channel(Magick::RedChannel)\n elsif params[:ec] == 'G'\n img = img.channel(Magick::GreenChannel)\n elsif params[:ec] == 'B'\n img = img.channel(Magick::BlueChannel)\n end\n\n #Applies a special effect to the image - QuantumRange\n img = img.sepiatone(Magick::QuantumRange * params[:qr].to_f) unless params[:qr].blank?\n\n #Vignette (Shape Edge)\n if params[:vig] == 'true'\n img = img.vignette\n end\n\n #Wet Floor\n if params[:wf]\n img = img.wet_floor\n end\n img.write(output)\n end\n img = Image.read(output).first\n send_data img.to_blob, :disposition => 'inline', :type => 'image/png'\n end",
"def convert_standalone_image(el, indent); end",
"def dump_colors( img )\n img.pixels.uniq.each_with_index do |color, i|\n print \"[#{i}] \"\n print Color.format( color )\n print \"\\n\"\n end\nend",
"def extract_cover\n puts 'Extract front cover'\n extract_png(1, 'cover')\n puts 'Extract back cover'\n extract_png(page_count, 'back')\n end",
"def extract_thumb(input, output, width, height)\n Image::Editing::ResizeToFill.new(input, output, width, height).run\n end",
"def test_has_transparent_foreground_on_bright_green_background\n Waveform.generate(fixture_asset(\"sample.wav\"), output(\"background_color-#00ff00+color-transparent.png\"), :background_color => \"#00ff00\", :color => :transparent)\n\n image = open_png(output(\"background_color-#00ff00+color-transparent.png\"))\n\n assert_equal ChunkyPNG::Color.from_hex(\"#00ff00\"), image[0, 0]\n assert_equal ChunkyPNG::Color::TRANSPARENT, image[60, 120]\n end",
"def putImage(theWidth, theHeight, theImage)\n\n\tputs \"Raw Image:\";\n\tputs theImage.join();\n\t\n\t\n\tputs \"\"\n\tputs \"Bitmap Image:\"\n\tn = 0;\n\n\t0.upto(theHeight - 1) do |y|\n\t\t0.upto(theWidth - 1) do |x|\n\t\t\tprint (theImage[n] == 1) ? '#' : ' ';\n\t\t\tn += 1;\n\t\tend\n\t\tputs \"\";\n\tend\n\nend",
"def spotimage\n\n if ! @commandline.argument('first').empty? && files = findfiles() then\n colorname = @commandline.option('colorname')\n colorspec = @commandline.option('colorspec')\n if colorname && ! colorname.empty? && colorspec && ! colorspec.empty? then\n files.each do |filename|\n s = SpotColorImage.new(self)\n s.registercolor(colorspec,colorname)\n s.convertgrayimage(filename)\n end\n else\n report(\"provide --colorname=somename --colorspec=c,m,y,k\")\n end\n else\n report(\"provide filename (png, jpg, pdf)\")\n end\n\n end",
"def to_image(filename = 'filename.png')\n png = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color::TRANSPARENT)\n height.times do |j|\n width.times do |i|\n png[i, j] = ChunkyPNG::Color.rgb(\n (red[i, j] * 255).to_i,\n (green[i, j] * 255).to_i,\n (blue[i, j] * 255).to_i\n )\n end\n end\n png.save(filename, :interlace => true)\n end",
"def pure_jpg\n Jhead.call(\"-purejpg\", @match, @pattern)\n end",
"def quality_and_strip(percentage)\n manipulate! do |img|\n img.format('jpg') # We want to enforce jpeg so we can use good compression.\n img.strip # Do not store EXIF data in the thumb to save space\n img.quality(percentage.to_s)\n img = yield(img) if block_given?\n img\n end\n end",
"def jpeg(*args)\n case @source.components\n when 2,4 then @source = AlphaStripper.new(@source)\n end\n JPEG.write(@source, *args)\n end",
"def do_colorize(image, hash)\n opc = hash[:opacity]\n i2 = image.colorize(opc, opc, opc, hash[:colorize])\n opcounter = hash[:opacity]\n while opcounter > 0.0\n #i2 = i2.darken(0.25)\n #i2 = i2.contrast(true)\n opcounter -= 0.15\n end\n i2 = i2.modulate 1.0, 1.0+(1.0-1.0*hash[:opacity]), 1.0\n return i2\n end",
"def to_pixel(**options) = convert_to('pixel', **options)",
"def obtain_main_image_colors\n pic = ImageList.new(@main_image.source)\n pic.resize!(0.20)\n #Reducing picture colors\n pic = pic.quantize(5, Magick::RGBColorspace, 0, 0, false) \n #By modulating them we get better colors\n pic = pic.modulate(1.2, 1.8, 1.0) #L S H\n #Background color will be the most used color in the picture\n color_pixels = pic.color_histogram\n \n max=0\n background_px = 0\n \n color_pixels.each do |k,v|\n if v >max\n max=v\n background_px = k\n end\n end \n \n @image_colors << Colour.new(background_px.red, background_px.green, background_px.blue) #image_colors[0] is the background\n \n color_pixels.each do |k,v|\n hsl = k.to_hsla\n if hsl[2]>=35 and hsl[2]<=75\n @image_colors << Colour.new(k.red, k.green, k.blue)\n end\n end\n \n puts '......'\n puts @image_colors[0].red\n puts @image_colors[0].green\n puts @image_colors[0].blue\n \n @image_colors[1] = @image_colors[1]==nil ? @image_colors[0] : @image_colors[1]\n @image_colors[2] = @image_colors[2]==nil ? @image_colors[0] : @image_colors[2]\n\n end",
"def to_tex\n q_url = \"http://dream.misasa.okayama-u.ac.jp/?q=\"\n basename = File.basename(image.name,\".*\")\n lines = []\n lines << \"\\\\begin{overpic}[width=0.49\\\\textwidth]{#{basename}}\"\n lines << \"\\\\put(1,74){\\\\colorbox{white}{(\\\\sublabel{#{basename}}) \\\\href{#{q_url}#{image.global_id}}{#{basename}}}}\"\n lines << \"%%(\\\\subref{#{basename}}) \\\\nolinkurl{#{basename}}\"\n lines << \"\\\\color{red}\"\n\n surface.surface_images.each do |osurface_image|\n oimage = osurface_image.image\n #image_region\n opixels = oimage.spots.map{|spot| [spot.spot_x, spot.spot_y]}\n worlds = oimage.pixel_pairs_on_world(opixels)\n pixels = image.world_pairs_on_pixel(worlds)\n oimage.spots.each_with_index do |spot, idx|\n length = image.length\n height = image.height\n x = \"%.1f\" % (pixels[idx][0] / length * 100)\n y = \"%.1f\" % (height.to_f / length * 100 - pixels[idx][1] / length * 100)\n line = \"\\\\put(#{x},#{y})\"\n line += \"{\\\\footnotesize \\\\circle{0.7} \\\\href{#{q_url}#{spot.target_uid}}{#{spot.name}}}\"\n line += \" % #{spot.target_uid}\" if spot.target_uid\n line += \" % \\\\vs(#{(\"%.1f\" % worlds[idx][0])}, #{(\"%.1f\" % worlds[idx][1])})\"\n lines << line\n end\n end\n\n width_on_stage = image.transform_length(image.width / image.length * 100)\n scale_length_on_stage = 10 ** (Math::log10(width_on_stage).round - 1)\n scale_length_on_image = image.transform_length(scale_length_on_stage, :world2xy).round\n lines << \"%%scale #{(\"%.0f\" % scale_length_on_stage)}\\ micro meter\"\n lines << \"\\\\put(1,1){\\\\line(1,0){#{(\"%.1f\" % scale_length_on_image)}}}\"\n\n lines << \"\\\\end{overpic}\"\n\n lines.join(\"\\n\")\n end",
"def make\n source = @file\n destination = Tempfile.new(@basename)\n\n Paperclip.run(\"convert\",\n \":source \" \\\n \"-quality 100 \" \\\n \"-bordercolor \\\"#000000\\\" \" \\\n \"-border 1x1 \" \\\n \"-fuzz 10% \" \\\n \"-trim +repage \" \\\n \":dest\",\n :source => File.expand_path(source.path),\n :dest => File.expand_path(destination.path)\n )\n\n destination\n end",
"def convert!(image, format, page = nil, &block)\n with_minimagick(image) do |img|\n img.format(format.downcase, page, &block)\n end\n end",
"def image_pixels(image_path)\n image = Magick::Image.from_blob(File.read(image_path)).first\n sx, sy = image.columns, image.rows\n \n grid = Array.new(sy) { Array.new }\n x, y = 0, 0\n image.each_pixel do |pixel|\n grid[y].concat [pixel.red, pixel.green, pixel.blue].map { |channel|\n ((255 * channel) / Magick::QuantumRange).to_i\n }\n x += 1\n if x == sx\n x = 0\n y += 1\n end\n end\n grid\nend",
"def optimize_for_pagespeed\n # according to https://developers.google.com/speed/docs/insights/OptimizeImages\n if self.file.content_type == 'image/jpeg'\n # convert orig.jpg -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG orig_converted.jpg\n manipulate! do |img|\n img.sampling_factor '4:2:0'\n img.strip\n img.quality 85\n img.interlace 'JPEG'\n img\n end\n else\n # convert cuppa.png -strip cuppa_converted.png\n manipulate! do |img|\n img.strip\n img\n end\n end\n end",
"def generate_image\n\t\tset_dimensions()\n\t\t\n\t\t# Create an image from scratch, save as an interlaced PNG.\n\t\tpng = ChunkyPNG::Image.new(@x_length, @y_length, ChunkyPNG::Color::TRANSPARENT)\n\n\t\t# Loop along the string array and write each char as a square.\n\t\ti_line = 0\n\t\t@input_text_array.each do |line|\n\n\t\t\t# Get the colour for the line.\n\t\t\tline_colour_r = @colour_r.next\n\t\t\tline_colour_g = @colour_g.next\n\t\t\tline_colour_b = @colour_b.next\n\n\t\t\t# Loop through each character, and alter the base line colour according\n\t\t\t# to the value of the cell.\n\t\t\ti_char = 0\n\t\t\tline.split('').each do |char|\n\t\t\t\t\n\t\t\t\t# The colour multiplier of the cell.\n\t\t\t\tmultiplier = CHARS.index(char).to_f / @highest_num\n\t\t\t\t\n\t\t\t\t# Wrap in a method using a begin/rescue block.\n\t\t\t\t# Fixes weird bug that I can't seem to replicate.\n\t\t\t\tdef try_colour(multiplier, line_colour)\n\t\t\t\t\tbegin\n\t\t\t\t\t\t(multiplier * line_colour).to_i\n\t\t\t\t\trescue\n\t\t\t\t\t\t255\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tcolour_r = try_colour(multiplier,line_colour_r)\n\t\t\t\tcolour_g = try_colour(multiplier,line_colour_g)\n\t\t\t\tcolour_b = try_colour(multiplier,line_colour_b)\n\t\t\t\t\n\t\t\t\t# Handle inversion of colours if necessary.\n\t\t\t\tif @colour_invert\n\t\t\t\t\tcolour_r = 255 - colour_r\n\t\t\t\t\tcolour_g = 255 - colour_g\n\t\t\t\t\tcolour_b = 255 - colour_b\n\t\t\t\tend\n\t\t\t\tcolour = ChunkyPNG::Color.rgba(colour_r, colour_g, colour_b, 255)\n\t\t\t\t\n\t\t\t\t# Draw each square.\n\t\t\t\tpng.rect(i_char, i_line,\n\t\t\t\t\ti_char+@pixel_size-1, i_line+@pixel_size-1,\n\t\t\t\t\tcolour, colour\n\t\t\t\t)\n\n\t\t\t\ti_char += @pixel_size\n\t\t\tend\n\t\t\ti_line += @pixel_size\n\t\tend\n\t\t\n\t\t# Add metadata if necessary.\n\t\tif @metadata\n\t\t\t@metadata.each do |key, value|\n\t\t\t\tpng.metadata[key.to_s] = value.to_s\n\t\t\tend\n\t\tend\n\n\t\t# Save to disk.\n\t\tpng.save(@image_file, :interlace => true)\n\tend",
"def show_image\n temp_floor_tile = Image.new('tiles\\tile_floor_1.png')\n hex_width = temp_floor_tile.width - 6\n hex_height = temp_floor_tile.width - 4\n temp_floor_tile.remove\n @hexArray.each_with_index do | line, x |\n bottom_y = hex_height * 11\n y_start = bottom_y - (11 - line.size) * (hex_height / 2)\n line.each_with_index do | hex, y |\n cur_x = x * hex_width\n cur_y = y_start - y * hex_height\n\n case hex.type\n when Hex::FLOOR_TYPE\n Image.new('tiles\\tile_floor_1.png', x:cur_x, y:cur_y)\n when Hex::LAVA_TYPE\n Image.new('tiles\\tile_liquid_1.png', x:cur_x, y:cur_y)\n when Hex::EXIT_TYPE\n Image.new('tiles\\tile_base.png', x:cur_x, y:cur_y)\n Image.new('tiles\\dung_ladderdown.png', x:cur_x, y:cur_y)\n else\n Image.new('tiles\\tile_base.png', x:cur_x, y:cur_y)\n end\n if hex.contained_object != nil && hex.contained_object.type == MovingObject::PLAYER_TYPE\n Image.new('tiles\\player.png', x:cur_x, y:cur_y)\n end\n end\n end\n end",
"def reformat(tifs, cfg)\n # do vis\n vis = File.basename(tifs['vis'], '.tif')\n command = \" #{cfg['awips_conversion']['vis_stretch']} #{vis}.tif #{vis}.stretched.tif\"\n puts(\"INFO: stretching #{command}\")\n shell_out!(command,clean_environment: true)\n command = \"gdalwarp #{cfg['awips_conversion']['warp_opts']} -te #{cfg['awips_conversion']['extents']} #{cfg['gdal']['co_opts']} -t_srs #{cfg['awips_conversion']['proj']} #{vis}.stretched.tif #{vis}.302.tif\"\n puts(\"INFO: warping to 302.. #{command}\")\n shell_out!(command,clean_environment: true)\n end",
"def process_images(dir)\n pattern = File.join(\"**\", dir, \"*.png\")\n files = Dir.glob(pattern)\n files.each do |f|\n unless f.include?(IMG_THUMB) || f.include?(IMG_FINAL)\n puts \"Converting image #{f}\"\n f2 = f.gsub /.png/, ''\n # thumbs\n system \"convert #{f} -resize #{IMG_THUMB_SIZE}^ -extent #{IMG_THUMB_SIZE} #{f2}#{IMG_THUMB}.png\" unless File.exists?(\"#{f2}#{IMG_THUMB}.png\")\n # final\n system \"convert #{f} -resize #{IMG_SIZE} #{f2}#{IMG_FINAL}.png\" unless File.exists?(\"#{f2}#{IMG_FINAL}.png\") \n end\n end\nend",
"def makeImage\n for i in 0...@width\n ti = 2.0*Math::PI*i/ImageWidth.to_f\n for j in 0...@height\n tj = 2.0*Math::PI*j/ImageHeight.to_f\n\n $image[3 * (@height * i + j)] = 127*(1.0 + Math::sin(ti))\n $image[3 * (@height * i + j) +1] = 127*(1.0 + Math::cos(2*tj))\n $image[3 * (@height * i + j) +2] = 127*(1.0 + Math::cos(ti+tj))\n end\n end\n end",
"def process_image(image_path, output_directory)\n parts = image_path.split(\"/\")\n filename = parts[parts.length - 1]\n image_small_path = output_directory + lowercase_filetype(filename)\n ratio = 0.125\n ratio = 0.071\n command = \"CoreImageTool load my_image #{image_path} \\\n filter my_image CILanczosScaleTransform scale=#{ratio} \\\n store my_image #{image_small_path} public.jpeg\"\n puts \"processing #{image_path} #{image_small_path}\"\n system(command) \n end",
"def blue_shift\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.blue_shift(2)\n img.write('public' + @photo.attachment_url)\n end",
"def image_magick(image)\n Open3.capture3(\n \"convert\", image.cached, # What to convert?\n \"-resize\", \"#{image.width}x#{image.height}^\", # resizing\n \"-gravity\", \"center\", \"-crop\", \"#{image.width}x#{image.height}+0+0\", # cropping\n \"-background\", \"#ffffff\", # background color in case image was transparent\n \"+repage\", \"-flatten\", # Discard canvas size and squash into single layer\n image.resized # Target path of output\n )\n end",
"def rgb(*args); end",
"def rgb(*args); end",
"def encode_png_image_with_interlacing(color_mode, compression = ZLib::DEFAULT_COMPRESSION)\n stream = \"\"\n 0.upto(6) do |pass|\n subcanvas = self.class.adam7_extract_pass(pass, self)\n subcanvas.encoding_palette = encoding_palette\n subcanvas.encode_png_image_pass_to_stream(stream, color_mode, compression)\n end\n stream\n end",
"def draw_and_save_image\n\t\tcolor = @avatar[:color]\n\t\tpng = ChunkyPNG::Image.new(250, 250, ChunkyPNG::Color::WHITE)\n\t\tcolor = ChunkyPNG::Color.rgba(color[:r], color[:g], color[:b], color[:alpha])\n\t\t@colorable_grid.each do |points|\n\t\t\tp1 = points[0]\n\t\t\tp2 = points[1]\n\t\t\tpng.rect(p1[0], p1[1], p2[0], p2[1] , color, color)\n\t\tend\n\t\tpng.save(File.join(Dir.pwd, \"/#{@term}.png\"), :interlace => true)\n\tend",
"def setup\n size 640, 360, P3D\n @img = load_image 'berlin-1.jpg'\n no_stroke\nend",
"def createAscii(options = {})\n if @status == true\n options = {\"width\" => 90, \"color\" => true}.merge(options)\n\t img = Magick::Image.from_blob(@data).first\n\t width = options[\"width\"]\n\t scale = (width.to_f / img.columns)\n\t \n\t height = ((img.rows * scale) / 2).to_i\n\t # puts height\n\t if height >= 100\n\t \theight = 80\n\t end\n\n\t border = \"+#{'-' * width}+\\n\"\n\t output = border.dup\n\n\t img.resize!(width, height)\n\t color_image = img.dup if options[\"color\"]\n\t img = img.quantize(@image_chars.length, Magick::GRAYColorspace).normalize\n\t quantum_calc = Magick::QuantumRange / (@image_chars.length - 1)\n\n\t \n\t img.view(0, 0, width, height) do |view|\n\t \n\t height.times do |i|\n\t \n\t output << '|'\n\t width.times do |j|\n\n\t character = @image_chars[view[i][j].red/quantum_calc] \n\n\t if options[\"color\"]\n\t pix = color_image.pixel_color(j,i)\n\t character = character.color(unified_rgb_value(pix.red), unified_rgb_value(pix.green), unified_rgb_value(pix.blue))\n\t end\n\n\t output << character\n\t end\n\n\t output << \"|\\n\"\n\t end\n\t end\n\n\n\t output << border\n\t return output\n end\n end",
"def create_banner_image(color)\n banner_file = \"theme/specktre_#{color}.png\"\n if ! File.file?(banner_file)\n\n puts(\"Building the banner file for #{color}\")\n\n red = (color.to_i(16) >> 16) % 256\n green = (color.to_i(16) >> 8) % 256\n blue = (color.to_i(16) % 256)\n\n start_color = (\n red * 0.9 * 65536 +\n green * 0.9 * 256 +\n blue * 0.9).to_i().to_s(16)\n end_color = (\n [red * 1.05, 255].min.to_i() * 65536 +\n [green * 1.05, 255].min.to_i() * 256 +\n [blue * 1.05, 255].min.to_i()).to_s(16)\n\n if !system(\"specktre new --size=3000x250 --start=#{start_color} --end=#{end_color} --squares --name=#{banner_file}\")\n raise RuntimeError, \"Error running the Specktre process for #{color}!\"\n end\n\n if !system(\"optipng #{banner_file}\")\n raise RuntimeError, \"Error running optipng on #{banner_file}\"\n end\n end\nend",
"def process_image(path)\n picture_name = File.basename(path)\n thumbnail_dir = File.join(File.dirname(path), \"thumbnails\")\n thumbnail_path = File.join(thumbnail_dir, \"#{File.basename(picture_name, File.extname(picture_name))}.jpg\")\n Dir.mkdir(thumbnail_dir) unless File.exist?(thumbnail_dir)\n\n image_optim = ImageOptim.new\n\n image = MiniMagick::Image.open(path)\n image_prop = {\n \"name\" => picture_name,\n \"thumb\" => \"thumbnails/#{picture_name}\",\n \"height\" => image.height,\n \"width\" => image.width\n }\n\n return image_prop if File.exist?(thumbnail_path)\n\n# -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB\n\n image.format \"jpeg\" unless File.extname(picture_name) == \"jpg\"\n image.combine_options do |b|\n b.resize \"#{MAX_DIMENSION}>\"\n b.sampling_factor \"4:2:0\"\n b.strip\n b.interlace \"JPEG\"\n b.colorspace \"RGB\"\n b.quality 85\n end\n image.write thumbnail_path\n\n image_optim.optimize_image!(path)\n image_optim.optimize_image!(thumbnail_path)\n\n image_prop\nend",
"def draw_image(data, row_number, digit)\n size = 28\n png = ChunkyPNG::Image.new(size, size, ChunkyPNG::Color::WHITE)\n data.each_with_index do |value, index|\n png[index % size, index / size] = ChunkyPNG::Color.rgb(255 - value.to_i, 255 - value.to_i, 255 - value.to_i)\n end\n png.save(\"images/#{digit}/digit_row_#{row_number}.png\", interlace: true)\nend",
"def generate_png\n command = \"python #{Rails.root}/lib/webkit2png --transparent -F -o #{id} -D #{Rails.root}/tmp #{url} \"\n system command\n return \"#{Rails.root}/tmp/#{id}-full.png\"\n end",
"def make_bg(bg_size = nil)\n begin\n img = Magick::Image.from_blob(resize_thumb(bg_size))[0]\n img.quantize.colorize(COLORIZE_LEVEL, COLORIZE_LEVEL, COLORIZE_LEVEL, '#d2f0ff').to_blob\n ensure\n GC.start\n end\n end",
"def test_refute_png_diff_with_1_percent_difference\n refute_png_diff(comparison_png(0), comparison_png(1), @black_white_distance * 0.01)\n end",
"def create_image(width, height, background = ChunkyPNG::Color::TRANSPARENT)\n\tpng = ChunkyPNG::Image.new(width, height, background)\nend",
"def test_hue_change_1\n b0 = Bitmap.new(\"#@@imgdir/random_rgba_40x32_a.png\")\n b0.hue_change(100)\n assert_bitmap_equal2(\"test_hue_change_1\", b0)\n end",
"def convert_frames\n MiniMagick.configure do |config|\n config.validate_on_create = false\n end\n\n Dir[\"#{templates_path}/**/*.psd\"].each do |psd|\n resulting_path = psd.gsub('.psd', '.png')\n next if File.exist?(resulting_path)\n\n UI.important \"Converting PSD file '#{psd}'\"\n image = MiniMagick::Image.open(psd)\n\n if psd =~ /iPhone-SE/\n UI.success \"Removing white background 🚫 ⬜️\"\n\n # The iPhone-SE screenshots from April 2016 have\n # 3 layers, a background, a product, and the 'put your image here' layer\n # imagemagick seems to add an additional layer with no label which this the\n # composite of all three. We want to remove the background and composite layer\n good_layers = image.layers.reject do |layer|\n label = layer.details['Properties']['label']\n label.to_s.length == 0 || label =~ /White B/i\n end\n product_layer = good_layers.shift\n\n good_layers.each do |layer|\n product_layer.layers << layer\n end\n\n image = product_layer\n end\n\n if image\n image.format 'png'\n image.trim\n\n image.write(resulting_path)\n else\n UI.error \"Could not parse PSD file at path '#{psd}'\"\n end\n end\n end",
"def transparent_pixels?(path)\n output = `identify -format '%[opaque]' #{Shellwords.escape(path)}`.downcase\n\n case output\n when 'true' # the image is all opaque pixels => no transparent\n false\n when 'false' # the image is not all opaque pixels => some transparent\n true\n else\n raise \"Unexpected output from identify: #{output.inspect}\"\n end\nend",
"def readText(qxd = 915, qyd = 76, axd = 388, ayd = 42, qx0 = 335, qy0 = 659, aAx0 = 366, aAy0 = 765, aDx0 = 913, aDy0 = 840) #for default measurements to function correctly, left edge of game screen should be around 190 pixels in.\n\t#r = rand(100000).to_s\n\t#system('screencapture /Users/rorycampbell/Documents/smallfrybeta/screenshot' + r + '.jpg')\n\t#img = Magick::Image.read('screenshot' + r + '.jpg').first\n\timg = Magick::Image.read('screenshotPNI.jpg').first\n\tquestion = img.crop(qx0, qy0, qxd, qyd, true).bilevel_channel(17000)\n\tanswerA = img.crop(aAx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerB = img.crop(aDx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerC = img.crop(aAx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerD = img.crop(aDx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\n\n\tquestion.write('question.jpg')\n\tanswerA.write('answerA.jpg')\n\tanswerB.write('answerB.jpg')\n\tanswerC.write('answerC.jpg')\n\tanswerD.write('answerD.jpg')\n\n\te = Tesseract::Engine.new {|e|\n\t e.language = :eng\n\t e.blacklist = '|_'\n\t}\n\n\tq = e.text_for('question.jpg').strip.gsub(/\\n/,\" \")\n\taA = e.text_for('answerA.jpg').strip \n\taB = e.text_for('answerB.jpg').strip \n\taC = e.text_for('answerC.jpg').strip \n\taD = e.text_for('answerD.jpg').strip\n\n\tqAndA = []\n\tqAndA << q << aA << aB << aC << aD\n\tqAndA.each do |text|\n\t\ttext.gsub!(')’','y')\n\tend\n\n\treturn qAndA \nend",
"def with_crop(left, top, right, bottom); end",
"def process_image(src, dest, maxw, maxh)\n i = QuickMagick::Image.read(src).first\n # AMF - added quality setting to limit size of images (some sites had high quality jpeg, so files sizes were still big)\n i.quality = 75\n w, h = i.width, i.height\n extra = (w - h/(maxh.to_f/maxw.to_f)).to_i\n if extra > 0\n i.shave(\"#{extra>>1}x0\") if i.width > i.height\n w -= extra\n end\n if w > maxw or h > maxh\n i.resize(\"#{maxw}x#{maxh}\")\n end\n i.save(dest)\n end",
"def do_overlay_image(image, hash)\n #puts \"get image\"\n #puts \"#{hash.inspect}\"\n #puts \"Image: #{hash[:image_path]}\"\n #puts \"File exists? #{File.exists?(hash[:image_path])}\"\n overlay_i = Magick::ImageList.new(hash[:image_path]).first\n #puts \"Do we want to colorize?\"\n if hash.has_key? :colorize\n \n #opc = hash[:opacity]\n overlay_i = do_colorize(overlay_i, hash.merge({:opacity=>0.5})) #overlay_i.colorize(opc, opc, opc, hash[:colorize])\n end\n return image.composite(overlay_i, 0, image.rows-overlay_i.rows, Magick::OverCompositeOp)\n end",
"def convert_image\n i = 0 \n main = [small\t=\t[\"jpg\",\"small\",240,160], \n\t medium\t=\t[\"jpg\",\"medium\",640,427], \n\t large\t=\t[\"jpg\",\"large\",1024,683]]\n while i < main.count\n # Runs the resize function with params to each size\n resize_image(main[i])\n i +=1\n end\n end",
"def logo\nsystem 'cls'\ngets.chomp\n\nrequire 'colorize'\nputs (\"\"\"\n ____ ___ ____ __ __ _ ______ _ __ __\n / __ \\\\/ | / __ \\\\/ //_/ / | / / __ \\\\ | / / / /\n / /_/ / /| | / /_/ / , < / |/ / / / / | /| / / / /\n / ____/ ___ |/ _, _/ /| | / /| / /_/ /| |/ |/ / /_/\n /_/ /_/ |_/_/ |_/_/ |_| /_/ |_/\\\\____/ |__/|__/ (_)\n\"\"\").colorize(:green)\n\nputs (\"\"\"\n\n ▄████████████▄\n ▄██▓▓▓▓▓▓████▓▓▓▓▓▓▓▓▄\n ▄██▓▓▓▓▓▓▓▓████▓▓▓▓▓▓▓▓▓▓▄\n ▄▀███▓▓▓▓▓▓▓▓▓▓████▓▓▓▓▓▓▓▓▓▓▓████████████▄\n ▄▀█████████████████ ███████████████████████▓▓\n ██████▀ ▄██▄ ▀█████ ███████████▀ ▄██▄ ▀████▓▓\n █████ ██████ █████ ███████████ ██████ ███\n ▀▀▀ ▀██▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀██▀ ▀▀\n\n\"\"\").colorize(:black)\n puts (\"\"\"\n ╔══════════╗ ╔══════════╗ ╔══════════╗ ╔══════════╗\n ║ Preview ║ ║ Register ║ ║ Log in ║ ║ Tour ║\n ╚══════════╝ ╚══════════╝ ╚══════════╝ ╚══════════╝\n \"\"\").colorize(:red)\nend",
"def toaster_filter\n manipulate! do |img|\n img.modulate '150,80,100'\n img.gamma 1.1\n img.contrast\n img.contrast\n img.contrast\n img.contrast\n img = yield(img) if block_given?\n img\n end\n end",
"def single_image\n page_number = 1\n\n input_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.jpg\"\n image = Magick::Image.read(input_image_path)[0]\n json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n json_text = File.read(json_path)\n json = JSON.parse(json_text)\n\n bounding_box = json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n draw = Magick::Draw.new\n\n # For drawing boxes around all words.\n # text_annotations = json[\"responses\"].first[\"textAnnotations\"][1..-1]\n # text_annotations.each do |text_annotation|\n # bounding_box = text_annotation[\"boundingPoly\"]\n # vertices = bounding_box[\"vertices\"]\n\n # p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n # p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n # p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n # p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n # draw.line(p1[0],p1[1], p2[0], p2[1])\n # draw.line(p1[0],p1[1], p3[0], p3[1])\n # draw.line(p2[0],p2[1], p4[0], p4[1])\n # draw.line(p3[0],p3[1], p4[0], p4[1])\n # end\n\n # For drawing colored boxes around all symbols\n\n confidence_symbols_to_colors = {\n very_confidence: '#BED1D8',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n pages = json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbol_total = symbols.count\n symbols.each.with_index do |symbol, index|\n puts \"Processing symbol #{index} of #{symbol_count}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence_number = (symbol['confidence'] * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n\n draw.stroke(color)\n draw.stroke_width(5)\n\n p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n draw.line(p1[0],p1[1], p2[0], p2[1])\n draw.line(p1[0],p1[1], p3[0], p3[1])\n draw.line(p2[0],p2[1], p4[0], p4[1])\n draw.line(p3[0],p3[1], p4[0], p4[1])\n\n draw.draw(image)\n end\n output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.5px.symbols.jpg\"\n image.write(output_image_path)\nend",
"def resizePngs\n destination=\"./Convert/\"\n search_for=[\"*.png\"]\n \n @files=readDirectoryFiles(destination,search_for)\n @viewport=Viewport.new(0,0,Graphics.width,Graphics.height)\n @viewport.z=999999\n \n @bar=Sprite.new(@viewport)\n @bar.bitmap=Bitmap.new(Graphics.width,34)\n pbSetSystemFont(@bar.bitmap)\n \n for i in 0...@files.length\n @files[i]=@files[i].gsub(/.png/) {\"\"}\n end\n \n return false if !Kernel.pbConfirmMessage(_INTL(\"There is a total of #{@files.length} PNG(s) available for conversion. Would you like to begin the process?\"))\n for i in 0...@files.length\n file=@files[i]\n \n width=((i*1.000)/@files.length)*Graphics.width\n @bar.bitmap.clear\n @bar.bitmap.fill_rect(0,0,Graphics.width,34,Color.new(255,255,255))\n @bar.bitmap.fill_rect(0,0,Graphics.width,32,Color.new(0,0,0))\n @bar.bitmap.fill_rect(0,0,width,32,Color.new(25*4,90*2,25*4))\n text=[[\"#{i}/#{@files.length}\",Graphics.width/2,2,2,Color.new(255,255,255),nil]]\n pbDrawTextPositions(@bar.bitmap,text)\n \n next if RTP.exists?(\"#{destination}New/#{file}.png\")\n \n sprite=pbBitmap(\"#{destination}#{file}.png\")\n width=sprite.width\n height=sprite.height\n \n bitmap=Bitmap.new(width/2,height/2)\n bitmap.stretch_blt(Rect.new(0,0,width/2,height/2),sprite,Rect.new(0,0,width,height))\n bitmap.saveToPng(\"#{destination}New/#{file}.png\")\n sprite.dispose\n pbWait(1)\n RPG::Cache.clear\n end\n @bar.dispose\n @viewport.dispose\n Kernel.pbMessage(_INTL(\"Done!\"))\nend",
"def test_load_save_load_valid_png_files_as_bmp\n\n each_file_with_updated_info do\n |file_path|\n\n #Valid color image with bit depth less than 16 and no transparency\n if @test_feature != \"x\" && @bit_depth != 16 && @test_feature != \"t\" &&\n (@color_type_desc == \"c\" || @color_type_desc == \"p\")\n\n img = Imgrb::Image.new(file_path)\n orig_rows = img.rows\n\n bmp_io = StringIO.new\n bmp_io.set_encoding(Encoding::BINARY)\n img.save_to_file(bmp_io, :bmp)\n bmp_str = bmp_io.string\n\n img_resaved = Imgrb::Image.new(bmp_str, :from_string)\n resaved_rows = img_resaved.rows\n\n assert orig_rows == resaved_rows, \"Resaved image does not give same pixel data as original for image located at: #{file_path}\"\n\n end\n\n end\n\n\n end",
"def composing\n background = Image.read('test.png').first\n avatar = Image.read('499317.jpeg').first\n\n avatar_resized = avatar.resize_to_fit(40,40)\n avatar_resized.border!(1, 1, 'black')\n avatar_resized.shadow(2, 5, 3)\n\n marketing_image = background.composite(avatar_resized, 30, 58, OverCompositeOp)\n\n text = \"耀你的命 show me your lives!\"\n\n content = Magick::Draw.new\n content.annotate(marketing_image, 0, 0, 60, 550, text) do\n self.font = './ZuiYouTi-2.ttf'\n self.pointsize = 24\n self.font_weight = Magick::BoldWeight\n self.fill = 'black'\n self.gravity = Magick::SouthEastGravity\n end\n\n\n marketing_image.write(\"marketing_image.png\")\nend",
"def setup\n size 640, 360\n @image = load_image \"test.jpg\"\n @image_mask = load_image \"mask.jpg\"\n @image.mask @image_mask\nend",
"def test055()\n begin\n theCommands = CommandModule::SmigCommands.new\n theSize = MIShapes.make_size(4, 1)\n bitmapObject = theCommands.make_createbitmapcontext(\n size: theSize,\n addtocleanup: true,\n preset: \"AlphaPreMulFirstRGB8bpcInt\")\n fillRect = MIDrawElement.new(:fillrectangle)\n fillRect.rectangle = MIShapes.make_rectangle(size: theSize)\n fillRect.fillcolor = MIColor.make_rgbacolor(1,0,0)\n\n drawCommand = CommandModule.make_drawelement(bitmapObject,\n drawinstructions: fillRect)\n theCommands.add_command(drawCommand)\n pixelDataRect = MIShapes.make_rectangle(xloc: 0, yloc: 0,\n width: 1, height: 1)\n getPixelDataCommand = CommandModule.make_getpixeldata(\n bitmapObject,\n rectangle: pixelDataRect)\n theCommands.add_command(getPixelDataCommand)\n theResult = Smig.perform_commands(theCommands)\n previousResult = '{\"pixeldata\":[[0,0,255,255,0,0]],\"contextinfo\":{\"alphainfo\":16386,\"bitspercomponent\":8,\"colorspace\":\"kCGColorSpaceSRGB\",\"bitsperpixel\":32},\"columnnames\":[\"x\",\"y\",\"Alpha\",\"Red\",\"Green\",\"Blue\"]}'\n if theResult != previousResult\n puts theResult\n raise \"Pixel data has changed.\"\n end\n \n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: #{Smig.exitstring}\"\n end\n puts e.message\n puts e.backtrace.to_s\n puts #{Smig.exitstring}\"\n ensure\n end\nend",
"def encode_png_image_with_interlacing(color_mode, bit_depth = 8, filtering = ChunkyPNG::FILTER_NONE)\n stream = \"\".b\n 0.upto(6) do |pass|\n subcanvas = self.class.adam7_extract_pass(pass, self)\n subcanvas.encoding_palette = encoding_palette\n subcanvas.encode_png_image_pass_to_stream(stream, color_mode, bit_depth, filtering)\n end\n stream\n end",
"def rgb_code(red, green, blue, background = T.unsafe(nil)); end",
"def rgb_code(red, green, blue, background = T.unsafe(nil)); end",
"def scan_for_colors; end",
"def optimize_cover(coverpath)\n puts 'Optimizing cover'\n `mogrify -resize 610 #{coverpath.shellescape}`\n `jpegoptim -m80 --strip-all #{coverpath.shellescape}`\n end",
"def process_image_black_and_white\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n size = OpenCV::Cv::Size.new(5,5)\n OpenCV::Cv::GaussianBlur(image, image, size, 0)\n OpenCV::Cv::adaptive_threshold(image, image, 251, OpenCV::CV_ADAPTIVE_THRESH_GAUSSIAN_C, OpenCV::CV_THRESH_BINARY, 19, 11)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_black_and_white = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_black_and_white\n end",
"def rgb(r, g, b)\n \"%.2X%.2X%.2X\" % [r,g,b].map{|i| [[i,255].min,0].max}\nend",
"def import_pixels(blob, columns, rows, depth, map, format = T.unsafe(nil)); end"
] |
[
"0.6789784",
"0.6426912",
"0.6267639",
"0.6188794",
"0.6138022",
"0.6126526",
"0.60962427",
"0.60889447",
"0.6058799",
"0.6045048",
"0.59996927",
"0.5942661",
"0.5926982",
"0.5922603",
"0.5901185",
"0.58667105",
"0.5866098",
"0.58300483",
"0.5829824",
"0.58087254",
"0.58045065",
"0.57958287",
"0.5783184",
"0.577454",
"0.5761142",
"0.57508427",
"0.5732213",
"0.571651",
"0.56647867",
"0.5655907",
"0.5651612",
"0.56462485",
"0.56215566",
"0.56214255",
"0.56201494",
"0.56059486",
"0.55783916",
"0.55682373",
"0.5567844",
"0.5564392",
"0.556373",
"0.55582905",
"0.55515563",
"0.5544422",
"0.5519217",
"0.5515623",
"0.5493746",
"0.54895985",
"0.5482586",
"0.5444658",
"0.5440901",
"0.5427726",
"0.54254305",
"0.5421332",
"0.54210466",
"0.5414521",
"0.5401909",
"0.5387047",
"0.5387011",
"0.538522",
"0.53733176",
"0.5372781",
"0.53400487",
"0.5337625",
"0.53209114",
"0.53209114",
"0.53168887",
"0.531634",
"0.53144974",
"0.5307325",
"0.53046304",
"0.5303238",
"0.5301852",
"0.52906793",
"0.5271153",
"0.5262635",
"0.5259335",
"0.52536744",
"0.52535015",
"0.5247354",
"0.523324",
"0.52298534",
"0.5220895",
"0.5219747",
"0.52118796",
"0.520837",
"0.52053964",
"0.5198804",
"0.5189644",
"0.5187606",
"0.5183072",
"0.5180724",
"0.517813",
"0.51744",
"0.51740044",
"0.51740044",
"0.5173657",
"0.51502544",
"0.5147697",
"0.5147075",
"0.5142679"
] |
0.0
|
-1
|
This algorithm ported directly from shotwell.
|
def do_redeye(eye,pixbuf)
#
# we remove redeye within a circular region called the "effect
#extent." the effect extent is inscribed within its "bounding
#rectangle." */
# /* for each scanline in the top half-circle of the effect extent,
# compute the number of pixels by which the effect extent is inset
#from the edges of its bounding rectangle. note that we only have
#to do this for the first quadrant because the second quadrant's
#insets can be derived by symmetry */
r = eye.radius
x_insets_first_quadrant = Array.new(eye.radius + 1)
i = 0
r.step(0,-1) do |y|
theta = Math.asin(y.to_f / r)
x = (r.to_f * Math.cos(theta) + 0.5).to_i
x_insets_first_quadrant[i] = eye.radius - x
i = i + 1
end
x_bounds_min = eye.x - eye.radius
x_bounds_max = eye.x + eye.radius
ymin = eye.y - eye.radius
ymin = (ymin < 0) ? 0 : ymin
ymax = eye.y
ymax = (ymax > (pixbuf.height - 1)) ? (pixbuf.height - 1) : ymax
#/* iterate over all the pixels in the top half-circle of the effect
#extent from top to bottom */
inset_index = 0
ymin.upto(ymax) do |y_it|
xmin = x_bounds_min + x_insets_first_quadrant[inset_index]
xmin = (xmin < 0) ? 0 : xmin
xmax = x_bounds_max - x_insets_first_quadrant[inset_index]
xmax = (xmax > (pixbuf.width - 1)) ? (pixbuf.width - 1) : xmax
xmin.upto(xmax) { |x_it| red_reduce_pixel(pixbuf,x_it, y_it) }
inset_index += 1
end
#/* iterate over all the pixels in the bottom half-circle of the effect
#extent from top to bottom */
ymin = eye.y
ymax = eye.y + eye.radius
inset_index = x_insets_first_quadrant.length - 1
ymin.upto(ymax) do |y_it|
xmin = x_bounds_min + x_insets_first_quadrant[inset_index]
xmin = (xmin < 0) ? 0 : xmin
xmax = x_bounds_max - x_insets_first_quadrant[inset_index]
xmax = (xmax > (pixbuf.width - 1)) ? (pixbuf.width - 1) : xmax
xmin.upto(xmax) { |x_it| red_reduce_pixel(pixbuf,x_it, y_it) }
inset_index -= 1
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def alg; end",
"def find_pair\n before = self.entropy\n reduce_pair_line\n reduce_pair_col\n reduce_pair_grid\n reduce_solved if before > self.entropy\n self\n end",
"def algorithms; end",
"def algorithms; end",
"def algorithms; end",
"def algorithms; end",
"def algorithms; end",
"def hiv_protease(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[23] = ['L',['I']]\n sdrm[24] = ['L',['I']]\n sdrm[30] = ['D',['N']]\n sdrm[32] = ['V',['I']]\n sdrm[46] = ['M',['I','L','V']]\n sdrm[47] = ['I',['V','A']]\n sdrm[48] = ['G',['V','M']]\n sdrm[50] = ['I',['V','L']]\n sdrm[53] = ['F',['L']]\n sdrm[54] = ['I',['V','L','M','T','A','S']]\n sdrm[73] = ['G',['S','T','C','A']]\n sdrm[76] = ['L',['V']]\n sdrm[82] = ['V',['A','T','S','F','L','C','M']]\n sdrm[83] = ['N',['D']]\n sdrm[84] = ['I',['V','A','C']]\n sdrm[85] = ['I',['V']]\n sdrm[88] = ['N',['D','S']]\n sdrm[90] = ['L',['M']]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n end\n end\n return out_hash\nend",
"def genome(liszt)\n=begin\n[samopen] SAM header is present: 2 sequences\n7621912 reads; of these:\n 4009241 (52.60%) were paired; of these:\n 1983557 (49.47%) aligned concordantly 0 times\n 1818685 (45.36%) aligned concordantly exactly 1 time\n 206999 (5.16%) aligned concordantly >1 times\n ----\n 1983557 pairs aligned concordantly 0 times; of these:\n 409503 (20.64%) aligned discordantly 1 time\n ----\n 1574054 pairs aligned 0 times concordantly or discordantly; of these:\n 3148108 mates make up the pairs; of these:\n 1009275 (32.06%) aligned 0 times\n 35392 (1.12%) aligned exactly 1 time\n 2103441 (66.82%) aligned >1 times\n 3612671 (47.40%) were unpaired; of these:\n 498719 (13.80%) aligned 0 times\n 2246121 (62.17%) aligned exactly 1 time\n 867831 (24.02%) aligned >1 times\n=end\n #puts(liszt);exit\n dict={}; liszt.shift\n dict[\"total\"]=liszt.shift.split[0]; #liszt.shift\n dict[\"paired\"]=liszt.shift.split[0]; liszt.shift #conc 0\n dict[\"conc_once\"]=liszt.shift.split[0]\n dict[\"conc_mult\"]=liszt.shift.split[0]\n liszt.shift(2); dict[\"disc_once\"]=\"\"; dict[\"disc_mult\"]=\"\"\n line=liszt.shift\n line.include?(\">1 times\") ? dict[\"disc_mult\"]=line.split[0] : dict[\"disc_once\"]=line.split[0]\n liszt.shift\n dict[\"unaligned_pairs\"]=liszt.shift.split[0]\n liszt.shift\n dict[\"unmates\"]=liszt.shift.split[0] #unaligned mates\n dict[\"mate_once\"]=liszt.shift.split[0]\n dict[\"mate_mult\"]=liszt.shift.split[0]\n dict[\"unpaired\"]=liszt.shift.split[0]\n dict[\"unpair_unaligned\"]=liszt.shift.split[0]\n dict[\"unpair_once\"]=liszt.shift.split[0]\n dict[\"unpair_mult\"]=liszt.shift.split[0]\n dict\nend",
"def sdrm_int(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[66] = ['T',['A','I','K']]\n # sdrm[68] = ['L',['V']] not included any more\n sdrm[74] = ['L',['M']]\n sdrm[92] = ['E',['Q']]\n sdrm[95] = ['Q',['K']]\n sdrm[97] = ['T',['A']]\n sdrm[121] = ['F',['Y']]\n sdrm[140] = ['G',['A','S','C']]\n sdrm[143] = [\"Y\",[\"C\",\"H\",\"R\"]]\n sdrm[147] = ['S',['G']]\n sdrm[148] = ['Q',['H','K','R']]\n sdrm[155] = ['N',['S','H']]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n\n end\n end\n return out_hash\nend",
"def gettrys(tcoords)\n # Indexa coordenadas de las lineas con menor incognitas\n p \"hmiss............\"\n p tcoords[:hmiss]\n hlower_c = lowerabsent(tcoords[:hmiss]) # [{:hindex=>x, :coords=> [[]]\n vlower_c = lowerabsent(tcoords[:vmiss],\"v\") # [{:vindex=>x, :coords=>[[]]\n slower_c = lowerabsent(tcoords[:smiss],\"s\") # [{:sindex=>x, :coords=>[[]]\n\n # combierte las coordenadas en numeros -> contiene menor incognitas\n hlower_n = hlower_c.collect {|line| missto_n(line[:hindex])} # [{:hindex=>0, :numbers=>[3, 4]}, x]\n vlower_n = vlower_c.collect {|line| missto_n(line[:vindex],tcoords[:vwhole], \"v\")} # [{:vindex=>0, :numbers=>[3, 4]}, x]\n #slower_n = slower_c.collect {|line| missto_n(line[:sindex], tcoords[:swhole], \"s\")} # [{:sindex=>2, :numbers=>[4, 6, 8]}, x]\n p \"****** H vs V *******\"\n p hlower_c.length < vlower_c.length ? \"h < v\" : \"h > v\"\n # cantidad de incognitas decide si se usa h o v\n p lower_c = hlower_c.length < vlower_c.length ? hlower_c : vlower_c\n lower_n = lower_c[0].keys[0][0] == \"h\" ? hlower_n : vlower_n\n # le pone cuadro a cada coord y separa coordenadas, una por linea\n hvindex_sindex_coords = locatecoord_onsquere(lower_c, tcoords[:swhole])\n sqr_n = hvindex_sindex_coords.collect {|item| missto_n(item[:sindex], tcoords[:swhole],\"s\")}\n # buscar que sqr tiene menos coincidencias\n hvindex_sindex_coords.collect { |main|\n main[:sqr_options] = sqr_n.collect {|numbers| numbers[:numbers] if main[:sindex] == numbers[:sindex] }.compact.flatten\n main[:options] = lower_n.collect {|numbers| numbers[:numbers] if main[main.keys[0]] == numbers[numbers.keys[0]] }.compact.flatten\n main[:reduce] = main[:options] - ([1,2,3,4,5,6,7,8,9] - main[:sqr_options])\n\n }\n # numbers[:numbers] if main[main.keys[0]] == numbers[numbers.keys[0]]\n result = hvindex_sindex_coords.group_by {|g| g[:reduce].length}\n\n p \"*******start Result\"\n reduce_index = result.collect {|x,y| x }.min\n result[reduce_index].map {|e| p e} # inspect\n result[reduce_index].map do |item|\n\n case item.keys[0][0]\n when \"h\"\n if item[:reduce].length == 1\n x = item[:coord][0]\n y = item[:coord][1]\n @tbls[:notformated][x][y] = item[:reduce][0]\n @tbls[:formated][x][y] = formato(@tbls[:notformated][x][y].to_s,:red, :yellow)\n elsif item[:reduce].length > 1\n # Pregunta en linea vertical\n end\n when \"v\"\n p \"################## - caso vertical pendiente - ###################\"; exit\n end\n\n end\n\n end",
"def outsense_edist(u, v)\n\n # initialize m and n\n m = u.length\n n = v.length\n\n # create hash of arrays where \n # hash.key holds h and array index holds d\n # thus hash[h][d] = front(h, d) = i\n front = Hash.new(Array.new)\n \n # initialize d with 0 for the first front\n d = 0\n\n # calculate front(0, 0)\n front[0][d] = lcplen(u, v, m, n)\n \n # till front(n - n, d) = m\n while front[n-m][d] != m-1\n\n # increase d\n d += 1\n \n # fronts calculated according to script\n ((-d)..d).each do |h|\n front[h][d] = outsense_next_front(front, h, d, u, v, m, n)\n end\n end\n\n # length of array with hash key m - n (= h) is \n # as long as the index of its last entry (= d) + 1\n return (front[m-n].length - 1)\nend",
"def findlargestdrop(arr)\n\n\n\nend",
"def query_each_side_has_a_block x, y, z, do_update = false\r\n arr = Array.new(6, false)\r\n arr[0] = get_block_at(x, y - 1, z) == nil #bottom\r\n arr[1] = get_block_at(x, y, z - 1) == nil #sides\r\n arr[2] = get_block_at(x - 1, y, z) == nil #sides\r\n arr[3] = get_block_at(x + 1, y, z) == nil #sides\r\n arr[4] = get_block_at(x, y, z + 1) == nil #sides\r\n arr[5] = get_block_at(x, y + 1, z) == nil #top\r\n \r\n if do_update \r\n chx = (x / Util::Chunk_Size).floor\r\n chy = (y / Util::Chunk_Size).floor\r\n chz = (z / Util::Chunk_Size).floor\r\n \r\n if chy != ((y - 1) / Util::Chunk_Size).floor\r\n add_chunk_update_request(chx, ((y - 1) / Util::Chunk_Size).floor, chz)\r\n elsif chy != ((y + 1) / Util::Chunk_Size).floor\r\n add_chunk_update_request(chx, ((y + 1) / Util::Chunk_Size).floor, chz)\r\n end\r\n \r\n if chx != ((x - 1) / Util::Chunk_Size).floor\r\n add_chunk_update_request(((x - 1) / Util::Chunk_Size).floor, chy, chz)\r\n elsif chx != ((x + 1) / Util::Chunk_Size).floor\r\n add_chunk_update_request(((x + 1) / Util::Chunk_Size).floor, chy, chz)\r\n end\r\n \r\n if chz != ((z + 1) / Util::Chunk_Size).floor\r\n add_chunk_update_request(chx, chy, ((z + 1) / Util::Chunk_Size).floor)\r\n elsif chz != ((z - 1) / Util::Chunk_Size).floor\r\n add_chunk_update_request(chx, chy, ((z - 1) / Util::Chunk_Size).floor)\r\n end\r\n \r\n end\r\n\r\n #@called += 1\r\n #puts @called\r\n \r\n return arr\r\n end",
"def problem_108(size = 1001)\n func = lambda do |a|\n if a.length == 1\n a[0]+1\n else\n m = a[0]\n (2*m+1) * func.call(a[1,a.length]) -m\n end\n end\n\n primes = Primes.upto(200)\n prime_number = lambda do |a|\n r = 1\n a.sort.reverse.each_with_index { |m,i| r *= primes[i] ** m }\n r\n end\n\n values = {}\n last = 0\n 1.upto(100).each do |nn|\n nn.groupings do |a|\n sols = func.call a\n ans = prime_number.call a\n# puts \"np=#{nn} sols=#{sols} ans=#{ans} => #{a.inspect}\"\n if values[sols]\n values[sols] = [values[sols],[ans,a]].min\n else\n values[sols] = [ans,a]\n end\n true\n end\n size.upto(size*5/4) do |num|\n if values[num]\n puts \"for np = #{nn} => #{num} => #{values[num].inspect}\"\n if last == values[num]\n puts \"factors = #{values[num][0].factors}\"\n return values[num][0] \n end\n last = values[num]\n break\n end\n end\n #values.sort.each do |k,v|\n # puts \"#{k} => #{v}\"\n #end\n end\n nil\nend",
"def icecreamParlor(m, arr)\n # Complete this function\n res = []\n arr.each_index do |i|\n if i + 1 !=nil\n j = i + 1\n while j <= arr.length - 1\n if arr[i]+arr[j] == m\n res.push([i+1,j+1])\n end\n j+=1\n end\n end\n end\n res\nend",
"def magic_alignement()\n\t\tdt = @buswi[0][0]\n\t\tokb = [@buswi[0]]\n\n\t\tremb = @buswi[1..].clone\n\t\tt=0\n\t\tloop do \n\t\t\tt = t + dt\n\t\t\tokb=[]\n\t\t\tremb.each do |p,i|\n\t\t\t\tif (t+i)%p == 0\n\t\t\t\t\tdt = dt.lcm(p)\n\t\t\t\t\tokb << [p,i]\n\t\t\t\tend\n\t\t\tend\n\t\t\tremb = remb - okb\n\t\t\tbreak if remb.empty?\n\t\tend\n\t\tt\n\tend",
"def lcs_phase_two(arr)\n return arr.max if arr.max < 0 #edge case\n\n current = 0\n largest = 0\n\n arr.each do |ele|\n current += ele\n current = 0 if current < 0 #bookmark\n largest = current if largest < current\n end\n\n largest\nend",
"def solve( n = 2_000 )\n # We can classify every tile according to its angular position around the\n # unit circle, setting position 0 at the top since that's where each row\n # starts in the problem statement. Positions 1-5 then follow every 60° as\n # we work our way counter-clockwise. Depending on which of these positions\n # each tile falls (or between which pair of positions), we use different\n # formulae to calculate its six neighbors to the N, NW, SW, S, SE, and NE:\n # \n # Pos 0: n even = fhp\n # N = n + ring (g) S = n - ring + 6 (a)\n # NW = n + ring + 1 (h) SE = n + ring - 1 (f)\n # SW = n + 1 NE = n + (2*ring + 5) (p)\n #\n # Pos 0-1: n even = bh, n odd = ag \n # N = n + ring (g) S = n - ring + 6 (a)\n # NW = n + ring + 1 (h) SE = n - ring + 5 (b)\n # SW = n + 1 NE = n - 1\n #\n # Pos 1: n even = bh, n odd = gi\n # N = n + ring (g) S = n + 1\n # NW = n + ring + 1 (h) SE = n - ring + 5 (b)\n # SW = n + ring + 2 (i) NE = n - 1\n #\n # Pos 1-2: n even = bh, n odd = ci\n # N = n - 1 S = n + 1\n # NW = n + ring + 1 (h) SE = n - ring + 5 (b)\n # SW = n + ring + 2 (i) NE = n - ring + 4 (c)\n #\n # Pos 2: n even = hj\n # N = n - 1 S = n + ring + 3 (j)\n # NW = n + ring + 1 (h) SE = n + 1\n # SW = n + ring + 2 (i) NE = n - ring + 4 (c)\n #\n # Pos 2-3: n even = dj, n odd = ci\n # N = n - ring + 3 (d) S = n + ring + 3 (j)\n # NW = n - 1 SE = n + 1\n # SW = n + ring + 2 (i) NE = n - ring + 4 (c)\n #\n # Pos 3: n even = dj, n odd = ik\n # N = n - ring + 3 (d) S = n + ring + 3 (j)\n # NW = n - 1 SE = n + ring + 4 (k)\n # SW = n + ring + 2 (i) NE = n + 1\n #\n # Pos 3-4: n even = dj, n odd = ek\n # N = n - ring + 3 (d) S = n + ring + 3 (j)\n # NW = n - ring + 2 (e) SE = n + ring + 4 (k)\n # SW = n - 1 NE = n + 1\n #\n # Pos 4: n even = jl\n # N = n + 1 S = n + ring + 3 (j)\n # NW = n - ring + 2 (e) SE = n + ring + 4 (k)\n # SW = n - 1 NE = n + ring + 5 (l)\n #\n # Pos 4-5: n even = fl, n odd = ek\n # N = n + 1 S = n - 1\n # NW = n - ring + 2 (e) SE = n + ring + 4 (k)\n # SW = n - ring + 1 (f) NE = n + ring + 5 (l)\n #\n # Pos 5: n even = fl, n odd = km\n # N = n + ring + 6 (m) S = n - 1\n # NW = n + 1 SE = n + ring + 4 (k)\n # SW = n - ring + 1 (f) NE = n + ring + 5 (l)\n #\n # Pos 5-0, except last: n even = fl, n odd = gm\n # N = n + ring + 6 (m) S = n - ring (g)\n # NW = n + 1 SE = n - 1\n # SW = n - ring + 1 (f) NE = n + ring + 5 (l)\n #\n # Pos 5-0, only last: n even = flo, n odd = gmo\n # N = n + ring + 6 (m) S = n - ring (g)\n # NW = n - ring + 1 (f) SE = n - 1\n # SW = n - (2*ring - 7) (o) NE = n + ring + 5 (l)\n #\n # From these formula, we can derive the difference between a tile and each\n # of its neighbors. If we arrange all potential differences in ascending\n # order, it becomes obvious that for n even or odd, some deltas will al-\n # ways be even, and thus can never be prime (>2).\n #\n # Furthermore, we can see that only in certain positions will a tile ever\n # differ from three neighbors by odd amounts (position 0 and just to the\n # right of position 0). In all other cases, at most two deltas will be\n # odd, meaning PD(n) will be 2 or less.\n #\n # n even n odd\n # a = ring - 6 even a\n # b = ring - 5 b even\n # c = ring - 4 even c\n # d = ring - 3 d even\n # e = ring - 2 even e\n # f = ring - 1 f even\n # g = ring even g\n # h = ring + 1 h even\n # i = ring + 2 even i\n # j = ring + 3 j even\n # k = ring + 4 even k\n # l = ring + 5 l even\n # m = ring + 6 even m\n # o = 2ring - 7 o o\n # p = 2ring + 5 p p\n pd3 = [1, 2]\n base, ring = 8, 12\n \n while pd3.size < n\n # Only at position 0 and one tile to the right will there ever be three\n # odd deltas, so those are the only ones we have to check for primality.\n # Both share a delta of f = ring - 1.\n if (ring - 1).prime?\n # Check the other odd deltas for position 0. \n pd3 << base if (ring + 1).prime? && (2*ring + 5).prime?\n\n # Check the other odd deltas for one tile to the right of position 0.\n pd3 << base + ring - 1 if (ring + 5).prime? && (2*ring - 7).prime?\n end\n\n # Advance the first tile of the current ring (base), and the number of\n # tiles it contains (ring). \n base += ring\n ring += 6\n end\n\n pd3[-1]\n end",
"def walk(grid, x, y)\n [N, S, E, W].shuffle.each do |dir|\n nx, ny = x + DX[dir], y + DY[dir]\n if nx >= 0 && ny >= 0 && ny < grid.length && nx < grid[ny].length && grid[ny][nx] == 0\n grid[y][x] |= dir\n grid[ny][nx] |= OPPOSITE[dir]\n \n return [nx, ny]\n end\n end\n \n nil\nend",
"def optimize_moves(orig)\n # Put counts of each item into a hash.\n m = Hash.new(0)\n orig.each {|e| m[e] += 1}\n\n # Now, apply optimizations.\n curr_count = sum_values(m)\n prev_count = -1\n while curr_count != prev_count\n annihilate(m, :R, :L)\n annihilate(m, :r, :l)\n # :r * ROT_STEPS --> :R\n if m[:r] >= ROT_STEPS\n\tm[:r] -= ROT_STEPS\n\tm[:R] += 1\n end\n # :l * ? --> :L\n if m[:l] >= ROT_STEPS\n\tm[:l] -= ROT_STEPS\n\tm[:L] += 1\n end\n # [:r, :r, :r, :r] --> [:R, :l, :l]\n if m[:r] > ROT_STEPS/2\n\tm[:r] -= (ROT_STEPS/2 + 1)\n\tm[:R] += 1\n\tm[:l] += (ROT_STEPS/2 - 1)\n end\n # [:l, :l, :l, :l] --> [:L, :r, :r]\n if m[:l] > ROT_STEPS/2\n\tm[:l] -= (ROT_STEPS/2 + 1)\n\tm[:L] += 1\n\tm[:r] += (ROT_STEPS/2 - 1)\n end\n # \n # 12 big revolves is the identity\n if m[:L] >= 12\n\tm[:L] -= 12\n end\n if m[:R] >= 12\n\tm[:R] -= 12\n end\n # \n # 7 big revolves is 5 of the opposite.\n if m[:L] >= 7\n\tm[:L] -= 7\n\tm[:R] += 5\n end\n if m[:R] >= 7\n\tm[:R] -= 7\n\tm[:L] += 5\n end\n prev_count = curr_count\n curr_count = sum_values(m)\n end\n # Sort so that translations come after the rotations.\n trans_arr = []\n rot_arr = []\n m.each_key {|k|\n if BIG_R.include?(k) || LITTLE_R.include?(k)\n\tm[k].times {|i| rot_arr << k}\n else\n\tm[k].times {|i| trans_arr << k}\n end\n }\n\n rot_arr + trans_arr\n end",
"def algorithm=(_); end",
"def algorithm=(_); end",
"def algorithm=(_); end",
"def algorithm=(_); end",
"def ukp5(ukpi, return_used_items = false)\n n = ukpi[:n]\n c = ukpi[:c]\n items = ukpi[:items].clone\n\n max_w = items.max_by { | i | i[:w] }[:w]\n g = Array.new(c+max_w+1, 0)\n d = Array.new(c+max_w+1, n-1)\n sort_items_by_profitability!(items)\n\n last_y_where_nonbest_item_was_used = 0\n items.each_with_index do | it, ix |\n wi = it[:w]\n pi = it[:p]\n if g[wi] < pi then\n g[wi] = pi\n d[wi] = ix\n last_y_where_nonbest_item_was_used = wi if wi > last_y_where_nonbest_item_was_used && ix != 0\n end\n end\n\n opt = 0\n (1..(c-1)).each do | y |\n next if g[y] <= opt\n break if last_y_where_nonbest_item_was_used < y\n\n opt = gy = g[y]\n dy = d[y]\n\n # this block is a copy-past of the loop bellow only for the best item\n bi = items[0]\n pb = bi[:p]\n wb = bi[:w]\n next_y = y + wb\n old_gny = g[next_y]\n new_gny = gy + pb\n if old_gny < new_gny then\n g[next_y] = new_gny\n d[next_y] = 0\n end\n\n (1..dy).each do | ix |\n it = items[ix]\n pi = it[:p]\n wi = it[:w]\n ny = y + wi\n ogny = g[ny]\n ngny = gy + pi\n if ogny < ngny then\n g[ny] = ngny\n d[ny] = ix\n last_y_where_nonbest_item_was_used = ny if ny > last_y_where_nonbest_item_was_used\n end\n end\n end\n\n if last_y_where_nonbest_item_was_used < c-1 then\n y_ = last_y_where_nonbest_item_was_used\n while d[y_] != 0 do\n y_ += 1\n end\n# puts \"Periodicity used - c: #{c}; last_y: #{y_}\"\n\n extra_capacity = c - y_\n c1, a1 = items[0][:p], items[0][:w]\n qt_best_item_used = Rational(extra_capacity, a1).ceil\n space_used_by_best_item = qt_best_item_used*a1\n profit_generated_by_best_item = qt_best_item_used*c1\n\n opt_y = get_opt_y(c-space_used_by_best_item, items, g, d)\n g[c] = g[opt_y] + profit_generated_by_best_item\n end\n\n opt = g[c] if opt < g[c]\n\n if return_used_items then\n g.slice!(c+1, max_w)\n d.slice!(c+1, max_w)\n opt_y = get_opt_y(c, items, g, d)\n get_used_items_for_y(opt_y, items, g, d)\n else\n opt\n end\nend",
"def solve( n = 16 )\n max = 0\n \n (1..10).each do |a|\n (1..10).each do |b|\n next if b == a\n (1..10).each do |c|\n next if c == b || c == a\n (1..10).each do |d|\n next if d == c || d == b || d == a\n (1..10).each do |e|\n next if e == d || e == c || e == b || e == a\n\n rotate = 3*[a, b, c, d, e].each_with_index.min[1]\n (1..10).each do |f|\n next if f == e || f == d || f == c || f == b || f == a\n (1..10).each do |g|\n next if g == f || g == e || g == d || g == c || g == b || g == a\n \n t = a + f + g\n (1..10).each do |h|\n next if h == g || h == f || h == e || h == d || h == c || h == b || h == a\n next unless t == b + g + h\n\n (1..10).each do |i|\n next if i == h || i == g || i == f || i == e || i == d || i == c || i == b || i == a\n next unless t == c + h + i\n\n (1..10).each do |j|\n next if j == i || j == h || j == g || j == f || j == e || j == d || j == c || j == b || j == a\n next unless t == d + i + j && t == e + j + f\n\n s = [a, f, g, b, g, h, c, h, i, d, i, j, e, j, f]\n rotate.times {s.push s.shift}\n\n s = s.join\n next if n != s.length\n\n max = [max, s.to_i].max\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n\n max\n end",
"def sequence(hidden, open)\n weight = { 1 => \"A\", 2 => \"2\", 3 => \"3\", 4 => \"4\", 5 => \"5\", 6 => \"6\", 7 => \"7\", 8 => \"8\", 9 => \"9\", \n 10 => \"T\", 11 => \"J\", 12 => \"Q\", 13 => \"K\" }\n i = 0\n result = []\n inputs = 1\n differ = 0\n if weight.key(hidden[i]) > weight.key(hidden[i+2])\n small = weight.key(hidden[i+2])\n big = weight.key(hidden[i])\n differ = big - small\n elsif weight.key(hidden[i]) < weight.key(hidden[i+2])\n small = weight.key(hidden[i])\n big = weight.key(hidden[i+2])\n differ = big - small\n else\n return false\n end\n return false if differ > 4\n if differ > 1\n start = small + 1\n end1 = big - 1\n start.upto(end1) do |j|\n open.each_index do |k|\n if open[k] == weight[j]\n unless result.include? weight[j]\n result << open[k]\n result << open[k+1]\n inputs += 1\n end \n end \n end \n end\n end\n return false unless differ == inputs \n if result.size < 6\n steps = (6-result.size)/2\n start = big + 1\n end1 = big + steps\n start.upto(end1) do |j|\n open.each_index do |k|\n if open[k] == weight[j]\n unless result.include? weight[j]\n result << open[k]\n result << open[k+1]\n end \n end \n end \n end\n if result.size < 6\n steps = (6-result.size)/2\n return false if small - steps < 1 \n start = small - steps\n end1 = small - 1\n start.upto(end1) do |j|\n open.each_index do |k|\n if open[k] == weight[j]\n unless result.include? weight[j]\n result << open[k]\n result << open[k+1]\n end \n end \n end \n end\n return false if result.size < 6\n end\n end \n result \n end",
"def sdrm_nrti(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[41] = ['M',['L']]\n sdrm[65] = ['K',['R']]\n sdrm[67] = ['D',['N','G','E']]\n sdrm[69] = ['T',['D']]\n sdrm[70] = ['K',['R','E']]\n sdrm[74] = ['L',['V','I']]\n sdrm[75] = ['V',['M','T','A','S']]\n sdrm[77] = ['F',['L']]\n sdrm[115] = ['Y',['F']]\n sdrm[116] = ['F',['Y']]\n sdrm[151] = ['Q',['M']]\n sdrm[184] = ['M',['V','I']]\n sdrm[210] = ['L',['W']]\n sdrm[215] = [\"T\",[\"Y\",\"F\",\"I\",\"C\",\"D\",\"V\",\"E\",\"S\"]]\n sdrm[219] = [\"K\",[\"Q\",\"E\",\"N\",\"R\"]]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n\n end\n end\n return out_hash\nend",
"def problem_60a\n num_cut = 5\n# simple\n pairs = {}\n seen_primes = []\n num_primes = 0\n last = start = Time.now\n Primes.each do |p|\n next if p == 2\n b = p.to_s\n seen_primes.each_index do |sp_i|\n sp = seen_primes[sp_i]\n a = sp.to_s\n ai,bi = a.to_i,b.to_i\n ab = (a + b).to_i\n ba = (b + a).to_i\n\n if ba.prime? && ab.prime?\n # We have a pair that works both ways so add the peer to each prime\n pairs[ai] = aa = ((pairs[ai] || []) << bi).uniq\n pairs[bi] = bb = ((pairs[bi] || []) << ai).uniq\n next unless pairs[bi].length >= num_cut - 1 # bi is biggest of pair\n\n check = ([ai] + aa) & ([bi] + bb)\n if check.length >= num_cut\n puts \"Try #{check.inspect}\"\n perm = check.permutation(2).to_a\n new = perm.select do |x,y|\n (x.to_s + y.to_s).to_i.prime? && (x.to_s + y.to_s).to_i.prime?\n end\n if new.length == perm.length\n n = new.flatten.uniq\n sum = n.reduce(&:+)\n puts \"#{n.inspect} *** #{sum}\"\n return sum\n end\n end\n end\n end\n seen_primes << p\n end\n nil\nend",
"def solution(a)\n # write your code in Ruby 2.2\n binding.pry\n trips = Hash.new {|h,k| h[k]=0}\n start = 0\n ending = 0\n min = nil\n a.each_with_index do |trip,i|\n ending = i\n\n if trips[trip] == 0\n min = ending - start\n end\n trips[trip] += 1\n\n while start < ending\n break if trips[a[start]] - 1 == 0\n trips[start] -= 1\n start += 1\n min = ending - start if ending-start < min\n end\n end\n min\nend",
"def smoothing; end",
"def solution(s, p, q)\n # write your code in Ruby 2.2\n g = s.length + 1\n a = (s.length + 1)**3\n c = (s.length + 1)**2\n tmp = []\n res = []\n tmp.push 0\n o = 0\n s.split('').each do |i|\n o += if i == 'T'\n 1\n elsif i == 'G'\n g\n elsif i == 'C'\n c\n else\n a\nend\n tmp.push o\n end\n (0...p.length).each do |k|\n o = tmp[q[k] + 1] - tmp[p[k]]\n if o >= a\n res.push 1\n elsif o >= c\n res.push 2\n elsif o >= g\n res.push 3\n else\n res.push 4\n end\n end\n res\nend",
"def hourglassSum(arr)\n m = Matrix[*arr]\n\n # minimum possible result\n result = -9*7\n\n for i in (0..3)\n for j in (0..3)\n aux = lilHourglass(m.minor((i..i+2),(j..j+2)) )\n if aux > result\n result = aux \n end\n end\n end\n result\nend",
"def solution(a)\n cars_going_east = [0]\n\n a.each do |direction|\n next_counter = direction.zero? ? cars_going_east.last + 1 : cars_going_east.last\n cars_going_east << next_counter\n end\n\n passings = 0\n a.each_with_index do |direction, index|\n passings += cars_going_east[index] if direction == 1\n end\n\n return -1 if passings > 1000000000\n passings\nend",
"def minimumBribes(q)\r\n moves = 0\r\n r = (0..q.size-1).to_a\r\n\r\n until q == (1..q.size).to_a do\r\n q.map { |a| a - 1 }\r\n .reverse_each.with_index do |person, i|\r\n i = q.size - i - 1\r\n if person - i > 2\r\n puts \"Too chaotic\"\r\n return\r\n end\r\n\r\n if person > r[i] && person > q[person] -1\r\n moves += person - r[i]\r\n q = q - [person + 1]\r\n q.insert(person, person + 1)\r\n end\r\n end\r\n end\r\n\r\n puts moves\r\nend",
"def minimumBribes(q)\n bribe_count = 0\n # q.each_with_index do |person,i|\n i = q.size-1\n while i >= 0 do\n person = q[i]\n position = i+1\n offset = person - position\n\n if offset > 2\n puts \"Too chaotic\"\n return\n else\n j=[0,person-2].max\n while j < i do\n if q[j] > person\n bribe_count += 1\n else\n # break if j+1 == person\n end\n j+=1\n end\n end\n i-=1\n end\n puts bribe_count\nend",
"def find3(a, X)\n # scan through array\n # build hash storing complement in each key\n complements = {}\n a.each_with_index do |val, ind|\n if complements[X - val]\n complements[X - val].push(ind)\n else\n complements[X - val] = [ind]\n end\n end\n\n # scan through the array again\n # get complement\n # for each value scan the remainder of the arrray\n # for a value such taht a + b = the complement\n\n # for each character we have built a dictionary such that, we can find\n # x = a + complement\n\n # [1, 2, 3]\n # 1 + 2 = 3\n # 1 + 3 = 4 =>\n\n # for each value in the array (a) look at all following values (b) and see if a + b\n # is in the dictionary, if it is, check that their indices do not collide with the index\n # stored at dict(a+b)\n\n a.each_with_index do |va, i|\n a.each_with_index do |vb, j|\n break if i == j\n\n complement = va + vb\n indices = complements[complement]\n\n indices.each do |z|\n # every index is unique\n return [i, j, z] unless z == i || z == j\n end\n end\n end\n\n return nil\nend",
"def ukp4(ukpi)\n n = ukpi[:n]\n c = ukpi[:c]\n items = ukpi[:items].clone\n\n g = Array.new(c+1, 0)\n sort_items_by_profitability!(items)\n\n items.each do | item |\n pi = item[:p]\n wi = item[:w]\n max_xi = Rational(c, wi).floor\n z = pi\n y = wi\n max_xi.times do\n if g[y] == 0 then\n g[y] = z\n else\n z = g[y]\n end\n z += pi\n y += wi\n end\n\n break if g[c] != 0\n end\n\n g\nend",
"def joltageDiff(input)\n # add my input device with rating +3\n input.append(input.max + 3)\n arr = input\n .sort\n .reverse\n \n diffs = arr\n .map.with_index{ |n, i|\n if i < arr.size - 1\n n - arr[i+1]\n end\n }\n diffs.pop # remove last element\n # puts diffs.sort\n counts = [0, 0, 0]\n counts[0] = diffs.select{ |n| n == 1 }.size + 1 # fuck knows why this is here.. #dirtyhack\n counts[1] = diffs.select{ |n| n == 2 }.size\n counts[2] = diffs.select{ |n| n == 3 }.size\n #puts counts\n return counts\nend",
"def returnPermutationsBefore(multiLetterDivisor)\n \n #Define functions used by this function\n \n #--------------------------------------------------------------- \n \n #function that returns sum of all elements before given position\n #This function is used to track how many alphabetically preceding\n #letters are still available for our mathematical calculation\n \n def sumPrecedingArrayEntries(array, position)\n sum = 0\n for i in 0..position-1\n sum += array[i]\n end\n return sum\n end\n\n #---------------------------------------------------------------\n \n #Function that calculates the permutations that can alphabetically\n #precede the given spot in word using given parameters. This function gives\n #the count for each letter and its results are summed together.\n \n def findPermutationsBefore(noToPermutate, availablePrecedingLetters,\n multiLetterDivisor) \n return (getFactorial(noToPermutate-1) * availablePrecedingLetters) / (multiLetterDivisor)\n end\n \n #---------------------------------------------------------------\n\n #variable for running count of permutations that alphabetically\n #precede the given word as we loop and parse through given word\n \n permutationsBefore = 0\n \n #Array to keep track of which letters have been consumed.\n #Could also update totalLettersBefore in hash table\n #and parse hash table but array better suited for sequential\n #parsing by index\n \n usedLettersArray = Array.new(@uniqueLetterCount, 0)\n \n #Loop to parse through @arrayOfChars (original, unsorted word)\n \n for i in 0..@length-2\n \n #For sake of readability, use currentLetterData to reference\n #inner hash for each letter.\n #Thus @letterHash[@arrayOfChars[i]][\"totalLettersBefore\"] becomes\n #currentLetterData[\"totalLettersBefore\"]\n \n currentLetterData = @letterHash[@arrayOfChars[i]]\n \n #sumPrecedingArrayEntries parses usedLettersArray and returns\n #the sum of all entries prior to given index (alphabetical\n #index of currentLetter). Thus, this call returns number of\n #consumed letters that precede currentLetter\n \n qtyPrecedingUsedLetters = sumPrecedingArrayEntries(usedLettersArray,\n currentLetterData[\"alphabeticalIndex\"])\n \n #update qtyPrecedingAvailableLetters by subtracting used letters\n #from currentLetter's totalLettersBefore obtained from hash table. \n \n qtyPrecedingAvailableLetters = currentLetterData[\"totalLettersBefore\"] -\n qtyPrecedingUsedLetters\n \n #Add the permutations for current spot to running total.\n \n permutationsBefore += findPermutationsBefore(@length-i,\n qtyPrecedingAvailableLetters, multiLetterDivisor)\n \n #To prepare for next iteration, update multiLetterDivisor as needed\n #after consuming current character. Update usedLettersArray after\n #updating multiLetterDivisor. NOTE: multiLetterDivisor is a copy\n #of instance variable @multiLetterDivisor. Copy is used so that\n #@multiLetterDivisor remains preserved for other functions such as\n #printAlphabeticalPositionUserFriendly\n \n #To see how multiLetterDivisor works, imagine a word with 3 A's.\n #Initially this letter contributes 3! to multiLetterDivisor.\n #After 1 A is used, we divide multiLetterDivisor by\n #(occurrences of A - number of A's consumed). We make this update\n #Before updating usedLettersArray. So for first consumption\n #multiLetterDivisor gets divided by 3-0 = 3. After dividing by 3 A\n #contributes 3!/3 = 2! to the collective divisor. Next time A is consumed\n #multiLetterDivisor gets divided by 3-1 = 2. So after 2 A's are\n #consumed, A contributes 2!/2 = 1 to multiLetterDivisor.\n \n multiLetterDivisor /= (currentLetterData[\"occurrencesOfLetter\"] -\n usedLettersArray[currentLetterData[\"alphabeticalIndex\"]])\n usedLettersArray[currentLetterData[\"alphabeticalIndex\"]] += 1\n end\n return permutationsBefore\n end",
"def correct(element)\n result = nil\n element.downto(0).each do |j|\n i = element - j\n if j == element && j % 3 == 0\n result = Array.new(j, 5)\n elsif i % 5 == 0 && j % 3 == 0\n result = Array.new(j, 5) + Array.new(i, 3)\n elsif i == element && i % 5 == 0\n result = Array.new(i, 3)\n end\n\n break if result\n end\n\n if result.nil?\n puts -1\n else\n puts result.join()\n end\nend",
"def anchored; end",
"def finalscore(h,flattenarray,originalarray)\r\n # puts \"==>> #{originalarray}\"\r\n max_index = originalarray.each_index.max_by { |i| originalarray[i].size }\r\n # puts \"max index = #{max_index}\"\r\n # puts \"abcscs = #{originalarray[max_index].length}\"\r\n maxsize = originalarray[max_index].length+1\r\n min_index = originalarray.each_index.min_by { |i| originalarray[i].size }\r\n minsize = originalarray[min_index].length+1\r\n frequency = flattenarray.length\r\n # puts \"***** max= #{maxsize} min = #{minsize} f= #{frequency}\"\r\n h.each do |key,value|\r\n # if key == \"B00APE06UA\"\r\n # puts \"value = #{value }\"\r\n # puts \"value[0] = #{value[0] }\"\r\n # puts \"value[1] = #{value[1]}== #{(value[1]-minsize+1)}/#{(maxsize-minsize)}\"\r\n # puts \"value[0] = #{value[0]} == #{value[0].clone}/#{frequency}\"\r\n # end\r\n\r\n # value[0]= 10000*value[0]/frequency\r\n # value[1]= 100*(value[1]-minsize+1)/(maxsize-minsize)\r\n value [1] = 10000*( value[1]/value[0])\r\n # if key ==\"B00APE06UA\"\r\n # puts \"value [1] = #{value[1]}\"\r\n # puts \" ==>>>> #{value[0]} =========#{value[1]} #{(value[1]-minsize+1)}/#{(maxsize-minsize)} \"\r\n # end\r\n total_score = value[0]+value[1]\r\n # puts\" #{total_score}\"\r\n h[key] = total_score\r\n end\r\n return h\r\nend",
"def compute(name, ref, span, snps)\n return if span.length < 1\n\n span.sort! {|a,b| a[0] <=> b[0]}\n head = span.shift\n ss,ee = head[0],head[1]\n array = []\n \n array << ss \n span.each do |breaks|\n array << breaks[0]\n array << breaks[1]\n end\n array << ee \n\n while array.size > 0\n s = array.shift\n e = array.shift\n# $stderr.puts \"#{ref}\\t#{s}\\t#{e}\"\n (s..e).each do |i|\n @coverage[ref][i] += 1 #Compute coverage on base i\n end\n end\n\n snps.each_key do |pos|\n refbase = @seq[ref][pos-1,1].upcase\n curbase = snps[pos][:snpbase]\n if snps.key?(pos + 1) or snps.key?(pos + 2) or snps.key?(pos - 1) or snps.key?(pos - 2)\n if snps.key?(pos + 1) and refbase == snps[pos+1][:snpbase] and curbase == @seq[ref][pos,1].upcase\n snps[pos][:info] << \"swap;\"\n elsif snps.key?(pos - 1) and refbase == snps[pos-1][:snpbase] and curbase == @seq[ref][pos-2,1].upcase \n snps[pos][:info] << \"swap;\"\n elsif snps.key?(pos + 2) and refbase == snps[pos+2][:snpbase] and curbase == @seq[ref][pos+1,1].upcase\n snps[pos][:info] << \"swap;\"\n elsif snps.key?(pos - 2) and refbase == snps[pos-2][:snpbase] and curbase == @seq[ref][pos-3,1].upcase\n snps[pos][:info] << \"swap;\"\n elsif snps.key?(pos + 1) or snps.key?(pos - 1) \n snps[pos][:info] << \"mnp;\"\n else\n snps[pos][:info] << \"snp;\" \n end\n else\n snps[pos][:info] << \"snp;\" \n end\n @snp[ref][pos] = '' unless @snp[ref].key?(pos)\n @snp[ref][pos] << snps[pos][:info]\n end\nend",
"def part_two(input)\n found = false\n cleaned = input.each_with_index.map { |v, i| [v, i] unless v == 'x' }.compact\n iter = cleaned.map(&:first).max\n index = cleaned.map(&:first).find_index(iter)\n t = iter\n until found\n t += iter\n puts \"#{t}\"\n found = true\n v = t - index\n cleaned.each do |bus, i|\n if (v + i) % bus != 0\n found = false\n break\n end\n end\n end\n t\nend",
"def alg4(max_value)\n perimeters = Hash.new 0\n (6..max_value/2).each do |p_sub|\n p = p_sub * 2\n (p_sub-1..3).each do |a|\n b = p * (p - 2*a) / (2.0 * (p-a))\n # avoid double counting\n break if b > a\n\n if b > 0 && b == b.to_i\n #puts \"debug: adding perimeter #{p} = #{a} + #{b} + ...\"\n perimeters[p] += 1\n end\n end\n end\n return perimeters\nend",
"def ject(ary)\nr = [ary]\nw = []\n\nr.flatten.each do |y| \n\tif y == 0\n\t\tw << 0\n\telse\n\t\t3.times {|idx| w << ( y / (idx + 2) )}\n\tend\nend\nw\nend",
"def frac (k, c, s)\n #\n ans = []\n tile = ['G', 'L']\n possible_source_sequences = tile.repeated_permutation(k).to_a\n seq = possible_source_sequences.dup\n for i in (2..c)\n seq = seq.map.with_index { |e, i| e.map { |ee| ee = (ee == 'G') ? 'G'*k : possible_source_sequences[i].join('') }}\n seq = seq.map { |e| e.join('').split('') }\n end\n\n for ii in (1..s)\n ss = seq.transpose\n ssl = ss.map { |e| e.count('L') }\n\n fewest_lead = ssl.min\n index_fewest_lead = ssl.find_index(fewest_lead)\n ans.push(index_fewest_lead)\n break if fewest_lead == 1\n tmp = []\n ss[index_fewest_lead].each.with_index { |e, i| tmp.push(seq[i]) if e == 'L'}\n seq = tmp\n return ['IMPOSSIBLE'] if ii == s and fewest_lead != 1\n end\n\n return ans.collect { |e| e + 1 }\nend",
"def formingMagicSquare(s)\r\n out = 100\r\n for i in 0...8 do\r\n cost = 0\r\n for j in 0...3 do\r\n for k in 0...3 do\r\n cost += ($magic_square[i][j][k] - s[j][k]).abs\r\n end\r\n end\r\n puts cost\r\n out = [out, cost].min\r\n end \r\n out\r\nend",
"def heuristic(current:, target:)\n d = (current[0].real - target[0].real).abs + (current[0].imag - target[0].imag).abs\n d += 7 if d <= 8 && current[1] != target[1]\n\n d\nend",
"def to_compress\n a = lx.dup\n b = rx.dup\n ts = transcript.dup\n w = ts.challenge_scalar(\"w\")\n q = GENERATOR_BJ * w\n\n a_sum = a.dup\n b_sum = b.dup\n g_sum = vec_g.dup\n h_sum = vec_h2.dup\n\n terms = []\n until a_sum.length == 1\n a_lo = []\n b_lo = []\n g_lo = []\n h_lo = []\n a_hi = []\n b_hi = []\n g_hi = []\n h_hi = []\n half = a_sum.length / 2\n a_sum.each.with_index do |_, i|\n if i < half\n a_lo << a_sum[i]\n b_lo << b_sum[i]\n g_lo << g_sum[i]\n h_lo << h_sum[i]\n else\n a_hi << a_sum[i]\n b_hi << b_sum[i]\n g_hi << g_sum[i]\n h_hi << h_sum[i]\n end\n end\n alo_bhi = a_lo.zip(b_hi).map { |x, y| FIELD.mod(x * y) }.sum\n ahi_blo = a_hi.zip(b_lo).map { |x, y| FIELD.mod(x * y) }.sum\n\n l_k =\n g_hi.zip(a_lo).map { |x, y| x * y }.sum(INFINITY_J) +\n h_lo.zip(b_hi).map { |x, y| x * y }.sum(INFINITY_J) + q * alo_bhi\n r_k =\n g_lo.zip(a_hi).map { |x, y| x * y }.sum(INFINITY_J) +\n h_hi.zip(b_lo).map { |x, y| x * y }.sum(INFINITY_J) + q * ahi_blo\n\n ts.points << l_k\n ts.points << r_k\n uk = ts.challenge_scalar(\"uk\")\n uk_inv = FIELD.inverse(uk)\n terms << { L: l_k, R: r_k }\n\n a_sum = []\n b_sum = []\n g_sum = []\n h_sum = []\n a_lo.each.with_index do |_, i|\n a_sum << (a_lo[i] * uk + a_hi[i] * uk_inv)\n b_sum << (b_lo[i] * uk_inv + b_hi[i] * uk)\n g_sum << (g_lo[i] * uk_inv + g_hi[i] * uk)\n h_sum << (h_lo[i] * uk + h_hi[i] * uk_inv)\n end\n end\n\n a0 = a_sum.first\n b0 = b_sum.first\n\n Compressed.new(v, p_a, p_s, p_t1, p_t2, tx, tx_bf, e, a0, b0, terms)\n end",
"def get_products_but_self(arr)\n # raise 'need more than itself to get all other products' if arr.length < 2\n # result = [] \n # #first just try to come up with a way that works even if it's slow \n # arr.each_with_index do |el,idx|\n # arr[idx] = 1 \n # result << arr.reduce(:*) O(n) in a O(n) loop \n # arr[idx] = el \n # end \n # result This works, Time: O(n^2) space:O(n), created 1 new array Now try to optimize \n \n # Faster way, trying greedy way, constanly update the variable\n products_before_el = [1] # when we are at the first el, the product before that we use 1\n products_after_el = [] #we know that product after the last el, we can use 1, and since\n #we can only multiply, we backwards from the last el for products after el\n end_idx = arr.length - 1 \n products_after_el[end_idx] = 1\n (1..end_idx).each do |i| # time O(n)\n products_before_el[i] = products_before_el[i-1]*arr[i-1]\n products_after_el[end_idx - i] = products_after_el[end_idx - i + 1]*arr[end_idx - i +1]\n end \n result = []\n arr.length.times do |i| \n result[i] = products_before_el[i] * products_after_el[i]\n end \n result \n\n # Can we improve on space? \nend",
"def fitness( candidate, target )\n total = 0\n\n i = 0\n candidate.each_byte do |char_num|\n abs_distance = ( target[i].ord - char_num ).abs\n total += abs_distance\n i += 1\n end\n\n total\nend",
"def pe52(startAt, endAt)\n (startAt..endAt).step(6).each do |x|\n bNum = x/6\n bNumCSort = bNum.to_s.chars.sort\n next if bNumCSort != x.to_s.chars.sort\n next if bNumCSort != (bNum*5).to_s.chars.sort\n next if bNumCSort != (bNum*4).to_s.chars.sort\n next if bNumCSort != (bNum*3).to_s.chars.sort\n next if bNumCSort != (bNum*2).to_s.chars.sort\n return bNum\n end\n false\nend",
"def sluggish_octopus(fishes) \n fishes.each_with_index do |fish1, i1|\n max_length = true\n fishes.each_with_index do |fish2, i2|\n next if i1 == i2\n # puts \"#{fish1} --- #{fish2}\"\n max_length = false if fish1.length < fish2.length\n end\n\n return fish1 if max_length == true\n end\nend",
"def knot_hash(input)\n sequence = input.bytes.to_a\n sequence << [17, 31, 73, 47, 23]\n sequence = sequence.flatten\n list = (0..255).to_a\n\n @current_position = 0\n @skip_size = 0\n # list = (0..4).to_a\n # sequence = [3, 4, 1, 5]\n\n # sequence = '1,2,3'.bytes.to_a\n # sequence << [17, 31, 73, 47, 23]\n # sequence = sequence.flatten\n\n 64.times do\n sequence.each do |seq|\n puts \"STARTING SEQ #{seq}\"\n if @current_position + seq > list.size\n puts \"wrapping\"\n ending_array = list[@current_position..-1]\n ending_array_size = ending_array.size\n puts \"ending array is #{ending_array.inspect}\"\n beginning_array = list[0...seq - ending_array.size]\n puts \"beginning array is #{beginning_array.inspect}\"\n beginning_array_size = beginning_array.size\n array_to_modify = ending_array + beginning_array\n puts \"array_to_modify is #{array_to_modify.inspect}\"\n array_to_modify.reverse!\n puts \"reversed array_to_modify is #{array_to_modify.inspect}\"\n # array_to_modify.rotate(@current_position)\n array_to_modify[0...ending_array_size].each_with_index do |a,i|\n list[@current_position+i] = a\n end\n puts list.inspect\n\n array_to_modify[-beginning_array_size..-1].each_with_index do |a,i|\n list[i] = a\n end\n\n puts list.inspect\n else\n puts \"not wrapping\"\n array_to_modify = list[@current_position...@current_position+seq]\n array_to_modify.reverse!\n array_to_modify.each_with_index do |a,i|\n list[@current_position + i] = a\n end\n puts list.inspect\n\n end\n\n if @current_position + seq + @skip_size > list.size\n @current_position = (@current_position + seq + @skip_size) % list.size\n else\n @current_position = @current_position + seq + @skip_size\n end\n puts \"@current_position is #{@current_position}\"\n @skip_size += 1\n end\n @list = list\n end\n\n foo = []\n @list.each_slice(16) do |chunk|\n foo << chunk.inject(:^)\n end\n\n result = []\n foo.each do |hex|\n if hex.to_s(16).size == 1\n result << '0' + hex.to_s(16)\n else\n result << hex.to_s(16)\n end\n end\n\n result.join\nend",
"def look_at_tie(hand1,hand2)\n\t# Empty face_value1 array created for hand1 faces\n\tface_value1 = []\n\t# Empty face_value2 array created for hand2 faces\n\tface_value2 = []\n\n\thand1.each do |card|\n\t\t# Pushing the face of each card into the empty array and grabbing it by the first index. Ex: \"Kd\" => \"K\" (\"[0][1]\")\n\t\tface_value1 << card[0]\n\tend \n\t# Setting the face_changer function equal to the hand1_faces variable\n\thand1_faces = face_changer(face_value1)\n\t# Sorting the array of faces(after they go through facechanger they turn into integers)\n \tsorted_faces1 = hand1_faces.sort\n \tsorted_faces_sum1 = sorted_faces1.sum\n \t# new_hand1 puts non-duplicated elements into an array\n \tnew_hand1 =\tsorted_faces1.group_by { |card| card }.select { |k, v| v.size.eql? 1 }.keys\n \t# Finds the duplicates and returns one\n \thand1_dupes = sorted_faces1.select{|item| sorted_faces1.count(item) > 1}.uniq\n \t# Adds duplicates together\n \thand1_dupes_sum = hand1_dupes.sum\n \tnext_kicker1 = new_hand1.pop\n\thand2.each do |card|\n\t\tface_value2 << card[0]\n\tend\n\thand2_faces = face_changer(face_value2)\n \tsorted_faces2 = hand2_faces.sort\n \tsorted_faces_sum2 = sorted_faces2.sum\n \tnew_hand2 = sorted_faces2.group_by { |card| card }.select { |k, v| v.size.eql? 1 }.keys\n \thand2_dupes = sorted_faces2.select{|item| sorted_faces2.count(item) > 1}.uniq\n \thand2_dupes_sum = hand2_dupes.sum\n \tnext_kicker2 = new_hand2.pop\n\n \t# If hand1's duplicate sum is greater than hand2's duplicate sum then return the \"hand1 wins string\"\n\tif hand1_dupes_sum > hand2_dupes_sum \n\t\t\"Player One(hand1) wins!\" \n \t# If hand1's duplicate sum is less than hand2's duplicate sum then return the \"hand2 wins string\"\n\telsif hand1_dupes_sum < hand2_dupes_sum\n\t \t \"Player Two(hand2) wins!\"\n \t# If hand1's duplicate sum is equal to hand2's duplicate sum then go to next conditional\n\telse \n \tsplit_the_pot(hand1,hand2)\n end\nend",
"def hcv_ns5a(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[28] = ['M',['T']]\n sdrm[30] = ['L',['H','K','R','Q','A','S','D']]\n sdrm[31] = ['L',['M','V','F']]\n sdrm[32] = ['P',['L']]\n sdrm[44] = ['K',['R']]\n sdrm[58] = ['H',['D','P','S']]\n sdrm[64] = ['T',['A','S']]\n sdrm[77] = ['P',['A','S']]\n sdrm[78] = ['R',['K']]\n sdrm[79] = ['T',['A']]\n sdrm[83] = ['T',['M']]\n sdrm[85] = ['S',['N','H','Y']]\n sdrm[92] = ['A',['P','T','K','E']]\n sdrm[93] = ['Y',['C','F','H','N']]\n sdrm[107] = ['K',['T','S']]\n sdrm[121] = ['I',['V']]\n sdrm[135] = ['T',['A']]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n end\n end\n return out_hash\nend",
"def run(size)\n t = Time.now\n\n puts \"P4\\n#{size} #{size}\"\n\n byte_acc = 0\n bit_num = 0\n\n y = 0\n while y < size\n ci = (2.0*y/size)-1.0\n\n x = 0\n while x < size\n zrzr = zr = 0.0\n zizi = zi = 0.0\n cr = (2.0*x/size)-1.5\n escape = 0b1\n\n z = 0\n while z < 50\n tr = zrzr - zizi + cr\n ti = 2.0*zr*zi + ci\n zr = tr\n zi = ti\n # preserve recalculation\n zrzr = zr*zr\n zizi = zi*zi\n if zrzr+zizi > 4.0\n escape = 0b0\n break\n end\n z += 1\n end\n\n byte_acc = (byte_acc << 1) | escape\n bit_num += 1\n\n # Code is very similar for these cases, but using separate blocks\n # ensures we skip the shifting when it's unnecessary, which is most cases.\n if (bit_num == 8)\n print byte_acc.chr\n byte_acc = 0\n bit_num = 0\n elsif (x == size - 1)\n byte_acc <<= (8 - bit_num)\n print byte_acc.chr\n byte_acc = 0\n bit_num = 0\n end\n x += 1\n end\n y += 1\n end\n\n STDERR.puts(\"time(#{Time.now - t})\")\nend",
"def solve(file)\r\n x, y = Integer($sx), Integer($sy)\r\n visited = []\r\n discovered = []\r\n value = $table[\"#{x} #{y}\"]\r\n value = value.to_s\r\n direction, weight = value.split(/\\s/,2)\r\n discovered.push(\"#{x} #{y}\")\r\n \r\n while discovered.size != 0\r\n current = discovered.pop\r\n x, y = current.split(/\\s/)\r\n x = Integer(x)\r\n y = Integer(y)\r\n value = $table[current]\r\n value = value.to_s\r\n direction, weight = value.split(/\\s/,2)\r\n \r\n if visited.include?(current) == false\r\n visited.push(current)\r\n direction = direction.split(//)\r\n \r\n i = 0\r\n while i < direction.size\r\n case direction[i]\r\n when \"u\"\r\n y = y - 1\r\n if visited.include?(\"#{x} #{y}\") == false\r\n discovered.push(\"#{x} #{y}\")\r\n if \"#{x} #{y}\" == \"#{$ex} #{$ey}\"\r\n result = true\r\n end\r\n end\r\n y = y + 1\r\n when \"d\"\r\n y = y + 1\r\n if visited.include?(\"#{x} #{y}\") == false\r\n discovered.push(\"#{x} #{y}\")\r\n if \"#{x} #{y}\" == \"#{$ex} #{$ey}\"\r\n result = true\r\n end\r\n end\r\n y = y - 1\r\n when \"l\"\r\n x = x - 1\r\n if visited.include?(\"#{x} #{y}\") == false\r\n discovered.push(\"#{x} #{y}\")\r\n if \"#{x} #{y}\" == \"#{$ex} #{$ey}\"\r\n result = true\r\n end\r\n end\r\n x = x + 1\r\n when \"r\"\r\n x = x + 1\r\n if visited.include?(\"#{x} #{y}\") == false\r\n discovered.push(\"#{x} #{y}\")\r\n if \"#{x} #{y}\" == \"#{$ex} #{$ey}\"\r\n result = true\r\n end\r\n end\r\n x = x - 1\r\n end\r\n i = i + 1\r\n end\r\n end\r\n end\r\n puts discovered\r\n if result == true\r\n puts result\r\n else\r\n puts false\r\n end\r\n end",
"def collisions(arr)\n new_arr = []\n result = []\n arr.each do |i|\n if i > 0\n new_arr << i\n else\n if new_arr.empty?\n result << i\n else\n if new_arr[-1] == -(i)\n new_arr.pop\n else\n while !new_arr.empty? && new_arr[-1] < -(i)\n new_arr.pop\n end\n if new_arr.empty?\n result << i\n end\n end\n end\n end\n end\n return (result.concat(new_arr))\nend",
"def fully_extend_all reps=nil\n dist.branches.times do |i|\n hits = mapee(i).hits\n len = mapee(i).length\n mapee(i).clear_hits\n reps = (@len.to_f / len).round if reps.nil?\n mapee(i).length = @len\n reps.times do |j|\n new_hits = HitSq.new\n new_hits << hits\n new_hits * (1.0/reps)\n new_hits + (j.to_f / reps)\n# puts new_hits.hits.inspect\n mapee(i) << new_hits\n end\n# puts mapee(i).hits.hits.inspect\n end\n end",
"def hard(input)\n group_weight = input.sum / 4\n count = 2\n groups = []\n loop do\n groups = input.combination(count).select { |c| c.sum == group_weight }\n break unless groups.empty?\n count += 1\n end\n group = groups.sort_by { |g| quantum_entanglement(g) }.first\n quantum_entanglement(group)\nend",
"def optimize(ary, total)\n return [] if ary.empty?\n table = []\n (ary.size+1).times { |i| table[i] = [] }\n (0..total).each { |zerg| table[0][zerg] = 0 }\n (1..ary.size).each do |base|\n table[base][0] = 0\n (1..total).each do |zerg|\n if ary[base-1].zerg <= zerg && (ary[base-1].minerals + table[base-1][zerg - ary[base-1].zerg] > table[base-1][zerg])\n table[base][zerg] = ary[base-1].minerals + table[base-1][zerg - ary[base-1][1]]\n else\n table[base][zerg] = table[base-1][zerg]\n end\n end\n end\n result = []\n i, k = ary.size, total\n while i > 0 && k > 0\n if table[i][k] != table[i-1][k]\n result << ary[i-1]\n k -= ary[i-1].zerg\n end\n i -= 1\n end\n result\nend",
"def problem_60\n prime_check = lambda do |a,b|\n (a + b).to_i.prime? && (b + a).to_i.prime?\n end\n\n find_match = lambda do |a,k|\n r = a.select {|p| k != p && prime_check.call(k,p) }\n end\n\n primes = Primes.upto(10_000).map(&:to_s)\n primes.delete(\"2\")\n\n hit = {}\n\n primes.each do |p1|\n p1a = find_match.call(primes,p1)\n p1a.each do |p2|\n p2a = find_match.call(p1a,p2)\n p2a.each do |p3|\n p3a = find_match.call(p2a,p2)\n p3a.each do |p3|\n p4a = find_match.call(p3a,p3)\n p4a.each do |p4|\n p5a = find_match.call(p4a,p4)\n if p5a.length > 0\n p5a.each do |p5|\n a = [p1,p2,p3,p4,p5]\n sum = a.map(&:to_i).reduce(&:+)\n unless hit[sum]\n puts \"#{sum} #{a.inspect}\"\n else\n hit[sum] = true\n end\n return sum\n end\n end\n end\n end\n end\n end\n end\nend",
"def get_sum_through(target, piece)\n target -= 1\n highest_multiple = target / piece * piece\n sum_chunk = highest_multiple + piece\n quantity = target / piece / 2\n odd = target / piece % 2\n odd_piece = odd * sum_chunk / 2\n\n sum_chunk * quantity + odd_piece\nend",
"def ftks\n limit = 50\n result = 0\n # these are the correct right angles\n result += limit * limit * 3\n # these are the ones on their side\n (1..limit).each do |i|\n result += i / 2 * 2\n end\n # there are some on their little angles\n (2..limit).each do |long|\n (1..(long - 1)).each do |tall|\n gcd = intGCDInts long, tall\n longd, talld = long / gcd, tall / gcd\n maxn = ((limit - long) / talld > tall / longd ? tall / longd : (limit - long) / talld)\n minn = (long / talld > (limit - tall) / longd ? (limit - tall) / longd : long / talld)\n # p \"(#{long}, #{tall}) => (#{longd}, #{talld}) : #{maxn} + #{minn}\"\n result += (maxn + minn) * 2\n end\n end\n result\nend",
"def hourglassSum(arr)\n sums = []\n arr.each_with_index do |array, i|\n n = 0\n 4.times do\n sum_array = arr[i][n..n+2]\n sum_array << arr[i+1][n+1]\n sum_array += arr[i+2][n..n+2]\n sums << sum_array.inject(0, :+)\n n += 1\n end\n break if i == 3\n end\n result = sums.sort{|a,b| b <=> a}.first\nend",
"def cracklepop3\n (1..100).zip(Array.new 100, nil).map do |i,x|\n [i%3, i%5].map.with_index do |y, j| \n x = x.to_s + ['crackle','pop'][j] if y==0\n end\n x ? x : i\n end\nend",
"def NL43_locator(seq=\"\",temp_dir=File.dirname($0))\n hxb2_ref = \"TGGAAGGGCTAATTTGGTCCCAAAAAAGACAAGAGATCCTTGATCTGTGGATCTACCACACACAAGGCTACTTCCCTGATTGGCAGAACTACACACCAGGGCCAGGGATCAGATATCCACTGACCTTTGGATGGTGCTTCAAGTTAGTACCAGTTGAACCAGAGCAAGTAGAAGAGGCCAAATAAGGAGAGAAGAACAGCTTGTTACACCCTATGAGCCAGCATGGGATGGAGGACCCGGAGGGAGAAGTATTAGTGTGGAAGTTTGACAGCCTCCTAGCATTTCGTCACATGGCCCGAGAGCTGCATCCGGAGTACTACAAAGACTGCTGACATCGAGCTTTCTACAAGGGACTTTCCGCTGGGGACTTTCCAGGGAGGTGTGGCCTGGGCGGGACTGGGGAGTGGCGAGCCCTCAGATGCTACATATAAGCAGCTGCTTTTTGCCTGTACTGGGTCTCTCTGGTTAGACCAGATCTGAGCCTGGGAGCTCTCTGGCTAACTAGGGAACCCACTGCTTAAGCCTCAATAAAGCTTGCCTTGAGTGCTCAAAGTAGTGTGTGCCCGTCTGTTGTGTGACTCTGGTAACTAGAGATCCCTCAGACCCTTTTAGTCAGTGTGGAAAATCTCTAGCAGTGGCGCCCGAACAGGGACTTGAAAGCGAAAGTAAAGCCAGAGGAGATCTCTCGACGCAGGACTCGGCTTGCTGAAGCGCGCACGGCAAGAGGCGAGGGGCGGCGACTGGTGAGTACGCCAAAAATTTTGACTAGCGGAGGCTAGAAGGAGAGAGATGGGTGCGAGAGCGTCGGTATTAAGCGGGGGAGAATTAGATAAATGGGAAAAAATTCGGTTAAGGCCAGGGGGAAAGAAACAATATAAACTAAAACATATAGTATGGGCAAGCAGGGAGCTAGAACGATTCGCAGTTAATCCTGGCCTTTTAGAGACATCAGAAGGCTGTAGACAAATACTGGGACAGCTACAACCATCCCTTCAGACAGGATCAGAAGAACTTAGATCATTATATAATACAATAGCAGTCCTCTATTGTGTGCATCAAAGGATAGATGTAAAAGACACCAAGGAAGCCTTAGATAAGATAGAGGAAGAGCAAAACAAAAGTAAGAAAAAGGCACAGCAAGCAGCAGCTGACACAGGAAACAACAGCCAGGTCAGCCAAAATTACCCTATAGTGCAGAACCTCCAGGGGCAAATGGTACATCAGGCCATATCACCTAGAACTTTAAATGCATGGGTAAAAGTAGTAGAAGAGAAGGCTTTCAGCCCAGAAGTAATACCCATGTTTTCAGCATTATCAGAAGGAGCCACCCCACAAGATTTAAATACCATGCTAAACACAGTGGGGGGACATCAAGCAGCCATGCAAATGTTAAAAGAGACCATCAATGAGGAAGCTGCAGAATGGGATAGATTGCATCCAGTGCATGCAGGGCCTATTGCACCAGGCCAGATGAGAGAACCAAGGGGAAGTGACATAGCAGGAACTACTAGTACCCTTCAGGAACAAATAGGATGGATGACACATAATCCACCTATCCCAGTAGGAGAAATCTATAAAAGATGGATAATCCTGGGATTAAATAAAATAGTAAGAATGTATAGCCCTACCAGCATTCTGGACATAAGACAAGGACCAAAGGAACCCTTTAGAGACTATGTAGACCGATTCTATAAAACTCTAAGAGCCGAGCAAGCTTCACAAGAGGTAAAAAATTGGATGACAGAAACCTTGTTGGTCCAAAATGCGAACCCAGATTGTAAGACTATTTTAAAAGCATTGGGACCAGGAGCGACACTAGAAGAAATGATGACAGCATGTCAGGGAGTGGGGGGACCCGGCCATAAAGCAAGAGTTTTGGCTGAAGCAATGAGCCAAGTAACAAATCCAGCTACCATAATGATACAGAAAGGCAATTTTAGGAACCAAAGAAAGACTGTTAAGTGTTTCAATTGTGGCAAAGAAGGGCACATAGCCAAAAATTGCAGGGCCCCTAGGAAAAAGGGCTGTTGGAAATGTGGAAAGGAAGGACACCAAATGAAAGATTGTACTGAGAGACAGGCTAATTTTTTAGGGAAGATCTGGCCTTCCCACAAGGGAAGGCCAGGGAATTTTCTTCAGAGCAGACCAGAGCCAACAGCCCCACCAGAAGAGAGCTTCAGGTTTGGGGAAGAGACAACAACTCCCTCTCAGAAGCAGGAGCCGATAGACAAGGAACTGTATCCTTTAGCTTCCCTCAGATCACTCTTTGGCAGCGACCCCTCGTCACAATAAAGATAGGGGGGCAATTAAAGGAAGCTCTATTAGATACAGGAGCAGATGATACAGTATTAGAAGAAATGAATTTGCCAGGAAGATGGAAACCAAAAATGATAGGGGGAATTGGAGGTTTTATCAAAGTAAGACAGTATGATCAGATACTCATAGAAATCTGCGGACATAAAGCTATAGGTACAGTATTAGTAGGACCTACACCTGTCAACATAATTGGAAGAAATCTGTTGACTCAGATTGGCTGCACTTTAAATTTTCCCATTAGTCCTATTGAGACTGTACCAGTAAAATTAAAGCCAGGAATGGATGGCCCAAAAGTTAAACAATGGCCATTGACAGAAGAAAAAATAAAAGCATTAGTAGAAATTTGTACAGAAATGGAAAAGGAAGGAAAAATTTCAAAAATTGGGCCTGAAAATCCATACAATACTCCAGTATTTGCCATAAAGAAAAAAGACAGTACTAAATGGAGAAAATTAGTAGATTTCAGAGAACTTAATAAGAGAACTCAAGATTTCTGGGAAGTTCAATTAGGAATACCACATCCTGCAGGGTTAAAACAGAAAAAATCAGTAACAGTACTGGATGTGGGCGATGCATATTTTTCAGTTCCCTTAGATAAAGACTTCAGGAAGTATACTGCATTTACCATACCTAGTATAAACAATGAGACACCAGGGATTAGATATCAGTACAATGTGCTTCCACAGGGATGGAAAGGATCACCAGCAATATTCCAGTGTAGCATGACAAAAATCTTAGAGCCTTTTAGAAAACAAAATCCAGACATAGTCATCTATCAATACATGGATGATTTGTATGTAGGATCTGACTTAGAAATAGGGCAGCATAGAACAAAAATAGAGGAACTGAGACAACATCTGTTGAGGTGGGGATTTACCACACCAGACAAAAAACATCAGAAAGAACCTCCATTCCTTTGGATGGGTTATGAACTCCATCCTGATAAATGGACAGTACAGCCTATAGTGCTGCCAGAAAAGGACAGCTGGACTGTCAATGACATACAGAAATTAGTGGGAAAATTGAATTGGGCAAGTCAGATTTATGCAGGGATTAAAGTAAGGCAATTATGTAAACTTCTTAGGGGAACCAAAGCACTAACAGAAGTAGTACCACTAACAGAAGAAGCAGAGCTAGAACTGGCAGAAAACAGGGAGATTCTAAAAGAACCGGTACATGGAGTGTATTATGACCCATCAAAAGACTTAATAGCAGAAATACAGAAGCAGGGGCAAGGCCAATGGACATATCAAATTTATCAAGAGCCATTTAAAAATCTGAAAACAGGAAAATATGCAAGAATGAAGGGTGCCCACACTAATGATGTGAAACAATTAACAGAGGCAGTACAAAAAATAGCCACAGAAAGCATAGTAATATGGGGAAAGACTCCTAAATTTAAATTACCCATACAAAAGGAAACATGGGAAGCATGGTGGACAGAGTATTGGCAAGCCACCTGGATTCCTGAGTGGGAGTTTGTCAATACCCCTCCCTTAGTGAAGTTATGGTACCAGTTAGAGAAAGAACCCATAATAGGAGCAGAAACTTTCTATGTAGATGGGGCAGCCAATAGGGAAACTAAATTAGGAAAAGCAGGATATGTAACTGACAGAGGAAGACAAAAAGTTGTCCCCCTAACGGACACAACAAATCAGAAGACTGAGTTACAAGCAATTCATCTAGCTTTGCAGGATTCGGGATTAGAAGTAAACATAGTGACAGACTCACAATATGCATTGGGAATCATTCAAGCACAACCAGATAAGAGTGAATCAGAGTTAGTCAGTCAAATAATAGAGCAGTTAATAAAAAAGGAAAAAGTCTACCTGGCATGGGTACCAGCACACAAAGGAATTGGAGGAAATGAACAAGTAGATGGGTTGGTCAGTGCTGGAATCAGGAAAGTACTATTTTTAGATGGAATAGATAAGGCCCAAGAAGAACATGAGAAATATCACAGTAATTGGAGAGCAATGGCTAGTGATTTTAACCTACCACCTGTAGTAGCAAAAGAAATAGTAGCCAGCTGTGATAAATGTCAGCTAAAAGGGGAAGCCATGCATGGACAAGTAGACTGTAGCCCAGGAATATGGCAGCTAGATTGTACACATTTAGAAGGAAAAGTTATCTTGGTAGCAGTTCATGTAGCCAGTGGATATATAGAAGCAGAAGTAATTCCAGCAGAGACAGGGCAAGAAACAGCATACTTCCTCTTAAAATTAGCAGGAAGATGGCCAGTAAAAACAGTACATACAGACAATGGCAGCAATTTCACCAGTACTACAGTTAAGGCCGCCTGTTGGTGGGCGGGGATCAAGCAGGAATTTGGCATTCCCTACAATCCCCAAAGTCAAGGAGTAATAGAATCTATGAATAAAGAATTAAAGAAAATTATAGGACAGGTAAGAGATCAGGCTGAACATCTTAAGACAGCAGTACAAATGGCAGTATTCATCCACAATTTTAAAAGAAAAGGGGGGATTGGGGGGTACAGTGCAGGGGAAAGAATAGTAGACATAATAGCAACAGACATACAAACTAAAGAATTACAAAAACAAATTACAAAAATTCAAAATTTTCGGGTTTATTACAGGGACAGCAGAGATCCAGTTTGGAAAGGACCAGCAAAGCTCCTCTGGAAAGGTGAAGGGGCAGTAGTAATACAAGATAATAGTGACATAAAAGTAGTGCCAAGAAGAAAAGCAAAGATCATCAGGGATTATGGAAAACAGATGGCAGGTGATGATTGTGTGGCAAGTAGACAGGATGAGGATTAACACATGGAAAAGATTAGTAAAACACCATATGTATATTTCAAGGAAAGCTAAGGACTGGTTTTATAGACATCACTATGAAAGTACTAATCCAAAAATAAGTTCAGAAGTACACATCCCACTAGGGGATGCTAAATTAGTAATAACAACATATTGGGGTCTGCATACAGGAGAAAGAGACTGGCATTTGGGTCAGGGAGTCTCCATAGAATGGAGGAAAAAGAGATATAGCACACAAGTAGACCCTGACCTAGCAGACCAACTAATTCATCTGCACTATTTTGATTGTTTTTCAGAATCTGCTATAAGAAATACCATATTAGGACGTATAGTTAGTCCTAGGTGTGAATATCAAGCAGGACATAACAAGGTAGGATCTCTACAGTACTTGGCACTAGCAGCATTAATAAAACCAAAACAGATAAAGCCACCTTTGCCTAGTGTTAGGAAACTGACAGAGGACAGATGGAACAAGCCCCAGAAGACCAAGGGCCACAGAGGGAGCCATACAATGAATGGACACTAGAGCTTTTAGAGGAACTTAAGAGTGAAGCTGTTAGACATTTTCCTAGGATATGGCTCCATAACTTAGGACAACATATCTATGAAACTTACGGGGATACTTGGGCAGGAGTGGAAGCCATAATAAGAATTCTGCAACAACTGCTGTTTATCCATTTCAGAATTGGGTGTCGACATAGCAGAATAGGCGTTACTCGACAGAGGAGAGCAAGAAATGGAGCCAGTAGATCCTAGACTAGAGCCCTGGAAGCATCCAGGAAGTCAGCCTAAAACTGCTTGTACCAATTGCTATTGTAAAAAGTGTTGCTTTCATTGCCAAGTTTGTTTCATGACAAAAGCCTTAGGCATCTCCTATGGCAGGAAGAAGCGGAGACAGCGACGAAGAGCTCATCAGAACAGTCAGACTCATCAAGCTTCTCTATCAAAGCAGTAAGTAGTACATGTAATGCAACCTATAATAGTAGCAATAGTAGCATTAGTAGTAGCAATAATAATAGCAATAGTTGTGTGGTCCATAGTAATCATAGAATATAGGAAAATATTAAGACAAAGAAAAATAGACAGGTTAATTGATAGACTAATAGAAAGAGCAGAAGACAGTGGCAATGAGAGTGAAGGAGAAGTATCAGCACTTGTGGAGATGGGGGTGGAAATGGGGCACCATGCTCCTTGGGATATTGATGATCTGTAGTGCTACAGAAAAATTGTGGGTCACAGTCTATTATGGGGTACCTGTGTGGAAGGAAGCAACCACCACTCTATTTTGTGCATCAGATGCTAAAGCATATGATACAGAGGTACATAATGTTTGGGCCACACATGCCTGTGTACCCACAGACCCCAACCCACAAGAAGTAGTATTGGTAAATGTGACAGAAAATTTTAACATGTGGAAAAATGACATGGTAGAACAGATGCATGAGGATATAATCAGTTTATGGGATCAAAGCCTAAAGCCATGTGTAAAATTAACCCCACTCTGTGTTAGTTTAAAGTGCACTGATTTGAAGAATGATACTAATACCAATAGTAGTAGCGGGAGAATGATAATGGAGAAAGGAGAGATAAAAAACTGCTCTTTCAATATCAGCACAAGCATAAGAGATAAGGTGCAGAAAGAATATGCATTCTTTTATAAACTTGATATAGTACCAATAGATAATACCAGCTATAGGTTGATAAGTTGTAACACCTCAGTCATTACACAGGCCTGTCCAAAGGTATCCTTTGAGCCAATTCCCATACATTATTGTGCCCCGGCTGGTTTTGCGATTCTAAAATGTAATAATAAGACGTTCAATGGAACAGGACCATGTACAAATGTCAGCACAGTACAATGTACACATGGAATCAGGCCAGTAGTATCAACTCAACTGCTGTTAAATGGCAGTCTAGCAGAAGAAGATGTAGTAATTAGATCTGCCAATTTCACAGACAATGCTAAAACCATAATAGTACAGCTGAACACATCTGTAGAAATTAATTGTACAAGACCCAACAACAATACAAGAAAAAGTATCCGTATCCAGAGGGGACCAGGGAGAGCATTTGTTACAATAGGAAAAATAGGAAATATGAGACAAGCACATTGTAACATTAGTAGAGCAAAATGGAATGCCACTTTAAAACAGATAGCTAGCAAATTAAGAGAACAATTTGGAAATAATAAAACAATAATCTTTAAGCAATCCTCAGGAGGGGACCCAGAAATTGTAACGCACAGTTTTAATTGTGGAGGGGAATTTTTCTACTGTAATTCAACACAACTGTTTAATAGTACTTGGTTTAATAGTACTTGGAGTACTGAAGGGTCAAATAACACTGAAGGAAGTGACACAATCACACTCCCATGCAGAATAAAACAATTTATAAACATGTGGCAGGAAGTAGGAAAAGCAATGTATGCCCCTCCCATCAGTGGACAAATTAGATGTTCATCAAATATTACTGGGCTGCTATTAACAAGAGATGGTGGTAATAACAACAATGGGTCCGAGATCTTCAGACCTGGAGGAGGCGATATGAGGGACAATTGGAGAAGTGAATTATATAAATATAAAGTAGTAAAAATTGAACCATTAGGAGTAGCACCCACCAAGGCAAAGAGAAGAGTGGTGCAGAGAGAAAAAAGAGCAGTGGGAATAGGAGCTTTGTTCCTTGGGTTCTTGGGAGCAGCAGGAAGCACTATGGGCTGCACGTCAATGACGCTGACGGTACAGGCCAGACAATTATTGTCTGATATAGTGCAGCAGCAGAACAATTTGCTGAGGGCTATTGAGGCGCAACAGCATCTGTTGCAACTCACAGTCTGGGGCATCAAACAGCTCCAGGCAAGAATCCTGGCTGTGGAAAGATACCTAAAGGATCAACAGCTCCTGGGGATTTGGGGTTGCTCTGGAAAACTCATTTGCACCACTGCTGTGCCTTGGAATGCTAGTTGGAGTAATAAATCTCTGGAACAGATTTGGAATAACATGACCTGGATGGAGTGGGACAGAGAAATTAACAATTACACAAGCTTAATACACTCCTTAATTGAAGAATCGCAAAACCAGCAAGAAAAGAATGAACAAGAATTATTGGAATTAGATAAATGGGCAAGTTTGTGGAATTGGTTTAACATAACAAATTGGCTGTGGTATATAAAATTATTCATAATGATAGTAGGAGGCTTGGTAGGTTTAAGAATAGTTTTTGCTGTACTTTCTATAGTGAATAGAGTTAGGCAGGGATATTCACCATTATCGTTTCAGACCCACCTCCCAATCCCGAGGGGACCCGACAGGCCCGAAGGAATAGAAGAAGAAGGTGGAGAGAGAGACAGAGACAGATCCATTCGATTAGTGAACGGATCCTTAGCACTTATCTGGGACGATCTGCGGAGCCTGTGCCTCTTCAGCTACCACCGCTTGAGAGACTTACTCTTGATTGTAACGAGGATTGTGGAACTTCTGGGACGCAGGGGGTGGGAAGCCCTCAAATATTGGTGGAATCTCCTACAGTATTGGAGTCAGGAACTAAAGAATAGTGCTGTTAACTTGCTCAATGCCACAGCCATAGCAGTAGCTGAGGGGACAGATAGGGTTATAGAAGTATTACAAGCAGCTTATAGAGCTATTCGCCACATACCTAGAAGAATAAGACAGGGCTTGGAAAGGATTTTGCTATAAGATGGGTGGCAAGTGGTCAAAAAGTAGTGTGATTGGATGGCCTGCTGTAAGGGAAAGAATGAGACGAGCTGAGCCAGCAGCAGATGGGGTGGGAGCAGTATCTCGAGACCTAGAAAAACATGGAGCAATCACAAGTAGCAATACAGCAGCTAACAATGCTGCTTGTGCCTGGCTAGAAGCACAAGAGGAGGAAGAGGTGGGTTTTCCAGTCACACCTCAGGTACCTTTAAGACCAATGACTTACAAGGCAGCTGTAGATCTTAGCCACTTTTTAAAAGAAAAGGGGGGACTGGAAGGGCTAATTCACTCCCAAAGAAGACAAGATATCCTTGATCTGTGGATCTACCACACACAAGGCTACTTCCCTGATTGGCAGAACTACACACCAGGGCCAGGGGTCAGATATCCACTGACCTTTGGATGGTGCTACAAGCTAGTACCAGTTGAGCCAGATAAGGTAGAAGAGGCCAATAAAGGAGAGAACACCAGCTTGTTACACCCTGTGAGCCTGCATGGAATGGATGACCCTGAGAGAGAAGTGTTAGAGTGGAGGTTTGACAGCCGCCTAGCATTTCATCACGTGGCCCGAGAGCTGCATCCGGAGTACTTCAAGAACTGCTGACATCGAGCTTGCTACAAGGGACTTTCCGCTGGGGACTTTCCAGGGAGGCGTGGCCTGGGCGGGACTGGGGAGTGGCGAGCCCTCAGATGCTGCATATAAGCAGCTGCTTTTTGCCTGTACTGGGTCTCTCTGGTTAGACCAGATCTGAGCCTGGGAGCTCTCTGGCTAACTAGGGAACCCACTGCTTAAGCCTCAATAAAGCTTGCCTTGAGTGCTTCAAGTAGTGTGTGCCCGTCTGTTGTGTGACTCTGGTAACTAGAGATCCCTCAGACCCTTTTAGTCAGTGTGGAAAATCTCTAGCACCCAGGAGGTAGAGGTTGCAGTGAGCCAAGATCGCGCCACTGCATTCCAGCCTGGGCAAGAAAACAAGACTGTCTAAAATAATAATAATAAGTTAAGGGTATTAAATATATTTATACATGGAGGTCATAAAAATATATATATTTGGGCTGGGCGCAGTGGCTCACACCTGCGCCCGGCCCTTTGGGAGGCCGAGGCAGGTGGATCACCTGAGTTTGGGAGTTCCAGACCAGCCTGACCAACATGGAGAAACCCCTTCTCTGTGTATTTTTAGTAGATTTTATTTTATGTGTATTTTATTCACAGGTATTTCTGGAAAACTGAAACTGTTTTTCCTCTACTCTGATACCACAAGAATCATCAGCACAGAGGAAGACTTCTGTGATCAAATGTGGTGGGAGAGGGAGGTTTTCACCAGCACATGAGCAGTCAGTTCTGCCGCAGACTCGGCGGGTGTCCTTCGGTTCAGTTCCAACACCGCCTGCCTGGAGAGAGGTCAGACCACAGGGTGAGGGCTCAGTCCCCAAGACATAAACACCCAAGACATAAACACCCAACAGGTCCACCCCGCCTGCTGCCCAGGCAGAGCCGATTCACCAAGACGGGAATTAGGATAGAGAAAGAGTAAGTCACACAGAGCCGGCTGTGCGGGAGAACGGAGTTCTATTATGACTCAAATCAGTCTCCCCAAGCATTCGGGGATCAGAGTTTTTAAGGATAACTTAGTGTGTAGGGGGCCAGTGAGTTGGAGATGAAAGCGTAGGGAGTCGAAGGTGTCCTTTTGCGCCGAGTCAGTTCCTGGGTGGGGGCCACAAGATCGGATGAGCCAGTTTATCAATCCGGGGGTGCCAGCTGATCCATGGAGTGCAGGGTCTGCAAAATATCTCAAGCACTGATTGATCTTAGGTTTTACAATAGTGATGTTACCCCAGGAACAATTTGGGGAAGGTCAGAATCTTGTAGCCTGTAGCTGCATGACTCCTAAACCATAATTTCTTTTTTGTTTTTTTTTTTTTATTTTTGAGACAGGGTCTCACTCTGTCACCTAGGCTGGAGTGCAGTGGTGCAATCACAGCTCACTGCAGCCTCAACGTCGTAAGCTCAAGCGATCCTCCCACCTCAGCCTGCCTGGTAGCTGAGACTACAAGCGACGCCCCAGTTAATTTTTGTATTTTTGGTAGAGGCAGCGTTTTGCCGTGTGGCCCTGGCTGGTCTCGAACTCCTGGGCTCAAGTGATCCAGCCTCAGCCTCCCAAAGTGCTGGGACAACCGGGCCCAGTCACTGCACCTGGCCCTAAACCATAATTTCTAATCTTTTGGCTAATTTGTTAGTCCTACAAAGGCAGTCTAGTCCCCAGCAAAAAGGGGGTTTGTTTCGGGAAAGGGCTGTTACTGTCTTTGTTTCAAACTATAAACTAAGTTCCTCCTAAACTTAGTTCGGCCTACACCCAGGAATGAACAAGGAGAGCTTGGAGGTTAGAAGCACGATGGAATTGGTTAGGTCAGATCTCTTTCACTGTCTGAGTTATAATTTTGCAATGGTGGTTCAAAGACTGCCCGCTTCTGACACCAGTCGCTGCATTAATGAATCGGCCAACGCGCGGGGAGAGGCGGTTTGCGTATTGGGCGCTCTTCCGCTTCCTCGCTCACTGACTCGCTGCGCTCGGTCGTTCGGCTGCGGCGAGCGGTATCAGCTCACTCAAAGGCGGTAATACGGTTATCCACAGAATCAGGGGATAACGCAGGAAAGAACATGTGAGCAAAAGGCCAGCAAAAGGCCAGGAACCGTAAAAAGGCCGCGTTGCTGGCGTTTTTCCATAGGCTCCGCCCCCCTGACGAGCATCACAAAAATCGACGCTCAAGTCAGAGGTGGCGAAACCCGACAGGACTATAAAGATACCAGGCGTTTCCCCCTGGAAGCTCCCTCGTGCGCTCTCCTGTTCCGACCCTGCCGCTTACCGGATACCTGTCCGCCTTTCTCCCTTCGGGAAGCGTGGCGCTTTCTCATAGCTCACGCTGTAGGTATCTCAGTTCGGTGTAGGTCGTTCGCTCCAAGCTGGGCTGTGTGCACGAACCCCCCGTTCAGCCCGACCGCTGCGCCTTATCCGGTAACTATCGTCTTGAGTCCAACCCGGTAAGACACGACTTATCGCCACTGGCAGCAGCCACTGGTAACAGGATTAGCAGAGCGAGGTATGTAGGCGGTGCTACAGAGTTCTTGAAGTGGTGGCCTAACTACGGCTACACTAGAAGGACAGTATTTGGTATCTGCGCTCTGCTGAAGCCAGTTACCTTCGGAAAAAGAGTTGGTAGCTCTTGATCCGGCAAACAAACCACCGCTGGTAGCGGTGGTTTTTTTGTTTGCAAGCAGCAGATTACGCGCAGAAAAAAAGGATCTCAAGAAGATCCTTTGATCTTTTCTACGGGGTCTGACGCTCAGTGGAACGAAAACTCACGTTAAGGGATTTTGGTCATGAGATTATCAAAAAGGATCTTCACCTAGATCCTTTTAAATTAAAAATGAAGTTTTAAATCAATCTAAAGTATATATGAGTAAACTTGGTCTGACAGTTACCAATGCTTAATCAGTGAGGCACCTATCTCAGCGATCTGTCTATTTCGTTCATCCATAGTTGCCTGACTCCCCGTCGTGTAGATAACTACGATACGGGAGGGCTTACCATCTGGCCCCAGTGCTGCAATGATACCGCGAGACCCACGCTCACCGGCTCCAGATTTATCAGCAATAAACCAGCCAGCCGGAAGGGCCGAGCGCAGAAGTGGTCCTGCAACTTTATCCGCCTCCATCCAGTCTATTAATTGTTGCCGGGAAGCTAGAGTAAGTAGTTCGCCAGTTAATAGTTTGCGCAACGTTGTTGCCATTGCTACAGGCATCGTGGTGTCACGCTCGTCGTTTGGTATGGCTTCATTCAGCTCCGGTTCCCAACGATCAAGGCGAGTTACATGATCCCCCATGTTGTGCAAAAAAGCGGTTAGCTCCTTCGGTCCTCCGATCGTTGTCAGAAGTAAGTTGGCCGCAGTGTTATCACTCATGGTTATGGCAGCACTGCATAATTCTCTTACTGTCATGCCATCCGTAAGATGCTTTTCTGTGACTGGTGAGTACTCAACCAAGTCATTCTGAGAATAGTGTATGCGGCGACCGAGTTGCTCTTGCCCGGCGTCAATACGGGATAATACCGCGCCACATAGCAGAACTTTAAAAGTGCTCATCATTGGAAAACGTTCTTCGGGGCGAAAACTCTCAAGGATCTTACCGCTGTTGAGATCCAGTTCGATGTAACCCACTCGTGCACCCAACTGATCTTCAGCATCTTTTACTTTCACCAGCGTTTCTGGGTGAGCAAAAACAGGAAGGCAAAATGCCGCAAAAAAGGGAATAAGGGCGACACGGAAATGTTGAATACTCATACTCTTCCTTTTTCAATATTATTGAAGCATTTATCAGGGTTATTGTCTCATGAGCGGATACATATTTGAATGTATTTAGAAAAATAAACAAATAGGGGTTCCGCGCACATTTCCCCGAAAAGTGCCACCTGACGTCTAAGAAACCATTATTATCATGACATTAACCTATAAAAATAGGCGTATCACGAGGCCCTTTCGTCTCGCGCGTTTCGGTGATGACGGTGAAAACCTCTGACACATGCAGCTCCCGGAGACGGTCACAGCTTGTCTGTAAGCGGATGCCGGGAGCAGACAAGCCCGTCAGGGCGCGTCAGCGGGTGTTGGCGGGTGTCGGGGCTGGCTTAACTATGCGGCATCAGAGCAGATTGTACTGAGAGTGCACCATATGCGGTGTGAAATACCGCACAGATGCGTAAGGAGAAAATACCGCATCAGGCGCCATTCGCCATTCAGGCTGCGCAACTGTTGGGAAGGGCGATCGGTGCGGGCCTCTTCGCTATTACGCCAGGGGAGGCAGAGATTGCAGTAAGCTGAGATCGCAGCACTGCACTCCAGCCTGGGCGACAGAGTAAGACTCTGTCTCAAAAATAAAATAAATAAATCAATCAGATATTCCAATCTTTTCCTTTATTTATTTATTTATTTTCTATTTTGGAAACACAGTCCTTCCTTATTCCAGAATTACACATATATTCTATTTTTCTTTATATGCTCCAGTTTTTTTTAGACCTTCACCTGAAATGTGTGTATACAAAATCTAGGCCAGTCCAGCAGAGCCTAAAGGTAAAAAATAAAATAATAAAAAATAAATAAAATCTAGCTCACTCCTTCACATCAAAATGGAGATACAGCTGTTAGCATTAAATACCAAATAACCCATCTTGTCCTCAATAATTTTAAGCGCCTCTCTCCACCACATCTAACTCCTGTCAAAGGCATGTGCCCCTTCCGGGCGCTCTGCTGTGCTGCCAACCAACTGGCATGTGGACTCTGCAGGGTCCCTAACTGCCAAGCCCCACAGTGTGCCCTGAGGCTGCCCCTTCCTTCTAGCGGCTGCCCCCACTCGGCTTTGCTTTCCCTAGTTTCAGTTACTTGCGTTCAGCCAAGGTCTGAAACTAGGTGCGCACAGAGCGGTAAGACTGCGAGAGAAAGAGACCAGCTTTACAGGGGGTTTATCACAGTGCACCCTGACAGTCGTCAGCCTCACAGGGGGTTTATCACATTGCACCCTGACAGTCGTCAGCCTCACAGGGGGTTTATCACAGTGCACCCTTACAATCATTCCATTTGATTCACAATTTTTTTAGTCTCTACTGTGCCTAACTTGTAAGTTAAATTTGATCAGAGGTGTGTTCCCAGAGGGGAAAACAGTATATACAGGGTTCAGTACTATCGCATTTCAGGCCTCCACCTGGGTCTTGGAATGTGTCCCCCGAGGGGTGATGACTACCTCAGTTGGATCTCCACAGGTCACAGTGACACAAGATAACCAAGACACCTCCCAAGGCTACCACAATGGGCCGCCCTCCACGTGCACATGGCCGGAGGAACTGCCATGTCGGAGGTGCAAGCACACCTGCGCATCAGAGTCCTTGGTGTGGAGGGAGGGACCAGCGCAGCTTCCAGCCATCCACCTGATGAACAGAACCTAGGGAAAGCCCCAGTTCTACTTACACCAGGAAAGGC\"\n hxb2_l = hxb2_ref.size\n head = \"\"\n 8.times {head << (65 + rand(25)).chr}\n temp_file = temp_dir + \"/temp\"\n temp_aln = temp_dir + \"/temp_aln\"\n\n l1 = 0\n l2 = 0\n name = \">test\"\n temp_in = File.open(temp_file,\"w\")\n temp_in.puts \">ref\"\n temp_in.puts hxb2_ref\n temp_in.puts name\n temp_in.puts seq\n temp_in.close\n\n print `muscle -in #{temp_file} -out #{temp_aln} -quiet`\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n aln_test =~ /^(\\-*)(\\w.*\\w)(\\-*)$/\n gap_begin = $1.size\n gap_end = $3.size\n aln_test2 = $2\n ref = aln_seq[\">ref\"]\n ref = ref[gap_begin..(-gap_end-1)]\n ref_size = ref.size\n if ref_size > 1.3*(seq.size)\n l1 = l1 + gap_begin\n l2 = l2 + gap_end\n max_seq = aln_test2.scan(/[ACGT]+/).max_by(&:length)\n aln_test2 =~ /#{max_seq}/\n before_aln_seq = $`\n before_aln = $`.size\n post_aln_seq = $'\n post_aln = $'.size\n before_aln_seq_size = before_aln_seq.scan(/[ACGT]+/).join(\"\").size\n b1 = (1.3 * before_aln_seq_size).to_i\n post_aln_seq_size = post_aln_seq.scan(/[ACGT]+/).join(\"\").size\n b2 = (1.3 * post_aln_seq_size).to_i\n if (before_aln > seq.size) and (post_aln <= seq.size)\n ref = ref[(before_aln - b1)..(ref_size - post_aln - 1)]\n l1 = l1 + (before_aln - b1)\n elsif (post_aln > seq.size) and (before_aln <= seq.size)\n ref = ref[before_aln..(ref_size - post_aln - 1 + b2)]\n l2 = l2 + post_aln - b2\n elsif (post_aln > seq.size) and (before_aln > seq.size)\n ref = ref[(before_aln - b1)..(ref_size - post_aln - 1 + b2)]\n l1 = l1 + (before_aln - b1)\n l2 = l2 + (post_aln - b2)\n end\n temp_in = File.open(temp_file,\"w\")\n temp_in.puts \">ref\"\n temp_in.puts ref\n temp_in.puts name\n temp_in.puts seq\n temp_in.close\n print `muscle -in #{temp_file} -out #{temp_aln} -quiet`\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n aln_test =~ /^(\\-*)(\\w.*\\w)(\\-*)$/\n gap_begin = $1.size\n gap_end = $3.size\n aln_test2 = $2\n ref = aln_seq[\">ref\"]\n ref = ref[gap_begin..(-gap_end-1)]\n ref_size = ref.size\n end\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n aln_test =~ /^(\\-*)(\\w.*\\w)(\\-*)$/\n gap_begin = $1.size\n gap_end = $3.size\n aln_test = $2\n aln_test =~ /^(\\w+)(\\-*)\\w/\n s1 = $1.size\n g1 = $2.size\n aln_test =~ /\\w(\\-*)(\\w+)$/\n s2 = $2.size\n g2 = $1.size\n ref = aln_seq[\">ref\"]\n ref = ref[gap_begin..(-gap_end-1)]\n\n l1 = l1 + gap_begin\n l2 = l2 + gap_end\n repeat = 0\n\n if g1 == g2 and (s1 + g1 + s2) == ref.size\n if s1 > s2 and g2 > 2*s2\n ref = ref[0..(-g2-1)]\n repeat = 1\n l2 = l2 + g2\n elsif s1 < s2 and g1 > 2*s1\n ref = ref[g1..-1]\n repeat = 1\n l1 = l1 + g1\n end\n else\n if g1 > 2*s1\n ref = ref[g1..-1]\n repeat = 1\n l1 = l1 + g1\n end\n if g2 > 2*s2\n ref = ref[0..(-g2 - 1)]\n repeat = 1\n l2 = l2 + g2\n end\n end\n\n while repeat == 1\n temp_in = File.open(temp_file,\"w\")\n temp_in.puts \">ref\"\n temp_in.puts ref\n temp_in.puts name\n temp_in.puts seq\n temp_in.close\n print `muscle -in #{temp_file} -out #{temp_aln} -quiet`\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n aln_test =~ /^(\\-*)(\\w.*\\w)(\\-*)$/\n gap_begin = $1.size\n gap_end = $3.size\n aln_test = $2\n aln_test =~ /^(\\w+)(\\-*)\\w/\n s1 = $1.size\n g1 = $2.size\n aln_test =~ /\\w(\\-*)(\\w+)$/\n s2 = $2.size\n g2 = $1.size\n ref = aln_seq[\">ref\"]\n ref = ref[gap_begin..(-gap_end-1)]\n l1 = l1 + gap_begin\n l2 = l2 + gap_end\n repeat = 0\n if g1 > 2*s1\n ref = ref[g1..-1]\n repeat = 1\n l1 = l1 + g1\n end\n if g2 > 2*s2\n ref = ref[0..(-g2 - 1)]\n repeat = 1\n l2 = l2 + g2\n end\n end\n ref = hxb2_ref[l1..(hxb2_l - l2 - 1)]\n\n temp_in = File.open(temp_file,\"w\")\n temp_in.puts \">ref\"\n temp_in.puts ref\n temp_in.puts name\n temp_in.puts seq\n temp_in.close\n print `muscle -in #{temp_file} -out #{temp_aln} -quiet`\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n ref = aln_seq[\">ref\"]\n\n #refine alignment\n\n if ref =~ /^(\\-+)/\n l1 = l1 - $1.size\n elsif ref =~ /(\\-+)$/\n l2 = l2 + $1.size\n end\n l1 = 0 if l1 < 0\n if (hxb2_l - l2 - 1) >= l1\n ref = hxb2_ref[l1..(hxb2_l - l2 - 1)]\n temp_in = File.open(temp_file,\"w\")\n temp_in.puts \">ref\"\n temp_in.puts ref\n temp_in.puts name\n temp_in.puts seq\n temp_in.close\n print `muscle -in #{temp_file} -out #{temp_aln} -quiet`\n aln_seq = fasta_to_hash(temp_aln)\n aln_test = aln_seq[name]\n ref = aln_seq[\">ref\"]\n\n ref_size = ref.size\n sim_count = 0\n (0..(ref_size-1)).each do |n|\n ref_base = ref[n]\n test_base = aln_test[n]\n sim_count += 1 if ref_base == test_base\n end\n similarity = (sim_count/ref_size.to_f*100).round(1)\n print `rm -f #{temp_file}`\n print `rm -f #{temp_aln}`\n loc_p1 = l1 + 1\n loc_p2 = hxb2_l - l2\n if seq.size != (loc_p2 - loc_p1 + 1)\n indel = true\n elsif aln_test.include?(\"-\")\n indel = true\n end\n return [loc_p1,loc_p2,similarity,indel,aln_test,ref]\n else\n return [0,0,0,0,0,0,0]\n end\nrescue\n return [0,0,0,0,\"N\",\"N\"]\nend",
"def dominant_octopus(fish)\n #sorted = []\n return fish if fish.length < 2\n pivot = fish.first\n left = fish[1..-1].select { |feesh| feesh.length <= pivot.length }\n #p left\n right = fish[1..-1].select { |feesh| feesh.length > pivot.length }\n\n dominant_octopus(left) + [pivot] + dominant_octopus(right)\n \n\n\nend",
"def nexus(hsh)\n nexus = []\n hsh.each do |k, v|\n nexus << k if k == v\n end\n\n return nexus.min if nexus.empty? == false\n \n difference = 1\n loop do\n\n hsh.each do |k, v|\n if k - v == difference || v - k == difference\n nexus << k\n else\n next\n end\n end\n\n if nexus.empty?\n difference += 1\n else\n return nexus.min\n end\n end\nend",
"def solution(s, p, q)\r\n # write your code in Ruby 2.2\r\n # A -1\r\n # C -2\r\n # G -3\r\n # T -4\r\n # s - string with n charactekrs\r\n #cagccta\r\n #0123345\r\n #p,q - not empty arrays\r\n #\r\n #p[0]=2 q[0]=4 gcc 322 => 2\r\n #p[1]=5 q[1]=5 t 4 => 4\r\n \r\n \r\n arr = Array.new(q.count)\r\n \r\n \r\n\r\n \r\n arr.each_with_index{|el, i|\r\n \r\n ss = s[p[i]..q[i]]\r\n \r\n if ss.index('A') \r\n n = 1\r\n elsif ss.index('C')\r\n n=2\r\n elsif ss.index('G')\r\n n=3\r\n else \r\n n=4\r\n end\r\n \r\n arr[i] = n\r\n \r\n }\r\n \r\n \r\n \r\n arr\r\n \r\nend",
"def transform line\n i = 1\n tortoise = line[i]\n hare = line[i * 2]\n while tortoise != hare\n i += 1\n tortoise = line[i]\n hare = line[i * 2]\n end\n v = i\n\n mu = 0\n tortoise = line[mu]\n hare = line[v * 2 + mu]\n while tortoise != hare\n mu += 1\n tortoise = line[mu]\n hare = line[v * 2 + mu]\n end\n\n lam = 1\n hare = line[mu + lam]\n while tortoise != hare\n lam += 1\n hare = line[mu + lam]\n end\n #puts \"v mu lam %d %d %d\" % [v, mu, lam]\n \n line[mu, lam] \nend",
"def find_small_set_of_string_in_large_string( large_string, small_string_set)\n \n #create and array of size L,\n small_string_size = small_string_set[0].size\n window_array = []\n \n (0..small_string_size-1).each do |index|\n window_array[index] = {}\n end\n \n #build dthe window array as we look a all the small string in a set\n small_string_set.each do |str|\n (0..str.size - 1).each do |index|\n if !window_array[index].has_key? str[index] \n #create new hash\n window_array[index][str[index]]={}\n end\n window_array[index][str[index]][str] = str\n end\n end\n\n all_found = []\n (0..large_string.size - small_string_size).each do |window_start|\n found_set = []\n first_set = true\n qualified_length = 0\n\n (window_start..window_start + small_string_size -1 ).each do |index|\n \n #puts \"String start at index #{window_start} '#{\"\"<<large_string[window_start]}'\"\n \n if window_array[ index - window_start ].has_key? large_string[index ]\n if first_set \n window_array[ index - window_start ][large_string[index]].each do |key, val|\n found_set.push(key)\n end\n first_set = false\n else\n window_array[ index - window_start ][large_string[index]].each do |key, val|\n if !found_set.include? key\n found_set.delete(key)\n end\n end\n end\n qualified_length += 1 if !found_set.empty? #suvire from the delete, increase the qualified lenghth\n elsif first_set == false and found_set.empty?\n #puts \"stop examing 1\"\n break\n else\n #puts \"stop examing 2 -- #{window_start.to_s} #{index.to_s}\"\n break\n end\n end #end of exampling each slow of the window\n #only print and save qualify string\n #p qualified_length , window_array.size\n if qualified_length == window_array.size\n all_found = all_found | found_set\n \n #puts \"Found:\" + found_set.join(\",\")\n end\n \n end\n #p window_array\n return all_found\nend",
"def awesome(arr, target)\n hash = Hash.new(0)\n i = 0\n j = i + 1\n while i < arr.size\n hash[arr[i] + arr[j]] += 1 \n if j < arr.size\n j += 1\n else\n i += 1\n if j = i + 1 > arr.length\n j = i \n else\n j = i + 1\n \n end\n\n end\n \n end\n return true if hash[target] >= 1\n false\nend",
"def checkmate(k,a)\n # Checkmate test where king may be: k_attacks - used - king_attaks - cells_behind_the_king\n all = all_position\n p used = [k,a]\n k_attacks = king_position(k).uniq \n a_attacks = (amazon_postion(a) - free_cells(k,a)).uniq\n stand_positions = a_attacks - k_attacks - used\n safe_squares = (all - k_attacks - a_attacks - used).uniq\n ans = stand_positions.reduce([]){ |acc,x| \n if (safe_squares & king_position(x)).empty?\n p x\n acc.push(x) \n end\n acc\n }\n p ans\n ans.size\n \nend",
"def am(amida, y, x)\n #p \"==== NOW ===\"\n #p y \n #p x\n #p amida\n\n if y == H \n #p \"=====GOAL\"\n if x + 1 == K\n $cnt = $cnt + 1\n end\n return\n end\n\n if x < W - 1\n to_right_amida = Marshal.load(Marshal.dump(amida))\n to_right_amida[y][x] = 1\n am(to_right_amida, y + 1, x + 1)\n end\n\n to_streight_amida = Marshal.load(Marshal.dump(amida))\n am(to_streight_amida, y + 1, x)\n\n if x > 0\n to_left_amida = Marshal.load(Marshal.dump(amida))\n to_left_amida[y][x - 1] = 1\n am(to_left_amida, y + 1, x - 1)\n end\nend",
"def decodeHalfway(input)\n sum = 0\n\n # Only have to loop through half the array since the numbers are being compared halfway around\n # Multiply each matching character by 2 to compensate for not looping through its pair\n input.chars[0..input.length/2 - 1].each_with_index do |char, i|\n sum += 2*char.to_i if char == input[i + input.length/2]\n end\n sum\nend",
"def locator2(image)\n result = []\n how_wide = image.first.length\n how_long = image.length\n\n image.each_with_index do |e, i|\n e.each_with_index do |e2, i2|\n next unless e2.zero? && no_overlaps?(result, i, i2)\n answer = {\n corner: [i, i2],\n height: 1,\n width: 1\n }\n result << answer\n\n lookahead = i2 + 1\n until lookahead >= how_wide || e[lookahead] == 1\n answer[:width] += 1\n lookahead += 1\n end\n\n lookdown = i + 1\n until lookdown >= how_long || image[lookdown][i2] == 1\n answer[:height] += 1\n lookdown += 1\n end\n end\n end\n p result\n result\nend",
"def sentinel_rt (aa_array,start_aa=1)\n out_hash = {}\n sen = {15=>\"KRS\", 16=>\"I\", 17=>\"N\", 18=>\"KRS\", 24=>\"*\", 41=>\"I\", 42=>\"KN\", 45=>\"KR\", 51=>\"KR\", 53=>\"K\", 71=>\"*\", 76=>\"K\", 79=>\"K\", 86=>\"K\", 88=>\"*\", 89=>\"KN\", 93=>\"EKR\", 99=>\"EKRS\", 110=>\"KN\", 112=>\"EKRS\", 113=>\"K\", 141=>\"EKRS\", 152=>\"EKRS\", 153=>\"*\", 155=>\"EKRS\", 185=>\"KN\", 186=>\"KN\", 190=>\"R\", 192=>\"K\", 212=>\"*\", 213=>\"KR\", 229=>\"*\", 231=>\"KRS\", 233=>\"K\", 239=>\"*\", 252=>\"*\", 256=>\"KN\", 262=>\"KR\", 266=>\"*\", 273=>\"EKS\", 285=>\"EKR\", 298=>\"N\", 302=>\"KN\", 305=>\"KN\", 316=>\"EKR\", 324=>\"K\", 337=>\"*\", 344=>\"K\", 352=>\"EKRS\", 364=>\"KN\", 378=>\"N\", 383=>\"*\", 384=>\"EKRS\", 396=>\"K\", 398=>\"*\", 401=>\"*\", 402=>\"*\", 404=>\"K\", 406=>\"*\", 410=>\"*\", 413=>\"KN\", 414=>\"*\", 415=>\"KN\", 426=>\"*\", 430=>\"KN\", 436=>\"R\", 438=>\"K\", 443=>\"N\", 444=>\"EKRS\", 449=>\"K\", 453=>\"KR\", 456=>\"EKRS\", 462=>\"ERS\", 471=>\"K\", 478=>\"KN\", 488=>\"K\", 490=>\"R\", 498=>\"KN\", 504=>\"KRS\", 511=>\"K\", 514=>\"K\", 516=>\"N\", 523=>\"KN\", 535=>\"*\", 541=>\"EKRS\", 543=>\"EKRS\", 544=>\"ERS\", 546=>\"N\", 549=>\"KN\", 555=>\"EKRS\"}\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sen.keys.include?(position)\n test_aa = aa_array[array_position]\n if sen[position].include?(test_aa)\n out_hash[position] = test_aa\n end\n end\n end\n return out_hash\nend",
"def euler66\n max = 0\n val = 0\n min = 0 \n set = Set.new\n vec = [] \n (2..1000).each do |r|\n num = 1\n \n set.clear()\n vec.clear() \n\n sr = Math.sqrt(r)\n min = val = sr.floor\n\n next if min*min==r\n\n print \"#{r}: \" if $debug\n\n num = ( r - val*val ) / num\n \n #print \"(#{num})\"\n\n tval = 0 \n tmin = -min\n while ( ( sr - tmin ) / num ) > 1\n tval += 1\n tmin += num\n #print \"#{tmin} #{( ( sr - tmin ) / num )}\"\n end\n min = tmin \n val = tval\n\n print \"(#{tval}_#{min}_#{num})\" if $debug\n set.add(\"#{tval}_#{min}_#{num}\")\n vec.push(tval)\n\n # This section get from Euler64\n freq = 1\n while true\n num = ( r - min*min ) / num\n \n tval = 0 \n tmin = -min\n while ( ( sr - tmin ) / num ) > 1\n tval += 1\n tmin += num\n end\n min = tmin \n val = tval\n\n str = \"#{tval}_#{min}_#{num}\"\n break if set.include?(str) \n print \" (#{str})\" if $debug\n set.add(str)\n vec.push(tval)\n freq += 1\n end\n print \" # #{freq}\" if $debug\n\n num = 1\n if vec.size==1\n den = vec.last\n lnum = 2 \n vec.reverse.drop(lnum).each do |v|\n tval = den\n den = v*den + num \n num = tval \n end\n num = sr.floor * den + num \n else \n n = vec.size\n vec_ = vec + vec # One frequent section is not enough\n\n # variable backup\n tden = den \n tnum = num\n\n # We need to continue trying ... \n (n..2*n).each do |nn|\n tvec = vec_[0..nn-1]\n den = tvec.reverse.drop(1).last\n tvec.reverse.drop(2).each do |v|\n tval = den\n den = v*den + num \n num = tval \n end\n num = sr.floor * den + num\n \n break if (num*num-den*den*r)==1 # Check if this fraction is any \n den = tden \n num = tnum\n end \n end\n \n puts \" => #{num} #{den} \" if $debug\n\n if max < num \n $ans = r\n max = num\n end\n end\nend",
"def minimumBribes(q)\n count = 0\n q.each_with_index do |element, index|\n return 'Too chaotic' if element-index-1>2\n start_index = index < 100 ? 0 : index-100\n\n (start_index..index-1).each do |x|\n count +=1 if q[x] > element\n end\n end \n count\nend",
"def stderrs; end",
"def derive_moves_metadata(s)\n # puts \"Deriving move metadata...\" #NICE TO HAVE\n known_moves = Array.new(s[:num_moves]) {|e| e = {x: -1, y: -1}}\n unknown_moves = [*1..s[:num_moves]]\n for y in 0...s[:moves].length do\n row = s[:moves][y]\n for x in 0...row.length do\n if s[:moves][y][x] > 0\n known_moves[s[:moves][y][x]-1] = {x: x, y: y}\n unknown_moves = unknown_moves - [s[:moves][y][x]]\n end\n end\n end\n m = -1\n if not unknown_moves.empty?\n m = unknown_moves[0]\n end\n next_highest_known_m = -1\n for i in m...known_moves.length do\n if known_moves[i][:x] != -1\n next_highest_known_m = i\n break\n end\n end\n next_highest_unknown_m = -1\n unknown_moves.each do |unknown_move|\n if unknown_move >= m\n next_highest_unknown_m = unknown_move\n break\n end\n end\n # I'm really bothered by this part, but as stated up top, this is being done\n # for the sake of simplicity for now, and will be refactored later...\n r_known_cells = Array.new(s[:r_num_cells].length) {|e| e = Array.new()}\n r_free_cells = s[:r_num_cells].clone\n for i in 0...known_moves.length do\n next if known_moves[i][:x] == -1\n r = s[:regions][known_moves[i][:y]][known_moves[i][:x]]\n r_free_cells[r] -= 1\n r_known_cells[r].push(i+1)\n end\n s[:m] = m\n s[:known_moves] = known_moves\n s[:unknown_moves] = unknown_moves\n s[:next_highest_known_m] = next_highest_known_m\n s[:next_highest_unknown_m] = next_highest_unknown_m\n s[:r_known_cells] = r_known_cells\n s[:r_free_cells] = r_free_cells\nend",
"def movingShift(s, shift)\nres = ''\n s.chars.each do |x|\n ord = x.ord\n if x.ord > 64 && x.ord < 91\n ord = ((ord - 65 + shift) % 26) + 65\n else\n if x.ord > 96 && x.ord < 123\n ord = ((ord - 97 + shift) % 26) + 97\n end\n end\n shift+=1\n res += ord.chr\n end\n l = (res.length/5.0).ceil\nputs l\nputs res\n [res[0..l-1], res[l..2*len-1],res[2*l..3*l-1],res[3*l..4*len-1],res[4*l..-1]]\nend",
"def solution(a)\n accessed = Array.new(a.size + 1, nil)\n caterpillar_back = 0\n count = 0\n\n a.each_with_index do |x, caterpillar_front|\n if accessed[x] == nil\n accessed[x] = caterpillar_front\n else\n new_caterpillar_back = accessed[x] + 1\n first_part_size = caterpillar_front - caterpillar_back\n second_part_size = caterpillar_front - new_caterpillar_back\n count += first_part_size * (first_part_size + 1) / 2\n count -= (second_part_size) * (second_part_size + 1) / 2\n caterpillar_back.upto(new_caterpillar_back - 1) { |n| accessed[a[n]] = nil}\n accessed[x] = caterpillar_front\n caterpillar_back = new_caterpillar_back\n end\n end\n\n remaining_size = a.size - caterpillar_back\n count += (remaining_size) * (remaining_size + 1) / 2\n end",
"def better_sum1(arr, target) # this one is going to return true or false\n pairs = Set.new\n\n arr.each do |ele|\n if pairs.include?(ele)\n return true\n else\n pairs << target - ele\n end\n end\n false\nend",
"def _reduce_684(val, _values, result)\n result = [ @builder.kwnilarg(val[0][0], val[0][1]) ]\n \n result\nend",
"def check_duplication (n=10)\n\n # get the first n hits\n less_hits = @hits[0..[n-1,@hits.length].min]\n averages = []\n\n less_hits.each do |hit|\n # indexing in blast starts from 1\n start_match_interval = hit.hsp_list.each.map{|x| x.hit_from}.min - 1\n end_match_interval = hit.hsp_list.map{|x| x.hit_to}.max - 1\n \n #puts \"#{hit.xml_length} #{start_match_interval} #{end_match_interval}\" \n\n coverage = Array.new(hit.xml_length,0)\n hit.hsp_list.each do |hsp|\n aux = []\n # for each hsp\n # iterate through the alignment and count the matching residues\n [*(0 .. hsp.align_len-1)].each do |i|\n residue_hit = hsp.hit_alignment[i]\n residue_query = hsp.query_alignment[i]\n if residue_hit != ' ' and residue_hit != '+' and residue_hit != '-'\n if residue_hit == residue_query \n idx = i + (hsp.hit_from-1) - hsp.hit_alignment[0..i].scan(/-/).length \n aux.push(idx)\n #puts \"#{idx} #{i} #{hsp.hit_alignment[0..i].scan(/-/).length}\"\n # indexing in blast starts from 1\n coverage[idx] += 1\n end\n end\n end\n end\n overlap = coverage.reject{|x| x==0}\n averages.push(overlap.inject(:+)/(overlap.length + 0.0))\n end\n \n # if all hsps match only one time\n if averages.reject{|x| x==1} == []\n return [\"NO\",1]\n end\n\n R.eval(\"library(preprocessCore)\")\n\n #make the wilcox-test and get the p-value\n R.eval(\"coverageDistrib = c#{averages.to_s.gsub('[','(').gsub(']',')')}\")\n R. eval(\"pval = wilcox.test(coverageDistrib - 1)$p.value\")\n pval = R.pull \"pval\"\n\n if pval < 0.01\n status = \"YES\"\n else\n status = \"NO\"\n end\n return [status, pval]\n end",
"def winner(array)\n\n win_x_combo = nil\n win_o_combo = nil\n xs = []\n os = []\n\n def x_extractor_helper(array, index) \n array.select.with_index.select do |j, index| \n j == \"X\" || j == \" X \"\n end\n end\n\n def o_extractor_helper(array, index) \n array.select.with_index.select do |j, index| #// or each_with_index\n j == \"O\" || j == \" O \"\n end\n end\n\n def array_dividing_helper_method(array) # need to go a level deeper in array to access [\"a\", 1] ?!\n output_array = []\n array.each do | index0 |\n output_array << index0[1] # need output_array to be local variable??! \n end \n #end # OLD ending to array_dividing_helper_method\n return output_array\n end # ends array_dividing_helper_method\n\n\n xs = array_dividing_helper_method(x_extractor_helper(array, array))\n os = array_dividing_helper_method(o_extractor_helper(array, array))\n\n WIN_COMBINATIONS.each do |combo|\n #os.all? # Instead, try \"os contains WIN_COMBINATIONS[i][0] and WIN_COMBINATIONS[i][1] and [i][2] \"\n if ( ( xs.include?(combo[0]) ) && ( xs.include?(combo[1]) ) ) # was win_x_combo, not xs\n if ( xs.include?(combo[2]) )\n #puts \"Winning X Combo is #{combo} \"\n win_x_combo = combo\n #return combo\n else puts \"No x Win Combination. current combo is #{combo}\"\n end\n end\n end\n \n WIN_COMBINATIONS.each do |combo|\n if ( ( os.include?(combo[0]) ) && ( os.include?(combo[1]) ) ) \n if ( os.include?(combo[2]) )\n #puts \"Winning O Combo is #{combo} \"\n win_o_combo = combo\n #return combo\n #else puts \"No o Win Combination\"\n end\n end\n end \n\n\n if ( win_x_combo != nil )\n puts \" X Won!\"\n return \"X\"\n end\n\n if ( win_o_combo != nil )\n puts \" O Won!\"\n return \"O\"\n else puts (\"No winner\") and\n return nil\n end\n\n\nend",
"def solution\n (1..40).inject(:*) / (1..20).inject(:*)**2\nend",
"def _reduce_656(val, _values, result)\n result = [ @builder.kwnilarg(val[0], val[1]) ]\n \n result\nend",
"def getMostOccur \n tmpArry=[]\n tmpWArry=[];\n\t @maxparam =0 #use for store the param\n @maxelement =0 #use for store the element\n\t\t i=0\n while i<@parameters.paramsArr.length do\n \t temelementslength = @parameters.paramsArr[i].elementsArr.length\t\n \t j=0\n while j < temelementslength do\t\t\n if @parameters.paramsArr[i].elementsArr[j].times == @parameters.paramsArr[@maxparam].elementsArr[@maxelement].times\n \n tmpArry << [i , j]\n elsif @parameters.paramsArr[i].elementsArr[j].times > @parameters.paramsArr[@maxparam].elementsArr[@maxelement].times\n tmpArry.clear\n tmpArry << [i , j]\n\t\t \t @maxparam = i \n @maxelement = j\n end\t \n j+=1\n end\n i+=1\n end\n #add by chuangye -----------------------------start\n if @useweight==1\n maxweight=@parameters.paramsArr[tmpArry[0][0]].elementsArr[tmpArry[0][1]].weight\n for k in 0...tmpArry.length do\n if @parameters.paramsArr[tmpArry[k][0]].elementsArr[tmpArry[k][1]].weight==maxweight\n tmpWArry << tmpArry[k]\n elsif @parameters.paramsArr[tmpArry[k][0]].elementsArr[tmpArry[k][1]].weight>maxweight\n tmpWArry.clear\n tmpWArry << tmpArry[k]\n end\n end\n tmp=randchar(0,tmpWArry.length-1)\n @maxparam = tmpWArry[tmp][0]\n @maxelement = tmpWArry[tmp][1]\n else\n #add by chuangye -----------------------------end\n tmp = randchar(0 , tmpArry.length-1)\n @maxparam = tmpArry[tmp][0]\n @maxelement = tmpArry[tmp][1]\n end\n end",
"def two_sum_big_gun(array, target)\n nums = Hash.new(0)\n\n array.each do |el|\n nums[el] += 1\n end\n\n array.any? do |el|\n wing = target - el\n nums[wing] > 0\n end\n\nend",
"def fours\r\n left, right = self.pops self.size/3\r\n left.twos + right.twos\r\n end",
"def solution(arr)\n temp_hash_odd_balls = {}\n\n arr.each { |el| temp_hash_odd_balls[el] ? temp_hash_odd_balls.delete(el) : temp_hash_odd_balls[el] = 0 }\n\n temp_hash_odd_balls.keys.first\nend",
"def problem_104\n all = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n k = 2\n low_fn0,low_fn1 = 1,1\n hi_fn0,hi_fn1 = 1,1\n loop do\n k += 1\n low_fn0,low_fn1 =(low_fn0 + low_fn1) % 10_000_000_000, low_fn0\n hi_fn0, hi_fn1 = hi_fn0 + hi_fn1, hi_fn0\n if hi_fn0 > 1_000_000_000_000_000_000\n hi_fn0 /= 10\n hi_fn1 /= 10\n end\n front = false\n next unless k > 300\n hi = hi_fn0.to_s[0,9].split(//)\n if (hi & all).length == 9\n puts \"front #{k}\" \n front = true\n end\n if (low = low_fn0.to_s).length >= 9\n low = low[-9,9].split(//)\n if (low & all).length == 9\n puts \"back #{k}\" \n return k if front\n end\n end\n end\nend",
"def minimumBribes(q)\n cont = 0\n for i in (q.size-1).downto(2)\n #p \" (#{i}) ==> #{q}\"\n if !v(q,i)\n cont = \"Too chaotic\"\n break\n elsif q[i]-1 != i\n if q[i-1]-1 == i \n aux = q[i]\n q[i] = q[i-1]\n q[i-1] = aux\n else\n aux = q[i]\n q[i] = q[i-2]\n q[i-2] = q[i-1]\n q[i-1] = aux\n cont += 1 \n end\n cont += 1 \n end\n end\n printf \"%s\\n\", q[0] != 1 && cont != \"Too chaotic\" ? cont+1 : cont\nend",
"def walkhigh(i,j,object)\r\n w=0\r\n counter =4\r\n while w < 4\r\n if @nha2[i][j+w] == object\r\n counter =counter -1\r\n end\r\n w+=1\r\n end\r\n return counter\r\n end"
] |
[
"0.6287924",
"0.567249",
"0.56470215",
"0.56470215",
"0.56470215",
"0.56470215",
"0.56470215",
"0.5637161",
"0.5600668",
"0.557326",
"0.55539596",
"0.5537526",
"0.55296856",
"0.5529109",
"0.5520327",
"0.551692",
"0.5516786",
"0.5513311",
"0.54849905",
"0.54689443",
"0.5456625",
"0.54493207",
"0.54493207",
"0.54493207",
"0.54493207",
"0.54036146",
"0.5401421",
"0.53896904",
"0.53879464",
"0.53838766",
"0.5362948",
"0.53603107",
"0.5357687",
"0.53394294",
"0.533765",
"0.5334681",
"0.53212637",
"0.5318725",
"0.53144354",
"0.530204",
"0.530176",
"0.5300285",
"0.52992016",
"0.5297691",
"0.528544",
"0.5284442",
"0.5281388",
"0.52778846",
"0.52725536",
"0.5268538",
"0.5255658",
"0.524753",
"0.52430815",
"0.5239928",
"0.5239272",
"0.52390325",
"0.5236037",
"0.52352494",
"0.5233224",
"0.5227236",
"0.5224845",
"0.52206767",
"0.52193415",
"0.5212603",
"0.5211988",
"0.52083707",
"0.52040434",
"0.5203587",
"0.52002174",
"0.5196411",
"0.5195471",
"0.5194325",
"0.51929575",
"0.5191691",
"0.5189787",
"0.5181181",
"0.5179345",
"0.51686925",
"0.5167552",
"0.51668274",
"0.51665604",
"0.5163153",
"0.51596135",
"0.5151518",
"0.5144897",
"0.51429707",
"0.51424456",
"0.5138418",
"0.51377535",
"0.5134783",
"0.5131166",
"0.5130031",
"0.5128952",
"0.51241726",
"0.5120184",
"0.51178885",
"0.511764",
"0.5112753",
"0.5111019",
"0.51059926",
"0.5103415"
] |
0.0
|
-1
|
display all current user computers
|
def list
user = User.find(current_user.id)
@computers = user.computer.all
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def index\n if signed_in?\n @computers = current_user.computers.all.decorate\n @computer = current_user.computers.new\n end\n end",
"def list_current_user\n abort \"You have no current user set!\".yellow unless current_user_exists?\n puts \"\\nCurrent User\"\n config.current_user.each do |k,v|\n if k == 'password'\n puts \"#{k.yellow}: ** HIDDEN **\".yellow\n else\n puts \"#{k.yellow}: #{v}\".yellow unless v.nil?\n end\n end\n end",
"def view_all_users\n # !! get all user so can interact after viewing them? all_users\n # User.select(:username).each_with_index {|user, index| puts \"#{index+1}. #{user.username}\"}\n #??????\n User.select(:username).each {|user| puts user.username}\n end",
"def index\n @users = GuestUsers::User.where(host: current_user) || []\n end",
"def list_current_users *args\r\n puts \"not implemented yet\"\r\n end",
"def index\n @hostnames = current_user.hostnames.all\n end",
"def get_domain_computers()\n\t\tcomputer_list = []\n\t\tdevisor = \"-------------------------------------------------------------------------------\\r\\n\"\n\t\traw_list = client.shell_command_token(\"net view\").split(devisor)[1]\n\t\tif raw_list =~ /The command completed successfully/\n\t\t\traw_list.sub!(/The command completed successfully\\./,'')\n\t\t\traw_list.gsub!(/\\\\\\\\/,'')\n\t\t\traw_list.split(\" \").each do |m|\n\t\t\t\tcomputer_list << m\n\t\t\tend\n\t\tend\n\n\t\treturn computer_list\n\tend",
"def getAllUsers()\n puts \"\\nUSERS:\"\n puts \"-------------------------------------------------\"\n @users.each {|user| puts \"ID: \" + user.id.to_s + \" Name: \" + user.name}\n puts \"-------------------------------------------------\"\n end",
"def current_users\n @title = \"Usuarios actuales\"\n @current_users = GetCurrentUsers.call(@previa_group)\n end",
"def index\n @computadors = Computador.all\n end",
"def index\n @clusters = current_user.clusters.all if current_user.clusters.any?\n @infrastructures = current_user.infrastructures.all if current_user.infrastructures.any?\n end",
"def index\n\t @contentPageHeading = 'My Companies'\n\t @companies = current_user.companies\n\t @user_companies = UserCompany.where(:user_id => current_user.id)\n\t # @public_companies = Array.new\n\t # for user_company in @user_companies\n\t # \t@public_companies.push(user_company,Company.find(user_company.pc_id))\n\t # end\n\t\t# @public_companies = Company.find(:all, :order => 'name', :conditions => 'id IN (SELECT pc_id FROM user_companies WHERE user_id = '+current_user.id.to_s+')')\n end",
"def show \n available_users\n end",
"def index\n @users = current_user.users\n end",
"def show_all()\n\t#images\n\tfor i in 0..3\n\t\tfor j in 0..4\n\t\t\t@computerimages[i][j].path = \"images/#{$game.players[i + 1].hand[j]}.png\"\n\t\tend\n\tend\n\t#ranks\n\tfor i in 0..3\n\t\t@computerranks[i].text = $game.ranks[$game.players[i + 1].ranks[0]]\n\tend\t\nend",
"def index\n @user_workspaces = UserWorkspace.owned_by(current_user)\n end",
"def index\n index! {\n @users = current_company.users\n }\n end",
"def show!\n puts 'Current Hosts:'\n @plataforms.each do |key, plataform|\n puts plataform.toString\n end\n end",
"def index\n @computers = Computer.all.where(operational: true).order(:name).paginate(page: params[:page], per_page: 10 )\n #@computers = Computer.all.order(:name).paginate(page: params[:page], per_page: 10 ) ORIGINAL\n end",
"def index\n @loggedin_user=current_user.name\n @users = User.all\n end",
"def list_users\n abort \"You have no users within your config file!\".yellow if config.empty?\n puts \"\\nUser Configuration\"\n config.each do |k, v|\n next if k == 'current_user'\n puts \"\\nEnvironment: #{k}\"\n print_hash_values v\n end\n\n list_current_user if current_user_exists?\n end",
"def index\n\t\t@users = User.all_except(current_user)\n @folders = current_user.folders unless current_user.nil?\n end",
"def index\n @computers_activities = ComputersActivity.all\n end",
"def list\n\trequire_relative '../lib/localhost'\n\t\n\tterminal = self.terminal\n\t\n\tLocalhost::Authority.list do |authority|\n\t\tterminal.print(\n\t\t\t:hostname, authority.hostname, \" \",\n\t\t\t:name, authority.name, \"\\n\", :reset,\n\t\t\t\"\\tCertificate Path: \", authority.certificate_path, \"\\n\",\n\t\t\t\"\\t Key Path: \", authority.key_path, \"\\n\",\n\t\t\t\"\\t Expires: \", authority.certificate.not_after, \"\\n\",\n\t\t\t:reset, \"\\n\"\n\t\t)\n\tend\nend",
"def index\n @sys_users = Sys::User.all\n end",
"def list_users(workspace)\n puts \"\\nUser List\\n\\n\"\n tp workspace.users, \"id\", \"name\", \"real_name\", \"status_text\", \"status_emoji\"\nend",
"def list_all_members\n @users.each { |x| puts \"-#{x.first}\"}\n end",
"def list_all_users\n\n end",
"def list_users\n tp @users, :real_name, :slack_id, :user_name => {:display_method => :name}\n end",
"def index\n @computers_keyboards = ComputersKeyboard.all\n end",
"def all_users\n `dscl . list /Users`.split(\"\\n\").delete_if { |e| e =~ /^_/ }\n end",
"def index\n @system_users = SystemUser.all\n end",
"def index\n @colaboradors = current_user.empresa.colaboradors.all\n end",
"def wholist( user )\n\t\trval = \"[Connected Users]\\n\" <<\n\t\t \" *#{user}*\\n\"\n\n\t\t@users.each do |u|\n\t\t\tnext if u == user\n\t\t\trval << \" #{u}\\n\"\n\t\tend\n\n\t\treturn rval\n\tend",
"def wholist( user )\n\t\trval = \"[Connected Users]\\n\" <<\n\t\t\t\" *#{user}*\\n\"\n\t\t@users.each {|u|\n\t\t\tnext if u == user\n\t\t\trval << \" #{u}\\n\"\n\t\t}\n\n\t\treturn rval\n\tend",
"def index\n\t\t# current_user.cdg_id\n\t\t@@users = SoapConnection::ChoferUsers.users( (1 rescue 1) ).compact rescue []\n\t\t@users = @@users\n\tend",
"def index\n @users = User.where(company_id: current_user.company_id)\n end",
"def all_users\n\t\tshared_users.map(&:id).join(\", \")\n\tend",
"def index\n\t\t# will automatically go into views/users and look for 'index' file to render\n\t\t@all_users = User.all\n\t\t# p @all_users, \"all users\"\n\tend",
"def index\n @cpus = Cpu.all\n end",
"def index\n @cursos = current_user.cursos.all\n end",
"def users\n User.where(network_id: context[:current_network]&.id)\n end",
"def index\n @user = current_user\n @home = current_user.homes\n # Lists each user's home(s). Available because in our model, I have set it up so that one user can have many homes.\n end",
"def index\n @users = User.all\n @user = current_user\n end",
"def index\n @account_users = AccountUser.account_users_for(current_user.id)\n end",
"def show\n @users = User.all\n @user = current_user\n end",
"def index\n if @current_user\n @pools = @current_user.pools\n else\n render :splash\n end\n end",
"def index\n @proyectos_users = ProyectosUser.all\n end",
"def list\n @all_users = User.find(:all)\n end",
"def list\n get('users')['users']\n end",
"def other_users_online()\n userlist = `ps haeo user | sort -u`.split(\"\\n\")\n userlist -= userlist.grep(/s0840449|root/)\n not userlist.empty?\nend",
"def index\n @users = User.all\n @current_user = current_user ? current_user.first : nil\n end",
"def index\n @users = User.all\n if current_user.pivitol_tracker_token != nil\n tracker_api = TrackerAPI.new\n @tracker_projects = tracker_api.projects(current_user.pivitol_tracker_token)\n end\n end",
"def index\n if current_user.admin?\n @companies = Company.all.order(:name).page(params[:page]).per(10)\n else\n @companies = current_user.company\n end\n end",
"def all_people_scheduled\n Entry.users_for_client(self.id)\n end",
"def available_collaborators\n Set[*self.account.users].difference(self.users).to_a\n end",
"def users\n gateway_check\n unavailable_servers_check\n @users\n end",
"def list_pucs\n\treturn if authorise_for_web(program_name?,'read') == false \n\n \tif params[:page]!= nil \n\n \t\tsession[:pucs_page] = params['page']\n\n\t\t render_list_pucs\n\n\t\t return \n\telse\n\t\tsession[:pucs_page] = nil\n\tend\n\n\tlist_query = \"@puc_pages = Paginator.new self, Puc.count, @@page_size,@current_page\n\t @pucs = Puc.find(:all,\n\t\t\t\t :limit => @puc_pages.items_per_page,\n\t\t\t\t :offset => @puc_pages.current.offset)\"\n\tsession[:query] = list_query\n\trender_list_pucs\nend",
"def view_by_system\n system \"clear\"\n prompt = TTY::Prompt.new\n prompt.select(\"Choose a console to view games\") do |menu|\n menu.choice \"PC\", -> {show_games_by_system(\"PC\")}\n menu.choice \"PlayStation 4\", -> {show_games_by_system(\"PlayStation 4\")}\n menu.choice \"XBOX1\", -> {show_games_by_system(\"Xbox One\")}\n menu.choice \"Nintendo Switch\", -> {show_games_by_system(\"Nintendo Switch\")}\n end\n end",
"def list\n\t\t# retrieve all users\n @users = User.find(:all)\n end",
"def display_all_clients\n clients.each_with_index do |client, index|\n puts \"Client ##{index + 1}. #{client.name.capitalize}\"\n end\n end",
"def index\n @computers_chipsets = ComputersChipset.all\n end",
"def all_users\n render \"all_users\"\n end",
"def index\n @computers = Computer.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @computers }\n end\n end",
"def collect_user_details\n cmd = 'lsuser -a ALL' # get all user names\n result ||= inspec.backend.run_command(cmd)\n return [] if result.exit_status.to_i != 0\n names = result.stdout.split(\"\\n\")\n users_cache = []\n names.sort.uniq.each do |n|\n users_cache << AixUser(inspec, n)\n end\n users_cache\n end",
"def index\n @counterparties = current_user.counterparties\n end",
"def visible_users\n is_superadmin? ? User.all : title.users\n end",
"def index\n @clients = current_user.is_admin ? Client.all : current_user.clients\n end",
"def index\n @users = User.find_all_with_authorization(current_user)\n end",
"def all_users\n Skype.find_users_of_type \"ALL_USERS\"\n end",
"def index\n @cms_users = User.all\n end",
"def list_user(param = '1110')\n @group_users.each { |item| puts item.info(param) }\n end",
"def users\n return @canonical_user_pool if @canonical_user_pool\n Egi::Fedcloud::Vmhound::Log.debug \"[#{self.class}] Retrieving all users\"\n check_retval @user_pool.info!\n\n @canonical_user_pool = []\n @user_pool.each { |user| @canonical_user_pool << canonical_user(user) }\n @canonical_user_pool\n end",
"def index\n \t@all_users = User.all\n end",
"def show\n @users = User.all\n authorize @colaboradore\n end",
"def users(*params)\n puts \"Users:\"\n @users.each do |user|\n muted = @muted_users.include?(user)\n puts \"#{user}#{muted ? \" (muted)\" : \"\"}\"\n end\n end",
"def users\n gateway_check\n @users\n end",
"def enum_users\n\tos = @client.sys.config.sysinfo['OS']\n\tusers = []\n\tuser = @client.sys.config.getuid\n\tpath4users = \"\"\n\tsysdrv = @client.fs.file.expand_path(\"%SystemDrive%\")\n\n\tif os =~ /7|Vista|2008/\n\t\tpath4users = sysdrv + \"\\\\users\\\\\"\n\t\tprofilepath = \"\\\\AppData\\\\Local\\\\VMware\\\\\"\n\telse\n\t\tpath4users = sysdrv + \"\\\\Documents and Settings\\\\\"\n\t\tprofilepath = \"\\\\Application Data\\\\VMware\\\\\"\n\tend\n\n\tif user == \"NT AUTHORITY\\\\SYSTEM\"\n\t\tprint_status(\"Running as SYSTEM extracting user list..\")\n\t\t@client.fs.dir.foreach(path4users) do |u|\n\t\t\tuserinfo = {}\n\t\t\tnext if u =~ /^(\\.|\\.\\.|All Users|Default|Default User|Public|desktop.ini|LocalService|NetworkService)$/\n\t\t\tuserinfo['username'] = u\n\t\t\tuserinfo['userappdata'] = path4users + u + profilepath\n\t\t\tusers << userinfo\n\t\tend\n\telse\n\t\tuserinfo = {}\n\t\tuservar = @client.fs.file.expand_path(\"%USERNAME%\")\n\t\tuserinfo['username'] = uservar\n\t\tuserinfo['userappdata'] = path4users + uservar + profilepath\n\t\tusers << userinfo\n\tend\n\treturn users\nend",
"def show\n @list = current_user.list\n end",
"def collectors\n data = User.\n all.\n order(:name).\n map{|u| {id: u.id, name: u.name}}\n\n render_ok users: data\n end",
"def getAllOnlineUsers\n return false if !@usrData\n @usrData[login]\n end",
"def index\n @all_users = User.all\n\trender \"list_users\"\n end",
"def list_users\n http_get(:uri=>\"/users\", :fields=>x_cookie)\n end",
"def index\n @engines = Engine.owner(current_user)\n end",
"def show_users\n @users = User.all\n end",
"def index\n if current_user.admin == 0\n @eleves_cu = @eleves.where(:user_id => current_user.id).all\n end\n end",
"def user_list\n @room = current_user.room\n @user_list = @room.users\n render partial: \"user_list\"\n end",
"def index\n if current_user.admin?\n @users = User.all\n end\n \n end",
"def index\r\n @channels = current_user.channels.all\r\n end",
"def index_user\n\t\t@user_convos = Conversation.involving_user(params[:user_id])\n\t\trender_list_of_convos(@user_convos)\n\tend",
"def users\n @page_title = _('Users for calendar %{calendar_name}') % {:calendar_name => @calendar}\n @users = @calendar.users.order :lastname, :firstname\n end",
"def html_index\n\t\t@users = User.all\n\tend",
"def ultimas_compras\n\t\tresu = []\n\t\tlista = current_user.compras.limit(10).order(\"created_at DESC\")\n\n\t\tlista.each do |compra|\n\t\t\tif(compra.users.first == current_user)\n\t\t\t\tresu << compra\n\t\t\tend\n\t\tend\n\t\tresu\n\tend",
"def users(*params)\n puts \"Users:\"\n\n @users.each do |user|\n muted = @muted_users.include?(user)\n puts \"#{user}#{muted ? ' (muted)' : ''}\"\n end\n end",
"def index\n @users = User.where(id: current_user.id)\n @pillboxes = Pillbox.where(user_id: current_user.id)\n @physicians = Physician.where(user_id: current_user.id)\n end",
"def index\n #@complaint_users = ComplaintUser.all\n @complaint_users = ComplaintUser.where([\"user_id = ?\", current_user.id]).order(\"created_at DESC\")\n end",
"def print_user_list\n puts \"Please write down the slected movies onto piece of paper.\"\n puts \"Ability so save list will be implemented in near future.\"\n puts \"Please stand by :) \\n\\n\"\n\n puts \"Here are your selected movies:\"\n for film in @user_list\n puts \" - #{film}\"\n end\n puts \"\"\n end",
"def users_by_name\n if in_admin_mode?\n query = create_query(:User, :all, by: :name)\n show_selected_users(query)\n else\n flash_error(:permission_denied.t)\n redirect_to(action: \"list_rss_logs\")\n end\n end",
"def list_collaborators(app_name)\n collaborators = get(\"/apps/#{escape(app_name)}/collaborators\")\n\n if collaborators.class == Array\n collaborators.map { |item| {:username => item['collaborator']['user']['username']} }\n else\n return []\n end\n end",
"def user_list\n execute('dscacheutil -q user') do |result|\n users = []\n result.stdout.each_line do |line|\n users << line.split(': ')[1].strip if /^name:/.match?(line)\n end\n\n yield result if block_given?\n\n users\n end\n end"
] |
[
"0.6756206",
"0.6462351",
"0.6424491",
"0.63315994",
"0.62772167",
"0.62321085",
"0.6181889",
"0.6097736",
"0.6088224",
"0.60542756",
"0.60407895",
"0.5988704",
"0.5986329",
"0.5938417",
"0.59100336",
"0.5893264",
"0.5864887",
"0.5836878",
"0.5789722",
"0.5788966",
"0.5776196",
"0.5773832",
"0.57736576",
"0.57523954",
"0.5738198",
"0.5737717",
"0.57223666",
"0.57169634",
"0.5712419",
"0.5685476",
"0.5682321",
"0.56817824",
"0.56786484",
"0.56709784",
"0.5667615",
"0.5649337",
"0.5647919",
"0.5627343",
"0.56208843",
"0.5599698",
"0.55931777",
"0.55885124",
"0.5575064",
"0.5567271",
"0.55637455",
"0.55553406",
"0.5553863",
"0.5551997",
"0.5551807",
"0.5535606",
"0.55349314",
"0.55216354",
"0.5521363",
"0.5513546",
"0.55099696",
"0.55097485",
"0.55041134",
"0.55014557",
"0.54977363",
"0.54974663",
"0.5493897",
"0.5491751",
"0.54895204",
"0.54882604",
"0.54868424",
"0.54781413",
"0.5464736",
"0.5457735",
"0.54568666",
"0.5455744",
"0.54541284",
"0.54531777",
"0.54488045",
"0.54477537",
"0.54453576",
"0.54389346",
"0.5438455",
"0.5437642",
"0.54315966",
"0.5430657",
"0.5426186",
"0.54189366",
"0.54177165",
"0.54133683",
"0.5408702",
"0.54080456",
"0.5405038",
"0.54048216",
"0.54013115",
"0.53926635",
"0.53926235",
"0.53905714",
"0.5388289",
"0.538665",
"0.5385831",
"0.538523",
"0.53847134",
"0.53834033",
"0.5379594",
"0.53791714"
] |
0.83014435
|
0
|
simulate the P2P network i starting origins n peers tr array of [t, r]
|
def simulate i, n, tr
unless tr[0].is_a?(Numeric) && tr[1].is_a?(Numeric)
require 'pry'
binding.pry
end
er = tr[0].to_f / (n-2)
ps = i.to_f / n
data = {prior_s: ps, prob_ex: er, total_queries: 0, kdist: []}
# every peer (other than origins) might get to do a direct query and/or get extra responses
know = Array.new(n - i) { false }
data[:responses] = []
k = i
j = 0
while k < n
# pick a peer that doesn't know yet
z = know.each_index.find { |l| !know[l] }
resp = 0
loop do
# record current knowledge dist
data[:kdist][data[:total_queries]] = k
# make a new query
data[:total_queries] += 1
# how many peers responded?
resp = k.times.count { rand < tr[1] }
break if resp > 0
end
data[:responses][j] = {extra: [], queries: data[:total_queries] - 1}
# how many non-origin peers responded?
exres = 0
if resp > i
exres = resp - i
end
nonorg = 0
# record responses
extra = 0
know.each_index do |l|
# if this is the querying peer
if l == z
# they get a direct response
data[:responses][j][:direct] = resp
know[l] = true
next
end
# else see how many extra responses we got
# resp peers are sending extra responses
exre_senders = resp
# subtract 1 if this is one of the k peers
if know[l] && nonorg < exres
exre_senders -= 1
nonorg += 1
end
reses = exre_senders.times.count { rand < er }
# if we got respones
if reses > 0
# record it
data[:responses][j][:extra] << reses
# check if this spread knowledge
if !know[l]
know[l] = true
extra += 1
end
end
end
k += 1 + extra
j += 1
end
data[:kdist][data[:total_queries]] = n
data
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def simulate i, n, t\n er = t.to_f / (n-2)\n ps = i.to_f / n\n data = {prior_s: ps, prob_ex: er, total_queries: 0, kdist: []}\n\n # every peer (other than origins) might get to do a direct query and/or get extra responses\n know = Array.new(n - i) { false }\n data[:responses] = []\n\n k = i\n j = 0\n while k < n\n # record current knowledge dist\n data[:kdist][data[:total_queries]] = k\n # gonna make a new query\n data[:total_queries] += 1\n\n z = know.each_index.find { |l| !know[l] }\n data[:responses][j] = {extra: [], queries: data[:total_queries] - 1}\n\n # record responses\n extra = 0\n know.each_index do |l|\n # if this is the querying peer\n if l == z\n # they get a direct response\n data[:responses][j][:direct] = k\n know[l] = true\n next\n end\n # else see how many extra responses we got (can't send to itself)\n reses = (k - (know[l] ? 1 : 0)).times.count { rand < er }\n\n # if we got respones\n if reses > 0\n # record it\n data[:responses][j][:extra] << reses\n\n # check if this spread knowledge\n if !know[l]\n know[l] = true\n extra += 1\n end\n end\n end\n\n k += 1 + extra\n j += 1\n end\n data[:kdist][data[:total_queries]] = n\n\n data\nend",
"def connect(p0) end",
"def fillInNodes()\n msg = Msg.new\n msg.setConfig(\"type\", 1)\n msg.setConfig(\"ttl\", $ports.length)\n msg.setConfig(\"seq\", nextSeqNum())\n msg_str = $hostname + \"\\t\"\n if $neighbors.length > 0\n $neighbors.each do |dst, distance|\n msg_str += dst + \",\" + distance.to_s + \"\\t\"\n end\n msg.setMessage(msg_str)\n $clients.each do |dst, client| \n sendMessage(client, msg)\n end\n end\nend",
"def step(n=10, &blk)\n (n-1).times do\n random_join\n yield resulting_maze if block_given?\n\n vertical_connections\n yield resulting_maze if block_given?\n end\n final_row\n yield resulting_maze if block_given?\n\n self\n end",
"def connect_nonblock(p0) end",
"def test_discover_neighborhood\n\tpeer2peer do |remote|\n\t mission, subtask, next_mission =\n\t\tTasks::Simple.new(:id => 'mission'), \n\t\tTasks::Simple.new(:id => 'subtask'),\n\t\tTasks::Simple.new(:id => 'next_mission')\n\t mission.depends_on subtask\n\t mission.signals(:stop, next_mission, :start)\n\n\t remote.plan.add_mission(mission)\n\t remote.plan.add_mission(next_mission)\n\tend\n\n\tr_mission\t= remote_task(:id => 'mission', :permanent => true)\n\tr_subtask\t= remote_task(:id => 'subtask', :permanent => true)\n\tr_next_mission = remote_task(:id => 'next_mission', :permanent => true)\n\n\t# We don't know about the remote relations\n\tassert_equal([], r_mission.children.to_a)\n\tassert_equal([], r_mission.event(:stop).child_objects(EventStructure::Signal).to_a)\n\n\t# add remote relations\n\tremote_peer.discover_neighborhood(r_mission, 1) do |r_mission|\n\t proxies = r_mission.children.to_a\n\t assert_equal(1, proxies.to_a.size)\n\t assert_equal(r_subtask, proxies.first)\n\t proxies = r_mission.event(:stop).child_objects(EventStructure::Signal).to_a\n\t assert_equal(r_next_mission.event(:start), proxies.first)\n\tend\n\n\tplan.unmark_permanent(r_mission)\n\tplan.unmark_permanent(r_subtask)\n\tplan.unmark_permanent(r_next_mission)\n\tengine.wait_one_cycle\n\tassert_equal([remote_peer.task], plan.permanent_tasks.to_a)\n end",
"def make_outer_connections\n per_batch = 1000\n\n outer_neigh = Answer.where(:question_id.ne => self.question_id, :team_id => self.team_id).shuffle[0..99]\n\nouter_neigh.each do |a|\n #0.step(outer_neigh.count, per_batch) do |offset|\n # outer_neigh.limit(per_batch).skip(offset).each do |a|\n if self.id != a.id\n SimilarityMachine::create_connection(self,a)\n end\n # end\n #end\nend\n\n true\n end",
"def initialize(numInputs, numHidden, numNeuronsPerHiddenLayer, numOutputs, weightRange)\n\t\t@input_layer = Array.new\n\t\t@hidden_layers = Array.new\n\t\t@output_layer = Array.new\n\t\t@hidden_layer_neuron_count = numNeuronsPerHiddenLayer\n\n\t\tfor i in 0...numInputs do \n\t\t\t@input_layer << Node.new\n\t\t\t@input_layer[i].add_incoming_connection(Connection.new(0))\n\t\tend\n\n\t\t@hidden_layers << Array.new\n\n\t\toldlayer = hidden_layers[0]\n\n\t\tfor i in 0...numNeuronsPerHiddenLayer do\n\t\t\tn = Node.new\n\t\t\t@input_layer.each do |p|\n\t\t\t\tc = Connection.new(weightRange)\n\t\t\t\tc.previous = p\n\t\t\t\tc.next = n\n\t\t\t\tp.add_outgoing_connection(c)\n\t\t\t\tn.add_incoming_connection(c)\n\t\t\tend\n\t\t\toldlayer << n\n\t\tend\n\n\t\toldlayer = hidden_layers[0]\n\n\t\tfor i in 1...numHidden do \n\t\t\tl = Array.new\n\t\t\tfor j in 0...numNeuronsPerHiddenLayer do \n\t\t\t\tn = Node.new\n\t\t\t\t\n\t\t\t\toldlayer.each do |o|\n\t\t\t\t\tc = Connection.new(weightRange)\n\t\t\t\t\tc.previous = o\n\t\t\t\t\tc.next = n\n\t\t\t\t\to.add_outgoing_connection(c)\n\t\t\t\t\tn.add_incoming_connection(c)\n\t\t\t\tend\n\n\t\t\t\tl << n\n\t\t\tend\n\t\t\t@hidden_layers << l\n\t\t\toldlayer = l\n\t\tend\n\n\t\tfor i in 0...numOutputs do \n\t\t\tn = Node.new\n\t\t\toldlayer.each do |o|\n\t\t\t\t\tc = Connection.new(weightRange)\n\t\t\t\t\tc.previous = o\n\t\t\t\t\tc.next = n\n\t\t\t\t\to.add_outgoing_connection(c)\n\t\t\t\t\tn.add_incoming_connection(c)\n\t\t\t\tend\n\t\t\t@output_layer << n\n\t\tend\n\tend",
"def draw_peers\r\n draw_rect(0, 50, WIDTH-300, HEIGHT, COLOR_WHITE, 0)\r\n $peers.length.times do |i|\r\n draw_peer(i, 200, 100) if (i == 0)\r\n draw_peer(i, 50, 200) if (i == 1)\r\n draw_peer(i, 50, 300) if (i == 2)\r\n draw_peer(i, 200, 400) if (i == 3)\r\n draw_peer(i, 350, 300) if (i == 4)\r\n draw_peer(i, 350, 200) if (i == 5)\r\n end\r\n end",
"def make_inner_connections\n per_batch = 1000\n\n inner_neigh = Answer.where(:question_id => self.question_id, :team_id => self.team_id).shuffle[0..99]\n\ninner_neigh.each do |a|\n #0.step(inner_neigh.count, per_batch) do |offset|\n # inner_neigh.limit(per_batch).skip(offset).each do |a|\n if self.id != a.id\n SimilarityMachine::create_connection(self,a)\n end\n #end\n # end\nend\n\n true\n end",
"def peers_connect\r\n\t\t\tpr = protocols.first\r\n\t\t\th = {\r\n\t\t\t\thandler: self.type.to_s,\r\n\t\t\t\tprotocol: pr.type.to_s,\r\n\t\t\t\tssl: @parent.ssl_enabled?\r\n\t\t\t}\r\n\t\t\tps = hive.peers_random(h,20)\r\n\t\t\tcounter = 0\r\n\t\t\tps.each{|ph| \r\n\t\t\t\tpeer = hive.peer_from_hash(ph)\r\n\t\t\t\tnext if peer.host_id == @parent.queen_id\r\n\t\t\t\tnext if peer.uuid == @parent.uuid\r\n\t\t\t\tnext if peers.any?{|p| p.uuid == peer.uuid }\r\n\t\t\t\tret = pr.connect_peer(peer.host,peer.port)\r\n\t\t\t\tnext if !ret\r\n\t\t\t\tcounter += 1\r\n\t\t\t\tbreak if counter > 20# @parent::MIN_PEERS\r\n\t\t\t}\r\n\t\t\tcounter\r\n\t\tend",
"def build_assignment_graph(layer)\n\t\th = @via_positions.length\n\t\tfail if (h == 0) || h.odd?\n\t\tfail if @start_node.pads.min < 0 || @start_node.pads.max >= @layer_count\n\t\tfail if @end_node.pads.min < 0 || @end_node.pads.max >= @layer_count\n\t\tvia_count = h / 2\n\t\tputs via_count\n\t\tlayers = 0..(@layer_count - 1) \n\t\tcolums = 0..(via_count * 2) # F O F O F for via_count == 2 \n\t\t#vp = @via_positions.dup # x,y pairs\n\t\t#vp.unshift(@start_node.y)\n\t\t#vp.unshift(@start_node.x)\n\t\tvp = [@start_node.x, @start_node.y] + @via_positions\n\t\tm = Array.new(@layer_count){Array.new(via_count * 2 + 1)}\n\t\tfor i in colums # from T back to S\n\t\t\tif i.even?\n\t\t\t\ty = vp.pop\n\t\t\t\tx = vp.pop\n\t\t\tend\n\t\t\tfor j in layers\n\t\t\t\tl = Array.new\n\t\t\t\tif i.even? # forward\n\t\t\t\t\tk = i + 1\n\t\t\t\t\twhile k > 0\n\t\t\t\t\t\tk -= 2\n\t\t\t\t\t\tif k == -1 # link forward node to T node\n\t\t\t\t\t\t\tl << @end_node if @end_node.pads.include?(j)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tif (h = m[j][k])\n\t\t\t\t\t\t\t\tl << h # link to up/down node \n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tunless l.empty?\n\t\t\t\t\t\tm[j][i] = F_node.new(x, y, j, l)\n\t\t\t\t\t\tl.each{|el|\n\t\t\t\t\t\t#unless @segment_list.index{|m| m.x1 == && m.y1 == el.y1 & m.x2 == el.x2 && m.y2 == el.y2}\n\t\t\t\t\t\t\t@segment_list << Segment.new(x, y, el.x, el.y)\n\t\t\t\t\t\t}\n\t\t\t\t\tend\n\t\t\t\telse #up/down\n\t\t\t\t\tfor k in layers do\n\t\t\t\t\t\tif (k != j) && (h = m[k][i - 1])\n\t\t\t\t\t\t\tl << h\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tunless l.empty?\n\t\t\t\t\t\tm[j][i] = V_node.new(x, y, j, l)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t#puts @segment_list.length\n\t\t@segment_list.uniq!{|el| [el.x1, el.y1, el.x2, el.y2]}\n\t\tputs @segment_list.length\n\t\t@all_intersecting_segments = Array.new\n\t\t@segment_list.each{|el|\n\t\t\t@all_intersecting_segments += el.intersecting_segments\n\t\t}\n\t\t@all_intersecting_segments.uniq!\n\n\t\tfor j in layers\n\t\t\tif (h = m[j][-1]) && @start_node.pads.include?(j)\n\t\t\t\t@start_node.next << h\n\t\t\tend\n\t\tend\n\tend",
"def generate_nodes!\n 7.times do |index|\n game.nodes.create(\n position: index,\n land_ids: land_ids_for_node(index)\n )\n end\n end",
"def edgeb_network(cmd)\n node = $node_info.new \n $lock.synchronize{\n \n node.src = $hostname\n node.dst = cmd[1]\n node.cost = 1\n node.nexthop = cmd[1]\n $rt[cmd[1]] = node\n if $local_ip == nil then $local_ip = cmd[2] end\n\n $network.undir_connection($hostname, cmd[1], cmd[3].to_i, 1) \n }\n #puts \"THIS IS THE ROUTING TABLE: #{$rt}\"\nend",
"def sample_nodes(n)\n if n >= @nodes.length\n @nodes.dup\n else\n result = []\n while result.length < n\n node = sample_node\n result << node unless result.include? node\n end\n result\n end\n end",
"def trips_number(start, finish, opts, graph = MainGraph)\n RoutePlanner.new(graph).trips_number(start, finish, opts)\n end",
"def create_connection tile\n walls = @maze.get_adjacent_walls tile\n if walls.length>0\n @maze.size+=1\n walls.sample.type = 0\n end\n end",
"def ping_nodes\n\t\twhile true\n\t\t\tsleep(rand(60))\n\t\t\tn = rand(@neighbour_nodes.count)\n\t\t\tnode = @neighbour_nodes[n]\n\t\t\ts = UDPSocket.new\n\t\t\tbegin\n\t\t\t\tTimeout::timeout(10){ \n\t\t\t\t\tputs \"Pinging #{node}\"\n\t\t\t\t\tsend_message [\"PING\", @info], 0, node.host, node.port\n\t\t\t\t\t@waiting = true\n\t\t\t\t\twhile waiting?\n\t\t\t\t\t\tsleep(0.2)\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\trescue Timeout::Error => ex\n\t\t\t\tif waiting?\n\t\t\t\t\tputs \"Conenction to #{node} timed out, sending DROP_NODE to all remaining nodes\"\n\t\t\t\t\t@neighbour_nodes - [node]\n\t\t\t\t\t@neighbour_nodes.each do |n|\n\t\t\t\t\t\tsend_message [\"DROP_NODE\", node], 0, n.host, n.port\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\trescue Socket::Error => ex\n\t\t\t\tputs \"Connection to #{node} failed, trying again in 60 seconds\"\n\t\t\trescue => ex\n\t\t\t\tputs ex.message\n\t\t\tend\n\t\tend\n\tend",
"def initializePesos\r\n \t@cantNeuronas.times do\r\n\t patron = @patrones[rand(@patrones.count-1)]\r\n @neuronas << {:class=>rand(@cantClases), :pesos => initPesos}\r\n\tend\r\n end",
"def generate_triples(outside_nodes, inside_nodes)\n triples = []\n # outside_nodes : ABCDE\n # inside_nodes : abcde\n inside_nodes.push(inside_nodes.first) # inside_nodes becomes abcdea\n # triples is going to be : Aab Bbc Ccd Dde Eea\n 0.upto(outside_nodes.size - 1) do |i|\n triple = outside_nodes[i, 1] + inside_nodes[i, 2] \n triples.push(triple)\n end\n triples\nend",
"def gen_binomial_tree_prices\n u = udp[:u]\n d = udp[:d]\n tree = [[initial_per_share]]\n t = 0\n while t < duration - 1e-6\n t += dt\n this_arr = tree.last.collect { |s| s * d }\n this_arr << tree.last.last * u\n tree << this_arr\n end\n tree\n end",
"def initialize(n)\n\t\t@nums=(1..n).to_a.sort{ rand() - 0.5 }\n\t\tindex_pairs_sum\n\tend",
"def sockMerchant(n, ar)\n paired_socks = {}\n pairs = 0\n\n ar.each do |sock|\n paired_socks[sock] ? paired_socks[sock] = paired_socks[sock] + 1 : paired_socks[sock] = 1\n end\n\n paired_socks.each do |(color,socks)|\n pairs = pairs + socks / 2\n end\n\n pairs\n end",
"def internal_connections\n stroke(200, 0, 0, 80)\n nodes[0..nodes.size - 1].each_with_index do |pi, i|\n nodes[i + 1..nodes.size - 1].each do |pj|\n line(pi.x, pi.y, pj.x, pj.y)\n end\n end\n end",
"def connect_supernodes(sns)\n ping_msg = construct_ping\n group = ThreadGroup.new\n sns.each do |sn|\n t = Thread.new(sn) { |sn|\n sock = handshaking(sn)\n if !sock.nil? and ping(sock,ping_msg)\n @lock.synchronize { @socks << sock }\n end\n }\n group.add(t)\n end\n group.list.each { |t| t.join }\n end",
"def init players\n @setup[players.size.to_s].each do |player_id, nodes|\n player_id = player_id.to_i\n nodes.each do |node|\n find_node( node['node'] ).owner = player_id\n find_node( node['node'] ).add_soldiers player_id, node['number_of_soldiers']\n end\n end\n end",
"def rand_population(n)\r\n\t\treturn Array.new(n) { Snek.new(@start_x,@start_y, Array.new(@nb_heuristic) { @random.rand(-5.0..5.0) }) }\r\n\tend",
"def t0_setup\n @my_big_input_array = []\n @my_big_result_array = []\n for num in 1..12\n playing_board(num)\n end\n solution_board\n end",
"def simulate(lines,numTrains,passengers,simMonitor)\r\n p_threads = [] #ok\r\n t_threads = [] #ok\r\n stations = {}\r\n trains = {} \r\n \r\n init_lines = {}\r\n ret_lines = {}\r\n lines.each{|k,v|\r\n init_lines[k] = v[1..v.length-1]\r\n } \r\n lines.each{|k,v|\r\n ret_lines[k] = v[0..v.length-2].reverse\r\n }\r\n \r\n @lines = lines\r\n @passengers = passengers\r\n @numTrains = numTrains\r\n \r\n metro_lines = lines.keys #array of the metrolines. red, blue, yellow etc\r\n people = passengers.keys\r\n \r\n metro_lines.each{|i| #access the stations in each metroline\r\n station_names = lines[i]\r\n station_names.each{|j|\r\n if stations[j] == nil\r\n stations[j] = {} #hash for metroline\r\n end\r\n \r\n if stations[j][i] == nil\r\n stations[j][i] = {} #hash for trains at station (for line) CHECK IF POPULATED\r\n end\r\n stations[j][\"passenger\"] = {} #hash for passengers at station \r\n }\r\n }\r\n \r\n @stations = stations\r\n for i in 0...people.length\r\n itin = passengers[people[i]] \r\n first_stop = itin[0]\r\n stations[first_stop][\"passenger\"][people[i]] = true\r\n end \r\n \r\n @passengers.each{|p,val|\r\n @check[p] = false\r\n }\r\n \r\n @simMonitor = simMonitor\r\n @simMonitor.each{|a,b |\r\n @t_cond[a] = b.new_cond\r\n @p_cond[a] = b.new_cond\r\n }\r\n \r\n numTrains.each{|key,val|\r\n index = val\r\n begin\r\n @trains[key + \" \" + index.to_s] = {}\r\n index -= 1\r\n end until(index == 0)\r\n }\r\n\r\nindex = 0\r\n@trains.each{|key,val|\r\n index = index + 1\r\n t_threads.push(\r\n Thread.new do\r\n train_work(@lines, index , numTrains, @passengers, @stations, trains, key, @t_cond, @p_cond)\r\n \r\n if(passengers.empty?)\r\n train_work(ret_lines, index , numTrains, passengers, stations, trains, key, @t_cond, @p_cond)\r\n train_work(init_lines, index , numTrains, passengers, stations, trains, key, @t_cond, @p_cond) \r\n else \r\n until(!@check.values.include?(false))\r\n train_work(ret_lines, index , numTrains, passengers, stations, trains, key, @t_cond, @p_cond)\r\n train_work(init_lines, index , numTrains, passengers, stations, trains, key, @t_cond, @p_cond)\r\n end\r\n end\r\n end\r\n )\r\n }\r\n \r\n @check.each{|p, val|\r\n itinerary = @passengers[p]\r\n p_threads.push(\r\n Thread.new do\r\n passenger_work(itinerary, lines, p)\r\n @check[p] = true\r\n end\r\n \r\n )\r\n }\r\n \r\n \r\n p_threads.each{|x|\r\n x.join\r\n }\r\n t_threads.each{|x|\r\n x.join \r\n }\r\n \r\n end",
"def initialize(pts)\n @genes = Array.new\n for i in 0...pts.length\n pair = pts.shift\n x = pair.shift\n y = pair.shift\n @genes << Gene.new(\"Node #{i}\", x, y)\n end\n end",
"def replicate_machines(train, count)\n t_array = [train]\n (count - 1).times do |_i|\n new_train = Train.new(name: train.name, distance: train.distance, price: train.price,\n index: @machine_index, reserved: true)\n @machine_index += 1\n t_array << new_train\n end\n t_array\n end",
"def process(n)\n foundpart = 0\n parts = []\n for i in 0..n-1 do # init participants ary\n parts.push 1\n end\n infolog {\"Starting, num-parts=#{n}\"}\n round = 0\n finished = false\n while !finished and round < @maxrounds\n round += 1\n numparts = parts.select{|it| it>0}.size\n infolog {\"ROUND ##{round}: num-parts=#{numparts}\"}\n deblog {\" parts=#{parts}\"}\n for i in 0..n-1 do\n if parts[i] > 0 and !finished\n for j in i+1..i+n do\n k = j % n\n #tracelog {\"k=#{k}\"}\n if parts[k] > 0\n parts[i] += parts[k]\n deblog {\"part##{i} steals from part#{k}: #{parts[k]} => #{parts[i]}\"}\n parts[k] = 0\n if parts[i] == n\n infolog {\"FINISHED at round##{round}, participant=#{i+1}\"}\n foundpart = i+1\n finished = true\n end\n break\n end\n end\n else\n tracelog {\"part##{i} has nothing, is skipped.\"} unless finished\n end\n end\n end\n foundpart\nend",
"def generate\n # Vælg et tilfældigt koordinat til at starte med.\n random_start = [@prng.rand(@width),@prng.rand(@height)]\n \n # Opret en stak og læg det tilfældige koordinat på stakken.\n stack = Array.new\n stack.push random_start\n until stack.empty?\n # Tag koordinaterne fra det øverste element på stakken.\n x,y = stack.last\n # Marker cellen som besøgt.\n @grid[y][x].visited = true\n # Gem alle cellens nabo-celler.\n neighbors = Array.new\n neighbors.push [x, y-1] unless y-1 < 0 # Nord\n neighbors.push [x+1, y] unless x+1 >= @width # Øst\n neighbors.push [x, y+1] unless y+1 >= @height # Syd\n neighbors.push [x-1, y] unless x-1 < 0 # Vest\n # Sorter de naboer fra der allerede er blevet besøgt af algoritmen.\n neighbors.delete_if {|x, y| @grid[y][x].visited }\n # tjek om der er nogle ubesøgte naboer.\n if neighbors.any?\n # Vælg en tilfældig ubesøgt nabo.\n random_neighbor = neighbors.sample(random:@prng)\n # Forbind denne celle med den tilfældige nabo.\n connect stack.last, random_neighbor\n # Læg den tilfældige nabo øverst på stakken.\n stack.push random_neighbor\n else\n # Hvis der ingen naboer er, så tager den en celle af stakken.\n stack.pop\n end\n end\n end",
"def next_nodes\n transitions.map(&:target)\n end",
"def handle_addrs count = 32\n @node.addrs.weighted_sample(count.to_i) do |addr|\n Time.now.tv_sec + 7200 - addr.time\n end.map do |addr|\n [addr.ip, addr.port, Time.now.tv_sec - addr.time] rescue nil\n end.compact\n end",
"def connect(params)\n order = params[:order]; from = params[:from]; to = params[:to]\n\n if to.kind_of?(Enumerable)\n to.each do |singularized_to|\n connect :from => from, :to => singularized_to, :order => order\n end\n else\n edges.add(from, to, order)\n end\n end",
"def generatePairs\n for i in 0...@parameters.paramsArr.length-1 do \n for j in i+1 ...@parameters.paramsArr.length do\n tmppairs = Pairs.new i,j\n for k in 0...@parameters.paramsArr[i].elementsArr.length do\n for h in 0...@parameters.paramsArr[j].elementsArr.length do \n tmppair = Pair.new k,h #there we store the index of value but not the true value\n @parameters.paramsArr[i].elementsArr[k].addTimes\n @parameters.paramsArr[j].elementsArr[h].addTimes\n tmppairs.addPair tmppair #temppairs just like ABpairs not all AB AC BC\n \n end\n end\n @pairs << tmppairs #@pairs is all the pairs like AB AC BC \n end\n end\n\n #if has limit then update the pairs with limit conditions\n if @haslimit\n \tputs \"update pairs with limit....\"\n updatePairsWithLimit\n end\n end",
"def initiate\n primary, *secondaries = @nodes.shuffle\n\n primary.promote\n secondaries.each(&:demote)\n\n return primary, secondaries\n end",
"def start_peers\n\t\tDRb.stop_service\n\t\tremote_process do\n\t\t DRb.start_service DISCOVERY_SERVER, Rinda::TupleSpace.new\n\t\tend\n\n\t\tif engine.running?\n\t\t begin\n\t\t\tengine.quit\n\t\t\tengine.join\n\t\t rescue ControlQuitError\n\t\t end\n\t\tend\n\n\t\tremote_process do\n\t\t central_tuplespace = DRbObject.new_with_uri(DISCOVERY_SERVER)\n\n\t\t cs = ConnectionSpace.new :ring_discovery => false, \n\t\t\t:discovery_tuplespace => central_tuplespace, :name => \"remote\",\n :plan => plan\n\n getter = Class.new do\n attr_accessor :cs\n def get; DRbObject.new(cs) end\n end.new\n getter.cs = cs\n\n Distributed.state = cs\n\n DRb.start_service REMOTE_SERVER, getter\n\n\t\t cs.extend RemotePeerSupport\n\t\t cs.testcase = self\n\n\t\t def cs.start_control_thread\n\t\t\tengine.run\n\t\t end\n\n\t\t yield(cs) if block_given?\n\t\tend\n\n\t\tDRb.start_service LOCAL_SERVER\n\t\t@central_tuplespace = DRbObject.new_with_uri(DISCOVERY_SERVER)\n\t\t@remote = DRbObject.new_with_uri(REMOTE_SERVER).get\n\t\t@local = ConnectionSpace.new :ring_discovery => false, \n\t\t :discovery_tuplespace => central_tuplespace, :name => 'local', \n\t\t :plan => plan\n Distributed.state = local\n\n remote.start_control_thread\n engine.run\n\t end",
"def test_connect_increments_neighbor_count\n @test_loc.connect @test_neighbor_list[0]\n assert_equal 1, @test_loc.neighbors.count\n end",
"def create_graph(arr)\n nodes = []\n (0...arr.size).each do |i|\n node = Node.new(i)\n nodes.push(node)\n end\n nodes.each_with_index do |node,i|\n arr[i].each {|val| node.connections.push(nodes[val])} \n end\n nodes\nend",
"def create_graph(arr)\n nodes = []\n (0...arr.size).each do |i|\n node = Node.new(i)\n nodes.push(node)\n end\n nodes.each_with_index do |node,i|\n arr[i].each {|val| node.connections.push(nodes[val])} \n end\n nodes\nend",
"def test_random_neighbor_many_connections\n neighbor_list = [@loc2, @loc3, @loc4]\n\n @loc1.add_neighbor @loc2\n @loc1.add_neighbor @loc3\n @loc1.add_neighbor @loc4\n\n assert_includes neighbor_list, @loc1.random_neighbor\n end",
"def cycle(n)\n RGL::ImplicitGraph.new { |g|\n g.vertex_iterator { |b| 0.upto(n - 1, &b) }\n g.adjacent_iterator { |x, b| b.call((x + 1) % n) }\n g.directed = true\n }\nend",
"def SetUpNodes\n \n @nodes.each do |node|\n\n if node.type==\"R\" or node.type==\"A\" or node.type==\"G\"\n \t\n\tSetMode(node)\n\n\tEnforceChannels(node)\n\t\n\tSetEssid(node) # after this stage, with omf-5.4 the wlan interface is created.\n\t\n\tSetWifiPower(node)\n\n\tSetMtu(node)\n\t\n\tSetIp(node)\n\t\n\tNode(node.id).exec(\"sysctl -w net.ipv4.conf.all.send_redirects=0\")\n \n EnforceRates(node)\n\t\n end\n #final settings\n #self.GetGroupInterface(node, ifn).txqueuelen=\"10\"\n end\n end",
"def peer2peer(&remote_init)\n\t\tstart_peers(&remote_init)\n\t\tsetup_connection\n\t end",
"def tdist(n, t); p_t(n, t); end",
"def build_nth_order(order)\n each_node_with_connections(order-1) do |node|\n connect :from => node,\n :to => discover_connections(node, order),\n :order => order\n end\n end",
"def peer_list\n ip_list = []\n raw_peers.each_slice(6) { |e| ip_list << e if e.length == 6 }\n\n ip_list.map! { |e| { :ip => e[0..3].join('.'), :port => (e[4] * 256) + e[5] } }\n end",
"def create_pairs(teams)\n return RoundRobinTournament.schedule(teams.shuffle)\nend",
"def spinup(cnt=10,start=0)\r\n if @bees.count > 0\r\n\t\t@bees.each{|b| b[:bee].disconnect }\r\n end\r\n\r\n\t@bees = []\r\n\tcnt.times {|i|\r\n\t\tbee = {}\r\n\t\tcport = \"353#{i + start + 1}\"\r\n\t\tbee[:bee] = Bee.new(\r\n\t\t\thost: \"127.0.0.1\",\r\n\t\t\tport: cport,\r\n\t\t\tqueen: '127.0.0.1:3333',\r\n\t\t\tssl_on: true,\r\n\t\t\tdata_dir: File.join(@data_dir,\"test_hive_clients_#{cport}\"),\r\n\t\t\thive_type: 'HiveSqlite',\r\n\t\t\thandler_protocols: { 'P2pMainV1' => { \r\n\t\t\t\toptions: {\r\n\t\t\t\t\tcallback: lambda {|s,p,d| i_got_mail(s,p,d) }\r\n\t\t\t\t},\r\n\t\t\t\tprotocols: [{ plugin_config:{ port: cport }}],\r\n\t\t\t}}\r\n\t\t)\r\n\t\tbee[:bee].hive.scorched_earth\r\n\r\n # This is not really needed except the start line, it is just cruft\r\n # to set up vars for the IRB console\r\n\t\tbee[:mh] = bee[:bee].handlers.first\r\n\r\n\t\t@bees[i] = bee\r\n\t}\r\n\t@bees.each{|b|\r\n\t\tb[:bee].start\r\n\t}\r\n\tsleep(1)\r\n\tbeeit(0)\r\n\ttrue\r\nend",
"def initialize(x, y)\n\t\t@neurons = Array.new\n\t\tx.times do\n\t\t\tneuron = Array.new(y)\n\t\t\t\n\t\t\t#create random weights\n\t\t\tneuron.each_index do |weight|\n\t\t\t\tneuron[weight] = rand * 2.0 - 1.0\n\t\t\tend\n\t\t\t@neurons << neuron\n\t\tend\n\tend",
"def learn_structure\n puts \"Learning undirected net structure...\"\n # Perform step until every pair of adjacent variables is dependent, and\n # set final_net to the _second-to-last_ state of @net\n begin\n puts \"n = #{n}\"\n final_net = net\n step\n end while n < 1\n \n net = final_net\n \n direct_edges\n end",
"def interconnect_mrm_rx(port)\n#ring frames\n#Test\n#TestPropagate\n#TestMgrNAck\n#TopologyChange\n#LinkUp\n#LinkDown\n\n test \"interconnect_mrm_rx port #{port}\" do\n primary = (port == $ring_port0) ? true : false\n in_ring = (port == $ring_port_in) ? true : false\n\n t_i(\"Create MC_Test frame\")\n frame = frame_create(MC_TEST, SC_STRING, 0, 0, \"mrp\")\n rx_ifh = rx_ifh_create(IGNORE, $ts.dut.port_list[port])\n\n sleep 2\n\n test \"Check LOC active\" do\n status = $ts.dut.call(\"mesa_mrp_status_get\", 0)\n status = primary ? status[\"p_status\"] : status[\"s_status\"]\n if (!in_ring && status[\"tst_loc\"] != true)\n t_e(\"Unexpected tst_loc #{status[\"tst_loc\"]}\")\n end\n end\n\n test \"Transmit TST frame on ring port to see no forwarding\" do\n frametx = frame.dup + \"mrp_tst t_sa #{UC_NUMBER_O} c_seq_num 1 \"\n frame_tx(frametx, port, \"\", \"\", \"\", \"\")\n end\n\n test \"Check status\" do\n status = $ts.dut.call(\"mesa_mrp_status_get\", 0)\n status = primary ? status[\"p_status\"] : status[\"s_status\"]\n if (!in_ring && status[\"tst_loc\"] == true)\n t_e(\"Unexpected tst_loc #{status[\"tst_loc\"]}\")\n end\n end\n\n sleep 2\n\n test \"Check LOC active\" do\n status = $ts.dut.call(\"mesa_mrp_status_get\", 0)\n status = primary ? status[\"p_status\"] : status[\"s_status\"]\n if (status[\"tst_loc\"] != true)\n t_e(\"Unexpected tst_loc #{status[\"tst_loc\"]}\")\n end\n end\n\n test \"Transmit Propagate frame on ring port to check forwarding and no copy to CPU\" do\n frametx = frame.dup + \"mrp_prop_nack \"\n framerx = in_ring ? \"\" : frametx\n primary ? frame_tx(frametx, port, \"\", framerx, \"\", \"\") : frame_tx(frametx, port, framerx, \"\", \"\", \"\")\n end\n\n test \"Transmit MgrNAck frame on ring port to see forwarding and no copy to CPU\" do\n frametx = frame.dup + \"mrp_prop_nack t_s_type 1 \"\n framerx = in_ring ? \"\" : frametx\n primary ? frame_tx(frametx, port, \"\", framerx, \"\", \"\") : frame_tx(frametx, port, framerx, \"\", \"\", \"\")\n end\n\n t_i(\"Create MC_Control frame\")\n frame = frame_create(MC_CONTROL, SC_STRING, 0, 0, \"mrp\")\n\n test \"Transmit Topology frame on ring port to see no copy to CPU and no forwarding\" do\n frametx = frame.dup + \"mrp_topo \"\n frame_tx(frametx, port, \"\", \"\", \"\", \"\")\n end\n\n test \"Transmit LinkChange LinkDown frame on ring port to see copy to CPU and no forwarding\" do\n frametx = frame.dup + \"mrp_lnk \"\n cpy_cpu = in_ring ? \"\" : rx_ifh + frametx\n frame_tx(frametx, port, \"\", \"\", \"\", cpy_cpu)\n end\n\n test \"Transmit LinkChange LinkUp frame on ring port to see copy to CPU and no forwarding\" do\n frametx = frame.dup + \"mrp_lnk t_type 5 \"\n cpy_cpu = in_ring ? \"\" : rx_ifh + frametx\n frame_tx(frametx, port, \"\", \"\", \"\", cpy_cpu)\n end\n end\nend",
"def set_routes(my_port, name, node_type, keys)\r\n # Give Access To This Node's Name\r\n get \"/peer_name\" do\r\n return name\r\n end\r\n # Give Access To This Node's Type (Client/Miner)\r\n get \"/peer_type\" do\r\n return node_type.to_s\r\n end\r\n # Give Access To This Node's Public Key For Validation & Handshake\r\n get \"/peer_key_public\" do\r\n return \"#{keys[0]},#{keys[2]}\"\r\n end\r\n # Give Access To This Node's Discovered Peers\r\n get \"/peer_peers\" do\r\n peer_ports = \"\"\r\n $peers.length.times do |i|\r\n peer_ports += \",\" if (i != 0)\r\n peer_ports += $peers[i].port.to_s\r\n end\r\n return peer_ports\r\n end\r\n # Another Peer Requests Handshake\r\n post \"/peer_handshake\" do\r\n port = params[\"port\"].chomp.to_i\r\n signature = params[\"signature\"].chomp.to_i\r\n timestamp = params[\"timestamp\"].chomp.to_i\r\n # Handshake Only With Undiscovered Peers\r\n if (search_peers_by_port(port) == -1)\r\n key_public = Faraday.get(\"#{URL}:#{port}/peer_key_public\").body\r\n key_public = key_public.split(\",\") # Convert String To Array\r\n # Validate Node's Authenticity Using RSA Decryption\r\n if (validate_signature(key_public, signature, timestamp))\r\n add_peer(port)\r\n handshake_peer(my_port, port, [keys[1], keys[2]])\r\n end\r\n end\r\n end\r\n # Request To Mine A Block\r\n post \"/mine_block\" do\r\n amount = params[\"amount\"].to_s\r\n payer = params[\"payer\"].to_s\r\n timestamp = params[\"timestamp\"].to_s\r\n signature = params[\"signature\"].to_s\r\n prev_hash = params[\"prev_hash\"].to_s\r\n payee = params[\"payee\"].to_s\r\n miner = my_port.to_s\r\n\r\n payer_peer = search_peers_by_port(payer)\r\n if (payer_peer != -1 && payer_peer.node_type != 3) # Validate if peer exists and is not rogue\r\n mine(amount, payer, payee, miner, timestamp, signature, prev_hash)\r\n else\r\n puts \"Denied mining request from rogue node\".red\r\n $status = \"Denied mining request from rogue node\"\r\n end\r\n end\r\n # Recieve A Mined Block\r\n post \"/block_mined\" do\r\n amount = params[\"amount\"].to_s\r\n payer = params[\"payer\"].to_s\r\n payee = params[\"payee\"].to_s\r\n miner = params[\"miner\"].to_s\r\n timestamp = params[\"timestamp\"].to_s\r\n signature = params[\"signature\"].to_s\r\n prev_hash = params[\"prev_hash\"].to_s\r\n nonce = params[\"nonce\"].to_s\r\n # Add Block If Not Already Mined\r\n block_exists = check_if_block_exists(miner.to_i, timestamp.chomp.to_i)\r\n add_block(amount, payer, payee, miner, timestamp, signature, prev_hash, nonce, true) if (!block_exists)\r\n end\r\n # Peer Sent A Mined Block\r\n post \"/broadcast_block\" do\r\n amount = params[\"amount\"].to_f\r\n signature = params[\"signature\"].to_s\r\n timestamp = params[\"timestamp\"].to_i\r\n prev_hash = params[\"prev_hash\"].to_s\r\n nonce = params[\"nonce\"].to_s\r\n hash = params[\"hash\"].to_s\r\n payer = params[\"payer\"].to_i\r\n payee = params[\"payee\"].to_i\r\n miner = params[\"miner\"].to_i\r\n\r\n payer_peer = search_peers_by_port(payer)\r\n if (prev_hash == \"0000000000000000000000000000000000000000000000000000000000000000\" && $blockchain.length > 0)\r\n # Genesis Node is being shared with everyone, this node does not require as it already has a chain. Ignore.\r\n else\r\n if (payer_peer != -1 && payer_peer.node_type != 3) # Validate if peer exists and is not rogue\r\n is_valid = validate_block(amount, signature, timestamp, prev_hash, nonce, hash, payer, payee, miner)\r\n if (is_valid)\r\n puts \"VALIDATED OK\".green\r\n add_block(amount, payer, payee, miner, timestamp, signature, prev_hash, nonce, false)\r\n end\r\n else\r\n puts \"Denied block broadcast from rogue node\".red\r\n $status = \"Denied block broadcast from rogue node\"\r\n end\r\n end\r\n end\r\n # Broadcast First Block (Genesis Block) To Peers\r\n post \"/genesis\" do\r\n broadcast_block($blockchain[0])\r\n end\r\nend",
"def main\r\n # Generate RSA Keys\r\n primes = generate_primes(12)\r\n keys = generate_rsa_keys(primes[0], primes[1])\r\n key_public = [keys[0], keys[2]]\r\n key_private = [keys[1], keys[2]]\r\n\r\n # Establish Node Server\r\n node_details = set_node_details\r\n port = node_details[0]\r\n name = node_details[1]\r\n node_type = node_details[2]\r\n if (node_details.length == 3) # Node Details Returns Required Values\r\n initialize_server(port)\r\n set_routes(port, name, node_type, keys)\r\n else # Node Details Returns An Error\r\n puts \"Error: #{node_details}\"\r\n $status = \"Error: #{node_details}\"\r\n end\r\n\r\n # Discover Peers Parallely To Other Crypto Fucntions (Hence New Thread)\r\n Thread.new {\r\n discover_peers(port, key_private)\r\n new_block(GENESIS_REWARD, 1801, port, key_private) if (port == 1801)\r\n begin\r\n Faraday.post(\"#{URL}:1801/genesis\") if (port != 1801) # Get First Block in Blockchain From Genesis Node\r\n rescue\r\n # Node Responts With No Data\r\n end\r\n }\r\n\r\n Thread.new { Interface.new(port, key_public, key_private).show }\r\nend",
"def Start\n \n\n \n #start the applications\n info(\"Starting applications.\")\n @receiverApps.StartAll\n @daemons.StartAll\n @itgManagers.StartAll\n\n info(\"Wait for applications to start\")\n wait(5)\n \n numRepetitions=3\n interval=120\n \n duration=(numRepetitions)*interval+30\n\n \n currTime=0\n \n @flows=AggregatorFlows.new\n \n flow=Flow.new(0, 500, @orbit.GetSenders()[0].id, @orbit.GetReceivers()[0].id)\n \n flow.SetEnd(duration)\n \n @flows.Push(flow)\n \n info(\"Starting rt loggers\")\n @rtloggers.StartAll\n\n #start the flows\n info (\"Starting traffic generation\")\n\t\n while (@flows.FlowsLeft()>0)\n\t flow=@flows.NextFlow\n\t #start a new flow through an itgManager; the flow automatically stops.\n\t if (flow.bitrate>0)\n\t info(\"Starting a flow from #{flow.sender.id} to #{flow.receiver.id} at #{flow.bitrate} kbps\")\n\t FindITGManager(flow.sender.id).StartFlow(flow, FindITGRecv(flow.receiver.id))\n\t end\n end\n \n k=0\n \n if (property.freezeTopology.to_s==\"yes\" and @orbit.class.to_s==\"OrbitLayer25\")\n\tinfo(\"Freezing topology\")\n\t@orbit.FreezeTopology()\n end\n \n wait(30)\n \n while (k<numRepetitions) do\n \n \n info(\"Changing channels...\")\n \n if (@nodes.size==2)\n\t\n\tinfo(\"Setting interface #{k%2} of node 1 on channel #{@orbit.channels[4]}.\")\n\t@orbit.GetGroupInterface(@nodes[1], @orbit.GetInterfaces[k%2]).channel=\"#{@orbit.channels[4]}\"\n\n\tif (property.switchOff.to_s!=\"no\")\n\t info(\"Also setting interface down and then up.\")\n\t @orbit.GetGroupInterface(@nodes[1], @orbit.GetInterfaces[k%2]).down\n \t @orbit.GetGroupInterface(@nodes[1], @orbit.GetInterfaces[k%2]).up\n\tend\n\t\n\t\n\tinfo(\"Setting interface #{(k+1)%2} of node 1 to channel #{@orbit.channels[0]}\")\n\t@orbit.GetGroupInterface(@nodes[1], @orbit.GetInterfaces[(k+1)%2]).channel=\"#{@orbit.channels[0]}\"\n end \n \n @nodes.each do |node|\n\t@orbit.GetInterfaces().each do |ifn|\n\t \n\t @orbit.Node(@nodes[0].id).exec(\"iwconfig #{ifn.name} >> /var/log/mesh.log\")\n \n\tend\n end\n\t \n k=k+1\n \n wait(interval)\n\n \n end\n \n info(\"Stopping applications.\")\n @rtloggers.StopAll\n @receiverApps.StopAll\n @daemons.StopAll\n @itgManagers.StopAll\n \n self.DeleteIptableRules()\n\n \n end",
"def main(ufds)\n @ufds = ufds\n info(\"Starting RPNI (#{@ufds.size} states)\")\n # First loop, iterating all PTA states\n (1...@ufds.size).each do |i|\n # we ignore those that have been previously merged\n next if @ufds.slave?(i)\n # second loop: states of lower rank, with ignore\n (0...i).each do |j|\n next if @ufds.slave?(j)\n # try to merge this pair, including determinization\n # simply break the loop if it works!\n success = successfull_merge_or_nothing(i,j)\n if success\n info(\"#{i} and #{j} successfully merged\")\n break\n end\n end # j loop\n end # i loop\n @ufds\n end",
"def create_nodes\n @nodes = [*0...@table.flatten.length]\n end",
"def generate_new_population_layer(n)\n\t\tcurrent_layer = @layers[n]\n\n\t\tparent_population = ((n == 0 || !@parents_from_previous_layer) ? current_layer : (@layers[n - 1] + current_layer)).sort\n\n\t\tnew_population = []\n\n\t\t# elitism\n\t\telitism = @layer_elitism\n\t\telitism = @overall_elitism if n == (@layers.size - 1) && @overall_elitism > elitism\n\n\t\tif elitism > 0\n\t\t\tcurrent_layer.sort.reverse[0, [elitism, current_layer.size].min].each do |i|\n\t\t\t\tnew_population << i\n\t\t\tend\n\t\tend\n\n\t\t(@layer_size - new_population.size).times do\n\t\t\tparent1_index = Array.new(@tournament_size){ rand(parent_population.size) }.max\n\t\t\tparent2_index = Array.new(@tournament_size){ rand(parent_population.size) }.reject{ |v| v == parent1_index }.max\n\t\t\twhile parent2_index == nil || parent2_index == parent1_index\n\t\t\t\tparent2_index = rand(parent_population.size)\n\t\t\tend\n\n\t\t\tparent1 = parent_population[parent1_index]\n\t\t\tparent2 = parent_population[parent2_index]\n\t\t\t\n\t\t\tparent1.tag_as_used\n\t\t\tparent2.tag_as_used\n\t\t\tnew_solution = parent1.solution.crossover(parent2.solution).mutate!(@mutation_rate)\n\t\t\tnew_population << Individual.new(new_solution, [parent1.age, parent2.age].max + 1)\n\t\tend\n\n\t\t@layers[n] = new_population\n\tend",
"def crear_serie(n)\n array = [1, 2]\n\n # times indica cuantas vecesdebe ejecutarse un fragmento de codigo\n (n - 2).times {\n array << array [-1] + array [-2]\n }\n \n return array\nend",
"def move_to_next_generation\n @x.times{ |r|\n @y.times{|c| \n @mat[r][c].step_generation\n }\n } \n end",
"def spoof_and_receive_probes(receiver2spoofer2targets, settings={ :probe_type => :rr, :retry => false }, &probe_requests_to_destinations )\n # thread out on receivers\n # iterate through until the next one will add too many targets\n # each time, add the targets to the receiver targets\n # and append to a receiver hash its targets\n # once i hit the limit, call receive, then thread out over the spoofers\n settings[ :probe_type ]=:rr if not settings.include?( :probe_type )\n settings[ :retry ]=false if not settings.include?( :retry )\n trivial_timeout=15\n results=[]\n unsuccessful_receivers=[]\n receiver_threads=[]\n privates=[]\n blacklisted=[]\n receiver2spoofer2targets.values.each {|spoofer2targets|\n spoofer2targets.each{|spoofer,targets|\n spoofer2targets[spoofer],privates,blacklisted=inspect_targets(targets,privates,blacklisted,@controller_log)\n }\n spoofer2targets.delete_if {|spoofer,targets| targets.empty?}\n }\n log { \"spoof_and_receive_probes(}, receiver2spoofer2targets: #{receiver2spoofer2targets.inspect}\" }\n for receiver in receiver2spoofer2targets.keys\n log {\"receiver is \" + receiver + \" total targs \" + receiver2spoofer2targets[receiver].values.collect{|requests| probe_requests_to_destinations.call(requests)}.flatten.length.to_s + \" total spoofers \" + receiver2spoofer2targets[receiver].length.to_s}\n receiver_threads << Thread.new(receiver,settings[:retry]) { |my_receiver_name,my_retry_command|\n begin # exception block for the receiver thread\n total_targets=receiver2spoofer2targets[my_receiver_name].values.collect{|requests| probe_requests_to_destinations.call(requests)}.flatten.length.to_s\n Thread.current[:receiver]=my_receiver_name\n Thread.current[:success]=false # false until proven true\n\n # may throw UnknownVPError\n my_receiver=self.get_vp(my_receiver_name)\n fid=0\n Timeout::timeout(trivial_timeout, SockTimeout.new(\"#{my_receiver_name} timed out after #{trivial_timeout} getting ready to receive spoofed #{settings[:probe_type].to_s}\")) {\n fid=case settings[:probe_type]\n when :rr\n my_receiver.receive_spoofed_rr\n when :ts\n my_receiver.receive_spoofed_ts\n when :tr\n my_receiver.receive_spoofed_tr\n end\n }\n # while i theoretically could catch the timeout here and assume that it might\n # still be receiving, in practice i'll need the fid to fetch the file later\n # could modify that if it ends up being a problem\n\n holes_to_punch=[]\n probes_to_send=Hash.new { |hash, key| hash[key] = [] }\n spoofer_count=0\n log {\"Before each_pair: #{my_receiver_name} #{receiver2spoofer2targets.inspect}\"}\n receiver2spoofer2targets[my_receiver_name].each_pair{|spoofer,targets|\n log {\"Before while loop: #{my_receiver_name} spoofer #{spoofer} targets #{targets.inspect}\"}\n spoofer_count += 1\n while targets.length>0\n log {\"top of targets.length loop: spoofer for #{my_receiver_name} is \" + spoofer + \" #{targets.length} \" + probe_requests_to_destinations.call(targets).join(\",\")}\n if (holes_to_punch.length + targets.length >= $MAX_HOLES) or (spoofer_count==receiver2spoofer2targets[my_receiver_name].keys.length)\n num_to_take=[$MAX_HOLES-holes_to_punch.length,targets.length].min\n init_length=holes_to_punch.length\n probes_to_send[spoofer] += targets[0...num_to_take]\n holes_to_punch += probe_requests_to_destinations.call(targets[0...num_to_take])\n targets[0...num_to_take]=[]\n log {\"before send probes: spoofer for #{my_receiver_name} is \" + spoofer + \" down to #{targets.length} \" }\n # send probes\n log {my_receiver_name + \" punching holes \" + holes_to_punch.join(\" \")}\n begin\n receiver_timeout=Controller::calculate_ping_timeout(holes_to_punch.length)\n Timeout::timeout(receiver_timeout, SockTimeout.new(\"#{my_receiver_name} timed out after #{receiver_timeout} punching #{holes_to_punch.length} holes\")) {\n my_receiver.punch_holes(holes_to_punch)\n }\n # handle timeouts a bit differently bc it\n # still might have punched some holes\n # so we continue even if it fails the 2nd time\n rescue SockTimeout\n if my_retry_command\n my_retry_command=false\n sleep 2\n retry\n else\n log {\"#{my_receiver_name} timed out punching holes EXCEPTION! \" + $!.to_s }\n end\n rescue java.lang.OutOfMemoryError => e\n raise \"OOM here! #{e.backtrace.inspect}\"\n rescue Exception\n if my_retry_command\n my_retry_command=false\n sleep 2\n retry\n else\n # we raise here to get to the\n # quarantine\n # no point in spoofing\n raise\n end\n end # send probes\n sleep 2\n spoofer_threads=[]\n max_length=probes_to_send.values.collect{|x| x.length}.max\n spoofer_timeout=Controller::calculate_spoof_timeout(max_length)\n for spoofer_key in probes_to_send.keys\n spoofer_threads << Thread.new(spoofer_key){|my_spoofer_name|\n begin # exception block for spoofer thread\n Thread.current[:host] = my_spoofer_name\n\n # may raise UnknownVPError\n my_spoofer=self.get_vp(my_spoofer_name)\n log {\"spoofing as #{my_receiver_name} from #{my_spoofer_name}: #{probes_to_send[my_spoofer_name].length} #{probe_requests_to_destinations.call(probes_to_send[my_spoofer_name]).join(\" \")}\"}\n\n Timeout::timeout(spoofer_timeout, SockTimeout.new(\"#{my_spoofer_name} timed out after #{spoofer_timeout} spoofing #{probes_to_send[my_spoofer_name].length} probes as #{my_receiver_name}\")){\n case settings[:probe_type]\n when :rr\n my_spoofer.spoof_rr({$pl_host2ip[my_receiver_name] => probes_to_send[my_spoofer_name]})\n when :ts\n my_spoofer.spoof_ts({$pl_host2ip[my_receiver_name] => probes_to_send[my_spoofer_name]})\n when :tr\n my_spoofer.spoof_tr({$pl_host2ip[my_receiver_name] => probes_to_send[my_spoofer_name]})\n end\n }\n rescue java.lang.OutOfMemoryError => e\n raise \"OOM here! #{e.backtrace.inspect}\"\n rescue Exception\n if settings.include?(:backtrace)\n $!.set_backtrace($!.backtrace + settings[:backtrace])\n end\n log { \"Spoofer error\" }\n quarantine(my_spoofer_name,( settings.include?(:maxalert) ? settings[:maxalert] : TEXT ),$!)\n end # exception block for spoofer thread\n }\n end # for spoofer_key in probes_to_send.keys\n # need to make sure the other threads all end (w timeouts if nothing else) to\n # make sure join returns\n spoofer_threads.each{|t|\n log {\"Waiting for spoofer #{t[:host]}\"}\n t.join\n }\n log {\"bottom of targets.length loop: spoofer for #{my_receiver_name} was \" + spoofer + \" down to #{targets.length} \" }\n holes_to_punch=[]\n probes_to_send.clear\n else # ^-- if $MAX_HOLES_TO_PUNCH or spoofer_count == # spoofers\n holes_to_punch += probe_requests_to_destinations.call(targets)\n probes_to_send[spoofer] += targets\n targets=[]\n end\n end # while targets.size>0\n } # receiver2spoofer2targets[my_receiver_name].each_pair{|spoofer,targets|\n\n\n # sleep to make sure last probes get back\n sleep 2\n fetch_timeout= 20 + (total_targets.to_f/100.0).round\n Timeout::timeout(fetch_timeout, SockTimeout.new(\"#{my_receiver_name} timed out after #{fetch_timeout} trying to kill and retrieve #{fid}\")) {\n probes=my_receiver.kill_and_retrieve(fid)\n log {\"Saving results for \" + my_receiver_name}\n Thread.current[:results]=probes\n Thread.current[:success]=true\n }\n # end exception block for the receiver thread\n rescue java.lang.OutOfMemoryError => e\n raise \"OOM here! #{e.backtrace.inspect}\"\n rescue Exception\n if my_retry_command\n my_retry_command=false\n sleep 2\n retry\n else\n if settings.include?(:backtrace)\n $!.set_backtrace($!.backtrace + settings[:backtrace])\n end\n quarantine(my_receiver_name,( settings.include?(:maxalert) ? settings[:maxalert] : TEXT ),$!)\n end\n end # exception block for receiver thread\n } # receiver_threads << Thread.new\nend # for receiver in\nreceiver_threads.each{|rt|\n log {\"Waiting for receiver #{rt[:receiver]}\"}\n # need to make sure the other threads all end (w timeouts if nothing else) to\n # make sure join returns\n rt.join\n if rt[:success]\n log {\"Adding results for #{rt[:receiver]}\"}\n results << [rt[:results],rt[:receiver]]\n else\n unsuccessful_receivers << rt[:receiver]\n end\n}\nreturn results,unsuccessful_receivers,privates,blacklisted\nend",
"def start_solution plan\n solutions = []\n 15.times do\n s = mutate_pairs plan, valid_solution2(false)\n solutions << s\n end\n\n #0.times do\n # s = random_solution plan\n #end\n\n 10.times do\n s = structured_solution plan\n solutions << mutate_pairs(plan, s)\n end\n sort_soluitons plan, solutions\n end",
"def bridge_on(*nodes)\n results = []\n nodes.zip(each_exit.cycle) do |curr, exit_node|\n node = curr.sample\n node .add_link exit_node.id\n exit_node.add_link node .id\n results << node\n end\n results\n end",
"def edgebReflex(msg, client)\n msg = msg.split(',')\n dstip = msg[0]\n srcip = msg[1]\n dst = msg[2]\n $ips[$hostname] = srcip\n $ips[dst] = dstip\n $dist[dst] = 1\n $neighbors[dst] = 1\n $next[dst] = dst\n $clients[dst] = client\n fillInNodes()\nend",
"def lerp(matrix, amount)\n end",
"def managePeers(classifiedPeers)\n result = ManagePeersResult.new\n\n @logger.debug \"Manage peers: #{classifiedPeers.disconnectedPeers.size} disconnected, #{classifiedPeers.handshakingPeers.size} handshaking, #{classifiedPeers.establishedPeers.size} established\"\n @logger.debug \"Manage peers: #{classifiedPeers}\"\n\n # Unchoke some peers. According to the specification:\n #\n # \"...unchoking the four peers which have the best upload rate and are interested. These four peers are referred to as downloaders, because they are interested in downloading from the client.\"\n # \"Peers which have a better upload rate (as compared to the downloaders) but aren't interested get unchoked. If they become interested, the downloader with the worst upload rate gets choked. \n # If a client has a complete file, it uses its upload rate rather than its download rate to decide which peers to unchoke.\"\n # \"at any one time there is a single peer which is unchoked regardless of its upload rate (if interested, it counts as one of the four allowed downloaders). Which peer is optimistically \n # unchoked rotates every 30 seconds. Newly connected peers are three times as likely to start as the current optimistic unchoke as anywhere else in the rotation. This gives them a decent chance \n # of getting a complete piece to upload.\"\n #\n # This doesn't define initial rampup; On rampup we have no peer upload rate information. \n\n # We want to end up with:\n # - At most 4 peers that are both interested and unchoked. These are Downloaders. They should be the ones with \n # the best upload rate.\n # - All peers that have a better upload rate than Downloaders and are not interested are unchoked. \n # - One random peer that is unchoked. If it is interested, it is one of the 4 downloaders. \n # When choosing this random peer, peers that have connected in the last N seconds should be 3 times more \n # likely to be chosen. This peer only changes every 30 seconds.\n\n # Step 1: Pick the optimistic unchoke peer \n\n selectOptimisticPeer(classifiedPeers)\n\n # Step 2: Update the downloaders to be the interested peers with the best upload rate.\n\n if classifiedPeers.interestedPeers.size > 0\n bestUploadInterested = classifiedPeers.interestedPeers.sort{ |a,b| b.uploadRate.value <=> a.uploadRate.value}.first(@targetUnchokedPeerCount)\n\n # If the optimistic unchoke peer is interested, he counts as a downloader.\n if @optimisticUnchokePeer && @optimisticUnchokePeer.peerInterested\n peerAlreadyIsDownloader = false\n bestUploadInterested.each do |peer|\n if peer.eql?(@optimisticUnchokePeer)\n peerAlreadyIsDownloader = true\n break\n end\n end\n bestUploadInterested[bestUploadInterested.size-1] = @optimisticUnchokePeer if ! peerAlreadyIsDownloader\n end\n\n # If one of the downloaders has changed, choke the peer\n downloadersMap = {}\n @downloaders.each{ |d| downloadersMap[d.trackerPeer] = d }\n bestUploadInterested.each do |peer|\n if downloadersMap.delete peer.trackerPeer\n # This peer was already a downloader. No changes.\n else\n # This peer wasn't a downloader before. Now it is; unchoke it\n result.unchoke.push peer if peer.peerChoked\n end\n end\n # Any peers remaining in the map are no longer a downloader. Choke them.\n result.choke = result.choke.concat(downloadersMap.values)\n \n @downloaders = bestUploadInterested\n end\n\n # Step 3: Unchoke all peers that have a better upload rate but are not interested.\n # However, if we just started up, only unchoke targetUnchokedPeerCount peers.\n if @downloaders.size > 0\n if classifiedPeers.uninterestedPeers.size > 0\n classifiedPeers.uninterestedPeers.each do |peer|\n if peer.uploadRate.value > @downloaders[0].uploadRate.value && peer.peerChoked\n result.unchoke.push peer\n end\n if peer.uploadRate.value < @downloaders[0].uploadRate.value && ! peer.peerChoked && ! peer.eql?(@optimisticUnchokePeer)\n result.choke.push peer\n end\n end\n end\n else\n # No downloaders yet, so we can't tell who is fast or not. Unchoke some\n result.unchoke = result.unchoke.concat(classifiedPeers.uninterestedPeers.first(@targetUnchokedPeerCount))\n end\n\n @logger.debug \"Manage peers result: #{result}\"\n\n result\n end",
"def get_route(curr_pos, end_time, pmap, tws, twe) \n ans = []\n starting_tuple = curr_pos << 0 # 0 is the waiting time\n ans << starting_tuple # [y, x, time unit]\n \n\t\n\t\n max_y = pmap.length - 1 \n max_x = pmap[0].length - 1\n \n highest_score = 0.0\n \n\ttime_for_score = 0.0\n\ttime_for_get_ans = 0.0\n\t\n\ttemp = -1\n\ttemp1 = 0\n\tfor y in 0..max_y\n\t\ttemp1 = pmap[y].count(temp)+ temp1 \n\tend\n\t\n\tno_of_pokemon = (pmap.length*pmap[0].length - temp1)\n\t\n\tnumber_of_loops = 0.7541*Math.log(no_of_pokemon,E) + 0.9829\n\t\n\n\t\n\t\n for h in 0...number_of_loops\n pmap1 = Marshal.load(Marshal.dump(pmap))\n tws1 = Marshal.load(Marshal.dump(tws))\n twe1 = Marshal.load(Marshal.dump(twe))\n\t\t\n time_taken = Time.now\n sortedArrayByRatioDistStart1 = []\n ans1 = []\n ans1 = getArrayResultsWithStartingPokemon(starting_tuple, pmap1, tws1, twe1, sortedArrayByRatioDistStart1, end_time, h)\n\t\ttime_for_get_ans = Time.now - time_taken + time_for_get_ans\n\t\t\n\t\tpmap1 = Marshal.load(Marshal.dump(pmap))\n tws1 = Marshal.load(Marshal.dump(tws))\n twe1 = Marshal.load(Marshal.dump(twe))\n\t\t\n\t\ttime_taken = Time.now\n score_time1 = get_score(ans1, pmap1, tws1, twe1)\n route_score1 = score_time1[0].round\n route_time1 = score_time1[1].round(3)\n time_for_score = Time.now - time_taken + time_for_score\n\t\t\n if highest_score <= route_score1\n final_ans = ans1\n highest_score = route_score1\n end\n\t\t\n\t\t\n end\n \n\n return final_ans\nend",
"def stepPerms(n)\n # dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]\n \n dp = Array.new(n + 1, 0)\n dp[0] = 1 # when number of steps are 0 there is only 1 way\n \n (1..n).each do |i|\n dp[i] += dp[i - 1] if i - 1 >= 0\n dp[i] += dp[i - 2] if i - 2 >= 0\n dp[i] += dp[i - 3] if i - 3 >= 0\n end\n\n dp[n]\nend",
"def create_node(l)\n node = Node.create(net_id: id, layer: l)\n # Unless L is first layer, generate upward connections\n unless l <= 0\n # For each parent node...\n loop_over_nodes(l - 1) do |i|\n parent = layer_n_nodes(l - 1)[i]\n # Generate a random connection weight between -1 and 1\n weight = rand * 2 - 1\n Connection.create(parent_id: parent.id,\n child_id: node.id,\n weight: weight.round(3))\n end\n end\n # Unless L is last layer, generate downward connections\n unless l >= num_layers - 1\n # For each child node...\n loop_over_nodes(l + 1) do |i|\n child = layer_n_nodes(l + 1)[i]\n # Generate a random connection weight between -1 and 1\n weight = rand * 2 - 1\n Connection.create(parent_id: node.id,\n child_id: child.id,\n weight: weight.round(3))\n end\n end\n end",
"def pagerank(g, s)\n raise if g.size1 != g.size2\n\n i = Matrix.I(g.size1) # identity matrix\n p = (1.0/g.size1) * Matrix.ones(g.size1,1) # teleportation vector\n t = 1-s # probability of teleportation\n\n (t*((i-s*g).invert)*p).column(0)\nend",
"def initialize(source_instance,transition) \n @number=0 \n @nodecost=0\n @passby=false\n @instance=source_instance\n @transition=transition\n @neighbours=[]\n \n @name = \"NODE \" +source_instance + \" - \" + transition.to_s \n \n end",
"def step\n any_independent = false\n net.edges.each do |e|\n a, b = e.source, e.target\n intersect = (@net.adjacent_either(a, b) & @net.verts_on_paths(a, b)).extend(PowerSet)\n \n # Is |Aab ^ Uab| > n? \n if intersect.length <= n\n next\n else\n # Are a and b independent conditioned on any subsets of Aab ^ Uab of cardinality n+1?\n valid_intersects = intersect.power_set.select {|s| s.length == n+1}.reject { |subset| subset.include?(a) || subset.include?(b) }\n if valid_intersects.any? { |subset|\n print \"Testing independence between #{a.name} and #{b.name}, conditioning on #{(subset.any? ? subset.map(&:name).join(', ') : 'nothing') + '...'}\"\n print (coindependent?(p_value, a, b, *subset) ? \"[+]\\n\" : \"[-]\\n\")\n coindependent?(p_value, a, b, *subset)\n }\n @net = remove_edge(net, e)\n net.edges.each do |e|\n puts \"#{e.source.name} => #{e.target.name}\"\n end\n any_independent = true\n end\n end\n end\n @n += 1\n any_independent\n end",
"def move(pid, num_punters, map, claimed, rem, setup=false, tbl=nil)\n sites = map['sites']\n rivers = map['rivers']\n mines = map['mines']\n _format = \"\"\"\nInvoke C++ program with the following format:\nn m k pid np\ns_1 t_1 c_1\n...\ns_m t_m c_m (edges)\na_1 ... a_k (mines)\nmode\nextra\n\n0 <= s_i, t_i < m\n-1 <= c_i < np (-1: not claimed)\n0 <= a_i < n\n\n\nif mode == 'state'\n extra == ''\n The C++ program should return\n 'tbl (state)'\n where state is a string representing a state (without spaces)\nif mode == 'run'\n extra looks like:\ntbl\nai_kind\n The C++ program should return\n 'pass'\n or\n 'claim s t'\n in one line.\n \"\"\"\n n = sites.size\n m = rivers.size\n k = mines.size\n np = num_punters\n edges = []\n cl = {}\n for c in claimed\n cl[[c[1], c[2]]] = c[0]\n end\n for e in rivers\n col = -1\n if cl[[e['source'], e['target']]]\n col = cl[[e['source'], e['target']]]\n end\n edges << [e['source'], e['target'], col]\n end\n io = IO.popen(File.expand_path(File.dirname($0)) + '/core', 'r+')\n io.puts(\"#{n} #{m} #{k} #{pid} #{np} #{rem}\")\n for i in 0 ... m\n io.puts(edges[i].join(' '))\n end\n mine_ids = []\n for i in 0 ... k\n mine_ids << (mines[i]).to_s\n end\n io.puts(mine_ids.join(' '))\n ai_kind = @ai_kind\n if ai_kind == 'hybrid'\n # Choose AI type by np, size, and so on\n if np == 2\n ai_kind = 'two_player_minmax'\n elsif np >= 4\n ai_kind = 'mine_connect'\n else\n ai_kind = 'greedy'\n end\n end\n if setup\n io.puts('setup')\n else\n io.puts('run')\n io.puts(tbl)\n io.puts(ai_kind)\n end\n io.close_write\n eval = 0\n STDERR.puts(\"playing as punter #{pid} (total = #{num_punters})\")\n while answer = io.gets.chomp.split\n if answer[0] != 'info'\n break\n end\n # info eval (turns) (value)\n if answer[1] == 'eval'\n turns = answer[2].to_i\n eval = answer[3].to_i\n if turns >= 0\n STDERR.puts(\"evaluation: turns=#{turns}, value=#{eval}\")\n else\n STDERR.puts(\"full evaluation: value=#{eval}\")\n end\n end\n end\n if answer[0] == 'pass'\n return {'pass' => {'punter' => pid}}, eval\n end\n if answer[0] == 'claim'\n s = answer[1].to_i\n t = answer[2].to_i\n return {'claim' => {'punter' => pid, 'source' => s, 'target' => t}}, eval\n end\n if answer[0] == 'tbl'\n STDERR.puts(\"Got tbl (tbl size = #{answer[1].size})\")\n return answer[1]\n end\n end",
"def config_sim(paths)\r\n @paths = paths\r\n @passengers = initialize_passengers\r\n\r\n # Plan each passenger's trip\r\n passengers.each_with_index { |x, index|\r\n s1 = paths[x.passenger].first\r\n s2 = paths[x.passenger].last\r\n p = plan(s1, s2)\r\n c = color(plan(s1,s2))\r\n x.set_plan(Hash[p.zip(c.map {|i| i.include?(',') ? (i.split /, /) : i})])\r\n # when passenger has more than 2 stops?\r\n }\r\n \r\n i = 0\r\n @paths.each {|name, path|\r\n #find the station in the first index of path array\r\n @stations.each {|x| \r\n if x.to_s.include? path.first\r\n #add Passenger in passenger attribute of that station\r\n x.add_passenger(@passengers.at(i))\r\n i += 1\r\n end\r\n }\r\n }\r\n end",
"def joinNetwork( gateInetAddr_in, id_in )\n @netWorkMember = true\n @id = id_in\n @gateInetAddr = gateInetAddr_in\n @guid = Hash_Func( @id )\n for m in 0..@guid.length\n n = @guid[m].to_i\n @routing_table[[0,m,n]] = { :node_id => @guid, :ip_address => @localInetAddr.ip, \\\n :port => @localInetAddr.port }\n end\n if gateInetAddr_in.ip == nil\n puts @id, \"First Node in Network! Waiting for peers ...\"\n return @next_nid\n else\n joinMesg = { :type => \"JOINING_NETWORK_SIMPLIFIED\", :node_id => @guid, \\\n :ip_address => @localInetAddr.ip, :port => @localInetAddr.port }.to_json\n @s.send joinMesg, 0, @gateInetAddr.ip, @gateInetAddr.port\n return @next_nid\n end\n @next_nid += 1\n end",
"def ipmt(i, per, n, pv)\n pmt = pmt(i, n, pv)\n return ipmtp(i, per, pv, pmt)\n end",
"def crossover(p0, p1)\n children = []\n if rand < @rate\n c0, c1 = Chromosome.new, Chromosome.new\n min = [p0.length, p1.length].min\n index = rand(min)\n for i in index...min\n c0 << p0[i].copy\n c1 << p1[i].copy\n end\n children << fill(c0, p1)\n children << fill(c1, p0)\n end\n children\n end",
"def simulate(player1, player2, runs)\n separation\n tateti = Tateti.new\n p1 = 0\n p2 = 0\n ties = 0\n runs.times do\n loop do\n tateti = player1.play(tateti)\n break p1 += 1 if !tateti.winner.nil?\n break ties += 1 if tateti.tie?\n tateti = player2.play(tateti)\n break p2 += 1 if !tateti.winner.nil?\n break ties += 1 if tateti.tie?\n end\n tateti.empty_board\n end\n print_stats(player1, player2, runs, p1, p2, ties)\nend",
"def save_message_from(n, delta)\n incoming[neighbors.index(n)] = delta\n end",
"def initialize(inputNodes, hiddenNodes, outputNodes, learningRate=0.3, momentum=0.2)\n # Make sure we add the bias node to the input\n @inputNodes = inputNodes + 1\n @hiddenNodes = hiddenNodes\n @outputNodes = outputNodes\n\n @learningRate = learningRate\n @momentum = momentum\n\n @w_1 = NeuralNetwork::create_matrix(@inputNodes, @hiddenNodes, 0.0)\n @w_2 = NeuralNetwork::create_matrix(@hiddenNodes, @outputNodes, 0.0)\n \n # Randomize the values of Nthe nodes [-0.5, 0.5]\n @w_1.map! { |arr| arr.map { |v| rand(-0.5..0.5) } }\n @w_2.map! { |arr| arr.map { |v| rand(-0.5..0.5) } }\n\n # It helps to store the current state of node activations\n @activation_input = [1.0] * @inputNodes\n @activation_hidden = [1.0] * @hiddenNodes\n @activation_output = [1.0] * @outputNodes\n\n @din = NeuralNetwork::create_matrix(@inputNodes, @hiddenNodes, 0.0)\n @dout = NeuralNetwork::create_matrix(@hiddenNodes, @outputNodes, 0.0)\n\n puts \"\\n================================================================================================\\n[+]Weights from input to hidden nodes [#{@inputNodes}x#{@hiddenNodes}] has been initialized with small random values\"\n puts \"[+]Weights from hidden to output nodes [#{@hiddenNodes}x#{@outputNodes}] has been nitialized to small random values\\n================================================================================================\\n\"\n\n puts \"Neural network initialized with values \\n \\t Input Nodes:[{#{@inputNodes}]\\t Hidden Nodes: [#{@hiddenNodes}]\\t Output Nodes: [#{@outputNodes}]} \\n--------------------------------------------------------------------------------\\n\"\n puts \"\"\n\n end",
"def connect(peer)\n return if @connections[peer]\n @connections[peer] = []\n peer.connections[self] = []\n\n Layout.parallel_links.times do\n local = add_link\n remote = peer.add_link\n @connections[peer].push([local, remote])\n peer.connections[self].push([remote, local])\n end\n end",
"def fill_train(train)\n 120.times { train.board(active_passenger, station) }\n end",
"def sockMerchant(n, ar)\n hash = Hash.new(0)\n pares = Array.new\n ar.each{|key| hash[key] += 1}\n #puts hash\n hash.each do |ky, t|\n if t - 1 > 0\n t % 2 == 0 ? pares << t/2 : pares << (t-1)/2\n end\n end\n pares.length > 0 ? \"Result: #{pares.reduce(:+)}\" : 0\nend",
"def loop_over_nodes(l)\n layer_n_nodes(l).length.times do |i|\n yield i\n end\n end",
"def snail(array)\n return Array.new if array == [[]]\n\n # step_map is an array saying how many\n # steps to take before each turn\n step_map = Array.new\n (1 .. array.length).to_a.reverse.each do |i|\n step_map << i\n step_map << i\n end\n step_map.shift\n\n result = Array.new\n direction = :East\n y = 0\n x = -1\n\n step_map.each do |steps|\n steps.times do\n case direction\n when :East\n x += 1\n when :West\n x -= 1\n when :South\n y += 1\n when :North\n y -= 1\n end\n\n result << array[y][x]\n end\n\n direction = turnFrom direction\n end\n\n result\nend",
"def game_of_life2(rows,columns,grid,generations)\n puts \"#{grid}\"\n temp2 = Marshal.dump(grid)\n temp = Marshal.load(temp2)\n future = Marshal.load(temp2)\n for x in 1..generations\n puts \"Generation #{x}\"\n\n #Loop through each cell\n for i in 0..temp.length-1\n for j in 0..temp[i].length-1\n alive_neighbours = 0\n\n #Finding number of neighbours for current cell\n for a in -1..1\n for b in -1..1\n\n #Variables for counting Neighbors\n x = 0\n y = 0\n\n #Current number of rows and columns\n nx = temp.length-1\n ny = temp[i].length-1\n\n #Corner Cases including cyclic neighbors\n\n #Top Left Corner\n if i==0 and j==0\n if i+a<0 and j+b<0\n x=nx\n y=ny\n elsif i+a<0\n x = nx\n y = j+b\n elsif j+b<0\n x = i+a\n y = ny\n else\n x = i+a\n y = j+b\n end\n\n #Top Right Corner\n elsif i==0 and j==ny\n if i+a<0 and j+b>ny\n x = nx\n y = 0\n elsif i+a<0\n x = nx\n y = j+b\n elsif j+b>ny\n x = i+a\n y = 0\n else\n x = i+a\n y = j+b\n end\n\n #Bottom Right Corner\n elsif i==nx and j==ny\n if i+a>nx and j+b>ny\n x = 0\n y = 0\n elsif i+a>nx\n x = 0\n y = j+b\n elsif j+b>ny\n x = i+a\n y = 0\n else\n x = i+a\n y = j+b\n end\n\n #Bottom Left Corner\n elsif i==nx and j==0\n if i+a>nx and j+b<0\n x = 0\n y = ny\n elsif i+a>nx\n x = 0\n y = j+b\n elsif j+b<0\n x = i+a\n y = ny\n else\n x = i+a\n y = j+b\n end\n\n #Edge Cases\n\n #Top Edge\n elsif i==0 and i+a<0\n x = nx\n y = j+b\n\n #Bottom Edge\n elsif i==nx and i+a>nx\n x = 0\n y = j+b\n\n #Left Edge\n elsif j==0 and j+b<0\n x = i+a\n y = ny\n\n #Right Edge\n elsif j==ny and j+b>ny\n x = i+a\n y = j\n\n #Internal life\n else\n x = i+a\n y = j+b\n end\n alive_neighbours = alive_neighbours + temp[x][y]\n end\n end\n\n #Current cell to be subtracted to avoid duplicates\n alive_neighbours = alive_neighbours- temp[i][j]\n\n #Implenting rules of GOF\n\n #Lonely Cell dies\n if temp[i][j]==1 and alive_neighbours<=2\n future[i][j] = 0\n\n #Cell dies due to overcrowding\n elsif temp[i][j]==0 and alive_neighbours>3\n future[i][j] = 0\n\n #A new cell is born if there are 3 neighbors\n elsif temp[i][j]==0\n future[i][j] = 1\n end\n end\n end\n\n #Display the new generation\n for a in 0..future.length-1\n for b in 0..future[a].length-1\n if future[a][b]==1\n print \"@ \"\n else\n print \". \"\n end\n end\n puts \"\"\n end\n\ttemp3 = Marshal.dump(future)\n\ttemp = Marshal.load(temp3)\n end\n return future\nend",
"def manageConnections(classifiedPeers)\n\n n = classifiedPeers.handshakingPeers.size + classifiedPeers.establishedPeers.size\n if n < @targetActivePeerCount\n result = classifiedPeers.disconnectedPeers.shuffle.first(@targetActivePeerCount - n)\n @logger.debug \"There are #{n} peers connected or in handshaking. Will establish #{result.size} more connections to peers.\"\n result\n else\n []\n end\n end",
"def fork_remote_tasks(parents)\n families = []\n next_generation = []\n parents.each do |parent|\n if parent.children.size.zero?\n logger.debug(\"#{parent} Reached leaf. Nothing to do.\")\n next\n end\n parent.children.each do |child|\n families << [parent, child]\n next_generation << child\n end\n end\n\n if families.size.zero?\n logger.info(\"Reached bottom of the tree. Nothing to do.\")\n return\n end\n\n Parallel.map(families, config.parallel => families.size) do |family|\n parent = family[0]\n child = family[1]\n logger.info(\"Run remote [#{parent.level}]. #{parent.host} => #{child.host}\")\n config.remote_task.run(parent.host, child.host)\n end\n\n fork_remote_tasks(next_generation)\n end",
"def connect( from: nil, to: nil )\n input_neuron = @neurons[ to ]\n output_neuron = @neurons[ from ]\n input_neuron.add_input( output_neuron )\n end",
"def initialize(n = 2)\n @n = n;\n @xn = Array.new(@n, 0.0);\n @wn = Array.new(@n, 0.0);\n @v = 0.0;\n end",
"def generate_neighbours(current_node)\n moves = [[ 1, 2], [-1, 2], [ 1,-2], [-1,-2], [ 2, 1], [-2, 1], [ 2,-1], [-2,-1]]\n moves.each do |move|\n neigbour_helper(current_node, move[0], move[1])\n end\n end",
"def primary()\n while true\n moves = []\n map = $network.frame\n\n (0...map.height).each do |y|\n (0...map.width).each do |x|\n loc = Location.new(x, y)\n site = map.site(loc)\n\n next if site.owner != $tag\n\n next if should_wait(map, site)\n\n valid = valid_moves(map, loc)\n if valid.empty?\n opts = $directions\n #opts = site.strength == 255 ? directions : ([GameMap::DIRECTIONS[0] ] + directions\n moves << Move.new(loc, opts.shuffle.first)\n else\n moves << Move.new(loc, valid.shuffle.first)\n end\n\n end\n end\n\n $network.send_moves(moves)\n end\nend",
"def reproduction\n # Refill the population with children from the mating pool\n @population.each_index do |i|\n # Sping the wheel of fortune to pick two parents\n m = rand(@mating_pool.size).to_i\n d = rand(@mating_pool.size).to_i\n # Pick two parents\n mom = @mating_pool[m]\n dad = @mating_pool[d]\n # Get their genes\n momgenes = mom.dna\n dadgenes = dad.dna\n # Mate their genes\n child = momgenes.crossover(dadgenes)\n # Mutate their genes\n child.mutate(@mutation_rate)\n # Fill the new population with the new child\n location = Vec2D.new(width / 2, height + 20)\n @population[i] = Rocket.new(location, child)\n end\n @generations += 1\n end",
"def generate_adjacencies(board)\n b2 = duplicate(board)\n b2.each_with_index do |row, y_idx|\n row.each_with_index do |cell, x_idx|\n next unless cell == MINE\n increment_neighbors(b2, [x_idx, y_idx])\n end\n end\nend",
"def test_proxy_graph_separation\n\ttasks = prepare_plan :add => 3\n\tproxies = tasks.map { |t| transaction[t] }\n\n\tt1, t2, t3 = tasks\n\tp1, p2, p3 = proxies\n\tp1.depends_on p2\n\n\tassert_equal([], t1.enum_for(:each_child_object, Hierarchy).to_a)\n\tt2.depends_on t3\n\tassert(! Hierarchy.linked?(p2, p3))\n end",
"def maxtrips(start, finish, stops1, stops2)\n vnum1 = vertex_num_for(start)\n vnum2 = vertex_num_for(finish)\n (stops1..stops2).map {|n| (a_matrix**n)[vnum1, vnum2]}.inject(&:+)\n end",
"def set_initial_parameters\n p x_range = [-4, 0, 4]\n p y_range = [-4, -2, 0]\n p machines = %w[6 6 7 7 7 6 6 7 7]\n\n sleep_sec = 3\n [x_range, y_range, sleep_sec, machines]\nend",
"def initializeWeights\n @matrixWeights = Array.new\n @umbral = Array.new\n for i in 0..@numNeuronas-1\n aux = Array.new\n for j in 0..@numEntradas-1\n aux << (2*0.05*rand-0.05)\n end\n @matrixWeights << aux\n @umbral << (2*0.05*rand-0.05)\n end\n end"
] |
[
"0.62776434",
"0.56342787",
"0.55337226",
"0.54760855",
"0.5253529",
"0.5198142",
"0.517477",
"0.5146634",
"0.5137675",
"0.5136337",
"0.5064142",
"0.50373375",
"0.4990826",
"0.49727556",
"0.49395207",
"0.49336106",
"0.48921725",
"0.4889871",
"0.4880847",
"0.48753926",
"0.48680457",
"0.4859078",
"0.48576102",
"0.4827872",
"0.48111743",
"0.4808441",
"0.48053753",
"0.4801905",
"0.4792469",
"0.4791872",
"0.4791334",
"0.47880068",
"0.47613615",
"0.47610217",
"0.47523135",
"0.4750839",
"0.47501808",
"0.47342384",
"0.4731248",
"0.47206426",
"0.4701576",
"0.4701576",
"0.47002345",
"0.46985424",
"0.46977195",
"0.4685074",
"0.468107",
"0.46783015",
"0.46608457",
"0.4660423",
"0.4649959",
"0.46485946",
"0.46374357",
"0.46227154",
"0.4619049",
"0.46131596",
"0.46017957",
"0.4590831",
"0.45721474",
"0.45628664",
"0.45624825",
"0.45622543",
"0.4560879",
"0.4559124",
"0.45571798",
"0.45567378",
"0.45509604",
"0.45484152",
"0.45444334",
"0.45439282",
"0.45419914",
"0.4539783",
"0.4536011",
"0.4532867",
"0.45275122",
"0.45259175",
"0.4523567",
"0.4522842",
"0.4519526",
"0.4518231",
"0.4510773",
"0.45084715",
"0.4506035",
"0.45028463",
"0.45005566",
"0.44959217",
"0.44949841",
"0.44924748",
"0.44893265",
"0.4489215",
"0.44886163",
"0.4487958",
"0.4482736",
"0.44756845",
"0.44660255",
"0.4465176",
"0.4454755",
"0.44537142",
"0.44536626",
"0.44486356"
] |
0.67510366
|
0
|
GET /drawings/1 GET /drawings/1.json
|
def show
@drawing = Drawing.find(params[:id])
render json: @drawing
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def index\n @drawings = Drawing.all\n end",
"def index\n @draws = Draw.paginate(:page => params[:page], :per_page => 50)\n @winning_draws = Draw.where(:selection => \"WINNER\")\n @draw = Draw.new\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @draws }\n end\n end",
"def show\n @draw = Draw.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @draw }\n end\n end",
"def drawings\n\t@drawings || read_drawings\n end",
"def drawings\n @drawings ||= []\n end",
"def show\n @draw_data = Draw.find_by_id params[:id]\n end",
"def new\n @drawing = Drawing.new\n\n render json: @drawing\n end",
"def index\n @drawables = Drawable.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @drawables }\n end\n end",
"def show\n @withdrawal = Withdrawal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @withdrawal }\n end\n end",
"def new\n @draw = Draw.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @draw }\n end\n end",
"def draw\n @deck = Deck.find(params[:id])\n drawed_cards = @deck.draw_five_cards\n render json: {\n cards: drawed_cards,\n deck_id: @deck.id,\n remaining: @deck.card_codes.count\n }\n end",
"def create\n @draw = Draw.new(params[:draw])\n\n respond_to do |format|\n if @draw.save\n format.html { redirect_to @draw, notice: 'Draw was successfully created.' }\n format.json { render json: @draw, status: :created, location: @draw }\n else\n format.html { render action: \"new\" }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @drawing = Drawing.new(params[:drawing])\n\n if @drawing.save\n render json: @drawing, status: :created, location: @drawing\n else\n render json: @drawing.errors, status: :unprocessable_entity\n end\n end",
"def create\n @draw = Draw.new(draw_params)\n respond_to do |format|\n if @draw.save\n format.html { redirect_to @draw, notice: 'Draw was successfully created.' }\n format.json { render :show, status: :created, location: @draw }\n else\n format.html { render :new }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @drawing = Drawing.new(drawing_params)\n\n respond_to do |format|\n if @drawing.save\n format.html { redirect_to @drawing, notice: 'Drawing was successfully created.' }\n format.json { render :show, status: :created, location: @drawing }\n else\n format.html { render :new }\n format.json { render json: @drawing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @sightings = Sighting.all\n render json: @sightings\n end",
"def destroy\n @draw = Draw.find(params[:id])\n @draw.destroy\n\n respond_to do |format|\n format.html { redirect_to draws_url }\n format.json { head :no_content }\n end\n end",
"def update\n @drawing = Drawing.find(params[:id])\n\n if @drawing.update_attributes(params[:drawing])\n head :no_content\n else\n render json: @drawing.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @draw.update(draw_params)\n format.html { redirect_to @draw, notice: 'Draw was successfully updated.' }\n format.json { render :show, status: :ok, location: @draw }\n else\n format.html { render :edit }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @draw = current_user.draws.find(params[:id])\n prevent_if_drawn\n \n @draw.destroy\n\n respond_to do |format|\n format.html { redirect_to draws_url }\n format.json { head :ok }\n end\n end",
"def set_drawing\n @drawing = Drawing.find(params[:id])\n end",
"def update\n @draw = Draw.find(params[:id])\n\n respond_to do |format|\n if @draw.update_attributes(params[:draw])\n format.html { redirect_to @draw, notice: 'Draw was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @draw = current_user.draws.find(params[:id])\n prevent_if_drawn\n\n respond_to do |format|\n if @draw.update_attributes(params[:draw])\n format.html { redirect_to @draw, notice: 'Draw was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @drawing.update(drawing_params)\n format.html { redirect_to @drawing, notice: 'Drawing was successfully updated.' }\n format.json { render :show, status: :ok, location: @drawing }\n else\n format.html { render :edit }\n format.json { render json: @drawing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_draw\n @draw = Draw.find(params[:id])\n end",
"def show\n @crossing = Crossing.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @crossing }\n end\n end",
"def show\n @internaldraw = Internaldraw.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @internaldraw }\n end\n end",
"def index\n sighting = Sighting.all \n render json: SightingSerializer.new(sighting)\n end",
"def show\n if @drawing.name == 'EllieDee'\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => JSON::parse(@drawing.to_json).merge(\"last_req\" => $last_req).to_json }\n end\n # @drawing['last_req'] = $last_req\n # render :json => Group.find(params[:id]), :methods => :message\n end\n end",
"def show\n @withdrawal_request = WithdrawalRequest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @withdrawal_request }\n end\n end",
"def show\n @polygon = Polygon.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @polygon }\n end\n end",
"def show\n render json: @dice\n end",
"def show\n animal = Animal.find(params[:id])\n #return all the sightings for the animal\n render json: animal.to_json(include: :sightings)\nend",
"def index\n @worksheet.workbook.drawings.index(self)\n end",
"def show\n @drawable = Drawable.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @drawable }\n end\n end",
"def index\n @biddings = Bidding.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @biddings }\n end\n end",
"def show\n @sighting = Sighting.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sighting }\n end\n end",
"def show\n @batting_line = BattingLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @batting_line }\n end\n end",
"def show\n @budgeting_type = BudgetingType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @budgeting_type }\n end\n end",
"def destroy\n @draw.destroy\n respond_to do |format|\n format.html { redirect_to draws_url, notice: 'Draw was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def show\n @balance = scope.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @balance }\n end\n end",
"def index\n @dices = Dice.all\n\n render json: @dices\n end",
"def index\n @withdraws = Withdraw.all\n end",
"def show\n @bidding = Bidding.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @bidding }\n end\n end",
"def get_document_drawing_object_by_index(request)\n data, _status_code, _headers = get_document_drawing_object_by_index_with_http_info(request)\n request_token if _status_code == 401\n data\n end",
"def show\n @boat = Boat.find(params[:id])\n\n render json: @boat\n end",
"def index\n @pricings = Pricing.all\n\n render json: @pricings\n end",
"def index\n @drawers = Drawer.all\n\n respond_to do |wants|\n wants.html # index.html.erb\n wants.xml { render :xml => @drawers }\n end\n end",
"def index\n @batting_lines = BattingLine.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @batting_lines }\n end\n end",
"def show\n @sighting = Sighting.find(params[:id])\n if @sighting\n render json: @sighting, status: :ok\n else\n render json: @sighting.errors, status: :unprocessable_entity\n end\n end",
"def index\n @funds = Fund.all\n\n render json: @funds\n end",
"def get_relevant_drawings(args={})\n nums = args[:nums]\n bonus = args[:bonus]\n \n drawings = Drawing.find_by_game_nums_and_bonus(@game.id,nums,bonus)\n\n #strip out records with no prize\n drawings.reject{|d| !has_prize({bonus_match: d.has_bonus_match(bonus),matches: d.matches_count(nums), game_slug: @game.slug })}\n end",
"def show\n sighting = Sighting.find(params[:id])\n #render json: sighting.to_json(:include => {:bird => {:only =>[:name, :species]}, :location => {:only =>[:latitude, :longitude]}}, :except => [:updated_at])\n end",
"def drawings\n return self.notice_relationships.map {|e| (e.pattern + \"/\" + e.drawing_revision.to_s).gsub(/\\/$/, '') }.join(\", \")\n end",
"def show\n @internship = Internship.find(params[:id])\n @diaries = Diary.where(:internship_id => @internship.id).paginate(:page => params[:page]).order('id DESC')\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @internship }\n end\n end",
"def show\n @booking = Booking.find(params[:id])\n render json: @booking\nend",
"def drawings\n Drawing.where(label: self)\n end",
"def appointed_draws\n draws.\n joins(:appointment).\n order('appointments.appointed_at ASC' )\n end",
"def index\n @fights = Fight.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @fights.to_json( :include => { :field_initial => { :only => [:name] }, :field_actual => { :only => [:name] }, :category => { :only => [:name] }, :competitor_blue => { :only => [:last_name, :lot_number] }, :competitor_red => { :only => [:last_name, :lot_number] }, :competitor_winner => { :only => [:last_name, :lot_number] }, :previous_fight_blue => { :only => [:id, :number], :include => { :field_initial => { :only => [:name] } } }, :previous_fight_red => { :only => [:id, :number], :include => { :field_initial => { :only => [:name] } } } } ) }\n end\n end",
"def show\n animal = Animal.find(params[:id])\n render json: animal.as_json(include: :sightings) \n end",
"def show\n @flight = Flight.find(params[:id])\n render json: @flight\n end",
"def index\n @flights = Flight.all\n render json: @flights\n end",
"def show\n @graphic = Graphic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @graphic }\n end\n end",
"def show\n @graphic = Graphic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @graphic }\n end\n end",
"def get_drawing_object_list\n\n begin\n str_uri = $product_uri + '/words/' + @filename + '/drawingObjects'\n signed_str_uri = Aspose::Cloud::Common::Utils.sign(str_uri)\n\n response_stream = RestClient.get(signed_str_uri, {:accept => 'application/json'})\n\n stream_hash = JSON.parse(response_stream)\n stream_hash['Code'] == 200 ? stream_hash['DrawingObjects']['List'] : false\n\n rescue Exception => e\n print e\n end\n\n end",
"def get_finding_info\n\t\tidDec = params[:idDec].to_i\n\t\tidMap = params[:idMap].to_i\n\t\thallazgo = Finding.where(\"decision_map_id = ? AND governance_decision_id = ?\", idMap, idDec).first\n\t\trespond_to do |format|\n\t\t\tformat.json {render json: hallazgo}\n \tend\n\tend",
"def show\n @balance_detail = scope.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @balance_detail }\n end\n end",
"def index\n @banks = Bank.all\n render json: @banks\n end",
"def index\n @budgets = Budget.find_owned_by current_user\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @budgets }\n end\n end",
"def burndown\n @sprint = Sprint.find(params[:id])\n\n respond_to do |format|\n format.html { \n @graph = open_flash_chart_object(800, 500, url_for( :action => 'burndown', :id => params[:id], :format => :json )) \n }\n format.json { \n chart = @sprint.flash_burndown\n render :text => chart, :layout => false\n }\n end\n end",
"def show\n @county = Entity.where(id: params[:id]).where(entity_type: 'County').first\n respond_with(@county) do |format|\n format.geojson { render text: @county.to_geojson }\n end\n end",
"def show\n render json: @sighting\n end",
"def index\n @sightings = Sighting.where(date: params[:start_date]..params[:end_date])\n render json: @sightings\n end",
"def destroy\n @drawing = Drawing.find(params[:id])\n @drawing.destroy\n\n head :no_content\n end",
"def serv_json\n \"http://api.dribbble.com/shots/popular?page=1\"\n end",
"def show\n @white_paper = WhitePaper.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @white_paper }\n end\n end",
"def show\n @bill = Bill.find(params[:id])\n\n render json: @bill\n end",
"def show\n @fund = Fund.friendly.find(params[:id])\n\n render json: @fund\n end",
"def new\n @withdrawal = Withdrawal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @withdrawal }\n end\n end",
"def show\n render \"api/v1/bounties/show\"\n end",
"def index\n @bills = @dwelling.bills\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @bills }\n end\n end",
"def get_brandings\n request :get, \"/v3/brandings.json\"\n end",
"def show\n @grant_round = GrantRound.find(params[:id])\n\n render json: @grant_round\n end",
"def show\n @distraction = Distraction.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @distraction }\n end\n end",
"def index\n @bookings = Booking.all\n\n render json: @bookings\n end",
"def all_booking_of_client\n\t\t@bookings = Booking.where(client_id: params[:client_id])\n\t\trender json: @bookings, status: 200\n\tend",
"def getbalance(args={})\n {\n :method=> \"GetBalances\"\n }.to_json\n end",
"def index\n @panel_billings = Panel::Billing.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @panel_billings }\n end\n end",
"def show\n @withdrawal = Withdrawal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @withdrawal }\n end\n end",
"def balances(id)\n get(\"/accounts/#{id}/balances\")\n end",
"def show\n @bank = Bank.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @bank }\n end\n end",
"def show\n @curve = Curve.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @curve }\n end\n end",
"def destroy\n @internaldraw = Internaldraw.find(params[:id])\n @internaldraw.destroy\n\n respond_to do |format|\n format.html { redirect_to(internaldraws_url) }\n format.xml { head :ok }\n end\n end",
"def show\n\t\t@booking = Booking.find(params[:id])\n\t\trender json: @booking, status: 200\n\tend",
"def show\n @holding = Holding.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @holding }\n end\n end",
"def show\n @ship = Ship.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ship }\n end\n end",
"def show\n @forest = Forest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @forest }\n end\n end",
"def show\n @bill_point = BillPoint.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @bill_point }\n end\n end",
"def show\n @kf_diary = Kf::Diary.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @kf_diary }\n end\n end",
"def show\n @bird = Bird.joins(:sightings).find(params[:id])\n if @bird\n render json: {\n \"bird\": @bird,\n \"sightings\": [@bird.sightings]\n }, status: :ok\n else\n render json: @bird.errors, status: :unprocessable_entity\n end\n end"
] |
[
"0.71373606",
"0.7108541",
"0.7031232",
"0.6586291",
"0.6414555",
"0.63620937",
"0.62450653",
"0.60835487",
"0.60278845",
"0.6012221",
"0.5936713",
"0.5911544",
"0.58977276",
"0.58437717",
"0.5809068",
"0.5800402",
"0.5795278",
"0.5788694",
"0.5782666",
"0.5779801",
"0.5744717",
"0.5721219",
"0.57041544",
"0.5659904",
"0.5650567",
"0.56390667",
"0.5631852",
"0.5618934",
"0.5610318",
"0.5597434",
"0.55943686",
"0.55794364",
"0.5567265",
"0.5561472",
"0.5547338",
"0.55268776",
"0.5526481",
"0.5520987",
"0.55018765",
"0.5497089",
"0.54675245",
"0.5467301",
"0.5426925",
"0.5411108",
"0.5400802",
"0.53897375",
"0.53843504",
"0.53825855",
"0.53752047",
"0.5362982",
"0.5350083",
"0.5348095",
"0.5320807",
"0.5318962",
"0.5313444",
"0.53134024",
"0.53120655",
"0.5305716",
"0.53040963",
"0.5303944",
"0.5302219",
"0.5297753",
"0.5283886",
"0.5283886",
"0.52563983",
"0.52519464",
"0.52447665",
"0.52377105",
"0.52316344",
"0.5230865",
"0.52266425",
"0.5219541",
"0.521857",
"0.52137387",
"0.52083915",
"0.52049786",
"0.5204537",
"0.5193177",
"0.5190262",
"0.518745",
"0.5185699",
"0.5185593",
"0.51802474",
"0.5175741",
"0.5175545",
"0.51701957",
"0.5168332",
"0.51427746",
"0.51427215",
"0.51373434",
"0.51300365",
"0.5124023",
"0.51239705",
"0.51234674",
"0.5122096",
"0.5120564",
"0.5120339",
"0.5119839",
"0.5117954",
"0.51179373"
] |
0.74483734
|
0
|
GET /drawings/new GET /drawings/new.json
|
def new
@drawing = Drawing.new
render json: @drawing
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def new\n @draw = Draw.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @draw }\n end\n end",
"def new\n @withdrawal = Withdrawal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @withdrawal }\n end\n end",
"def create\n @draw = Draw.new(params[:draw])\n\n respond_to do |format|\n if @draw.save\n format.html { redirect_to @draw, notice: 'Draw was successfully created.' }\n format.json { render json: @draw, status: :created, location: @draw }\n else\n format.html { render action: \"new\" }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @drawing = Drawing.new(params[:drawing])\n\n if @drawing.save\n render json: @drawing, status: :created, location: @drawing\n else\n render json: @drawing.errors, status: :unprocessable_entity\n end\n end",
"def create\n @drawing = Drawing.new(drawing_params)\n\n respond_to do |format|\n if @drawing.save\n format.html { redirect_to @drawing, notice: 'Drawing was successfully created.' }\n format.json { render :show, status: :created, location: @drawing }\n else\n format.html { render :new }\n format.json { render json: @drawing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @draw = Draw.new(draw_params)\n respond_to do |format|\n if @draw.save\n format.html { redirect_to @draw, notice: 'Draw was successfully created.' }\n format.json { render :show, status: :created, location: @draw }\n else\n format.html { render :new }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @withdrawal_request = WithdrawalRequest.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @withdrawal_request }\n end\n end",
"def new\n @holding = Holding.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @holding }\n end\n end",
"def new\n @holding = Holding.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @holding }\n end\n end",
"def index\n @draws = Draw.paginate(:page => params[:page], :per_page => 50)\n @winning_draws = Draw.where(:selection => \"WINNER\")\n @draw = Draw.new\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @draws }\n end\n end",
"def new\n @polygon = Polygon.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @polygon }\n end\n end",
"def create\n @lucky_draw = LuckyDraw.new(lucky_draw_params)\n\n respond_to do |format|\n if @lucky_draw.save\n format.html { redirect_to lucky_draws_path }\n format.json { render :show, status: :created, location: @lucky_draw }\n else\n format.html { render :new }\n format.json { render json: @lucky_draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @internaldraw = Internaldraw.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @internaldraw }\n end\n end",
"def new\n @stalking = Stalking.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stalking }\n end\n end",
"def new\n @shipping = scope.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @shipping }\n end\n end",
"def new\n @goat = Goat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @goat }\n end\n end",
"def new\n @sighting = Sighting.new\n\t@types = Type.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sighting }\n end\n end",
"def new\n @budgeting_type = BudgetingType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @budgeting_type }\n end\n end",
"def new\n @party = Party.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @party }\n end\n end",
"def create\n @internaldraw = Internaldraw.new(params[:internaldraw])\n\n respond_to do |format|\n if @internaldraw.save\n format.html { redirect_to(@internaldraw, :notice => 'Internaldraw was successfully created.') }\n format.xml { render :xml => @internaldraw, :status => :created, :location => @internaldraw }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @internaldraw.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @withdrawal = Withdrawal.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @withdrawal }\n end\n end",
"def new\n @flight = Flight.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @flight }\n end\n end",
"def new\n @inning = Inning.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @inning }\n end\n end",
"def show\n @drawing = Drawing.find(params[:id])\n\n render json: @drawing\n end",
"def new\n @boat = Boat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json {render json: @boat}\n end\n end",
"def new\n @generation = Generation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @generation }\n end\n end",
"def new\n @breadcrumb = 'create'\n @bank = Bank.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @bank }\n end\n end",
"def new\n @bank = Bank.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @bank }\n end\n end",
"def new\n @wedding = Wedding.new\n @services = Service.all\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @wedding }\n end\n end",
"def new\n @ship = Ship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ship }\n end\n end",
"def new\n @lost = Lost.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lost }\n end\n end",
"def new\n @borrow = Borrow.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @borrow }\n end\n end",
"def new\n tournament = Tournament.find(params[:tournament_id])\n @registration = Registration.new(tournament:tournament)\n tournament.draws.order('draws.is_single DESC, draws.title').each do |draw|\n @registration.draw_registrations.build(draw_id: draw.id)\n end\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @registration }\n end\n end",
"def new\n \n @ship = Ship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ship }\n end\n end",
"def new\n @ped = Ped.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ped }\n end\n end",
"def new\n @drawable = Drawable.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @drawable }\n end\n end",
"def new\n @batting_line = BattingLine.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @batting_line }\n end\n end",
"def new\n @bill = Bill.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @bill }\n end\n end",
"def new\n @bill = Bill.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @bill }\n end\n end",
"def new\n fetch_data\n @payment = Payment.new(:payment_date => Date.today)\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @payment }\n end\n end",
"def new\n @bill_point = BillPoint.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @bill_point }\n end\n end",
"def new\n @dotsmember = Dotsmember.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @dotsmember }\n end\n end",
"def new\n @landing = Landing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @landing }\n end\n end",
"def new\n @lineup = Lineup.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lineup }\n end\n end",
"def new\n @bill = @dwelling.bills.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @bill }\n end\n end",
"def new\n @line = Line.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line }\n end\n end",
"def new\n @budget = Budget.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @budget }\n end\n end",
"def new\n @listing = Listing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @listing }\n end\n end",
"def new\n @listing = Listing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @listing }\n end\n end",
"def new\n @listing = Listing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @listing }\n end\n end",
"def new\n @closing_day = ClosingDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @closing_day }\n end\n end",
"def new\n @hold_date = HoldDate.new\n @customer_names = Customer.all(:order => 'last_name ASC')\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @hold_date }\n end\n end",
"def new\n @distraction = Distraction.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @distraction }\n end\n end",
"def new\n @shooting = Shooting.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @shooting }\n end\n end",
"def new\n @title = t('view.banks.new_title')\n @bank = Bank.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @bank }\n end\n end",
"def new\n @ped_strategy = PedStrategy.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ped_strategy }\n end\n end",
"def new\n @pickup = Pickup.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @pickup }\n end\n end",
"def new\n @gpath = Gpath.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gpath }\n end\n end",
"def new\n @listing = Listing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json => @listing }\n end\n end",
"def new\n @dayoff = Dayoff.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @dayoff }\n end\n end",
"def new\n @green = Green.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @green }\n end\n end",
"def new\r\n @bill = Bill.new\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.json { render json: @bill }\r\n end\r\n end",
"def new\n @round = Round.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @round }\n end\n end",
"def new\n @shipping_line = ShippingLine.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @shipping_line }\n end\n end",
"def new\n @point = Point.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @point }\n end\n end",
"def new\n @finance = Finance.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @finance }\n end\n end",
"def new\n @crossing = Crossing.new(trip_report_id: params[:trip_report_id])\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @crossing }\n end\n end",
"def new\n @strategy = Strategy.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @strategy }\n end\n end",
"def new\n @internship = Internship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @internship }\n end\n end",
"def new\n @internship = Internship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @internship }\n end\n end",
"def new\n @posting = Posting.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @posting }\n end\n end",
"def new\n\t\t@household = Household.new\n\n\t\trespond_to do |format|\n\t\t\tformat.html # new.html.erb\n\t\t\tformat.json { render json: @household }\n\t\tend\n\tend",
"def new\n @seat = Seat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @seat }\n end\n end",
"def new\n @budget = Budget.new\n\n respond_to do |format|\n format.html # new.html.erb\n # format.json { render json: @budget }\n end\n end",
"def new\n @breakdown = Breakdown.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @breakdown }\n end\n end",
"def new\n @basis = Base.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @basis }\n end\n end",
"def new\n @fight = Fight.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fight }\n end\n end",
"def new\n @ongoing = Ongoing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ongoing }\n end\n end",
"def new\n @click = Click.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @click }\n end\n end",
"def new\n @dartboard = Dartboard.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @dartboard }\n end\n end",
"def new\n @debt = Debt.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @debt }\n end\n end",
"def new\n @debt = Debt.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @debt }\n end\n end",
"def new\n @page = 'newdoll'\n @doll = current_user.dolls.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @doll }\n end\n end",
"def new\n @layer = Layer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @layer }\n end\n end",
"def new\n @dependent_relationship = DependentRelationship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @dependent_relationship }\n end\n end",
"def new\n @debt = Debt.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @debt }\n end\n end",
"def new\n @floor = Floor.new(dungeon_id: params[:dungeon_id])\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @floor }\n end\n end",
"def new\n @borrow_request = BorrowRequest.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @borrow_request }\n end\n end",
"def new\n @externaldraw = Externaldraw.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @externaldraw }\n end\n end",
"def new\n @dragon = Dragon.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @dragon }\n end\n end",
"def new\n @widget = Widget.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @widget }\n end\n end",
"def new\n @observation = Observation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @observation }\n end\n end",
"def new\n @observation = Observation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @observation }\n end\n end",
"def new\n @polygon_mark = PolygonMark.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @polygon_mark }\n end\n end",
"def new\n @winning_number = WinningNumber.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @winning_number }\n end\n end",
"def new\n @booking = Booking.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @booking }\n end\n end",
"def new\n @booking = Booking.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @booking }\n end\n end",
"def new\n @neighborhood = Neighborhood.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @neighborhood }\n end\n end",
"def new\n @neighborhood = Neighborhood.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @neighborhood }\n end\n end",
"def new\n @pokeparty = Pokeparty.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @pokeparty }\n end\n end"
] |
[
"0.75208336",
"0.6978218",
"0.69780195",
"0.6862454",
"0.68167627",
"0.6771684",
"0.6691346",
"0.6449592",
"0.6449592",
"0.639493",
"0.6382087",
"0.636552",
"0.63246375",
"0.63104844",
"0.63050336",
"0.6297263",
"0.62531143",
"0.62492716",
"0.6231992",
"0.61975193",
"0.6183648",
"0.6176668",
"0.6165515",
"0.6142476",
"0.61340594",
"0.61306584",
"0.6129614",
"0.6110609",
"0.61081547",
"0.6107637",
"0.610447",
"0.6102939",
"0.609955",
"0.6084903",
"0.60771406",
"0.60551345",
"0.60425043",
"0.604109",
"0.604109",
"0.6038204",
"0.60333186",
"0.6031124",
"0.60301733",
"0.60266066",
"0.60258925",
"0.6018045",
"0.6017189",
"0.6012117",
"0.6012117",
"0.6012117",
"0.6011785",
"0.60037047",
"0.59945524",
"0.59838235",
"0.5977905",
"0.59705067",
"0.59692764",
"0.59677005",
"0.5960139",
"0.59564847",
"0.5954882",
"0.5953557",
"0.5952934",
"0.5949954",
"0.5946511",
"0.59461284",
"0.5944954",
"0.59420794",
"0.5939751",
"0.5939751",
"0.59372985",
"0.5932365",
"0.59299254",
"0.59271973",
"0.5924252",
"0.59228003",
"0.5921362",
"0.59208983",
"0.5919329",
"0.59159404",
"0.59154963",
"0.59154963",
"0.5905899",
"0.5902985",
"0.5902447",
"0.58927816",
"0.5892284",
"0.5889364",
"0.5887879",
"0.5887052",
"0.58867854",
"0.58859146",
"0.58859146",
"0.5883416",
"0.5883231",
"0.58825666",
"0.58825666",
"0.5879813",
"0.5879813",
"0.58794093"
] |
0.7591941
|
0
|
POST /drawings POST /drawings.json
|
def create
@drawing = Drawing.new(params[:drawing])
if @drawing.save
render json: @drawing, status: :created, location: @drawing
else
render json: @drawing.errors, status: :unprocessable_entity
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def create\n @drawing = Drawing.new(drawing_params)\n\n respond_to do |format|\n if @drawing.save\n format.html { redirect_to @drawing, notice: 'Drawing was successfully created.' }\n format.json { render :show, status: :created, location: @drawing }\n else\n format.html { render :new }\n format.json { render json: @drawing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @draw = Draw.new(params[:draw])\n\n respond_to do |format|\n if @draw.save\n format.html { redirect_to @draw, notice: 'Draw was successfully created.' }\n format.json { render json: @draw, status: :created, location: @draw }\n else\n format.html { render action: \"new\" }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @draw = Draw.new(draw_params)\n respond_to do |format|\n if @draw.save\n format.html { redirect_to @draw, notice: 'Draw was successfully created.' }\n format.json { render :show, status: :created, location: @draw }\n else\n format.html { render :new }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def drawing_params\n params.require(:drawing).permit(:name, :leds, :user_id, :leds => [])\n end",
"def index\n @draws = Draw.paginate(:page => params[:page], :per_page => 50)\n @winning_draws = Draw.where(:selection => \"WINNER\")\n @draw = Draw.new\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @draws }\n end\n end",
"def index\n @drawings = Drawing.all\n end",
"def new\n @drawing = Drawing.new\n\n render json: @drawing\n end",
"def create\n @structure_drawing = @sub_project.structure_drawings.build(structure_drawing_params)\n\n respond_to do |format|\n if @structure_drawing.save\n format.html { redirect_to project_sub_project_structure_drawings_path(@project, @sub_project), notice: 'Structure drawing was successfully created.' }\n format.json { render :show, status: :created, location: @structure_drawing }\n else\n format.html { render :new }\n format.json { render json: @structure_drawing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @drawing = Drawing.find(params[:id])\n\n if @drawing.update_attributes(params[:drawing])\n head :no_content\n else\n render json: @drawing.errors, status: :unprocessable_entity\n end\n end",
"def post_drawing_object(request)\n data, _status_code, _headers = post_drawing_object_with_http_info(request)\n request_token if _status_code == 401\n data\n end",
"def create\n @sighting = Sighting.new(sighting_params)\n\n if @sighting.save\n render json: @sighting, status: :created, location: @sighting\n else\n render json: @sighting.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @drawing.update(drawing_params)\n format.html { redirect_to @drawing, notice: 'Drawing was successfully updated.' }\n format.json { render :show, status: :ok, location: @drawing }\n else\n format.html { render :edit }\n format.json { render json: @drawing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @lucky_draw = LuckyDraw.new(lucky_draw_params)\n\n respond_to do |format|\n if @lucky_draw.save\n format.html { redirect_to lucky_draws_path }\n format.json { render :show, status: :created, location: @lucky_draw }\n else\n format.html { render :new }\n format.json { render json: @lucky_draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def draw_params\n params.require(:draw).permit(:email, :drawtype)\n end",
"def update\n respond_to do |format|\n if @draw.update(draw_params)\n format.html { redirect_to @draw, notice: 'Draw was successfully updated.' }\n format.json { render :show, status: :ok, location: @draw }\n else\n format.html { render :edit }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @sighting = Sighting.new(sighting_params)\n\n if @sighting.save\n render json: @sighting, status: :created, location: @sighting\n else\n render json: @sighting.errors, status: :unprocessable_entity\n end\n end",
"def drawings\n @drawings ||= []\n end",
"def show\n @drawing = Drawing.find(params[:id])\n\n render json: @drawing\n end",
"def create\n @internaldraw = Internaldraw.new(params[:internaldraw])\n\n respond_to do |format|\n if @internaldraw.save\n format.html { redirect_to(@internaldraw, :notice => 'Internaldraw was successfully created.') }\n format.xml { render :xml => @internaldraw, :status => :created, :location => @internaldraw }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @internaldraw.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n sighting = Sighting.create(sighting_params)\n if sighting.valid?\n render json: sighting\n else\n render json: sighting.errors\n end\n end",
"def new\n @draw = Draw.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @draw }\n end\n end",
"def draw\n @deck = Deck.find(params[:id])\n drawed_cards = @deck.draw_five_cards\n render json: {\n cards: drawed_cards,\n deck_id: @deck.id,\n remaining: @deck.card_codes.count\n }\n end",
"def create\n @stroke = Stroke.new(stroke_params)\n\n respond_to do |format|\n if @stroke.save\n format.html { redirect_to @stroke, notice: 'Stroke was successfully created.' }\n format.json { render :show, status: :created, location: @stroke }\n else\n format.html { render :new }\n format.json { render json: @stroke.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @draw = current_user.draws.find(params[:id])\n prevent_if_drawn\n\n respond_to do |format|\n if @draw.update_attributes(params[:draw])\n format.html { redirect_to @draw, notice: 'Draw was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def drawings\n\t@drawings || read_drawings\n end",
"def destroy\n @draw = current_user.draws.find(params[:id])\n prevent_if_drawn\n \n @draw.destroy\n\n respond_to do |format|\n format.html { redirect_to draws_url }\n format.json { head :ok }\n end\n end",
"def update\n @draw = Draw.find(params[:id])\n\n respond_to do |format|\n if @draw.update_attributes(params[:draw])\n format.html { redirect_to @draw, notice: 'Draw was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_drawing\n @drawing = Drawing.find(params[:id])\n end",
"def new\n tournament = Tournament.find(params[:tournament_id])\n @registration = Registration.new(tournament:tournament)\n tournament.draws.order('draws.is_single DESC, draws.title').each do |draw|\n @registration.draw_registrations.build(draw_id: draw.id)\n end\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @registration }\n end\n end",
"def destroy\n @draw.destroy\n respond_to do |format|\n format.html { redirect_to draws_url, notice: 'Draw was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def update\n respond_to do |format|\n if @structure_drawing.update(structure_drawing_params)\n format.html { redirect_to project_sub_project_structure_drawings_path(@project, @sub_project), notice: 'Structure drawing was successfully updated.' }\n format.json { render :show, status: :ok, location: @structure_drawing }\n else\n format.html { render :edit }\n format.json { render json: @structure_drawing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @dice = Dice.new(dice_params)\n\n if @dice.save\n render json: @dice, status: :created, location: @dice\n else\n render json: @dice.errors, status: :unprocessable_entity\n end\n end",
"def destroy\n @draw = Draw.find(params[:id])\n @draw.destroy\n\n respond_to do |format|\n format.html { redirect_to draws_url }\n format.json { head :no_content }\n end\n end",
"def round_params\n params.require(:round).permit(:debate_id, :round_number, :start_time, :end_time, :status)\n end",
"def stroke_params\n params.require(:stroke).permit(:theta_id, :type_id, :shape_id, :pos)\n end",
"def create\n @wedding = Wedding.new(params[:wedding])\n if (!params[:wedding][:service_type_ids])\n params[:wedding][:service_type_ids] = params[:wedding][:service_type_ids].split(';')\n end\n params[:wedding][:service_type_ids] ||= []\n ServiceType.all.each do |service_type|\n @wedding.service_types_weddings << ServiceTypesWedding.create(:service_type_id => service_type.id, \n :wedding_id => @wedding.id,\n :activated => params[:wedding][:service_type_ids].include?(service_type.id.to_s))\n end\n\n respond_to do |format|\n if @wedding.save\n format.html { redirect_to @wedding, notice: 'Wedding was successfully created.' }\n format.json { render json: @wedding, status: :created, location: @wedding }\n else\n format.html { render action: \"new\" }\n format.json { render json: @wedding.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create \n\t\ttimestamp = Time.now.to_s\n File.open(\"#{Rails.root}/public/uploads/drawing_#{timestamp}.png\", 'wb') do |f|\n f.write(params[:image].read)\n end\n drawing = Drawing.new\n drawing.drawing_img = \"/uploads/drawing_#{timestamp}.png\"\n drawing.word_id = params[:word_id]\n drawing.save\n render nothing: true\n\tend",
"def index\n @sightings = Sighting.all\n render json: @sightings\n end",
"def painting_params\n params.require(:painting).permit(:trees, :river, :cabin, :beach, :mountains, :waterfall, :guest, :animalguest, :startcolour, :shape, :likes, :artwork, :profile_id, :episode, :season, :other)\n end",
"def create\n @withdrawal_request = WithdrawalRequest.new(withdrawal_request_params)\n\n respond_to do |format|\n if @withdrawal_request.save\n format.html { redirect_to @withdrawal_request, notice: 'Withdrawal request was successfully created.' }\n format.json { render :show, status: :created, location: @withdrawal_request }\n else\n format.html { render :show }\n format.json { render json: @withdrawal_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def mark_drawn!\n # update point tables\n game.point_tables.create(started_at: game.started_at, ended_at: Time.zone.now, result: 'Draw')\n\n # reset board!\n reset_board!\n\n game.update_status(Game::DRAWN)\n end",
"def create\n @sighting = Sighting.new(params[:sighting])\n\n respond_to do |format|\n if @sighting.save\n format.html { redirect_to \"/static_pages/home\", notice: 'Sighting was successfully created.' }\n format.json { render json: @sighting, status: :created, location: @sighting }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sighting.errors, status: :unprocessable_entity }\n end\n end\n end",
"def show\n @draw = Draw.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @draw }\n end\n end",
"def create\n @crossing = Crossing.new(params[:crossing])\n\n respond_to do |format|\n if @crossing.save\n format.html { redirect_to @crossing.trip_report, notice: 'Crossing was successfully created.' }\n format.json { render json: @crossing, status: :created, location: @crossing }\n else\n format.html { render action: \"new\" }\n format.json { render json: @crossing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @white_paper = WhitePaper.new(params[:white_paper])\n\n respond_to do |format|\n if @white_paper.save\n format.html { redirect_to @white_paper, notice: 'White paper was successfully created.' }\n format.json { render json: @white_paper, status: :created, location: @white_paper }\n else\n format.html { render action: \"new\" }\n format.json { render json: @white_paper.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @printing = Printing.new(printing_params)\n\n respond_to do |format|\n if @printing.save\n format.html { redirect_to @printing, notice: 'Printing was successfully created.' }\n format.json { render action: 'show', status: :created, location: @printing }\n else\n format.html { render action: 'new' }\n format.json { render json: @printing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def withdraw_params\n params.require(:withdraw).permit(:amount)\n end",
"def set_draw\n @draw = Draw.find(params[:id])\n end",
"def destroy\n @drawing.destroy\n respond_to do |format|\n format.html { redirect_to :back, notice: 'Drawing was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def dosing_params\n params.require(:dosing).permit(:attack_id, :drug_id, :dosed_at)\n end",
"def create\n @wedding = Wedding.new(params[:wedding])\n\n respond_to do |format|\n if @wedding.save\n format.html { redirect_to inhabitants_path }\n format.json { render inhabitants_path }\n else\n format.html { render action: \"new\" }\n format.json { render json: @wedding.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @bill = Bill.find(params[:bill_id])\n @breakdown = @bill.breakdowns.build(params[:breakdown])\n @breakdown.save\n\n redirect_to @bill\n\n #respond_to do |format|\n #if @breakdown.save\n #format.html { redirect_to @breakdown, notice: 'Breakdown was successfully created.' }\n #format.json { render json: @breakdown, status: :created, location: @breakdown }\n #else\n #format.html { render action: \"new\" }\n #format.json { render json: @breakdown.errors, status: :unprocessable_entity }\n #end\n #end\n end",
"def add_drawing_object(drawing)\n @drawings << drawing\n end",
"def save_financials\n current_user.update(assets: params[:assets], average_annual_income: params[:average_annual_income], credit_score: params[:credit_score], total_debt: params[:total_debt])\n user_listings = current_user.listings\n render json: [current_user, user_listings]\n end",
"def create\n @grant_round = GrantRound.new(grant_round_params(params[:grant_round]))\n\n if @grant_round.save\n render json: @grant_round, status: :created, location: @grant_round\n else\n render json: @grant_round.errors, status: :unprocessable_entity\n end\n end",
"def create\n @trace = Trace.new\n if @trace.save\n @trace.import_points(points_data)\n status = :created\n else\n status = :bad_request\n end\n\n render json: @trace, status: status\n end",
"def create\n\n @listing = Listing.new(listing_params)\n\n @listing.save\n\n render json: @listing\n redirect_to listings_path # redirect to home page\n end",
"def update\n respond_to do |format|\n if @lucky_draw.update(lucky_draw_params)\n format.html { redirect_to @lucky_draw, notice: 'Lucky draw was successfully updated.' }\n format.json { render :show, status: :ok, location: @lucky_draw }\n else\n format.html { render :edit }\n format.json { render json: @lucky_draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @scrapping_datum = ScrappingDatum.new(scrapping_datum_params)\n\n respond_to do |format|\n if @scrapping_datum.save\n format.html { redirect_to @scrapping_datum, notice: 'Scrapping datum was successfully created.' }\n format.json { render :show, status: :created, location: @scrapping_datum }\n else\n format.html { render :new }\n format.json { render json: @scrapping_datum.errors, status: :unprocessable_entity }\n end\n end\n end",
"def sighting_params\n params.require(:sighting).permit(:day, :latitude, :longitude)\n end",
"def create\n @polygon = Polygon.new(params[:polygon])\n\n respond_to do |format|\n if @polygon.save\n format.html { redirect_to @polygon, notice: 'Polygon was successfully created.' }\n format.json { render json: @polygon, status: :created, location: @polygon }\n else\n format.html { render action: \"new\" }\n format.json { render json: @polygon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @round = Round.new(round_params)\n\n respond_to do |format|\n if @round.save\n format.html { redirect_to @round.debate }\n format.json { render :show, status: :created, location: @round }\n else\n format.html { render :new }\n format.json { render json: @round.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @crossing = Crossing.new(crossing_params)\n\n respond_to do |format|\n if @crossing.save\n format.html { redirect_to @crossing, notice: 'Crossing was successfully created.' }\n format.json { render :show, status: :created, location: @crossing }\n else\n format.html { render :new }\n format.json { render json: @crossing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @drawer = Drawer.new(params[:drawer].permit(:label, :row, :column))\n\n respond_to do |wants|\n if @drawer.save\n flash[:notice] = 'Drawer was successfully created.'\n wants.html { redirect_to(\"/drawers/new\") }\n wants.xml { render :xml => @drawer, :status => :created, :location => @drawer }\n else\n wants.html { render :action => \"new\" }\n wants.xml { render :xml => @drawer.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @outing = Outing.new(params[:outing])\n\n respond_to do |format|\n if @outing.save\n format.html { redirect_to @outing, notice: 'Outing was successfully created.' }\n format.json { render json: @outing, status: :created, location: @outing }\n else\n format.html { render action: \"new\" }\n format.json { render json: @outing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @dog_poly = DogPoly.new(dog_poly_params)\n\n respond_to do |format|\n if @dog_poly.save\n format.html { redirect_to @dog_poly, notice: 'Dog poly was successfully created.' }\n format.json { render :show, status: :created, location: @dog_poly }\n else\n format.html { render :new }\n format.json { render json: @dog_poly.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @wing = Wing.new(wing_params)\n\n respond_to do |format|\n if @wing.save\n format.html { redirect_to @wing, notice: 'Wing was successfully created.' }\n format.json { render :show, status: :created, location: @wing }\n else\n format.html { render :new }\n format.json { render json: @wing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @diningt = Diningt.new(diningt_params)\n\n respond_to do |format|\n if @diningt.save\n format.html { redirect_to @diningt, notice: 'Diningt was successfully created.' }\n format.json { render :show, status: :created, location: @diningt }\n else\n format.html { render :new }\n format.json { render json: @diningt.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n pay_period_id = params[:withdrawal].delete(:pay_period_id)\n params[:withdrawal][:pay_period_id] = pay_period_id || current_user.current_pay_period.id\n @withdrawal = Withdrawal.new(params[:withdrawal])\n\n respond_to do |format|\n if @withdrawal.save\n format.html { redirect_to @withdrawal.pay_period, notice: 'Withdrawal was successfully created.' }\n format.json { render json: @withdrawal.pay_period, status: :created, location: @withdrawal.pay_period }\n else\n format.html { render action: \"new\" }\n format.json { render json: @withdrawal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n sighting = Sighting.all \n render json: SightingSerializer.new(sighting)\n end",
"def create\n @externaldraw = Externaldraw.new(params[:externaldraw])\n\n respond_to do |format|\n if @externaldraw.save\n format.html { redirect_to(@externaldraw, :notice => 'Externaldraw was successfully created.') }\n format.xml { render :xml => @externaldraw, :status => :created, :location => @externaldraw }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @externaldraw.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @bathroom = Bathroom.new(bathroom_params.except(:stalls))\n num_stalls = bathroom_params[:stalls].to_i\n\n respond_to do |format|\n if @bathroom.save\n (0..(num_stalls - 1)).each do |i|\n Stall.new({ bathroom_id: @bathroom.id, state: false, number: @bathroom.stalls.count }).save\n end\n format.html { redirect_to @bathroom, notice: 'Bathroom was successfully created.' }\n format.json { render :show, status: :created, location: @bathroom }\n else\n format.html { render :new }\n format.json { render json: @bathroom.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @drink = Drink.new(drink_params)\n\n respond_to do |format|\n if @drink.save\n format.html { redirect_to new_drink_path, notice: 'Drycken skapades.' }\n format.json { render :show, status: :created, location: @drink }\n else\n format.html { render :new }\n format.json { render json: @drink.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @debate = Debate.new\n @debate.title = params[:title]\n @debate.image = params[:image]\n @debate.content = params[:content]\n @debate.user_id = current_user.id\n\n respond_to do |format|\n if @debate.save\n if params[:points]\n params[:points].each do |p|\n Point.create(user_id: current_user.id, debate_id: @debate.id, title: p)\n end\n end\n format.html { redirect_to @debate, notice: 'Debate was successfully created.' }\n format.json { render :show, status: :created, location: @debate }\n else\n format.html { render :new }\n format.json { render json: @debate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @shiping = Shiping.new(shiping_params)\n @user = current_user\n\n respond_to do |format|\n if @shiping.save\n format.html { redirect_to @shiping, notice: 'Shiping was successfully created.' }\n format.json { render :show, status: :created, location: @shiping }\n else\n format.html { render :new }\n format.json { render json: @shiping.errors, status: :unprocessable_entity }\n end\n end\n end",
"def sighting_params\n params.require(:sighting).permit(:comment, :location, :date, :size, :user_id)\n end",
"def create\n @flight = Flight.new(params[:flight])\n\n if @flight.save\n render json: @flight, status: :created, location: @flight\n else\n render json: @flight.errors, status: :unprocessable_entity\n end\n end",
"def create\n booking = Booking.create(booking_params)\n render json: booking\n end",
"def create\n @tier_filling = TierFilling.new(tier_filling_params)\n\n respond_to do |format|\n if @tier_filling.save\n format.html { redirect_to @tier_filling, notice: 'Tier filling was successfully created.' }\n format.json { render :show, status: :created, location: @tier_filling }\n else\n format.html { render :new }\n format.json { render json: @tier_filling.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @winding = Winding.new(winding_params)\n #Codigo para gerar gcode a 90 graus\n generate_gcode\n\n respond_to do |format|\n if @winding.save\n format.html { redirect_to @winding, notice: 'Winding was successfully created.' }\n format.json { render :show, status: :created, location: @winding }\n else\n format.html { render :new }\n format.json { render json: @winding.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @holding = Holding.new(params[:holding].merge(@yahoo_data))\n\n respond_to do |format|\n if @holding.save\n format.html { redirect_to @holding, notice: 'Holding was successfully created.' }\n format.json { render json: @holding, status: :created, location: @holding }\n else\n format.html { render action: \"new\" }\n format.json { render json: @holding.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @dino = Dino.new(dino_params)\n\n if @dino.save\n render json: @dino, status: :created, location: @dino\n else\n render json: @dino.errors, status: :unprocessable_entity\n end\n end",
"def appointed_draws\n draws.\n joins(:appointment).\n order('appointments.appointed_at ASC' )\n end",
"def create\n @ending = Ending.new(ending_params)\n\n respond_to do |format|\n if @ending.save\n format.html { redirect_to @ending, notice: 'Ending was successfully created.' }\n format.json { render :show, status: :created, location: @ending }\n else\n format.html { render :new }\n format.json { render json: @ending.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @holding = current_user.holdings.build(holding_params)\n\n respond_to do |format|\n if @holding.save\n format.html { redirect_to @holding, notice: 'Holding was successfully created.' }\n format.json { render :show, status: :created, location: @holding }\n else\n format.html { render :new }\n format.json { render json: @holding.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @bidding = Bidding.new(params[:bidding])\n\n respond_to do |format|\n if @bidding.save\n format.html { redirect_to @bidding, notice: 'Bidding was successfully created.' }\n format.json { render json: @bidding, status: :created, location: @bidding }\n else\n format.html { render action: \"new\" }\n format.json { render json: @bidding.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\n @drawing = Drawing.new(form_params)\n @drawing.picture = PictureAttachmentHelper.convert_data_uri_to_upload(params[\"picture\"])\n @drawing.save\n redirect_to root_path\n end",
"def create\n\t\t# A drink is instantiated by the current user\n\t\t@drink = current_user.drinks.build(drink_params)\n\t\t# If the drink instance is saved as a record in our db\n\t\tif\t@drink.save \n\t\t\t# render json for that drink instance\n\t\t\trender :json => @drink\n\t\telse \n\t\t\t# otherwise render json in the for of an error\n\t\t\trender :json => { :errors => @drink.errors.full_messages}, :status => 422\n\t\tend\n\tend",
"def create\n @painting.artwork.attach(params[:painting][:artwork])\n @profile = Profile.new \n @profile.id = current_user.profile.id #current_user = device and need to sign in\n @profile.save\n @painting.profile_id = @profile.id\n\n respond_to do |format|\n if @painting.save\n format.html { redirect_to @painting, notice: 'Painting was successfully created.' }\n format.json { render :show, status: :created, location: @painting }\n else\n format.html { render :new }\n format.json { render json: @painting.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @ship_fitting = ShipFitting.new(ship_fitting_params)\n\n respond_to do |format|\n if @ship_fitting.save\n format.html { redirect_to @ship_fitting, notice: 'Ship fitting was successfully created.' }\n format.json { render :show, status: :created, location: @ship_fitting }\n else\n format.html { render :new }\n format.json { render json: @ship_fitting.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @drawable = Drawable.new(params[:drawable])\n\n respond_to do |format|\n if @drawable.save\n format.html { redirect_to @drawable, notice: 'Drawable was successfully created.' }\n format.json { render json: @drawable, status: :created, location: @drawable }\n else\n format.html { render action: \"new\" }\n format.json { render json: @drawable.errors, status: :unprocessable_entity }\n end\n end\n end",
"def planting_params\n params.require(:planting).permit(:date, :seed_treated, :soil_condition, :grow_id)\n end",
"def create\n @savings = Savings.new(params[:savings])\n\n respond_to do |format|\n if @savings.save\n flash[:notice] = 'Savings was successfully created.'\n format.html { redirect_to(@savings) }\n format.xml { render :xml => @savings, :status => :created, :location => @savings }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @savings.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @withdrawal = Withdrawal.new(params[:withdrawal])\n\n respond_to do |format|\n if @withdrawal.save\n flash[:notice] = 'Withdrawal was successfully created.'\n format.html { redirect_to(@withdrawal) }\n format.xml { render :xml => @withdrawal, :status => :created, :location => @withdrawal }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @withdrawal.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @batting_line = BattingLine.new(params[:batting_line])\n\n respond_to do |format|\n if @batting_line.save\n format.html { redirect_to @batting_line, notice: 'Batting line was successfully created.' }\n format.json { render json: @batting_line, status: :created, location: @batting_line }\n else\n format.html { render action: \"new\" }\n format.json { render json: @batting_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def booking_params\n params.require(:booking).permit(:cut, :wash, :colour)\n end",
"def index\n @sightings = Sighting.where(date: params[:start_date]..params[:end_date])\n render json: @sightings\n end",
"def index\n @drawables = Drawable.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @drawables }\n end\n end",
"def update\n if @sighting.update(sighting_params)\n render json: @sighting\n else\n render json: @sighting.errors, status: :unprocessable_entity\n end\n end",
"def create\n @spending = Spending.new(spending_params)\n respond_to do |format|\n if @spending.save \n format.html { redirect_to new_spending_url, notice: 'Spending was successfully created.' }\n format.json { render action: 'show', status: :created, location: @spending }\n else\n format.html { render action: 'new' }\n format.json { render json: @spending.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
[
"0.6910724",
"0.6687737",
"0.6657411",
"0.64601356",
"0.6385349",
"0.62101865",
"0.6162789",
"0.60166717",
"0.5957114",
"0.59391785",
"0.59104735",
"0.58873063",
"0.58715785",
"0.58024114",
"0.5800152",
"0.56954676",
"0.5686099",
"0.56544584",
"0.56416744",
"0.5616906",
"0.5557558",
"0.55435795",
"0.55265975",
"0.55253196",
"0.54438025",
"0.54305834",
"0.5377824",
"0.53746223",
"0.53293586",
"0.5279108",
"0.5222599",
"0.51919407",
"0.51802415",
"0.51791406",
"0.5171371",
"0.5166168",
"0.5163445",
"0.5142366",
"0.5140739",
"0.5134533",
"0.5124262",
"0.5098483",
"0.50759244",
"0.50623286",
"0.50622255",
"0.5047769",
"0.50414336",
"0.50300956",
"0.5009721",
"0.5007317",
"0.5004963",
"0.50017315",
"0.49876288",
"0.49869725",
"0.49788395",
"0.4978711",
"0.49731848",
"0.49636102",
"0.4957861",
"0.49569482",
"0.49561688",
"0.49533078",
"0.49509105",
"0.49444526",
"0.49404886",
"0.49324834",
"0.4901621",
"0.49012262",
"0.48875535",
"0.48757035",
"0.48650602",
"0.4862932",
"0.4861079",
"0.48581362",
"0.48545933",
"0.48517522",
"0.4850714",
"0.48425493",
"0.4835749",
"0.48313057",
"0.48257864",
"0.48217294",
"0.48106834",
"0.48102012",
"0.48086163",
"0.48085523",
"0.48035353",
"0.47996607",
"0.47979996",
"0.47971305",
"0.47968206",
"0.47927853",
"0.4791239",
"0.47854903",
"0.47782946",
"0.47751388",
"0.47731757",
"0.4769354",
"0.47679022",
"0.476166"
] |
0.7109006
|
0
|
PATCH/PUT /drawings/1 PATCH/PUT /drawings/1.json
|
def update
@drawing = Drawing.find(params[:id])
if @drawing.update_attributes(params[:drawing])
head :no_content
else
render json: @drawing.errors, status: :unprocessable_entity
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def update\n @draw = Draw.find(params[:id])\n\n respond_to do |format|\n if @draw.update_attributes(params[:draw])\n format.html { redirect_to @draw, notice: 'Draw was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @drawing.update(drawing_params)\n format.html { redirect_to @drawing, notice: 'Drawing was successfully updated.' }\n format.json { render :show, status: :ok, location: @drawing }\n else\n format.html { render :edit }\n format.json { render json: @drawing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @draw.update(draw_params)\n format.html { redirect_to @draw, notice: 'Draw was successfully updated.' }\n format.json { render :show, status: :ok, location: @draw }\n else\n format.html { render :edit }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @draw = current_user.draws.find(params[:id])\n prevent_if_drawn\n\n respond_to do |format|\n if @draw.update_attributes(params[:draw])\n format.html { redirect_to @draw, notice: 'Draw was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @lucky_draw.update(lucky_draw_params)\n format.html { redirect_to @lucky_draw, notice: 'Lucky draw was successfully updated.' }\n format.json { render :show, status: :ok, location: @lucky_draw }\n else\n format.html { render :edit }\n format.json { render json: @lucky_draw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @structure_drawing.update(structure_drawing_params)\n format.html { redirect_to project_sub_project_structure_drawings_path(@project, @sub_project), notice: 'Structure drawing was successfully updated.' }\n format.json { render :show, status: :ok, location: @structure_drawing }\n else\n format.html { render :edit }\n format.json { render json: @structure_drawing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @stroke.update(stroke_params)\n format.html { redirect_to @stroke, notice: 'Stroke was successfully updated.' }\n format.json { render :show, status: :ok, location: @stroke }\n else\n format.html { render :edit }\n format.json { render json: @stroke.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @withdraw.update(withdraw_params)\n format.html { redirect_to @withdraw, notice: 'Withdraw was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @withdraw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @withdrawal = Withdrawal.find(params[:id])\n\n respond_to do |format|\n if @withdrawal.update_attributes(params[:withdrawal])\n format.html { redirect_to action: :index, notice: 'Withdrawal was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @withdrawal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @much_withdraw.update(much_withdraw_params)\n format.html { redirect_to \"/\", notice: 'much withdraw so success' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @much_withdraw.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @crossing = Crossing.find(params[:id])\n\n respond_to do |format|\n if @crossing.update_attributes(params[:crossing])\n format.html { redirect_to @crossing, notice: 'Crossing was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @crossing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n # TODO: Also update stocks!\n if @dosing.update(dosing_params)\n format.html { redirect_to @dosing, notice: 'Dosing was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @dosing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @wing.update(wing_params)\n @wing.floors.each { |f| f.touch }\n format.html { redirect_to @wing, notice: t('.update_ok', item: @wing.name) }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @wing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @withdrawal_request = WithdrawalRequest.find(params[:id])\n\n respond_to do |format|\n if @withdrawal_request.update_attributes(params[:withdrawal_request])\n format.html { redirect_to @withdrawal_request, notice: 'Withdrawal request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @withdrawal_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @internaldraw = Internaldraw.find(params[:id])\n\n respond_to do |format|\n if @internaldraw.update_attributes(params[:internaldraw])\n format.html { redirect_to(@internaldraw, :notice => 'Internaldraw was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @internaldraw.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @dog_poly.update(dog_poly_params)\n format.html { redirect_to @dog_poly, notice: 'Dog poly was successfully updated.' }\n format.json { render :show, status: :ok, location: @dog_poly }\n else\n format.html { render :edit }\n format.json { render json: @dog_poly.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @batting_line = BattingLine.find(params[:id])\n\n respond_to do |format|\n if @batting_line.update_attributes(params[:batting_line])\n format.html { redirect_to @batting_line, notice: 'Batting line was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @batting_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @polygon = Polygon.find(params[:id])\n\n respond_to do |format|\n if @polygon.update_attributes(params[:polygon])\n format.html { redirect_to @polygon, notice: 'Polygon was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @polygon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @image_section = ImageSection.find(params[:id])\n ci = @image_section.combined_image\n\n respond_to do |format|\n if @image_section.update_attribute(:sketchpad_json, params[:drawn_json])\n format.html { redirect_to edit_image_section_path(ci.image_sections.sample), \n notice: 'Image section was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @image_section.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @line = Line.find(params[:id])\n @budget = @line.budget\n\n respond_to do |format|\n if @line.update_attributes(params[:line])\n format.html { redirect_to budget_path(@budget), notice: 'Line was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @thickness.update(thickness_params)\n format.html { redirect_to @thickness, notice: 'Thickness was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @thickness.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @keystroke = Keystroke.find(params[:id])\n\n respond_to do |format|\n if @keystroke.update_attributes(params[:keystroke])\n format.html { redirect_to @keystroke, notice: 'Keystroke was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @keystroke.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n resource.update(deposit_contract_params)\n respond_with client, resource\n end",
"def update\n @drawable = Drawable.find(params[:id])\n\n respond_to do |format|\n if @drawable.update_attributes(params[:drawable])\n format.html { redirect_to @drawable, notice: 'Drawable was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @drawable.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @externaldraw = Externaldraw.find(params[:id])\n\n respond_to do |format|\n if @externaldraw.update_attributes(params[:externaldraw])\n format.html { redirect_to(@externaldraw, :notice => 'Externaldraw was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @externaldraw.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def patch\n headers = {\"If-Match\" => @version}\n response = @context.request :patch, \"#{@path}/#{@id}\", @data.to_json, headers\n @version += 1\n response\n # 'X-HTTP-Method-Override' => 'PATCH'\n end",
"def update\n respond_to do |format|\n if @ship_fitting.update(ship_fitting_params)\n format.html { redirect_to @ship_fitting, notice: 'Ship fitting was successfully updated.' }\n format.json { render :show, status: :ok, location: @ship_fitting }\n else\n format.html { render :edit }\n format.json { render json: @ship_fitting.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @api_v1_canvas.update(api_v1_canvas_params)\n format.html do\n redirect_to @api_v1_canvas, notice: 'Canvas was successfully updated.'\n end\n\n format.json { render :show, status: :ok, location: @api_v1_canvas }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_canvas.errors, status: :unprocessable_entity }\n end\n end\n end",
"def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end",
"def update\n @bubble_tea = BubbleTea.find(params[:id])\n\n if @bubble_tea.update(bubble_tea_params)\n render json: @bubble_tea\n else\n render plain: \"Failed to update drink information\"\n end\n end",
"def update\n if @person.seat\n render json: {errors: 'Cannot update a seated person'}, status: 422\n else\n @person.update person_params\n render json: @person\n end\n end",
"def update\n respond_to do |format|\n if @crossing.update(crossing_params)\n format.html { redirect_to @crossing, notice: 'Crossing was successfully updated.' }\n format.json { render :show, status: :ok, location: @crossing }\n else\n format.html { render :edit }\n format.json { render json: @crossing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @budget_line.update(budget_line_params)\n format.html { redirect_to @budget_line, notice: 'Budget line was successfully updated.' }\n format.json { render :show, status: :ok, location: @budget_line }\n else\n format.html { render :edit }\n format.json { render json: @budget_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @kickoff = Kickoff.find(params[:id])\n\n respond_to do |format|\n if @kickoff.update_attributes(params[:kickoff])\n format.html { redirect_to @kickoff, notice: 'Kickoff was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @kickoff.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n sighting = Sighting.find(params[:id])\n sighting.update(sighting_params)\n \n # if sighting was valid and found then return the json\n if sighting.valid?\n render json: sighting\n else\n render json: sighting.errors\n end\n end",
"def update\n respond_to do |format|\n if @setbreak.update(setbreak_params)\n format.json { respond_with_bip @setbreak }\n else\n format.json { respond_with_bip @setbreak }\n end\n end\n end",
"def update\n ingredient.update(ingredient_params)\n render json: ingredient\n end",
"def update\n @flight = Flight.find(params[:id])\n\n if @flight.update(params[:flight])\n head :no_content\n else\n render json: @flight.errors, status: :unprocessable_entity\n end\n end",
"def update\n @brush_holder = BrushHolder.find(params[:id])\n if params[:to_needs_editing] # if update call from needs editing, set part status accordingly\n @brush_holder.release_status = \"needs editing\"\n else\n @brush_holder.release_status = \"pending\"\n end\n respond_to do |format|\n if @brush_holder.update_attributes(brush_holder_params)\n format.html { redirect_to(@brush_holder, :notice => 'Brush holder was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @brush_holder.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @dragon = Dragon.find(params[:id])\n\n respond_to do |format|\n if @dragon.update_attributes(params[:dragon])\n format.html { redirect_to @dragon, :notice => 'Dragon was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @dragon.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @bidding = Bidding.find(params[:id])\n\n respond_to do |format|\n if @bidding.update_attributes(params[:bidding])\n format.html { redirect_to @bidding, notice: 'Bidding was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @bidding.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @bill_point = BillPoint.find(params[:id])\n\n respond_to do |format|\n if @bill_point.update_attributes(params[:bill_point])\n format.html { redirect_to @bill_point, notice: 'Bill point was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @bill_point.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @sighting.update(sighting_params)\n render json: @sighting, status: :ok, location: @sighting\n else\n render json: @sighting.errors, status: :unprocessable_entity\n end\n end",
"def set_drawing\n @drawing = Drawing.find(params[:id])\n end",
"def update\n if @painting.artwork\n @painting.artwork.purge\n end\n # if @car.pictures\n # @car.pictures.purge\n # end\n respond_to do |format|\n if @painting.update(painting_params)\n format.html { redirect_to @painting, notice: 'Painting was successfully updated.' }\n format.json { render :show, status: :ok, location: @painting }\n else\n format.html { render :edit }\n format.json { render json: @painting.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @crossbow.update(crossbow_params)\n format.html { redirect_to @crossbow, notice: 'Crossbow was successfully updated.' }\n format.json { render :show, status: :ok, location: @crossbow }\n else\n format.html { render :edit }\n format.json { render json: @crossbow.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def update\n respond_to do |format|\n if @dependence.update(dependence_params)\n format.html { redirect_to @dependence, notice: 'Dependence was successfully updated.' }\n format.json { render :show, status: :ok, location: @dependence }\n else\n format.html { render :edit }\n format.json { render json: @dependence.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @twenty.update(twenty_params)\n format.html { redirect_to @twenty, notice: 'Twenty was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @twenty.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @visualization = Visualization.find(params[:id])\n update = visualization_params\n\n # ADMIN REQUEST\n if can_admin?(@visualization)\n if update.key?(:featured)\n if update['featured'] == '1'\n update['featured_at'] = Time.now\n else\n update['featured_at'] = nil\n end\n end\n end\n\n respond_to do |format|\n if can_edit?(@visualization) && @visualization.update_attributes(update)\n format.html { redirect_to @visualization, notice: 'Visualization was successfully updated.' }\n format.json { render json: {}, status: :ok }\n else\n @visualization.errors[:base] << 'Permission denied' unless can_edit?(@visualization)\n format.html { redirect_to request.referrer, alert: @visualization.errors.full_messages }\n format.json do\n render json: @visualization.errors.full_messages,\n status: :unprocessable_entity\n end\n end\n end\n end",
"def update\n @table = Table.find(params[:id])\n\n respond_to do |format|\n if @table.update_attributes(params[:table].permit(:name, :notes, :x, :y, :table_type, :guest_ids => []))\n format.html { redirect_to @table, notice: 'Table was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @table.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @budget = Budget.find(params[:id])\n\n respond_to do |format|\n if @budget.update_attributes(params[:budget])\n format.html { redirect_to @budget, notice: 'Budget was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @budget.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @budget = Budget.find(params[:id])\n\n respond_to do |format|\n if @budget.update_attributes(params[:budget])\n format.html { redirect_to @budget, notice: 'Budget was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @budget.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @order.status == \"preparing\"\n format.json { render text: '', status: 409 }\n else\n if @order.update(order_params)\n @drink = Drink.where(drink: @order.drink).first\n format.html { redirect_to @order, notice: 'Order was successfully updated.' }\n response_json = {drink: @drink.drink, cost: @drink.cost, additions: @order.additions, _links: { next: {profile: \"http://#{my_address}:3000/payment\", href: \"http://#{my_address}:3000/payments/order/#{@order.id}\", enctype: 'application/json'}}}\n format.json { render text: response_json, status: :created, location: @order }\n \n else\n format.html { render action: 'edit' }\n format.json { render json: @order.errors, status: :unprocessable_entity }\n end\n end\n end\n end",
"def update\n respond_to do |format|\n if @scrapping_datum.update(scrapping_datum_params)\n format.html { redirect_to @scrapping_datum, notice: 'Scrapping datum was successfully updated.' }\n format.json { render :show, status: :ok, location: @scrapping_datum }\n else\n format.html { render :edit }\n format.json { render json: @scrapping_datum.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @goat = Goat.find(params[:id])\n\n respond_to do |format|\n if @goat.update_attributes(params[:goat])\n format.html { redirect_to @goat, notice: 'Goat was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @goat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @sighting = Sighting.find(params[:id])\n\n respond_to do |format|\n if @sighting.update_attributes(params[:sighting])\n format.html { redirect_to @sighting, notice: 'Sighting was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sighting.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @dice = Dice.find(params[:id])\n\n if @dice.update(dice_params)\n head :no_content\n else\n render json: @dice.errors, status: :unprocessable_entity\n end\n end",
"def update\n @holding = Holding.find(params[:id])\n\n respond_to do |format|\n if @holding.update_attributes(params[:holding].merge(@yahoo_data))\n format.html { redirect_to @holding, notice: 'Holding was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @holding.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @point_consumption = PointConsumption.find(params[:id])\n\n respond_to do |format|\n if @point_consumption.update_attributes(params[:point_consumption])\n format.html { redirect_to @point_consumption, :notice => 'Point consumption was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @point_consumption.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def patch(path, data)\n request 'PATCH', path, body: data.to_json\n end",
"def update\n @flat_happening = FlatHappening.find(params[:id])\n\n if @flat_happening.update_attributes(params[:flat_happening])\n head :no_content\n else\n render json: @flat_happening.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @spending.update(spending_params)\n format.html { redirect_to @spending, notice: 'Spending was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @spending.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @tier_filling.update(tier_filling_params)\n format.html { redirect_to @tier_filling, notice: 'Tier filling was successfully updated.' }\n format.json { render :show, status: :ok, location: @tier_filling }\n else\n format.html { render :edit }\n format.json { render json: @tier_filling.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @budget = Budget.find(params[:id])\n\n respond_to do |format|\n if @budget.update_attributes(params[:budget])\n format.html { redirect_to @budget, notice: 'Budget was successfully updated.' }\n # format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n # format.json { render json: @budget.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @flying_object = FlyingObject.find(params[:id])\n\n respond_to do |format|\n if @flying_object.update_attributes(params[:flying_object])\n format.html { redirect_to(@flying_object, :notice => 'Flying object was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @flying_object.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_plant\n @plant.deleted = false\n\n respond_to do |format|\n if set_attributes_from_filemaker(@plant)\n format.json do\n render status: :created,\n json: {\n id: @plant.id,\n botanical_name: @plant.botanical_name,\n alternative_names: @plant.alternative_names,\n updated_at: @plant.updated_at,\n visible: (!@plant.deleted).to_s\n }\n end\n else\n format.json do\n render json: @plant.errors, status: :unprocessable_entity\n end\n end\n end\n end",
"def update\n @paper = Paper.find(params[:id])\n\n respond_to do |format|\n if @paper.update_attributes(params[:paper])\n format.html { redirect_to @paper, notice: 'Paper was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @paper.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @shipping_line = ShippingLine.find(params[:id])\n\n respond_to do |format|\n if @shipping_line.update_attributes(params[:shipping_line])\n format.html { redirect_to @shipping_line, :notice => 'Shipping line was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @shipping_line.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @shiping.update(shiping_params)\n format.html { redirect_to @shiping, notice: 'Shiping was successfully updated.' }\n format.json { render :show, status: :ok, location: @shiping }\n else\n format.html { render :edit }\n format.json { render json: @shiping.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @withdrawal = Withdrawal.find(params[:id])\n\n respond_to do |format|\n if @withdrawal.update_attributes(params[:withdrawal])\n flash[:notice] = 'Withdrawal was successfully updated.'\n format.html { redirect_to(@withdrawal) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @withdrawal.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @fabric = Fabric.find(params[:id])\n\n respond_to do |format|\n if @fabric.update_attributes(params[:fabric])\n format.html { redirect_to @fabric, notice: 'Fabric was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fabric.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch!\n request! :patch\n end",
"def update\n if @sighting.update(sighting_params)\n render json: @sighting\n else\n render json: @sighting.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @bow.update(bow_params)\n format.html { redirect_to @bow, notice: 'Bow was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @bow.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @drink.update(drink_params)\n format.html { redirect_to edit_drink_path(@drink), notice: 'Drycken uppdaterades.' }\n format.json { render :show, status: :ok, location: @drink }\n else\n format.html { render :edit }\n format.json { render json: @drink.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @circle = Circle.find(params[:id])\n\n respond_to do |format|\n if @circle.update_attributes(params[:circle])\n format.html { redirect_to @circle, :notice => 'Circle was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @circle.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @knob = Knob.find(params[:id])\n\n respond_to do |format|\n if @knob.update_attributes(params[:knob])\n flash[:notice] = 'Knob was successfully updated.'\n format.html { redirect_to(@knob) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @knob.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @withdrawal_request.update(withdrawal_request_params)\n format.html { redirect_to @withdrawal_request, notice: 'Withdrawal request was successfully updated.' }\n format.json { render :show, status: :ok, location: @withdrawal_request }\n else\n format.html { render :show }\n format.json { render json: @withdrawal_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @officer = Officer.find(params[:id])\n\n respond_to do |format|\n if @officer.update_attributes(params[:officer])\n format.html { redirect_to @officer, :notice => 'Officer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @officer.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @circular.update(circular_params)\n format.html { redirect_to @circular, notice: 'Circular was successfully updated.' }\n format.json { render :show, status: :ok, location: @circular }\n else\n format.html { render :edit }\n format.json { render json: @circular.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @articy_draft.update(articy_draft_params)\n format.html { redirect_to @articy_draft, notice: 'Articy draft was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @articy_draft.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @holding = Holding.find(params[:id])\n\n respond_to do |format|\n if @holding.update_attributes(params[:holding])\n format.html { redirect_to @holding, notice: 'Holding was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @holding.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @data = @recipe.update(params[:id], recipe_params)\n render json: @data\n end",
"def update\n @officer = Officer.find(params[:id])\n\n respond_to do |format|\n if @officer.update_attributes(params[:officer])\n format.html { redirect_to @officer, notice: 'Officer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @officer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @officer.update(officer_params)\n format.html { redirect_to @officer, notice: 'Officer was successfully updated.' }\n format.json { render :show, status: :ok, location: @officer }\n else\n format.html { render :edit }\n format.json { render json: @officer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @officer.update(officer_params)\n format.html { redirect_to @officer, notice: 'Officer was successfully updated.' }\n format.json { render :show, status: :ok, location: @officer }\n else\n format.html { render :edit }\n format.json { render json: @officer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @flat = Flat.find(params[:id])\n\n respond_to do |format|\n if @flat.update_attributes(params[:flat])\n format.html { redirect_to @flat, notice: 'Flat was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @flat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @circle = Circle.find(params[:id])\n\n respond_to do |format|\n if @circle.update_attributes(params[:circle])\n format.html { redirect_to @circle, notice: 'Circle was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @circle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @circle = Circle.find(params[:id])\n\n respond_to do |format|\n if @circle.update_attributes(params[:circle])\n format.html { redirect_to @circle, notice: 'Circle was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @circle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @dragon = Dragon.find(params[:id])\n dragon = dragon_params\n dragon.delete(:guid)\n Dragon.reflect_on_all_associations(:belongs_to).each do |assoc|\n name = assoc.name\n attr_key = assoc.options[:foreign_key] || (name.to_s + \"_id\")\n dragon[attr_key.to_sym] = dragon[name.to_sym].sub(/.*\\//,'') if dragon[name.to_sym]\n dragon.delete(name.to_sym)\n end\n respond_to do |format|\n if @dragon.update_attributes(dragon)\n format.html { redirect_to(@dragon, :notice => 'Dragon was successfully updated.') }\n format.xml { head :ok }\n format.json { render :json => custom_item_hash(@dragon), :status => :ok, :location => @dragon }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @dragon.errors, :status => :unprocessable_entity }\n format.json { render :json => @dragon.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @spoofer = Spoofer.find(params[:id])\n\n respond_to do |format|\n if @spoofer.update_attributes(params[:spoofer])\n format.html { redirect_to @spoofer, notice: 'Spoofer was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @spoofer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n liner = Liner.find_by(liner_reference: liner_params[\"liner_reference\"])\n original_thickness = liner.original_thickness.to_i\n current_thickness = liner_params[\"current_thickness\"].to_i\n thickness_loss_per_day = original_thickness - current_thickness\n liner_params[\"thickness_loss_per_day\"] = thickness_loss_per_day\n if @liner.update(liner_params)\n format.html { redirect_to @liner, notice: 'Liner was successfully updated.' }\n format.json { render :show, status: :ok, location: @liner }\n else\n format.html { render :edit }\n format.json { render json: @liner.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @breakdown = Breakdown.find(params[:id])\n\n respond_to do |format|\n if @breakdown.update_attributes(params[:breakdown])\n format.html { redirect_to @breakdown, notice: 'Breakdown was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @breakdown.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @squat_data_point = SquatDataPoint.find(params[:id])\n\n respond_to do |format|\n if @squat_data_point.update_attributes(params[:squat_data_point])\n format.html { redirect_to @squat_data_point, notice: 'Squat data point was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @squat_data_point.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @ship = Ship.find(params[:id])\n\n respond_to do |format|\n if @ship.update_attributes(params[:ship])\n format.html { redirect_to @ship, notice: 'Ship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ship.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @bath.update(bath_params)\n format.html { redirect_to @bath, notice: 'Bath was successfully updated.' }\n format.json { render :show, status: :ok, location: @bath }\n else\n format.html { render :edit }\n format.json { render json: @bath.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @dining = Dining.find(params[:id])\n\n respond_to do |format|\n if @dining.update_attributes(params[:dining])\n flash[:notice] = 'Dining was successfully updated.'\n format.html { redirect_to(@dining) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @dining.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @funding_requirement.update(funding_requirement_params)\n format.html { redirect_to @funding_requirement, notice: 'Funding requirement was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @funding_requirement.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @ship = Ship.find(params[:id])\n\n respond_to do |format|\n if @ship.update_attributes(params[:ship])\n format.html { redirect_to @ship, notice: 'Ship was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ship.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
[
"0.7125346",
"0.711631",
"0.70599157",
"0.7040108",
"0.6485048",
"0.6449785",
"0.63194305",
"0.611239",
"0.608619",
"0.60325533",
"0.59873444",
"0.5968558",
"0.59627676",
"0.59383816",
"0.5936856",
"0.59348726",
"0.59338003",
"0.5921413",
"0.59095186",
"0.588861",
"0.586535",
"0.5853284",
"0.5847042",
"0.58461994",
"0.58374774",
"0.58238477",
"0.57980794",
"0.57701",
"0.57582706",
"0.5740692",
"0.5738142",
"0.57348675",
"0.5734719",
"0.57316434",
"0.5727226",
"0.57245654",
"0.5723666",
"0.5673192",
"0.5655909",
"0.5652868",
"0.56394714",
"0.56358993",
"0.563382",
"0.56210005",
"0.5618878",
"0.5615175",
"0.5601591",
"0.55982685",
"0.5590703",
"0.55878764",
"0.5584965",
"0.55809265",
"0.55809265",
"0.5578086",
"0.5573961",
"0.55714595",
"0.55702376",
"0.5568679",
"0.55683315",
"0.556805",
"0.55659366",
"0.55646014",
"0.55640113",
"0.5561154",
"0.55588955",
"0.5552507",
"0.5547514",
"0.5547156",
"0.5547073",
"0.5545684",
"0.5544762",
"0.5544061",
"0.55427307",
"0.5540404",
"0.55403215",
"0.5538057",
"0.5536179",
"0.55338204",
"0.55335003",
"0.5530151",
"0.5524344",
"0.55192184",
"0.5517087",
"0.5516922",
"0.5516529",
"0.5512656",
"0.5512656",
"0.55069613",
"0.5506007",
"0.5506007",
"0.55044025",
"0.5502543",
"0.550231",
"0.54980874",
"0.5494336",
"0.54937595",
"0.5492281",
"0.5492277",
"0.5485622",
"0.5484463"
] |
0.73792917
|
0
|
DELETE /drawings/1 DELETE /drawings/1.json
|
def destroy
@drawing = Drawing.find(params[:id])
@drawing.destroy
head :no_content
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def destroy\n @draw = Draw.find(params[:id])\n @draw.destroy\n\n respond_to do |format|\n format.html { redirect_to draws_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @draw.destroy\n respond_to do |format|\n format.html { redirect_to draws_url, notice: 'Draw was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @draw = current_user.draws.find(params[:id])\n prevent_if_drawn\n \n @draw.destroy\n\n respond_to do |format|\n format.html { redirect_to draws_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @drawing.destroy\n respond_to do |format|\n format.html { redirect_to :back, notice: 'Drawing was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @internaldraw = Internaldraw.find(params[:id])\n @internaldraw.destroy\n\n respond_to do |format|\n format.html { redirect_to(internaldraws_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @withdraw.destroy\n respond_to do |format|\n format.html { redirect_to withdraws_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @withdrawal = Withdrawal.find(params[:id])\n @withdrawal.destroy\n\n respond_to do |format|\n format.html { redirect_to withdrawals_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @drawable = Drawable.find(params[:id])\n @drawable.destroy\n\n respond_to do |format|\n format.html { redirect_to drawables_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @structure_drawing.destroy\n respond_to do |format|\n format.html { redirect_to project_sub_project_structure_drawings_path(@project, @sub_project), notice: 'Structure drawing was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @lucky_draw.destroy\n respond_to do |format|\n format.html { redirect_to lucky_draws_url, notice: 'Lucky draw was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @withdrawal_request = WithdrawalRequest.find(params[:id])\n @withdrawal_request.destroy\n\n respond_to do |format|\n format.html { redirect_to withdrawal_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @much_withdraw.destroy\n respond_to do |format|\n format.html { redirect_to much_withdraws_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @externaldraw = Externaldraw.find(params[:id])\n @externaldraw.destroy\n\n respond_to do |format|\n format.html { redirect_to(externaldraws_url) }\n format.xml { head :ok }\n end\n end",
"def delete\n client.delete(\"/#{id}\")\n end",
"def destroy\n @batting_line = BattingLine.find(params[:id])\n @batting_line.destroy\n\n respond_to do |format|\n format.html { redirect_to batting_lines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line = Line.find(params[:id])\n @line.destroy\n\n respond_to do |format|\n format.html { redirect_to budget_path(@line.budget) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @stroke.destroy\n respond_to do |format|\n format.html { redirect_to strokes_url, notice: 'Stroke was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete(id:)\n id_check(:id, id)\n\n cf_delete(path: \"/organizations/#{org_id}/railguns/#{id}\")\n end",
"def destroy\n #binding.pry\n @balance = Balance.find(params[:id])\n @balance.destroy\n respond_to do |format|\n format.html { redirect_to balances_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @withdrawal = Withdrawal.find(params[:id])\n @withdrawal.destroy\n\n respond_to do |format|\n format.html { redirect_to(withdrawals_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @budget_line.destroy\n respond_to do |format|\n format.html { redirect_to budget_lines_url, notice: 'Budget line was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end",
"def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end",
"def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end",
"def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end",
"def destroy\n @withdrawal_request.destroy\n respond_to do |format|\n format.html { redirect_to withdrawal_requests_url, notice: 'Withdrawal request was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @drawer.destroy\n\n respond_to do |wants|\n wants.html { redirect_to(drawers_url) }\n wants.xml { head :ok }\n end\n end",
"def destroy\n id = @api_v1_canvas.id\n @api_v1_canvas.destroy\n respond_to do |format|\n format.html do\n redirect_to api_v1_canvases_url, notice: 'Canvas was successfully destroyed.'\n end\n\n format.json do\n msg = { id: id }\n broadcast(\"deleted\", msg)\n head :no_content\n end\n end\n end",
"def destroy\n @sighting = Sighting.find(params[:id])\n @sighting.destroy\n\n respond_to do |format|\n format.html { redirect_to sightings_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @polygon = Polygon.find(params[:id])\n @polygon.destroy\n\n respond_to do |format|\n format.html { redirect_to polygons_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @thickness.destroy\n respond_to do |format|\n format.html { redirect_to thicknesses_url }\n format.json { head :no_content }\n end\n end",
"def delete(path)\n RestClient.delete request_base+path\n end",
"def destroy\n @dragon = Dragon.find(params[:id])\n @dragon.destroy\n\n respond_to do |format|\n format.html { redirect_to dragons_url }\n format.json { head :ok }\n end\n end",
"def DeleteView id\n \n APICall(path: \"views/#{id}.json\",method: 'DELETE')\n \n end",
"def deletef\n url = prefix + \"deletef\" + id_param\n return response(url)\n end",
"def delete\n render json: UserBoards.delete(params[\"id\"])\n end",
"def delete\n render json: Post.delete(params[\"id\"])\n end",
"def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def delete\n request(:delete)\n end",
"def destroy\n @roof = Roof.find(params[:roof_id])\n @status = @roof.statuses.find(params[:id])\n @status.destroy\n\n respond_to do |format|\n format.html { redirect_to statuseses_url }\n format.json { head :no_content }\n end\n end",
"def delete\n render :json => @fiestas.delete_at(params[:id].to_i)\n end",
"def destroy\n @dart = Dart.find(params[:id])\n @dart.destroy\n\n respond_to do |format|\n format.html { redirect_to darts_url }\n format.json { head :no_content }\n end\n end",
"def delete path\n make_request(path, \"delete\", {})\n end",
"def delete\n render json: Alien.delete(params[\"id\"])\n end",
"def destroy\n @diagram = Diagram.find(params[:id])\n @diagram.destroy\n\n respond_to do |format|\n format.html { redirect_to(diagrams_url) }\n format.xml { head :ok }\n end\n end",
"def test_del\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n id = last_response.body\n\n delete \"/traces/#{id}\"\n assert last_response.ok?\n\n get \"/traces/#{id}\"\n\n contents = JSON.parse last_response.body\n assert_kind_of(Hash, contents, 'Response contents is not a hash')\n assert contents.key? 'description'\n assert(!last_response.ok?)\n end",
"def destroy\n @flat = Flat.find(params[:id])\n @flat.destroy\n\n respond_to do |format|\n format.html { redirect_to flats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @flat = Flat.find(params[:id])\n @flat.destroy\n\n respond_to do |format|\n format.html { redirect_to flats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line = Line.find_by_no(params[:id])\n @line.destroy\n\n respond_to do |format|\n format.html { redirect_to lines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @lineup = Lineup.find(params[:id])\n @lineup.destroy\n\n respond_to do |format|\n format.html { redirect_to lineups_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @flat = Flat.find(params[:id])\n @flat.destroy\n\n respond_to do |format|\n format.html { redirect_to flats_url }\n format.json { head :ok }\n end\n end",
"def delete\n api(\"Delete\")\n end",
"def destroy\n @bow.destroy\n respond_to do |format|\n format.html { redirect_to bows_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @budgeting_type = BudgetingType.find(params[:id])\n @budgeting_type.destroy\n\n respond_to do |format|\n format.html { redirect_to budgeting_types_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @crossing = Crossing.find(params[:id])\n @crossing.destroy\n\n respond_to do |format|\n format.html { redirect_to @crossing.trip_report }\n format.json { head :no_content }\n end\n end",
"def delete\n api_delete(\"/listings/#{@listing_id}\")\n end",
"def destroy\n @svgpost = Svgpost.find(params[:id])\n @svgpost.destroy\n\n respond_to do |format|\n format.html { redirect_to svgposts_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @shipping_line = ShippingLine.find(params[:id])\n @shipping_line.destroy\n\n respond_to do |format|\n format.html { redirect_to shipping_lines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @forest = Forest.find(params[:id])\n @forest.destroy\n\n respond_to do |format|\n format.html { redirect_to forests_url }\n format.json { head :no_content }\n end\n end",
"def delete\n render json: Item.delete(params[\"id\"])\n end",
"def destroy\n @bidding = Bidding.find(params[:id])\n @bidding.destroy\n\n respond_to do |format|\n format.html { redirect_to biddings_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @zombie_sighting = ZombieSighting.find(params[:id])\n @zombie_sighting.destroy\n\n respond_to do |format|\n format.html { redirect_to zombie_sightings_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @painting.destroy\n respond_to do |format|\n format.html { redirect_to paintings_url, notice: 'Painting was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @shipdesign = Shipdesign.find(params[:id])\n @shipdesign.destroy\n\n respond_to do |format|\n format.html { redirect_to shipdesigns_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item1 = LineItem1.find(params[:id])\n @line_item1.destroy\n\n respond_to do |format|\n format.html { redirect_to line_item1s_url }\n format.json { head :no_content }\n end\n end",
"def api_delete(path, data = {})\n api_request(:delete, path, :data => data)\n end",
"def destroy\n @diagnoz = Diagnoz.find(params[:id])\n @diagnoz.destroy\n\n respond_to do |format|\n format.html { redirect_to diagnozs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @basis = Base.find(params[:id])\n @basis.destroy\n\n respond_to do |format|\n format.html { redirect_to bases_url }\n format.json { head :no_content }\n end\n end",
"def incident_delete(statuspage_id, incident_id)\n data = {}\n data['statuspage_id'] = statuspage_id\n data['incident_id'] = incident_id\n\n request :method => :post,\n :url => @url + 'incident/delete',\n :payload => data\n end",
"def destroy\n @budget = Budget.find(params[:id])\n @budget.destroy\n\n respond_to do |format|\n format.html { redirect_to budgets_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @climb_datum = ClimbDatum.find(params[:id])\n @climb_datum.destroy\n\n respond_to do |format|\n format.html { redirect_to climb_data_url }\n format.json { head :no_content }\n end\n end",
"def delete!\n request! :delete\n end",
"def destroy\n @bath.destroy\n respond_to do |format|\n format.html { redirect_to baths_url, notice: 'Bath was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @twentyfour.destroy\n respond_to do |format|\n format.html { redirect_to twentyfours_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @observance.destroy\n respond_to do |format|\n format.html { redirect_to observances_url }\n format.json { head :no_content }\n end\n end",
"def delete\n url = prefix + \"delete\" + id_param\n return response(url)\n end",
"def destroy\n @budget = Budget.find(params[:id])\n @budget.destroy\n respond_to do |format|\n format.html { redirect_to budgets_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @skydatum = Skydatum.find(params[:id])\n @skydatum.destroy\n\n respond_to do |format|\n format.html { redirect_to skydata_url }\n format.json { head :no_content }\n end\n end",
"def delete_drawing_object(request)\n data, _status_code, _headers = delete_drawing_object_with_http_info(request)\n request_token if _status_code == 401\n data\n end",
"def destroy\n @bill.destroy\n render json: @bill\n end",
"def destroy\n @discipleship.destroy\n respond_to do |format|\n format.html { redirect_to discipleships_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n # find ALL servings associated with this purchase and delete them\n all_servings = Serving.where(purchase_id: @purchase.id)\n puts \"all servings associated with this purchase: #{all_servings}\"\n all_servings.destroy_all\n puts \"deleted servings\"\n @purchase.destroy\n puts \"deleted purchase\"\n render json: {status: 204, purchase: @purchase}\n end",
"def soccer_delete\n base_delete(params, \"Soccer\")\n end",
"def destroy\n @holding = Holding.find(params[:id])\n @holding.destroy\n\n respond_to do |format|\n format.html { redirect_to holdings_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @holding = Holding.find(params[:id])\n @holding.destroy\n\n respond_to do |format|\n format.html { redirect_to holdings_url }\n format.json { head :no_content }\n end\n end",
"def delete endpoint\n do_request :delete, endpoint\n end",
"def destroy\n @graphic = Graphic.find(params[:id])\n @graphic.destroy\n\n respond_to do |format|\n format.html { redirect_to(graphics_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @line = Line.find(params[:id])\n @line.destroy\n\n respond_to do |format|\n format.html { redirect_to new_line_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n @shooting = Shooting.find(params[:id])\n @shooting.destroy\n\n respond_to do |format|\n format.html { redirect_to shootings_url }\n format.json { head :no_content }\n end\n end",
"def test_delete_drawing_object\n remote_file_name = 'TestDeleteDrawingObject.docx'\n\n upload_file File.join(local_test_folder, local_file), remote_data_folder + '/' + remote_file_name\n\n request = DeleteDrawingObjectRequest.new(name: remote_file_name, index: 0, node_path: '', folder: remote_data_folder)\n\n @words_api.delete_drawing_object(request)\n end",
"def destroy\n @twenty.destroy\n respond_to do |format|\n format.html { redirect_to twenties_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @articy_draft.destroy\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n @spending.destroy\n respond_to do |format|\n format.html { redirect_to spendings_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @dow.destroy\n respond_to do |format|\n format.html { redirect_to dows_url, notice: 'Dow was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @shipcount.destroy\n respond_to do |format|\n format.html { redirect_to shipcounts_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @service_dependance = ServiceDependance.find(params[:id])\n @service_dependance.destroy\n\n respond_to do |format|\n format.html { redirect_to service_dependances_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_detail.destroy\n respond_to do |format|\n format.html { redirect_to line_details_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @dragon = Dragon.find(params[:id])\n @dragon.destroy\n\n respond_to do |format|\n format.html { redirect_to(dragons_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @datapoint.destroy\n respond_to do |format|\n format.html { redirect_to datapoints_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n render_json_auto @survey.delete_filter(params[:id].to_i) and return\n end"
] |
[
"0.76401263",
"0.7478449",
"0.735697",
"0.70703363",
"0.6947641",
"0.68477297",
"0.67222047",
"0.66976917",
"0.6584963",
"0.654797",
"0.65413046",
"0.65351266",
"0.64933217",
"0.64792794",
"0.6429699",
"0.6410615",
"0.63008165",
"0.62999004",
"0.62818027",
"0.6236122",
"0.6236063",
"0.6211045",
"0.6211045",
"0.6211045",
"0.6211045",
"0.6206355",
"0.61933506",
"0.61807823",
"0.6161322",
"0.61522955",
"0.6147596",
"0.6143788",
"0.6140547",
"0.61281836",
"0.611233",
"0.61098874",
"0.6099547",
"0.60925245",
"0.60907125",
"0.6082446",
"0.6082406",
"0.6079474",
"0.6078871",
"0.6072765",
"0.60690194",
"0.6067905",
"0.6067416",
"0.6067416",
"0.6062781",
"0.60577434",
"0.6046431",
"0.6044874",
"0.6039762",
"0.60387295",
"0.602988",
"0.60289156",
"0.60287005",
"0.6027334",
"0.60255826",
"0.6013323",
"0.60071087",
"0.5996443",
"0.599415",
"0.5993525",
"0.5992221",
"0.5989173",
"0.5982949",
"0.5963712",
"0.5962444",
"0.59567076",
"0.5956527",
"0.595307",
"0.59515387",
"0.59505916",
"0.59497494",
"0.5948144",
"0.59462434",
"0.5943084",
"0.59417486",
"0.5940321",
"0.59397197",
"0.5938839",
"0.5928386",
"0.59279996",
"0.59279996",
"0.59263414",
"0.5924589",
"0.59229755",
"0.591741",
"0.5917316",
"0.591394",
"0.59119165",
"0.59109",
"0.59093434",
"0.5905152",
"0.59011316",
"0.58996165",
"0.58993435",
"0.5894821",
"0.5890834"
] |
0.7392531
|
2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.