query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
listlengths
19
19
metadata
dict
Description Opens the general page of the elements editor: the video icon redirects to VideoEditorControllernew the audio icon redirects to AudioEditorControllernew the image icon redirects to GalleriesControllerimage_for_image_editor (and successively to ImageEditorControlleredit) Mode Html
def new render :layout => 'media_element_editor' end
[ "def site_editor\n @browser.link(:text=>\"Site Editor\").click\n SiteEditor.new(@browser)\n end", "def editorial_markup\r\n\t\r\n\tend", "def set_elements\n super\n element(:title) {b.h2(:class => \"uif-headerText\").span}\n element(:submit_button) {b.button(:id => \"submitEditor\")}\n element(:cancel_button) {b.button(:id => \"cancelEditor\")}\n element(:close_button) {b.button(:id => \"closeEditor\")}\n element(:return_to_search_button) {b.button(:id => \"returnToSearch_button\")}\n element(:message) {b.span(:id => \"workMessageSection_span\")}\n # Navigation Area Elements\n # TODO Check on necessity of plurality for add instance button once it is functioning again. (see OLE-4294)\n element(:delete_bib_button) {b.img(:xpath => \"//img[@class='deleteBib']\")}\n element(:holdings_links) {b.divs(:class => \"holdingIdentifierClass\")}\n element(:item_links) {b.divs(:class => \"itemIdentifierClass\")}\n element(:add_instance_buttons) {b.imgs(:class => \"addInstance\")}\n element(:delete_instance_buttons) {b.imgs(:title => \"Delete Instance\")}\n element(:add_item_buttons) {b.imgs(:title => \"Add Item\")}\n element(:delete_item_buttons) {b.imgs(:title => \"Delete Item\")}\n end", "def default\r\n can_view, msg = dc_user_can_view(@parent, @page)\r\n return msg unless can_view\r\n\r\n html = '<div class=\"picture-gallery\"><ul>'\r\n DcGallery.where(doc_id: @opts[:doc_id], active: true).order_by(order: 1).each do |picture|\r\n html << '<li>'\r\n if @opts[:edit_mode] > 1\r\n html << edit_menu(picture)\r\n html << %(\r\n <span class=\"dc-inline-link dc-link-ajax\" data-url=\"/cmsedit/run?control=DcGalleryControl.picture_remove;id=#{picture.id};table=DcGallery\"\r\n data-confirm=\"#{t('drgcms.confirm_delete')}\" title=\"#{t('drgcms.delete')}\">\r\n <i class=\"mi-o mi-delete\"></i>\r\n </span>)\r\n end\r\n html << \"#{@parent.link_to(i@parent.mage_tag(picture.thumbnail, title: picture.title), picture.picture)}<li>\"\r\n end\r\n html << '</ul></div>'\r\nend", "def editor\n edit_config\n end", "def edit_description; end", "def new\n @editor = Editor.new\n @editor.build_logo\n @title = \"Creer un editeur\"\n ariane.add \"Nouvel editeur\", new_editor_path\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @editor }\n end\n end", "def edit_html\n ''\n end", "def fleximage_editor\n \n ar_object = Kernel::const_get(params[:ar_object_class]).find(params[:ar_object_id])\n display_editor = (params[:display_editor] == \"false\")\n display_thumbnail = (params[:display_thumbnail] == \"true\")\n \n render :update do |page| \n page.replace(MainController.fleximage_domid(ar_object),\n render(:partial => \"/main/media_edit\", \n :locals => {:ar_object => ar_object, \n :timestamp => nil,\n :display_thumbnail => display_thumbnail, \n :display_editor => display_editor})\n )\n\t\tend\n end", "def render_editor(element)\n render_element(element, :editor)\n end", "def getEditorUrl()\n\t\treturn createUrl('editor')\n\tend", "def edit\n\t\traise NotImplementedError, \"FIXME: Implement editing comments.\"\n\t\t#respond_to do |format|\n\t\t#\tformat.html # edit.html.erb\n\t\t#end\n\tend", "def interactive_generator\n \n web_ui = ToolWebUI.new()\n web_ui.show\n \nend", "def advanced_editor_on(object, attribute)\n cn = current_container\n\t\tcss_files = []\n #google_map = false\n #cn ||= object.send(current_container_type.pluralize).delete_if{ |e| e.websites.empty? }.first if (object.class.to_s == \"Page\")\n #IF THE WS IS A WEBSITE\n #TODO check for blanklight website\n \n if cn && cn.class == Website\n Dir[\"public/website_files/#{cn.title}/stylesheets/*.css\"].collect do |uploaded_css|\n css_files << uploaded_css.split(\"public\")[1]\n end\n end\n \n css_files << \"/stylesheets/fckeditor.css\" if css_files.empty?\n \n css_file_name = \"&css_file_name[]=\" + css_files.join(',') \n\n field = ''\n object.new_record? ? new_item = \"&new=true\" : new_item = \"\"\n field += '<script type=\"text/javascript\" src=\"/ckeditor/ckeditor.js\"></script>'\n field += '<script type=\"text/javascript\">CKEDITOR.replace(\\'ckInstance\\', {customConfig : \\'/admin/ck_config?' + new_item + css_file_name + '\\'});</script>'\n return field\n end", "def edit_gallery_title_desc(gallery_name = \"test\", gallery_title = \"samplegallery\", gallery_desc = \"Its a sample gallery\",_browser = @browser)\n wait = Selenium::WebDriver::Wait.new(:timeout => 15)\n Log.logger.info(\"Editing '#{gallery_name}' Gallery properties (Title + Desc).\")\n self.open_gallery(gallery_name)\n wait.until { _browser.find_element(:xpath => @galmgr.edit_gallery) }.click\n frame = wait.until { _browser.find_element(:xpath => @galmgr.edit_overlay_frame) }\n _browser.switch_to.frame(frame)\n temp = wait.until { _browser.find_element(:xpath => @galmgr.gallery_title) }\n temp.clear\n temp.send_keys(gallery_title)\n wait.until { _browser.find_element(:xpath => @galmgr.gallery_desc) }\n self.type_text_in_wysiwyg_editor(gallery_desc)\n ## we need to be on the overlay at this point of execution\n wait.until { _browser.find_element(:xpath => @galmgr.save_gallery_btn) }.click\n _browser.switch_to.default_content\n end", "def editor\n # return if need_login true, true\n @Title = \"Tags\"\n @tabindex = params[:tabindex] ? params[:tabindex].to_i : (session[:tabindex] || 0)\n # The list of orphan tags gets all tags of this type which aren't linked to a table\n @taglist = Tag.strmatch(\"\", userid: session[:user_id], tagtype: Tag.index_to_type(@tabindex) )\n session[:tabindex] = @tabindex\n render :partial=>\"editor\"\n end", "def create_content_editor(name)\n if $editable_content_authorization\n content_for(:javascript_data) { <<-SCRIPTDATA\n $(function() {\n $(\"#ec_edit_button_#{name}\").click( function(event) {\n openEditor(\"#{name}\", \"#{controller_name()}\", \"#{action_name()}\");\n event.preventDefault();\n });\n });\nSCRIPTDATA\n }\n end\n end", "def set_elements\n super\n element(:message) {b.li(:class => 'uif-infoMessageItem')}\n element(:messages) {b.lis(:class => 'uif-infoMessageItem')}\n element(:message_header) {b.h3(:class => 'uif-pageValidationHeader')}\n element(:submit_button) {b.button(:id => \"submitEditor\")}\n element(:cancel_button) {b.button(:id => \"cancelEditor\")}\n element(:close_button) {b.button(:id => \"closeEditor\")}\n element(:return_to_search_button) {b.button(:id => \"returnToSearch_button\")}\n # Navigation Area Elements\n element(:delete_bib_button) {b.button(:title => 'Delete Bib')}\n element(:add_instance_button) {b.button(:title => 'Add Instance')}\n element(:add_einstance_button) {b.button(:title => 'Add EInstance')}\n # @note Vakata Context Menu items are only present on the screen after the containing menu header has been right-clicked.\n element(:delete_instance_button) {b.div(:id => 'vakata-contextmenu').ul.li(:index => 0).a(:rel => \"Delete\")}\n element(:add_item_button) {b.button(:title => 'Add Item')}\n element(:delete_item_button) {b.div(:id => 'vakata-contextmenu').ul.li(:index => 0).a(:rel => 'Delete')}\n end", "def editor_url=(_); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description Adds a link of this element to your section. found: reloads the element in compact mode compact: [this action doesn't occur] expanded: removes the element and reloads the whole page Mode Ajax + Json Specific filters ApplicationControllerinitialize_media_element ApplicationControllerinitialize_media_element_destination
def add @ok_msg = t('other_popup_messages.correct.add.media_element') if @ok if !current_user.bookmark('MediaElement', @media_element_id) @ok = false @error = I18n.t('activerecord.errors.models.bookmark.problem_creating_for_media_element') end else @error = I18n.t('activerecord.errors.models.bookmark.problem_creating_for_media_element') end if @destination == ButtonDestinations::FOUND_MEDIA_ELEMENT prepare_media_element_for_js @ok_msg = nil render 'media_elements/reload.js' else render :json => {:ok => @ok, :msg => (@ok ? @ok_msg : @error)} end end
[ "def render_new_content_link(element)\n\t\t\t\tlink_to_overlay_window(\n\t\t\t\t\trender_icon('create') + t('add new content'),\n\t\t\t\t\talchemy.new_admin_element_content_path(element),\n\t\t\t\t\t{\n\t\t\t\t\t\t:size => '335x70',\n\t\t\t\t\t\t:title => t('Select an content'),\n\t\t\t\t\t\t:overflow => true\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t:id => \"add_content_for_element_#{element.id}\",\n\t\t\t\t\t\t:class => 'small button with_icon new_content_link'\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\tend", "def create_expand_collapse_link(update_element_id, *args, &block)\n return '' if update_element_id.blank?\n \n options = args.extract_options!\n # default config options\n options.reverse_merge!(:link_text => update_element_id,\n :link_style => \"\",\n :style => \"\", \n :class => nil,\n :icon_left_margin => \"5px\",\n :icon_float => \"\")\n \n link_text = if block_given?\n capture(&block)\n else\n options[:link_text]\n end\n\n unless options[:icon_float].blank?\n expand_link = (expand_image(options[:icon_left_margin], options[:icon_float]) + link_text).html_safe\n collapse_link = (collapse_image(options[:icon_left_margin], options[:icon_float]) + link_text).html_safe\n else\n expand_link = (link_text + expand_image(options[:icon_left_margin])).html_safe\n collapse_link = (link_text + collapse_image(options[:icon_left_margin])).html_safe\n end\n\n expand_link_id = update_element_id + '_name_more_link'\n collapse_link_id = update_element_id + '_name_less_link'\n \n expand_link_content = link_to_function(expand_link, :id => expand_link_id, :style => \"vertical-align: baseline; #{options[:link_style]}\") do |page| \n page.toggle expand_link_id, collapse_link_id\n page.visual_effect :toggle_blind, update_element_id, :duration => '0.2'\n end.html_safe\n\n collapse_link_content = link_to_function(collapse_link, :id => collapse_link_id, :style => \"display:none; vertical-align: baseline; #{options[:link_style]}\") do |page| \n page.toggle expand_link_id, collapse_link_id\n page.visual_effect :toggle_blind, update_element_id, :duration => '0.2'\n end.html_safe\n \n span_content = expand_link_content + collapse_link_content\n \n content = content_tag(:span, span_content, :class => options[:class], :style => \"vertical-align: baseline; #{options[:style]}\")\n\n return content\n\n end", "def render_create_content_link(element, options = {})\n\t\t\t\tdefaults = {\n\t\t\t\t\t:label => t('add new content')\n\t\t\t\t}\n\t\t\t\toptions = defaults.merge(options)\n\t\t\t\tlink_to(\n\t\t\t\t\toptions[:label],\n\t\t\t\t\talchemy.admin_contents_path(\n\t\t\t\t\t\t:content => {\n\t\t\t\t\t\t\t:name => options[:content_name],\n\t\t\t\t\t\t\t:element_id => element.id\n\t\t\t\t\t\t}\n\t\t\t\t\t),\n\t\t\t\t\t:method => 'post',\n\t\t\t\t\t:remote => true,\n\t\t\t\t\t:id => \"add_content_for_element_#{element.id}\",\n\t\t\t\t\t:class => 'button new_content_link'\n\t\t\t\t)\n\t\t\tend", "def render_new_content_link(element)\n link_to_overlay_window(\n render_icon(:create) + _t('add new content'),\n alchemy.new_admin_element_content_path(element),\n {\n :size => '310x115',\n :title => _t('Select an content'),\n :overflow => true\n },\n {\n :id => \"add_content_for_element_#{element.id}\",\n :class => 'button with_icon new_content_link'\n }\n )\n end", "def media_link &block\n ASObj.generate :media_link,true,&block\n end", "def render_new_content_link(element)\n link_to_dialog(\n \"#{render_icon(:create)} #{_t('add new content')}\".html_safe,\n alchemy.new_admin_element_content_path(element),\n {\n size: '310x115',\n title: _t('Select an content'),\n overflow: true\n },\n {\n id: \"add_content_for_element_#{element.id}\",\n class: 'button with_icon new_content_link'\n }\n )\n end", "def click_create_new_media_handling\n wait_for_element_and_click media_handling_link\n end", "def switcher_link_to_remote(text, options={}, html_options={}, &block)\n id = html_options.delete(:id) || \"lm_#{rand(1000000)}\"\n inner_id = html_options.delete(:inner_id) || \"#{id}_more\"\n link_id = html_options.delete(:link_id) || \"#{id}_link\"\n action_id = html_options.delete(:action_id) || \"#{id}_action\"\n icon = boolean_default(options.delete(:icon), true)\n action_icon_id = id + '_action_icon'\n action_label_id = id + '_action_label'\n css_class = html_options.delete(:class)\n style = html_options.delete(:style)\n inner_css_class = html_options.delete(:inner_class)\n open = options.delete(:open) || false\n sticky = boolean_default(options.delete(:sticky), false)\n\n function = update_page do |page|\n page << \"if ($('#{inner_id}').style.display == 'none' && (typeof #{id} == 'undefined' || (typeof #{id} != 'undefined' && #{id} != true))) {\"\n page << remote_function({\n :update => \"#{inner_id}\",\n :success => update_page do |p|\n p << \"var #{id} = true;\"\n p[inner_id].visual_effect :blind_down, {:duration => 0.3}\n if sticky \n p << \"$('#{action_icon_id}').removeClassName('closed');\"\n p << \"$('#{action_icon_id}').addClassName('opened');\"\n else\n p[action_id].hide\n end\n end\n }.merge(options))\n page << \"} else if ($('#{inner_id}').style.display == 'none' && !(typeof #{id} == 'undefined') && #{id}) {\"\n page[inner_id].visual_effect :blind_down, {:duration => 0.3}\n if sticky \n page << \"$('#{action_icon_id}').removeClassName('closed');\"\n page << \"$('#{action_icon_id}').addClassName('opened');\"\n else\n page[action_id].hide\n end\n page << \"} else {\"\n page[inner_id].visual_effect :blind_up, {:duration => 0.3}\n page[link_id].show\n if sticky \n page << \"$('#{action_icon_id}').removeClassName('opened');\"\n page << \"$('#{action_icon_id}').addClassName('closed');\"\n else\n page[action_id].show\n end\n page << \"}\"\n end\n\n onclick = \"#{\"#{html_options[:onclick]}; \" if html_options[:onclick]}#{function}; return false;\"\n href = html_options[:href] || '#'\n\n html = <<-HTML\n<div id=\"#{id}\" class=\"switcher #{css_class}\" style=\"#{style}\">\n <div id=\"#{action_id}\" class=\"switcherAction\" style=\"#{open && !sticky ? 'display:none;' : ''}\">\n <a id=\"#{link_id}\" href=\"#{href}\" onclick=\"#{escape_once(onclick)};return false;\">\n <span id=\"#{action_icon_id}\" class=\"actionIcon #{open ? 'opened' : 'closed'}\" style=\"#{icon ? '' : 'display:none;'}\"></span>\n <span id=\"#{action_label_id}\" class=\"actionLabel\">#{text}</span>\n </a>\n </div>\n <div id=\"#{inner_id}\" class=\"#{inner_css_class}\" style=\"#{open ? '' : 'display:none;'}\">\n #{capture(&block)}\n </div>\n</div>\n HTML\n concat(html)\n end", "def add_content\n self.link(:id=>\"navigation_create_and_add_link\").fire_event(\"onmouseover\")\n self.link(:text=>\"Add content\").click\n self.wait_until { self.text.include? \"Collected items\" }\n self.class.class_eval { include AddContentContainer }\n end", "def add_content\n self.link(:id=>\"navigation_create_and_add_link\").fire_event(\"onmouseover\")\n self.link(:text=>\"Add content\").click\n self.wait_until { @browser.text.include? \"Collected items\" }\n self.class.class_eval { include AddContentContainer }\n end", "def add_href\n return if attributes.key?(\"href\")\n return unless attributes.key?(\"id\")\n attributes[\"href\"] = client.connection.api_path(\"#{collection.name}/#{attributes['id']}\")\n end", "def respond_to_url_change\n return if apotomo_root.find_by_id('deep_link') # add only once.\n apotomo_root << widget(\"apotomo/deep_link_widget\", :setup, 'deep_link')\n end", "def expand_contract_section(arg_heading, id, options={}, &block) \n expanded = (params[\"umlaut.show_#{id}\"] == \"true\") || options[:initial_expand] || false\n \n icon = image_tag( ( expanded ? \"list_open.png\" : \"list_closed.png\"),\n :alt => \"\",\n :class => \"toggle_icon\",\n :border => \"0\")\n heading = content_tag(:span,( expanded ? \"Hide \" : \"Show \"), :class=>'expand_contract_action_label') + arg_heading\n\n link_params = params.merge('umlaut.request_id' => @user_request.id,\n \"umlaut.show_#{id}\" => (! expanded).to_s ,\n \n # Need to zero out format-related params for when we're coming\n # from a partial html api request, so the link we generate\n # is not to format json/xml/etc. \n :format => nil, \n 'umlaut.response_format' => nil,\n 'umlaut.jsonp'=>nil,\n \n # In Rails3, an :anchor param will actually be used for #fragmentIdentifier\n # on end of url\n :anchor => \"#{id}_toggle_link\"\n )\n \n # Make sure a self-referencing link from partial_html_sections\n # really goes to full HTML view.\n link_params[:action] = \"index\" if link_params[:action] == \"partial_html_sections\"\n \n \n \n return content_tag(:div, :class => \"expand_contract_section\") do\n link_to( icon + heading, link_params, \n :id => \"#{id}_toggle_link\", \n :class => \"expand_contract_toggle\" ) + \"\\n\" +\n content_tag(:div, :id => id, \n :class => \"expand_contract_content\", \n :style => (\"display: none;\" unless expanded), \n &block)\n end \n end", "def link_to_add_field(*args, &block)\n options = args.extract_options!.symbolize_keys\n association = args.pop.to_sym\n options['data-add-field'] = association\n args << default_location(options) << options\n template.link_to *args, &block\n end", "def render_create_content_link(element, content_name, options = {}, options_for_content = {})\n defaults = {\n :label => _t('Add %{name}', :name => _t(content_name, :scope => :content_names))\n }\n options = defaults.merge(options)\n link_to(render_icon(:create) + options[:label], alchemy.admin_contents_path(\n :content => {\n :name => content_name,\n :element_id => element.id\n },\n :options => options_for_content.to_json\n ),\n :method => :post,\n :remote => true,\n :id => \"add_content_for_element_#{element.id}\",\n :class => 'button with_icon new_content_link'\n )\n end", "def media_link(object, show_delete: false)\n return content_tag(:div, \"[#{t('common.none')}]\", class: \"no-value\") if object.nil?\n\n content_tag(:div, class: \"media-thumbnail\") do\n concat(\n link_to(image_tag(thumb_path(object)), url_for(object.item), target: \"_blank\", rel: \"noopener\")\n )\n\n concat(\n content_tag(:div, class: \"links\") do\n dl_path = rails_blob_path(object.item, disposition: \"attachment\")\n concat(\n link_to(content_tag(:i, \"\", class: \"fa fa-download\"), dl_path, class: \"download\")\n )\n\n if show_delete\n data = {\"confirm-msg\" => t(\"response.remove_media_object_confirm.#{object.kind}\")}\n concat(\n link_to(content_tag(:i, \"\", class: \"fa fa-trash-o\"), \"#\", class: \"delete\", data: data)\n )\n end\n end\n )\n end\n end", "def add_another_section\n frm.link(:id=>/SectionConfirmForm:saveAddAnotherbutton/).click\n AddEditSection.new(@browser)\n end", "def element_edit_link(survey, survey_version, element)\n generate_element_edit_link( url_for([:edit, survey, survey_version, element.assetable]) )\n end", "def render_create_content_link(element, content_name, options = {}, options_for_content = {})\n defaults = {\n label: _t('Add %{name}', name: _t(content_name, scope: :content_names))\n }\n options = defaults.merge(options)\n link_to(render_icon(:create) + options[:label], alchemy.admin_contents_path(\n content: {\n name: content_name,\n element_id: element.id\n },\n options: options_for_content.to_json\n ),\n method: :post,\n remote: true,\n id: \"add_content_for_element_#{element.id}\",\n class: 'button with_icon new_content_link'\n )\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description Removes the link of this element from your section. found: reloads the element in compact mode compact: removes the element and reloads the whole page expanded: removes the element and reloads the whole page Mode Ajax + Json Specific filters ApplicationControllerinitialize_media_element ApplicationControllerinitialize_media_element_destination
def remove @ok_msg = t('other_popup_messages.correct.remove.media_element') if @ok bookmark = Bookmark.where(:user_id => current_user.id, :bookmarkable_type => 'MediaElement', :bookmarkable_id => @media_element_id).first if bookmark.nil? @ok = false @error = I18n.t('activerecord.errors.models.bookmark.problem_destroying_for_media_element') else bookmark.destroy if Bookmark.where(:user_id => current_user.id, :bookmarkable_type => 'MediaElement', :bookmarkable_id => @media_element_id).any? @ok = false @error = I18n.t('activerecord.errors.models.bookmark.problem_destroying_for_media_element') end end else @error = I18n.t('activerecord.errors.models.bookmark.problem_destroying_for_media_element') end if @destination == ButtonDestinations::FOUND_MEDIA_ELEMENT prepare_media_element_for_js render 'media_elements/reload.js' else render :json => {:ok => @ok, :msg => (@ok ? @ok_msg : @error)} end end
[ "def remove_this_publication(main_title)\n target_div_id = self.text_field(:value=>main_title).parent.parent.parent.id\n self.div(:id=>target_div_id).button(:id=>/displayprofilesection_remove_link_/).click\n self.wait_for_ajax\n end", "def remove_link\n # cocoon JS needs class specifically remove_fields.dynamic, just treat em all\n # like dynamic, it seems okay.\n template.link_to(I18n.t(\"kithe.repeatable_input.remove\"), '#', class: \"remove_fields dynamic btn btn-secondary\")\n end", "def destroy\n @element_type.destroy\n\n head :no_content\n end", "def remove_medium_link(opts)\n opts[:text] ||= I18n.t('remove_link', :scope => [:has_media, :form])\n link_to opts[:text], medium_url(opts[:medium]), :remote => true, :method => :delete\n end", "def remove_from_library\n self.remove_from_library_button\n self.remove_from_library_button_element.wait_while_present\n sleep 1.5\n self.wait_for_ajax\n end", "def cleared_linked_display\n h.content_tag(:div, linked_display, class:'images single clear').html_safe\n end", "def destroy\n begin\n @element = Element.find_by_id(params[:id])\n @page = @element.page\n if @element.destroy\n unless session[:clipboard].nil?\n session[:clipboard] = nil if session[:clipboard][:element_id] == params[:id]\n end\n end\n rescue\n log_error($@)\n render :update do |page|\n Alchemy::Notice.show_via_ajax(page, _(\"element_not_successfully_deleted\"), :error)\n end\n end\n end", "def link_to_remove(*args, &block)\n\t\t\t\toptions = args.extract_options!.symbolize_keys\n\t\t\t\toptions[:class] = [options[:class], \"remove_nested_fields\"].compact.join(\" \")\n\t\t\t\toptions[:data] = {record: object_name}\n\t\t\t\targs << (options.delete(:href) || \"javascript:void(0)\") if !block_given?\n\t\t args << options\n\t\t @template.hidden_field_tag(\"#{object_name}[_destroy]\", object._destroy) + @template.link_to(*args, &block)\n\t\t\tend", "def link_to_remove(*args, &block)\n options = args.extract_options!.symbolize_keys\n options[:class] = [options[:class], \"remove_nested_fields\"].compact.join(\" \")\n\n # Extracting \"milestones\" from \"...[milestones_attributes][...]\"\n md = object_name.to_s.match /(\\w+)_attributes\\](?:\\[[\\w\\d]+\\])?$/\n association = md && md[1]\n options[\"data-association\"] = association\n\n args << (options.delete(:href) || \"javascript:void(0)\")\n args << options\n hidden_field(:_destroy) << @template.link_to(*args, &block)\n end", "def cleared_linked_display\n h.content_tag(:div, linked_display, class: 'images single clear').html_safe\n end", "def removePostByClickingRemoveLink()\n el= @driver.find_element(:xpath, \"//div[@class='view-more-actions my-post']/div/a[4]/span[contains(text(),'REMOVE')]\")\n el.click\n wait = Selenium::WebDriver::Wait.new(:timeout => 10)\n wait.until { @driver.find_element(:link => \"Yes, Delete this Post\").displayed? }\n el2= @driver.find_element(:link, \"Yes, Delete this Post\")\n el2.click\n end", "def destroy\n @scraping_element = ScrapingElement.find(params[:id])\n @scraping_element.destroy\n\n respond_to do |format|\n format.html { redirect_to scraping_elements_url }\n format.json { head :no_content }\n end\n end", "def link_to_remove_field(*args, &block)\n options = args.extract_options!.symbolize_keys\n options['data-remove-field'] = options[:association] || true\n args << default_location(options) << options\n hidden_field(:_destroy, :'data-destroy-field' => true) + template.link_to(*args, &block)\n end", "def remove_complex_contents\n selector = COMPLEX_CONTENT_ELEMENTS.join(\",\")\n doc.search(selector).each(&:remove)\n end", "def destroy\n @page_element.destroy\n respond_to do |format|\n format.html { redirect_to council_page_page_elements_path(@council) }\n format.json { head :no_content }\n end\n end", "def destroy\n @scraping_html_element.destroy\n respond_to do |format|\n format.html { redirect_to scraping_html_elements_url, notice: 'Scraping html element was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_element(element); end", "def destroy\n @recommended_link.destroy\n\n head :no_content\n end", "def clear_links ()\n\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description Updates the general information of the element (title, description and tags) Mode Ajax Specific filters ApplicationControllerinitialize_media_element_with_owner_and_private
def update if @ok @media_element.title = params[:title] @media_element.description = params[:description] @media_element.tags = params[:tags_value] @media_element.save_tags = true if !@media_element.save @errors = convert_media_element_error_messages @media_element.errors else @media_element.set_status current_user.id end end end
[ "def update\n if @ok\n @media_element.title = params[:title]\n @media_element.description = params[:description]\n @media_element.tags = params[:tags]\n @media_element.save_tags = true\n if params[:is_public]\n @media_element.is_public = true\n @media_element.publication_date = Time.zone.now\n end\n @error_fields = @media_element.errors.messages.keys if !@media_element.save\n end\n end", "def edit_description; end", "def update\n @description = Description.find(params[:id])\n params_description = description_params\n if params_description[:title]==@description.title || @description.media.size==1\n success = @description.update_attributes(params_description)\n else\n @medium.descriptions.delete(@description)\n @description = Description.new(params_description)\n @medium.descriptions << @description\n success = @description.save\n end \n \n respond_to do |format|\n if success\n flash[:notice] = ts('edit.successful', :what => Description.model_name.human.capitalize)\n format.html { redirect_to edit_medium_url(@medium) }\n format.xml { head :ok }\n else\n format.html { render :action => 'edit' }\n format.xml { render :xml => @description.errors.to_xml }\n end\n end\n end", "def set_artwork_description\n @artwork = Artwork.find(params[:id])\n @artwork.update_attribute(:description, params[:value])\n \n respond_to do |wants|\n desc = @artwork.description\n desc = '~' if desc.blank?\n wants.js { render :text => desc }\n end\n end", "def fleximage_editor\n \n ar_object = Kernel::const_get(params[:ar_object_class]).find(params[:ar_object_id])\n display_editor = (params[:display_editor] == \"false\")\n display_thumbnail = (params[:display_thumbnail] == \"true\")\n \n render :update do |page| \n page.replace(MainController.fleximage_domid(ar_object),\n render(:partial => \"/main/media_edit\", \n :locals => {:ar_object => ar_object, \n :timestamp => nil,\n :display_thumbnail => display_thumbnail, \n :display_editor => display_editor})\n )\n\t\tend\n end", "def set_title_and_description\n \t\tresp = get_resp(self.url)\n \t\tself.title = resp.match(/<title>(.+)<\\/title>/)[1]\n \t\tself.description = resp.match(/<meta name=\"description\" content=\"([^\\\"]*)/)[1]\n \t\tself.save!\n \tend", "def description=(text)\n edit_description\n self.text_area(:id=>\"contentmetadata_description_description\").set text\n end", "def set_titlepic\n @attachment = Attachment.find(params[:id]) \n if @attachment.image? # if attachment is an Image set flag\n @attachment.parent.attachments.update_all(\"flag_titlepic=0\")\n @attachment.flag_titlepic=true\n @attachment.save\n end\n respond_to do |format|\n format.html { \n redirect_to @attachment}\n format.js { \n @parent=@attachment.parent\n @attachments=@parent.attachments\n render :refresh_list\n }\n end\n end", "def setdescription\n @user = User.find_by_authentication_token(params[:auth_token])\n\n update_attrs = {description: params[:description]}\n @image = Image.where({user_id: @user.id, id: params[:id]}).first\n if (!@image.nil?)\n @image.update_attributes(update_attrs)\n end\n\n respond_to do |format|\n format.json { head :no_content }\n end\nend", "def initialize_media_element_creation\n record = MediaElement.new :media => params[:media]\n record.title = params[:title_placeholder] != '0' ? '' : params[:title]\n record.description = params[:description_placeholder] != '0' ? '' : params[:description]\n record.tags = params[:tags_value]\n record.user_id = current_user.id\n record.save_tags = true\n record\n end", "def list_media_details(gallery_name = \"test\", _browser = @browser)\n wait = Selenium::WebDriver::Wait.new(:timeout => 15)\n Log.logger.info(\"Listing Media properties and ids to edit it (for Gallery: #{gallery_name.inspect})\")\n self.open_gallery(gallery_name)\n wait.until { _browser.find_element(:xpath => @galmgr.edit_media) }.click\n frame = wait.until { _browser.find_element(:xpath => @galmgr.edit_overlay_frame) }\n _browser.switch_to.frame(frame)\n edit_media_ids = Hash.new\n i = 1\n wait.until { _browser.find_element(:xpath => \"//div[contains(@id, 'media-edit-')]\") }\n med_ct = Integer(_browser.find_elements(:xpath => \"//div[contains(@id, 'media-edit-')]\").size)\n Log.logger.info(\"Found editable images: #{med_ct}\")\n while i < med_ct+1\n media_url = _browser.find_element(:xpath => \"//div[contains(@id, 'media-edit-#{i}')]//img[contains(@class, '')]\").attribute(\"src\")\n Log.logger.info(\"Working on image number #{i}: #{media_url.inspect}\")\n if (i == 1)\n if(_browser.find_elements(:xpath => \"//select[@id = 'edit-field-license-und']\").size < 1)\n media_license_setting = \"\"\n media_type = \"video\"\n else\n media_license_setting = \"//select[@id = 'edit-field-license-und']\"\n media_type = \"image\"\n end\n media_title = \"//input[@id = 'edit-media-title-und-0-value']\"\n media_description = \"//textarea[@id = 'edit-media-description-und-0-value']\"\n media_tag = \"//input[@id = 'edit-field-tags-und']\"\n else\n if(_browser.find_elements(:xpath => \"//select[@id = 'edit-field-license-und--#{i}']\").size < 1)\n media_license_setting = \"\"\n media_type = \"video\"\n else\n media_license_setting = \"//select[@id = 'edit-field-license-und--#{i}']\"\n media_type = \"image\"\n end\n media_title = \"//input[@id = 'edit-media-title-und-0-value--#{i}']\"\n media_description = \"//textarea[@id = 'edit-media-description-und-0-value--#{i}']\"\n media_tag = \"//input[@id = 'edit-field-tags-und--#{i}']\"\n end\n\n Log.logger.info(\"image number #{i} media-type: #{media_type.inspect}\")\n Log.logger.info(\"image number #{i} media-title: #{media_title.inspect}\")\n edit_media_ids[media_url] = Hash.new() unless (edit_media_ids[media_url])\n edit_media_ids[media_url][:license] = media_license_setting\n edit_media_ids[media_url][:tag] = media_tag\n edit_media_ids[media_url][:desc] = media_description\n edit_media_ids[media_url][:title] = media_title\n edit_media_ids[media_url][:type] = media_type\n i += 1\n end\n return edit_media_ids\n end", "def description\n self.span(:id=>\"contentmetadata_description_display\").text\n end", "def apply_additional_descMetadata\n if self.respond_to? \"descMetadata\"\n if self.respond_to? \"identifier\" then self.identifier = self.pid end\n if self.respond_to? \"primary_display_url\" then self.primary_display_url = \"#{CONTENT_LOCATION_URL_BASE}/resources/#{self.pid}\" end\n if self.respond_to? \"record_change_date\" then self.record_change_date = Time.now.strftime(\"%Y-%m-%d\") end\n\n if self.respond_to?(\"contentMetadata\") && self.respond_to?(:get_resource_metadata_by_sequence_no)\n if self.contentMetadata.changed?\n # When the contentMetadata has changed, we retrieve the content with sequence no 1 (primary content)\n content_metadata = self.get_resource_metadata_by_sequence_no(\"1\")\n # and update descMetadata with the metadata \n unless content_metadata.nil?\n self.descMetadata.update_mods_content_metadata_by_params(content_metadata[:asset_id], content_metadata[:datastream_id], content_metadata[:content_size], content_metadata[:mime_type]) if self.descMetadata.respond_to? :update_mods_content_metadata_by_params\n end \n end\n end\n end\n end", "def edit\n @data = MediasHlp.getMedia(params[:id])\n @media = @data['media']\n @mode = 'U'\n\n @lang = Helper.getLang()\n @libraries = Helper.getLibraries(9,@lang);\n\n render 'admin/media/media'\n end", "def update_event_description\n\t flash.keep(:url)\n\t\t\n\t\t#find the event \n\t @event = Event.find(:first, :conditions => [\"userid = ? AND eventid = ?\", session[\"timeline_id\"], params[:event][:update_eventid]])\n\t \n\t\t\n\t\t#if it doesnt find it \n\t\tif (@event.nil?)\n\t\t\tprint \"\\n\\n\\n WE COULD NOT FIND AN EVENT TO UPDATE \\n\\n\\n\"\n\t\telse\n\t\t #update its description\n\t\t @event.desc = params[:event][:update_desc]\n\t\t\n\t\t print \"\\n\\n\\n WE ARE TRYING TO UPDATE IT !!! \" + params[:event][:update_desc] + \" \\n\\n\\n \"\n\t\t\n\t\t if @event.save\n\t\t\t respond_to do |format|\n\t\t\t format.html { redirect_to (\"/events/timeline/#{session[\"timeline_id\"]}\") }\n\t\t\t format.js \n\t\t\t end\n\t else\n\t\t print \"\\n\\n\\n SOMETHING SCREWED UP COULD NOT UPDATE THE EVENT DESC \\n\\n\"\n\t end\n\t end\n\t\t\n\tend", "def set_time_entry_description\n data=params\n @time_entry = Physical::Timeandexpenses::TimeEntry.find(data[:id])\n @time_entry.update_attribute(:description,data[:value])\n render :text => @time_entry.description\n end", "def set_expense_entry_description\n data=params\n @expense_entry = Physical::Timeandexpenses::ExpenseEntry.find(data[:id])\n @expense_entry.update_attribute(:description,data[:value])\n render :text => @expense_entry.description\n end", "def update\n json_response(@description.update!(description_params))\n end", "def set_time_entry_description\n data=params\n @time_entry = TneInvoiceTimeEntry.find(data[:id])\n @time_entry.update_attribute(:description,data[:value])\n render :text => @time_entry.description\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets media elements using Userown_media_elements
def get_own_media_elements current_user_own_media_elements = current_user.own_media_elements(@page, @for_page, @filter) @media_elements = current_user_own_media_elements[:records] @pages_amount = current_user_own_media_elements[:pages_amount] end
[ "def get_result_media_elements\n resp = current_user.search_media_elements(@word, @page, @for_page, @order, @filter)\n @media_elements = resp[:records]\n @pages_amount = resp[:pages_amount]\n @media_elements_amount = resp[:records_amount]\n @tags = []\n @tags = resp[:tags] if resp.has_key? :tags\n end", "def media\n self.dig_for_array(\"media\")\n end", "def get_result_media_elements_by_specific_tag\n resp = current_user.search_media_elements(@specific_tag_id, @page, @for_page, @order, @filter)\n @media_elements = resp[:records]\n @pages_amount = resp[:pages_amount]\n @media_elements_amount = resp[:records_amount]\n end", "def own_media_elements(page, per_page, filter=Filters::ALL_MEDIA_ELEMENTS, from_gallery=false)\n page = 1 if !page.is_a?(Fixnum) || page <= 0\n for_page = 1 if !for_page.is_a?(Fixnum) || for_page <= 0\n offset = (page - 1) * per_page\n select = 'media_elements.*'\n select = \"#{select}, (SELECT COUNT (*) FROM bookmarks WHERE bookmarks.bookmarkable_type = #{self.class.connection.quote 'MediaElement'} AND bookmarks.bookmarkable_id = media_elements.id AND bookmarks.user_id = #{self.class.connection.quote self.id.to_i}) AS bookmarks_count, (SELECT COUNT(*) FROM media_elements_slides WHERE (media_elements_slides.media_element_id = media_elements.id)) AS instances\" if !from_gallery\n relation = MediaElement.select(select).of(self)\n if [Filters::VIDEO, Filters::AUDIO, Filters::IMAGE].include? filter\n relation = relation.where('sti_type = ?', filter.capitalize)\n end\n pages_amount = Rational(relation.count, per_page).ceil\n resp = []\n if from_gallery\n resp = relation.limit(per_page).offset(offset)\n else\n relation.limit(per_page).offset(offset).each do |me|\n me.set_status self.id, {:bookmarked => :bookmarks_count}\n resp << me\n end\n end\n {:records => resp, :pages_amount => pages_amount}\n end", "def get_media_elements(page)\n MediaElement.joins(:taggings).where(:taggings => {:tag_id => self.id}).order('media_elements.updated_at DESC').page(page)\n end", "def media_elements_at\n case self.kind\n when AUDIO, VIDEO1, VIDEO2\n resp = self.media_elements_slides.first\n resp.nil? ? nil : resp.media_element\n when COVER, IMAGE1, IMAGE3\n self.media_elements_slides.first\n when IMAGE2\n resp = [nil, nil]\n mes = self.media_elements_slides\n resp[mes[0].position - 1] = mes[0] if !mes[0].nil?\n resp[mes[1].position - 1] = mes[1] if !mes[1].nil?\n resp\n when IMAGE4\n resp = [nil, nil, nil, nil]\n mes = self.media_elements_slides\n resp[mes[0].position - 1] = mes[0] if !mes[0].nil?\n resp[mes[1].position - 1] = mes[1] if !mes[1].nil?\n resp[mes[2].position - 1] = mes[2] if !mes[2].nil?\n resp[mes[3].position - 1] = mes[3] if !mes[3].nil?\n resp\n else\n nil\n end\n end", "def list\n make_request(\"GetMediaList\").xpath(\"/response/media\").map {|node| MediaListItem.new(node) }\n end", "def list_media\n self.class.get(\"/gp/gpMediaList\")\n end", "def get_audios_and_videos_for_reload\n x = current_user.own_media_elements(1, GalleriesController::AUDIOS_FOR_PAGE, Filters::AUDIO, true)\n @audios = x[:records]\n @audios_tot_pages = x[:pages_amount]\n x = current_user.own_media_elements(1, GalleriesController::VIDEOS_FOR_PAGE, Filters::VIDEO, true)\n @videos = x[:records]\n @videos_tot_pages = x[:pages_amount]\n end", "def get_medias(data)\n result = @client.api_request(\n :method => \"usermedia.get\",\n :params => {\n :userids => data[:userid],\n :output => \"extend\"\n }\n )\n result ? result : nil\n end", "def mediafiles\n source_node.xpath('.//MediaFile').to_a.collect do |node|\n Mediafile.new(node)\n end\n end", "def ig_media\n\t\tif has_ig_username?\n\t\t\ttag = instagram_username\n\t\telse\n\t\t\ttag = find_ig_tag(name)\n\t\t\treturn [] if tag.nil?\n\t\tend\n\t\tmedia = ig_client.tag_recent_media(tag)\n\tend", "def search_media_elements(word, page, for_page, order=nil, filter=nil, only_tags=nil)\n only_tags = false if only_tags.nil?\n page = 1 if page.class != Fixnum || page <= 0\n for_page = 1 if for_page.class != Fixnum || for_page <= 0\n filter = Filters::ALL_MEDIA_ELEMENTS if filter.nil? || !Filters::MEDIA_ELEMENTS_SEARCH_SET.include?(filter)\n order = SearchOrders::UPDATED_AT if order.nil? || !SearchOrders::MEDIA_ELEMENTS_SET.include?(order)\n offset = (page - 1) * for_page\n if word.blank?\n return search_media_elements_without_tag(offset, for_page, filter, order)\n else\n if word.class != Fixnum\n word = word.to_s\n if only_tags\n return get_tags_associated_to_media_element_search(word, filter)\n else\n resp = search_media_elements_with_tag(word, offset, for_page, filter, order)\n resp[:tags] = get_tags_associated_to_media_element_search(word, filter)\n return resp\n end\n else\n return search_media_elements_with_tag(word, offset, for_page, filter, order)\n end\n end\n end", "def media\n @fields.values.inject(Widgets::Media.new) do |media, field|\n media + field.widget.media\n end\n end", "def get_user_recent_media\n response = @client.get(\"#{@base_url}/v1/users/self/media/recent\", access_token: get_user_access_token)\n medias = JSON.parse(response.body) \n if(medias[\"meta\"][\"code\"] == 200)\n media_url = []\n medias[\"data\"].each do |media|\n url = media[\"images\"][\"standard_resolution\"][\"url\"]\n media_url.push(url)\n end\n media_url \n end\n end", "def find_media(media_u_id)\n\t\t\tif !@media.nil? \n\t\t\t\treturn @media.find { |m| m.u_id == media_u_id }\n\t\t\tend\n\t\t\treturn nil\n\t\tend", "def media\n return @media\n end", "def my_created_elements\n MediaElement.where(:user_id => user.id).count\n end", "def all_shared_elements\n MediaElement.where(:is_public => true).count\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /action_states GET /action_states.json
def index @action_states = ActionState.all end
[ "def get_states\n perform(:get, 'enum/states', nil, nonauth_headers).body\n end", "def index\n @states = states.all\n json_response(@states)\n end", "def states\n response = params[:name].present? ? State.search(params[:name].to_s) : @country.states\n render json: response\n end", "def index\n @api_states = Api::State.all\n end", "def index\n @requests_states = Requests::State.all\n end", "def index\n @ag_states = Ag::State.all\n end", "def index\n @event_states = EventState.all\n end", "def list_states\n if params[:country_2_code].present?\n all_states = [[\"\", \"Select State/Province\"]]\n Country.find_country_by_alpha2(\"#{params[:country_2_code]}\").states.sort.map { |state|\n all_states << [\"#{state[0]}\", \"#{state[1].first[1]}\"]\n }\n render :json => all_states\n else\n render :text => \"Please select a country to continue...\"\n end\n end", "def index\n @intervention_states = InterventionState.all\n end", "def device_states_list\n get \"deviceStates\"\n end", "def index\n @user_states = UserState.all\n end", "def states\r\n @states.collect {|id| $data_states[id] }\r\n end", "def index\n @asset_states = AssetState.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @asset_states }\n end\n end", "def index\n if params.has_key?(\"country_id\")\n @db_country = DbCountry.find(params[:country_id])\n #@db_state = DbState.where((country_id: params[:id]))\n @db_states = @db_country.states\n else\n @db_states = DbState.all\n end\n render json: @db_states\n end", "def index\n @states = @country.states.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @states }\n end\n end", "def index\n @service_states = ServiceState.all\n end", "def show\n\t\t@state = State.find(params[:id])\n\n\t\trespond_to do |format|\n\t\t\tformat.html #show.html.erb\n\t\t\tformat.json { render json: @state }\n\t\tend\n\tend", "def index\n @server_states = ServerState.all\n end", "def index\n @oxidation_states = OxidationState.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /action_states POST /action_states.json
def create @action_state = ActionState.new(action_state_params) respond_to do |format| if @action_state.save format.html { redirect_to [project, @action_state], notice: 'Action state was successfully created.' } format.json { render :show, status: :created, location: @action_state } end end end
[ "def create\n state.attributes = state_params\n\n respond_to do |format|\n if state.save\n format.html { redirect_to admin_states_path, notice: 'State was successfully created.' }\n format.json { render :show, status: :created, location: state }\n else\n format.html { render :new }\n format.json { render json: state.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @action_states = ActionState.all\n end", "def create\n @state = State.new(state_params)\n\n if @state.save\n render json: @state, status: :created, location: @state\n # 'state was successfully created.'\n else\n render json: @state.errors, status: :unprocessable_entity\n end\n end", "def states_params\n\t \t params.require(:state).permit(:country_id, :name, :status)\n\t end", "def create\n @state = current_user.states.new(state_params)\n\n respond_to do |format|\n if @state.save\n format.html { redirect_to @state, notice: 'State was successfully created.' }\n format.json { render :show, status: :created, location: @state }\n else\n format.html { render :new }\n format.json { render json: @state.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\t\t@state = State.new(params[:state])\n\t\t@country = Country.find_by_iso_code(@state.country_iso_code)\n\t\tif (@country.nil?)\n\t\t\tformat.html { render action: \"new\" }\n\t\t\tformat.json { render json: @state.errors, status: :unprocessable_entity }\n\t\telse\n\t\t\t@state.country = @country\n\t\t\t@country.states.append @state\n\t\tend\n\n\t\trespond_to do |format|\n\t\t\tif @state.save && @country.save\n\t\t\t\tformat.html { redirect_to @state, notice: \"State was successfully created\" }\n\t\t\t\tformat.json { render json: @state, status: :created, location: @state }\n\t\t\telse\n\t\t\t\tformat.html { render action: \"new\"}\n\t\t\t\tformat.json { render json: @state.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def create\n @map_state = MapState.new(params[:map_state])\n\n respond_to do |format|\n if @map_state.save\n format.html { redirect_to @map_state, :notice => 'Map state was successfully created.' }\n format.json { render :json => @map_state, :status => :created, :location => @map_state }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @map_state.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @state = State.new(params[:state])\n\n respond_to do |format|\n if @state.save\n format.html { redirect_to @state, notice: 'State was successfully created.' }\n format.json { render json: @state, status: :created, location: @state }\n else\n format.html { render action: \"new\" }\n format.json { render json: @state.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ag_state = Ag::State.new(ag_state_params)\n\n respond_to do |format|\n if @ag_state.save\n format.html { redirect_to @ag_state, notice: 'State was successfully created.' }\n format.json { render :show, status: :created, location: @ag_state }\n else\n format.html { render :new }\n format.json { render json: @ag_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @api_state = Api::State.new(api_state_params)\n\n if @api_state.save\n render json: @api_state, status: :created, location: @api_state\n else\n render json: @api_state.errors, status: :unprocessable_entity\n end\n end", "def create\n @requests_state = Requests::State.new(requests_state_params)\n\n respond_to do |format|\n if @requests_state.save\n format.html { redirect_to @requests_state, notice: 'State was successfully created.' }\n format.json { render action: 'show', status: :created, location: @requests_state }\n else\n format.html { render action: 'new' }\n format.json { render json: @requests_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ot_state = OtState.new(params[:ot_state])\n\n respond_to do |format|\n if @ot_state.save\n format.html { redirect_to @ot_state, notice: 'Ot state was successfully created.' }\n format.json { render json: @ot_state, status: :created, location: @ot_state }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ot_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @state = State.new(params[:state])\n\n respond_to do |format|\n if @state.save\n format.html { redirect_to(states_path, :notice => 'State was Created Successfully.') }\n format.xml { render :xml => @state, :status => :created, :location => @state }\n else\n\t@country = Country.all\n format.html { render :action => \"new\" }\n format.xml { render :xml => @state.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @state = State.new(params[:state])\n\n respond_to do |format|\n if @state.save\n format.html { redirect_to(states_url, :notice => 'State was successfully created.') }\n format.xml { render :xml => @state, :status => :created, :location => @state }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @state.errors, :status => :unprocessable_entity }\n end\n end\n end", "def states\n response = params[:name].present? ? State.search(params[:name].to_s) : @country.states\n render json: response\n end", "def create\n @event_state = EventState.new(event_state_params)\n\n respond_to do |format|\n if @event_state.save\n format.html { redirect_to @event_state, notice: 'Event state was successfully created.' }\n format.json { render :show, status: :created, location: @event_state }\n else\n format.html { render :new }\n format.json { render json: @event_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @state = @country.states.build(params[:state])\n\n respond_to do |format|\n if @state.save\n format.html { redirect_to([@country, @state], :notice => 'State was successfully created.') }\n format.xml { render :xml => @state, :status => :created, :location => [@country, @state] }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @state.errors, :status => :unprocessable_entity }\n end\n end\n end", "def index\n @states = states.all\n json_response(@states)\n end", "def create\n @observation_state = ObservationState.new(params[:observation_state])\n\n respond_to do |format|\n if @observation_state.save\n flash[:notice] = 'ObservationState was successfully created.'\n format.html { redirect_to(observation_state_observation_cities_url(@observation_state)) }\n format.xml { render :xml => @observation_state, :status => :created, :location => @observation_state }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @observation_state.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /action_states/1 PATCH/PUT /action_states/1.json
def update respond_to do |format| if @action_state.update(action_state_params) format.html { redirect_to [project, @action_state], notice: 'Action state was successfully updated.' } format.json { render :show, status: :ok, location: @action_state } end end end
[ "def update\n respond_to do |format|\n if @requests_state.update(requests_state_params)\n format.html { redirect_to @requests_state, notice: 'State was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @requests_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @state = State.find(params[:id])\n\n respond_to do |format|\n if @state.update_attributes(params[:state])\n format.html { redirect_to @state, notice: 'State was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @state.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @api_state = Api::State.find(params[:id])\n\n if @api_state.update(api_state_params)\n head :no_content\n else\n render json: @api_state.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if state.update(state_params)\n format.html { redirect_to admin_state_path(state), notice: 'State was successfully updated.' }\n format.json { render :show, status: :ok, location: state }\n else\n format.html { render :edit }\n format.json { render json: state.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @ot_state = OtState.find(params[:id])\n\n respond_to do |format|\n if @ot_state.update_attributes(params[:ot_state])\n format.html { redirect_to @ot_state, notice: 'Ot state was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ot_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @state = State.find(params[:id])\n\n respond_to do |format|\n if @state.update_attributes(params[:state])\n format.html { redirect_to(states_path, :notice => 'State was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @state.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @intervention_state.update(intervention_state_params)\n format.html { redirect_to intervention_states_url, notice: \"Intervention state was successfully updated.\" }\n format.json { render :show, status: :ok, location: @intervention_state }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @intervention_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @state = @country.states.find(params[:id])\n\n respond_to do |format|\n if @state.update_attributes(params[:state])\n format.html { redirect_to([@country, @state], :notice => 'State was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @state.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @modelstate.update(params[:modelstates])\n format.html { redirect_to @modelstate, notice: 'Modelstate was successfully updated.' }\n format.json { render :show, status: :ok, location: @modelstate }\n else\n format.html { render :edit }\n format.json { render json: @modelstate.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @state_option = StateOption.find(params[:id])\n\n respond_to do |format|\n if @state_option.update_attributes(params[:state_option])\n format.html { redirect_to @state_option, :notice => 'State option was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @state_option.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @map_state = MapState.find(params[:id])\n\n respond_to do |format|\n if @map_state.update_attributes(params[:map_state])\n format.html { redirect_to @map_state, :notice => 'Map state was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @map_state.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @state = State.find(params[:id])\n\n respond_to do |format|\n if @state.update_attributes(params[:state])\n format.html { redirect_to(@state, :notice => 'State was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @state.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @ag_state.update(ag_state_params)\n format.html { redirect_to @ag_state, notice: 'State was successfully updated.' }\n format.json { render :show, status: :ok, location: @ag_state }\n else\n format.html { render :edit }\n format.json { render json: @ag_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @sprint_state.update(sprint_state_params)\n format.html { redirect_to @sprint_state, notice: 'Sprint state was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @sprint_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @event_state.update(event_state_params)\n format.html { redirect_to @event_state, notice: 'Event state was successfully updated.' }\n format.json { render :show, status: :ok, location: @event_state }\n else\n format.html { render :edit }\n format.json { render json: @event_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @state = State.find(params[:id])\n\n respond_to do |format|\n if @state.update_attributes(params[:state])\n flash[:notice] = 'State was successfully updated.'\n format.html { redirect_to(@state) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @state.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service_state.update(service_state_params)\n format.html { redirect_to @service_state, notice: 'Service state was successfully updated.' }\n format.json { render :show, status: :ok, location: @service_state }\n else\n format.html { render :edit }\n format.json { render json: @service_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @federal_state.update(federal_state_params)\n format.html { redirect_to @federal_state, notice: 'Federal state was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @federal_state.errors, status: :unprocessable_entity }\n end\n end\n end", "def change_state\n ticket = Ticket.find_by(id: params[:id])\n name = params[:state]\n if current_user.allowed_ticket_state.has_key?(name)\n ticket.send(\"#{name}_state!\")\n ticket.update_attributes(agent_id: current_user.id) if current_user.is_agent?\n ticket.reload\n render json: ticket.as_json\n else\n render json: {\"#{name}\": 'state not allowed'}, status: :unprocessable_entity\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
current_organisation returns organisation obj for current organisation return nil if no current organisation defined
def current_organisation() begin organisation = ( Thread.current[:organisation_id].blank? ? nil : Organisation.find( Thread.current[:organisation_id] ) ) return organisation rescue ActiveRecord::RecordNotFound return nil end end
[ "def organisation?\n current_organisation.present?\n end", "def set_current_organisation( organisation )\n # able to handle organisation obj or organisation_id\n #case organisation\n # when Organisation then organisation_id = organisation.id\n # when Integer then organisation_id = organisation\n # when Array then organisation_id = organisation\n # else\n # raise ArgumentError, \"invalid organisation object or id\"\n #end\n #old_id = ( Thread.current[:organisation_id].nil? ? '%' : Thread.current[:organisation_id] )\n if organisation.is_a? Integer\n organisation = Organisation.where(id: organisation).first\n end\n \n Thread.current[:organisation_id] = organisation.present? ? organisation.root.subtree.map(&:id) : nil\n Thread.current[:current_organisation_id] = organisation.present? ? organisation.subtree.map(&:id) : nil\n Thread.current[:root_organisation_id] = organisation.present? ? organisation.root.id : nil\n #organisation = Organisation.find(organisation_id) rescue nil\n #Time.zone = organisation.time_zone || 'Singapore' rescue 'Singapore'\n end", "def current_organisation_id()\n return Thread.current[:organisation_id]\n end", "def organisation\n organisations.first\n end", "def organisation\n Organisation.new(organisation_name)\n end", "def organisation\n if @organisation.nil?\n @organisation = LUSI::API::Organisation::Organisation.new\n @organisation.load(self.lusi_api, in_use_only: false)\n end\n @organisation\n end", "def organization\n @organization ||= current_assignment.organization\n end", "def org\n @org ||= org_options.first\n end", "def current_organization\n fog_model_interface.current_organization\n end", "def current_organisation_name\n if current_permission.nil?\n return \"You need to select an organisation to work for!\"\n end\n if current_permission.organisation.nil?\n return \"Error: My current permission has no organisation\"\n end\n current_permission.organisation.name\n end", "def organisation_name\n return if partnership?\n\n organisation.name\n end", "def organization\n return @organization if @organization\n @organization = Organization.find(organization_id)\n end", "def organization\n return @organization\n end", "def organization\n organization_quarter.organization unless organization_quarter.nil?\n end", "def organisation?\n session[:organisation] and session[:organisation].size > 0\n end", "def org\n client.org(org_id)\n end", "def current_company\n @company ||= current_user.company if current_user.present?\n end", "def organisation=(new_organisation)\n organisation_id = new_organisation.id unless new_organisation.nil?\n end", "def current_company\n if employment = current_employment\n return employment.employer\n end\n nil\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
current_organisation_id returns organisation_id for current organisation
def current_organisation_id() return Thread.current[:organisation_id] end
[ "def current_organisation()\n begin\n organisation = (\n Thread.current[:organisation_id].blank? ?\n nil :\n Organisation.find( Thread.current[:organisation_id] )\n )\n\n return organisation\n\n rescue ActiveRecord::RecordNotFound\n return nil\n end \n end", "def set_current_organisation( organisation )\n # able to handle organisation obj or organisation_id\n #case organisation\n # when Organisation then organisation_id = organisation.id\n # when Integer then organisation_id = organisation\n # when Array then organisation_id = organisation\n # else\n # raise ArgumentError, \"invalid organisation object or id\"\n #end\n #old_id = ( Thread.current[:organisation_id].nil? ? '%' : Thread.current[:organisation_id] )\n if organisation.is_a? Integer\n organisation = Organisation.where(id: organisation).first\n end\n \n Thread.current[:organisation_id] = organisation.present? ? organisation.root.subtree.map(&:id) : nil\n Thread.current[:current_organisation_id] = organisation.present? ? organisation.subtree.map(&:id) : nil\n Thread.current[:root_organisation_id] = organisation.present? ? organisation.root.id : nil\n #organisation = Organisation.find(organisation_id) rescue nil\n #Time.zone = organisation.time_zone || 'Singapore' rescue 'Singapore'\n end", "def org_id\n @org_id ||= query_org_id # lazy query org_id when not set by login response\n end", "def org_id\n query('select id from Organization').first['Id']\n end", "def org_id\n object = query('SELECT Id FROM Organization').first\n if object && object[:id]\n return object[:id].is_a?(Array) ? object[:id].first : object[:id]\n end\n end", "def organisation=(new_organisation)\n organisation_id = new_organisation.id unless new_organisation.nil?\n end", "def organisation\n organisations.first\n end", "def select_org\n if params[:current_org_id]\n session[:org_id]=params[:current_org_id]\n end\n end", "def get_org_id\n\n \t\t\tuserInfoPath = \"/accounts/api/me\"\n\n \t\t\trequest = Net::HTTP::Get.new(userInfoPath, authHeader)\n\n \t\t\tresponse = @http.request(request)\n\n \t\t\tjsonData = JSON.parse(response.body)\n\n \t\t\treturn jsonData['user']['organization']['id']\n \t\tend", "def connected_organization_id\n return @connected_organization_id\n end", "def my_site_id\n if self.current_user.present? && self.current_user.role != 'ROLE_SITE-SU'\n self.participating_sites.each do |e|\n if self.current_user.organization.present? && e.organization.present? && e.organization.id == self.current_user.organization.id\n return e.id\n end\n end\n else\n return nil\n end\n end", "def organisation?\n current_organisation.present?\n end", "def get_company_id\n if is_secretary_or_team_manager?\n current_service_session.assignment.nil? ? current_service_session.user.company_id : current_service_session.assignment.user.company_id\n else\n current_user.company_id\n end\n end", "def current_organisation_name\n if current_permission.nil?\n return \"You need to select an organisation to work for!\"\n end\n if current_permission.organisation.nil?\n return \"Error: My current permission has no organisation\"\n end\n current_permission.organisation.name\n end", "def organisation=(new_org)\n org_id = new_org.id unless new_org.nil?\n end", "def organisation\n Organisation.new(organisation_name)\n end", "def app_owner_organization_id\n return @app_owner_organization_id\n end", "def current_organization\n fog_model_interface.current_organization\n end", "def org\n client.org(org_id)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set_current_organisation modellevel ability to set the current organisation NOTE: USE WITH CAUTION normally this should NEVER be done from the models ... it's only useful and safe WHEN performed at the start of a background job (DelayedJobperform)
def set_current_organisation( organisation ) # able to handle organisation obj or organisation_id #case organisation # when Organisation then organisation_id = organisation.id # when Integer then organisation_id = organisation # when Array then organisation_id = organisation # else # raise ArgumentError, "invalid organisation object or id" #end #old_id = ( Thread.current[:organisation_id].nil? ? '%' : Thread.current[:organisation_id] ) if organisation.is_a? Integer organisation = Organisation.where(id: organisation).first end Thread.current[:organisation_id] = organisation.present? ? organisation.root.subtree.map(&:id) : nil Thread.current[:current_organisation_id] = organisation.present? ? organisation.subtree.map(&:id) : nil Thread.current[:root_organisation_id] = organisation.present? ? organisation.root.id : nil #organisation = Organisation.find(organisation_id) rescue nil #Time.zone = organisation.time_zone || 'Singapore' rescue 'Singapore' end
[ "def organisation_id=(new_organisation_id)\n unless self.can_change_org? || new_organisation_id.nil? || self.organisation.nil?\n # rip all permissions from the user\n self.roles.delete_all\n end\n # set the user's new organisation\n super(new_organisation_id)\n self.save!\n # rip api permissions from the user\n self.remove_token!\n end", "def set_organization\n if current_user\n current_organization = Organization.find(current_user.organization_id)\n set_current_tenant(current_organization)\n end\n end", "def update\n if !current_user.admin?\n head :forbidden\n else\n if @organisation.update(organisation_params)\n render json: @organisation.to_json, status: :ok\n else\n render json: @organisation.errors, status: :unprocessable_entity\n end\n end\n end", "def organisation=(new_organisation)\n organisation_id = new_organisation.id unless new_organisation.nil?\n end", "def organisation=(new_org)\n org_id = new_org.id unless new_org.nil?\n end", "def set_project\n @project = Project.find(params[:id]) if current_user.has_role?(:vendor, Project.find(params[:id])) || current_user.has_role?(:sponsor, Project.find(params[:id])) ||\n current_user.has_role?(:admin, Project.find(params[:id]))\n end", "def set_organisation_uid\n client = ServiceRegistry.service(:auth_api_client).new(@auth_token)\n organisations = client.organisations(types: [:law_firm])\n\n if organisations.empty?\n false\n else\n defence_request.organisation_uid = organisations.first.uid\n end\n end", "def inherit_settings_from(current_community)\n # Mark as organization user if signed up through market place which is only for orgs\n self.is_organization = current_community.only_organizations\n self.min_days_between_community_updates = current_community.default_min_days_between_community_updates\n end", "def set_organization_of(user)\n @organization = user.organization rescue nil\n end", "def org_id=(new_org_id)\n unless self.can_change_org? || new_org_id.nil? || self.org.nil? || (new_org_id.to_s == self.org.id.to_s)\n # rip all permissions from the user\n self.perms.delete_all\n end\n # set the user's new organisation\n super(new_org_id)\n self.save!\n # rip api permissions from the user\n self.remove_token!\n end", "def autonomous_system_organization; end", "def organisation=(org)\n\t if supplier \n exist_supplier = org.suppliers.find_or_build_from( :name => supplier.name, \n :uid => supplier.uid, \n :organisation => org, \n :vat_number => supplier.vat_number, \n :company_number => supplier.company_number)\n self.supplier = exist_supplier || supplier\n self.supplier.organisation = org unless exist_supplier\n else\n @organisation = org\n end\n\tend", "def set_selected_organization(org)\n session[USER_SELECTED_ORGANIZATION] = org.short_name\n end", "def edit\n @organisation = Organisation.find(params[:id])\n setup_organisation\n end", "def current_organisation()\n begin\n organisation = (\n Thread.current[:organisation_id].blank? ?\n nil :\n Organisation.find( Thread.current[:organisation_id] )\n )\n\n return organisation\n\n rescue ActiveRecord::RecordNotFound\n return nil\n end \n end", "def organization\n @organization ||= current_assignment.organization\n end", "def move_to(org)\n self.organisation = org\n self.save\n end", "def check_and_set_organisation(user)\n\n return if user.organisations.any?\n\n user.organisations.create\n\n end", "def current_company=(company_obj)\n self.current_company_id = company_obj.id\n self.save\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
where_restrict_organisation gens organisation restrictive where clause for each klass NOTE: subordinate join tables will not get the default scope by Rails theoretically, the default scope on the master table alone should be sufficient in restricting answers to the current_organisation alone .. HOWEVER, it doesn't feel right. adding an additional .where( where_restrict_organisations(klass1, klass2,...)) for each of the subordinate models in the join seems like a nice safety issue.
def where_restrict_organisation(*args) args.map{|klass| "#{klass.table_name}.organisation_id = #{Thread.current[:organisation_id]}"}.join(" AND ") end
[ "def where_restrict_tenant(*args)\n args.map { |klass| \"#{klass.table_name}.tenant_id = #{Thread.current[:tenant_id]}\" }.join(\" AND \")\n end", "def where_restrict_account(*args)\n args.map{|klass| \"#{klass.table_name}.account_id = #{Thread.current[:account_id]}\"}.join(\" AND \")\n end", "def search_model_clause\n # The concrete class could could be any subclass of @klass or @klass itself\n return if @klass == ActiveFedora::Base\n clauses = ([@klass] + @klass.descendants).map do |k|\n ActiveFedora::SolrQueryBuilder.construct_query_for_rel(has_model: k.to_s)\n end\n clauses.size == 1 ? clauses.first : \"(#{clauses.join(' OR ')})\"\n end", "def join_scope(table, foreign_table, foreign_klass)\n return super unless connected_through_array?\n\n predicate_builder = predicate_builder(table)\n scope_chain_items = join_scopes(table, predicate_builder)\n klass_scope = klass_join_scope(table, predicate_builder)\n\n klass_scope.where!(build_id_constraint_between(table, foreign_table))\n klass_scope.where!(type => foreign_klass.polymorphic_name) if type\n klass_scope.where!(klass.send(:type_condition, table)) \\\n if klass.finder_needs_type_condition?\n\n scope_chain_items.inject(klass_scope, &:merge!)\n end", "def apply_filter_by_associations_distinct_on_limit_strategy(ds)\n k = filter_by_associations_limit_key \n ds.where(k=>apply_distinct_on_eager_limit_strategy(associated_eager_dataset.select(*k)))\n end", "def apply_filter_by_associations_limit_strategy(ds)\n case filter_by_associations_limit_strategy\n when :distinct_on\n apply_filter_by_associations_distinct_on_limit_strategy(ds)\n when :window_function\n apply_filter_by_associations_window_function_limit_strategy(ds)\n else\n ds\n end\n end", "def filter_by_associations_conditions_dataset\n cached_fetch(:filter_by_associations_conditions_dataset) do\n ds = associated_eager_dataset.unordered\n ds = filter_by_associations_add_conditions_dataset_filter(ds)\n ds = apply_filter_by_associations_limit_strategy(ds)\n ds\n end\n end", "def filter_for_organization\n model.where(organization_id: @organization.id)\n end", "def apply_filter_by_associations_limit_strategy(ds)\n case filter_by_associations_limit_strategy\n when :correlated_subquery\n apply_correlated_subquery_limit_strategy(ds)\n else\n super\n end\n end", "def prepare_join_classes(scope)\n scope_config = auth_scope(scope).config\n\n unless auth_scope(scope).role_subject_class.acts_as_authorization_role_subject?\n auth_scope(scope).role_subject_class.instance_eval do\n acts_as_authorization_role_subject(scope_config.to_h)\n end\n end\n \n if auth_scope(scope).config.with_permissions\n unless auth_scope(scope).permission_subject_class.acts_as_authorization_permission_subject?\n auth_scope(scope).permission_subject_class.instance_eval do\n acts_as_authorization_permission_subject(scope_config.to_h)\n end\n end\n unless auth_scope(scope).permission_role_class.acts_as_authorization_permission_role?\n auth_scope(scope).permission_role_class.instance_eval do\n acts_as_authorization_permission_role(scope_config.to_h)\n end\n end\n end\n end", "def org_conditions(ids)\n if current_user.is_user_in_role?(\"GEO Focal\") || current_user.is_user_in_role?(\"Admin\")\n return nil # these roles should see everything\n end\n size=ids.size - 1\n condition = Array.new\n ids.each_with_index do |id,index|\n id=id.to_s\n id=id.split(',')\n condition.push(\"(org_l1_id=#{id[0]} and org_id=#{id[1]})\")\n if size != index\n condition.push(\" OR \")\n end\n end\n condition.join('')\n end", "def joins_and_conditions_from_current_scope\n join_dependency = construct_join_dependency_for_association_find\n relation = construct_relation_for_association_find(join_dependency)\n joins_sql = relation.arel.join_sql\n conditions_sql = arel.where_sql || ''\n conditions_sql.sub!('WHERE', '')\n [joins_sql, conditions_sql]\n end", "def search_constrains\n {store: current_store}.tap do |c|\n c.merge!(vendor_id: current_group) if third_party?\n c.merge!(permitted_categories: current_group.available_categories) if current_group.limited_categories?\n end\n end", "def filter_by_associations_add_conditions_dataset_filter(ds)\n k = filter_by_associations_conditions_associated_keys\n ds.select(*k).where(Sequel.negate(k.zip([])))\n end", "def add_constraints(scope)\n tables = construct_tables\n \n chain.each_with_index do |reflection, i|\n table, foreign_table = tables.shift, tables.first\n \n if reflection.source_macro == :has_and_belongs_to_many\n join_table = tables.shift\n \n scope = scope.joins(join(\n join_table,\n table[reflection.association_primary_key].\n in(join_table[reflection.association_foreign_key])\n ))\n \n table, foreign_table = join_table, tables.first\n end\n \n if reflection.source_macro == :belongs_to\n if reflection.options[:polymorphic]\n key = reflection.association_primary_key(klass)\n else\n key = reflection.association_primary_key\n end\n \n foreign_key = reflection.foreign_key\n else\n key = reflection.foreign_key\n foreign_key = reflection.active_record_primary_key\n end\n \n conditions = self.conditions[i]\n \n if reflection == chain.last\n # GroupedScope changed this line.\n # scope = scope.where(table[key].eq(owner[foreign_key]))\n scope = if owner.group.present?\n scope.where(table[key].in(owner.group.ids_sql))\n else\n scope.where(table[key].eq(owner[foreign_key]))\n end\n \n if reflection.type\n scope = scope.where(table[reflection.type].eq(owner.class.base_class.name))\n end\n \n conditions.each do |condition|\n if options[:through] && condition.is_a?(Hash)\n condition = { table.name => condition }\n end\n \n scope = scope.where(interpolate(condition))\n end\n else\n constraint = table[key].eq(foreign_table[foreign_key])\n \n if reflection.type\n type = chain[i + 1].klass.base_class.name\n constraint = constraint.and(table[reflection.type].eq(type))\n end\n \n scope = scope.joins(join(foreign_table, constraint))\n \n unless conditions.empty?\n scope = scope.where(sanitize(conditions, table))\n end\n end\n end\n \n scope\n end", "def finder_sql_with_included_associations(options = {})#:nodoc\n join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merge_includes(scope(:find, :include), options[:include]), options[:joins])\n sql = construct_finder_sql_with_included_associations_with_ext(options, join_dependency)\n end", "def add_joins_and_conditions(query, reflection)\n # construct the join from journals table to the assignments_table\n query.join(join_table).on(\n join_table.primary_key.eq(\n assignments_table[:assigned_to_id]\n ).and(\n assignments_table[:assigned_to_type].eq(\n assigned_to_klass.base_class.name\n )\n )\n )\n\n # construct the join from papers table to the journals table\n query.outer_join(through_table).on(\n through_table[through_reflection.foreign_key].eq(\n join_table.primary_key\n )\n )\n\n # construct the join from tasks table to the papers table\n query.outer_join(klass.arel_table).on(\n if klass.column_names.member?(reflection.foreign_key)\n # has_one on the through_klass\n klass.arel_table[reflection.foreign_key]\n .eq(through_klass.arel_table.primary_key)\n else\n # belongs_to on the through_klass\n klass.arel_table.primary_key\n .eq(through_klass.arel_table[reflection.foreign_key])\n end)\n\n common_query.add_column_condition(\n query: query,\n column: through_klass.arel_table.primary_key,\n values: @target.where_values_hash[through_target_reflection.foreign_key]\n )\n\n query\n end", "def where_permits( priv, keyword_args = {} )\n priv, association = disassemble_priv( priv )\n if association.nil?\n return <<-END_SQL\n (#{table_name}.id in\n #{self.ids_permitting_internal( priv, keyword_args )})\n END_SQL\n else\n klass = self.class_for_associate(association)\n fk = self.reflect_on_association(association).foreign_key.to_s\n return <<-END_SQL\n (#{table_name}.#{fk} in\n #{klass.ids_permitting_internal( priv, keyword_args )})\n END_SQL\n end\n end", "def apply_filtering(klass, params, fields)\n rel = klass\n havings = []\n unless(params[:filters].blank?)\n filters = JSON.load(params[:filters])\n filters['rules'].each do |filter|\n field = discover_field(filter['field'].gsub('___', '.'), fields)\n oper = filter['op']\n raise ArgumentError.new(\"Invalid search operator received: #{oper}\") unless SEARCH_OPERS.keys.include?(oper)\n data = filter['data']\n if(fields.is_a?(Hash) && fields[field][:having])\n havings << [\"#{fields[field][:having]} #{SEARCH_OPERS[oper].first}\", SEARCH_OPERS[oper].last.call(data)]\n end\n if(defined?(ActiveRecord::Relation) && rel.is_a?(ActiveRecord::Relation))\n if(!fields.is_a?(Hash) || fields[field][:having].blank? || fields[field][:where])\n rel = rel.where([\n \"#{database_name_by_string(field, klass, fields)} #{SEARCH_OPERS[oper].first}\",\n SEARCH_OPERS[oper].last.call(data)\n ])\n end\n else\n if(!fields.is_a?(Hash) || fields[field][:having].blank? || fields[field][:where])\n rel = rel.scoped(\n :conditions => [\n \"#{database_name_by_string(field, klass, fields)} #{SEARCH_OPERS[oper].first}\",\n SEARCH_OPERS[oper].last.call(data)\n ]\n )\n end\n end\n end\n end\n unless(havings.blank?)\n ary = [\"(#{havings.map(&:first).join(') AND (')})\", *havings.map(&:last)]\n rel = defined?(ActiveRecord::Relation) && rel.is_a?(ActiveRecord::Relation) ? rel.having(ary) : rel.scoped(:having => ary)\n end\n rel\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pass target to the scope handler of the specified type and name. If `name` is not specified then `:default` name is used. If `type` is not specified then we try to infer the type from the target class.
def apply_scope(target, type:, name: :default, scope_options: nil) raise ActionPolicy::UnknownScopeType.new(self.class, type) unless self.class.scoping_handlers.key?(type) raise ActionPolicy::UnknownNamedScope.new(self.class, type, name) unless self.class.scoping_handlers[type].key?(name) mid = :"__scoping__#{type}__#{name}" scope_options ? send(mid, target, **scope_options) : send(mid, target) end
[ "def bind_name(name, type)\n @names[name.to_sym] = type unless name.nil?\n end", "def type_of(name)\n return @scope[name.to_sym][:type] if @scope[name.to_sym]\n @enclosing&.type_of(name)\n end", "def method_missing(sym, *args, &block)\n target = if !block && args.empty? && sym =~ /^[A-Za-z_][A-Za-z_0-9]*$/\n up_scope!(sym.to_s)\n end\n\n (target || @scope).send sym, *args, &block\n end", "def authorization_scope_type_for(policy, target)\n policy.resolve_scope_type(target)\n end", "def call_scope_by_type(type, scope, target, value, options) #:nodoc:\n if type == :boolean\n target.send(scope)\n elsif value && options.key?(:using)\n value = value.values_at(*options[:using])\n target.send(scope, *value)\n else\n target.send(scope, value)\n end\n end", "def method_missing(name, *args, &block)\n if scopes.include?(name)\n scopes[name].call(self, *args)\n elsif klass\n target.send(name, *args, &block)\n else\n @parent.fuse(@conditions); @parent.send(name, *args, &block)\n end\n end", "def for(type_name)\n raise NameError, \"No handler for type #{type_name}\" unless types[type_name]\n types[type_name]\n end", "def target(*args)\n if args.blank?\n const_defined?(:Target) ? const_get(:Target) : (@target || name[0..-5].classify.constantize)\n else\n self.target = args.first\n end\n end", "def target_name=(name)\n meta(TARGET_NAME_KEY, name)\n target_identifier { Object.const_get(name) } if @identifier.nil?\n end", "def bind(arg_name, klass)\n @bindings[arg_name] = klass\n end", "def target_type\n load_target\n @target_type ||= @identifier.call\n end", "def search_target(target = nil, **opt)\n opt = request_parameters if target.blank? && opt.blank?\n case target\n when Hash then opt.merge!(target.symbolize_keys)\n when Symbol, String then opt[:target] = target.to_sym\n end\n (opt[:target] || opt[:controller])&.to_sym\n end", "def get_class_from_scope(scope, name)\n scope.const_get(name)\n end", "def target_class_name\n options[:class_name] || name.to_s.classify\n end", "def context_type\n params[:type] ? (\"#{params[:type]}\".constantize == Kase ? :kase : \"#{params[:type]}\".constantize.kind) : super\n end", "def target_name(*args)\n if args.blank?\n (const_defined?(:TargetName) ? const_get(:TargetName) : (@target_name || target_model.name.underscore.titleize)).to_s\n else\n self.target_name = args.first\n end\n end", "def name_target=(value)\n @name_target = value\n end", "def method_scope(method_name, target: :self)\n MethodIntrospection.simple_lookup_chain_for(object, target).map{ |lookup_class|\n if RUBY_VERSION >= \"2.6.0\"\n case\n when lookup_class.public_method_defined?(method_name, true)\n :public\n when lookup_class.protected_method_defined?(method_name, true)\n :protected\n when lookup_class.private_method_defined?(method_name, true)\n :private\n else\n nil\n end\n else\n case\n when lookup_class.public_method_defined?(method_name)\n :public\n when lookup_class.protected_method_defined?(method_name)\n :protected\n when lookup_class.private_method_defined?(method_name)\n :private\n else\n nil\n end\n end\n }.compact.first\n end", "def target_klass\n target_klass_name.constantize\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define scope type matcher. Scope matcher is an object that implements `===` (_case equality_) or a Proc. When no type is provided when applying a scope we try to infer a type from the target object by calling matchers one by one until we find a matching type (i.e. there is a matcher which returns `true` when applying it to the target).
def scope_matcher(type, class_or_proc) scope_matchers << [type, class_or_proc] end
[ "def applies_type?(scope, type)\n !scope.key?(\"type\") || type&.to_sym.eql?(scope[\"type\"].to_sym)\n end", "def applies_type?(scope, type); end", "def scope_type=(value)\n @scope_type = value\n end", "def type?(type)\n @scope.type?(type)\n end", "def type_matcher(mod)\n TypeMatcher.new(mod)\n end", "def scope_type\n return @scope_type\n end", "def call_scope_by_type(type, scope, target, value, options) #:nodoc:\n if type == :boolean\n target.send(scope)\n elsif value && options.key?(:using)\n value = value.values_at(*options[:using])\n target.send(scope, *value)\n else\n target.send(scope, value)\n end\n end", "def applies?(scope, path, type)\n applies_type?(scope, type) && applies_path?(scope, path)\n end", "def authorization_scope_type_for(policy, target)\n policy.resolve_scope_type(target)\n end", "def scope_class\n @scope_class ||= Scope\n end", "def type_of(name)\n return @scope[name.to_sym][:type] if @scope[name.to_sym]\n @enclosing&.type_of(name)\n end", "def is_scope?(scope)\n (scope.is_a? ActiveRecord::Relation) || (scope.is_a? Arel::SelectManager)\n end", "def apply_scope(target, type:, name: :default, scope_options: nil)\n raise ActionPolicy::UnknownScopeType.new(self.class, type) unless\n self.class.scoping_handlers.key?(type)\n\n raise ActionPolicy::UnknownNamedScope.new(self.class, type, name) unless\n self.class.scoping_handlers[type].key?(name)\n\n mid = :\"__scoping__#{type}__#{name}\"\n scope_options ? send(mid, target, **scope_options) : send(mid, target)\n end", "def applies?(scope, path, type); end", "def emit_scope_matches(scope, &block)\n MATCHERS.each do |matcher|\n matcher.each(scope, &block)\n end\n end", "def apply_scope(scope)\n case scope\n when Proc\n instance_exec(&scope)\n when Symbol\n send(scope)\n when Criteria\n merge(scope)\n else\n self\n end\n end", "def set_scope_class\n klass = self.class::Scope\n klass.send(:include, ScopeMethods)\n @scope_class = klass.new(@scope, @search_attributes)\n end", "def class_scope?\n @type == :class || @type == :module\n end", "def class_scope?\n @type == :class or @type == :module\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main method for getting all Available TimeBlock(s) for a given date. +:base_time: DateTime used for determining the base scan date range.
def available_on(base_time) # Stash this for future use, as we will be using it to set a # baseline date in order to derive a bunch of different appointments # from. set_base_time(base_time) # Fetch all TimeEntris related for this date query. time_entries = time_entries_for(base) # Transform TimeEntry(s) -> TimeSlot(s). available_slots = generate_time_slots(time_entries) # Combine all sequential linear slots to into a single window. # This produces multiple windows windows = combine_linear_slots(available_slots) # Generate TimeBlocks from the Available Slot ranges open_time_blocks = generate_time_blocks(windows) # Optimize & Filter our wide collection of TimeBlocks. optimized_blocks = optimize_time_blocks(open_time_blocks) # Finally, present the TimeBlock(s) as Appointment records # to the Customer. final = transform_blocks_to_appointments(optimized_blocks) end
[ "def valid_blocks(base_time)\n set_base_time(base_time)\n time_entries = time_entries_for(base)\n end", "def hotel_blocks_for_specific_date_range(start_date, end_date)\n specific_date_range = Hotel::DateRange.new(start_date, end_date)\n hotel_blocks_for_specific_date_range = hotel_blocks.select do |hotel_block|\n hotel_block.date_range == specific_date_range\n end\n return hotel_blocks_for_specific_date_range\n end", "def hotel_block_list(start_date, end_date)\n given_date_range = Hotel::DateRange.new(start_date, end_date)\n # get the list of the hotel_block for the given date\n hotel_block_list = hotel_blocks.select do |hotel_block|\n hotel_block.date_range.overlap?(given_date_range)\n end\n return hotel_block_list\n end", "def index\n @time_blocks = TimeBlock.all\n end", "def build_available_slots(non_recurring_slots, recurring_slots, blocked_slots)\n availability = []\n loop do\n week_day = @date.wday\n availability << {\n date: @date.to_date,\n slots: non_recurring_slots[week_day] + recurring_slots[week_day] - blocked_slots[week_day]\n }\n break if (@date += 1.day) > @end_date\n end\n availability\n end", "def booking_date_slots\n\t\tresource = @company.resources.find_by_name(params[:resource])\n\t\t@slot_array = resource.available_time_slot params[:date_of_booking]\n\tend", "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 available_rooms_of_hotel_blocks(start_date, end_date)\n hotel_blocks_for_specific_date_range = hotel_blocks_for_specific_date_range(start_date, end_date)\n if hotel_blocks_for_specific_date_range.empty? \n raise ArgumentError.new (\"no hotel_block for the given date range.\")\n end\n available_rooms_of_hotel_blocks = hotel_blocks_for_specific_date_range.map do |hotel_block|\n hotel_block.rooms\n end\n all_available_rooms_of_hotel_blocks = available_rooms_of_hotel_blocks.flatten\n end", "def index\n @available_times = AvailableTime.all\n end", "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\n end", "def block_slots\n slots = []\n\n unless block_delivery_end_time.blank? || block_delivery_start_time.blank?\n\n available_hours = block_delivery_end_time - block_delivery_start_time\n\n number_of_slots = available_hours / 60.minutes\n\n number_of_slots.to_i.times do |i|\n slots << {\n from: block_delivery_start_time + i.hours,\n to: block_delivery_start_time + (i + 1).hours,\n type: :daytime\n }\n end\n end\n\n slots\n end", "def time_slots # does not take availability into account\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 starttime = Time.zone.now + 10.minutes\n # Then we have to round to the next hour block\n starttime = Time.zone.at( (starttime.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 starttime = [starttime, starttime.change(hour: opening_hour)].max\n\n # Determine the furthest in the future we will allow reservations\n end_time = (starttime + 3.days).change(hour: closing_hour)\n\n # Now, we want to make a list of every hour between our starttime 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 = starttime\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 time_slots # does not take availability into account\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 bookings\n date = Date.parse(place_params[:on_day]).beginning_of_day\n\n starts = date.advance(hours: 7).to_i\n ends = date.advance(hours: 19).to_i\n\n bookings_on_day = @place.bookings.on_day(date)\n\n @bookings = (starts..ends).step(1.hour).to_a.map do |time|\n BookingStruct.new(Time.at(time), true)\n end\n\n @bookings.each_with_index do |time, index|\n next if !@bookings[index].ok.nil?\n\n booking = bookings_on_day.detect {|b| b.date == time.date}\n services = booking.booked_services rescue nil\n duration = DateTime.parse(services.sum(:service_duration)) if services\n\n if !booking.nil?\n mark_booking_unavailable(booking, duration, index)\n if duration.hour > 0 && duration.min > 0\n (1..duration.hour).each do |h|\n mark_booking_unavailable(booking, duration, index+h)\n end\n end\n end\n end\n end", "def makeBlocks(days, startTimeString, endTimeString, info)\n\tblocks = []\n\tdays.split(\"\").each do |d|\n\t\tb = Block.new(d, startTimeString, endTimeString, info)\n\t\tblocks << b\n\tend\n\t(blocks)\nend", "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 makeBlocks(days, startTimeString, endTimeString, info)\n\tblocks = []\n\tdays.split(\"\").each do |d|\n\t\tb = SCHBlock.new(d, startTimeString, endTimeString, info)\n\t\tblocks << b\n\tend\n\t(blocks)\nend", "def get_readings_from_remote_for_dates(type, start_date, end_date)\n readings = []\n start_date.upto(end_date) do |date|\n readings += get_readings_from_remote(type, date)\n end\n return readings\nend", "def create_block_by_date(rooms_per_block, check_in, check_out, block_id, discount_percent: 0.0)\n while self.list_vacancies(check_in, check_out).empty?\n raise StandardError(\"No more vacancies!\")\n end\n\n room_num_array = self.list_vacancies(check_in, check_out).take(rooms_per_block).to_a\n\n # take one of the rooms from the room_num_array to make a reservation\n room_num = room_num_array.first\n\n new_block = Hotel::Block.new(room_num_array, check_in, check_out, block_id, discount_percent: 0.0)\n\n new_block.make_reservation(room_num, check_in, check_out, discount_percent: 0)\n\n @blocks << new_block\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Public api for returning all collisions for a given Range. The Range is transformed into a TimeBlock, and then pushed through the pipeline for natural detection of any collisions.
def collisions_for(range) collider.detect TimeBlock.new( start_time: range.begin, end_time: range.end, session: @session) end
[ "def collisions\n @@collisions || {}\n end", "def collide_hash_all(hash_rects)\n hash_rects.select { |key,value|\n value.collide_rect?+(self)\n }\n end", "def collisions(rect)\n remain = visible_sprites(rect).to_a\n coll = remain.select { |item| item.intersect_rect? rect }\n [coll, coll - remain]\n end", "def detect_collisions\n\t\t@all_entities.each do |entity|\n\t\t\t@all_entities.each do |other|\n\t\t\t\tif entity.overlaps?(other)\n\t\t\t\t\tentity.collision(other)\n\t\t\t\tend\n\t\t\tend\n\t\tend\t\n\tend", "def check_collisions!\n 1000.times do\n @particles.values.map(&:tick)\n position_groups = @particles.values.group_by(&:position)\n collisions = position_groups.select { |pos, particles| particles.size > 1 }\n collisions.values.flatten.collect(&:num).map { |num| @particles.delete(num) }\n end\n @particles\n end", "def collide_hash(hash_rects)\n hash_rects.each { |key,value|\n if value.collide_rect?+(self); return [key,value]; end\n }\n return nil\n end", "def each_collision(game_object)\r\n start_x = (game_object.bb.left / @grid[0]).to_i\r\n stop_x = (game_object.bb.right / @grid[0]).to_i\r\n \r\n (start_x ... stop_x).each do |x|\r\n start_y = (game_object.bb.top / @grid[1]).to_i\r\n stop_y = (game_object.bb.bottom / @grid[1]).to_i\r\n \r\n (start_y ... stop_y).each do |y|\r\n yield @map[x][y] if @map[x] && @map[x][y] && @map[x][y] != game_object # Don't yield collisions with itself\r\n end\r\n end\r\n end", "def fetch_halls(range_time)\n schedule.select { |period| range_time.include? to_time_string(period.range_time) }.flat_map(&:hall)\n end", "def calc_box_collision\n return unless state.world_lookup.keys.length > 0 # return unless hash has atleast 1 key\n collision_floor!\n collision_left!\n collision_right!\n collision_ceiling!\n end", "def within_range(x, y, range)\n cells_intersecting_circle(x, y, range).flatten.find_all do |entity|\n distance_between(x, y, entity.cx, entity.cy) <= range\n end\n end", "def compute_overlap range, ranges\n ranges.inject(0) do |memo, other|\n next memo unless intersects? range, other\n lower_bound = range.begin > other.begin ? range.begin : other.begin\n upper_bound = range.end < other.end ? range.end : other.end\n memo += upper_bound - lower_bound\n end\n end", "def overlap_with(time_range)\n raise TypeError unless time_range.is_a?(TimeRange)\n\n self.class.new(\n [self.begin, time_range.begin].max,\n [max, time_range.max].min\n ) if overlaps?(time_range)\n end", "def collide bodies\n\t\t[bodies].flatten.each do |body|\n\t\t\t\n\t\t\tnext unless body.linear_velocity.has_velocity?\n\t\t\n\t\t\tstop = body.pos + body.linear_velocity\n\t\t\n\t\t\told_group = @location[body]\n\t\t\trv,node2,@location[body] = point_inside_groups?( stop, body.radius )\n\n\t\t\tpoint_check = false\t\n\t\n\t\t\tif @location[body] == OUTSIDE\n\t\t\t\tunless old_group.nil? or old_group == OUTSIDE\n#\t\t\t\t\tputs \"body #{body} would end up leaving level at node #{node2}\"\n\t\t\t\t\t@location[body] = old_group\n\t\t\t\t\tpoint_check = true\n\t\t\t\tend\n\n\t\t\telsif old_group != @location[body]\n#\t\t\t\tputs \"body #{body} entered level group #{@location[body]}\"\n\t\t\t\tunless old_group.nil? or old_group == OUTSIDE\n\t\t\t\t\tpoint_check = true \n\t\t\t\tend\n\t\t\tend\n\t\t\n\t\t\t# the most surfaces we can hit at once is 3 walls at a corner\n\t\t\t# thus we run this loop 3 times detection and resolving collisions with nodes\n\t\t\t# from ProcessShips in file ships.c \n\n\t\t\t100.times do # added more to stop flying through \n\t\t\n\t\t\t\t# find out where our movement collided\n\t\t\t\tcollided = ray_collide_group body, @location[body] \n\n\t\t\t\t# no collisions\n\t\t\t\tunless collided\n\t\t\t\t\tif point_check\n#\t\t\t\t\t\tputs \"point check says we collided but ray check says we didn't\"\n\t\t\t\t\t\t@location[body] = old_group\n\t\t\t\t\tend\n\t\t\t\t\tbreak # we are done\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# validate we have needed data\n\t\t\t\tunless @collide_node and @collide_point\n#\t\t\t\t\tputs \"ray check says we collided but we missing node/point\"\n\t\t\t\t\tnext\n\t\t\t\tend\n\n\t\t\t\t# another check\n\t\t\t\tif !node2.nil? and node2.index != @collide_node.index\n#\t\t\t\t\tputs \"point check says we hit node #{node2.index} \"+\n#\t\t\t\t\t\t\"but ray check says we hit node #{@collide_node.index}\"\n\t\t\t\tend\n\n# start experiment\n=begin\n\n\t\t\t\t@nodes = []\n\t\t\t\tif @nodes.include? @collide_node\n\t\t\t\t\tputs \":: last loop failed to stop me from colliding against same node\"\n\t\t\t\t\texit\n\t\t\t\t\t#puts \":: going to test for collision against front node\"\n\t\t\t\t\t_start = body.pos + 0\n\t\t\t\t\t_stop = body.pos + body.linear_velocity\n\t\t\t\t\tif !@last_node.nil? and \n\t\t\t\t\t\t\t\t\tray_collide_node @last_node.back, _start, _stop, body.radius, body.linear_velocity\n\t\t\t\t\t\tputs \":: collision found!\"\n\t\t\t\t\t\tunless @collide_point and @collide_node\n\t\t\t\t\t\t\tputs \":: I collided with level but collide point and/or node is/are false\"\n\t\t\t\t\t\t\tnext false\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\tputs \":: no collision found\"\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\t@nodes << @collide_node\n\t\t\t\t@last_node = @collide_node\n\n=end\n# end experiment\n\n\t\t\t\t# send body/node/point back to caller so they can perform collision response\n\t\t\t\tyield body, @collide_node, @collide_point\n\t\t\n\t\t\t\t# if debugging enabled render node we collided with and it's normal\n\t\t\t\tif $options[:debug]\n\t\t\t\t\td = @collide_node.distance - body.radius\n#\t\t\t\t\tputs \"collided at point=#{@collide_point} distance=#{d} with:\"\n#\t\t\t\t\tputs \" node=#{@collide_node.index} normal=#{@collide_node.normal}\"\n\t\t\t\t\t$render.models << render_node(@collide_node,@collide_point) # planes with normal(0,0,-1) will not render?\n\t\t\t\t\tpos = @collide_point.dup; pos.x *= -1 # fix the position for rendering lines\n\t\t\t\t\t$render.models << Line.new({:lines => [[\n\t\t\t\t\t\tpos.to_a,\n\t\t\t\t\t\t(pos + (@collide_node.normal * 100)).to_a\n\t\t\t\t\t]]})\n\t\t\t\tend\n\n\t\t\tend\n\n\t\t\t# do one last ray check to validate response\n\t\t\tcollided = ray_collide_group body, @location[body] \n\t\t\tif collided\n#\t\t\t\tputs \"failed to contain #{body} in group #{@location[body]} (ray check)\" \n\t\t\t\texit\n\t\t\tend\n\n\t\t\t# do one last point check to validate response\n\t\t\tstop = body.pos + body.linear_velocity\n\t\t\t_in_same_group,_node1 = point_inside_group?( stop, @location[body], body.radius )\n\t\t\tunless _in_same_group\n#\t\t\t\tputs \"failed to contain #{body} in group #{@location[body]} (point check)\" \n\t\t\t\texit\n\t\t\tend\n\t\t\n\t\tend\n\tend", "def conflicting_blocks(daterange)\n validate(:daterange, daterange)\n return blocks.select { |block| block.conflict?(daterange) }\n end", "def each_collision(*klasses)\r\n # Make sure klasses is always an array.\r\n Array(klasses).each do |klass|\r\n \r\n if self.respond_to?(:instance_methods) && klass.respond_to?(:instance_methods)\r\n if self.instance_methods.include?(:radius) && klass.instance_methods.include?(:radius)\r\n self.each_bounding_circle_collision(klass) do |o1, o2|\r\n yield o1, o2\r\n end\r\n next\r\n end\r\n \r\n if self.instance_methods.include?(:bounding_box) && klass.instance_methods.include?(:bounding_box)\r\n self.each_bounding_box_collision(klass) do |o1, o2|\r\n yield o1, o2\r\n end\r\n next\r\n end\r\n end\r\n \r\n #\r\n # Possible optimization, look into later.\r\n #\r\n # type1 = self.instance_methods.include?(:bounding_box) ? :bb : :bc\r\n # type2 = klass.instance_methods.include?(:bounding_box) ? :bb : :bc\r\n # Pointless optmization-attempts?\r\n #if type1 != type2\r\n # self.all.each do |object1|\r\n # object2_list.each do |object2|\r\n # next if object1 == object2 # Don't collide objects with themselves\r\n # yield object1, object2 if object1.bounding_box_bounding_circle_collision?(object2)\r\n # end\r\n # end\r\n #end\r\n object2_list = (klass.respond_to?(:all) ? klass.all : Array(klass))\r\n self.all.each do |object1|\r\n object2_list.each do |object2|\r\n next if object1 == object2 # Don't collide objects with themselves\r\n yield object1, object2 if object1.collides?(object2)\r\n end\r\n end\r\n end\r\n end", "def each(&block)\r\n @range.each(&block)\r\n end", "def blocks_by_room(start_date, end_date, room)\n range = Hotel::DateRange.new(start_date, end_date)\n return @blocks.select do |block| # which blocks have an overlap with the range passed\n block.range.overlap?(range) && block.rooms.include?(room)\n end\n end", "def collisions\n from = @rc\n mask = @game_board.dup\n if from\n queen = mask.element(*from)\n mask.set_at(*from,1)\n end\n rc = from\n collision_count = 0\n collision_count += mask.row(rc[0]).count {|e| e.class == Queen}\n collision_count += mask.column(rc[1]).count {|e| e.class == Queen}\n\n mask.rows.each_with_index do |row,index|\n p_row = @rc[0]+index\n m_row = @rc[0]-index\n p_col = @rc[1]+index\n m_col = @rc[1]-index\n a,b,c,d = [m_row,m_col],[m_row,p_col],[p_row,m_col],[p_row,p_col]\n valid_range = 0...mask.column_size\n collision_count+=1 if valid_range.include?(m_row) && valid_range.include?(m_col) && mask[*a].class == Queen\n collision_count+=1 if valid_range.include?(m_row) && valid_range.include?(p_col) && mask[*b].class == Queen\n collision_count+=1 if valid_range.include?(p_row) && valid_range.include?(m_col) && mask[*c].class == Queen\n collision_count+=1 if valid_range.include?(p_row) && valid_range.include?(p_col) && mask[*d].class == Queen\n end\n mask.set_at(*from,queen) if from\n collision_count\n end", "def each( )\n @ranges.each do |range|\n range.each do |number|\n yield( number )\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all valid TimeBlock(s) for a given base time.
def valid_blocks(base_time) set_base_time(base_time) time_entries = time_entries_for(base) end
[ "def validate_time_blocks(time_blocks)\n b = time_blocks.select(&:collision_free?)\n\n # Test environment has unreliable data entry for start times.\n b = b.select(&:in_future?) unless Rails.env.test?\n\n b\n end", "def half_hour_blocks( time_start, time_end )\n # Parse time to make adding to it easier.\n time_start = parse_time( time_start )\n time_end = parse_time( time_end )\n raise \"End time before start time\" unless time_start < time_end\n blocks = []\n # Make a 2d array representing each half-hour segment.\n begin\n block = []\n block.push( time_start.strftime( '%l:%M' ).lstrip )\n time_start = time_start + HALF_HOUR\n block.push( time_start.strftime( '%l:%M' ).lstrip )\n blocks.push( block )\n end until time_start >= time_end\n blocks\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 convert_to_timeblocks timeslots\n slots = timeslots.order(:offset).group_by(&:day)\n Hash[slots.map { |i,slots| [i, slots.group_by { |slot| slot.offset / minutes_per_block }]}]\n end", "def valid_appointments(base_time)\n transform_blocks_to_appointments(valid_blocks(base_time))\n end", "def makeBlocks(days, startTimeString, endTimeString, info)\n\tblocks = []\n\tdays.split(\"\").each do |d|\n\t\tb = Block.new(d, startTimeString, endTimeString, info)\n\t\tblocks << b\n\tend\n\t(blocks)\nend", "def generate_time_slots(time_entries)\n time_entries.map { |entry| extract_available_slots(entry) }.flatten\n end", "def block_slots\n slots = []\n\n unless block_delivery_end_time.blank? || block_delivery_start_time.blank?\n\n available_hours = block_delivery_end_time - block_delivery_start_time\n\n number_of_slots = available_hours / 60.minutes\n\n number_of_slots.to_i.times do |i|\n slots << {\n from: block_delivery_start_time + i.hours,\n to: block_delivery_start_time + (i + 1).hours,\n type: :daytime\n }\n end\n end\n\n slots\n end", "def index\n @time_blocks = TimeBlock.all\n end", "def makeBlocks(days, startTimeString, endTimeString, info)\n\tblocks = []\n\tdays.split(\"\").each do |d|\n\t\tb = SCHBlock.new(d, startTimeString, endTimeString, info)\n\t\tblocks << b\n\tend\n\t(blocks)\nend", "def all_slots(interval=30.minutes, &block)\n return to_enum(:all_slots, interval) unless block_given?\n time = self.begin\n while time < self.end\n yield Slot.new(time)\n time += interval\n end\n end", "def available_on(base_time)\n # Stash this for future use, as we will be using it to set a\n # baseline date in order to derive a bunch of different appointments\n # from.\n set_base_time(base_time)\n\n # Fetch all TimeEntris related for this date query.\n time_entries = time_entries_for(base)\n\n # Transform TimeEntry(s) -> TimeSlot(s).\n available_slots = generate_time_slots(time_entries)\n\n # Combine all sequential linear slots to into a single window.\n # This produces multiple windows\n windows = combine_linear_slots(available_slots)\n\n # Generate TimeBlocks from the Available Slot ranges\n open_time_blocks = generate_time_blocks(windows)\n\n # Optimize & Filter our wide collection of TimeBlocks.\n optimized_blocks = optimize_time_blocks(open_time_blocks)\n\n # Finally, present the TimeBlock(s) as Appointment records\n # to the Customer.\n final = transform_blocks_to_appointments(optimized_blocks)\n end", "def timeslots\n unless @timeslots.present?\n timeslots = Timeslot\n .timeslots_for(@schedule_range, @form)\n .select { |ts| ts.blocks >= @blocks_needed }\n timeslots = @schedule_range.all_timeslots if timeslots.empty?\n @timeslots = timeslots.sort_by { |ts| [ts.day_id, ts.start_minute] }\n end\n\n @timeslots\n end", "def split_times(start_time, end_time)\n start_int = start_time.gsub(/30$/,\"50\").to_i\n end_int = end_time[0,4].gsub(/30$/,\"50\").to_i \n end_period = end_time[-2] + end_time[-1]\n time_frame = []\n if end_period == \"PM\"\n if end_int != 1200 and end_int != 1250\n end_int += 1200\n end\n if start_int < 800\n start_int += 1200\n end\n end\n while (start_int < end_int)\n time_frame.push(start_int.to_s.gsub(/50$/,\"30\").to_i)\n start_int += 50\n end \n return time_frame\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 time_slots # does not take availability into account\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 time_slots # does not take availability into account\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 starttime = Time.zone.now + 10.minutes\n # Then we have to round to the next hour block\n starttime = Time.zone.at( (starttime.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 starttime = [starttime, starttime.change(hour: opening_hour)].max\n\n # Determine the furthest in the future we will allow reservations\n end_time = (starttime + 3.days).change(hour: closing_hour)\n\n # Now, we want to make a list of every hour between our starttime 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 = starttime\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 find_block_info blockinfo\n expiry = blockinfo.first['expiry']\n if (expiry == \"infinity\")\n \t expiry = nil\n else\n expiry = Time.parse(expiry)\n end\n [blockinfo.first['id'].to_i, blockinfo.first['by'].to_s, Time.parse(blockinfo.first['timestamp']), expiry, blockinfo.first['reason'].to_s]\n end", "def get_free_times(appointment_length)\n free_times = []\n BEGINNING_OF_DAY.upto(END_OF_DAY) do |current_time_slot|\n current_time_slot\n free = self.is_free_time_slot(current_time_slot, appointment_length)\n if free\n presentable_time = convert_to_presentable_time(current_time_slot)\n free_times.push(presentable_time)\n end\n end\n return free_times\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all valid Appointments for a given base time.
def valid_appointments(base_time) transform_blocks_to_appointments(valid_blocks(base_time)) end
[ "def appointments_with_times_only_for_public_scheduler\n self.appointments.map{ |appt| {id: appt.id, start_time: appt.start_time, status: appt.status}}\n end", "def available_on(base_time)\n # Stash this for future use, as we will be using it to set a\n # baseline date in order to derive a bunch of different appointments\n # from.\n set_base_time(base_time)\n\n # Fetch all TimeEntris related for this date query.\n time_entries = time_entries_for(base)\n\n # Transform TimeEntry(s) -> TimeSlot(s).\n available_slots = generate_time_slots(time_entries)\n\n # Combine all sequential linear slots to into a single window.\n # This produces multiple windows\n windows = combine_linear_slots(available_slots)\n\n # Generate TimeBlocks from the Available Slot ranges\n open_time_blocks = generate_time_blocks(windows)\n\n # Optimize & Filter our wide collection of TimeBlocks.\n optimized_blocks = optimize_time_blocks(open_time_blocks)\n\n # Finally, present the TimeBlock(s) as Appointment records\n # to the Customer.\n final = transform_blocks_to_appointments(optimized_blocks)\n end", "def appointments\n @date = Date.today\n @start_date = @date.beginning_of_week(:sunday).to_date\n @end_date = @date.end_of_week(:sunday).to_date\n @rooms = Room.all\n @counselors = Counselor.all\n @cases = Case.all\n @counselor_room = CounselorAvailability.new\n @counselor_availabilities = CounselorAvailability.where(\"start_at BETWEEN '#{@start_date} 00:01:01' and '#{@end_date} 23:59:59'\")\n @common_appointments = Array.new\n @main_appoints = Array.new\n @counselor_availabilities.each do |a|\n @common_appointments << a.start_at.strftime(\"%Y-%m-%d %H:%M:%S\")+a.room_id.to_s\n @main_appoints << a\n end\n end", "def available_appointments(location)\n upcoming_appointments.all(location: location, arrival_date: Date.today)\n end", "def registration_appointments\n\t\tpage = get :registration_appointments\n\t\tappointments = []\n\t\tpage.search('table.DataGrid tr.clsDataGridData').each do |tr|\n\t\t\tstart_time = Time.parse tr.children[0].text\n\t\t\tend_time = Time.parse tr.children[1].text\n\t\t\tappointments << {\n\t\t\t\t:start => start_time,\n\t\t\t\t:end => end_time\n\t\t\t}\n\t\tend\n\t\tappointments\n\tend", "def get_appointments\n @get_appointments ||= appointment_service.get_appointments(three_months_ago, one_year_from_now)\n end", "def fetch_appointments(t_d)\r\n state.appointments.where do |a|\r\n next if a == nil\r\n a.attributes[:start_date].include? \"#{t_d}\"\r\n end\r\n end", "def open_appointment_times(date)\n appointments = self.appointments.given_date(date).confirmed\n increment = self.clinic.appointment_time_increment\n stop_time = 60 - increment\n times = []\n (9..16).each do |h|\n (0..stop_time).step(increment) do |m|\n ampm = ''\n if h < 12\n ampm = 'AM'\n else\n ampm = 'PM'\n end\n\n hr = ''\n if h != 12\n hr = h % 12\n else\n hr = h\n end\n min = ''\n if m == 0\n min = '00'\n else\n min = m\n end\n\n times.append(\"#{hr}:#{min} #{ampm}\")\n end\n end\n appointments.find_each do |appt|\n hour = appt.appointment_time_hour_24\n minute = appt.appointment_time_minute\n minute = '00' if minute == 0\n\n ampm = ''\n if hour < 12\n ampm = 'AM'\n else\n ampm = 'PM'\n end\n hour = hour % 12 if hour != 12\n if times.include?(\"#{hour}:#{minute} #{ampm}\")\n times.delete(\"#{hour}:#{minute} #{ampm}\")\n end\n end\n times\n end", "def appointments(officer_id)\n client.get(\"officers/#{officer_id}/appointments/\")\n end", "def appointment_time\n rec = self\n cond = {:start_time => self.start_time, \n :end_time => self.end_time,\n :id => self.id\n }\n if self.start_time > self.end_time\n errors.add(:appointment_invalid, \"start time must be before end time\")\n else\n # check for appointment overlap with other appointments\n cond_str = '(start_time >= :start_time and start_time <= :end_time) or ' +\n '(start_time <= :start_time and end_time >= :start_time) or ' +\n '(start_time <= :start_time and end_time >= :start_time)'\n cond_str = \"id <> :id and (#{cond_str})\" if self.id \n \n overlap_recs = self.class.where(\n [cond_str, cond]) \n if overlap_recs.size > 0 \n errors.add(:appointment_overlap, \"can not schedule\")\n end\n end \n end", "def get_today_appointments(appointments, exception_appointments, today_date,parameter)\n tday = []\n tday_appointments = appointments.reject{|appt| appt[:activity_start_date].to_date > today_date}\n tday_appointments.each do |appointment|\n is_exception = false\n if (appointment[:activity_start_date].to_date == today_date) or (appointment[:activity_start_date_array].include?(today_date))\n unless appointment[:activity_repeat]\n unless is_exception\n appointment[:activity_is_instance] = false\n appointment[:activity_instance_start_date] = appointment[:activity_start_date].to_date\n appointment[:activity_instance_start_date_with_time] = appointment[:activity_start_date]\n appointment[:activity_instance_end_date] = appointment[:activity_end_date].to_date\n appointment[:activity_instance_end_date_with_time] = appointment[:activity_end_date]\n end\n else\n unless appointment[:activity_start_date_array].blank?\n idx = appointment[:activity_start_date_array].index{|start_date| start_date == today_date}\n # Find exception dates for all appointments that have task_id equal to parent activity's id \n # and exception start date = start_date_array[idx]\n # It is important to convert the exception_start_date to date format (from datetime)\n exception_appt_dates = exception_appointments.collect{|appt| appt[:activity].exception_start_date.to_date if ((appt[:activity].task_id == appointment[:activity_id]) and (appt[:activity].exception_start_date.to_date == appointment[:activity_start_date_array][idx])) }\n is_exception = exception_appt_dates.include?(appointment[:activity_start_date_array][idx])\n unless is_exception\n #create an instance\n appointment[:activity_is_instance] = true\n appointment[:activity_instance_start_date] = appointment[:activity_start_date_array][idx]\n appointment[:activity_instance_start_date_with_time] = \"#{appointment[:activity_instance_start_date]} #{appointment[:activity_start_date].strftime(\"%H:%M:%S\")}\"\n appointment[:activity_instance_end_date] = appointment[:activity_end_date_array][idx]\n appointment[:activity_instance_end_date_with_time] = \"#{appointment[:activity_instance_end_date]} #{appointment[:activity_end_date].strftime(\"%H:%M:%S\")}\"\n end\n end\n end\n unless appointment.blank?\n if appointment[:activity_instance_start_date]==Time.zone.now.to_date\n tday << appointment\n end\n end\n end\n end\n tday = tday.flatten\n\n tday\n end", "def appointments\n Appointment.all.filter { |appointment| appointment.provider_id == self.id || appointment.user_id == self.id}\n end", "def bookings_for(date)\n appointments_for_date = appointments.all.map do |appointment|\n time = appointment.start_date.strftime('%H:%M')\n in_timezone(time).strftime('%H:%M') if \\\n appointment.start_date.strftime('%d/%m/%Y') == date\n end\n appointments_for_date\n end", "def get_appts\n @user = current_user\n @appointments = @user.appointments.actual.includes(:status, :address, :assignments, {:subscription => :subscriptionable}, :employees, :team)\n # filter by the datetime object via params from fullcalendar\n filter_show = ActiveSupport::JSON.decode(params[:filter_show])\n appointments_in_range = @appointments.where(\"appointments.start_time >= :start_time AND appointments.start_time <= :end_time\", {:start_time => Time.at(params['start'].to_i), :end_time => Time.at(params['end'].to_i)} )\n events = []\n appointments_in_range.each do |appointment|\n if appointment_is_allowed?(appointment, filter_show)\n customer = appointment.subscription.subscriptionable\n eventHash = {:id => appointment.id, :title => calendar_title(appointment, customer), :start => \"#{appointment.start_time.iso8601}\", :end => \"#{appointment.end_time.iso8601}\", :allDay => false, :recurring => appointment.subscription.repeat }\n\n eventHash[:backgroundColor] = event_background_color(appointment, params[:event_color])\n eventHash[:borderColor] = eventHash[:backgroundColor]\n\n events << eventHash\n # optional day view\n #events << {:id => event.id, :title => @customer_name, :url => \"/appointments/\"+event.id.to_s+\"/edit\", :description => \"Description here\", :start => \"#{event.start_time.iso8601}\", :end => \"#{event.end_time.iso8601}\", :allDay => true}\n end\n end\n render :json => events\n end", "def appointments=(value)\n @appointments = value\n end", "def appointments\n return @appointments\n end", "def get_free_times(appointment_length)\n free_times = []\n BEGINNING_OF_DAY.upto(END_OF_DAY) do |current_time_slot|\n current_time_slot\n free = self.is_free_time_slot(current_time_slot, appointment_length)\n if free\n presentable_time = convert_to_presentable_time(current_time_slot)\n free_times.push(presentable_time)\n end\n end\n return free_times\n end", "def my_appointments(user)\n Appointment.where(user_id: user.id)\n end", "def index\n @assistent_appointments = AssistentAppointment.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all TimeEntry(s) that match the current session properties. +:target_date+ A DateTime to base the TimeEntry collection query from.
def time_entries_for(target_date) target_day = Skej::NLP.parse(session, target_date.to_s) .strftime('%A') .downcase .to_sym TimeEntry.where(build_query_params).with_day(target_day).map do |entry| entry.session = session and entry end end
[ "def time_entries\n get_ticket_property_list(\"time_entries\" , Unfuddled::TimeEntry)\n end", "def entries\n settings.time_entries.present? ? settings.time_entries : []\n end", "def time_entries(range_start = nil, range_end = nil)\n options = {}\n\n options = {\"range_start\" =>\n range_start.strftime(DATE_FORMAT)} if range_start\n options = {\"range_end\" =>\n range_end.strftime(DATE_FORMAT)} if range_end\n\n # do the actual request\n get_request(\"/users/#{@user_id}/time_entries\", options)\n end", "def list_timeentries(range_start=nil, range_end=nil)\n if range_start.is_a?(Date)\n range_start = range_start.strftime(\"%Y-%m-%dT00:00:00Z\")\n else\n range_start = range_start.strftime(\"%Y-%m-%dT%H:%M:%SZ\") unless range_start.nil?\n end\n if range_end.is_a?(Date)\n range_end = range_end.strftime(\"%Y-%m-%dT23:59:59Z\")\n else\n range_end = range_end.strftime(\"%Y-%m-%dT%H:%M:%SZ\") unless range_end.nil?\n end\n request(\"get\", \"#{@user_id}/time_entries?api_key=#{@api_key}&access_token=#{@access_token}&range_start=#{range_start}&range_end=#{range_end}\", \"TimeEntries\")\n end", "def fetch_time_entries\n self.time_entries = { }\n fetch_time_entries_by_project\n end", "def time_entries\n @_time_entries ||= Users::TimeEntries.new(@_client)\n end", "def time_entries(options = {})\n entries = []\n time_invested(options).groups.each { |g| entries << g[\"time_entries\"] }\n\n process_list_response( entries.flatten , Unfuddled::TimeEntry )\n end", "def time_entries(start_date, end_date)\n opts = {\n params: {\n start_date: start_date.to_datetime.iso8601,\n end_date: end_date.to_datetime.iso8601\n }\n }\n\n begin\n response = toggl_resource['time_entries'].get(opts)\n rescue => e\n raise 'Error getting Toggl data: ' + e.response\n end\n data = JSON.parse response\n\n data.map do |entry|\n duration = entry['duration'].to_f\n\n # Negative duration means the task is currently running.\n # In this case, we'll set duration to how long it's been running\n if duration < 0\n duration = Time.now - Time.at(duration.abs)\n end\n\n {\n description: entry['description'],\n start: Date.parse(entry['start']),\n duration: duration\n }\n end\n end", "def time_entries\n @_time_entries ||= Projects::TimeEntries.new(@_client)\n end", "def all_matchday_times\n all_matches = fetch_matches\n matchtimes = Hash[(1..38).collect { |md| [md, []] }]\n all_matches.each do |m|\n matchtimes[m['matchday']].push(m['utcDate'])\n end\n matchtimes\n end", "def index\n @session_times = SessionTime.all\n end", "def get_time( query, source )\n @times[ query ][ source ]\n end", "def index\n @target_times = TargetTime.all.order(\"player_count, difficulty_id\")\n end", "def sessions_in_range (from, to) \n sessions = self.sessions.where(\"start_time < ? AND exit_time > ?\", to, from)\n end", "def time_entry_scope\n scope = TimeEntry.visible.where(@query.statement)\n if @issue\n scope = scope.on_issue(@issue)\n elsif @project\n scope = scope.on_project(@project, Setting.display_subprojects_issues?)\n end\n scope\n end", "def entries\n \n return self.timesheet_entries\n \n end", "def time_entry_scope(options={})\n @query.results_scope(options)\n end", "def timers_list\n @timers_list\n end", "def target_schedule\n return @target_schedule\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Produces TimeSlot(s) from a collection of TimeEntries
def generate_time_slots(time_entries) time_entries.map { |entry| extract_available_slots(entry) }.flatten end
[ "def time_entries(options = {})\n entries = []\n time_invested(options).groups.each { |g| entries << g[\"time_entries\"] }\n\n process_list_response( entries.flatten , Unfuddled::TimeEntry )\n end", "def days_from_timeslot_matches(timeslots_container, day_with_hours)\n result = []\n\n day_with_hours.each_with_index do |day_with_hour, i|\n result.push(day_with_hour)\n _, day, _, _ = day_with_hour #\n next if day.nil?\n\n timeslot_matches = timeslots_container[i]\n next if (timeslot_matches.size == 0)\n\n timeslot_matches.each do |timeslot_match|\n start_hour, start_min, end_hour, end_min = get_hour_from_timeslot_match(timeslot_match)\n\n start_t = create_datetime_if_exists(day.year, day.month, day.day, start_hour, start_min)\n end_t = create_datetime_if_exists(day.year, day.month, day.day, end_hour, end_min)\n\n result.push([timeslot_match, day, start_t, end_t])\n end\n end\n\n result\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 compile_and_return_time_slots(start, finish)\n slots = []\n total = num_slots(start, finish)\n 1.upto(total) do\n slots << start.to_formatted_string\n start += (DURATION_IN_MINUTES * 60)\n end\n slots\n end", "def time_slots # does not take availability into account\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 starttime = Time.zone.now + 10.minutes\n # Then we have to round to the next hour block\n starttime = Time.zone.at( (starttime.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 starttime = [starttime, starttime.change(hour: opening_hour)].max\n\n # Determine the furthest in the future we will allow reservations\n end_time = (starttime + 3.days).change(hour: closing_hour)\n\n # Now, we want to make a list of every hour between our starttime 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 = starttime\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 get_times\n work_time = [@starts.h, @ends.round_up]\n meeting_times = []\n @meetings.each do |meeting|\n meeting_time = Array.new(2)\n meeting_time[0] = hour_offset(@starts.h, meeting.starts.h) + \n minute_offset(meeting.starts.m)\n meeting_time[1] = hour_offset(@starts.h, meeting.ends.h) + \n minute_offset(meeting.ends.m)\n meeting_times << meeting_time\n end if @meetings\n \n times = [work_time, meeting_times]\n end", "def time_slots # does not take availability into account\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 time_entries\n get_ticket_property_list(\"time_entries\" , Unfuddled::TimeEntry)\n end", "def timeslots\n\t\tif (self != nil)\n\t\t\tcompany = self.company\n\t\t\tstart_time = company.start_time\n\t\t\tend_time = company.end_time\n\t\t\tcompany_duration = (( end_time - start_time )/60).round(2)\n\t\t\tno_of_slots = ( company_duration / (self.time_slot.hour*60 + self.time_slot.min) ).to_i\n\t\t\ttime_slot_array =Array.new\n\t\t\tremember_hour = start_time.hour.round\n\t\t\tremember_min = start_time.min\n\t\t\tno_of_slots.times do | index |\n\t\t\t\ta = remember_hour == 0 ? \"00\" : remember_hour\n\t\t\t\tb = remember_min == 0 ? \"00\" : remember_min\n\t\t\t\tc = ((remember_min + self.time_slot.min)/60 )+remember_hour+self.time_slot.hour == 0 ? \"00\" :((remember_min + self.time_slot.min)/60 )+remember_hour+self.time_slot.hour\n\t\t\t\td = (remember_min + self.time_slot.min) % 60 == 0 ? \"00\" : (remember_min + self.time_slot.min) % 60\n\t\t\t\ttime_slot_array << [\"#{a}:#{b}-#{c}:#{d}\", index]\n\t\t\t\tremember_hour = ((remember_min + self.time_slot.min)/60 )+remember_hour+self.time_slot.hour\n\t\t\t\tremember_min = (remember_min + self.time_slot.min) % 60\n\t\t\tend\n\t\t\ttime_slot_array\n\t\tend\n\tend", "def time_entries(start_date, end_date)\n opts = {\n params: {\n start_date: start_date.to_datetime.iso8601,\n end_date: end_date.to_datetime.iso8601\n }\n }\n\n begin\n response = toggl_resource['time_entries'].get(opts)\n rescue => e\n raise 'Error getting Toggl data: ' + e.response\n end\n data = JSON.parse response\n\n data.map do |entry|\n duration = entry['duration'].to_f\n\n # Negative duration means the task is currently running.\n # In this case, we'll set duration to how long it's been running\n if duration < 0\n duration = Time.now - Time.at(duration.abs)\n end\n\n {\n description: entry['description'],\n start: Date.parse(entry['start']),\n duration: duration\n }\n end\n end", "def get_times_array(padding = true)\n @times = (padding) ? [@start_dt - 1.hour] : [@start_dt]\n \n # and including every 1/2 hour until one hour after the selected end time\n while true do\n tmp = @times.last + 30.minutes\n (padding) ? (tmp == (@end_dt + 1.hour)) ? break : '' : (tmp == @end_dt) ? break : ''\n @times.push(tmp)\n end\n end", "def create_slots\n date = @start_date\n @slots = []\n while date < @end_date\n @slots << @tutor.slots.create(start_time: @start_time, duration: @duration, slot_type: @slot_type)\n date = date + 7\n @start_time = @start_time + 7\n end\n return @slots\n end", "def create_time_slots\n if !(self.starts_at < self.ends_at)\n raise 'Error, ends at should be greater that starts at' #TODO: move to a class validation\n end\n hour = self.starts_at\n end_time = self.ends_at\n\n while hour < end_time\n puts hour\n TimeSlot.create!(:starts_at=> hour, :ends_at => hour + 1.hour, :event => self )\n hour += 1.hour\n end\n\n return true\n\n end", "def from_meeting_rooms!(meeting_rooms)\n @time_slots = []\n meeting_rooms.each do |meeting_room|\n meeting_room.time_slots.each do |time_slot|\n if time_slot.is_a? TimeSlot\n @time_slots << time_slot.duration_in_minutes\n end\n end\n end\n self\n end", "def get_times_array(padding = true)\n times = (padding) ? [start_dt - 1.hour] : [start_dt]\n\n # and including every 1/2 hour until one hour after the selected end time\n loop do\n tmp = times.last + 30.minutes\n (padding) ? (tmp == (end_dt + 1.hour)) ? break : '' : (tmp == end_dt) ? break : ''\n times.push(tmp)\n end\n return times\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 index\n @line_day_time_slots = LineDay::TimeSlot.all\n end", "def datetime_ranges\n return [] if days.empty? || time_range[:start] == 0\n ranges = []\n days.each do |day|\n ranges << (day.to_time + time_range[:start]..\n day.to_time + time_range[:end])\n end\n ranges\n end", "def convert_time_slots\n time_slots\n .chars.each_slice(2)\n .map { |data| data.join('').unpack1('S') }\n .map.with_index do |data, index|\n 16.times\n .select { |i| (data & (1 << i)).positive? }\n .map { |i| self.class.time_slot_codes.key(i) }\n .reduce((index + 1).to_s, :+)\n end\n .select { |r| r.length > 1 }\n .join\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Responsible combining a collection of slots into common groups, defined by touching boundaries. +:slots: Array / Collection of TimeSlot(s)
def combine_linear_slots(slots) last_slot = false end_time = false start_time = false flushed = false # Tracks the current continuity chain count = 0 aggregate = [] debug = [] slots.sort_by(&:start_time).each_with_index do |slot, i| # Very close to each other, mark it as a continuation # to the end_time. start_time = slot.start_time unless last_slot end_time = slot.end_time unless last_slot if slot.start_time < (end_time + 30.seconds) debug << "slot:#{slot.start_time} - neighbor detected" end_time = slot.end_time elsif last_slot debug << "slot:#{slot.start_time} - gap detected" aggregate << TimeSlot.new(start_time, end_time, slot.time_entry) start_time = slot.start_time end_time = slot.end_time end last_slot = slot end aggregate << TimeSlot.new(start_time, end_time, last_slot.time_entry) if last_slot aggregate.uniq end
[ "def unavailable_slots(sport, start_time, end_time, free_for_coach_id = nil)\n free_for_coach_id = free_for_coach_id.to_i\n sport_courts = if sport.present?\n courts.for_sport(sport)\n elsif free_for_coach_id > 0\n courts.for_sport(Coach.find(free_for_coach_id).sports)\n else\n courts\n end\n sport_court_ids = sport_courts.pluck(:id).sort\n\n taken_timeslots = reservations.where(court_id: sport_court_ids).\n overlapping(start_time, end_time).\n select(:start_time, :end_time, :court_id, :coach_id)\n\n unavailable_slots = []\n\n # bruteforce here, check each of 15 minutes part of datetimes range\n while end_time > start_time do\n ends = start_time + 15.minutes\n taken_courts = taken_timeslots.map do |timeslot|\n reservation_belongs_to_coach = free_for_coach_id > 0 && timeslot.coach_id == free_for_coach_id\n if timeslot.overlapping?(start_time, ends) && !reservation_belongs_to_coach\n timeslot.court_id\n end\n end.compact.uniq.sort\n\n unavailable_slots << { start: start_time, end: ends } if taken_courts == sport_court_ids\n\n start_time += 15.minutes\n end\n\n # combine slots\n unavailable_slots.\n chunk_while { |prv, nxt| prv[:end] == nxt[:start] }.\n flat_map { |chunk| { start: chunk.first[:start], end: chunk.last[:end] } }\n end", "def group_slots(start_time, end_time, duration)\n\n raise ArgumentError if !(start_time and end_time and duration)\n raise ArgumentError, \"end_time occurs before than start_time\" if start_time > end_time\n raise ArgumentError, \"duration is lower than or equal to zero\" if duration <= 0\n\n from = start_time.to_i\n to = (end_time - duration).to_i\n\n (from..to).step(30.minutes).map do |timestamp|\n start_time + (timestamp - start_time.to_i).seconds\n end\n end", "def build_available_slots(non_recurring_slots, recurring_slots, blocked_slots)\n availability = []\n loop do\n week_day = @date.wday\n availability << {\n date: @date.to_date,\n slots: non_recurring_slots[week_day] + recurring_slots[week_day] - blocked_slots[week_day]\n }\n break if (@date += 1.day) > @end_date\n end\n availability\n end", "def timeslots\n\t\tif (self != nil)\n\t\t\tcompany = self.company\n\t\t\tstart_time = company.start_time\n\t\t\tend_time = company.end_time\n\t\t\tcompany_duration = (( end_time - start_time )/60).round(2)\n\t\t\tno_of_slots = ( company_duration / (self.time_slot.hour*60 + self.time_slot.min) ).to_i\n\t\t\ttime_slot_array =Array.new\n\t\t\tremember_hour = start_time.hour.round\n\t\t\tremember_min = start_time.min\n\t\t\tno_of_slots.times do | index |\n\t\t\t\ta = remember_hour == 0 ? \"00\" : remember_hour\n\t\t\t\tb = remember_min == 0 ? \"00\" : remember_min\n\t\t\t\tc = ((remember_min + self.time_slot.min)/60 )+remember_hour+self.time_slot.hour == 0 ? \"00\" :((remember_min + self.time_slot.min)/60 )+remember_hour+self.time_slot.hour\n\t\t\t\td = (remember_min + self.time_slot.min) % 60 == 0 ? \"00\" : (remember_min + self.time_slot.min) % 60\n\t\t\t\ttime_slot_array << [\"#{a}:#{b}-#{c}:#{d}\", index]\n\t\t\t\tremember_hour = ((remember_min + self.time_slot.min)/60 )+remember_hour+self.time_slot.hour\n\t\t\t\tremember_min = (remember_min + self.time_slot.min) % 60\n\t\t\tend\n\t\t\ttime_slot_array\n\t\tend\n\tend", "def convert_to_timeblocks timeslots\n slots = timeslots.order(:offset).group_by(&:day)\n Hash[slots.map { |i,slots| [i, slots.group_by { |slot| slot.offset / minutes_per_block }]}]\n end", "def add_to_list(new_r)\n # Other Cases\n # For each INTERVAL in LIST, update items if necessary\n # 5 cases between two INTERVALs interactions\n # Case 1. A fully cover B\n # Case 2. B partically overlap A (end_item of B is between A)\n # Case 3. A partially overlap B (end_item of A is between B)\n # Case 4. B fully cover A \n # Case 5. A, B are mutually exclusive --> do nothing \n i = 0\n while @list[i]\n # Case 1\n if (new_r.start <= @list[i].start && new_r.endt >= @list[i].endt)\n @list[i].items = combine_items(new_r.items, @list[i].items, true)\n # Case 2\n elsif (new_r.endt > @list[i].start && new_r.endt < @list[i].endt)\n items_list = combine_items(new_r.items, @list[i].items, false)\n time_slot = Interval.new(@list[i].start, new_r.endt, items_list)\n @list[i].start = new_r.endt\n @list.insert(i, time_slot)\n i += 1\n # Case 3\n elsif (new_r.start > @list[i].start && new_r.start < @list[i].endt)\n items_list = combine_items(new_r.items, @list[i].items, false)\n time_slot = Interval.new(new_r.start, @list[i].endt, items_list)\n @list[i].endt = new_r.start\n @list.insert(i + 1, time_slot)\n i += 1\n # Case 4\n elsif (new_r.start > @list[i].start && new_r.endt < @list[i].endt)\n time_slot = Interval.new(new_r.endt, @list[i].endt, list[i].items)\n @list[i].endt = new_r.start\n items_list = combine_items(new_r.items, @list[i].items, false)\n @list.insert(i+1, Interval.new(new_r.start, new_r.endt, items_list))\n @list.insert(i+1, time_slot)\n i += 2\n end\n i += 1\n end\n \n # Edge Case\n # Check begin/end of LIST as new RIDE could be out of LIST boundary\n if (new_r.start < @list[0].start)\n @list.insert(0, Interval.new(new_r.start, @list[0].start, new_r.items))\n end\n if (new_r.endt > @list[@list.length-1].endt) \n @list.insert(@list.length, Interval.new(@list[@list.length-1].endt, new_r.endt, new_r.items))\n end\n @list\n end", "def update_slots\n @slots = get_slots_for_range\n @slots.each do |slot|\n slot.start_time = slot.start_time + @start_adjustment.seconds\n slot.duration = @new_duration\n slot.save\n end\n return @slots\n end", "def add_if_can!(ti)\n \n intervals = self.capacity_intervals.overlapping(ti).order('start_time')\n \n does_not_fit = false\n intervals.each do |i|\n does_not_fit = does_not_fit || (i.capacity-ti.capacity < 0)\n end\n \n toAdd = []\n if(intervals.size == 0)\n return false\n elsif(ti.start_time < intervals.first.start_time or ti.end_time > intervals.last.end_time) \n return false\n elsif(does_not_fit)\n return false\n elsif(intervals.size == 1) #both in one interval \n if(intervals[0].start_time != ti.start_time)\n toAdd << capacity_intervals.new({:capacity=>intervals[0].capacity, :start_time=>intervals[0].start_time, :end_time=>ti.start_time})\n end\n \n toAdd << capacity_intervals.new({:capacity=>intervals[0].capacity-ti.capacity, :start_time=>ti.start_time, :end_time=>ti.end_time})\n \n if(intervals[0].end_time != ti.end_time)\n toAdd << capacity_intervals.new({:capacity=>intervals[0].capacity, :start_time=>ti.end_time, :end_time=>intervals[0].end_time})\n end\n \n else #both in their own interval\n #Left and Right\n if(intervals.first.start_time != ti.start_time)\n toAdd << capacity_intervals.new({:capacity=>intervals.first.capacity, :start_time=>intervals.first.start_time, :end_time=>ti.start_time})\n end\n toAdd << capacity_intervals.new({:capacity=>intervals.first.capacity-ti.capacity, :start_time=>ti.start_time, :end_time=>intervals.first.end_time})\n toAdd << capacity_intervals.new({:capacity=>intervals.first.capacity-ti.capacity, :start_time=>intervals.last.start_time, :end_time=>ti.end_time})\n if(intervals.last.end_time != ti.end_time)\n toAdd << capacity_intervals.new({:capacity=>intervals.last.capacity, :start_time=>ti.end_time, :end_time=>intervals.last.end_time})\n end\n \n #Middle\n if (intervals.size > 2)\n intervals[1..-2].each{|i| toAdd << capacity_intervals.new({:capacity=>i.capacity - ti.capacity, :start_time=>i.start_time, :end_time=>i.end_time})}\n end\n \n end\n \n intervals.each do |i|\n i.delete\n end\n toAdd.each do |i|\n i.save!\n end\n \n return true\n end", "def merge_ranges(meetings)\n # sort by start times \n sorted_meetings = meetings.sort \n\n #initialize merged_meetings w/earliest meeting \n merged_meetings = [sorted_meetings[0]]\n\n sorted_meetings[1..-1].each do |current_meeting_start, current_meeting_end|\n last_merged_meeting_start, last_merged_meeting_end = merged_meetings[-1]\n\n # if current and last mtgs overlap, use latest end time\n if current_meeting_start <=last_merged_meeting_end \n merged_meetings[-1] = [last_merged_meeting_start, [last_merged_meeting_end, current_meeting_end].max]\n # add current mtg since it doesn't overlap\n else\n merged_meetings.push([current_meeting_start, current_meeting_end])\n end\n end\n merged_meetings\nend", "def create_time_slots\n if !(self.starts_at < self.ends_at)\n raise 'Error, ends at should be greater that starts at' #TODO: move to a class validation\n end\n hour = self.starts_at\n end_time = self.ends_at\n\n while hour < end_time\n puts hour\n TimeSlot.create!(:starts_at=> hour, :ends_at => hour + 1.hour, :event => self )\n hour += 1.hour\n end\n\n return true\n\n end", "def block_slots\n slots = []\n\n unless block_delivery_end_time.blank? || block_delivery_start_time.blank?\n\n available_hours = block_delivery_end_time - block_delivery_start_time\n\n number_of_slots = available_hours / 60.minutes\n\n number_of_slots.to_i.times do |i|\n slots << {\n from: block_delivery_start_time + i.hours,\n to: block_delivery_start_time + (i + 1).hours,\n type: :daytime\n }\n end\n end\n\n slots\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 build_slots(current_time, finish_time, start_hour, finish_hour)\n while current_time < finish_time\n slots_quantity = get_slots_quantity(start_hour, finish_hour)\n\n (1..slots_quantity).each do\n verterx = @elements_factory.create_vertex(current_time, current_time.class,\n {gained_weight: 0, duration: @slots_size})\n @slots << verterx\n\n current_time += @slots_size\n break if current_time >= finish_time\n end\n\n current_time = current_time.beginning_of_day + start_hour.seconds_since_midnight.seconds + 1.day if start_hour.seconds_since_midnight > finish_hour.seconds_since_midnight\n end\n end", "def create_slots\n date = @start_date\n @slots = []\n while date < @end_date\n @slots << @tutor.slots.create(start_time: @start_time, duration: @duration, slot_type: @slot_type)\n date = date + 7\n @start_time = @start_time + 7\n end\n return @slots\n end", "def condense_blocks\n @rooms.each do |room_id, room|\n blocks = []\n start_time = room[:bookings][0]\n bookings_in_block = 1\n\n room[:bookings][1..-1].each.with_index(1) do |booking, index|\n if booking != start_time + 30 * 60 * bookings_in_block then\n end_time = room[:bookings][index - 1] + 30 * 60\n\n blocks << {\n :start => start_time.utc.iso8601,\n :end => end_time.utc.iso8601,\n :duration => (end_time - start_time) / 60\n }\n\n start_time = booking\n bookings_in_block = 1\n else\n bookings_in_block += 1\n end\n end\n\n end_time = room[:bookings][-1] + 30 * 60\n\n blocks << {\n :start => start_time.utc.iso8601,\n :end => end_time.utc.iso8601,\n :duration => (end_time - start_time) / 60\n }\n\n room[:bookings] = blocks\n end\nend", "def update_timeslots\n room_bookings = Booking.where(room_id: params[:id]) #Booking.where(room_id: params[:id], start_date: params[:start_date])\n next_day = (params[:start_date].to_datetime + 1.day).to_date\n bookings = room_bookings.where('start_date = ? OR start_date =?', params[:start_date], next_day)\n \n @timeslots = Room.timeslots_for(params[:start_date], @room.book_start, @room.book_end) #Room.timeslots_for(params[:start_date])\n @timeslot_select = Room.timeslot_select(params[:start_date], @room.book_start, @room.book_end) #Room.timeslot_select(params[:start_date])\n\n @result = []\n\n @timeslots.each do |ts|\n if (ts + params[:duration].to_i.hour) < params[:start_date].to_datetime.end_of_day\n bookings.each do |booking|\n if ts.between?(booking.check_in - params[:duration].to_i.hour, booking.check_out) || ts.between?(booking.check_in, booking.check_out)\n @result << ts\n end\n end\n else\n bookings.each do |booking|\n if (ts + params[:duration].to_i.hour).between?(booking.check_in - params[:duration].to_i.hour, booking.check_out) || ts.between?(booking.check_in, booking.check_out)\n @result << ts\n end\n end\n end\n end\n @result\n end", "def overlapping_slot_indices(time_slots_1, time_slots_2)\n indices = []\n\n current_idx = 0\n time_slots_1.each_with_index do |slot, slot_idx|\n while current_idx < time_slots_2.size && slot.first >= time_slots_2[current_idx].last\n current_idx+=1\n end\n break if current_idx == time_slots_2.size\n\n no_overlap = (time_slots_2[current_idx].first >= slot.last || time_slots_2[current_idx].last <= slot.first)\n indices << slot_idx unless no_overlap\n end\n indices\n end", "def time_slots # does not take availability into account\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 starttime = Time.zone.now + 10.minutes\n # Then we have to round to the next hour block\n starttime = Time.zone.at( (starttime.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 starttime = [starttime, starttime.change(hour: opening_hour)].max\n\n # Determine the furthest in the future we will allow reservations\n end_time = (starttime + 3.days).change(hour: closing_hour)\n\n # Now, we want to make a list of every hour between our starttime 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 = starttime\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 coalesced\n last_slot = nil\n coales = inject(self.class.new) do |accum, this_slot|\n if last_slot\n rng = this_slot.range\n last_rng = last_slot.range\n if (rng.intersects?(last_rng) || rng.succeeds?(last_rng)) &&\n (this_slot.participants == last_slot.participants)\n last_slot = Timeslot.new(\n (last_rng.begin...rng.end), \n this_slot.participants\n )\n else\n accum << last_slot\n last_slot = this_slot\n end\n else\n last_slot = this_slot\n end\n accum\n end\n if last_slot \n coales << last_slot\n end\n coales\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a collection of TimeBlock(s), return only the ones that have no detectable collisions (and thus are valid). +:time_blocks+ All extracted TimeBlock(s) you wish to have validated.
def validate_time_blocks(time_blocks) b = time_blocks.select(&:collision_free?) # Test environment has unreliable data entry for start times. b = b.select(&:in_future?) unless Rails.env.test? b end
[ "def valid_blocks(base_time)\n set_base_time(base_time)\n time_entries = time_entries_for(base)\n end", "def invalid_blocks\n\t\treturn self.chain.reject( &:valid? )\n\tend", "def valid_schedule?(time_blocks)\n time_blocks = quicksort_timeblocks(time_blocks)\n return !exists_overlap?(time_blocks)\n end", "def detect_invalid_blocks\n self.class.combination(@frontier.select(&:invalid?)).detect do |block_array|\n holds_all_syntax_errors?(block_array)\n end || []\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 prune_basic_blocks(blocks); end", "def conflicting_blocks(daterange)\n validate(:daterange, daterange)\n return blocks.select { |block| block.conflict?(daterange) }\n end", "def test_check_block_bad_time\n\t refute @checker.check_block('0', '0', 'SYSTEM>111111(40)', '-1.-1', '1', '1', 0)\n end", "def valid_tickets\n @nearby_tickets.filter_map do |ticket|\n in_ranges = ticket.map do |val|\n merged_rules.map {|val_range| val_range.include?(val)}.include?(true)\n end\n ticket unless in_ranges.include?(false)\n end\n end", "def verify_transaction_data\n\n @blocks.each do |block|\n\n block_transactions = block.transactions\n block_users = []\n\n # Loop through each transaction\n block_transactions.split(\":\").each do |transaction|\n\n from = t_from(transaction)\n to = t_to(transaction)\n amt = t_amt(transaction).to_i\n\n if from.length > 6 || from.length < 1\n puts \"Line #{block.number}: Invalid block, address #{from} is not > 6 alphabetic characters.\"\n return false\n end\n\n if to.length > 6 || to.length < 1\n puts \"Line #{block.number}: Invalid block, address #{to} is not > 6 alphabetic characters.\"\n return false\n end\n\n # If it's from the system, ignore adding SYSTEM to the @user_list or decreasing coins\n if(from != \"SYSTEM\")\n\n if !@user_list.user_exist?(from)\n from = @user_list.add_user(from, 0)\n else\n from = @user_list.find_user(from)\n end\n\n from.num_coins -= amt\n\n block_users << from\n\n end\n\n if !@user_list.user_exist?(to)\n to = @user_list.add_user(to, 0)\n else\n to = @user_list.find_user(to)\n end\n\n to.num_coins += amt\n\n block_users << to\n\n end\n\n # Check the users in this block for a negative balance\n block_users.each do |user|\n\n if user.negative_balance?\n puts \"Line #{block.number}: Invalid block, address #{user.name} has #{user.num_coins} billcoins!\"\n return false\n end\n\n end\n\n end\n\n end", "def prune_basic_blocks(blocks)\n visited = Set.new\n queue = [blocks.fetch(0)]\n\n until queue.empty?\n current_block = queue.shift\n next if visited.include?(current_block)\n\n visited << current_block\n queue.concat(current_block.outgoing_blocks)\n end\n\n blocks.select! { |_, block| visited.include?(block) }\n end", "def exists_overlap?(time_blocks)\n (0..time_blocks.size - 2).each do |i|\n if (time_blocks[i].term == time_blocks[i+1].term &&\n time_blocks[i].day == time_blocks[i+1].day &&\n time_blocks[i].end_time > time_blocks[i+1].start_time)\n return true\n end\n end\n return false\n end", "def blocks filter = nil\n blocks = @client.query_get \"blocks\", filter\n if blocks[\"success\"]\n return blocks[\"blocks\"]\n else\n return nil\n end\n end", "def optimize_time_blocks(time_blocks)\n Optimizer.new.optimize(time_blocks)\n end", "def convert_to_timeblocks timeslots\n slots = timeslots.order(:offset).group_by(&:day)\n Hash[slots.map { |i,slots| [i, slots.group_by { |slot| slot.offset / minutes_per_block }]}]\n end", "def contains_block?(block_of_time)\n if(self.start_time <= block_of_time.start_time &&\n self.end_time >= block_of_time.end_time)\n true\n else\n false\n end\n end", "def test_blocks_not_consecutive\n block_num_checker = BlockNumChecker::new\n arr = [0,1,2,8,4,5,6]\n assert_equal 1, block_num_checker.check_block(arr)\n end", "def verify_block(wallets)\n # we always do these steps\n apply_transactions wallets\n verify_transaction_list\n verify_positive_balances wallets\n verify_hash\n\n # we only do these steps when there is a nxt block\n unless @nxt.nil?\n verify_id\n verify_prev_hash\n verify_timestamp\n\n @nxt.verify_block wallets\n end\n\n wallets\n end", "def intersecting_units(block)\n # create set of cells in the block\n block_set = Set.new(block.cell_ary)\n intersection_values = Set.new\n remainder_values = Set.new\n\n # find the units (columns & rows) that intersect\n unit_set = Set.new\n block.foreach_cell do |cell|\n unit_set.add(block.grid.rows[cell.ref.row])\n unit_set.add(block.grid.columns[cell.ref.col])\n end\n\n # For each intersecting unit, we create a Set that is the cells in the intersection of\n # the block and the intersecting unit. Using Set operations, we can then find hidden pairs.\n unit_set.each do |unit|\n # Create the intersection set.\n intersection_values.clear\n intersection = block.intersection(unit)\n\n # Create a set of all candidates that are in the intersection cells\n intersection.each do |cell|\n intersection_values.merge(cell.candidates)\n end\n\n # Create a set of the cells in the block that are not in the intersection - call it the\n # remainder set\n remainder_set = block_set - intersection\n\n # Create the set of all candidates that are in the remainder set\n remainder_values.clear\n remainder_set.each do |cell|\n remainder_values.merge(cell.candidates)\n end\n\n # Now, subtract the remainder value set from the intersection value set. Any cells in the\n # resulting set are hidden in the intersection.\n hidden_candidates = intersection_values - remainder_values\n\n # Here we walk through the cells in the intersecting unit that are not in the intersection\n # and mark the hidden candidates.\n # puts \"line 109 algorithms.rb\"\n unit = Set.new(unit.cell_ary)\n remainder_set = unit - intersection\n remainder_set.each do |cell|\n hidden_candidates.each do |candidate|\n cell.mark(candidate)\n end\n end\n\n # Next, we reverse the process by finding hidden values in the intersection that are not\n # in the unit remainder set.\n remainder_set = unit_set - intersection\n\n # Create the set of all candidates that are in the remainder set\n remainder_values.clear\n remainder_set.each do |cell|\n remainder_values.merge(cell.candidates)\n end\n\n # Now, subtract the remainder value set from the intersection value set. Any cells in the\n # resulting set are hidden in the intersection.\n hidden_candidates = intersection_values - remainder_values\n\n # Here we walk through the cells in the block that are not in the intersection\n # and mark the hidden candidates.\n remainder_set = block - intersection\n remainder_set.each do |cell|\n hidden_candidates.each do |candidate|\n cell.mark(candidate)\n end\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a collection of TimeBlock(s), return a more optimized subset of the given collection. +:time_blocks: Collection of TimeBlock(s) to be filtered and optimized.
def optimize_time_blocks(time_blocks) Optimizer.new.optimize(time_blocks) end
[ "def quicksort_timeblocks(time_blocks)\n if (time_blocks.size <= 1)\n return time_blocks\n end\n\n pivot = time_blocks[0]\n left = []\n right = []\n\n time_blocks[1..time_blocks.size-1].each do |tb|\n if (tb.term.to_i < pivot.term.to_i)\n left.push(tb)\n elsif (pivot.term.to_i < tb.term.to_i)\n right.push(tb)\n elsif (before_in_week(tb.day, pivot.day))\n left.push(tb)\n elsif (before_in_week(pivot.day, tb.day))\n right.push(tb)\n elsif (tb.start_time < pivot.start_time)\n left.push(tb)\n else\n right.push(tb)\n end\n end\n\n sorted_left = quicksort_timeblocks(left)\n sorted_right = quicksort_timeblocks(right)\n time_blocks = sorted_left.push(pivot) + sorted_right\n return time_blocks\n end", "def subset( *keys, &select_block )\n subset_params =\n if block_given?\n filter_parameters.select &select_block\n else\n filter_parameters.slice( *keys )\n end\n subset = self.class.new( subset_params )\n subset.predicates = predicates.clone\n subset\n end", "def subset_for transactions\n first_seens = transactions.collect { |tx| tx['first_seen'] }\n extra = 60\n min = (first_seens.min || 0) - extra\n max = (first_seens.max || 0) + extra\n $mempool.mempool.select { |k,v| k.to_i.between?(min, max) }\n end", "def filter(array, block)\n return array.select(&block) # Your code here\nend", "def filter_by_hours\n meters = Meter.all\n filtered_meters = []\n min_hours = get_from_slider\n\n meters.each do |m|\n if m.timeLimit >= min_hours\n filtered_meters << m\n end\n end\n\n return filtered_meters\n end", "def validate_time_blocks(time_blocks)\n b = time_blocks.select(&:collision_free?)\n\n # Test environment has unreliable data entry for start times.\n b = b.select(&:in_future?) unless Rails.env.test?\n\n b\n end", "def prune_basic_blocks(blocks); end", "def additional_blocks_with_time_report_query\n return @@additional_blocks if defined?(@@additional_blocks)\n\n @@additional_blocks = Dir.glob(\"#{Redmine::Plugin.directory}/*/app/views/my/blocks/_*.{rhtml,erb}\").inject({}) do |h,file|\n name = File.basename(file).split('.').first.gsub(/^_/, '')\n\n ################\n # Smile specific : partials overriden in plugin ignored\n unless (\n # Query selection partials ignored : plugins overrides partial\n name.end_with?('_query_selection') ||\n # Core blocks partials ignored : plugins overrides partial\n (name == 'issues') ||\n CORE_BLOCKS.keys.include?(name)\n )\n h[name] = {:label => name.to_sym, :partial => \"my/blocks/#{name}\"}\n else\n Rails.logger.debug \"==>prof additional_blocks_with_time_report_query, overriden by plugin : #{name} partial\"\n end\n\n h\n end\n\n Rails.logger.debug \"==>prof additional_blocks_with_time_report_query #{@@additional_blocks}\"\n @@additional_blocks\n end", "def intersect(intersections)\n result = Array(intersections).each_with_object([]) do |intersection, memo|\n memo.concat(intersect_with_time_interval(intersection))\n end\n\n Collection.new(result)\n end", "def reduce_blocks(blks, filter = writable_mifare_blocks)\n if identify_2d_array(blks)\n hsh = blks.to_h\n filter.map { |x| hsh[x] }.compact.flatten\n else\n filter.map { |x| blks[x] }.compact.flatten\n end\n end", "def fast_collect(collection, &block)\n collection.map do |item|\n Thread.new do\n Thread.current[:result] = block.call(item)\n end\n end.collect do |thread|\n thread.join\n thread[:result]\n end\n end", "def time_block_with_most_events(events)\n min_t, max_t = events.flatten.minmax\n \n events_on_times = (min_t..max_t).map do |t|\n [ t, events.select { |x, y| t.between?(x, y) }.count ]\n end\n \n max_events = events_on_times.map { |t, c| c }.max\n time_blocks = events_on_times.select { |t, c| c == max_events }.map(&:first)\n \n [max_events] + time_blocks.minmax\nend", "def filter_by_time \n\t\t#filtered_by_time logic moved to index in order to avoid duplicated code\n\tend", "def prune_basic_blocks(blocks)\n visited = Set.new\n queue = [blocks.fetch(0)]\n\n until queue.empty?\n current_block = queue.shift\n next if visited.include?(current_block)\n\n visited << current_block\n queue.concat(current_block.outgoing_blocks)\n end\n\n blocks.select! { |_, block| visited.include?(block) }\n end", "def filter!(&block)\n @rows.select!(&block)\n end", "def partition\n time_points = @time_intervals.flat_map { |i| [i.started_at, i.ended_at] }.uniq.sort\n start_time_points = time_points[0..-2]\n end_time_points = time_points[1..-1]\n raw_intervals = start_time_points.zip(end_time_points)\n Collection.new(raw_intervals.map { |r| Interval.new(*r) })\n end", "def blocks filter = nil\n blocks = @client.query_get \"blocks\", filter\n if blocks[\"success\"]\n return blocks[\"blocks\"]\n else\n return nil\n end\n end", "def blocks_for_block_size\n # We're already done with the last block behavior, if we wanted a small\n # last block, or if we only generated a single block\n return block_list if block_list.size <= 1 || last_block == :small_last\n\n case last_block\n when :truncate_all\n # Implemented in add_for_block_size\n nil\n when :small_last\n # Implemented just above\n nil\n when :truncate_last\n block_list.pop\n else # default to :big_last behavior\n last = block_list.pop\n block_list.last.words.concat(last.words)\n end\n\n block_list\n end", "def condense_blocks\n @rooms.each do |room_id, room|\n blocks = []\n start_time = room[:bookings][0]\n bookings_in_block = 1\n\n room[:bookings][1..-1].each.with_index(1) do |booking, index|\n if booking != start_time + 30 * 60 * bookings_in_block then\n end_time = room[:bookings][index - 1] + 30 * 60\n\n blocks << {\n :start => start_time.utc.iso8601,\n :end => end_time.utc.iso8601,\n :duration => (end_time - start_time) / 60\n }\n\n start_time = booking\n bookings_in_block = 1\n else\n bookings_in_block += 1\n end\n end\n\n end_time = room[:bookings][-1] + 30 * 60\n\n blocks << {\n :start => start_time.utc.iso8601,\n :end => end_time.utc.iso8601,\n :duration => (end_time - start_time) / 60\n }\n\n room[:bookings] = blocks\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The size of a TimeBlock. Based on the minute duration of the chosen Service.
def block_size session.chosen_service.duration rescue session.business.services.first.duration end
[ "def size_time\n\t\t\t\t\tif !scheduled?\n\t\t\t\t\t\traise \"Schedule event to specific date first.\"\n\t\t\t\t\tend\n\t\t\t\t\tif @size.nil?\n\t\t\t\t\t\t@size = DateTime.parse(\"2000-01-01 00:00:00 +0000\")\n\t\t\t\t\t\tself.reservations.each do |reservation|\n\t\t\t\t\t\t\tif reservation.above_line?\n\t\t\t\t\t\t\t\t@size += reservation.size.seconds_since_midnight.seconds\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\treturn @size\n\t\t\t\tend", "def block_size\n self[:block_size]\n end", "def block_size\n check_valid\n md.block_size\n end", "def unit_size\n @unit_size ||= (GTBS::Act_large_units[self.id] or 1)\n end", "def size(base = self.date_from)\n\t\t\t\t\treturn self.send(\"size_#{self.capacity_type.to_s}\", base)\n\t\t\t\tend", "def block_size\n @block_size\n end", "def size\n\t\t\t\t\treturn self.send(\"size_#{self.capacity_type.to_s}\")\n\t\t\t\tend", "def block_size\n @disk.block_size\n end", "def block_sizes\n unless defined?(@block_sizes) then\n @block_sizes = split_comma(@data[18]).collect { |x| x.to_i }\n end\n @block_sizes\n end", "def size\n @size ||= approximate_size\n end", "def total_size\n @total_size\n end", "def actual_size\n @actual_size\n end", "def size_in_kb\n @size.to_f / 1024 if @size\n end", "def size_in_kb\n if @size\n @size.to_f/1024\n end\n end", "def part_size_in_bytes\n data[:part_size_in_bytes]\n end", "def event_block_height(event)\n event.time_length * calendar_hour_size_pixels\n end", "def sizes\n Vultr::Resource::Plan.new(@faraday)\n end", "def part_size_in_bytes\n data.part_size_in_bytes\n end", "def size_mb \n return size / 1048576 # (1024 * 1024) \n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch the timezone for the chosen office. While also memoizing the time_zone result as
def time_zone return @time_zone_cache if @time_zone_cache # Get the office id from the session json store id = @session.store[:chosen_office_id] office = Office .where(business_id: @session.business_id, id: id) .first if office.present? @time_zone_cache = office.time_zone end @time_zone_cache end
[ "def time_zone\n @session.chosen_office.time_zone if @session.chosen_office.present?\n end", "def tz_timezone ; @venue.tz_timezone; end", "def timezone\n TimeZoneHelper.info_hash(tzinfo_tz, rails_tz)\n end", "def tz\n # logger.debug(\"CHC: customer tz called from #{caller.join(\"\\n\")}\")\n if tzb = time_zone_binary\n tzb.to_r / MINS_PER_DAY\n else\n nil\n end\n end", "def timezone()\n if @hash\n @hash[:TZID]\n else\n nil\n end\n end", "def time_zone\n addresses.primary.blank? || addresses.primary.time_zone.blank? ? nil : addresses.primary.time_zone\n end", "def get_timezone(zone_identifier)\n TZInfo::Timezone.get(zone_identifier)\nend", "def _extract_calendar_timezone\n return nil unless parent\n return nil unless parent.is_a?(Icalendar::Calendar)\n calendar_timezones = parent.timezones\n calendar_timezones.each do |tz|\n break unless tz.valid?(true)\n ugly_tzid = tz.tzid\n break unless ugly_tzid\n tzid = Array(ugly_tzid).first.to_s.gsub(/^([\"'])|([\"'])$/, '')\n tz_found = ActiveSupport::TimeZone[tzid]\n return tz_found if tz_found\n end\n nil\n rescue StandardError\n nil\n end", "def timezone\n @history.objects.find { |o| o.name == \"tz\" }.val\n end", "def timezone_at(lng: 0.0, lat: 0.0)\n if lng > 180.0 or lng < -180.0 or lat > 90.0 or lat < -90.0\n raise ::TimezoneFinder::CoordinatesOutOfBoundsError.new(lng, lat)\n end\n\n possible_polygons = shortcuts_of(lng, lat)\n\n # x = longitude y = latitude both converted to 8byte int\n x = Helpers.coord2int(lng)\n y = Helpers.coord2int(lat)\n\n nr_possible_polygons = possible_polygons.length\n\n return nil if nr_possible_polygons == 0\n\n return TIMEZONE_NAMES[id_of(possible_polygons[0])] if nr_possible_polygons == 1\n\n # initialize the list of ids\n # and sort possible_polygons from least to most occurrences of zone_id\n possible_polygons, ids, only_one_zone = compile_id_list(possible_polygons, nr_possible_polygons)\n\n return TIMEZONE_NAMES[ids[0]] if only_one_zone\n\n # otherwise check if the point is included for all the possible polygons\n (0...nr_possible_polygons).each do |i|\n polygon_nr = possible_polygons[i]\n\n # get the boundaries of the polygon = (lng_max, lng_min, lat_max, lat_min)\n @binary_file.seek((@bound_start_address + 16 * polygon_nr))\n boundaries = Helpers.fromfile(@binary_file, false, 4, 4)\n # only run the expensive algorithm if the point is withing the boundaries\n unless x > boundaries[0] or x < boundaries[1] or y > boundaries[2] or y < boundaries[3]\n\n outside_all_holes = true\n # when the point is within a hole of the polygon, this timezone doesn't need to be checked\n _holes_of_line(polygon_nr) do |hole_coordinates|\n if Helpers.inside_polygon(x, y, hole_coordinates)\n outside_all_holes = false\n break\n end\n end\n\n if outside_all_holes\n if Helpers.inside_polygon(x, y, coords_of(polygon_nr))\n return TIMEZONE_NAMES[ids[i]]\n end\n end\n end\n # when after the current polygon only polygons from the same zone appear, return this zone\n same_element = Helpers.all_the_same(i + 1, nr_possible_polygons, ids)\n return TIMEZONE_NAMES[same_element] if same_element != -1\n end\n nil\n end", "def timezone\n return attribute_get(:timezone) if attribute_get(:timezone) =~ /GMT[+-]\\d{1,2}/\n time = TZInfo::Timezone.get(attribute_get(:timezone)).current_period\n seconds = time.utc_offset\n offset = (seconds / (60*60))\n attribute_set(:timezone, (offset < 0 ? \"GMT#{offset}\" : \"GMT+#{offset}\"))\n attribute_get(:timezone)\n end", "def current_user_timezone\n app_get_geo_data_by_ip.try(:timezone) || \"America/La_Paz\"\n end", "def find_timezone(city)\n @cities = City.all\n cityObject = @cities.where(name: city.downcase)\n\n timezone=nil\n cityObject.each do |c|\n timezone = c.timezone\n end\n\n return timezone\n end", "def certain_timezone_at(lng: 0.0, lat: 0.0)\n if lng > 180.0 or lng < -180.0 or lat > 90.0 or lat < -90.0\n raise ::TimezoneFinder::CoordinatesOutOfBoundsError.new(lng, lat)\n end\n\n possible_polygons = shortcuts_of(lng, lat)\n\n # x = longitude y = latitude both converted to 8byte int\n x = Helpers.coord2int(lng)\n y = Helpers.coord2int(lat)\n\n possible_polygons.each do |polygon_nr|\n # get boundaries\n @binary_file.seek((@bound_start_address + 16 * polygon_nr))\n boundaries = Helpers.fromfile(@binary_file, false, 4, 4)\n unless x > boundaries[0] or x < boundaries[1] or y > boundaries[2] or y < boundaries[3]\n\n outside_all_holes = true\n # when the point is within a hole of the polygon this timezone doesn't need to be checked\n _holes_of_line(polygon_nr) do |hole_coordinates|\n if Helpers.inside_polygon(x, y, hole_coordinates)\n outside_all_holes = false\n break\n end\n end\n\n if outside_all_holes\n if Helpers.inside_polygon(x, y, coords_of(polygon_nr))\n return TIMEZONE_NAMES[id_of(polygon_nr)]\n end\n end\n end\n end\n nil\n end", "def find_zone(time_zone)\n find_zone!(time_zone) rescue nil\n end", "def tzinfo; end", "def regional_office_for_scheduled_timezone(hearing, vacols_record)\n ro_key = if vacols_record.hearing_type == HearingDay::REQUEST_TYPES[:travel] || hearing.hearing_day.nil?\n vacols_record.hearing_venue\n else\n hearing.hearing_day&.regional_office || \"C\"\n end\n\n RegionalOffice.find!(ro_key) if ro_key.present?\n end", "def timezone\n return call('Bugzilla.tomezone')\n end", "def curr_date_in_timezone\n Time.now.getlocal(address_timezone_offset)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a random amount of blocks (30min per block) to the end of an existing start.
def random_range_end(start) start + (rand(1..5) * 30).minutes end
[ "def add_for_num_blocks(words)\n # We just add to the single block, and we split this when we call\n # #blocks\n @single_block += words\n end", "def refresh_offset\n 300 + rand(0..60)\n end", "def generate_blocks (map)\n blocks = 0\n while blocks < $NUM_BLOCKS\n rand_row = Random.rand($MAP_HEIGHT / 3..$MAP_HEIGHT - ($MAP_HEIGHT / 3)) # Only spawn block in the middlish\n rand_col = Random.rand($MAP_WIDTH)\n\n if map[rand_row][rand_col].is_a? Air\n map[rand_row][rand_col] = Block.new(rand_row, rand_col, true)\n blocks += 1\n end\n end\n\n map\n end", "def add_for_block_size(words)\n # If we're running :truncate_all, then just append the block for this\n # document and return\n if last_block == :truncate_all\n if block_list.empty?\n name = I18n.t('lib.frequency.block_size_dataset',\n num: block_list.size + 1, size: block_size)\n block_list.push(Block.new(words: words[0...block_size],\n name: name))\n end\n return\n end\n\n # Make the first block, if needed\n unless block_list.last\n block_list.push(\n Block.new(\n words: [],\n name: I18n.t('lib.frequency.block_size_dataset',\n num: 1, size: block_size)\n )\n )\n end\n\n # Fill up the last block\n current_left = block_size - block_list.last.words.size\n if current_left.positive?\n block_list.last.words.concat(words.shift(current_left))\n end\n\n # Bail if there weren't enough words in the document to finish that block\n return if block_list.last.words.size < block_size\n\n # Turn the remaining words into blocks and append\n words.in_groups_of(block_size, false).each do |b|\n name = I18n.t('lib.frequency.block_size_dataset',\n num: block_list.size + 1, size: block_size)\n block_list.push(Block.new(words: b, name: name))\n end\n end", "def generateStartBlock\n # Set player to stand on start block\n @player.y = @@LOSEFLOOR - 100 - Tile::HEIGHT - 0.55 * @player.height\n # Set floor\n @floor = @player.y\n # Make the start block\n Block.new(0, @@LOSEFLOOR - 100, 20, 2)\n end", "def add_for_block_size(words)\n # If we're running :truncate_all, then just append the block for this\n # document and return\n if @last_block == :truncate_all\n if @blocks.empty?\n name = I18n.t('lib.frequency.block_size_dataset',\n num: @blocks.size + 1, size: @block_size)\n @blocks << Block.new(words[0...@block_size], name)\n end\n return\n end\n\n # Make the first block, if needed\n unless @blocks.last\n @blocks << Block.new([], I18n.t('lib.frequency.block_size_dataset',\n num: 1, size: @block_size))\n end\n\n # Fill up the last block\n current_left = @block_size - @blocks.last.words.size\n @blocks.last.words += words.shift(current_left) if current_left > 0\n\n # Bail if there weren't enough words in the document to finish that block\n return if @blocks.last.words.size < @block_size\n\n # Turn the remaining words into blocks and append\n words.in_groups_of(@block_size, false).each do |b|\n name = I18n.t('lib.frequency.block_size_dataset',\n num: @blocks.size + 1, size: @block_size)\n @blocks << Block.new(b, name)\n end\n end", "def add_for_num_blocks(words)\n # We just add to the single block, and we split this when we call\n # #blocks\n single_block.concat(words)\n end", "def create_blocks prev_hash, n, opts = {}\n interval = opts[:interval] || 600\n time = opts[:time] || Time.now.to_i\n bits = opts[:bits] || 553713663\n block = @store.get_block(prev_hash)\n n.times do |i|\n block = create_block block.hash, true, [], @key, 50e8, {\n time: time += interval, bits: bits }\n # block = @store.get_block(block.hash)\n # puts \"#{i} #{block.hash[0..8]} #{block.prev_block.reverse_hth[0..8]} #{Time.at(block.time).strftime('%Y-%m-%d %H:%M:%S')} c: #{block.chain} b: #{block.bits} n: #{block.nonce} w: #{block.work}\"\n end\n block\nend", "def random_spawn_countdown minimum\n 10.randomize(:ratio, :sign).to_i + 60\n end", "def generate_random_block_id\n return ((0..9).to_a.sample(5)).join\n end", "def makeDurationBlockRel(relname, var_to_copy, binding, block_dur, skip_blocks)\n block_var = createNewVariable(relname + \"_blocks\", \"block_num\")\n rel_var = make_rel(relname, var_to_copy, 0)\n\n var_to_copy = getVariable(var_to_copy)\n binding = getVariable(binding)\n\n\n block_dur = block_dur * 1000 # Convert to milliseconds\n block_num = 1\n for bindcell in binding.cells\n cell_dur = bindcell.offset - bindcell.onset\n if cell_dur <= block_dur\n cell = block_var.make_new_cell()\n cell.change_arg(\"block_num\", block_num.to_s)\n cell.change_arg(\"onset\", bindcell.onset)\n cell.change_arg(\"offset\", bindcell.offset)\n block_num += 1\n else\n num_possible_blocks = cell_dur / block_dur #Integer division\n if num_possible_blocks > 0\n for i in 0..num_possible_blocks\n if i % skip_blocks == 0\n cell = block_var.make_new_cell()\n cell.change_arg(\"block_num\", block_num.to_s)\n cell.change_arg(\"onset\", bindcell.onset + i * block_dur)\n if bindcell.onset + (i + 1) * block_dur <= bindcell.offset\n cell.change_arg(\"offset\", bindcell.onset + (i + 1) * block_dur)\n else\n cell.change_arg(\"offset\", bindcell.offset)\n end\n block_num += 1\n end\n end\n end\n end\n end\n setVariable(relname + \"_blocks\", block_var)\nend", "def makeDurationBlockRel(relname, var_to_copy, binding, block_dur, skip_blocks)\n block_var = createVariable(relname + \"_blocks\", \"block_num\")\n rel_var = make_rel(relname, var_to_copy, 0)\n\n var_to_copy = getVariable(var_to_copy)\n binding = getVariable(binding)\n\n\n block_dur = block_dur * 1000 # Convert to milliseconds\n block_num = 1\n for bindcell in binding.cells\n cell_dur = bindcell.offset - bindcell.onset\n if cell_dur <= block_dur\n cell = block_var.make_new_cell()\n cell.change_arg(\"block_num\", block_num.to_s)\n cell.change_arg(\"onset\", bindcell.onset)\n cell.change_arg(\"offset\", bindcell.offset)\n block_num += 1\n else\n num_possible_blocks = cell_dur / block_dur #Integer division\n if num_possible_blocks > 0\n for i in 0..num_possible_blocks\n if i % skip_blocks == 0\n cell = block_var.make_new_cell()\n cell.change_arg(\"block_num\", block_num.to_s)\n cell.change_arg(\"onset\", bindcell.onset + i * block_dur)\n if bindcell.onset + (i + 1) * block_dur <= bindcell.offset\n cell.change_arg(\"offset\", bindcell.onset + (i + 1) * block_dur)\n else\n cell.change_arg(\"offset\", bindcell.offset)\n end\n block_num += 1\n end\n end\n end\n end\n end\n setVariable(relname + \"_blocks\", block_var)\nend", "def create_block_of_rooms(start_date, end_date, discounted_rate)\n dates = date_range(start_date, end_date)\n new_block = RoomBlock.new(start_date, end_date, room_cost: discounted_rate)\n new_block.id = assign_block_id\n\n num_of_rooms = 0\n @rooms.each do |room|\n if is_available?(room, dates) && is_not_blocked?(room, dates)\n new_block.add_room(room)\n num_of_rooms += 1\n end\n if num_of_rooms == 5\n break\n end\n end\n\n @room_blocks << new_block\n\n return new_block\n end", "def create_blocks(count)\n (0...count).to_a.map { create_block }\n end", "def create_random_list(limit)\n limit.times do\n add(rand(10))\n end\n end", "def insert_coins(count = 0)\n super\n self.period += (5 * count.to_i)\n end", "def append_random; end", "def create_blocks(count)\n begin\n create_blocks! count\n rescue\n nil\n end\n end", "def no_of_blocks\n @highlighted_blocks = \"\"\n blocks = Random.rand(5) + 1\n blocks.times {|count|\n row = Random.rand(5)\n column = Random.rand(5)\n @highlighted_blocks << \"#button_#{row}_#{column} \"\n }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add hvac Add the daylighting controls for lobby, cafe, dinning and banquet
def add_daylighting_controls(building_vintage) space_names = ['Banquet_Flr_6','Dining_Flr_6','Cafe_Flr_1','Lobby_Flr_1'] space_names.each do |space_name| space = self.getSpaceByName(space_name).get space.addDaylightingControls(building_vintage, false, false) end end
[ "def addDaylightingControls()\n \n OpenStudio::logFree(OpenStudio::Info, 'openstudio.model.Model', 'Started adding daylighting controls.')\n \n # Add daylighting controls to each space\n self.getSpaces.sort.each do |space|\n added = space.addDaylightingControls(self.template, false, false)\n end\n \n OpenStudio::logFree(OpenStudio::Info, 'openstudio.model.Model', 'Finished adding daylighting controls.')\n \n end", "def addDaylightingControls(vintage, remove_existing_controls, draw_daylight_areas_for_debugging = false)\n \n OpenStudio::logFree(OpenStudio::Debug, \"openstudio.model.Space\", \"******For #{self.name}, adding daylight controls.\")\n\n # Check for existing daylighting controls\n # and remove if specified in the input\n existing_daylighting_controls = self.daylightingControls\n if existing_daylighting_controls.size > 0\n if remove_existing_controls\n existing_daylighting_controls.each do |dc|\n dc.remove\n end\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{self.name}, removed #{existing_daylighting_controls.size} existing daylight controls before adding new controls.\")\n else\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{self.name}, daylight controls were already present, no additional controls added.\")\n return false\n end\n end\n\n areas = nil\n \n req_top_ctrl = false\n req_pri_ctrl = false\n req_sec_ctrl = false\n \n # Get the area of the space\n space_area_m2 = self.floorArea\n \n # Get the LPD of the space\n space_lpd_w_per_m2 = self.lightingPowerPerFloorArea\n \n # Determine the type of control required\n case vintage\n when 'DOE Ref Pre-1980', 'DOE Ref 1980-2004', '90.1-2004', '90.1-2007'\n \n # Do nothing, no daylighting controls required\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, daylighting control not required by this standard.\")\n return false\n \n when '90.1-2010'\n \n req_top_ctrl = true\n req_pri_ctrl = true\n \n areas = self.daylighted_areas(vintage, draw_daylight_areas_for_debugging)\n \n # Sidelighting\n # Check if the primary sidelit area < 250 ft2\n if areas['primary_sidelighted_area'] == 0.0\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, primary sidelighting control not required because primary sidelighted area = 0ft2 per 9.4.1.4.\")\n req_pri_ctrl = false\n elsif areas['primary_sidelighted_area'] < OpenStudio.convert(250, 'ft^2', 'm^2').get\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, primary sidelighting control not required because primary sidelighted area < 250ft2 per 9.4.1.4.\")\n req_pri_ctrl = false\n else \n # Check effective sidelighted aperture\n sidelighted_effective_aperture = self.sidelightingEffectiveAperture(areas['primary_sidelighted_area'])\n if sidelighted_effective_aperture < 0.1\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, primary sidelighting control not required because sidelighted effective aperture < 0.1 per 9.4.1.4 Exception b.\")\n req_pri_ctrl = false\n else\n # TODO Check the space type\n # if \n # OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{self.name}, primary sidelighting control not required because space type is retail per 9.4.1.4 Exception c.\")\n # req_pri_ctrl = false\n # end\n end\n end\n \n # Toplighting\n # Check if the toplit area < 900 ft2\n if areas['toplighted_area'] == 0.0\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, toplighting control not required because toplighted area = 0ft2 per 9.4.1.5.\")\n req_top_ctrl = false\n elsif areas['toplighted_area'] < OpenStudio.convert(900, 'ft^2', 'm^2').get\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, toplighting control not required because toplighted area < 900ft2 per 9.4.1.5.\")\n req_top_ctrl = false\n else \n # Check effective sidelighted aperture\n sidelighted_effective_aperture = self.skylightEffectiveAperture(areas['toplighted_area'])\n if sidelighted_effective_aperture < 0.006\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, toplighting control not required because skylight effective aperture < 0.006 per 9.4.1.5 Exception b.\")\n req_top_ctrl = false\n else\n # TODO Check the climate zone. Not required in CZ8 where toplit areas < 1500ft2\n # if \n # OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{self.name}, toplighting control not required because space type is retail per 9.4.1.5 Exception c.\")\n # req_top_ctrl = false\n # end\n end\n end\n \n when '90.1-2013'\n \n req_top_ctrl = true\n req_pri_ctrl = true\n req_sec_ctrl = true\n \n areas = self.daylighted_areas(vintage, draw_daylight_areas_for_debugging)\n \n # Primary Sidelighting\n # Check if the primary sidelit area contains less than 150W of lighting\n if areas['primary_sidelighted_area'] == 0.0\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, primary sidelighting control not required because primary sidelighted area = 0ft2 per 9.4.1.1(e).\")\n req_pri_ctrl = false\n elsif areas['primary_sidelighted_area'] * space_lpd_w_per_m2 < 150.0\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, primary sidelighting control not required because less than 150W of lighting are present in the primary daylighted area per 9.4.1.1(e).\")\n req_pri_ctrl = false\n else\n # Check the size of the windows\n if areas['total_window_area'] < 20.0\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, primary sidelighting control not required because there are less than 20ft2 of window per 9.4.1.1(e) Exception 2.\")\n req_pri_ctrl = false\n else \n # TODO Check the space type\n # if \n # OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, primary sidelighting control not required because space type is retail per 9.4.1.1(e) Exception c.\")\n # req_pri_ctrl = false\n # end\n end\n end\n \n # Secondary Sidelighting\n # Check if the primary and secondary sidelit areas contains less than 300W of lighting\n if areas['secondary_sidelighted_area'] == 0.0\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, secondary sidelighting control not required because secondary sidelighted area = 0ft2 per 9.4.1.1(e).\")\n req_pri_ctrl = false \n elsif (areas['primary_sidelighted_area'] + areas['secondary_sidelighted_area']) * space_lpd_w_per_m2 < 300\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, secondary sidelighting control not required because less than 300W of lighting are present in the combined primary and secondary daylighted areas per 9.4.1.1(e).\")\n req_sec_ctrl = false\n else\n # Check the size of the windows\n if areas['total_window_area'] < 20\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, secondary sidelighting control not required because there are less than 20ft2 of window per 9.4.1.1(e) Exception 2.\")\n req_sec_ctrl = false\n else \n # TODO Check the space type\n # if \n # OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, primary sidelighting control not required because space type is retail per 9.4.1.1(e) Exception c.\")\n # req_sec_ctrl = false\n # end\n end\n end\n\n # Toplighting\n # Check if the toplit area contains less than 150W of lighting\n if areas['toplighted_area'] == 0.0\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, toplighting control not required because toplighted area = 0ft2 per 9.4.1.1(f).\")\n req_pri_ctrl = false \n elsif areas['toplighted_area'] * space_lpd_w_per_m2 < 150\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, toplighting control not required because less than 150W of lighting are present in the toplighted area per 9.4.1.1(f).\")\n req_sec_ctrl = false\n else\n # TODO exception 2 for skylights with VT < 0.4\n # TODO exception 3 for CZ 8 where lighting < 200W\n end\n\n when 'AssetScore'\n \n # Same as 90.1-2010 but without effective aperture limits\n # to avoid needing to perform run to get VLT for layered windows.\n \n req_top_ctrl = true\n req_pri_ctrl = true\n \n areas = self.daylighted_areas(vintage, draw_daylight_areas_for_debugging)\n \n # Sidelighting\n # Check if the primary sidelit area < 250 ft2\n if areas['primary_sidelighted_area'] == 0.0\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, primary sidelighting control not required because primary sidelighted area = 0ft2 per 9.4.1.4.\")\n req_pri_ctrl = false\n elsif areas['primary_sidelighted_area'] < OpenStudio.convert(250, 'ft^2', 'm^2').get\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, primary sidelighting control not required because primary sidelighted area < 250ft2 per 9.4.1.4.\")\n req_pri_ctrl = false\n end\n \n # Toplighting\n # Check if the toplit area < 900 ft2\n if areas['toplighted_area'] == 0.0\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, toplighting control not required because toplighted area = 0ft2 per 9.4.1.5.\")\n req_top_ctrl = false\n elsif areas['toplighted_area'] < OpenStudio.convert(900, 'ft^2', 'm^2').get\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, toplighting control not required because toplighted area < 900ft2 per 9.4.1.5.\")\n req_top_ctrl = false \n end \n \n end # End of vintage case statement\n \n # Output the daylight control requirements\n OpenStudio::logFree(OpenStudio::Debug, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, toplighting control required = #{req_top_ctrl}\")\n OpenStudio::logFree(OpenStudio::Debug, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, primary sidelighting control required = #{req_pri_ctrl}\")\n OpenStudio::logFree(OpenStudio::Debug, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, secondary sidelighting control required = #{req_sec_ctrl}\")\n\n # Stop here if no lighting controls are required.\n # Do not put daylighting control points into the space.\n if !req_top_ctrl && !req_pri_ctrl && !req_sec_ctrl\n OpenStudio::logFree(OpenStudio::Debug, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, no daylighting control is required.\")\n return false\n end\n \n # Record a floor in the space for later use\n floor_surface = nil\n self.surfaces.each do |surface|\n if surface.surfaceType == \"Floor\"\n floor_surface = surface\n break\n end\n end\n \n # Find all exterior windows/skylights in the space and record their azimuths and areas\n windows = {}\n skylights = {}\n self.surfaces.each do |surface|\n next unless surface.outsideBoundaryCondition == \"Outdoors\" && (surface.surfaceType == \"Wall\" || surface.surfaceType == \"RoofCeiling\")\n \n # Skip non-vertical walls and non-horizontal roofs\n straight_upward = OpenStudio::Vector3d.new(0, 0, 1)\n surface_normal = surface.outwardNormal\n if surface.surfaceType == \"Wall\"\n # TODO stop skipping non-vertical walls\n unless surface_normal.z.abs < 0.001 \n if surface.subSurfaces.size > 0\n OpenStudio::logFree(OpenStudio::Warn, \"openstudio.model.Space\", \"Cannot currently handle non-vertical walls; skipping windows on #{surface.name} in #{self.name} for daylight sensor positioning.\")\n next\n end\n end\n elsif surface.surfaceType == \"RoofCeiling\"\n # TODO stop skipping non-horizontal roofs\n unless surface_normal.to_s == straight_upward.to_s\n if surface.subSurfaces.size > 0\n OpenStudio::logFree(OpenStudio::Warn, \"openstudio.model.Space\", \"Cannot currently handle non-horizontal roofs; skipping skylights on #{surface.name} in #{self.name} for daylight sensor positioning.\")\n OpenStudio::logFree(OpenStudio::Debug, \"openstudio.model.Space\", \"---Surface #{surface.name} has outward normal of #{surface_normal.to_s.gsub(/\\[|\\]/,'|')}; up is #{straight_upward.to_s.gsub(/\\[|\\]/,'|')}.\")\n next\n end\n end\n end\n \n # Find the azimuth of the facade\n facade = nil\n group = surface.planarSurfaceGroup\n if group.is_initialized\n group = group.get\n site_transformation = group.buildingTransformation\n site_vertices = site_transformation * surface.vertices\n site_outward_normal = OpenStudio::getOutwardNormal(site_vertices)\n if site_outward_normal.empty?\n OpenStudio::logFree(OpenStudio::Error, \"openstudio.model.Space\", \"Could not compute outward normal for #{surface.name.get}\")\n next\n end\n site_outward_normal = site_outward_normal.get\n north = OpenStudio::Vector3d.new(0.0,1.0,0.0)\n if site_outward_normal.x < 0.0\n azimuth = 360.0 - OpenStudio::radToDeg(OpenStudio::getAngle(site_outward_normal, north))\n else\n azimuth = OpenStudio::radToDeg(OpenStudio::getAngle(site_outward_normal, north))\n end\n else\n # The surface is not in a group; should not hit, since\n # called from Space.surfaces\n next\n end\n \n #TODO modify to work for buildings in the southern hemisphere?\n if (azimuth >= 315.0 || azimuth < 45.0)\n facade = \"4-North\"\n elsif (azimuth >= 45.0 && azimuth < 135.0)\n facade = \"3-East\"\n elsif (azimuth >= 135.0 && azimuth < 225.0)\n facade = \"1-South\"\n elsif (azimuth >= 225.0 && azimuth < 315.0)\n facade = \"2-West\"\n end\n \n # Label the facade as \"Up\" if it is a skylight\n if surface_normal.to_s == straight_upward.to_s\n facade = \"0-Up\"\n end\n \n # Loop through all subsurfaces and \n surface.subSurfaces.each do |sub_surface|\n next unless sub_surface.outsideBoundaryCondition == \"Outdoors\" && (sub_surface.subSurfaceType == \"FixedWindow\" || sub_surface.subSurfaceType == \"OperableWindow\" || sub_surface.subSurfaceType == \"Skylight\")\n\n # Find the area\n net_area_m2 = sub_surface.netArea\n \n # Find the head height and sill height of the window\n vertex_heights_above_floor = []\n sub_surface.vertices.each do |vertex|\n vertex_on_floorplane = floor_surface.plane.project(vertex)\n vertex_heights_above_floor << (vertex - vertex_on_floorplane).length\n end\n head_height_m = vertex_heights_above_floor.max\n #OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"---head height = #{head_height_m}m, sill height = #{sill_height_m}m\")\n \n # Log the window properties to use when creating daylight sensors\n properties = {:facade => facade, :area_m2 => net_area_m2, :handle => sub_surface.handle, :head_height_m => head_height_m}\n if facade == '0-Up'\n skylights[sub_surface] = properties\n else\n windows[sub_surface] = properties\n end\n \n end #next sub-surface\n end #next surface\n \n # TODO Determine the illuminance setpoint for the controls based on space type\n daylight_stpt_lux = 300\n space_name = self.name.get\n daylight_stpt_lux = nil\n if space_name.match(/post-office/i)# Post Office 500 Lux\n daylight_stpt_lux = 500\n elsif space_name.match(/medical-office/i)# Medical Office 3000 Lux\n daylight_stpt_lux = 3000\n elsif space_name.match(/office/i)# Office 500 Lux\n daylight_stpt_lux = 500\n elsif space_name.match(/education/i)# School 500 Lux\n daylight_stpt_lux = 500\n elsif space_name.match(/retail/i)# Retail 1000 Lux\n daylight_stpt_lux = 1000\n elsif space_name.match(/warehouse/i)# Warehouse 200 Lux\n daylight_stpt_lux = 200\n elsif space_name.match(/hotel/i)# Hotel 300 Lux\n daylight_stpt_lux = 300\n elsif space_name.match(/multifamily/i)# Apartment 200 Lux\n daylight_stpt_lux = 200\n elsif space_name.match(/courthouse/i)# Courthouse 300 Lux\n daylight_stpt_lux = 300\n elsif space_name.match(/library/i)# Library 500 Lux\n daylight_stpt_lux = 500\n elsif space_name.match(/community-center/i)# Community Center 300 Lux\n daylight_stpt_lux = 300\n elsif space_name.match(/senior-center/i)# Senior Center 1000 Lux\n daylight_stpt_lux = 1000\n elsif space_name.match(/city-hall/i)# City Hall 500 Lux\n daylight_stpt_lux = 500\n else\n OpenStudio::logFree(OpenStudio::Warn, \"openstudio.model.Space\", \"Space #{space_name} is an unknown space type, assuming office and 300 Lux daylight setpoint\")\n daylight_stpt_lux = 300\n end \n \n # Get the zone that the space is in\n zone = self.thermalZone\n if zone.empty?\n OpenStudio::logFree(OpenStudio::Error, \"openstudio.model.Space\", \"Space #{self.name.get} has no thermal zone\")\n else\n zone = zone.get\n end \n \n # Sort by priority; first by facade, then by area\n sorted_windows = windows.sort_by { |window, vals| [vals[:facade], vals[:area]] }\n sorted_skylights = skylights.sort_by { |skylight, vals| [vals[:facade], vals[:area]] }\n \n # Report out the sorted skylights for debugging\n OpenStudio::logFree(OpenStudio::Debug, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, Skylights:\")\n sorted_skylights.each do |sky, p|\n OpenStudio::logFree(OpenStudio::Debug, \"openstudio.model.Space\", \"---#{sky.name} #{p[:facade]}, area = #{p[:area_m2].round(2)} m^2\")\n end\n \n # Report out the sorted windows for debugging\n OpenStudio::logFree(OpenStudio::Debug, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, Windows:\")\n sorted_windows.each do |win, p|\n OpenStudio::logFree(OpenStudio::Debug, \"openstudio.model.Space\", \"---#{win.name} #{p[:facade]}, area = #{p[:area_m2].round(2)} m^2\")\n end\n\n # Add the required controls\n sensor_1_frac = 0.0\n sensor_2_frac = 0.0\n sensor_1_window = nil\n sensor_2_window = nil\n \n case vintage\n when 'DOE Ref Pre-1980', 'DOE Ref 1980-2004', '90.1-2004', '90.1-2007'\n \n # Do nothing, no daylighting controls required\n \n when '90.1-2010', 'AssetScore'\n \n if req_top_ctrl && req_pri_ctrl\n # Sensor 1 controls toplighted area\n sensor_1_frac = areas['toplighted_area']/space_area_m2\n sensor_1_window = sorted_skylights[0]\n # Sensor 2 controls primary area\n sensor_2_frac = areas['primary_sidelighted_area']/space_area_m2\n sensor_2_window = sorted_windows[0]\n elsif req_top_ctrl && !req_pri_ctrl\n # Sensor 1 controls toplighted area\n sensor_1_frac = areas['toplighted_area']/space_area_m2\n sensor_1_window = sorted_skylights[0]\n elsif !req_top_ctrl && req_pri_ctrl\n if sorted_windows.size == 1\n # Sensor 1 controls the whole primary area\n sensor_1_frac = areas['primary_sidelighted_area']/space_area_m2\n sensor_1_window = sorted_windows[0]\n else\n # Sensor 1 controls half the primary area\n sensor_1_frac = (areas['primary_sidelighted_area']/space_area_m2)/2\n sensor_1_window = sorted_windows[0]\n # Sensor 2 controls the other half of primary area\n sensor_2_frac = (areas['primary_sidelighted_area']/space_area_m2)/2\n sensor_2_window = sorted_windows[1]\n end \n end\n \n when '90.1-2013'\n \n if req_top_ctrl && req_pri_ctrl && req_sec_ctrl\n # Sensor 1 controls toplighted area\n sensor_1_frac = areas['toplighted_area']/space_area_m2\n sensor_1_window = sorted_skylights[0]\n # Sensor 2 controls primary + secondary area\n sensor_2_frac = (areas['primary_sidelighted_area'] + areas['secondary_sidelighted_area'])/space_area_m2\n sensor_2_window = sorted_windows[0]\n elsif !req_top_ctrl && req_pri_ctrl && req_sec_ctrl\n # Sensor 1 controls primary area\n sensor_1_frac = areas['primary_sidelighted_area']/space_area_m2\n sensor_1_window = sorted_windows[0] \n # Sensor 2 controls secondary area\n sensor_2_frac = (areas['secondary_sidelighted_area']/space_area_m2)/2\n sensor_2_window = sorted_windows[0]\n elsif req_top_ctrl && !req_pri_ctrl && req_sec_ctrl\n # Sensor 1 controls toplighted area\n sensor_1_frac = areas['toplighted_area']/space_area_m2\n sensor_1_window = sorted_skylights[0]\n # Sensor 2 controls secondary area\n sensor_2_frac = (areas['secondary_sidelighted_area']/space_area_m2)/2\n sensor_2_window = sorted_windows[0]\n elsif req_top_ctrl && !req_pri_ctrl && !req_sec_ctrl\n # Sensor 1 controls toplighted area\n sensor_1_frac = areas['toplighted_area']/space_area_m2\n sensor_1_window = sorted_skylights[0] \n elsif !req_top_ctrl && req_pri_ctrl && !req_sec_ctrl\n # Sensor 1 controls primary area\n sensor_1_frac = areas['primary_sidelighted_area']/space_area_m2\n sensor_1_window = sorted_windows[0] \n elsif !req_top_ctrl && !req_pri_ctrl && req_sec_ctrl\n # Sensor 1 controls secondary area\n sensor_1_frac = areas['secondary_sidelighted_area']/space_area_m2\n sensor_1_window = sorted_windows[0] \n end\n \n end # End of vintage case statement \n \n # Place the sensors and set control fractions\n # get the zone that the space is in\n zone = self.thermalZone\n if zone.empty?\n OpenStudio::logFree(OpenStudio::Error, \"openstudio.model.Space\", \"Space #{self.name}, cannot determine daylighted areas.\")\n return false\n else\n zone = self.thermalZone.get\n end\n \n # Sensors\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, sensor 1 fraction = #{sensor_1_frac.round(2)}.\")\n OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{vintage} #{self.name}, sensor 2 fraction = #{sensor_2_frac.round(2)}.\")\n \n # First sensor\n if sensor_1_window\n # OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{self.name}, calculating daylighted areas.\")\n # runner.registerInfo(\"Daylight sensor 1 inside of #{sensor_1_frac.name}\")\n sensor_1 = OpenStudio::Model::DaylightingControl.new(model)\n sensor_1.setName(\"#{self.name} Daylt Sensor 1\")\n sensor_1.setSpace(self)\n sensor_1.setIlluminanceSetpoint(daylight_stpt_lux)\n sensor_1.setLightingControlType(\"Stepped\")\n sensor_1.setNumberofSteppedControlSteps(3) #all sensors 3-step per design\n # Place sensor depending on skylight or window\n sensor_vertex = nil\n if sensor_1_window[1][:facade] == '0-Up'\n sub_surface = sensor_1_window[0]\n outward_normal = sub_surface.outwardNormal\n centroid = OpenStudio::getCentroid(sub_surface.vertices).get\n ht_above_flr = OpenStudio::convert(3.0, \"ft\", \"m\").get\n outward_normal.setLength(sensor_1_window[1][:head_height_m] - ht_above_flr)\n sensor_vertex = centroid + outward_normal.reverseVector\n else\n sub_surface = sensor_1_window[0]\n window_outward_normal = sub_surface.outwardNormal\n window_centroid = OpenStudio::getCentroid(sub_surface.vertices).get\n window_outward_normal.setLength(sensor_1_window[1][:head_height_m])\n vertex = window_centroid + window_outward_normal.reverseVector\n vertex_on_floorplane = floor_surface.plane.project(vertex)\n floor_outward_normal = floor_surface.outwardNormal\n floor_outward_normal.setLength(OpenStudio::convert(3.0, \"ft\", \"m\").get)\n sensor_vertex = vertex_on_floorplane + floor_outward_normal.reverseVector\n end\n sensor_1.setPosition(sensor_vertex)\n #TODO rotate sensor to face window (only needed for glare calcs)\n zone.setPrimaryDaylightingControl(sensor_1)\n zone.setFractionofZoneControlledbyPrimaryDaylightingControl(sensor_1_frac)\n end\n \n # Second sensor\n if sensor_2_window\n # OpenStudio::logFree(OpenStudio::Info, \"openstudio.model.Space\", \"For #{self.name}, calculating daylighted areas.\")\n # runner.registerInfo(\"Daylight sensor 2 inside of #{sensor_2_frac.name}\")\n sensor_2 = OpenStudio::Model::DaylightingControl.new(model)\n sensor_2.setName(\"#{self.name} Daylt Sensor 2\")\n sensor_2.setSpace(self)\n sensor_2.setIlluminanceSetpoint(daylight_stpt_lux)\n sensor_2.setLightingControlType(\"Stepped\")\n sensor_2.setNumberofSteppedControlSteps(3) #all sensors 3-step per design\n # Place sensor depending on skylight or window\n sensor_vertex = nil\n if sensor_2_window[1][:facade] == '0-Up'\n sub_surface = sensor_2_window[0]\n outward_normal = sub_surface.outwardNormal\n centroid = OpenStudio::getCentroid(sub_surface.vertices).get\n ht_above_flr = OpenStudio::convert(3.0, \"ft\", \"m\").get\n outward_normal.setLength(sensor_2_window[1][:head_height_m] - ht_above_flr)\n sensor_vertex = centroid + outward_normal.reverseVector\n else\n sub_surface = sensor_2_window[0]\n window_outward_normal = sub_surface.outwardNormal\n window_centroid = OpenStudio::getCentroid(sub_surface.vertices).get\n window_outward_normal.setLength(sensor_2_window[1][:head_height_m])\n vertex = window_centroid + window_outward_normal.reverseVector\n vertex_on_floorplane = floor_surface.plane.project(vertex)\n floor_outward_normal = floor_surface.outwardNormal\n floor_outward_normal.setLength(OpenStudio::convert(3.0, \"ft\", \"m\").get)\n sensor_vertex = vertex_on_floorplane + floor_outward_normal.reverseVector\n end\n sensor_2.setPosition(sensor_vertex)\n #TODO rotate sensor to face window (only needed for glare calcs)\n zone.setSecondaryDaylightingControl(sensor_2)\n zone.setFractionofZoneControlledbySecondaryDaylightingControl(sensor_2_frac)\n end\n \n return true\n \n end", "def akrasia_horizon\n Time.use_zone(@timezone) do\n -8.days.ago.beginning_of_day\n end\n end", "def add_a_hl\n end", "def set_clocks\n now = DateTime.now\n $current_time.value = now.strftime(DateTimeFormat)\n $universal_time.value = now.new_offset.strftime(DateTimeFormat)\n $lunar_date.value = '%4d\\'%02d\\'%02d' % LunarYear.lunar_date(now.to_date)\n now\nend", "def add_holidays\n Log.add_info(request, params.inspect)\n\n raise(RequestPostOnlyException) unless request.post?\n\n holidays = params[:thetisBoxEdit]\n unless holidays.nil?\n holidays.split(\"\\n\").each do |holiday|\n tokens = holiday.split(',')\n date = DateTime.parse(tokens.shift.strip)\n date += date.offset # 2011-01-01 09:00:00 +0900 (==> 2011-01-01 00:00:00 UTC)\n name = tokens.join(',').strip\n\n schedule = Schedule.new\n schedule.xtype = Schedule::XTYPE_HOLIDAY\n schedule.scope = Schedule::SCOPE_ALL\n schedule.title = name\n schedule.start = date\n schedule.end = date\n schedule.allday = true\n schedule.save!\n end\n end\n\n @holidays = Schedule.get_holidays\n render(:partial => 'config_holidays', :layout => false)\n\n rescue => evar\n Log.add_error(request, evar)\n flash[:notice] = 'ERROR:' + t('msg.format_invalid')\n\n @holidays = Schedule.get_holidays\n render(:partial => 'config_holidays', :layout => false)\n end", "def apply_standard_controls(template, climate_zone)\n \n # Energy Recovery Ventilation\n if self.is_energy_recovery_ventilator_required(template, climate_zone)\n self.apply_energy_recovery_ventilator\n end\n \n # Economizers\n self.set_economizer_limits(template, climate_zone)\n self.set_economizer_integration(template, climate_zone) \n \n # Multizone VAV Systems\n if self.is_multizone_vav_system\n \n # VAV Reheat Control\n self.set_vav_damper_action(template, climate_zone)\n \n # Multizone VAV Optimization\n if self.is_multizone_vav_optimization_required(template, climate_zone)\n self.enable_multizone_vav_optimization\n else\n self.disable_multizone_vav_optimization\n end\n \n end\n \n # Single zone systems\n if self.thermalZones.size == 1\n self.apply_single_zone_controls(template, climate_zone)\n end\n\n # DCV\n if self.is_demand_control_ventilation_required(template, climate_zone)\n self.enable_demand_control_ventilation\n else\n # TODO Need to convert the design spec OA objects\n # to per-area only so that if VRP is enabled we\n # don't get DCV accidentally? See PNNL Achieving 30% 5.2.2.21,\n # not convinced that this is actually necessary with current E+\n # capabilities.\n end\n \n # SAT reset\n if self.is_supply_air_temperature_reset_required(template, climate_zone)\n self.enable_supply_air_temperature_reset\n end\n \n # TODO Optimum Start\n # for systems exceeding 10,000 cfm\n # need 1.9.0 for this AVM\n \n # TODO night damper shutoff\n \n # TODO night cycle\n \n # TODO night fan shutoff > 0.75 hp\n \n end", "def create\n @daylight = Daylight.new(daylight_params)\n\n respond_to do |format|\n if @daylight.save\n format.html { redirect_to @daylight, notice: 'Daylight was successfully created.' }\n format.json { render json: @daylight, status: :created, location: @daylight }\n else\n format.html { render action: \"new\" }\n format.json { render json: @daylight.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_hl_de\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 add_veth veth\n cmd = \"#{@vzctl} set #{@ctid} --netif_add #{veth[:ifname]},#{veth[:mac]},#{veth[:host_ifname]},\" \\\n \"#{veth[:host_mac]}, #{veth[:bridge]}\"\n execute(cmd)\n end", "def add_exterior_lights(building_type, building_vintage, climate_zone, prototype_input)\n # TODO Standards - translate w/linear foot of facade, door, parking, etc\n # into lookup table and implement that way instead of hard-coding as\n # inputs in the spreadsheet.\n OpenStudio::logFree(OpenStudio::Info, 'openstudio.model.Model', 'Started adding exterior lights')\n\n # Occupancy Sensing Exterior Lights\n # which reduce to 70% power when no one is around.\n unless prototype_input['occ_sensing_exterior_lighting_power'].nil?\n occ_sens_ext_lts_power = prototype_input['occ_sensing_exterior_lighting_power']\n occ_sens_ext_lts_sch_name = prototype_input['occ_sensing_exterior_lighting_schedule']\n occ_sens_ext_lts_name = 'Occ Sensing Exterior Lights'\n occ_sens_ext_lts_def = OpenStudio::Model::ExteriorLightsDefinition.new(self)\n occ_sens_ext_lts_def.setName(\"#{occ_sens_ext_lts_name} Def\")\n occ_sens_ext_lts_def.setDesignLevel(occ_sens_ext_lts_power)\n occ_sens_ext_lts_sch = self.add_schedule(occ_sens_ext_lts_sch_name)\n occ_sens_ext_lts = OpenStudio::Model::ExteriorLights.new(occ_sens_ext_lts_def, occ_sens_ext_lts_sch)\n occ_sens_ext_lts.setName(\"#{occ_sens_ext_lts_name} Def\")\n occ_sens_ext_lts.setControlOption('AstronomicalClock')\n end\n\n # Building Facade and Landscape Lights\n # that don't dim at all at night.\n unless prototype_input['nondimming_exterior_lighting_power'].nil?\n nondimming_ext_lts_power = prototype_input['nondimming_exterior_lighting_power']\n nondimming_ext_lts_sch_name = prototype_input['nondimming_exterior_lighting_schedule']\n nondimming_ext_lts_name = 'NonDimming Exterior Lights'\n nondimming_ext_lts_def = OpenStudio::Model::ExteriorLightsDefinition.new(self)\n nondimming_ext_lts_def.setName(\"#{nondimming_ext_lts_name} Def\")\n nondimming_ext_lts_def.setDesignLevel(nondimming_ext_lts_power)\n nondimming_ext_lts_sch = self.add_schedule(nondimming_ext_lts_sch_name)\n nondimming_ext_lts = OpenStudio::Model::ExteriorLights.new(nondimming_ext_lts_def, nondimming_ext_lts_sch)\n nondimming_ext_lts.setName(\"#{nondimming_ext_lts_name} Def\")\n nondimming_ext_lts.setControlOption('AstronomicalClock')\n end\n\n # Fuel Equipment, As Exterior:FuelEquipment is not supported by OpenStudio yet,\n # temporarily use Exterior:Lights and set the control option to ScheduleNameOnly\n # todo: change it to Exterior:FuelEquipment when OpenStudio supported it.\n unless prototype_input['exterior_fuel_equipment1_power'].nil?\n fuel_ext_power = prototype_input['exterior_fuel_equipment1_power']\n fuel_ext_sch_name = prototype_input['exterior_fuel_equipment1_schedule']\n fuel_ext_name = 'Fuel equipment 1'\n fuel_ext_def = OpenStudio::Model::ExteriorLightsDefinition.new(self)\n fuel_ext_def.setName(\"#{fuel_ext_name} Def\")\n fuel_ext_def.setDesignLevel(fuel_ext_power)\n fuel_ext_sch = self.add_schedule(fuel_ext_sch_name)\n fuel_ext_lts = OpenStudio::Model::ExteriorLights.new(fuel_ext_def, fuel_ext_sch)\n fuel_ext_lts.setName(\"#{fuel_ext_name}\")\n fuel_ext_lts.setControlOption('ScheduleNameOnly')\n end\n\n unless prototype_input['exterior_fuel_equipment2_power'].nil?\n fuel_ext_power = prototype_input['exterior_fuel_equipment2_power']\n fuel_ext_sch_name = prototype_input['exterior_fuel_equipment2_schedule']\n fuel_ext_name = 'Fuel equipment 2'\n fuel_ext_def = OpenStudio::Model::ExteriorLightsDefinition.new(self)\n fuel_ext_def.setName(\"#{fuel_ext_name} Def\")\n fuel_ext_def.setDesignLevel(fuel_ext_power)\n fuel_ext_sch = self.add_schedule(fuel_ext_sch_name)\n fuel_ext_lts = OpenStudio::Model::ExteriorLights.new(fuel_ext_def, fuel_ext_sch)\n fuel_ext_lts.setName(\"#{fuel_ext_name}\")\n fuel_ext_lts.setControlOption('ScheduleNameOnly')\n end\n\n OpenStudio::logFree(OpenStudio::Info, 'openstudio.model.Model', 'Finished adding exterior lights')\n \n return true\n end", "def air_loop_hvac_demand_control_ventilation_required?(air_loop_hvac, climate_zone)\n OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', \"For #{template} #{climate_zone}: #{air_loop_hvac.name}: DCV is not required for any system.\")\n dcv_required = false\n return dcv_required\n end", "def add_time_zone_info(offset_hours_std = -8, offset_hours_dst = -7)\n base_bias = (-1 * offset_hours_std * 60).to_s\n standard_bias = '0'\n savings_bias = (offset_hours_std - offset_hours_dst).to_s\n @node.add(\"#{NS_EWS_TYPES}:TimeZone\") do |tz|\n tz.add(\"#{NS_EWS_TYPES}:Bias\", base_bias) # e.g. '480'\n tz.add(\"#{NS_EWS_TYPES}:StandardTime\") do |stime|\n stime.add(\"#{NS_EWS_TYPES}:Bias\", standard_bias) # e.g. '0'\n stime.add(\"#{NS_EWS_TYPES}:Time\", '02:00:00')\n stime.add(\"#{NS_EWS_TYPES}:DayOrder\", '1')\n stime.add(\"#{NS_EWS_TYPES}:Month\", '11')\n stime.add(\"#{NS_EWS_TYPES}:DayOfWeek\", 'Sunday')\n end\n tz.add(\"#{NS_EWS_TYPES}:DaylightTime\") do |dtime|\n dtime.add(\"#{NS_EWS_TYPES}:Bias\", savings_bias) # e.g. '-60'\n dtime.add(\"#{NS_EWS_TYPES}:Time\", '02:00:00')\n dtime.add(\"#{NS_EWS_TYPES}:DayOrder\", '2')\n dtime.add(\"#{NS_EWS_TYPES}:Month\", '3')\n dtime.add(\"#{NS_EWS_TYPES}:DayOfWeek\", 'Sunday')\n end\n end\n end", "def add_baseline_economizer(template, climate_zone)\n \n end", "def defineSaturdaySundayAndWendnesdayAsHoliday\n Setting['plugin_redmine_workload']['general_workday_monday'] = 'checked';\n Setting['plugin_redmine_workload']['general_workday_tuesday'] = 'checked';\n Setting['plugin_redmine_workload']['general_workday_wednesday'] = '';\n Setting['plugin_redmine_workload']['general_workday_thursday'] = 'checked';\n Setting['plugin_redmine_workload']['general_workday_friday'] = 'checked';\n Setting['plugin_redmine_workload']['general_workday_saturday'] = '';\n Setting['plugin_redmine_workload']['general_workday_sunday'] = '';\n end", "def zones_add name:, zgID:, adtype: \n call_adglare_api 'zones_add', {zgID: zgID, adtype: adtype, name: name}\n end", "def enable_demand_control_ventilation()\n\n # Get the OA intake\n controller_oa = nil\n controller_mv = nil\n if self.airLoopHVACOutdoorAirSystem.is_initialized\n oa_system = self.airLoopHVACOutdoorAirSystem.get\n controller_oa = oa_system.getControllerOutdoorAir \n controller_mv = controller_oa.controllerMechanicalVentilation\n if controller_mv.demandControlledVentilation == true\n OpenStudio::logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', \"For #{self.name}: DCV was already enabled.\")\n return true\n end\n else\n OpenStudio::logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', \"For #{self.name}: Could not enable DCV since the system has no OA intake.\")\n return false\n end\n \n # Change the min flow rate in the controller outdoor air\n controller_oa.setMinimumOutdoorAirFlowRate(0.0)\n \n # Enable DCV in the controller mechanical ventilation\n controller_mv.setDemandControlledVentilation(true)\n\n return true\n\n end", "def set_default_times\n if !self.start\n return\n end\n\n if self.start.hour == 0 # hour set to 0 if not otherwise defined...\n self.start = self.start + 9.hours\n end\n\n if !self.end\n if self.online?\n self.end = self.start + 1.hour\n else\n diff = 17 - self.start.hour\n self.end = self.start + diff.hours\n end\n end\n # TODO: Set timezone for online events. Where to get it from, though?\n # TODO: Check events form to add timezone autocomplete.\n # Get timezones from: https://timezonedb.com/download\n\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a planet based on user's inputs
def generate_planet puts "\nLet's create a planet from scratch." print "Please enter its name first: " name = gets.chomp print "What's its diameter of this planet in km? " diameter = gets.chomp.to_f print "What's its mass in kg? (example of input format: 3.30 x 10^23 ) " mass = gets.chomp print "What's the year length of this planet in days? " yr_length = gets.chomp.to_f print "What's the distance from the sun to this planet in km? " dis_from_sun = gets.chomp.to_f print "How many moons does this planet have? Enter 0 if there is none. " moons = gets.chomp.to_i planet = Planet.new({"name" => name, "diameter" => diameter, "mass" => mass, "yr_length" => yr_length, "dis_from_sun" => dis_from_sun, "moons" => moons}) return planet end
[ "def build_planet()\n puts \"\\nAdding planet. Please tell me more about this planet.\"\n \n print \"Enter the planet name: \"\n name = gets.chomp.capitalize\n \n print \"\\nEnter the planet color: \"\n color = gets.chomp.downcase\n \n print \"\\nEnter planet mass in kg: \"\n mass_kg = gets.chomp.to_f\n \n print \"\\nEnter planet's distance from the sun in km: \"\n distance_from_sun_km = gets.chomp.to_f\n \n print \"\\nEnter a fun fact about the planet: \"\n fun_fact = gets.chomp\n \n return Planet.new(name, color, mass_kg, distance_from_sun_km, fun_fact)\n end", "def create_planet\n puts \"Name?\"\n user_planet_name = gets.chomp\n puts \"Size?\"\n user_planet_size = gets.chomp\n puts \"Color?\"\n user_planet_color = gets.chomp\n puts \"Type?\"\n user_planet_type = gets.chomp\n puts \"How many moons?\"\n user_planet_moons = gets.chomp\n # Create a new object if the user wants to create a new planet\n return Planet.new(user_planet_name, user_planet_size, user_planet_color, user_planet_type, user_planet_moons)\n end", "def define_new_planet\n print \"\\nWhat is the name of the planet? \"\n planet_name = gets.chomp.capitalize\n print \"What is the diameter of #{planet_name} (in miles)? \"\n planet_diameter = gets.chomp.to_i\n print \"What is #{planet_name}'s distance from the sun (in millions of miles): \"\n planet_distance_from_sun = gets.chomp.to_f\n print \"What is the #{planet_name}'s year length (in Earth years)? \"\n planet_year_length = gets.chomp.to_f\n print \"How many moon's does #{planet_name} have? \"\n planet_moons = gets.chomp.to_i\n return new_planet = Planet.new(planet_name, planet_diameter, planet_distance_from_sun, planet_year_length, planet_moons)\nend", "def instantiate_sun_and_planets\n sun = SolarSystem.new(\"Sun\")\n \n mars = Planet.new(\"Mars\", \"red\", 6.4171e23, 230000000, \"Mars has 2 moons: Phobos and Deimos\")\n jupiter = Planet.new(\"Jupiter\", \"orange & brown\", 1.8982e27, 778000000, \"Jupiter has 79 known moons; its largest moon has a bigger diameter than Mercury\")\n mercury = Planet.new(\"Mercury\", \"red\", 0.330e24, 57e6, \"Mercury has no moons 😢\")\n venus = Planet.new(\"Venus\", \"yellow\", 4.87e24, 108e6, \"Venus has no moons 😢 \")\n earth = Planet.new(\"Earth\", \"blue-green\", 5.972e24, 1.496e8, \"Earth has one singular and beautiful moon\")\n \n sun.add_planet(mars)\n sun.add_planet(jupiter)\n sun.add_planet(mercury)\n sun.add_planet(venus)\n sun.add_planet(earth)\n \n return sun\nend", "def add_planet\n planet_variables = [\"name\",\"color\",\"mass (kg)\",\"distance from sun (km)\",\"fun fact\"]\n new_planet_args = []\n\n puts \">>>>>>> ADDING NEW PLANET:\"\n\n planet_variables.each do |variable|\n print \"New planet #{variable} > \"\n input = gets.chomp\n until valid_planet_arg?(input, variable)\n print \"That's not valid input for the new planet's #{variable}. Try again > \"\n input = gets.chomp\n end\n new_planet_args << input\n end\n @solar_system.add_planet(Planet.new(*new_planet_args))\n end", "def planet; end", "def add_planet_from_user\n print \"What is the name of the planet you would like to add? \"\n name = gets.chomp.capitalize\n\n print \"What color is the planet? \"\n color = gets.chomp.downcase\n\n print \"What is the mass of the planet in kilograms? \"\n mass = gets.chomp.to_i\n\n print \"How far away is the planet from the sun in kilometers? \"\n distance = gets.chomp.to_i\n\n print \"Let's add a fun fact about the planet! Complete the sentence. #{name}..\"\n fact = gets.chomp.downcase\n\n new_planet = Planet.new(name, color, mass, distance, fact)\n return new_planet\n end", "def user_create_planet(solar_system)\n\tputs \"What is the name of the planet?\"\n\tuser_planet_name = gets.chomp.capitalize\n\n\tputs \"What color is #{user_planet_name}?\"\n\tuser_planet_color = gets.chomp.downcase\n\n\tputs \"What is its mass in kilograms?\"\n\tuser_planet_mass = verify_number(gets.chomp)\n\n\tputs \"What distance is the planet from the sun (in kilometers)?\"\n\tuser_planet_distance = verify_number(gets.chomp)\n\n\tputs \"Can you share a fun fact about #{user_planet_name}?\"\n\tuser_planet_fun_fact = gets.chomp.capitalize\n\n\tuser_planet = Planet.new(user_planet_name,user_planet_color, user_planet_mass,user_planet_distance,user_planet_fun_fact)\n\tsolar_system.add_planet(user_planet)\nend", "def planet\n sample(planets)\n end", "def main\n solar_system = SolarSystem.new('Sol')\n earth = Planet.new('Earth', 'blue-green', 5.972e24, 1.496e8, 'only planet known to support life')\n mars = Planet.new('Mars', 'red', 6.39e23, 2.279e8, 'named after the Roman God of War')\n mercury = Planet.new('Mercury', 'gray', 3.3011e23, 77e7, 'has the shortest orbital period, 87.97 days')\n\n solar_system.add_planet(earth)\n solar_system.add_planet(mars)\n solar_system.add_planet(mercury)\n\n puts \"Great, we've added some planets.\"\n puts \"Select the number of the action you would like to do next:\"\n puts \"1. List planets\"\n puts \"2. Explore planet details\"\n puts \"3. Add a planet\"\n puts \"4. Exit\"\n \n user_input = gets.chomp.to_i\n\n if user_input == 1\n solar_system.list_planets\n elsif user_input == 2\n puts \"Great! What planet would you like to learn about?\"\n planet_to_search = gets.chomp\n solar_system.find_planet_by_name(planet_to_search)\n elsif user_input == 3\n puts \"FUN! Let's do this. We'll need a few details, so let's get started.\"\n print \"Name --> \"\n planet_name = gets.chomp\n print \"Color --> \"\n planet_color = gets.chomp\n print \"Mass (in kg) --> \"\n planet_mass = gets.chomp.to_i\n print \"Distance from sun (in km) --> \"\n planet_distance = gets.chomp.to_i\n print \"Fun fact --> \"\n planet_fact = gets.chomp\n planet_name = Planet.new(planet_name, planet_color, planet_mass, planet_distance, planet_fact)\n solar_system.add_planet(planet_name)\n solar_system.list_planets\n elsif user_input == 4\n Exit\n end\n\n #solar_system.find_planet_by_name('Venus')\n\nend", "def generer_planetes( n )\n (0...n).map do |i|\n Planete.new( \"#{i}\", 0, rand(10E+15), rand_vector, rand_vector )\n end\nend", "def add_new_planet our_solar_system\n puts \"Please enter the planet name\"\n planet_name = gets.chomp.capitalize\n print \"Please enter the length of time the planet takes to go around its star in earth days. ➤ \"\n year_length = gets.chomp.to_f.round(2)\n print \"Please enter how far is the planet from the sun in kilometers. ➤ \"\n distance_from_the_sun = gets.chomp.to_f.round(2)\n print \"Please enter the mass of a planet in kilograms. ➤ \"\n mass = gets.chomp\n print \"Please enter a diameter of the planet in kilometers. ➤ \"\n diameter = gets.chomp.to_f.round(2)\n print \"Please enter what is the composition of the atmosphere. ➤ \"\n atmospheric_components = gets.chomp\n\n new_planet = Planet.new(planet_name, year_length, distance_from_the_sun, mass, diameter, atmospheric_components)\n our_solar_system.add_planet(new_planet)\n puts \"New planet #{planet_name} is added.\".red\nend", "def planet\n fetch('stargate.planets')\n end", "def mk_systeme( n )\n planetes = (0...n).map do |i|\n Planete.new( \"#{i}\",\n 0,\n rand(10E+15),\n Vector[rand(10E+10), rand(10E+10)],\n Vector[rand(10E+10), rand(10E+10)]\n )\n end\n\n SystemePlanetaire.new( *planetes )\nend", "def main\n # let's user know what to expect\n puts \"Fill in the information below to create a planet within your solar system.\"\n\n # user names their solar system so\n # new solar system is created that can be\n # accessed throughout the code\n print \"Name your solar system: \"\n solar_system_name = gets.chomp.to_s\n solar_system_name = SolarSystem.new(solar_system_name)\n\n # calls add_new_planet method to create new planet\n add_new_planet(solar_system_name)\n\n # default value is nil until user enters input\n yes_or_no = nil\n # until user doesn't want to add a new planet\n # user will be asked to add new planet\n until yes_or_no == \"no\"\n # asks for user input\n print \"\\nAdd another planet? (yes/no): \"\n yes_or_no = gets.chomp.to_s\n\n # if user wants to add new planet\n # user will be asked the same questions when\n # they were asked to add the first planet\n if yes_or_no =~ /[yY][eE][sS]/\n add_new_planet(solar_system_name)\n # if user doesn't want to add new planet\n # they are given a few options to proceed\n elsif yes_or_no =~ /[nN][oO]/\n # default value of user_options is nil\n user_options = nil\n\n # until user wants to exit, options will\n # continue to show up\n until user_options == \"3\"\n # asks user to make decision\n print \"\\nOptions:\\n1. List Planets\\n2. Search Planet Details\\n3. Exit\\n\"\n print \"\\nYour choice (1/2/3): \"\n user_options = gets.chomp.to_s\n\n # user will be shown the list of planets\n if user_options =~ /[1]/ && user_options.length == 1\n list = solar_system_name.list_planets\n puts \"\\n#{list}\"\n # user will be shown the details of the planet\n # they want to learn about\n elsif user_options =~ /[2]/ && user_options.length == 1\n planet_details(solar_system_name)\n # user will exit the program completely\n elsif user_options =~ /[3]/ && user_options.length == 1\n puts \"Goodbye!\\n\"\n end\n end\n end\n end\nend", "def planet\n fetch('dune.planets')\n end", "def main\n # Creating a solar systeme\n solar_system = SolarSystem.new('Sun')\n\n # Creating planet earth\n earth = Planet.new('Earth', 'blue-green', 5.972e24, 1.496e8, 'Only planet known to support life')\n # Adding planet earth to the list\n solar_system.add_planets(earth)\n\n # creating planet mars\n mars = Planet.new('Mars', 'red', 6.420e23, 2.279e8, 'It is the second smallest planet')\n\n # adding planet mars to the list\n solar_system.add_planets(mars)\n\n # Creating planent jupiter\n jupiter = Planet.new('Jupiter', 'pearl', 1.898e27, 7.785e8, 'The largest planet in the solar system')\n\n # Adding planet jupiter to the list\n solar_system.add_planets(jupiter)\n\n message_to_user(solar_system)\n\nend", "def add_planet_to_list (solar_system)\n print \"What is the name of the planet? \"\n name = gets.chomp.capitalize\n print \"What color is the planet? \"\n color = gets.chomp\n print \"What is the mass in kg? \"\n mass = gets.chomp.to_f\n print \"What is the distance from the sun? \"\n distance_from_sun = gets.chomp.to_f\n print \"Name one fun fact about this planet: \"\n fun_fact = gets.chomp\n\n new_planet = Planet.new(name, color, mass, distance_from_sun, fun_fact)\n solar_system.add_planet(new_planet)\nend", "def planet\n fetch('hitchhikers_guide_to_the_galaxy.planets')\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
def decimal_base(n) ten_to_position = 1 loop do n = 1 break if n == 0 ten_to_position = 10 end ten_to_position end
def decimal_base(n) 10**(n-1) end
[ "def super_digit(n)\n\n # return n for all one digit n values \n if n < 10\n return n\n end\n\n # add each digit, peeling of last one in place each time\n return super_digit(n % 10 + super_digit(n/10))\n\nend", "def super_digit(n)\n while n > 9\n n = n % 10 + super_digit(n / 10)\n end\n return n\nend", "def base_converter(num, b)\n return \"\" if num == 0\n digits = ('0'..'9').to_a + ('a'..'f').to_a\n base_converter(num/b, b) + digits[num % b]\nend", "def digits(base=10)\n 1 + (Math.log(self) / Math.log(base)).floor\n end", "def floorInBase(n, base)\n return base * (n / base).floor\n end", "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 decimal(digits, base)\n e = digits.size - 1\n v = 0\n digits.each do |n|\n v += n.to_i * base**e\n e -= 1\n end\n v\n end", "def digital_root(n)\n n < 10 ? n : digital_root(n / 10 + n % 10)\nend", "def s(n)\n ((9*n-1)*(10**n)+1)/9\nend", "def nondec_digits(range,base=10,&b)\n yield 0 if range.first<=0\n (1..base-1).each { |x| nondec_digits_internal(x,x,range,base,&b) }\n end", "def find_nth_digit(n)\n base = 9\n digits = 1\n numbers_with_digits = base * digits \n while n > numbers_with_digits\n n -= numbers_with_digits\n digits += 1\n base *= 10\n numbers_with_digits = base * digits\n end\n (10 ** (digits - 1) + (n - 1) / digits).to_s[(n - 1)% digits].to_i\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 num_to_s (num, base)\n digits = []\n power = 0\n\n until num / (base**power) == 0\n digits.unshift (num / (base ** power) % base).to_s\n power += 1\n end\n\n digits.join('')\n\nend", "def last_n_digits(num, n)\r\n # your code goes here\r\n num % 10**n\r\nend", "def champernowne(n)\n # Find which base-10 'power' n belongs to.\n # (if it is ones, tens, hundreds, thousands, etc)\n power = 0\n 0.step do |d|\n if 9*(d+1) * 10**(d) >= n\n power = d\n break\n end\n end\n return n if power == 0\n digits = power + 1\n # Get all the numbers that we've passed through before reaching n.\n bounds = (0..(power-1)).map { |d| 9*(d+1) * 10**(d) }\n passed_indices = bounds.reduce(0, :+) # In the case where n is in [1, 9], bounds defaults to 0.\n normalized_position = n - passed_indices\n number = (10**power + (normalized_position - 1) / (digits)).to_s\n # This variable holds the index of the digit to be returned.\n normalized_index = normalized_position % digits\n return (normalized_index == 0 ? number[-1] : number[normalized_index-1]).to_i\nend", "def round_1_sig_fig n \n get_first_digit(n) * 10**length(n)\nend", "def breakdown(n)\n puts \"The digits of #{n} are: \"\n l=n.to_s.length\n while l>0 do \n a=n%10**(l)\n b=10**(l-1)\n puts a/b\n l-=1\n end\nend", "def round_1_sig_fig n \n get_first_digit(n) * 10**length(n)\nend", "def place_to_num(place, base = 10)\n place > 1 ? base**(place - 1) : 1\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the acceleration of a stepper, in (micro)steps per second squared, or raises an error.
def acceleration=(new_acceleration) Klass.setAcceleration(@handle, @index, new_acceleration.to_f) new_acceleration end
[ "def setAcceleration(acceleration)\n @acceleration = acceleration\n end", "def accelerate(new_speed)\n @speed = new_speed\n end", "def set_acceleration(acceleration)\n send_request(FUNCTION_SET_ACCELERATION, [acceleration], 'S', 0, '')\n end", "def acceleration=(value)\r\n if value.is_a? Array\r\n @acceleration_x, @acceleration_y = value\r\n else\r\n @acceleration_x, @acceleration_y = value, value\r\n end\r\n end", "def accelerate (rateOfAcceleration)\n @speed = @speed + rateOfAcceleration\n end", "def accelerate\n @speed = @speed + 10.0\n end", "def accelerate(time) \n @velocity += time * @acceleration;\n @velocity = @max_speed if @velocity > @max_speed\n end", "def accelerate(time)\n @velocity += time * @acceleration\n @velocity = @max_speed if @velocity > @max_speed\n end", "def accelerate\n self.current_speed += 1 \n end", "def accelerate(time)\n @velocity += time * @acceleration\n if(@velocity > @maxSpeed)\n @velocity = @maxSpeed\n end\n end", "def accelerate\n @speed += 25\n end", "def set_speed(new_speed:)\n if new_speed > 30\n new_speed = 30\n elsif new_speed < 0\n new_speed = 0\n end\n @curr_speed = new_speed \n end", "def accelerate\n @speed += 8\n end", "def step_acceleration(time, state)\n\t\t\n#\t\tpp state\n\n\t\tt1, t1p = state[0]\n\t\tt2, t2p = state[1]\n\t\tf = state[2][0]\n\n\t\t# modulo the positions\n#\t\tt1 = begin m = t1 % (2.0 * PI); m > PI ? -(PI - m) : m end\n#\t\tt2 = begin m = t2 % (2.0 * PI); m > PI ? -(PI - m) : m end\n\n\t\t# bind velocities\n\t\tt1p = (t1p < T1P_MIN) ? T1P_MIN : ((t1p > T1P_MAX) ? T1P_MAX : t1p)\n\t\tt2p = (t2p < T2P_MIN) ? T2P_MIN : ((t2p > T2P_MAX) ? T2P_MAX : t2p)\n\n\t\t# f\n#\t\tassert{ inputs.include?('F') }\n#\t\tf = inputs['F']\n#\t\tassert{ [0.0, -1.0, 1.0].include?(f) }\n\t\t\n\t\t# tau\n\t\ttau = f * TORQUE \n\n\t\t# phi 2\n\t\tphi2 = M2 * LC2 * G * cos(t1 + t2 - PI / 2.0)\n\n\t\t# phi 1\n\t\tphi1 = -M2 * L1 * LC2 * (t2p ** 2.0) * sin(t2) - 2.0 * M2 * L1 * LC2 * t2p * t1p * sin(t2) + (M1 * LC1 + M2 * L1) * G * cos(t1 - PI / 2.0) + phi2\n\n\t\t# d2\n\t\td2 = M2 * (LC2 ** 2.0 + L1 * LC2 * cos(t2)) + I2\n\n\t\t# d1\n\t\td1 = M1 * (LC1 ** 2.0) + M2 * ((L1 ** 2.0) + (LC2 ** 2.0) + 2.0 * L1 * LC2 * cos(t2)) + I1 + I2\n\n\t\t# t2pp\n\t\tt2pp = (tau + (d2 / d1) * phi1 - phi2) / (M2 * (LC2 ** 2.0) + I2 - (d2 ** 2.0) / d1)\n\n\t\t# t1pp\n\t\tt1pp = (d2 * t2pp + phi1) / -d1\n\n#\t\t$stderr << \"debug acceleration t1pp #{t1pp}, t2pp #{t2pp}\\n\"\n\t\tmask = 1_000_000_000_000_000\n\t\tt1pp = (t1pp * mask).to_i / mask.to_f\n\t\tt2pp = (t2pp * mask).to_i / mask.to_f\n#\t\tt1pp = (t1pp * 10_000).to_i / 10_000.0\n#\t\tt2pp = (t2pp * 10_000).to_i / 10_000.0\n\n\t\n\t\t[t1pp, t2pp, 0.0]\n\tend", "def set_Speed(value)\n set_input(\"Speed\", value)\n end", "def setSpeed(value)\r\n @speed = value\r\n end", "def car_accelerate()\n @speed += 10\n @fuel_level -= 5\nend", "def increase_speed amount\n error(\n \"Argument passed to #increment_speed must be a Float or Integer, but got\",\n \"#{seconds.inspect}:#{amount.class.name}\"\n ) unless ([Float, Integer].include? amount.class)\n @speed += amount\n end", "def set_speed(value)\n do_command(\"setSpeed\", [value,])\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the current position of a stepper, in (micro)steps, or raises an error.
def current_position=(new_current_position) Klass.setCurrentPosition(@handle, @index, new_current_position.to_i) new_current_position end
[ "def current_step=(value)\n @current_step = value\n end", "def next_step!\n self.stepper_current_step = self.next_step\n self\n end", "def stepper_target=(position)\n\t\t\t\traise ArgumentError.new \"Position must be an integer\" unless position.is_a? Fixnum\n\n\t\t\t\twrite(0x41, [position].pack(\"l>\"))\n\t\t\tend", "def next_step=(step)\n @next_step = step\n end", "def current_step=(step)\n @current_step = step\n end", "def set_position\n return if position.present?\n return self.position = 0 if participatory_process.steps.select(&:persisted?).empty?\n\n self.position = participatory_process.steps.maximum(:position) + 1\n end", "def next_step\n self.current_step = steps[steps.index(current_step)+1]\n end", "def progressSetPosition _obj, _args\n \"_obj progressSetPosition _args;\" \n end", "def set_invalid_steps(steps)\n self.invalid_steps = steps\n end", "def setpoint\n @setpoint\n end", "def move_prev\n self.step -= 1\n 'prev'\n end", "def test_set_step()\n @socket.write(ACTIVITIES[:set_step])\n\n # choose step to select and create new gradient step\n n, m, expectfail = choose_step()\n s = Step.generate()\n self.send_blob(\"#{n.chr}#{m.chr}#{s.stop.chr()}#{s.color.r.chr()}#{s.color.g.chr()}#{s.color.b.chr()}#{s.color.a.chr()}\")\n\n # handle result\n if not expectfail\n # expect success\n assert(RESULT_SCS, @socket.read(1))\n @images[@selected].styles[n].color.steps[m] = s\n else\n # expect failure\n assert(RESULT_FAL, @socket.read(1))\n end\n end", "def move(to)\n @position = to\n self\n end", "def stepper_position\n\t\t\t\tread(0x40, 4).pack(\"C*\").unpack(\"l>\")[0]\n\t\t\tend", "def set_step_exception(exception)\n @current_step.result = false\n @current_step.exception = exception\n end", "def previous_step!\n self.stepper_current_step = self.previous_step\n self\n end", "def push_step(position)\n # Get the next position\n current = @movement[:waypoints][:next].last\n current ||= @position[:current]\n log \"Current step: #{current.inspect}\"\n push_forward_step(current, position)\n end", "def setCurrentWaypoint _obj, _args\n \"_obj setCurrentWaypoint _args;\" \n end", "def target_position=(new_target_position)\n Klass.setTargetPosition(@handle, @index, new_target_position.to_i)\n\t new_target_position\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the engaged state of the Phidget.
def engaged=(new_state) tmp = new_state ? 1 : 0 Klass.setEngaged(@handle, @index, tmp) new_state end
[ "def set_gstate\n @p.set_gstate(self)\n end", "def put_hat_on\n self.hat_state = true\n end", "def set_state(is_on)\n @client.set_state(is_on)\n end", "def thing_state=(value)\n @children['thing-state'][:value] = value\n end", "def enter_in_using_skill_state\n @state = :using_skill\n @update_callback = :update_4_step_animation\n @update_callback_count = 0\n @prelock_direction = @direction\n @direction = 6\n update_appearance(0)\n end", "def soak\n self.state = \"soaked\"\n end", "def advance(state)\n @state = state\n end", "def pause=(state)\n @paused = state\n end", "def set_state(state)\n request = Http.put(\"#{@@apiserver}/machine/#{self.identifier}\", { \"state\" => state })\n logger.info \"#{Time.now} #{self.identifier}: setting state of VM to #{state}\"\n\n end", "def enter_in_giving_pokemon_state\n @state = :giving_pokemon\n @update_callback = :update_giving_pokemon_state\n @update_callback_count = 0\n @prelock_direction = @direction\n @direction = 2\n update_appearance(0)\n end", "def do_enter_state(state)\n @state = state\n @state_at[@state] = Time.now\n end", "def set_PostState(value)\n set_input(\"PostState\", value)\n end", "def state=(new_state)\n self.hmd_states.build(state: new_state)\n self.current_state = new_state.to_sym\n end", "def set_state(state)\n # Sets state of a VM\n request = Http.put(\"#{@@apiserver}/machine/#{self.identifier}\", { \"state\" => state })\n logger.info \"#{Time.now} #{self.identifier}: setting state of VM to #{state}\"\n\n end", "def toggle_state\n if state == :current\n self.state = :historical\n elsif state == :historical\n self.state = :current\n end\n\n Inkblot::Display.again\n end", "def enter_state\n end", "def state=(state)\n @state = state\n notify\n end", "def set_published_state\n self.published = payload[\"isLivingLegend\"]\n end", "def update_view\n set_foreground(Qt::Brush.new(STATE_COLORS[state]))\n set_tool_tip(\"State: #{state}\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the target position of a stepper, in (micro)steps, or raises an error.
def target_position=(new_target_position) Klass.setTargetPosition(@handle, @index, new_target_position.to_i) new_target_position end
[ "def stepper_target=(position)\n\t\t\t\traise ArgumentError.new \"Position must be an integer\" unless position.is_a? Fixnum\n\n\t\t\t\twrite(0x41, [position].pack(\"l>\"))\n\t\t\tend", "def setup_move_to_target\n return unless PONY::ERRNO.check_sequence(current_act)\n stop_all_movements\n xpos = target.x + (flip ? -@acts[1] : @acts[1])\n ypos = target.y + @acts[2]\n goto(xpos, ypos, @acts[3], @acts[4], @acts[5] || 0)\n end", "def setup_target_move\n return unless PONY::ERRNO::check_sequence(current_act)\n args = [@acts[1], @acts[2], @acts[3], @acts[4], @acts[5] || 0]\n current_action_targets.each do |target|\n target.goto(*args)\n end\n end", "def move(to)\n @position = to\n self\n end", "def next_step=(step)\n @next_step = step\n end", "def move_to(target, lp = nil)\n current = position_value\n if target != current\n checked_transaction do\n ds = list_dataset\n op, ds = if target < current\n target = 1 if target < 1\n [:+, ds.where(position_field=>target...current)]\n else\n lp ||= last_position\n target = lp if target > lp\n [:-, ds.where(position_field=>(current + 1)..target)]\n end\n ds.update(position_field => Sequel::SQL::NumericExpression.new(op, position_field, 1))\n update(position_field => target)\n end\n end\n self\n end", "def current_step=(value)\n @current_step = value\n end", "def target=(new_value)\n @target = new_value unless const_defined?(:Target)\n end", "def set_invalid_steps(steps)\n self.invalid_steps = steps\n end", "def test_set_step()\n @socket.write(ACTIVITIES[:set_step])\n\n # choose step to select and create new gradient step\n n, m, expectfail = choose_step()\n s = Step.generate()\n self.send_blob(\"#{n.chr}#{m.chr}#{s.stop.chr()}#{s.color.r.chr()}#{s.color.g.chr()}#{s.color.b.chr()}#{s.color.a.chr()}\")\n\n # handle result\n if not expectfail\n # expect success\n assert(RESULT_SCS, @socket.read(1))\n @images[@selected].styles[n].color.steps[m] = s\n else\n # expect failure\n assert(RESULT_FAL, @socket.read(1))\n end\n end", "def set_move_target cf=current_file\n ff = expand_path(cf)\n return unless File.directory? ff\n\n @move_target = ff\n message \"Move target set to #{cf}.\"\nend", "def move_towards_target\t\t\t\r\n if @x_target && @x != @x_target\r\n x_step = @x_target - @x\r\n self.x = @x + x_step * (1.0 - @x_lag)\r\n end\r\n \r\n if @y_target && @y != @y_target\r\n y_step = @y_target - @y\r\n self.y = @y + y_step * (1.0 - @y_lag)\r\n end\r\n end", "def run_to_relative_position(desired_position)\n ensure_valid_speed\n old_position = position\n\n LegoEv3::Commands::TachoMotor.set_position_sp!(@connection, @id, old_position + desired_position)\n LegoEv3::Commands::TachoMotor.run_to_abs_pos!(@connection, @id)\n\n loop do\n break if operation_completed?(old_position)\n end\n\n position\n end", "def move=(value)\n @move = value\n end", "def step_rotate\n # set new target if no target set yet, or target is reached\n @target_rotation = generate_target_rotation if @target_rotation.nil? || target_rotation_distance.abs < 0.1\n # \"rotate\" by increasing the current roation with step_rotation_distance\n @rotation = rotation + step_rotation_distance\n end", "def next_step!\n self.stepper_current_step = self.next_step\n self\n end", "def progressSetPosition _obj, _args\n \"_obj progressSetPosition _args;\" \n end", "def setup_target_slide\n return TSBS.error(@acts[0], 4, @used_sequence) if @acts.size < 5\n args = [@acts[1], @acts[2], @acts[3], @acts[4], @acts[5] || 0]\n if area_flag\n target_array.each do |target|\n target.slide(*args)\n end\n return\n end\n target.slide(*args)\n end", "def target=(value)\n @target = value\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the velocity limit of a stepper, in (micro)steps per second, or raises an error.
def velocity_limit=(new_velocity_limit) Klass.setVelocityLimit(@handle, @index, new_velocity_limit.to_f) new_velocity_limit end
[ "def velocity_limit=(new_velocity_limit)\n Klass.setVelocityLimit(@handle, @index, new_velocity_limit.to_f)\n new_velocity_limit\n end", "def setVelocity(velocity)\n @velocity = velocity\n end", "def limit(velocity_limit)\r\n velocity_norm = @velocity.norm\r\n if velocity_norm > velocity_limit\r\n @velocity.mul(velocity_limit / velocity_norm)\r\n end\r\n end", "def speed_limit=(vector_or_shared_value)\n if vector_or_shared_value.kind_of? Numeric\n axis_limit_x = axis_limit_y = vector_or_shared_value / Jemini::Math::SQUARE_ROOT_OF_TWO\n else\n axis_limit_x = vector_or_shared_value.x\n axis_limit_y = vector_or_shared_value.y\n end\n @body.set_max_velocity(axis_limit_x, axis_limit_y)\n end", "def set_max_velocity(velocity)\n send_request(FUNCTION_SET_MAX_VELOCITY, [velocity], 'S', 0, '')\n end", "def velocity=(velocity)\n @velocity = velocity\n end", "def set_speed(new_speed:)\n if new_speed > 30\n new_speed = 30\n elsif new_speed < 0\n new_speed = 0\n end\n @curr_speed = new_speed \n end", "def limit_velocity\n speed = Math.sqrt(@body.vel.x ** 2 + @body.vel.y ** 2)\n if speed > MAX_VELOCITY\n vel_cos = @body.vel.x / speed\n vel_sin = @body.vel.y / speed\n rot_matrix = Matrix[[vel_cos, -vel_sin], [vel_sin, vel_cos]]\n new_vel_cos, new_vel_sin = (rot_matrix * Matrix[[MAX_VELOCITY], [0]]).to_a.flatten\n\n @body.vel = CP::Vec2.new(new_vel_cos, new_vel_sin)\n end\n end", "def setSpeed(value)\r\n @speed = value\r\n end", "def scale_vel_vector(factor)\n @m_Velocity.mul(factor)\n end", "def set_Speed(value)\n set_input(\"Speed\", value)\n end", "def velocity(val = nil)\n val.nil? ? @state.velocity : @state.velocity = val\n end", "def set_speed(value)\n do_command(\"setSpeed\", [value,])\n end", "def sliderSetSpeed _obj, _args\n \"_obj sliderSetSpeed _args;\" \n end", "def speed=(ms)\n exec_command(\"setSpeed\", {\"speed\"=>ms})\n end", "def set_speed(ms)\n exec_command(\"setSpeed\", {\"speed\"=>ms})\n end", "def setVelocity _obj, _args\n \"_obj setVelocity _args;\" \n end", "def speed=(value)\n @speed = value\n end", "def setMaxSpeed(maxSpeed)\n @maxSpeed = maxSpeed;\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a NxN grid of points on a face of the cube. Note that this will generate (N+1)(N+1) points. Each point is projected on the sphere and stored in an array. Note that all these are points on the unit sphere, and so their distance to the origin is 1, and so each point can be used as its own normal.
def grid(face, n) dx = 2.0/n dy = 2.0/n a = Array.new n += 1 n.times do |j| y = -1.0 + j*dy n.times do |i| x = -1.0 + i*dx lon, lat = QuadSphere::CSC.inverse(face, x, y) sx = Math::cos(lat) * Math::cos(lon) sy = Math::cos(lat) * Math::sin(lon) sz = Math::sin(lat) a << [sx,sy,sz] end end a end
[ "def grid\n (0...@height).map do |y|\n (0...@width).map do |x|\n yield cube(x,y)\n end\n end\n end", "def points_to_grid(points, width, height, zeroItem = 0, oneItem=1)\n grid = Grid.new(width, height, zeroItem) \n points.each {|point| grid[int_point(point)] = oneItem} \n return grid \n end", "def grid(n, m)\n Array.new(n) { Array.new(m) }\nend", "def MakeSphere(positionR, radius, ra, dec)\r\n pointNum = 100\r\n i = 0\r\n while i < pointNum do\r\n j = 0\r\n while j < pointNum do\r\n l_theta = cycle * i.to_f / pointNum.to_f\r\n l_phi = cycle * j.to_f / pointNum.to_f\r\n\r\n # Central coordinate\r\n x = positionR * Math.cos(ra) *Math.cos(dec)\r\n y = positionR * Math.sin(ra) * Math.cos(dec)\r\n z = positionR * Math.sin(dec)\r\n\r\n # Each point\r\n x = x + radius * Math.cos(l_phi) * Math.sin(l_theta)\r\n y = y + radius * Math.sin(l_phi) * Math.sin(l_theta)\r\n z = z + radius * Math.cos(l_theta)\r\n\r\n # To rotate the coordinate\r\n zz =- x # Go well and for some reason put minus.\r\n xx = y\r\n yy = z\r\n\r\n # plot\r\n GL.Vertex3d(xx, yy, zz)\r\n j = j + 1\r\n end\r\n i = i + 1\r\n end\r\nend", "def parallelizable_meshpoints\n approximate_grid_size / ntheta\nend", "def createslicemeshes(grid, x = nil, y = nil, z = nil, step = nil, offset = nil)\n if [x, y, z].all?(&:nil?)\n x = 0.5\n y = 0.5\n z = 0.5\n end\n mesh_x = (createxslicemesh(grid, x, step, offset) if x)\n mesh_y = (createyslicemesh(grid, y, step, offset) if y)\n mesh_z = (createzslicemesh(grid, z, step, offset) if z)\n [mesh_x, mesh_y, mesh_z]\n end", "def generate_grid\n grid = []\n @y.times do\n row = []\n @x.times do\n row << nil\n end\n grid << row\n end\n grid\n end", "def grid(n, m)\n arr = Array.new(n) { Array.new(m, :N) }\n arr\nend", "def grid(n, m)\n Array.new(n) { Array.new(m) } # use {} block to make subarrays\nend", "def grid(n, m)\n Array.new(n) { Array.new(n) } # If you attempted to write this as Array.new(n, Array.new(m)) the contents would be repeated for each array rather\nend", "def generate_grid x = @x, y = @y\n new_grid = []\n\n y.times { new_grid << [] }\n new_grid.each do |array|\n x.times do\n array << []\n end\n end\n end", "def generate_points(n, radius)\n n.times.map do\n random_radius = rand * radius\n random_angle = rand * 2 * Math::PI\n x = random_radius * Math.cos(random_angle)\n y = random_radius * Math.sin(random_angle)\n\n [x, y]\n end\nend", "def create_starting_grid()\n grid_values = []\n for a in 1..9\n for b in 1..9\n point_value = [a, b, \"S\"]\n grid_values << point_value \n end\n end\n return grid_values\n end", "def new_cube(n)\r\n return n*n*n,70;\r\nend", "def create_grid\n grid = Array.new(6, Array.new(7, BLANK))\n end", "def three_row_grid\n grid = []\n grid << [\n Cell.new(:alive, 0, 0),\n Cell.new(:alive, 0, 1),\n Cell.new(:dead, 0, 2)\n ]\n grid << [\n Cell.new(:alive, 1, 0),\n Cell.new(:dead, 1, 1),\n Cell.new(:dead, 1, 2)\n ]\n grid << [\n Cell.new(:dead, 2, 0),\n Cell.new(:dead, 2, 1),\n Cell.new(:dead, 2, 2)\n ]\n grid\nend", "def grid\n Matrix.build(@row_count, @column_count) { Cell.new }.to_a\n end", "def points(num_points, prime)\n intercept = @coefficients[0] # the first coefficient is the intercept\n (1..num_points).map do |x|\n y = intercept\n (1...@coefficients.length).each do |i|\n y = (y + @coefficients[i] * x ** i) % prime\n end\n Point.new(x, y)\n end\n end", "def get_grid(x, y)\n grid = Array.new(x) {Array.new(y){0}}\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
p grid(0, 3) Create triangle strips to represent a NxN mesh. The given array should then contain (N+1)2 points, arranged as N+1 rows of N+1 points.
def mesh2strips(n,a) dx = 2.0/n dy = 2.0/n row = n+1 n.times do |j| glBegin(GL_TRIANGLE_STRIP) rowi = j*row row.times do |x| add_vertex(a[rowi+x]) add_vertex(a[rowi+row+x]) end glEnd end end
[ "def grid(n, m)\n Array.new(n) { Array.new(m) }\nend", "def grid(face, n)\n dx = 2.0/n\n dy = 2.0/n\n a = Array.new\n n += 1\n\n n.times do |j|\n y = -1.0 + j*dy\n n.times do |i|\n x = -1.0 + i*dx\n lon, lat = QuadSphere::CSC.inverse(face, x, y)\n sx = Math::cos(lat) * Math::cos(lon)\n sy = Math::cos(lat) * Math::sin(lon)\n sz = Math::sin(lat)\n a << [sx,sy,sz]\n end\n end\n\n a\n end", "def grid(n, m)\n Array.new(n) { Array.new(n) } # If you attempted to write this as Array.new(n, Array.new(m)) the contents would be repeated for each array rather\nend", "def grid(n, m)\n Array.new(n) { Array.new(m) } # use {} block to make subarrays\nend", "def grid(n, m)\n arr = Array.new(n) { Array.new(m, :N) }\n arr\nend", "def triangle_array(n)\n array = []\n 1.upto(n) do |i|\n array << i * (i + 1) / 2\n end\n \n array\nend", "def pascals_triangle(n)\n triangle = [[1]]\n\n (1...n).each do |lvl_idx| # levels of pyramid by array idx\n current_lvl = []\n prev_lvl = triangle[lvl_idx - 1] \n\n (0..lvl_idx).each do |pos| # elements of level\n left = (pos == 0) ? 0 : prev_lvl[pos - 1]\n right = (pos == lvl_idx) ? 0 : prev_lvl[pos]\n current_lvl[pos] = left + right\n end\n triangle << current_lvl\n end\n triangle\nend", "def create_grid\n grid = Array.new(6, Array.new(7, BLANK))\n end", "def createslicemeshes(grid, x = nil, y = nil, z = nil, step = nil, offset = nil)\n if [x, y, z].all?(&:nil?)\n x = 0.5\n y = 0.5\n z = 0.5\n end\n mesh_x = (createxslicemesh(grid, x, step, offset) if x)\n mesh_y = (createyslicemesh(grid, y, step, offset) if y)\n mesh_z = (createzslicemesh(grid, z, step, offset) if z)\n [mesh_x, mesh_y, mesh_z]\n end", "def three_row_grid\n grid = []\n grid << [\n Cell.new(:alive, 0, 0),\n Cell.new(:alive, 0, 1),\n Cell.new(:dead, 0, 2)\n ]\n grid << [\n Cell.new(:alive, 1, 0),\n Cell.new(:dead, 1, 1),\n Cell.new(:dead, 1, 2)\n ]\n grid << [\n Cell.new(:dead, 2, 0),\n Cell.new(:dead, 2, 1),\n Cell.new(:dead, 2, 2)\n ]\n grid\nend", "def triangulate(vertices)\n\t\tedges = []\n tris = []\n # sort by X coord\n vertices = vertices.sort_by {|p|p.x}\n # center/radius cache used by circum_circle\n cc_cache = {}\n\n # Set up the supertriangle\n # This is a triangle which encompasses all the sample points.\n # The supertriangle coordinates are added to the end of the\n # vertex list. The supertriangle is the first triangle in\n # the triangle list.\n number_of_vertices = vertices.size\n\t\tbounding_p1, bounding_p2, bounding_p3 = get_bounding_vertices(vertices)\n\t\tvertices << bounding_p1 << bounding_p2 << bounding_p3\n\t\ttris << ITRIANGLE.new(number_of_vertices, number_of_vertices+1, number_of_vertices+2)\n\n # Include each point one at a time into the existing mesh\n vertices.each_with_index { |current_point, i|\n edges.clear\n # Set up the edge buffer.\n # If the point (xp,yp) lies inside the circumcircle then the\n # three edges of that triangle are added to the edge buffer\n # and that triangle is removed.\n j = 0\n\t\t\ttris_size = tris.size\n\t\t\twhile j < tris_size\n\t\t\t\tcurrent_triangle = tris[j]\n if !current_triangle.complete\n p1 = vertices[current_triangle.p1]\n p2 = vertices[current_triangle.p2]\n p3 = vertices[current_triangle.p3]\n inside,xc,yc,r = circum_circle(current_point, p1, p2, p3, cc_cache)\n if (xc + r) < current_point.x\n current_triangle.complete = true\n end\n if inside\n\t\t\t\t\t\tedges << IEDGE.new(current_triangle.p1, current_triangle.p2)\n edges << IEDGE.new(current_triangle.p2, current_triangle.p3)\n edges << IEDGE.new(current_triangle.p3, current_triangle.p1)\n tris.delete_at(j)\n\t\t\t\t\t\ttris_size -= 1\n j -= 1\n end\n end\n j += 1\n end #while j\n\t\t\t\n\t\t\twhile !edges.empty?\n\t\t\t\tedge = edges.shift\n\t\t\t\trejected = edges.reject! {|e| e == edge}\n\t\t\t\ttris << ITRIANGLE.new(edge.p1, edge.p2, i) if rejected.nil? \n\t\t \tend\n \n } #each i\n \n\t\t# Remove supertriangle vertices\n\t\t3.times do \n\t\t\tvertices.pop\n\t\tend\n\t\tnumber_of_vertices = vertices.size\n\n # Remove triangles with supertriangle vertices\n # These are triangles which have a vertex number greater than number_of_vertices\n\t\ttris.delete_if {|tri| tri.p1 >= number_of_vertices || tri.p2 >= number_of_vertices || tri.p3 >= number_of_vertices}\n\n [ vertices, tris ]\n end", "def generate_triangle_numbers(n)\n is_triangle = Array.new(n+1, false)\n \n index = 1\n increment = 1\n while index < is_triangle.length\n is_triangle[index] = true\n increment += 1\n index += increment\n end\n \n return is_triangle\nend", "def add_triangles(pbar, ents, points, triangles, start, count)\r\n mesh = Geom::PolygonMesh.new(points.size, count)\r\n points.each{ |pt| mesh.add_point(Geom::Point3d.new(pt[0..2])) }\r\n (start..(start + count - 1)).each { |i|\r\n k = i * 3\r\n break if k + 3 > triangles.size\r\n mesh.add_polygon(triangles[k+2] + 1, triangles[k+1] + 1, triangles[k] + 1)\r\n }\r\n ents.add_faces_from_mesh(mesh)\r\n return start + count\r\n end", "def all_triples()\n return [] if(@points.size < 3) #check for more than 2 items\n x = Array.new\n @points.combination(3).each {|a,b,c| x << CCWTriple.new(a,b,c)} #combine all points to Triangle objects\n return x\n end", "def generate_grid\n grid = []\n @y.times do\n row = []\n @x.times do\n row << nil\n end\n grid << row\n end\n grid\n end", "def hollow_triangle(n)\n return ['#'] if n == 1\n width = 1 + 2*(n-1)\n first_row, last_row = '#'.center(width, '_'), '#'*width\n middle_rows =\n (1..width-4).step(2).each_with_object([]) { |fill_length, triangle|\n triangle << \"##{'_'*fill_length}#\".center(width, '_') }\n\n [first_row, *middle_rows, last_row]\nend", "def renderTriangles(p,c)\n n = p.size/6\n i = 0\n n.times do\n lines = [p[i],p[i+1],p[i+2],p[i+3],p[i+4],p[i+5],p[i],p[i+1]]\n #Uncommenting this line would make every single triangle a random color\n #c.setFill(\"rgb(#{rand(255)},#{rand(255)},#{rand(255)})\")\n c.drawPolyLine(lines)\n i += 6\n end\nend", "def triangles()\n @triangles = []\n loop_start_time = Time.now\n while @triangles.size != @count\n begin\n t = Triangle.new(*random_coordinate_triplet)\n if t.possible? && within_threshold(t) && within_threshold2(t)\n @triangles << t\n else\n if (Time.now - loop_start_time) > 10\n raise 'too much calculation'\n end\n end\n rescue Math::DomainError\n puts \"Out of domain... trying again.\"\n end\n end\n @triangles\n end", "def generate_surrounding_spaces(x, y)\n surround_array = []\n# Loop over 3x3 grid\n for i in x-1..x+1\n for j in y-1..y+1\n # Exclude the center square and ones not on the grid\n if ((i==x) && (j==y)) || !is_on_grid(i,j)\n next\n end\n surround_array.push([j, i])\n end\n end\n\n return surround_array\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set client stats details Author: Puneet Date: 02/02/2018 Reviewed By:
def set_client_stats(client_stats_data) @client_stats = CompanyApi::Response::Entity::ClientStats.new(client_stats_data) end
[ "def populate_client_usage(client)\n client_id = client.id\n registration_count = User.using_client_shard(client: client).where(client_id: client_id).count\n kyc_submissions_count = UserKycDetail.using_client_shard(client: client).\n where(client_id: client_id).sum(:submission_count)\n\n client_usage_obj = ClientUsage.find_or_initialize_by(client_id: client_id)\n client_usage_obj.registration_count = registration_count\n client_usage_obj.kyc_submissions_count = kyc_submissions_count\n client_usage_obj.save! if client_usage_obj.changed?\n client_usage_obj\n end", "def client_info\n #implement\n client_information = \"#{@name_str} #{@age_num} #{@pet_num}\"\n end", "def update_updated_at_and_by\n #logger.info { \"FILTTERISSÄ: #{response.headers[\"Status\"]}\" }\n if response.headers[\"Status\"] =~ /^20/\n @collection.set_update_info(DateTime.now, (@user ? @user.guid : @client.id))\n # @collection.updated_at = DateTime.now\n # @collection.updated_by = @user ? @user.guid : @client.id\n # @collection.save\n\n end\n end", "def update_from_client\n if @client.fetched?\n self.image = generate_pie(@client.percent)\n self.tooltip = \"%d%% used in %d%% of the period\\n%dGB used, %dGB left\" %\n [@client.percent, @client.percent_of_date, @client.used, @client.left]\n else\n update_from_default\n end\n end", "def details\n response = cs_get \"/clients/#{client_id}.json\", {}\n Hashie::Mash.new(response)\n end", "def details\n response = CreateSend.get \"/clients/#{client_id}.json\", {}\n Hashie::Mash.new(response)\n end", "def client_id=(client_id); end", "def add_client_detail(xml)\n xml.ClientDetail{\n xml.AccountNumber @credentials.account_number\n xml.MeterNumber @credentials.meter\n }\n end", "def add_client_detail(xml)\n xml.ClientDetail{\n xml.AccountNumber @credentials.account_number\n xml.MeterNumber @credentials.meter\n xml.Localization{\n xml.LanguageCode 'en' # English\n xml.LocaleCode 'us' # United States\n }\n }\n end", "def printstats\n u = sec2dhms(Time.new - @@starttime)\n\n info(\"Had #{@@totalclients} clients and #{@@bogusclients} bogus clients. Uptime #{u[0]} days #{u[1]} hours #{u[2]} min. #{@connections.size} connection(s) in use now.\")\n end", "def setup_db_stats_client\n raw_statsd_client = request.env['statsd.service.client']\n @db_stats = StatsdWrapper.new(raw_statsd_client)\n end", "def update_client_info\n\n client = Client.where(id: @client_id).first\n client.company_name = @company_name\n client.save!\n\n set_props_arr = [\n GlobalConstant::Client.has_company_info_property\n ]\n\n set_props_arr.push(GlobalConstant::Client.has_mobile_app_property) if@mobile_app_flag.to_i == 1\n set_props_arr.push(GlobalConstant::Client.has_one_million_users_property) if @one_m_users_flag.to_i == 1\n Client.atomic_update_bitwise_columns(@client_id, set_props_arr, [])\n\n success\n\n end", "def create_client_info\n store.hmset(@client.uid, \"gen_func\", \"increment by 1\", \"min_critical\", MIN_CRITICAL, \"max_critical\", MAX_CRITICAL )\n end", "def set(user_id, client_id, status)\n engine.set(user_id.to_s, client_id.to_s, status.to_s)\n end", "def post_stats_message(\n data:\n )\n stats = get_stats(user: data.user)\n fields = []\n stats.each do |key, value|\n fields.push({ \"value\": \"#{key} #{value} Appreciations\"})\n end\n text = \"*Your Stats*\"\n _web_client_post_message(data: data, text: text, fields: fields)\n end", "def details\n @stats_by_date = current_user.record_by_date(\n Date.new(params[:year].to_i, params[:month].to_i, params[:date].to_i)\n ).statistics\n p @stats_by_date\n end", "def fetch_stats\n resp = client.get\n if resp.status == 200\n JSON.parse(resp.body) rescue nil\n end\n rescue => exc\n error \"failed to fetch cadvisor stats: #{exc.message}\"\n nil\n end", "def get_family_summary\n \t@clients = Client.find_all_by_family_id(self.id)\n @familycount = @clients.count\n \t@get_family_summary = \"##{self.id}: #{self.get_primaryclient_name} (#{@familycount} member#{\"s\" unless @familycount==1})\"\n \n end", "def line_stats=(line_stats)\n @additions, @deletions = *line_stats\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set Client BT Addresss Data Author: Puneet Date: 02/02/2018 Reviewed By:
def set_client_bt_addresses_data(client_bt_addresses_data) @client_bt_addresses = CompanyApi::Response::Entity::ClientBrandedTokenAddresses.new(client_bt_addresses_data) end
[ "def set_Address(value)\n set_input(\"Address\", value)\n end", "def set_address(new_address)\r\n update(address: new_address)\r\n end", "def update_contact_info txn\n AddressManager::set_user_address txn.user, txn\n end", "def set_address(new_address)\n update(address: new_address)\n end", "def set_Addresses(value)\n set_input(\"Addresses\", value)\n end", "def set_street_address_1_update\n @customer = Customer.find(id)\n\n Order.find(id).update_column(:street_address_1, @customer.street_address_1)\n end", "def set_street_address_1_update\n @customer = Customer.find(customer_id)\n\n Order.find(id).update_column(:street_address_1, @customer.street_address_1)\n end", "def set_ToAddress(value)\n set_input(\"ToAddress\", value)\n end", "def address=(value)\n @address = value\n end", "def save_address\n end", "def addresses=(value)\n @addresses = value\n end", "def set_order_address id, address\n post_request \"orders/#{id}/set_address\", {order: {address: address.to_h}}\n end", "def set_FromAddress(value)\n set_input(\"FromAddress\", value)\n end", "def set_street_address_1_save\n @customer = Customer.find(customer_id)\n\n Order.find(id).update_column(:street_address_1, @customer.street_address_1)\n end", "def bcc=(addresses)\n address_list_assign('Bcc', addresses)\n end", "def update_address_changes\n address_changes.create\n end", "def build_address(b, type)\n b.Address do\n send(\"#{type}_streets\").split(\"\\n\").each { |l| b.StreetLines l } if send(\"#{type}_streets\")\n b.City send(\"#{type}_city\") if send(\"#{type}_city\")\n b.StateOrProvinceCode state_code(send(\"#{type}_state\")) if send(\"#{type}_state\")\n b.PostalCode send(\"#{type}_postal_code\") if send(\"#{type}_postal_code\")\n b.CountryCode country_code(send(\"#{type}_country\")) if send(\"#{type}_country\")\n b.Residential send(\"#{type}_residential\")\n end\n end", "def set_street_address_2_update\n @customer = Customer.find(id)\n\n Order.find(id).update_column(:street_address_2, @customer.street_address_2)\n end", "def create\n @customer = User.find_by(id: current_user.id)\n address = @customer.addresses.create(\n line_1: \"Address line 1\",\n line_2: \"\",\n city: \"City\",\n state: \"State\",\n postcode: \"Postcode\",\n country_or_region: \"Country/Region\"\n )\n address.line_1 = \"Address##{address.id}\"\n address.save!\n redirect_to edit_my_addresses_path(@customer, anchor: \"address#{address.id}\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get(Symbol) method that returns a node by the id returns
def get id @nodes[id] end
[ "def get_node(id)\n @nodes[id.to_i]\n end", "def get_node(id)\n get_object('node', id)\n end", "def get_node(id)\n get_object('node', id)\n end", "def get_one(id)\n data = @adapter.get_one(@href, id)\n data.nil? ? nil : Node.resolve(@adapter, @config, data, @href)\n end", "def node(id)\r\n if id.start_with? '*'\r\n ai = id[1..-1]\r\n return find {|n| n.id.end_with? ai}\r\n end\r\n find{|n| n.id.eql? id}\r\n end", "def []( id )\n get_node_by_id( id ) ||\n get_edge_by_id( id )\n end", "def find_by_id(id)\n @nodes.find { |node| node.id == id }\n end", "def get_node(key)\n return @nodes[key]\n end", "def load( id )\n begin\n res = $neo.get_node( id.to_i )\n rescue\n res = nil\n end\n if res\n @node_id = id.to_i\n end\n end", "def []( id )\n get_tree_by_id( id ) ||\n get_network_by_id( id )\n end", "def get(id)\n return @value[id] ;\n end", "def get id\n get_single id\n @elements[id]\n end", "def node(key)\n node_hash[key]\n end", "def fetch_node(key)\n node = fetch_node_nt(key)\n raise unless node\n node\n end", "def get_node(key)\n get_node_pos(key)[0]\n end", "def node_from_id(input)\n\n site_id = @context['__site_id']\n \n # Attempt to locate the node.\n node = Rails.cache.fetch \"node_id:#{site_id}:#{input}\" do\n n = node_scope.where(:id => input.to_i).first\n n.blank? ? nil : n.to_liquid\n end\n\n node\n \n end", "def id\n @node.id\n end", "def node(name)\n nodes.fetch(name)\n end", "def node( node_id )\n SheldonClient::Read.fetch_sheldon_object( :node, node_id )\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
connect(Edge) method that adds a connection to the list of nodes returns
def connect edge self.add edge.src self.add edge.dst @nodes[edge.src] << edge edge end
[ "def connect_over(node); end", "def connect_via(edge)\n if edge.to == self && ! slots.in.include?(edge.label)\n slots.in.add(edge.label)\n end\n\n if edge.from == self && ! slots.out.include?(edge.label)\n slots.out.add(edge.label)\n end\n\n super\n end", "def connect_to(node1,node2)\n # assuming node1 and node2 are part of this graph\n node1.outgoing << node2\n node2.incoming << node1\n end", "def connect(vertex1, vertex2, edge_attributes = {})\n self.vertices << vertex1 unless self.vertices.include? vertex1\n self.vertices << vertex2 unless self.vertices.include? vertex2\n edge = Edge.new(edge_attributes)\n self.edges << edge\n edge << vertex1 << vertex2\n end", "def add_connections node_names\n @connections = @connections.union node_names\n end", "def connect a, b, value=nil\n # TODO: are self loops okay?\n # TODO: this doesn't allow parallel edges?\n \n self << a\n self << b\n \n edge = Edge.new(a, b, value)\n \n # initialize edge list for nodes a and b\n @edges[a] ||= []\n @edges[b] ||= []\n \n # check if this edges already exists\n @edges[a] << edge unless @edges[a].include? edge\n @edges[b] << edge unless @edges[b].include? edge\n \n uncache\n end", "def connect(node0, node1)\n @connections << [node0, node1] unless @connections.include? [node0, node1]\n @connections << [node1, node0] unless @connections.include? [node1, node0]\n end", "def store_connection_info(vertex, edge)\n @edges << edge\n @connections << vertex\n end", "def connect node1, node2\n if !Set.new([node1, node2]).subset? @nodes\n raise BadNodeInput, 'The graph does not have either ' + node1 + ' or ' + node2\n end\n @connections[node1] ||= Array.new\n @connections[node1].push node2\n unless node1.eql? node2\n @connections[node2] ||= Array.new\n @connections[node2].push node1\n end\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 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 connect_to_node!(other_node, relation)\n @connections << ::Rbt::QueryTree::Connection.new(self, other_node, relation)\n end", "def make_connection(v1, v2)\n raise \"not a vertex\" unless v1.is_a?(Vertex) && v2.is_a?(Vertex)\n raise \"already connected\" if is_connected?(v1, v2)\n # Make new edge\n edge = Edge.new(v1, v2)\n # Connect the two using the vertex method \"connect\"\n v1.connect(v2, edge)\n v2.connect(v1, edge)\n\n # Add to edge catalog\n @edges << edge\n edge\n end", "def add_edge(nodeA, nodeB)\n nodeA.adjacents << nodeB\n end", "def connect_endpoint(collection, edge)\n if collection.any? { |o| ! edge.equal?(o) && edge.similar?(o) }\n raise DuplicateEdgeError.new(self, edge)\n end\n\n collection.add(edge)\n end", "def add_edge(e)\n @edges[e.from] << e\n end", "def add_next(edge)\n self.next = edge\n return edge\n end", "def add_edge(edge)\n @edges << edge\n self\n end", "def connect(src, dest, len = 1)\n\t\tif self.include?(src) and self.include?(dest) and !edge_exists?(src, dest) and len > 0\n\t\t\t\t@e << Edge.new(src, dest, len)\n\t\telse\n\t\t\treturn nil\n\t\tend\n\t\ttrue\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
path_number(List, Symbol, Hash, String) return the number of paths with in the limits returns
def path_number visit_path, dst, limits, condition=EG paths = route(visit_path, dst, limits, condition) select_condition = condition == EG ? EG : condition == UNTIL ? LESS : UNTIL return (paths.select {|path| eval final_eval( select_condition, limits )}).length end
[ "def path_count(*args)\n path_rels(*args).size\n end", "def path_captures\n return 0 unless conditions[:path]\n Behavior.count_parens_up_to(conditions[:path], conditions[:path].size)\n end", "def number_of_paths(n)\n return 0 if n < 0\n return 1 if n == 1 || n == 0\n number_of_paths(n - 1) + number_of_paths(n - 2) + number_of_paths(n - 3)\nend", "def path_length\n @path_length ||= if (match = @node.inner_text.match(/pathlen:(\\d+)/))\n match[1].to_i\n end\n end", "def path_length\n @path_length ||= if (match = value.match(/pathlen:(\\d+)/))\n match[1].to_i\n end\n end", "def actual_path_length\n folders.count\n end", "def total_paths(initial_s)\n reachable_stops(initial_s).count\n end", "def countpaths(graph, start, stop)\n if start == stop\n return 1\n else \n sum = 0\n graph[start].each { |nxt|\n if $pathcache.has_key?(nxt)\n tmp = $pathcache[nxt]\n else\n tmp = countpaths(graph, nxt, stop)\n $pathcache.store(nxt, tmp)\n end\n sum += tmp \n }\n return sum\n end\nend", "def get_longest_path_length(x)\n compute_longest_paths\n @longest_path[x].length - 1\n end", "def count_routes(n)\n\n\treturn 0\nend", "def path_length(guess)\n Log.indent(\"path_length #{guess.inspect}\") do\n do_path_length(guess).tap{|x| Log.debug(\"returning #{x.inspect}\")}\n end\n end", "def howManyMineHits(path)\n path.select { |i| @structure[i] & MINE > 0 }\n end", "def open_path_count(map, origin_loc)\n return 0 unless origin_loc\n\n ok_cells = [FOOD_SYMBOL, nil]\n max_x, max_y = map_dimensions(map)\n cell_count = max_x * max_y\n\n spanning_path = Set.new\n to_check = [origin_loc]\n\n count = 0\n while to_check.size > 0 && count < cell_count\n loc = to_check.shift\n\n POSSIBLE_MOVES.each do |move|\n next_loc = find_next_loc(map, loc, move)\n next if !next_loc\n next if spanning_path.include?([next_loc.x, next_loc.y])\n next if !map[next_loc.x][next_loc.y].in?(ok_cells)\n\n spanning_path << [next_loc.x, next_loc.y]\n to_check << next_loc\n end\n end\n\n spanning_path.size\n end", "def length_in_bp_within_path\n return 0 if @trail.empty?\n reduce(0) do |total, onode|\n total + onode.node.length_alone\n end\n end", "def routes_num_with_length_limited(from = nil, to = nil, max_length = 0)\n find_routes_num(from, to, 0, max_length)\n end", "def n_paths(graph, from)\n counter = { from => 1 }\n graph.topsort.each do |v|\n next if v == from\n in_edges = graph.edges.select { |e| e.target == v && graph.adjacent(v, :direction => :in).include?(e.source) }\n counter[v] = in_edges.map { |e| counter[e.source] }.inject(:+)\n end\n counter\nend", "def paths()\n assert( @maximum.exists?, \"you cannot obtain paths() for an infinite Repeater\" )\n assert( @maximum <= 10, \"if you really need to obtain paths() for a Repeater with greater than 10 elements, change this assertion\" )\n \n #\n # First, compile the element to its paths. We will end up with a BranchPoint.\n \n element_paths = nil\n if @element.is_an?(ExpressionForm) then\n element = @element.paths\n else\n element = BranchPoint.new( Sequence.new(@element) )\n end\n \n #\n # Next, produce a BranchPoint with a Sequence for each count we are doing.\n \n run = Sequence.new()\n minimum.times do\n run << element\n end\n \n result = BranchPoint.new( run )\n (maximum - minimum).times do\n run = Sequence.new( run, element )\n run.minimal = false\n result << run\n end\n \n \n #\n # Finally, get the paths of the produced Sequence.\n \n return result.paths\n end", "def get_max_path(num_pyramid)\n num_pyramid.each_index do |i|\n next if i == 0\n num_pyramid[i].each_index do |j|\n num_pyramid[i][j] += [num_pyramid[i - 1][j], num_pyramid[i - 1][j + 1]].max\n end\n end\n\n num_pyramid[-1].first\nend", "def countSubst(path)\n count = 0\n path.each do | atom |\n if @atoms[atom].size > 2 then\n count += (@atoms[atom].size - 2)\n end\n end\n count\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
step_number(Hash, String) return the eval expression for the conditions returns
def final_eval condition, limits return "#{condition[:steps]}#{limits[:steps]}" if limits.has_key? :steps return "#{condition[:cost]}#{limits[:cost]}" if limits.has_key? :cost false end
[ "def first_step_nr\n first_step[\"step\"]\n end", "def step\n read_attribute(:step) or ( input and input.step )\n end", "def step_state(number)\n s = @step_states[number] if @step_states[number]\n return s\n end", "def step_result; end", "def steps(n)\nend", "def input_step(step_value)\n return unless step_value\n\n @input_divisor ||= 10**Math.log10(1 / multiplier).ceil\n step_value / @input_divisor\n end", "def step_number(string)\n return string.split('-',5)[2].to_i\n end", "def expression\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 23 )\n\n\n __LT27__ = nil\n __LEQ28__ = nil\n __GT29__ = nil\n __GEQ30__ = nil\n __EQ31__ = nil\n __NE32__ = nil\n\n\n begin\n # at line 242:5: exp ( ( LT | LEQ | GT | GEQ | EQ | NE ) exp )*\n @state.following.push( TOKENS_FOLLOWING_exp_IN_expression_1224 )\n exp\n @state.following.pop\n # at line 242:9: ( ( LT | LEQ | GT | GEQ | EQ | NE ) exp )*\n while true # decision 26\n alt_26 = 2\n look_26_0 = @input.peek( 1 )\n\n if ( look_26_0 == EQ || look_26_0.between?( GEQ, GT ) || look_26_0 == LEQ || look_26_0 == LT || look_26_0 == NE )\n alt_26 = 1\n\n end\n case alt_26\n when 1\n # at line 242:10: ( LT | LEQ | GT | GEQ | EQ | NE ) exp\n # at line 242:10: ( LT | LEQ | GT | GEQ | EQ | NE )\n alt_25 = 6\n case look_25 = @input.peek( 1 )\n when LT then alt_25 = 1\n when LEQ then alt_25 = 2\n when GT then alt_25 = 3\n when GEQ then alt_25 = 4\n when EQ then alt_25 = 5\n when NE then alt_25 = 6\n else\n raise NoViableAlternative( \"\", 25, 0 )\n\n end\n case alt_25\n when 1\n # at line 242:11: LT\n __LT27__ = match( LT, TOKENS_FOLLOWING_LT_IN_expression_1228 )\n\n # --> action\n $cuads.add_E(__LT27__.text)\n # <-- action\n\n\n when 2\n # at line 242:42: LEQ\n __LEQ28__ = match( LEQ, TOKENS_FOLLOWING_LEQ_IN_expression_1234 )\n\n # --> action\n $cuads.add_E(__LEQ28__.text)\n # <-- action\n\n\n when 3\n # at line 242:75: GT\n __GT29__ = match( GT, TOKENS_FOLLOWING_GT_IN_expression_1240 )\n\n # --> action\n $cuads.add_E(__GT29__.text)\n # <-- action\n\n\n when 4\n # at line 242:106: GEQ\n __GEQ30__ = match( GEQ, TOKENS_FOLLOWING_GEQ_IN_expression_1246 )\n\n # --> action\n $cuads.add_E(__GEQ30__.text)\n # <-- action\n\n\n when 5\n # at line 242:139: EQ\n __EQ31__ = match( EQ, TOKENS_FOLLOWING_EQ_IN_expression_1252 )\n\n # --> action\n $cuads.add_E(__EQ31__.text)\n # <-- action\n\n\n when 6\n # at line 242:170: NE\n __NE32__ = match( NE, TOKENS_FOLLOWING_NE_IN_expression_1258 )\n\n # --> action\n $cuads.add_E(__NE32__.text)\n # <-- action\n\n\n end\n @state.following.push( TOKENS_FOLLOWING_exp_IN_expression_1264 )\n exp\n @state.following.pop\n\n else\n break # out of loop for decision 26\n end\n end # loop for decision 26\n\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__, 23 )\n\n\n end\n\n return \n end", "def generate_step_from_row( row, test_case_id, step_number )\n # Append a step\n step = Step.new\n step.action = row[3]\n step.result = row[4]\n step.test_case_id = test_case_id\n step.step_number = step_number\n \n return step\n end", "def take_steps(n, steps = 1)\n\treturn 0 if n < 0\n\n\treturn 1 if n == 0\n\treturn @hash[n] unless @hash[n].nil?\n\t\n\t@hash[n] = take_steps(n - 1) + take_steps(n - 2) + take_steps(n - 3)\n\treturn @hash[n]\nend", "def expr1\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 2 )\n value = nil\n e = nil\n\n begin\n # at line 28:5: e= number ( '*' e= number | '/' e= number )*\n @state.following.push( TOKENS_FOLLOWING_number_IN_expr1_207 )\n e = number\n @state.following.pop\n # --> action\n value = e \n # <-- action\n # at line 29:5: ( '*' e= number | '/' e= number )*\n while true # decision 2\n alt_2 = 3\n look_2_0 = @input.peek( 1 )\n\n if ( look_2_0 == T__12 )\n alt_2 = 1\n elsif ( look_2_0 == T__13 )\n alt_2 = 2\n\n end\n case alt_2\n when 1\n # at line 29:7: '*' e= number\n match( T__12, TOKENS_FOLLOWING_T__12_IN_expr1_217 )\n @state.following.push( TOKENS_FOLLOWING_number_IN_expr1_221 )\n e = number\n @state.following.pop\n # --> action\n value *= e \n # <-- action\n\n when 2\n # at line 30:7: '/' e= number\n match( T__13, TOKENS_FOLLOWING_T__13_IN_expr1_231 )\n @state.following.push( TOKENS_FOLLOWING_number_IN_expr1_235 )\n e = number\n @state.following.pop\n # --> action\n value /= e \n # <-- action\n\n else\n break # out of loop for decision 2\n end\n end # loop for decision 2\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__, 2 )\n\n end\n \n return value\n end", "def kaprekar_step(n)\n\n # TODO: Solve it!\n\n end", "def flow_expression\n\n @dict.fexp\n end", "def numeric_loop_param\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 73 )\n return_value = NumericLoopParamReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n numeric_loop_param_start_index = @input.index\n\n root_0 = nil\n string_literal538 = nil\n __DOUBLEDOT541__ = nil\n index_name537 = nil\n keyREVERSE539 = nil\n integer_expr540 = nil\n integer_expr542 = nil\n\n tree_for_string_literal538 = nil\n tree_for_DOUBLEDOT541 = 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 return_value\n end\n root_0 = @adaptor.create_flat_list\n\n\n # at line 497:4: index_name 'IN' ( keyREVERSE )? integer_expr DOUBLEDOT integer_expr\n @state.following.push( TOKENS_FOLLOWING_index_name_IN_numeric_loop_param_3172 )\n index_name537 = index_name\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, index_name537.tree )\n end\n string_literal538 = match( T__102, TOKENS_FOLLOWING_T__102_IN_numeric_loop_param_3174 )\n if @state.backtracking == 0\n\n tree_for_string_literal538 = @adaptor.create_with_payload( string_literal538 )\n @adaptor.add_child( root_0, tree_for_string_literal538 )\n\n end\n # at line 497:20: ( keyREVERSE )?\n alt_133 = 2\n alt_133 = @dfa133.predict( @input )\n case alt_133\n when 1\n # at line 497:22: keyREVERSE\n @state.following.push( TOKENS_FOLLOWING_keyREVERSE_IN_numeric_loop_param_3178 )\n keyREVERSE539 = keyREVERSE\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, keyREVERSE539.tree )\n end\n\n end\n @state.following.push( TOKENS_FOLLOWING_integer_expr_IN_numeric_loop_param_3183 )\n integer_expr540 = integer_expr\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, integer_expr540.tree )\n end\n __DOUBLEDOT541__ = match( DOUBLEDOT, TOKENS_FOLLOWING_DOUBLEDOT_IN_numeric_loop_param_3185 )\n if @state.backtracking == 0\n\n tree_for_DOUBLEDOT541 = @adaptor.create_with_payload( __DOUBLEDOT541__ )\n @adaptor.add_child( root_0, tree_for_DOUBLEDOT541 )\n\n end\n @state.following.push( TOKENS_FOLLOWING_integer_expr_IN_numeric_loop_param_3187 )\n integer_expr542 = integer_expr\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, integer_expr542.tree )\n end\n # - - - - - - - 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 success = true\n\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__, 73 )\n memoize( __method__, numeric_loop_param_start_index, success ) if @state.backtracking > 0\n\n end\n \n return return_value\n end", "def test_step_id; end", "def total_steps\n 3\n end", "def calc_seq(num, steps)\n if @h[num]\n @h[num] + steps - 1\n elsif num == 1\n steps\n elsif num % 2 == 0\n calc_seq(num / 2, steps + 1)\n else\n calc_seq(3 * num + 1, steps + 1)\n end\nend", "def create_steps(value)\n temp = []\n st_count = 0\n value.each do |x|\n temp[st_count] = {}\n temp[st_count][:step_number] = \"#{st_count+1}\"\n temp[st_count][:actions] = \"<p>#{x}</p>\"\n temp[st_count][:expected_results] = \"<p>Should pass</p>\"\n temp[st_count][:execution_type] = \"2\"\n temp[st_count][:active] = \"1\"\n st_count += 1\n end\n return temp\nend", "def current_step_hash\n @wizard_steps[current_step - 1]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the account for this business linked to a "money" program with is_money == true
def cashbox return @cashbox if @cashbox.present? return nil unless has_money_program? @cashbox = self.accounts.where(:program_id => money_program.id, :is_money => true).first end
[ "def payable_account\n payable_account = self.accounts.where(:type=>'payable').first\n payable_account\n end", "def payment_entry\n business_account.entries.find { |e|\n e.code == number.to_s and not e.accounts.include? commodity_account\n }\n end", "def get_account_from(description)\n if transaction_filter.class != Hash\n return @default_credit_account\n end\n\n return get_account_from_transaction_filter_and(description)\n end", "def financial_account\n FinancialAccount.find_account(self)\n end", "def direct_account\n # We don't care if no bookings\n return nil if bookings.empty?\n\n # Take any booking\n booking = bookings.first\n involved_accounts = [booking.credit_account, booking.debit_account]\n\n relevant_account = involved_accounts - [Account.find_by_code(\"1100\"), Account.find_by_code(\"2000\")]\n\n return relevant_account.first\n end", "def business_account\n customer_or_supplier \\\n proc { customer.receivable_account },\n proc { supplier.payable_account }\n end", "def balance_for(other_user)\n Money.new(all_balances[other_user.id], 'PLN')\n end", "def find_deposit_account(deposit_type)\n self.deposit_accounts.select {|i| i.kind == deposit_type.to_sym}.first\n end", "def balance\n @accounts.values.first\n end", "def account\n find('Account', account_id)\n end", "def account_to; Account.get(self.account_to_id); end", "def get_account_number\n @acct_num\n end", "def sum_pay_account_type\n if direction == :ingoing\n Account::ASSET_ACCOUNT\n else\n Account::DEBT_ACCOUNT\n end\n end", "def find_account(owner, currency = default_currency)\n scope_for_owner(owner).currency(currency.to_s).first\n end", "def account\n return @account if @account\n @account = @db[ACCOUNT_COLLECTION_NAME].find_one()\n end", "def sum_account_type\n if direction == :outgoing\n Account::ASSET_ACCOUNT\n else\n Account::DEBT_ACCOUNT\n end\n end", "def get_account()\n\t\treturn self.get(\"account\",\"\")\n\tend", "def primary_account\n accounts.first\n end", "def account_by_id_for_user(id_for_user)\n Account.find(:first, :include => :financial_inst,\n :conditions => [\"account_key = ? AND id_for_user = ?\", account_key, id_for_user])\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries to detect the current processor based if any of the processors exist. Mogrify have precedence over gm by default. === Returns [String] The detected procesor
def choose_processor self.processor = if MiniMagick::Utilities.which('mogrify') :mogrify elsif MiniMagick::Utilities.which('gm') :gm else nil end end
[ "def choose_processor\n if `type -P mogrify`.size > 0\n return\n elsif `type -P gm`.size > 0\n self.processor = \"gm\"\n end\n end", "def gm?\n choose_processor if processor.nil?\n\n return processor.to_s.downcase.to_sym == :gm unless processor.nil?\n false\n end", "def mogrify?\n choose_processor if processor.nil?\n\n return processor.to_s.downcase.to_sym == :mogrify unless processor.nil?\n false\n end", "def processor\n begin\n require \"image_processing\"\n rescue LoadError\n ActiveSupport::Deprecation.warn(\"Using mini_magick gem directly is deprecated and will be removed in Rails 6.1. Please add `gem 'image_processing', '~> 1.2'` to your Gemfile.\")\n return nil\n end\n\n ImageProcessing.const_get(ActiveStorage.variant_processor.to_s.camelize) if ActiveStorage.variant_processor\n end", "def processor_class\n @processor_class ||= processor_classes.find { |c| c.available? }\n raise \"None of the Miso::Processor classes are available.\" unless @processor_class\n @processor_class\n end", "def processor_name\n self.class.processor_name\n end", "def getProcessorName; self.class.name; end", "def processor_classes\n @processor_classes ||= [CoreImage, GraphicsMagick, ImageMagick]\n end", "def processor?(name)\n registered?(name) && dataflow_class_for(name).ancestors.include?(Wukong::Processor)\n end", "def processor\n options[:ignored] || options[:processor]\n end", "def processors\n self.config[:processors] || []\n end", "def processor_name(name = nil)\n if name\n @processor_name = name\n else\n (defined?(@processor_name) && @processor_name) || self.name\n end\n end", "def file_is_processor?(path)\n return false unless path\n processor_registered?(processor_name_from_file(path))\n end", "def p4_cpu(os)\n cpu = RbConfig::CONFIG['target_cpu']\n case os\n when :darwin, :linux\n if cpu =~ /i686/\n 'x86'\n elsif cpu =~ /universal/\n 'x86_64'\n else\n cpu\n end\n else\n case cpu\n when /ia/i\n 'ia64'\n else\n cpu\n end\n end\nend", "def host_processors\n case host\n when /darwin/\n `sysctl -n hw.ncpu`.to_i\n when /linux/\n `nproc`.to_i\n else\n 1\n end\nend", "def processor_registered? name\n Wukong.registry.registered?(name.to_s.to_sym)\n end", "def fetch(processor_name)\n idx = processors.index {|processor| processor.name.equal?(processor_name)}\n idx or raise(UnknownProcessor.new(processor_name))\n end", "def processor\n case @processor_key\n when :availability\n Processors::Availability\n when :capacity_profile\n Processors::CapacityProfile\n when :generic\n Processors::Generic\n when :price\n Processors::Price\n when :profile\n Processors::Profile\n when :temperature\n Processors::Temperature\n else\n raise \"Unknown processor #{@processor_key.inspect} for user curve #{@key.inspect}\"\n end\n end", "def ogg_processor\n ret = nil\n @processors.each do |proc|\n if proc.output_type == :ogg\n ret = proc\n end\n end\n ret\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Discovers the imagemagick version based on mogrify's output. === Returns The imagemagick version
def image_magick_version @@version ||= Gem::Version.create(`mogrify --version`.split(' ')[2].split('-').first) end
[ "def exiftool_version\n @exiftool_version ||= `#{exiftool_command} -ver`.to_f\n end", "def imagemagick7?; end", "def valid_version_installed?\n image_magick_version >= minimum_image_magick_version\n end", "def version\n Gem.loaded_specs['image_optim'].version.to_s\n rescue\n 'DEV'\n end", "def minimum_image_magick_version\n @@minimum_version ||= Gem::Version.create('6.6.3')\n end", "def has_imagemagick?\n system(\"which identify > /dev/null\") && system(\"which convert > /dev/null\")\n end", "def imagemagick?; end", "def inkscape_version\n query(\"inkscape-version\")\n end", "def exif_tool_version\n ng_xml.css(\"fits > identification > identity > tool[toolname='Exiftool']\").map { |n| n['toolversion'] }\n end", "def exif_version\n ng_xml.css(\"fits > metadata > image > exifVersion[toolname='Exiftool']\").map(&:text)\n end", "def magick_formats\n @magick_formats ||= `convert -version`\n .scan(/Delegates.*/)\n .first\n .delete_prefix('Delegates (built-in):')\n .split\n end", "def check_previous_imagemagick(im_check)\n im_version = `Magick-config --version` rescue nil\n if im_version.nil? || im_version.empty? then\n say \"The message above is normal.\"\n return\n end\n if !im_check\n say \"ImageMagick #{im_version.chomp} is already installed on this system.\"\n return\n end\n \n terminate <<-VERS_MSG\n ImageMagick #{im_version.chomp} is already installed on this system.\n Having two different versions of ImageMagick usually causes problems, \n either during installation or when you try to run RMagick. You should\n uninstall the other version before installing a different version with\n this script.\n\n If you installed the existing version of ImageMagick using this script and\n the version number has not changed, then you can ignore this message.\n\n To bypass this check use the --no-im-check option.\n \n VERS_MSG\n end", "def info\r\n output = Image.run_command(\"identify #{@filename}\")\r\n info_array = output.split \r\n return({\r\n :format => info_array[1].downcase.to_sym,\r\n :width => info_array[2].match(/^\\d+/)[0].to_i,\r\n :height => info_array[2].match(/\\d+$/)[0].to_i \r\n })\r\n \r\n end", "def choose_processor\n self.processor = if MiniMagick::Utilities.which('mogrify')\n :mogrify\n elsif MiniMagick::Utilities.which('gm')\n :gm\n else\n nil\n end\n end", "def version\n @version ||= begin\n path = MacOS.app_with_bundle_id(FORGE_BUNDLE_ID) || MacOS.app_with_bundle_id(APPLE_BUNDLE_ID)\n if not path.nil? and path.exist?\n `mdls -raw -name kMDItemVersion \"#{path}\" 2>/dev/null`.strip\n elsif prefix.to_s == \"/usr/X11\"\n # Some users disable Spotlight indexing. If we're working with the\n # system X11 distribution, we can't get the version from pkgutil, so\n # just use the expected version.\n case MacOS.version\n when '10.5' then '2.1.6'\n when '10.6' then '2.3.6'\n when '10.7' then '2.6.3'\n else 'dunno'\n end\n else\n # Finally, try to find it via pkgutil. This is slow, and only works\n # for the upstream XQuartz package, so use it as a last resort.\n MacOS.pkgutil_info(FORGE_PKG_ID)[/version: (\\d\\.\\d\\.\\d).+$/, 1]\n end\n end\n end", "def get_gcovr_version()\n version_number_major = 0\n version_number_minor = 0\n\n command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_GCOVR_POST_REPORT, [], \"--version\")\n shell_result = @ceedling[:tool_executor].exec(command[:line], command[:options])\n version_number_match_data = shell_result[:output].match(/gcovr ([0-9]+)\\.([0-9]+)/)\n\n if !(version_number_match_data.nil?) && !(version_number_match_data[1].nil?) && !(version_number_match_data[2].nil?)\n version_number_major = version_number_match_data[1].to_i\n version_number_minor = version_number_match_data[2].to_i\n end\n\n return version_number_major, version_number_minor\n end", "def version_tag\n \"RMagick_#{version.gsub(\".\",\"-\")}\"\n end", "def processor\n begin\n require \"image_processing\"\n rescue LoadError\n ActiveSupport::Deprecation.warn(\"Using mini_magick gem directly is deprecated and will be removed in Rails 6.1. Please add `gem 'image_processing', '~> 1.2'` to your Gemfile.\")\n return nil\n end\n\n ImageProcessing.const_get(ActiveStorage.variant_processor.to_s.camelize) if ActiveStorage.variant_processor\n end", "def get_gcovr_version()\n gcovr_version_number_major = 0\n gcovr_version_number_minor = 0\n\n command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_POST_REPORT, [], \"--version\")\n shell_result = @ceedling[:tool_executor].exec(command[:line], command[:options])\n version_number_match_data = shell_result[:output].match(/gcovr ([0-9]+)\\.([0-9]+)/)\n\n if !(version_number_match_data.nil?) && !(version_number_match_data[1].nil?) && !(version_number_match_data[2].nil?)\n gcovr_version_number_major = version_number_match_data[1].to_i\n gcovr_version_number_minor = version_number_match_data[2].to_i\n end\n\n return gcovr_version_number_major, gcovr_version_number_minor\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The minimum allowed imagemagick version === Returns The minimum imagemagick version
def minimum_image_magick_version @@minimum_version ||= Gem::Version.create('6.6.3') end
[ "def valid_version_installed?\n image_magick_version >= minimum_image_magick_version\n end", "def image_magick_version\n @@version ||= Gem::Version.create(`mogrify --version`.split(' ')[2].split('-').first)\n end", "def os_minimum_version\n return @os_minimum_version\n end", "def version\n Gem.loaded_specs['image_optim'].version.to_s\n rescue\n 'DEV'\n end", "def imagemagick7?; end", "def min_version\n @min_version ||= nil\n end", "def minimum_version\n lowest_no_flavour = available_version_definitions.versions_array\n .select { |v| v.flavour.nil? }\n .min_by(&:to_s)\n return lowest_no_flavour unless lowest_no_flavour.nil?\n\n available_version_definitions.versions_array\n .min_by(&:to_s)\n end", "def minimum_required_os_version\n return @minimum_required_os_version\n end", "def min_sdk_version\n info.try(:[], 'MinimumOSVersion')\n end", "def check_partial_imagemagick_versions\n prefix = config_string('prefix') || ''\n matches = [\n prefix+'/lib/lib?agick*',\n prefix+'/include/ImageMagick',\n prefix+'/bin/Magick-config',\n ].map do |file_glob|\n Dir.glob(file_glob)\n end\n matches.delete_if { |arr| arr.empty? }\n if 0 < matches.length && matches.length < 3\n msg = \"\\nWarning: Found a partial ImageMagick installation. Your operating system likely has some built-in ImageMagick libraries but not all of ImageMagick. This will most likely cause problems at both compile and runtime.\\nFound partial installation at: \"+prefix+\"\\n\"\n Logging.message msg\n message msg\n end\n end", "def min_pdf_version\n if bits > 8\n # 16-bit color only supported in 1.5+ (ISO 32000-1:2008 8.9.5.1)\n 1.5\n elsif alpha_channel?\n # Need transparency for SMask\n 1.4\n else\n 1.0\n end\n end", "def mobile_os_minimum_version\n return @mobile_os_minimum_version\n end", "def minimum_warning_os_version\n return @minimum_warning_os_version\n end", "def minimum_required_patch_version\n return @minimum_required_patch_version\n end", "def minimum_supported_mobipocket_version\n @minimum_supported_mobipocket_version ||= @data[104, 4].unpack('N*')[0]\n end", "def has_imagemagick?\n system(\"which identify > /dev/null\") && system(\"which convert > /dev/null\")\n end", "def require_mini_magick!\n unless defined?(MiniMagick)\n begin \n require 'mini_magick'\n rescue LoadError => e\n raise 'Required options need the mini_magick gem installed.'\n end\n end\n end", "def imagemagick?; end", "def minimum_supported_windows_release\n return @minimum_supported_windows_release\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether the imagemagick's version is valid === Returns [Boolean]
def valid_version_installed? image_magick_version >= minimum_image_magick_version end
[ "def valid?\n versions.any?\n end", "def invalid?\n %w(undefined 0).include?(version.to_s)\n end", "def valid_version?(version)\n version =~ /\\d+\\.\\d+\\.\\d+(\\.(alpha|beta|rc)(\\.\\d+)?)?/\nend", "def valid?\n run_command(\"identify\", @path)\n true\n rescue MiniMagick::Invalid\n false\n end", "def gem_valid_version?\n gem_version.present? && parse_gem_version(gem_version).present?\n end", "def valid_version?(version)\n file = version.split(\".\")\n library = VERSION.split(\".\")\n return false if file[0] != library[0] || file[1] != library[1]\n if library[1].to_i.even?\n return file[2].to_i <= library[2].to_i\n else\n return file[2] == library[2]\n end\n end", "def version_ok?\n @version_ok ||= ((GIT_VERSION <=> version) <= 0)\n end", "def is_valid_build_version?(version)\n return !!BUILD_VERSION_REGEX.match(version)\n end", "def valid?\n gem_name.present? || gem_with_version?\n end", "def check_version(v)\n return true if (!version || version[0..4].gsub(\".\",\"\").to_i>=v)\n return false\n end", "def has_version?\n !@spec.version.nil?\n end", "def version_check(library, version=nil)\n built = Rubygame::VERSIONS[library]\n return false unless built\n if version\n major,minor,bug = version\n built_major,built_minor,built_bug = built\n return true if built_major > major\n return false if built_major < major\n \n return true if built_minor > minor\n return false if built_minor < minor\n \n return false if built_bug < bug\n end\n return true\nend", "def valid_schema_version?\n schema_version = PROIEL::PROIELXML::Schema.check_schema_version_of_xml_file(@filename)\n\n if schema_version.nil?\n @errors << 'invalid schema version'\n\n false\n else\n true\n end\n rescue PROIEL::PROIELXML::Schema::InvalidSchemaVersion => e\n @errors << e.message\n\n false\n end", "def valid_other_image_parameters?\n # check version of gif\n return Image.gif89a?(@file_temp_path) if @file_type == GIF_TYPE\n # check \"color system\" of \"jpeg, jpg\" file\n return Image.rgb_color_system?(@file_temp_path) if @file_type == JPEG_TYPE\n # always return true with \"png\" file\n true if @file_type == PNG_TYPE\n end", "def valid?\n formats.count > 0\n end", "def valid_other_image_parameters?\n # check version of gif\n return Image.gif89a?(@file_temp_path) if @file_type == GIF_TYPE\n # check \"color system\" of \"jpeg, jpg\" file\n return Image.rgb_color_system?(@file_temp_path) if @file_type == JPG_TYPE\n # always return true with \"png\" file\n true if @file_type == PNG_TYPE\n end", "def valid_version?(arg)\n return false unless arg.is_a?(String) || arg.is_a?(Symbol)\n return true if arg.to_s == 'latest'\n arg =~ /^[0-9]+\\.[0-9]+\\.[0-9]+$/ ? true : false\n end", "def valid_image_format?\n VALID_FILE_MIMETYPES.include? self.filetype\n end", "def valid_file?\n if @image.size.zero?\n errors.add_to_base(\"Please enter an image filename\")\n return false\n end\n unless @image.content_type =~ /^image/\n errors.add(:image, \"is not a recognized format\")\n return false\n end\n if @image.size > 1.megabyte\n errors.add(:image, \"can't be bigger than 1 megabyte\")\n return false\n end\n return true\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Picks the right processor if it isn't set and returns whether it's mogrify or not. === Returns [Boolean]
def mogrify? choose_processor if processor.nil? return processor.to_s.downcase.to_sym == :mogrify unless processor.nil? false end
[ "def gm?\n choose_processor if processor.nil?\n\n return processor.to_s.downcase.to_sym == :gm unless processor.nil?\n false\n end", "def choose_processor\n if `type -P mogrify`.size > 0\n return\n elsif `type -P gm`.size > 0\n self.processor = \"gm\"\n end\n end", "def choose_processor\n self.processor = if MiniMagick::Utilities.which('mogrify')\n :mogrify\n elsif MiniMagick::Utilities.which('gm')\n :gm\n else\n nil\n end\n end", "def processor?(name)\n registered?(name) && dataflow_class_for(name).ancestors.include?(Wukong::Processor)\n end", "def explicit_reduce_processor?\n settings[:reducer]\n end", "def processor_registered? name\n Wukong.registry.registered?(name.to_s.to_sym)\n end", "def file_is_processor?(path)\n return false unless path\n processor_registered?(processor_name_from_file(path))\n end", "def explicit_map_processor?\n settings[:mapper]\n end", "def is_per_cpu?\n @per_core || (@per_cpu && (@per_cpu.size == @@system.cpus.count))\n end", "def processor\n begin\n require \"image_processing\"\n rescue LoadError\n ActiveSupport::Deprecation.warn(\"Using mini_magick gem directly is deprecated and will be removed in Rails 6.1. Please add `gem 'image_processing', '~> 1.2'` to your Gemfile.\")\n return nil\n end\n\n ImageProcessing.const_get(ActiveStorage.variant_processor.to_s.camelize) if ActiveStorage.variant_processor\n end", "def processor_class\n @processor_class ||= processor_classes.find { |c| c.available? }\n raise \"None of the Miso::Processor classes are available.\" unless @processor_class\n @processor_class\n end", "def read_processors?\n config && read_post_processor?\n end", "def compute_on_promotion?\n @compute_on_promotion ||= calculable.respond_to?(:promotion)\n end", "def register(processor)\n return false if @processors.include? processor\n @processors[processor] = true\n end", "def cpu?\n has_node? :CPU\n end", "def processor\n options[:ignored] || options[:processor]\n end", "def processingMode(expected = nil)\n case expected\n when 1.0, 'json-ld-1.0'\n @processingMode == 'json-ld-1.0'\n when 1.1, 'json-ld-1.1'\n @processingMode.nil? || @processingMode == 'json-ld-1.1'\n when nil\n @processingMode || 'json-ld-1.1'\n else\n false\n end\n end", "def using_cpu?\n return @status[ 'CPU' ][ 'Active' ]\n end", "def is_processing\n return @is_processing\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Picks the right processor if it isn't set and returns whether it's graphicsmagick or not. === Returns [Boolean]
def gm? choose_processor if processor.nil? return processor.to_s.downcase.to_sym == :gm unless processor.nil? false end
[ "def choose_processor\n self.processor = if MiniMagick::Utilities.which('mogrify')\n :mogrify\n elsif MiniMagick::Utilities.which('gm')\n :gm\n else\n nil\n end\n end", "def mogrify?\n choose_processor if processor.nil?\n\n return processor.to_s.downcase.to_sym == :mogrify unless processor.nil?\n false\n end", "def choose_processor\n if `type -P mogrify`.size > 0\n return\n elsif `type -P gm`.size > 0\n self.processor = \"gm\"\n end\n end", "def graphic_instance?\n has_gpu = `lspci | grep -i -o 'NVIDIA'`\n is_graphic_instance = !has_gpu.strip.empty?\n\n is_graphic_instance\nend", "def graphic_instance?\n has_gpu = Mixlib::ShellOut.new(\"lspci | grep -i -o 'NVIDIA'\")\n has_gpu.run_command\n\n !has_gpu.stdout.strip.empty?\nend", "def has_imagemagick?\n system(\"which identify > /dev/null\") && system(\"which convert > /dev/null\")\n end", "def processor\n begin\n require \"image_processing\"\n rescue LoadError\n ActiveSupport::Deprecation.warn(\"Using mini_magick gem directly is deprecated and will be removed in Rails 6.1. Please add `gem 'image_processing', '~> 1.2'` to your Gemfile.\")\n return nil\n end\n\n ImageProcessing.const_get(ActiveStorage.variant_processor.to_s.camelize) if ActiveStorage.variant_processor\n end", "def file_is_processor?(path)\n return false unless path\n processor_registered?(processor_name_from_file(path))\n end", "def cpu?\n has_node? :CPU\n end", "def is_per_cpu?\n @per_core || (@per_cpu && (@per_cpu.size == @@system.cpus.count))\n end", "def use_remote_pix?\r\n PictureProcessor.use_remote_pix?\r\n end", "def using_cpu?\n return @status[ 'CPU' ][ 'Active' ]\n end", "def processor?(name)\n registered?(name) && dataflow_class_for(name).ancestors.include?(Wukong::Processor)\n end", "def processor_registered? name\n Wukong.registry.registered?(name.to_s.to_sym)\n end", "def can_render_images_on?\n self.ppi && self.resolution_x && self.resolution_y\n end", "def valid_version_installed?\n image_magick_version >= minimum_image_magick_version\n end", "def processingMode(expected = nil)\n case expected\n when 1.0, 'json-ld-1.0'\n @processingMode == 'json-ld-1.0'\n when 1.1, 'json-ld-1.1'\n @processingMode.nil? || @processingMode == 'json-ld-1.1'\n when nil\n @processingMode || 'json-ld-1.1'\n else\n false\n end\n end", "def can_use_png?\n return browser_version.to_i >= 7 if browser_name== 'ie'\n true\n end", "def imagemagick7?; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a Project object identified by given string The following identifiers are accepted /gdc/md/ /gdc/projects/
def [](id, options = {}) return id if id.respond_to?(:project?) && id.project? if id == :all Project.all else if id.to_s !~ %r{^(\/gdc\/(projects|md)\/)?[a-zA-Z\d]+$} fail(ArgumentError, 'wrong type of argument. Should be either project ID or path') end id = id.match(/[a-zA-Z\d]+$/)[0] if id =~ /\// response = GoodData.get PROJECT_PATH % id Project.new response end end
[ "def [](id)\n if id.to_s !~ /^(\\/gdc\\/(projects|md)\\/)?[a-zA-Z\\d]+$/\n raise ArgumentError.new(\"wrong type of argument. Should be either project ID or path\")\n end\n\n id = id.match(/[a-zA-Z\\d]+$/)[0] if id =~ /\\//\n\n response = GoodData.get PROJECT_PATH % id\n Project.new response['project']\n end", "def [](id)\n return id if id.respond_to?(:is_project?) && id.is_project?\n if id == :all\n Project.all\n else\n if id.to_s !~ /^(\\/gdc\\/(projects|md)\\/)?[a-zA-Z\\d]+$/\n raise ArgumentError.new('wrong type of argument. Should be either project ID or path')\n end\n\n id = id.match(/[a-zA-Z\\d]+$/)[0] if id =~ /\\//\n\n response = GoodData.get PROJECT_PATH % id\n Project.new response\n end\n end", "def project(name_or_id)\n attribute = (name_or_id.is_a?(Integer) || name_or_id.to_i != 0 ? :id : :name)\n self.projects.find {|project| project.send(attribute) == name_or_id.to_s}\n end", "def parse_project_name(text)\n parsed_project = nil\n\n if text.include? 'deploy'\n /^.*deploy.*\\s(?<project>.*)\\sto.*/ =~ text\n parsed_project = project\n elsif text.include? 'current'\n /^.*current.*of\\s(?<project>.*)\\sto.*$/ =~ text\n parsed_project = project\n end\n\n return parsed_project\n end", "def find_project\n identifier = params[:project_id]\n scope = Project.active.has_module(:repository)\n project = scope.find_by_identifier(identifier.downcase)\n raise ActiveRecord::RecordNotFound unless project\n return project\n end", "def find_by_id(id)\n hash = Backlogjp.base._command \"getProject\", id\n\n Project.new(hash) unless hash.empty?\n end", "def get_project_by_id(id)\n require_relative 'telerivet/project'\n Project.new(self, self.do_request(\"GET\", get_base_api_path() + \"/projects/#{id}\"))\n end", "def extract_project(a_string)\n a_string.scan(/([a-zA-Z]*)-?(\\d*)/).first\nend", "def get_project(name)\n params = {\n 'command' => 'listProjects',\n\t'listall' => true\n }\n\n json = send_request(params)\n projects = json['project']\n return nil unless projects\n\n projects.each { |n|\n if name.is_uuid? then\n return n if n['id'] == name\n else\n return n if n['name'] == name\n end\n }\n nil\n end", "def project_by_name(project_name)\n projects.find { |project| project['name'].casecmp(project_name) == 0 }\n end", "def find_project_by_id(id)\n projects.find_by_id(id)\n end", "def find_project\n identifier = get_project_identifier\n project = Project.find_by_identifier(identifier.downcase)\n raise ActiveRecord::RecordNotFound, \"No project found with identifier '#{identifier}'\" if project.nil?\n return project\n end", "def get_project(name)\n @projects[name]\n end", "def gcloud_project_id\n stdout = Open3.capture3(\"gcloud config list project\").first\n stdout.scan(/project = (.*)/).first.first\nend", "def find_project(id) # Finds a project by id -> Project obj\n @project = Project.find_by_id(id)\n end", "def project(name)\n @projects.find { |p| p.name == name }\n end", "def project(id)\n @xml.search(\"object[@id='#{id}']\")\n end", "def get_project(name, owner_id)\n get :get_project, :name => name, :owner_id => owner_id\n end", "def get_project(project_id)\n get \"projects/#{project_id}\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets author of project
def author # TODO: Return object instead @json['project']['meta']['author'] end
[ "def author\n @author ||= run 'git config --get user.name'\n end", "def get_author()\n return @author\n end", "def author\n @author || 'Unknown'\n end", "def author\n return @author\n end", "def author\n file.version.author.name\n end", "def author\n page.version.author.name\n end", "def author\n @info[:Author]\n end", "def git_author_name\n `git log #{git_sha} -n 1 --pretty=%an`.chomp\n end", "def author\n @title_pages.each { |tp| tp.author and return tp.author }\n nil\n end", "def commit_author(commit)\n h commit.author.name\n end", "def author\n owner_name.empty? ? owner_username : owner_name\n end", "def author\n parse('app.author')\n end", "def git_author_email\n `git log #{git_sha} -n 1 --pretty=%ae`.chomp\n end", "def author\n comments.first.author\n end", "def author\n authors.first\n end", "def get_author_username\n return User.find_by(id: self.author_id).username\n end", "def author\n ['@',self.user.id, self.user.name.split().join].join('-')\n end", "def author\n @author ||= begin\n name = grit.config['user.name']\n email = grit.config['user.email']\n Grit::Actor.new(name, email)\n end\n end", "def get_author(id)\n return @client.raw(\"get\", \"/content/authors/#{id}\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets ruby wrapped raw project JSON data
def data raw_data['project'] end
[ "def getProject(projectName)\n data = CLIENT.repository(projectName)\n return data\nend", "def get_project_info(project, all_data = true)\n result = @client.api_helper.get_response(Config::TODOIST_PROJECTS_GET_COMMAND, {project_id: project.id, all_data: true})\n \n project = result[\"project\"] ? ParseHelper.make_object(result[\"project\"]) : nil\n notes = result[\"notes\"] ? ParseHelper.make_objects_as_hash(result[\"notes\"]) : nil\n return {\"project\" => project, \"notes\" => notes}\n end", "def getProjectID()\n result = RestClient.get GITHUB_API + PROJECTS_PATH, :accept => 'application/vnd.github.inertia-preview+json', :'Authorization' => 'token ' + CONFIG['OAUTH']\n result = JSON.parse(result) \n end", "def get_project_info()\n GitBox::base_uri @server\n GitBox::basic_auth @user, @pass\n GitBox::get(\"/projects/#{@project}.json\")\n end", "def metadata\n project_metadata&.data\n end", "def details\n get(\"project/details\")[\"project\"]\n end", "def details\n get(\"/project/details\")[\"project\"]\n end", "def get_json\n return JSON(@asset_repo.get_json(@pid.gsub(\"druid:\", \"\")))\n rescue => e\n return nil\n end", "def gem_data(name)\n query_str = File.join(CONFIG[:api_url], name + '.json')\n uri = URI.parse(query_str)\n resp = Net::HTTP.get_response(uri)\n begin\n resp.value\n JSON.parse(resp.body)\n rescue\n raise resp.body\n end\n end", "def to_project\n { project: { uuid: project_id,\n name: project['project_name'],\n client: project['client_name']\n } }\n end", "def json_data; end", "def project(project=nil)\n return nil if not project\n cmd = {\"cmd\" => \"viewProject\", \"token\" => @token}\n cmd = {\"ixProject\" => project.to_s}.merge(cmd) if project.class == Fixnum\n cmd = {\"sProject\" => project}.merge(cmd) if project.class == String\n result = Hpricot.XML(@connection.post(@api_url,to_params(cmd)).body)\n return_value = list_process(result,\"project\",\"sProject\")\n return_value[return_value.keys[0]]\n end", "def data\n Github::Api.new(github_id).parse\n end", "def parse(json)\n projects = super(json)\n projects.collect do |raw_project|\n project = Project.new\n project.id = raw_project[\"id\"]\n project.name = raw_project[\"name\"]\n project.count = raw_project[\"count\"]\n project\n end\n end", "def build_project\n @id ||= @project.at('id').inner_html\n @api_url ||= \"#{CONFIG[:api_location]}/projects/#{@id}\"\n @url ||= \"http://www.pivotaltracker.com/projects/#{@id}\"\n @name = @project.at('name').inner_html\n @iteration_length = @project.at('iteration_length').inner_html\n @week_start_day = @project.at('week_start_day').inner_html\n @point_scale = @project.at('point_scale').inner_html.split(',')\n end", "def to_json_raw_object()\n #This is a stub, used for indexing\n end", "def project_details(project_id)\n return get(\"/projects/#{project_id}\")\n end", "def getActualJsonObject()\n return $jsonObjectMain\nend", "def get(projectId)\r\n\t\t\t\tresponse = ZohoHTTPClient.get(getProjectUrl(projectId),getQueryMap)\r\n\t\t\t\treturn $projectParser.getProject(response)\r\n\t\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes dashboards for project
def delete_dashboards Dashboard.all.map { |data| Dashboard[data['link']] }.each { |d| d.delete } end
[ "def delete_dashboards\n Dashboard.all.map { |data| Dashboard[data['link']] }.each(&:delete)\n end", "def destroy\n return render_not_found('dashboard') unless dashboard\n authorize! :destroy_impac_dashboards, dashboard\n\n if dashboard.destroy\n MnoEnterprise::EventLogger.info('dashboard_delete', current_user.id, 'Dashboard Deletion', dashboard)\n head status: :ok\n else\n render_bad_request('destroy dashboard', 'Unable to destroy dashboard')\n end\n end", "def destroy\n conf.delete 'dashboard'\n end", "def destroy\n @dashboard_project.destroy\n respond_to do |format|\n format.html { redirect_to dashboard_projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_dashboard(dash_id)\n @dash_service.delete_dashboard(dash_id)\n end", "def delete_stream_dashboard(project_id, stream_dashboard_id)\n delete \"projects/#{project_id}/streamDashboards/#{stream_dashboard_id}\"\n end", "def delete_dashboard( name )\n\n raise ArgumentError.new(format('wrong type. \\'name\\' must be an String, given \\'%s\\'', name.class.to_s)) unless( name.is_a?(String) )\n raise ArgumentError.new('missing name') if( name.size.zero? )\n\n endpoint = format( '/api/dashboards/db/%s', slug(name) )\n\n @logger.debug(\"Deleting dashboard #{slug(name)} (DELETE #{endpoint})\") if @debug\n\n delete(endpoint)\n end", "def destroy\n @dashboard = Dashboard.find(params[:id])\n @dashboard.destroy\n\n respond_to do |format|\n format.html { redirect_to dashboards_url }\n format.json { head :ok }\n end\n end", "def destroy\n @dashboard = Dashboard.find(params[:id])\n @dashboard.destroy\n\n respond_to do |format|\n format.html { redirect_to dashboards_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @dashboard.destroy\n respond_to do |format|\n format.html { redirect_to dashboards_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @dashboard = Dashboard.find(params[:id])\n @dashboard.destroy\n\n respond_to do |format|\n format.html { redirect_to(dashboards_url) }\n format.xml { head :ok }\n end\n end", "def delete_board(dashboard_id)\n request(Net::HTTP::Delete, \"/api/#{API_VERSION}/#{RESOURCE_NAME}/#{dashboard_id}\", nil, nil, false)\n end", "def destroy\r\n @dashboard.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to(default_dashboard_path) }\r\n format.xml { head :ok }\r\n end\r\n end", "def destroy\n @api_v1_metrics_dashboard.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_metrics_dashboards_url, notice: 'Metrics dashboard was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n appctrl_delete( 'Project' )\n end", "def destroy\n @api_v1_groups_metrics_dashboard.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_groups_metrics_dashboards_url, notice: 'Groups metrics dashboard was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_data\n Report.plugin_matrix.each do |resource_name, measurements|\n model = Object.const_get((resource_name + 'Resource').camelcase(:upper))\n model.dataset.all.each(&:delete)\n\n measurements.each do |measurement_name|\n table = Plugin.where(name: measurement_name).first.storage_table\n Iam.settings.DB[table.to_sym].delete\n end\n end\n Iam.settings.DB[:projects].delete\n Iam.settings.DB[:clients].delete\n end", "def destroy\n @api_v1_shared_metrics_dashboard.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_shared_metrics_dashboards_url, notice: 'Shared metrics dashboard was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @data_dashboard.destroy\n respond_to do |format|\n format.html { redirect_to data_dashboards_url, notice: 'Data dashboard was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets project role byt its summary
def get_role_by_summary(role_summary, role_list = roles) role_list.each do |role| return role if role.summary.downcase == role_summary.downcase end nil end
[ "def summary\n @json['projectRole']['meta']['summary']\n end", "def get_role user\n project_role_user = ProjectRoleUser.where(:project_id => self, :user_id => user).first\n if project_role_user\n project_role_user.role.name\n else\n nil\n end\n end", "def role_for_user(user)\n user.roles.where(:project_id => self.id).first.try(:print_role)\n end", "def display_role\n ROLE_LIST[self.role]\n end", "def getRole\r\n\t\t\t\t\treturn @role\r\n\t\t\t\tend", "def role\n @role\n end", "def role\n return @role\n end", "def print_role\n ROLES[self.role_id]\n end", "def role_in_project(project)\n if project.scrum_master == self\n return :scrum_master\n elsif project.product_owner == self\n return :product_owner\n elsif project.team_member_ids.include?(self.id.to_s)\n return :team_member\n elsif\n project.stakeholder_ids.include?(self.id.to_s)\n return :stakeholder\n end\n nil\n end", "def detailed_roles\n return @detailed_roles\n end", "def role_for_project(project)\n # No role on archived projects\n return nil unless project && project.active?\n if logged?\n # Find project membership\n membership = memberships.detect {|m| m.project_id == project.id}\n if membership\n membership.role\n else\n @role_non_member ||= Role.non_member\n end\n else\n @role_anonymous ||= Role.anonymous\n end\n end", "def description_for(role)\n role_descriptions[role]\n end", "def description_for(role)\n role_descriptions[role]\n end", "def research_role role\n return case role\n when 'primary-pi' then 'PI'\n when 'pi' then 'OP'\n when 'co-investigator' then 'OP'\n when 'faculty-collaborator' then 'RC'\n when 'consultant' then 'RC'\n when 'staff-scientist' then 'OP'\n when 'postdoc' then 'OP'\n when 'grad-research-assistant' then 'SC'\n when 'undergrad-research-assistant' then 'SC'\n when 'research-assistant-coordinator' then 'SC'\n when 'technician' then 'OP'\n when 'mentor' then 'RC'\n when 'general-access-user' then 'RC'\n when 'business-grants-manager' then 'SC'\n when 'research-nurse' then 'N'\n when 'other' then 'RC'\n else 'NA'\n end\n end", "def role; end", "def title\n @json['projectRole']['meta']['title']\n end", "def role\n template.dig('Metadata', 'Role')\n end", "def projects_by_role\n return @projects_by_role if @projects_by_role\n\n @projects_by_role = Hash.new { |h, k| h[k]=[] }\n memberships.each do |membership|\n membership.roles.each do |role|\n @projects_by_role[role] << membership.project if membership.project\n end\n end\n @projects_by_role.each do |role, projects|\n projects.uniq!\n end\n\n @projects_by_role\n end", "def role\n @instance['role']\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns invitations to project
def invitations res = [] tmp = GoodData.get @json['project']['links']['invitations'] tmp['invitations'].each do |invitation| res << GoodData::Invitation.new(invitation) end res end
[ "def invitations\n invitations = client.get @json['project']['links']['invitations']\n invitations['invitations'].pmap do |invitation|\n client.create GoodData::Invitation, invitation\n end\n end", "def invitations\n @title = \"Invitaciones\"\n @invitations = GetInvitationsForUser.call(@user)\n end", "def list_invitations\n Invitation.find(:flow_id => id)\n end", "def pending_project_invites\n ProjectInvite.where(invited_organisation_uri: self.uri, open: true)\n end", "def organization_invitations(org, options = {})\n get \"#{Organization.path org}/invitations\", options\n end", "def invitations\n Invitation.arel_table\n end", "def invitations(user_id = nil)\n if user_id\n @tropo_client.get(\"users/#{user_id}/invitations\")\n else\n @tropo_client.get(\"invitations\")\n end\n end", "def invite_users\n @project = Project.find(params[:id])\n end", "def team_invitations(team_id, options = {})\n get \"teams/#{team_id}/invitations\", options\n end", "def invites\n raise 'Tried to request invites from a non-server channel' unless server\n\n invites = JSON.parse(API::Channel.invites(@bot.token, @id))\n invites.map { |invite_data| Invite.new(invite_data, @bot) }\n end", "def invited_users\n User.where(invited_by_id: self.id, invited_by_type: 'Organization', invitation_accepted_at: nil)\n end", "def find_project_invitations(project_id, opts = {})\n data, _status_code, _headers = find_project_invitations_with_http_info(project_id, opts)\n data\n end", "def invites_from_me\n invites.where(:created_by => self)\n end", "def friend_invitations\n get_call(\"user/#{user_id}/friends/invitations.json\")\n end", "def organization_invitations\n request = get '/1/organizations/invitations'\n convert_to_mashes request\n end", "def invitations_url\n \"https://github.com/#{context.repo}/invitations\"\n end", "def index\n @pending_invitations = @organization.invitations.pending\n @declined_invitations = @organization.invitations.declined\n @contributors = @organization.contributors\n @invitation = Invitation.new(organization: @organization)\n\n authorize! @invitation\n end", "def group_invites\n @invites = GroupsController.group_invites current_user\n end", "def team_invitations(team_id, options = T.unsafe(nil)); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if this object instance is project
def project? true end
[ "def is_for_project?\n not self.project.nil?\n end", "def project?\n course_type_name == \"project\"\n end", "def has_project?\n !project_id.nil? && project.visible\n end", "def belongs_to_project?(project)\n (source_type == \"project\") &&\n (project_id == project.id)\n end", "def project_create?\n is_project_create\n end", "def core_project?\n @core_project\n end", "def active?\n self.project_active\n end", "def package_project_valid?\n Project.first(:code => metadata[\"dmd-project\"], :account => {:code => metadata[\"dmd-account\"]}) != nil\n end", "def has_project?(name)\n available_projects.has_key?(name)\n end", "def project_path?\n @project_path && (! @project_path.empty?)\n end", "def no_project?(config)\n !config.has_key?(:project)\n end", "def owner?(project)\n if id == project.user.id\n true\n else\n false\n end\n end", "def project_exists?(name)\n projects.include?(name)\n end", "def is_assigned?(project)\n projects.include?(project)\n end", "def has_loaded_project?(name)\n loaded_projects.has_key?(name)\n end", "def create_project?\n return true if self.admin? # admin always true\n \n # False if they have not paid and they have added at least one project\n return false if self.subscription.nil? && self.projects.count >= 1\n \n # False if they have not paid\n return false if self.subscription.nil? && 14.days.ago > self.created_at \n return true\n end", "def has_config?\n configatron.projects[@project_code]\n end", "def construction_project?\n self.category_ids.include?(4)\n end", "def InTaskHierarchy?()\n return @ProjectFile != nil\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets project update date
def updated DateTime.parse(@json['project']['meta']['updated']) end
[ "def updated_at\n Time.parse(github_repo_info['updated_at'])\n end", "def updated_for_repo(repo)\n repo.updated_at.iso8601\n end", "def update_project_time\n self.project.update_project_time\n end", "def updated_date_time\n return @updated_date_time\n end", "def last_update_date_time\n return @last_update_date_time\n end", "def reporthelp_updated_at( report )\n return apphelp_date( report.updated_at )\n end", "def last_update_date\n self.forum_posts.last_posting_date\n end", "def last_updated\n self.dig_for_datetime(\"lastUpdateOn\")\n end", "def last_updated\n self.dig_for_datetime(\"companySummary\", \"lastUpdateOn\")\n end", "def last_status_date\n status = get_status\n date = nil\n date = status.updated_at if status\n self.projects.each { |p|\n sub = p.last_status_date\n date = sub if sub and (date == nil or sub > date)\n }\n return date\n end", "def date\n data[\"date\"] ||= (draft? ? source_file_mtime : site.time)\n end", "def user_returned_date\n (updated_at).strftime(\"%d/%m/%Y\")\n end", "def last_updated\n time = self.updated_at\n if time < Time.now - (3600 * 24)\n time.strftime(\"%b %-d, %Y\")\n else\n time.strftime(\"%l:%M %p\")\n end\n end", "def updated_at\n revision.created_at\n end", "def version_date\n vc = VersionCommitter.where(version_id: uri)\n @created = vc.first.created_at unless vc.empty?\n end", "def last_status_update_date_time\n return @last_status_update_date_time\n end", "def submitted_at\n self.latest_version.created_at.strftime(\"%a. %-m/%-d, %Y\")\n end", "def last_updated_date_time\n return @last_updated_date_time\n end", "def release_date_time\n return @release_date_time\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run validation on project Valid settins for validation are (default all): ldm Checks the consistency of LDM objects. pdm Checks LDM to PDM mapping consistency, also checks PDM reference integrity. metric_filter Checks metadata for inconsistent metric filters. invalid_objects Checks metadata for invalid/corrupted objects. asyncTask response
def validate(filters = %w(ldm, pdm, metric_filter, invalid_objects)) response = GoodData.post "#{GoodData.project.md['validate-project']}", 'validateProject' => filters polling_link = response['asyncTask']['link']['poll'] polling_result = GoodData.get(polling_link) while polling_result['wTaskStatus'] && polling_result['wTaskStatus']['status'] == 'RUNNING' sleep(3) polling_result = GoodData.get(polling_link) end polling_result end
[ "def validate(filters = %w(ldm pdm metric_filter invalid_objects))\n response = GoodData.post \"#{GoodData.project.md['validate-project']}\", 'validateProject' => filters\n polling_link = response['asyncTask']['link']['poll']\n GoodData.poll_on_response(polling_link) do |body|\n body['wTaskStatus'] && body['wTaskStatus']['status'] == 'RUNNING'\n end\n end", "def validate(filters = %w(ldm pdm metric_filter invalid_objects))\n response = client.post \"#{md['validate-project']}\", 'validateProject' => filters\n polling_link = response['asyncTask']['link']['poll']\n client.poll_on_response(polling_link) do |body|\n body['wTaskStatus'] && body['wTaskStatus']['status'] == 'RUNNING'\n end\n end", "def run_on_project\n @errors = []\n\n # run validations against it\n # TODO: Move validation classes to class level definition\n @validations.each do |val_clazz|\n (@errors << run_validation(@project, val_clazz)).flatten!\n end\n\n if @errors.size == 0\n outputs 'VALIDATE', 'OK, model is consistent.', :ok\n else\n outputs 'VALIDATE', 'ERROR, detected inconsistencies:', :error\n @errors.each do |val_error|\n outputs 'VALIDATE', val_error.to_s, :error\n end\n end\n\n @errors\n end", "def run_validation(project, validation_class)\n $log.debug \"Running validation class #{validation_class}\"\n val_object = validation_class.new(project)\n val_object.run_validations\n val_object.errors\n end", "def validate\n validate_localizations_repo\n validate_project_repo\n end", "def check_project\n return if project.dataset_names.empty?\n return unless project.done_preprocessing?(false)\n to_run = project.next_distances(true)\n to_run = project.next_inclade(true) if to_run.nil?\n queue_job(to_run) unless to_run.nil?\n end", "def perform_validations\n error_count = 0\n Pkg::Params::VALIDATIONS.each do |v|\n variable_name = v[:var]\n variable_value = self.instance_variable_get(\"@#{v[:var]}\")\n validations = v[:validations]\n validations.each do |validation|\n unless Pkg::ConfigValidations.send(validation, variable_value)\n warn \"Warning: variable \\\"#{variable_name}\\\" failed validation \\\"#{validation}\\\"\"\n error_count += 1\n end\n end\n end\n\n if error_count != 0\n warn \"Warning: #{error_count} validation failure(s).\"\n end\n end", "def validate\n unless TrueClass === @obsolete or FalseClass === @obsolete then\n raise RuntimeError.new( 'task validation failed: obsolete must be true or false ')\n end\n unless @id.is_a? Integer then\n raise RuntimeError.new( 'task validation failed: id must be an Integer' )\n end\n unless @role_id.is_a? Integer or @role_id.nil? then\n raise RuntimeError.new( 'task validation failed: role_id must be nil or an Integer' )\n end\n unless @label.is_a? String then\n raise RuntimeError.new( 'task validation failed: label must be a String' )\n end\n unless @inflows.is_a? Array then\n raise RuntimeError.new( 'task validation failed: incoming flows must be an Array' )\n else\n @inflows.each do |f|\n unless f.is_a? WorkFlowFlow\n raise RuntimeError.new( 'task validation failed: an incoming flow is not a WorkFlowFlow' )\n end\n end\n end\n unless @outflows.is_a? Array then\n raise RuntimeError.new( 'task validation failed: outgoing flows must be an Array' )\n else\n @outflows.each do |f|\n unless f.is_a? WorkFlowFlow\n raise RuntimeError.new( 'task validation failed: an outgoing flow is not a WorkFlowFlow' )\n end\n end\n end\n end", "def run_validation(vmode)\n validate(vmode)\n self\n end", "def validate()\n\t\t\traise InvalidDataError, 'Cannot validate an empty definition.' unless @csdl.length > 0\n\n\t\t\tbegin\n\t\t\t\tres = @user.callAPI('validate', { 'csdl' => @csdl })\n\n\t\t\t\tif res.has_key?('dpu')\n\t\t\t\t\t@total_dpu = Float(res['dpu'])\n\t\t\t\telse\n\t\t\t\t\traise CompileFailedError, 'Validated successfully but no DPU in the response'\n\t\t\t\tend\n\n\t\t\t\tif res.has_key?('created_at')\n\t\t\t\t\t@created_at = Date.parse(res['created_at'])\n\t\t\t\telse\n\t\t\t\t\traise CompileFailedError, 'Validated successfully but no created_at in the response'\n\t\t\t\tend\n\t\t\trescue APIError => err\n\t\t\t\tclearHash()\n\n\t\t\t\tcase err.http_code\n\t\t\t\twhen 400\n\t\t\t\t\traise CompileFailedError, err\n\t\t\t\telse\n\t\t\t\t\traise APIError('Unexpected APIError code: ' + err.http_code.to_s + ' [' + err.inspect + ']', err.http_code)\n\t\t\t\tend\n\t\t\tend\n\t\tend", "def validate()\n validate_start_probabilities()\n validate_exit_probabilities()\n validate_emission_probabilities()\n end", "def run_validate(target_dir)\n commands[:validate_command].run({ :target_dir => target_dir })\n end", "def custom_validations\n self.validate_baseline && validate_baseline_date && \n self.validate_trial_days && self.validates_goal_name && self.validation_due_date\n end", "def run\n runner = self\n @test_cases.each do |path|\n next if ENV['TEST_CASE'] && !File.basename(path).match(ENV['TEST_CASE'])\n\n Aws::ModelValidators.load_json(path).tap do |test_case|\n\n models = test_case.inject({}) { |h,(k,v)| h[k.to_sym] = v; h }\n errors = models.delete(:errors)\n\n @group.it(File.basename(path[0..-6])) do\n pending unless errors\n results = described_class.new.validate(models, apply_schema: false)\n unless runner.results_match?(results, errors)\n expect(results).to eq(errors)\n end\n end\n\n end\n end\n end", "def all_models_validate\n errors.add consumer.errors unless consumer.valid?\n consumer.details.each do |detail|\n errors.add detail.errors unless detail.valid?\n end\n end", "def validate\n validate_internal\n end", "def run_validations(context)\n __run_validations__(context)\n end", "def validate\n validate_single_record\n\n validates_presence :oai_record_prefix\n validates_presence :oai_admin_email\n validates_presence :oai_repository_name\n\n validate_oai_admin_email_is_email\n validate_repo_set_fields\n validate_sponsor_set_fields\n end", "def validate\n validate_arguments!\n error_if_no_local_bot_found\n\n manifest = parse_manifest\n\n { 'allow_duplicates' => 'duplicates_allowed',\n 'author' => 'publisher',\n 'incremental' => 'manually_end_run',\n 'public_repository' => 'public_repo_url',\n }.each do |deprecated,field|\n if manifest[deprecated]\n puts %(WARNING: \"#{deprecated}\" is deprecated. Use \"#{field}\" instead.)\n end\n end\n\n schema = JSON.load(File.read(File.expand_path('../../../../data/schema.json', __FILE__)))\n validator = JSON::Validator.new(schema, manifest, {\n clear_cache: false,\n parse_data: false,\n record_errors: true,\n errors_as_objects: true,\n })\n\n errors = validator.validate\n if errors.any?\n messages = ['`manifest.json` is invalid. Please correct the errors:']\n errors.each do |error|\n messages << \"* #{error.fetch(:message).sub(/ in schema \\S+\\z/, '')}\"\n end\n error messages.join(\"\\n\")\n end\n\n if manifest['transformers']\n difference = manifest['transformers'].map { |transformer| transformer['file'] } - manifest['files']\n if difference.any?\n messages = ['`manifest.json` is invalid. Please correct the errors:']\n messages << \"* Some transformer files are not listed in the top-level files: #{difference.join(', ')}\"\n error messages.join(\"\\n\")\n end\n end\n\n handler = Turbot::Handlers::ValidationHandler.new\n runner = TurbotRunner::Runner.new(working_directory, :record_handler => handler)\n begin\n rc = runner.run\n rescue TurbotRunner::InvalidDataType\n messages = ['`manifest.json` is invalid. Please correct the errors:']\n messages << %(* The property '#/data_type' value \"#{manifest['data_type']}\" is not a supported data type.)\n error messages.join(\"\\n\")\n end\n\n if rc == TurbotRunner::Runner::RC_OK\n puts \"Validated #{handler.count} records!\"\n else\n puts \"Validated #{handler.count} records before bot failed!\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retrieve market id get market id from Vendor classfile match up market id and vendor id provide a collection of all vendor instances associated with market by id
def vendors ##DON'T NEED TO PASS IN AN ARGUMENT JUST THE VALUE FROM THE ARGUMENT!!!! # lookup every vendor that matches this market id FarMar::Vendor.by_market(@id) ##OMG YAY, REMEMBER THIS TO BRING IN CLASSES FOR DIFFERENT METHODS, ##bring in class object and method and pass in the id from market end
[ "def vendors\n FarMar::Vendor.all.find_all {|instance| instance.market_id == id}\n end", "def vendors\n FarMar::Vendor.by_market(id)\n end", "def vendors(market_id)\n FarMar::Vendor.all.select { |vendor| vendor.market_id == market_id }\n end", "def vendors\n return FarMar::Vendor.by_market(@market_id)\n end", "def vendors\n FarMar::Vendor.market_vendors(@market_id)\n end", "def market\n FarMar::Market.all.select { |market| market.id == id}\n end", "def vendor\n sale_vendor = Vendor.new(:id, :name, :number_of_employees, :market_id)\n Vendor.all.each do |ven_id, ven|\n if ven_id == vendor_id\n sale_vendor = ven\n end\n end\n return sale_vendor\n end", "def market\n FarMar::Market.find(self.market_id)\n end", "def products\n\t\tproducts = []\n\t\tFarMar::Vendor.all.each do |vendor|\n\t\t\tif vendor.market_id == @id\n\t\t\t\tfind_product = FarMar::Product.by_vendor(vendor.id)\n\t\t\t\tfind_product.each do |product|\n\t\t\t\t\tproducts << product\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\treturn products\n\tend", "def market\n market_id = self.market_id\n market = FarMar::Market.find(market_id)\n return market\n end", "def market\n return FarMar::Market.find(@market_id)\n end", "def vendor\n FarMar::Vendor.find(@vendor_id)\n end", "def vendors\n sql.execute('select name,url from vendors').map {|row| Vendor.new(*row)}\n end", "def products\n FarMar::Vendor.by_market(@id).flat_map { |vendor| vendor.products }\n end", "def vendor\n vendor_id = self.vendor_id\n vendor = FarMar::Vendor.find(vendor_id)\n return vendor\n end", "def products\n FarMar::Product.by_vendor(self.id)\n end", "def vendor(sale_vendor_id)\n FarMar::Vendor.by_vendor(sale_vendor_id)\n end", "def vendor_id\n @vendor_id\n end", "def vendor\n return FarMar::Vendor.find(@vendor_id)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Elect a primary server within this topology.
def elect_primary(description, servers); self; end
[ "def elect_primary!(description)\n @topology = topology.elect_primary(description, servers_list)\n end", "def elect_primary(description, servers)\n if description.replica_set_name == replica_set_name\n unless detect_stale_primary!(description)\n servers.each do |server|\n if server.primary? && server.address != description.address\n server.description.unknown!\n end\n end\n update_max_election_id(description)\n update_max_set_version(description)\n end\n else\n log_warn(\n \"Server #{description.address.to_s} has incorrect replica set name: \" +\n \"'#{description.replica_set_name}'. The current replica set name is '#{replica_set_name}'.\"\n )\n end\n self\n end", "def elect_first_available_server(job)\n # job.quantum = @quantum\n @servers.each do |server|\n # unless the server run a job, execute the job on it and exit loop\n unless !!server.job\n server.call(@timestep, job)\n @job_queue.delete(job)\n break\n end\n end\n end", "def set_primary(node)\n host, port = *node\n @primary = [host, port]\n @primary_pool = Pool.new(self, host, port, :size => @pool_size, :timeout => @timeout)\n end", "def set_primary(node)\n host, port = *node\n @primary = [host, port]\n @primary_pool = Pool.new(self, host, port, :size => @pool_size, :timeout => @pool_timeout)\n end", "def start\n retry_jobs if JR.config[:retry_jobs_at_start]\n EM.start_server(*self.config[:server], Server, self, self.storage)\n self.config[:distributors].each do |distributor|\n connect_to(distributor)\n end\n end", "def server\n\t\treturn @server ||= self.create_server\n\tend", "def force_primary(address)\n current_primary = admin_client.cluster.next_primary\n if current_primary.address == address\n raise \"Attempting to set primary to #{address} but it is already the primary\"\n end\n encourage_primary(address)\n\n if unfreeze_server(address)\n # Target server self-elected as primary, no further action is needed.\n return\n end\n\n step_down\n persistently_step_up(address)\n admin_client.cluster.next_primary.unknown!\n new_primary = admin_client.cluster.next_primary\n if new_primary.address != address\n raise \"Elected primary #{new_primary.address} is not what we wanted (#{address})\"\n end\n end", "def thread\n @primary_server ? @primary_server.thread : nil\n end", "def set_up_server\n node = Chef::Node.new\n node.name 'nothing'\n node.automatic[:platform] = 'kitchen_metal'\n node.automatic[:platform_version] = 'kitchen_metal'\n Chef::Config.local_mode = true\n run_context = Chef::RunContext.new(node, {},\n Chef::EventDispatch::Dispatcher.new(Chef::Formatters::Doc.new(STDOUT,STDERR)))\n recipe_exec = Chef::Recipe.new('kitchen_vagrant_metal',\n 'kitchen_vagrant_metal', run_context)\n\n # We require a platform, but layout in driver is optional\n recipe_exec.instance_eval get_platform_recipe\n recipe = get_driver_recipe\n recipe_exec.instance_eval recipe if recipe\n return run_context\n end", "def next_primary(ping = nil, session = nil)\n ServerSelector.primary.select_server(self, nil, session)\n end", "def primary_app_server\n @primary_app_server ||= find_servers(:roles => :app, :only => {:primary => true}).first || find_servers(:roles => :app).first\n end", "def server\n return @server if @server\n @server = runner.get_server(self)\n end", "def get_server(id)\n OpenStack::Compute::Server.new(self,id)\n end", "def unfreeze_server(address)\n begin\n direct_client(address).use('admin').database.command(replSetFreeze: 0)\n rescue Mongo::Error::OperationFailure => e\n # Mongo::Error::OperationFailure: cannot freeze node when primary or running for election. state: Primary (95)\n if e.code == 95\n # The server we want to become primary may have already become the\n # primary by holding a spontaneous election and winning due to the\n # priorities we have set.\n admin_client.cluster.servers_list.each do |server|\n server.unknown!\n end\n if admin_client.cluster.next_primary.address == address\n puts \"#{Time.now} [CT] Primary self-elected to #{address}\"\n return true\n end\n end\n raise\n end\n false\n end", "def server(name, options = {}, &blk)\n add_child(:servers, Hubcap::Server.new(self, name, options, &blk))\n end", "def master\n find_host_with_role :master\n end", "def knife_solo hostname, options={}\n Ponyup::Provisioners::KnifeSolo.define hostname, options\n Ponyup::Runner.add_setup_task \"host:#{hostname}:provision\"\n end", "def join(server, already); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sharded topologies have no replica set name.
def replica_set_name; nil; end
[ "def replica_set?; false; end", "def replica_set?\n type == Mongo::Cluster::Topology::ReplicaSetNoPrimary ||\n type == Mongo::Cluster::Topology::ReplicaSetWithPrimary\n end", "def reconfiguring_replica_set?\n err = details[\"err\"] || details[\"errmsg\"] || details[\"$err\"] || \"\"\n NOT_MASTER.include?(details[\"code\"]) || err.include?(\"not master\")\n end", "def sharded?\n $mongo_client ||= initialize_scanned_client!\n $sharded ||= ($mongo_client.cluster.sharded? || single_mongos?)\nend", "def single_rs_member?\n ClusterConfig.instance.single_server? && ClusterConfig.instance.replica_set_name\nend", "def replica_set_member?\n ok? && !(standalone? || mongos?)\n end", "def replica_set?\n type == Mongo::Cluster::Topology::ReplicaSet\n end", "def replica_set_name\n @replica_set_name ||= options[REPLICA_SET_NAME]\n end", "def check_if_has_primary\n unless topology.replica_set?\n raise ArgumentError, \"check_if_has_primary should only be called when topology is replica set, but it is #{topology.class.name.sub(/.*::/, '')}\"\n end\n\n primary = servers_list.detect do |server|\n # A primary with the wrong set name is not a primary\n server.primary? && server.description.replica_set_name == topology.replica_set_name\n end\n unless primary\n @topology = Topology::ReplicaSetNoPrimary.new(\n topology.options, topology.monitoring, self)\n end\n end", "def replicas; end", "def replica_set_name\n options[:replica_set_name]\n end", "def replicaset?\n replicaset.is_a?(String) || nodes.length > 1\n end", "def replica_set?\n $mongo_client ||= initialize_scanned_client!\n $replica_set ||= $mongo_client.cluster.replica_set?\nend", "def create_replication_set\n self.class.with_connection_error_handling { pglogical.create_publication(PUBLICATION_NAME) }\n refresh_excludes\n end", "def replica_set\n return nil if @machine.config.mongodb.nil?\n\n @machine.config.mongodb.replsets.find do |rs|\n rs.members.find do |member|\n member[:host] == @machine.name\n end\n end\n end", "def shard_swapping_prohibited?; end", "def ghost?\n ok? &&\n config['isreplicaset'] == true\n end", "def replica?\n configuration_hash[:replica]\n end", "def update_rs_with_primary_from_member\n if topology.replica_set_name != updated_desc.replica_set_name\n log_warn(\n \"Removing server #{updated_desc.address.to_s} because it has an \" +\n \"incorrect replica set name (#{updated_desc.replica_set_name}); \" +\n \"current set name is #{topology.replica_set_name}\"\n )\n remove\n check_if_has_primary\n return\n end\n\n if updated_desc.me_mismatch?\n log_warn(\n \"Removing server #{updated_desc.address.to_s} because it \" +\n \"reported itself as #{updated_desc.me}\"\n )\n remove\n check_if_has_primary\n return\n end\n\n have_primary = false\n servers_list.each do |server|\n if server.primary?\n have_primary = true\n break\n end\n end\n\n unless have_primary\n @topology = Topology::ReplicaSetNoPrimary.new(\n topology.options, topology.monitoring, self)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A sharded topology is sharded.
def sharded?; true; end
[ "def shard_swapping_prohibited?; end", "def sharded?\n $mongo_client ||= initialize_scanned_client!\n $sharded ||= ($mongo_client.cluster.sharded? || single_mongos?)\nend", "def set_sharding\n Rails.application.config.allow_sharding = params[:state]\n render :get_sharding\n end", "def needs_sharded_reflection?(owner, reflection)\n (owner.class.shards_associated? && reflection.klass.sharding_enabled?) ||\n (owner.class.dynashard_model? && reflection.klass.sharding_enabled? && owner.class.superclass.dynashard_context == reflection.klass.dynashard_context)\n end", "def choose_shard\n unless Rails.application.config.allow_sharding\n logger.info \"no sharding\"\n # when allow_sharding is false, always return the odd shard\n @shard = \"odd\"\n else\n logger.info \"sharded world\"\n @shard = params[:shard_override]\n if @shard == \"\"\n # take the last character of the IP address and sort evens and odds\n if request.remote_ip[-1].to_i % 2 == 0\n @shard = \"even\"\n else\n @shard = \"odd\"\n end\n end\n end\n logger.info \"set shard to #{@shard}\"\n end", "def sharding_enabled?\n Dynashard.enabled? && !@dynashard_context.nil?\n end", "def shard_swapping_prohibited?\n ActiveSupport::IsolatedExecutionState[:active_record_prohibit_shard_swapping]\n end", "def shard_world; end", "def choose_shard\n unless Rails.application.config.allow_sharding\n logger.info \"no sharding\"\n # when allow_sharding is false, always return the odd shard\n @shard = \"odd\"\n else\n logger.info \"sharded world\"\n @shard = params[:shard_override]\n if ! @shard\n # take the last character of the IP address and sort evens and odds\n # logger.info \"using #{ip()} as the IP and the last char is #{ip()[-1].to_i} and it is #{ip()[-1].to_i % 2 == 0}\"\n # if rand(2) == 0\n if ip()[-1].to_i % 2 == 0\n @shard = \"even\"\n else\n @shard = \"odd\"\n end\n # alternate universe\n # take the last character of the client port and sort to evens / odds\n # derp can't find it.\n # next choice: random\n # if [0,1].sample == 0\n # @shard = \"even\"\n # else\n # @shard = \"odd\"\n # end\n end\n end\n logger.info \"set shard to >>#{@shard}<<\"\n end", "def dynashard_sharded_subclass\n if sharding_enabled?\n spec = Dynashard.shard_context[dynashard_context]\n raise \"Missing #{dynashard_context} shard context\" if spec.nil?\n spec = spec.call if spec.respond_to?(:call)\n shard_klass = Dynashard.class_for(spec)\n Dynashard.sharded_model_class(shard_klass, self)\n end\n end", "def balanced_shard\n # TODO Disabling balanced shard until we rework counts to go faster\n #@_ar_sharded_balance_count ||= 0\n #@_ar_sharded_semaphore ||= Mutex.new\n #returning_shard = nil\n #\n ## Do a thread sync on the balancing agent so we don't rebalance while\n ## we are retrieving a shard class\n #@_ar_sharded_semaphore.synchronize do\n #\n # # Rebalance every 10000 lookups\n # if @_ar_sharded_balance_count.to_i > 10000\n # @_ar_sharded_laggers = []\n #\n # # Find the leaders count\n # # TODO this is a bottle neck on large sets.\n # max_count = 0\n # @_ar_cached_shard_classes.each do |shard_class|\n # curr_count = shard_class.count\n # max_count = curr_count if curr_count > max_count\n # end\n #\n # # Designate the laggers\n # # You are a lagger if you are 10% behind the leader\n # @_ar_cached_shard_classes.each do |shard_class|\n # curr_count = shard_class.count\n # @_ar_sharded_laggers << shard_class if (max_count * 0.9) > curr_count\n # end\n #\n # #After rebalancing reset the counter\n # @_ar_sharded_balance_count = 0\n # end\n #\n # # If we have laggers favor them half the time to have them catch up\n # if @_ar_sharded_laggers.present? && rand >= 0.5\n # returning_shard = @_ar_sharded_laggers.sample\n # else\n # returning_shard = random_shard\n # end\n #\n # @_ar_sharded_balance_count += 1\n #end\n #\n #returning_shard\n @_ar_cached_shard_classes.sample\n end", "def sharded_column\n @sharded_column\n end", "def prohibit_shard_swapping(enabled = true)\n prev_value = ActiveSupport::IsolatedExecutionState[:active_record_prohibit_shard_swapping]\n ActiveSupport::IsolatedExecutionState[:active_record_prohibit_shard_swapping] = enabled\n yield\n ensure\n ActiveSupport::IsolatedExecutionState[:active_record_prohibit_shard_swapping] = prev_value\n end", "def topology_start; end", "def prune_data!\n raise \"Cannot prune a shard that isn't still slaving from another shard\" unless @master.is_slave?\n unless [:initializing, :exporting, :importing].include? @state\n raise \"Shard #{self} is not in a state compatible with calling prune_data! (current state=#{@state})\"\n end\n \n tables = Table.from_config 'sharded_tables'\n \n if @state == :initializing\n @state = :exporting\n sync_configuration\n end\n \n if @state == :exporting\n stop_query_killer\n export_schemata tables\n export_data tables, @min_id, @max_id\n @state = :importing\n sync_configuration\n end\n \n if @state == :importing\n stop_query_killer\n import_schemata!\n alter_schemata if respond_to? :alter_schemata\n disable_monitoring\n restart_mysql '--skip-log-bin', '--skip-log-slave-updates', '--innodb-autoinc-lock-mode=2', '--skip-slave-start'\n import_data tables, @min_id, @max_id\n restart_mysql # to clear out previous options '--skip-log-bin', '--skip-log-slave-updates', '--innodb-autoinc-lock-mode=2'\n enable_monitoring\n start_query_killer\n end\n end", "def distributed?\n @distributed\n end", "def connected_to(role: T.unsafe(nil), shard: T.unsafe(nil), prevent_writes: T.unsafe(nil), &blk); end", "def shard\n Shard.default\n end", "def clustered_state\n super\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new version of the app in HockeyApp.
def create_version Milkrun.say "Creating new version of app in HockeyApp" body = {}.tap do |json| json[:bundle_version] = version_code json[:bundle_short_version] = version_name json[:status] = 1 end headers = {}.tap do |h| h["X-HockeyAppToken"] = token h["Accept"] = "application/json" h["Content-Type"] = "application/json" end url = "#{base_url}/#{app_id}/app_versions/new" response = Excon.post(url, body: body.to_json, connect_timeout: 10, headers: headers) if response.status != 201 Milkrun.error response.data.to_s raise "Failed to post new version to HockeyApp!" end Milkrun.say "New version created in HockeyApp" end
[ "def make_version\n version = HockeyApp::Version.new(app, client)\n version.notes = self.notes\n version.notes_type = HockeyApp::Version::NOTES_TYPES_TO_SYM.invert[self.notes_type]\n version.notify = HockeyApp::Version::NOTIFY_TO_BOOL.invert[self.notify]\n version.status = HockeyApp::Version::STATUS_TO_SYM.invert[self.status]\n version.tags = self.tags\n version\n end", "def create_new_version\n version = Google::Apis::AppengineV1beta5::Version.new(\n :id => @version_id,\n :name => \"apps/#{@app_id}/services/#{@service_id}/versions/#{@version_id}\",\n :api_version => @version_info['api_version'],\n :runtime => @version_info['runtime'],\n :threadsafe => @version_info['threadsafe'],\n :handlers => @version_info['handlers'].map do |handler|\n if handler.key?('static_files')\n Google::Apis::AppengineV1beta5::UrlMap.new(\n :url_regex => handler['url'],\n :static_files => Google::Apis::AppengineV1beta5::StaticFilesHandler.new(\n :path => handler['static_files'],\n :upload_path_regex => \"#{@bucket_uri}/#{@uploaded_files[handler][:bucket]}\"))\n elsif handler.key?('static_dir')\n # TODO(nelsona): Add support to directories\n raise 'Uploading directories is not supported'\n elsif handler.key?('script')\n Google::Apis::AppengineV1beta5::UrlMap.new(\n :url_regex => handler['url'],\n :script => Google::Apis::AppengineV1beta5::ScriptHandler.new(\n :script_path => handler['script']))\n else\n raise 'Unknown handler tye'\n end\n end\n .compact,\n :deployment => {\n :files => Hash[*@uploaded_files.map do |_, path|\n [::File.basename(path[:filename]), Google::Apis::AppengineV1beta5::FileInfo.new(\n :source_url => \"#{@bucket_uri}/#{path[:bucket]}\")]\n end\n .flatten]\n }\n )\n\n STDERR.print 'Requesting create new version for the application...'\n new_version = @app_engine.create_app_service_version(\n @app_id, @service_id, version)\n STDERR.puts ' done.'\n\n @operation_id = new_version.name.split('/').last\n end", "def create_app\n post_app('name' => app_name)\n end", "def create_application_version\n resp = @elasticbeanstalk.create_application_version({\n application_name: @app_name,\n auto_create_application: true,\n description: \"#{@app_name} version #{@sha_hash}\",\n source_bundle: {\n s3_bucket: @eb_bucket_name,\n s3_key: @zipfile_name,\n },\n version_label: @sha_hash,\n })\n\n # Make sure the application and application version were created\n if resp\n if resp.to_h[:application_version][:application_name] == @app_name and resp.to_h[:application_version][:version_label] == @sha_hash\n return true\n else\n return false\n end\n end\n end", "def create\n @version = @app.versions.new(version_params)\n\n respond_to do |format|\n if @version.save\n format.html { redirect_to user_app_version_path(@user, @app, @version), notice: 'Version was successfully created.' }\n format.json { render :show, status: :created, location: @version }\n else\n format.html { render :new }\n format.json { render json: @version.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @app_version = @app.app_versions.new(params[:app_version])\n\n respond_to do |format|\n if @app_version.save\n format.html { redirect_to(@app, :notice => 'Version was successfully created.') }\n format.xml { render :xml => @app_version, :status => :created, :location => @app_version }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @app_version.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create!\n @client.create_version(@repo_name, @package_name, @version_name)\n end", "def create_application!(name: nil, primary_language: nil, version: nil, sku: nil, bundle_id: nil, bundle_id_suffix: nil, company_name: nil)\n # First, we need to fetch the data from Apple, which we then modify with the user's values\n r = request(:get, 'ra/apps/create/?appType=ios')\n data = parse_response(r, 'data')\n\n # Now fill in the values we have\n data['versionString']['value'] = version\n data['newApp']['name']['value'] = name\n data['newApp']['bundleId']['value'] = bundle_id\n data['newApp']['primaryLanguage']['value'] = primary_language || 'English'\n data['newApp']['vendorId']['value'] = sku\n data['newApp']['bundleIdSuffix']['value'] = bundle_id_suffix\n data['companyName']['value'] = company_name if company_name\n\n # Now send back the modified hash\n r = request(:post) do |req|\n req.url 'ra/apps/create/?appType=ios'\n req.body = data.to_json\n req.headers['Content-Type'] = 'application/json'\n end\n\n data = parse_response(r, 'data')\n handle_itc_response(data)\n end", "def create\n name = shift_argument || options[:app] || ENV['PEBBLES_APP']\n validate_arguments!\n\n params = {\n \"name\" => name,\n }\n\n info = api.post_app(params).body\n\n begin\n action(\"Creating #{info['name']}\") do\n if info['create_status'] == 'creating'\n Timeout::timeout(options[:timeout].to_i) do\n loop do\n break if api.get_app(info['name']).body['create_status'] == 'complete'\n sleep 1\n end\n end\n end\n end\n\n # (options[:addons] || \"\").split(\",\").each do |addon|\n # addon.strip!\n # action(\"Adding #{addon} to #{info[\"name\"]}\") do\n # api.post_addon(info[\"name\"], addon)\n # end\n # end\n\n if buildpack = options[:buildpack]\n api.put_config_vars(info[\"name\"], \"BUILDPACK_URL\" => buildpack)\n display(\"BUILDPACK_URL=#{buildpack}\")\n end\n\n hputs([ info[\"web_url\"], git_url(info['name']) ].join(\" | \"))\n rescue Timeout::Error\n hputs(\"Timed Out! Run `pebbles status` to check for known platform issues.\")\n end\n\n unless options[:no_remote].is_a? FalseClass\n create_git_remote(options[:remote] || \"pebbles\", git_url(info['name']))\n end\n end", "def create\n name = shift_argument || options[:app] || ENV['HEROKU_APP']\n no_remote = !options[:no_remote].nil?\n remote = options[:remote]\n remote = \"heroku\" if remote == nil\n addons = options[:addons]\n password = options[:password]\n password = newpass if password == nil\n opts = \"\"\n if no_remote\n opts = opts + \"--no-remote \"\n else\n opts = opts + \"--remote #{remote}\"\n end\n opts = opts + \"--addons #{addons}\" unless addons.nil?\n system \"heroku apps:create #{name} #{opts} --stack cedar --buildpack http://github.com/heathprovost/openbd-heroku.git\"\n system \"heroku config:set OPENBD_PASSWORD=#{password} --app #{name}\"\n system \"heroku labs:enable user-env-compile --app #{name}\"\n end", "def create_pliveo_app()\n info = {\n \"answer_url\" => build_url(account_id,\"answer\"),\n \"app_name\" => account_id,\n \"hangup_url\" => build_url(account_id,\"hangup\"),\n \"fallback_url\" => build_url(account_id,\"fallback\"),\n \"message_url\" => build_url(account_id,\"message\")\n } \n # plivo call \n c = Plivo::RestAPI.new(AUTH_ID, AUTH_TOKEN)\n r = c.create_application(info)\n logger.info \"APPLICATION CREATE RESPONSE IS #{r.inspect}\"\n\n if r[0] = 201\n # app is created successfully save to database \n logger.info \"created app!\"\n prepare_for_save(info)\n end\n end", "def create\n server = Chaos::Server.new \"ssh://#{options[:server]}\"\n server.ask_user_password unless server.password?\n\n name = options[:name] || File.basename(Dir.pwd)\n app = Chaos::App.new name, server\n\n display_ \"Create app '#{app}' on '#{app.server}'...\", :topic\n app.create\n\n display_ \"Done.\", :topic\n if File.basename(Dir.pwd) == app.name\n if Dir.exist?('.git') && !app.server.host.nil? && !app.git.nil?\n if system \"git remote add #{app.server} git@#{app.server}:#{app}.git > /dev/null 2>&1\"\n display_ \"Git remote added to the current directory ('git push #{app.server} master' to deploy)\"\n end\n end\n end\n display_ \"* Git : #{app.git}\"\n display_ \"* Url : #{app.http}\"\n end", "def new\n @app_version = @app.app_versions.new(params[:app_version])\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @app_version }\n end\n end", "def write_app_version\n prompt_user \"Bumping from #{@original_version} to #{version}. Continue?\"\n File.open(File.join(Rails.root, 'VERSION'), 'w') { |file| file.write(version) }\n puts \"VERSION file saved\"\n end", "def create_new_app\n rake 'install --trace'\n FileUtils.rm_rf(rails_app)\n sh \"relevance_rails new #{rails_app} --database=#{database} --relevance-dev\"\n end", "def new\n @app_version = @app.app_versions.build\n # @app_version = AppVersion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @app_version }\n end\n end", "def create_app()\n app = OpenShift::TestApplication.new(self)\n\n $logger.info(\"Created new application #{app.name} for account #{@name}\")\n\n @apps << app\n app\n end", "def create_app name, template\n\t\t\tdata = {\n\t\t\t\t'name' => name,\n\t\t\t\t'template' => template,\n\n\t\t\t\t'token' => auth_token,\n\t\t\t}.to_json\n\n\t\t\tJSON.parse(post('/apps.json', data).body) rescue nil\n\t\tend", "def create(*args)\n if !self.is_?(App)\n self.app_name = HesCentral.application_repository_name\n end\n super(*args)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether the environment is valid for this provider.
def valid? env_keys.all? { |k| env.key?(k) } end
[ "def valid_for_environment?\n current_env = ENV['RAILS_ENV']\n self.environment.nil? || current_env.nil? || self.environment.split(/,/).include?(current_env)\n end", "def validate_envs?()\n\t\tenv = @options[:env]\n\n\t\tres = subset?([env], @envs_list)\n\t\tif ! res\n\t\t\tputs \"Environment #{env}, is not valid\"\n\t\tend\n\n\t return res\t\n\tend", "def valid?\n @scopes.empty? || present_in_access_token?\n end", "def running_protected_environment?\n protected_environments.collect(&:to_sym).include?(Rails.env.to_sym)\n end", "def valid?\n connection_valid? && company_valid?\n end", "def test_environment_valid?\n return true unless @environment == \"test\"\n !!@test_url\n end", "def ready?\n # If the environment doesn't have any required_contexts configured, just\n # return true.\n return true if environment.required_contexts.blank?\n\n # Only look at commit status contexts that are passing.\n contexts = statuses.success\n\n environment.required_contexts.each do |name|\n status = contexts.find { |c| c.context == name }\n return false unless status\n return false unless status.success?\n end\n\n true\n end", "def required_environment_variables_set?\n !!ENV['PERCY_TOKEN']\n end", "def valid?(env)\n request = Rack::Request.new(env)\n unless (access_id = request.params['AccessKeyID'])\n #puts \"AccessKeyID not found in Params\"\n return false\n end\n unless (secret_key = @accounts[access_id])\n #puts \"No SecretKey found for AccessKeyID #{access_id.inspect}\"\n return false\n end\n AuthenticatedApi::Server.valid_signature?(request, secret_key)\n end", "def valid?()\n @config_mutex.synchronize() do\n return !@config.nil?() && missing_keys(@config).empty?()\n end\n end", "def valid?\n CONFIG_KEYS.none? { |key| send(key).nil? }\n end", "def environment_configured?\n Rails.env.test? || required_vars.empty? || required_vars.all?{|var_name| !ENV[var_name].nil? && !ENV[var_name].empty?}\n end", "def valid?(context = self)\n return false if context.site_name.nil? || context.webex_id.nil?\n return false if context.password.nil? && context.session_ticket.nil?\n true\n end", "def environments?\n name == Environments\n end", "def safe_environment?\n Rails.env != \"production\"\n end", "def is_engine_environment?\n\n (@fei == get_expression_pool.engine_environment_id)\n end", "def valid?\n OGP_REQUIRED_FIELDS.all? { |k| metadata[k].present? }\n end", "def env_vars_set?\n env_var_ids = [\n 'P_USER',\n 'P_PASSWORD',\n 'P_IP_ADDRESS',\n 'P_PORT',\n 'P_SERVER_PATH',\n 'P_SECRET'\n ]\n env_var_ids.all? { |env_id| !ENV[env_id].nil? }\n end", "def environment?(key)\n config[:environment] == key\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /people_tasks GET /people_tasks.json
def index @people_tasks = TasksPerson.all respond_to do |format| format.html # index.html.erb format.json { render json: @people_tasks } end end
[ "def show\n @tasks_person = TasksPerson.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tasks_person }\n end\n end", "def index\n @resource_in_tasks = @task.resource_in_tasks\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @resource_in_tasks }\n end\n end", "def get(params = {})\n response = client.get \"/_tasks\", params.merge(action: \"tasks.list\", rest_api: \"tasks.list\")\n response.body\n end", "def show\n @task = Task.find(params[:id])\n render json: @task\n end", "def show\n @task = Task.find(params[:id])\n\n render json: @task\n end", "def list\n if params[:story_id]\n story = Story.where(id: params[:story_id]).first\n if story\n authorized_account = authorized_account_for_project story.iteration.project\n if authorized_account\n authorized_account.fetch_tasks story\n story.reload\n render json: {tasks: story.tasks}\n else\n render json: {error: I18n.t(\"request.forbidden\")}, status: :forbidden\n end\n else\n render json: {error: I18n.t(\"request.not_found\")}, status: :not_found\n end\n else\n render json: {error: \"#{I18n.t('request.bad_request')}: story_id is required.\"}, status: :bad_request\n end\n end", "def query_tasks_to_person\n begin\n id = get_entry(\"Enter id: \").to_i\n t = Menu.data_handler.get_tasks_to_person(id)\n puts \"#{t.size} tasks found\".yellow\n output_results(t)\n puts\n rescue NoMethodError\n puts \"Could not found person with id #{id}.\".red\n end\n nil\n end", "def index\n @tasks = User.find(params[:user_id]).tasks\n end", "def query_tasks(options = nil)\n require_relative 'task'\n @api.cursor(Task, get_base_api_path() + \"/tasks\", options)\n end", "def index\n if params.has_key?(:story_id)\n set_story\n json_response(@story.tasks)\n else\n json_response(Task.all)\n end\n end", "def index\n @personal_tasks = PersonalTask.all_personal_tasks(session[:userid])\n @complete = PersonalTask.all_complete_personal_tasks(session[:userid])\n @incomplete = PersonalTask.all_incomplete_personal_tasks(session[:userid])\n end", "def show\n @task_list = current_user.task_lists.find(params[:id])\n\n render json: @task_list\n end", "def index\n\n @taskable = find_teamtask\n @teamtasks = @taskable.teamtasks\n end", "def new\n @tasks_person = TasksPerson.new \n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tasks_person }\n end\n end", "def index\n @user_tasks_infos = UserTasksInfo.all\n end", "def show\n @meeting_task = MeetingTask.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @meeting_task }\n end\n end", "def task(name)\n get \"#{base_url}/tasks/#{name}\"\n end", "def show\n @internships_task = InternshipsTask.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @internships_task }\n end\n end", "def staff_post_task\n staff = params[:user_id].present? ? User.where(:id => params[:user_id]).first : current_user\n tasks = staff.tasks.map{|t| {\n id: t.id, \n title: t.event, \n start_year: get_year(t.start_date),\n start_month: get_month(t.start_date) - 1,\n start_day: get_day(t.start_date),\n start_hour: get_hour(t.start_date),\n start_minute: get_minute(t.start_date),\n end_year: get_year(t.end_date),\n end_month: get_month(t.end_date) - 1,\n end_day: get_day(t.end_date),\n end_hour: get_hour(t.end_date),\n end_minute: get_minute(t.end_date)\n }}\n render json: tasks.to_json\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /people_tasks/1 GET /people_tasks/1.json
def show @tasks_person = TasksPerson.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @tasks_person } end end
[ "def index\n @people_tasks = TasksPerson.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @people_tasks }\n end\n end", "def show\n @task = Task.find(params[:id])\n render json: @task\n end", "def show\n @task = Task.find(params[:id])\n\n render json: @task\n end", "def query_tasks_to_person\n begin\n id = get_entry(\"Enter id: \").to_i\n t = Menu.data_handler.get_tasks_to_person(id)\n puts \"#{t.size} tasks found\".yellow\n output_results(t)\n puts\n rescue NoMethodError\n puts \"Could not found person with id #{id}.\".red\n end\n nil\n end", "def index\n @resource_in_tasks = @task.resource_in_tasks\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @resource_in_tasks }\n end\n end", "def details\n params.require(:id)\n render json: Task.find(params[:id])\n end", "def task(name)\n get \"#{base_url}/tasks/#{name}\"\n end", "def show\n @subtask = Subtask.find(params[:id])\n render json: @subtask\n end", "def show\n @subtask = @task.subtasks.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @subtask }\n end\n end", "def show\n @internships_task = InternshipsTask.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @internships_task }\n end\n end", "def show\n @task_time = @task.task_times.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @task_time }\n end\n end", "def new\n @tasks_person = TasksPerson.new \n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tasks_person }\n end\n end", "def get(params = {})\n response = client.get \"/_tasks\", params.merge(action: \"tasks.list\", rest_api: \"tasks.list\")\n response.body\n end", "def show\n @task1 = Task1.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @task1 }\n end\n end", "def index\n @tasks = User.find(params[:user_id]).tasks\n end", "def show\n @meeting_task = MeetingTask.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @meeting_task }\n end\n end", "def show\n @todo_task = TodoTask.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @todo_task }\n end\n end", "def show\n @volunteer_task = VolunteerTask.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @volunteer_task }\n end\n end", "def list\n if params[:story_id]\n story = Story.where(id: params[:story_id]).first\n if story\n authorized_account = authorized_account_for_project story.iteration.project\n if authorized_account\n authorized_account.fetch_tasks story\n story.reload\n render json: {tasks: story.tasks}\n else\n render json: {error: I18n.t(\"request.forbidden\")}, status: :forbidden\n end\n else\n render json: {error: I18n.t(\"request.not_found\")}, status: :not_found\n end\n else\n render json: {error: \"#{I18n.t('request.bad_request')}: story_id is required.\"}, status: :bad_request\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /people_tasks/new GET /people_tasks/new.json
def new @tasks_person = TasksPerson.new respond_to do |format| format.html # new.html.erb format.json { render json: @tasks_person } end end
[ "def new\n @task = tasks.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task }\n end\n end", "def new\n @task = @user.tasks.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task }\n end\n end", "def new\n # raise params.inspect\n @task = Task.new \n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task }\n end\n end", "def new\n\n\n\n @task = Task.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task }\n end\n end", "def new\n @personal_task = PersonalTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @personal_task }\n end\n end", "def new\n @template_task = TemplateTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @template_task }\n end\n end", "def new\n @task = Checklists::Task.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task_list }\n end\n end", "def create\n @tasks_person = TasksPerson.new(params[:tasks_person])\n\n respond_to do |format|\n if @tasks_person.save\n format.html { redirect_to @tasks_person, notice: 'Tasks person was successfully created.' }\n format.json { render json: @tasks_person, status: :created, location: @tasks_person }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tasks_person.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task_list }\n end\n end", "def new\n @rake_task = RakeTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @rake_task }\n end\n end", "def new\n @todo_task = TodoTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @todo_task }\n end\n end", "def new\n @project = Project.find(params[:project_id])\n @task = @project.tasks.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @task }\n end\n end", "def create\n @personal_task = PersonalTask.new(params[:personal_task])\n\n respond_to do |format|\n if @personal_task.save\n format.html { redirect_to :action => \"index\", notice: 'Personal Task was successfully created !!' }\n format.json { render json: @personal_task, status: :created, location: @personal_task }\n else\n format.html { render action: \"new\" }\n format.json { render json: @personal_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @internships_task = InternshipsTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @internships_task }\n end\n end", "def new\n @type_task = TypeTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @type_task }\n end\n end", "def create\n #@task = Task.new(task_params)\n task = @task_list.tasks.create!(task_params)\n render json: task\n end", "def new\n @volunteer_task = VolunteerTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @volunteer_task }\n end\n end", "def new\n @tasktype = Tasktype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tasktype }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /people_tasks POST /people_tasks.json
def create @tasks_person = TasksPerson.new(params[:tasks_person]) respond_to do |format| if @tasks_person.save format.html { redirect_to @tasks_person, notice: 'Tasks person was successfully created.' } format.json { render json: @tasks_person, status: :created, location: @tasks_person } else format.html { render action: "new" } format.json { render json: @tasks_person.errors, status: :unprocessable_entity } end end end
[ "def create\n #@task = Task.new(task_params)\n task = @task_list.tasks.create!(task_params)\n render json: task\n end", "def staff_post_task\n staff = params[:user_id].present? ? User.where(:id => params[:user_id]).first : current_user\n tasks = staff.tasks.map{|t| {\n id: t.id, \n title: t.event, \n start_year: get_year(t.start_date),\n start_month: get_month(t.start_date) - 1,\n start_day: get_day(t.start_date),\n start_hour: get_hour(t.start_date),\n start_minute: get_minute(t.start_date),\n end_year: get_year(t.end_date),\n end_month: get_month(t.end_date) - 1,\n end_day: get_day(t.end_date),\n end_hour: get_hour(t.end_date),\n end_minute: get_minute(t.end_date)\n }}\n render json: tasks.to_json\n end", "def create\n @personal_task = PersonalTask.new(params[:personal_task])\n\n respond_to do |format|\n if @personal_task.save\n format.html { redirect_to :action => \"index\", notice: 'Personal Task was successfully created !!' }\n format.json { render json: @personal_task, status: :created, location: @personal_task }\n else\n format.html { render action: \"new\" }\n format.json { render json: @personal_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_task(name, tags= \"\", coworker_emails = \"\", reporter_emails = \"\")\n\n t = Task.new\n t.name = name\n t.tags = tags\n\n t._serialize\n\n\n Task._load(post_request(\"/users/#{@user_id}/tasks\", t._serialize))\n end", "def create\n @work_task = WorkTask.new(work_task_params)\n @work_task.user_id = current_user.id\n\n if @work_task.save\n render :json => @work_task\n else\n render json: @work_task.errors\n end\n end", "def create\n @personal_task = PersonalTask.new(personal_task_params)\n @personal_task.userid = session[:userid]\n if personal_task_params[:label] == nil || personal_task_params[:label] == \"\"\n @personal_task.label = 0\n end\n @personal_task.complete = false\n respond_to do |format|\n if @personal_task.save\n flash[:alert] = \"Task created\"\n format.html { redirect_to @personal_task }\n format.json { render action: 'show', status: :created, location: @personal_task }\n else\n format.html { render action: 'new' }\n format.json { render json: @personal_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def save\n\n # Creates an array of hashes containing data about each task\n tasks = JSON.parse(params[:task_list][\"other\"])[\"tasks\"]\n\n # Iterating through all the task hashes\n tasks.each do |task_params|\n\n # Look up the correct task from the database\n task = Task.find(task_params[\"id\"])\n\n # Update it with new data\n task.update!({\n name: task_params[\"name\"],\n start: Date.parse(task_params[\"start\"]),\n finish: Date.parse(task_params[\"end\"]),\n progress: task_params[\"progress\"].to_i\n })\n end\n end", "def create\n @internships_task = InternshipsTask.new(params[:internships_task])\n\n respond_to do |format|\n if @internships_task.save\n format.html { redirect_to @internships_task, :notice => 'Internships task was successfully created.' }\n format.json { render :json => @internships_task, :status => :created, :location => @internships_task }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @internships_task.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @api_task = Task.new(api_task_params)\n\n if @api_task.save\n render :show, status: :created\n else\n render json: @api_task.errors, status: :unprocessable_entity\n end\n end", "def create\n @task = Task.find_by_id(params[:task_id])\n @sub_task = @task.sub_tasks.create(sub_task_params)\n\n respond_to do |format|\n if @sub_task.save\n format.html { redirect_to @task, notice: 'Sub task was successfully created.' }\n format.json { render :show, status: :created, location: @sub_task }\n else\n format.html { render :new }\n format.json { render json: @sub_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @subtask = @task.subtasks.create(params[:subtask])\n respond_to do |format|\n if @subtask.save\n format.html { redirect_to [@subtask.task], notice: 'Subtask was successfully created.' }\n format.json { render json: @subtask, status: :created, location: @subtask }\n else\n format.html { render action: \"new\" }\n format.json { render json: @subtask.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n project = @user.projects.create(projects_params)\n task = Task.create(project_id: project.id, description: \"Have fun!\")\n render json: project\n end", "def create\n @project = Project.find(params[:project_id])\n @task = @project.tasks.build(params[:task])\n\n respond_to do |format|\n if @task.save\n format.html { redirect_to([@task.project, @task], :notice => 'Task was successfully created.') }\n format.json { render :json => @task, :status => :created, :location => [@task.project, @task] }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @task.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @task = Task.find(params[:task_id])\n if (@task.taskable_type == \"User\" && @task.taskable == @current_user) ||\n (@task.taskable_type == \"Event\" && @task.taskable == Event.find(params[:event_id]))\n @subtask = @task.subtasks.create(subtask_params)\n render json: @subtask\n else\n render json: { error: \"No such task for user\" }, status: :unauthorized\n end\n end", "def create\n @work_task = WorkTask.new(work_task_params)\n\n respond_to do |format|\n if @work_task.save\n format.html { redirect_to @work_task, notice: 'Work task was successfully created.' }\n format.json { render :show, status: :created, location: @work_task }\n else\n format.html { render :new }\n format.json { render json: @work_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @spiffy_task = SpiffyTask.new(spiffy_task_params)\n\n respond_to do |format|\n if @spiffy_task.save\n format.html { redirect_to @spiffy_task, notice: 'Spiffy task was successfully created.' }\n format.json { render :show, status: :created, location: @spiffy_task }\n else\n format.html { render :new }\n format.json { render json: @spiffy_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @default_task = DefaultTask.new(params[:default_task])\n\n if @default_task.save\n render json: @default_task, status: :created, location: @default_task\n else\n render json: @default_task.errors, status: :unprocessable_entity\n end\n end", "def create\n @event_task = @event.event_tasks.new(event_task_params)\n\n respond_to do |format|\n if @event_task.save\n format.html { redirect_to @event_task, notice: 'Event task was successfully created.' }\n format.json { render :show, status: :created, location: @event_task }\n else\n format.html { render :new }\n format.json { render json: @event_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @volunteer_task = VolunteerTask.new(params[:volunteer_task])\n\n respond_to do |format|\n if @volunteer_task.save\n format.html { redirect_to @volunteer_task, notice: 'Volunteer task was successfully created.' }\n format.json { render json: @volunteer_task, status: :created, location: @volunteer_task }\n else\n format.html { render action: \"new\" }\n format.json { render json: @volunteer_task.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /people_tasks/1 PUT /people_tasks/1.json
def update @tasks_person = TasksPerson.find(params[:id]) respond_to do |format| if @tasks_person.update_attributes(params[:tasks_person]) format.html { redirect_to @tasks_person, notice: 'Tasks person was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @tasks_person.errors, status: :unprocessable_entity } end end end
[ "def update\n @project = Project.find(params[:project_id])\n @task = @project.tasks.find(params[:id])\n\n respond_to do |format|\n if @task.update_attributes(params[:task])\n format.html { redirect_to([@task.project, @task], :notice => 'Task was successfully updated.') }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @task.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_task.update(api_v1_task_params)\n format.html { redirect_to @api_v1_task, notice: 'Task was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_task }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @task.update(task_param)\n render json: get_task_hash(@task)\n else\n render json: @task.errors.full_messages\n end\n end", "def save\n\n # Creates an array of hashes containing data about each task\n tasks = JSON.parse(params[:task_list][\"other\"])[\"tasks\"]\n\n # Iterating through all the task hashes\n tasks.each do |task_params|\n\n # Look up the correct task from the database\n task = Task.find(task_params[\"id\"])\n\n # Update it with new data\n task.update!({\n name: task_params[\"name\"],\n start: Date.parse(task_params[\"start\"]),\n finish: Date.parse(task_params[\"end\"]),\n progress: task_params[\"progress\"].to_i\n })\n end\n end", "def update\n @personal_task = PersonalTask.find(params[:id])\n\n respond_to do |format|\n if @personal_task.update_attributes(params[:personal_task])\n format.html { redirect_to :action => \"index\", notice: 'Personal task was successfully updated !!' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @personal_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_task.update(api_task_params)\n format.html { redirect_to @api_task, notice: 'Task was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_task }\n else\n format.html { render :edit }\n format.json { render json: @api_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def update \n\t logger.debug \"Params --------------------------------------- #{params}\"\n\n\t logger.debug \"task params --------------------------------------#{task_params}\"\n\t format_task_attributes(task_params)\n\t \n\t logger.debug \"-------------------------------------------------------------\"\n\t logger.debug \"Updated Params #{@updated_params}\"\n\t @updated_params[:id]=params[:id]\n\t @task = Task.find(@updated_params[:id])\n\t logger.debug \"#########################\"\n\t logger.debug \"Task found \"\n\t \n\t @task.assign_attributes(@updated_params)\n\t authorize! :update, @task\n\t @task.is_completed=false\n\t save_task\n\tend", "def update(options: {}, **data)\n\n refresh_with(parse(client.put(\"/tasks/#{gid}\", body: data, options: options)).first)\n end", "def update\n # raise params.to_yaml\n @task = Task.find(params[:id])\n \n respond_to do |format|\n if @task.update_attributes(params[:task])\n flash[:notice] = 'Task was successfully updated.'\n format.html { redirect_to(@task) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @task.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @task1 = Task1.find(params[:id])\n\n respond_to do |format|\n if @task1.update_attributes(params[:task1])\n format.html { redirect_to @task1, notice: 'Task1 was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @task1.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @task = Task.find(params[:task_id])\n @subtask = Subtask.find(params[:id])\n if (@task.taskable_type == \"User\" && @task.taskable == @current_user) ||\n (@task.taskable_type == \"Event\" && @task.taskable == Event.find(params[:event_id])) &&\n (@subtask.task == @task)\n @subtask.update(subtask_params)\n render json: @subtask\n else\n render json: { error: \"No such task for user\" }, status: :unauthorized\n end\n end", "def update_task(id, title, description)\n task = Task.find(id)\n task.title = title\n task.description = description\n task.save\nend", "def update\n if @work_task.update(work_task_params)\n render :json => @work_task\n else\n render :json => @work_task.errors\n end\n end", "def update\n respond_to do |format|\n if @complex_task.update(complex_task_params)\n format.html { redirect_to @complex_task, notice: 'Complex task was successfully updated.' }\n format.json { render :show, status: :ok, location: @complex_task }\n else\n format.html { render :edit }\n format.json { render json: @complex_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @subtask = @task.subtasks.find(params[:id])\n respond_to do |format|\n if @subtask.update_attributes(params[:subtask])\n format.html { redirect_to [@subtask.task], notice: 'Subtask was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @subtask.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @internships_task = InternshipsTask.find(params[:id])\n\n respond_to do |format|\n if @internships_task.update_attributes(params[:internships_task])\n format.html { redirect_to @internships_task, :notice => 'Internships task was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @internships_task.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @spiffy_task.update(spiffy_task_params)\n format.html { redirect_to @spiffy_task, notice: 'Spiffy task was successfully updated.' }\n format.json { render :show, status: :ok, location: @spiffy_task }\n else\n format.html { render :edit }\n format.json { render json: @spiffy_task.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_task(id, response)\n auth_token = $1 if response.body =~ /\"csrf-token\".*content=\"(.+)\"/ or nil\n raise \"Not authenticated to perform this action.\" if auth_token.nil?\n\n #COOKIE COOKIE COOKIE COOKIE COOKIE COOKIE\n cookie = response['set-cookie'].split('; ')[0]\n\n uri = URI.parse(\"http://fluttrly.com/tasks/#{id}\")\n http = Net::HTTP.new(uri.host, uri.port) \n request = Net::HTTP::Put.new(uri.request_uri)\n params = {\n 'authenticity_token' => auth_token,\n 'completed' => \"true\"\n }\n request[\"Cookie\"] = cookie\n request.set_form_data(params)\n response = http.request(request)\n end", "def update_task(project_id, task_id, params = {})\n c_r Lokalise::Resources::Task, :update, [project_id, task_id], params\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /people_tasks/1 DELETE /people_tasks/1.json
def destroy @tasks_person = TasksPerson.find(params[:id]) @tasks_person.destroy respond_to do |format| format.html { redirect_to people_tasks_url } format.json { head :no_content } end end
[ "def destroy\n @personal_task = PersonalTask.find(params[:id])\n @personal_task.destroy\n\n respond_to do |format|\n format.html { redirect_to personal_tasks_url }\n format.json { head :ok }\n end\n end", "def destroy\n @action_task = ActionTask.find(params[:id])\n @action_task.destroy\n\n respond_to do |format|\n format.html { redirect_to action_tasks_url }\n format.json { head :no_content }\n end\n end", "def delete_task id\n request :delete, \"tasks/#{id}\"\n nil\n end", "def destroy\n @task1 = Task1.find(params[:id])\n @task1.destroy\n\n respond_to do |format|\n format.html { redirect_to task1s_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_v1_task.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_tasks_url, notice: 'Task was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @task_entry.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @patient_task = PatientTask.find(params[:id])\n @patient_task.destroy\n\n respond_to do |format|\n format.html { redirect_to patient_tasks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @task = Task.find(params[:id])\n @task.destroy\n\n Task.find_by_name(unescape_url(params[:id]))\n respond_to do |format|\n format.html { redirect_to(tasks_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @todo_task = TodoTask.find(params[:id])\n @todo_task.destroy\n\n respond_to do |format|\n format.html { redirect_to todo_tasks_url }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @status_task = StatusTask.find(params[:id])\r\n @status_task.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to status_tasks_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @contest_task = ContestTask.find(params[:id])\n @contest_task.destroy\n\n respond_to do |format|\n format.html { redirect_to contest_tasks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @meeting_task = MeetingTask.find(params[:id])\n @meeting_task.destroy\n\n respond_to do |format|\n format.html { redirect_to meeting_tasks_url }\n format.json { head :ok }\n end\n end", "def destroy\n @internships_task = InternshipsTask.find(params[:id])\n @internships_task.destroy\n\n respond_to do |format|\n format.html { redirect_to internships_tasks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @complex_task.destroy\n respond_to do |format|\n format.html { redirect_to complex_tasks_url, notice: 'Complex task was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @rake_task = RakeTask.find(params[:id])\n @rake_task.destroy\n\n respond_to do |format|\n format.html { redirect_to rake_tasks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @resource_in_task.destroy\n\n respond_to do |format|\n format.html { redirect_to task_resource_in_tasks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_task.destroy\n respond_to do |format|\n format.html { redirect_to api_tasks_url, notice: 'Task was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @volunteer_task = VolunteerTask.find(params[:id])\n @volunteer_task.destroy\n\n respond_to do |format|\n format.html { redirect_to volunteer_tasks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @completed_task = CompletedTask.find(params[:id])\n @completed_task.destroy\n\n respond_to do |format|\n format.html { redirect_to completed_tasks_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the jira web.xml file with the soulwing (CAS library) authentication configuration
def config_web_xml() web_xml = File.readlines(self.web_xml()).map do |line| if line =~ /#{web_xml_token}/ template = File.open("#{DEPLOYER_HOME}/resources/jira_cas_web.xml") { |f| f.read() } line + ERB.new(template).result(self.send(:binding)) else line end end File.open(self.web_xml(), "w") do |io| web_xml.each { |line| io.puts(line) } end end
[ "def do_auth\r\n send_request_cgi({\r\n 'uri' => normalize_uri(target_uri.path.to_s, 'login.jsp'),\r\n 'method' => 'POST',\r\n 'cookie' => \"atlassian.xsrf.token=#{@xsrf_token}; #{@session_id}\",\r\n 'vars_post' => {\r\n 'os_username' => datastore['HttpUsername'],\r\n 'os_password' => datastore['HttpPassword'],\r\n 'os_destination' => '',\r\n 'user_role' => '',\r\n 'atl_token' => '',\r\n 'login' => 'Log+In'\r\n }\r\n })\r\n end", "def add_web_authentication_detail(xml)\n xml.WebAuthenticationDetail{\n xml.UserCredential{\n xml.Key @credentials.key\n xml.Password @credentials.password\n }\n }\n end", "def add_authentication(xml)\n xml.tag! :Authentication do\n xml.tag! :client, @options[:login]\n xml.tag! :password, @options[:password]\n end\n end", "def config_web_xml()\n web_xml = File.readlines(self.web_xml)\n \n web_xml = web_xml.map do |line|\n if line =~ /#{web_xml_token}/\n template = File.open(\"#{DEPLOYER_HOME}/resources/confluence_cas_web.xml\") { |f| f.read }\n ERB.new(template).result(self.send(:binding))\n else\n line\n end\n end\n \n File.open(self.web_xml, \"w\") do |io|\n web_xml.each { |line| io.puts(line) }\n end\n end", "def configure(jira_url:, jira_username:, jira_api_token:)\n warn \"danger-jira_sync plugin configuration is missing jira_url\" if jira_url.blank?\n warn \"danger-jira_sync plugin configuration is missing jira_username\" if jira_username.blank?\n warn \"danger-jira_sync plugin configuration is missing jira_api_token\" if jira_api_token.blank?\n\n @jira_client = JIRA::Client.new(\n site: jira_url,\n username: jira_username,\n password: jira_api_token,\n context_path: \"\",\n auth_type: :basic\n )\n end", "def add_authentication(xml)\n xml.tag! :Name, @options[:login]\n xml.tag! :Password, @options[:password]\n xml.tag! :ClientId, @options[:merchant_id]\n xml.tag! :Mode, \"P\"\n end", "def set_credentials(db_user, db_pass)\n @environments.each do |env| \n @config_doc[env]['username'] = db_user\n @config_doc[env]['password'] = db_pass\n end\n end", "def update_web_application_security(doc)\n wasec = doc.elements.to_a('//webAppSecurity')\n if wasec.empty?\n @logger.debug('sso - update detects no webAppSecurity config - add it')\n add_web_app_security(doc)\n else\n srs = doc.elements.to_a('//webAppSecurity[@ssoRequireSSL]')\n if srs.empty?\n @logger.debug('sso - update detects existing webAppSecurity with no ssoRequireSSL - update it')\n update_wasec(doc, wasec)\n end\n end\n end", "def auth_xml=(value)\n @children['auth-xml'][:value] = value\n end", "def update_configuration(xml, options = {})\n client = extract_client!(options)\n\n # The Artifactory api requires a content type of 'application/xml'.\n # See http://bit.ly/1l2IvZY\n headers = { \"Content-Type\" => \"application/xml\" }\n client.post(\"/api/system/configuration\", xml, headers)\n end", "def jira_password\r\n datastore['JIRAPASS']\r\n end", "def authenticate\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.aaaUser(name: @user, pwd: @password)\n end\n post_url = URI.encode(@baseurl.to_s + '/api/mo/aaaLogin.xml')\n puts 'POST REQUEST', post_url if @debug\n puts 'POST BODY', builder.to_xml if @debug\n puts 'Initiating authentication with APIC'\n response = @client.post(post_url, body: builder.to_xml)\n puts 'POST RESPONSE: ', response.body if @debug\n doc = Nokogiri::XML(response.body)\n fail ApicAuthenticationError,\n sprintf('Authentication error(%s): %s',\n doc.at_css('error')['code'], doc.at_css('error')['text']) \\\n if doc.at_css('error')\n fail ApicErrorResponse,\n sprintf('Unexpected HTTP Error response code(%s): %s',\n response.code, response.body) if response.code != 200\n @auth_cookie = doc.at_css('aaaLogin')['token']\n @refresh_time = doc.at_css('aaaLogin')['refreshTimeoutSeconds']\n end", "def add_authentication\n if session.open?\n self['Cookie'] = session.cookie\n else\n basic_auth(user, password)\n end\n end", "def config_user(username)\n @defaults.add('default_rhlogin', username)\n end", "def acquia_conf_auth\n user_data = JSON.parse(File.read(acquia_conf_path))\n { username: user_data['email'], password: user_data['key'] }\n end", "def configure(connection)\n connection.request :authorization, :basic, @token, ''\n end", "def authenticate\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.aaaUser(name: @user, pwd: @password)\n end\n post_url = URI::Parser.new.escape(@baseurl.to_s + '/api/mo/aaaLogin.xml')\n puts 'POST REQUEST', post_url if @debug\n puts 'POST BODY', builder.to_xml if @debug\n response = @client.post(post_url, body: builder.to_xml)\n puts 'POST RESPONSE: ', response.body if @debug\n doc = Nokogiri::XML(response.body)\n fail ApicAuthenticationError, 'Authentication error(%s): %s' % [doc.at_css('error')['code'], doc.at_css('error')['text']] \\\n if doc.at_css('error')\n fail ApicErrorResponse, 'Unexpected HTTP Error response code(%s): %s' % [response.code, response.body] if response.code != 200\n @auth_cookie = doc.at_css('aaaLogin')['token']\n @refresh_time = doc.at_css('aaaLogin')['refreshTimeoutSeconds']\n end", "def add_basic_auth(uri)\n uri.user = @configs[:username]\n uri.password = @configs[:password]\n return uri\n end", "def set_auth(domain, user, passwd)\n uri = to_resource_url(domain)\n @www_auth.set_auth(uri, user, passwd)\n reset_all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shortcut to jira entityengine.xml file
def entityengine_xml() "#{self.build_dir()}/src/edit-webapp/WEB-INF/classes/entityengine.xml" end
[ "def config_entityengine_xml()\n ee_xml = File.readlines(self.entityengine_xml()).map do |line|\n if m = /(#{Regexp.quote(self.entityengine_xml_db_token())})/.match(line)\n self.debug(m[0])\n new_str = \"#{m.pre_match}#{entityengine_db}#{m.post_match}\"\n self.debug(new_str)\n new_str\n elsif m = /(#{Regexp.quote(self.entityengine_xml_schema_token())})/.match(line)\n self.debug(m[0])\n new_str = \"#{m.pre_match}#{self.entityengine_schema()}#{m.post_match}\"\n self.debug(new_str)\n new_str\n else\n line\n end\n end\n \n File.open(self.entityengine_xml(), \"w\") do |io|\n ee_xml.each { |line| io.puts(line) }\n end\n end", "def xwork_xml()\n \"#{build_dir}/src/confluence/WEB-INF/classes/xwork.xml\"\n end", "def add_entity_from(xml)\n entity = add_entity(values_from(xml, :term, :key_column))\n xml.css('field').each { |field| entity.add_attribute_from(field) }\n entity.add_files_from(xml, path: path)\n entity\n end", "def external_entity_name\n raise \"Not implemented\"\n end", "def save(import_entity)\n $import_entity_count ||= 0\n $import_entity_count += 1\n File.open(\"import_entities-#{$import_entity_count}.xml\", 'w') { |f|\n f.write \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n<jobs>\\n#{import_entity}\\n</jobs>\"\n }\nend", "def entitystore; end", "def entity_description\n cdq.models.current.entitiesByName[name]\n end", "def import_xml(xml)\t\t\t\n\t\t\tdoc = REXML::Document.new xml\n # Cut to the context object\n\t\t\tctx = REXML::XPath.first(doc, \".//ctx:context-object\", {\"ctx\"=>\"info:ofi/fmt:xml:xsd:ctx\"})\n\t\t\tctx.attributes.each do |attr, val|\t\t\t\t\n\t\t\t\t@admin.each do |adm, vals|\n\t\t\t\t\tself.set_administration_key(adm, val) if vals[\"label\"] == attr\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tend\n\t\t\tend\n\t\t\tctx.to_a.each do | ent |\n\t\t\t\tif @@defined_entities.value?(ent.name())\n\t\t\t\t\tvar = @@defined_entities.keys[@@defined_entities.values.index(ent.name())]\n\t\t\t\t\tmeth = \"import_#{var}_node\"\n\t\t\t\t\tself.send(meth, ent)\n\t\t\t\telse\n\t\t\t\t\tself.import_custom_node(ent)\n\t\t\t\tend\n\t\t\tend\n end", "def use_xml(xml_filename)\n\t\t\tQuarto.xml_source = File.open(\"#{@project_path}/xml/#{xml_filename}\")\n\t\tend", "def web_xml()\n \"#{build_dir}/src/confluence/WEB-INF/web.xml\"\n end", "def show\n\t # Check for required parameters\n\t raise ArgumentError.new() unless params[:eid]\n\t @entity_id = params[:eid]\n\t # Create a unique name for the extjs data namespace\n\t @dns = namespace_id(@entity_id)\n\t # Verify that the user has rights\n\t module_right?(@entity_id, UR_MODULE_SYSADMIN_HUB)\n\tend", "def find_entities\n result_xml.xpath('//entry')\n end", "def printEntity()\n #Simply print the XML to Standard Out.\n puts returnEntity()\n end", "def engine_environment_id\n\n @eei ||= new_fei(\n :workflow_definition_url => 'ee',\n :workflow_definition_name => 'ee',\n :workflow_instance_id => '0',\n :expression_name => EN_ENVIRONMENT)\n end", "def seraph_config_xml()\n \"#{build_dir}/src/confluence/WEB-INF/classes/seraph-config.xml\"\n end", "def jira_str(defect_id, title)\n \"JIRA ID #{FWConfig::JIRA_ID_PREFIX}#{defect_id}\\n#{title}\"\n end", "def config_web_xml()\n web_xml = File.readlines(self.web_xml()).map do |line|\n if line =~ /#{web_xml_token}/\n template = File.open(\"#{DEPLOYER_HOME}/resources/jira_cas_web.xml\") { |f| f.read() }\n line + ERB.new(template).result(self.send(:binding))\n else\n line\n end\n end\n \n File.open(self.web_xml(), \"w\") do |io|\n web_xml.each { |line| io.puts(line) }\n end \n end", "def get_entity(eid)\n endpoint_url = URI.join(self.engine.base_url, \"entities/#{eid}?v=#{self.engine.version}\")\n\n self.get(endpoint_url, {})\n end", "def jira_url\n config.jira_url\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the jira entityengine.xml file with the correct database configs
def config_entityengine_xml() ee_xml = File.readlines(self.entityengine_xml()).map do |line| if m = /(#{Regexp.quote(self.entityengine_xml_db_token())})/.match(line) self.debug(m[0]) new_str = "#{m.pre_match}#{entityengine_db}#{m.post_match}" self.debug(new_str) new_str elsif m = /(#{Regexp.quote(self.entityengine_xml_schema_token())})/.match(line) self.debug(m[0]) new_str = "#{m.pre_match}#{self.entityengine_schema()}#{m.post_match}" self.debug(new_str) new_str else line end end File.open(self.entityengine_xml(), "w") do |io| ee_xml.each { |line| io.puts(line) } end end
[ "def update_db\n require \"../conf/db_schema.rb\"\n Knj::Db::Revision.new.init_db(\"debug\" => false, \"db\" => @db, \"schema\" => Openall_time_applet::DB_SCHEMA)\n end", "def update_db\n require \"#{File.dirname(__FILE__)}/../conf/db_schema.rb\"\n Knj::Db::Revision.new.init_db(\"debug\" => false, \"db\" => @db, \"schema\" => Openall_time_applet::DB_SCHEMA)\n end", "def entityengine_xml()\n \"#{self.build_dir()}/src/edit-webapp/WEB-INF/classes/entityengine.xml\"\n end", "def configure_database db_config\n @database = Database.new @client, *db_config.values_at('name', 'user', 'password')\n @models = db_config['models']\n @namespace = db_config['namespace'] || \"Oo\"\n logger.info %Q(Configured OpenERP database \"#{db_config['name']}\" at \"#{client.connection.host}\")\n end", "def updateDefect(defect, jiralink)\n begin\n return @db.execute(\"update v1link set jira_link=\\\"#{jiralink}\\\" where defect = \\\"#{defect}\\\"\")\n rescue SQLite3::Exception => e\n print \"Exception (v1persist): #{e}\"\n end\n end", "def update_db_settings(file_path, env, tag)\n config = YAML.load_file(file_path)\n if config[env]\n unless tag == \"master\"\n config[env][\"database\"] = \"#{config[env][\"database\"]}_#{tag}\"\n end\n save_yaml(file_path, config)\n else\n puts \"WARNING: #{env} DB not defined in database.yml\"\n end\n end", "def config_db\n enable_gem 'mysql2'\n mirror 'config/database.yml'\n database_name = project_name # ask 'database name?'\n gsub_file 'config/database.yml', /database: test/, \"database: #{database_name}\"\n end", "def entitystore; end", "def edit_build(carbon_home,location,usr,pwd,url,dialects,driver) \n\n\tFile.open(File.join(Dir.pwd,'build.xml')) do |config_file|\n\t\t# Open the document and edit the port (carbon.xml)\n\t\tconfig = Document.new(config_file)\n\t\n\t\tconfig.root.elements[14].attributes['value']=carbon_home\n\n\t\tif(dialects == 'mysql')\n\t\t\tconfig.root.elements[21].attributes['value']=location\n\t\t\tconfig.root.elements[22].attributes['value']=usr\n\t\t\tconfig.root.elements[23].attributes['value']=pwd\n\t\t\tconfig.root.elements[24].attributes['value']=url\n\t\t\tconfig.root.elements[25].attributes['value']=dialects\n\t\t\tconfig.root.elements[26].attributes['value']=driver\n\t\tend\n\n\t\tif(dialects == 'oracle')\n\t\t\tconfig.root.elements[15].attributes['value']=location\n\t\t\tconfig.root.elements[16].attributes['value']=usr\n\t\t\tconfig.root.elements[17].attributes['value']=pwd\n\t\t\tconfig.root.elements[18].attributes['value']=url\n\t\t\tconfig.root.elements[19].attributes['value']=dialects\n\t\t\tconfig.root.elements[20].attributes['value']=driver\n\t\tend\n\n\t\n\t\n\t\t# Write the result to a new file.\n\t\tformatter = REXML::Formatters::Default.new\n\t\tFile.open(File.join('result_build.xml'), 'w') do |result|\n\t\tformatter.write(config, result)\n\t\tend\n\t\n\tend \n\n\tFile.delete(File.join('build.xml'))\n\tFile.rename( File.join('result_build.xml'),File.join('build.xml') )\n\n\t#call buld.xml to setup the connection with database\n\tif(dialects == 'mysql')\n\t\tif RUBY_PLATFORM.downcase.include?(\"mswin\")\n\t\t\t`ant startServerWindows -Dscript=normal -Ddatabase.name=mysql`\n\t\telsif RUBY_PLATFORM.downcase.include?(\"linux\")\n\t\t\t`ant startServerUnix -Dscript=normal -Ddatabase.name=mysql`\n\t\tend\n\tend\n\n\tif(dialects == 'oracle')\n\t\tif RUBY_PLATFORM.downcase.include?(\"mswin\")\n\t\t\t`ant startServerWindows -Dscript=normal -Ddatabase.name=oracle`\n\t\telsif RUBY_PLATFORM.downcase.include?(\"linux\")\n\t\t\t`ant startServerUnix -Dscript=normal -Ddatabase.name=oracle`\n\t\tend\n\tend\n\nend", "def update_development_info_jira (jira_issues, name, type)\n\tif type == \"branch\"\n\t\tfield = JIRA_FIELD_BRANCH\n\telsif type == \"pull_request\"\n\t\tfield = JIRA_FIELD_PULL_REQUEST\n\tend\n\ti = 0;\n\twhile (i < jira_issues.length) do\n\t\tjira_issue = jira_issues[i].join\n\n\t\tdata = {\n\t\t\t\"fields\" => {\n\t\t\t\tfield => name\n\t\t\t}\n\t\t}.to_json\n\n\t\theaders = {\n\t :\"Authorization\" => \"Basic #{JIRA_TOKEN}\",\n\t :\"Content-Type\" => \"application/json\"\n\t }\n\n\t if jira_issue =~ /(?:|^)(JQWE-[0-9]+|PQ-[0-9]+|JTQ-[0-9]+|JRQ-[0-9]+|JCEQ-[0-9]+|JITR.+-[0-9]+|TOOLSONE-[0-9]+)(?=|$)/i\n\t\t\turl = JACKTHREADS_JIRA_URL + jira_issue\n\t\telse\n\t\t\turl = THRILLIST_JIRA_URL + jira_issue\n\t\tend\n\n\t\tresponse = RestClient.put( url, data, headers )\n\n\t\ti+=1\n\tend\n\n\t#\"customfield_10000\" = branch\n\t#\"customfield_10123\" = pull_request\nend", "def update_from(xml, *fields)\n update values_from(xml, *fields)\n save\n end", "def update\n @cloud_engine = CloudEngine.find(params[:id])\n\n respond_to do |format|\n if @cloud_engine.update_attributes(params[:cloud_engine])\n format.html { redirect_to(@cloud_engine, :notice => 'Cloud engine was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @cloud_engine.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_db(config, options = {})\r\n\r\n begin\r\n options ||= {}\r\n\r\n runtime_user = config[:username]\r\n\r\n Conn.remove_connection\r\n Conn.establish_connection config\r\n\r\n if have_db_control?\r\n warn \"WARNING: Runtime user '#{runtime_user}' has full access to the database. (this is not recommended)\" unless Rails.env.test?\r\n else\r\n raise NeedFullAccess, 'please provide update_username and update_password for a user with full access to the database' unless config[:update_username]\r\n\r\n use_config = config.dup\r\n use_config[:username] = config[:update_username]\r\n use_config[:password] = config[:update_password]\r\n\r\n Conn.remove_connection\r\n Conn.establish_connection use_config\r\n\r\n raise NeedFullAccess, 'provided update user does not have full access to the database' unless have_db_control?\r\n end\r\n\r\n unless Conn.object_exists?(VERSION_TABLE_NAME)\r\n debug 'Creating version tracking table...'\r\n db_connection.execute <<-EOSQL\r\nCREATE TABLE [#{VERSION_TABLE_NAME}] (\r\n [object_name] VARCHAR(120) NOT NULL PRIMARY KEY,\r\n [object_type] VARCHAR(40) NOT NULL,\r\n [object_version] VARCHAR(40) NOT NULL,\r\n [created] DATETIME NOT NULL,\r\n [updated] DATETIME NOT NULL,\r\n [created_by] VARCHAR(120),\r\n [updated_by] VARCHAR(120)\r\n)\r\n EOSQL\r\n end\r\n\r\n if (proc = (options[:before_update] || options[:pre_update] || @pre_update))\r\n if proc.is_a?(String)\r\n code = proc\r\n proc = Proc.new { |db_conn, user| eval code }\r\n end\r\n if proc.respond_to?(:call)\r\n debug 'Running pre-update code...'\r\n proc.call db_connection, runtime_user\r\n end\r\n end\r\n\r\n debug 'Processing source list...'\r\n sources.each do |src|\r\n src.name_prefix = table_prefix\r\n\r\n cur_ver = get_version src.prefixed_name\r\n\r\n if cur_ver\r\n raise ObjectTypeMismatch, \"object type mismatch for #{src.prefixed_name}\" unless src.type.upcase == cur_ver['object_type'].upcase\r\n if cur_ver['object_version'].to_i >= src.version.to_i\r\n debug \" > Preserving #{src.prefixed_name}...\"\r\n next # source\r\n else\r\n debug \" > Updating #{src.prefixed_name}...\"\r\n if src.is_create?\r\n db_connection.execute src.drop_sql\r\n end\r\n end\r\n else\r\n debug \" > Creating #{src.prefixed_name}...\"\r\n end\r\n\r\n db_connection.execute src.update_sql\r\n db_connection.execute src.grant_sql(runtime_user)\r\n set_version src.prefixed_name, src.type, src.version\r\n\r\n src.name_prefix = ''\r\n end\r\n\r\n if (proc = (options[:after_update] || options[:post_update] || @post_update))\r\n if proc.is_a?(String)\r\n code = proc\r\n proc = Proc.new { |db_conn, user| eval code }\r\n end\r\n if proc.respond_to?(:call)\r\n debug 'Running post-update code...'\r\n proc.call db_connection, runtime_user\r\n end\r\n end\r\n\r\n yield db_connection, runtime_user if block_given?\r\n\r\n ensure\r\n Conn.remove_connection\r\n end\r\n\r\n true\r\n end", "def update_data\n # This code is actually for the Bermuda company register\n #\n # Get all the pages containing companies...\n a_z_links = Nokogiri.HTML(open(\"https://www.roc.gov.bm/roc/rocweb.nsf/ReviewPublicRegA-Z?OpenForm\")).search(\"a\")\n # iterate through them...\n a_z_links.each do |link|\n page = Nokogiri.HTML(open(\"https://www.roc.gov.bm\" + link[:href]))\n # find all the companies in the table...\n page.search(\"//table[2]//tr\").each do |tr|\n # extract the information\n name = begin\n tr.at_xpath(\".//td[2]//a\").inner_text.strip\n rescue StandardError\n nil\n end\n company_number = begin\n tr.at(\"td a\").inner_text.strip\n rescue StandardError\n nil\n end\n incorporation_date = begin\n tr.at(\".//td[3]//a\").inner_text.to_date.to_s\n rescue StandardError\n nil\n end\n next if !name && !company_number && !incorporation_date\n\n # save the entity hash in the local database, using #save_entity helper method, which\n # validating it against the company schema first\n save_entity(name: name, company_number: company_number, incorporation_date: incorporation_date, retrieved_at: Time.now.to_s)\n end\n end\n end", "def modify_database_yml_as_needed!\n require 'yaml'\n\n db_yaml_file = File.join('config', 'database.yml')\n db_yaml = YAML.load_file(db_yaml_file)\n\n unless db_yaml[rails_env]\n notify(\"adding environment '#{rails_env}' to database.yml\") do\n test_content = db_yaml['test']\n raise \"No default database.yml entry for 'test'?!?\" unless test_content\n\n db_yaml[rails_env] = test_content.dup\n new_yaml = YAML.dump(db_yaml)\n # Get rid of the silly '---' line that YAML.dump puts at the start.\n new_yaml = new_yaml.split(\"\\n\").map { |l| l unless l =~ /^\\-+$/i }.compact.join(\"\\n\")\n File.open(db_yaml_file, 'w') { |f| f.puts new_yaml }\n end\n end\n end", "def update_configuration(xml, options = {})\n client = extract_client!(options)\n\n # The Artifactory api requires a content type of 'application/xml'.\n # See http://bit.ly/1l2IvZY\n headers = { \"Content-Type\" => \"application/xml\" }\n client.post(\"/api/system/configuration\", xml, headers)\n end", "def update_ead(filename, resources, pdf: false)\n logger.info \"Updating DAO URLs in #{filename}\"\n ead = Nokogiri::XML(File.open(filename))\n\n resources.each do |r|\n cid = r.source_metadata_identifier&.first\n component = ead.at_xpath(\"//ead:c[@id=\\'#{cid}\\']\", namespaces_for_xpath)\n create_or_update_dao(ead, component, r, pdf) if component\n end\n\n File.open(filename, \"w\") { |f| f.puts(ead.to_xml) }\n @updated_eads << filename\n end", "def update_schema(engine_name, schema)\n post(\"engines/#{engine_name}/schema\", schema)\n end", "def update\n @engine = Engine.find(params[:id])\n\n respond_to do |format|\n if @engine.update_attributes(params[:engine])\n flash[:notice] = 'Engine was successfully updated.'\n format.html { redirect_to(@engine) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @engine.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shortcut to jira seraphconfig.xml file
def seraph_config_xml() "#{self.build_dir()}/src/webapp/WEB-INF/classes/seraph-config.xml" end
[ "def seraph_config_xml()\n \"#{build_dir}/src/confluence/WEB-INF/classes/seraph-config.xml\"\n end", "def config_seraph_config_xml()\n seraph_xml = File.readlines(self.seraph_config_xml)\n \n seraph_xml = seraph_xml.map do |line|\n if m = /(#{Regexp.quote(seraph_config_xml_token)})/.match(line)\n debug(m[0])\n debug(\"#{m.pre_match}#{cas_authenticator_class}#{m.post_match}\")\n \"#{m.pre_match}#{cas_authenticator_class}#{m.post_match}\"\n else\n line\n end\n end\n \n File.open(self.seraph_config_xml, \"w\") do |io|\n seraph_xml.each { |line| io.puts(line) }\n end\n end", "def config_seraph_config_xml()\n seraph_xml = File.readlines(self.seraph_config_xml()).map do |line|\n if m = /(#{Regexp.quote(self.seraph_config_xml_auth_class_token())})/.match(line)\n self.debug(m[0])\n new_str = \"#{m.pre_match}#{self.cas_authenticator_class()}#{m.post_match}\"\n self.debug(new_str)\n new_str\n elsif m = /(#{Regexp.quote(self.seraph_config_xml_logout_url_token())})/.match(line)\n self.debug(m[0])\n new_str = \"#{m.pre_match}#{self.cas_server_url()}/logout#{m.post_match}\"\n self.debug(new_str)\n new_str\n else\n line\n end\n end\n \n File.open(self.seraph_config_xml(), \"w\") do |io|\n seraph_xml.each { |line| io.puts(line) }\n end\n end", "def jira_url\n config.jira_url\n end", "def config_file\n CONFIG_FILE\n end", "def configuration_file_path; end", "def john_config_file\n ::File.join(::Msf::Config.data_directory, \"jtr\", \"john.conf\")\n end", "def config\n respond_to { |format| format.xml }\n end", "def config_web_xml()\n web_xml = File.readlines(self.web_xml()).map do |line|\n if line =~ /#{web_xml_token}/\n template = File.open(\"#{DEPLOYER_HOME}/resources/jira_cas_web.xml\") { |f| f.read() }\n line + ERB.new(template).result(self.send(:binding))\n else\n line\n end\n end\n \n File.open(self.web_xml(), \"w\") do |io|\n web_xml.each { |line| io.puts(line) }\n end \n end", "def config_file\n @config_file\n end", "def config_path\n File.join( solr_home, 'conf' )\n end", "def post_config(job_name, xml)\n @client.post_config(\"/job/#{job_name}/config.xml\", xml)\n end", "def post_config(job_name, xml)\n @logger.info \"Posting the config.xml of '#{job_name}'\"\n @client.post_config(\"/job/#{path_encode job_name}/config.xml\", xml)\n end", "def configure(jira_url:, jira_username:, jira_api_token:)\n warn \"danger-jira_sync plugin configuration is missing jira_url\" if jira_url.blank?\n warn \"danger-jira_sync plugin configuration is missing jira_username\" if jira_username.blank?\n warn \"danger-jira_sync plugin configuration is missing jira_api_token\" if jira_api_token.blank?\n\n @jira_client = JIRA::Client.new(\n site: jira_url,\n username: jira_username,\n password: jira_api_token,\n context_path: \"\",\n auth_type: :basic\n )\n end", "def jobconf path\n log_path = File.join(path, \"_logs\", \"history\")\n jobconf_xml = fs.entries(log_path).select{|path| path =~ /.*.xml/}.first\n fs.open(jobconf_xml).read\n end", "def parse_config\n end", "def config\n get('/_config')\n end", "def declare_configuration_options\n ws.config.declare \"daemon_polling_period\", \"string\",\n default: \"60\",\n doc: \"Enter the github polling period\"\n\n ws.config.declare \"daemon_buildbot_host\", \"string\",\n default: \"localhost\",\n doc: \"Enter builbot host/ip\"\n\n ws.config.declare \"daemon_buildbot_port\", \"string\",\n default: \"8010\",\n doc: \"Enter buildbot http port\"\n\n ws.config.declare \"daemon_project\", \"string\",\n default: File.basename(ws.root_dir),\n doc: \"Enter the project name\"\n\n ws.config.declare \"daemon_max_age\", \"string\",\n default: \"120\",\n doc: \"Enter events and pull requests max age\"\n end", "def settings()\n configatron\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the jira seraph_config.xml file with the soulwing authenticator.
def config_seraph_config_xml() seraph_xml = File.readlines(self.seraph_config_xml()).map do |line| if m = /(#{Regexp.quote(self.seraph_config_xml_auth_class_token())})/.match(line) self.debug(m[0]) new_str = "#{m.pre_match}#{self.cas_authenticator_class()}#{m.post_match}" self.debug(new_str) new_str elsif m = /(#{Regexp.quote(self.seraph_config_xml_logout_url_token())})/.match(line) self.debug(m[0]) new_str = "#{m.pre_match}#{self.cas_server_url()}/logout#{m.post_match}" self.debug(new_str) new_str else line end end File.open(self.seraph_config_xml(), "w") do |io| seraph_xml.each { |line| io.puts(line) } end end
[ "def config_seraph_config_xml()\n seraph_xml = File.readlines(self.seraph_config_xml)\n \n seraph_xml = seraph_xml.map do |line|\n if m = /(#{Regexp.quote(seraph_config_xml_token)})/.match(line)\n debug(m[0])\n debug(\"#{m.pre_match}#{cas_authenticator_class}#{m.post_match}\")\n \"#{m.pre_match}#{cas_authenticator_class}#{m.post_match}\"\n else\n line\n end\n end\n \n File.open(self.seraph_config_xml, \"w\") do |io|\n seraph_xml.each { |line| io.puts(line) }\n end\n end", "def update_configuration creds = nil\n puts \"Will try and update configuration in #{@conf}\"\n creds = read_credentials if creds.nil?\n File.open(@conf, \"w\") do |f|\n [\"access key\", \"secret access key\",\n \"entry point (default being https://aws.amazon.com if blank)\"\n ].each_with_index do |prompt, i|\n line = prompt_line prompt, creds[i]\n f.puts line if not line.empty?\n end\n end\n end", "def seraph_config_xml()\n \"#{build_dir}/src/confluence/WEB-INF/classes/seraph-config.xml\"\n end", "def add_authentication(xml)\n xml.tag! :Authentication do\n xml.tag! :client, @options[:login]\n xml.tag! :password, @options[:password]\n end\n end", "def add_authentication(xml)\n xml.tag! :Name, @options[:login]\n xml.tag! :Password, @options[:password]\n xml.tag! :ClientId, @options[:merchant_id]\n xml.tag! :Mode, \"P\"\n end", "def update_ssl_config(doc)\n sso_ssl = doc.elements.to_a(\"//ssl[@id='ssoSSLConfig']\")\n if sso_ssl.empty?\n @logger.debug('sso - update detects no custom ssl config - add it')\n add_custom_ssl(doc)\n else\n @logger.debug('sso - update detects custom ssl config - update it')\n update_custom_ssl(doc, sso_ssl)\n end\n end", "def make_jass_conf(file_name, keytab, principal)\n str = %(Client {\\n) +\n %( com.sun.security.auth.module.Krb5LoginModule required\\n) +\n %( useTicketCache=false\\n) +\n %( useKeyTab=true\\n) +\n %( keyTab=\"#{keytab}\"\\n) +\n %( principal=\"#{principal}\";\\n};)\n File.open(file_name, 'w') { |file| file.write str }\n end", "def refresh_login\n @max_api_version = appliance_api_version\n @token = login\n self\n end", "def seraph_config_xml()\n \"#{self.build_dir()}/src/webapp/WEB-INF/classes/seraph-config.xml\"\n end", "def configure(jira_url:, jira_username:, jira_api_token:)\n warn \"danger-jira_sync plugin configuration is missing jira_url\" if jira_url.blank?\n warn \"danger-jira_sync plugin configuration is missing jira_username\" if jira_username.blank?\n warn \"danger-jira_sync plugin configuration is missing jira_api_token\" if jira_api_token.blank?\n\n @jira_client = JIRA::Client.new(\n site: jira_url,\n username: jira_username,\n password: jira_api_token,\n context_path: \"\",\n auth_type: :basic\n )\n end", "def acquia_conf_auth\n user_data = JSON.parse(File.read(acquia_conf_path))\n { username: user_data['email'], password: user_data['key'] }\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 reload!\n config = YAML.load_file(File.join(Rails.root,'config','sipgate.yml'))\n\n @server = XMLRPC::Client.new2(\"https://#{config['username']}:#{config['password']}@samurai.sipgate.net/RPC2\")\n http = @server.instance_variable_get(:@http)\n http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n http.ca_file = File.join(Rails.root, 'lib', 'cacert.pem')\n\n @own_uri_list = nil\n @phonebook = {}\n end", "def update_config email = nil, pin = nil, debug = false\n\n if ! email && ! pin\n STDERR.puts 'missing email and / or pin'\n STDERR.puts 'usage: lightwaverf update email@email.com 1111'\n return\n end\n\n # Login to LightWaveRF Host server\n uri = URI.parse 'https://lightwaverfhost.co.uk/manager/index.php'\n http = Net::HTTP.new uri.host, uri.port\n http.use_ssl = true if uri.scheme == 'https'\n\n # Thanks Fitz http://lightwaverfcommunity.org.uk/forums/topic/pauly-lightwaverf-command-line-not-working/\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n data = 'pin=' + pin + '&email=' + email\n headers = { 'Content-Type'=> 'application/x-www-form-urlencoded' }\n resp, data = http.post uri.request_uri, data, headers\n\n if resp and resp.body\n rooms = self.get_rooms_from resp.body, debug\n # Update 'room' element in LightWaveRF Gem config file\n if rooms.any?\n config = self.get_config\n config['room'] = rooms\n self.put_config config\n debug and ( p '[Info - LightWaveRF Gem] Updated config with ' + rooms.size.to_s + ' room(s): ' + rooms.to_s )\n else\n debug and ( p '[Info - LightWaveRF Gem] Unable to update config: No active rooms or devices found' )\n end\n else\n debug and ( p '[Info - LightWaveRF Gem] Unable to update config: No response from Host server' )\n end\n self.get_config\n end", "def config_devise\n file = 'config/initializers/devise.rb'\n if FileTest.exists?(file) then\n if File.readlines(file).grep(/browserid_authenticatable/).size <= 0\n inject_into_file file, :before => /^end/ do\n \"\\n config.warden do |manager| \\n manager.default_strategies(:scope => :user).unshift :browserid_authenticatable\\n end\\n\"\n end\n else\n say \"'browserid_authenticatable' already added !\"\n end\n else\n say \"'config/initializers/devise.rb' does not exists !\"\n end\n end", "def update_keystore_config(doc)\n keystore = doc.elements.to_a(\"//keyStore[@id='ssoKeyStore']\")\n if keystore.empty?\n @logger.debug('sso - update detects no ssoKeyStore ssl config - add it')\n add_key_store(doc)\n else\n @logger.debug('sso - update detects ssoKeyStore ssl config - update it')\n update_key_store(doc, keystore)\n end\n end", "def save_config_signature\n Origen.app.session.origen_sim[\"#{id}_config\"] = config\n end", "def update_configuration(xml, options = {})\n client = extract_client!(options)\n\n # The Artifactory api requires a content type of 'application/xml'.\n # See http://bit.ly/1l2IvZY\n headers = { \"Content-Type\" => \"application/xml\" }\n client.post(\"/api/system/configuration\", xml, headers)\n end", "def write_config\n file new_resource.config_path do\n content new_resource.config_content\n group new_resource.group\n mode '600'\n notifies :reload, new_resource, :immediately\n owner new_resource.owner\n verify \"#{monit_binary} -t -c #{Poise::Backports::VERIFY_PATH}\" if defined?(verify)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shortcut to jiraapplication.properties file
def jira_application_properties() "#{self.build_dir()}/src/edit-webapp/WEB-INF/classes/jira-application.properties" end
[ "def config_jira_application_properties()\n jira_props = File.readlines(self.jira_application_properties()).map do |line|\n if m = /(#{Regexp.quote(jira_home_token)})/.match(line)\n self.debug(m[0])\n new_str = \"#{self.jira_home_token()} #{self.data_dir()}\"\n self.debug(new_str)\n new_str\n else\n line\n end\n end\n \n File.open(self.jira_application_properties(), \"w\") do |io|\n jira_props.each { |line| io.puts(line) }\n end\n end", "def confluence_init_properties()\n \"#{build_dir}/src/confluence/WEB-INF/classes/confluence-init.properties\"\n end", "def config_confluence_init_properties()\n File.open(self.confluence_init_properties, \"w\") do |io|\n io.puts(\"confluence.home=#{data_dir}\")\n end\n end", "def jira_password\r\n datastore['JIRAPASS']\r\n end", "def jira_url\n config.jira_url\n end", "def show\n puts \"------------------- settings -------------------\"\n puts \"Application: #{application}\"\n puts \"Branch: #{branch}\"\n puts \"Stage: #{stage}\"\n puts \"Deployer: #{deployer}\"\n puts \"Local User: #{get_local_user}\"\n puts \"URL: #{webhook_url}\"\n puts \"------------------------------------------------\"\n end", "def properties_file\n File.join(@base_path, PROP_FILE)\n end", "def env_key; end", "def log4j_properties_file\n FilePath.new(@root_directory, \".tc.dev.log4j.properties\")\n end", "def flash_config\n File.read(@path+\"/flash_config.json\")\n end", "def config_file\n File.join(Gem.user_home, '.gemrc')\n end", "def package_settings\n properties[:package_settings]\n end", "def find_logging_property\n installed_path = File.join(File.expand_path('../../..', File.dirname(__FILE__)), 'java')\n config = Command.find_files(\"logging.properties\", [Updater.jarfile_dest_path, installed_path])\n if config.empty?\n puts \"Cannot find 'logging.properties' file in '#{Updater.jarfile_dest_path}' or \" +\n \"'#{installed_path}'.\" unless ENV['TD_TOOLBELT_DEBUG'].nil?\n []\n else\n config.first\n end\n end", "def launch_configuration_name\n data[:launch_configuration_name]\n end", "def defaults_from_config_file(filename,options={})\n @rc_file = File.join(ENV['HOME'],filename)\n end", "def gitlab\n conf['dashboard']['gitlab']\n end", "def find_logging_property\n installed_path = File.join(File.expand_path('../../..', File.dirname(__FILE__)), 'java')\n config = Command.find_files(\"logging.properties\", [Updater.jarfile_dest_path, installed_path])\n if config.empty?\n $stdout.puts \"Cannot find 'logging.properties' file in '#{Updater.jarfile_dest_path}' or \" +\n \"'#{installed_path}'.\" unless ENV['TD_TOOLBELT_DEBUG'].nil?\n []\n else\n config.first\n end\n end", "def task_notes\n \"#{JIRA_BASE_URL}/browse/#{key}\"\n end", "def default_properties_file\n # try the current directory\n file = File.expand_path(DEF_PROP_FILE_NM)\n return file if File.exists?(file)\n # try home\n home = ENV['HOME'] || ENV['USERPROFILE'] || '~'\n file = File.expand_path(DEF_PROP_FILE_NM, home)\n file if File.exists?(file)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the jira.home property in the file: jiraapplication.properties.
def config_jira_application_properties() jira_props = File.readlines(self.jira_application_properties()).map do |line| if m = /(#{Regexp.quote(jira_home_token)})/.match(line) self.debug(m[0]) new_str = "#{self.jira_home_token()} #{self.data_dir()}" self.debug(new_str) new_str else line end end File.open(self.jira_application_properties(), "w") do |io| jira_props.each { |line| io.puts(line) } end end
[ "def set_workspace_home\n begin\n if not (workspace_home = ENV['WORKSPACE_HOME'] )\n workspace_home = Dor::Config.robots.workspace\n end\n rescue NameError => e\n LyberCore::Log.fatal(\"WORKSPACE_HOME is undefined. Do you need to set it in your config file?\")\n raise e\n end\n end", "def jira_application_properties()\n \"#{self.build_dir()}/src/edit-webapp/WEB-INF/classes/jira-application.properties\"\n end", "def set_home(home)\n @gem_home = home\n ensure_gem_subdirectories(@gem_home)\n end", "def set_mapr_java_home\n set_java_home('/opt/mapr/conf/env.sh')\n end", "def jmeter_home\n @jmeter_home ||= \"#{user_home}/jmeter\"\n end", "def stub_home\n @original_home = ENV[\"HOME\"]\n \tENV[\"HOME\"] = new_home_directory\n end", "def jruby_home\n ENV['JRUBY_HOME'] || RbConfig::CONFIG['prefix']\n end", "def home\n @home ||= ENV.fetch(\"HOME\").tr(\"\\\\\", \"/\")\nend", "def config_confluence_init_properties()\n File.open(self.confluence_init_properties, \"w\") do |io|\n io.puts(\"confluence.home=#{data_dir}\")\n end\n end", "def home\n ENV['RIB_HOME'] ||= File.expand_path(\n [\"#{config[:prefix]}/.rib\", '~/.rib', '~/.config/rib'].find{ |path|\n File.exist?(File.expand_path(path))\n } || '~/.rib'\n )\n end", "def orbit_home\n ENV.fetch('ORBIT_HOME')\n rescue KeyError\n abort '$ORBIT_HOME not set'\n end", "def nailgun_home\n ENV['NAILGUN_HOME'] || File.expand_path('tool/nailgun', jruby_home)\n end", "def jira_url\n config.jira_url\n end", "def home_directory=(home_directory)\n @home_directory = home_directory\n @modified = true\n end", "def get_java_home_path\r\n return get_java_property('java.home')\r\n end", "def home\n File.expand_path(Origen.site_config.home_dir)\n end", "def set_git_urls\n self.url = GitHosting.repository_path(self) if self.url.blank?\n self.root_url = self.url if self.root_url.blank?\n end", "def home_dir\n @home_dir ||= root_dir\n end", "def solr_home\n @solr_home ||= configuration_from_key('solr', 'solr_home')\n @solr_home ||= File.join(::Rails.root, 'solr')\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Places IST banner jpg in imaages directory
def config_ist_banner() FileUtils.cp("#{UcbDeployer::RESOURCES_DIR}/ist_banner.jpg", "#{self.build_dir()}/src/webapp/images/") end
[ "def anaura_bay_image_path\n File.expand_path( \"../anaura_bay.jpg\", __FILE__ )\nend", "def banner_path\n path = @path[0...@path.length - 4] + '_banner.png'\n path_remote = @path_remote[0...@path_remote.length - 4] + '_banner.png'\n File.exists?(path) ? path_remote : 'https://maps.avicus.net' + '/default_map_banner.png' # May need configured\n end", "def images_path\n @imags_path ||= File.expand_path 'images/', assets_path\n end", "def image\n MAIN_CDN + \"headshots/current/168x168/#{@id}.jpg\"\n end", "def image_jpg_path\n \"%s/app/assets/images/game_images/%s.jpg\" %[Rails.root, self.name.dehumanize]\n end", "def image(filename)\n return ROOT + '/images/' + filename\n end", "def banner_img(opts={:width=>700, :height=>120})\n p = Page.new(request.path)\n image_tag p.banner_url, opts\n end", "def base_images_path\n path_for('image', 'sample.png').gsub('/sample.png', '')\n end", "def intro_background_by_current_filename\n image = current_path.sub(/\\.html$/,'.jpg')\n prefix = \"assets/images/backgrounds/\"\n\n if file = sitemap.resources.find { |x| x.path =~ %r{#{prefix}#{image}}}\n file.path.sub(/^assets\\/images\\//, '')\n else\n data.page.intro.image rescue \"\"\n end\n end", "def copy_generated_images(parent)\n img = parent.find_inspire_image\n mobile = parent.image_for img, 'mobile_inspire'\n desktop = parent.image_for img, 'desktop_inspire'\n thumbnails = parent.image_for '', 'thumbnails'\n\n FileUtils.cp(mobile, \"#{data_path}/inspire/mobile\")\n FileUtils.cp(desktop, \"#{data_path}/inspire/desktop\")\n FileUtils.cp_r(\"#{thumbnails}/.\", \"#{data_path}/thumbnails\")\n end", "def move_image_from(img_loc)\n root = File.expand_path(File.dirname(__FILE__) + \"/../\")\n system(\"mkdir #{root}/public/#{options[:img_url]}\") unless File.exist?(root + \"/public/images/attractions\")\n\n new_img_loc = root + \"/public/#{options[:img_url]}\"\n system(\"cp #{img_loc} #{new_img_loc}\")\n end", "def banner_url\n return @banner_url unless @banner_url.nil?\n p= \"/\" + @@settings.images_dir + \"/banner\" + @path.gsub(/\\.html$/, \".jpg\")\n unless File.exists?(@@settings.views + p)\n p = parent ? parent.banner_url : \"/\" + @@settings.images_dir + \"/banner/default.jpg\"\n end\n @banner_url = p\n return @banner_url\n end", "def image_png\r\ndirectory = File.expand_path File.dirname(__FILE__)\r\nspecific_filename = directory + \"/\" + \"Media/shop.png\"\r\nend", "def add_image_files\n dir = \"#{@package_dir}/xl/media\"\n\n @workbook.images.each_with_index do |image, index|\n FileUtils.mkdir_p(dir)\n FileUtils.cp(image[0], \"#{dir}/image#{index + 1}.#{image[1]}\")\n end\n end", "def update_image_source(img)\n @content.gsub!(img, \"/images/\" << img.gsub(@base.gsub(\"weblog\",\"\"), \"\").gsub(\".a/\", \"\") << \".jpg\")\n end", "def anaura_bay_image\n File.new( anaura_bay_image_path )\nend", "def site_image_path(src)\n rewrite_asset_path(src.expand_url(\"#{account_site_assets}/images/\"))\n end", "def pic_a_file(folderName); end", "def get_image_path\n get_source_filepath.gsub('public', '')\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove jars from WEBINF/lib that have been installed at the container level to avoid conflicts.
def reshuffle_jars() FileUtils.mkdir_p("#{self.build_dir()}/src/edit-webapp/WEB-INF/lib/") FileUtils.cp(Dir["#{UcbDeployer::RESOURCES_DIR}/soulwing-casclient-*"], "#{self.build_dir()}/src/edit-webapp/WEB-INF/lib/") # These have been placed in $CATALINA_HOME/lib ["mail", "activation", "javamail", "commons-logging", "log4j"].each do |jar| FileUtils.rm_rf(Dir["#{self.build_dir()}/src/webapp/WEB-INF/lib/#{jar}-*"]) end end
[ "def reshuffle_jars()\n FileUtils.cp(Dir[\"#{UcbDeployer::RESOURCES_DIR}/soulwing-casclient-*\"],\n \"#{build_dir}/src/confluence/WEB-INF/lib/\")\n # Remove the jars that are installed at the container level\n [\"postgresql\", \"activation\", \"mail\"].each do |jar|\n FileUtils.rm_rf(Dir[\"#{build_dir}/src/confluence/WEB-INF/lib/#{jar}-*\"])\n end\n end", "def remove_jcl_over_slf\n dir_glob = Dir.glob(File.join @app_dir, 'WEB-INF', 'lib', 'jcl-over-slf4*.jar')\n dir_glob.each do |f|\n File.delete f\n end\n end", "def remove_dest_jars\n jars = Dir[ File.join( jar_dest, \"*.jar\" ) ].sort\n FileUtils::rm_f jars unless jars.empty?\n end", "def purge_jars\n from_directory do\n result = []\n Find.find(\"src\") do |file|\n next unless file =~ /.jar$/ && !File.symlink?(file)\n\n new_location = File.join(\"kit\", \"jars\", Pathname.new(file).split[1])\n FileUtils.mv(file, new_location)\n\n link_target = Pathname.new(new_location)\n .relative_path_from(Pathname.new(file).split.first)\n .to_s\n\n File.symlink(link_target, file)\n result << [file, new_location]\n end\n\n result\n end\n end", "def purge_jars\n from_directory do\n result = []\n Find.find(\"src\") do |file|\n next unless file =~ /.jar$/ && !File.symlink?(file)\n\n new_location = File.join(\"kit\", \"jars\", Pathname.new(file).split[1])\n FileUtils.mv(file, new_location)\n\n link_target = Pathname.new(new_location)\n .relative_path_from(Pathname.new(file).split.first)\n .to_s\n\n File.symlink(link_target, file)\n result << [file, new_location]\n end\n\n result\n end\n end", "def remove_all_webapps\n super\n end", "def remove_gems(app)\n SOURCE_GEMS_TO_REMOVE.each do |gem|\n rm_r \"#{app}/Contents/Resources/lib/#{gem}\", fileutils_options\n end\n end", "def remove_bundled()\n src = @context.registers[:site].source\n @files.each {|f|\n @context.registers[:site].static_files.select! {|s|\n if s.class == StaticFile\n s.path != File.join(src, f)\n else\n true\n end\n }\n }\n end", "def reset_registered_jarfiles\n @registered_jarfiles = {}\n end", "def restrict_frameworks\n remove_from_config('require \"rails/all\"')\n remove_from_config('require_relative \"boot\"')\n remove_from_env_config(\"development\", \"config.active_storage.*\")\n frameworks = <<~RUBY\n require \"rails\"\n require \"active_model/railtie\"\n require \"active_job/railtie\"\n require \"active_record/railtie\"\n require \"action_controller/railtie\"\n require \"action_mailer/railtie\"\n require \"action_view/railtie\"\n require \"rails/test_unit/railtie\"\n RUBY\n environment = File.read(\"#{app_path}/config/application.rb\")\n File.open(\"#{app_path}/config/application.rb\", \"w\") { |f| f.puts frameworks + \"\\n\" + environment }\n end", "def remove_classes_and_modules\n initialize_classes_and_modules\n end", "def clean_runtime_dirs(options)\n dirs = []\n %w(dependencies build_dependencies repo).each do |dir|\n dirs << dir if options[dir.to_sym] == true\n end\n\n return if dirs.empty?\n\n dirs.map! { |dir| \"app-root/runtime/#{dir.gsub(/_/, '-')}/*\" }\n\n out, err, rc = run_in_container_context(\"shopt -s dotglob; rm -rf #{dirs.join(' ')}\",\n chdir: @container_dir,\n expected_exitstatus: 0)\n end", "def cleanup\n RubyTerminal.options[:reload_paths] << \"app\" << \"lib\" << \"test\"\n RubyTerminal.with_reload_paths do |paths|\n mark_const_unloadable_in(paths)\n end\n action_controller_dispatcher.cleanup_application\n end", "def link_container_libs\n if container_libs_directory.exist?\n container_libs = ContainerUtils.libs(@app_dir, container_libs_directory)\n\n if container_libs\n FileUtils.mkdir_p(tomcat_lib) unless tomcat_lib.exist?\n container_libs.each { |lib| FileUtils.ln_sf(File.join('..', '..', lib), tomcat_lib) }\n end\n end\n end", "def clean_sprockets_assets\n manifest.clean(backups_to_keep)\n end", "def remove_jekyll_assets(files)\n files.each {|f| f.remove_jekyll_asset }\n end", "def clean_up\n FileUtils.rm(\n Dir.glob('build/{src,lib}.{rb,c,js}') +\n Dir.glob('build/ruby2d-opal.{rb,js}') +\n Dir.glob('build/app.c')\n )\nend", "def remove_old_deploys\n deploys = all_deploy_names true\n\n return unless deploys.length > Sunshine.max_deploy_versions\n\n lim = Sunshine.max_deploy_versions + 1\n\n rm_deploys = deploys[0..-lim]\n rm_deploys.map!{|d| \"#{self.deploys_path}/#{d}\"}\n\n @shell.call \"rm -rf #{rm_deploys.join(\" \")}\"\n end", "def remove_fake_rails_app(class_name)\n Object.send(:remove_const, :Rails)\n Object.send(:remove_const, class_name)\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Switch Roles! Print 10 Write a method, array_print_10, that puts the numbers 0 9 using an array and the each method
def array_print_10 end
[ "def array_print_10\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].each do |n|\n puts n\n end\nend", "def print_array(array)\n (length(array)).times do |i|\n print array[i]\n end\n # raise NotImplementedError\nend", "def print_array(array)\n length(array).times do |index|\n puts array[index]\n end\n # raise NotImplementedError\nend", "def list_roles\n #-find all characters that actor plays\n #-iterate over characters and compare to itself\n #-mutate each array 'character-show name'\n characters.collect do |character|\n \"#{character.name} - #{character.show.name}\"\n #binding.pry\n end\n\n end", "def print_array(array)\n print array\n end", "def print_array (array_of_integers)\n print array_of_integers\nend", "def print_board_array(array)\n dic_letter = {0 => 'A', 1 => 'B', 2 => 'C'}\n # Première ligne\n puts \" \" * 3 + \"1\".center(@slot.w) + \" \" + \"2\".center(@slot.w) \\\n + \" \" + \"3\".center(@slot.w) + \"\\n\\n\"\n array.each_with_index do |row, i|\n # Parcours ligne par ligne les 3 cases (slot) d'une ligne (1/2/3)\n @slot.h.times do |j|\n # Print the 3 characters (blank, or A/B/C)\n (j == @slot.h / 2) ? (print \" #{dic_letter[i]} \") : (print \" \" * 3)\n # Parcours tous les slots d'une ligne et lit \"sa\" ligne j\n row.each_with_index do |cell, k|\n print cell[j]\n k == 2 ? (print \"\\n\") : (print \"|\")\n end\n end\n # Separator between each row\n puts ' ' * 3 + '-' * (@slot.w + 1 + @slot.w + 1 + @slot.w) if i < 2\n end\n puts \"\\n\\n\"\n end", "def Print_Array(array)\n array.each do |val|\n print (val.to_s + \" \")\n end\nend", "def printArray anArray\n\tanArray.each do |i|\n\t\tputs i\n\tend\nend", "def printCardArray()\n\t\tprint @cards\n\tend", "def display_board\n puts \" #{@letter[0]} | #{@letter[1]} | #{@letter[2]} \"\n puts \" -------------\"\n puts \" #{@number[0]}| #{@board_array[0]} | #{@board_array[1]} | #{@board_array[2]} |\"\n puts \" |-----------|\"\n puts \" #{@number[1]}| #{@board_array[3]} | #{@board_array[4]} | #{@board_array[5]} |\"\n puts \" |-----------|\"\n puts \" #{@number[2]}| #{@board_array[6]} | #{@board_array[7]} | #{@board_array[8]} |\"\n puts \" ------------\"\n end", "def printArray\n i = 0\n while (i < (@commandArray.length + 1))\n puts @commandArray.at(i)\n i += 1\n end\n end", "def print_board\r\n\t\t@board_array.each do |char|\r\n\t\t\tprint \"#{char} \"\r\n\t\tend\r\n\t\tputs \"\"\r\n\t\t@board_array\r\n\tend", "def display_rainbow (arr)\n puts \"R: #{arr[0]}, O: #{arr[1]}, Y: #{arr[2]}, G: #{arr[3]}, B: #{arr[4]}, I: #{arr[5]}, V: #{arr[6]}\"\nend", "def roles_assigned_to_shift( for_print )\n self.roles.empty? ? for_print : self.roles.map { |role| role.name }.join(\", \") \n end", "def cadenas(arr)\n 10.times do\n puts \"Cadena aleatoria: #{(65+rand(26)).chr*5}\"\n end\n \nend", "def print_nums(x, y)\n \n title = \"Roulette Numbers\"\n title_start = x + (4 * BAR_LENGTH - title.size) / 2\n cur_color = 0\n y_offset = 0\n x_offset = 0\n numstr = \" \"\n \n # print the title\n Ncurses.mvprintw(y, title_start, title)\n \n @r_nums.each_with_index do |num, i|\n \n if (num == \"00\" || num == 0)\n cur_color = 1 \n elsif (i.even?)\n cur_color = 3 \n else\n cur_color = 2 \n end\n \n if num.to_s.size == 1\n numstr = \" \"\n else\n numstr = \" \"\n end\n \n if num.is_a? Integer\n Ncurses.attron(Ncurses.COLOR_PAIR(cur_color))\n Ncurses.mvprintw(y + y_offset + 2, x + x_offset, \" \" + num.to_s + numstr)\n Ncurses.attroff(Ncurses.COLOR_PAIR(cur_color))\n else\n Ncurses.attron(Ncurses.COLOR_PAIR(1))\n Ncurses.mvprintw(y + y_offset + 2, x + x_offset, \" \" + num + numstr)\n Ncurses.attroff(Ncurses.COLOR_PAIR(1))\n end\n \n if (i + 1) % BAR_LENGTH == 0\n y_offset += 1\n x_offset = 0\n else\n x_offset += 4 \n end\n \n end\n end", "def print_all_game_actors(print_title, game_actors)\n puts\n puts(print_title)\n game_actors.each do |ga|\n puts(\"\\t >> #{ga}\")\n end\n puts\nend", "def mtdarry\n 10.times do |num|\n puts num\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a method, range_print_10, that prints the numbers 0 9 using a range and the each method
def range_print_10 end
[ "def range_print_10\n (0..9).each do |n|\n puts n\n end\nend", "def range_print_10\n (0..9).step(1) do |n| \n puts n \n end \n \nend", "def integer_print_10\nend", "def integer_print_10\n 10.times{|x| print x}\nend", "def integer_print_10\n\n 10.times {|i| p i}\nend", "def integer_print_10\n 10.times do |x|\n print x\n end\nend", "def print_range(start_range, end_range)\n start_range == end_range ? \"#{start_range}\" : \"#{start_range}-#{end_range}\"\n end", "def array_print_10\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].each do |n|\n puts n\n end\nend", "def printOnetoHundred \n\n\n(1..100).each{|number| p number}\n\n\nend", "def print_the_numbers(range)\n for number in range\n puts \"An odd number: #{number}\" if number.odd?\n puts \"An even number: #{number}\" if number.even?\n end\nend", "def print1to20\n i = 1\n\n while i <= 20\n puts i\n i += 1\n end\nend", "def print1_255\n (1..255).each { |n| puts n }\nend", "def array_print_10\nend", "def print_odd_numbers_r(bound=99, n=3)\n if iteration <= bound\n puts n\n print_odd_numbers_r(bound, n+2)\n end\n\nend", "def print_posts(range: nil)\n if @past_index.nil?\n term.erase_body\n print_header\n @posts.each_with_index do |post, i|\n print_item(post, i, x: 0, reverse: @cur_index == i)\n end\n elsif range\n range.each do |i|\n print_item(@posts[i], i, x: 0, reverse: @cur_index == i)\n end\n else\n return if @past_index == @cur_index\n print_item(@posts[@past_index], @past_index, x: 0)\n print_item(@posts[@cur_index], @cur_index, x: 0, reverse: true)\n end\n term.mvaddstr(@cur_index + 4, 0, '>')\n term.refresh\n end", "def fizzbuzz(start_num, end_num)\n for curr_num in (start_num..end_num)\n if curr_num % 15 == 0\n print \"FizzBuzz\"\n elsif curr_num % 5 == 0\n print \"Buzz\"\n elsif curr_num % 3 == 0\n print \"Fizz\"\n else\n print curr_num\n end\n print \", \" if curr_num < end_num\n end\n puts \"\"\nend", "def print1to255\n (1..255).each do |i|\n puts i\n end\nend", "def print\n 9.times do \n puts \"Ruby Basic Exercises\"\n end\nend", "def print_instruction\n splits = sliced_print_range\n range = parsed_command_of(splits)\n report(range)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a method, integer_print_10, that prints the numbers 0 9 using an integer and the times method
def integer_print_10 end
[ "def integer_print_10\n 10.times{|x| print x}\nend", "def integer_print_10\n\n 10.times {|i| p i}\nend", "def integer_print_10\n 10.times do |x|\n print x\n end\nend", "def print\n 9.times do \n puts \"Ruby Basic Exercises\"\n end\nend", "def repeat(str, int)\n int.times { puts str }\nend", "def p_times statement,num\n num.times do |i|\n puts statement\n end\nend", "def range_print_10\n (0..9).each do |n|\n puts n\n end\nend", "def print_four_times( to_print )\n 4.times do\n puts to_print\n end\nend", "def range_print_10\n (0..9).step(1) do |n| \n puts n \n end \n \nend", "def repeater(str, int)\n\tint.times {puts str}\nend", "def times_three_and_plus_five(number)\n puts \"three and plus five: #{number * 3 + 5}\"\nend", "def speak(integer)\n integer.times {puts \"woof!\"}\n end", "def p_times(statement, num)\n num.times { puts statement }\nend", "def repeat(input_str, number)\n number.times {puts input_str}\nend", "def multiply_table(number)\n\tx = (0..10).to_a\n\tx.each { |i| puts \"#{i} * #{number} = #{i * number}\"}\nend", "def mtdarry\n 10.times do |num|\n puts num\n end\nend", "def speak(integer)\n integer.times do\n print \"Woof! \"\n end\n end", "def ten_mult(number)\n return number * 10\nend", "def repeat(string, integer)\n unless integer.to_i > 0 || integer.is_a?(Integer)\n puts \"Incorrect input\"\n return\n end\n if string.empty?\n puts \"The string is empty\"\n return\n end\n integer.times { puts \"#{string}\"}\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse file Clean balnk or empty lines form a file storing significat lines in given new file returns the number of significant lines
def parse( new_file_name = "#{@full_pathname}.clean.txt" ) lines_total = 0 lines_removed = 0 new_file = File.open( new_file_name, 'w' ) File.open( @full_pathname, 'r' ) do |f| f.each_line do |curr_line| # Make sure each line has a valid UTF-8 sequence of characters: curr_line = EncodingTools.force_valid_encoding( curr_line ) curr_line = ResultFileNormalizer.hints_remover( curr_line ) lines_total += 1 # Check if current line should be removed if !ResultFileNormalizer.is_data_line?( curr_line ) # Remove the line lines_removed += 1 else new_file << curr_line end end end lines_total - lines_removed end
[ "def parse_file\n line_count = 0\n @text.each_line do |line|\n if line == nil || line == '' || line.size == 0 || line[0] == '#' || line[0] == \"\\n\"\n next\n end\n elements = line.split(' ')\n if elements.size > 2\n puts 'Waring : '.red + 'in file \"' + @file_name.yellow + '\" ignoring line ' + line_count.to_s.yellow + ' ( it has more than one space and is not a comment )'\n else\n if elements.size == 1\n @ret << Manga_data.new(nil, nil, nil, elements[0], nil)\n else\n @ret << Manga_data.new(nil, elements[0], elements[1], nil, nil)\n end\n end\n line_count += 1\n end\n end", "def count_file(file)\n pre_selected = IO.readlines(file)\n .map { |line| line.strip }\n .select { |line| !line.empty? }\n .select { |line| !line.start_with? '#' }\n\n begin\n idx = pre_selected.find_index { |line| line.start_with? '=' }\n if idx != nil\n pre_selected = drop_while_comment pre_selected, idx\n end\n end while idx != nil\n\n pre_selected = pre_selected.reject { |line| line == 'end' }\n .reject { |line| line == '}' }\n puts \"#{File.basename file}: #{pre_selected.size}\"\n pre_selected.size\n end", "def process_count\n File.new(infile).each_with_index do |line, index|\n result = col_filter.process(row_filter.process(line.chomp, row: index))\n unless result.nil? or result.empty?\n key = unstring(line).split(';').values_at(*key_columns)\n key_value = key_values[key] || key_values[key] = { name: key, \n elements: Hash.new(0), \n sum: 0 }\n result.chomp.split(';').each do |column|\n heading << column if heading.index(column).nil?\n key_value[:elements][column] += 1\n key_value[:sum] += 1\n sums[column] += 1\n end\n end\n end\n end", "def check_fct_nbr\n @file.seek(0, IO::SEEK_SET)\n fct_nbr = 0\n in_fct = false\n nbr_line = 1\n @file.each_line do |line| \n if /^{/.match(line) || (/\\).+{\\s*$/.match(line) && !in_fct)\n in_fct = true\n fct_nbr += 1\n if fct_nbr > @max_fct_in_file\n puts \"--ligne #{@blue}#{nbr_line}#{@default} : #{fct_nbr} fonctions dans le fichier\"\n @error += 1\n end\n elsif line =~ /^}/\n in_fct = false\n end\n nbr_line += 1\n end\nend", "def check_fct_size\n @file.seek(0, IO::SEEK_SET)\n nbr_line = 1\n line_in_fct = 0\n in_fct = false\n @file.each_line do |line| \n if /^{/.match(line) || (/{\\s*$/.match(line) && !in_fct)\n in_fct = true\n elsif line =~ /^}/\n in_fct = false\n line_in_fct = 0\n else\n if in_fct\n line_in_fct += 1\n end\n if line_in_fct > @max_line_in_fct\n puts \"--ligne #{@blue}#{nbr_line}#{@default} : Fonction de plus de #{@max_line_in_fct} lignes\"\n @error += 1\n end\n end\n nbr_line += 1\n end\nend", "def filter( fin, fout )\n dropped_lines = 0\n changed_lines = 0\n tab_lines = 0\n empty_lines = 0\n total = 0\n while( line = fin.gets )\n total += 1\n lstr = line.rstrip\n\n changed_lines += 1 if ( line != ( lstr + \"\\n\" ) )\n\n if lstr.empty?\n empty_lines += 1\n else\n if empty_lines > 0\n fout.puts\n dropped_lines += empty_lines - 1\n empty_lines = 0\n end\n tab_lines += 1 if lstr =~ /\\t/\n # line.gsub!( /\\t/, \" \" )\n fout.puts lstr\n end\n end\n dropped_lines += empty_lines\n [ changed_lines, dropped_lines, tab_lines, total ]\n end", "def paragraph_count(all_lines_from_file)\n all_lines_from_file.split(/\\n\\n/).length\nend", "def count_pbars(fn)\n\n blin = 0;\n nev = 0;\n\n for l in File.readlines(fn)\n w = l.split(' ')\n nw = w.length\n\n if (blin == 0) then \n if (w[0] == 'ProductPrint') and (w[1].index('mu2e::StepPointMCs_muonBeamFilter_Coll31OutRecord') != nil) then\n blin = 1\n end\n else\n if (nw == 11) and (w[10] == 'Transportation') then\n if (w[1] == '100001') then nev += 1 end\n blin = 0\n end\n end\n end\n\n puts \"nev = #{nev}\"\nend", "def parse_wn_dict_data_from_text_file( filename ) \r\n wordText = \"\"\r\n wordArr = []\r\n prev_pos = \"\"\r\n count = 0\r\n \r\n File.open( filename ).each do |line| \r\n #break if count > 1000\r\n begin \r\n if line.first_letter != \" \" \r\n parse_word(wordText).save_to_db if wordText.strip.length > 0\r\n # wordArr << wordText if wordText.strip.length > 0\r\n # new word begins with a line \r\n #without leading blank space \r\n wordText = line.strip \r\n puts \"process : \" + wordText \r\n \r\n count += 1\r\n else \r\n # reformat input so that each pos \r\n # appear in only 1 line \r\n # each pos is separated by @\r\n # if line begin with \"1:\" or \"2:\"... \r\n # replace with previous type of pos\r\n line.strip! \r\n # parser.is_pos_begin(\"adj : having a toe or toes of a specified kind; often used in\")\r\n if line.split[0] == \"See\"\r\n wordText += \"@\" + line\r\n elsif is_pos_begin(line) \r\n prev_pos = line.split[0] \r\n wordText += \"@\" + line.gsub(/[1]/, \"\") \r\n elsif (is_numeric(line.first_letter) && line.second_letter == \":\") \r\n line = line[2..-1].strip\r\n line = prev_pos + \" : \" + line \r\n \r\n wordText += \"@\" + line\r\n elsif (is_numeric(line.two_first_letters) && line.second_letter == \":\")\r\n line = line[3..-1].strip\r\n line = prev_pos + \" : \" + line \r\n wordText += \"@\" + line\r\n else\r\n wordText += line + \" \" \r\n end\r\n end \r\n rescue => e\r\n puts \"hmm error in parse_wn_dict_data_from_text_file\"\r\n end \r\n end \r\n \r\n parse_word(wordText).save_to_db if wordText.strip.length > 0 \r\n \r\n end", "def update_misc_seg_line_numbers\n segments = MiscSegmentsEra.where(:era_id => @era_job.era_id).map(&:segment_text)\n raw_era_file = File.open(\"#{@era_job.era.inbound_file_information.file_path}/#{@era_job.era.inbound_file_information.name}\", 'r')\n\n @segments = ''\n IO.foreach(raw_era_file){|segment| @segments += segment}\n @raw_835_segments = @segments.delete(\"\\n\").split(\"~\").collect{|line| line.strip+\"~\\n\"}\n\n @raw_835_segments.each_with_index do |line, index|\n @track_number = line.split(@delimiter)[2].chomp.split(/~/).first if /^ST((\\*)|(\\|)).*$/.match(line)\n if check_835_file(segments, line) && @track_number == @era_check.tracking_number\n misc_segment = MiscSegmentsEra.where(:era_id => @era_job.era_id, :segment_text => @formated_text, :segment_line_number_in_file => nil).first\n misc_segment.update_attributes(:segment_line_number_in_file => index + 1, :segment_text => line.chop) if misc_segment\n end\n end\n end", "def n_lines(filename); end", "def lines(textFile)\n textFile.to_a.select {|line| /\\S/ =~ line and /^\\#/ !~ line}.length\nend", "def validate\n @file.each_line.first.split(/\\t/).count == 6\n end", "def parse\n\t\tfile = File.new(@filename, \"r\")\n\t\tline = file.gets.chomp\n\t\twhile !line.nil?\n\t\t\tif line =~ /(Underflow|Overflow)/ #if exception\n\t\t\t\tline =~ /Overflow/ ? overflow = true : overflow = false\n\t\t\t\tidentifier = line[/[0-9][0-9]*/] #get exception identifier\n\t\t\t\tline = file.gets.chomp\t\t\t\t\t\n\t\t\t\tline = file.gets.chomp if line =~ /The constraints are unsat/\t\t\t\t\n\t\t\t\tline = file.gets.chomp if line =~ /KLEE: WARNING:/\t\t\t\t\n\t\t\t\t# For a given identifier, there can me multiple warnings of a potential \n\t\t\t\t# overflow/underflow, store only the last one.\n\t\t\t\t# By creating a new array, previous values are overwritten\n\t\t\t\tvalues = []\n\t\t\t\twhile line =~ /^arr[0-9]/\t#if arr value\n\t\t\t\t\tline = file.gets.chomp\n\t\t\t\t\t#~ puts \"#{identifier}: #{line}\"\t#debugging\n\t\t\t\t\tvalues.push line #store value as sring with no regard to type (rational, float, integer)\t\t\t\t\t\n\t\t\t\t\tline = file.gets.chomp\n\t\t\t\tend\n\t\t\t\tif not values.empty? #if some arr values were found, store them\t\t\t\t\t\n\t\t\t\t\toverflow ? @overflow[\"#{identifier}\"] = values : @underflow[\"#{identifier}\"] = values\n\t\t\t\tend\n\t\t\telse \n\t\t\t\tline = file.gets #if not exception warning\n\t\t\tend\n\t\tend #iterate over lines in file\n\tend", "def analyze filename = \"input_text.txt\"\n return if @@hanzis.empty?\n readfile(filename).each do |x|\n @@hanzis[x.to_sym] = \n @@hanzis[x.to_sym] + 1 unless @@hanzis[x.to_sym].nil?\n end\n end", "def count_lines()\n count = 0\n csvfile = File.new(TESTFILE)\n \n File.open(csvfile, 'r') do |f|\n f.each do |line|\n #although this check is technically unnecessary, it may be good to keep as a safety that the file format has not changed\n # m = /\\d+,([.0-9]+).+/.match(line)\n # # Only continue if line correctly parsed\n # if m != nil \n count += 1\n # # Double check for problematic lines for reg. exp.\n # else\n # print \"\\nLine Not Properly Parsed: \"+line\n # erroneous_lines.push(line)\n # end\n end\n end\n \n print \"\\nFile path: \"+csvfile.path()\n print \"\\nNumber of Different Products Sold: \"+ count.to_s()+\"\\n\"\nend", "def count_lines(all_lines_from_file)\n all_lines_from_file.lines.count\nend", "def parse_file\n count = 0\n read_items {|row, i| count=i}\n update_attribute :total_items, count\n count\n end", "def remove_line(file)\n lines = File.readlines(file)\n size1 = lines.size\n #remove the line if it contains the specified characters\n lines.delete_if {|line| line.include? SYMBOLS}\n size2 = lines.size\n #overwrite the file\n File.open(file, \"w+\") do |file|\n lines.each do |record|\n file.puts record\n end\n end\n #number of remove lines\n size1-size2\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /widgets GET /widgets.json
def index @widgets = Widget.all respond_to do |format| format.html # index.html.erb format.json { render json: @widgets } end end
[ "def index\n @widgets = @widget_user.widgets\n render json: { widgets: @widgets }\n end", "def index\n @widgets = request_widgets(visible_widgets_url)\n end", "def all_visible_widgets\n user_id = params[:id]\n api_link = VISIBLE_WIDGETS_URL + client_id + '&client_secret=' + client_secret\n response = showoff_api_call(api_link, 'get')\n @widgets = response['data']['widgets']\n code = response['code']\n flash[:error] = response['message'] if code != 0\n rescue StandardError => e\n flash[:error] = \"Something went wrong in widgets index! #{e}\"\n end", "def show\n @widget = Widget.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @widget }\n end\n end", "def show\n\t\t@widget = Widget.find(params[:id])\n\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.json\t{ render json: @widget }\n\t\tend\n\tend", "def widgets\n @party.get(\"reports/#{@id}/widgets\")['Widgets']\n end", "def widget_data\n widget = WidgetService.widget(params[:widget_id])\n render json: {\n id: widget.id,\n dataset: widget.dataset,\n visualization: widget.widget_config,\n name: widget.name,\n description: widget.description,\n metadata: widget.metadata\n }\n end", "def visible_widgets\n user_id = params[:id]\n user_info = params[:user_info]\n if user_info.eql?('true')\n my_widgets_url = MY_USER_WIDGETS + \"client_id=#{client_id}&client_secret=#{client_secret}\"\n response = showoff_api_call(my_widgets_url, 'get', authorization_bearer(current_user.showoff_access_token))\n else\n user_widgets_url = USER_WIDGETS + \"#{user_id}/widgets/?client_id=#{client_id}&client_secret=#{client_secret}\"\n response = showoff_api_call(user_widgets_url, 'get', {})\n end\n if response['data']['widgets'].present?\n @user = response['data']['widgets'].first['user']\n @widgets = response['data']['widgets'] if response['data'].present?\n else\n @user = nil\n @widgets = []\n end\n response = 200\n rescue StandardError => e\n @user = nil\n @widgets = []\n flash[:error] = \"Something went wrong in user show! #{e}\"\n end", "def widget_data\n widget = Widget.find(params[:widget_id])\n data = widget.get_filtered_dataset false, 10000\n render json: {id: widget.id,\n visualization: widget.visualization,\n name: widget.name,\n description: widget.description,\n data: data['data']}.to_json\n end", "def show\n @widget_type = WidgetType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @widget_type }\n end\n end", "def widget_data\n widget = Widget.find(params[:widget_id])\n datasets = []\n @site.contexts.each {|c| c.context_datasets.each {|cd| datasets << cd.dataset_id}}\n if datasets.include? widget.dataset_id # To get only a widget for a dataset for this site\n data = widget.get_filtered_dataset false, 10000\n render json: {id: widget.id,\n visualization: widget.visualization,\n name: widget.name,\n description: widget.description,\n data: data['data']}.to_json\n else\n render json: {}\n end\n end", "def show\n @pwidget = Pwidget.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @pwidget }\n end\n end", "def index\n @simple_widgets = SimpleWidget.all\n end", "def show\n @component_widget = ComponentWidget.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @component_widget }\n end\n end", "def show\n @widget_profile = WidgetProfile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @widget_profile }\n end\n end", "def get_widgets(user_id=nil, user_email=nil)\n Echochamber::Request.get_widgets(token, user_id, user_email)\n end", "def widget\n PassaporteWeb::Resources::Widget.new(api)\n end", "def update_widgets\n @dashboard = Dashboard.find(params[:dashboard_id])\n widgets = ActiveSupport::JSON.decode(params[:widgets])\n respond_to do |format|\n if @dashboard.update_widgets(widgets)\n format.json { head :no_content }\n else\n format.json { render json: @dashboard.errors, status: :unprocessable_entity }\n end\n end\n end", "def widget\n NexaasID::Resources::Widget.new(api_token, config)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /widgets/1 DELETE /widgets/1.json
def destroy @widget = Widget.find(params[:id]) @widget.destroy respond_to do |format| format.html { redirect_to widgets_url } format.json { head :no_content } end end
[ "def destroy\n @widget.destroy\n respond_to do |format|\n format.html { redirect_to widgets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @simple_widget.destroy\n respond_to do |format|\n format.html { redirect_to simple_widgets_url, notice: 'Simple widget was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @widget = Widget.find(params[:id])\n @widget.destroy\n\n respond_to do |format|\n format.html { redirect_to(widgets_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @widget_type = WidgetType.find(params[:id])\n @widget_type.destroy\n\n respond_to do |format|\n format.html { redirect_to widget_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @pwidget = Pwidget.find(params[:id])\n @pwidget.destroy\n\n respond_to do |format|\n format.html { redirect_to pwidgets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @users_widget = UsersWidget.find(params[:id])\n @users_widget.destroy\n\n respond_to do |format|\n format.html { redirect_to users_widgets_url }\n format.json { head :ok }\n end\n end", "def destroy\n @component_widget = ComponentWidget.find(params[:id])\n @component_widget.destroy\n\n respond_to do |format|\n format.html { redirect_to component_widgets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n authorize! :destroy_impac_widgets, widget\n\n if widget.destroy\n MnoEnterprise::EventLogger.info('widget_delete', current_user.id, 'Widget Deletion', widget)\n head status: :ok\n else\n render_bad_request('destroy widget', 'Unable to destroy widget')\n end\n end", "def delete_widget widget\n @widgets.delete widget\n end", "def destroy\n @widget_instance.destroy\n respond_to do |format|\n format.html { redirect_to widget_instances_url, notice: 'Widget instance was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @author_widget.destroy\n respond_to do |format|\n format.html { redirect_to author_widgets_url, notice: t('widget_destroy_success') }\n format.json { head :no_content }\n end\n end", "def destroy\n @concrete_widget = SWUI::ConcreteWidget.find(params[:id])\n @concrete_widget.destroy\n\n respond_to do |format|\n format.html { redirect_to(concrete_widgets_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @widget_attr.destroy\n respond_to do |format|\n format.html { redirect_to widget_attrs_url, notice: 'Widget attr was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @author_widget.destroy\n respond_to do |format|\n format.html {redirect_to author_widgets_url, notice: t('widget_destroy_success')}\n format.json {head :no_content}\n end\n end", "def destroy\n @user_widget.destroy\n respond_to do |format|\n format.html { redirect_to user_widgets_url, notice: 'User widget was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @gradient_widget.destroy\n respond_to do |format|\n format.html { redirect_to gradient_widgets_url, notice: 'Gradient widget was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @rightwidget.destroy\n respond_to do |format|\n format.html { redirect_to rightwidgets_url, notice: 'Rightwidget was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy\n @widget_profile = WidgetProfile.find(params[:id])\n @widget_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to widget_profiles_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setting up a Mock to simulate the requests.
def setup @requester = Rack::MockRequest.new(SampleApp) end
[ "def setup_base_mocks\n RunGitHub.any_instance.expects(:ask).with(\"GitHub Username:\").returns(\"github_username\")\n RunGitHub.any_instance.expects(:ask).with(\"GitHub Password:\").returns(\"github_password\")\n client = mock(\"RestClient::Resource\")\n RestClient::Resource.expects(:new).with(\"http://github.com\", \"github_username\", \"github_password\").returns(client)\n post = mock(\"RestClient::Resource\")\n client.expects(:[]).with(\"/api/v2/yaml/repos/create\").returns(post)\n post\n end", "def mock_request url, body\n @webmocks[url] ||= {}\n @webmocks[url] = body\n\n #puts \"registering #{url}\"\n\n FakeWeb.register_uri :get, url, :body => body\nend", "def mas_net_http_get(obj_stubs = {})\n request = Spec::Mocks::Mock.new(Net::HTTP::Get)\n Net::HTTP::Get.stub!(:new).and_return(request)\n obj_stubs.each do |method, value|\n request.stub!(method).and_return(value)\n end\n request\nend", "def require_requests_and_mock\n requests.each do |request|\n require_item(request, @request_path)\n if service::Mock.method_defined?(request.last)\n mocked_requests << request.last\n else\n service::Mock.module_eval <<-EOS, __FILE__, __LINE__\n def #{request.last}(*args)\n Fog::Mock.not_implemented\n end\n EOS\n end\n end\n end", "def mas_net_http(response, obj_stubs = {})\n http = mock(Net::HTTP, obj_stubs)\n Net::HTTP.stub!(:new).and_return(http)\n http.stub!(:request).and_return(response)\n http.stub!(:start).and_yield(http)\n http.stub!(:use_ssl=)\n http.stub!(:verify_mode=)\n http\nend", "def mock_request\n ugly_warning \"Hard-coded use of Waves::Dispatchers::Default\"\n @request ||= ::Rack::MockRequest.new( ::Waves::Dispatchers::Default.new )\n end", "def mas_net_http_post(obj_stubs = {})\n request = Spec::Mocks::Mock.new(Net::HTTP::Post)\n Net::HTTP::Post.stub!(:new).and_return(request)\n obj_stubs.each do |method, value|\n request.stub!(method).and_return(value)\n end\n request\nend", "def request_stub\n @request_stub ||= WebMock::RequestStub.new(:any, endpoint).tap{ |s| s.to_rack(app) }\n end", "def setup_base_mocks\n client = mock(\"Heroku::Client\")\n Heroku::Client.expects(:new).with(\"heroku_username\", \"heroku_password\").returns(client)\n client\n end", "def api\n api_double = double('api')\n api_double.stub(:request) do \n last_request\n end\n api_double.stub(:response) do \n last_response\n end\n api_double.stub(:env) do \n last_request.env\n end\n api_double.extend Base.helpers\nend", "def request\n @request ||= Rack::MockRequest.new(mack_app)\n end", "def stubbed_net_http(response, obj_stubs = {}, host = 'twitter.com', port = 80)\n http = Net::HTTP.new(host, port)\n Net::HTTP.stub!(:new).and_return(http)\n http.stub!(:request).and_return(response)\n http\nend", "def mock_request(*args)\n http_method, request_uri, params, headers = args[0].to_sym, args[1], args[2], args[3]\n params ||= {}\n fixture_filename = fixture_filename = \"#{Digest::MD5.hexdigest(\"#{http_method}#{request_uri}#{params.inspect}#{headers.reject{|key, value| key == \"Authorization\"}}\")}.fixture\"\n begin\n return read_fake_url(fixture_filename)[2][\"body\"]\n rescue FixtureNotFound\n if http_method.eql?(:get)\n r = @service.get(@rest_base + request_uri, headers)\n elsif http_method.eql?(:post)\n r = @service.post(@rest_base + request_uri, body, headers)\n elsif http_method.eql?(:put)\n r = @service.put(@rest_base + request_uri, params, headers)\n elsif http_method.eql?(:delete)\n r = @service.delete(@rest_base + request_uri, headers)\n end\n response = {\n \"body\" => r.body,\n \"status\" => r.code,\n \"Content-Type\" => r[\"Content-Type\"]\n }\n fixtures_dir = \"../tests/sbc/support/fixtures/\"\n FileUtils.mkdir_p(fixtures_dir)\n File.open(File::join(fixtures_dir, fixture_filename), 'w') do |f|\n f.puts [request_uri, http_method, response].to_json\n end\n retry\n end\n end", "def mock\n self.known_queues = Set.new\n self.connection.close if self.connection(ensure_started: false)\n self.connection = BunnyMock.new(self.config).start\n end", "def request\n @request ||= Rack::MockRequest.new(mack_app)\n end", "def request_stub; end", "def request\n @request ||= Rack::MockRequest.new(app)\n end", "def mock_web(mocks)\n mocks.each do |url, file|\n stub_request(:get, url).to_return(body: File.read(\"spec/modsvaskr_test/web_mocks/#{file}\"))\n end\n end", "def stub_network\n stub_request(:get, %r{http://[^/]+/html}).to_return(method(:respond_html))\n stub_request(:get, %r{http://[^/]+/get\\b}).to_return(method(:respond_echo))\n stub_request(:post, %r{http://[^/]+/post\\b}).to_return(method(:respond_echo))\n stub_request(:get, %r{http://[^/]+/status/\\d+}).to_return(method(:respond_status))\n stub_request(:get, %r{http://[^/]+/(relative-)?redirect/\\d+}).to_return(method(:respond_redirect))\n stub_request(:get, %r{http://[^/]+/delay/\\d+}).to_timeout\n stub_request(:get, %r{http://[^/]+/xml}).to_return(method(:respond_xml))\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Admin only; get a sample of students for looking at data across the site
def sample_students_json raise Exceptions::EducatorNotAuthorized unless current_educator.can_set_districtwide_access? seed = params.fetch(:seed, '42').to_i n = params.fetch(:n, '40').to_i authorized_sample_students = authorized do Student.active.sample(n, random: Random.new(seed)) end sample_students_json = authorized_sample_students.as_json({ only: [:id, :grade, :first_name, :last_name], include: { school: { only: [:id, :name, :school_type] } } }) render json: { sample_students: sample_students_json } end
[ "def sample_students_json\n seed = params.fetch(:seed, '42').to_i\n n = params.fetch(:n, '40').to_i\n authorized_sample_students = authorized do\n Student.active.sample(n, random: Random.new(seed))\n end\n sample_students_json = authorized_sample_students.as_json({\n only: [:id, :grade, :first_name, :last_name],\n include: {\n school: {\n only: [:id, :name, :school_type]\n }\n }\n })\n render json: {\n sample_students: sample_students_json\n }\n end", "def school_students(query={})\n self.simple_client.get(\"/api/v1/schools/my/students?#{query.to_query}\")\n end", "def get_student\n\t\tstudents_array = []\n\t\tstudents.each do |student|\n\t\t\tstudent.performances.each do |performance|\n\t\t\t\tstudents_array += [student] if performance.rate == 3\n\t\t\t\tstudents_array += [student, student] if performance.rate == 2\n\t\t\t\tstudents_array += [student, student, student] if performance.rate == 1\n\t\t\tend\n\t\tend\n\t\tstudents_array.sample\n\tend", "def view_students\n requires({'role'=>'admin'})\n @students = User.find_all_by_role_and_deleted_at(:student, nil)\n end", "def all_students\n # binding.pry\n student_array = BoatingTest.all.select do |test_info|\n test_info.instructor == self \n end \n student_array.map(&:student)\n end", "def make_students\n students_array = Scraper.scrape_index_page(BASE_PATH + 'index.html')\n Student.create_from_collection(students_array)\n end", "def list_students\n if current_user.is_admin?\n @course = Course.find(params[:id])\n else\n @course = current_user.courses.find(params[:id])\n end\n @users = @course.users\n @students = Array.new\n @users.each do |x|\n if !x.is_teacher?\n @students << x\n end\n end\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @students }\n end\n rescue ActiveRecord::RecordNotFound => e\n prevent_access(e)\n end", "def students\n Rollcall::Student.find_all_by_school_id schools\n end", "def students\n self.course_person.all(:type => \"student\").persons\n end", "def display_students\n Student.all.each do |student|\n puts \"#{student.name.upcase}\".colorize(:blue)\n puts \" location:\".colorize(:light_blue) + \" #{student.location}\"\n puts \" profile quote:\".colorize(:light_blue) + \" #{student.profile_quote}\"\n puts \" bio:\".colorize(:light_blue) + \" #{student.bio}\"\n puts \" twitter:\".colorize(:light_blue) + \" #{student.twitter}\"\n puts \" linkedin:\".colorize(:light_blue) + \" #{student.linkedin}\"\n puts \" github:\".colorize(:light_blue) + \" #{student.github}\"\n puts \" blog:\".colorize(:light_blue) + \" #{student.blog}\"\n puts \"----------------------\".colorize(:green)\n end\n end", "def students\n if current_user.is_admin?\n @students= User.find(:all, :conditions => \"is_teacher = '0' and is_admin = '0'\")\n respond_to do |format|\n format.xml { render :xml => @students }\n end\n else\n respond_to do |format|\n format.xml { render :text => \"error\" }\n end\n end\n end", "def print_student_list()\n puts \"Students:\"\n puts \"----------------\"\n @students.each do |student|\n puts \"#{student.name}, Cohort: #{student.cohort.to_s}\"\n end\n puts \"Overall, we have #{@students.count} students\"\n end", "def students\n if usernames\n data = {}\n usernames.each {|u| data[u.username] = u.students}\n render json: data and return\n elsif current_user\n render json: {status: \"success\", response: current_user.students} and return\n else\n render json: {status: StatusCode::FAILURE, reason: \"no data provided\"}\n end\n end", "def access_student\n student_id = self.student_user_id\n student = User.find_by_id(student_id)\n return student\n end", "def get_student(parameters)\n json_post('students/api.json', parameters)\n end", "def show_student\n\t\tstudent = verify_student_teacher_relationship(params[:sid])\n\n\t\tif (student)\n\t\t\t@name = student.name\n\t\t\t@purchases = student.purchases.where(:purchased => false).to_a\n\t\t\t@purchased = student.purchases.where(:purchased => true).to_a\n\t\t\t@show_student = false\n\t\telse\n\t\t\tredirect_with_message(\"dashboard\", \"Student not found.\")\n\t\t\treturn\n\t\tend\n\tend", "def students\r\n\t\tputs \"student\"\r\n\t\tputs @students_list.length\r\n\t\ta= @students_list.length\r\n\t\tpointer = rand(0..a-1)\r\n\t\t@student = @students_list[pointer] \r\n\t\t@students_list.delete_at(pointer)\r\n\t\treturn @student\r\n\tend", "def student_ranking_per_school\n @courses ||= Course.all\n @students ||= Student.all\n @exam_groups ||= ExamGroup.result_published\n authorize! :read, @exam_groups.first\n end", "def student\n return @student\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /actionables GET /actionables.json
def index @actionables = Actionable.all end
[ "def available_actions\n actions = Inventory.where(dataset_id: params[:dataset_id]).order(:object_action).distinct(:object_action).pluck(:object_action)\n respond_to do |format|\n format.json { render json: { success: true, actions: actions } }\n end\n end", "def actions\n return @actions if @actions\n @actions = Client.get(\"/cards/#{id}/actions\").json_into(Action)\n end", "def index\n @user_actions = UserAction.all\n render json: @user_actions\n end", "def abilities\n get('/ability/')\n end", "def get_ability_actions(serializer)\n evaluate_option_root_first(serializer, :ability_actions)\n end", "def index\n @action_military_move_army_actions = Action::Military::MoveArmyAction.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @action_military_move_army_actions }\n end\n end", "def actions\n @actions = Permission.actions(params[:permissions_controller])\n\n respond_to do |format|\n format.json { render :json => @actions }\n end\n end", "def index\n @ai_actions = AiAction.all\n end", "def index\n @editables = Editable.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @editables }\n end\n end", "def actions\n require_parameters :issue\n issue_key = params[:issue]\n actions = Internal.issues.listActions(issue_key)\n render :json => jsonp(\n {\n :actions => actions.map { |t| t.key() }\n }\n )\n end", "def accessories\n render json: { collections: Collection.published_accessories }\n end", "def index\n @foundational_actions = FoundationalAction.all\n end", "def actions\n return @actions if @actions\n @actions = Client.get(\"/boards/#{id}/actions\").json_into(Action)\n end", "def index\n @simple_actions = SimpleAction.all\n end", "def index\n @military_battle_factions = Military::BattleFaction.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @military_battle_factions }\n end\n end", "def index\n @accessory_categories = AccessoryCategory.all\n\n render json: @accessory_categories\n end", "def index\n @creature_actions = CreatureAction.all\n end", "def index\n @objectives = @goal.objectives.all \n render json: @objectives \n end", "def index\n @borrow_requests = current_user.borrow_requests.actionable\n @pending_approvals = current_user.approvals.where(\"status = 'pending'\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @borrow_requests }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /actionables POST /actionables.json
def create @actionable = Actionable.new(actionable_params) respond_to do |format| if @actionable.save format.html { redirect_to @actionable, notice: 'Actionable was successfully created.' } format.json { render :show, status: :created, location: @actionable } else format.html { render :new } format.json { render json: @actionable.errors, status: :unprocessable_entity } end end end
[ "def index\n @actionables = Actionable.all\n end", "def create_actionable\n actionable_node = Neography::Node.create(\"object_id\" => self.id, \"object_type\" => self.class.to_s)\n actionable_node.add_to_index(\"actionables_nodes_index\", \"class0id\", \"#{self.class.to_s}0#{self.id}\")\n end", "def add_to_actions(action)\n action = MultiJson.dump action\n @actions << action\n self\n end", "def actions\n @actions = Permission.actions(params[:permissions_controller])\n\n respond_to do |format|\n format.json { render :json => @actions }\n end\n end", "def create\n @actions_action = ActionsAction.new(actions_action_params)\n\n respond_to do |format|\n if @actions_action.save\n format.html { redirect_to @actions_action, notice: 'Le lien entre actions a été créé.' }\n format.json { render :show, status: :created, location: @actions_action }\n else\n format.html { render :new }\n format.json { render json: @actions_action.errors, status: :unprocessable_entity }\n end\n end\n end", "def perform_optimization_actions_on_arrays(args = {}) \n post(\"/arrays.json/actions/optimize\", args)\nend", "def create\n @action = Action.new(action_params)\n\n if @action.save\n render :show, status: :created\n else\n render json: @action.errors, status: :unprocessable_entity\n end\n end", "def available_actions\n actions = Inventory.where(dataset_id: params[:dataset_id]).order(:object_action).distinct(:object_action).pluck(:object_action)\n respond_to do |format|\n format.json { render json: { success: true, actions: actions } }\n end\n end", "def index\n @user_actions = UserAction.all\n render json: @user_actions\n end", "def create\n @administration_action = Action.new(params[:action_item])\n\n respond_to do |format|\n if @administration_action.save\n format.html { redirect_to administration_actions_url, notice: 'Action was successfully created.' }\n format.json { render json: @administration_action, status: :created, location: @administration_action }\n else\n format.html { render action: \"new\" }\n format.json { render json: @administration_action.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ai_action = AiAction.new(ai_action_params)\n\n respond_to do |format|\n if @ai_action.save\n format.html { redirect_to [:admin, @ai_action], notice: 'Ai action was successfully created.' }\n format.json { render action: 'show', status: :created, location: @ai_action }\n else\n format.html { render action: 'new' }\n format.json { render json: @ai_action.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @accessory = Accessory.new(accessory_params)\n\n if @accessory.save\n render json: @accessory, status: :created\n else\n render json: @accessory.errors, status: :unprocessable_entity\n end\n end", "def create_action(body = {})\n post(actions_path, body)\n end", "def create\n @ability = @user.abilities.build(ability_params)\n \n respond_to do |format|\n if @ability.save\n format.html { redirect_to user_abilities_path(@user) }\n flash[:success] = \"Ability created!\"\n format.json { render :show, status: :created, location: @ability }\n else\n format.html { render :new }\n format.json { render json: @ability.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @action_set = ActionSet.new(params[:action_set])\n\n respond_to do |format|\n if @action_set.save\n format.html { redirect_to @action_set, :notice => 'Action set was successfully created.' }\n format.json { render :json => @action_set, :status => :created, :location => @action_set }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @action_set.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @wanted_action = WantedAction.new(params[:wanted_action])\n\n respond_to do |format|\n if @wanted_action.save\n format.html { redirect_to @wanted_action, notice: 'Wanted action was successfully created.' }\n format.json { render json: @wanted_action, status: :created, location: @wanted_action }\n else\n format.html { render action: \"new\" }\n format.json { render json: @wanted_action.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @accessory = Accessory.new(params[:accessory])\n\n if @accessory.save\n render json: @accessory, status: :created, location: @accessory\n else\n render json: @accessory.errors, status: :unprocessable_entity\n end\n end", "def create\n @species_action = SpeciesAction.new(species_action_params)\n\n respond_to do |format|\n if @species_action.save\n format.html { redirect_to @species_action, notice: 'Le lien entre l\\'action et l\\'espèce a été créé.' }\n format.json { render :show, status: :created, location: @species_action }\n else\n format.html { render :new }\n format.json { render json: @species_action.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @accessory_act = AccessoryAct.new(params[:accessory_act])\n\n respond_to do |format|\n if @accessory_act.save\n format.html { redirect_to @accessory_act, :notice => 'Accessory act was successfully created.' }\n format.json { render :json => @accessory_act, :status => :created, :location => @accessory_act }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @accessory_act.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /actionables/1 PATCH/PUT /actionables/1.json
def update respond_to do |format| if @actionable.update(actionable_params) format.html { redirect_to @actionable, notice: 'Actionable was successfully updated.' } format.json { render :show, status: :ok, location: @actionable } else format.html { render :edit } format.json { render json: @actionable.errors, status: :unprocessable_entity } end end end
[ "def update\n head :forbidden\n\n #@action = Action.find(params[:id])\n\n #if @action.update_attributes(params[:action])\n # head :no_content\n # else\n # render json: @action.errors, status: :unprocessable_entity\n # end\n end", "def update\n @action_set = ActionSet.find(params[:id])\n\n respond_to do |format|\n if @action_set.update_attributes(params[:action_set])\n format.html { redirect_to @action_set, :notice => 'Action set was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @action_set.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @ai_action.update(ai_action_params)\n format.html { redirect_to [:admin, @ai_action], notice: 'Ai action was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @ai_action.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @single_action.update(single_action_params)\n format.html { redirect_to @single_action, notice: 'Single action was successfully updated.' }\n format.json { render :show, status: :ok, location: @single_action }\n else\n format.html { render :edit }\n format.json { render json: @single_action.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if actions = params[:http_path_rule].try(:[], :actions)\n actions = JSON.load(actions) if String === actions\n params[:http_path_rule][:actions] = actions\n end\n\n @http_path_rule = collection.find(params[:id])\n\n respond_to do |format|\n if @http_path_rule.update_attributes(params[:http_path_rule])\n @core_application.send_to_redis\n format.html do\n flash[:success] = 'Path rule was successfully updated.'\n redirect_to @core_application\n end\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @http_path_rule.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @simple_action.update(simple_action_params)\n format.html { redirect_to @simple_action, notice: 'Simple action was successfully updated.' }\n format.json { render :show, status: :ok, location: @simple_action }\n else\n format.html { render :edit }\n format.json { render json: @simple_action.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @editability = Editability.find(params[:id])\n\n respond_to do |format|\n if @editability.update_attributes(params[:editability])\n format.html { redirect_to @editability, notice: 'Test was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @editability.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @action_item.update(action_item_params)\n format.html { redirect_to @action_item, notice: 'Action item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @action_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @administration_action = Action.find(params[:id])\n\n respond_to do |format|\n if @administration_action.update_attributes(params[:action_item])\n format.html { redirect_to administration_actions_url, notice: 'Action was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @administration_action.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @wanted_action = WantedAction.find(params[:id])\n\n respond_to do |format|\n if @wanted_action.update_attributes(params[:wanted_action])\n format.html { redirect_to @wanted_action, notice: 'Wanted action was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @wanted_action.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @action_item = ActionItem.find(params[:id])\n\n respond_to do |format|\n if @action_item.update_attributes(params[:action_item])\n format.html { redirect_to @action_item, notice: 'Action item was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @action_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @mappable.update(mappable_params)\n format.html { redirect_to @mappable, notice: 'Mappable was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mappable.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @action_required.update(action_required_params)\n format.html { redirect_to @action_required, notice: 'Action required was successfully updated.' }\n format.json { render :show, status: :ok, location: @action_required }\n else\n format.html { render :edit }\n format.json { render json: @action_required.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @action_object.update(action_object_params)\n format.html { redirect_to action: 'index', notice: 'Objeto de Ação alterado com sucesso.'}\n format.json { render :show, status: :ok, location: @action_object }\n else\n format.html { render :edit }\n format.json { render json: @action_object.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @attraction.update(attraction_params)\n format.html { redirect_to @attraction, notice: 'Attraction was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @attraction.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n @usertable = Usertable.find(params[:id])\r\n\r\n respond_to do |format|\r\n if @usertable.update_attributes(params[:usertable])\r\n format.html { redirect_to @usertable, notice: 'Your mood was successfully updated.' }\r\n format.json { head :ok }\r\n else\r\n format.html { render action: \"edit\" }\r\n format.json { render json: @usertable.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n respond_to do |format|\n if @miscellaneous_ability.update(miscellaneous_ability_params)\n format.html { redirect_to @miscellaneous_ability, notice: 'Miscellaneous ability was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @miscellaneous_ability.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @cable = @server.cables.find(params[:id])\n\n respond_to do |format|\n if @cable.update_attributes(params[:cable])\n format.html { redirect_to (@server), notice: 'Cable was successfully updated.' }\n #format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n #format.json { render json: @cable.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n json_update(factType,factType_params, FactType)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /actionables/1 DELETE /actionables/1.json
def destroy @actionable.destroy respond_to do |format| format.html { redirect_to actionables_url, notice: 'Actionable was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @single_action.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @ai_action.destroy\n respond_to do |format|\n format.html { redirect_to admin_ai_actions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @action_item = ActionItem.find(params[:id])\n @action_item.destroy\n\n respond_to do |format|\n format.html { redirect_to action_items_url }\n format.json { head :ok }\n end\n end", "def destroy\n @wanted_action = WantedAction.find(params[:id])\n @wanted_action.destroy\n\n respond_to do |format|\n format.html { redirect_to wanted_actions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @simple_action.destroy\n respond_to do |format|\n format.html { redirect_to indexfiltro_simple_actions_path, notice: 'Simple action was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @administration_action = Action.find(params[:id])\n @administration_action.destroy\n\n respond_to do |format|\n format.html { redirect_to administration_actions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @action_type = ActionType.find(params[:id])\n verify_user(@action_type.action_list.datum.user.id)\n @action_type.destroy\n\n respond_to do |format|\n format.html { redirect_to action_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @action_item.destroy\n respond_to do |format|\n format.html { redirect_to action_items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @accessory_act = AccessoryAct.find(params[:id])\n @accessory_act.destroy\n\n respond_to do |format|\n format.html { redirect_to accessory_acts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @action_set = ActionSet.find(params[:id])\n @action_set.destroy\n\n respond_to do |format|\n format.html { redirect_to action_sets_url }\n format.json { head :ok }\n end\n end", "def destroy\n @ability.destroy\n respond_to do |format|\n format.html { redirect_to abilities_url }\n flash[:success] = \"Ability deleted!\"\n format.json { head :no_content }\n end\n end", "def destroy\n @miscellaneous_ability.destroy\n respond_to do |format|\n format.html { redirect_to miscellaneous_abilities_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @iptable.destroy\n respond_to do |format|\n format.html { redirect_to iptables_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @walkthrough.destroy\n respond_to do |format|\n format.html { redirect_to controller: 'requests', action: \"show\", id: @walkthrough.request_id }\n format.json { head :no_content }\n end\n end", "def destroy\n @accessory = Accessory.find(params[:id])\n @accessory.destroy\n\n respond_to do |format|\n format.html { redirect_to accessories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @permit.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @action_name = ActionName.find(params[:id])\n @action_name.destroy\n\n respond_to do |format|\n format.html { redirect_to action_names_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @makeable.destroy\n respond_to do |format|\n format.html { redirect_to makeables_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @actionlist.destroy\n respond_to do |format|\n format.html { redirect_to actionlists_url, notice: 'Actionlist was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method showing lives remaining
def show_lives puts "Lives remaining: #{@players[0].name}: #{@players[0].life}/3 - #{@players[1].name}: #{@players[1].life}/3" end
[ "def show_lives(lives)\n puts \"#{lives} Lives left\"\n end", "def take_life\n @lives -= 1\n end", "def reduce_life\n if @lives > 0\n @lives -= 1\n end\n end", "def remove_life\r\n @lives -= 1\r\n end", "def life_count\n puts \"#{@player1.name}'s lives: #{@player1.lives}\\n#{@player2.name}'s lives: #{@player2.lives}\"\n end", "def player_lives_status(player, no_of_lives)\n \"#{player_name(player)} has #{no_of_lives} lives left.\\n\"\nend", "def lose_life()\r\n @life -= 1\r\n end", "def life\n return @life\n end", "def subtract_player_life\n @player.lose_life\n end", "def player_lives_status(player, num_lives)\n \"\\n#{player_name(player)} has #{num_lives} lives/life left.\\n\"\nend", "def lives_decriment\n\t\tlives_will_change!\n\t\tself.lives -= 1 \n\t\tself.hp = self.level+5\n\t\tself.save!\n\t\tif self.lives <=0 \n\t\t\t# restarts NPC's renders user-wizards unusable\n\t\t\tif self.user_id == 1\n\t\t\t\tself.default_values()\n\t\t\telse\n\t\t\t\tputs \"Game Over for #{self.name}!\"\n\t\t\t\tself.level = 0\n\t\t\tend\n\t\tend\n\tend", "def remaining\n total - used\n end", "def remaining_hours\n \n end", "def show_state\n if @life_points <= 0\n puts \">>> #{@name} a 0 points de vie\"\n else\n puts \">>> #{@name} a #{@life_points} points de vie\"\n end\n end", "def mdps_remaining\n render :text => \"#{@key.event.mdps_per_key - @key.current_mdp}\\n\"\n end", "def remaining\n (Time.now - @last_scrape).to_i \n end", "def remaining_time\n distance_of_time_in_words promised_for, Time.now\n end", "def lives_decriment\n\t\tlives_will_change!\n\t\tself.lives -= 1 \n\t\tself.hp = self.level+5\n\t\tself.save!\n\t\tif self.lives <=0 \n\t\t\tputs \"Game Over!\"\n\t\t\tself.destroy()\n\t\tend\n\tend", "def display_turns\n\t\tputs \"You have #{@turns_remaining} turns remaining\"\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the uploaded file. Resulting data will be in data
def parse(uploaded_file) parser_class = case uploaded_file.content_type when "application/vnd.ms-excel" ExcelParser when "text/csv", "application/octet-stream", "text/plain" CSVParser else self.errors << "Do not know how to parse #{uploaded_file.original_filename}. " + "Expects .csv or .xls (Excel) files." nil end if parser_class @data = parser_class.new(self).parse(uploaded_file) end self.valid? end
[ "def uploaded_data=(file)\n self.data = []\n if !file.kind_of?(String)\n self.name = file.original_filename\n self.content_type = file.content_type.chomp\n self.data = file.read\n end\n end", "def parse_data\n end", "def parse\n uploader = FileUpload.new(params[:contacts])\n uploader.parse\n \n unless uploader.errors.empty?\n @uploader = uploader\n render :action=>:new\n return\n end\n \n @columns = uploader.columns.map{|col| [(col+\" (column #{uploader.columns.index(col)+1})\").downcase,col.downcase]}\n @columns.unshift([\"Select\",nil])\n\n # Security reason this has been saved in Session. \n session[:filename] = uploader.new_filename\n\n end", "def parse_and_upload!\n parsed = multipart.open do |file|\n VBADocuments::MultipartParser.parse(file.path)\n end\n parsed_files.attach(io: StringIO.new(parsed['metadata'].to_s), filename: \"#{guid}_metadata.json\")\n pdf_keys = parsed.keys - ['metadata']\n pdf_keys.each do |k|\n parsed_files.attach(io: File.open(parsed[k]), filename: \"#{guid}_#{k}.pdf\")\n end\n save!\n end", "def parse\n file = File.read(@file)\n @data = JSON.parse(file)\n end", "def parse\n @file_data.each {|line|\n h = {}\n data_elements = line.split('|').collect(&:strip)\n #LastName | FirstName | MiddleInitial | Gender | FavoriteColor | DateOfBirth\n @data_collection << {:last_name => data_elements[0], :first_name => data_elements[1], :middle_initial => data_elements[2], :gender => (data_elements[3] == 'M') ? 'Male' : 'Female', :favorite_color => data_elements[4], :dob => data_elements[5].gsub('-', '/'), :dob_year => data_elements[5][-4,4]}\n }\n end", "def file_data\n return @file_data\n end", "def parse_file(filename); end", "def process_file(data)\n data = parse(data)\n data = strip_headers(data) if @has_headers\n data = apply_reject_lines(data) if @reject_lines\n data = strip_columns(data) if @strip\n data = sort_columns(data) if @sort_on\n data = apply_groups(data) if @groups\n apply_map(data) if @map\n end", "def parse\n read_header\n parse_text_segment\n parse_data_segment\n @data = nil\n end", "def uploaded_file\n instance_read(:uploaded_file)\n end", "def parse(data); end", "def process\n validate_file_type(@file_name, 'csv')\n convert_csv_file_to_object\n end", "def parse_files\n options.each do |type, filename|\n begin\n content[type] = FCSV.read(filename)\n rescue CSV::MalformedCSVError\n $stderr.puts \"Error parsing #{filename}: #{$!.message}\"\n exit 1\n rescue Errno::ENOENT, Errno::EACCES\n $stderr.puts \"Error reading #{filename}: #{$!.message}\"\n exit 1\n end\n end\n end", "def convertRawData(data)\n @raw_data['file'] = data\n @helper.post(@fields, @files, @raw_data)\n end", "def parse!\n # populate the downloadable_files array\n set_downloadable_files\n\n # populate the pieces array\n set_pieces\n end", "def parse_file!(filename)\n self.parse!(File.read(filename))\n end", "def update_file_meta_data\n if file.present? && file_changed?\n self.filename = read_attribute(:file)\n self.content_type = file.file.content_type unless file.file.content_type.blank?\n self.file_size = file.file.size unless file.file.size.blank?\n end\n end", "def parsed_file_name\n data_file_name.split('.')[0]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns array of keys that do not have value in the hash Given +required_keys+ should be an array of +string+
def missing_keys_from(required_keys) required_keys.select{ |k| self.get(k).to_s.empty? } end
[ "def reject_keys!(hash, keys)\n hash.reject { |k, _| keys.include?(k) }\n end", "def only(hash, *keys)\n s_keys = keys.flatten.collect{|k| k.to_s}\n hash.delete_if{ |k,v| !keys.flatten.include?(k) && !s_keys.include?(k) }\n hash\n end", "def extra_keys( keys )\n incoming = keys\n existing = places.flat_map{|subset, placeholders| placeholders.keys}\n\n # find the elements in incoming that are not in existing\n incoming - existing & incoming\n end", "def except(hash, *keys)\n s_keys = keys.flatten.collect{|k| k.to_s}\n hash.delete_if{ |k,v| keys.flatten.include?(k) || s_keys.include?(k) }\n hash\n end", "def without(*keys)\n keys = keys.flatten\n pairs = each_pair.filter { |k, _| !k.in?(keys) }\n pairs.to_h\n end", "def assert_missing_keys obj, keys, msg = nil\n keys = [ keys ] unless keys.kind_of?(Array)\n msg = message(msg) {\n \"Expected #{mu_pp(obj)} not to include any of these keys #{mu_pp(keys)}\"\n }\n keys.none? { |key| refute obj.key?(key), msg }\n end", "def not_matched_keys\n @not_matched.keys\n end", "def reachable_keys(keys)\n keyring = keys.to_set\n (@all_keys-keys).filter { |k| @required_keys[k] <= keyring } # subset\nend", "def missing\n @options.select { |opt| not present?(opt.key) }.map(&:key)\n end", "def required_keys_exist?(payload_hash)\n received_keys = payload_hash.keys\n\n REQUIRED_KEYS.each { |key|\n key_missing(key) unless received_keys.include?(key)\n }\n end", "def konly(*x)\n reject{ |k,v| !x.include?(k) }\n end", "def checked_keys(params_hash)\n params_hash.reject{ |key, value| value.blank? || value == '0' }.keys\n end", "def unmatched_keys; end", "def unique_keys(keys)\n # The simplest way is to stringify all keys before making them\n # unique. That works for Integer as well as Symbol.\n return keys.map(&:to_s).uniq\n end", "def missing_keys; end", "def accept_keys!(hash, keys)\n reject_keys!(hash, hash.keys - keys)\n end", "def assert_only_keys(hash, *keys)\n assert_exists(hash)\n assert(hash.respond_to?(:[]))\n values = hash.inject([]) { |vals, (k, v)| \n assert(keys.include?(k)); vals << hash[k] \n }\n assert(yield(*values)) if block_given?\n hash\n end", "def unused_keys\n keys - fetched_keys\n end", "def _keys_data_missing(options, required, result)\n return false unless required[0] == :keys\n\n return true unless options.key?(:keys)\n return true unless result[0][0].is_a?(Array)\n return true if result[0][0].length == 0\n false\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make Update expression 'SET = :' : points to a value from the expression_attribute_value
def make_update_expression_values(event,attr_values) update_string = 'SET ' event.each do |k,v| update_string += "#{make_expression_key(k,"names")} = #{attr_values[k].key(v)}, " end return update_string[0...-2] end
[ "def update_value(expr, expr_single)\n query = \"update replace \" + expr + \" with \" + expr_single\n execute_query(query)\n rescue => e\n raise e \n end", "def set(column, value)\n @set_clauses << [column, Translate.escape_sql(value)].join(' = ')\n end", "def expression=(value)\n @expression = value\n end", "def updateValuesSyntax\n str = String.new \n @SQLAttributes.each do |attribute| \n if !@Keys.include? attribute[0]\n str += attribute[0] + \"=?,\"\n end \n end \n str.chop! \n return str\n end", "def replacement_value\n case edit_type\n when 'SET'\n value\n when 'ADD'\n a = Healthtap::NoSql.attribute_value(document.table_name,\n item_hash, attribute_path) || []\n a.append(value)\n when 'DELETE'\n a = Healthtap::NoSql.attribute_value(document.table_name,\n item_hash, attribute_path) || []\n a - [value]\n end\n end", "def update_field field, value\n Formula.new update(\n @ast,\n [ by_type('begin'),\n by_both(\n by_type('send'),\n by_msg(field)),\n by_type('str')],\n -> (n) { n.updated(nil, [value]) })\n end", "def m_set_expr_attribute\n begin\n _type = SET_EXPR_ATTRIBUTE\n a = nil\n expr = nil\n id7 = nil\n # ActionTranslator.g:697:2: ( '%' a= ACTION '.' ID ( WS )? '=' expr= ATTR_VALUE_EXPR ';' )\n # ActionTranslator.g:697:4: '%' a= ACTION '.' ID ( WS )? '=' expr= ATTR_VALUE_EXPR ';'\n match(Character.new(?%.ord))\n if (self.attr_state.attr_failed)\n return\n end\n a_start813 = get_char_index\n m_action\n if (self.attr_state.attr_failed)\n return\n end\n a = CommonToken.new(self.attr_input, Token::INVALID_TOKEN_TYPE, Token::DEFAULT_CHANNEL, a_start813, get_char_index - 1)\n match(Character.new(?..ord))\n if (self.attr_state.attr_failed)\n return\n end\n id7start817 = get_char_index\n m_id\n if (self.attr_state.attr_failed)\n return\n end\n id7 = CommonToken.new(self.attr_input, Token::INVALID_TOKEN_TYPE, Token::DEFAULT_CHANNEL, id7start817, get_char_index - 1)\n # ActionTranslator.g:697:24: ( WS )?\n alt17 = 2\n la17_0 = self.attr_input._la(1)\n if (((la17_0 >= Character.new(?\\t.ord) && la17_0 <= Character.new(?\\n.ord)) || (la17_0).equal?(Character.new(?\\r.ord)) || (la17_0).equal?(Character.new(?\\s.ord))))\n alt17 = 1\n end\n case (alt17)\n when 1\n # ActionTranslator.g:697:24: WS\n m_ws\n if (self.attr_state.attr_failed)\n return\n end\n end\n match(Character.new(?=.ord))\n if (self.attr_state.attr_failed)\n return\n end\n expr_start826 = get_char_index\n m_attr_value_expr\n if (self.attr_state.attr_failed)\n return\n end\n expr = CommonToken.new(self.attr_input, Token::INVALID_TOKEN_TYPE, Token::DEFAULT_CHANNEL, expr_start826, get_char_index - 1)\n match(Character.new(?;.ord))\n if (self.attr_state.attr_failed)\n return\n end\n if ((self.attr_state.attr_backtracking).equal?(1))\n st = template(\"actionSetAttribute\")\n action = (!(a).nil? ? a.get_text : nil)\n action = RJava.cast_to_string(action.substring(1, action.length - 1)) # stuff inside {...}\n st.set_attribute(\"st\", translate_action(action))\n st.set_attribute(\"attrName\", (!(id7).nil? ? id7.get_text : nil))\n st.set_attribute(\"expr\", translate_action((!(expr).nil? ? expr.get_text : nil)))\n end\n self.attr_state.attr_type = _type\n ensure\n end\n end", "def set( row )\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 8 )\n __ID6__ = nil\n expr7 = nil\n\n begin\n # at line 52:9: ID '=' expr\n __ID6__ = match( ID, TOKENS_FOLLOWING_ID_IN_set_284 )\n match( T__18, TOKENS_FOLLOWING_T__18_IN_set_286 )\n @state.following.push( TOKENS_FOLLOWING_expr_IN_set_288 )\n expr7 = expr\n @state.following.pop\n # --> action\n row.set(__ID6__.text, expr7);\n # <-- action\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__, 8 )\n\n end\n\n return\n end", "def update_replace(expr, expr_single)\n query = \"update replace \"+expr+\" with \"+expr_single\n execute_query(query)\n rescue => e\n raise e \n end", "def setq(sym, expr)\n\t\tif expr.is_a?(String)\n\t\t\tif expr.match(/\\(list/)\t\n\t\t\t\tstr = \"(setq #{sym.to_s} #{expr.to_s})\" \n\t\t\telse\t\n\t\t\t\tstr = \"(setq #{sym.to_s} \\\"#{expr.to_s}\\\")\" \n\t\t\tend\t\n\t\t\tputs str\n\t\telse\n\t\t\tstr = \"(setq #{sym.to_s} #{expr.to_s})\" \n\t\t\tputs str\n\n\t\tend\t\n\t\tlisp_eval str\n\tend", "def test_assignment_binds_are_substituted\n table = Table.new(:users)\n um = Arel::UpdateManager.new Table.engine\n bp = Nodes::BindParam.new '?'\n um.set [[table[:name], bp]]\n visitor = Class.new(Arel::Visitors::ToSql) {\n include Arel::Visitors::BindVisitor\n }.new Table.engine.connection\n\n assignment = um.ast.values[0]\n actual = visitor.accept(assignment, collector) {\n \"replace\"\n }\n assert actual\n value = actual.value\n assert_like \"\\\"name\\\" = replace\", value\n end", "def expression=(new_expression)\n unless ['sample', 'full', 'nonstop'].include? new_expression.downcase\n return @expression\n end\n @expression = new_expression.downcase\n end", "def update(attribute, value)\n\t\tDisbatch.db[:tasks].update({:_id => @id}, {:$set => { attribute => value } })\n\tend", "def object_set_attribute(name, value)\n # TODO handle selection empty error\n execute(\"object-set-attribute:#{name},#{value}\")\n end", "def update_expression (fexp)\n\n fexp.application_context = application_context\n\n fexp.raw_rep_updated = true\n\n get_expression_pool.update(fexp)\n end", "def update_column(name, value); end", "def update_property(property, value)\n execute_sql_statement(<<-UPDATE_PROP\n update properties set\n value = '#{value}'\n where property = '#{property}';\n UPDATE_PROP\n )\n end", "def substitute_values(expression)\n if expression.is_a?(Array)\n pieces = expression[1..-1].collect do |value|\n escape_sql(value)\n end\n if expression.first == :in\n \"(#{pieces.join(', ')})\"\n else\n expression[0] % pieces\n end\n else\n expression\n end\n end", "def parsed_expression=(value)\n @parsed_expression = value\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a new archive by merging this and another archive
def merge(other) assert_archive other data = deep_clone(@data) merge_data data, other.as_json, other.uri self.class.new data end
[ "def merge!(other)\n assert_archive other\n clear_caches\n\n merge_data @data, other.as_json, other.uri\n nil\n end", "def make_archive(archivename, archive_comment, sdrf)\n project_dir = ExpandController.path_to_project_dir(command_object.project)\n extracted_dir = File.join(project_dir, \"extracted\")\n relative_sdrf = sdrf.sub(extracted_dir, \"\")\n relative_sdrf.gsub!(/^\\/*/, '') # remove leading /s\n \n # Find existing active archives made for sdrf storage\n old_archives = command_object.project.project_archives.find_all{|pa| \n (pa.status == ProjectArchive::Status::EXPANDED) && (pa.is_active) &&\n (pa.file_name.include? archivename)\n }\n # Deactivate them and remove any of their project files\n old_archives.each{|pa| \n pa.status = ProjectArchive::Status::NOT_EXPANDED\n pa.is_active = false\n pa.save\n pa.project_files.each{|pf|\n pf.destroy\n }\n }\n # If there are still any matching ProjectFiles, eg from original archive\n old_sdrf_files = []\n command_object.project.project_archives.each{|pa|\n found = pa.project_files.find_by_file_name(relative_sdrf) \n old_sdrf_files << found unless found.nil?\n }\n # Mark them as overwritten\n old_sdrf_files.each{|os|\n os.is_overwritten = true\n os.save\n }\n # Then make the new archive\n (archive = command_object.project.project_archives.new).save\n tarname = \"#{\"%03d\" % archive.attributes[archive.position_column]}_#{archivename}.tar\"\n archive.file_name = \"#{tarname}.gz\"\n archive.file_date = Time.now\n archive.is_active = true\n archive.comment = archive_comment \n archive.save\n\n # And tar it up\n absolute_desttgz = File.join(project_dir, archive.file_name)\n cmd = \"tar -czvf #{Shellwords.escape(absolute_desttgz)} -C #{Shellwords.escape(extracted_dir)} #{Shellwords.escape(relative_sdrf)}\"\n \n begin\n result = `#{cmd} 2>&1`\n command_object.stdout = \"#{command_object.stdout}\\nCompressed #{result} to #{File.basename(absolute_desttgz)}\"\n command_object.save\n\n # Finish updating the archive\n archive.file_size = File.size(absolute_desttgz)\n archive.signature = PipelineController.new.generate_file_signature(absolute_desttgz)\n archive.status = ProjectArchive::Status::EXPANDED\n archive.save\n\n # Then make the new ProjectFile for the sdrf\n (project_file = archive.project_files.new(\n :file_name => relative_sdrf,\n :file_size => File.size(sdrf),\n :file_date => File.ctime(sdrf),\n :signature => PipelineController.new.generate_file_signature(sdrf)\n )).save\n rescue Exception => e\n logger.error \"Error making ProjectArchive of SDRF with GeoIDs: #{e.class}: #{e.to_s}\"\n logger.error e.backtrace.join \"\\n\"\n archive.destroy\n command_object.stdout = \"#{command_object.stdout}\\nERROR: Couldn't make archive of updated SDRF: #{e.to_s}!}\"\n command_object.stderr = \"ERROR: Couldn't make archive of updated SDRF: #{e.to_s}!}\"\n command_object.save\n return false\n end\n true\n end", "def merge(source); end", "def archive!\n archive\n save!(validate: false)\n end", "def merge(other, sibling_compression_counter = nil)\n self.merge_actors(other)\n self.remove_duplicates()\n self.compress_history(sibling_compression_counter)\n end", "def create_archive\n created = false\n empty = true\n Dir.mktmpdir do |tmpdir|\n # create manifest\n tmpmf = File.join(tmpdir, DulHydra.export_set_manifest_file_name)\n # create the zip archive\n zip_name = \"export_set_#{Time.now.strftime('%Y%m%d%H%M%S')}.zip\"\n zip_path = File.join(tmpdir, zip_name)\n Zip::ZipFile.open(zip_path, Zip::ZipFile::CREATE) do |zip_file|\n CSV.open(tmpmf, 'wb') do |manifest|\n manifest << archive_manifest_header\n pids.each do |pid|\n # get Fedora object\n begin\n object = ActiveFedora::Base.find(pid, :cast => true) \n # skip if object is not content-bearing or user lacks :read permission\n next unless object.has_content? and user.can?(:read, object)\n content_ds = object.datastreams[DulHydra::Datastreams::CONTENT]\n # use guaranteed unique file name based on PID and dsID \n temp_file_path = File.join(tmpdir, content_ds.default_file_name)\n # write content to file\n File.open(temp_file_path, 'wb', :encoding => 'ascii-8bit') do |f|\n content_ds.write_content(f)\n end\n # Use original source file name, if available; otherwise the generated file name\n # Note that we keep the path of the source file in order to reduce likelihood\n # name conflicts, and since it is easy to flatten zip contents on extraction.\n # However, we don't want the path of the generated temp file, just the basename.\n file_name = object.source.first || File.basename(temp_file_path)\n # discard leading slash, if present\n file_name = file_name[1..-1] if file_name.start_with? '/'\n # add file to archive\n zip_file.add(file_name, temp_file_path)\n # add row to manifest\n manifest << archive_manifest_row(file_name, object)\n rescue ActiveFedora::ObjectNotFoundError => e\n logger.error e\n next\n end\n end # document_list\n end # manifest\n # check if the zip file is emtpy\n empty = (zip_file.size == 0)\n # write manifest \n zip_file.add(DulHydra.export_set_manifest_file_name, tmpmf) unless empty\n end # zip_file\n # update_attributes seems to be the way to get paperclip to work \n # when not using file upload form submission to create the attachment\n created = !empty && update_attributes({:archive => File.new(zip_path, \"rb\")})\n end # tmpdir is removed\n created\n end", "def archive\n request = Request.new(\n \"/#{ space.id }/assets/#{ id }/archived\",\n {},\n id = nil,\n version: sys[:version]\n )\n response = request.put\n result = ResourceBuilder.new(response, {}, {}).run\n refresh_data(result)\n end", "def merge_zip merged_build\n debug_msg \"Merging zip for #{merged_build}\"\n \n tmp = temp_dir\n \n title = merged_build.builds.map do |build| \n automation_by_name(build.name).name + \" v#{build.version}\"\n end.join(', ')\n names = merged_build.builds.map do |build| \n automation_by_name(build.name).short_name\n end.join(',')\n options = []\n options << \"-o\" << tmp\n options << '--title' << title\n options << '--names' << names\n merged_build.builds.each do |build|\n options << File.join(@public_dir, build.to_s)\n end\n SDoc::Merge.new.merge(options)\n \n prepare tmp\n \n tmp\n end", "def create(files, gzip: false)\n tgt_dir = File.dirname(archive)\n target = Tempfile.new(File.basename(archive), tgt_dir)\n target.binmode\n\n Gem::Package::TarWriter.new(target) do |tar|\n files.each do |fn|\n mode = File.stat(fn).mode\n if File.symlink?(fn)\n target = File.readlink(fn)\n tar.add_symlink(fn, target, mode)\n elsif File.directory?(fn)\n tar.mkdir(fn, mode)\n elsif File.file?(fn)\n file = File.open(fn, \"rb\")\n tar.add_file(fn, mode) do |io|\n io.write(file.read)\n end\n file.close\n end\n end\n end\n\n target.close\n if gzip\n Zlib::GzipWriter.open(archive, Zlib::BEST_COMPRESSION) do |gz|\n gz.mtime = File.mtime(target.path)\n gz.orig_name = File.basename(archive)\n File.open(target.path) do |file|\n while (chunk = file.read(16 * 1024))\n gz.write(chunk)\n end\n end\n end\n else\n FileUtils.mv(target.path, archive)\n end\n ensure\n target.close unless target.closed?\n end", "def archive!\n DocumentArchive.create!(:consumer_id => self.consumer_id, :suggested_standard_document_id => self.suggested_standard_document_id, :rejected_at => Time.now, :suggested_at => self.suggested_at, :source => self.source, :file_content_type => self.file_content_type, :cloud_service_full_path => self.cloud_service_full_path, :original_file_name => self.original_file_name)\n end", "def archive_file( src, dest )\n update_file( src, dest, true, false )\n end", "def join(other)\n new(entries.merge(other.entries) { |_name, old, new| old + new })\n end", "def create(options={})\n Archive.create(@config.merge(options))\n end", "def archive\n @repo.archive(sha, nil, :format => 'tgz', :prefix => \"#{safe_name}/\")\n end", "def archive_incremental(source_directory, destination_dir, file_prefix, file_suffix, tag_prefix)\n @project.from_directory do\n latest_tag_count = @project.latest_tag_count(tag_prefix)\n\n if latest_tag_count == 0\n archive_single(source_directory, File.join(destination_dir, file_prefix + file_suffix))\n else\n destination_file = File.join(destination_dir,\n \"#{file_prefix}_#{format(\"%04d\", latest_tag_count)}#{file_suffix}\")\n tag = @project.latest_tag(tag_prefix)\n log.debug \"creating #{destination_file} with files newer than #{tag}\"\n\n log.debug \"files that changed since then: #{@project.git.changed_files_since(tag)}\"\n list = @project.git.changed_files_since(tag).select do |file|\n File.expand_path(file) =~ /^#{File.expand_path(source_directory)}\\//\n end.map do |file|\n Pathname.new(file).relative_path_from Pathname.new(source_directory)\n end\n @project.from_directory source_directory do\n `tar -cJf #{destination_file} #{list.join(\" \")}`\n end\n\n destination_file\n end\n end\n end", "def merge(other_image)\n raise 'an image class must be supplied' unless other_image.is_a? Image\n raise 'cannot merge if the user is different' unless other_image.user == user\n raise 'cannot merge if the account_id is different' unless other_image.account_id == account_id\n raise 'cannot merge if the state is different' unless other_image.state == state\n\n new_image = Image.new\n new_image.user = @user\n new_image.entries = entries + other_image.entries\n new_image\n end", "def merge!(another)\n @manifest = merge(another).to_h\n end", "def generate_archive\n return if @cfg.archive\n @cfg.rgroup['archive'] = Array.new\n @cfg.save\n @cfg.load(@group)\n end", "def merge other\n if empty? then\n @parts = other.parts\n return self\n end\n\n other.parts.each do |other_part|\n self.parts.delete_if do |self_part|\n self_part.file and self_part.file == other_part.file\n end\n\n self.parts << other_part\n end\n\n self\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
destructively merge this with the given archive
def merge!(other) assert_archive other clear_caches merge_data @data, other.as_json, other.uri nil end
[ "def merge(other)\n assert_archive other\n\n data = deep_clone(@data)\n merge_data data, other.as_json, other.uri\n\n self.class.new data\n end", "def restore_archive\n end", "def archive!\n archive\n save!(validate: false)\n end", "def merge(other, sibling_compression_counter = nil)\n self.merge_actors(other)\n self.remove_duplicates()\n self.compress_history(sibling_compression_counter)\n end", "def merge(source); end", "def archives\n @parent.cleanup_archives\n end", "def merge other\n if empty? then\n @parts = other.parts\n return self\n end\n\n other.parts.each do |other_part|\n self.parts.delete_if do |self_part|\n self_part.file and self_part.file == other_part.file\n end\n\n self.parts << other_part\n end\n\n self\n end", "def merge!(an_a)\n self.class.merge(self, an_a)\n end", "def archive_all\n all.update_all(archived: true)\n end", "def merge!(another)\n @manifest = merge(another).to_h\n end", "def unarchive\n unless in_zip?\n zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]}\n zips.each do |item|\n FileUtils.mkdir_p current_dir.join(item.basename)\n Zip::File.open(item) do |zip|\n zip.each do |entry|\n FileUtils.mkdir_p File.join(item.basename, File.dirname(entry.to_s))\n zip.extract(entry, File.join(item.basename, entry.to_s)) { true }\n end\n end\n end\n gzs.each do |item|\n Zlib::GzipReader.open(item) do |gz|\n Gem::Package::TarReader.new(gz) do |tar|\n dest_dir = current_dir.join (gz.orig_name || item.basename).sub(/\\.tar$/, '')\n tar.each do |entry|\n dest = nil\n if entry.full_name == '././@LongLink'\n dest = File.join dest_dir, entry.read.strip\n next\n end\n dest ||= File.join dest_dir, entry.full_name\n if entry.directory?\n FileUtils.mkdir_p dest, mode: entry.header.mode\n elsif entry.file?\n FileUtils.mkdir_p dest_dir\n File.open(dest, 'wb') {|f| f.print entry.read}\n FileUtils.chmod entry.header.mode, dest\n elsif entry.header.typeflag == '2' # symlink\n File.symlink entry.header.linkname, dest\n end\n unless Dir.exist? dest_dir\n FileUtils.mkdir_p dest_dir\n File.open(File.join(dest_dir, gz.orig_name || item.basename), 'wb') {|f| f.print gz.read}\n end\n end\n end\n end\n end\n else\n Zip::File.open(current_zip) do |zip|\n zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry|\n FileUtils.mkdir_p File.join(current_zip.dir, current_zip.basename, File.dirname(entry.to_s))\n zip.extract(entry, File.join(current_zip.dir, current_zip.basename, entry.to_s)) { true }\n end\n end\n end\n ls\n end", "def merge_zip merged_build\n debug_msg \"Merging zip for #{merged_build}\"\n \n tmp = temp_dir\n \n title = merged_build.builds.map do |build| \n automation_by_name(build.name).name + \" v#{build.version}\"\n end.join(', ')\n names = merged_build.builds.map do |build| \n automation_by_name(build.name).short_name\n end.join(',')\n options = []\n options << \"-o\" << tmp\n options << '--title' << title\n options << '--names' << names\n merged_build.builds.each do |build|\n options << File.join(@public_dir, build.to_s)\n end\n SDoc::Merge.new.merge(options)\n \n prepare tmp\n \n tmp\n end", "def archive\n request = Request.new(\n \"/#{ space.id }/assets/#{ id }/archived\",\n {},\n id = nil,\n version: sys[:version]\n )\n response = request.put\n result = ResourceBuilder.new(response, {}, {}).run\n refresh_data(result)\n end", "def archive\n delete_content\n filename = 'archive.' + $el.file_name_nondirectory(buffer_file_name)\n timestamp = \"--- archived on #{Time.now.strftime('%Y-%m-%d at %H:%M')} --- \\n\"\n append_to_file timestamp, nil, filename\n append_to_file content, nil, filename \n end", "def merge!( other )\n my_keys = @ini.keys\n other_keys =\n case other\n when IniFile; other.instance_variable_get(:@ini).keys\n when Hash; other.keys\n else raise \"cannot merge contents from '#{other.class.name}'\" end\n\n (my_keys & other_keys).each do |key|\n @ini[key].merge!(other[key])\n end\n\n (other_keys - my_keys).each do |key|\n @ini[key] = other[key]\n end\n\n self\n end", "def archive\n delete_content\n filename = 'archive.' + $el.file_name_nondirectory(buffer_file_name)\n timestamp = \"--- archived on #{Time.now.strftime('%Y-%m-%d at %H:%M')} --- \\n\"\n append_to_file timestamp, nil, filename\n append_to_file content, nil, filename\n end", "def merge!(other)\n @base.merge!(other)\n self\n end", "def merge!(other)\n return self if other.nil?\n\n my_keys = @ini.keys\n other_keys = case other\n when IniFile\n other.instance_variable_get(:@ini).keys\n when Hash\n other.keys\n else\n raise Error, \"cannot merge contents from '#{other.class.name}'\"\n end\n\n (my_keys & other_keys).each do |key|\n case other[key]\n when Hash\n @ini[key].merge!(other[key])\n when nil\n nil\n else\n raise Error, \"cannot merge section #{key.inspect} - unsupported type: #{other[key].class.name}\"\n end\n end\n\n (other_keys - my_keys).each do |key|\n @ini[key] = case other[key]\n when Hash\n other[key].dup\n when nil\n {}\n else\n raise Error, \"cannot merge section #{key.inspect} - unsupported type: #{other[key].class.name}\"\n end\n end\n\n self\n end", "def merge(stanza)\n # Whe use the **stanza.hash.each**, so nil values (deleted values)\n # are also copied. \n stanza.hash.each { |k, v|\n self[k] = v if @hash[k] and @hash[k] != v \n }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the countdownDisplayBeforeRestartInMinutes property value. The number of minutes before the restart time to display the countdown dialog for pending restarts.
def countdown_display_before_restart_in_minutes return @countdown_display_before_restart_in_minutes end
[ "def countdown_display_before_restart_in_minutes=(value)\n @countdown_display_before_restart_in_minutes = value\n end", "def reminder_minutes_before_start\n return @reminder_minutes_before_start\n end", "def reminder_minutes_before_start=(value)\n @reminder_minutes_before_start = value\n end", "def restart_notification_snooze_duration_in_minutes\n return @restart_notification_snooze_duration_in_minutes\n end", "def restart_count\n return @restart_count\n end", "def schedule_imminent_restart_warning_in_minutes\n return @schedule_imminent_restart_warning_in_minutes\n end", "def schedule_restart_warning_in_hours\n return @schedule_restart_warning_in_hours\n end", "def restart_notification_snooze_duration_in_minutes=(value)\n @restart_notification_snooze_duration_in_minutes = value\n end", "def automatic_restart_time\n data[:automatic_restart_time]\n end", "def minutes\n (seconds % 3600) / 60\n end", "def seconds_before_retry\n @configuration[:seconds_before_retry]\n end", "def restart_count=(value)\n @restart_count = value\n end", "def password_minutes_of_inactivity_before_lock\n return @password_minutes_of_inactivity_before_lock\n end", "def schedule_imminent_restart_warning_in_minutes=(value)\n @schedule_imminent_restart_warning_in_minutes = value\n end", "def minutes_in_hour\r\n return 60\r\n end", "def minutes\n Integer(seconds % 3600) / 60\n end", "def password_minutes_of_inactivity_before_screen_timeout\n return @password_minutes_of_inactivity_before_screen_timeout\n end", "def minutes\n (@internal_seconds / 60) % 60\n end", "def minutes_left_in_hour(start)\n return @values[start.hour].wp_diff(start.min,60)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the countdownDisplayBeforeRestartInMinutes property value. The number of minutes before the restart time to display the countdown dialog for pending restarts.
def countdown_display_before_restart_in_minutes=(value) @countdown_display_before_restart_in_minutes = value end
[ "def countdown_display_before_restart_in_minutes\n return @countdown_display_before_restart_in_minutes\n end", "def reminder_minutes_before_start=(value)\n @reminder_minutes_before_start = value\n end", "def schedule_imminent_restart_warning_in_minutes=(value)\n @schedule_imminent_restart_warning_in_minutes = value\n end", "def restart_notification_snooze_duration_in_minutes=(value)\n @restart_notification_snooze_duration_in_minutes = value\n end", "def restart_count=(value)\n @restart_count = value\n end", "def schedule_restart_warning_in_hours=(value)\n @schedule_restart_warning_in_hours = value\n end", "def work_profile_password_minutes_of_inactivity_before_screen_timeout=(value)\n @work_profile_password_minutes_of_inactivity_before_screen_timeout = value\n end", "def password_minutes_of_inactivity_before_screen_timeout=(value)\n @password_minutes_of_inactivity_before_screen_timeout = value\n end", "def schedule_imminent_restart_warning_in_minutes\n return @schedule_imminent_restart_warning_in_minutes\n end", "def passcode_minutes_of_inactivity_before_screen_timeout=(value)\n @passcode_minutes_of_inactivity_before_screen_timeout = value\n end", "def auto_restart_notification_dismissal=(value)\n @auto_restart_notification_dismissal = value\n end", "def reminder_minutes_before_start\n return @reminder_minutes_before_start\n end", "def password_minutes_of_inactivity_before_lock=(value)\n @password_minutes_of_inactivity_before_lock = value\n end", "def passcode_minutes_of_inactivity_before_lock=(value)\n @passcode_minutes_of_inactivity_before_lock = value\n end", "def automatic_restart=(value)\n @automatic_restart = value\n end", "def minutes_of_inactivity_before_device_lock=(value)\n @minutes_of_inactivity_before_device_lock = value\n end", "def minimum_lifetime_in_minutes=(value)\n @minimum_lifetime_in_minutes = value\n end", "def restart_notification_snooze_duration_in_minutes\n return @restart_notification_snooze_duration_in_minutes\n end", "def automatic_restart_time\n data[:automatic_restart_time]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the gracePeriodInMinutes property value. The number of minutes to wait before restarting the device after an app installation.
def grace_period_in_minutes return @grace_period_in_minutes end
[ "def grace_period_in_minutes=(value)\n @grace_period_in_minutes = value\n end", "def grace_period\n @grace_period\n end", "def grace_period_hours\n return @grace_period_hours\n end", "def health_check_grace_period\n data[:health_check_grace_period]\n end", "def health_check_grace_period\n @group.health_check_grace_period\n end", "def deadline_grace_period_in_days\n return @deadline_grace_period_in_days\n end", "def grace_period_before_access_removal\n return @grace_period_before_access_removal\n end", "def grace_days_used\n @grace_days_used ||= grace_days_used!\n end", "def settings_sleep_timeout_in_minutes\n return @settings_sleep_timeout_in_minutes\n end", "def escalation_time_in_minutes\n return @escalation_time_in_minutes\n end", "def compliance_grace_period_expiration_date_time\n return @compliance_grace_period_expiration_date_time\n end", "def date_inside_grace_window(expires_on)\n (expires_on + Rails.configuration.registration_grace_window) - 1.day\n end", "def minimum_lifetime_in_minutes\n return @minimum_lifetime_in_minutes\n end", "def grace_period_hours=(value)\n @grace_period_hours = value\n end", "def lifetime_in_minutes\n return @lifetime_in_minutes\n end", "def default_lifetime_in_minutes\n return @default_lifetime_in_minutes\n end", "def restart_notification_snooze_duration_in_minutes\n return @restart_notification_snooze_duration_in_minutes\n end", "def minutes_of_inactivity_before_device_lock\n return @minutes_of_inactivity_before_device_lock\n end", "def grace_period_expires_date\n read_datetime_from_string('grace_period_expires_date')\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }