query
stringlengths 7
9.5k
| document
stringlengths 10
1.07M
| negatives
listlengths 19
19
| metadata
dict |
---|---|---|---|
A functional group of related transaction sets, within the scope of X12 standards, consists of a collection of similar transaction sets enclosed by a functional group header and a functional group trailer
|
def functional_group_loop
[functional_group_header, transactions, functional_group_trailer(@batch.id)].compact
end
|
[
"def functional_group_loop\n segments = []\n segments << functional_group_header\n segments << transactions\n segments << functional_group_trailer(nil)\n segments = segments.compact\n segments\n end",
"def ordered_groups\n output = Array.new\n set_group = proc{|title, fields|\n output.push({title: title, fields: fields})\n }\n return nil unless @control\n if @control[:um]\n set_group.call(\"Unique Mandatory\", @structured_data.dig(:unique, :mandatory))\n end\n if @control.dig(:rm, 0)\n set_group.call(\"Repeated Mandatory (Leg 1)\", @structured_data.dig(:repeated, 0, :mandatory))\n end\n if @control[:uc]\n set_group.call(\"Unique Conditional\", @structured_data.dig(:unique, :conditional))\n end\n if @control.dig(:rc, 0)\n set_group.call(\"Repeated Conditional (Leg 1)\", @structured_data.dig(:repeated, 0, :conditional))\n end\n if @control.dig(:ra, 0)\n set_group.call(\"Repeated Airline Use (Leg 1)\", @structured_data.dig(:repeated, 0, :airline))\n end\n if @control[:legs] && @control[:legs] > 1\n (1..@control[:legs]-1).each do |leg|\n if @control.dig(:rm, leg)\n set_group.call(\"Repeated Mandatory (Leg #{leg+1})\", @structured_data.dig(:repeated, leg, :mandatory))\n end\n if @control.dig(:rc, leg)\n set_group.call(\"Repeated Conditional (Leg #{leg+1})\", @structured_data.dig(:repeated, leg, :conditional))\n end\n if @control.dig(:ra, leg)\n set_group.call(\"Repeated Airline Use (Leg #{leg+1})\", @structured_data.dig(:repeated, leg, :airline))\n end\n end\n end\n if @control[:security]\n set_group.call(\"Security\", @structured_data.dig(:unique, :security))\n end\n if @control[:unknown]\n set_group.call(\"Unknown\", @structured_data[:unknown])\n end\n \n # Check that raw data presence and order in output matches raw input\n if output.map{|g| g[:fields].map{|k,v| v[:raw]}}.join == @raw_data\n return output\n else\n raw_output = Array.new\n raw_output.push({title: \"Raw Data\", fields: {0 => {description: \"Raw\", raw: @raw_data, interpretation: \"Something went wrong and we couldn’t parse this data.\"}}})\n return raw_output\n end\n end",
"def to_z88_sets(folder,refFolder)\n\t\tf = File.new(File.join(folder.path,\"z88sets.txt\"),\"w\")\n\t\tfActive = File.new(File.join(folder.path,\"z88setsactive.txt\"),\"w\")\n\t\t# get all types of elements\n\t\ttypes = getTypes\n\t\t#puts \"#{types}\\n\"\n\t\tcount = 1+types.count+@constraints.count\n\t\tf.write \"#{count}\\n\"\n\t\tfActive.write \"#{count}\\n\"\n\t\t#write element sets by diameters\n\t\ti=0\n\t\ttypes.each do |d,e|\n\t\t\ti=i+1\n\t\t\tdiam = sprintf(\"%#.6E\",d)\n\t\t\tfActive.write \"#ELEMENTS ELEMENTGEO 1 #{i} #{i} 1 0.000000E+000 0.000000E+000 0.000000E+000 0.000000E+000 #{diam} 0.000000E+000 0.000000E+000 0 0.000000E+000 0.000000E+000 0.000000E+000 0.000000E+000 \\\"ElementSet#{i}\\\"\\n\"\n\t\t\tf.write \"#ELEMENTS ELEMENTGEO #{i} #{e.count} \\\"ElementSet#{i}\\\"\\n\"\n\t\t\tj=0\n\t\t\te.each do |elem|\n\t\t\t\tf.write \"#{elem}\\t\"\n\t\t\t\tj=j+1\n\t\t\t\tf.write \"\\n\" if j%10 ==0\n\t\t\tend\n\t\t\tf.write \"\\n\" if j%10 !=0\n\t\tend\n\t\tf.write \"#ELEMENTS MATERIAL #{i+1} #{@elems.count} \\\"MatSet1\\\"\\n\"\n\t\t@elems.count.times do |k|\n\t\t\tf.write \"#{k+1}\\t\"\n\t\t\tf.write \"\\n\" if ((k+1)%10 ==0 ) && (k != @elems.count-1)\n\t\tend\n\t\tf.write \"\\n\"\n\t\tfActive.write \"#ELEMENTS MATERIAL 1 #{i+1} #{i+1} 52 \\\"Carbon Fiber\\\"\\n\"\n\t\t@constraints.count.times do |k|\n\t\t\ti=i+1\n\t\t\tf.write \"#NODES CONSTRAINT #{i+1} #{@constraints[k].nodes.count} \\\"#{@constraints[k].name}\\\"\\n\"\n\t\t\t@constraints[k].nodes.count.times do |j|\n\t\t\t\tf.write \"#{@constraints[k].nodes[j].tmpid}\\t\"\n\t\t\t\tf.write \"\\n\" if (j+1)%10 ==0\n\t\t\tend\n\t\t\tf.write \"\\n\"\n\t\t\tfActive.write \"#NODES CONSTRAINT 1 #{i+1} #{i+1} 11 #{@constraints[k].direction} #{@constraints[k].type} #{@constraints[k].value} \\\"#{@constraints[k].name}\\\"\\n\"\n\t\tend\n\t\t\n\t\tf.close\n\t\tfActive.close\n\t\t\n\tend",
"def grouping_sets_clause\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 103 )\n return_value = GroupingSetsClauseReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n grouping_sets_clause_start_index = @input.index\n\n root_0 = nil\n __LPAREN687__ = nil\n __RPAREN689__ = nil\n keyGROUPING685 = nil\n keySETS686 = nil\n grouping_expression_list688 = nil\n\n tree_for_LPAREN687 = nil\n tree_for_RPAREN689 = 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 650:4: keyGROUPING keySETS LPAREN grouping_expression_list RPAREN\n @state.following.push( TOKENS_FOLLOWING_keyGROUPING_IN_grouping_sets_clause_4061 )\n keyGROUPING685 = keyGROUPING\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, keyGROUPING685.tree )\n end\n @state.following.push( TOKENS_FOLLOWING_keySETS_IN_grouping_sets_clause_4063 )\n keySETS686 = keySETS\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, keySETS686.tree )\n end\n __LPAREN687__ = match( LPAREN, TOKENS_FOLLOWING_LPAREN_IN_grouping_sets_clause_4065 )\n if @state.backtracking == 0\n\n tree_for_LPAREN687 = @adaptor.create_with_payload( __LPAREN687__ )\n @adaptor.add_child( root_0, tree_for_LPAREN687 )\n\n end\n @state.following.push( TOKENS_FOLLOWING_grouping_expression_list_IN_grouping_sets_clause_4067 )\n grouping_expression_list688 = grouping_expression_list\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, grouping_expression_list688.tree )\n end\n __RPAREN689__ = match( RPAREN, TOKENS_FOLLOWING_RPAREN_IN_grouping_sets_clause_4069 )\n if @state.backtracking == 0\n\n tree_for_RPAREN689 = @adaptor.create_with_payload( __RPAREN689__ )\n @adaptor.add_child( root_0, tree_for_RPAREN689 )\n\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__, 103 )\n memoize( __method__, grouping_sets_clause_start_index, success ) if @state.backtracking > 0\n\n end\n \n return return_value\n end",
"def create_sub_structure(item_sets)\n item_set_array = []\n\n item_sets.each do |item_set|\n add_item_to_array(item_set_array, item_set)\n end\n\n item_set_array\n end",
"def grouping_sets_expr\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 105 )\n return_value = GroupingSetsExprReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n grouping_sets_expr_start_index = @input.index\n\n root_0 = nil\n rollup_cube_clause693 = nil\n grouping_expression_list694 = nil\n\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 # at line 656:2: ( rollup_cube_clause | grouping_expression_list )\n alt_176 = 2\n alt_176 = @dfa176.predict( @input )\n case alt_176\n when 1\n root_0 = @adaptor.create_flat_list\n\n\n # at line 656:4: rollup_cube_clause\n @state.following.push( TOKENS_FOLLOWING_rollup_cube_clause_IN_grouping_sets_expr_4098 )\n rollup_cube_clause693 = rollup_cube_clause\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, rollup_cube_clause693.tree )\n end\n\n when 2\n root_0 = @adaptor.create_flat_list\n\n\n # at line 656:25: grouping_expression_list\n @state.following.push( TOKENS_FOLLOWING_grouping_expression_list_IN_grouping_sets_expr_4102 )\n grouping_expression_list694 = grouping_expression_list\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, grouping_expression_list694.tree )\n end\n\n end# - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n if @state.backtracking == 0\n\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n @adaptor.set_token_boundaries( return_value.tree, return_value.start, return_value.stop )\n\n end\n 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__, 105 )\n memoize( __method__, grouping_sets_expr_start_index, success ) if @state.backtracking > 0\n\n end\n \n return return_value\n end",
"def grouping_sets\n raise Error, \"GROUP BY GROUPING SETS not supported on #{db.database_type}\" unless supports_grouping_sets?\n clone(:group_options=>:\"grouping sets\")\n end",
"def group_stack\n grp_stack = [ group_id ]\n sir_entries.each do |se|\n if se.rec_type == 0\n grp_stack.push( se.resp_group_id )\n elsif se.rec_type == 2\n grp_stack.pop\n end\n end\n grp_stack\n end",
"def changegroup_subset(bases, new_heads, source, extra_nodes=nil)\n unless extra_nodes\n if new_heads.sort! == heads.sort!\n common = []\n \n # parents of bases are known from both sides\n bases.each do |base|\n changelog.parents_for_node(base).each do |parent|\n common << parent unless null?(parent) #.null? # == NULL_ID\n end # end each\n end # end each\n \n # BAIL\n return get_changegroup(common, source)\n end # end if\n end # end unless\n \n run_hook :pre_outgoing, :throw => true, :source => source # call dem hooks\n \n \n # missing changelog list, bases, and heads\n #\n # Some bases may turn out to be superfluous, and some heads may be as\n # well. #nodes_between will return the minimal set of bases and heads\n # necessary to recreate the changegroup.\n # missing_cl_list, bases, heads = changelog.nodes_between(bases, heads)\n btw = changelog.nodes_between(bases, heads)\n missing_cl_list, bases, heads = btw[:between], btw[:roots], btw[:heads]\n changegroup_info missing_cl_list, source\n \n # Known heads are the list of heads about which it is assumed the recipient\n # of this changegroup will know.\n known_heads = []\n \n # We assume that all parents of bases are known heads.\n bases.each do |base|\n changelog.parents_for_node(base).each do |parent|\n known_heads << parent\n end # end each\n end # end each\n \n if known_heads.any? # unless known_heads.empty?\n # Now that we know what heads are known, we can compute which\n # changesets are known. The recipient must know about all\n # changesets required to reach the known heads from the null\n # changeset.\n has_cl_set = changelog.nodes_between(nil, known_heads)[:between]\n \n # cast to a hash for latter usage\n has_cl_set = Hash.with_keys has_cl_set\n else\n # If there were no known heads, the recipient cannot be assumed to\n # know about any changesets.\n has_cl_set = {}\n end\n \n # We don't know which manifests are missing yet\n missing_mf_set = {}\n # Nor do we know which filenodes are missing.\n missing_fn_set = {}\n \n ########\n # Here are procs for further usage\n \n # A changeset always belongs to itself, so the changenode lookup\n # function for a changenode is +identity+\n identity = proc {|x| x }\n \n # A function generating function. Sets up an enviroment for the\n # inner function.\n cmp_by_rev_function = proc do |rvlg|\n # Compare two nodes by their revision number in the environment's\n # revision history. Since the revision number both represents the\n # most efficient order to read the nodes in, and represents a\n # topological sorting of the nodes, this function if often useful.\n proc {|a, b| rvlg.rev(a) <=> rvlg.rev(b) }\n end\n \n # If we determine that a particular file or manifest node must be a\n # node that the recipient of the changegroup will already have, we can\n # also assume the recipient will have all the parents. This function\n # prunes them from the set of missing nodes.\n prune_parents = proc do |rvlg, hasses, missing|\n has_list = hasses.keys\n has_list.sort!(&cmp_by_rev_function(rvlg))\n \n has_list.each do |node|\n parent_list = revlog.parent_for_node(node).select {|p| not_null?(p) }\n end\n \n while parent_list.any?\n n = parent_list.pop\n unless hasses.include? n\n hasses[n] = 1\n p = revlog.parent_for_node(node).select {|p| not_null?(p) }\n parent_list += p\n end\n end\n \n hasses.each do |n|\n missing.slice!(n - 1, 1) # pop(n, None)\n end\n end\n \n # This is a function generating function used to set up an environment\n # for the inner funciont to execute in.\n manifest_and_file_collector = proc do |changed_fileset|\n # This is an information gathering function that gathers\n # information from each changeset node that goes out as part of\n # the changegroup. The information gathered is a list of which\n # manifest nodes are potentially required (the recipient may already\n # have them) and total list of all files which were changed in any\n # changeset in the changegroup.\n #\n # We also remember the first changenode we saw any manifest\n # referenced by so we can later determine which changenode owns\n # the manifest.\n \n # this is what we're returning\n proc do |cl_node|\n c = changelog.read cl_node\n c.files.each do |f|\n # This is to make sure we only have one instance of each\n # filename string for each filename\n changed_fileset[f] ||= f\n end # end each\n \n missing_mf_set[c[0]] ||= cl_node\n end # end proc\n end # end proc\n \n # Figure out which manifest nodes (of the ones we think might be part\n # of the changegroup) the recipients must know about and remove them\n # from the changegroup.\n prune_manifest = proc do\n has_mnfst_set = {}\n missing_mf_set.values.each do |node|\n # If a 'missing' manifest thinks it belongs to a changenode\n # the recipient is assumed to have, obviously the recipient\n # must have the manifest.\n link_node = changelog.node manifest[node].link_rev\n has_mnfst_set[n] = 1 if has_cl_set.include? link_node\n end # end each\n \n prune_parents[manifest, has_mnfst_set, missing_mf_set] # Proc#call\n end # end proc\n \n # Use the information collected in collect_manifests_and_files to say\n # which changenode any manifestnode belongs to.\n lookup_manifest_link = proc {|node| missing_mf_set[node] }\n \n # A function generating function that sets up the initial environment\n # the inner function.\n filenode_collector = proc do |changed_files|\n next_rev = []\n \n # This gathers information from each manifestnode included in the\n # changegroup about which filenodes the manifest node references\n # so we can include those in the changegroup too.\n #\n # It also remembers which changenode each filenode belongs to. It\n # does this by assuming the a filenode belongs to the changenode\n # the first manifest that references it belongs to.\n collect_missing_filenodes = proc do |node|\n r = manifest.rev node\n \n if r == next_rev[0]\n \n # If the last rev we looked at was the one just previous,\n # we only need to see a diff.\n delta_manifest = manifest.read_delta node\n \n # For each line in the delta\n delta_manifest.each do |f, fnode|\n f = changed_files[f]\n \n # And if the file is in the list of files we care\n # about.\n if f\n # Get the changenode this manifest belongs to\n cl_node = missing_mf_set[node]\n \n # Create the set of filenodes for the file if\n # there isn't one already.\n ndset = missing_fn_set[f] ||= {}\n \n # And set the filenode's changelog node to the\n # manifest's if it hasn't been set already.\n ndset[fnode] ||= cl_node\n end\n end\n else\n # Otherwise we need a full manifest.\n m = manifest.read node\n \n # For every file in we care about.\n changed_files.each do |f|\n fnode = m[f]\n \n # If it's in the manifest\n if fnode\n # See comments above.\n cl_node = msng_mnfst_set[mnfstnode]\n ndset = missing_fn_set[f] ||= {}\n ndset[fnode] ||= cl_node\n end\n end\n end\n \n # Remember the revision we hope to see next.\n next_rev[0] = r + 1\n end # end proc\n end # end proc\n \n # We have a list of filenodes we think need for a file, let's remove\n # all those we know the recipient must have.\n prune_filenodes = proc do |f, f_revlog|\n missing_set = missing_fn_set[f]\n hasset = {}\n \n # If a 'missing' filenode thinks it belongs to a changenode we\n # assume the recipient must have, the the recipient must have\n # that filenode.\n missing_set.each do |n|\n cl_node = changelog.node f_revlog[n].link_rev\n hasset[n] = true if has_cl_set.include? cl_node\n end\n \n prune_parents[f_revlog, hasset, missing_set] # Proc#call\n end # end proc\n \n # Function that returns a function.\n lookup_filenode_link_func = proc do |name|\n missing_set = missing_fn_set[name]\n \n # lookup the changenode the filenode belongs to\n lookup_filenode_link = proc do |node|\n missing_set[node]\n end # end proc\n end # end proc\n \n # add the nodes that were explicitly requested.\n add_extra_nodes = proc do |name, nodes|\n return unless extra_nodes && extra_nodes[name]\n \n extra_nodes[name].each do |node, link_node|\n nodes[node] = link_node unless nodes[node]\n end\n \n end\n \n # Now that we have all theses utility functions to help out and\n # logically divide up the task, generate the group.\n generate_group = proc do\n changed_files = {}\n group = changelog.group(missing_cl_list, identity, &manifest_and_file_collector[changed_files])\n group.each { |chunk| yield chunk }\n prune_manifests.call\n add_extra_nodes[1, msng_mnfst_set]\n msng_mnfst_lst = msng_mnfst_set.keys\n \n msng_mnfst_lst.sort!(&cmp_by_rev_function[manifest])\n \n group = manifest.group(msng_mnfst_lst, lookup_filenode_link,\n filenode_collector[changed_files])\n \n group.each {|chunk| yield chunk }\n \n msng_mnfst_lst = nil\n msng_mnfst_set.clear\n \n if extra_nodes\n extra_nodes.each do |fname|\n next if fname.kind_of?(Integer)\n msng_mnfst_set[fname] ||= {}\n changed_files[fname] = true\n end\n end\n \n changed_files.sort.each do |fname|\n file_revlog = file(fname)\n unless file_revlog.size > 0\n raise abort(\"empty or missing revlog for #{fname}\")\n end\n \n if msng_mnfst_set[fname]\n prune_filenodes[fname, file_revlog]\n add_extra_nodes[fname, missing_fn_set[fname]]\n missing_fn_list = missing_fn_set[fname].keys\n else\n missing_fn_list = []\n end\n \n if missing_fn_list.size > 0\n yield ChangeGroup.chunk_header(fname.size)\n yield fname\n missing_fn_list.sort!(&cmp_by_rev_function[file_revlog])\n group = file_revlog.group(missing_fn_list,\n lookup_filenode_link_func[fname])\n group.each {|chunk| yield chunk }\n end\n if missing_fn_set[fname]\n missing_fn_set.delete fname\n end\n end\n \n yield ChangeGroup.close_chunk\n \n if missing_cl_list\n run_hook :post_outgoing\n end\n end # end proc\n \n s = StringIO.new \"\", Support.binary_mode(\"w+\")\n generate_group.call do |chunk|\n s.write chunk\n end\n s.seek(0, IO::SEEK_SET)\n \n end",
"def apply_harvesting_set_membership(sets)\n\t\t#We delete previous set memberships and move to new set\n old_sets = harvesting_set_membership.dup\n old_sets.each { |s| self.remove_relationship(:is_member_of_collection, s) }\n sets.delete_if { |s| s == \"\"}.each { |s| self.add_relationship :is_member_of_collection, s }\n\tend",
"def make_is_groups( intake_headers_production )\n pallnos = Pallet.find(:all, :select => \"distinct pallets.id, (pallets.organization_code ||\n pallets.commodity_code || pallets.marketing_variety_code || pallets.old_pack_code ||\n pallets.grade_code || marks.brand_code || pallets.pick_reference_code || \n pallets.inventory_code || pallets.target_market_code ||\n pallet_bases.edi_out_pallet_base || \n CASE item_pack_products.size_ref\n WHEN 'NOS'::text THEN item_pack_products.actual_count::character varying\n ELSE item_pack_products.size_ref\n END) controlbreak\",\n :joins => 'join marks on marks.mark_code = pallets.carton_mark_code\n join pallet_format_products on pallet_format_products.id = pallets.pallet_format_product_id\n join pallet_bases on pallet_bases.pallet_base_code = pallet_format_products.pallet_base_code\n AND pallet_bases.id = pallet_format_products.pallet_base_id\n join fg_products on fg_products.fg_product_code = pallets.fg_product_code\n join item_pack_products on item_pack_products.item_pack_product_code = fg_products.item_pack_product_code\n AND item_pack_products.id = fg_products.item_pack_product_id',\n :conditions => ['pallets.consignment_note_number = ?',\n intake_headers_production.consignment_note_number]).map { |p| [p.controlbreak || \"NULL\", p.id] }.sort\n\n # Group sets of pallet nos\n groups = pallnos.group_by {|p| p[0]}\n # Yield each group back to the calling method\n groups.each { |group, content| yield content }\n end",
"def list12blocklevel(io)\n vars = io.read(36).unpack('l<*')\n\n result = {\n cbdxfHeader: vars[0], # cbdxfHeader (4 bytes): A signed integer that specifies the byte count for dxfHeader field. MUST be greater than or equal to zero.\n istnHeader: vars[1], # istnHeader (4 bytes): A signed integer that specifies a zero-based index to a Style record in the collection of Style records in the Globals Substream. The referenced Style specifies the cell style XF used for the table’s header row cells. If the value is -1, no style is specified for the table’s header row cells.\n cbdxfData: vars[2], # cbdxfData (4 bytes): A signed integer that specifies the byte count for dxfData field. MUST be greater than or equal to zero.\n istnData: vars[3], # istnData (4 bytes): A signed integer that specifies a zero-based index to a Style record in the collection of Style records in the Globals Substream. The referenced Style specifies the cell style used for the table’s data cells. If the value is -1, no style is specified for the table’s data cells.\n cbdxfAgg: vars[4], # cbdxfAgg (4 bytes): A signed integer that specifies the byte count for dxfAgg field. MUST be greater than or equal to zero.\n istnAgg: vars[5], # istnAgg (4 bytes): A signed integer that specifies a zero-based index to a Style record in the collection of Style records in the Globals Substream. The referenced Style specifies the cell style used for the table’s total row. If the value is -1, no style is specified for the table’s total row.\n cbdxfBorder: vars[6], # cbdxfBorder (4 bytes): A signed integer that specifies the byte count for dxfBorder field. MUST be greater than or equal to zero.\n cbdxfHeaderBorder: vars[7], # cbdxfHeaderBorder (4 bytes): A signed integer that specifies the byte count for dxfHeaderBorder field. MUST be greater than or equal to zero.\n cbdxfAggBorder: vars[8], # cbdxfAggBorder (4 bytes): A signed integer that specifies the byte count for dxfAggBorder field. MUST be greater than or equal to zero.\n }\n\n result[:dxfHeader] = dxfn12list(io.read(result[:cbdxfHeader])) unless result[:cbdxfHeader].zero? # dxfHeader (variable): An optional DXFN12List that specifies the formatting for the table’s header row cells. MUST exist if and only if cbdxfHeader is nonzero.\n result[:dxfData] = dxfn12list(io.read(result[:cbdxfData])) unless result[:cbdxfData].zero? # dxfData (variable): An optional DXFN12List that specifies the formatting for the table’s data cells. MUST exist if and only if cbdxfData is nonzero.\n result[:dxfAgg] = dxfn12list(io.read(result[:cbdxfAgg])) unless result[:cbdxfAgg].zero? # dxfAgg (variable): An optional DXFN12List that specifies the formatting for the table’s total row. MUST exist if and only if cbdxfAgg is nonzero.\n result[:dxfBorder] = dxfn12list(io.read(result[:cbdxfBorder])) unless result[:cbdxfBorder].zero? # dxfBorder (variable): An optional DXFN12 that specifies the formatting for the border of the table’s data cells. MUST exist if and only if cbdxfBorder is nonzero.\n result[:dxfHeaderBorder] = dxfn12list(io.read(result[:cbdxfHeaderBorder])) unless result[:cbdxfHeaderBorder].zero? # dxfHeaderBorder (variable): An optional DXFN12List that specifies the formatting for the border of the table’s header row cells. MUST exist if and only if cbdxfHeaderBorder is nonzero.\n result[:dxfAggBorder] = dxfn12list(io.read(result[:cbdxfAggBorder])) unless result[:cbdxfAggBorder].zero? # dxfAggBorder (variable): An optional DXFN12List that specifies the formatting for the border of the table’s total row. MUST exist if and only if cbdxfAggBorder is nonzero.\n\n result[:stHeader] = xlunicodestring(io) unless result[:istnHeader] == -1 # stHeader (variable): An optional XLUnicodeString that specifies the name of the style for the table’s header row cells. MUST exist if and only if istnHeader is not equal to -1. MUST be equal to the name of the Style record specified by istnHeader. If the style is a user-defined style, stHeader MUST be equal to the user field of the Style record.\n result[:stData] = xlunicodestring(io) unless result[:istnData] == -1 # stData (variable): An optional XLUnicodeString that specifies the name of the style for the table’s data cells. MUST exist if and only if istnData is not equal to -1. MUST be equal to the name of the Style record specified by istnData. If the style is a user-defined style, stData MUST be equal to the user field of the Style record.\n result[:stAgg] = xlunicodestring(io) unless result[:istnAgg] == -1 # stAgg (variable): An optional XLUnicodeString that specifies the name of the style for the table’s total row. MUST exist if and only if istnAgg is not equal to -1. MUST be equal to the name of the Style record specified by istnAgg. If the style is a user-defined style, stAgg MUST be equal to the user field of the Style record.\n\n result\n end",
"def maesb_generate_equipment_sets\n # Generate Equipment Sets\n ($data_weapons + $data_armors).compact.each { |equip| equip.maesb_generate_equip_set }\n # Update items to refer to the set to which they belong\n set_items = $data_armors.compact.select {|armor| !armor.maesb_sets.empty? }\n set_items.each { |set_item| \n set_item.maesb_sets.collect {|set| set.items }.flatten.uniq.each { |equip|\n equip.maesb_belongs_to_sets.push(set_item.id) \n }\n }\n end",
"def ordered_example_groups; end",
"def union_memberships; end",
"def filegroup_sections\n file_group_data = @file_groups.map do |file_group|\n filegroup_section(file_group)\n end\n %Q(<mets:fileSec ID=\"fileSec1\">#{file_group_data.join(\"\")}</mets:fileSec>)\n end",
"def get_cdr3_multiset(pred_f)\n pred_ms = Multiset.new\n IO.readlines(pred_f).each do |l|\n pred_lab = LabelPrediction.new(l, @delim)\n pred_ms.add(pred_lab.get_cdr3)\n end\n pred_ms\n end",
"def item_sets; end",
"def add_material_layer\n layers = %w(260 300 592)\n layers.each do |l|\n material = node.xpath(\"//marc:datafield[@tag='#{l}']\", NAMESPACE)\n material.each do |block|\n next unless block.xpath(\"marc:subfield[@code='8']\", NAMESPACE).empty?\n sf8 = Nokogiri::XML::Node.new \"subfield\", node\n sf8['code'] = '8'\n sf8.content = \"01\"\n block << sf8\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Generating check level segments
|
def generate_check
Output835.log.info "\n\nCheck number : #{@check.check_number} undergoing processing"
transaction_segments =[ transaction_set_header, financial_info, reassociation_trace]
transaction_segments << ref_ev_loop if @facility_output_config.details[:ref_ev_batchid]
transaction_segments += [reciever_id, date_time_reference, payer_identification_loop,
payee_identification_loop, reference_identification]
transaction_segments << claim_loop if !@check.interest_only_check
transaction_segments << provider_adjustment
transaction_segments = transaction_segments.flatten.compact
@se01[0] = transaction_segments.length + 1 if @se01
transaction_segments << transaction_set_trailer(transaction_segments.length + 1)
transaction_segments
end
|
[
"def create_segments\n Segment.split_to_segments(build_waypoints)\n end",
"def health_remark_code_segments\n @eob = service.insurance_payment_eob\n facility = @eob.check_information.job.batch.facility\n health_remark_code_segments = []\n health_remark_code_segments << compute_lq(\"in\")\n health_remark_code_segments << compute_lq(\"out\") \n if facility.details[:interest_in_service_line] && service.interest_service_line?\n health_remark_code_segments << lq_rx_segments(\"109975\") if @eob.claim_interest.to_f > 0.0 \n end \n health_remark_code_segments << lq_rx_segments(\"109702\") if @eob.hcra.to_f > 0.0\n health_remark_code_segments.compact!\n health_remark_code_segments.flatten\n end",
"def covered_branches; end",
"def test_seg_topo\n assert(LCD.make_digit([1, 0, 0, 0, 0, 0, 0]).start_with?(\" -- \\n\"))\n end",
"def handle_hierarchy(file, b)\n points = {}\n points[$clusters[0]] = 0\n points[$clusters[1]] = 0\n\n charts = \"\"\n 5.times do |x|\n img = \"#{b}-level-#{x}\" \n charts += \"\\\\includegraphics[width=8cm]{#{img}}\\n\" if File.exist?(\"#{img}.png\")\n dat_file = File.readlines(\"#{img}.dat\")\n inner_points = {}\n inner_points[$clusters[0]] = 0\n inner_points[$clusters[1]] = 0\n clusters_values = dat_file[0].split(\" \")\n dat_file.size.times do |j|\n unless dat_file[j].nil?\n values = dat_file[j].split(\" \")\n # puts values\n if values[1].to_f > values[2].to_f\n inner_points[clusters_values[1]] += 1 \n elsif values[1].to_f < values[2].to_f\n inner_points[clusters_values[2]] += 1 \n end\n end\n end\n value1 = clusters_values[1].nil? ? 0 : inner_points[clusters_values[1]]\n value2 = clusters_values[2].nil? ? 0 : inner_points[clusters_values[2]]\n #puts \"#{value1} v1 #{value2} v2\"\n if value1 > value2 \n points[clusters_values[1]] += 1 \n elsif value1 < value2 \n points[clusters_values[2]] += 1 \n end\n #puts \"#{hfcm_level} hfcm_level x #{hpcm_level} hpcm_level\"\n end\n write_table(file, points[$clusters[0]], points[$clusters[1]])\n file.write charts\nend",
"def generate_output(group, checks,check_hash=nil)\n nextgen = group.split('_').include?('notapplicable')\n if nextgen\n apply_format('delimited', checks,check_hash)\n else\n apply_format(insurance_eob_output_config.format.downcase, checks,check_hash)\n end\n end",
"def health_remark_code_segments\n health_remark_code_segments = [compute_lq(\"in\"), compute_lq(\"out\")]\n if @facility.details[:interest_in_service_line] && @service.interest_service_line?\n health_remark_code_segments << lq_rx_segments(\"109975\") if @eob.claim_interest.to_f > 0.0\n end\n health_remark_code_segments << lq_rx_segments(\"109702\") if @eob.hcra.to_f > 0.0\n health_remark_code_segments.compact.flatten\n end",
"def visit_rule_level(nodes); end",
"def levels\n # divide total points available in to X tiers\n # set up a hash\n # Beginner - 1\n # Good start - 2\n # Moving Up - 3\n # good - 4\n # Solid - 5\n # Nice - 6\n # Great - 7\n # Amazing - 8\n # Genius - 9\n # Queen Bee - 10\n end",
"def draw_snpinfo(current_track, snp_list, x_start, y_start)\n\n box_y_start = 0 #@box_size * Math.sqrt(2) *0.25 #@box_size/6\n\n x_text = @box_size * 1.15\n\n color_array = ['black','red', 'blue','gray','orange','green','purple','brown','skyblue','fuchsia','lime']\n\n track_name = snp_list.snpinfo_tracks[current_track].name\n\n snp_list.included_snps.each do |snp_index|\n snp = snp_list.snps[snp_index]\n val = snp.snpinfo_values[track_name]\n\tif val == 1\n @canvas.g.translate(x_start,y_start) do |check|\n\t check.styles(:fill=>color_array[current_track], :stroke=>'white', :stroke_width=>1)\n\t check.rect(@box_size * Math.sqrt(2) *0.25, @box_size * Math.sqrt(2) *0.25, x_text, box_y_start)\n end\n\tend\n\n end_x = x_text\n #x_text += @box_size + @box_size/2 - @box_size/10\n x_text = label_step(x_text)\n\n\n end\n\n @canvas.g.translate(x_start, y_start) do |checks|\n #checks.line(box_x_start, box_y_start , x_text, box_y_start)\n #checks.line(box_x_start, box_y_start + @box_size * Math.sqrt(2) *0.25 , x_text, box_y_start + @box_size * Math.sqrt(2) *0.25)\n end\n\n font_size = standard_font_size\n\n @canvas.g.translate(x_start,y_start).text(@box_size, font_size * 0.8) do |text|\n text.tspan(track_name).styles(:font_size=>font_size, :text_anchor=>'end')\n end\n\n end",
"def initialize level = 1, seq = nil\n super()\n @path = [:fw]\n seq = [:fw, :left, :fw, :right, :fw, :right, :fw, :left, :fw]\n level.times do\n @path.map! { |el| el == :fw ? seq.dup : el }.flatten!\n end\n end",
"def segments\n re = Array.new\n\n last_max = -1\n\n segs = index_segments\n segs.each_with_index do |range, i|\n sprints = range.to_a.map { |i| all_sprints[i] }\n span = range.max - range.min + 1\n w = range.min-last_max-1\n\n line_length = segment_width * w + inner_pad\n\n marker_length = segment_width * span - inner_pad\n\n re << [ :line, [line_length, sprints] ]\n re << [ :marker, [marker_length, sprints] ]\n\n last_max = range.max\n end\n\n # Last line\n butal = all_sprints.length - sprints.last.index - 1\n re << [ :line, segment_width * butal + inner_pad ]\n\n re\n end",
"def initialize(options)\n super(options[:path])\n @levels = options[:levels] || 2\n if @levels > 16 / SPLIT_PER_LEVEL\n raise ArgumentError, \"Maximum number of levels is #{16 / SPLIT_PER_LEVEL}\"\n end\n @padding = @levels * SPLIT_PER_LEVEL\n @splits = (0..(@levels - 1)).to_a.map { |n|\n [n * SPLIT_PER_LEVEL, SPLIT_PER_LEVEL] }\n end",
"def generate_linenumbers\n (0...@hilbert_basis.basis.to_a.size).to_a.combination(VERTICES).to_a\n end",
"def claim_loop\n segments = []\n lx_selection = @facility_config.details[:lx_segment][\"1\"] rescue \"1\"\n if lx_selection == \"[By Bill Type]\"\n eob_group = @eobs.group_by{|eob| eob.bill_type}\n eob_group.each_with_index do |group, index|\n segments << write_claim_payment_information({:eobs => group[1], :count_condition => 'single', :justification => 1, :index => index +1})\n end\n elsif lx_selection == '[3-Sequential Number]'\n segments = write_claim_payment_information({:eobs => @eobs, :count_condition => 'multiple', :justification => 3})\n else\n segments = write_claim_payment_information({:eobs => @eobs, :count_condition => 'single', :justification => 1, :value => lx_selection })\n end\n segments = segments.flatten.compact\n segments unless segments.blank?\n end",
"def segment lines\n groups = []\n lines.each do |line|\n groups << [] if line.depth == 0\n groups.last << line\n end\n groups\n end",
"def build_levels(build)\n\t\tlevels = \"#{build.name}\\n\" + build.lvls.reduce(\"\") {|str,(k,v)| str + \"#{k.to_s}: #{v}\\n\"} \n\tend",
"def check_time_segment_set_coverage_full_day(start_time, num_checked)\n # use Set class to perform intelligent merge/intersection calculations on range 0..1439\n all_day = (0..1439).to_a\n\n # check only non-destroyed time segments\n non_destroyed_time_segments = time_segments.select {|ts| not ts.marked_for_destruction?}.compact\n\n coverage = []\n non_destroyed_time_segments.each do |ts|\n this_time = (ts.start_min .. ts.end_min).to_a\n # Array#uniq! return array of unique elements or nil if no changes (all unique)\n if (coverage + this_time).uniq!\n create_time_segment_error(\"Time Segment Set invalid because there are overlapping time segments starting at #{ts.pretty_start} in profile #{self.name}\")\n end\n # Array#| Set Union on two arrays\n coverage |= this_time\n end\n\n unless (all_day - coverage).empty?\n uncovered_ranges = all_day - coverage\n uncovered_ranges.extend ArrayGroups\n\n uncovered_ranges.groups.each do |u|\n def pretty(i); TimeSegment.minutes_to_pretty(i); end\n create_time_segment_error(\"Time Segment Set invalid because there is a gap at #{pretty(u[0])} for profile #{self.name}\")\n\n end\n end\n\n end",
"def create_control_points(data)\n len_um = len_group(:um)\n len_rm = len_group(:rm)\n len_um_rm = len_group(:um,:rm)\n \n control = Hash.new\n # Set the invalid field and return control points:\n invalid = proc{|location|\n control.store(:unknown, location)\n return control\n }\n # Get a hex field size and return a decimal if valid, or call invalid if not:\n get_field_size = proc{|location, length|\n hex = data[location,length]\n invalid.call(location+length) if hex !~ /^[0-9A-F]+$/i\n hex.to_i(16)\n }\n # Set conditional and airline control points:\n get_conditional_and_airline = proc{|start_cond, len_cond_airline|\n control[:rc].push({start: start_cond, length: len_field(17)}) # Store in case next line fails\n rc_field_size = get_field_size.call(start_cond,len_field(17))\n len_cond = rc_field_size + len_field(17)\n len_airline = len_cond_airline - len_cond\n invalid.call(start_cond+len_field(17)) if len_airline < 0\n control[:rc].last[:length] = len_cond\n control[:ra].push(len_airline == 0 ? nil : {start: start_cond + len_cond, length: len_airline})\n }\n \n if data.length < len_um_rm\n # Mandatory data is too short\n invalid.call(0)\n end\n \n # NUMBER OF LEGS:\n legs = data[@fields.dig(5,:start),@fields.dig(5,:length)]\n if legs !~ /^[1-9]+$/\n invalid.call(0)\n end\n control.store(:legs, legs.to_i)\n \n # Set up arrays:\n control.store(:rm, Array.new) # Repeated Mandatory start and length data\n control.store(:rc, Array.new) # Repeated Conditional start and length data\n control.store(:ra, Array.new) # Repeated Airline use start and length data\n \n # UNIQUE MANDATORY FIELDS:\n control.store(:um, {start: 0, length: len_um})\n \n # REPEATED MANDATORY FIELDS (Leg 0):\n control[:rm].push({start: len_um, length: len_rm})\n \n # UNIQUE CONDITIONAL FIELDS:\n len_uc_rc0_ra0 = get_field_size.call(len_um_rm-len_field(6), len_field(6))\n \n if len_uc_rc0_ra0 == 0 # No unique or repeated[0] conditional fields\n control.store(:uc, nil)\n control[:rc].push(nil)\n control[:ra].push(nil)\n else\n # Check if version \">\" is in the correct position\n invalid.call(len_um_rm) if data.index(\">\") != len_um_rm\n \n invalid.call(len_um_rm) if len_uc_rc0_ra0 < len_field(8,9,10) # Check that field 10 is available\n control.store(:uc, {start: len_um_rm, length: len_field(8,9,10)}) # Store in case next line fails\n len_uc = get_field_size.call(len_um_rm+len_field(8,9), len_field(10)) + len_field(8,9,10)\n control[:uc][:length] = len_uc\n # Check if RC0 exists:\n if len_uc_rc0_ra0 >= control.dig(:uc,:length) + len_field(17) \n start_rc0 = len_um_rm + control.dig(:uc,:length)\n get_conditional_and_airline.call(start_rc0, len_uc_rc0_ra0-control.dig(:uc,:length), control.dig(:uc,:length))\n else\n # RC0 does not exist\n control[:rc].push(nil)\n control[:ra].push(nil)\n end\n \n end\n \n # Build rc[1..n] array:\n start_leg = len_um_rm + len_uc_rc0_ra0\n if control[:legs] > 1\n (1..(control[:legs]-1)).each do |leg|\n # Check that RMx is long enough\n invalid.call(start_leg) if data.length < start_leg + len_rm\n \n # Store start and length of mandatory fields in rm array\n control[:rm].push({start: start_leg, length: len_rm})\n \n # Get size of conditional fields\n len_rc_ra = get_field_size.call(start_leg+len_rm-2, len_field(6)) # Length of repeated conditional plus airline use\n if len_rc_ra == 0\n # No conditional or airline fields for this leg\n control[:rc].push(nil)\n control[:ra].push(nil)\n else\n invalid.call(start_leg+len_rm-len_field(6)) if len_rc_ra < len_field(17)\n get_conditional_and_airline.call(start_leg+len_rm,len_rc_ra)\n end\n \n # Set next leg start\n start_leg += (len_rm + len_rc_ra)\n end\n \n end\n \n start_remainder = start_leg\n len_remainder = data.length - start_leg\n return control unless len_remainder > 0\n \n if @fields[29].nil?\n # Boarding pass version does not have a security length field, so\n # consider everything at the end of the pass to be security data.\n control.store(:security, {start: start_remainder, length: len_remainder})\n else\n # Boarding pass version does have specific security fields, so perform\n # security field validity checks.\n \n # Check if security \"^\" starts at correct spot\n invalid.call(start_remainder) if (data.index(\"^\") != start_remainder && data.index(\">\",len_um_rm+1) != start_remainder)\n \n control.store(:security, {start: start_remainder, length: len_field(25,28,29)}) # Store in case next line fails\n len_security_data = get_field_size.call(start_remainder+len_field(25,28),len_field(29))\n len_security_total = len_field(25,28,29)+len_security_data\n \n # Check if enough security data exists\n invalid.call(start_remainder + len_field(25,28,29)) if len_security_total > len_remainder\n \n # Update security values\n control[:security] = {start: start_remainder, length: len_security_total}\n \n # Check if extra data exists after security\n invalid.call(start_remainder+len_security_total) if len_security_total < len_remainder\n end\n \n return control\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
The TRN segment is used to uniquely identify a claim payment and advice.
|
def reassociation_trace
simple_client_array_for_1000000009 = ["NAVICURE", "ASCEND CLINICAL LLC"]
trn_elements = ['TRN', '1', ref_number]
if simple_client_array_for_1000000009.include? (@client_name)
trn_elements << '1000000009'
elsif @check_amount.to_f > 0 && @check.payment_method == "EFT"
trn_elements << '1' + @facility.facility_tin if @facility.facility_tin.present?
else
trn_elements << '1999999999'
end
trn_elements.trim_segment.join(@element_seperator)
end
|
[
"def trn\n get :trn\n end",
"def reassociation_trace\n trn_elements = ['TRN', '1', ref_number]\n if @check_amount.to_f > 0 && @check.payment_method == \"EFT\"\n trn_elements << '1' + @facility.facility_tin if @facility.facility_tin.present?\n else\n trn_elements << '1999999999'\n end\n trn_elements.join(@element_seperator)\n end",
"def print_ref_tj_segment\n ref_tj_element_methods = @segments_list[:REF_TJ]\n ref_tj_elements = verify_ref_tj_condition{\n [\n send(ref_tj_element_methods[:REF_TJ00][0].to_sym, ref_tj_element_methods[:REF_TJ00][1]), #['segment_name', 'REF']\n send(ref_tj_element_methods[:REF_TJ01][0].to_sym, ref_tj_element_methods[:REF_TJ01][1]), #['print_constant', 'TJ']\n send(ref_tj_element_methods[:REF_TJ02][0].to_sym, ref_tj_element_methods[:REF_TJ02][1]) #tax_payer_identification_number\n ]\n }\n ref_tj_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def polish_taxpayer_identification_number; end",
"def tax_id_number\n self.dig_for_string(\"taxIdNumber\")\n end",
"def trident_version\n ua.match(TRIDENT_VERSION_REGEX) && $1\n end",
"def tax_roll_number\n self.dig_for_string(\"taxRollNumber\")\n end",
"def snr\n part.nr\n end",
"def print_n4_pr_segment\n n4_pr_element_methods = @segments_list[:N4_PR]\n n4_pr_elements = [\n send(n4_pr_element_methods[:N4_PR00][0].to_sym, n4_pr_element_methods[:N4_PR00][1]), #['segment_name', 'N4']\n send(n4_pr_element_methods[:N4_PR01][0].to_sym, n4_pr_element_methods[:N4_PR01][1]), #payer_city\n send(n4_pr_element_methods[:N4_PR02][0].to_sym, n4_pr_element_methods[:N4_PR02][1]), #payer_state\n send(n4_pr_element_methods[:N4_PR03][0].to_sym, n4_pr_element_methods[:N4_PR03][1]) #payer_zip_code\n ]\n n4_pr_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def other_claim_related_id\n elem = []\n if !eob.insurance_policy_number.blank?\n elem << 'REF'\n elem << 'IG'\n elem << eob.insurance_policy_number\n elem = Output835.trim_segment(elem)\n elem.join(@element_seperator)\n end\n end",
"def transaction_id\n @ipn['txn_id']\n end",
"def other_claim_related_id\n if @eob.insurance_policy_number.present?\n elem = ['REF','IG', @eob.insurance_policy_number].trim_segment.join(@element_seperator)\n end\n end",
"def set_TranscriptionSID(value)\n set_input(\"TranscriptionSID\", value)\n end",
"def tr\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 20 )\n __TR15__ = nil\n __TR16__ = nil\n\n begin\n # at line 116:4: ( ^( TAG TR ( tr_data )+ ) | ^( TAG TR ) )\n alt_24 = 2\n look_24_0 = @input.peek( 1 )\n\n if ( look_24_0 == TAG )\n look_24_1 = @input.peek( 2 )\n\n if ( look_24_1 == DOWN )\n look_24_2 = @input.peek( 3 )\n\n if ( look_24_2 == TR )\n look_24_3 = @input.peek( 4 )\n\n if ( look_24_3 == TAG )\n alt_24 = 1\n elsif ( look_24_3 == UP )\n alt_24 = 2\n else\n raise NoViableAlternative( \"\", 24, 3 )\n end\n else\n raise NoViableAlternative( \"\", 24, 2 )\n end\n else\n raise NoViableAlternative( \"\", 24, 1 )\n end\n else\n raise NoViableAlternative( \"\", 24, 0 )\n end\n case alt_24\n when 1\n # at line 116:6: ^( TAG TR ( tr_data )+ )\n match( TAG, TOKENS_FOLLOWING_TAG_IN_tr_776 )\n\n match( DOWN, nil )\n __TR15__ = match( TR, TOKENS_FOLLOWING_TR_IN_tr_778 )\n # --> action\n printStartTag(__TR15__);\n # <-- action\n # --> action\n putsEndingBracket;\n # <-- action\n # at file 116:58: ( tr_data )+\n match_count_23 = 0\n while true\n alt_23 = 2\n look_23_0 = @input.peek( 1 )\n\n if ( look_23_0 == TAG )\n alt_23 = 1\n\n end\n case alt_23\n when 1\n # at line 116:58: tr_data\n @state.following.push( TOKENS_FOLLOWING_tr_data_IN_tr_784 )\n tr_data\n @state.following.pop\n\n else\n match_count_23 > 0 and break\n eee = EarlyExit(23)\n\n\n raise eee\n end\n match_count_23 += 1\n end\n\n\n match( UP, nil )\n # --> action\n printEndTag(__TR15__);\n # <-- action\n\n when 2\n # at line 117:6: ^( TAG TR )\n match( TAG, TOKENS_FOLLOWING_TAG_IN_tr_795 )\n\n match( DOWN, nil )\n __TR16__ = match( TR, TOKENS_FOLLOWING_TR_IN_tr_797 )\n # --> action\n printStartTag(__TR16__);\n # <-- action\n # --> action\n printEndingBracket;\n # <-- action\n\n match( UP, nil )\n # --> action\n putsEndTag(__TR16__);\n # <-- action\n\n end\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__, 20 )\n\n end\n \n return \n end",
"def sns_topic_arn\n data.sns_topic_arn\n end",
"def reassociation_trace\n trn_elements = []\n trn_elements << 'TRN'\n trn_elements << '1'\n check_num = \"#{check.check_number.to_i}\"\n job = check.job\n if payer\n if job.payer_group == \"PatPay\"\n # checking whether the check_number is duplicated\n # in the whole check number array\n if Output835.element_duplicates?(check_num, @check_nums)\n # get all indexes at which duplicate elements are present\n # then check at what position the current element resides\n # that gives the duplication index as one moves from first to last elem of the array\n # For Ex : array = [a, b, c, c, d, e, f, e, g]\n # all_indices for 'c' would return [2, 3]\n # comparing the current element's index with that, we would get either '0' or '1' depending on\n # whether we're dealing with 'c' in 2nd place or at 3rd place, couting starts from 0th place\n # all_indices for 'e' would return [5, 7]\n counter = Output835.all_indices(check_num, @check_nums).index(index)\n # since counter starts from zero, adding 1 to get the correct count\n end\n check_num << \"#{check.batch.date.strftime(\"%m%d%y\")}\" unless check_num.blank?\n check_num << \"#{counter+1}\" if counter\n end\n end\n trn_elements << (check_num.blank? ? \"0\" : check_num)\n if @check_amount.to_f > 0 && check.payment_method == \"EFT\"\n unless facility.facility_tin.blank?\n trn_elements << '1' + facility.facility_tin\n end\n else\n trn_elements << '1999999999'\n end\n trn_elements = Output835.trim_segment(trn_elements)\n trn_elements.join(@element_seperator)\n end",
"def print_nm1_tt_segment\n nm1_tt_element_methods = @segments_list[:NM1_TT]\n nm1_tt_elements = [\n send(nm1_tt_element_methods[:NM1_TT00][0].to_sym, nm1_tt_element_methods[:NM1_TT00][1]), #crossover_carrier_name\n send(nm1_tt_element_methods[:NM1_TT01][0].to_sym, nm1_tt_element_methods[:NM1_TT01][1]), #carrier_name_entity_identifier_code\n send(nm1_tt_element_methods[:NM1_TT02][0].to_sym, nm1_tt_element_methods[:NM1_TT02][1]), #coordination_of_benefits_carrier_name\n send(nm1_tt_element_methods[:NM1_TT03][0].to_sym, nm1_tt_element_methods[:NM1_TT03][1]), #carrier_last_or_organization_name\n send(nm1_tt_element_methods[:NM1_TT04][0].to_sym, nm1_tt_element_methods[:NM1_TT04][1]), #carrier_first_name\n send(nm1_tt_element_methods[:NM1_TT05][0].to_sym, nm1_tt_element_methods[:NM1_TT05][1]), #carrier_middle_name\n send(nm1_tt_element_methods[:NM1_TT06][0].to_sym, nm1_tt_element_methods[:NM1_TT06][1]), #carrier_name_prefix\n send(nm1_tt_element_methods[:NM1_TT07][0].to_sym, nm1_tt_element_methods[:NM1_TT07][1]), #carrier_name_suffix\n send(nm1_tt_element_methods[:NM1_TT08][0].to_sym, nm1_tt_element_methods[:NM1_TT08][1]), #carrier_identification_code_qualifier\n send(nm1_tt_element_methods[:NM1_TT09][0].to_sym, nm1_tt_element_methods[:NM1_TT09][1]) #coordination_of_benefits_carrier_identifier\n ]\n nm1_tt_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def txn_num\n @spec[:txn_num]\n end",
"def tax_identification_number\n element_with_value('TaxIdentificationNumber', opts[:sender_vat_number] || '')\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
The N1 loop allows for name/address information for the payee which would be utilized to address remittance(s) for delivery.
|
def payee_identification_loop(repeat = 1)
payee = get_facility
if payee
if ( payee.name.blank? || payee.address_one.blank? || payee.city.blank? || payee.state.blank? || payee.zip_code.blank?)
@claim = payee.clone
payee = @facility #if any of the billing provider address details is missing get facility address
end
payee_segments = []
address_payee = @facility.details[:default_payee_details] ? @facility : payee
repeat.times do
payee_segments << payee_identification(payee)
payee_segments << address(address_payee)
payee_segments << geographic_location(address_payee)
payee_segments << payee_additional_identification(payee)
end
payee_segments.compact
end
end
|
[
"def payee_identification_loop(repeat = 1)\n payee = get_facility\n if payee\n if ( payee.name.blank? || payee.address_one.blank? || payee.city.blank? || payee.state.blank? || payee.zip_code.blank?)\n @claim = payee.clone\n payee = @facility #if any of the billing provider address details is missing get facility address\n end\n payee_segments = []\n address_payee = @facility.details[:default_payee_details] ? @facility : payee\n repeat.times do\n payee_segments << payee_identification(payee)\n payee_segments << address(address_payee)\n payee_segments << geographic_location(address_payee)\n end\n payee_segments.compact\n end\n end",
"def payee_identification_loop(repeat = 1)\n payee = get_facility\n if payee\n if ( payee.name.blank? || payee.address_one.blank? || payee.city.blank? || payee.state.blank? || payee.zip_code.blank?)\n @claim = payee.clone\n payee = @facility #if any of the billing provider address details is missing get facility address\n end\n payee_segments = []\n repeat.times do\n payee_segments << image_name_bac\n payee_segments << payee_identification(payee)\n payee_segments << address(payee)\n payee_segments << geographic_location(payee)\n payee_segments << payee_additional_identification(payee)\n payee_segments << payee_additional_identification_1_bac\n payee_segments << payee_additional_identification_2_bac\n payee_segments << name_bac\n end\n payee_segments = payee_segments.compact\n payee_segments unless payee_segments.blank?\n end \n end",
"def payer_identification_loop(repeat = 1)\n payer = get_payer\n output_version = @facility_config.details[:output_version]\n Output835.log.info \"\\n payer is #{payer.name}\"\n if payer\n payer_segments = []\n repeat.times do\n payer_segments << payer_identification(payer)\n payer_segments << address(payer)\n payer_segments << geographic_location(payer)\n payer_segments << unique_output_payid(payer) if @client.name.upcase == \"QUADAX\" and ((!(output_payid(payer).blank?))|| @eob_type == 'Patient')\n payer_segments << payer_additional_identification_bac(payer)\n payer_segments << reference_identification_bac\n payer_segments << submitter_identification_bac\n payer_segments << payer_technical_contact(payer) if ($IS_PARTNER_BAC || (output_version && output_version != '4010'))\n end\n payer_segments = payer_segments.compact\n payer_segments unless payer_segments.blank?\n end \n rescue NoMethodError\n raise \"Payer is missing for check : #{check.check_number} id : #{check.id}\"\n end",
"def create_emails\n return unless @name_changed\n\n @name_changed = false\n\n # Send email to people interested in this name.\n @initial_name_id = name_id\n taxa = name.approved_name.all_parents\n taxa.push(name)\n taxa.push(Name.find_by(text_name: \"Lichen\")) if name.is_lichen?\n done_user = {}\n taxa.each do |taxon|\n NameTracker.where(name: taxon).includes(:user).find_each do |n|\n next unless (n.user_id != user.id) && !done_user[n.user_id] &&\n (!n.require_specimen || observation.specimen)\n next if n.user.no_emails\n\n QueuedEmail::NameTracking.create_email(n, self)\n done_user[n.user_id] = true\n end\n end\n\n # Send email to people interested in this observation.\n return unless (obs = observation)\n\n owner = obs.user\n sender = user\n recipients = []\n\n # Send notification to owner if they want.\n recipients.push(owner) if owner&.email_observations_naming\n\n # Send to people who have registered interest in this observation.\n # Also remove everyone who has explicitly said they are NOT interested.\n obs.interests.each do |interest|\n if interest.state\n recipients.push(interest.user)\n else\n recipients.delete(interest.user)\n end\n end\n\n # Also send to people who registered positive interest in this name.\n # (Don't want *disinterest* in name overriding\n # interest in the observation, say.)\n taxa.each do |taxon|\n taxon.interests.each do |interest|\n recipients.push(interest.user) if interest.state\n end\n end\n\n # Remove users who have opted out of all emails.\n recipients.reject!(&:no_emails)\n\n # Send to everyone (except the person who created the naming!)\n (recipients.uniq - [sender]).each do |recipient|\n QueuedEmail::NameProposal.create_email(sender, recipient, obs, self)\n end\n end",
"def taxpayer_address\n options = { sub_object_attribute: :taxpayers, loop: :taxpayer_details }\n options[:address_not_required] = :same_address if params[:sub_object_index].to_i != 1\n\n wizard_address_step(NEW_STEPS, options)\n end",
"def each_address(name)\n name = Resolv::DNS::Name.create(name)\n\n return unless name.to_a.last == 'local'\n\n super(name)\n end",
"def auto_complete_for_payer_pay_address_one\n @payers = get_matching_payers(params[:payer_name], params[:payer_address_one])\n end",
"def get_unique_address(account_label)\n loop do\n random_address = rpc_client.getnewaddress(account_label)\n break random_address unless User.exists?(deposit_address: random_address)\n end\n end",
"def each_address(name)\n getaddresses(name).each { |address| yield(address)}\n end",
"def rep_address\n\"\\n\" + @recipient_name + \"\\n\" + @recipient_address + \n\"\\n\" + \"Washington DC 20510\" + \"\\n\" \nend",
"def send_referral_emails\n user.referrals.each do |ref|\n customer = Referral.find_by(id: user.id)\n ReferralMailer.notify_referral(ref, customer).deliver_now\n end\n end",
"def service_payment_info_loop\n end",
"def thankyou\n \n subscriptionId = params[\"subscription_id\"]\n result = ChargeBee::Address.retrieve({ \n :subscription_id => subscriptionId,\n :label => \"Shipping Address\"\n })\n @address = result.address\n \n end",
"def create_amount_to_bill_report\n\t\t\n\t\treport = {}\n\n\t\t@partners.each do |partner|\n\t\t\tnext if(partner.program_type == :direct) \n\t\t\treport[partner.partner_name] = {}\n\n\t\t\treport[partner.partner_name][:amount_to_bill] = partner.amount_due \n\t\tend\n\n\t\treport\n\tend",
"def rep_address\n \"\\n\" + @recipient_name + \"\\n\" + @recipient_address +\n \"\\n\" + \"Washington DC 20510\" + \"\\n\"\n end",
"def reconcile(amt, tip)\n cs = CheckSplitter.new(attendees.length, amt, tip)\n pay_each_person = cs.pay_each_person\n attendees.each do |attendee| \n if\n @members[attendee] += pay_each_person\n else\n @members[attendee] = pay_each_person\n end\n end\n @members\n end",
"def full_order_to_address\n ship_address.address1 + ' ' + ship_address.address2\n end",
"def add(billcoins, receiver, addresses)\n if addresses[receiver].nil?\n addresses[receiver] = billcoins\n else\n addresses[receiver] += billcoins\n end\n end",
"def print_layout_taxpayer_alternate_address\n { code: :taxpayer_alternate_address,\n parent_codes: %i[taxpayers],\n key_value: :party_type,\n key: '#key_value#_title',\n key_scope: %i[claim claim_payments taxpayer_address], # scope for the title translation\n type: :list,\n list_items: [{ code: :same_address, lookup: true, when: :object_index, is_not: [0] }] }\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Generating Eob level segments
|
def generate_eobs
Output835.log.info "\n\nPatient account number : #{@eob.patient_account_number}"
Output835.log.info "This EOB has #{@services.length} service lines"
Output835.log.info "This is a CLAIM LEVEL EOB" if @is_claim_eob
claim_segments = [claim_payment_loop, include_claim_dates]
claim_segments << claim_supplemental_info unless @facility.details[:interest_in_service_line]
claim_segments << claim_level_allowed_amount
claim_segments << standard_industry_code_segments(@eob, @is_claim_eob) if @is_claim_eob
claim_segments << service_payment_info_loop unless @is_claim_eob
update_clp! claim_segments
claim_segments.flatten.compact
end
|
[
"def Segment\n A = 1\n B = 2\n C = 4\n D = 8\n E = 16\n F = 32\n G = 64\n H = 128\n J = 256\n K = 512\n M = 1024\n N = 2048\n P = 4096\n\n def initialize(segments=0)\n @segments = segments\n end\n\n def s(seg=Segment.new)\n Segment.new seg.segments + SOUTH\n end\nend",
"def segments\n re = Array.new\n\n last_max = -1\n\n segs = index_segments\n segs.each_with_index do |range, i|\n sprints = range.to_a.map { |i| all_sprints[i] }\n span = range.max - range.min + 1\n w = range.min-last_max-1\n\n line_length = segment_width * w + inner_pad\n\n marker_length = segment_width * span - inner_pad\n\n re << [ :line, [line_length, sprints] ]\n re << [ :marker, [marker_length, sprints] ]\n\n last_max = range.max\n end\n\n # Last line\n butal = all_sprints.length - sprints.last.index - 1\n re << [ :line, segment_width * butal + inner_pad ]\n\n re\n end",
"def segments\n @segments ||= generate_segments\n end",
"def generate_linenumbers\n (0...@hilbert_basis.basis.to_a.size).to_a.combination(VERTICES).to_a\n end",
"def create_segments\n Segment.split_to_segments(build_waypoints)\n end",
"def leg(e)\n group = e.add_group\n entities = group.entities\n t_c = newTranslation 0, 0, @C\n t_b = newTranslation @B, 0, 0\n t_l_extra_neg = newTranslation 0, -@l_extra, 0\n\n # L segment's plane\n l_lower = [\n Geom::Point3d.new([0, 0, 0]),\n Geom::Point3d.new([@B, 0, 0]),\n Geom::Point3d.new([@B, @L, 0]),\n Geom::Point3d.new([0, @L, 0]),\n ]\n # The upper plane is @l_extra shorter\n l_upper = [\n t_c * l_lower[0],\n t_c * l_lower[1],\n t_l_extra_neg * t_c * l_lower[2],\n t_l_extra_neg * t_c * l_lower[3],\n ]\n\n l_left_panel = [\n l_lower[0], \n l_upper[0],\n l_upper[3],\n l_lower[3],\n ]\n l_right_panel = l_left_panel.map {|v| t_b * v}\n\n l_end_panel = [\n l_lower[0], \n l_right_panel[0],\n l_right_panel[1],\n l_upper[0],\n ]\n\n l1_lower = [\n Geom::Point3d.new([ 0, @d2 - @l1, @a1 + @p]),\n Geom::Point3d.new([@B, @d2 - @l1, @a1 + @p]),\n Geom::Point3d.new([@B, @d2, @a1 + @p]),\n Geom::Point3d.new([ 0, @d2, @a1 + @p]),\n ]\n # The upper plane is @l_extra longer\n l1_upper = [\n t_l_extra_neg * t_c * l1_lower[0],\n t_l_extra_neg * t_c * l1_lower[1],\n t_c * l1_lower[2],\n t_c * l1_lower[3],\n ]\n\n l1_left = [\n l1_lower[0], \n l1_upper[0],\n l1_upper[3],\n l1_lower[3],\n ]\n l1_right = l1_left.map {|v| t_b * v}\n\n l2_lower = [\n l_lower[3],\n l1_lower[0],\n l1_lower[1],\n l_lower[2],\n ]\n\n l2_upper = [\n l_upper[3],\n l1_upper[0],\n l1_upper[1],\n l_upper[2],\n ]\n\n l2_left = [\n l_lower[3],\n l_upper[3],\n l1_upper[0],\n l1_lower[0],\n ]\n l2_right = l2_left.map {|v| t_b * v}\n\n quad(entities, l_lower, @legColor)\n quad(entities, l_upper, @legColor)\n\n quad(entities, l_left_panel, @legColor)\n quad(entities, l_right_panel, @legColor)\n\n quad(entities, l_end_panel, @legColor)\n\n quad(entities, l1_lower, @legColor)\n quad(entities, l1_upper, @legColor)\n quad(entities, l1_left, @legColor)\n quad(entities, l1_right, @legColor)\n\n quad(entities, l2_lower, @legColor)\n quad(entities, l2_upper, @legColor)\n quad(entities, l2_left, @legColor)\n quad(entities, l2_right, @legColor)\n\n group\n end",
"def build_river_mouth_topo_segment\n @root = 0\n set_cell(@mouth,@n,:seg,@root)\n @root_s = @mouth\n @root_t = @n\n root_node = {s: @root_s, t: @root_t}\n @tree = [root_node]\n @segments = []\n @segments[@root] = @tree\n end",
"def generate_granular_segment_series\n reset_routing\n multiply_segments\n end",
"def crearImagen segmentos\n # Crear mapa de bits (Arreglo de 1001 arreglos de 1001 elementos == Matriz 1001x1001)\n bits = Array.new(1001) {|i| i = Array.new(1001, 0)}\n\n # Time to draw!\n # (Encender los bits en el mapa correspondientes a los puntos calculados)\n for punto in segmentos # Para todo punto en segmentos\n i = 500 - punto.y # Calcula la fila del arreglo\n j = 500 + punto.x # Calcula la columa del arreglo\n if i.between?(0, 1000) && j.between?(0, 1000)\n bits[i][j] = 1 # Enciende el bit\n end\n end\n\n # Generar salida\n output = \"P1\\n1001 1001\\n\"\n for i in 0..1000\n for j in 0..1000\n output.concat(bits[i][j].to_s).concat(' ')\n end\n output.concat(\"\\n\")\n end\n\n # Generar nombre de archivo\n temp = ARGV[0].split(\"/\").last\n filename = (temp.split(\".rtn\").first).concat(\".pbm\")\n\n # Escribir la salida en el archivo\n File.open(filename, 'w') do |content|\n content.print output\n end\nend",
"def calculate_segment_info\n\n # Transform path to local building coordinates.\n building_tr = @group.transformation\n path = @path.map { |p| p.transform building_tr.inverse }\n\n # Get tangent for each point in path.\n # Tangents point in the positive direction of path.\n tangents = []\n tangents << path[1] - path[0]\n if path.size > 2\n (1..path.size - 2).each do |corner_index|\n p_prev = path[corner_index - 1]\n p_this = path[corner_index]\n p_next = path[corner_index + 1]\n v_prev = p_this - p_prev\n v_next = p_next - p_this\n tangents << Geom.linear_combination(0.5, v_prev, 0.5, v_next)\n end\n end\n tangents << path[-1] - path[-2]\n\n # Rotate first and last tangent according to @end_angles.\n tangents.first.transform! Geom::Transformation.rotation ORIGIN, Z_AXIS, @end_angles.first\n tangents.last.transform! Geom::Transformation.rotation ORIGIN, Z_AXIS, @end_angles.last\n\n # If building should be drawn with it back along the path instead of its\n # front, reverse the path and tangents.\n # The terms left and right relates to the building front side.\n if @back_along_path\n path.reverse!\n tangents.reverse!\n tangents.each { |t| t.reverse! }\n end\n \n # Determine if interior corners (all but the building ends) are convex.\n convex = (1..path.size - 2).map do |corner_index|\n p_prev = path[corner_index - 1]\n p_this = path[corner_index]\n p_next = path[corner_index + 1]\n v_prev = p_this - p_prev\n v_next = p_next - p_this\n (v_prev * v_next).z > 0\n end\n \n # Get segment information.\n # Coordinates are relative to the segment group except for the group's\n # Transformation itself which is relative to the building group coordinates.\n segments_info = []\n (0..path.size - 2).each do |segment_index|\n \n segment_info = {}\n segments_info << segment_info\n \n first = segment_index == 0\n last = segment_index == path.size - 2\n \n # Values in main building @group's coordinates.\n corner_left = path[segment_index]\n corner_right = path[segment_index + 1]\n segment_vector = corner_right - corner_left\n length = segment_vector.length\n tangent_left = tangents[segment_index]\n tangent_right = tangents[segment_index + 1]\n transformation = Geom::Transformation.axes(\n corner_left,\n segment_vector,\n Z_AXIS * segment_vector,\n Z_AXIS\n )\n \n # Transformation of segment group.\n segment_info[:transformation] = transformation\n \n # The Length of the segment in the facade plane.\n segment_info[:length] = length\n\n # Values in local segment group's coordinates.\n tangent_left = tangent_left.transform transformation.inverse\n tangent_right = tangent_right.transform transformation.inverse\n plane_left = [ORIGIN, tangent_left.reverse]\n plane_right = [[length, 0, 0], tangent_right]\n side_planes = [plane_left, plane_right]\n \n # Vectors of adjacent path segments (in coordinates of local group).\n adjacent_vector_left = \n if first\n Z_AXIS*tangents.first.transform(transformation.inverse)\n else\n (path[segment_index]-path[segment_index-1]).transform(transformation.inverse).reverse\n end\n adjacent_vector_right = \n if last\n Z_AXIS*tangents.last.transform(transformation.inverse)\n else\n (path[segment_index+2]-path[segment_index+1]).transform transformation.inverse\n end\n segment_info[:adjacent_vector_left] = adjacent_vector_left\n segment_info[:adjacent_vector_right] = adjacent_vector_right\n segment_info[:adjacent_vectors] = [adjacent_vector_left, adjacent_vector_right]\n \n # Tangents of the corners for this segment.\n segment_info[:tangent_left] = tangent_left\n segment_info[:tangent_right] = tangent_right\n \n # Planes defining main sides of this segment.\n segment_info[:plane_left] = plane_left\n segment_info[:plane_right] = plane_right\n \n # Array of planes defining the main sides of the segment. 0th element is\n # left plane, 1st is right.\n segment_info[:side_planes] = side_planes\n\n # Determine planes to cut volume with for corner transitions.\n cts = @corner_transitions[@template.id]\n cut_planes = []\n if cts\n \n # Left side of segment\n ct = cts[segment_index-1]\n if ct && ct[\"length\"] && ct[\"length\"] > 0 && !first && convex[segment_index-1]\n half_angle = Y_AXIS.angle_between(tangent_left)\n tangent_vector = X_AXIS.reverse\n bisector_vector = Geom.linear_combination 0.5, X_AXIS.reverse, 0.5, tangent_left.reverse\n case ct[\"type\"]\n when \"chamfer_d\"\n diagonal_length = ct[\"length\"]\n projected_length = diagonal_length/(2*Math.sin(half_angle))\n cut_vector = bisector_vector\n when \"chamfer_p\"\n projected_length = ct[\"length\"]\n cut_vector = bisector_vector\n end\n if @back_along_path\n y = -(@template.depth || Template::FALLBACK_DEPTH)\n x = y*Math.tan(half_angle-90.degrees) + projected_length\n else\n x = projected_length\n y = 0\n end\n cut_planes[0] = [[x, y, 0], cut_vector]\n end\n \n # Right side of segment\n ct = cts[segment_index]\n if ct && ct[\"length\"] && ct[\"length\"] > 0 && !last && convex[segment_index]\n half_angle = Y_AXIS.angle_between(tangent_right.reverse)\n tangent_vector = X_AXIS\n bisector_vector = Geom.linear_combination 0.5, X_AXIS, 0.5, tangent_right\n case ct[\"type\"]\n when \"chamfer_d\"\n diagonal_length = ct[\"length\"]\n projected_length = diagonal_length/(2*Math.sin(half_angle))\n cut_vector = bisector_vector\n when \"chamfer_p\"\n projected_length = ct[\"length\"]\n cut_vector = bisector_vector\n end\n if @back_along_path\n y = -(@template.depth || Template::FALLBACK_DEPTH)\n x = length - y*Math.tan(half_angle-90.degrees) - projected_length\n else\n x = length - projected_length\n y = 0\n end\n cut_planes[1] = [[x, y, 0], cut_vector]\n end\n \n end\n \n # Array of planes defining how segment should be cut to leave space for\n # corner transition. 0th element is left plane, 1st is right.\n segment_info[:cut_planes] = cut_planes\n\n # List planes that are hidden within building.\n # All side and cut planes except for gables.\n internal_planes = []\n internal_planes << plane_left unless first\n internal_planes << plane_right unless last\n internal_planes += cut_planes.compact\n segment_info[:internal_planes] = internal_planes\n \n # List all planes defining the perimeter of segment.\n all_planes = side_planes + cut_planes.compact\n segment_info[:all_planes] = all_planes\n \n # List all planes for each side.\n segment_info[:planes_left] = [plane_left, cut_planes[0]].compact\n segment_info[:planes_right] = [plane_right, cut_planes[1]].compact\n \n # Information for the group the transition geometry is drawn to.\n # Group should be drawn at the left side of segment similar to how corner\n # parts are placed.\n if cts\n ct = cts[segment_index-1]\n if ct && ct[\"length\"] && ct[\"length\"] > 0 && !first && convex[segment_index-1]\n prev_segment = segments_info[segment_index-1]\n transition_group = {}\n tr_correction = transformation.inverse*prev_segment[:transformation]\n plane_left = prev_segment[:cut_planes][1].map { |c| c.transform tr_correction }\n plane_left[1].reverse!\n transition_group[:plane_left] = plane_left\n plane_right = cut_planes[0].dup\n plane_right[1] = plane_right[1].reverse\n transition_group[:plane_right] = plane_right\n transition_group[:planes] = [plane_left, plane_right]\n \n segment_info[:transition_group] = transition_group\n end\n end\n \n end\n\n segments_info\n\n end",
"def print_nm1_82_segment\n nm1_82_element_methods = @segments_list[:NM1_82]\n nm1_82_elements = [\n send(nm1_82_element_methods[:NM1_8200][0].to_sym, nm1_82_element_methods[:NM1_8200][1]), #['segment_name', 'NM1']\n send(nm1_82_element_methods[:NM1_8201][0].to_sym, nm1_82_element_methods[:NM1_8201][1]), #['print_constant', '82']\n send(nm1_82_element_methods[:NM1_8202][0].to_sym, nm1_82_element_methods[:NM1_8202][1]), #entity_type_qualifier\n send(nm1_82_element_methods[:NM1_8203][0].to_sym, nm1_82_element_methods[:NM1_8203][1]), #rendering_provider_last_or_organization_name\n send(nm1_82_element_methods[:NM1_8204][0].to_sym, nm1_82_element_methods[:NM1_8204][1]), #rendering_provider_first_name\n send(nm1_82_element_methods[:NM1_8205][0].to_sym, nm1_82_element_methods[:NM1_8205][1]), #rendering_provider_middle_name_or_initial\n send(nm1_82_element_methods[:NM1_8206][0].to_sym, nm1_82_element_methods[:NM1_8206][1]), #blank_segment\n send(nm1_82_element_methods[:NM1_8207][0].to_sym, nm1_82_element_methods[:NM1_8207][1]), #rendering_provider_name_suffix\n send(nm1_82_element_methods[:NM1_8208][0].to_sym, nm1_82_element_methods[:NM1_8208][1]), #rendering_provider_identification_code_qualifier\n send(nm1_82_element_methods[:NM1_8209][0].to_sym, nm1_82_element_methods[:NM1_8209][1]) #rendering_provider_identifier\n ]\n nm1_82_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def horloges_parties\n cmd = []\n cmd << %Q{-stroke gray50 -fill -pointsize 6.5 -strokewidth 2}\n # Pour le paradigme absolu\n decs = [0,30,60,90,120] # on en aura besoin ci-dessous\n decs.each do |dec|\n h = Horloge.new(horloge:realtime(dec).to_horloge, top:self.class.top_horloge_part_absolue, left:realpos(dec), bgcolor:'gray50', color:'gray90')\n cmd << h.magick_code\n end\n\n # Pour le paradigme propre au film\n [ne(:dv), ne(:d2)||ne(:cv), ne(:dn)].each_with_index do |neu, idx|\n next if neu.nil?\n dec = decs[idx+1]\n leftpos = realpos(dec)\n top = self.class.top_horloge_part_relative\n h = Horloge.new(horloge:neu.time.to_i.to_horloge, top:top, left:leftpos, bgcolor:'gray20', color:'white')\n cmd << h.magick_code\n # Pour le décalage\n leftdec = realpos(dec + 2.5)\n diff = neu.time.to_i - realtime(dec)\n pref = diff > 0 ? '+' : '−'\n cmd << %Q{-stroke black -fill black -draw \"text #{leftdec},#{top+LINE_HEIGHT/5} '#{pref}#{diff.abs.to_horloge}'\"}\n end\n\n return cmd.join(' ')\nend",
"def handle_hierarchy(file, b)\n points = {}\n points[$clusters[0]] = 0\n points[$clusters[1]] = 0\n\n charts = \"\"\n 5.times do |x|\n img = \"#{b}-level-#{x}\" \n charts += \"\\\\includegraphics[width=8cm]{#{img}}\\n\" if File.exist?(\"#{img}.png\")\n dat_file = File.readlines(\"#{img}.dat\")\n inner_points = {}\n inner_points[$clusters[0]] = 0\n inner_points[$clusters[1]] = 0\n clusters_values = dat_file[0].split(\" \")\n dat_file.size.times do |j|\n unless dat_file[j].nil?\n values = dat_file[j].split(\" \")\n # puts values\n if values[1].to_f > values[2].to_f\n inner_points[clusters_values[1]] += 1 \n elsif values[1].to_f < values[2].to_f\n inner_points[clusters_values[2]] += 1 \n end\n end\n end\n value1 = clusters_values[1].nil? ? 0 : inner_points[clusters_values[1]]\n value2 = clusters_values[2].nil? ? 0 : inner_points[clusters_values[2]]\n #puts \"#{value1} v1 #{value2} v2\"\n if value1 > value2 \n points[clusters_values[1]] += 1 \n elsif value1 < value2 \n points[clusters_values[2]] += 1 \n end\n #puts \"#{hfcm_level} hfcm_level x #{hpcm_level} hpcm_level\"\n end\n write_table(file, points[$clusters[0]], points[$clusters[1]])\n file.write charts\nend",
"def edges\n temp = []\n @strokes.each do |stroke|\n position = stroke.position\n colour = stroke.colour\n case stroke\n when CircleStroke\n radius = stroke.radius\n part = CirclePart.new(position, radius, colour)\n when LineStroke\n points = stroke.points.map { |p| p + position }\n part = PointsPart.new(points, colour)\n end\n temp << part\n end\n temp\n end",
"def end_vertices(e)\n self.Edges_Array.each do |edge|\n if (e==edge.label)\n puts \"The end vertices of edge #{edge.label} are #{edge.v} and #{edge.w} \"\n return \"#{edge.v}, #{edge.w}\"\n end\n end\n end",
"def outline_level; end",
"def view_segments\n each{ |type,obj| \n obj.lines.each{ |line| puts type.to_s + \": \" + line }\n }\n end",
"def draw_part(pts)\r\n\r\n # Draw holes\r\n for i in 0..(pts.length-1)\r\n draw_circle(pts[i], $normVec, $holeRadius)\r\n end\r\n \r\n # Loop through points\r\n for i in 0..(pts.length-1)\r\n \r\n # Get adjacent points\r\n adjPts = GetAdjacentPts(pts, i)\r\n \r\n # Compute start and end angles\r\n sAngle = angle_between_point_xy([adjPts[0],adjPts[1]])\r\n eAngle = angle_between_point_xy([adjPts[1],adjPts[2]])\r\n \r\n # Make adjustments\r\n sAngle = sAngle - 0.5\r\n eAngle = eAngle - 0.5\r\n if(eAngle < sAngle) \r\n eAngle = eAngle + 2 \r\n end\r\n\r\n # Draw curves\r\n draw_curve(adjPts[1], $normVec, $xaxis, $outerRadius, sAngle * Math::PI, eAngle * Math::PI)\r\n\r\n # Draw lines \r\n draw_line(add_outer_radius(adjPts[0],$outerRadius,sAngle),add_outer_radius(adjPts[1],$outerRadius,sAngle))\r\n \r\n end\r\n \r\nend",
"def builder_segment_z(register, number_batch, number_sequential_batch)\n segmento_z = '' # Descrição Posição Tamanho\n segmento_z << codigo_banco # Código do Banco 001..003 9(003)\n segmento_z << counter_batch(number_batch) # Lote de Serviço 004..007 9(004)\n segmento_z << '3' # Tipo de Registro 008..008 9(001)\n segmento_z << campo_numerico(number_sequential_batch, 5) # Número Seqüencial do Registro no Lote 009..013 9(005)\n segmento_z << 'Z' # Código Segmento no Registro Detalhe 014..014 X(001)\n segmento_z << campo_texto(register.authentication_payment, 64) # Autenticação do Pagamento 015..078 X(064)\n segmento_z << campo_numerico(register.protocol_payment, 25) # Protocolo do Pagamento 079..103 X(025)\n segmento_z << bloco_zerado(127) # Filler 104..230 X(127)\n segmento_z << campo_texto(register.occurrence, 10) # Ocorrências para o Retorno 231..240 X(010)\n clear_line(segmento_z)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get claim_number for payer_group not of type 'PatPay'
|
def claim_number
@eob.claim_number.to_s
end
|
[
"def get_payer_group\r\n case payer_type\r\n when 'PatPay'\r\n 'PatPay'\r\n else\r\n 'Insurance'\r\n end\r\n end",
"def claim_number\n str = eob.check_information.check_number.to_s if eob.check_information\n (str += '_' + eob.claim_number) if !eob.claim_number.blank?\n str\n end",
"def claim_number\n @eob.claim_number.present? ? \"#{@check.check_number}_#{@eob.claim_number}\" : \"#{@check.check_number}\"\n end",
"def test_get_payer_type_for_patpay_payer\n payid = '78787'\n payer = payers(:payer_221)\n assert_equal('PatPay', payer.get_payer_type(payid))\n end",
"def test_get_payid_of_patpay_payer\n payer_type = 'PatPay'\n assert_equal(\"P9998\", @payer.get_payid(payer_type,@facility_payids))\n end",
"def legacy_provider_number\n iplan = eobs.first.claim_information.iplan if eobs.first && eobs.first.claim_information\n supplimental_iplan = eobs.first.claim_information.supplemental_iplan if eobs.first && eobs.first.claim_information\n denied_amount = eobs.first.amount('total_denied') if eobs.first\n if iplan == 'MBR'\n supplimental_iplan\n elsif supplimental_iplan && denied_amount != 0.00\n supplimental_iplan\n elsif iplan\n iplan\n else\n payer.supply_payid if payer\n end\n end",
"def group_number\n # it seems 6P is group number\n self.additional_info.detect do |additional_info|\n [\"6P\", \"Group Number\"].include?(additional_info.id)\n end.group_policy_number\n end",
"def cpid\n first_mpi_claim = @eobs.detect{|eob| eob.claim_information}\n if first_mpi_claim && first_mpi_claim.claim_information.payid\n first_mpi_claim.claim_information.payid\n else\n payer_id\n end\n end",
"def payer_identifier(micr_line_information)\r\n payerid = nil\r\n if status.to_s.upcase == 'MAPPED'\r\n payerid = payid\r\n else\r\n unless micr_line_information.blank?\r\n payerid = micr_line_information.payid_temp\r\n end \r\n end\r\n payerid.to_s.upcase\r\n end",
"def payor_account_number\n case payor\n when :shipper\n shipper.account_number if shipper.respond_to?(:account_number)\n when :recipient\n recipient.account_number if recipient.respond_to?(:account_number)\n end\n end",
"def payer_id\n payer_of_first_check = checks.first.payer\n job = checks.first.job\n payer_type = job.payer_group if !job.blank?\n output_config = facility.output_config(payer_type)\n case output_config.grouping\n when 'By Check'\n payer_of_first_check.supply_payid if payer_of_first_check\n when 'By Payer','By Payer Id'\n payer_wise_payer_id(output_config)\n when 'By Batch', 'By Batch Date', 'By Cut'\n generic_payer_id(output_config)\n end\n end",
"def payer\n check = service.insurance_payment_eob.check_information\n micr = check.micr_line_information\n (micr and micr.payer) ? micr.payer : check.payer\n end",
"def claim_code\n perform_request(REQUEST_CLAIM_CODE).unpack(\"C\").first\n end",
"def get_payer\n is_grouped_payerwise = @facility_output_config.grouping == 'By Payer'\n if is_grouped_payerwise && @payer && @eob_type == 'Insurance' && @client_name != 'AHN'\n Output835.log.info \"\\n Getting payer details from payers table\"\n @payer\n else\n Output835.log.info \"\\n Getting payer details from facilities table\"\n @facility\n end\n end",
"def claim\n @claim ||= CLAIM_KEYS.find { |claim| payload&.key?(claim.to_s) }\n end",
"def payment_profile_id\n @customer_payment_profile_id\n end",
"def gateway_customer_profile_id_for_retailer(retailer)\n\t creditcards.where(:retailer_id => retailer.id).where(\"gateway_customer_profile_id is not null\").first.gateway_customer_profile_id rescue nil\n end",
"def service_payee_identification\n code, qual = nil, nil\n claim = eob.claim_information\n fac = facility\n\n if (claim && !claim.payee_npi.blank?)\n code = claim.payee_npi\n qual = 'XX'\n Output835.log.info \"Payee NPI from the 837 is chosen\"\n elsif (claim && !claim.payee_tin.blank?)\n code = claim.payee_tin\n qual = 'FI'\n Output835.log.info \"Payee TIN from 837 is chosen\"\n elsif !fac.facility_npi.blank?\n code = fac.facility_npi\n qual = 'XX'\n Output835.log.info \"facility NPI from FC is chosen\"\n elsif !fac.facility_tin.blank?\n code = fac.facility_tin\n qual = 'FI'\n Output835.log.info \"facility TIN from FC is chosen\"\n end\n\n return code, qual\n end",
"def get_account_payment_type\n self.le_account_payment_type.nil? ? \"\" : self.le_account_payment_type.name\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Used when additional reference numbers specific to the claim in the CLP segment are provided to identify information used in the process of adjudicating this claim
|
def other_claim_related_id
if @eob.insurance_policy_number.present?
elem = ['REF','IG', @eob.insurance_policy_number].trim_segment.join(@element_seperator)
end
end
|
[
"def other_claim_related_id\n elem = []\n if !eob.insurance_policy_number.blank?\n elem << 'REF'\n elem << 'IG'\n elem << eob.insurance_policy_number\n elem = Output835.trim_segment(elem)\n elem.join(@element_seperator)\n end\n end",
"def sequence_ref\n\t\t\t\t\traise \"Please define numbering ref.\"\n\t\t\t\tend",
"def print_ref_0k_segment\n ref_0k_element_methods = @segments_list[:REF_0K]\n ref_0k_elements = verify_ref_0k_condition{\n [\n send(ref_0k_element_methods[:REF_0K00][0].to_sym, ref_0k_element_methods[:REF_0K00][1]), #health_care_policy\n send(ref_0k_element_methods[:REF_0K01][0].to_sym, ref_0k_element_methods[:REF_0K01][1].to_s), #health_care_policy_id_qualifier\n send(ref_0k_element_methods[:REF_0K02][0].to_sym, ref_0k_element_methods[:REF_0K02][1]) #health_care_policy_identification\n ]\n }\n ref_0k_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def expand_reference(ref)\n ref.strip!\n if ref.match(/\\A(\\d+-?\\d*)\\Z/) # Just verse(s) given\n \"#{@passage_book} #{@passage_chapter}:#{ref}\"\n elsif ref.match(/\\A(\\d+):(\\d+-?\\d*)\\Z/) # Just chapter and verse(s) given\n \"#{@passage_book} #{ref}\"\n else\n ref\n end\n end",
"def reference_credit_note\n object.credit_note_ref.to_s\n end",
"def print_ref_lu_segment\n ref_lu_element_methods = @segments_list[:REF_LU]\n ref_lu_elements = verify_ref_lu_condition{\n [\n send(ref_lu_element_methods[:REF_LU00][0].to_sym, ref_lu_element_methods[:REF_LU00][1]), #service_identification\n send(ref_lu_element_methods[:REF_LU01][0].to_sym, ref_lu_element_methods[:REF_LU01][1].to_s), #service_reference_id_qualifier\n send(ref_lu_element_methods[:REF_LU02][0].to_sym, ref_lu_element_methods[:REF_LU02][1]) #service_reference_identification\n ]\n }\n ref_lu_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def reassociation_trace\n simple_client_array_for_1000000009 = [\"NAVICURE\", \"ASCEND CLINICAL LLC\"]\n trn_elements = ['TRN', '1', ref_number]\n if simple_client_array_for_1000000009.include? (@client_name)\n trn_elements << '1000000009'\n elsif @check_amount.to_f > 0 && @check.payment_method == \"EFT\"\n trn_elements << '1' + @facility.facility_tin if @facility.facility_tin.present?\n else\n trn_elements << '1999999999'\n end\n trn_elements.trim_segment.join(@element_seperator)\n end",
"def health_remark_code_segments\n @eob = service.insurance_payment_eob\n facility = @eob.check_information.job.batch.facility\n health_remark_code_segments = []\n health_remark_code_segments << compute_lq(\"in\")\n health_remark_code_segments << compute_lq(\"out\") \n if facility.details[:interest_in_service_line] && service.interest_service_line?\n health_remark_code_segments << lq_rx_segments(\"109975\") if @eob.claim_interest.to_f > 0.0 \n end \n health_remark_code_segments << lq_rx_segments(\"109702\") if @eob.hcra.to_f > 0.0\n health_remark_code_segments.compact!\n health_remark_code_segments.flatten\n end",
"def print_ref_hpi_segment\n ref_hpi_element_methods = @segments_list[:REF_HPI]\n ref_hpi_elements = verify_ref_hpi_condition{\n [\n send(ref_hpi_element_methods[:REF_HPI00][0].to_sym, ref_hpi_element_methods[:REF_HPI00][1]), #rendering_provider_information\n send(ref_hpi_element_methods[:REF_HPI01][0].to_sym, ref_hpi_element_methods[:REF_HPI01][1].to_s), #rendering_provider_id_qualifier\n send(ref_hpi_element_methods[:REF_HPI02][0].to_sym, ref_hpi_element_methods[:REF_HPI02][1]) #rendering_provider_identification\n ]\n }\n ref_hpi_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def print_ref_ea_segment\n ref_ea_element_methods = @segments_list[:REF_EA]\n ref_ea_elements = verify_ref_ea_condition{\n [\n send(ref_ea_element_methods[:REF_EA00][0].to_sym, ref_ea_element_methods[:REF_EA00][1]), #['segment_name', 'REF']\n send(ref_ea_element_methods[:REF_EA01][0].to_sym, ref_ea_element_methods[:REF_EA01][1].to_s), #['print_constant', 'EA']\n send(ref_ea_element_methods[:REF_EA02][0].to_sym, ref_ea_element_methods[:REF_EA02][1]) #medical_record_number\n ]\n }\n ref_ea_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def vref\r\n errors.add_to_base(\"Not that many PCs in the Reference Area\") unless ref <= MAX_REF\r\n errors.add_to_base(\"Can't be negative!\") unless ref >= 0\r\n end",
"def count_ref_crbbs\n @n_refs_with_recip = @reference.assembly.inject(0) do |sum, entry|\n name, contig = entry\n sum + (contig.hits.length > 0 ? 1 : 0)\n end\n end",
"def ref_seq\n\n if _ref_seq\n _ref_seq\n else\n seq = Reference.ref_seq(chromosome, start, stop, strand)\n update_attributes(:_ref_seq => seq)\n seq\n end\n\n end",
"def ref\n @referral['ref']\n end",
"def set_ref_seq\n\n seq = segments.map(&:ref_seq).reduce(:+)\n update_attributes(:_ref_seq => seq)\n\n seq\n\n end",
"def ref_number\n id + ORDER_NUMBER_START\n end",
"def enhance_referent(marc, request, accuracy)\n return unless accuracy > 2\n \n title_key = case request.referent.format\n when \"book\" then \"btitle\"\n when \"journal\" then \"jtitle\"\n when \"dissertation\" then \"title\"\n end\n metadata = request.referent.metadata\n unless metadata[title_key]\n if request.referent.metadata[\"title\"] && title_key != \"title\"\n request.referent.enhance_referent(title_key, metadata[\"title\"])\n else \n request.referent.enhance_referent(title_key, marc['245'].value)\n end\n end\n unless metadata[\"au\"]\n if marc['100'] && marc['100']['a']\n request.referent.enhance_referent('au', marc['100']['a'])\n end\n end\n unless metadata[\"aucorp\"]\n if marc['110'] && marc['110']['a']\n request.referent.enhance_referent('aucorp', marc['110']['a'])\n end \n end\n return unless accuracy > 3 \n unless metadata[\"place\"]\n if marc['260'] && marc['260']['a']\n request.referent.enhance_referent('place', marc['260']['a'])\n end \n end \n unless metadata[\"pub\"]\n if marc['260'] && marc['260']['b']\n request.referent.enhance_referent('pub', marc['260']['b'])\n end \n end \n unless metadata[\"edition\"] \n if marc['250'] && marc['250']['a']\n request.referent.enhance_referent('edition', marc['250']['a'])\n end \n end \n unless metadata[\"series\"]\n if marc['490'] && marc['490']['a']\n request.referent.enhance_referent('series', marc['490']['a'])\n elsif marc['730'] && marc['730']['a']\n request.referent.enhance_referent('series', marc['730']['a']) \n end \n end \n unless metadata[\"date\"] or request.referent.format == 'journal'\n if marc['260'] && marc['260']['c']\n request.referent.enhance_referent('date', marc['260']['c']) \n end \n end \n unless request.referent.format\n type = self.record_type(marc)\n request.referent.enhance_referent('format', 'book', false) if type == \"BKS\"\n request.referent.enhance_referent('format', 'journal', false) if type == \"SER\"\n end \n unless metadata[\"genre\"]\n if self.is_conference?(marc)\n if metadata[\"atitle\"]\n request.referent.enhance_referent('genre', 'proceeding')\n else\n request.referent.enhance_referent('genre', 'conference')\n end\n elsif type = self.nature_of_contents(marc)\n case type\n when \"dissertation\" then request.referent.enhance_referent('format', 'dissertation', false) \n when \"patent\" then request.referent.enhance_referent('format', 'patent', false)\n when \"report\" then request.referent.enhance_referent('genre', 'report')\n end\n else\n type = self.record_type(marc)\n if type == \"BKS\"\n request.referent.enhance_referent('format', 'book', false) unless request.referent.format == 'book'\n if metadata[\"atitle\"]\n request.referent.enhance_referent('genre', 'bookpart')\n else\n request.referent.enhance_referent('genre', 'book')\n end\n elsif type == \"SER\"\n request.referent.enhance_referent('format', 'journal', false) unless request.referent.format == 'journal' \n if metadata[\"atitle\"]\n request.referent.enhance_referent('genre', 'article')\n elsif metadata[\"issue\"]\n request.referent.enhance_referent('genre', 'issue')\n else\n request.referent.enhance_referent('genre', 'journal')\n end\n end\n end\n end\n \n unless metadata[\"isbn\"]\n if marc['020'] && marc['020']['a']\n request.referent.enhance_referent('isbn', marc['020']['a'])\n end\n end \n unless metadata[\"issn\"]\n if marc['022'] && marc['022']['a']\n request.referent.enhance_referent('issn', marc['022']['a'])\n end \n end \n unless metadata[\"sici\"]\n if marc['024'] && marc['024'].indicator1 == \"4\"\n request.referent.enhance_referent('sici', marc['024']['a']) \n end \n end\n \n unless metadata[\"coden\"]\n if marc['030'] && marc['030']['a']\n request.referent.enhance_referent('coden', marc['030']['a']) \n end \n end \n end",
"def health_remark_code_segments\n health_remark_code_segments = [compute_lq(\"in\"), compute_lq(\"out\")]\n if @facility.details[:interest_in_service_line] && @service.interest_service_line?\n health_remark_code_segments << lq_rx_segments(\"109975\") if @eob.claim_interest.to_f > 0.0\n end\n health_remark_code_segments << lq_rx_segments(\"109702\") if @eob.hcra.to_f > 0.0\n health_remark_code_segments.compact.flatten\n end",
"def print_ref_ig_segment\n ref_ig_element_methods = @segments_list[:REF_IG]\n ref_ig_elements = verify_ref_ig_condition{\n [\n send(ref_ig_element_methods[:REF_IG00][0].to_sym, ref_ig_element_methods[:REF_IG00][1]), #['segment_name', 'REF']\n send(ref_ig_element_methods[:REF_IG01][0].to_sym, ref_ig_element_methods[:REF_IG01][1].to_s), #['print_constant', 'IG']\n send(ref_ig_element_methods[:REF_IG02][0].to_sym, ref_ig_element_methods[:REF_IG02][1]) #insurance_policy_number\n ]\n }\n ref_ig_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
generating service level segments
|
def generate_services
is_adjustment_line = @service.adjustment_line_is?
service_segments = []
service_segments << service_payment_information unless is_adjustment_line
service_segments << service_date_reference
unless is_adjustment_line
cas_segments, pr_amount, crosswalked_codes = Output835.cas_adjustment_segments(@service, @client, @facility, @payer, @element_seperator, @eob, @batch, @check)
service_segments << cas_segments
else
pr_amount = 0.0
end
service_segments << service_line_item_control_num unless is_adjustment_line
service_segments << provider_control_number unless is_adjustment_line
supp_amount = supplemental_amount
service_segments << service_supplemental_amount(supp_amount) unless supp_amount.blank? || @service.amount('service_paid_amount').blank?
service_segments << patpay_specific_lq_segment if @facility.abbr_name == "RUMC"
service_segments << standard_industry_code_segments(@service)
[service_segments.compact.flatten, pr_amount]
end
|
[
"def segments\n @segments ||= generate_segments\n end",
"def create_segments\n Segment.split_to_segments(build_waypoints)\n end",
"def segments\n #segments = @route.segments.select do |segment|\n # [ActionController::Routing::DynamicSegment, ActionController::Routing::StaticSegment].include? segment.class\n #end\n #segments.pop if segments.last.is_a?(ActionController::Routing::StaticSegment) && segments.last.value == @action && segments.last.value != 'new'\n #segments\n resolve_segments\n end",
"def get_segments\n return make_request(\"#{self.endpoint}/list/segments\")\n end",
"def get_section_and_service(service_id)\n service_id.split('.')\n end",
"def generate_granular_segment_series\n reset_routing\n multiply_segments\n end",
"def segments\n\t\tSegmentList.new(@ida)\n\tend",
"def print_svc_segment\n svc_element_methods = @segments_list[:SVC]\n svc_elements = verify_svc_condition{\n [\n send(svc_element_methods[:SVC00][0].to_sym, svc_element_methods[:SVC00][1]), #['segment_name', 'SVC']\n send(svc_element_methods[:SVC01][0].to_sym, svc_element_methods[:SVC01][1]), #composite_medical_procedure\n send(svc_element_methods[:SVC02][0].to_sym, svc_element_methods[:SVC02][1]), #line_item_charge_amount\n send(svc_element_methods[:SVC03][0].to_sym, svc_element_methods[:SVC03][1]), #line_item_provider_payment_amount\n send(svc_element_methods[:SVC04][0].to_sym, svc_element_methods[:SVC04][1]), #national_uniform_billing_committee_revenue_code\n send(svc_element_methods[:SVC05][0].to_sym, svc_element_methods[:SVC05][1]), #units_of_service_paid_count\n send(svc_element_methods[:SVC06][0].to_sym, svc_element_methods[:SVC06][1]) #composite_medical_procedure_identifier\n ]\n }\n svc_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def lists_and_segments\n response = get \"listsandsegments\", {}\n Hashie::Mash.new(response)\n end",
"def segments\n @segments ||= begin\n segments = extract_segments.map do |segment|\n PackageFlightLegSegment.new(segment)\n end\n segments.each do |segment|\n segment.sibling_segments = segments\n end\n segments\n end\n end",
"def _segments\n # segments is lazy so it can pick up version values that come from\n # old marshaled versions, which don't go through marshal_load.\n # since this version object is cached in @@all, its @segments should be frozen\n\n @segments ||= @version.sub(/#{METADATA_PATTERN}$/, '').scan(/[0-9]+|[a-z]+/i).map do |s|\n /^\\d+$/ =~ s ? s.to_i : s\n end.freeze\n end",
"def segments\n @segments ||= @views.collect {|view_class| {:label => view_class[:description], :width => 0}}\n end",
"def segments\n template_snapshot.xpath('//psc:study-segment', Psc.xml_namespace)\n end",
"def Segment\n A = 1\n B = 2\n C = 4\n D = 8\n E = 16\n F = 32\n G = 64\n H = 128\n J = 256\n K = 512\n M = 1024\n N = 2048\n P = 4096\n\n def initialize(segments=0)\n @segments = segments\n end\n\n def s(seg=Segment.new)\n Segment.new seg.segments + SOUTH\n end\nend",
"def street_segments\r\n\t\tstart_street_segments + end_street_segments\r\n\tend",
"def segmentsByUser(user=\"gazebo\")\n headers[\"content-type\"]=\"text/html\";\n @segment_data = []\n # get user object \n u = User.find_by_name(user)\n su = SegmentsUsers.find_all_by_user_id(u.id)\n su.each do |s|\n sn = Segment.find(s.segment_id)\n @segment_data << sn.name\n end\n end",
"def route_services\n generated_route = []\n route_list.each do |item|\n if(item.is_a?(Service) || item.is_a?(CustomService))\n generated_route.push(item)\n elsif(item.is_a?(ServiceGroup))\n item.services.each do |srv|\n generated_route.push(srv)\n end\n end\n end\n generated_route\n end",
"def segments\n re = Array.new\n\n last_max = -1\n\n segs = index_segments\n segs.each_with_index do |range, i|\n sprints = range.to_a.map { |i| all_sprints[i] }\n span = range.max - range.min + 1\n w = range.min-last_max-1\n\n line_length = segment_width * w + inner_pad\n\n marker_length = segment_width * span - inner_pad\n\n re << [ :line, [line_length, sprints] ]\n re << [ :marker, [marker_length, sprints] ]\n\n last_max = range.max\n end\n\n # Last line\n butal = all_sprints.length - sprints.last.index - 1\n re << [ :line, segment_width * butal + inner_pad ]\n\n re\n end",
"def segments\n return @segments\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
supplies payment and control information to a provider for a particular service
|
def service_payment_information(eob = nil,service = nil,check = nil,is_claim_eob = nil,payer = nil)
@service = @service.nil?? service : @service
['SVC', composite_med_proc_id, @service.amount('service_procedure_charge_amount'), @service.amount('service_paid_amount'),
svc_revenue_code, @service.service_quantity.to_f.to_amount, svc_procedure_cpt_code].trim_segment.join(@element_seperator )
end
|
[
"def service_payment_info_loop\n end",
"def service_payment_information(eob = nil,service = nil,check = nil,is_claim_eob = nil,payer = nil)\n @service = @service.nil? ? service : @service\n ['SVC', composite_med_proc_id, @service.amount('service_procedure_charge_amount'), @service.amount('service_paid_amount'),\n '', @service.service_quantity.to_f.to_amount].trim_segment.join(@element_seperator )\n end",
"def add_paymentmethods; end",
"def update_service_information\n alter_svc_info if @service_payment_era_attributes['service_product_qualifier'] == 'NU'\n @service_payment_era = ServicePaymentEra.create!(@service_payment_era_attributes)\n @service_payment_era_attributes = ServicePaymentEra.new(:insurance_payment_era_id => @insurance_payment_era.id).attributes\n update_service_adjustments\n end",
"def process_payment!\n @payment_type.pay\n end",
"def insert_payment_method\n authorize current_employer\n @customer = Customer.new(customer_params)\n pay_service = Services::Pay.new(current_employer, nil, @customer.stripe_card_token)\n\n if pay_service.is_customer_saved?\n redirect_to employers_payment_methods_path,\n notice: 'You have successfully added your payment information!'\n else\n redirect_to employers_payment_verify_path, alert: \"There was an error processing your card. Contact support.\"\n end\n end",
"def show_payment\n end",
"def provider_class\n ::Spree::PAYONE::Provider::Payment::CashOnDelivery\n end",
"def enter_verifying_payment; end",
"def pay\n \n end",
"def add_payment_method\n authorize(current_employer)\n @customer = Customer.new\n end",
"def shipping_as_full_information_account\n shipping_address_form.continue_btn.click\n PaymentATG.new\n end",
"def service_ppp!()\n @service = TAC_PLUS_AUTHEN_SVC_PPP\n end",
"def payment\n \tcurrent_user\n \t@owner = Owner.find(@current_user.resource_id)\n \t@plan = SignupPlan.find_by_id(params[:id])\n \t@current_user.resource.signup_plan = @plan\n \t@invoice = Invoice.new\n \t@invoice.signup_plan = @plan\n \t@invoice.user = @current_user\n \t@invoice.amount = @plan.price\n \t@invoice.status = \"Payment due\"\n \t@invoice.save!\n end",
"def purchase(amount, description, payment_id, coupon_code = self.coupon_code)\n raise \"No Payment Method\" if self.customer_id.blank? && self.stripe_token.blank? && self.paypal_token.blank?\n\n coupon = CouponCode.find_by_code(coupon_code)\n unless coupon.blank?\n amount = process_coupon(coupon, amount)\n end\n\n #Calculate HST tax for Canadian registrants\n if self.country == 'CA'\n hst_tax = amount * 0.13\n amount += hst_tax\n end\n\n charge = self.payments.create(amount: amount, comment: description, stripe_token: payment_id, paypal_token: paypal_token)\n charge.process\n charge.save\n self.save\n\n #kick off the receipt email\n unless paypal_token.present? \n \tStripePayment.business_account_registration_receipt(self).deliver\n end\n end",
"def pay\n handle_action('pay')\n notify(\"paid\",nil)\n end",
"def create\n @payment_provider = PaymentProvider.new(payment_provider_params)\n\n respond_to do |format|\n if @payment_provider.save\n format.html { redirect_to settings_payments_path, notice: 'Payment provider was successfully created.' }\n format.json { render :show, status: :created, location: @payment_provider }\n else\n format.html { render :new }\n format.json { render json: @payment_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def provider\n #assign payment mode\n OffsitePayments.mode = preferred_test_mode == true ? :test : :production\n provider_class\n end",
"def licensing_billing_fillout(partner)\r\n # wait_until { !first(:id, \"conti_button\").nil? | !first(:id, \"submit_button\").nil?}\r\n # define base plan\r\n fill_base_plan(partner.base_plan)\r\n # define base plan subscription period\r\n fill_subscription_period(partner)\r\n # home specific items\r\n if partner.partner_info.type.eql?(\"MozyHome\")\r\n fill_additional_storage(partner)\r\n fill_additional_computers(partner)\r\n else\r\n end\r\n # server add-on\r\n server_plan_fill_out(partner)\r\n # coupon code\r\n coupon_code_fill_out(partner)\r\n # emea-vat number\r\n vat_fill_out(partner)\r\n # home-get plan summary\r\n get_plan_summary(partner)\r\n continue_btn.click\r\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
The DTM segment in the SVC loop is to be used to express dates and date ranges specifically related to the service identified in the SVC segment If service from and to dates are same, only print one segment with qual 472 Else print one segment each for the two dates
|
def service_date_reference
svc_date_segments = []
from_date = @service.date_of_service_from.strftime("%Y%m%d") unless @service.date_of_service_from.blank?
to_date = @service.date_of_service_to.strftime("%Y%m%d") unless @service.date_of_service_to.blank?
from_eqls_to_date = (from_date == to_date)
is_client_upmc = (@client_name == "UNIVERSITY OF PITTSBURGH MEDICAL CENTER")
if from_date && (!to_date || from_eqls_to_date || @client.group_code.to_s.strip == 'KOD')
if(@client_name == "ISTREAMS" && from_date == "20000101")
svc_date_segments = dtm_472("00000000")
elsif !(is_client_upmc && from_date == "20000112")
svc_date_segments = dtm_472(from_date) if can_print_service_date(from_date)
end
else
svc_date_segments << dtm_150(from_date) if can_print_service_date(from_date)
svc_date_segments << dtm_151(to_date) if can_print_service_date(to_date)
svc_date_segments unless svc_date_segments.join.blank?
end
end
|
[
"def service_date_reference\n svc_date_segments = []\n from_date = @service.date_of_service_from.strftime(\"%Y%m%d\") unless @service.date_of_service_from.blank?\n to_date = @service.date_of_service_to.strftime(\"%Y%m%d\") unless @service.date_of_service_to.blank?\n svc_date_segments << ['DTM', '150', from_date].join(@element_seperator) if can_print_service_date(from_date)\n svc_date_segments << ['DTM', '151', to_date].join(@element_seperator) if can_print_service_date(to_date)\n svc_date_segments unless svc_date_segments.blank?\n end",
"def service_date_reference\r\n service_date_elements, svc_date_segments = [], []\r\n from_date = service.date_of_service_from.strftime(\"%Y%m%d\") unless service.date_of_service_from.blank?\r\n to_date = service.date_of_service_to.strftime(\"%Y%m%d\") unless service.date_of_service_to.blank? \r\n from_eqls_to_date = (from_date == to_date)\r\n \r\n if !from_date.nil? && (to_date.nil? || from_eqls_to_date || @client.group_code.to_s.strip == 'KOD')\r\n if @client.name.strip.upcase == \"ISTREAMS\" and from_date == \"20000101\"\r\n service_date_elements = dtm_472(\"00000000\")\r\n else\r\n service_date_elements = dtm_472(from_date)\r\n end\r\n service_date_elements unless service_date_elements.blank?\r\n else\r\n if from_date\r\n svc_date_segments << dtm_150(from_date)\r\n end\r\n if to_date\r\n svc_date_segments << dtm_151(to_date)\r\n end\r\n svc_date_segments unless svc_date_segments.join.blank?\r\n end\r\n end",
"def service_date_reference\n service_date_elements, svc_date_segments = [], []\n from_date = service.date_of_service_from.strftime(\"%Y%m%d\") unless service.date_of_service_from.blank?\n to_date = service.date_of_service_to.strftime(\"%Y%m%d\") unless service.date_of_service_to.blank? \n if from_date\n service_date_elements << 'DTM'\n service_date_elements << '150'\n service_date_elements << from_date\n svc_date_segments << service_date_elements.join(@element_seperator)\n end\n if to_date\n service_date_elements = []\n service_date_elements << 'DTM'\n service_date_elements << '151'\n service_date_elements << to_date\n svc_date_segments << service_date_elements.join(@element_seperator)\n end\n svc_date_segments unless svc_date_segments.blank?\n end",
"def print_svc_segment\n svc_element_methods = @segments_list[:SVC]\n svc_elements = verify_svc_condition{\n [\n send(svc_element_methods[:SVC00][0].to_sym, svc_element_methods[:SVC00][1]), #['segment_name', 'SVC']\n send(svc_element_methods[:SVC01][0].to_sym, svc_element_methods[:SVC01][1]), #composite_medical_procedure\n send(svc_element_methods[:SVC02][0].to_sym, svc_element_methods[:SVC02][1]), #line_item_charge_amount\n send(svc_element_methods[:SVC03][0].to_sym, svc_element_methods[:SVC03][1]), #line_item_provider_payment_amount\n send(svc_element_methods[:SVC04][0].to_sym, svc_element_methods[:SVC04][1]), #national_uniform_billing_committee_revenue_code\n send(svc_element_methods[:SVC05][0].to_sym, svc_element_methods[:SVC05][1]), #units_of_service_paid_count\n send(svc_element_methods[:SVC06][0].to_sym, svc_element_methods[:SVC06][1]) #composite_medical_procedure_identifier\n ]\n }\n svc_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def print_dtm_150_segment\n dtm_150_element_methods = @segments_list[:DTM_150]\n dtm_150_elements = verify_dtm_150_condition{\n [\n send(dtm_150_element_methods[:DTM_15000][0].to_sym, dtm_150_element_methods[:DTM_15000][1]), #['segment_name', 'DTM']\n send(dtm_150_element_methods[:DTM_15001][0].to_sym, dtm_150_element_methods[:DTM_15001][1].to_s), #['print_constant', '150']\n send(dtm_150_element_methods[:DTM_15002][0].to_sym, dtm_150_element_methods[:DTM_15002][1]) #service_period_start\n ]\n }\n dtm_150_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def print_dtm_151_segment\n dtm_151_element_methods = @segments_list[:DTM_151]\n dtm_151_elements = verify_dtm_151_condition{\n [\n send(dtm_151_element_methods[:DTM_15100][0].to_sym, dtm_151_element_methods[:DTM_15100][1]), #['segment_name', 'DTM']\n send(dtm_151_element_methods[:DTM_15101][0].to_sym, dtm_151_element_methods[:DTM_15101][1].to_s), #['print_constant', '151']\n send(dtm_151_element_methods[:DTM_15102][0].to_sym, dtm_151_element_methods[:DTM_15102][1]) #coverage_amount\n ]\n }\n dtm_151_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def print_ts2_segment\n ts2_element_methods = @segments_list[:TS2]\n ts2_elements = verify_ts2_condition{\n [\n send(ts2_element_methods[:TS200][0].to_sym, ts2_element_methods[:TS200][1]), #provider_supplemental_summary_info\n send(ts2_element_methods[:TS201][0].to_sym, ts2_element_methods[:TS201][1]), #total_drg_amount\n send(ts2_element_methods[:TS202][0].to_sym, ts2_element_methods[:TS202][1]), #total_federal_specific_amount\n send(ts2_element_methods[:TS203][0].to_sym, ts2_element_methods[:TS203][1]), #total_hospital_specific_amount\n send(ts2_element_methods[:TS204][0].to_sym, ts2_element_methods[:TS204][1]), #toal_disproportionate_amount\n send(ts2_element_methods[:TS205][0].to_sym, ts2_element_methods[:TS205][1]), #total_capital_amount\n send(ts2_element_methods[:TS206][0].to_sym, ts2_element_methods[:TS206][1]), #total_indirect_medical_education_amount\n send(ts2_element_methods[:TS207][0].to_sym, ts2_element_methods[:TS207][1]), #total_outlier_day_count\n send(ts2_element_methods[:TS208][0].to_sym, ts2_element_methods[:TS208][1]), #total_day_outlier_amount\n send(ts2_element_methods[:TS209][0].to_sym, ts2_element_methods[:TS209][1]), #total_cost_outlier_amount\n send(ts2_element_methods[:TS210][0].to_sym, ts2_element_methods[:TS210][1]), #average_drg_length_of_stay\n send(ts2_element_methods[:TS211][0].to_sym, ts2_element_methods[:TS211][1]), #total_discharge_count\n send(ts2_element_methods[:TS212][0].to_sym, ts2_element_methods[:TS212][1]), #total_cost_report_day_count\n send(ts2_element_methods[:TS213][0].to_sym, ts2_element_methods[:TS213][1]), #total_covered_day_count\n send(ts2_element_methods[:TS214][0].to_sym, ts2_element_methods[:TS214][1]), #total_noncovered_day_count\n send(ts2_element_methods[:TS215][0].to_sym, ts2_element_methods[:TS215][1]), #total_msp_pass_through_amount\n send(ts2_element_methods[:TS216][0].to_sym, ts2_element_methods[:TS216][1]), #average_drg_weight\n send(ts2_element_methods[:TS217][0].to_sym, ts2_element_methods[:TS217][1]), #total_pps_capital_fsp_drg_amount\n send(ts2_element_methods[:TS218][0].to_sym, ts2_element_methods[:TS218][1]), #total_psp_capital_hsp_drg_amount\n send(ts2_element_methods[:TS219][0].to_sym, ts2_element_methods[:TS219][1]) #total_pps_dsh_drg_amount\n ]\n }\n ts2_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def print_dtm_233_segment\n dtm_233_element_methods = @segments_list[:DTM_233]\n dtm_233_elements = verify_dtm_233_condition{\n [\n send(dtm_233_element_methods[:DTM_23300][0].to_sym, dtm_233_element_methods[:DTM_23300][1]), #['segment_name', 'DTM']\n send(dtm_233_element_methods[:DTM_23301][0].to_sym, dtm_233_element_methods[:DTM_23301][1].to_s), #['print_constant', '233']\n send(dtm_233_element_methods[:DTM_23302][0].to_sym, dtm_233_element_methods[:DTM_23302][1]) #claim_statement_period_end\n ]\n }\n dtm_233_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def print_dtm_050_segment\n dtm_050_element_methods = @segments_list[:DTM_050]\n dtm_050_elements = verify_dtm_050_condition{\n [\n send(dtm_050_element_methods[:DTM_05000][0].to_sym, dtm_050_element_methods[:DTM_05000][1]), #claim_received_date\n send(dtm_050_element_methods[:DTM_05001][0].to_sym, dtm_050_element_methods[:DTM_05001][1].to_s), #claim_date_qualifier\n send(dtm_050_element_methods[:DTM_05002][0].to_sym, dtm_050_element_methods[:DTM_05002][1]) #received_date\n ]\n }\n dtm_050_elements.flatten.trim_segment.join(@facility_level_details[:element_separator])\n end",
"def process_claim_start_and_end_dates(c,date_qualifier)\n if date_qualifier == \"434\" or date_qualifier == \"472\"\n service_dates = c[1].split(\"-\")\n @claim_information[\"claim_statement_period_start_date\"] = service_dates[0].to_s if @claim_information.claim_statement_period_start_date.nil?\n @claim_information[\"claim_statement_period_end_date\"] = service_dates.length == 2 ? service_dates[1].to_s : service_dates[0].to_s if @claim_information.claim_statement_period_end_date.nil?\n elsif date_qualifier == \"435\" or date_qualifier == \"096\"\n if date_qualifier == \"435\"\n @claim_information[\"claim_statement_period_start_date\"] = c[1] if @claim_information.claim_statement_period_start_date.nil?\n @service_from_date = @claim_information.claim_statement_period_start_date\n else\n @claim_information[\"claim_statement_period_end_date\"] = c[1] if @claim_information.claim_statement_period_end_date.nil?\n @service_to_date = @claim_information.claim_statement_period_end_date\n end\n end\n end",
"def generate_services\n is_adjustment_line = @service.adjustment_line_is?\n service_segments = []\n service_segments << service_payment_information unless is_adjustment_line\n service_segments << service_date_reference\n unless is_adjustment_line\n cas_segments, pr_amount, crosswalked_codes = Output835.cas_adjustment_segments(@service, @client, @facility, @payer, @element_seperator, @eob, @batch, @check)\n service_segments << cas_segments\n else\n pr_amount = 0.0\n end\n service_segments << service_line_item_control_num unless is_adjustment_line\n service_segments << provider_control_number unless is_adjustment_line\n supp_amount = supplemental_amount\n service_segments << service_supplemental_amount(supp_amount) unless supp_amount.blank? || @service.amount('service_paid_amount').blank?\n service_segments << patpay_specific_lq_segment if @facility.abbr_name == \"RUMC\"\n service_segments << standard_industry_code_segments(@service)\n [service_segments.compact.flatten, pr_amount]\n end",
"def health_remark_code_segments\n @eob = service.insurance_payment_eob\n facility = @eob.check_information.job.batch.facility\n health_remark_code_segments = []\n health_remark_code_segments << compute_lq(\"in\")\n health_remark_code_segments << compute_lq(\"out\") \n if facility.details[:interest_in_service_line] && service.interest_service_line?\n health_remark_code_segments << lq_rx_segments(\"109975\") if @eob.claim_interest.to_f > 0.0 \n end \n health_remark_code_segments << lq_rx_segments(\"109702\") if @eob.hcra.to_f > 0.0\n health_remark_code_segments.compact!\n health_remark_code_segments.flatten\n end",
"def claim_loop\n segments = []\n lx_selection = @facility_config.details[:lx_segment][\"1\"] rescue \"1\"\n if lx_selection == \"[By Bill Type]\"\n eob_group = @eobs.group_by{|eob| eob.bill_type}\n eob_group.each_with_index do |group, index|\n segments << write_claim_payment_information({:eobs => group[1], :count_condition => 'single', :justification => 1, :index => index +1})\n end\n elsif lx_selection == '[3-Sequential Number]'\n segments = write_claim_payment_information({:eobs => @eobs, :count_condition => 'multiple', :justification => 3})\n else\n segments = write_claim_payment_information({:eobs => @eobs, :count_condition => 'single', :justification => 1, :value => lx_selection })\n end\n segments = segments.flatten.compact\n segments unless segments.blank?\n end",
"def check_time_segment_set_coverage_full_day(start_time, num_checked)\n # use Set class to perform intelligent merge/intersection calculations on range 0..1439\n all_day = (0..1439).to_a\n\n # check only non-destroyed time segments\n non_destroyed_time_segments = time_segments.select {|ts| not ts.marked_for_destruction?}.compact\n\n coverage = []\n non_destroyed_time_segments.each do |ts|\n this_time = (ts.start_min .. ts.end_min).to_a\n # Array#uniq! return array of unique elements or nil if no changes (all unique)\n if (coverage + this_time).uniq!\n create_time_segment_error(\"Time Segment Set invalid because there are overlapping time segments starting at #{ts.pretty_start} in profile #{self.name}\")\n end\n # Array#| Set Union on two arrays\n coverage |= this_time\n end\n\n unless (all_day - coverage).empty?\n uncovered_ranges = all_day - coverage\n uncovered_ranges.extend ArrayGroups\n\n uncovered_ranges.groups.each do |u|\n def pretty(i); TimeSegment.minutes_to_pretty(i); end\n create_time_segment_error(\"Time Segment Set invalid because there is a gap at #{pretty(u[0])} for profile #{self.name}\")\n\n end\n end\n\n end",
"def process_range(date, processor)\n order = parts(processor)\n\n parts = [order, order].zip(date.display_parts).map do |order, parts|\n order.map { |part| parts.include?(part['name']) ? part : nil }.compact\n end\n\n result = parts.zip([date, date.to]).map { |parts, date| parts.map { |part| part.process(date, processor) }.join(delimiter) }.compact\n result[0].gsub!(/\\s+$/, '')\n result.join(parts[0].last.range_delimiter)\n\n # case\n # when date.open_range?\n # result << parts.map { |part| part.process(date, processor) }.join(delimiter)\n # result << parts.last.range_delimiter\n # \n # when discriminator == 'month'\n # month_parts = parts.reject { |part| part['name'] == 'year' }\n # \n # result << month_parts.map { |part| part.process(date, processor) }.join(delimiter)\n # result << month_parts.last.range_delimiter\n # result << parts.map { |part| part.process(date.to, processor) }.join(delimiter)\n # \n # when discriminator == 'day'\n # day_parts = parts.select { |part| part['name'] == 'day' }\n # \n # result << day_parts.map { |part| part.process(date, processor) }.join(delimiter)\n # result << day_parts.last.range_delimiter\n # result << parts.map { |part| part.process(date.to, processor) }.join(delimiter)\n # \n # else # year\n # year_parts = parts.select { |part| part['name'] == 'year' }\n # \n # result << parts.map { |part| part.process(date, processor) }.join(delimiter)\n # result << year_parts.last.range_delimiter\n # result << year_parts.map { |part| part.process(date.to, processor) }.join(delimiter)\n # \n # end\n # \n # result.join\n end",
"def live_segmentations\n segmentations = Array.new\n \n segment = self.segments.new\n \n segmentations << segment.script(\"SELECT * FROM [$$brand_code$$_WeeklyCampaign] WHERE campaign_id = $$campaign_id$$\")\n segmentations << segment.script(\"SELECT * FROM [$$brand_code$$_Whole] Whole WHERE NOT EXISTS ( SELECT * FROM [$$brand_code$$_UNSUBS] Unsubs WHERE Unsubs.email_address = Whole.email_address ) AND NOT EXISTS ( SELECT * FROM ent.[ET_UNSUB] GlobalUnsubs WHERE GlobalUnsubs.email_address = Whole.email_address )\")\n \n versions.each do |v|\n list = (v.audience_list.split(',').collect { |a| \"'\" + a.lstrip + \"'\" }).join(', ')\n segmentations << segment.script(\"SELECT * FROM [$$treatment_name$$_WAU] WHERE email_version IN (#{list})\") \n end\n \n segmentations;\n end",
"def service_period\n Range.new(service_start, service_end) if service_start && service_end\n end",
"def claim_loop\n segments = []\n @eobs.each_with_index do |eob, index|\n @check_grouper.last_eob = eob\n @check = eob.check_information\n @job = @check.job\n if @check.micr_line_information && @check.micr_line_information.payer && @facility.details[:micr_line_info]\n @payer = @check.micr_line_information.payer\n else\n @payer = @check.payer\n end\n @facility_output_config = @facility.output_config(@payer.payer_type)\n @reason_codes = nil #this variable is used in child class for configurable section\n @eob = eob\n @claim = eob.claim_information\n @eob_index = index\n @services = eob.service_payment_eobs\n @is_claim_eob = (eob.category.upcase == \"CLAIM\")\n @count = count\n segments << transaction_set_line_number(index + 1)\n segments << transaction_statistics([eob])\n segments += generate_eobs\n end\n segments.flatten.compact\n end",
"def segments_params_1\n {\n dataSetId: @dataSetId,\n effectiveDate: @effectiveDate,\n modelYear: \"2017\",\n segmentCode: \"175\",\n residuals: true\n }\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Identifies the orionvm cloud === Return true:: If the orionvm cloud can be identified false:: Otherwise
|
def looks_like_orionvm?
hint?('orionvm') || looks_like_orionvm_v2? || looks_like_orionvm_v3?
end
|
[
"def cloud?\n self.automatic.has_key?(:cloud)\n end",
"def manage_ip?\n case type.hotspot\n when 'hsv1-mem' then true\n when 'hsv2-bam' then false\n else false\n end\n end",
"def is_current_cloud?\n # See https://developers.google.com/compute/docs/instances#dmi\n `grep Google /sys/firmware/dmi/entries/1-0/raw 2>&1 >/dev/null`\n return $?.success?\nend",
"def cloud?(node)\n node.key?('cloud')\n end",
"def cloud?(node = __getnode)\n # cloud is always present, but nil if not on a cloud\n !node[\"cloud\"].nil?\n end",
"def vmware_host?(node = __getnode)\n node.dig(\"virtualization\", \"system\") == \"vmware\" && node.dig(\"virtualization\", \"role\") == \"host\"\n end",
"def is_vmware?()\n @machine.provider_name.to_s().start_with?('vmware')\n end",
"def exists?\n vnic\n end",
"def openvz_host?(node = __getnode)\n node.dig(\"virtualization\", \"system\") == \"openvz\" && node.dig(\"virtualization\", \"role\") == \"host\"\n end",
"def detect_openstack\n return false unless nova_exists?\n @virtualization_data[:system] = 'openstack'\n @virtualization_data[:role] = 'host'\n true\n end",
"def vmware_vsphere?(node = __getnode)\n node.dig(\"virtualization\", \"system\") == \"vmware\" && node.dig(\"vmware\", \"host\", \"type\") == \"vmware_vsphere\"\n end",
"def is_vm?()\n vm=`/sbin/lspci -v | grep -i vmware`\n if vm.size() > 0\n return true\n end\n return false\nend",
"def openvz?(node = __getnode)\n node.dig(\"virtualization\", \"system\") == \"openvz\" && node.dig(\"virtualization\", \"role\") == \"guest\"\n end",
"def needs_host_list?\n vima? || okeanos?\n end",
"def dedicated_hana_vm_region?\n @flavors = @flavors || cloud_admin.compute.flavors\n @flavors\n .select do |f|\n f\n .extra_specs\n .select do |key, value|\n key == \"trait:CUSTOM_HANA_EXCLUSIVE_HOST\" && value == \"required\"\n end\n .length > 0 && f.name.starts_with?(\"hana_\")\n end\n .length > 0\n end",
"def on_cloudstack?\n cloudstack != nil\nend",
"def multivm?\n vms.length > 1\n end",
"def kvm_host?(node = __getnode)\n node.dig(\"virtualization\", \"system\") == \"kvm\" && node.dig(\"virtualization\", \"role\") == \"host\"\n end",
"def cloud_product?\n configured = gem_config :is_cloud_product\n return configured unless configured.nil?\n return @api.api_metadata.organization == \"CLOUD\" if @api.api_metadata.organization\n return true if PSEUDO_CLOUD_GEMS.any? { |pattern| pattern === name }\n return false if NON_CLOUD_GEMS.any? { |pattern| pattern === name }\n services.any? do |service|\n service.namespace =~ /^(::)?Google::Cloud::/\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Determines whether IP address is private (reserved) === Parameters address:: IP address to test (ie '192.168.0.1')
|
def is_private?(address)
[
IPAddr.new('10.0.0.0/8'),
IPAddr.new('172.16.0.0/12'),
IPAddr.new('192.168.0.0/16'),
].any? do |i|
i.include? address
end
end
|
[
"def private_ip_address?\n ip_address? && IpAddress.new(text).private?\n end",
"def is_private(ip)\n\t\tpriv = FALSE\n\t\tif (ip_int(\"10.0.0.0\")..ip_int(\"10.255.255.255\")) === ip_int(ip)\n\t\t\tpriv = TRUE\n\t\telsif (ip_int(\"172.16.0.0\")..ip_int(\"172.31.255.255\")) === ip_int(ip)\n\t\t\tpriv = TRUE\n\t\telsif (ip_int(\"192.168.0.0\")..ip_int(\"192.168.255.255\")) === ip_int(ip)\n\t\t\tpriv = TRUE\n\t\tend\n\t\treturn priv\n\tend",
"def is_on_private_range?(i)\n ipaddr = IPAddr.new(i)\n\n if IPAddr.new('10.0.0.0/8').include?(ipaddr) or IPAddr.new('192.168.0.0/16').include?(ipaddr)\\\n or IPAddr.new('172.16.0.0/12').include?(ipaddr)\n true\n else\n false\n end\nend",
"def is_private_ipv4(ip)\n regexp = /\\A(10\\.|192\\.168\\.|172\\.1[6789]\\.|172\\.2.\\.|172\\.3[01]\\.)/\n ip =~ regexp\nend",
"def check_private_network_segment(options)\n if options.has_key?(:ip)\n addr = options[:ip].split(\".\")\n # except for virbr{0|1} and hostonly network\n if @env[:machine].provider.driver.host_ubuntu?\n return false if addr[2] == '122' || addr[2] == '100' || addr[2] == '123'\n else\n return false if addr[2] == '123'\n end\n end\n true\n end",
"def private_ip?(ip_integer)\n ip_exists_in_range?(323_223_552_0, 323_230_105_5, ip_integer) || ip_exists_in_range?(288_672_972_8, 288_777_830_3, ip_integer) ||\n ip_exists_in_range?(167_772_160, 184_549_375, ip_integer)\n end",
"def ip_reserved?(addr)\n\treturn true if addr%256 ==0 or addr%256 == 255\n\tfalse\nend",
"def is_private_ip(ec2,ip)\n return ec2.instances.filter('private-ip-address', ip) \n end",
"def private_net_checker\n ->(addr) { private_nets_regex.any? { |net| net =~ addr } }\n end",
"def valid_ip?\n if production?\n describe_as_ip == :public\n else\n describe_as_ip.in? :public, :private, :loopback\n end\n end",
"def ip_address?(value)\n !!value.match(/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/)\n end",
"def reserved_net_checker\n ->(addr) { (private_nets_regex + reserved_nets_regex).any? { |net| net =~ addr } }\n end",
"def network_contains_address(address_to_match, ipaddress, iface)\n if ( peer = network[\"interfaces\"][iface][\"addresses\"][ipaddress.to_s][:peer] )\n IPAddress(peer) == IPAddress(address_to_match)\n else\n ipaddress.include? IPAddress(address_to_match)\n end\n end",
"def ip_public?(ip)\n ip_obj = IPAddr.new(ip.text)\n IGNORED_NETWORKS.each do |net|\n return false if net.include? ip_obj\n end\n true\n end",
"def check_ip; end",
"def have_ip?(addr)\n node[:network][:interfaces].map do |i, data|\n data['addresses'].map { |ip, crap| ip == addr }\n end.flatten.include? true\n end",
"def meta_address?\n ip_address == '0.0.0.0'\n end",
"def has_address(interface)\n ip = Facter::Util::IP.get_interface_value(interface, 'ipaddress')\n if ip.nil?\n false\n else\n true\n end\nend",
"def private_ip_address=(value)\n @private_ip_address = value\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Override to disable heartbeat
|
def run
unless @heartbeat_type == :none
super
end
end
|
[
"def shutdown\n\t\tself.stop_heartbeat\n\t\tsuper\n\tend",
"def disable_heartbeat(name, opts = {})\n data, _status_code, _headers = disable_heartbeat_with_http_info(name, opts)\n return data\n end",
"def restart\n\t\tself.stop_heartbeat\n\t\tsuper\n\t\tself.start_heartbeat\n\tend",
"def heartbeat\n end",
"def heartbeat_stop\n @heart.kill\n end",
"def cancel_heartbeat(&blk)\n raise 'This API endpoint cannot be used over HTTP.' unless block_given?\n\n websocket.subscribe :cancelheartbeat, &blk\n end",
"def stop_heartbeat\n\t\t@heartbeat[ :shutdown ] = true\n\t\t@heartbeat.run.join if @heartbeat.alive?\n\tend",
"def heartbeat=(heartbeat)\n @options[:heartbeat] = heartbeat\n end",
"def disable_heartbeat_with_http_info(name, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: HeartbeatApi.disable_heartbeat ...\"\n end\n # verify the required parameter 'name' is set\n if @api_client.config.client_side_validation && name.nil?\n fail ArgumentError, \"Missing the required parameter 'name' when calling HeartbeatApi.disable_heartbeat\"\n end\n # resource path\n local_var_path = \"/v2/heartbeats/{name}/disable\".sub('{' + 'name' + '}', name.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['GenieKey']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'DisableHeartbeatResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: HeartbeatApi#disable_heartbeat\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def stop_timer\n\n # Call base module handler\n super\n\n # Reset state\n\t\t\t@awaiting_confirmation = false\n\t\t\tset_warn_state(false)\n\t\tend",
"def set_heartbeat_interval(opts)\n opts = check_params(opts,[:intervals])\n super(opts)\n end",
"def heartbeat_interval\n @settings[:heartbeat] || @settings[:heartbeat_interval] || 0\n end",
"def raise_heartbeat_event\n raise_event(HeartbeatEvent.new(self))\n end",
"def heartbeat_interval\n @options[:heartbeat_interval]\n end",
"def send_heartbeat\n send_message DCell::Message::Heartbeat.new\n @heartbeat = after(self.class.heartbeat_rate) { send_heartbeat }\n end",
"def keep_alive=(enable); end",
"def disable_polling(reason = nil)\n self.deactivate\n self.deactivation_reason = reason.to_s\n self.deactivated_at = Time.now\n self.save!\n end",
"def disable!\n run(:disable)\n end",
"def heartbeats_enabled?\n @heartbeat_interval && (@heartbeat_interval > 0)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Helper method that will give you a joined pods/metrics query proxy.
|
def metrics
pods.outer_join(:github_pod_metrics).on(:id => :pod_id).join(:cocoadocs_pod_metrics).on(:id => :pod_id)
end
|
[
"def metrics\n pods.join(:github_pod_metrics).on(:id => :pod_id)\n .join(:cocoadocs_pod_metrics).on(:id => :pod_id)\n end",
"def metrics\n pods.join(:github_pod_metrics).on(:id => :pod_id)\n end",
"def afnetworking_github_pod_metrics\n Domain.github_pod_metrics.where(pod_id: afnetworking.id).all\n end",
"def picky_result search, pods, params, &rendering\n query = params[:query]\n \n results = search.interface.search query, params[:amount] || params[:ids] || 20, params[:'start-at'] || params[:offset] || 0\n results = results.to_hash\n results.extend Picky::Convenience\n \n CocoapodSearch.track_search query, results.total\n \n results.amend_ids_with results.ids.map { |id| rendering.call pods[id] }\n \n results\n end",
"def fetch_pods\n @release.clients.flat_map do |client, query|\n pods = SamsonKubernetes.retry_on_connection_errors { client.get_pods(query).fetch(:items) }\n pods.map! { |p| Kubernetes::Api::Pod.new(p, client: client) }\n end\n end",
"def afnetworking_cocoadocs_pod_metrics\n Domain.cocoadocs_pod_metrics.where(pod_id: afnetworking.id).all\n end",
"def pods\n @pods ||= new_group('Pods')\n end",
"def joined\n meta(joined: true)\n end",
"def run_queries\n metrics_in_order.each do |metric|\n query_method = \"query_#{metric}\"\n result = send(query_method)\n self[metric] = result.count\n end\n end",
"def search_metrics q, args={}\n raise Store::Error, \"Unable to connect to #{@origin_id} backend at #{@base_url}\" unless is_up?\n\n\t\t# TODO Pending redis pagination logic\n return [] if args[:page] and args[:page].to_i > 1\n\n r = redis_conn\n keys = r.keys \"#{REDIS_KEY}:#{@origin_id}#{q}\"\n keys.map!{|x|x.split(\":\").last}\n keys.map!{|x| \"#{@origin_id}#{SEP}#{x}\"}\n keys\n end",
"def query(metric_name, options={})\n key = build_key(metric_name)\n parse_time_range(options)\n key << assemble_for(options)\n if options[:id]\n key = \"dnid:#{options[:id]}\"\n real_key = DulyNoted.redis.get key\n if options[:meta_fields]\n options[:meta_fields].collect! { |x| x.to_s }\n result = {}\n options[:meta_fields].each do |field|\n result[field] = DulyNoted.redis.hget real_key, field\n end\n results = [result]\n else\n results = [DulyNoted.redis.hgetall(real_key)]\n end\n else\n keys = find_keys(key)\n grab_results = Proc.new do |metric|\n if options[:meta_fields]\n options[:meta_fields].collect! { |x| x.to_s }\n result = {}\n options[:meta_fields].each do |field|\n result[field] = DulyNoted.redis.hget metric, field\n end\n result\n else\n DulyNoted.redis.hgetall metric\n end\n end\n results = []\n if options[:time_start] && options[:time_end]\n keys.each do |key|\n results += DulyNoted.redis.zrangebyscore(key, options[:time_start].to_f, options[:time_end].to_f).collect(&grab_results)\n end\n else\n keys.each do |key|\n results += DulyNoted.redis.zrange(key, 0, -1).collect(&grab_results)\n end\n end\n end\n return results\n end",
"def custom_queries\n @custom_queries ||= ::Valkyrie::Persistence::CustomQueryContainer.new(query_service: self)\n end",
"def queries\n QUERIES.values.flatten + subtotal_queries + groups!\n end",
"def pods\n groups.find { |g| g.name == 'Pods' }\n end",
"def custom_queries\n @custom_queries ||= ::Valkyrie::Persistence::CustomQueryContainer.new(query_service: self)\n end",
"def db_query_metrics; end",
"def join(other, join_definition, relation_aliases = {})\n joined = index.join(other.index, join_definition, relation_aliases)\n new(joined, other.index.aliases(joined))\n end",
"def db_query_metric_set; end",
"def get_active_metrics(from)\n @metric_svc.get_active_metrics(from)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Look up an array of the first count tag IDs with the specified batch URN. Output parameters tagIds (array of string, `E12345678912345678`) ... Array of RFID tag identifiers
|
def get_query_tags(batch_urn,
count = 100000)
# prepare query url
_query_builder = Configuration.base_uri.dup
_query_builder << '/rest/tag/queryTags'
_query_builder = APIHelper.append_url_with_query_parameters _query_builder, {
'batchUrn' => batch_urn,
'count' => count
}
_query_url = APIHelper.clean_url _query_builder
# prepare headers
_headers = {
'accept' => 'application/json'
}
# prepare and execute HttpRequest
_request = @http_client.get _query_url, headers: _headers
BasicAuth.apply(_request)
_context = execute_request(_request)
# validate response against endpoint and global error codes
if _context.response.status_code == 400
raise APIException.new 'Unexpected error in API call. See HTTP response body for details.', _context
elsif _context.response.status_code == 401
raise APIException.new '', _context
end
validate_response(_context)
# return appropriate response type
decoded = APIHelper.json_deserialize(_context.response.raw_body)
return QueryTagsResponseModel.from_hash(decoded)
end
|
[
"def add_tag_return_IDs(tag)\n # Split and strip the tags\n tags = tag.split(\",\").collect{|x| x.strip}\n i = 0\n iDs = []\n while i < tags.count do\n # Check if tag exist, if not - add it\n if Teg.find_by_teg(tags[i]).nil?\n\tTeg.new(:teg => tags[i]).save\n end\n # Insert into array the id of the tag\n iDs << Teg.find_by_teg(tags[i]).id\n i +=1\n end\n # return the IDs\n return iDs\n end",
"def find_tag_id(tags)\n tagIdList = []\n i = 0\n # Scans the database in order to find all the tags id by tag\n while i < tags.count do\n t = Teg.find_by_teg(tags[i].strip)\n # If the tag exists, puts his id into array, else puts nil\n if !t.nil?\n\ttagIdList << t.id\n else\n\ttagIdList << nil\n end\n i+=1\n end\n # Returns the list of tags id\n return tagIdList\n end",
"def _tag_ids assoc_table, tag\n\t\th \t\t= {:assoc_table => _tag(assoc_table)}\n\t\ttags \t= _tag2 tag\n\t\th[:tid] = tags unless tags.empty?\n\t\tSdb[:_taga].filter(h).map(:assoc_id)\n\tend",
"def data_tag_ids table_name, tag\n\t\th \t\t\t= {:table_id => _tag(table_name)}\n\t\ttags \t\t= _tag2 tag\n\t\th[:tag_id]\t= tags unless tags.empty?\n\t\tSdb[:data_tag_assoc].filter(h).map(:index_id)\n\tend",
"def tag_id_lookup(record)\n tag_ids = []\n tag_ids << persister.configuration_architectures.lazy_find(record[\"architecture_id\"].to_s) if record[\"architecture_id\"]\n tag_ids << persister.configuration_compute_profiles.lazy_find(record[\"compute_profile_id\"].to_s) if record[\"compute_profile_id\"]\n tag_ids << persister.configuration_domains.lazy_find(record[\"domain_id\"].to_s) if record[\"domain_id\"]\n tag_ids << persister.configuration_environments.lazy_find(record[\"environment_id\"].to_s) if record[\"environment_id\"]\n tag_ids << persister.configuration_realms.lazy_find(record[\"realm_id\"].to_s) if record[\"realm_id\"]\n tag_ids\n end",
"def findBarcodeSequence(outputDirectory, barcodeTag)\n barcode = \"\"\n if barcodeTag == nil || barcodeTag.empty?()\n return \"\"\n end\n\n barcodeLabelFile = getBarcodeDefinitionFileName(outputDirectory)\n puts \"Looking for barcode labels in : \" + barcodeLabelFile\n\n lines = IO.readlines(barcodeLabelFile)\n\n lines.each do |line|\n tokens = line.split(\",\")\n if tokens[0].strip.eql?(barcodeTag)\n barcode = tokens[1].strip\n end\n end\n\n if barcode.empty?()\n raise \"Invalid barcode tag specified\"\n else\n return barcode\n end\n end",
"def set_tag_ids nids\n # Ensure that the user's tags are all and only those in nids\n oids = tagging_tags.pluck :id\n\n # Add new tags as necessary\n (nids - oids).each { |tagid| assert_tagging tagid, @tagging_user_id }\n\n # Remove tags as nec.\n (oids - nids).each { |tagid| refute_tagging tagid, @tagging_user_id }\n end",
"def determine_known_ids(feature_directory, tag_prefix = '@test_case_', id_column_name = 'test_case_id')\n known_ids = []\n\n found_tagged_objects = scan_for_tagged_tests(feature_directory, tag_prefix, id_column_name).collect { |result| result[:object] }\n\n found_tagged_objects.each do |element|\n if element.is_a?(CukeModeler::Row)\n row_id = row_id_for(element, id_column_name)\n known_ids << row_id if well_formed_sub_id?(row_id)\n else\n known_ids << test_id_for(element)\n end\n end\n\n known_ids\n end",
"def determine_known_ids(feature_directory, tag_prefix = '@test_case_', id_column_name = 'test_case_id')\n known_ids = []\n\n found_tagged_objects = scan_for_tagged_tests(feature_directory, tag_prefix, id_column_name)\n .collect { |result| result[:object] }\n\n found_tagged_objects.each do |element|\n if element.is_a?(CukeModeler::Row)\n row_id = row_id_for(element, id_column_name)\n known_ids << row_id if well_formed_sub_id?(row_id)\n else\n known_ids << test_id_for(element)\n end\n end\n\n known_ids\n end",
"def identifier_to_uids(identifier, opts = {})\n 2.times do\n results = search do |params|\n params.fq('identifier_ssim', identifier)\n end\n\n return results['response']['docs'].map { |doc| doc['id'] } if results['response']['numFound'].positive?\n sleep opts[:retry_with_delay] if opts[:retry_with_delay].present?\n end\n []\n end",
"def sr_get_tags(sr_uuid)\n sr_opaqueref = sr_get_ref(sr_uuid)\n sr_opaqueref.key?('Value') ? @connect.call('SR.get_tags', @session, vdi_get_ref(vdi_uuid)['Value']) : sr_opaqueref\n end",
"def tag_count( tagged_tickets )\n\t\ttag_count_array = []\n\t\tticket_array = tagged_tickets\n\t\tticket_array.each do | ticket |\n\t\t\t count_exists = tag_count_exists?( ticket[ 'tag' ], tag_count_array )\n\t\t\tif count_exists[ 'exists' ]\n\t\t\t\ttag_count_array[ count_exists[ 'matched_index' ] ][ 'count' ] += 1\n\t\t\t\ttag_count_array[ count_exists[ 'matched_index' ] ][ 'ticket_ids' ] |= [ ticket[ 'id' ] ]\n\t\t\telse\n\t\t\t\tnew_tag_count = create_count_hash( ticket[ 'tag' ], ticket[ 'id' ])\n\t\t\t\ttag_count_array.push( new_tag_count )\n\t\t\tend\n\t\tend\n\t\t\n\t\treturn tag_count_array\n\tend",
"def first_96_tags(tags)\n Array.new(96) { |i| tags[(i % tags.size)] }\n end",
"def get_tagid_by_names tagname, groupname = \"NETWORKTYPE\"\n\t\tselector = {:name => tagname}\n\t\ttaggroup = CmpTaggroup.find_by name: groupname\n\t\tselector[:groupid]= taggroup.id \n\t\ttags = CmpTag.where(selector).all\n\n\t\ttags #[1].id\n\tend",
"def sr_search_by_tag(tag)\n all_sr = sr_list('include', true)\n all_sr['Value'].select! do |sr_uuid|\n sr_get_tags(sr_uuid)['Value'].include?(tag)\n end\n all_sr\n end",
"def select_taguchi_array\n closest = 0\n [8, 16, 32, 64, 128, 256, 512].each do |n|\n if @genes_per_group <= n - 1\n closest = n\n break\n end\n end\n file_name = \"L#{closest}\"\n @taguchi_array = load_array_from_file file_name\n end",
"def get_tags(tag)\n # Get a list of all tags wihtout the priority\n tags = search_by_tags(tag).collect { |df| df.tags.collect { |_, t| t } }.flatten.sort\n # Count how many times each tag appears and sort inversely\n tags_count = tags.uniq.collect { |t| [tags.count(t), t] }.sort { |a, b| b[0] <=> a[0] }\n # Remove the counter\n tags_count.collect { |_, t| t }\n end",
"def recommended_search_tags(id)\n receipts = Receipt.where(buyer_id: id).order(\"created_at DESC\").limit(20)\n search_tags = {}\n receipts.each do |receipt|\n receipt.item_tags.each do |tag|\n if search_tags.has_key?(tag)\n current_val = search_tags[tag]\n search_tags[tag] = current_val + 1\n else\n search_tags[tag] = 1\n end\n end\n end\n if search_tags.length >= 4\n return Hash[search_tags.sort_by { |k,v| v }.reverse![0..3]]\n else\n return Hash[search_tags.sort_by { |k, v| v }.reverse!]\n end\n end",
"def search_by_product_ids(ids)\n msb_numbers = []\n\n ids.each do |id|\n j = search(id)\n msb = j['b'].collect { |e| e['Id'] }.map { |e| e.downcase }\n msb_numbers.concat(msb)\n end\n\n msb_numbers\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get a message to a single numeric tag code. Idempotent Behaviour This endpoint is idempotent and will respond with an appropriate HTTP status code to indicate the actual result 200 OK message available 400 BAD_REQUEST problem occurred, check message parameter for detailed information 401 UNAUTHORIZED user not authorized Input HTTP Headers: HTTP Basic Authorization (as specified above) Accept language (as specified above) Input parameters: tagCode (required, number, `0`) ... Result code of a tag action Output parameters: code (Number, `0`) ... Indicates the result code of this call (see `result codes`) message (string, `verified`) ... Result message in `AcceptLanguage` (see `Multi language support`)
|
def create_get_single_tag_code_message(body)
# prepare query url
_query_builder = Configuration.base_uri.dup
_query_builder << '/rest/tag/message'
_query_url = APIHelper.clean_url _query_builder
# prepare headers
_headers = {
'accept' => 'application/json',
'content-type' => 'application/json; charset=utf-8'
}
# prepare and execute HttpRequest
_request = @http_client.post _query_url, headers: _headers, parameters: body.to_json
BasicAuth.apply(_request)
_context = execute_request(_request)
# validate response against endpoint and global error codes
if _context.response.status_code == 400
raise APIException.new 'Unexpected error in API call. See HTTP response body for details.', _context
elsif _context.response.status_code == 401
raise APIException.new '', _context
end
validate_response(_context)
# return appropriate response type
decoded = APIHelper.json_deserialize(_context.response.raw_body)
return GetSingleTagCodeMessageResponseModel.from_hash(decoded)
end
|
[
"def message\n RESPONSE_MESSAGES[code]\n end",
"def message_id_tag(params={:id => 0, :text => nil, :location=>:body, :action=>:generate})\n#puts \"**** params=#{params}\"\n case params[:action]\n when :generate\n if params[:location] == :body\n return \"##{params[:id]}\"\n else\n return \"(SimJos message ##{params[:id]})\"\n end\n when :find\n if params[:location] == :body\n params[:text] =~ /[\\s\\(\\[]*!([0-9]*)/ || params[:text] =~ /confirm +[!#]([0-9]*)/i\n return $1 ? $1.to_i : nil\n else\n params[:text] =~ /SimJos message #([0-9]{1,9})\\)/i\n return $1 ? $1.to_i : nil\n end\n when :confirm_tag # This is for use in an explanation of how to confirm\n return \"!#{params[:id]}\"\n end\n end",
"def message_id_tag(params={:id => 0, :text => nil, :location=>:body, :action=>:generate})\n tag_string = SiteSetting.message_id_string\n#puts \"**** params=#{params}\"\n case params[:action]\n when :generate\n if params[:location] == :body\n return \"##{params[:id]}\"\n else\n return \"(#{tag_string} ##{params[:id]})\"\n end\n when :find\n if params[:location] == :body\n params[:text] =~ /[\\s\\(\\[]*!([0-9]+)/ || params[:text] =~ /confirm +[!#]([0-9]+)/i\n return $1 ? $1.to_i : nil\n else\n params[:text] =~ Regexp.new(tag_string + '\\s#([0-9]{1,9})\\)', true)\n return $1 ? $1.to_i : nil\n end\n when :confirm_tag # This is for use in an explanation of how to confirm\n return \"!#{params[:id]}\"\n end\n end",
"def response_code_message(response_code)\n case response_code\n when 1\n \"Success\"\n when 2\n \"Error\"\n when 3\n \"Server Too Busy\"\n when 4\n \"Protocol Error\"\n when 5\n \"Operation Not Supported\"\n when 6\n \"Recursion Count Too High\"\n when 7\n \"Server Read-only\"\n when 100\n \"Handle Not Found\"\n when 101\n \"Handle Already Exists\"\n when 102\n \"Invalid Handle\"\n when 200\n \"Values Not Found\"\n when 201\n \"Value Already Exists\"\n when 202\n \"Invalid Value\"\n when 300\n \"Out of Date Site Info\"\n when 301\n \"Server Not Responsible\"\n when 302\n \"Service Referral\"\n when 303\n \"Prefix Referral\"\n when 400\n \"Invalid Admin\"\n when 401\n \"Insufficient Permissions\"\n when 402\n \"Authentication Needed\"\n when 403\n \"Authentication Failed\"\n when 404\n \"Invalid Credential\"\n when 405\n \"Authentication Timed Out\"\n when 406\n \"Authentication Error\"\n when 500\n \"Session Timeout\"\n when 501\n \"Session Failed\"\n when 502\n \"Invalid Session Key\"\n when 504\n \"Invalid Session Setup Request\"\n when 505\n \"Session Duplicate Msg Rejected\"\n else\n \"Response Code Message Missing!\"\n end\n end",
"def get_tag_value_int (tag_path)\n\n $test_logger.log(\"Get tag value in integer #{tag_path}\")\n\n #Get tag text and data type\n tag_val, data_type = get_tag_value tag_path, true\n\n #Parse int value\n int_val = 0\n if data_type == DataType::HEX\n int_val = tag_val.hex\n elsif data_type == DataType::DEC || data_type == DataType::DEC_BIG\n int_val = tag_val.to_i\n end\n\n #Return int value\n int_val\n end",
"def voip_response_code\n voip_response(:response_code)\n end",
"def reply_code\n return \"No response.\" if response.nil?\n return (not response.first.last.kind_of?(Hash) or response.first.last[\"reply_code\"].nil?) ? \"Unexpected response hash.\" : response.first.last[\"reply_code\"] if response.instance_of?(Hash)\n response_match = response.match(/\\<reply-code\\>(.+)\\<\\/reply-code\\>/) if response.instance_of?(String)\n return (response_match.nil?) ? \"Unexpected response string.\" : response_match[1] if response.instance_of?(String)\n return \"Unexpected response type.\"\n end",
"def send_message_by_tag(tag, messaging_channel, message)\n Utils.assert_type(tag, \"tag\", Hash)\n Utils.assert_keys_present(messaging_channel, %i[channel number], \"messaging_channel\")\n Utils.assert_keys_present(message, [:body], \"message\")\n\n channel = Utils.get_enum_value(\n P::MessagingChannel, messaging_channel.fetch(:channel, \"UNSPECIFIED\"), \"MESSAGING_CHANNEL\"\n )\n\n command = P::SendMessageTagCommand.new(\n channel_number: P::MessagingChannelNumber.new(number: messaging_channel[:number], channel: channel),\n tag: { key: tag[:key], value: { value: tag[:value] } },\n message: Utils::OutgoingMessageSerializer.serialize(message)\n )\n send_command(:send_message_tag, command)\n end",
"def get_response_code\n @result_code\n end",
"def token_get_message(webhook_token, webhook_id, message_id)\n Discordrb::API.request(\n :webhooks_wid_messages_mid,\n webhook_id,\n :get,\n \"#{Discordrb::API.api_base}/webhooks/#{webhook_id}/#{webhook_token}/messages/#{message_id}\"\n )\n end",
"def get_message(message_code)\n message = case message_code\n when :save_ok then 'File saved.'\n else 'This message code was not recognised.'\n end\n end",
"def get_message_status(message_id)\n generate_token\n options = { body: {}, headers: { \"Authorization\" => \"Bearer #{@token}\" } }\n response = HTTParty.get(\"https://api.telstra.com/v1/sms/messages/#{message_id}\", options)\n return JSON.parse(response.body)\n end",
"def reply_code\n root['ReplyCode'].to_i\n end",
"def parse_result(code, body, message, nfg_method)\n return_value = Hash.new\n if code == '200'\n parsed = REXML::Document.new(body)\n # Build return hash parsing XML response\n if parsed.root.nil?\n return_value['StatusCode'] = 'MissingParameter'\n return_value['Message'] = body\n return_value['ErrorDetails'] = nil\n else\n return_value = parsed.root.elements['soap:Body'].elements[\"#{nfg_method}Response\"].elements[\"#{nfg_method}Result\"]\n end\n else\n return_value['StatusCode'] = 'UnexpectedError'\n return_value['Message'] = message\n return_value['ErrorDetails'] = body\n end\n return_value\n end",
"def get_by_code(code)\n HttpClient::Preconditions.assert_class('code', code, String)\n r = @client.request(\"/harmonization/codes/#{CGI.escape(code)}\").get\n ::Io::Flow::V0::Models::HsCode.new(r)\n end",
"def code\n @response.code.to_i\n end",
"def getTypeFromCode(code)\n if ERROR_CODES.has_key? code\n return ERROR_CODES[code]\n elsif MESSAGE_CODES.has_key? code\n return MESSAGE_CODES[code]\n end\n return nil\n end",
"def get_tag(project_id, tag_id)\n get \"projects/#{project_id}/tags/#{tag_id}\"\n end",
"def get_message\n get_status[:message]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get application data from tags, which returns data encoded on the tags. This function also returns the lock state of the application data. Idempotent Behaviour This endpoint is idempotent and will respond with an appropriate HTTP status code to indicate the actual result 200 OK tags found and result available (also returned if only a subset of tags have this keys) 400 BAD_REQUEST problem occurred, check message parameter for detailed information 401 UNAUTHORIZED user not authorized 404 NOT_FOUND no matching tags found or none the tags found does have keys with given name Input HTTP Headers: HTTP Basic Authorization (as specified above) Accept language (as specified above) Input parameters: tagIds (required, string, `0EEEE100000001`) ... Identifier for each tag to be queried appId (required, string, `ndef`) ... Application ID which references the data Output parameters: code (Number, `0`) ... Indicates the result code of this call (see `result codes`) tagId (string, `0EEEE100000001`) ... Tag ID tagCode (Number, `0`) ... Indicates if the result code for this tag (see `Possible result codes for a tag actions`) value (string, `AQIDBAUGBwgJCgsM`) ... Application data (Base64 encoded) locked (boolean, `false`) ... Tag has been made readonly
|
def create_get_application_data_from_tags(body)
# prepare query url
_query_builder = Configuration.base_uri.dup
_query_builder << '/rest/tag/value'
_query_url = APIHelper.clean_url _query_builder
# prepare headers
_headers = {
'accept' => 'application/json',
'content-type' => 'application/json; charset=utf-8'
}
# prepare and execute HttpRequest
_request = @http_client.post _query_url, headers: _headers, parameters: body.to_json
BasicAuth.apply(_request)
_context = execute_request(_request)
# validate response against endpoint and global error codes
if _context.response.status_code == 400
raise APIException.new 'Unexpected error in API call. See HTTP response body for details.', _context
elsif _context.response.status_code == 401
raise APIException.new '', _context
elsif _context.response.status_code == 404
raise APIException.new 'Unexpected error in API call. See HTTP response body for details.', _context
end
validate_response(_context)
# return appropriate response type
decoded = APIHelper.json_deserialize(_context.response.raw_body)
return GetApplicationDataFromTagsResponseModel.from_hash(decoded)
end
|
[
"def read\n return unless locks\n\n result = locks.find(data_bag_id)\n\n result.to_hash if result\n end",
"def create_get_keys_used_for_tag_authentication(body)\n\n # prepare query url\n _query_builder = Configuration.base_uri.dup\n _query_builder << '/rest/tag/key'\n _query_url = APIHelper.clean_url _query_builder\n\n # prepare headers\n _headers = {\n 'accept' => 'application/json',\n 'content-type' => 'application/json; charset=utf-8'\n }\n\n # prepare and execute HttpRequest\n _request = @http_client.post _query_url, headers: _headers, parameters: body.to_json\n BasicAuth.apply(_request)\n _context = execute_request(_request)\n\n # validate response against endpoint and global error codes\n if _context.response.status_code == 400\n raise APIException.new 'Unexpected error in API call. See HTTP response body for details.', _context\n elsif _context.response.status_code == 401\n raise APIException.new '', _context\n elsif _context.response.status_code == 404\n raise APIException.new 'Unexpected error in API call. See HTTP response body for details.', _context\n end\n validate_response(_context)\n\n # return appropriate response type\n decoded = APIHelper.json_deserialize(_context.response.raw_body)\n return GetKeysUsedForTagAuthenticationResponseModel.from_hash(decoded)\n end",
"def find(secret_name, tags = [], decrypt = true)\n tags = [tags] unless tags.is_a? Array\n\n return_data = []\n @data.each do |secret_data|\n if (secret_data[:name] == secret_name)\n next unless tags.empty? || (tags - secret_data[:tags]).empty?\n # If no tags or secret has all tags\n\n this_secret = secret_data.dup\n if decrypt\n this_secret[:secret] = @@master_key.decryptSecret(@@master_key.class.hex_to_bin this_secret[:secret])\n end\n\n return_data.push(this_secret)\n end\n end\n return_data\n end",
"def virtualApps_locked\n raise \"virtualApps_locked: cache lock not held\" unless @cacheLock.sync_locked?\n\n #\n # Not supported in v2.0 or v2.5\n #\n if @v2\n @virtualApps = {}\n @virtualAppsByMor = {}\n end\n\n return(@virtualApps) if @virtualApps\n\n logger.info \"MiqVimInventory.virtualApps_locked: loading VirtualApp cache for #{@connId}\"\n begin\n @cacheLock.sync_lock(:EX) if (unlock = @cacheLock.sync_shared?)\n\n ra = getMoPropMulti(inventoryHash_locked['VirtualApp'], @propMap[:VirtualApp][:props])\n\n @virtualApps = {}\n @virtualAppsByMor = {}\n ra.each do |rpObj|\n addObjHash(:VirtualApp, rpObj)\n end\n ensure\n @cacheLock.sync_unlock if unlock\n end\n logger.info \"MiqVimInventory.virtualApps_locked: loaded VirtualApp cache for #{@connId}\"\n\n @virtualApps\n end",
"def get_aab_info(app_name)\n begin\n response = connection.get(aab_info_url(app_name)) do |request|\n request.headers[AUTHORIZATION] = \"Bearer \" + @auth_token\n end\n rescue Faraday::ResourceNotFound\n UI.user_error!(\"#{ErrorMessage::INVALID_APP_ID}: #{app_name}\")\n end\n\n AabInfo.new(response.body)\n end",
"def get_from_data_bags_cache(data_bag)\n encrypted_data_bags[data_bag]\n end",
"def get_from_data_bags_cache(data_bag)\n encrypted_data_bags[data_bag]\n end",
"def content_by_tag(tags)\n x = tags.gsub(\" \", \"/\")\n JSON.parse(self.class.get(\"/search?tag=\" + \"#{x}\" + \"#{@token}\").body)\n end",
"def key_access\n appkey = Applikation.find_by(appkey: params[:appkey])\n unless appkey\n render json: { error: \"invalid appkey\"}, status: :unauthorized\n end\n end",
"def tags\n get.tagGuids\n end",
"def tagList()\n http, req = initReq(\"tags/\")\n JSON.parse(http.request(req).body)\nend",
"def get_all\n opts = @options.merge(\n headers: headers(auth: true),\n )\n\n req = self.class.get '/application', opts\n handle_status_code req\n\n self.parse(req)['d']\n end",
"def get_tag_info(id)\n \tJSON.parse(Typhoeus::Request.get(\"https://app.asana.com/api/1.0/tasks/\" + id + \"/tags\", userpwd: $key).body)\n end",
"def gp_get_status(scope, query_aid = [])\n scope_byte = { :issuer_sd => 0x80, :apps => 0x40, :files => 0x20,\n :files_modules => 0x10 }[scope]\n data = Asn1Ber.encode [{:class => :application, :primitive => true,\n :number => 0x0F, :value => query_aid}]\n apps = [] \n first = true # Set to false after the first GET STATUS is issued.\n loop do\n raw = iso_apdu :cla => 0x80, :ins => 0xF2, :p1 => scope_byte,\n :p2 => (first ? 0 : 1), :data => [0x4F, 0x00]\n if raw[:status] != 0x9000 && raw[:status] != 0x6310 \n raise Smartcard::Iso::ApduException, raw\n end\n \n offset = 0\n loop do\n break if offset >= raw[:data].length\n aid_length, offset = raw[:data][offset], offset + 1\n app = { :aid => raw[:data][offset, aid_length] }\n offset += aid_length\n \n if scope == :issuer_sd\n lc_states = { 1 => :op_ready, 7 => :initialized, 0x0F => :secured,\n 0x7F => :card_locked, 0xFF => :terminated }\n lc_mask = 0xFF\n else\n lc_states = { 1 => :loaded, 3 => :installed, 7 => :selectable,\n 0x83 => :locked, 0x87 => :locked }\n lc_mask = 0x87\n end\n app[:lifecycle] = lc_states[raw[:data][offset] & lc_mask]\n\n permission_bits = raw[:data][offset + 1]\n app[:permissions] = Set.new()\n [[1, :mandated_dap], [2, :cvm_management], [4, :card_reset],\n [8, :card_terminate], [0x10, :card_lock], [0x80, :security_domain],\n [0xA0, :delegate], [0xC0, :dap_verification]].each do |mask, perm|\n app[:permissions] << perm if (permission_bits & mask) == mask\n end\n offset += 2\n \n if scope == :files_modules\n num_modules, offset = raw[:data][offset], offset + 1\n app[:modules] = []\n num_modules.times do\n aid_length = raw[:data][offset]\n app[:modules] << { :aid => raw[:data][offset + 1, aid_length] }\n offset += 1 + aid_length \n end\n end\n \n apps << app\n end\n break if raw[:status] == 0x9000\n first = false # Need more GET STATUS commands.\n end\n apps\n end",
"def get_devices_by_tag(app_id, tag)\n get \"/application/#{app_id}/tag/#{tag}\"\n end",
"def application_details\n response = client.as(client.app_secret).execute(\n method: :get,\n path: \"/a/#{app_id}\",\n auth_method: HttpClient::AuthMethod::BASIC\n )\n ApplicationDetail.new(**response)\n end",
"def app_by_tag(tag)\n manifest[:applications][tag]\n end",
"def lookup_data\n \n # Note: At least one query parameter is required\n render :json => {\n :success => false,\n :message => \"No query parameters\",\n :apps_data => []\n } unless request.query_parameters\n \n # Get query parameters\n query = get_query\n \n # Get list of fields to return\n fields = get_fields\n \n # Get list of fields to remove\n without = get_without_fields\n\n # Check if sorting method is specified\n sort_field = get_sorting('popularity_weight')\n \n # If the limit is specified set it otherwise default to 100\n limit_num = get_limit\n\n apps = AppData.where(query)\n .sort(sort_field)\n .fields(fields)\n .limit(limit_num)\n .all\n \n # Apply interests weighting if interests exist \n apps = weight_interests(apps, request.query_parameters['interests'])\n \n # Return result as json\n render :json => {\n :success => true,\n :message => \"Success\",\n :apps_data => apps.as_json(:only => fields, :except => without)\n }\n \n end",
"def tags\n _get(\"/query/image/tags\") { |json| json }\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Look up an array of the first count batchUrns with the specified customer PO. NOTE: Only one customerPO can be specified. Output parameters batchUrns (array of string, `urn:uuid:smartracgroup:batch:99990001`) ... Array of batch URNs
|
def get_query_batches(customer_po,
count = 100000)
# prepare query url
_query_builder = Configuration.base_uri.dup
_query_builder << '/rest/tag/queryBatches'
_query_builder = APIHelper.append_url_with_query_parameters _query_builder, {
'customerPO' => customer_po,
'count' => count
}
_query_url = APIHelper.clean_url _query_builder
# prepare headers
_headers = {
'accept' => 'application/json'
}
# prepare and execute HttpRequest
_request = @http_client.get _query_url, headers: _headers
BasicAuth.apply(_request)
_context = execute_request(_request)
# validate response against endpoint and global error codes
if _context.response.status_code == 400
raise APIException.new 'Unexpected error in API call. See HTTP response body for details.', _context
elsif _context.response.status_code == 401
raise APIException.new '', _context
end
validate_response(_context)
# return appropriate response type
decoded = APIHelper.json_deserialize(_context.response.raw_body)
return QueryBatchesResponseModel.from_hash(decoded)
end
|
[
"def batch_path\n if @discovery_document['batchPath']\n return @batch_path ||= (\n self.document_base.join(Addressable::URI.parse('/' +\n @discovery_document['batchPath']))\n ).normalize\n else\n return nil\n end\n end",
"def send_batch(batch)\n smarty_request = Request.new\n\n return if batch.empty?\n\n converted_lookups = remap_keys(batch.all_lookups)\n\n if batch.size > 1\n smarty_request.payload = @serializer.serialize(converted_lookups)\n else\n smarty_request.parameters = converted_lookups[0]\n end\n\n response = @sender.send(smarty_request)\n\n raise response.error if response.error\n\n results = @serializer.deserialize(response.payload)\n results = [] if results.nil?\n assign_results_to_lookups(batch, results)\n end",
"def send_batch(batch)\n smarty_request = Request.new\n\n return if batch.empty?\n\n converted_lookups = remap_keys(batch.all_lookups)\n\n if batch.size > 1\n smarty_request.payload = @serializer.serialize(converted_lookups)\n else\n smarty_request.parameters = converted_lookups[0]\n end\n\n response = @sender.send(smarty_request)\n\n raise response.error if response.error\n\n candidates = @serializer.deserialize(response.payload)\n candidates = [] if candidates.nil?\n\n assign_candidates_to_lookups(batch, candidates)\n end",
"def batch_one\n @batch_one ||= begin\n response = client.search.call(operation, message: query)\n records = response_records(response, response_type)\n @records_found = response_return(response, response_type)[:records_found].to_i\n @records_retrieved = records.count\n @query_id = response_return(response, response_type)[:query_id].to_i\n records\n end\n end",
"def find_batchid\n parse(conf['BATCH']['batchid']).strip\n end",
"def request_uri\n if @calls.nil? || @calls.empty?\n raise BatchError, 'Cannot make an empty batch request'\n end\n # All APIs have the same batch path, so just get the first one.\n return @calls.first[1].api_method.api.batch_path\n end",
"def send_batch_request(batch)\n post_data = batch.to_json\n resp = RestClient.post(@url, post_data, content_type: 'application/json', user_agent: \"syncano-ruby-#{Syncano::VERSION}\")\n if resp.nil? || resp.body.nil? || resp.body.empty?\n raise Jimson::ClientError::InvalidResponse.new\n end\n\n return resp.body\n end",
"def findClothesWithBatchFolder(num,batch_folder)\n clothes =[]\n Clothing.where(number: num).each do |clothing|\n clothing.batch_information.each do |batch_type|\n if batch_type.include?(batch_folder)\n clothes.push(clothing)\n break\n end\n end\n end\n return clothes\n end",
"def list_batch_subscribe(batch, double_optin=false, update_existing=false, replace_interests=true)\n self.class.post(VERSION,\n :query => build_query('listBatchSubscribe',\n {:batch => batch,\n :double_optin => double_optin,\n :update_existing => update_existing,\n :replace_interests => replace_interests}))\n end",
"def commit_batch(arg)\n path_to_batch = \"\"\n #they passed a batch\n if arg.kind_of?(CnpBatchRequest) then\n path_to_batch = arg.get_batch_name\n if((au = arg.get_au_batch) != nil) then \n # also commit the account updater batch\n commit_batch(au)\n end\n elsif arg.kind_of?(CnpAUBatch) then\n path_to_batch = arg.get_batch_name\n elsif arg.kind_of?(String) then\n path_to_batch = arg\n else\n raise RuntimeError, \"You entered neither a path nor a batch. Game over :(\"\n end\n #the batch isn't closed. let's help a brother out\n if (ind = path_to_batch.index(/\\.closed/)) == nil then\n if arg.kind_of?(String) then\n new_batch = CnpBatchRequest.new\n new_batch.open_existing_batch(path_to_batch)\n new_batch.close_batch()\n path_to_batch = new_batch.get_batch_name\n # if we passed a path to an AU batch, then new_batch will be a new, empty batch and the batch we passed\n # will be in the AU batch variable. thus, we wanna grab that file name and remove the empty batch.\n if(new_batch.get_au_batch != nil) then\n File.remove(path_to_batch)\n path_to_batch = new_batch.get_au_batch.get_batch_name\n end \n elsif arg.kind_of?(CnpBatchRequest) then\n arg.close_batch()\n path_to_batch = arg.get_batch_name\n elsif arg.kind_of?(CnpAUBatch) then\n arg.close_batch()\n path_to_batch = arg.get_batch_name \n end\n ind = path_to_batch.index(/\\.closed/)\n end\n transactions_in_batch = path_to_batch[ind+8..path_to_batch.length].to_i\n\n # if the cnp request would be too big, let's make another!\n if (@num_total_transactions + transactions_in_batch) > @MAX_NUM_TRANSACTIONS then\n finish_request\n initialize(@options)\n create_new_cnp_request\n else #otherwise, let's add it line by line to the request doc\n # @num_batch_requests += 1\n #how long we wnat to wait around for the FTP server to get us a response\n @RESPONSE_TIME_OUT += 90 + (transactions_in_batch * 0.25)\n #don't start looking until there could possibly be a response\n @POLL_DELAY += 30 +(transactions_in_batch * 0.02)\n @num_total_transactions += transactions_in_batch\n # Don't add empty batches\n @num_batch_requests += 1 unless transactions_in_batch.eql?(0)\n File.open(@path_to_batches, 'a+') do |fo|\n File.foreach(path_to_batch) do |li|\n fo.puts li\n end\n end\n \n File.delete(path_to_batch)\n end\n end",
"def query_batches(options={}) path = \"/api/v2/batches\"\n get(path, options, AvaTax::VERSION) end",
"def next_batch\n return batch_one if @batch_one.nil?\n return if records_retrieved?\n\n retrieve_batch\n end",
"def find_all_from_batch(no=Voucher.get_current_batch_code)\n Voucher.find(:all, :conditions => [\"batch = ?\", no], :order => 'created_at ASC')\n end",
"def get_batch(companyId, id) path = \"/api/v2/companies/#{companyId}/batches/#{id}\"\n get(path, {}, AvaTax::VERSION) end",
"def batch_id\n return nil if @batch.nil?\n \n # get batch values sorted by keys\n values = @batch.sort.collect { |x| x[1] }\n \n # clean up each value\n values.collect! do |x|\n x = \"\" if x.nil?\n x.downcase.gsub(/[^a-z\\d]/, \"\")\n end\n \n # separate by underscores\n values.join(\"_\")\n end",
"def retrieve_all_items(batch)\n unless batch.is_a?(Hash) && batch.has_key?(\"data\") && batch[\"data\"].is_a?(Hash) && batch[\"data\"].has_key?(\"items\")\n raise \"jawbone_up_api retrieve_all_items() was given a bad batch: #{batch}\"\n end\n\n items = batch[\"data\"][\"items\"]\n while batch[\"data\"].has_key?(\"links\") do\n unless batch[\"data\"][\"links\"].has_key?(\"next\")\n raise \"jawbone_up_api retrieve_all_items() has links but no next: #{batch}\"\n end\n batch = get_path(batch[\"data\"][\"links\"][\"next\"])\n items += batch[\"data\"][\"items\"]\n end\n\n items\n end",
"def get_next_batch_blasts(service_id = nil, batch_size = nil)\n exec_get(\"#{@base_path}/api/v2/vendors/blasts/next_batch.json?api_key=#{@api_key}\")\n end",
"def query_batches(options={})\n path = \"/api/v2/batches\"\n get(path, options)\n end",
"def my_batch_id(opts = {}, &blk)\n batch_size = opts[:batch_size] || 1000\n relation = self.reorder(\"#{quoted_table_name}.#{quoted_primary_key} ASC\").limit(batch_size)\n ids = relation.pluck(\"#{Profile.quoted_table_name}.#{Profile.quoted_primary_key}\")\n while ids.any?\n ids_size = ids.size\n primary_key_offset = ids.last\n blk.call(ids)\n break if ids_size < batch_size\n ids = relation.where(\"#{quoted_table_name}.#{quoted_primary_key} > ?\", primary_key_offset).pluck(quoted_primary_key)\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get authentication keys for encoded tags, which can be used to access the tag memory. The key names, content and access rules need to be defined when ordering the tags. It is possible to have several applications with their corresponding keys on a tag. Idempotent Behaviour This endpoint is idempotent and will respond with an appropriate HTTP status code to indicate the actual result 200 OK tags found and result available (also returned if only a subset of tags have this keys) 400 BAD_REQUEST problem occurred, check message parameter for detailed information 401 UNAUTHORIZED user not authorized 404 NOT_FOUND no matching tags found or none the tags found does have keys with given name Input HTTP Headers: HTTP Basic Authorization (as specified above) Accept language (as specified above) Input parameters: tagIds (required, string, `0EEEE100000001`) ... Identifier for each tag to be queried appId (required, string, `SC Public Transport`) ... Application ID which references the key Output parameters: code (Number, `0`) ... Indicates the result code of this call (see `result codes`) tagId (string, `0EEEE100000001`) ... Tag ID tagCode (Number, `0`) ... Indicates if the result code for this tag (see `Possible result codes for a tag actions`) key (string, `0102030405060708090A0B0C`) ... Key blob (AsciiHex encoded key)
|
def create_get_keys_used_for_tag_authentication(body)
# prepare query url
_query_builder = Configuration.base_uri.dup
_query_builder << '/rest/tag/key'
_query_url = APIHelper.clean_url _query_builder
# prepare headers
_headers = {
'accept' => 'application/json',
'content-type' => 'application/json; charset=utf-8'
}
# prepare and execute HttpRequest
_request = @http_client.post _query_url, headers: _headers, parameters: body.to_json
BasicAuth.apply(_request)
_context = execute_request(_request)
# validate response against endpoint and global error codes
if _context.response.status_code == 400
raise APIException.new 'Unexpected error in API call. See HTTP response body for details.', _context
elsif _context.response.status_code == 401
raise APIException.new '', _context
elsif _context.response.status_code == 404
raise APIException.new 'Unexpected error in API call. See HTTP response body for details.', _context
end
validate_response(_context)
# return appropriate response type
decoded = APIHelper.json_deserialize(_context.response.raw_body)
return GetKeysUsedForTagAuthenticationResponseModel.from_hash(decoded)
end
|
[
"def keys_tag(project_id, params)\n path = sprintf(\"/api/v2/projects/%s/keys/tag\", project_id)\n data_hash = {}\n post_body = nil\n \n if params.present?\n unless params.kind_of?(PhraseApp::RequestParams::KeysTagParams)\n raise PhraseApp::ParamsHelpers::ParamsError.new(\"Expects params to be kind_of PhraseApp::RequestParams::KeysTagParams\")\n end\n end\n \n data_hash = params.to_h\n err = params.validate\n if err != nil\n return nil, err\n end\n reqHelper = PhraseApp::ParamsHelpers::BodyTypeHelper.new(data_hash, post_body)\n rc, err = PhraseApp.send_request(@credentials, \"PATCH\", path, reqHelper.ctype, reqHelper.body, 200)\n if err != nil\n return nil, err\n end\n \n return PhraseApp::ResponseObjects::AffectedResources.new(JSON.load(rc.body)), err\n end",
"def keys\n RubyKongAuth::KeyAuth.all consumer_id: self.id\n end",
"def keys\n @tags.nil? ? [] : @tags.keys\n end",
"def hmac_keys service_account_email: nil, project_id: nil,\n show_deleted_keys: nil, token: nil, max: nil,\n user_project: nil\n gapi = service.list_hmac_keys \\\n max: max, token: token,\n service_account_email: service_account_email,\n project_id: project_id, show_deleted_keys: show_deleted_keys,\n user_project: user_project\n\n HmacKey::List.from_gapi \\\n gapi, service,\n service_account_email: nil, show_deleted_keys: nil,\n max: max, user_project: user_project\n end",
"def fetch_signing_keys\n response = JSON.parse(Net::HTTP.get(URI(signing_keys_url)))\n response['keys']\n rescue JSON::ParserError\n raise StandardError, 'Unable to fetch AzureAD signing keys.'\n end",
"def keys\n raise APIError, \n \"To add a key, you must be authenticated\" if @api.read_only?\n\n result = @api.get(\"/user/keys\")\n return unless result and result[\"public_keys\"]\n result[\"public_keys\"].inject([]) { |result, element| result << Key.new(@api, element) }\n end",
"def keys\n ::M2X::Client::Key.list(@client, params.merge(device: self[\"id\"]))\n end",
"def tags\n _get(\"/query/image/tags\") { |json| json }\n end",
"def list_keys\n client.make_request('/list-keys', 'get')\n end",
"def keys\n doc = JSON.parse get('/api/v1/ssh_keys')\n doc[\"ssh_keys\"]\n end",
"def keys\n @resource.jiak.client.keys(jiak.bucket)\n end",
"def describe_keypairs( options = {} )\n options = { :key_name => [] }.merge(options)\n params = pathlist(\"KeyName\", options[:key_name] )\n return response_generator(:action => \"DescribeKeyPairs\", :params => params)\n end",
"def parse_auth_keys\n tuples = config.scan(AUTH_KEY_REGEXP)\n hsh = {}\n tuples.map do |(key, algorithm, mode, password)|\n hsh[key] = {\n algorithm: algorithm,\n mode: mode,\n password: password\n }\n hsh[key]\n end\n\n { auth_keys: hsh }\n end",
"def list_keys(iam, user_name)\n begin\n list_access_keys_response = iam.list_access_keys({ user_name: user_name })\n\n if list_access_keys_response.access_key_metadata.count == 0\n puts \"No access keys.\"\n else\n puts \"Access keys:\"\n list_access_keys_response.access_key_metadata.each do |key_metadata|\n puts \" Access key ID: #{key_metadata.access_key_id}\"\n end\n end\n\n rescue Aws::IAM::Errors::NoSuchEntity\n puts \"Cannot find user '#{user_name}'.\"\n exit(false)\n end\nend",
"def list_crypto_keys request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n verb, uri, query_string_params, body = ServiceStub.transcode_list_crypto_keys_request request_pb\n query_string_params = if query_string_params.any?\n query_string_params.to_h { |p| p.split \"=\", 2 }\n else\n {}\n end\n\n response = @client_stub.make_http_request(\n verb,\n uri: uri,\n body: body || \"\",\n params: query_string_params,\n options: options\n )\n operation = ::Gapic::Rest::TransportOperation.new response\n result = ::Google::Cloud::Kms::V1::ListCryptoKeysResponse.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end",
"def authentication_keys\n @authentication_keys ||= User.authentication_keys\n end",
"def get_keys_info_array(parse_key)\n self.parsed_content.get_keys_info_array(parse_key)\n end",
"def keys\n JSON.parse get('/users/ssh_keys', :accept => 'json').to_s\n end",
"def tags\n get.tagGuids\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Create a new key value entry inside a dictionary with the specified name at the root of this database. Successful completion means the named dictionary will contain one more entry than it need even if it did not previously exist.
|
def create_entry( dictionary_name, key_name, value )
KeyError.not_new( dictionary_name, self )
KeyError.not_new( key_name, self )
KeyError.not_new( value, self )
self[ dictionary_name ] = {} unless self.has_key?( dictionary_name )
self[ dictionary_name ][ key_name ] = value
end
|
[
"def insert_directory(directory, directory_name)\n if !directory.has_key?(directory_name)\n directory[directory_name] = Hash.new{}\n end\nend",
"def insert_name_into_hash(hash, name)\r\n sub_hash = {}\r\n if hash[name]\r\n if !hash[name].kind_of? Array\r\n hash[name] = [hash[name]]\r\n end\r\n hash[name] << sub_hash\r\n else\r\n hash[name] = sub_hash\r\n end\r\n sub_hash\r\n end",
"def insert_file_into_directory(file_name, directory, directory_name)\n dir_hash = directory[directory_name]\n dir_hash[file_name] = Hash.new{}\nend",
"def create_environment(name)\r\n env_id = @db_interface.increment_hash(@env_iterator, Transformer::KeyElementBuilder::ITERATOR_KEY, 1)\r\n result = @db_interface.add_to_hash_ne(@env_key, name, env_id)\r\n raise Transformer::MappingException, \"Environment with such a name already exist.\" unless result\r\n #Create info hash for environment where iterator for generating ids of collections and files will be saved\r\n env_id\r\n end",
"def create(k, v)\n # just anal about logging sql, so heres this\n logger.debug settings.db[:cfg_map].insert_sql(map_key: k, map_val: v)\n\n # actually create the row. returns the id of the new record\n settings.db[:cfg_map].insert(map_key: k, map_val: v)\n end",
"def create_if_not_exists(hash, key, val, name: key.to_sym)\n return if hash.key?(key)\n\n self.class.send(:attr_accessor, name)\n send(\"#{name}=\", val)\n end",
"def create_if_exists(hash, *args, name:)\n exists = false\n args.each do |key|\n exists = false\n break unless hash.is_a?(Hash)\n\n exists = hash.key?(key)\n break unless exists\n\n hash = hash[key]\n end\n return unless exists\n return if respond_to?(name) && !send(name).nil?\n\n self.class.send(:attr_accessor, name)\n send(\"#{name}=\", hash)\n end",
"def insertMapping(name, id)\n row = DatabaseManager.row('SYMPLECTIC_COLL_MAP')\n row.setColumn('key_text', name)\n row.setColumn('collection_id', id)\n DatabaseManager.insert(DSpace.context, row)\nend",
"def new_entry(key, key_hash, value)\n if key.kind_of?(String) and !key.frozen?\n key = key.dup\n key.freeze\n end\n\n @size += 1\n Entry.new key, key_hash, value\n end",
"def insert(name, value)\n @original[name] = value\n if value.class.name == \"Hash\" || value.class.superclass.name == \"Hash\"\n value = CollectionUtils::HashDeserializedObject.new(value)\n end\n name = convert_name(name.to_s)\n self.class.send(:attr_accessor, name)\n instance_variable_set(\"@#{name}\", value)\n define_singleton_method \"#{name}=\".to_sym do |arg|\n @original[name] = arg\n instance_variable_set(\"@#{name}\", arg)\n end\n define_singleton_method \"#{name}\".to_sym do\n instance_variable_get(\"@#{name}\")\n end\n end",
"def put(namespace, key, entry); end",
"def add(name, dir)\n @entries[name.to_s] = dir.to_s\n save_map\n return @entries\n end",
"def addFood(newFood)\n name = newFood.name\n if @base.has_key?(name.downcase)\n puts(\"Database already contains this food\")\n else\n @base[name.downcase] = newFood\n end\n end",
"def find_or_create(name)\n raise unless name.is_a?(String)\n @cache[name] ||= @name_generator.next\n end",
"def create_index(lineno, index_name, key, value)\n if index_name != nil\n if @indexes[index_name] == nil\n #puts \"#{lineno}: create index #{index_name}\"\n @indexes[index_name] = {} #empty hash\n end\n if key != nil\n #p \"#{lineno}: Add (key,value) #{key} => #{@class_stack.last[0]} to index #{index_name}\"\n if @indexes[index_name][key] != nil\n raise \"duplicate key #{key} in index #{index_name}\"\n end\n @indexes[index_name][key] = value\n end\n end\n end",
"def add_nested(nested_values = {}, nested_name, hash_name)\n\t\t# get the correct hash\n\t\thsh = send(hash_name)\n\t\t# make the key by stripping all but the last part of the object name\n\t\tnested_key = nested_name.gsub(/(.*\\[)|(\\])/, '')\n\t\t# the key should map to a hash regardless of which hash it's in\n\t\thsh[nested_key] = {} unless hsh.has_key?(nested_key) && hsh[nested_key].is_a?(Hash)\n\t\t# merge in the values\n\t\thsh[nested_key].merge!(nested_values)\n\tend",
"def store_the_names(normal_name, sec_name, hash)\n\thash[normal_name] = sec_name\n\thash\nend",
"def add(tagname, keyname, definition)\n tagname = tagname.downcase\n keyname = keyname.downcase\n # See if the tag exists yet, if not create it and add then return\n if @mydata[tagname].nil?\n puts \"Tag '#{tagname}' not found, trying to add\"\n h = { keyname => Array.new.push(definition)}\n @mydata.store(tagname, h)\n# puts \"Storing #{keyname} = #{definition} to #{tagname}\"\n# @mydata.store[tagname](keyname, Array.new.push(definition))\n Dictfile::save_data(DATAFILE,@mydata)\n return true\n end\n\n # See if the acronym already exists\n if @mydata[tagname].has_key?(keyname)\n item = @mydata[tagname].fetch(keyname)\n # Check for duplicate, skip if found\n if item.include?(definition)\n return nil\n end\n # Push the new definition onto the end of array record.\n definition = item.push(definition)\n else\n # Create a new array and push definition.\n definition = Array.new.push(definition)\n end\n # Store the updated array to the hash then save it to the Dictfile\n @mydata[tagname].store(keyname, definition)\n Dictfile::save_data(DATAFILE,@mydata)\n return true\n end",
"def find_or_create_child(name, value = nil)\n find_child(name) || create_child(name, value)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Delete an existing key value entry inside the dictionary with the specified name at the root of this database. Successful completion means the named dictionary will contain one less entry if that key existed.
|
def delete_entry( dictionary_name, key_name )
KeyError.not_new( dictionary_name, self )
KeyError.not_new( key_name, self )
self[ dictionary_name ].delete( key_name )
end
|
[
"def delete_value(name)\n\t\treturn self.client.sys.registry.delete_value(self.hkey, name)\n\tend",
"def delete_document(name)\n #We have to delete <info, <emapping, <amapping, <content, and field in envId:collId:documents\n doc_id = get_document_id(name)\n return unless doc_id\n @builder = Transformer::KeyBuilder.new(@env_id, @coll_id, doc_id)\n del_keys = [@builder.content_key, @builder.info, @builder.elem_mapping_key, @builder.attr_mapping_key, @builder.namespace_key]\n @db_interface.transaction do\n @db_interface.delete_keys del_keys\n @db_interface.delete_from_hash(@doc_key, [name])\n end\n end",
"def del(key)\n response = db.delete_item(@table_name, {'HashKeyElement' => {'S' => key}})\n true\n end",
"def remove_by_name(name)\n entry = @entries.find {|e| e.name == name}\n if !entry.nil?\n @entries.delete(entry)\n end\n end",
"def delete(keyname)\n keyname = keyname.to_s\n @@cache.delete(namespace_keyname(keyname), nil)\n end",
"def del(name)\n data.delete(name)\n end",
"def DeleteKey(hkey, name)\n check RegDeleteKeyExW(hkey, name.to_wstring, 0, 0)\n end",
"def delete_pair(key, value)\n key = key.split('') if key.is_a?(String)\n if key.empty?\n @values.delete(value)\n elsif key == @compressed_key\n @compressed_values.delete(value)\n @compressed_key.clear\n elsif @children[key[0]]\n @children[key[0]].delete_pair(key[1..-1], value)\n @children.delete(key[0]) if @children[key[0]].empty?\n end\n self\n end",
"def delete_key_pair(name)\n delete(\"tenants/#{tenant}/sshkeys/#{name}\")\n end",
"def registry_deleteval(key,valname)\n\tbegin\n\t\troot_key, base_key = client.sys.registry.splitkey(key)\n\t\topen_key = client.sys.registry.open_key(root_key, base_key, KEY_WRITE)\n\t\topen_key.delete_value(valname)\n\t\topen_key.close\n\t\treturn true\n\tend\nend",
"def delete(table, key_name, key_value)\n\t\t@conn.exec(\"DELETE FROM #{table} WHERE #{key_name}=\" + key_value + \";\")\n\tend",
"def delete(name)\n existing_tag = one.delete(name)\n existing_tag && new(existing_tag) || nil\n end",
"def delete(name)\n if not @objects.key?(name)\n return\n end\n\n obj, dtor = @objects[name]\n @objects.delete(name)\n destroy(obj, dtor)\n end",
"def delete(key)\n if exists? (key)\n remove_entry(key)\n CacheResult.new(true,\"#{MY_MESSAGES[:success]} Key #{key} deleted\", nil)\n else\n CacheResult.new(false,\"#{MESSAGES[:not_found]} Key #{key} not found\", nil)\n end\n end",
"def delete(name)\n\t\t#check if really exits.\n\t\tif (File.file?\"#{name}\")\n\t\t\tFile.delete(name)\n\t\telse\n\t\t\t#There is no database with that name\n\t\t\t-1\n\t\tend\n\tend",
"def remove_key hash, key\n\t\t@db.hdel hash,key\n\tend",
"def remove key, name = nil\n if name\n h = @var_map[key]\n r = h.delete name\n @var_map.delete key if h.empty?\n r\n else\n @var_map.delete key\n end\n end",
"def erase(cartridge_name, version, cartridge_version)\n unless exist?(cartridge_name, cartridge_version, version)\n raise KeyError.new(\"key not found: (#{cartridge_name}, #{version}, #{cartridge_version})\")\n end\n\n entry = nil\n @semaphore.synchronize do\n # find a \"template\" entry\n entry = select(cartridge_name, version, cartridge_version)\n\n # Now go back and find all occurrences of the \"template\"\n @index[cartridge_name].each_key do |k2|\n @index[cartridge_name][k2].each_pair do |k3, v3|\n if v3.eql?(entry)\n remove(cartridge_name, k2, k3)\n end\n end\n end\n\n FileUtils.rm_r(entry.repository_path)\n parent = Pathname.new(entry.repository_path).parent\n FileUtils.rm_r(parent) if 0 == parent.children.count\n end\n\n entry\n end",
"def delete(value)\n #get hashed value\n hash_value = hash_function(value)\n\n # check if value exists\n result = search(value)\n\n # if value exists\n if result\n # set value to nil\n @@collection[hash_value] = nil\n # return confirmation\n \"value deleted\"\n else\n # return error message\n \"value not found\"\n end\n\n\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
edit item in the json file and save
|
def edit(class_name, object)
begin
@data = get_all()
# go through all items in the file
@data[class_name].map!{|item|
if item["id"] == object["id"]
object
else
item
end
}
save()
rescue Exception => e
raise "Either class_name: #{class_name} or object: #{object} are invalid."
end
end
|
[
"def edit\n require 'ruby-debug'; debugger\n if storage.respond_to?(\"json_file\")\n output \"#{cyan(\"Boom!\")} #{Platform.edit(storage.json_file)}\"\n else\n output \"This storage backend #{red storage.class} does not store #{cyan(\"Boom!\")} data on your computer\"\n end\n end",
"def edit(json_file)\n unless ENV['EDITOR'].nil?\n unless windows?\n system(\"`echo $EDITOR` #{json_file} &\")\n else\n system(\"start %EDITOR% #{json_file}\")\n end\n else\n system(\"#{open_command} #{json_file}\")\n end\n\n \"Make your edits, and do be sure to save.\"\n end",
"def update\n @jsonfile = Jsonfile.find(params[:id])\n\n respond_to do |format|\n if @jsonfile.update_attributes(params[:jsonfile])\n format.html { redirect_to(@jsonfile, :notice => 'Jsonfile was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @jsonfile.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_json(file, data)\t\t\t\n\tFile.open(file, 'w+') {|f| f.write(JSON.generate(data)) }\nend",
"def save_file\n @stored_file = File.new(\"list.json\", \"w+\")\n hashed = Hash.new(\"items\")\n @items.each_with_index do |item, index|\n hashed[\"#{item.description},#{item.completed_status},#{item.priority.to_s},#{item.date_string}\"] = index \n end\n @stored_file.write(hashed.to_json)\n end",
"def store_file(path)\n if path\n data = Editor.model2data(@treeview.model.iter_first)\n File.open(path + '.tmp', 'wb') do |output|\n if @options_menu.pretty_item.active?\n output.puts JSON.pretty_generate(data)\n else\n output.write JSON.unparse(data)\n end\n end\n File.rename path + '.tmp', path\n @filename = path\n toplevel.display_status(\"Saved data to '#@filename'.\")\n unchange\n end\n rescue SystemCallError => e\n Editor.error_dialog(self, \"Failed to store JSON file: #{e}!\")\n end",
"def update_file\n file = File.read('./user.json')\n data_hash = JSON.parse(file)\n data_hash['balance'] = @user[:balance]\n File.write('./user.json', JSON.dump(data_hash))\n end",
"def update_file\n updated_data = Login.load_data.each { |user| user['playlist'] = @user.playlist if user['id'] == @user.uid.to_s }\n File.open(userdata, 'w') do |f|\n f.puts JSON.pretty_generate(updated_data)\n end\n puts 'Sweet! Your list has been updated!'.colorize(:light_green)\n @prompt.keypress('Press any key to return to the previous menu..')\n menu = Menu.new(@user)\n menu.menu_router\n end",
"def update_file\n updated_data = Login.load_data.each { |user| user['mylist'] = @mylist if user['id'] == @user.uid.to_s }\n File.open(userdata, 'w') do |f|\n f.puts JSON.pretty_generate(updated_data)\n end\n puts 'Sweet! Your list has been updated!'.colorize(:light_green)\n @prompt.keypress('Press any key to return to the previous menu..')\n @menu.my_list\n end",
"def save\n #we create a hash to save the values into:\n new_json = {name: @name, email: @email, permissions: @permissions}.to_json\n #we open a new file and append (a) the new values to it.\n open('users.json', 'a') do |file|\n file.puts new_json\n end\n\n end",
"def edit\n save\n editor.open(file_path)\n create_tasks\n true\n end",
"def updated(item)\n bowline.updated(\n name, \n item.id, \n item.to_js\n ).call\n end",
"def update obj, &block\n populate(obj, &block).save!\n json obj\n end",
"def update\n json_response(@food_item.update!(food_item_params))\n end",
"def save\n if new_record?\n overwrite @api.post(\"/meetings/#{meeting.shortcode_url}/items.json\",\n 'content' => content)\n else\n overwrite @api.put(\"/items/#{shortcode_url}.json\", 'content' => content)\n end\n end",
"def save\n save_to_disk(JSON.parse(self.to_json))\n end",
"def reedit\n __log_activity\n __debug_route\n @item = wf_single(event: :edit)\n upload_authorize!\n respond_to do |format|\n format.html\n format.json { render json: @item }\n format.xml { render xml: @item }\n end\n rescue => error\n post_response(error)\n end",
"def proposal_edit(name)\n usage -1 if name.nil? or name == \"\" or @data==\"\"\n prop = JSON.parse(@data)\n prop[\"attributes\"][\"chef\"][\"servers\"].each { |s,v| \n fname = File.expand_path(v[\"client_key\"])\n v[\"client_key\"] = IO.read(fname)\n }\n @data = prop.to_json\n orig_proposal_edit(name)\nend",
"def update_data website\n dest = get_dest_path website.preview\n data_dir = File.join(dest, \"_data\")\n FileUtils.mkdir_p(data_dir)\n data_file = File.join(data_dir, \"scribae.json\")\n comps = Component.all\n data = {\n \"components\" => comps\n }\n File.open(data_file,'w') do |f| \n f.write data.to_json\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
get from json file class data
|
def get_data(class_name)
return JSON.parse(File.read(@database_file))[class_name]
# error handling
rescue Errno::ENOENT
File.open(@database_file, 'w+')
File.write(@database_file, [])
retry
end
|
[
"def read\n JSON.parse(File.read(@json))\n end",
"def retrieve\n raise \"Can't retrieve from JSON file. Use text file.\"\n end",
"def parse json; return JSON.parse File.read json end",
"def fetch_json_info\n return {} unless File.exist?(@json_file)\n content = File.read(@json_file, encoding: 'utf-8')\n JSON.parse(content, symbolize_names: true)\n end",
"def read_classes\n\n data = File.read(PLAYER_CLASSES)\n JSON.parse(data).map do |player_class|\n Character.new(\n player_class['name'],\n player_class['short_description'],\n player_class['stats']\n )\n end\n\nend",
"def parse_file(filename)\n klass = class_name(filename)\n read_file(filename) do |data|\n data = JSON.parse(data, :object_class => Types::Base, :max_nesting => 100)\n store_schema(data) do\n if data.resources # discovery format\n parse_resource(data)\n else\n data_types[klass] = {}\n data_types[klass] = parse_object(data)\n end\n end\n end\n klass\n end",
"def import_JSON_File (path)\r\n\r\n\tfile = File.open path\r\n\tdata = JSON.load file\r\n\tfile.close\r\n\r\n\tpalestras = []\r\n\r\n\tdata['data'].each { |nome| palestras.append Palestra.new nome }\r\n\r\n\treturn palestras\r\n\r\nend",
"def get_data_from_json_file(filename)\n file_to_parse = File.read(filename)\n data_hash = JSON.parse(file_to_parse)\n return data_hash\nend",
"def initialize json_file\n @json_file = JSON.parse(File.read(json_file))\n @date = @json_file[\"date\"]\n @base = @json_file[\"base\"]\n @rates = @json_file[\"rates\"]\n @rate_keys = @json_file[\"rates\"].keys\n @rate_values = @json_file[\"rates\"].values\n end",
"def read_from_json\n JSON.parse File.new(@filepath).read\n end",
"def initialize(json_file)\n @json_file = JSON.parse(json_file)\n end",
"def parse(data)\n select_json_library unless @json_obj\n o = @json_obj.parse(data)\n if @create_objects && o.kind_of?(Hash) \n if o.has_key?(\"json_class\")\n class_name = o[\"json_class\"].split('::').inject(Kernel) do |scope, const_name| \n scope.const_get(const_name)\n end\n if class_name.respond_to?(:from_json)\n return class_name.from_json(o)\n else\n return o\n end\n end\n else\n return o\n end\n end",
"def parse\n file = File.read(@file)\n @data = JSON.parse(file)\n end",
"def initialize(json_file)\n @json_file = JSON.parse(File.read(json_file))\n end",
"def load_model(model_class)\n begin\n file_content = File.read(model_class.db_filename)\n json_data = JSON.parse(file_content)\n rescue Errno::ENOENT\n # The file does not exists\n json_data = []\n end\n json_data.each do |data_hash|\n new_object = model_class.from_hash(data_hash)\n new_object.save\n end\nend",
"def read_json(path = self.path)\n self.path = path\n self.mega_hash = JSON.parse(File.read(self.path)) if File.exist?(self.path)\n mega_hash\n end",
"def json_file_fixture(path)\n return JSON.parse(File.read(file_fixture(path)), symbolize_names: true)\n end",
"def read_json_file\n file_name_and_extension = [file_selection_opts[@selected_file], file_processor.file_ext].join\n file_full_path = File.join(file_processor.file_path, file_name_and_extension)\n @content = JSON.parse(File.read(file_full_path))\n content_keys = content.first.keys\n @content_fields_hash = Hash[(1..content_keys.size).zip content_keys]\n get_field_name\n end",
"def load\n json = File.read(path)\n raise \"Impossible to load result, empty descriptor: #{path}.\" if json.empty?\n @data = JSON.parse(json, {:symbolize_names=>true})\n @data[:files] ||= {}\n @results = (self[:results] || []).map{ |rs| MiGA::Result.new rs }\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
get pets client from json using client id and returning it
|
def get_pet_list_by_client_id(client_id)
pet_list = []
for pet in get_data("pets")
if client_id == pet["client_id"]
pet_list.push(pet)
end
end
return pet_list
end
|
[
"def get_client_by_id client_id\n @clients[client_id]\n end",
"def find_client(id:)\n response = get(\"clients/#{id}\")\n PhysitrackApi::Response.from(response)\n end",
"def client_by_id(id)\n clients.select { |client| client.id == id }.first\n end",
"def get_client_by_id(id)\n request 'clients.getClient', id\n end",
"def details\n response = CreateSend.get \"/clients/#{client_id}.json\", {}\n Hashie::Mash.new(response)\n end",
"def details\n response = cs_get \"/clients/#{client_id}.json\", {}\n Hashie::Mash.new(response)\n end",
"def get_client_pets\n if @client_arr == []\n client_info = \"No clients in system.\\n\"\n else\n client_info = @client_arr.inject(\"\") do |client_info_str, client|\n client_info_str << \"#{client.name_str} pets: #{client.get_pets}\\n\"\n end\n end\n return client_info \n end",
"def getClient(name)\n @clients.each { |client| client.name == name}.first\n end",
"def get_client(id)\n conn = @client.get do |req|\n req.url \"/api/v2/client/#{id}\"\n req.headers[\"Authorization\"] = @token\n end\n conn.body\n end",
"def get_cocktail_info_from_cocktail_db(cocktail_db_drink_id)\n response = RestClient.get 'https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=' + cocktail_db_drink_id\n drink_info = JSON.parse(response)[\"drinks\"][0]\nend",
"def get_prod(id)\n\tkey = \"b05dcd698e5ca2eab4a0cd1eee4117e7db2a10c4\"\n url = \"http://api.zappos.com/Product/#{id}?includes=[%22styles%22]&key=#{key}\"\n\n\tresult = JSON.parse(open(url).read)\n \n #return product info as a json object\n product = result['product']\n end",
"def client(name)\n client_to_find = name\n @clients.find {|key, value| key == client_to_find } \n end",
"def client_data\n @client_data ||= JSON.parse(client_data_json)\n end",
"def find_by_code(client_code)\n json = client.get(\"clients/find-by-code.json\", {client_code: client_code})\n Invoicexpress::Model::Client.new(json[\"client\"])\n end",
"def get_client_meta(client_id)\n path = type_info(:client, :path)\n json_get(@target, \"#{path}/#{Addressable::URI.encode(client_id)}/meta\", @key_style, headers)\n end",
"def show\n @vkontakte_client = VkontakteClient.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @vkontakte_client }\n end\n end",
"def get_record_by_id(id) \n\t\turl = URI.escape(\"http://clientcloud.herokuapp.com/retrieve?key=#{ENV[\"APPLICATION_KEY\"]}&id=#{id}&business_detail\")\n\t\tresponse = open(url).read\n\t\treturn JSON.parse(response)\n\tend",
"def show\n #using find_by for if else conditional\n selected_client = Client.find_by(id: params[:id])\n if selected_client\n render json: selected_client, status: :created\n else\n render json: {error: \"Show has failed, in tragedy\"}, status: 422\n end\n end",
"def get_client_id(url)\n return nil unless url\n SmartClient.all.each do |client|\n return client.client_id if url.include?(client.name)\n end\n nil\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
get tasks list of the jobs from json using job id and returning it
|
def get_task_list_by_job_id(job_id)
list_tasks = []
for task in get_data("tasks")
if job_id == task["job_id"]
list_tasks.push(task)
end
end
return list_tasks
end
|
[
"def get_job(id)\n conn = @client.get do |req|\n req.url \"/api/v2/job/#{id}\"\n req.headers[\"Authorization\"] = @token\n end\n conn.body\n end",
"def list_all_with_details\n response_json = @client.api_get_request(\"\")\n response_json[\"jobs\"]\n end",
"def get_jobs_by_client_id(client_id)\n jobs = []\n for job in get_data(\"jobs\")\n if client_id == job[\"client_id\"]\n jobs.push(job)\n end\n end\n\n return jobs\n end",
"def getMyJobList\n request \"/Job/getMyJobList.json\"\n end",
"def find_job_by_id(id)\n plan.find_tasks(Job).with_arguments(job_id: id).to_a.first\n end",
"def list_jobs(json_payload={})\n conn = @client.get do |req|\n req.url '/api/v2/job/list?'\n req.headers[\"Authorization\"] = @token\n req.params = json_payload\n end\n conn.body\n end",
"def jobs\n response = request(\"?depth=1\")\n # get the JSON key from the tree by removing the branch\n response = JSON.parse(response.body)[\"jobs\"]\n\n response\n end",
"def getExecutionsForAJob(job_id)\n uri = URI(RUNDECKSERVER + ':' + RUNDECKPORT + '/api/1/job/' + job_id + '/executions')\n http = Net::HTTP.new(uri.host, uri.port)\n headers = {\n 'Content-Type'=> 'application/json',\n 'X-RunDeck-Auth-Token'=> API_KEY \n}\n r = http.get(uri.path, headers)\n return r.body.force_encoding(\"UTF-8\")\nend",
"def production_job_list(production_id)\n http_get(\"content/ea/api/productions/#{production_id}/jobs.v1.json\")\n end",
"def get_tag_jobs(id, options={})\n get(\"1/tags/#{id}/jobs\", options)\n end",
"def listjobs(project=self.project)\n get('listjobs.json', project: project).reject{|k,v| k=='status'}\n end",
"def list_all_with_details\n @logger.info \"Obtaining the details of all jobs\"\n response_json = @client.api_get_request(\"\")\n response_json[\"jobs\"]\n end",
"def get_jobs(url)\n result = JSON.parse(get_data(url))\n job_list = []\n result[\"jobs\"].each do |job|\n job = JenkinsJob.new job[\"name\"], job[\"color\"], job[\"url\"]\n job_list << job\n end\n job_list\nend",
"def find_jobs(params:)\n response = HTTParty.get(\"#{@host}/api/jobs\", query: params)\n\n return response[\"jobs\"] \n end",
"def get_startup_jobs(id)\n get(\"1/startups/#{id}/jobs\")\n end",
"def list\n @logger.info \"Obtaining the tasks currently in the build queue\"\n response_json = @client.api_get_request(\"/queue\")\n tasks = []\n response_json[\"items\"].each do |item|\n tasks << item[\"task\"][\"name\"]\n end\n tasks\n end",
"def split_job(json)\n json['tasks'].each do |task|\n body,preamble = make_preamble(task.to_json)\n msg = enqueue_task(body,preamble)\n @enqueued_tasks.push(msg)\n end\n end",
"def tasks(project_id)\n account = Config.details \n c = FreshBooks::Client.new(account[\"account\"], account[\"token\"])\n c.task.list :project_id => project_id\n end",
"def getTaskByID(id) \n ret = nil \n\n @Tasks.each do |task| \n ret = task if task.ID == id\n end \n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
get jobs from json using difference of job date and local date now returning jobs for next 7 days
|
def get_jobs_last_7_days()
@data = get_all()
now = Time.now.to_date
jobs = []
for job in @data["jobs"]
parsed_date = Date.strptime(job["date"], "%d/%m/%Y")
days_difference = (parsed_date - now).to_i
if days_difference <= 7 && days_difference >= 0
jobs.push(job)
end
end
return jobs
end
|
[
"def get_jobs(url)\n result = JSON.parse(get_data(url))\n job_list = []\n result[\"jobs\"].each do |job_data|\n @@total_job_count += 1\n next if job_data[\"color\"] == \"blue\"\n\n build_score = -1\n build_text = \"\"\n test_score = -1\n test_text = \"\"\n health_report = job_data[\"healthReport\"]\n if health_report\n health_report_build = health_report[1]\n if health_report_build\n build_score = health_report_build[\"score\"]\n build_text = health_report_build[\"description\"]\n end\n health_report_test = health_report[0]\n if health_report_test\n test_score = health_report_test[\"score\"]\n test_text = health_report_test[\"description\"]\n end\n end\n \n lastCompleted = DateTime.strptime(\"0\", '%Q')\n last_completed_build = job_data[\"lastCompletedBuild\"]\n if last_completed_build\n last_job_url = last_completed_build[\"url\"] + \"/api/json\"\n #logger.info \"last_job_url = #{last_job_url}\"\n last_comp_data = JSON.parse(get_data(last_job_url))\n lastCompleted = DateTime.strptime(\"#{last_comp_data[\"timestamp\"]}\", '%Q')\n claimed_by = \"\"\n claim_reason = \"\"\n last_comp_data[\"actions\"].each do |action|\n puts action\n if action[\"claimedBy\"]\n claimed_by = action[\"claimedBy\"]\n claim_reason = action[\"reason\"]\n end\n end\n end\n\n job = JenkinsJob.new job_data[\"name\"], job_data[\"color\"], job_data[\"url\"], build_score, build_text, test_score, test_text, lastCompleted, claimed_by, claim_reason\n job_list << job\n end\n job_list\nend",
"def retrieve_json_data_since day, count\n tickets = []\n puts \"retrieving tickets data since #{day.to_s} backward #{count} days...\"\n count.times do\n stime = day.strftime('%Y-%m-%d') + \" 00:00:00\"\n etime = day.strftime('%Y-%m-%d') + \" 23:59:59\"\n puts \" retrieving tickets during #{stime} - #{etime}\"\n tcks = get_pospal_tickets_within(stime, etime)\n tickets += tcks\n day = day.prev_day\n puts \" done. total tickets: #{tcks.size}\"\n end\n puts \"done. total tickets: #{tickets.size}\"\n return tickets\nend",
"def getJobs(company)\n puts \"Fetching jobs for company #{company[:id]}\"\n uri = URI.join(\"https://angel.co\",\"/job_listings/browse_startup_details\")\n params = { :startup_id => company[:id] }\n \n response = makeHttpRequest(uri, $headers, params, nil, MaxQps)\n if response == nil\n puts \"Error Getting jobs for company #{company}\"\n return nil\n end\n doc = Nokogiri::HTML(response.body)\n node = doc.xpath(\"//div[contains(@class, 'details-row') and contains(@class, 'product')]\")\n if(node == nil)\n puts \"Error Getting jobs for company #{company}\"\n return nil\n end\n \n company_profile = getCompanyProfile(company)\n \n $description = \"\"\n $description += doc.xpath(\"//div[contains(@class, 'details-row') and contains(@class, 'product')]\").inner_html.to_s\n $description += \"<br>\"\n $description += \"<div>For more information about #{company[:company]} visit <a href=\\\"#{company[:company_url]}\\\">#{company[:company_url]}</a>.</div>\"\n jobNodes = doc.xpath(\"//div[contains(@class, 'details-row') and contains(@class, 'jobs')]/div[@class='content']/div[@class='listing-row']\")\n \n company_profile[:description] = sanitizeDescription($description)\n active = doc.xpath(\"//div[@class='active']\").inner_text.strip\n \n active_time = (Time.zone.now().to_time - ChronicDuration.parse(active).seconds).to_s\n \n if(jobNodes == nil)\n puts \"Error Getting jobs for company #{company}\"\n return nil\n end\n jobs = []\n jobNodes.each do |jobNode|\n title = jobNode.xpath(\".//div[@class='top']/div[@class='title']\").inner_text\n tags = jobNode.xpath(\".//div[@class='tags']\").inner_text.split(\"\\u00B7\")\n record = {:job_title => title, :duration => (tags[0].nil?)? \"\" : tags[0].strip, :location => (tags[1].nil?)? \"\" : tags[1].strip, :area => (tags[2].nil?)? \"\" : tags[2].strip, :tags => (tags[3].nil?)? \"\" : tags.drop(3).join(\",\").strip}\n record[:job_url] = uri\n record[:description] = company_profile[:description]\n record[:active_time] = active_time\n record[:company] = company[:company]\n record[:company_logo] = company[:image_url]\n record[:job_url] = company[:company_url]\n # since there is no job id, creating job id by appending company id with hash of job title\n record[:id] = company[:id]+\"_\"+Digest::SHA1.hexdigest(title)\n record[:video_url] = company_profile[:video_url]\n jobs.push(record)\n end\n return jobs\nend",
"def last_20_jobs(project_id)\n api(\"projects/#{project_id}/jobs\").sort_by { |j| -j['id'] }\nend",
"def next_jobs\n now = Time.now\n earliest = nil\n jobs = Array.new\n\n @jobs.each do |entry|\n job, trigger = entry.job, entry.trigger\n time = trigger.fire_time_after(now)\n\n case\n when time.nil?\n # do nothing\n when now.to_i == entry.earliest.to_i\n unless entry.last.to_i == now.to_i\n entry.last = now\n jobs << entry\n end\n else\n entry.earliest = time\n end\n\n end\n\n jobs\n end",
"def jobs\n response = request(\"?depth=1\")\n # get the JSON key from the tree by removing the branch\n response = JSON.parse(response.body)[\"jobs\"]\n\n response\n end",
"def latest_jobs(project_id)\n last_20_jobs(project_id).each_with_object({}) do |job, all_latest_jobs|\n branch = job['ref']\n job_name = job['name']\n all_latest_jobs[branch] = {} if all_latest_jobs[branch].nil?\n all_latest_jobs[branch][job_name] = job if all_latest_jobs[branch][job_name].nil?\n end\nend",
"def scrape_jobs\n @scraper = FreelancerFinder::Scraper.new\n @scraper.scrape_recent_jobs.each do |job_hash|\n FreelancerFinder::Job.new(job_hash) unless FreelancerFinder::Job.all.detect {|job| job.path == job_hash[:path]} # next create a job instance from the data we just scraped unless it exists already\n end\n end",
"def job_arrival(jobs)\n # put new job in queue\n new_jobs = Array.new\n jobs.each do |job|\n if job.arrival == @timestep\n # update the deadline according to the current timestep\n job.deadline += @timestep\n @job_queue << job\n new_jobs << job\n end\n end\n return new_jobs\n end",
"def load_sched json_obj\n return if json_obj.nil?\n\n json_obj.each do |name,obj| # each scheduled query\n sql = obj['query'] rescue nil\n if sql.nil?\n STDERR.puts \"ERROR: unable to read query attr for '#{name}'\"\n next\n end\n\n #sub_value_list obj, sql\n\n run_report_single_query name, obj, sql\n\n end\n end",
"def get_jobs(url)\n result = JSON.parse(get_data(url))\n job_list = []\n result[\"jobs\"].each do |job|\n job = JenkinsJob.new job[\"name\"], job[\"color\"], job[\"url\"]\n job_list << job\n end\n job_list\nend",
"def get_pull_requests(days=7)\n update_pull_requests if @pull_requests.nil?\n @pull_requests.take_while do |pr|\n pr.created_at.to_date > Date.today - days\n end\n end",
"def get_enphase_last_7_day_summaries\n rescue_from_error { Enphase.get_enphase_last_7_day_summaries(@user_id, params[:system_id]) }\n @start_time = Time.now.to_f\n \n total_end_time = Time.now.to_f\n build_job(@start_time, total_end_time)\n \n respond_to do |format|\n format.json { render json: @response.to_json }\n end\n end",
"def parse_schedule_response(response)\n dates_of_games = []\n parsed_response = JSON.parse(response)\n games = parsed_response['fullgameschedule']['gameentry']\n\n games.each do |game|\n unless dates_of_games.include?(game['date'])\n dates_of_games << game['date']\n end\n end\n\n dates_of_games\n end",
"def client_tasks_upcoming\n today = Time.zone.now\n self.find_all {|e| (e.completed.nil? or !e.completed) and (e.complete_by >= today and e.complete_by <= (today + 6.days)) }\n end",
"def list_jobs(json_payload={})\n conn = @client.get do |req|\n req.url '/api/v2/job/list?'\n req.headers[\"Authorization\"] = @token\n req.params = json_payload\n end\n conn.body\n end",
"def small_steps_for_day\n date = params[:date]\n date = Date.parse(date) unless date.is_a? Date\n is_update = params[:is_update] || false\n\n @week = @program.weeks.where(\"DATE(?) BETWEEN start_date AND end_date\", date).first\n\n @week_data = @week.as_json(only: :id)\n\n if is_update\n @small_steps = @week.small_steps.collect { |ss| ss if ss.can_check_in_on_date(date) }.compact\n check_in = @week.check_ins.find_by(created_at: date)\n\n @week_data[:check_in_id] = check_in.id unless check_in.nil?\n @week_data[:check_in_comments] = check_in.comments unless check_in.nil?\n else\n @small_steps = @week.small_steps.collect { |ss| ss if ss.needs_check_in_on_date(date) }.compact\n end\n \n @small_steps_data = @small_steps.as_json(only: [:id, :name, :frequency_name, :times_per_week, :specific_days, :note, :attachments])\n \n @week_data[:small_steps] = @small_steps_data\n\n render status: 200, json: {\n success: true,\n data: { week: @week_data }\n }\n end",
"def extract_relevant_dates()\n dates = Array.new\n events = Array.new\n tag_set = @extended_appointment_page.parser().xpath(\"(//table)[2]//following-sibling::tr[position()>1]\")\n raise DataMiningError.new(\"Reaktion auf Quartalszahlen\", \"Could not extract any release dates for quarterly figures\") if tag_set.nil? || tag_set.size() < 1\n tag_set.each do |tr|\n # This is neccesary to remove HTML escaped whitespace: \n nbsp = Nokogiri::HTML(EscapedCharacters::SPACE).text\n raw_date = tr.xpath(\"td[1]\").first().content().sub(nbsp,'').strip()\n #Rails.logger.debug(\"#{self.class}: Adding release date: #{raw_date}\")\n raw_event = tr.xpath(\"td[3]\").first().content().strip()\n date = Util.to_date_time(raw_date)\n # Make sure date is in the past and the event is in the white list\n if date < DateTime.now && EVENTS_WHITE_LIST.include?(raw_event)\n dates << date\n events << raw_event\n end\n end\n # For debugging only\n #for i in 0..dates.size-1\n # Rails.logger.debug(\"#{self.class}: Date: #{dates[i]}, Event: #{events[i]}\")\n #end\n begin\n release_date = Util.get_latest(dates)\n Rails.logger.debug(\"#{self.class}: Last release date: #{release_date}\")\n rescue RuntimeError => e\n Rails.logger.warn(\"#{self.class}: #{e.to_s}\")\n raise DataMiningError.new(\"Reaktion auf Quartalszahlen\", \"Could not find any quaterly figures for the last 100 days\")\n end\n before_after = Util.calc_compare_dates(release_date)\n dates = Hash.new\n dates['release'] = release_date\n dates['before'] = before_after[0]\n dates['after'] = before_after[1]\n return dates\n end",
"def requests_for_date(date)\r\n #find all requests in this zip on this date\r\n s = Schedule.for(self.location, date)\r\n puts \"generated schedule\", s\r\n requests = []\r\n s.stops.each do |stop|\r\n puts stop\r\n requests << stop.requests if stop\r\n puts \"requests: \" + requests.to_s\r\n end\r\n requests.flatten.sort_by{|r| r.order.address.addr1}\r\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
get jobs list from json using client id and returning it
|
def get_jobs_by_client_id(client_id)
jobs = []
for job in get_data("jobs")
if client_id == job["client_id"]
jobs.push(job)
end
end
return jobs
end
|
[
"def getMyJobList\n request \"/Job/getMyJobList.json\"\n end",
"def list_all_with_details\n response_json = @client.api_get_request(\"\")\n response_json[\"jobs\"]\n end",
"def list_jobs(json_payload={})\n conn = @client.get do |req|\n req.url '/api/v2/job/list?'\n req.headers[\"Authorization\"] = @token\n req.params = json_payload\n end\n conn.body\n end",
"def list_all_with_details\n @logger.info \"Obtaining the details of all jobs\"\n response_json = @client.api_get_request(\"\")\n response_json[\"jobs\"]\n end",
"def get_jobs(url)\n result = JSON.parse(get_data(url))\n job_list = []\n result[\"jobs\"].each do |job|\n job = JenkinsJob.new job[\"name\"], job[\"color\"], job[\"url\"]\n job_list << job\n end\n job_list\nend",
"def find_jobs(params:)\n response = HTTParty.get(\"#{@host}/api/jobs\", query: params)\n\n return response[\"jobs\"] \n end",
"def production_job_list(production_id)\n http_get(\"content/ea/api/productions/#{production_id}/jobs.v1.json\")\n end",
"def jobs\n response = request(\"?depth=1\")\n # get the JSON key from the tree by removing the branch\n response = JSON.parse(response.body)[\"jobs\"]\n\n response\n end",
"def jobs_list(project_id, page, per_page, params)\n path = sprintf(\"/api/v2/projects/%s/jobs\", project_id)\n data_hash = {}\n post_body = nil\n \n if params.present?\n unless params.kind_of?(PhraseApp::RequestParams::JobsListParams)\n raise PhraseApp::ParamsHelpers::ParamsError.new(\"Expects params to be kind_of PhraseApp::RequestParams::JobsListParams\")\n end\n end\n \n data_hash = params.to_h\n err = params.validate\n if err != nil\n return nil, err\n end\n reqHelper = PhraseApp::ParamsHelpers::BodyTypeHelper.new(data_hash, post_body)\n rc, err = PhraseApp.send_request_paginated(@credentials, \"GET\", path, reqHelper.ctype, reqHelper.body, 200, page, per_page)\n if err != nil\n return nil, err\n end\n \n return JSON.load(rc.body).map { |item| PhraseApp::ResponseObjects::Job.new(item) }, err\n end",
"def get_job(id)\n conn = @client.get do |req|\n req.url \"/api/v2/job/#{id}\"\n req.headers[\"Authorization\"] = @token\n end\n conn.body\n end",
"def listjobs(project=self.project)\n get('listjobs.json', project: project).reject{|k,v| k=='status'}\n end",
"def jobs(agent_id, options={})\n \targs = {agentId: agent_id}.merge(options)\n \tget('getJobs', args)\n end",
"def getCategoryJobList\n request \"/Job/getCategoryJobList.json\"\n end",
"def getExecutionsForAJob(job_id)\n uri = URI(RUNDECKSERVER + ':' + RUNDECKPORT + '/api/1/job/' + job_id + '/executions')\n http = Net::HTTP.new(uri.host, uri.port)\n headers = {\n 'Content-Type'=> 'application/json',\n 'X-RunDeck-Auth-Token'=> API_KEY \n}\n r = http.get(uri.path, headers)\n return r.body.force_encoding(\"UTF-8\")\nend",
"def list\n @client = Helper.setup(parent_options)\n if options[:filter] && options[:status]\n name_filtered = @client.job.list(options[:filter])\n puts @client.job.list_by_status(options[:status], name_filtered)\n elsif options[:filter]\n puts @client.job.list(options[:filter])\n elsif options[:status]\n puts @client.job.list_by_status(options[:status])\n else\n puts @client.job.list_all\n end\n end",
"def jobs\n build_query('jobs')\n end",
"def list_jobs(state, opts = {})\n raise ArgumentError unless [:all, :running, :done].include? state\n state = nil if state == :all\n\n headers = gen_headers(opts)\n\n attempt(opts[:attempts]) do\n # method = opts[:head] ? :head : :get\n method = :get # until added to Manta service\n result = @client.send(method, job_url(), { :state => state }, headers)\n raise unless result.is_a? HTTP::Message\n\n if result.status == 200\n # return true, result.headers if method == :head\n return [], result.headers if result.body.size == 0\n\n raise unless result.headers['Content-Type'] ==\n 'application/x-json-stream; type=job'\n\n json_chunks = result.body.split(\"\\n\")\n job_entries = json_chunks.map { |i| JSON.parse(i) }\n\n return job_entries, result.headers\n end\n\n raise_error(result)\n end\n end",
"def msf_job_info id\n begin\n response = RestClient.get \"#{@url}msf/job/#{id}/info\", {:params => {:token => @token}}\n details = JSON.parse(response.body)\n print_good \"Retrieved job information [id: #{id}]\"\n details\n rescue => e\n print_error \"Could not retrieve job info: #{e.message}\"\n end\nend",
"def getCurrentJobs\n getJobs('0/')\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
In production this route kicks in, and in dev we load /assets/modejson.js from the /app/assets/javascripts/modejson.js location..
|
def mode_json
path = 'node_modules/ace-builds/src-min-noconflict/mode-json.js'
file_contents = File.read(path)
render js: file_contents, content_type: Mime::Type.lookup('application/javascript')
end
|
[
"def config_js\n [\n src_config_path.join('routes.js').to_s,\n src_config_path.join('router.js').to_s,\n src_config_path.join('app.js').to_s\n ]\n end",
"def request_debug_assets?; end",
"def ext\n respond_to do |format|\n format.js {\n render :text => Netzke::Core::DynamicAssets.ext_js\n }\n\n format.css {\n render :text => Netzke::Core::DynamicAssets.ext_css\n }\n end\n end",
"def asset_handler\n tags = String.new\n tags << tag(:link, rel: \"stylesheet\", href: \"/stylesheets/icons.css\")\n if controller_name == \"rich_subscriptions\"\n tags << content_tag(:script, \"\", src: \"/javascripts/#{fingerprinted_asset('map')}.js\")\n tags << tag(:link, rel: \"stylesheet\", href: \"/stylesheets/leaflet/leaflet.css\")\n tags << tag(:link, rel: \"stylesheet\", href: \"/stylesheets/leaflet/leaflet-slider.css\")\n tags << tag(:link, rel: \"stylesheet\", href: \"/stylesheets/leaflet/L.Control.Locate.min.css\")\n tags << tag(:link, rel: \"stylesheet\", href: \"/stylesheets/#{fingerprinted_asset('map')}.css\")\n else\n tags << content_tag(:script, \"\", src: \"/javascripts/#{fingerprinted_asset('application')}.js\")\n tags << tag(:link, rel: \"stylesheet\", href: \"/stylesheets/#{fingerprinted_asset('application')}.css\")\n end\n tags.html_safe\n end",
"def r_js_asset\n render_asset 'text/javascript'\n end",
"def include_registered_js \n \n case RAILS_ENV\n when 'production'\n # look for build versions of js in javascripts/deploy if app is in production\n filename = ActionView::Helpers::AssetTagHelper.const_get(:JAVASCRIPTS_DIR) + '/deploy/' + @controller.controller_name + '-all.js'\n if (!FileTest.exist?(filename)) #<-- look for /javascripts/deploy/controller_name.js \n #LOG.info(\"Resistor::View::AssetMgr -- FAILED TO FIND DEPLOYED CONTROLLER JAVASCRIPT /javascripts/deploy/#{@controller.controller_name}\")\n #LOG.info(\"Loading development resources instead\")\n \n sources = self.get_javascript_development_sources\n else\n sources = self.get_javascript_production_sources\n end\n when 'development'\n sources = self.get_javascript_development_sources \n end \n \n # return javascript_include_tag on each source\n sources.collect {|source| javascript_include_tag(source)}.join(\"\\n\") \n end",
"def javascript_path; end",
"def javascript_manifest_file\n if Rails.application.config.x.action_view.javascript_manifest_resolver\n Rails.application.config.x.action_view.javascript_manifest_resolver.call(request)\n else\n DEFAULT\n end\n end",
"def serve_assets\n if @serve_assets.nil?\n ENV['RACK_ENV'] == 'production' ? (@serve_assets = 'remote') : (@serve_assets = 'local_dynamic')\n end\n @serve_assets\n end",
"def javascript\n load_file_if_true( @config[\"custom_js\"], \"javascript.js\" )\n end",
"def overviewer_config_path\n 'javascript/overviewerConfig.js' if overviewer_config_path_exists?\n end",
"def javascript_path(path, options={})\n asset_path(path, :type => :javascript)\n end",
"def manifest_file_path\n site.assets_path.join(\"config/manifest.js\")\n end",
"def copy_js_files\n available_js.each do |name|\n filename = [name, :js].compact.join(\".\")\n case name\n when 'Controller'\n template \"js/#{filename}\", File.join(\"app/assets/javascripts/controller\", \"#{plural_table_name.capitalize}.js\") \n when 'Model'\n template \"js/#{filename}\", File.join(\"app/assets/javascripts/model\", \"#{singular_table_name.capitalize}.js\")\n when 'Store'\n template \"js/#{filename}\", File.join(\"app/assets/javascripts/store\", \"#{plural_table_name.capitalize}.js\")\n else\n template \"js/#{filename}\", File.join(\"app/assets/javascripts/view\", singular_table_name, filename)\n end\n end\n end",
"def js_path\n File.join(Merb.dir_for(:javascript), 'kin')\n end",
"def set_static_includes\r\n @javascripts = [JS_SCRIPTACULOUS_SKOBEE_DEFAULT, JS_SKOBEE_PLANS, JS_DATEPICKER, JS_JSON]\r\n end",
"def min_js_file\n build_path.join('scripts.min.js')\n end",
"def js(action)\n best_asset( action, Tension::JS )\n end",
"def required_js_files(context)\n scripts = ['right']\n config = RightRails::Config\n\n\n if config.include_scripts_automatically?\n # hooking up the 'rails' javascript module if required\n scripts << 'right/rails' if config.include_rails_module?\n\n # adding the modules if needed\n scripts += modules_registry_for(context).collect do |package|\n \"right/#{package}\"\n end\n\n # swapping to the sources in the development mode\n if config.swap_builds_and_sources? && config.dev_env?\n scripts = scripts.collect do |package|\n \"#{package}-src\"\n end\n end\n\n # loading up the locales if available\n if defined?(I18n)\n locale_file = \"#{config.locales_path}/#{I18n.locale.to_s.downcase}\"\n\n if File.exists? \"#{locale_file}.js\"\n scripts << locale_file.slice(config.public_path.size + \"/javascripts/\".size, locale_file.size)\n end\n end\n end\n\n # switching to CDN server if asked\n if !config.dev_env? && config.use_cdn_in_production?\n scripts.map! do |script|\n header = File.read(\"#{config.public_path}/javascripts/#{script}.js\", 100)\n\n if version = header[/\\d+\\.\\d+\\.\\d+/]\n script += \"-#{version}\"\n end\n\n if script.slice(0, 6) == 'right/' # plugins and modules\n script.gsub! 'right/', (\n header.include?('/ui/') ? 'ui/' : 'plugins/'\n )\n script.gsub! 'plugins/', '' if script.include?('/i18n/')\n end\n\n \"#{config.cdn_url}/#{script}.js\"\n end\n end\n\n scripts\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a static route in EOS. May add or overwrite an existing route. ===Commands ip route [router_ip] [distance] [tag ] [name ]
|
def create(destination, nexthop, opts = {})
cmd = "ip route #{destination} #{nexthop}"
cmd << " #{opts[:router_ip]}" if opts[:router_ip]
cmd << " #{opts[:distance]}" if opts[:distance]
cmd << " tag #{opts[:tag]}" if opts[:tag]
cmd << " name #{opts[:name]}" if opts[:name]
configure cmd
end
|
[
"def create_route(route_table_id, destination_cidr_block, options = {})\n request_hash = { 'RouteTableId' => route_table_id,\n 'DestinationCidrBlock' => destination_cidr_block }\n request_hash['GatewayId'] = options[:gateway_id] unless options[:gateway_id].right_blank?\n request_hash['InstanceId'] = options[:instance_id] unless options[:instance_id].right_blank? \n link = generate_request(\"CreateRoute\", request_hash)\n request_info(link, RightHttp2xxParser.new(:logger => @logger))\n rescue Exception\n on_exception\n end",
"def add_route(station, line)\n Neo4j::Transaction.run do\n rel = Neo4j::Relationship.create(:route, self, station)\n rel[:distance] = 1.0\n rel[:line] = line\n end\n\n self\n end",
"def add_route(point, distance)\n Neo4j::Transaction.run do\n rel = Neo4j::Relationship.create(:route, self, point)\n rel[:distance] = distance.to_f\n end\n\n self\n end",
"def post_route(route, message)\n raise TypeError unless route.is_a? Route\n @changeset = @api.create_changeset(message, tags={'created_by'=>'ITCR'})\n ways_list = []\n nodes_list = create_node_list(route.path)\n\n until nodes_list.empty? # For node's maximum limit of a way\n way_nodes = nodes_list.take(MAX_NODES)\n nodes_list = nodes_list.drop(MAX_NODES)\n way_id = create_way(way_nodes)\n ways_list << way_id\n end\n\n relation = create_relation(ways_list) # Link ways to relation\n relation = add_stops(relation, route.stops) # Add bus stops to relation\n\n @api.save(relation, @changeset) # Save relation using the API\n puts 'Relation created succesfuly.'\n @api.close_changeset(@changeset)\n @changeset.id\n end",
"def create_route(route_list)\n @route_gen.info_list = route_list\n id = @route_gen.gen_id\n path = @route_gen.gen_path\n stops = gen_stops\n path = @route_gen.insert_stops_in_path(path, stops)\n\n #Insert start and end point as stops\n stops.insert(0,Stop.new(\"Punto inicial de la ruta\",path.first))\n #stops.append(Stop.new(\"Punto final de la ruta\",path.last))\n\n route = Route.new(id, path, stops)\n route\n end",
"def aws_instance_create_route_to_nat(instance)\n log \"AWS: creating Route for Subnet '#{self.subnet.driver_id}' to NAT Instance '#{self.driver_id}'\"\n self.scenario.subnets.select { |s| s.driver_id and !s.internet_accessible }.each do |subnet|\n aws_call('aws_subnet_route_table_route_to_nat_create', subnet_id: subnet.driver_id, instance_id: instance.id)\n end\n end",
"def addRoute(city1, city2, distance)\n @routes[city1].push(EndpointCity.new(city2, distance))\n @routes[city2].push(EndpointCity.new(city1, distance))\n end",
"def route\n router = packet['route.router']\n raise 'Router not found' unless router\n router.route(self)\n end",
"def add_static_route(logical_router_id, static_route, opts = {})\n data, _status_code, _headers = add_static_route_with_http_info(logical_router_id, static_route, opts)\n data\n end",
"def add_static_route(logical_router_id, static_route, opts = {})\n data, _status_code, _headers = add_static_route_with_http_info(logical_router_id, static_route, opts)\n return data\n end",
"def create_route(title, distance, locations, mode_of_travel = \"driving\", accepted_deviation = 0)\n begin\n route_class = ModelFabric.get_class(SocialFramework.route_class)\n location_class = ModelFabric.get_class(SocialFramework.location_class)\n\n return unless mode_of_travel == \"driving\" or mode_of_travel == \"bicycling\" or\n mode_of_travel == \"walking\" or mode_of_travel == \"transit\"\n route = route_class.new title: title, distance: distance,\n mode_of_travel: mode_of_travel, accepted_deviation: accepted_deviation\n route.users << self\n route.save\n\n locations.each do |location|\n new_location = location_class.create route: route, latitude: location[:latitude],\n longitude: location[:longitude]\n end\n return route\n rescue\n route.destroy unless route.nil?\n Rails.logger.warn \"Couldn't create route\"\n return\n end\n end",
"def create\n config_set('route_map', 'create', @set_args)\n end",
"def create(pid)\n configure \"router ospf #{pid}\"\n end",
"def create\n Feature.ospf_enable\n config_set('ospf', 'router', state: '', name: @name)\n wait_for_process_initialized\n end",
"def route(str)\n str = str.chomp\n str = \" #{str}\" unless str =~ /\\n/\n insert_into_file \"config/routes.rb\", \"#{str}\\n\", before: /^end\\n/\nend",
"def add(entry)\n _check_open!\n ::Dnet.route_add(@handle, entry)\n end",
"def update_network_static_route(options = {})\r\n # Validate required parameters.\r\n validate_parameters(\r\n 'network_id' => options['network_id'],\r\n 'static_route_id' => options['static_route_id']\r\n )\r\n # Prepare query url.\r\n _path_url = '/networks/{networkId}/staticRoutes/{staticRouteId}'\r\n _path_url = APIHelper.append_url_with_template_parameters(\r\n _path_url,\r\n 'networkId' => options['network_id'],\r\n 'staticRouteId' => options['static_route_id']\r\n )\r\n _query_builder = Configuration.base_uri.dup\r\n _query_builder << _path_url\r\n _query_url = APIHelper.clean_url _query_builder\r\n # Prepare headers.\r\n _headers = {\r\n 'accept' => 'application/json',\r\n 'content-type' => 'application/json; charset=utf-8'\r\n }\r\n # Prepare and execute HttpRequest.\r\n _request = @http_client.put(\r\n _query_url,\r\n headers: _headers,\r\n parameters: options['update_network_static_route'].to_json\r\n )\r\n CustomHeaderAuth.apply(_request)\r\n _context = execute_request(_request)\r\n validate_response(_context)\r\n # Return appropriate response type.\r\n decoded = APIHelper.json_deserialize(_context.response.raw_body) unless\r\n _context.response.raw_body.nil? ||\r\n _context.response.raw_body.to_s.strip.empty?\r\n decoded\r\n end",
"def create_route(attributes)\n \n unless attributes[:source_data_set_id]\n attributes[:source_data_set_id] = attributes[:source_data_set] && attributes[:source_data_set].id || nil\n end\n \n attributes[:category] ||= attributes[:category_id] \n attributes[:category] = attributes[:category].id if attributes[:category].kind_of? PublicEarth::Db::Category\n\n place = new(one.create_route(\n nil, \n attributes[:name], \n attributes[:route_vertexes] || nil,\n attributes[:original_id], \n attributes[:original_uri], \n attributes[:priority],\n attributes[:category],\n attributes[:source_data_set_id],\n attributes[:is_visible] || true\n ))\n \n place.created = 'route'\n \n # Create the name attribute...\n place.details.from attributes[:source_data_set_id]\n place.details.name = attributes[:name]\n place.details.save\n \n place\n end",
"def add_route(route)\n @routes << route\n route\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Validates that role exists in config file
|
def role_valid
if (APP_CONFIG["user_roles"]+SYSTEM_DATA["user_roles"]).select{|role| role["name"] == self.role}.empty?
errors.add(:role, "Role does not exist in config")
end
end
|
[
"def validate_role(role)\n if @role_config.include?(role)\n role\n else\n raise UndefinedRole, \"#{role.inspect} not defined\"\n end\n end",
"def validate(role, _environments, cookbooks, roles) # rubocop:disable CyclomaticComplexity\n # validate the role passed in match the name of either the .rb or .json\n file = %W{roles/#{role}.rb roles/#{role}.json}.find { |f| File.exist?(f) }\n role = role.split(\"/\").last if role =~ /\\// # pull out directories\n if file\n c_role = evaluate_c_role(file)\n Spiceweasel::Log.debug(\"role: '#{role}' name: '#{c_role.name}'\")\n unless role.eql?(c_role.name)\n STDERR.puts \"ERROR: Role '#{role}' listed in the manifest does not match the name '#{c_role.name}' within the #{file} file.\"\n exit(-1)\n end\n role_run_list(c_role, cookbooks, role, roles)\n else # role is not here\n STDERR.puts \"ERROR: Invalid Role '#{role}' listed in the manifest but not found in the roles directory.\"\n exit(-1)\n end\n end",
"def role_exists?(project_root, role_name)\n Dir.exists?(\"#{project_root}/puppet/roles/#{role_name}\")\n end",
"def role_exists?(iam_client, role_name)\n response = iam_client.get_role(role_name: role_name)\n return true if response.role.role_name\nrescue StandardError => e\n puts \"Error while determining whether the role \" \\\n \"'#{role_name}' exists: #{e.message}\"\nend",
"def valid_role? role\n valid_roles.include? role.to_s.downcase.to_sym\n end",
"def validate\n return false if @role_array.empty?\n\n @role_array.each do |role|\n return false unless ROLES[role]\n end\n\n return true\n end",
"def role?(role)\n keys.include?(role)\n end",
"def has_role?(role_name)\n role_identifiers.include? role_name\n end",
"def role_required?\n @role_required || false\n end",
"def config_member?\n self.role.is_a? ConfigRole\n end",
"def must_have_a_role\n errors.add(:roles, \"Must have a staff or admin role\") unless admin_or_staff?\n end",
"def has_role?(arg) \n if arg.is_a?(Array)\n required_roles = arg.collect {|role| role.to_s}\n else\n required_roles = arg.to_s.to_a\n end\n not (self.roles.to_s.split(' ') & required_roles).empty?\n end",
"def role?(role)\n role_registry.has?(role)\n end",
"def validate_aws_config_file!\n config_file = config[:aws_config_file]\n Chef::Log.debug \"Using AWS config file at #{config_file}\"\n\n raise ArgumentError, \"The provided --aws_config_file (#{config_file}) cannot be found on disk.\" unless File.exist?(config_file)\n\n aws_config = ini_parse(File.read(config_file))\n profile_key = config[:aws_profile]\n profile_key = \"profile #{profile_key}\" if profile_key != \"default\"\n\n unless aws_config.values.empty?\n if aws_config[profile_key]\n config[:region] = aws_config[profile_key][\"region\"]\n else\n raise ArgumentError, \"The provided --aws-profile '#{profile_key}' is invalid.\"\n end\n end\n end",
"def isAnsibleRole?(path)\n begin\n Dir.foreach(path) { |entry|\n if File.directory?(path+\"/\"+entry) and\n [\"tasks\", \"vars\"].include?(entry)\n return true # https://knowyourmeme.com/memes/close-enough\n elsif [\"metadata.rb\", \"recipes\"].include?(entry)\n return false\n end\n }\n rescue Errno::ENOTDIR\n end\n false\n end",
"def validate_config\n return if File.readable?(config_file)\n\n raise Errno::EACCES, \"#{config_file} is not readable\"\n\n # FIX ME: need to validate contents/structure?\n end",
"def has_role?(name)\n roles.include? to_role_name(name)\n end",
"def role_exists?(iam_client, role_arn)\n puts \"Searching for role with ARN '#{role_arn}'...\"\n response = iam_client.list_roles\n if response.roles.count.positive?\n if role_found?(response.roles, role_arn)\n puts \"Role found.\"\n return true\n end\n while response.next_page? do\n response = response.next_page\n if response.roles.count.positive?\n if role_found?(response.roles, role_arn)\n puts \"Role found.\"\n return true\n end\n end\n end\n end\n puts \"Role not found.\"\n return false\nrescue StandardError => e\n puts \"Role not found: #{e.message}\"\n return false\nend",
"def require_valid_role\n @role = params[:role]\n unless UserRole::ALL_ROLES.include?(@role)\n flash[:error] = t('user_role.filter.not_a_role', :role => @role)\n redirect_to :controller => 'user', :action => 'view', :display_name => @this_user.display_name\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Clear all tokens that have expired
|
def clear_expired_tokens
access_tokens.where("token_expire < ?", Time.now).destroy_all
end
|
[
"def expire_all_tokens!\n tokens.map(&:expire!)\n end",
"def revoke_all_tokens\n token_expiration = DateTime.now + JWTAuth::JWTAuthenticator.refresh_exp\n active_tokens = self.active_tokens\n\n return if active_tokens.blank?\n\n ActiveToken.transaction do\n active_tokens.each { |token| token.update(exp: token_expiration) }\n end\n end",
"def cleantokenlist\n current_time = Time.now.to_i\n Token.where(:expires_on.lt => current_time).delete\n end",
"def expire_access_tokens\n access_tokens.not_expired.update_all(expired_at: Time.now)\n end",
"def clear_all_expired\n t = Time.now\n\n @cache.each_pair do |name, entry|\n clear_if_expired(name, entry, t)\n end\n end",
"def expired!\n @token = @expires_at = nil\n end",
"def delete_all_expired_for(time)\n expired_for(time).delete_all\n end",
"def invalidate_tokens!\n increment!(:token_version)\n end",
"def delete_token\n expired_tokens = BlacklistedJwtToken.expired\n if expired_tokens\n expired_tokens.delete_all\n end\n\n render nothing: true\n end",
"def invalidate_tokens\n increment(:token_version)\n end",
"def clear_access_token\n update_access_token(nil)\n end",
"def invalidate\n @access_token = nil\n end",
"def expire_reset_tokens\n ResetToken.where(user_id: self.id).each(&:mark_used)\n end",
"def revoke!\n return if revoked?\n update(revoked_at: Time.now)\n tokens.update_all(revoked_at: Time.now, updated_at: Time.now)\n end",
"def clean_expired!\n sessions.remove( { :expire => { '$lt' => Time.now } } )\n end",
"def delete_expired\n @values.delete_expired\n end",
"def clear_expired(request)\n entries_for(request)\n .where {|t| t.created_at < Time.now - ttl }\n .delete\n end",
"def remove_expired_keys\n self.user_key.each do |user_key|\n if user_key.expired?\n self.remove_user_key(user_key)\n user_key.delete\n end\n end\n end",
"def clear_auth_token\n self.auth_token = nil\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
create new FantasyStat load_tournament_list load_tournament_game_data create_leagues load_player_data
|
def load_fantasy_stats
load_tournament_list
load_tournament_game_data
create_leagues
load_player_data
end
|
[
"def create_teams\n # Get relevant players data and balance for team creation.\n players_pool = users.pluck(:user_id, :rating)\n balanced_teams_hash = balance_players(players_pool)\n\n # Create real teams for match with the balanced team hash.\n Team.create_for_match(balanced_teams_hash, id)\n save_users_and_attributes(:id, :name, :rating, :status,\n :facebook_link, :donator,\n :win_count, :lose_count)\n end",
"def create_teams_from_teams_playoffs()\n end",
"def create_stat_team_data\n # all_teams_hashes \n # <---- calls the API we should only to this once when seeding the data\n \n $Total_arr.each do |team|\n Stat.create_or_find_by(\n team_api_id: team['team']['id'],\n team_name: team['team']['name'],\n wins: team['won'],\n draws: team['draw'],\n losses: team['lost'],\n goals_for: team['goalsFor'],\n goals_against: team['goalsAgainst'],\n standing: team['position'],\n )\n end\nend",
"def create_players\n\t\t\tend",
"def create_match(match_data)\n participants = match_data[\"participantIdentities\"]\n for participant in participants do\n # Create a new Match object.\n match = Match.new\n # Set the Match's summoner_id field.\n summoner = create_summoner(participant[\"player\"][\"summonerName\"])\n match.summoner_id = summoner.id\n # Set the Match's champion_id and win field.\n participant_data = match_data[\"participants\"]\n current_summoner = participant_data.find do |data|\n data[\"participantId\"] == participant[\"participantId\"]\n end\n match.champion_id = Champion.find_by(champ_id: current_summoner[\"championId\"]).id\n match.win = current_summoner[\"stats\"][\"win\"]\n # Set the Match's game_id field.\n match.game_id = match_data[\"gameId\"]\n # Set the Match's ban field.\n bans = match_data[\"teams\"][0][\"bans\"] + match_data[\"teams\"][1][\"bans\"]\n if bans.empty?\n match.ban = -1\n else\n match.ban = bans.find {|ban| ban[\"pickTurn\"] == participant[\"participantId\"]}[\"championId\"]\n end\n # Save the Match to the database!\n match.save\n end\nend",
"def create_empty_league\n # no op\n end",
"def seed_sf_challonge\n File.open(\"lib/assets/tournament.json\", 'r') do |f|\n f.each_line.with_index do |line, i|\n puts i + 1 #keep track file running when seeding data\n players_hash = {}\n tournament_object = JSON.parse(line)['tournament']\n date = tournament_object['started_at'].split('T')[0]\n\n tournament_object['participants'].each do |participant|\n id = participant['participant']['id']\n player_name = remove_player_tag(participant['participant']['name'])\n\n players_hash[id] = player_name\n end\n\n tournament_object['matches'].each do |match|\n player_1 = players_hash[match['match']['player1_id']]\n player_2 = players_hash[match['match']['player2_id']]\n game = tournament_object['game_name']\n score = match['match']['scores_csv']\n winner_id = players_hash[match['match']['winner_id']]\n\n seed_data(player_1, player_2, winner_id, score, game, date)\n end\n end\n end\nend",
"def load_teams_from_leagues\n logout\n login\n PrivateLeague.all.each do |pl|\n puts \"Pulling Data from Teams for PL #{pl.name}:#{pl.league_id}\"\n visit_league_url(pl.league_id)\n sleep(5)\n all_teams.each do |url, name|\n puts \" #{name} : #{url.split('=')[1]}\"\n @team = Team.find_or_create_by_team_id(url.split(\"=\")[1]) \n @team.private_league_id = pl.league_id\n @team.save!\n end\n end\n end",
"def create\n #Setting up the players \n setup = SetupPlayers.run(params[:players])\n t_size = setup[:t_size]\n player_names = setup[:player_names]\n \n #Tournament creation\n if (t_size != 'too big')\n tournament = Tournament.new(tournament_params)\n tournament.size = t_size\n if (tournament.save)\n #Match setup for the tournament\n SetupMatches.run(tournament, t_size, player_names)\n redirect_to tournament_path(tournament.id)\n else\n #Tournament name was blank\n flash[:alert] = \"Tournament name must not be empty!\"\n redirect_to group_path(params[:tournament][:group_id])\n end\n else\n #error tournament size is too big\n flash[:alert] = \"You chose a size that is currently unsupported. Please choose less participants.\"\n redirect_to group_path(params[:tournament][:group_id])\n end\n\n end",
"def new_game\n params_check(params[:player_names]) {\n @game = Game.create\n params[:player_names].split(\",\").each do |player_name|\n player = Player.create(name: player_name, game: @game)\n 10.times do |i|\n i == 10 ? Frame.create!(game: @game, player: player, position: i, final_frame: true) : Frame.create!(game: @game, player: player, position: i + 1)\n end\n end\n players = @game.players.map{ |player| { \"#{player.name}\": player.id } }\n process_response(@game.present?, \"Congratulations, you started a new game. Here's your game id: #{@game.id} and player data: #{players}\", @game.id)\n }\n end",
"def create\n server = params[:summoner][:server].downcase\n name = params[:summoner][:name].downcase\n\n @summoner = Summoner.new(summoner_params)\n @summoner.user_id = current_user.id\n\n search_string = \"https://community-league-of-legends.p.mashape.com/api/v1.0/#{server}/summoner/getSummonerByName/#{name}\"\n response = Unirest.get(search_string)\n\n if response.code == 200 && response.body[\"summonerLevel\"] == 30\n @summoner.name = response.body[\"name\"]\n @summoner.icon_id = response.body[\"profileIconId\"]\n @summoner.riot_id = response.body[\"summonerId\"]\n @summoner.acct_id = response.body[\"acctId\"]\n \n search_string = \"https://community-league-of-legends.p.mashape.com/api/v1.0/#{server}/summoner/getLeagueForPlayer/#{@summoner.riot_id}\"\n response = Unirest.get(search_string)\n\n if response.code == 200\n response.body[\"entries\"][\"array\"].each do |entry|\n if entry[\"playerOrTeamName\"] == response.body[\"requestorsName\"]\n @summoner.league = entry\n end\n end\n end\n\n search_string = \"https://community-league-of-legends.p.mashape.com/api/v1.0/#{server}/summoner/retrieveTopPlayedChampions/#{@summoner.acct_id}\"\n response = Unirest.get(search_string)\n\n if response.code == 200\n @summoner.most_played = {}\n response.body[\"array\"].each do |value|\n value[\"stats\"][\"array\"].each do |stat|\n if stat[\"statType\"] == \"TOTAL_SESSIONS_PLAYED\"\n @summoner.most_played[\"#{stat[\"championId\"]}\"] = \"#{stat[\"value\"]}\"\n end\n end\n end\n end\n\n search_string = \"https://community-league-of-legends.p.mashape.com/api/v1.0/#{server}/summoner/getSummonerHonor/#{@summoner.acct_id}\"\n response = Unirest.get(search_string)\n\n if response.code == 200\n @summoner.honor = response.body\n end\n end\n\n respond_to do |format|\n if @summoner.save\n format.html { redirect_to @summoner, notice: 'Summoner was successfully created.' }\n format.json { render action: 'show', status: :created, location: @summoner }\n else\n format.html { render action: 'new' }\n format.json { render json: @summoner.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_game_profile\n\t\tscrape_top_games_index.each do |game| \n\t\t\tTop100Games::Game.create_from_index(game) \n\t\t\tbinding.pry\n\t\tend\n\tend",
"def create_team_poolplay\n pool = self.poolplay_teams # Team objects\n save_team_play_to_database(tournament_id, pool, \"poolplay\")\n end",
"def player_data(player)\n players = ScoreBoard.new()\n players.player = player.id\n players.score = player.score \n players\nend",
"def create_players\n #Retrieve an array of player name (via class View)\n players = @view.create_players\n\n #Use this array to create the two players\n @player_one = Player.new(players[0])\n @player_two = Player.new(players[1])\n end",
"def create_teams_for_sport(sport, num_players)\n current_year = Time.new.year\n classes = (current_year..current_year+4).to_a # for the players\n\n College.all.each do |c|\n team = Team.new\n team.college = c # for now\n team.name = c.name\n team.description = sport.description\n team.sport = sport\n\n # players\n create_players(team, classes, num_players)\n team.save \n end \nend",
"def create\n # render text: params\n @tournament_stat = TournamentStat.new(tournament_stat_params)\n\n respond_to do |format|\n if @tournament_stat.save\n format.html { redirect_to @tournament_stat, notice: 'Tournament stat was successfully created.' }\n format.json { render action: 'show', status: :created, location: @tournament_stat }\n else\n format.html { render action: 'new' }\n format.json { render json: @tournament_stat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @league = League.new(league_params)\n if @league.save\n render json: @league\n else\n render error: { error: \"Unable to create league.\"}, status: 400\n end\n end",
"def create_players\n players = []\n players << create_player('player_1')\n players << create_player('player_2')\n players\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
A pull request has been closed
|
def process_closed_pull_request(pull_request)
pr_name = pull_request['base']['repo']['full_name'].to_s
pr_number = pull_request['number'].to_s
pr_key = pr_name + ":" + pr_number
current_commit_hash = pull_request['head']['sha'].to_s
# Delete the PR from the redis store
@redis.del(pr_key)
return 200
end
|
[
"def close\n return unless request_exists?\n @github.close_issue source_repo, @current_request.number\n unless request_exists?('open', @current_request.number)\n puts 'Successfully closed request.'\n end\n end",
"def process_closed_pull_request(pull_request)\n pr_name = pull_request['base']['repo']['full_name'].to_s\n pr_number = pull_request['number'].to_s\n current_commit_hash = pull_request['head']['sha'].to_s\n\n # Delete the PR from the redis store\n @redis.del(pr_name + \":\" + pr_number)\n return 200\n end",
"def pull_request_close(organization, repo, pr_number)\n IssueClose.new(organization, repo, pr_number, type: \"pulls\").met?\n end",
"def close_existing\n prs = @gh_conn.pull_requests(@repo.name)\n\n # find any open PRs by cookstyle bot\n prs.filter! { |x| x[:user][:login] == \"cookstyle[bot]\" && x[:state] == \"open\" }\n\n # We only want to close out the oldest PR if there's 2 or more\n return unless prs.count >= 2\n\n # sort by created date, drop the last one (current), and then close each old one why not\n # just assume there's only a new and old? Well what if someone reopens it or something\n # odd happens and the old one is never closed? Might as well assume 2+ to close\n old_prs = prs.sort_by { |pr| pr[:created_at] }\n old_prs.pop\n old_prs.each do |old_pr|\n @gh_conn.add_comment(@repo.name, old_pr[:number], \"Closing this pull request as it has been superseded by https://github.com/#{@repo.name}/pull/#{@number}, which was created with Cookstyle #{Cookstyle::VERSION}.\")\n @gh_conn.close_pull_request(@repo.name, old_pr[:number])\n end\n end",
"def close_pull_request(repo, number, options = {})\n options.merge! :state => 'closed'\n update_pull_request(repo, number, options)\n end",
"def reopen_succesfull_pull(repo, pull_request_id)\n client.update_pull_request(repo, pull_request_id, nil, nil, PR_OPEN_STATE)\n client.remove_label(repo, issue_id, CI_FAILED_LABEL)\n end",
"def hendl_pr(original)\n puts \"#{original.number} is a pull request\"\n if original.state != \"open\"\n puts \"#{original.number} is already closed - nothing to do here\"\n return\n end\n\n body = [\"Hello @#{original.user.login},\"]\n body << reason\n body << \"Sorry for the troubles, we'd appreciate if you could re-submit your Pull Request with these changes to the new repository\"\n\n client.add_comment(source, original.number, body.join(\"\\n\\n\"))\n smart_sleep\n client.close_pull_request(source, original.number)\n end",
"def closed_pull_requests\n OctocatHerder::PullRequest.find_closed_for_repository(owner_login, name, connection)\n end",
"def reject_failing_pull(repo, pull_request_id)\n client.close_pull_request(repo, pull_request_id)\n client.add_labels_to_an_issue(repo, pull_request_id, [CI_FAILED_LABEL])\n end",
"def close(number)\n request = get_request_by_number(number)\n repo = github.source_repo\n github.close_issue(repo, request.number)\n unless github.request_exists?('open', request.number)\n puts 'Successfully closed request.'\n end\n end",
"def close\n client.close_issue(repository, number)\n end",
"def fetch_closed_pull_requests\n pull_requests = []\n options = { state: \"merged\", scope: :all }\n\n @client.merge_requests(@project_id, options).auto_paginate do |new_pr|\n new_pr = stringify_keys_deep(new_pr.to_hash)\n # align with Github naming\n new_pr[\"number\"] = new_pr[\"iid\"]\n new_pr[\"html_url\"] = new_pr[\"web_url\"]\n new_pr[\"merged_at\"] = new_pr[\"updated_at\"]\n new_pr[\"pull_request\"] = true\n new_pr[\"user\"] = { login: new_pr[\"author\"][\"username\"], html_url: new_pr[\"author\"][\"web_url\"] }\n # to make it work with older gitlab version or repos that lived across versions\n new_pr[\"merge_commit_sha\"] = new_pr[\"merge_commit_sha\"].nil? ? new_pr[\"sha\"] : new_pr[\"merge_commit_sha\"]\n pull_requests << new_pr\n end\n\n print_empty_line\n\n GitHubChangelogGenerator::Helper.log.info \"Pull Request count: #{pull_requests.count}\"\n pull_requests.map { |pull_request| stringify_keys_deep(pull_request.to_hash) }\n end",
"def open_pull_request\n outgoing_pull_requests.find(&:open?)\n end",
"def reopen_pull(repo, pull_number, options = {})\n options[:state] = 'open'\n patch \"#{Repository.path repo}/pulls/#{pull_number}\", options\n end",
"def close_issue(owner, repo, number, options={})\n Issues.patch(\"/repos/#{owner}/#{repo}/issues/#{number}\",:headers => @auth, :body => options.to_json) #needs auth\n end",
"def alert_reserved_and_exit\n cli.say \"The current branch #{config.github_repo}/#{git.current_branch} is a reserved branch and can not have pull requests.\"\n exit 1\n end",
"def dismiss_pull_request_review(repo, number, review, message, options = T.unsafe(nil)); end",
"def pull_request\n get\n end",
"def pull_request\n @pull_request ||= client.pull_request(repo, number)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
A PR review has been reported
|
def process_created_review(review_payload)
pr_name = review_payload['repository']['full_name'].to_s
pr_number = review_payload['pull_request']['number'].to_s
comment_user = review_payload['review']['user']['id'].to_s
approvals = evaluate_review_state(review_payload['review']['state'])
current_commit_hash = review_payload['pull_request']['head']['sha'].to_s
submit_status(pr_name, pr_number, current_commit_hash, comment_user, approvals)
end
|
[
"def submit_pull_request_review(repo, number, review, event, options = T.unsafe(nil)); end",
"def atest_ID_25863_reposted_review()\n # Need clarification\n end",
"def pull_request_review?\n github_event == 'pull_request_review'\n end",
"def print_pr_resume(prs)\n if prs.any?\n puts \"[PRS=#{prs.any?}] PRs opened. Analyzing them...\"\n return\n end\n if @options[:changed_since] >= 0\n puts \"[PRS=#{prs.any?}] No Pull Requests opened or with changes \" \\\n \"newer than #{options[:changed_since]} seconds\"\n else\n puts \"[PRS=#{prs.any?}] No Pull Requests opened\"\n end\n end",
"def submit\n general_violations = generate_general_violations\n submission_body = generate_body\n\n # If the review resolver says that there is nothing to submit we skip submission\n return unless ReviewResolver.should_submit?(self, submission_body)\n\n @review_json = @client.create_pull_request_review(@ci_source.repo_slug, @ci_source.pull_request_id, event: generate_event(general_violations), body: submission_body)\n end",
"def apply(pr, pull_request_hash)\n if !previously_applied?(pr) && matches?(pull_request_hash)\n add_reviewer(pr)\n end\n end",
"def review_requested?\n github_event == 'review_requested'\n end",
"def pre_artwork_complete(design)\n\n pre_art_review_type = ReviewType.get_pre_artwork\n pre_art_design_review = design.design_reviews.detect { |dr| \n dr.review_type_id == pre_art_review_type.id\n }\n\n done = ReviewStatus.find_by_name('Review Completed')\n done.id == pre_art_design_review.review_status_id\n \n end",
"def pull_request_reviews(repo, number, options = T.unsafe(nil)); end",
"def review\n # record a payment exemption if there is one, before submission\n @resource&.identifier&.record_payment\n end",
"def report_success\n set_status(\"success\", pull_request? ? \"PR Preview\" : \"Branch Preview\")\nend",
"def review(post, approved = false)\n # reporter and reviewer cannot be same person\n return if post.reported_by == self or post.reported_by.nil?\n # cannot review unless is a site admin or a category admin\n return unless able_to_review?(post)\n return if post.reviewed_by\n decision = approved ? 'positive' : 'negative'\n\n rev = Moderation.with(:post_id, post.id)\n rev.update(:reviewer => self, :result => decision)\n if approved\n sanction(post)\n post.reported_by.incr(:conduct_karma, 5)\n else\n post.reported_by.incr(:conduct_karma, -5)\n end\n\n rev\n end",
"def post_pcb_design_results(design_review, review_results)\n\n results = {:success => true,\n :alternate_msg => 'The following updates have been made - '}\n\n audit_skipped = design_review.design.audit.skip?\n \n if !audit_skipped &&\n (review_results[:designer][\"id\"] == '' ||\n review_results[:peer][\"id\"] == '')\n results[:success] = false\n results[:alternate_msg] = 'The Designer and Peer must be specified - results not recorded'\n elsif !audit_skipped &&\n (review_results[:designer][\"id\"] ==\n review_results[:peer][\"id\"])\n results[:success] = false\n results[:alternate_msg] = 'The Designer and Peer must be different - results not recorded'\n elsif audit_skipped && review_results[:designer][\"id\"] == ''\n results[:success] = false\n results[:alternate_msg] = 'The Designer must be specified - results not recorded'\n else\n design = design_review.design\n\n designer = User.find(review_results[:designer][\"id\"])\n design.designer_id = designer.id\n \n priority = Priority.find(review_results[:priority][\"id\"])\n priority_update = design.priority_id != priority.id\n design.priority_id = priority.id\n\n if !audit_skipped\n peer = User.find(review_results[:peer][\"id\"])\n design.peer_id = peer.id\n end\n \n design.save\n \n if !audit_skipped\n if peer.is_a_role_member?(\"Valor\")\n # set Valor reviewer as peer\n design.set_role_reviewer(Role::find_by_name(\"Valor\"), peer, @logged_in_user)\n else\n results[:alternate_msg] += \"Peer, #{peer.name}, does not have Valor reviewer role and was not assigned. \" \n end\n else\n results[:alternate_msg] += 'No Valor reviewer set (Audit Skipped) - '\n end\n\n for review in design.design_reviews\n review.priority_id = priority.id\n if (review.review_type.name != 'Release' &&\n review.review_type.name != 'Pre-Artwork')\n review.designer_id = designer.id\n end\n review.save\n end\n\n results[:alternate_msg] += \"Criticality is #{priority.name}, \" if priority_update\n results[:alternate_msg] += \"The Designer is #{designer.name}\"\n if !audit_skipped\n results[:alternate_msg] += \" and the Peer is #{peer.name}\"\n end\n\n end\n\n return results\n \nend",
"def on_synchronize\n number = @payload[\"number\"]\n\n if PullRequest.exists?(number: number)\n pr = PullRequest.find_by(number: number)\n\n status = \"pending\"\n description = \"Not all reviewers have approved. Comment \\\"LGTM\\\" to give approval.\"\n\n if pr.status == \"approved\"\n status = \"success\"\n description = \"Code review complete\"\n end\n\n pr_sha = @payload[\"pull_request\"][\"head\"][\"sha\"]\n\n github = Octokit::Client.new(access_token: ENV[\"CODY_GITHUB_ACCESS_TOKEN\"])\n github.create_status(\n @payload[\"repository\"][\"full_name\"],\n pr_sha,\n status,\n context: \"code-review/cody\",\n description: description,\n target_url: ENV[\"CODY_GITHUB_STATUS_TARGET_URL\"]\n )\n end\n end",
"def on_synchronize\n number = @payload[\"number\"]\n repository = @payload['repository']['full_name']\n\n if pr = PullRequest.find_by(number: number, repository: repository)\n\n status = \"pending\"\n description = \"Not all reviewers have approved. Comment \\\"LGTM\\\" to give approval.\"\n\n if pr.status == \"approved\"\n status = \"success\"\n description = \"Code review complete\"\n end\n\n pr_sha = @payload[\"pull_request\"][\"head\"][\"sha\"]\n\n github = Octokit::Client.new(access_token: Rails.application.secrets.github_access_token)\n github.create_status(\n @payload[\"repository\"][\"full_name\"],\n pr_sha,\n status,\n context: \"code-review/cody\",\n description: description,\n target_url: Setting.lookup(\"status_target_url\")\n )\n else\n CreateOrUpdatePullRequest.new.perform(@payload[\"pull_request\"])\n end\n end",
"def repost\n\n design_review = DesignReview.find(params[:design_review][:id])\n\n # Set the status for the design review.\n in_review = ReviewStatus.find_by_name('In Review')\n design_review.review_status_id = in_review.id\n design_review.posting_count += 1\n design_review.reposted_on = Time.now\n design_review.save\n\n review_results = \n design_review.design_review_results.delete_if { |rr| rr.result == 'WAIVED' }\n\n reviewer_list = {}\n params[:board_reviewers].each do |role_id, reviewer_id|\n reviewer_list[role_id.to_i] = reviewer_id.to_i\n end\n\n current_time = Time.now\n review_results.each do |review_result|\n\n if reviewer_list[review_result.role_id] != review_result.reviewer_id\n review_result.reviewer_id = reviewer_list[review_result.role_id]\n end\n review_result.result = 'No Response'\n review_result.reviewed_on = current_time\n review_result.save\n end\n \n\n # Store the comment if the designer entered one.\n if params[:post_comment][:comment] != \"\"\n DesignReviewComment.new(:comment => params[:post_comment][:comment],\n :user_id => @logged_in_user.id,\n :design_review_id => design_review.id).save\n end\n\n # Let everybody know that the design has been posted.\n DesignReviewMailer::design_review_posting_notification(design_review,\n params[:post_comment][:comment], true).deliver\n\n if design_review.design.design_center == @logged_in_user.design_center\n redirect_to(:action => 'index', :controller => 'tracker')\n else\n flash['notice'] = 'The design center is not set to your default location - ' +\n @logged_in_user.design_center.name\n redirect_to(:action => 'view', :id => design_review.id)\n end\n\n end",
"def pending_repost?\n self.review_status_id == ReviewStatus.find(:first,\n :conditions => \"name='Pending Repost'\").id\n end",
"def reviewed?\n @status == :reviewed\n end",
"def closed_submission_status\n 'Closed for Review'\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Evaluates and submits a status for the commodus review
|
def submit_status(pr_name, pr_number, current_commit_hash, comment_user, approvals)
pr_key = pr_name + ":" + pr_number
# Grab the stored payload
stored_payload_value = @redis.hget(pr_key, current_commit_hash)
# Ensure that a key actually exists
if !stored_payload_value.nil?
stored_payload = JSON.parse(stored_payload_value)
plus_ones = stored_payload['plus_one_count'].to_i
authors = stored_payload['authors']
creator = stored_payload['creator'].to_s
# Check if the commenting user is the creator or has already commented
is_comment_user_creator_or_author = authors.include?(comment_user) || creator === comment_user
plus_ones_to_add = is_comment_user_creator_or_author ? 0 : approvals
# If there is no net change
if plus_ones_to_add === 0
return 200
end
plus_ones = plus_ones + plus_ones_to_add
# Ensure the count isn't negative
if plus_ones < 0
plus_ones = 0
end
# Update authors list
if !authors.include?(comment_user)
authors.push(comment_user)
end
payload_to_store = {
:plus_one_count => plus_ones,
:authors => authors,
:creator => creator,
}
# Store the new payload data
@redis.hset(pr_key, current_commit_hash, payload_to_store.to_json)
if plus_ones >= NEEDED_PLUS_ONES
status = 'success'
else
status = 'pending'
end
@client.create_status(
pr_name,
current_commit_hash,
status,
{
'description' => '(' + plus_ones.to_s + '/' + NEEDED_PLUS_ONES.to_s + ') required approvals.',
'context' => 'robinpowered/commodus'
}
)
else
return 404
end
return 200
end
|
[
"def process_created_review(review_payload)\n pr_name = review_payload['repository']['full_name'].to_s\n pr_number = review_payload['pull_request']['number'].to_s\n comment_user = review_payload['review']['user']['id'].to_s\n approvals = evaluate_review_state(review_payload['review']['state'])\n current_commit_hash = review_payload['pull_request']['head']['sha'].to_s\n\n submit_status(pr_name, pr_number, current_commit_hash, comment_user, approvals)\n end",
"def update_review_status(status, user)\n \n if status && status.id != self.review_status_id &&\n (self.review_status.name == 'Review On-Hold' ||\n self.review_status.name == 'In Review')\n\n self.record_update('Review Status', \n self.review_status.name, \n status.name,\n user)\n\n if self.review_status.name == 'Review On-Hold'\n self.remove_from_hold(status.id)\n elsif self.review_status.name == 'In Review'\n self.place_on_hold\n end\n self.save\n \n true\n else\n false\n end \n \n end",
"def approval_of_admin\n status = params[:status]\n @order = Order.find(params[:id])\n @order.update_attributes!(:status => status)\n @order_email = Order.find(params[:id])\n if status == \"5\"\n @reviewer = @order.reviews.last.user\n OrderMailer.admin_review_approved(@order_email, @reviewer).deliver_now\n elsif status == \"6\"\n @reviewer = @order.reviews.last.user\n OrderMailer.admin_review_rejected(@order_email,@reviewer).deliver_now\n user = User.find(@order.user_id)\n user_orders_count = user.orders.count\n if user_orders_count == 1\n @order.update_attributes!(:status => 7)\n end\n end\n redirect_to admin_reviewed_by_reviewer_path , :notice => \"Order successfully updated.\"\n end",
"def on_synchronize\n number = @payload[\"number\"]\n repository = @payload['repository']['full_name']\n\n if pr = PullRequest.find_by(number: number, repository: repository)\n\n status = \"pending\"\n description = \"Not all reviewers have approved. Comment \\\"LGTM\\\" to give approval.\"\n\n if pr.status == \"approved\"\n status = \"success\"\n description = \"Code review complete\"\n end\n\n pr_sha = @payload[\"pull_request\"][\"head\"][\"sha\"]\n\n github = Octokit::Client.new(access_token: Rails.application.secrets.github_access_token)\n github.create_status(\n @payload[\"repository\"][\"full_name\"],\n pr_sha,\n status,\n context: \"code-review/cody\",\n description: description,\n target_url: Setting.lookup(\"status_target_url\")\n )\n else\n CreateOrUpdatePullRequest.new.perform(@payload[\"pull_request\"])\n end\n end",
"def submit\n general_violations = generate_general_violations\n submission_body = generate_body\n\n # If the review resolver says that there is nothing to submit we skip submission\n return unless ReviewResolver.should_submit?(self, submission_body)\n\n @review_json = @client.create_pull_request_review(@ci_source.repo_slug, @ci_source.pull_request_id, event: generate_event(general_violations), body: submission_body)\n end",
"def update_review_status_if_changes_substantial\n return unless @description.save_version?\n\n @description.update_review_status(@description.review_status)\n end",
"def post_pcb_design_results(design_review, review_results)\n\n results = {:success => true,\n :alternate_msg => 'The following updates have been made - '}\n\n audit_skipped = design_review.design.audit.skip?\n \n if !audit_skipped &&\n (review_results[:designer][\"id\"] == '' ||\n review_results[:peer][\"id\"] == '')\n results[:success] = false\n results[:alternate_msg] = 'The Designer and Peer must be specified - results not recorded'\n elsif !audit_skipped &&\n (review_results[:designer][\"id\"] ==\n review_results[:peer][\"id\"])\n results[:success] = false\n results[:alternate_msg] = 'The Designer and Peer must be different - results not recorded'\n elsif audit_skipped && review_results[:designer][\"id\"] == ''\n results[:success] = false\n results[:alternate_msg] = 'The Designer must be specified - results not recorded'\n else\n design = design_review.design\n\n designer = User.find(review_results[:designer][\"id\"])\n design.designer_id = designer.id\n \n priority = Priority.find(review_results[:priority][\"id\"])\n priority_update = design.priority_id != priority.id\n design.priority_id = priority.id\n\n if !audit_skipped\n peer = User.find(review_results[:peer][\"id\"])\n design.peer_id = peer.id\n end\n \n design.save\n \n if !audit_skipped\n if peer.is_a_role_member?(\"Valor\")\n # set Valor reviewer as peer\n design.set_role_reviewer(Role::find_by_name(\"Valor\"), peer, @logged_in_user)\n else\n results[:alternate_msg] += \"Peer, #{peer.name}, does not have Valor reviewer role and was not assigned. \" \n end\n else\n results[:alternate_msg] += 'No Valor reviewer set (Audit Skipped) - '\n end\n\n for review in design.design_reviews\n review.priority_id = priority.id\n if (review.review_type.name != 'Release' &&\n review.review_type.name != 'Pre-Artwork')\n review.designer_id = designer.id\n end\n review.save\n end\n\n results[:alternate_msg] += \"Criticality is #{priority.name}, \" if priority_update\n results[:alternate_msg] += \"The Designer is #{designer.name}\"\n if !audit_skipped\n results[:alternate_msg] += \" and the Peer is #{peer.name}\"\n end\n\n end\n\n return results\n \nend",
"def on_synchronize\n number = @payload[\"number\"]\n\n if PullRequest.exists?(number: number)\n pr = PullRequest.find_by(number: number)\n\n status = \"pending\"\n description = \"Not all reviewers have approved. Comment \\\"LGTM\\\" to give approval.\"\n\n if pr.status == \"approved\"\n status = \"success\"\n description = \"Code review complete\"\n end\n\n pr_sha = @payload[\"pull_request\"][\"head\"][\"sha\"]\n\n github = Octokit::Client.new(access_token: ENV[\"CODY_GITHUB_ACCESS_TOKEN\"])\n github.create_status(\n @payload[\"repository\"][\"full_name\"],\n pr_sha,\n status,\n context: \"code-review/cody\",\n description: description,\n target_url: ENV[\"CODY_GITHUB_STATUS_TARGET_URL\"]\n )\n end\n end",
"def submit_pull_request_review(repo, number, review, event, options = T.unsafe(nil)); end",
"def closed_submission_status\n 'Closed for Review'\n end",
"def test_update\n\n review_status = ReviewStatus.find(review_statuses(:in_review).id)\n review_status.name = 'Test'\n\n get(:update,\n { :review_status => review_status.attributes },\n cathy_admin_session)\n assert_equal('Update recorded', flash['notice'])\n assert_redirected_to(:action => 'edit', :id => review_status.id)\n assert_equal('Test', review_status.name)\n \n end",
"def update_status\n # If a thesis has been set to 'Pending publication' or 'Published', this\n # method cannot change it; other methods will set/revert that status.\n return if ['Pending publication', 'Published', 'Publication error'].include? publication_status\n\n # Still here? Then we proceed...\n # By default, a thesis is set to 'Not ready for production'\n self.publication_status = 'Not ready for publication'\n # If all qualifying conditions are met, then we set status to\n # 'publication review'. This will leave unchanged a thesis that was\n # already set to 'Pending publication' via another method.\n self.publication_status = 'Publication review' if evaluate_status\n # Please note that the 'pending publiation' and 'published' statuses can\n # not be set via this method - they get assigned elsewhere.\n end",
"def pre_artwork_complete(design)\n\n pre_art_review_type = ReviewType.get_pre_artwork\n pre_art_design_review = design.design_reviews.detect { |dr| \n dr.review_type_id == pre_art_review_type.id\n }\n\n done = ReviewStatus.find_by_name('Review Completed')\n done.id == pre_art_design_review.review_status_id\n \n end",
"def assignment_update\n\n assignment = OiAssignment.find(params[:assignment][:id])\n completed = !assignment.complete? && ( params[:status][:status_id] == '1' || params[:status][:status_id] == '2' )\n reset = assignment.complete? && params[:status][:status_id] == '0'\n status_change = ( assignment.complete.to_s != params[:status][:status_id] )\n \n if completed || reset || status_change\n assignment.complete = params[:status][:status_id]\n assignment.completed_on = Time.now if completed\n end\n\n assignment.cc_hw_engineer = params[:assignment][:cc_hw_engineer] == '1'\n assignment.save\n \n post_comment = \"\"\n \n if completed || reset || status_change \n post_comment = \"-- TASK COMPLETE --\\n\" if params[:status][:status_id] == '1'\n post_comment = \"-- TASK CANCELLED --\\n\" if params[:status][:status_id] == '2'\n post_comment = \"-- TASK REOPENED --\\n\" if reset\n end\n \n post_comment += params[:post_comment][:comment]\n \n if post_comment.size > 0\n \n OiAssignmentComment.new(:comment => post_comment,\n :user_id => @logged_in_user.id,\n :oi_assignment_id => assignment.id).save\n\n flash['notice'] = 'The work assignment has been updated - mail sent'\n OiInstructionMailer.oi_task_update(assignment, @logged_in_user, \n completed, reset).deliver\n else\n flash['notice'] = 'No updates included with post - the work assignment has not been updated'\n end\n \n redirect_to(:action => 'assignment_view', :id => assignment.id)\n \n end",
"def repost\n\n design_review = DesignReview.find(params[:design_review][:id])\n\n # Set the status for the design review.\n in_review = ReviewStatus.find_by_name('In Review')\n design_review.review_status_id = in_review.id\n design_review.posting_count += 1\n design_review.reposted_on = Time.now\n design_review.save\n\n review_results = \n design_review.design_review_results.delete_if { |rr| rr.result == 'WAIVED' }\n\n reviewer_list = {}\n params[:board_reviewers].each do |role_id, reviewer_id|\n reviewer_list[role_id.to_i] = reviewer_id.to_i\n end\n\n current_time = Time.now\n review_results.each do |review_result|\n\n if reviewer_list[review_result.role_id] != review_result.reviewer_id\n review_result.reviewer_id = reviewer_list[review_result.role_id]\n end\n review_result.result = 'No Response'\n review_result.reviewed_on = current_time\n review_result.save\n end\n \n\n # Store the comment if the designer entered one.\n if params[:post_comment][:comment] != \"\"\n DesignReviewComment.new(:comment => params[:post_comment][:comment],\n :user_id => @logged_in_user.id,\n :design_review_id => design_review.id).save\n end\n\n # Let everybody know that the design has been posted.\n DesignReviewMailer::design_review_posting_notification(design_review,\n params[:post_comment][:comment], true).deliver\n\n if design_review.design.design_center == @logged_in_user.design_center\n redirect_to(:action => 'index', :controller => 'tracker')\n else\n flash['notice'] = 'The design center is not set to your default location - ' +\n @logged_in_user.design_center.name\n redirect_to(:action => 'view', :id => design_review.id)\n end\n\n end",
"def status_text\n\t\treturn \"Awaiting Review\" if (!complete && is_pending && !provPassReq)\n\t\treturn '<span style=\"color:#EEA236;\">Provisional Requested</span>' if (!complete && pass && provPassReq && !provPass)\n\t\treturn '<span style=\"color:#EEA236;\">Provisionally Passed</span>' if (complete && pass && provPassReq && provPass)\n\t\treturn \"In Progress\" if (!complete)\n\t\treturn '<span style=\"color:#009933;\">Test Passed</span>' if (complete && pass)\n\t\treturn '<span style=\"color:#B40404;\">Test Failed</span>' if (complete && !pass)\n\tend",
"def evaluate_review_state(state)\n net_pluses = 0\n\n if state == \"approved\"\n net_pluses = 1\n elsif state == \"changes_requested\"\n net_pluses = -1\n end\n\n return net_pluses\n end",
"def status(assignment, student)\n s = assignment.get_submission(student)\n if s\n if s.complete?\n return 'complete'\n # content_tag(:span, 'COMPLETE', class: \"radius success label\")\n # link_to \"Submitted URL\", s.url\n # link_to \"Review\", edit_assignment_submission_path(assignment.id, s)\n else\n return 'up_for_review'\n # content_tag(:span, 'UP FOR REVIEW', class: \"radius regular label\")\n # link_to \"Submitted URL\", s.url\n # link_to \"Review\", edit_assignment_submission_path(assignment.id, s)\n end\n else\n return 'no_submission'\n # content_tag(:span, 'NO SUBMISSION', class: \"radius alert label\")\n end\n end",
"def update\n learner_only\n respond_to do |format|\n if @session_review.update(session_review_params)\n @session_review.date = Date.today\n @session_review.save!\n r = @session_review.request\n r.status = \"Completed\"\n r.save!\n format.html { redirect_to @session_review, notice: 'Session review was successfully updated.' }\n format.json { render :show, status: :ok, location: @session_review }\n else\n format.html { render :edit }\n format.json { render json: @session_review.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Evaluates the PR review state
|
def evaluate_review_state(state)
net_pluses = 0
if state == "approved"
net_pluses = 1
elsif state == "changes_requested"
net_pluses = -1
end
return net_pluses
end
|
[
"def unreviewed_pr_ck(comm_st)\n puts comm_st.statuses[0]['state']\n @unreviewed_pr = false\n rescue NoMethodError\n @unreviewed_pr = true\n # in this situation we have no reviews-tests set at all.\n end",
"def releasable?; review_state? :ready; end",
"def reviewed?\n @status == :reviewed\n end",
"def recompute_all_states(options={})\n reviews.each_with_index do |review, i|\n t0 = Time.now\n nb_opinions = 0\n review.paragraphs.each do |paragraph|\n if options[:also_opinions]\n paragraph.opinions.each do |opinion|\n nb_opinions += 1\n opinion.update_status(get_products)\n opinion.accept! if opinion.to_review? and options[:force_to_review_ok]\n end\n end\n paragraph.update_status\n end\n review.update_status\n puts \"review #{i} processed in #{'%2.5f' % (Time.now - t0)} s for #{nb_opinions} opinions\"\n end\n true\n end",
"def post_next_review_prompt?(design)\n \n # Get the design review identified by the phase id\n next_design_review = design.design_reviews.detect { |dr| design.phase_id == dr.review_type_id }\n \n review_states = ['In Review',\n 'Pending Repost',\n 'Review Completed',\n 'Review On-Hold']\n !next_design_review ||\n !review_states.detect { |rs| rs == next_design_review.review_status.name }\n \n end",
"def atest_ID_25863_reposted_review()\n # Need clarification\n end",
"def on_reviewing_entry(state, event, *event_args)\n super\n\n if !simulating || !submission.auto_review\n __debug_sim('[auto_review: false]') if simulating\n __debug_sim('Waiting for reviewer evaluation.')\n __debug_sim('REVIEWER must `approve!` or `reject!` to advance...')\n\n elsif submission.auto_approve # TODO: remove\n __debug_sim('[auto_review: true]')\n __debug_sim('[auto_approve: true]')\n __debug_sim('SYSTEM review approves the submission.')\n\n approve! # NOTE: => :approved\n\n elsif submission.auto_reject # TODO: remove\n __debug_sim('[auto_review: true]')\n __debug_sim('[auto_reject: true]')\n __debug_sim('SYSTEM review rejects the submission.')\n\n reject! # NOTE: => :rejected\n\n else # TODO: remove\n __debug_sim('[auto_review: true]')\n __debug_sim('[auto_approve: false]')\n __debug_sim('[auto_reject: false]')\n __debug_sim('SYSTEM must `approve!` or `reject!` to advance...')\n\n end\n\n self\n end",
"def state_string\n if self.review_state == 0\n \"In Process\"\n else\n \"Completed\"\n end\n end",
"def reviewed?\n review_count = Review.where(user: user, essay: assignment.essays).count\n total_count = assignment.user_assignments.count\n total_count - review_count - 1 <= 0\n end",
"def test_can_mark_performance_correctly_based_on_reviews_from_the_wild\n sample = Employee.new(\"Sample Sampleson\", \"sample@email.com\", \"555-555-5555\", 40000)\n\n sample.add_review(communication_positive)\n assert_equal sample.is_satisfactory?, true\n\n sample.add_review(communication_negative)\n assert_equal sample.is_satisfactory?, false\n\n sample.add_review(cooperation_positive)\n assert_equal sample.is_satisfactory?, true\n\n sample.add_review(cooperation_negative)\n assert_equal sample.is_satisfactory?, false\n\n sample.add_review(job_knowledge_positive)\n assert_equal sample.is_satisfactory?, true\n\n sample.add_review(job_knowledge_negative)\n assert_equal sample.is_satisfactory?, false\n end",
"def pre_artwork_complete(design)\n\n pre_art_review_type = ReviewType.get_pre_artwork\n pre_art_design_review = design.design_reviews.detect { |dr| \n dr.review_type_id == pre_art_review_type.id\n }\n\n done = ReviewStatus.find_by_name('Review Completed')\n done.id == pre_art_design_review.review_status_id\n \n end",
"def process_created_review(review_payload)\n pr_name = review_payload['repository']['full_name'].to_s\n pr_number = review_payload['pull_request']['number'].to_s\n comment_user = review_payload['review']['user']['id'].to_s\n approvals = evaluate_review_state(review_payload['review']['state'])\n current_commit_hash = review_payload['pull_request']['head']['sha'].to_s\n\n submit_status(pr_name, pr_number, current_commit_hash, comment_user, approvals)\n end",
"def check_outstanding_reviews?(assignment, reviewer)\n @review_mappings = ReviewResponseMap.where(reviewer_id: reviewer.id, reviewed_object_id: assignment.id)\n @num_reviews_total = @review_mappings.size\n if @num_reviews_total.zero?\n true\n else\n @num_reviews_completed = 0\n @review_mappings.each do |map|\n @num_reviews_completed += 1 if !map.response.empty? && map.response.last.is_submitted\n end\n @num_reviews_in_progress = @num_reviews_total - @num_reviews_completed\n @num_reviews_in_progress < Assignment.max_outstanding_reviews\n end\n end",
"def pre_art_pcb(design_review, review_results)\n return (review_results.find { |rr| rr.role.name == \"PCB Design\" } &&\n design_review.review_type.name == \"Pre-Artwork\")\nend",
"def test_repost_review\n \n mx234a_pre_artwork = design_reviews(:mx234a_pre_artwork)\n pre_art_review = ReviewType.get_pre_artwork\n \n post(:repost_review,\n { :design_review_id => mx234a_pre_artwork.id },\n cathy_designer_session)\n\n assert_equal(mx234a_pre_artwork.design.id, assigns(:design_review).design.id)\n assert_equal(pre_art_review.id, assigns(:design_review).review_type_id)\n\n reviewer_list = assigns(:reviewers)\n assert_equal(14, reviewer_list.size)\n\n expected_values = [ set_group('CE-DFM Engineer', 8, 3),\n set_group('CE-DFT Engineer', 7, 2),\n set_group('Component Development', 15, 2),\n set_group('Hardware Engineer (EE)', 5, 4),\n set_group('Mechanical Engineer', 10, 2),\n set_group('Mechanical Mfg Engineer', 11, 2),\n set_group('New Product Planner', 13, 2),\n set_group('PCB Design Input Gate', 14, 2),\n set_group('PCB Design Manager', 12, 1),\n set_group('PCB Mechanical Engineer', 16, 2),\n set_group('SLM BOM', 17, 1),\n set_group('SLM Vendor', 18, 1),\n set_group('TDE Engineer', 9, 2),\n set_group('Valor', 6, 4) ]\n\n for review_group in reviewer_list\n expected_val = expected_values.shift\n\n assert_equal(expected_val[:group], review_group.role.display_name)\n assert_equal(expected_val[:group_id], review_group.role_id)\n assert_equal(expected_val[:reviewer_count], review_group.role.active_users.size)\n end\n\n end",
"def review_result\n return @review_result\n end",
"def new_design_check?\n self.full_review?\n end",
"def post_pcb_design_results(design_review, review_results)\n\n results = {:success => true,\n :alternate_msg => 'The following updates have been made - '}\n\n audit_skipped = design_review.design.audit.skip?\n \n if !audit_skipped &&\n (review_results[:designer][\"id\"] == '' ||\n review_results[:peer][\"id\"] == '')\n results[:success] = false\n results[:alternate_msg] = 'The Designer and Peer must be specified - results not recorded'\n elsif !audit_skipped &&\n (review_results[:designer][\"id\"] ==\n review_results[:peer][\"id\"])\n results[:success] = false\n results[:alternate_msg] = 'The Designer and Peer must be different - results not recorded'\n elsif audit_skipped && review_results[:designer][\"id\"] == ''\n results[:success] = false\n results[:alternate_msg] = 'The Designer must be specified - results not recorded'\n else\n design = design_review.design\n\n designer = User.find(review_results[:designer][\"id\"])\n design.designer_id = designer.id\n \n priority = Priority.find(review_results[:priority][\"id\"])\n priority_update = design.priority_id != priority.id\n design.priority_id = priority.id\n\n if !audit_skipped\n peer = User.find(review_results[:peer][\"id\"])\n design.peer_id = peer.id\n end\n \n design.save\n \n if !audit_skipped\n if peer.is_a_role_member?(\"Valor\")\n # set Valor reviewer as peer\n design.set_role_reviewer(Role::find_by_name(\"Valor\"), peer, @logged_in_user)\n else\n results[:alternate_msg] += \"Peer, #{peer.name}, does not have Valor reviewer role and was not assigned. \" \n end\n else\n results[:alternate_msg] += 'No Valor reviewer set (Audit Skipped) - '\n end\n\n for review in design.design_reviews\n review.priority_id = priority.id\n if (review.review_type.name != 'Release' &&\n review.review_type.name != 'Pre-Artwork')\n review.designer_id = designer.id\n end\n review.save\n end\n\n results[:alternate_msg] += \"Criticality is #{priority.name}, \" if priority_update\n results[:alternate_msg] += \"The Designer is #{designer.name}\"\n if !audit_skipped\n results[:alternate_msg] += \" and the Peer is #{peer.name}\"\n end\n\n end\n\n return results\n \nend",
"def post_review?(next_review, user)\n\n (next_review && \n !self.review_locked? && \n next_review.designer_id == user.id &&\n next_review.review_type_id == next_review.design.phase_id)\n\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get the view_model class for the given model instance. Note: ViewModels are usually of class ViewModels::. (As returned by default_view_model_class_for) Override specific_mapping if you'd like to install your own. OR: Override default_view_model_class_for(model) if you'd like to change the default.
|
def view_model_class_for model
specific_view_model_class_for(model) || default_view_model_class_for(model)
end
|
[
"def model_class\n unless instance_variable_defined?(:@model_class)\n # try to auto-detect the model class based on our name\n self.model_class_name =\n ViewModel::Registry.infer_model_class_name(self.view_name)\n end\n\n @model_class\n end",
"def model_class\n @model_class ||= mapping.to\n end",
"def model_class\n @model_class ||= controller_name.classify.constantize\n end",
"def model_class(model_name)\n class_map[model_name.to_sym] || model_name.camelize.constantize\n end",
"def modelClass\n @modelClass ||= begin\n if dynamicSubclass?\n # TODO this will probably break if the user namespaces the model class\n Object.const_get(name.split('_').first)\n else\n self\n end\n end\n end",
"def model_class\n @model_class ||= Object.const_get(self.to_s[0..-6])\n end",
"def view_model_name\n \"#{view_name}_view_model\"\n end",
"def model_class\n model.to_s.classify.constantize\n end",
"def to_class(model_name)\r\n Kernel.const_get(model_name.to_s.camelize)\r\n end",
"def view_component_class_for(model)\n if model.kind_of?(Work)\n SearchResult::WorkComponent\n elsif model.kind_of?(Collection)\n SearchResult::CollectionComponent\n else\n raise ArgumentError.new(\"Don't know proper search results ViewModel class for #{model}\")\n end\n end",
"def ret_model_class(opts = {})\n fail Error, \"Unexpected that opts[:model_name] and opts[:model_class] are both non nil\" if opts[:model_name] and opts[:model_class]\n if opts[:model_class]\n opts[:model_class]\n else\n model_name =\n if opts[:model_name]\n opts[:model_name]\n elsif not opts[:donot_find_subtype]\n Model.find_subtype_model_name(self, opts)\n else\n self[:model_name]\n end\n Model.model_class(model_name)\n end\n end",
"def view_model_path\n @view_model_path ||= self.name.gsub(/^ViewModels::|(\\w+)(::)?/) { $1.underscore.pluralize + ($2 ? '/' : '').to_s if $1 }\n end",
"def view_model_path\n @view_model_path || @view_model_path = self.name.underscore\n end",
"def model\n @model ||= if self.class.path_to_model\n m = eval(self.class.path_to_model)\n if m\n if m.respond_to?(:_controller=)\n m.send(:_controller=, self)\n end\n else\n fail \"No model object found at path: #{self.class.path_to_model}\"\n end\n m\n end\n end",
"def object_model\n @object_model_found ||= find_first_class(@object_model, default_object_model_class_name)\n end",
"def get_content_model(model_name)\n model_hash = content_types.select{|x| x[:name] == model_name}.first\n return model_hash[:class_name].nil? ? model_name.constantize : model_hash[:class_name].constantize\n end",
"def model_class\n klass = model_name.camelize.constantize\n if sti_model?\n raise \"you can only pass a type which descends from #{params[:controller]}\" unless klass.sti_model? and klass.superclass == base_model_class\n end\n klass\n end",
"def current_model\n Object.const_get(params[:model].classify)\n end",
"def class_at_path(path)\n if path\n begin\n # remove the _ and then singularize\n if path.last == :[]\n index = -2\n else\n index = -1\n end\n\n klass_name = path[index].singularize.camelize\n\n klass = $page.model_classes[klass_name] || Model\n rescue NameError => e\n # Ignore exception, just means the model isn't defined\n klass = Model\n end\n else\n klass = Model\n end\n\n klass\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Sets self.hotness according to the idea's age, upvotes/downvotes, and whether or not the idea has 'preferred' status. Hotness is used to determine where in the list the idea will appear. We've used the same algorithm as reddit does for sorting its contents. At present, having posting an idea later gives more hotness to the idea than upvotes, since vote_weight is calculated using log(10), while the newness of the idea is just newness / 45000. If an idea has preferred status, it is the equivalent of the idea having PREFERRED_MAGNITUDE extra upvotes when it comes to sorting it in the list. If if an idea is preferred, PREFERRED_MAGNITUDE = 5000, and has no upvotes, it will have the approximate hotness of an idea posted about 2 days later. That being the case, if a preferred idea gets no upvotes, it will be overtaken by other ideas about 2 days later. You can see more details about the subject at:
|
def set_hotness!
preferred_weight = self.preferred ? PREFERRED_MAGNITUDE : 0
vote_weight = vote_tally + preferred_weight
newness = self.created_at.to_f || Time.now.to_f
sign = vote_weight < 0 ? -1 : 1
upvote_magnitude = [ vote_weight.abs, 1.1 ].max
order = Math.log upvote_magnitude, 10
self.hotness = sign * order + newness / 45000
end
|
[
"def calc_hot_score\n points = upvotes - downvotes\n time_ago_in_hours = ((Time.now - created_at) / 3600).round\n score = hot_score(points, time_ago_in_hours)\n\n update_attributes(points: points, hot_score: score)\n end",
"def hot_count=(value)\n @hot_count = value\n end",
"def hot_count\n @hot_count\n end",
"def update_food_heuristics\n warn \"updating food heuristics...\"\n fs_need_update = @ai.food_squares - @ai.known_food\n #fs_need_deleted = @ai.known_food - @ai.food_squares\n \n fs_need_update.each do |fs|\n fs.food_steps[fs] = 0\n need_update = fs.update_adjacent_scores(fs)\n while(nx = need_update.shift )\n need_update.concat nx.update_adjacent_scores(fs)\n end\n end\n @ai.known_food = @ai.food_squares\n end",
"def add_review_votes_to_review\n # increment the count of votes regardless of stance\n if self.review.helpful_count.nil?\n self.review.helpful_count = 1\n else\n self.review.helpful_count += 1\n end\n\n # adjust the score to incorporate the up-vote, if it's an up-vote\n if self.helpful?\n if self.review.helpful_score.nil?\n self.review.helpful_score = 1\n else\n self.review.helpful_score += 1\n end\n end\n \n self.review.save!\n end",
"def update_helpful_votes_reputation\r\n\r\n if moving_from_active\r\n #Optimize the DB access here. Will not have to do it if this feature isn't needed\r\n self.helpfuls.map(&:user).each do |user|\r\n Reputable::Event.create :user => user, :action => :removed_helpful_given_qa\r\n Reputable::Event.create :user => self.user, :action => :removed_helpful_received_qa\r\n end\r\n end\r\n if moving_to_active\r\n self.helpfuls.map(&:user).each do |user|\r\n Reputable::Event.create :user => user, :action => :helpful_given_qa\r\n Reputable::Event.create :user => self.user, :action => :helpful_received_qa\r\n end\r\n end\r\n end",
"def interestingness\n self.score * @@voting_momentum - Time.now.to_i + created_at.to_i\n end",
"def hottness_score_class\n case object.hottness\n when 10..24 then 'text-warning'\n when 25..Inf then 'text-danger'\n end\n end",
"def interestingness\n self.score * (SECONDS_PER_DAY / AppSettings.voting_momentum) - Time.now.to_i + created_at.to_i\n end",
"def classification_with_ties\n result = []\n result << @schulze_basic.potential_winners # add potential winners on first place\n result += @schulze_basic.ties.clone.sort_by { |tie| -@schulze_basic.ranking[tie[0]] } # add ties by ranking\n result.uniq! # remove duplicates (potential winners are also ties)\n add_excludeds(result)\n end",
"def counting_recommendation\n count = @shoe.count\n if count <= 1\n @cold\n elsif count <= 10\n @warm\n else\n @hot\n end\n end",
"def mark_as_best\n question.update_attribute(:best_answer, self)\n end",
"def hs_weight(hs, wt)\n if hs != hot_standby && hot_standby == default_hot_standby\n self.lweight = wt unless weight == wt\n self.lhot_standby = hs\n elsif hs != hot_standby && hot_standby != default_hot_standby\n self.lhot_standby = hs\n self.lweight = wt unless weight == wt\n elsif wt != weight && weight == default_weight\n self.lweight = wt\n elsif wt != weight && weight != default_weight\n self.lweight = wt\n end\n set_args_keys_default\n end",
"def avgerage_likes\n\t\tamt = self.reputation_count\n\t\tsum = self.reputations.summarize(:fondness).first\n\n\t\t(sum.fondness / amt).round\n\tend",
"def rateBoringness\n distanceToUnseen = boringnesses[:unseen] || LargeFiniteNumber\n distanceToFood = boringnesses[:food] || LargeFiniteNumber\n distanceToEnemy = boringnesses[:enemyHill] || LargeFiniteNumber\n # Apply a sub-linear function to each distance so that\n # farther away distances have less influence than close.\n # Food is more important than unexplored spaces.\n # Enemy nests are even more important(?).\n # Using a continuous function (rather than e.g. if distanceToFood < 6)\n # makes it easier to write a function that can fairly compare any\n # two locations we're considering moving to, even when the two\n # locations fall on different sides of that threshold.\n result = Math.sqrt(distanceToUnseen * ExploreWeight) +\n Math.sqrt(distanceToFood * FoodWeight) +\n Math.sqrt(distanceToEnemy * HillWeight)\n #log \"#{@col},#{@row} boringness: #{distanceToUnseen}, #{distanceToFood}, #{distanceToEnemy} ==> #{result}\"\n return result\n end",
"def set_vote_tally!\n self.vote_tally = self.get_upvotes.size - self.get_downvotes.size\n end",
"def hot?\n ((psar_impact == 1) ||\n (pmr && (pmr.hot || pmr.crit_sit)))\n end",
"def analyze_vote_ovals\n Hot_columns.each do |col_index|\n Hot_rows.each do |row_index|\n vote_oval_pos = transform_point(BPoint.new(col_index, row_index))\n @upstream.ann_point(vote_oval_pos.x, vote_oval_pos.y)\n xpos = vote_oval_pos.x - i2p(Vote_oval_width)/2.0\n ypos = vote_oval_pos.y-i2p(Vote_oval_height)/2.0\n width = i2p(Vote_oval_width)\n height = i2p(Vote_oval_height)\n @upstream.ann_rect(xpos, ypos, width, height)\n score = shrink_to_one :ballot, xpos, ypos, width, height\n if score < (QuantumRange * VoteOvalDetectThresh).to_int then\n @raw_marked_votes << [row_index, col_index]\n end\n end\n end\n end",
"def update_best\n if @best_price < @ep.max\n @best_price = @ep.max\n res_i = @ep.index(@best_price)\n @best_weight = @bw[res_i]\n @best_baggage = in_bag(@cg[res_i])\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
sets the idea's vote_tally field to be equal to the number upvotes minus the number of downvotes it has
|
def set_vote_tally!
self.vote_tally = self.get_upvotes.size - self.get_downvotes.size
end
|
[
"def calculate_tallied_votes\n self.tallied_votes = upvotes - downvotes\n self.save\n end",
"def get_vote_tally\n return self.get_upvotes.size - self.get_downvotes.size\n end",
"def votes\n self.up_votes - self.down_votes\n end",
"def unvote_for(idea)\n voted_ideas.delete(idea)\n t = Idea.find(idea.id).trend\n if t.trending > 4\n t.trending = t.trending - 4\n else\n t.trending = 0\n end\n t.save\n end",
"def reset_votes\n self.upvotes = 0\n self.downvotes = 0\n self.save\n end",
"def downvote_count\n downvotes.count\n end",
"def decrease_vote_count\n \tcount = voteable.votes_count\n \tcount = count - 1\n \tvoteable.update_attributes(votes_count: count)\n end",
"def down_votes_count\n votes.try(:[], 'down_count') || 0\n end",
"def vote_score\n self.votes.upvotes.count - self.votes.downvotes.count\n end",
"def downvote\n if self.rating == nil\n self.rating = 0\n end\n self.rating-=1\n self.save\n self.rating\n end",
"def upvote_count\n upvotes.count\n end",
"def downvote!\n ActsAsNpsRateable::NpsRating.update_counters(id, down_votes: 1, net_votes: -1)\n end",
"def up_votes_count\n votes.try(:[], 'up_count') || 0\n end",
"def downvotes_count\n post_votes.where(value: -1).sum(:value) * -1\n end",
"def up_down_votes\n Vote.seperate_votes(self.votes)\n end",
"def downvotes_count\n topic_votes.where(value: -1).sum(:value) * -1\n end",
"def dem_votes\n @dem_votes = @dem_votes + 1\nend",
"def upVote(rushee)\n verifyApproval(rushee)\n self.approvals.find_by(rushee: rushee).update_attribute(\"vote\", true) \n end",
"def downvote\n\t\t@post = Post.find(params[:id])\n\t\tnew_count = @post.post_count = @post.post_count - 1\n\t\t@post.update_attributes(:post_count => new_count)\n\t\tredirect_to posts_path\n\tend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Adds a downvote to the idea and then saves it, causing the idea's hotness to update
|
def downvote_and_update(user)
self.disliked_by user
self.save
end
|
[
"def downvote\n if self.rating == nil\n self.rating = 0\n end\n self.rating-=1\n self.save\n self.rating\n end",
"def upVote(rushee)\n verifyApproval(rushee)\n self.approvals.find_by(rushee: rushee).update_attribute(\"vote\", true) \n end",
"def vote up\n end",
"def vote_for(idea)\n self.votes.create(idea_id: idea.id)\n if idea.user.own_idea_notifications\n VoteNotification.send_notification(self, idea, [idea.user])\n end\n idea.save\n end",
"def downvote!(user_id)\n downvotes.create user_id: user_id\n end",
"def upvote!(user_id)\n upvotes.create user_id: user_id\n end",
"def add_review_votes_to_review\n # increment the count of votes regardless of stance\n if self.review.helpful_count.nil?\n self.review.helpful_count = 1\n else\n self.review.helpful_count += 1\n end\n\n # adjust the score to incorporate the up-vote, if it's an up-vote\n if self.helpful?\n if self.review.helpful_score.nil?\n self.review.helpful_score = 1\n else\n self.review.helpful_score += 1\n end\n end\n \n self.review.save!\n end",
"def downvote!\n ActsAsNpsRateable::NpsRating.update_counters(id, down_votes: 1, net_votes: -1)\n end",
"def calculate_tallied_votes\n self.tallied_votes = upvotes - downvotes\n self.save\n end",
"def update\n @suggestion = Suggestion.find(params[:suggestion][:id])\n\n if suggestion_check?\n @suggestion.update_attribute(:being_voted, true)\n session[:suggestion_count] -= 1\n session[:suggested_item].push(@suggestion)\n redirect_to root_path\n else\n flash[:suggestion_error] = \"You already made a suggestion\"\n redirect_to :back\n end\n end",
"def unvote_for(idea)\n voted_ideas.delete(idea)\n t = Idea.find(idea.id).trend\n if t.trending > 4\n t.trending = t.trending - 4\n else\n t.trending = 0\n end\n t.save\n end",
"def auto_upvote\n upvote(self.user)\n end",
"def voteup\n @post = Post.find_by(id: params[:id])\n # @post.update(vote_count: @post.vote_count + 1)\n @post.upvote\n redirect_to posts_path\n end",
"def upvote id\n vote 1, id\n end",
"def upvote\n @link = Link.find(params[:id])\n @user = User.find(current_user.id)\n @vote = @link.votes.create(params[:link])\n @vote.user = @user\n @vote.link = @link\n @vote.score = 1\n \n respond_to do |format|\n if @vote.save!\n format.html { redirect_to(links_path, :notice => 'Your vote has been cast.') }\n else\n format.html { redirect_to(links_path, :notice => 'Error recording vote, please try again later.') }\n end\n \n end\n end",
"def up_vote\n if current_user\n answer_id = params[:answer_id]\n can_vote = Vote.can_vote(answer_id, current_user.uid)\n if can_vote\n answer = Answer.find_by_id(answer_id)\n answer.vote += 1\n answer.save!\n \n Vote.add_vote(answer_id, current_user.uid)\n end\n end\n render :nothing => true\n end",
"def downvote\n\t\t@post = Post.find(params[:id])\n\t\tnew_count = @post.post_count = @post.post_count - 1\n\t\t@post.update_attributes(:post_count => new_count)\n\t\tredirect_to posts_path\n\tend",
"def upvote\n @post = Post.find(params[:id])\n @post_count = Post.count\n @vote = Vote.new(user_id: session[:id], post_id: @post.id, score: 1)\n if @vote.save\n @post.update_attribute(:respect, @post.respect + 1)\n flash[:notice] = 'Post upvoted successfully'\n end\n redirect_to(action: 'index', topic_id: @topic.id)\n end",
"def add_vote(vote)\n self.score = self.score + vote.value\n self.votes_count = self.votes_count + 1\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns the tally of votes for the idea (upvotes downvotes)
|
def get_vote_tally
return self.get_upvotes.size - self.get_downvotes.size
end
|
[
"def set_vote_tally!\n self.vote_tally = self.get_upvotes.size - self.get_downvotes.size\n end",
"def tally_votes\n tallies = {}\n if vote_tallies.present?\n vote_tallies.each do |vote_tally|\n tallies[vote_tally.candidacy] = vote_tally.vote_count\n end\n else\n votes.each do |vote|\n candidacy = vote.candidacy\n tallies[candidacy] ||= 0\n tallies[candidacy] += 1\n end\n end\n\n tallies\n end",
"def votes_count\n votes.count\n end",
"def upvote_count\n upvotes.count\n end",
"def number_of_votes_given\n self.votes.count - self.captions.count\n end",
"def votes\n self.up_votes - self.down_votes\n end",
"def downvote_count\n downvotes.count\n end",
"def vote_score\n self.votes.upvotes.count - self.votes.downvotes.count\n end",
"def votes_count\n votes.size\n end",
"def total_votes\n @votes.count\n end",
"def number_of_votes\n poll_options.sum(:number_of_votes)\n end",
"def downvotes_count\n topic_votes.where(value: -1).sum(:value) * -1\n end",
"def downvotes_count\n post_votes.where(value: -1).sum(:value) * -1\n end",
"def vote_counts\n self.votes.group(:score).count\n end",
"def upvotes_count\n topic_votes.where(value: 1).sum(:value)\n end",
"def numVotes(actionIdeaID)\n \treturn ActionIdeaVote.where(actionIdeaID = self.action_idea_id).count()\n end",
"def downvotes\n notes.select(&:downvote?).size\n end",
"def rate\n votes = answers.inject(0) do |sum, a| \n sum + a.votes.count \n end\n \n # Return a count of votes and answers\n answers.count + votes\n end",
"def vote_count\n count = Vote.find_all_by_question_id(self.id)\n if count\n return count.count\n else\n return 0\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
converts idea.youtube_link into the form needed to make the video embeddable
|
def embed_link
return nil if self.youtube_link.nil?
id_regex = /(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/
youtube_id = self.youtube_link.match(id_regex)
return nil if youtube_id.nil?
return YOUTUBE_EMBED_PREFIX + youtube_id[1] + "?rel=0"
end
|
[
"def convert_to_youtube_embed_link\n self.video_url.gsub!(/(youtube.com\\/)(.)*v=([\\w\\-_]+)(.)*$/, '\\1embed/\\3')\n end",
"def convert_to_embedded_url\n youtube_id = youtube_video_id_from_link(url)\n self.url = youtube_embedded_url(youtube_id) if youtube_id\n end",
"def youtube_embed_url\n VideoInfo.new(self.video_url).embed_url if self.video_url?\n end",
"def youtube_embed\n if self.video[/youtu\\.be\\/([^\\?]*)/]\n youtube_id = $1\n else\n # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367\n self.video[/^.*((v\\/)|(embed\\/)|(watch\\?))\\??v?=?([^\\&\\?]*).*/]\n youtube_id = $5\n end\n if youtube_id\n return \"http://www.youtube.com/embed/\"+youtube_id+\"?wmode=transparent\" \n else\n return \"\"\n end\n end",
"def youtube_movie_embed\n str1 = \"http://www.youtube.com/v/\" \n str2 = movie_home_url.split('v=',2).last unless movie_home_url.nil?\n str3 = \"&hl=en_US&fs=1&\"\n return [str1,str2,str3].join \n end",
"def youtube_shorten\n if self.youtube_video\n self.youtube_video = self.youtube_video.sub(/^.*http:\\/\\/www.youtube.com\\/\\w+\\/([^ ]+).*$/, '\\1')\n end\n end",
"def source_url\n \"https://www.youtube.com/watch?v=#{@element.embed_id}\"\n end",
"def youtube_embedded_url(video_id)\n \"https://www.youtube.com/embed/#{video_id}\"\n end",
"def markdown_extention_youtube_links(html)\n html = html.gsub /<a\\shref=\"http:\\/\\/www\\.youtube\\.com\\/watch\\?v=(.*).*\".*>.*<\\/a>/o, \n \"<p><iframe class=\\\"youtube-player\\\" src=\\\"http://www.youtube.com/embed/\\\\1\\\"></iframe></p>\"\n return html\n end",
"def youtube_video_id\n video_id = link.match(/\\?v=/) ? link.split('?v=')[1] : link.split('/').last\n video_id = video_id.split('&')[0] if video_id =~ /&/\n self.vid = video_id\n end",
"def youtube_embed(youtube_url)\n\t # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367\n\t youtube_url.to_s[/^.*((v\\/)|(embed\\/)|(watch\\?))\\??v?=?([^\\&\\?]*).*/]\n\t youtube_id = $5\n\t youtube_id\n\tend",
"def get_embed_url(embed_code)\n regex = /(youtu\\.be\\/|youtube\\.com\\/(watch\\?(.*&)?v=|(embed|v)\\/))([^\\?&\"'>]+)/\n url = \"\" #placeholder url\n\n if embed_code.match(regex) != nil && embed_code.include?(\"iframe\")\n youtube_id = embed_code.match(regex)[5]\n Rails.logger.debug \"youtube_id : #{youtube_id}\"\n url = \"http://www.youtube.com/embed/\"+youtube_id\n end\n return url\n end",
"def youtube_url\n \"https://www.youtube.com/watch?v=#{@data['youtubeID']}\" if @data['youtubeID']\n end",
"def oembed_url\n \"https://www.youtube.com/oembed?format=json&url=#{source_url}\"\n end",
"def youtube_code\n code = self.link.match(/v=(.*)/)\n code.captures.first\n end",
"def youtube\n youtube_embed = '<iframe title=\"YouTube video player\" width=\"640\" height=\"390\" src=\"http://www.youtube.com/embed/VIDEO_ID\" frameborder=\"0\" allowfullscreen></iframe>' \n if self.url =~ /.*http:\\/\\/(\\w+\\.)?youtube.com\\/watch.*/\n self.url.match(/v=(\\w+)/)\n return youtube_embed.gsub(/VIDEO_ID/, $1) \n end\n return nil\n end",
"def youtube_url; \"https://youtube.com/user/#{youtube}\" end",
"def embed(youtube_url)\n youtube_id = youtube_url.split('=').last\n content_tag(:iframe, nil, src: \"//www.youtube.com/embed/#{youtube_id}\")\n end",
"def embedded_video s\n %(<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/#{video_id s}?rel=0\" frameborder=\"0\" allowfullscreen></iframe>)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns true if the idea has preferred status, false otherwise
|
def preferred?
self.preferred
end
|
[
"def awarded_by_interview_committee?\n application_interview_decision_type.nil? ? false : application_interview_decision_type.yes_option\n end",
"def active?\n name = self.review_status.name\n name == 'In Review' || name == 'Pending Repost' || name == 'Review On-Hold'\n end",
"def win?\n milestones.each do |mile|\n return false unless mile.status == 'Aprobado'\n end\n true\n end",
"def reviewed?\n @status == :reviewed\n end",
"def awarded_by_review_committee?\n application_review_decision_type.nil? ? false : application_review_decision_type.yes_option\n end",
"def reviewed?\n !application_review_decision_type.nil?\n end",
"def boolean_status\n !!(@status_hint == 'good')\n end",
"def current_alternative?\n return current_alternative == alternate_setting\n end",
"def good?\n @summary[:total_score] <= Constants::THRESHOLDS[\"Project\"]\n end",
"def releasable?; review_state? :ready; end",
"def is_active(effort)\n if effort.deliverable and effort.deliverable.project_phase and effort.deliverable.project_phase.project\n return effort.deliverable.project_phase.project.status == 'Active'\n end\nend",
"def satisfied?\n satisfied\n end",
"def not_tracked?\n\t\treturn self.status == '?'\n\tend",
"def starred?\n star_status\n end",
"def approved?\n (status == APPROVED)\n end",
"def awarded_by_final_committee?\n application_final_decision_type.nil? ? false : application_final_decision_type.yes_option\n end",
"def landed?\n !!@status \n end",
"def recommendable?() false end",
"def desired_state?\n return true unless options.key?(:desired_state)\n\n options[:desired_state]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Convert an Excel serialformat date to a Ruby date object
|
def serial_to_date (s)
# round down and convert from string if need be
# zero day is actually "Jan 0" and indexing starts from 1, so subtract 2
s = s.to_i() - 2
# add to zero day
return JAN_1_1900 + s
end
|
[
"def ruby_to_excel(date, use_1904=false)\n date = date.to_datetime\n base = base_date(use_1904)\n date_float = (date - base).to_f\n date_float += 1 if adjust_for_stupid_leap_year?(date, use_1904)\n date_float\n end",
"def excel_to_ruby(val=0.0, use_1904=false)\n val = val.to_f\n\n base = base_date(use_1904)\n date = base + val\n date -= 1 if adjust_for_stupid_leap_year?(date, use_1904)\n\n hour = (val % 1) * 24\n min = (hour % 1) * 60\n sec = (min % 1) * 60\n\n hour = hour.floor\n min = min.floor\n sec = sec.round\n\n DateTime.new(date.year, date.month, date.day, hour, min, sec)\n end",
"def date(cell, str = +'')\n value_serialization false, DateTimeConverter.date_to_serial(cell.value).to_s, str\n end",
"def date_to_oa_date(date)\n (date.jd - 2415019).to_f\n end",
"def cell_date(cell_value)\n case cell_value\n when Cell\n cell_date(cell_value.value)\n else\n cell_value.to_date\n end\n end",
"def get_date(rally_date_field)\n the_date=DateTime.parse(rally_date_field).to_date()\n #the_date=DateTime.new(date_arr[0],date_arr[1],date_arr[2])\n return(the_date)\nend",
"def typecast_to_date(value)\n if value.kind_of?(Hash)\n typecast_hash_to_date(value)\n else\n Date.parse(value.to_s)\n end\n end",
"def to_date\n parts = to_citeproc\n\n if parts.empty? || parts.include?(0)\n nil\n else\n begin\n ::Date.new(*parts)\n rescue\n # Catch invalid dates (e.g., if the month is 13).\n nil\n end\n end\n end",
"def typecast_to_date(value)\n if value.is_a?(Hash)\n typecast_hash_to_date(value)\n elsif value.is_a?(Time) # sometimes people think date is time!\n value.to_date\n elsif value.to_s =~ /(\\d{4})[\\-|\\/](\\d{2})[\\-|\\/](\\d{2})/\n # Faster than parsing the date\n Date.new($1.to_i, $2.to_i, $3.to_i)\n else\n Date.parse(value)\n end\n rescue ArgumentError\n value\n end",
"def date_to_binary(val); end",
"def to_date\n ::Date.new(year, month, day)\n end",
"def convert_date(date)\n Date.strptime(date, ROOMORAMA_DATE_FORMAT).strftime(POPLIDAYS_DATE_FORMAT)\n end",
"def to_date\n ::Date.new(@year, @month, @day)\n end",
"def typecast_value_date(value)\n case value\n when DateTime, Time\n Date.new(value.year, value.month, value.day)\n when Date\n value\n when String\n Sequel.string_to_date(value)\n when Hash\n Date.new(*[:year, :month, :day].map{|x| (value[x] || value[x.to_s]).to_i})\n else\n raise InvalidValue, \"invalid value for Date: #{value.inspect}\"\n end\n end",
"def convert_datetimes_intelligently!\n dt_attrs = @converted_headers.select { |obj| obj.match(/_(?:dt?|at|on)\\z/) }\n dt_idxs = dt_attrs.map { |obj| @converted_headers.find_index(obj) }\n\n spreadsheet.map! { |row|\n dt_idxs.each { |idx|\n to_convert = row[idx]\n row[idx] = to_convert.try(:to_datetime) || to_convert\n }\n row }\n end",
"def format_date(a_cell)\n isdate = true if(nil != (dt = a_cell.match(@date_RE)))\n isdate = true if(isdate || (nil != (dt = a_cell.match(@date_with_dashes_RE))) )\n isdate = true if(isdate || (nil != (dt = a_cell.match(@date_with_time_RE))) )\n if isdate\n begin\n mod_dt = DateTime.parse(a_cell)\n cary = \"#{mod_dt.month}/#{mod_dt.day}/#{mod_dt.year}\"\n if(true == verbose?)\n puts \"\"\n puts \"*** Converted date to #{cary} ***\"\n puts \"\"\n end\n a_cell = cary\n rescue ArgumentError => e\n # Either this is not a date, or the date format is unrecognized,\n # nothing to see here, moving on.\n end\n end\n a_cell\n end",
"def time_to_oa_date(time)\n time = time.respond_to?(:to_time) ? time.to_time : time\n # Local dates are stored as UTC by truncating the offset:\n # 1970-01-01 00:00:00 +0200 => 1970-01-01 00:00:00 UTC\n # This is done because SpreadsheetML is not timezone aware.\n (time + time.utc_offset).utc.to_f / 24 / 3600 + 25569\n end",
"def from_dmy(date)\n date.to_s.gsub(/^(\\d{2})[\\/-](\\d{2})[\\/-](\\d{4})/, '\\3/\\2/\\1').to_date\n end",
"def time_to_oa_date(time)\n # Local dates are stored as UTC by truncating the offset:\n # 1970-01-01 00:00:00 +0200 => 1970-01-01 00:00:00 UTC\n # This is done because SpreadsheetML is not timezone aware.\n (time.to_f + time.utc_offset) / 86400 + 25569\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Converts the string form of a number to the bestfitting numeric type.
|
def str_to_number(s)
val_str = s.to_s()
if INT_REGEX.match(val_str)
return val_str.to_i()
elsif FLOAT_REGEX.match(val_str)
return val_str.to_f()
else
raise ArgumentError, "can't understand numeric format '#{s}'"
end
end
|
[
"def convert_string_to_number(str); end",
"def convert_string_to_number(str)\n matches = RE_NUMBER_STR.match(str)\n\n s = matches[:sign] == '-' ? -1 : 1\n i = matches[:integer].to_i\n f = matches[:fractional].to_i\n d = matches[:fractional] ? matches[:fractional].length : 0\n t = matches[:exponent_sign] == '-' ? -1 : 1\n e = matches[:exponent].to_i\n\n # I know this formula looks nutty, but it's exactly what's defined in the\n # spec, and it works.\n value = s * (i + f * 10**-d) * 10**(t * e)\n\n # Maximum and minimum values aren't defined in the spec, but are enforced\n # here for sanity.\n if value > Float::MAX\n value = Float::MAX\n elsif value < -Float::MAX\n value = -Float::MAX\n end\n\n value\n end",
"def convert_to_num(val)\n if val.class == String\n if val.include?(\".\")\n val.to_f\n else\n val.to_i\n end\n else\n # if it's not a string assume it's already a num\n # and just return it\n val\n end\nend",
"def to_number( word )\n begin\n return Integer( word )\n rescue\n puts $!\n end\n begin\n return Float( word )\n rescue\n puts $!\n end\n nil\n end",
"def numeric string\n Float(string) rescue nil\nend",
"def to_numeric(num)\n num = num.to_s\n num = (num =~ /\\./) ? sprintf(\"%.5f\", num).to_f : num.to_i\nend",
"def to_float_or_int str\n Integer(str) rescue Float(str) rescue nil\n end",
"def _parse_numeric( str )\n Integer(str) rescue (Float(str) rescue nil)\n end",
"def scanAsNumber(str)\n if(str =~ /^[0-9]*$/)\n return str.to_i ;\n else\n return str.to_f ;\n end\n end",
"def convert_value( value )\n if value =~ /\\A\\d+\\Z/ then\n Float( value ).to_i\n elsif value =~ /\\A\\d+\\.\\d+\\Z/\n Float( value )\n else\n value\n end\n end",
"def convert_if_needed(value) #:nodoc:\n if value =~ /^[+-]?\\d+\\.?\\d*$/ # float\n value = value.to_f\n elsif value =~ /^[+-]?\\d+$/ # int\n value = value.to_i\n else\n value\n end\n end",
"def is_number? string\n true if Float(string) rescue false\n end",
"def convert_to_numeric(val)\n return BigDecimal(val, Float::DIG) if val.is_a?(Float)\n return val if val.is_a?(Numeric)\n # Eliminate any commas, $'s (or other currency symbol), or _'s.\n cursym = Regexp.quote(FatTable.currency_symbol)\n clean_re = /[,_#{cursym}]/\n val = val.to_s.clean.gsub(clean_re, '')\n return nil if val.blank?\n case val\n when /(\\A[-+]?\\d+\\.\\d*\\z)|(\\A[-+]?\\d*\\.\\d+\\z)/\n BigDecimal(val.to_s.clean)\n when /\\A[-+]?[\\d]+\\z/\n val.to_i\n when %r{\\A([-+]?\\d+)\\s*[:/]\\s*([-+]?\\d+)\\z}\n Rational($1, $2)\n end\n end",
"def check_type (num)\n # convert to float if validated number contains a decimal\n if num =~ /\\./\n return num = Float(num)\n else\n return num = Integer(num)\n end\nend",
"def convert_str_to(input_str, data_type)\n\tif data_type == \"int\"\n\t\tinput_str.to_i\n\telsif data_type == \"float\"\n\t\tinput_str.to_f\n\telsif data_type == \"boolean\"\n\t\tto_bool(input_str)\n\telse \n\t\tinput_str\n\tend\nend",
"def to_numeric(num)\n if num.nil?\n 0\n elsif num.kind_of? Integer\n num\n else\n 1 # We count each instance of a string this way\n end\n end",
"def to_numeric(value, _column=nil, _attr_key=nil)\n return nil if blank_value? value\n case value\n when String\n value.to_f\n when Numeric\n value\n end\n end",
"def float_or_interger(str)\n if str.include?\".\"\n num =str.to_f\n else\n num = str.to_i\n end\n return num\nend",
"def string_to_number(s)\n s.to_i\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
returns array of strings to print out for syntax.
|
def syntax
t = @cmd_args
t = [[t]] if !t.is_a? Array
args = []
count = 0
t.each do |expected_array|
count += 1
if count == 1
str = "Syntax: #{@cmd_name}"
else
str = " #{@cmd_name}"
end
expected_array.each do |expected|
# each expected arg.
str += case expected
when :arg_none then ""
when :arg_dir! then " <direction>"
when :arg_str! then " <string literal>"
when :arg_word!then " <word>"
when :arg_int! then " <#>"
when :arg_obj_inv! then " <item>"
when :arg_obj_room! then " <item>"
when :arg_obj_inv_or_room! then " <item>"
when :arg_class! then " <Class>"
when :arg_player_in_game! then " <player in game>"
when :arg_player_offline! then " <any player>"
when :arg_actor_room! then " <npc/player>"
when String then " " + expected
else ""
end
end
args << str
end
return args
end
|
[
"def syntax\n contents.zip(gaps).flatten\n end",
"def syntaxes\n Uv.syntaxes\n end",
"def syntaxes\r\n playbook.syntaxes\r\n end",
"def syntaxes\n playbook.syntaxes\n end",
"def terminalList\n [\n %w[ asterisk * ],\n %w[ at_sign @ ],\n %w[ bang_equal != ],\n %w[ box <> ],\n %w[ comma , ],\n %w[ dot . ],\n %w[ equals = ],\n %w[ greater > ],\n %w[ greater_equal >= ],\n %w[ hat_equal ^= ],\n %w[ less < ],\n %w[ less_equal <= ],\n %w[ lparen ( ],\n %w[ lbracket \\[ ],\n %w[ minus_sign - ],\n %w[ plus + ],\n %w[ rparen ) ],\n %W[ rbracket \\] ],\n %w[ slash / ],\n %w[ strokestroke || ],\n %w[ plparser_ident <id> ],\n %w[ plparser_qident <quoted_identifier> ],\n %w[ plparser_number <numeric_literal> ],\n %w[ plparser_string <string_literal> ],\n ].collect! { |a| a.unshift(:T) } +\n\n [\n %w[ action ],\n %w[ audited_cursorid ],\n %w[ authenticated_identity ],\n %w[ authentication_data ],\n %w[ authentication_method ],\n %w[ authentication_type ],\n %w[ bg_job_id ],\n %w[ client_identifier ],\n %w[ client_info ],\n %w[ current_bind ],\n %w[ current_edition_id ],\n %w[ current_edition_name ],\n %w[ current_schema ],\n %w[ current_schema_id ],\n %w[ current_sql ],\n %w[ current_sql_length ],\n %w[ current_user ],\n %w[ current_userid ],\n %w[ database_role ],\n %w[ db_domain ],\n %w[ db_name ],\n %w[ db_unique_name ],\n %w[ dblink_info ],\n %w[ enterprise_identity ],\n %w[ entryid ],\n %w[ external_name ],\n %w[ fg_job_id ],\n %w[ global_context_memory ],\n %w[ global_uid ],\n %w[ host ],\n %w[ identification_type ],\n %w[ instance ],\n %w[ instance_name ],\n %w[ ip_address ],\n %w[ isdba ],\n %w[ lang ],\n %w[ language ],\n %w[ module ],\n %w[ network_protocol ],\n %w[ nls_calendar ],\n %w[ nls_currency ],\n %w[ nls_date_format ],\n %w[ nls_date_language ],\n %w[ nls_sort ],\n %w[ nls_territory ],\n %w[ os_user ],\n %w[ policy_enterprise_identity ],\n %w[ policy_invoker ],\n %w[ proxy_global_uid ],\n %w[ proxy_user ],\n %w[ proxy_userid ],\n %w[ server_host ],\n %w[ service_name ],\n %w[ session_edition_id ],\n %w[ session_edition_name ],\n %w[ sessionid ],\n %w[ sid ],\n %w[ statementid ],\n %w[ terminal ],\n %w[ userenv ],\n ].collect! { |a| [ :T, ('qt' + a[0]).to_sym, \"&q'%s'\" % a[0] ] }\n\n end",
"def commands\n args.commands.map do |cmd|\n if cmd.respond_to?(:join)\n cmd.map { |c| c.index(' ') ? \"'#{c}'\" : c }.join(' ')\n else\n cmd.to_s\n end\n end\n end",
"def commands\n args.commands.map do |cmd|\n if cmd.respond_to?(:join)\n # a simplified `Shellwords.join` but it's OK since this is only used to inspect\n cmd.map { |c| (c.index(' ') || c.empty?) ? \"'#{c}'\" : c }.join(' ')\n else\n cmd.to_s\n end\n end\n end",
"def printable_commands(*)\n item = []\n item << banner\n item << (desc ? \"# #{desc.gsub(/\\s+/m, ' ')}\" : \"\")\n [item]\n end",
"def get_string_literals\n code.scan(/@\"(.+?)\"@|@'(.+?)'@/m)\n end",
"def list_syntaxes\n uri = URI.parse(\"#{BASE_URL}/syntaxes\")\n response = JSON.parse(@client.get(uri).body)\n return response['syntaxes'].map { |obj| Pastee::Syntax.new(obj) } if response['success']\n\n throw_error(response)\n end",
"def text\n map(&:text).join\n end",
"def canonical_syntax_strings\n @canonical_syntax_strings ||= flag_syntax.map(&:canonical_str)\n end",
"def syntax(syntax = nil)\n @syntax = syntax if syntax\n syntax_list = []\n if parent\n syntax_list << parent.syntax.to_s.gsub(/<[\\w\\s-]+>/, '').gsub(/\\[[\\w\\s-]+\\]/, '').strip\n end\n syntax_list << (@syntax || name.to_s)\n syntax_list.join(\" \")\n end",
"def rough_instructions\n all_instructions.join(' ').split\n end",
"def usage_examples\n String.new.tap do |s|\n s << \"Examples:\"\n @examples.each do |ex|\n s << \"\\n #{@name} #{ex}\"\n end\n end\n end",
"def getAllTexts intervalRange\n texts = [[]]\n curr_alts = []\n # Go through the interval token by token. It is indexed by token, \n # not by character\n intervalRange.each do |j|\n tok = @tokens.get(j)\n\n # If the text is parsed code or whitespace\n if (tok.channel == 0 || tok.channel == 1)\n texts.each do |text|\n text << tok.getText\n end\n\n # Get directives\n elsif (tok.channel == 2)\n d = strip_directive(tok)\n # TODO make sure combinations of alts are handled\n case d.command\n when\"ALT\"\n # Trigger creation of alternative magnet\n curr_alts << []\n texts.each do |text|\n curr_alt = Array.new(text)\n curr_alt << d.arg\n curr_alts.last << curr_alt\n end\n when \"ENDALT\"\n texts << curr_alts.pop\n end\n end\n end\n\n ret = texts.map {|t| t.join}\n # puts \"Ret\"\n # pp ret\n return ret\n end",
"def get_face_syntax(face)\n # TODO convert to array\n \t\"f #{face.join(\" \")}\"\n end",
"def literals_list\n @literals ||= \"\"\n end",
"def text\n #[@organism, @symbol, @description, @aka, @protnames, @summary,@comentaries.join(\". \")].join(\". \") \n [@symbol, @description, @aka, @protnames, @summary].flatten.join(\". \") \n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
automatically creates new rooms and digs them out in a direction. if a room is supplied we use it unconditionally.
|
def buildwalk(dir, supplied=nil)
if supplied
if supplied.is_a?(Room)
found = {:room=>supplied}
else
view "Linking failed. Target was not a room." + ENDL
return nil
end
else
m = Automap.new(in_room, [(-1..1),(-1..1)], {:full_traverse=>true})
found = m.find(Automap.offset([0,0], dir))
end
if !found
new_room = Room.dig_rooms(in_room.vnum, Vnum.gen_vnum, dir)
new_room.sector = in_room.sector # same sector as old room
new_room.namespace = in_room.namespace
new_room.assign_tag Tag.gen_generic_tag(new_room), in_room.namespace
return new_room
else
Room.dig_rooms(in_room.vnum, found[:room].vnum, dir)
return found[:room]
end
end
|
[
"def create_rooms\n $room1 = Room.new(\"Room 1\", \"This is room 1\", {}, {fork: $fork, bag: $bag, balloon: $balloon, key: $key, chest: $chest})\n $room2 = Room.new(\"Room 2\", \"This is room 2\", {}, {})\n $room3 = Room.new(\"Room 3\", \"This is room 3\", {}, {})\n $room4 = Room.new(\"Room 4\", \"This is room 4\", {}, {})\n $room5 = Room.new(\"Room 5\", \"This is room 5\", {}, {})\nend",
"def buildRoom(l, n)\n i = 0\n \n @lastRoom = l\n @battle = false\n @door = Door.new\n @door.buildObject(n) \n \n # If there is a bad guy in this room, build and name it, and give it a level.\n if @hasNPC\n @NPC = NPC.new($npc_names[rand(5)], 1 + rand(2))\n end\n \n # Build the objects in this room, if there are any.\n for obj in @objs_arr\n obj.buildObject\n end \n end",
"def calc_room\n return unless state.game_state == :room\n return state.game_state = :maze if state.room.attempted >= state.room.attempts\n state.room.attempted += 1\n\n room = random_room\n\n if valid_room?(room) \n state.room.rects << room\n else\n calc_room # Attempt to generate another room\n end\n end",
"def set_directions\n $room1.directions = {e: $room2}\n $room2.directions = {w: $room1, n: $room3, e: $room4, s: $room5}\n $room3.directions = {s: $room2}\n $room4.directions = {w: $room2}\n $room5.directions = {n: $room2}\nend",
"def assign_room(r)\n if r.class.to_s.byteslice(0, 17) == Masqueraide::Room.to_s\n @room = r\n @room.ai = self\n return @room\n elsif r.class.superclass.to_s.byteslice(0, 17) == Masqueraide::Room.to_s\n @room = r\n @room.ai = self\n return @room\n elsif Symbol.all_symbols.include? r.to_sym\n result = ROOMS.key?(r.to_sym)\n if result == false\n raise 'RoomNotFoundException: ' + 'Room not found for: ' + r.to_s\n else\n @room = ROOMS[r.to_sym]\n # Only applies to a special case like twitter.\n @room = @room.new(@username) if @room == Masqueraide::Room::Twitter\n @room.ai = self\n return @room\n end\n end\n end",
"def create_room\n Room.new\n end",
"def add_door(room)\n return if self == room or @doors.include? room\n @doors << room\n room.add_door self\n end",
"def rooms_around(room)\n # Get the person's rooms in alphabetical order\n rooms = memberships.unarchived.alpha\n\n # If there are 5 or fewer we don't need to do anything fancy\n return rooms if rooms.length <= 5\n\n # Get the index for the current room\n room_idx = rooms.index(Membership.joining(self,room).first)\n\n # By default, show two rooms on either side\n lower = room_idx-2 < 0 ? 0 : room_idx-2\n upper = room_idx+2 > rooms.length-1 ? rooms.length-1 : room_idx+2\n\n # If this room is near the bottom of the list, fill in from the top\n if lower < 2\n upper += 2-lower\n rooms = rooms[lower..upper][0,5]\n\n # If this room is near the top of the list, fill in from the bottom\n elsif rooms.length-upper < 2\n lower -= rooms.length-upper+1\n logger.debug(\"__NOW__ LENGTH: #{rooms.length}, LOWER: #{lower}, UPPER: #{upper}, IDX: #{room_idx}\")\n rooms = rooms[lower..upper][-5,5]\n\n # No need to fill, just show that subset\n else\n rooms = rooms[lower..upper]\n end\n\n rooms\n end",
"def room(room_id = nil)\n room_id ? Room.new(self, :_id => room_id) : @room\n end",
"def new_rooms\n min_rooms = MIN_NEXT_ROOMS\n max_rooms = MAX_NEXT_ROOMS\n rand(min_rooms..max_rooms).times do\n @next_rooms << Zarta::Room.new(@dungeon)\n end\n end",
"def link_to_room(direction:, room:)\n opposite_direction = LunchGame::Helpers.opposite_direction(direction)\n instance_variable_set(\"@#{direction}_room\", room)\n room.instance_variable_set(\"@#{opposite_direction}_room\", self)\n end",
"def add_rooms_to_dungeon(dungeon)\n dungeon.add_room(:largecave,\n \"Large Cave\",\n \"a large cavernous cave\",\n { :west => :smallcave })\n\n dungeon.add_room(:smallcave,\n \"Small Cave\",\n \"a small, claustrophobic cave\",\n { :east => :largecave })\n\nend",
"def create_rooms\n @rooms = []\n (1..20).each do |room_num|\n room = Hotel::Room.new(room_num: 1)\n room.room_num = room_num\n @rooms << room\n end\n return @rooms\n end",
"def add_room(room)\n\t\t@rooms.push(room)\n\tend",
"def new_room(&blk)\n @rooms.each do |r|\n blk.call(r)\n end\n\n @onnew.push(blk)\n end",
"def create_room()\n if @room == nil\n songs = []\n guests = []\n print \"enter a capacity: \"\n capacity = self.input.to_i\n print \"enter an entry fee: \"\n entry_fee = self.input.to_i\n @room = Room.new(songs, guests, capacity, entry_fee)\n else\n puts \"\\n\" + \"-- Room Contents --\\n\".center(30)\n puts \"songs: #{@room.songs}\"\n puts \"guests: #{@room.guests}\"\n puts \"capacity: #{@room.capacity}\"\n puts \"entry fee: #{@room.entry_fee}\"\n puts \"\\n\"\n end\n end",
"def createnewroom(dir, roomdesc)\n ##########Setting up the direction to move#############\n #changex = String.new\n #changy = String.new\n\n case dir\n\n when \"north\"\n changex = 1\n changey = 0\n when \"south\"\n changex = -1\n changey = 0\n when \"east\"\n changex = 0\n changey = +1\n when \"west\"\n changex = 0\n changey = -1\n end\n ############################################################\n\n\n ############################checking of the tile even exits##############################\n if Tile.find_by_xcoord_and_ycoord(self.tile.xcoord+changex, self.tile.ycoord+changey) != nil\n self.sendtoplayer2( \"there is already a room in that exit direction\")\n return\n end\n\n @newtile = Tile.new\n @newtile.xcoord = self.tile.xcoord+changex\n @newtile.ycoord = self.tile.ycoord+changey\n @newtile.desc = roomdesc\n exitsvar = {reversedir(dir) => self.tile.id}\n @newtile.exits = exitsvar\n @newtile.save\n @currenttile = self.tile\n if @currenttile.exits\n exitsvar = @currenttile.exits\n exitsvar.merge!({dir => @newtile.id})\n else\n exitsvar = {}\n exitsvar = {dir => @newtile.id}\n end\n @currenttile.exits = exitsvar\n @currenttile.save\n self.sendtoplayer2(\"Created new room to the #{dir}\")\n end",
"def create_rooms(rooms_params)\n\t\trooms_params[:extra_info] ||= \"\"\n\n\t\trooms_params[:range].each do |number|\n\t\t\trooms << Room.create( number: number.to_i, \n\t\t\t\t\t\t\t\t\t\t\t\t\t capacity: rooms_params[:capacity].to_i, \n\t\t\t\t\t\t\t\t\t\t\t\t\t extra_info: rooms_params[:extra_info],\n\t\t\t\t\t\t\t\t\t\t\t\t\t name: rooms_params[:name] )\n\t\tend\n\tend",
"def create_default_rooms\n wish_list_name = 'Wish List'\n self.dressing_rooms.create label: wish_list_name unless self.dressing_rooms.any? {|room| room.label == wish_list_name}\n\n closet_name = 'My Closet'\n self.dressing_rooms.create label: closet_name unless self.dressing_rooms.any? {|room| room.label == closet_name}\n\n session_name = \"My Cart\"\n session_room = self.dressing_rooms.create label: session_name unless self.dressing_rooms.any? {|room| room.label == session_name}\n self.recent_dressing_room = session_room if self.recent_dressing_room.nil?\n self.save!\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
continuously check for new messages
|
def start()
unread = notifications()['UnreadMessage'].to_i
@thread = Thread.new do
loop do
unread_messages = notifications()['UnreadMessage'].to_i
if unread_messages > unread then
@callback.call if @callback
unread = unread_messages
end
sleep 3
end
end
'checking for new message every 3 seconds ...'
end
|
[
"def check_and_update_msgs\n\t\ttodos = todo_msgs\n\t\tdel_msgs_by_time(find_latest_time(todos))\n\t\tadd_next_ocurrences(todos) # add another if recurring\n\t\tpretify_msgs(todos)\n\tend",
"def sleep_until_change\n @imap.idle do |r|\n begin\n Catfriend.whisper \"#{id}: #{r}\"\n next if r.instance_of? Net::IMAP::ContinuationRequest\n\n if r.instance_of? Net::IMAP::UntaggedResponse\n case r.name\n when 'EXISTS', 'EXPUNGE', 'FETCH'\n @imap.idle_done\n end\n end\n rescue => e\n error e.message\n end\n end\n\n count = get_unseen_count\n if count != @message_count\n notify_message(count) if count > @message_count\n @message_count = count\n Catfriend.whisper \"message count changed to #@message_count\"\n else\n Catfriend.whisper \"message count unchanged from #@message_count\"\n end\n rescue Net::IMAP::Error, IOError\n # reconnect and carry on\n reconnect unless stopping?\n rescue => e\n unless stopping?\n # todo: see if we have to re-open socket\n notify_message \"#{@message_count} [error: #{e.message}]\"\n puts e.backtrace.join \"\\n\"\n end\n end",
"def notification_loop(period = 0.1)\n already_summarized = Set.new\n was_connected = nil\n while true\n mutex.synchronize do\n has_valid_connection =\n begin\n client.poll\n true\n rescue Exception\n begin\n connect(nil)\n true\n rescue Exception\n end\n end\n \n already_summarized = \n summarize_pending_messages(already_summarized) do |id, msg|\n yield id, msg\n end\n if has_valid_connection\n was_connected = true\n end\n \n if has_valid_connection && !was_connected\n Readline.puts \"reconnected\"\n elsif !has_valid_connection && was_connected\n Readline.puts \"lost connection, reconnecting ...\"\n end\n was_connected = has_valid_connection\n end\n sleep period\n end\n end",
"def work(message)\n if message.is_a?(Message)\n self.count = count + 1\n\n Concurrent::IVar.new(:ok)\n else\n expected_messages_received?\n end\n end",
"def has_next_message\n\t\tend",
"def check_msgs\n\t\tmessages = Message.all\t\n\t\tmessages.each do |m|\n\t\t\tstatus = get_msg_info(m.sid)\n\t\t\tm.status = status unless status==\"Error\" and m.status != \"Error\"\n\t\t\tm.save\n\t\tend\n\tend",
"def begin_polling\n self.stop_poll = false\n poll do\n retrieve_new_messages\n end\n end",
"def start\n @last_message_date ||= @mailbox.last.date\n @thread = Thread.new do\n loop do\n sleep( @frequency)\n check\n end\n end\n end",
"def sync_new(mailbox)\n # Skip any mailbox with attributes in ignore_attr\n return if ! (mailbox.attr & @@ignore_attr).empty?\n return if !@running\n\n name = Net::IMAP.decode_utf7(mailbox.name)\n cache = @mailboxes[name] || Mailbox.new(name)\n\n puts \"Examining mailbox #{name}\"\n\n begin\n @imap.examine(mailbox.name)\n rescue => e\n puts \"Failed to examine mailbox: #{e}\"\n return\n end\n\n uidvalidity = @imap.responses[\"UIDVALIDITY\"][-1]\n uidnext = @imap.responses[\"UIDNEXT\"][-1]\n\n if cache.uidvalidity != uidvalidity\n puts \"UIDVALIDITY differ, rescaning all mailbox\"\n ids = @imap.search([\"NOT\", \"DELETED\"])\n else\n if (cache.uidmax + 1 == uidnext)\n puts \"No new messages\"\n return\n end\n puts \"UIDVALIDITY match, get new messages only\"\n ids = ((cache.uidmax + 1) .. uidnext).to_a\n end\n\n puts \"; got #{ids.size} messages\"\n\n while(!(block = ids.shift(@@buf_size)).empty?)\n\n break if ! @running\n puts \"; requesting messages #{block.first}..#{block.last} from server\"\n\n msgs = @imap.fetch((block.first..block.last), [\"UID\", \"X-GM-MSGID\", \"X-GM-THRID\", \"X-GM-LABELS\", \"FLAGS\", \"RFC822\"])\n\n if ! msgs\n puts msgs\n next\n end\n\n msgs.each { |msg|\n break if ! @running\n\n body = msg.attr[\"RFC822\"]\n body.force_encoding(\"binary\") if body.respond_to?(:force_encoding) \n body.gsub(\"\\r\\n\", \"\\n\")\n\n labels = msg.attr[\"X-GM-LABELS\"].push(name).collect { |label| Net::IMAP.decode_utf7(label.to_s) }\n\n state = msg.attr[\"FLAGS\"].collect { |flag| flag.to_s.downcase.to_sym }\n puts state\n\n begin\n response = RestClient.post \"http://localhost:8042/message.json\", \n { :body => body, :labels => labels, :state => state, :mailbox => name },\n { :content_type => :json, :accept => :json}\n rescue RestClient::ResourceNotFound => e\n puts \"Warning: resource not found\"\n next\n rescue => e\n puts \"Failed to communicate with heliotrope : #{e.class}\"\n @running = false\n break\n end\n\n puts response \n response = JSON.parse(response)\n\n if response[\"response\"] == \"ok\"\n if response[\"status\"] == \"seen\"\n cache.num_seen += 1\n else\n cache.num_indexed += 1\n end\n else\n cache.num_bad += 1\n puts \"Error for message: \" + response[\"error_message\"]\n end\n\n cache.uidmax = [cache.uidmax || 0, msg.attr[\"UID\"]].max\n }\n end\n\n puts \"Store mailbox #{name} cache\"\n cache.uidnext = uidnext\n cache.uidvalidity = uidvalidity\n @mailboxes[name] = cache\n save_mailboxes\n end",
"def process_messages\n execute_sql_query(\n 'select * from messages where processed = 0 and direction = \\'in\\';'\n ).each do |msg|\n execute_sql_statement(\n 'update messages set processed = \\'1\\' ' \\\n \"where id = '#{msg[0]}';\"\n )\n activate(payload: msg[3], flag: msg[2])\n end\n end",
"def process_messages\n sleep 0.05\nend",
"def is_new?(message)\n result = false\n previous_messages = cache_get(message[:station_id])\n if(previous_messages)\n seen_message_before = previous_messages.any? { |m| message[:text] == m[:text] }\n\n if !seen_message_before\n if previous_messages.length > 7\n @logger.debug(\"New message - programme has changed for #{:station_id}\")\n @logger.debug(previous_messages)\n result = true \n else\n @logger.debug(\"Previous_messages.length < 7\")\n end\n end\n end\n result\n end",
"def process_privmsg_loop\n while true\n check_privmsg_output if @next_message_time <= Time.now && !@privmsg_buffer.empty?\n\n sleep 0.05\n end\n end",
"def watchMail(imap, folder)\n \n # Loop for checking message increase in the folder\n begin\n \n imap.select(folder)\n \n # Get the current folder size\n fsize = imap.status(folder, [\"MESSAGES\"])\n csize = fsize[\"MESSAGES\"]\n \n loop do\n fsize = imap.status(folder, [\"MESSAGES\"])\n if fsize[\"MESSAGES\"] > csize\n message_ids = imap.uid_search(\"ALL\")\n uid = message_ids.last\n email = imap.uid_fetch(uid, \"ENVELOPE\")[0].attr[\"ENVELOPE\"]\n pp \"[#{email.from[0].name}] #{email.subject}\"\n csize = fsize[\"MESSAGES\"]\n else\n sleep(10)\n end\n end\n rescue => e\n exit(1)\n end\nend",
"def run!\n while true\n begin\n listings = fetch_listings\n rescue Exception => e\n puts \"Exception while fetching listings: #{e}\"\n end\n if listings\n new_listings = process_listings( listings )\n if new_listings.any?\n puts \"======================================\"\n puts \" #{new_listings.count} new listings!\"\n puts \" (feed: #{feed_title})\"\n puts \"======================================\"\n\n `say \"#{new_listings.count} new listings!\"`\n alert new_listings\n end\n else\n puts \"no listings at '#{ rss_feed_url }'\"\n end\n sleep 300\n end\n true\n end",
"def message_received(&callback)\n if block_given?\n @message_received_callbacks << callback\n else\n @message_received_callbacks.each { |c| c.call }\n if @check_interval > 0\n now = Time.now\n if (now - @last_received) > MIN_RESTART_INACTIVITY_TIMER_INTERVAL\n @last_received = now\n restart_inactivity_timer\n end\n end\n end\n true\n end",
"def scan\n @@scanning = true\n if AppVariable.exists?(name: 'latest_message_epoch_time')\n thr = Thread.new do\n GmailReader.read_bank_notices(AppVariable.find(1).value)\n @@scanning = false\n end\n else\n @@scanning = false\n end\n head :no_content\n end",
"def process_privmsg_loop\n loop do\n check_privmsg_output if @next_message_time <= Time.now && !@privmsg_buffer.empty?\n\n sleep 0.05\n end\n end",
"def check\n # if the server doesn't support us, we just do nothing.\n return unless Config.server.respond_to?(:broadcast_message)\n\n info \"starting email checker loop\"\n\n Thread.new do\n loop do\n debug \"checking email\"\n\n begin\n with_imap do |imap|\n imap.search(['NOT', 'DELETED']).each do |message_id|\n info \"mail found, handling\"\n handle_message_id(imap, message_id)\n end\n end\n\n rescue Exception => ex\n error \"checking email: #{ex}\"\n end\n\n break unless poll_email?\n\n sleep (Config.email['interval'] || 30)\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns a byte array representing this command, appropriate for sending to the sign's serial port
|
def to_bytes
# set defaults
self.sender ||= :pc
self.receiver ||= 1
bytes = []
bytes.concat [0x00] * 5 # start of command
bytes.concat [0x01] # <SOH>
bytes.concat self.sender.to_bytes # Sender Address
bytes.concat self.receiver.to_bytes # Reciver Address
bytes.concat [0x02] # <STX>
bytes.concat string_to_ascii_bytes(command_code) # Command Code
bytes.concat command_payload_bytes # command specific payload
bytes.concat [0x03] # <ETX>
bytes.concat generate_checksum_bytes(bytes[10..-1]) # Checksum bytes (4)
bytes.concat [0x04] # <EOT>
bytes
end
|
[
"def command_payload_bytes\n raise MovingsignApi::NotImplementedError, \"Needs to be implemented in subclass.\"\n end",
"def build_payload(command)\n [PAYLOAD_START, command, 0, 0, 0, 0, 0, 0].pack('CCCCCCCC')\n end",
"def to_s\n return command\n end",
"def to_binary\n return '' unless @ready\n\n to_a.pack('C*') rescue binding.pry\n end",
"def to_wire\n content = ''\n @avps.each { |a| content += a.to_wire }\n length_8, length_16 = Internals::UInt24.to_u8_and_u16(content.length + 20)\n code_8, code_16 = Internals::UInt24.to_u8_and_u16(@command_code)\n request_flag = @request ? '1' : '0'\n proxy_flag = @proxyable ? '1' : '0'\n flags_str = \"#{request_flag}#{proxy_flag}000000\"\n\n header = [@version, length_8, length_16, flags_str, code_8, code_16, @app_id, @hbh, @ete].pack('CCnB8CnNNN')\n header + content\n end",
"def to_a\n return [] unless @ready\n\n bytes = [OP_CODES[@op][@mode][:byte]]\n\n if [:a, :ar].include?(@mode) || (@arg && @arg > 255)\n bytes += [@arg.ls_byte, @arg.ms_byte]\n elsif @arg\n bytes += [@arg]\n else\n bytes\n end\n end",
"def build_packet\r\n return [@request_id, @command_type, @string1, @string2].pack(\"VVa#{@string1.length}a2\")\r\n end",
"def build_packet\n return [@request_id, @command_type, @string1, @string2].pack(\"VVa#{@string1.length}a2\")\n end",
"def bytes\n\t\tbin.unpack('C*')\n\tend",
"def bytes\n # preamble + payload + error_correction\n payload\n end",
"def encode_command(cmd)\n # use strict_encode because linefeeds are not correctly handled in our model\n Base64.strict_encode64(cmd.encode(Encoding::UTF_16LE)).chomp\n end",
"def message_for_sending\n json = self.to_apple_json\n message = \"\\0\\0 #{self.device.to_hexa}\\0#{json.length.chr.force_encoding 'ascii-8bit'}#{json}\"\n message\n end",
"def bytes\n\t\t@ida.get_many_bytes(self[0].address, instruction_size).unpack(\"C*\")\n\tend",
"def to_s\r\n packet = build_packet\r\n @packet_size = packet.length\r\n return [@packet_size].pack(\"V\") + packet\r\n end",
"def payload\n if self.send_type == EasyIP::Operand::STRING\n self.data.unpack(\"Z*\")\n else\n values = self.data.unpack(\"v\" * self.send_size)\n end\n end",
"def request\n ## Encode the request for sending to the device:\n return self.map {|w| MTik::Request::to_tikword(w)}.join + 0x00.chr\n end",
"def packed()\n body = @flags.chr +\n @authen_method.chr +\n @priv_lvl.chr + \n @authen_type.chr +\n @service.chr +\n @user_len.chr +\n @port_len.chr +\n @rem_addr_len.chr +\n @arg_cnt.chr\n \n body << @arg_lens.pack('C*') if (@arg_lens.length != 0)\n body << @user if (@user)\n body << @port if (@port)\n body << @rem_addr if (@rem_addr)\n body << @args.join if (@args.length != 0)\n\n return(body)\n end",
"def byte_string\n [@integer].pack(pack_char)\n end",
"def to_s\n @packet_data\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns command specific byte array payload
|
def command_payload_bytes
raise MovingsignApi::NotImplementedError, "Needs to be implemented in subclass."
end
|
[
"def build_payload(command)\n [PAYLOAD_START, command, 0, 0, 0, 0, 0, 0].pack('CCCCCCCC')\n end",
"def to_bytes\n # set defaults\n self.sender ||= :pc\n self.receiver ||= 1\n\n bytes = []\n\n bytes.concat [0x00] * 5 # start of command\n bytes.concat [0x01] # <SOH>\n bytes.concat self.sender.to_bytes # Sender Address\n bytes.concat self.receiver.to_bytes # Reciver Address\n bytes.concat [0x02] # <STX>\n bytes.concat string_to_ascii_bytes(command_code) # Command Code\n bytes.concat command_payload_bytes # command specific payload\n bytes.concat [0x03] # <ETX>\n bytes.concat generate_checksum_bytes(bytes[10..-1]) # Checksum bytes (4)\n bytes.concat [0x04] # <EOT>\n\n bytes\n end",
"def bytes\n # preamble + payload + error_correction\n payload\n end",
"def payload_bytes\n if @payload.is_a? String\n return @payload\n end\n return @payload_raw\n end",
"def command_content\n return @command_content\n end",
"def payload\n if self.send_type == EasyIP::Operand::STRING\n self.data.unpack(\"Z*\")\n else\n values = self.data.unpack(\"v\" * self.send_size)\n end\n end",
"def generate\n\t\tcmd = (datastore['CMD'] || '') << \"\\x00\"\n\t\tcall = \"\\xe8\" + [cmd.length].pack('V')\n\t\tpayload =\n\t\t\t\"\\x48\\x31\\xc0\" + # xor rax, rax\n\t\t\t\"\\x48\\xb8\\x3b\\x00\\x00\\x02\\x00\\x00\\x00\\x00\" + # mov rax, 0x200003b (execve)\n\t\t\tcall + # call CMD.len\n\t\t\tcmd + # CMD\n\t\t\t\"\\x48\\x8b\\x3c\\x24\" + # mov rdi, [rsp]\n\t\t\t\"\\x48\\x31\\xd2\" + # xor rdx, rdx\n\t\t\t\"\\x52\" + # push rdx\n\t\t\t\"\\x57\" + # push rdi\n\t\t\t\"\\x48\\x89\\xe6\" + # mov rsi, rsp\n\t\t\t\"\\x0f\\x05\" # syscall\n\tend",
"def payload; message[:payload]; end",
"def read_command\n message = socket.recv_message #=> ZMQ::Message\n worker_id = Identity.new(message.unwrap.data.to_s.to_sym)\n json = message.first.data\n parameters = begin\n JSON.parse(json).with_indifferent_access\n rescue\n JobDispatch.logger.error(\"Received invalid json data: #{json.inspect} from socket id '#{worker_id}'\")\n {error: \"Invalid JSON\"}\n end\n Command.new(worker_id, parameters)\n end",
"def payload\n Utils.bytes_to_hex_string(uid.last(BYTES[:payload]))\n end",
"def payload_data\n reply.documents[0][PAYLOAD].data\n end",
"def to_a\n return [] unless @ready\n\n bytes = [OP_CODES[@op][@mode][:byte]]\n\n if [:a, :ar].include?(@mode) || (@arg && @arg > 255)\n bytes += [@arg.ls_byte, @arg.ms_byte]\n elsif @arg\n bytes += [@arg]\n else\n bytes\n end\n end",
"def commandhash\n return @commandHash\n end",
"def build_payload(target)\r\n target_name = \"#{target[:version]}-#{target[:os]}-#{target[:arch]}\"\r\n selected = TARGET_MATRIX[target_name]\r\n unless selected\r\n MiscUtils::myputs \"Target not available, check User-Agent format!\"\r\n MiscUtils::myputs target_name\r\n return ''\r\n end\r\n \r\n MiscUtils::myputs \"Building payload for '#{target_name}'...\"\r\n MiscUtils::myputs \"Return address: #{sprintf(\"0x%08x\",selected[:ret_address])}, \" +\r\n \"shellcode: #{selected[:shellcode].size} bytes.\"\r\n \r\n payload = String.rand_alpha(selected[:padding_size]-selected[:shellcode].size)\r\n \r\n unless target[:os] =~ /Windows/\r\n payload << selected[:shellcode]\r\n payload << selected[:prepend_data]\r\n \r\n # Handle big-endian / little-endian\r\n if target[:arch] == \"PPC\"\r\n payload << [selected[:ret_address]].pack(\"N\")\r\n else\r\n payload << [selected[:ret_address]].pack(\"V\")\r\n end\r\n else\r\n payload << selected[:prepend_data]\r\n payload << [selected[:ret_address]].pack(\"V\")\r\n payload << selected[:shellcode]\r\n end\r\n \r\n # Appended data comes always at end of payload\r\n payload << selected[:append_data]\r\n \r\n MiscUtils::myputs \"Payload: #{payload.size} bytes (padding=#{payload[0,8]}...)\"\r\n \r\n return payload\r\n end",
"def build_packet\n return [@request_id, @command_type, @string1, @string2].pack(\"VVa#{@string1.length}a2\")\n end",
"def make_command(msg_id, extra)\r\n\t\t# Two opcodes, get handled differently..\r\n\t\tcase msg_id\r\n\t\twhen 0x30001\r\n\t\t\tdata = [0xf0f0f0f0,0x0004000b,0x0003001c].pack('VVV')\r\n\r\n\t\twhen 0x30002\r\n\t\t\tdata = [0xf0f0f0f1,0xffffffff,0,0x989680,0x00000002].pack('VVVVV')\r\n\r\n\t\tend\r\n\r\n\t\t# Put some data on...\r\n\t\tdata << extra\r\n\r\n\t\t# Pad it to 8 bytes...\r\n\t\tleft = data.length % 8\r\n\t\tdata << (\"\\x00\" * (8 - left)) if (left > 0)\r\n\r\n\t\t# Combine the pieces..\r\n\t\tpkt = [\r\n\t\t\t(data.length / 8) + 1, # chunkLen\r\n\t\t\tmsg_id # msg ID\r\n\t\t].pack('VV')\r\n\t\tpkt << data\r\n\r\n\t\tpkt\r\n\tend",
"def build_packet\r\n return [@request_id, @command_type, @string1, @string2].pack(\"VVa#{@string1.length}a2\")\r\n end",
"def retrbinary(cmd, blocksize, rest_offset = T.unsafe(nil)); end",
"def to_s\n return command\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
set definition and create events
|
def definition_attributes=(definition_attributes)
self.definition = ActivityDefinition::BaseActivityDefinition.from_attributes definition_attributes
self.create_events_from_definition
end
|
[
"def create_events\n @events = []\n @lines.each do |l|\n e = Event.new l\n @events << e\n end\n end",
"def on_def(name, params, bodystmt); end",
"def create_default_events\n EventType::DEFAULT_EVENTS.each_value do |e|\n event = self.event_types.find_by_name(e[:name])\n unless event\n self.event_types.create(e) do |et|\n et.editable = e[:editable] if e.has_key?(:editable)\n end\n end\n end\n end",
"def make_event\n\t\tEvent.create :user_id => self.user_id, :script_tag => self.id, :install_event_id => self.event_id, :title => self.title, :start_time => self.start_time, :end_time => self.end_time, :event_type => \"Script\"\n\tend",
"def definition=(value)\n @definition = value\n end",
"def initialize_event_machine; end",
"def definition(definition_name)\n @definition_name = definition_name\n end",
"def initialize_events(&block)\n @event.tick << block if block_given?\n clock = proc do\n if @trigger.stop?\n stop\n else\n @midi_output.do_clock\n end\n end\n @event.clock = clock\n @event.start << proc { @midi_output.do_start }\n @event.stop << proc { @midi_output.do_stop }\n @event\n end",
"def create_event_types\n EventType.create(title: 'Talk', length: 30, color: '#FF0000', description: 'Presentation in lecture format',\n minimum_abstract_length: 0,\n maximum_abstract_length: 500, program_id: id)\n EventType.create(title: 'Workshop', length: 60, color: '#0000FF', description: 'Interactive hands-on practice',\n minimum_abstract_length: 0,\n maximum_abstract_length: 500, program_id: id)\n end",
"def createEvent(evFrom)\n end",
"def define_event_helpers\n @event_block = {}\n EVENTS.each do |event|\n clazz = class << self; self; end\n clazz.send :define_method, \"on_#{event}\" do |&block|\n @event_block[event] = block\n end\n clazz.send :define_method, \"trigger_#{event}\" do |*args|\n @event_block[event].call *args if @event_block[event]\n end\n end\n end",
"def event *names, &blk\n names.each do |name|\n Bot::Events.create name, self, nil, &blk\n end\n end",
"def define_event( *args )\n for event in args\n unless event.is_a?( Symbol )\n raise( ArgumentError, 'Expected a Symbol' )\n end\n @control_events[event] = event\n end\n nil\n end",
"def create_event_runner\n self.event_runner = Ray::DSL::EventRunner.new\n end",
"def send_events; end",
"def create_pseudo_events\r\n Pseudo.each do |ev|\r\n @events[ev] = {callbacks: {}}\r\n end\r\n end",
"def create_event(options={})\n\t\t\tEvent.create({\n\t\t\ttitle: \"Event's name\",\n\t\t\tlocal: \"Event's local\",\n\t\t\tdescription: \"Event's test description\",\n\t\t\tstart_time: DateTime.now,\n\t\t\tend_time: 2.days.from_now\n\t\t\t}.merge(options))\n\t\tend",
"def set_Event(value)\n set_input(\"Event\", value)\n end",
"def register_events(klass, state, other_params, &exec_block)\n @klass_being_defined = klass\n @state_being_defined = state\n\n # if an initial state has not been set, then set it. In practice, means the first state definition\n # gets the initial state.\n @cfsm_initial_state[ klass ] = state unless @cfsm_initial_state[ klass ]\n\n # Evaluate the transition definitions\n self.instance_eval( &exec_block ) if exec_block\n\n @klass_being_defined = nil\n @state_being_defined = nil\n @other_params = other_params\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /users/:user_id/uploads Create an upload for the given user. Uploading the image happens behind the scenes in the Upload model.
|
def create
@upload = @user.uploads.build(upload_params)
authorize @upload
respond_to do |format|
if @upload.save
format.json { render json: @upload }
format.html { redirect_to user_uploads_path(@user) }
else
format.json { render json: @upload.errors }
format.json { render :new }
end
end
end
|
[
"def create\n\t\trequire_user\n\t\t@uploads = Upload.new(params[:upload])\n\t\tcurrent_user.uploads << @uploads\n\t\t@uploads.user_id = current_user.id\n\n\t\tif @uploads.save && current_user.save\n\t\t\tredirect_to user_uploads_path, :notice => \"Upload saved!\"\n\t\telse\n\t\t\tredirect_to user_uploads_path, :notice => \"Upload cannot be saved!\"\n\t\tend\n\tend",
"def upload\n user = current_user\n # Get params from the request\n picture = upload_image_params\n # Convert Base64 to binary data\n picture_bin = Base64.decode64(picture[:base64])\n picture_name = picture[:fname]\n # Create a new file for saving image\n file_name = Time.new.to_s.gsub!(' ', '_') + '.jpg' \n file_name_rpath = File.join('public', 'uploads', file_name)\n image_file = File.new(file_name_rpath, File::CREAT|File::TRUNC|File::RDWR, 0644)\n image_file.syswrite(picture_bin)\n image_file.close()\n # Update image file name to user object\n user.profile_pic = file_name\n user.save\n # Expose to response\n @pub_filename = file_name\n end",
"def upload_file(upload, user, client_name)\n if upload != nil\n if user.link_picture != nil\n File.delete('public/images/' << user.link_picture)\n end\n name = upload['img'].original_filename\n directory = 'public/images/' + client_name + '/users/' + user.username\n path = File.join(directory, name)\n File.open(path, 'wb') { |f| f.write(upload['img'].read) }\n path_img = client_name + '/users/' + user.username + '/' + name\n User.where(:id => user.id).update_all(link_picture: path_img)\n end\n end",
"def create_upload io\n post_request \"uploads\", {file: io}\n end",
"def create\n @user_song_upload = current_user.user_song_uploads.build(params[:user_song_upload])\n\n respond_to do |format|\n if @user_song_upload.save\n format.html { redirect_to @user_song_upload, notice: 'User song upload was successfully created.' }\n format.json { render json: @user_song_upload, status: :created, location: @user_song_upload }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_song_upload.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user_file = UserFile.new(user_file_params)\n\n respond_to do |format|\n if @user_file.save\n format.html { redirect_to @user_file, notice: 'User file was successfully created.' }\n format.json { render :show, status: :created, location: @user_file }\n else\n format.html { render :new }\n format.json { render json: @user_file.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_upload_request\n call(:post, upload_path)\n end",
"def create\n @user_file = UserFile.new(params[:user_file])\n\n respond_to do |format|\n if @user_file.save\n format.html { redirect_to @user_file, :notice => 'User file was successfully created.' }\n format.json { render :json => @user_file, :status => :created, :location => @user_file }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @user_file.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user_file = UserFile.new(params[:user_file])\n\n respond_to do |format|\n if @user_file.save\n format.html { redirect_to @user_file, notice: 'User file was successfully created.' }\n format.json { render json: @user_file, status: :created, location: @user_file }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_file.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @super_d_upload = current_user.super_d_uploads.build(super_d_upload_params)\n\n respond_to do |format|\n if @super_d_upload.save\n format.html { redirect_to @super_d_upload, notice: 'Super d upload was successfully created.' }\n format.json { render :new, status: :created, location: @super_d_upload }\n else\n format.html { render :new }\n format.json { render json: @super_d_upload.errors, status: :unprocessable_entity }\n end\n end\n end",
"def file_upload(params_userfile)\n content_upload(params_userfile.read)\n end",
"def create\n @ufile = Ufile.new(params[:ufile])\n @ufile.user_id = current_user.id\n respond_to do |format|\n if @ufile.save\n format.html { redirect_to \"/ufiles\", notice: 'Ufile was successfully created.' }\n format.json { render json: @ufile, status: :created, location: @ufile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ufile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user_upload_log = UserUploadLog.new(user_upload_log_params)\n\n respond_to do |format|\n if @user_upload_log.save\n format.html { redirect_to @user_upload_log, notice: 'User upload log was successfully created.' }\n format.json { render :show, status: :created, location: @user_upload_log }\n else\n format.html { render :new }\n format.json { render json: @user_upload_log.errors, status: :unprocessable_entity }\n end\n end\n end",
"def test_monkey_upload_for_user\n # Step 1\n @user = setup_user\n\n # Step 2\n upload_and_link_image_by_user_id(@user)\n assert_response(@response, :success)\n\n # Step 3\n params = {\n 'user_id' => @user.id,\n 'api_key' => @api_key\n }\n\n get '/user', params\n assert_response(@response, :succes)\n\n # Step 4\n assert(@parsed_response['count'] == 1, @parsed_response)\n image = @parsed_response['images'].first\n assert(image['image_path'], image)\n assert_equal('user_id', image['type_name'], image)\n assert_equal('XX3', image['user_type'], image)\n assert_equal(@user.id.to_s, image['ext_id'], image)\n assert_equal(@user.id, image['user_id'], image)\n assert_equal(@user.display_name, image['user'], image)\n assert_match(@user.cookie_id, image['caption'], image)\n end",
"def create\n success = true\n photos = params[:upload].delete(:photos)\n u = upload_params\n respond_to do |format|\n if photos ## Batch photo upload\n photos.each do |p|\n @upload = Upload.new(u)\n @upload.user = current_user\n @upload.photo = p\n success = @upload.save\n break unless success\n end\n else # Simple single photo upload\n @upload = Upload.new(u)\n @upload.user = current_user\n success = @upload.save\n end\n if success\n notice = 'Upload was successfully saved.'\n @uploads = current_user.uploads\n filter_uploads\n format.html { redirect_to uploads_url, notice: notice }\n format.json { render json: @uploads, status: :created }\n else\n format.html { render :new }\n format.json { render json: {errors: @upload.errors}, status: :unprocessable_entity }\n end\n \n end\n end",
"def create\n @user_csv_upload = UserCsvUpload.new(user_csv_upload_params)\n\n uploaded_io = params[:name]\n File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|\n file.write(uploaded_io.read)\n end\n\n respond_to do |format|\n if @user_csv_upload.save\n format.html { redirect_to @user_csv_upload, notice: 'User csv upload was successfully created.' }\n format.json { render :show, status: :created, location: @user_csv_upload }\n else\n format.html { render :new }\n format.json { render json: @user_csv_upload.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @upload = Upload.new(params[:upload])\n if(@upload.name==\"\")\n\t\t\t@upload.name=@upload.content.original_filename\n\t\tend\n\n if(@upload.uploadGroup==\"\")\n @upload.uploadGroup=(User.findById(@upload.ownerId)).userType\n end\n\n respond_to do |format|\n if @upload.save\n format.html { redirect_to @upload, notice: 'Upload was successfully created.' }\n format.json { render json: @upload, status: :created, location: @upload }\n @users = User.findByGroup(@upload.uploadGroup)\n UploadMailer.notification_email(@users, @upload).deliver\n else\n format.html { render action: \"new\" }\n format.json { render json: @upload.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @image_user = ImageUser.new(image_user_params)\n @image_user.user_id = params[:user_id]\n @image_user.image_id = params[:image_id]\n puts 'CREATING NEW IMAGEUSER', @image_user.inspect\n respond_to do |format|\n if @image_user.save\n format.json {\n puts @image_user.inspect\n head :no_content\n }\n else\n format.json { render json: @image_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user_image = UserImage.new(params[:user_image])\n\n respond_to do |format|\n if @user_image.save\n format.html { redirect_to(@user_image, :notice => 'User image was successfully created.') }\n format.xml { render :xml => @user_image, :status => :created, :location => @user_image }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user_image.errors, :status => :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /users/:user_id/uploads/:id Deletes the given user upload.
|
def destroy
@upload = @user.uploads.find(params[:id])
authorize @upload
@upload.destroy
redirect_to user_uploads_path(@user)
end
|
[
"def destroy\n @upload = current_user.uploads.find(params[:id])\n @upload.destroy\n\n respond_to do |format|\n format.html { redirect_to(uploads_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @userfile = Userfile.find(params[:id])\n @userfile.destroy\n\n respond_to do |format|\n format.html { redirect_to uploads_url }\n format.json { head :no_content }\n end\n end",
"def delete_upload_request(upload_id)\n call(:delete, upload_path(\"#{upload_id}/\"))\n end",
"def destroy\r\n @fileupload = Fileupload.find(params[:id])\r\n\r\n File.delete(\"#{RAILS_ROOT}/public/files/#{@fileupload.username+'_'+@fileupload.filename}\")\r\n @fileupload.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to(fileuploads_url) }\r\n format.xml { head :ok }\r\n end\r\n end",
"def destroy\n @user_file = UserFile.find(params[:id])\n @user_file.destroy\n\n respond_to do |format|\n format.html { redirect_to user_files_url }\n format.json { head :no_content }\n end\n end",
"def delete_upload_user(username:)\n ensure_successful_response(client.delete_user(user_name: username))\n end",
"def destroy\n upload = Upload.find(params[:id])\n upload.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_uploads_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user_file.destroy\n respond_to do |format|\n format.html { redirect_to user_files_url }\n format.json { head :no_content }\n end\n end",
"def delete_upload(upl_id, opts = {})\n upload_delete_with_http_info(upl_id, opts)\n nil\n end",
"def destroy\n @upload = Upload.find(params[:id])\n @upload.destroy\n\n respond_to do |format|\n format.html { redirect_to uploads_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @userfile.destroy\n respond_to do |format|\n format.html { redirect_to userfiles_url, notice: 'Userfile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @file_upload = FileUpload.find(params[:id])\n @file_upload.destroy\n\n respond_to do |format|\n format.html { redirect_to file_uploads_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @fileupload = Fileupload.find(params[:id])\n @fileupload.destroy\n \n respond_to do |format|\n format.html { redirect_to(fileuploads_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @file_upload = FileUpload.find(params[:id])\n @file_upload.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_file_uploads_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @upload = Upload.find(params[:id])\n @upload.destroy\n\n respond_to do |format|\n format.html { redirect_to(uploads_url) }\n format.xml { head :ok }\n end\n end",
"def delete_user(user)\n delete user_path(user)\n end",
"def destroy\n @user = User.find(params[:user_id])\n @photo = @user.photos.find(params[:id])\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to user_photos_url(user) }\n format.json { head :ok }\n end\n end",
"def destroy\n @user_import_file.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_import_files_url) }\n format.json { head :no_content }\n end\n end",
"def delete_user_with_request(user_id, request)\n start.uri('/api/user')\n .url_segment(user_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .delete()\n .go()\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
create grants array define a method to search for duplicates search for grant number in grants array
|
def grant_search(grants, grant_number)
# set up location = nil
return if grant_number == nil
duplicate_index = nil
# search grant hash in the array and if find the duplicate, then set up index # location
grants.each_with_index do |grant, i|
if grant[:grant_number] == grant_number
duplicate_index = i
break
end
end
duplicate_index
end
|
[
"def grants_sub_list\n users = GrantsData.has_grants.concat User.marked_complete_grants\n users = users.uniq\n subs = Array.new()\n users.each do |u|\n if User.is_charity(u)\n subs.push(u)\n end\n end\n session[:grants_sub] = subs.count()\n subs\nend",
"def assigned_investors(sale_rep)\n assigned_accounts = []\n @hash_row_array.each do |hash|\n if hash[\"SALES_REP\"] == sale_rep\n if assigned_accounts.include?(hash[\"INVESTOR\"]) == false\n assigned_accounts << hash[\"INVESTOR\"]\n end\n end\n end\n return assigned_accounts\nend",
"def ==(grants)\n size == grants.size && all? {|grant| grants.include?(grant)}\n end",
"def get_grant_info\n # See https://help.nla.gov.au/trove/becoming-partner/for-content-partners/adding-NHMRC-ARC\n # - Funder: Upper case for consistency (in both Funder & PURL)\n # - Grant Num: Upper case for consistency (in both Grant Num & PURL)\n grant_info = []\t\t\t# Ordered list of unique funders & grant numbers\n gwarnings = []\t\t\t# List of warnings\n\n grant_info_rel = {}\t\t\t# Hash for dc.relation\n @dc[:relation].each{|s|\t\t# Format: URL_PREFIX/funder/grant_num\n s.strip.match(PURL_REGEX)\n if [$1, $2, $3].all?{|o| !o.to_s.empty?}\n funder, grant_num = $2.upcase, $3.upcase\n next unless process_grant(funder, grant_num, grant_info, gwarnings, \"dc.relation\", grant_info_rel)\n\n else\n gwarnings << \"dc.relation purl format\"\n end\n }\n\n grant_info_gn = {}\t\t\t# Hash for dc.relation.grantnumber\n @dc[:grantnumber].each{|s|\t\t# Format: funder/grant_num\n s.strip.match(FUNDER_GRANTNUM_REGEX)\n if [$1, $2].all?{|o| !o.to_s.empty?}\n funder, grant_num = $1.upcase, $2.upcase\n next unless process_grant(funder, grant_num, grant_info, gwarnings, \"dc.relation.grantnumber\", grant_info_gn, grant_info_rel)\n\n else\n gwarnings << \"dc.relation.grantnumber format\"\n end\n }\n\n gwarnings << \"dc.relation/dc.relation.grantnumber grants differ\" unless grant_info_rel == grant_info_gn\n [gwarnings, grant_info]\n end",
"def grants_individual\n @users = Array.new()\n User.all.each do |u|\n if !u.admin?\n @users.push(u)\n end\n end\n end",
"def uniq_array(some_array)\n new_array = []\n puts '#############################################################'\n puts 'SCRIPT USING: .include? METHOD TO FIND UNIQUE NUMBERS IN ARRAY' \n puts 'TESTING ARRAY: ' + some_array.inspect\n puts '#############################################################'\n puts \n puts 'Logging results of loop: '\n\n some_array.each do |a|\n if ! new_array.include?(a)\n new_array.push(a)\n puts \"Pushed \" + a.to_s + \" into output array:\" + new_array.inspect\n else\n new_array\n puts a.to_s + \" is duplicate data.\"\n end #END IF BLOCK\n end #END LOOP\n puts\n puts '######################################################################'\n puts \"FINAL OUTPUT: ALL UNIQUE NUMBERS PUT INTO A NEW ARRAY \" + new_array.inspect.chomp\n puts '######################################################################'\nend",
"def assignments_that_should_have_found_email(hits)\n found_schools = {}\n bad_assignments = Set.new\n\n hits.each do |id, hit|\n if found_schools[\"#{hit[:school]} #{hit[:region]}\"].nil? && hit[:found_teacher] == 'yes'\n found_schools[\"#{hit[:school]} #{hit[:region]}\"] = true\n end\n end\n\n hits.each do |id, hit|\n if found_schools[\"#{hit[:school]} #{hit[:region]}\"] && hit[:found_teacher] == 'no'\n bad_assignments << id\n end\n end\n\n bad_assignments\nend",
"def duplicates_in_set(*grain_values)\n # ensure that the input is a flattened array\n ids = [*grain_values].flatten.uniq\n\n # make a hash of grains to model instances with\n # the corresponding grain\n grains_to_rows = model.where(grain => ids)\n .order(grain)\n .select(:id, grain)\n .to_a\n .group_by(&grain)\n\n # convert the values to the ids of duplicates,\n # excluding one corresponding to each grain\n grains_to_dups = grains_to_rows.update(grains_to_rows) do |k,v1,v2|\n v2 = v1.map(&:id).sort[1..-1]\n end\n\n # return just the unique id values, flattened into a single array\n grains_to_dups.values.flatten.uniq\n end",
"def my_hash_finding_method(hash, number)\n new_array = []\n hash.each do |name, age|\n if (age == number)\n new_array.push(name)\n end\n end\n new_array\nend",
"def grant_records\n GrantRecord.where(\"grantmaker_id = #{self.id}\")\n end",
"def accountability_groups(name_array, min_members)\n name_array = name_array.clone\n num_groups = name_array.length/min_members\n group_counter = 0\n group_array = Array.new(num_groups) { [] }\n\n while name_array.length > 0\n\ngroup_array[group_counter].push(name_array.delete_at(rand(0...name_array.length)))\n if group_counter == num_groups - 1\n group_counter = 0\n else\n group_counter += 1\n end\n end\n\n return group_array\n\nend",
"def add_redundancy(pw_data)\n entries = 8000 + SecureRandom.random_number(4000)\n position = SecureRandom.random_number(entries)\n \n ret = entries.times.map{ # or whatever... just create noise ;)\n { SecureRandom.uuid.chars.to_a.shuffle.join => SecureRandom.uuid.chars.to_a.shuffle.join }\n }\n ret[position] = pw_data\n ret << position\n \n ret\n end",
"def count_grant_entries\n session[:grants_number] = GrantsData.where(userID: current_user.id).count\nend",
"def grants=(_arg0); end",
"def find_dup(arr)\n occurances = arr.each_with_object(Hash.new(0)) { |el, hsh| hsh[el] += 1 }\n duplicate = occurances.select { |_, value| value == 2 }\n duplicate.key(2)\nend",
"def process_queries(queries, m)\n arr = []\n perm = *(1..m)\n i = 0\n while i < queries.length\n if perm.include?(queries[i])\n index = perm.find_index(queries[i])\n arr += [index]\n deleted = perm.delete_at(index)\n perm.unshift(deleted)\n end\n i+=1\n end\n\n return arr\nend",
"def find_duplicates(a)\n len=a.length\n n=len-2\n xor= 0\n x,y=0,0 #variables to store duplicates\n \n #xor of all numbers from 1 to n\n for i in 1..n \n xor^=i\n end\n #xor of all array elements\n for i in 0...len \n xor^=a[i]\n end\n #Rightmost set bit\n set_bit_pos= xor & ~(xor-1)\n #Divinding array in two sets ,one with set bit at set_bit_pos and other with 0.\n for i in 0...len\n if (a[i] & set_bit_pos == 0)\n x^=a[i] # XOR of first-set(with 0 at set_bit_pos) in array\n else\n y^=a[i] # XOR of second-set(with 1 at set_bit_pos) in array\n end\n end\n \n for i in 0..n\n if (i & set_bit_pos == 0)\n x^=i # XOR of first-set(with 0 at set_bit_pos) in range\n else\n y^=i # XOR of second-set(with 1 at set_bit_pos) in range\n end\n end\n print \"#{x} #{y}\"\n\treturn\nend",
"def grants_to_apply\n sort(requested_with_admin_flag - existing_with_admin_flag)\n end",
"def find_duplicates_4(a)\n len = a.length\n n = len-2\n xor = 0\n x,y = 0,0 #variables to store duplicates\n\n #xor of all numbers from 1 to n\n for i in 1..n\n xor ^= i\n end\n #xor of all array elements\n for i in 0...len\n xor ^= a[i]\n end\n #Rightmost set bit\n set_bit_pos = xor & ~(xor-1)\n #Divinding array in two sets ,one with set bit at set_bit_pos and other with 0.\n for i in 0...len\n if (a[i] & set_bit_pos == 0)\n x ^= a[i] # XOR of first-set(with 0 at set_bit_pos) in array\n else\n y ^= a[i] # XOR of second-set(with 1 at set_bit_pos) in array\n end\n end\n\n for i in 0..n\n if (i & set_bit_pos == 0)\n x ^= i # XOR of first-set(with 0 at set_bit_pos) in range\n else\n y ^= i # XOR of second-set(with 1 at set_bit_pos) in range\n end\n end\n print \"#{x} #{y}\"\n return\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /helps/1 GET /helps/1.json
|
def show
@help = Help.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @help }
end
end
|
[
"def show\n @helptext = Helptext.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @helptext }\n end\n end",
"def show\n @shelter = Shelter.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @shelter }\n end\n end",
"def index\n @helps = Help.all\n end",
"def show\n render json: MangaBookshelf.find_shelves(params[:id])\n end",
"def index\n @helptexts = Helptext.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @helptexts }\n end\n end",
"def show\n @helloworld = Helloworld.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @helloworld }\n end\n end",
"def index\n @need_helps = NeedHelp.find_all_by_gid(params[:gid])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @need_helps }\n end\n end",
"def show\n @need_help = NeedHelp.find(params[:id])\n\n respond_to do |format|\n format.json {render json: @need_help}\n end\n end",
"def show\n @need_help = NeedHelp.find(params[:id])\n\n respond_to do |format|\n format.json { render json: @need_help }\n end\n end",
"def index\n @hellows = Hellow.all\n end",
"def helps(id)\n helps_data(request(\"needs/helps/#{id}.xml\", :auth => true))\n end",
"def index\n @shelters = Shelter.all\n @shelters = Shelter.paginate(:page => params[:page], :per_page =>10)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @shelters }\n end\n end",
"def index\n @snippet = Snippet.find_by_slug(params[:id])\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @snippets }\n end\n end",
"def new\n @shelter = Shelter.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @shelter }\n end\n end",
"def index\n @admin_helps = Admin::Help.all\n end",
"def show\r\n @help_item = HelpItem.find(params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @help_item }\r\n end\r\n end",
"def show\n render json: @shelter\n end",
"def show\n @h1 = H1.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @h1 }\n end\n end",
"def show\n @helpfullink = Helpfullink.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @helpfullink }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /helps/new GET /helps/new.json
|
def new
@help = Help.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @help }
end
end
|
[
"def new\n @shelter = Shelter.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @shelter }\n end\n end",
"def new\n @what = What.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @what }\n end\n end",
"def new\n @helptext = Helptext.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @helptext }\n end\n end",
"def new\n @new_recipe = NewRecipe.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @new_recipe }\n end\n end",
"def new\n\tputs \"new\"\n @resource = Resource.new\n\n respond_to do |format|\n format.json { render json: @resource }\n#\t format.html { render html: @resources }\n end\n end",
"def new\n @thing = Thing.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @thing }\n end\n end",
"def new\n @how = How.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @how }\n end\n end",
"def new\n @things_to_do = ThingsToDo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @things_to_do }\n end\n end",
"def new_stories\n get('/newstories.json')\n end",
"def new\n @helloworld = Helloworld.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @helloworld }\n end\n end",
"def new\n @new_item = NewItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @new_item }\n end\n end",
"def new\n @thing = Thing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @thing }\n end\n end",
"def new\n @need_help = NeedHelp.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @need_help }\n end\n end",
"def new\n @todo_topic = TodoTopic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @todo_topic }\n end\n end",
"def new\n @would = Would.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @would }\n end\n end",
"def new\n @snippet = Snippet.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @snippet }\n end\n end",
"def new\n @spec = Spec.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @spec }\n end\n end",
"def new\n @snippet = Snippet.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @snippet }\n end\n end",
"def new\n @todo = Todo.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @todo }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Takes a cache method, and expiry predicate fn and a on_miss fn and returns the value of the cache_method
|
def read(cache_method, expired_fn: self.class.default_expired_fn, on_miss: F.identity)
if cache.send(cache_method) && !expired_fn.(cache, cache_method) #not_expired?(cache_method)
log_cache_hit
get(cache_method)
else
log_cache_failure
write(cache_method, on_miss.(get(cache_method)))
end
end
|
[
"def caching_method(method) \n returning send(\"_queued_method_#{method}\") do |results|\n Rails.cache.write queued_method_key(method), results\n Rails.cache.delete queued_method_queued_key(method)\n end\n end",
"def cached_call func, ttl, *params\n \n #\n cache_key = Cache.key_for_method func, params\n \n #check if result for this call is in cache \n cache = @redis.get(cache_key)\n if cache \n $logger.info \"return cached result with key : #{cache_key}\"\n return cache \n end\n \n #store the result with the key\n $logger.info \"cached call with key : #{cache_key}\"\n result = func.call(*params)\n if ttl\n @redis.set(cache_key, result.to_s, {:ex => ttl})\n else\n @redis.set(cache_key, result.to_s)\n end\n \n return result\n end",
"def cache_method(method_name, options = {})\n options = DEFAULT_OPTIONS.merge(options || {})\n cache_module = const_get(\"#{self.name}Cache\")\n cache_key_method = options[:cache_key] || options[\"cache_key\"]\n cache_module.class_eval do\n define_method(method_name) do\n key = \"#{self.class.name}/#{method_name}/#{self.send(cache_key_method)}\"\n cached_value_for(key, ->{super()})\n end\n end\n end",
"def signature_value(method,signature,value=:_get_)\n if value == :_get_\n # if expired, it'll return nil\n [method,signature,:value].inject(cache_data,:fetch) if signature_expiration(method, signature) > DateTime.now\n else\n [method,signature].inject(cache_data,:fetch)[:value] = value\n end\n end",
"def get_method_cache(method)\n mc = cache_data[method]\n mc.merge! reads: 0, writes:0 if mc.empty?\n mc\n end",
"def fetch(key, opts={}, &blk)\n expires_in = opts[:expires_in] || DEFAULT_EXPIRATION\n race_ttl = opts[:race_condition_ttl] || DEFAULT_RACE_TTL\n retries = opts[:max_retries] || MAX_RETRIES\n\n now = Time.now.to_i\n ttl = expires_in + retries * race_ttl\n t_key = timer(key)\n\n if val = redis.get(key) # cache hit\n if redis.get(t_key).to_i < now # expired entry or dne\n redis.set t_key, now + race_ttl # block other callers for recalc duration\n begin\n Timeout.timeout(race_ttl) do # if recalc exceeds race_ttl, abort\n val = Marshal.dump(blk.call) # determine new value\n redis.multi do # atomically cache + mark as valid\n redis.setex key, ttl, val\n redis.set t_key, now + expires_in\n end\n end\n rescue Timeout::Error => e # eval timed out, use cached val\n end\n end\n else # cache miss\n val = Marshal.dump(blk.call) # determine new value\n redis.multi do # atomically cache + mark as valid\n redis.setex key, ttl, val\n redis.set t_key, now + expires_in\n end\n end\n\n Marshal.load(val)\n end",
"def queued_method(method, options = {})\n caching_key = queued_method_key method\n Rails.cache.delete(caching_key) if options[:force]\n data = queued_method_data(method) \n if queued_method_expired?(data)\n puts \"expired #{Time.now} : #{data.inspect}\"\n if options[:fallback]\n data = {:results => send(options[:fallback])}\n queued_method_queue(method)\n else\n data = caching_method(method)\n end\n else\n queued_method_queue(method) if queued_method_stale?(data)\n end\n \n data[:results]\n end",
"def call_with_cache(method, args)\n if opts = self.class.handler_opts[method][:cache]\n begin\n # If there are uncacheable parameters, abort and just call the method.\n raise unless (request.params.keys - self.class::KEYS - opts[:keys]).empty?\n\n # Compute cache key for this method, args, and params.\n args_key = args.map { |a| escape a }.join(\"&\")\n \n opts_key = opts[:keys].map { |k|\n escape request.params[k]\n }.join(\"&\")\n\n format_key = request.path[/\\.(\\w+)$/, 1]\n \n if opts[:proc]\n result = opts[:proc].call(\n :method => method,\n :args => args,\n :request => request,\n :format => format_key,\n :client => @client\n )\n if result\n proc_key = escape result\n else\n # Don't cache.\n raise\n end\n else\n proc_key = ''\n end\n \n key = \"#{self.class}/#{method}/#{args_key}/#{opts_key}/#{proc_key}/#{format_key}\"\n\n # Check the cache and attempt to respond immediately.\n if value = API.cache[key]\n Ramaze::Log.info \"Cache hit\"\n response['Content-Type'] = CONTENT_TYPES[format_key]\n return value\n end\n\n # Nope? Invoke the method and cache the result.\n value = format(send(method, *args))\n\n API.cache.store key, value, :ttl => opts[:ttl]\n rescue => e\n # Under no circumstances are we to cache something weird, like a file.\n # If that were to happen, we'd hit an error in escape().\n format(send(method, *args))\n end\n else\n format(send(method, *args))\n end\n end",
"def call\n case cache_operation\n when :fetch\n MethodCacheable.store.fetch(key, options) do\n send_to_caller\n end\n when :read\n read(method, args)\n when :write\n write(method, args) do\n send_to_caller\n end\n end\n end",
"def cache_method(*methods)\n options = methods.extract_options!\n methods.each do |method|\n define_cache_method method, options\n end\n end",
"def cache_fetcher; end",
"def define_cachedp_method\n # we don't expect this to be called more than once, but we're being\n # defensive.\n return if defined?(cached?)\n\n if defined?(::ActiveRecord) && ::ActiveRecord::VERSION::STRING >= '5.1.0'\n def cached?(payload)\n payload.fetch(:cached, false)\n end\n else\n def cached?(payload)\n payload[:name] == CACHED_QUERY_NAME\n end\n end\n end",
"def call\n if @cache.nil? || Time.now - @last_fetch > CACHE_EXPIRY\n @cache = fetch_conditions\n end\n @cache\n end",
"def cache_methods(*method_names, expires_in:)\n method_names.each do |method_name|\n cache_method(method_name, expires_in: expires_in)\n end\n end",
"def expire_cache!(key)\n raise 'The expire_cache method must be implemented'\n end",
"def singleton_add_cached_method(method_name)\n self.singleton_methods_to_be_cached.delete(method_name)\n self.singleton_cached_methods <<= method_name\n class_eval <<-END_EVAL, __FILE__, __LINE__ + 1\n class <<self\n alias :uncached_#{method_name} :#{method_name}\n def #{method_name}(*args)\n MethodCacher.config.caching_strategy.fetch(singleton_cached_method_key(:#{method_name}, *args)) { uncached_#{method_name}(*args) }\n end\n\n def clear_cache_for_#{method_name}(*args)\n MethodCacher.config.caching_strategy.delete(singleton_cached_method_key(:#{method_name}, *args))\n end\n end\n END_EVAL\n end",
"def method_missing(name, *params)\n\t\t\t@cache.respond_to?(name) ? @cache.method(name).(*params) : super\n\t\tend",
"def cache_if!(condition, *args, &block); end",
"def memoize_method(method)\n visibility = method_visibility(method)\n define_memoize_method(method)\n send(visibility, method)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Look up the generator class. Require its class file, find the class in ObjectSpace, tag it with this spec, and return.
|
def klass
unless @klass
require class_file
@klass = lookup_class
@klass.spec = self
end
@klass
end
|
[
"def lookup_class\r\n ObjectSpace.each_object(Class) do |obj|\r\n return obj if obj.ancestors.include?(Rails::Generator::Base) and\r\n obj.name.split('::').last == class_name\r\n end\r\n raise NameError, \"Missing #{class_name} class in #{class_file}\"\r\n end",
"def lookup_class\n ObjectSpace.each_object(Class) do |obj|\n return obj if obj.ancestors.include?(Rails::Generator::Base) and\n obj.name.split('::').last == class_name\n end\n raise NameError, \"Missing #{class_name} class in #{class_file}\"\n end",
"def generator_classes\n classes = Hash.new { |h,k| h[k] = [] }\n class_re = /([^:]+)Generator$/\n ObjectSpace.each_object(Class) do |object|\n if md = class_re.match(object.name) and object < Rails::Generator::Base\n classes[Inflector.underscore(md.captures.first)] << object\n end\n end\n classes\n end",
"def generate_class(yard_class)\n debug_msg(yard_class.path.to_s)\n\n meths = yard_class.meths(:included=>false, :inherited=>false)\n\n if yard_class.type == :class\n model = Model::Class.new\n model.superclass = yard_class.superclass ? yard_class.superclass.path : 'Object'\n else \n model = Model::Module.new\n end\n\n model.path = yard_class.path\n model.name = yard_class.name.to_s\n model.namespace = yard_class.namespace.path #full_name.split('::')[0...-1].join('::'),\n model.comment = yard_class.docstring.to_s\n model.format = 'rdoc' #TODO: how to determine? rdoc, markdown or plaintext ?\n model.constants = yard_class.constants.map{ |x| x.path } #TODO: complete_name(x.name, c.full_name) }\n model.includes = yard_class.instance_mixins.map{ |x| x.path }\n model.extensions = yard_class.class_mixins.map{ |x| x.path }\n model.modules = yard_class.children.select{ |x| x.type == :module }.map{ |x| x.path }\n #yard_class.modules.map{ |x| complete_name(x.name, c.full_name) }\n model.classes = yard_class.children.select{ |x| x.type == :class }.map{ |x| x.path }\n #yard_class.classes.map{ |x| complete_name(x.name, c.full_name) }\n\n model.methods = meths.select.map{ |m| m.path }\n #model.methods = meths.select{ |m| m.scope == :instance }.map{ |m| m.path }\n #model.class_methods = meths.select{ |m| m.scope == :class }.map{ |m| m.path }\n\n model.accessors = yard_class.attributes[:class].map{ |k, rw| yard_class.path + '.' + k.to_s } +\n yard_class.attributes[:instance].map{ |k, rw| yard_class.path + '#' + k.to_s }\n #model.class_accessors = yard_class.attributes[:class].map{ |k, rw| yard_class.path + '.' + k.to_s }\n\n model.files = yard_class.files.map{ |f, l| \"/#{f}\" } # :#{l}\" }\n\n model.tags = translate_tags(yard_class)\n\n #@files.concat(yard_class.files.map{ |f, l| f })\n\n @table[model.path] = model.to_h\n end",
"def generator_for(generator_name, opts={})\n opts[:target_project] = self\n return SC::Generator.load(generator_name, opts)\n end",
"def generate_class(rdoc_class)\n debug_msg \" %s\" % [ rdoc_class.full_name ]\n\n if rdoc_class.type=='class'\n model = Shomen::Model::Class.new\n else\n model = Shomen::Model::Module.new\n end\n\n modules = (rdoc_class.modules_hash || {}).values\n classes = (rdoc_class.classes_hash || {}).values\n\n model.path = rdoc_class.full_name\n model.name = rdoc_class.name\n model.namespace = rdoc_class.full_name.split('::')[0...-1].join('::')\n model.includes = rdoc_class.includes.map{ |x| x.name } # FIXME: How to \"lookup\" full name?\n model.extensions = [] # TODO: How to get extension modules?\n model.comment = comment(rdoc_class.comment)\n model.format = 'rdoc' # or tomdoc ?\n model.constants = rdoc_class.constants.map{ |x| complete_name(x.name, rdoc_class.full_name) }\n\n model.modules = modules.map{ |x| complete_name(x.name, rdoc_class.full_name) }\n model.classes = classes.map{ |x| complete_name(x.name, rdoc_class.full_name) }\n\n model.methods = rdoc_class.method_list.map{ |m| method_name(m) }.uniq\n model.accessors = rdoc_class.attributes.map{ |a| method_name(a) }.uniq #+ \":#{a.rw}\" }.uniq\n\n model.files = (rdoc_class.in_files || []).map{ |x| \"/#{x.full_name}\" }\n\n if rdoc_class.file\n model.files.unshift(\"/#{rdoc_class.file.full_name}\")\n end\n\n if rdoc_class.type == 'class'\n # HACK: No idea why RDoc is returning some weird superclass:\n # <RDoc::NormalClass:0xd924d4 class Object < BasicObject includes: []\n # attributes: [] methods: [#<RDoc::AnyMethod:0xd92b8c Object#fileutils\n # (public)>] aliases: []>\n # Maybe it has something to do with #fileutils?\n model.superclass = (\n case rdoc_class.superclass\n when nil\n when String\n rdoc_class.superclass\n else\n rdoc_class.superclass.full_name\n end\n )\n end\n\n @table[model.path] = model.to_h\n end",
"def create_instance type, options=nil\n class_name = \"#{type.to_s.camel_case}Generator\"\n registered_entities.each do |entity|\n if(entity.to_s.match(/::#{class_name}$/) || entity.to_s.match(/^#{class_name}$/))\n return entity.new\n end\n end\n raise Sprout::Errors::MissingGeneratorError.new \"Could not find any generator named: (#{class_name}). Perhaps you need to add a RubyGem to your Gemfile?\"\n end",
"def classSetup\n doc = {}\n Ops.set(doc, \"listEntries\", { \"classes\" => \"class\" })\n Ops.set(doc, \"rootElement\", \"autoinstall\")\n # doc[\"systemID\"] = \"/usr/share/autoinstall/dtd/classes.dtd\";\n Ops.set(doc, \"nameSpace\", \"http://www.suse.com/1.0/yast2ns\")\n Ops.set(doc, \"typeNamespace\", \"http://www.suse.com/1.0/configns\")\n XML.xmlCreateDoc(:class, doc)\n nil\n end",
"def assert_generated_class(path, parent = nil, class_name = class_name_from_path(path))\n assert_generated_file(\"#{path}.rb\") do |body|\n assert_match /class #{class_name}#{parent.nil? ? '':\" < #{parent}\"}/, body, \"the file '#{path}.rb' should be a class\"\n yield body if block_given?\n end\n end",
"def lookup_class(arg = nil)\n arg ? @lookup_class = arg : @lookup_class ||= VerbSegments\n end",
"def find_class_in_object_space(klass)\n if NewRelic::LanguageSupport.object_space_usable?\n ObjectSpace.each_object(klass) do |x|\n return x\n end\n end\n return nil\n end",
"def query_class\n\t\treturn self.client.sys.registry.query_class(self.hkey)\n\tend",
"def assert_generated_class(path,parent=nil)\n path=~/\\/?(\\d+_)?(\\w+)$/\n class_name=$2.camelize\n assert_generated_file(\"#{path}.rb\") do |body|\n assert body=~/class #{class_name}#{parent.nil? ? '':\" < #{parent}\"}/,\"the file '#{path}.rb' should be a class\"\n yield body if block_given?\n end\n end",
"def class_def(klass_path, opts ={})\n # if :types => true then we get the types\n args = []\n args << 'gc'\n args << '-t' if opts[:types]\n args << \"#{klass_path}\"\n out = run_wbem_cli(*args)\n raise \"Bad response\" if out.empty?\n # this stupid response does not have the dot between the class\n # name, so lets build it\n cn, path = out.chomp.split(\" \")\n props = fields(\"#{path}\")\n end",
"def building_class\n self.dig_for_string(\"buildingClass\")\n end",
"def generate_custom_classes\r\n\t\t# TODO: this method assumes an application to find the metadata on; the metadata should be part of this class instance instead, shared with the app when present\r\n\t\tparent_class_name = {\r\n\t\t\t'CustomMaterial' => 'MaterialBase',\r\n\t\t\t'Effect' => 'Effect',\r\n\t\t\t'Behavior' => 'Behavior',\r\n\t\t\t'RenderPlugin' => 'RenderPlugin'\r\n\t\t}\r\n\t\t@class_by_ref = {}\r\n\t\t@doc.xpath('/UIP/Project/Classes/*').each do |reference|\r\n\t\t\tpath = absolute_path( reference['sourcepath'] )\r\n\t\t\tnext unless File.exist?( path )\r\n\t\t\tparent_class = app.metadata.by_name[ parent_class_name[reference.name] ]\r\n\t\t\traise \"Error, unsupported custom class #{reference.name}\" unless parent_class\r\n\t\t\tparent_props = parent_class.properties\r\n\t\t\tnew_defaults = Hash[ reference.attributes.map{ |name,attr| [name,attr.value] }.select{ |name,val| parent_props[name] } ]\r\n\t\t\tproperty_el = case reference.name\r\n\t\t\t\twhen 'CustomMaterial', 'Effect', 'RenderPlugin'\r\n\t\t\t\t\tdoc = Nokogiri.XML(File.read(path,encoding:'utf-8'))\r\n\t\t\t\t\tdoc.at('/*/MetaData') || doc.at('/*/metadata') # Some render plugins in the wild use lower-case tag name :/\r\n\t\t\t\twhen 'Behavior'\r\n\t\t\t\t\tlua = File.read(path,encoding:'utf-8')\r\n\t\t\t\t\tmeta = lua[ /--\\[\\[(.+?)(?:--)?\\]\\]/m, 1 ]\r\n\t\t\t\t\tNokogiri.XML(\"<MetaData>#{meta}</MetaData>\").root\r\n\t\t\tend\r\n\t\t\t@class_by_ref[ \"##{reference['id']}\" ] = app.metadata.create_class( property_el, parent_class, reference.name, new_defaults )\r\n\t\tend\r\n\t\tnil\r\n\tend",
"def class_name\n assert_exists\n return @o.invoke(\"className\")\n end",
"def generator(target = Rails)\n generator = Generator.build(self, target)\n end",
"def get_class\n @class ||= Class.new\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Search for the first Class descending from Rails::Generator::Base whose name matches the requested class name.
|
def lookup_class
ObjectSpace.each_object(Class) do |obj|
return obj if obj.ancestors.include?(Rails::Generator::Base) and
obj.name.split('::').last == class_name
end
raise NameError, "Missing #{class_name} class in #{class_file}"
end
|
[
"def lookup_class\n ObjectSpace.each_object(Class) do |obj|\n return obj if obj.ancestors.include?(Rails::Generator::Base) and\n obj.name.split('::').last == class_name\n end\n raise NameError, \"Missing #{class_name} class in #{class_file}\"\n end",
"def find_class_named(name)\n return self if full_name == name\n @classes.each_value {|c| return c if c.find_class_named(name) }\n nil\n end",
"def find_class_named_from name, from\n from = find_class_named from unless RDoc::Context === from\n\n until RDoc::TopLevel === from do\n return nil unless from\n\n klass = from.find_class_named name\n return klass if klass\n\n from = from.parent\n end\n\n find_class_named name\n end",
"def searchable_classname(klass)\n # climb hierarchy until we find the class that includes Searchable\n # this will return the top-level class if it doesn't, but that shouldn't be a problem\n while Info[klass.name.to_sym].nil?\n break if klass.superclass.nil?\n klass = klass.superclass\n end\n klass.name.to_sym\n end",
"def find_by_class(name)\n return unless Throttled.configuration.inherit_strategies?\n\n const = name.is_a?(Class) ? name : constantize(name)\n return unless const.is_a?(Class)\n\n const.ancestors.each do |m|\n strategy = find(m.name)\n return strategy if strategy\n end\n\n nil\n end",
"def findExactClassMatch(name)\n fname = name.tr(':', '_')\n return ClassIndex.classExists?(fname)\n end",
"def class_by_name name\n # http://stackoverflow.com/questions/14070369/how-to-instantiate-class-from-name-string-in-rails\n Object.const_get name.to_s\n\n end",
"def findClassesThatMatch(name)\n fname = name.tr(':', '_')\n return ClassIndex.findClasses(fname)\n end",
"def search_class\n klass = if args[1]\n target.eval(args[1])\n else\n target_self\n end\n\n klass.is_a?(Module) ? klass : klass.class\n end",
"def pick_class(name, list)\n list.find { |klass| klass.basename == name }\n end",
"def get_class(name)\n name.split(/::/).inject(Object) { |p, n| p.const_get(n) } \n end",
"def get_class_by_name!(name , super_class = :Object)\n c = get_class_by_name(name)\n return c if c\n create_class( name ,super_class)\n end",
"def pick_class(name, list)\n\t\tlist.find { |klass| klass.basename == name }\n\tend",
"def find_finder_class_for(record) #:nodoc:\n class_hierarchy = [record.class]\n\n while class_hierarchy.first != @klass\n class_hierarchy.insert(0, class_hierarchy.first.superclass)\n end\n\n class_hierarchy.detect { |klass| !klass.abstract_class? }\n end",
"def get_class_by_name( name )\n raise \"get_class_by_name #{name}.#{name.class}\" unless name.is_a?(Symbol)\n c = classes[name]\n #puts \"MISS, no class #{name} #{name.class}\" unless c # \" #{classes}\"\n #puts \"CLAZZ, #{name} #{c.get_type.get_length}\" if c\n c\n end",
"def get_class_by_name( name )\n raise \"get_class_by_name #{name}.#{name.class}\" unless name.is_a?(Symbol)\n c = self.classes[name]\n #puts \"MISS, no class #{name} #{name.class}\" unless c # \" #{self.classes}\"\n #puts \"CLAZZ, #{name} #{c.get_type.get_length}\" if c\n c\n end",
"def lookup_task_klass(klass_name)\n if Object.const_defined?(klass_name)\n klass_name.constantize\n else\n Task.descendants.find do |descendant|\n descendant.name.demodulize == klass_name\n end\n end\n end",
"def get_class_by_name! name\n c = get_class_by_name(name)\n return c if c\n create_class name , get_class_by_name(:Object)\n end",
"def klass_for(name)\n @match_sets ? @match_sets[name] : nil\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return the watch for the object, or a new watch if none found. The new watch should be active if the object is new, correspoding to the watch being on by default when the user creates a new CI or Outage.
|
def watched_by_or_new(user)
watched_by(user) || watches.build(user: user, active: !persisted?)
end
|
[
"def watching\n @watching ||= ApiFactory.new 'Repos::Watching'\n end",
"def watching\n @watching ||= ApiFactory.new 'Activity::Watching'\n end",
"def watcher(name)\n watchers.find { |watcher| watcher.name == name }\n end",
"def watching?(object)\n interest_in(object) == :watching\n end",
"def watchlist\n super || self.create_watchlist\n end",
"def is_watchable?\n true\n end",
"def create_watching\n @watching = Watching.add_watcher(owner, event.lesson)\n end",
"def watch\n start_watch\n end",
"def make_watchable\n include Watchable\n end",
"def watching?\n @watcher && @watcher.alive? ? true : false\n end",
"def watch!\n start_watch true\n end",
"def watches?(watchable)\n check_watchable(watchable)\n\n fetch_watching(watchable) ? true : false\n end",
"def watch_method; end",
"def watch_change?\n !!@watch_change\n end",
"def [](watchlist_id)\n all.detect do |watchlist|\n watchlist.id == watchlist_id\n end\n end",
"def watching=(name)\n gateway_check\n update_status(@status, name, nil, nil, nil, 3)\n end",
"def watchers; end",
"def toggle_watch\n @watch_list = @ads_user.watch_lists.where(:model_id => params[:model_id], :model_type => params[:model_type]).first\n if @watch_list.nil? then\n #not in list, add to list\n @watch_list = @ads_user.watch_lists.new(:model_id => params[:model_id], :model_type => params[:model_type], :active => true)\n @watch_list.save!\n else\n #in the list, check if \n @watch_list.update_attribute(:active, !@watch_list.active)\n end\n end",
"def retrieve_watcher(user, repo, watcher)\n repo_bound_item(user, repo, watcher, :watchers,\n [\"repos/#{user}/#{repo}/stargazers\"],\n {'repo' => repo, 'owner' => user},\n 'login', order = :desc)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /active_stats/new GET /active_stats/new.json
|
def new
@active_stat = ActiveStat.new
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @active_stat }
end
end
|
[
"def new\n @stat = Stat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stat }\n end\n end",
"def new\n @stat = Stat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @stat }\n end\n end",
"def new\n @new_status = NewStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @new_status }\n end\n end",
"def create\n @active_stat = ActiveStat.new(params[:active_stat])\n\n respond_to do |format|\n if @active_stat.save\n format.html { redirect_to @active_stat, :notice => 'Active stat was successfully created.' }\n format.json { render :json => @active_stat, :status => :created, :location => @active_stat }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @active_stat.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @statistic = Statistic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @statistic }\n end\n end",
"def new\n @stat_misc = StatMisc.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stat_misc }\n end\n end",
"def new\n @task_stat = TaskStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task_stat }\n end\n end",
"def new\n @current_stat = CurrentStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @current_stat }\n end\n end",
"def new\n @stat_value = StatValue.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stat_value }\n end\n end",
"def new\n @httpstatus = Httpstatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @httpstatus }\n end\n end",
"def new\n @match_stat = MatchStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @match_stat }\n end\n end",
"def new\n @annual_stat = AnnualStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @annual_stat }\n end\n end",
"def new\n @email_stat = EmailStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @email_stat }\n end\n end",
"def new\n @group_stat = GroupStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @group_stat }\n end\n end",
"def new\n @smalltrialstatus = Smalltrialstatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @smalltrialstatus }\n end\n end",
"def new\n @file_stat = FileStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @file_stat }\n end\n end",
"def new\n @weekly_stat = WeeklyStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @weekly_stat }\n end\n end",
"def new\n @rushing_stat = RushingStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @rushing_stat }\n end\n end",
"def new\n @statistic_type = StatisticType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @statistic_type }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /active_stats POST /active_stats.json
|
def create
@active_stat = ActiveStat.new(params[:active_stat])
respond_to do |format|
if @active_stat.save
format.html { redirect_to @active_stat, :notice => 'Active stat was successfully created.' }
format.json { render :json => @active_stat, :status => :created, :location => @active_stat }
else
format.html { render :action => "new" }
format.json { render :json => @active_stat.errors, :status => :unprocessable_entity }
end
end
end
|
[
"def stats\n get 'stats', format: 'json'\n end",
"def send_stats\n first_time = @prev_stat.empty?\n stats = build_request\n @stat.keys.each { |k| stats[k] = @stat[k] - @prev_stat[k] }\n @prev_stat.replace(@stat)\n # These should be reported as absolute values\n [:mt, :ma, :mc].each {|k| @prev_stat[k] = 0}\n return if first_time\n\n req = Net::HTTP::Post.new('/')\n req.set_form_data(stats)\n res = Net::HTTP.start(API, use_ssl: true) { |http| http.request(req) }\n unless res.is_a?(Net::HTTPOK)\n STDERR.puts \"Error sending stat: #{res.message}\"\n end\n res\n end",
"def stats\n request :get, \"_stats\"\n end",
"def send_stats\n render json: { rate: user.success_rate_stats,\n stats: quiz.progress_stats,\n quizzes: user.total_quizzes_stats }\n end",
"def import_active_stats\n\n end",
"def stats\r\n StatsController.instance\r\n end",
"def service_stats\n\t\trequest_today = Property.where(created_at: Date.today).count\n\t\trequest_remaining = Property.where(processed: false).count\n\t\tlast_request = Property.last.created_at.to_i\n\t\trequests_yesterday = Property.where(created_at: Date.today-1.day).count\n\t\trequests_this_week = Property.where(created_at: Date.today..Date.today-7.days).count\n\t\trequests_last_week = Property.where(created_at: Date.today-7.days..Date.today-14.days).count\n\t\trequests_this_month = Property.where(created_at: Date.today..Date.today-30.days).count\n\t\trequests_last_month = Property.where(created_at: Date.today-30.days..Date.today-60.days).count\n\t\trender json: { status: 200, response: { request_today: request_today, request_remaining: request_remaining,\n\t\t\t\t\tlast_request: last_request, requests_yesterday: requests_yesterday, requests_this_week: requests_this_week,\n\t\t\t\t\trequests_last_week: requests_last_week, requests_this_month: requests_this_month, requests_last_month: requests_last_month }}\n\tend",
"def trips_stats \n @all = current_user.trip_requests.trips.count\n @completed = current_user.trip_requests.trips.completed.count\n @cancelled = current_user.trip_requests.trips.cancelled.count\n @pending = current_user.trip_requests.trips.pending.count\n @on_going = current_user.trip_requests.trips.on_going.count\n @active = current_user.trip_requests.trips.active.count\n @monthly_successful = current_user.trip_requests.completed.trips.group_by_month(:created_at, format: \"%b\", reverse:true).count\n @monthly_pending = current_user.trip_requests.pending.trips.group_by_month(:created_at, format: \"%b\", reverse:true).count\n @response = { all: @all, completed: @completed, cancelled: @cancelled, active: @active, monthly_pending:@monthly_pending, monthly_successful:@monthly_successful, pending: @pending, on_going: @on_going }\n json_response(@response)\n end",
"def new\n @active_stat = ActiveStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @active_stat }\n end\n end",
"def counts\n counts = Actuator.counts\n respond_to do |format|\n format.html { render json: counts}\n format.json { render json: counts}\n end\n end",
"def write_thread_stats\n request({req: 'writethreadstats'})\n end",
"def alert_status\n mets = metrics(params[:test]);\n mets.ensure_worker_running\n\n stats = mets.thread_safe_stats\n render json: stats.alert_status\n end",
"def stats\n @log.debug(\"Controller: Stats Called\")\n res = {\n :producers => producer_stats,\n :consumers => consumer_stats,\n :tasks => task_stats\n }\n end",
"def post_stats(server_count, shards: nil, shard_count: nil)\n jsonPost = {\n server_count: server_count,\n shards: shards,\n shard_count: shard_count\n }.to_json\n @conn.post(\"bots/#{@id}/stats\", jsonPost, { 'Content-Type' => 'application/json' })\n end",
"def report_count_of_action_sid_by_profile_accesses_json(opts={})\r\n @data[:elements] = []\r\n setup_count_of_action_sid_by_profile_accesses_x_axis_json\r\n\r\n report_serie_28_json(opts[:serie1] || {})\r\n\r\n setup_count_of_action_sid_by_profile_accesses_y_axis_json\r\n setup_style_of_count_of_action_sid_by_profile_accesses_json(opts)\r\n return @data\r\n end",
"def stats\n perform_get('/stats', Neows::Models::Stat)\n end",
"def health_after_rest\n stats[:health] + REST_ADD\n end",
"def write_db_stats\n @db_stats.write_request_summary\n @db_stats = nil # prevent reuse\n true\n end",
"def registerStats\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PUT /active_stats/1 PUT /active_stats/1.json
|
def update
@active_stat = ActiveStat.find(params[:id])
respond_to do |format|
if @active_stat.update_attributes(params[:active_stat])
format.html { redirect_to @active_stat, :notice => 'Active stat was successfully updated.' }
format.json { head :ok }
else
format.html { render :action => "edit" }
format.json { render :json => @active_stat.errors, :status => :unprocessable_entity }
end
end
end
|
[
"def update_statistics\n HTTP.post(\"/video/#{@id}/stats\")\n true\n end",
"def update\n @stat = Stat.find(params[:id])\n\n if @stat.update(stat_params)\n head :no_content\n else\n render json: @stat.errors, status: :unprocessable_entity\n end\n end",
"def update\n logger.debug(\"Update of #{params[:id]}\")\n use_count = application_user.use_counters.find_or_create_by_name(params[:name])\n use_count.count = params[:count].to_i\n if use_count.save\n render :json => 'done'\n else\n render :json => 'failed', :status => 500\n end\n end",
"def update\n @current_stat = CurrentStat.find(params[:id])\n\n respond_to do |format|\n if @current_stat.update_attributes(params[:current_stat])\n format.html { redirect_to(@current_stat, :notice => 'Current stat was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @current_stat.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @active_stat = ActiveStat.new(params[:active_stat])\n\n respond_to do |format|\n if @active_stat.save\n format.html { redirect_to @active_stat, :notice => 'Active stat was successfully created.' }\n format.json { render :json => @active_stat, :status => :created, :location => @active_stat }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @active_stat.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def stats\n get 'stats', format: 'json'\n end",
"def update_stats\n @profile = Profile.find(params[:id])\n @profile = @profile.from_json(params[:profile_object])\n\n\n respond_to do |format|\n if @profile.save #update_attributes(params[:profile])\n format.html { render :text => \"Stats saved\" }\n format.js { render :text => \"Stats saved\" }\n else\n format.html { render :text => \"Could not save stats\" }\n format.js { render :text => \"Could not save stats\" }\n end\n end\n end",
"def update\n @backend_stat = Backend::Stat.find(params[:id])\n\n respond_to do |format|\n if @backend_stat.update_attributes(params[:backend_stat])\n format.html { redirect_to @backend_stat, notice: 'Stat was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @backend_stat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_node_stats(node,age,kind)\n start_date = node.pub_date\n end_date = start_date + age.days\n\n stat = node.stats.find(:first, :conditions => ['period = ? AND kind = ?',age,kind]) || node.stats.new(:kind => kind)\n results = @profile.post_stats(:start_date => start_date, :end_date => end_date).by_node_path(node.path[0,120]).results\n\n bounces = 0 \n \n results.each do |r|\n stat.pageviews += r.pageviews.to_i\n stat.visits += r.visits.to_i\n stat.new_visits += r.newVisits.to_i\n stat.period = age\n bounces += r.bounces.to_i\n end\n\n if bounces == 0 \n stat.bounce_rate = 0 \n else\n stat.bounce_rate = bounces.to_f/stat.visits.to_f\n end\n\n if stat.new_visits == 0 \n stat.percent_new_visits = 0 \n else\n stat.percent_new_visits = stat.new_visits.to_f/stat.visits.to_f\n end\n\n stat.save\n return \"Updated #{age}-day views. (#{kind})\"\nend",
"def update\n @analytics_usage = AnalyticsUsage.find(params[:id])\n\n respond_to do |format|\n if @analytics_usage.update_attributes(params[:analytics_usage])\n format.html { redirect_to @analytics_usage, notice: 'Analytics usage was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @analytics_usage.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @metric = Metric.find(params[:id])\n\n if @metric.update(params[:metric])\n head :no_content\n else\n render json: @metric.errors, status: :unprocessable_entity\n end\n end",
"def destroy\n @active_stat = ActiveStat.find(params[:id])\n @active_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to active_stats_url }\n format.json { head :ok }\n end\n end",
"def update_api_status()\n api_status = generate_api_status()\n if !api_status.nil? and !api_status.empty?\n HelperFunctions.write_file(HEALTH_FILE, api_status)\n end\n end",
"def update\n respond_to do |format|\n if @site_stat.update(site_stat_params)\n @site_stat.touch # set update timestamp\n format.html { redirect_to action: 'index', notice: 'Site stat was successfully updated.' }\n format.json { render action: 'show', status: :ok, location: @site_stat }\n else\n format.html { render action: 'edit' }\n format.json { render json: @site_stat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def enable_statistics\n HTTP.put(\"/video/#{@id}\", {:stat => true})\n true\n end",
"def update_dashboard\n fleet_utilized_percentage = (StatsService.percent_utilized_within_range(Date.today, Date.tomorrow) * 100).to_i\n car_actions_count = Reservation.get_actionable_reservation_count\n\n StatsService.update_admin_dashboard('attention', 'current', car_actions_count )\n StatsService.update_admin_dashboard('fleet_utilized', 'value', fleet_utilized_percentage )\n \n end",
"def update\n @active_status = ActiveStatus.find(params[:id])\n\n respond_to do |format|\n if @active_status.update_attributes(params[:active_status])\n flash[:notice] = 'ActiveStatus was successfully updated.'\n format.html { redirect_to(@active_status) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @active_status.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n if @base_objective.update(base_objective_params)\n head 200\n end\n end",
"def update_status(new_stat)\n\n attrs = ActionController::Parameters.new({status: new_stat, req_to_del_at: nil})\n self.update_attributes(attrs.permit(Team::PERMIT_BASE))\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /active_stats/1 DELETE /active_stats/1.json
|
def destroy
@active_stat = ActiveStat.find(params[:id])
@active_stat.destroy
respond_to do |format|
format.html { redirect_to active_stats_url }
format.json { head :ok }
end
end
|
[
"def destroy\n @backend_stat = Backend::Stat.find(params[:id])\n @backend_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to backend_stats_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @stat = Stat.find(params[:id])\n @stat.destroy\n\n respond_to do |format|\n format.html { redirect_to stats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @stat = Stat.find(params[:id])\n @stat.destroy\n\n respond_to do |format|\n format.html { redirect_to stats_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @visit_stat = VisitStat.find(params[:id])\n @visit_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to(scaffold_visit_stats_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @current_stat = CurrentStat.find(params[:id])\n @current_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to(current_stats_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @stat = Stat.find(params[:id])\n @stat.destroy\n\n respond_to do |format|\n format.html { redirect_to(stats_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @sub_stat.destroy\n respond_to do |format|\n format.html { redirect_to sub_stats_url, notice: 'Sub stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @file_stat = FileStat.find(params[:id])\n @file_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to file_stats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @statistic = Statistic.find(params[:id])\n @statistic.destroy\n\n respond_to do |format|\n format.html { redirect_to statistics_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @statistic.destroy\n respond_to do |format|\n format.html { redirect_to statistics_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @rushing_stat = RushingStat.find(params[:id])\n @rushing_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to rushing_stats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @task_stat = TaskStat.find(params[:id])\n @task_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to task_stats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @system_stat.destroy\n respond_to do |format|\n format.html { redirect_to system_stats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @soccer_stat = SoccerStat.find(params[:id])\n @soccer_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to \"/stats\", notice: 'Soccer stats deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @baseball_stat = BaseballStat.find(params[:id])\n @baseball_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to \"/stats\", notice: 'Baseball stats deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @analytics_usage = AnalyticsUsage.find(params[:id])\n @analytics_usage.destroy\n\n respond_to do |format|\n format.html { redirect_to analytics_usages_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @email_stat = EmailStat.find(params[:id])\n @email_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to email_stats_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @health.destroy\n respond_to do |format|\n format.html { redirect_to \"/dashboard\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @admin_stats_bar.destroy\n respond_to do |format|\n format.html { redirect_to admin_stats_bars_url }\n format.json { head :no_content }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /active_stats/team/1 GET /active_stats/team/1.json
|
def team
@team = Team.where('team_id = ?', params[:id])
@active_stats = ActiveStat.where('team_id = ?', params[:id])
respond_to do |format|
format.html
format.json
end
end
|
[
"def get_team_stats()\n query_params = { }\n headers = {}\n body = nil\n\n path = \"/team/stats\"\n\n @client.request(\n method: :get,\n path: path,\n query: query_params,\n headers: headers,\n body: body)\n end",
"def get_team_stats(team); end",
"def team(id)\n get \"/teams/#{id}\"\n end",
"def show\n @ultimate_team = UltimateTeam.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ultimate_team }\n end\n end",
"def index\n league = get_league\n @teams = league.teams\n render json: @teams, status: 201\n end",
"def team\n result = get_response(\"team.info\")\n \n unless result.empty?\n result = {\n :name => result[\"team\"][\"name\"],\n :url => \"https://#{result[\"team\"][\"domain\"]}.slack.com\"\n }\n end\n \n render json: result\n end",
"def get_team_list ( page = 1 )\n get_api_resource \"#{@@api_base_url}teams/#{page}\"\n end",
"def get_team ( team_key )\n get_api_resource \"#{@@api_base_url}team/#{team_key}\"\n end",
"def team\n teams.where(hubstats: true).first\n end",
"def index\n @test_team_stats = TestTeamStat.all\n end",
"def show\n @team = Team.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @league }\n end\n end",
"def profile(team_name)\n get_request(\"/2.0/teams/#{team_name.to_s}\")\n end",
"def stats\n get 'stats', format: 'json'\n end",
"def get_team(id)\n @client.raw('get', \"/config/teams/#{id}\")\n end",
"def get(team_name)\n name = CGI.escape(team_name)\n Twitch::Status.map(404 => nil) do\n json = @query.connection.get(\"teams/#{name}\")\n Team.new(json)\n end\n end",
"def get_team_season_stats_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatsApi.get_team_season_stats ...'\n end\n # resource path\n local_var_path = '/stats/season'\n\n # query parameters\n query_params = {}\n query_params[:'year'] = opts[:'year'] if !opts[:'year'].nil?\n query_params[:'team'] = opts[:'team'] if !opts[:'team'].nil?\n query_params[:'conference'] = opts[:'conference'] if !opts[:'conference'].nil?\n query_params[:'startWeek'] = opts[:'start_week'] if !opts[:'start_week'].nil?\n query_params[:'endWeek'] = opts[:'end_week'] if !opts[:'end_week'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = []\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Array<TeamSeasonStat>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatsApi#get_team_season_stats\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def show\n\t\t@team = Team.find(params[:id])\n\t\trender '/teams/show.json.jbuilder'\n\tend",
"def index\n @team = Team.find(params[:team_id])\n @sprints = @team.sprints.find(:all)\n\n respond_to do |format|\n format.html\n format.json\n end\n end",
"def index\n @player_teams = PlayerTeam.all\n render json: @player_teams, status: :ok\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
The schema defines some tags that may not be empty. This method removes any such empty tags from the tree.
|
def delete_invalid_empty_tags!(node)
node.children.reject! do |child|
if child.is_a?(TagNode)
if child.children.empty? and !@schema.tag_may_be_empty?(child.tag_name)
true
else
delete_invalid_empty_tags!(child)
false
end
end
end
node
end
|
[
"def delete_empty_tags\n sorted_tags = Tag.all.sort_by { |tag| tag.articles.count }\n return if sorted_tags.first.articles.count > 0\n\n sorted_tags.each { |tag| tag.delete if tag.articles.count == 0 }\n end",
"def destroy_empty\n if content.empty? and children.empty?()\n _unhook!\n destroy\n else\n raise \"Refusing to delete node: it either has content or children.\"\n end\n end",
"def delete_all_tags\n delete_tags(self.tags)\n nil\n end",
"def clean_up_tags\n self.tags.each do |tag|\n if tag.todos.count == 1\n tag.destroy\n end\n end\n end",
"def prune!\n self.children.each {|c| c.prune!}\n\n self.children =\n self.children.reject do |c|\n c.tag != :text && c.children.empty?\n end\n end",
"def handle_empty_tag(tag, attrs)\r\n handle_start_tag(tag, attrs)\r\n handle_end_tag(tag)\r\n end",
"def clear_empty_text_nodes(xml_doc)\n xml_doc.root.children.each { |t| t.content = t.content.gsub(/^\\n\\s*\\n*$/, '') }\n end",
"def remove_empty_attributes(node)\n children = node.children\n attributes = node.attributes\n\n attributes.each do |key, value|\n node.remove_attribute(key) if value.to_s.strip.empty?\n end\n\n children.each do |c|\n remove_empty_attributes(c)\n end\n end",
"def delete_unwanted_children\n @children.keys.each do |key|\n if(@children[key][:value].class.name === \"Array\")\n if(@children[key][:value].empty?)\n @children.tap { |hs| hs.delete(key) }\n end\n else\n if(@children[key][:value].nil?)\n @children.tap { |hs| hs.delete(key) }\n end\n end\n end\n end",
"def cleanup\n Tag.all.each do |t|\n t.destroy if t.recipes.blank?\n end\n\n Category.all.each do |c|\n c.destroy if c.recipes.blank?\n end\n\n end",
"def remove_empty\r\n empty = @subs.empty?\r\n\r\n @children.each_value do |room|\r\n if room.remove_empty\r\n empty = false\r\n end\r\n end\r\n\r\n if empty && !@parent.nil?\r\n @parent.remove self\r\n end\r\n\r\n empty\r\n end",
"def purge_unused_tags!\n context.purge_unused_tags!\n end",
"def clear_tags\n\t\tif @tags\n\t\t\t@tags.each { |tag, __unused| self.class.remove_object_with_tag(self, tag) }\n\t\t\t@tags.clear\n\t\tend\n\t\treturn self\n\tend",
"def clean_tree rn\n return if(rn.elements.nil?)\n rn.elements.delete_if{|n| n.class.name == \"Treetop::Runtime::SyntaxNode\" }\n rn.elements.each {|n| clean_tree(n) }\n end",
"def empty\n each { |x| x.inner_html = nil }\n end",
"def delete_all_tags\n for tag in tags\n tag.reload\n tag.unlink\n end\n tags.clear\n end",
"def remove_empty_models\n models.reject! { |_, properties| properties[\"attributes\"].blank? && properties[\"associations\"].blank? }\n end",
"def clear_all_tags()\n puts \"Deleting Tags...\"\n Tag.delete_all()\n puts \"Finished deleting all tags.\"\nend",
"def remove_empty_statement\n @statement_list.reject!{|x|\n x.class == StEmpty\n }\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Whether Markdown implements the PHP Markdown extra syntax. Note: it is not guaranteed that if this is false, then no special features will be used.
|
def markdown_extra?
true
end
|
[
"def markdown?\n @use_markdown && markdown_processor\n end",
"def markdown?\n defined?(RDiscount) or defined?(BlueCloth)\n end",
"def markdown_allowed?\n @markdown_allowed\n end",
"def markdown?\n @source == :markdown || @source == :md\n end",
"def supported?(syntax)\n begin\n markup_syntax_module(syntax)\n return true\n rescue NameError\n return false\n end\n end",
"def markdown_type?\n markdown_file.present?\n end",
"def markdown_extensions\n @markdown_extensions ||= {\n no_intra_emphasis: true,\n tables: true,\n fenced_code_blocks: true,\n autolink: true,\n strikethrough: true\n }\n end",
"def latex?\n false\n end",
"def markdown_tag?(string)\n !!(string =~ /^\\s?[#-]|^\\s?\\~\\~\\~|^\\s?\\`\\`\\`/)\n end",
"def render_template_notes_as_markdown?\n preference = ENV['RENDER_TEMPLATE_NOTES_AS_MARKDOWN']\n\n if preference.nil?\n true\n else\n to_bool(preference)\n end\n end",
"def is_markdownable \n return false unless (IS_MARKDOWNABLE.include?(@parser.tag_name))\n \n if (@parser.is_start_tag)\n ret = true\n if (@keep_html)\n diff = @parser.tag_attributes.reject { |a| @parser.tag_name.include?(a) }\n ret = false unless diff.empty? # non markdownable attributes given\n end\n if (ret)\n IS_MARKDOWNABLE.each do |attr, type|\n if ((type == 'required') && @parser.tag_attributes[attr].nil?)\n # required Markdown attribute not given\n ret = false\n break\n end\n end\n end\n unless (ret)\n @not_converted << (@parser.tag_name + '::' + @parser.open_tags.join('/'))\n end\n return ret\n else\n if (!@not_converted.empty? && (@not_converted.last == (@parser.tag_name + '::' + @parser.open_tags.join('/'))))\n @not_converted.pop\n return false\n end\n return true\n end\n end",
"def tomdoc?\n @format == 'tomdoc'\n end",
"def is_markdownable \n return false unless (IS_MARKDOWNABLE.include?(@parser.tag_name))\n=======\n # indent next output (start tag) or unindent (end tag)\n def indent(str, output = true)\n if (@parser.is_start_tag)\n @indent << str\n out(str, true) if @output\n else\n @indent = @indent.slice(0, (str.size * -1))\n end\n end \n \n # handle plain text\n def handle_text \n if (has_parent('pre') && @parser.node.index(\"\\n\"))\n @parser.node.gsub!(\"\\n\", \"\\n#{@indent}\")\n end\n if (!has_parent('code') && !has_parent('pre'))\n # entity decode\n decode(@parser.node)\n if (!@skip_conversion)\n # escape some chars in normal text\n @parser.node.gsub!(@escape_in_text['search'], @escape_in_text['replace'])\n end\n else\n @parser.node.gsub!(['"', '&apos'], ['\"', '\\''])\n end\n out(@parser.node)\n @last_closed_tag = ''\n end \n \n # handle non-Markdownable tags\n def handle_tag_to_text\n if (!@keep_html)\n set_linebreaks(2) if (!@parser.is_start_tag && @parser.is_block_element)\n else\n # dont convert to markdown inside this tag\n # TODO: markdown extra\n if (!@parser.is_empty_tag)\n if (@parser.is_start_tag)\n unless (@skip_conversion)\n @skip_conversion = @parser.tag_name + '::' + @parser.open_tags.join('/')\n end\n else\n if (@skip_conversion == (@parser.tag_name + '::' + @parser.open_tags.join('/'))\n @skip_conversion = false\n end\n end\n end # end !@parser.is_empty_tag\n \n if (@parser.is_block_element)\n if (@parser.is_start_tag)\n if (%w(ins del).include?(parent))\n # looks like ins or del are block elements now\n out(\"\\n\", true)\n indent(' ')\n end\n if (@parser.tag_name != 'pre')\n out(@parser.node + \"\\n\" + @indent)\n @parser.is_empty_tag ? set_linebreaks(1) : indent(' ')\n @parser.html = @parser.html.lstrip\n else\n # dont indent inside <pre> tags\n out(@parser.node)\n @static_indent = @indent\n @indent = ''\n end\n else\n @output = rstrip(@output) unless @parser.keep_whitespace\n if (@parser.tag_name != 'pre')\n indent(' ')\n out(\"\\n\" + @indent + @parser.node)\n else\n # reset indentation\n out(@parser.node)\n @indent = @static_indent\n end\n \n if (%w(ins del).include?(parent))\n # ins or del was block element\n out(\"\\n\")\n indent(' ')\n end\n \n @parser.tag_name == 'li' ? set_linebreaks(1) : set_linebreaks(2)\n end\n else\n out(@parser.node)\n end\n \n if (%w(code pre).include?(@parser.tag_name))\n if (@parser.is_start_tag)\n buffer\n else\n # add stuff so cleanup just reverses this\n tmp = unbugger.gsub('>', '&gt;')\n out(tmp.gsub('<', '&lt;'))\n end\n end\n end\n end",
"def formatting_note\n if markdown?\n %(HTML and\n #{link_to(\"Markdown\",\n \"http://daringfireball.net/projects/markdown/basics\",\n :popup => true)}\n formatting supported)\n else \n \"HTML formatting supported\"\n end\n end",
"def supported?\n PlainTextExtractor.supported_extensions.include?(self.ext_as_sym) unless ext_as_sym==:no_extension and !plain_text?\n end",
"def export_footnotes?\n \"t\" == @options[\"f\"]\n end",
"def paragraphs?\n false\n end",
"def check_with_markdown(text)\n text.starts_with? self.markdown_identifier\n end",
"def markup?(filename)\n gitlab_markdown?(filename) ||\n asciidoc?(filename) ||\n filename.downcase.end_with?(*%w(.textile .rdoc .org .creole .wiki\n .mediawiki .rst))\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
a Rational Number (two ints reping the num and denom of a rat num) outputs: Array (an arr of denoms that are part of an Egyptian Fraction rep of the num) reqs: take a Rational Number rtn an arr reping an Egyptian Fraction rep of the num struct: Array (to hold denoms) algo: init the output arr to [] init a sum at 0 init the denom at 1 while the sum is rat throw away the new sum else sum = new sum copy denom to the output arr increment the denom
|
def egyptian(rat_num)
arr = []
sum = 0
temp_sum = sum
denom = 1
while sum < rat_num && denom < 1_000_000
temp_sum += Rational(1, denom)
if temp_sum > rat_num # overshot
temp_sum = sum # reset
else
sum = temp_sum
arr << denom
end
# p "denom = #{denom}, sum = #{sum}, arr = #{arr}"
denom += 1
end
arr
end
|
[
"def egyptian(rational_num)\n\ttotal = 0\n\tresult = []\n\tdenominator = 1 \n\tloop do \n\t\tif total + Rational(1, denominator) <= rational_num \n\t\t\ttotal += Rational(1, denominator)\n\t\t\tresult << denominator \n\t\tend \n\t\treturn result if total == rational_num \n\t\tdenominator += 1\n\tend\nend",
"def unegyptian(arr)\n sum = 0\n arr.each { |denom| sum += Rational(1, denom) }\n sum\nend",
"def fractions\n fractions = []\n top_product = 1\n bottom_product = 1\n \n (10..99).each do |numerator|\n (10..99).each do |denominator|\n ratio = numerator.fdiv(denominator)\n if numerator % 10 == denominator / 10 && numerator != denominator\n if (numerator / 10).fdiv(denominator % 10) == ratio\n top_product *= numerator\n bottom_product *= denominator\n fractions << [numerator, denominator]\n end\n end\n end\n end\n print fractions\n puts \"\"\n puts top_product\n puts bottom_product\n reduce_fraction(top_product,bottom_product)\nend",
"def to_r\n return Rational(numerator,denominator)\n end",
"def egyptian(rational)\n denominators = []\n unit_denominator = 1\n until rational == 0\n unit_fraction = Rational(1, unit_denominator)\n if unit_fraction <= rational\n rational -= unit_fraction\n denominators << unit_denominator\n end\n unit_denominator += 1\n end\n denominators\nend",
"def unegyptian(array)\n sum = 0\n array.each do |elem| \n sum += Rational(1, elem)\n end\n sum\nend",
"def curious_fraction(numerator,denominator)\n numerators = numerator.to_s.split('').map(&:to_i)\n denominators = denominator.to_s.split('').map(&:to_i)\n\n if numerators[0]==denominators[0] && numerators[0]!=0\n numerators.shift\n denominators.shift\n return (numerators[0].to_f)/denominators[0]\n \n elsif numerators[1]==denominators[0] && numerators[1]!=0\n numerators.pop\n denominators.shift\n return (numerators[0].to_f)/denominators[0]\n \n elsif numerators[0]==denominators[1] && numerators[0]!=0\n numerators.shift\n denominators.pop\n return (numerators[0].to_f)/denominators[0]\n\n elsif numerators[1]==denominators[1] && numerators[1]!=0\n numerators.pop\n denominators.pop\n return (numerators[0].to_f)/denominators[0]\n else\n false\n end\n\nend",
"def unegyptian(denominators)\n denominators.reduce(0/1r) do |accumulator, denominator|\n accumulator += Rational(1, denominator)\n end\nend",
"def jruby_scale_down_rational(rat)\n return rat if rat.numerator <= java.lang.Long::MAX_VALUE\n [10, 100, 1000].each do |scale_by|\n new_numerator = rat.numerator / scale_by\n if new_numerator <= java.lang.Long::MAX_VALUE\n return Rational(new_numerator, rat.denominator / scale_by)\n end\n end\n end",
"def + r\n ans = MyRational.new(@num,@den)\n ans.add! r\n ans\n end",
"def rad(n)\n factors = []\n p = 1\n\n factors = `factor #{n}`.chomp.split(\" \")\n factors.delete_at(0)\n factors.uniq.collect{|x| p *= x.to_i}\n p\nend",
"def rational\n Rational(integer, integer(0..INTMAX))\n end",
"def toDigArray(prec = 100)\n localNum = @num.abs\n a = Array.new\n prec.times{\n a.push((localNum/@den))\n localNum = (localNum*10) % (@den*10)\n }\n a[0] *= -1 if @num < 0\n return a\n end",
"def + r\r\n ans = MyRational.new(@num,@den)\r\n ans.add! r\r\n ans\r\n end",
"def to_a\n return fraction.to_a\n end",
"def expand(x,digits)\n #puts(\"x #{x}, digits #{digits}\")\n fraction = \"1\"\n i=1\n y = Rational(x.to_s)\n fact = 1\n while true\n fraction = Rational(fraction.to_s) + Rational(y.to_s,fact.to_s)\n\n if fraction.numerator.to_s.length >= digits\n return [fraction.numerator,fraction.denominator]\n end\n i += 1\n fact *= i\n y = Rational(Rational(y.to_s) * Rational(x.to_s))\n end\nend",
"def + r\n ans = MyRational.new(@num, @den)\n ans.add! r\n ans\n end",
"def rad\n self.prime_factors.uniq.reduce( :* )\n end",
"def add(rational)\n\n\t\t#\tCopy the second rational\n\t\ttemp = RationalNumber.new(rational.numerator, rational.denominator)\n\n\t\t#\tMake sure we have LCD \n\t\tif not self.denominator == rational.denominator\n\t\t\ttemp.denominator = rational.denominator * self.denominator\n\t\t\ttemp.numerator = rational.numerator * self.denominator\n\t\tend\n\n\t\t#\tNow add...\n\t\tself.numerator = self.numerator + temp.numerator\n\n\t\treturn self\n\tend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 230, 57960] inputs: Array (an arr of denoms that are part of an Egyptian Fraction rep of the num) outputs: a Rational Number (two ints reping the num and denom of a rat num) reqs: take an arr reping an Egyptian Fraction rep of the num rtn a Rational Number struct: num (to hold sum of fractional elements) algo: init a sum at 0 for each element in the arr add rat(1/denom) to the sum rtn the sum
|
def unegyptian(arr)
sum = 0
arr.each { |denom| sum += Rational(1, denom) }
sum
end
|
[
"def egyptian(rat_num)\n arr = []\n sum = 0\n temp_sum = sum\n denom = 1\n while sum < rat_num && denom < 1_000_000\n temp_sum += Rational(1, denom)\n if temp_sum > rat_num # overshot\n temp_sum = sum # reset\n else\n sum = temp_sum\n arr << denom\n end\n # p \"denom = #{denom}, sum = #{sum}, arr = #{arr}\"\n denom += 1\n end\n arr\nend",
"def unegyptian(array)\n sum = 0\n array.each do |elem| \n sum += Rational(1, elem)\n end\n sum\nend",
"def egyptian(rational_num)\n\ttotal = 0\n\tresult = []\n\tdenominator = 1 \n\tloop do \n\t\tif total + Rational(1, denominator) <= rational_num \n\t\t\ttotal += Rational(1, denominator)\n\t\t\tresult << denominator \n\t\tend \n\t\treturn result if total == rational_num \n\t\tdenominator += 1\n\tend\nend",
"def fractions\n fractions = []\n top_product = 1\n bottom_product = 1\n \n (10..99).each do |numerator|\n (10..99).each do |denominator|\n ratio = numerator.fdiv(denominator)\n if numerator % 10 == denominator / 10 && numerator != denominator\n if (numerator / 10).fdiv(denominator % 10) == ratio\n top_product *= numerator\n bottom_product *= denominator\n fractions << [numerator, denominator]\n end\n end\n end\n end\n print fractions\n puts \"\"\n puts top_product\n puts bottom_product\n reduce_fraction(top_product,bottom_product)\nend",
"def egyptian(rational)\n denominators = []\n unit_denominator = 1\n until rational == 0\n unit_fraction = Rational(1, unit_denominator)\n if unit_fraction <= rational\n rational -= unit_fraction\n denominators << unit_denominator\n end\n unit_denominator += 1\n end\n denominators\nend",
"def curious_fraction(numerator,denominator)\n numerators = numerator.to_s.split('').map(&:to_i)\n denominators = denominator.to_s.split('').map(&:to_i)\n\n if numerators[0]==denominators[0] && numerators[0]!=0\n numerators.shift\n denominators.shift\n return (numerators[0].to_f)/denominators[0]\n \n elsif numerators[1]==denominators[0] && numerators[1]!=0\n numerators.pop\n denominators.shift\n return (numerators[0].to_f)/denominators[0]\n \n elsif numerators[0]==denominators[1] && numerators[0]!=0\n numerators.shift\n denominators.pop\n return (numerators[0].to_f)/denominators[0]\n\n elsif numerators[1]==denominators[1] && numerators[1]!=0\n numerators.pop\n denominators.pop\n return (numerators[0].to_f)/denominators[0]\n else\n false\n end\n\nend",
"def unegyptian(denominators)\n denominators.reduce(0/1r) do |accumulator, denominator|\n accumulator += Rational(1, denominator)\n end\nend",
"def rationalize(*eps)\n #This is a stub, used for indexing\n end",
"def reduce(frac)\n n, d = frac.split('/').map(&:to_i)\n unless (g = gcd(n, d)) == 1\n n /= g; d /= g\n end\n \"#{n}/#{d}\"\nend",
"def to_r\n return Rational(numerator,denominator)\n end",
"def rad(n)\n factors = []\n p = 1\n\n factors = `factor #{n}`.chomp.split(\" \")\n factors.delete_at(0)\n factors.uniq.collect{|x| p *= x.to_i}\n p\nend",
"def add_fractions(a, b)\n denominator = lcm(a[1],b[1])\n result = []\n result << (denominator / a[1]) * a[0] + (denominator / b[1]) * b[0]\n result << denominator\n #reduce the result\n return result\nend",
"def reduce_fraction(numerator, denominator)\n smaller_term = numerator < denominator ? numerator : denominator\n\n smaller_term.downto(2) do |factor|\n if numerator % factor == 0 && denominator % factor == 0\n numerator /= factor\n denominator /= factor\n result = reduce_fraction(numerator, denominator)\n end\n end\n\n [numerator, denominator]\n end",
"def numerator() end",
"def jruby_scale_down_rational(rat)\n return rat if rat.numerator <= java.lang.Long::MAX_VALUE\n [10, 100, 1000].each do |scale_by|\n new_numerator = rat.numerator / scale_by\n if new_numerator <= java.lang.Long::MAX_VALUE\n return Rational(new_numerator, rat.denominator / scale_by)\n end\n end\n end",
"def rational\n Rational(integer, integer(0..INTMAX))\n end",
"def bookmakers_return_rate\n fs = fractions\n 1 - fs.reduce(:*) / fs.reduce(:+) if fs.any?\n end",
"def find_biggest_denominator(denominator, rat_num)\n denominator == nil ? denominator = 1 : denominator += 1\n loop do\n break if (rat_num - Rational(1, denominator)) >= 0\n denominator += 1\n end\n denominator\nend",
"def rad\n self.prime_factors.uniq.reduce( :* )\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Reload the balancer data from the API
|
def balancer_reload(balancer)
if balancer.persisted?
begin
load_balancer_data(balancer)
rescue Miasma::Error::ApiError::RequestError => e
if e.response_error_msg.include?("LoadBalancerNotFound")
balancer.state = :terminated
balancer.status = "terminated"
balancer.valid_state
else
raise
end
end
end
balancer
end
|
[
"def balancer_reload(balancer)\n if(balancer.persisted?)\n result = request(\n :path => \"/loadbalancers/#{balancer.id}\",\n :method => :get,\n :expects => 200\n )\n lb = result.get(:body, 'loadBalancer')\n balancer.load_data(\n :name => lb[:name],\n :name => lb[:name],\n :state => lb[:status] == 'ACTIVE' ? :active : :pending,\n :status => lb[:status],\n :created => lb.get(:created, :time),\n :updated => lb.get(:updated, :time),\n :public_addresses => lb['virtualIps'].map{|addr|\n if(addr[:type] == 'PUBLIC')\n Balancer::Address.new(\n :address => addr[:address],\n :version => addr['ipVersion'].sub('IPV', '').to_i\n )\n end\n }.compact,\n :private_addresses => lb['virtualIps'].map{|addr|\n if(addr[:type] != 'PUBLIC')\n Balancer::Address.new(\n :address => addr[:address],\n :version => addr['ipVersion'].sub('IPV', '').to_i\n )\n end\n }.compact,\n :servers => lb.fetch('nodes', []).map{|s|\n srv = self.api_for(:compute).servers.all.detect do |csrv|\n csrv.addresses.map(&:address).include?(s[:address])\n end\n if(srv)\n Balancer::Server.new(self.api_for(:compute), :id => srv.id)\n end\n }.compact\n ).valid_state\n else\n balancer\n end\n end",
"def refresh\n new_data = self.class.find(id)\n self.api_data = new_data.api_data\n self.response = new_data.response\n self\n end",
"def rebalance!\n read_load_balancers\n \n @load_balancers.each do |load_balancer|\n next if load_balancer[\"virtualServers\"].empty?\n next if 100 == load_balancer[\"virtualServers\"].inject(0) { |sum, vs| sum += vs[\"allocation\"] }\n\n # Create allocation slots.\n count = load_balancer[\"virtualServers\"].count\n allocation = [100 / count] * count\n (100 % count).times { |i| allocation[i] += 1 }\n\n # Rebalance allocations.\n load_balancer[\"virtualServers\"].each do |vs|\n vs[\"allocation\"] = allocation.pop\n end\n\n # Update the VIP object.\n @logger.debug(\"Rebalancing VIP #{load_balancer['id']}\")\n @logger.debug(\"-- #{load_balancer}\")\n @services[\"VirtualIpAddress\"].object_with_id(load_balancer[\"id\"]).editObject(\"virtualServers\" => load_balancer[\"virtualServers\"])\n end\n end",
"def refresh!\n fetch_data\n end",
"def reload\n proxy_owner.buckets(true)\n end",
"def reload\n mass_assign(resource.find(data_bag, self)._attributes_)\n self\n end",
"def refresh!\n self.data = client.get(path).data\n end",
"def reload_data\n reset_collection_data\n reload_collection_data\n end",
"def reload_dataset\n @dataset = Biomart::Dataset.new( @url, { :name => @dataset_name } )\n end",
"def load_balancer_data(balancer = nil)\n params = Smash.new(\"Action\" => \"DescribeLoadBalancers\")\n if balancer\n params[\"LoadBalancerNames.member.1\"] = balancer.id || balancer.name\n end\n result = all_result_pages(nil, :body,\n \"DescribeLoadBalancersResponse\", \"DescribeLoadBalancersResult\",\n \"LoadBalancerDescriptions\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(params),\n )\n end\n if balancer\n health_result = all_result_pages(nil, :body,\n \"DescribeInstanceHealthResponse\", \"DescribeInstanceHealthResult\",\n \"InstanceStates\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(\n \"LoadBalancerName\" => balancer.id || balancer.name,\n \"Action\" => \"DescribeInstanceHealth\",\n ),\n )\n end\n end\n result.map do |blr|\n (balancer || Balancer.new(self)).load_data(\n Smash.new(\n :id => blr[\"LoadBalancerName\"],\n :name => blr[\"LoadBalancerName\"],\n :state => :active,\n :status => \"ACTIVE\",\n :created => blr[\"CreatedTime\"],\n :updated => blr[\"CreatedTime\"],\n :public_addresses => [\n Balancer::Address.new(\n :address => blr[\"DNSName\"],\n :version => 4,\n ),\n ],\n :servers => [blr.get(\"Instances\", \"member\")].flatten(1).compact.map { |i|\n Balancer::Server.new(self.api_for(:compute), :id => i[\"InstanceId\"])\n },\n ).merge(\n health_result.nil? ? {} : Smash.new(\n :server_states => health_result.nil? ? nil : health_result.map { |i|\n Balancer::ServerState.new(\n self.api_for(:compute),\n :id => i[\"InstanceId\"],\n :status => i[\"State\"],\n :reason => i[\"ReasonCode\"],\n :state => i[\"State\"] == \"InService\" ? :up : :down,\n )\n },\n )\n )\n ).valid_state\n end\n end",
"def reload\n old_data = @data.dup\n self.load\n @data = old_data.merge! @data\n end",
"def reload!\n ensure_connection!\n resp = connection.get_bucket name\n if resp.success?\n @gapi = resp.data\n else\n fail ApiError.from_response(resp)\n end\n end",
"def reload\n proxy_owner.objects(true)\n end",
"def reload!\n ensure_connection!\n resp = connection.get_sink name\n if resp.success?\n @gapi = resp.data\n else\n fail ApiError.from_response(resp)\n end\n end",
"def reload\n response = @client.get(\"/Numbers/#{self.number_id}\")\n self.set_paramaters(Elk::Util.parse_json(response.body))\n response.code == 200\n end",
"def refresh\n # re-download the model from the server\n set_model\n end",
"def refresh\n File.atomic_write('data/copy.json') do |file|\n file.write(copy_api_records)\n end\n render json: copy_api_records\n end",
"def reload!\n ensure_service!\n @gapi = service.get_dataset dataset_id\n @reference = nil\n @exists = nil\n self\n end",
"def reload!\n ensure_service!\n @gapi_json = service.get_model dataset_id, model_id\n @reference = nil\n @exists = nil\n self\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Fetch balancers or update provided balancer data
|
def load_balancer_data(balancer = nil)
params = Smash.new("Action" => "DescribeLoadBalancers")
if balancer
params["LoadBalancerNames.member.1"] = balancer.id || balancer.name
end
result = all_result_pages(nil, :body,
"DescribeLoadBalancersResponse", "DescribeLoadBalancersResult",
"LoadBalancerDescriptions", "member") do |options|
request(
:method => :post,
:path => "/",
:form => options.merge(params),
)
end
if balancer
health_result = all_result_pages(nil, :body,
"DescribeInstanceHealthResponse", "DescribeInstanceHealthResult",
"InstanceStates", "member") do |options|
request(
:method => :post,
:path => "/",
:form => options.merge(
"LoadBalancerName" => balancer.id || balancer.name,
"Action" => "DescribeInstanceHealth",
),
)
end
end
result.map do |blr|
(balancer || Balancer.new(self)).load_data(
Smash.new(
:id => blr["LoadBalancerName"],
:name => blr["LoadBalancerName"],
:state => :active,
:status => "ACTIVE",
:created => blr["CreatedTime"],
:updated => blr["CreatedTime"],
:public_addresses => [
Balancer::Address.new(
:address => blr["DNSName"],
:version => 4,
),
],
:servers => [blr.get("Instances", "member")].flatten(1).compact.map { |i|
Balancer::Server.new(self.api_for(:compute), :id => i["InstanceId"])
},
).merge(
health_result.nil? ? {} : Smash.new(
:server_states => health_result.nil? ? nil : health_result.map { |i|
Balancer::ServerState.new(
self.api_for(:compute),
:id => i["InstanceId"],
:status => i["State"],
:reason => i["ReasonCode"],
:state => i["State"] == "InService" ? :up : :down,
)
},
)
)
).valid_state
end
end
|
[
"def balancer_reload(balancer)\n if(balancer.persisted?)\n result = request(\n :path => \"/loadbalancers/#{balancer.id}\",\n :method => :get,\n :expects => 200\n )\n lb = result.get(:body, 'loadBalancer')\n balancer.load_data(\n :name => lb[:name],\n :name => lb[:name],\n :state => lb[:status] == 'ACTIVE' ? :active : :pending,\n :status => lb[:status],\n :created => lb.get(:created, :time),\n :updated => lb.get(:updated, :time),\n :public_addresses => lb['virtualIps'].map{|addr|\n if(addr[:type] == 'PUBLIC')\n Balancer::Address.new(\n :address => addr[:address],\n :version => addr['ipVersion'].sub('IPV', '').to_i\n )\n end\n }.compact,\n :private_addresses => lb['virtualIps'].map{|addr|\n if(addr[:type] != 'PUBLIC')\n Balancer::Address.new(\n :address => addr[:address],\n :version => addr['ipVersion'].sub('IPV', '').to_i\n )\n end\n }.compact,\n :servers => lb.fetch('nodes', []).map{|s|\n srv = self.api_for(:compute).servers.all.detect do |csrv|\n csrv.addresses.map(&:address).include?(s[:address])\n end\n if(srv)\n Balancer::Server.new(self.api_for(:compute), :id => srv.id)\n end\n }.compact\n ).valid_state\n else\n balancer\n end\n end",
"def load_balancers_to_add\n @local.load_balancers - @aws.load_balancer_names\n end",
"def balancer_reload(balancer)\n if balancer.persisted?\n begin\n load_balancer_data(balancer)\n rescue Miasma::Error::ApiError::RequestError => e\n if e.response_error_msg.include?(\"LoadBalancerNotFound\")\n balancer.state = :terminated\n balancer.status = \"terminated\"\n balancer.valid_state\n else\n raise\n end\n end\n end\n balancer\n end",
"def rebalance!\n read_load_balancers\n \n @load_balancers.each do |load_balancer|\n next if load_balancer[\"virtualServers\"].empty?\n next if 100 == load_balancer[\"virtualServers\"].inject(0) { |sum, vs| sum += vs[\"allocation\"] }\n\n # Create allocation slots.\n count = load_balancer[\"virtualServers\"].count\n allocation = [100 / count] * count\n (100 % count).times { |i| allocation[i] += 1 }\n\n # Rebalance allocations.\n load_balancer[\"virtualServers\"].each do |vs|\n vs[\"allocation\"] = allocation.pop\n end\n\n # Update the VIP object.\n @logger.debug(\"Rebalancing VIP #{load_balancer['id']}\")\n @logger.debug(\"-- #{load_balancer}\")\n @services[\"VirtualIpAddress\"].object_with_id(load_balancer[\"id\"]).editObject(\"virtualServers\" => load_balancer[\"virtualServers\"])\n end\n end",
"def update_all_status\n begin\n @loadbalancers = services.loadbalancing.loadbalancers(tenant_id: @scoped_project_id)\n @states = []\n @loadbalancers.each do |lb|\n begin\n @states << services.loadbalancing.loadbalancer_statuses(lb.id)\n rescue ::Core::ServiceLayer::Errors::ApiError\n end\n end\n @states\n end\n end",
"def update_load_balancers(group, remove, add)\n @aws.detach_load_balancers({\n auto_scaling_group_name: group.name,\n load_balancer_names: remove\n })\n @aws.attach_load_balancers({\n auto_scaling_group_name: group.name,\n load_balancer_names: add\n })\n end",
"def get_balancers(_site_info)\n balancers_fqhn = require_fqhns('bal', get_servers_data(_site_info, 'balancers', 'external_fqhn'))\n end",
"def update_status\n begin\n @states = services.loadbalancing.loadbalancer_statuses(params[:id])\n rescue ::Core::ServiceLayer::Errors::ApiError\n\n end\n end",
"def load_balancer\n fail 'Can not determine hostname to load client for' if @new_resource.f5.nil?\n @@load_balancers ||= []\n add_lb(@new_resource.f5) if @@load_balancers.empty?\n add_lb(@new_resource.f5) if @@load_balancers.find { |lb| lb.name == @new_resource.f5 }.nil?\n @@load_balancers.find { |lb| lb.name == @new_resource.f5 }\n end",
"def each_load_balancer\n ids = list_load_balancers.map { |l| l[:id] }\n last = ids.pop\n\n ids.each do |id|\n yield get_load_balancer(id)\n # Otherwise we hit the API rate limits\n sleep(1)\n end\n\n yield get_load_balancer(last) if last\n end",
"def update_status\n @states = services.loadbalancing.loadbalancer_statuses(params[:id])\n end",
"def update\n @loadbalancer = Loadbalancer.find(params[:id])\n checkaccountobject(\"loadbalancers\",@loadbalancer)\n respond_to do |format|\n if @loadbalancer.update_attributes(params[:loadbalancer])\n format.html { redirect_to @loadbalancer, notice: 'Loadbalancer was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @loadbalancer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def balancer_all(options={})\n result = request(\n :path => '/loadbalancers',\n :method => :get,\n :expects => 200\n )\n result.fetch(:body, 'loadBalancers', []).map do |lb|\n Balancer.new(\n self,\n :id => lb[:id],\n :name => lb[:name],\n :state => lb[:status] == 'ACTIVE' ? :active : :pending,\n :status => lb[:status],\n :created => lb.get(:created, :time),\n :updated => lb.get(:updated, :time),\n :public_addresses => lb['virtualIps'].map{|addr|\n if(addr[:type] == 'PUBLIC')\n Balancer::Address.new(\n :address => addr[:address],\n :version => addr['ipVersion'].sub('IPV', '').to_i\n )\n end\n }.compact,\n :private_addresses => lb['virtualIps'].map{|addr|\n if(addr[:type] != 'PUBLIC')\n Balancer::Address.new(\n :address => addr[:address],\n :version => addr['ipVersion'].sub('IPV', '').to_i\n )\n end\n }.compact\n ).valid_state\n end\n end",
"def update\n # Re-authenticate if needed.\n @lb_model.maybe_reauthenticate if @lb_model.respond_to? :maybe_reauthenticate\n\n # Check whether any previously submitted operations have completed.\n poll_async_jobs\n # TODO: Consider instead exposing poll_async_jobs for\n # RoutingDaemon to invoke directly.\n\n # Filter out operations that involve pools that are in the process\n # of being added to the load balancer, as denoted by the existence\n # of job ids associated with such pools, and jobs that are waiting\n # on other jobs. Note that order is preserved.\n # [Operation] -> [Operation], [Operation]\n ready_ops, @ops = @ops.partition {|op| op.jobids.empty? && op.blocked_on_cnt.zero?}\n\n # TODO: Delete pairs of Operation objects that cancel out (e.g., an\n # :add_pool_member and a :delete_pool_member operation for the same\n # member, when neither operation has been submitted or blocks another\n # operation).\n\n # Combine similar operations, such as two :add_pool_member\n # operations that affect the same pool.\n ready_ops = combine_like_ops ready_ops\n\n # Put these combined ops back into @ops so we can track them after\n # we have submitted them.\n @ops = @ops + ready_ops\n\n # Submit ready operations to the load balancer.\n ready_ops.each do |op|\n begin\n @logger.info \"Submitting operation to load balancer: #{op}.\"\n op.jobids = @lb_model.send op.type, *op.operands\n @logger.info \"Got back jobids #{op.jobids.join ', '}.\"\n\n # In case the operation generates no jobs and is immediately done, we\n # must reap it now because there will be no completion of a job to\n # trigger the reaping.\n reap_op_if_no_remaining_tasks op\n rescue => e\n @logger.warn \"Got exception: #{e.message}\"\n @logger.debug \"Backtrace:\\n#{e.backtrace.join \"\\n\"}\"\n\n @logger.info \"Cancelling the operation and any operations that it blocks...\"\n\n cancel_op op\n\n @logger.info \"Done.\"\n end\n end\n end",
"def load_balancer # rubocop:disable AbcSize\n raise 'Can not determine hostname to load client for' if @new_resource.f5.nil?\n @@load_balancers ||= []\n add_lb(@new_resource.f5) if @@load_balancers.empty?\n add_lb(@new_resource.f5) if @@load_balancers.find { |lb| lb.name == @new_resource.f5 }.nil?\n @@load_balancers.find { |lb| lb.name == @new_resource.f5 }\n end",
"def balancer_all(options = {})\n load_balancer_data\n end",
"def index\n @cabinet_balancers = Balancer.all\n end",
"def balancer\n @balancer ||= RightSupport::Net::RequestBalancer.new(@@hostnames,\n :policy=>RightSupport::Net::Balancing::StickyPolicy,\n :resolve => REPOSE_RESOLVE_TIMEOUT)\n end",
"def index\n @admin_balancers = Balancer.all\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return all load balancers
|
def balancer_all(options = {})
load_balancer_data
end
|
[
"def balancer_all(options={})\n result = request(\n :path => '/loadbalancers',\n :method => :get,\n :expects => 200\n )\n result.fetch(:body, 'loadBalancers', []).map do |lb|\n Balancer.new(\n self,\n :id => lb[:id],\n :name => lb[:name],\n :state => lb[:status] == 'ACTIVE' ? :active : :pending,\n :status => lb[:status],\n :created => lb.get(:created, :time),\n :updated => lb.get(:updated, :time),\n :public_addresses => lb['virtualIps'].map{|addr|\n if(addr[:type] == 'PUBLIC')\n Balancer::Address.new(\n :address => addr[:address],\n :version => addr['ipVersion'].sub('IPV', '').to_i\n )\n end\n }.compact,\n :private_addresses => lb['virtualIps'].map{|addr|\n if(addr[:type] != 'PUBLIC')\n Balancer::Address.new(\n :address => addr[:address],\n :version => addr['ipVersion'].sub('IPV', '').to_i\n )\n end\n }.compact\n ).valid_state\n end\n end",
"def list_loadbalancers(attributes = {}, headers = {})\n Validators::Loadbalancer.validate_attributes!(attributes, :list)\n get!(\"loadbalancers\", attributes, headers)\n end",
"def lbs\n lb = client.get(:loadbalancers)\n msg = \"Status: #{lb.status}\"\n raise Idcf::Cli::CliError, msg if !lb.success? || lb.status != 200\n\n lb.body\n end",
"def list_load_balancers(options={})\n response = lbreq(\"GET\",lbmgmthost,\"#{lbmgmtpath}/loadbalancers\",lbmgmtport,lbmgmtscheme)\n CloudLB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n balancers = CloudLB.symbolize_keys(JSON.parse(response.body)[\"loadBalancers\"])\n return options[:show_deleted] == true ? balancers : balancers.select{|lb| lb[:status] != \"DELETED\"}\n end",
"def index\n @cabinet_balancers = Balancer.all\n end",
"def index\n @admin_balancers = Balancer.all\n end",
"def find_elbs\n @client.describe_elastic_load_balancers({:stack_id => stack_id})[:elastic_load_balancers]\n end",
"def describe_load_balancers(ids = [], options = {})\n ids = [*ids]\n params = {}\n params['Marker'] = options[:marker] if options[:marker]\n params['PageSize'] = options[:page_size] if options[:page_size]\n params.merge!(Fog::AWS.serialize_keys('LoadBalancerArns', ids)) if ids.any?\n params.merge!(Fog::AWS.serialize_keys('Names', options[:names])) if options[:names]\n request({\n 'Action' => 'DescribeLoadBalancers',\n :parser => Fog::Parsers::AWS::ELBV2::DescribeLoadBalancers.new\n }.merge!(params))\n end",
"def each_load_balancer\n ids = list_load_balancers.map { |l| l[:id] }\n last = ids.pop\n\n ids.each do |id|\n yield get_load_balancer(id)\n # Otherwise we hit the API rate limits\n sleep(1)\n end\n\n yield get_load_balancer(last) if last\n end",
"def init_elbs\n elbs = []\n all_records_retrieved = false\n next_marker = nil\n\n until all_records_retrieved\n response = @@client.describe_load_balancers({\n marker: next_marker\n }.reject { |k, v| v.nil? })\n\n elbs << response.load_balancer_descriptions\n next_marker = response.next_marker\n\n if next_marker == nil\n all_records_retrieved = true\n end\n end\n\n Hash[elbs.flatten.map { |elb| [elb.load_balancer_name, elb] }]\n end",
"def describe_load_balancers(options = {})\n unless options.is_a?(Hash)\n Fog::Logger.deprecation(\"describe_load_balancers with #{options.class} is deprecated, use all('LoadBalancerNames' => []) instead [light_black](#{caller.first})[/]\")\n options = { 'LoadBalancerNames' => [options].flatten }\n end\n\n if names = options.delete('LoadBalancerNames')\n options.update(Fog::AWS.indexed_param('LoadBalancerNames.member', [*names]))\n end\n\n request({\n 'Action' => 'DescribeLoadBalancers',\n :parser => Fog::Parsers::AWS::ELB::DescribeLoadBalancers.new\n }.merge!(options))\n end",
"def describe_load_balancers(options = {})\n unless options.is_a?(Hash)\n Fog::Logger.deprecation(\"describe_load_balancers with #{options.class} is deprecated, use all('LoadBalancerNames' => []) instead [light_black](#{caller.first})[/]\")\n options = { 'LoadBalancerNames' => [options].flatten }\n end\n\n if names = options.delete('LoadBalancerNames')\n options.update(Fog::AWS.indexed_param('LoadBalancerNames.member', [*names]))\n end\n\n request({\n 'Action' => 'DescribeLoadBalancers',\n :parser => Fog::Parsers::AWS::ELBV2::DescribeLoadBalancers.new\n }.merge!(options))\n end",
"def load_balancers_to_add\n @local.load_balancers - @aws.load_balancer_names\n end",
"def load_balancer_data(balancer = nil)\n params = Smash.new(\"Action\" => \"DescribeLoadBalancers\")\n if balancer\n params[\"LoadBalancerNames.member.1\"] = balancer.id || balancer.name\n end\n result = all_result_pages(nil, :body,\n \"DescribeLoadBalancersResponse\", \"DescribeLoadBalancersResult\",\n \"LoadBalancerDescriptions\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(params),\n )\n end\n if balancer\n health_result = all_result_pages(nil, :body,\n \"DescribeInstanceHealthResponse\", \"DescribeInstanceHealthResult\",\n \"InstanceStates\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(\n \"LoadBalancerName\" => balancer.id || balancer.name,\n \"Action\" => \"DescribeInstanceHealth\",\n ),\n )\n end\n end\n result.map do |blr|\n (balancer || Balancer.new(self)).load_data(\n Smash.new(\n :id => blr[\"LoadBalancerName\"],\n :name => blr[\"LoadBalancerName\"],\n :state => :active,\n :status => \"ACTIVE\",\n :created => blr[\"CreatedTime\"],\n :updated => blr[\"CreatedTime\"],\n :public_addresses => [\n Balancer::Address.new(\n :address => blr[\"DNSName\"],\n :version => 4,\n ),\n ],\n :servers => [blr.get(\"Instances\", \"member\")].flatten(1).compact.map { |i|\n Balancer::Server.new(self.api_for(:compute), :id => i[\"InstanceId\"])\n },\n ).merge(\n health_result.nil? ? {} : Smash.new(\n :server_states => health_result.nil? ? nil : health_result.map { |i|\n Balancer::ServerState.new(\n self.api_for(:compute),\n :id => i[\"InstanceId\"],\n :status => i[\"State\"],\n :reason => i[\"ReasonCode\"],\n :state => i[\"State\"] == \"InService\" ? :up : :down,\n )\n },\n )\n )\n ).valid_state\n end\n end",
"def load_balancer_names\n @group.load_balancer_names\n end",
"def get_balancers(_site_info)\n balancers_fqhn = require_fqhns('bal', get_servers_data(_site_info, 'balancers', 'external_fqhn'))\n end",
"def update_all_status\n begin\n @loadbalancers = services.loadbalancing.loadbalancers(tenant_id: @scoped_project_id)\n @states = []\n @loadbalancers.each do |lb|\n begin\n @states << services.loadbalancing.loadbalancer_statuses(lb.id)\n rescue ::Core::ServiceLayer::Errors::ApiError\n end\n end\n @states\n end\n end",
"def load_balancer(elb_connection = Fog::AWS[:elb])\n if resources.nil?\n elb_connection.load_balancers.get(live_resources['LoadBalancers'].first['Name'])\n else\n elb_connection.load_balancers.get(resources['LoadBalancer']['LoadBalancerName'])\n end\n end",
"def index\n @loadbalancers = getmydata(\"Loadbalancer\")\n pagination\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @loadbalancers }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Round 3 Write a function called toonify that takes two parameters, accent and sentence. If accent is the string "daffy", return a modified version of sentence with all "s" replaced with "th". If the accent is "elmer", replace all "r" with "w". Feel free to add your own accents as well! If the accent is not recognized, just return the sentence asis. toonify("daffy", "so you smell like sausage") => "tho you thmell like thauthage"
|
def toonify(accent, sentence)
if accent == 'daffy'
return sentence.gsub('s', 'th')
elsif accent == 'elmer'
return sentence.gsub('r', 'w')
else
return sentence
end
end
|
[
"def toonify(accent, sentence)\n if accent == \"daffy\"\n return sentence.gsub('s', 'th')\n elsif accent == \"elmer\"\n return sentence.gsub('r', 'w')\n else\n return sentence\n end\nend",
"def toonify(accent, sentence)\n\tif accent === \"daffy\"\n\t\tp sentence.gsub(\"s\", \"th\")\n\t\t#gsub(pattern, replacement) → new_str\n\telsif accent === \"elmer\"\n\t\tp sentence.gsub(\"r\", \"w\")\n\telse\n\t\tp sentence\n\tend\nend",
"def toonify(accent, sentence)\n if accent == \"daffy\"\n return sentence.sub('s', 'th')\n elsif accent == \"elmer\"\n return sentence.sub('r', 'w')\n else\n return sentence\n end\nend",
"def toonify (accent, sentence)\n if (accent == 'daffy')\n daffy_new = sentence.gsub!('s', 'th')\n return daffy_new\n elsif (accent == 'elmer')\n elmer_new = sentence.gsub!('r', 'w')\n return elmer_new\n else \n return sentence\n end\nend",
"def toonify(accent, sentence)\n if accent == :daffy\n sentence.gsub('s', 'th')\n elsif accent == :elmer\n sentence.gsub('r', 'w')\n else\n sentence\n end\nend",
"def toonify accent, sentence\n\tif accent === \"daffy\"\n\t\tputs sentence.gsub /[s]/, 'th'\n\telsif accent === \"elmer\"\n\t\tputs sentence.gsub /[r]/, 'w'\n\telse\n\t\tputs sentence\n\tend\nend",
"def pig_latin_sentence(sentence)\r\n\tnew_sentence = \"\"\r\n\tsentence.split.each do |word|\r\n\t\tif word[0].downcase =~ /[aeiou]/\r\n\t\t\tword << \"way\" \r\n\t\telse\r\n\t\t\tn = /[aeiou]/.match word.downcase\r\n\t\t\tword = n.to_s + n.post_match + n.pre_match + \"ay\"\r\n\t\tend\r\n\t\tnew_sentence << word\r\n\tend\r\n\tnew_sentence\r\nend",
"def elite_translate(input)\n new_sentence = []\n sub_char = input.gsub(/[eoI]/,'e' => 3, 'o' => 0, 'I' => 1)\n split_sentence = sub_char.split()\n split_sentence.each() do |word|\n newWord = (word[1..-1]).gsub(/[s]/,'s' => 'z')\n new_sentence.push((word[0]) + newWord)\n # new_sentence.push((word[0]) + (word[1..-1]))\n end\n join_sentence = new_sentence.join(' ')\n join_sentence\nend",
"def censor(sentence, curse_words)\n censored = sentence.split(\" \").map { |word| curse_words.include?(word.downcase) ? replace_vowels(word) : word }\n censored.join(\" \")\nend",
"def word_substituter(string)\n shorten(string)\nend",
"def translate(input)\n #outStr = input.downcase\n outStr = input\n\n # replace words\n # still need to add punctuation and missing words\n outStr = single_words(outStr)\n\n # prepend and append\n outStr = prepend_and_append(outStr)\n\n # punctuation\n #outStr = punctuation(outStr)\n\n # change tags like &god or &bodypart, etc\n outStr = change_tags(outStr)\n\n\n puts outStr\n end",
"def silly_talk(sentence)\n vowels = 'aeiou'\n new_sentence = []\n\n sentence.split(' ').each do |word|\n new_word = ''\n if vowels.include?(word[-1])\n new_word = word + word[-1]\n else\n word.each_char do |char|\n if vowels.include?(char.downcase)\n new_word << char + 'b' + char.downcase\n else\n new_word << char\n end\n end\n end\n new_sentence << new_word\n end\n\n new_sentence.join(' ')\nend",
"def typoglycemiaSentence(input)\n words = input.split(' ')\n words.map! { |x| typoglycemiaWord(x) }\n words.join(\" \")\nend",
"def lotrify(str)\n str.gsub(\"Bilbo\", \"Frodo\")\nend",
"def translate(s)\n vowels = 'aeiou'\n phoneme1 = ['ch', 'qu', 'br', 'th']\n phoneme2 = ['sch', 'thr', 'squ']\n\nstring = s.split.each do |i|\n if vowels.include?i[0]\n i << \"ay\"\n elsif\n phoneme2.include?(i[0..2])\n return i[3..-1] + i[0..2] + \"ay\"\n elsif\n phoneme1.include?(i[0..1])\n return i[2..-1] + i[0..1] + \"ay\"\n else\n new_ending = i.slice!(0)\n i << new_ending + \"ay\" \n end\n end\n string = string.join(\" \")\nend",
"def abbreviate_sentence(sent)\n\n words = sent.split(\" \")\n new_sent = []\n words.each do |word|\n if word.length > 4\n new_sent << remove_vowels(word)\n else\n new_sent << word\n end\n end\n return new_sent.join(\" \")\n \n end",
"def amendTheSentence(s)\n s.gsub(/([A-Z])/, ' \\1').strip.downcase\nend",
"def word_substituter(tweet)\n shortened = []\n\n tweet_words = tweet.split\n\n tweet_words.each do |word|\n short_form = dictionary(word.downcase)\n if short_form\n shortened << short_form\n else\n shortened << word\n end\n end\n\n shortened.join(' ')\nend",
"def sentence_conv(sentence)\n sentence_arr = sentence.split(\" \")\n pig_sentence = \"\"\n sentence_arr.each do |word|\n pig_sentence << converter(word) + \" \"\n end\n return pig_sentence\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /generic_monographs POST /generic_monographs.json
|
def create
@generic_monograph = DisGenericMonograph.new(generic_monograph_params)
if @generic_monograph.save
flash[:notice] = "Task was successfully created."
respond_with(@generic_monograph)
else
flash[:notice] = "Task was not created."
end
end
|
[
"def create\n @generic_monograph = GenericMonograph.new(generic_monograph_params)\n\n respond_to do |format|\n if @generic_monograph.save\n format.html { redirect_to @generic_monograph, notice: 'Generic monograph was successfully created.' }\n format.json { render :show, status: :created, location: @generic_monograph }\n else\n format.html { render :new }\n format.json { render json: @generic_monograph.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @dis_generic_monograph = DisGenericMonograph.new(dis_generic_monograph_params)\n\n respond_to do |format|\n if @dis_generic_monograph.save\n format.html { redirect_to @dis_generic_monograph, notice: 'Dis generic monograph was successfully created.' }\n format.json { render :show, status: :created, location: @dis_generic_monograph }\n else\n format.html { render :new }\n format.json { render json: @dis_generic_monograph.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\n\n respond_to do |format|\n if @monograph.save\n format.html { redirect_to @monograph, notice: 'Monograph was successfully created.' }\n format.json { render :show, status: :created, location: @monograph }\n else\n format.html { render :new }\n format.json { render json: @monograph.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @generic_monographs = GenericMonograph.all\n end",
"def create\n @monograph_holding = MonographHolding.new(monograph_holding_params)\n\n respond_to do |format|\n if @monograph_holding.save\n format.html { redirect_to @monograph_holding, notice: 'Monograph holding was successfully created.' }\n format.json { render :show, status: :created, location: @monograph_holding }\n else\n format.html { render :new }\n format.json { render json: @monograph_holding.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @dis_generic_monographs = DisGenericMonograph.all\n end",
"def update\n respond_to do |format|\n if @generic_monograph.update(generic_monograph_params)\n format.html { redirect_to @generic_monograph, notice: 'Generic monograph was successfully updated.' }\n format.json { render :show, status: :ok, location: @generic_monograph }\n else\n format.html { render :edit }\n format.json { render json: @generic_monograph.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @monit = Monit.new(params[:monit])\n\n respond_to do |format|\n if @monit.save\n format.html { redirect_to @monit, notice: 'Monit was successfully created.' }\n format.json { render json: @monit, status: :created, location: @monit }\n else\n format.html { render action: \"new\" }\n format.json { render json: @monit.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @testmonial = Testmonial.new(testmonial_params)\n\n if @testmonial.save\n render json: @testmonial, status: :created\n else\n render json: @testmonial.errors, status: :unprocessable_entity\n end\n end",
"def create\n @motogp = Motogp.new(motogp_params)\n\n respond_to do |format|\n if @motogp.save\n format.html { redirect_to :action=>'index', notice: 'Motogp was successfully created.' }\n format.json { render :index, status: :created, location: @motogp }\n else\n format.html { render :new }\n format.json { render json: @motogp.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @sermon = Sermon.new(sermon_params)\n\n respond_to do |format|\n if @sermon.save\n format.html { redirect_to @sermon, notice: 'Sermon was successfully created.' }\n format.json { render json: @sermon.to_json }\n else\n format.html { render action: 'new' }\n format.json { render json: @sermon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @osmotic = Osmotic.new(osmotic_params)\n\n respond_to do |format|\n if @osmotic.save\n format.html { redirect_to @osmotic, notice: 'Osmotic was successfully created.' }\n format.json { render :show, status: :created, location: @osmotic }\n else\n format.html { render :new }\n format.json { render json: @osmotic.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @photograph = Photograph.new(params[:photograph])\n\n respond_to do |format|\n if @photograph.save\n format.html { redirect_to @photograph, notice: 'Photograph was successfully created.' }\n format.json { render json: @photograph, status: :created, location: @photograph }\n else\n format.html { render action: \"new\" }\n format.json { render json: @photograph.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @mona = Mona.new(mona_params)\n\n respond_to do |format|\n if @mona.save\n format.html { redirect_to @mona, notice: 'Mona was successfully created.' }\n format.json { render :show, status: :created, location: @mona }\n else\n format.html { render :new }\n format.json { render json: @mona.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @moretinymobbattle = Moretinymobbattle.new(params[:moretinymobbattle])\n\n respond_to do |format|\n if @moretinymobbattle.save\n format.html { redirect_to @moretinymobbattle, notice: 'Moretinymobbattle was successfully created.' }\n format.json { render json: @moretinymobbattle, status: :created, location: @moretinymobbattle }\n else\n format.html { render action: \"new\" }\n format.json { render json: @moretinymobbattle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @mobs_nano = MobsNano.new(params[:mobs_nano])\n\n respond_to do |format|\n if @mobs_nano.save\n flash[:notice] = 'MobsNano was successfully created.'\n format.html { redirect_to mobs_nano_url(@mobs_nano) }\n format.xml { head :created, :location => mobs_nano_url(@mobs_nano) }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @mobs_nano.errors.to_xml }\n end\n end\n end",
"def create\n @mon = Mon.new(mon_params)\n\n respond_to do |format|\n if @mon.save\n format.html { redirect_to @mon, notice: 'Mon was successfully created.' }\n format.json { render :show, status: :created, location: @mon }\n else\n format.html { render :new }\n format.json { render json: @mon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @meteo_datum = MeteoDatum.new(meteodatum_params)\n @meteo_datum.weather_station_id = params[:weather_station_id]\n\n if @meteo_datum.save\n render json: @meteo_datum, status: :created\n else\n render json: @meteo_datum.errors, status: :unprocessable_entity\n end\n end",
"def create\n @sermon = Sermon.new(params[:sermon])\n\n respond_to do |format|\n if @sermon.save\n format.html { redirect_to sermons_path, notice: 'Sermon was successfully created.' }\n format.json { render json: @sermon, status: :created, location: @sermon }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sermon.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PATCH/PUT /generic_monographs/1 PATCH/PUT /generic_monographs/1.json
|
def update
respond_to do |format|
if @generic_monograph.update(generic_monograph_params)
format.html { redirect_to @generic_monograph, notice: 'Combination dose was successfully updated.' }
format.json { render :show, status: :ok, location: @generic_monograph }
else
format.html { render :edit }
format.json { render json: @generic_monograph.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update\n respond_to do |format|\n if @generic_monograph.update(generic_monograph_params)\n format.html { redirect_to @generic_monograph, notice: 'Generic monograph was successfully updated.' }\n format.json { render :show, status: :ok, location: @generic_monograph }\n else\n format.html { render :edit }\n format.json { render json: @generic_monograph.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @dis_generic_monograph.update(dis_generic_monograph_params)\n format.html { redirect_to @dis_generic_monograph, notice: 'Dis generic monograph was successfully updated.' }\n format.json { render :show, status: :ok, location: @dis_generic_monograph }\n else\n format.html { render :edit }\n format.json { render json: @dis_generic_monograph.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @monograph.update(monograph_params)\n format.html { redirect_to @monograph, notice: 'Monograph was successfully updated.' }\n format.json { render :show, status: :ok, location: @monograph }\n else\n format.html { render :edit }\n format.json { render json: @monograph.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @monograph_holding.update(monograph_holding_params)\n format.html { redirect_to @monograph_holding, notice: 'Monograph holding was successfully updated.' }\n format.json { render :show, status: :ok, location: @monograph_holding }\n else\n format.html { render :edit }\n format.json { render json: @monograph_holding.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @generic.update(generic_params)\n format.html { redirect_to @generic, notice: 'Generic was successfully updated.' }\n format.json { render :show, status: :ok, location: @generic }\n else\n format.html { render :edit }\n format.json { render json: @generic.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @machinery = Machinery.find(params[:id])\n\n respond_to do |format|\n if @machinery.update_attributes(params[:machinery])\n format.html { redirect_to @machinery, notice: 'Machinery was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @machinery.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @generic_master.update(generic_master_params)\n format.html { redirect_to @generic_master, notice: \"#{@generic_master.table_name.titleize.singularize} was successfully updated.\" }\n format.json { render :show, status: :ok, location: @generic_master }\n else\n format.html { render :edit }\n format.json { render json: @generic_master.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @osmotic.update(osmotic_params)\n format.html { redirect_to @osmotic, notice: 'Osmotic was successfully updated.' }\n format.json { render :show, status: :ok, location: @osmotic }\n else\n format.html { render :edit }\n format.json { render json: @osmotic.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @photograph = Photograph.find(params[:id])\n\n respond_to do |format|\n if @photograph.update_attributes(params[:photograph])\n format.html { redirect_to @photograph, notice: 'Photograph was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @photograph.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mosaic.update(mosaic_params)\n format.html { redirect_to @mosaic, notice: 'Mosaic was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mosaic.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @generic_model.update(generic_model_params)\n format.html { redirect_to @generic_model, notice: 'Generic model was successfully updated.' }\n format.json { render :show, status: :ok, location: @generic_model }\n else\n format.html { render :edit }\n format.json { render json: @generic_model.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @testmonial = Testmonial.find(params[:id])\n\n if @testmonial.update(testmonial_params)\n head :no_content\n else\n render json: @testmonial.errors, status: :unprocessable_entity\n end\n end",
"def create\n @generic_monograph = GenericMonograph.new(generic_monograph_params)\n\n respond_to do |format|\n if @generic_monograph.save\n format.html { redirect_to @generic_monograph, notice: 'Generic monograph was successfully created.' }\n format.json { render :show, status: :created, location: @generic_monograph }\n else\n format.html { render :new }\n format.json { render json: @generic_monograph.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @monit = Monit.find(params[:id])\n\n respond_to do |format|\n if @monit.update_attributes(params[:monit])\n format.html { redirect_to @monit, notice: 'Monit was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @monit.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @mosaic = Mosaic.find(params[:id])\n\n respond_to do |format|\n if @mosaic.update_attributes(params[:mosaic])\n format.html { redirect_to @mosaic, notice: 'Mosaic was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @mosaic.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @monument.update(monument_params)\n format.html { redirect_to @monument, notice: 'Monument was successfully updated.' }\n format.json { render :show, status: :ok, location: @monument }\n else\n format.html { render :edit }\n format.json { render json: @monument.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @micropot.update(micropot_params)\n format.html { redirect_to @micropot, notice: 'Micropot was successfully updated.' }\n format.json { render :show, status: :ok, location: @micropot }\n else\n format.html { render :edit }\n format.json { render json: @micropot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mona.update(mona_params)\n format.html { redirect_to @mona, notice: 'Mona was successfully updated.' }\n format.json { render :show, status: :ok, location: @mona }\n else\n format.html { render :edit }\n format.json { render json: @mona.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @momo.update(momo_params)\n format.html { redirect_to @momo, notice: 'Momo was successfully updated.' }\n format.json { render :show, status: :ok, location: @momo }\n else\n format.html { render :edit }\n format.json { render json: @momo.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /generic_monographs/1 DELETE /generic_monographs/1.json
|
def destroy
@generic_monograph.destroy
respond_to do |format|
format.html { redirect_to generic_monographs_url, notice: 'Combination dose was successfully destroyed.' }
format.json { head :no_content }
end
end
|
[
"def destroy\n @generic_monograph.destroy\n respond_to do |format|\n format.html { redirect_to generic_monographs_url, notice: 'Generic monograph was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @dis_generic_monograph.destroy\n respond_to do |format|\n format.html { redirect_to dis_generic_monographs_url, notice: 'Dis generic monograph was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @monograph.destroy\n respond_to do |format|\n format.html { redirect_to monographs_url, notice: 'Monograph was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @agronomium = Agronomium.find(params[:id])\n @agronomium.destroy\n\n respond_to do |format|\n format.html { redirect_to agronomia_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mosaic.destroy\n respond_to do |format|\n format.html { redirect_to mosaics_url }\n format.json { head :no_content }\n end\n end",
"def delete_monster(monster_id)\n RESTful.delete(\"#{URL_MICROSERVICE_MONSTER}/monster/#{monster_id}\")\n end",
"def delete_floor_plan(args = {}) \n delete(\"/files.json/floorplan/images\", args)\nend",
"def destroy\n @mosaic = Mosaic.find(params[:id])\n @mosaic.destroy\n\n respond_to do |format|\n format.html { redirect_to mosaics_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @osmotic.destroy\n respond_to do |format|\n format.html { redirect_to osmotics_url, notice: 'Osmotic was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mystic.destroy\n respond_to do |format|\n format.html { redirect_to mystics_url }\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 @monograph_holding.destroy\n respond_to do |format|\n format.html { redirect_to monograph_holdings_url, notice: 'Monograph holding was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cephalopod.destroy\n respond_to do |format|\n format.html { redirect_to cephalopods_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @photograph = Photograph.find(params[:id])\n @photograph.destroy\n\n respond_to do |format|\n format.html { redirect_to photographs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @generic.destroy\n respond_to do |format|\n format.html { redirect_to generics_url, notice: 'Generic was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @humanoid.destroy\n respond_to do |format|\n format.html { redirect_to humanoids_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @monogram = Monogram.find(params[:id])\n @monogram.destroy\n\n respond_to do |format|\n format.html { redirect_to(monograms_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @monit = Monit.find(params[:id])\n @monit.destroy\n\n respond_to do |format|\n format.html { redirect_to monits_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @machinery = Machinery.find(params[:id])\n @machinery.destroy\n\n respond_to do |format|\n format.html { redirect_to machineries_url }\n format.json { head :no_content }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Searches through the instance variables of the class and creates a class method on the MetricFu module to read the value of the instance variable from the Configuration class.
|
def add_class_methods_to_metric_fu
instance_variables.each do |name|
method_name = name[1..-1].to_sym
method = <<-EOF
def self.#{method_name}
configuration.send(:#{method_name})
end
EOF
MetricFu.module_eval(method)
end
end
|
[
"def class_variables() end",
"def _set_instance_vars_from_config(config)\n config.config_options.each do |config_option|\n # Only internalize relevant config options µ\n case config_option\n when :plan,:project,:server,:devkey\n config_value = config.send(config_option)\n @log.debug(\"TestCollection internalizing config option: #{config_option} => #{config_value}\")\n self.instance_variable_set(('@' + config_option.to_s).to_sym,config_value)\n end\n\n end\n end",
"def instance_variables() end",
"def class_variable_get(sym) end",
"def class_variables; end",
"def add_attr_accessors_to_self\n instance_variables.each do |name|\n method_name = name[1..-1].to_sym\n MetricFu::Configuration.send(:attr_accessor, method_name)\n end\n end",
"def class_instance_variables\n field_mirrors(reflectee_send_from_module(:instance_variables))\n end",
"def get_instance(payload)\n ConfigurationInstance.new(@version, payload)\n end",
"def instance_by_config(config)\n (config[:klass] || constantize_class_name(config[:class_name])).new(config)\n end",
"def instance_by_config(config)\n klass = config[:klass] || config[:class_name].constantize\n klass.new(config)\n end",
"def initialize(...)\n @metrics = {}\n register(...)\n end",
"def method_missing(group_id, *args, &block)\n\n self.class.send :define_method, group_id do\n\n begin\n value = loadConf(group_id)\n return value\n rescue\n return nil\n end\n\n end\n\n self.send(group_id)\n\n end",
"def gauge_getter(name, metadata)\n klass = metadata[:klass]\n\n define_method(name) do |period = nil, options = {}|\n options, period = period, nil if period.is_a?(Hash) && !options\n options.reverse_merge!(period: period) if period\n options.reverse_merge!(type: metadata[:type])\n options.reverse_merge!(metadata[:options])\n klass.new options.merge(object: self)\n end\n end",
"def initialize\n\n # Set some defaults\n self.auth_location = 'usa'\n self.use_service_net = 'false'\n self.retention_days = 7\n\n config_file = find_config_file\n raise \"Unable to find configuration file\" if config_file.nil?\n\n File.open(config_file, 'r') do |file|\n while (line = file.gets)\n key, value = line.strip.split('=', 2)\n send(:\"#{key}=\", value)\n end\n end\n\n end",
"def instance\n Thread.current[:sauce_configuration] ||= Configuration.new\n end",
"def create_getters\n instance_variables.each do |v|\n define_singleton_method(v.to_s.tr('@','')) do\n instance_variable_get(v)\n end\n end\n end",
"def instance_variable_get(p0) end",
"def load config_file\n YAML.load_file(config_file).each do |parameter,value|\n instance_variable_set( \"@#{parameter}\", value )\n end\n end",
"def define_reflection_methods\n\n # *_class_name, *_class, *_table_name methods for all classes\n @config.classes.to_h.each do |class_type,class_name|\n class_type_name = class_type.to_s.gsub(/_class$/,'').singularize\n class_eval do\n \n # def CLASS_TYPE_class_name\n define_method \"#{class_type_name}_class_name\" do\n if @config.send(class_type).is_a?(Class)\n @config.send(class_type).name\n else\n @config.send(class_type).to_s.camelize\n end\n end\n alias_method \"#{class_type_name.pluralize}_class_name\", \"#{class_type_name}_class_name\"\n \n # def CLASS_TYPE_class\n define_method \"#{class_type_name}_class\" do\n \"::#{send(\"#{class_type_name}_class_name\")}\".constantize\n end\n alias_method \"#{class_type_name.pluralize}_class\", \"#{class_type_name}_class\"\n\n # def CLASS_TYPE_table_name\n define_method \"#{class_type_name}_table_name\" do\n send(\"#{class_type_name}_class\").table_name\n end\n alias_method \"#{class_type_name.pluralize}_table_name\", \"#{class_type_name}_table_name\"\n\n # def CLASS_TYPE_singular_key (used primarily for associations)\n define_method \"#{class_type_name}_singular_key\" do\n send(\"#{class_type_name}_class_name\").underscore.split(\"/\").last.singularize.to_sym\n end\n alias_method \"#{class_type_name.pluralize}_singular_key\", \"#{class_type_name}_singular_key\"\n\n # def CLASS_TYPE_plural_key (use primarily for associations)\n define_method \"#{class_type_name}_plural_key\" do\n send(\"#{class_type_name}_class_name\").underscore.split(\"/\").last.pluralize.to_sym\n end\n alias_method \"#{class_type_name.pluralize}_plural_key\", \"#{class_type_name}_plural_key\"\n \n # These define aliases for custom class names, like user_class and user_table_name aliased to subject_class and subject_table_name\n unless class_type.to_s.underscore == \"#{class_name.to_s.underscore}_class\"\n %w(_class_name _class _table_name _singular_key _plural_key).each do |suffix|\n alias_method \"#{class_name.to_s.underscore.singularize}#{suffix}\", \"#{class_type_name}#{suffix}\"\n alias_method \"#{class_name.to_s.underscore.pluralize}#{suffix}\", \"#{class_name.to_s.underscore.singularize}#{suffix}\"\n end\n end\n \n end\n end\n\n # *_foreign_key method for primary classes\n @config.primary_classes.to_h.each do |class_type,class_name|\n class_type_name = class_type.to_s.gsub(/_class$/,'').singularize\n class_eval do\n # def CLASS_TYPE_foreign_key\n define_method \"#{class_type_name}_foreign_key\" do\n # This is hideous, but we need some sort of fallback for cases like Rails 4 Heroku deploys where the environment and\n # database are not available.\n begin\n \"#{send(\"#{class_type_name}_table_name\").singularize}_#{send(\"#{class_type_name}_class\").primary_key}\"\n rescue\n \"#{send(\"#{class_type_name}_table_name\").singularize}_id\"\n end\n end\n alias_method \"#{class_type.to_s.gsub(/_class$/,\"\").pluralize}_foreign_key\", \"#{class_type.to_s.gsub(/_class$/,\"\").singularize}_foreign_key\"\n \n unless class_type.to_s.underscore == \"#{class_name.to_s.underscore}_class\"\n alias_method \"#{class_name.to_s.underscore.singularize}_foreign_key\", \"#{class_type.to_s.gsub(/_class$/,\"\").singularize}_foreign_key\" # CLASS_NAME_foreign_key\n alias_method \"#{class_name.to_s.underscore.pluralize}_foreign_key\", \"#{class_name.to_s.underscore.singularize}_foreign_key\"\n end\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Searches through the instance variables of the class and creates an attribute accessor on this instance of the Configuration class for each instance variable.
|
def add_attr_accessors_to_self
instance_variables.each do |name|
method_name = name[1..-1].to_sym
MetricFu::Configuration.send(:attr_accessor, method_name)
end
end
|
[
"def populating_attr_accessor(*symbols)\n attr_writer *symbols\n populating_attr_reader *symbols\n end",
"def metadata_accessors\n metamodel_klass.attributes.each do |attribute|\n next if respond_to?(attribute.name)\n\n define_singleton_method(attribute.name) do\n metamodel_store[attribute.name]\n end\n\n define_singleton_method(\"#{attribute.name}=\") do |value|\n metamodel_store[attribute.name] = value\n end\n end\n end",
"def singleton_attr_accessor( *symbols )\n\t\t\tsymbols.each do |sym|\n\t\t\t\tsingleton_class.__send__( :attr_accessor, sym )\n\t\t\tend\n\t\tend",
"def attributes(*args)\n attr_accessor(*args)\n end",
"def generate_attr_accessors\n metadata.keys.each do |attr_name|\n attr_accessor attr_name\n end\n end",
"def class_instance_variables\n field_mirrors(reflectee_send_from_module(:instance_variables))\n end",
"def update_attrs(hashit)\n hashit.instance_variables.each do |name|\n singleton_class.class_eval {attr_accessor \"#{name[1..-1]}\"} #remove leading @ from varname\n send(\"#{name[1..-1]}=\", hashit.instance_variable_get(name))\n end\n end",
"def instance_attr_accessor(base_name)\n i_var_name = to_i_var(base_name)\n getter_signature = to_snake(base_name)\n setter_signature = \"#{getter_signature}=\"\n\n unless respond_to? getter_signature\n define_singleton_method(getter_signature) do\n instance_variable_get(i_var_name)\n end\n end\n\n unless respond_to? setter_signature\n define_singleton_method(setter_signature) do |argument|\n instance_variable_set(i_var_name, argument)\n end\n end\n end",
"def define_accessors\n self.metadata.properties_and_identity.each do |name, _|\n self.model.send :attr_accessor, name.downcase\n end\n end",
"def set_attr_accessors\n @format.each do |key, _|\n define_method(key) {@data[key]}\n define_method(\"%s=\" % key) {|val| @data[key] = val}\n end\n end",
"def class_accessor(*symbols)\r\n class_writer(*symbols)\r\n class_reader(*symbols)\r\n end",
"def make_hash\n variables = self.instance_variables\n attr_hash = {}\n \n variables.each do |var|\n attr_hash[\"#{var.slice(1..-1)}\"] = self.send(\"#{var.slice(1..-1)}\")\n end\n \n attr_hash\n end",
"def templatable_attr (*symbols)\n symbols.each do |symbol|\n # define the instance setter method\n #\n define_method(\"#{symbol}=\".to_sym) do |value|\n instance_variable_set(\"@#{symbol}\", value)\n @@ever_been_set[self][symbol] = true\n end\n\n # define the instance getter method\n #\n define_method(symbol) do \n if @@ever_been_set[self][symbol]\n return instance_variable_get(\"@#{symbol}\")\n elsif self.class.class_variable_defined?(\"@@#{symbol}\")\n return self.class.class_exec { class_variable_get(\"@@#{symbol}\") }\n else\n return nil\n end\n end\n\n class_exec do\n # define the class setter method\n #\n # We have to use this send hack, since define_method is private.\n #\n self.class.send(:define_method, \"#{symbol}=\".to_sym) do |value|\n class_variable_set(\"@@#{symbol}\", value)\n end\n\n # define the class getter/setter method\n #\n # We want to be able to call this like a dsl as a setter, or like a\n # class method as a getter, so we need variable arity, which\n # define_method doesn't support. In order to use the standard `def`\n # with variable arity, eval'ing a string seems to be the only option.\n #\n # Oh man would I love for somebody to submit a patch to do this in a\n # less horrible way.\n #\n self.class.class_eval \"\n def #{symbol} (value = nil)\n if value\n class_variable_set(\\\"@@#{symbol}\\\", value)\n end\n class_variable_get(\\\"@@#{symbol}\\\") if class_variable_defined?(\\\"@@#{symbol}\\\")\n end\n \"\n end\n end\n end",
"def attr_accessor(*args)\n attr_reader(*args)\n attr_writer(*args)\n end",
"def instance_variables() end",
"def set_instance_variables(attributes, data)\n attributes.each do |att|\n instance_variable_set(\n \"@\" + underscore(att),\n traverse_hash(data, att.split('.'))\n )\n end\nend",
"def dsl_attr_setter(*symbols)\n symbols.each do |symbol|\n class_eval do\n CfnDsl.method_names(symbol) do |method|\n define_method(method) do |value|\n instance_variable_set(\"@#{symbol}\", value)\n end\n end\n end\n end\n end",
"def create_getters\n instance_variables.each do |v|\n define_singleton_method(v.to_s.tr('@','')) do\n instance_variable_get(v)\n end\n end\n end",
"def class_variables() end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Add the :stats task to the AVAILABLE_METRICS constant if we're running within rails.
|
def set_metrics
if rails?
@metrics = MetricFu::AVAILABLE_METRICS + [:stats, :rails_best_practices]
else
@metrics = MetricFu::AVAILABLE_METRICS
end
end
|
[
"def tasks_stats\n output_examples_total unless options[:report_only_tasks]\n output_task_totals\n end",
"def metrics\n with_stats_lock do\n @stats_hash.keys.map { |spec| spec.to_s }\n end\n end",
"def register_metrics!\n return if @registered\n @registered = true\n with_instance do |t|\n # Worker related\n t.add_gauge :dynflow_active_workers, 'The number of currently busy workers',\n [:queue, :world]\n t.add_counter :dynflow_worker_events, 'The number of processed events',\n [:queue, :world, :worker]\n\n # Execution plan related\n t.add_gauge :dynflow_active_execution_plans, 'The number of active execution plans',\n [:action, :world, :state]\n t.add_gauge :dynflow_queue_size, 'Number of items in queue',\n [:queue, :world]\n t.add_counter :dynflow_finished_execution_plans, 'The number of execution plans',\n [:action, :world, :result]\n\n # Step related\n # TODO: Configure buckets in a sane manner\n t.add_histogram :dynflow_step_real_time, 'The time between the start end end of the step',\n [:action, :phase]\n t.add_histogram :dynflow_step_execution_time, 'The time spent executing a step',\n [:action, :phase]\n\n # Connector related\n t.add_counter :dynflow_connector_envelopes, 'The number of envelopes handled by a connector',\n [:world, :direction]\n\n # Persistence related\n t.add_histogram :dynflow_persistence, 'The time spent communicating with the database',\n [:world, :method]\n end\n end",
"def application_metrics\n metrics = Danbooru::Metric::Set.new({\n danbooru_info: [:counter, \"Information about the current application build.\"],\n danbooru_artists_total: [:gauge, \"The total number of artists.\"],\n danbooru_artist_urls_total: [:gauge, \"The total number of artist URLs.\"],\n danbooru_artist_versions_total: [:counter, \"The total number of artist versions.\"],\n danbooru_background_jobs_total: [:gauge, \"The total number of background jobs.\"],\n danbooru_bans_total: [:gauge, \"The total number of user bans.\"],\n danbooru_bulk_update_requests_total: [:gauge, \"The total number of bulk update requests.\"],\n danbooru_comments_total: [:gauge, \"The total number of comments.\"],\n danbooru_comment_votes_total: [:gauge, \"The total number of comment votes.\"],\n danbooru_favorites_total: [:gauge, \"The total number of favorites.\"],\n danbooru_favorite_groups_total: [:gauge, \"The total number of favorite groups.\"],\n danbooru_forum_posts_total: [:gauge, \"The total number of forum posts.\"],\n danbooru_forum_topics_total: [:gauge, \"The total number of forum topics.\"],\n danbooru_media_assets_total: [:gauge, \"The total number of media assets. Excludes processing or failed assets.\"],\n danbooru_media_assets_file_size_bytes_total: [:gauge, \"The total file size of all active media assets. Does not include thumbnails.\"],\n danbooru_media_assets_pixels_total: [:gauge, \"The total number of pixels in all active media assets (that is, the sum of width * height for all images). Does not account for animated images.\"],\n danbooru_media_assets_duration_seconds_total: [:gauge, \"The total runtime of all active media assets. Includes videos, animated GIFs and PNGs, and ugoiras.\"],\n danbooru_post_votes_total: [:gauge, \"The total number of post votes.\"],\n danbooru_posts_total: [:gauge, \"The total number of posts.\"],\n danbooru_post_appeals_total: [:gauge, \"The total number of post appeals.\"],\n danbooru_post_flags_total: [:gauge, \"The total number of post flags.\"],\n danbooru_notes_total: [:gauge, \"The total number of notes.\"],\n danbooru_note_versions_total: [:counter, \"The total number of note versions.\"],\n danbooru_pools_total: [:gauge, \"The total number of pools.\"],\n danbooru_pools_post_count_total: [:gauge, \"The total number of posts in pools.\"],\n danbooru_tags_total: [:gauge, \"The total number of tags (excluding empty tags).\"],\n danbooru_tags_post_count_total: [:gauge, \"The total number of tags on posts.\"],\n danbooru_uploads_total: [:gauge, \"The total number of uploads.\"],\n danbooru_users_total: [:counter, \"The total number of users.\"],\n danbooru_user_feedbacks_total: [:gauge, \"The total number of user feedbacks (excluding deleted feedbacks).\"],\n danbooru_wiki_pages_total: [:gauge, \"The total number of wiki pages.\"],\n danbooru_wiki_page_versions_total: [:counter, \"The total number of wiki page versions.\"],\n })\n\n status = ServerStatus.new\n versions = {\n danbooru_version: status.danbooru_version,\n ruby_version: status.ruby_version,\n rails_version: status.rails_version,\n puma_version: status.puma_version,\n distro_version: status.distro_version,\n libvips_version: status.libvips_version,\n ffmpeg_version: status.ffmpeg_version,\n exiftool_version: status.exiftool_version,\n }\n metrics[:danbooru_info][versions].set(1)\n\n Artist.group(:is_deleted).pluck(Arel.sql(\"is_deleted, COUNT(*)\")).each do |deleted, count|\n metrics[:danbooru_artists_total][deleted: deleted].set(count)\n end\n\n ArtistURL.group(:is_active).pluck(Arel.sql(\"is_active, COUNT(*)\")).each do |active, count|\n metrics[:danbooru_artist_urls_total][active: active].set(count)\n end\n\n ArtistVersion.pluck(Arel.sql(\"COUNT(*)\")).each do |count|\n metrics[:danbooru_artist_versions_total].set(count)\n end\n\n metrics[:danbooru_background_jobs_total][status: \"queued\"].set(BackgroundJob.queued.count)\n metrics[:danbooru_background_jobs_total][status: \"running\"].set(BackgroundJob.running.count)\n metrics[:danbooru_background_jobs_total][status: \"finished\"].set(BackgroundJob.finished.count)\n metrics[:danbooru_background_jobs_total][status: \"discarded\"].set(BackgroundJob.discarded.count)\n\n Ban.pluck(Arel.sql(\"COUNT(*)\")).each do |count|\n metrics[:danbooru_bans_total].set(count)\n end\n\n BulkUpdateRequest.group(:status).pluck(Arel.sql(\"status, COUNT(*)\")).each do |status, count|\n metrics[:danbooru_bulk_update_requests_total][status: status].set(count)\n end\n\n Comment.group(:is_deleted).pluck(Arel.sql(\"is_deleted, COUNT(*)\")).each do |deleted, count|\n metrics[:danbooru_comments_total][deleted: deleted].set(count)\n end\n\n CommentVote.group(:score).active.pluck(Arel.sql(\"score, COUNT(*)\")).each do |score, count, score_sum|\n metrics[:danbooru_comment_votes_total][type: score > 0 ? \"up\" : \"down\"].set(count)\n end\n\n FavoriteGroup.group(:is_public).pluck(Arel.sql(\"is_public, COUNT(*)\")).each do |is_public, count|\n metrics[:danbooru_favorite_groups_total][public: is_public].set(count)\n end\n\n ForumPost.group(:is_deleted).pluck(Arel.sql(\"is_deleted, COUNT(*)\")).each do |deleted, count|\n metrics[:danbooru_forum_posts_total][deleted: deleted].set(count)\n end\n\n ForumTopic.group(:is_deleted).pluck(Arel.sql(\"is_deleted, COUNT(*)\")).each do |deleted, count|\n metrics[:danbooru_forum_topics_total][deleted: deleted].set(count)\n end\n\n MediaAsset.active.group(:file_ext).pluck(Arel.sql(\"file_ext, COUNT(*), SUM(file_size), SUM(image_width*image_height), COALESCE(SUM(duration), 0)\")).each do |file_ext, count, file_size, pixels, duration|\n metrics[:danbooru_media_assets_total][file_ext: file_ext].set(count)\n metrics[:danbooru_media_assets_file_size_bytes_total][file_ext: file_ext].set(file_size)\n metrics[:danbooru_media_assets_pixels_total][file_ext: file_ext].set(pixels)\n metrics[:danbooru_media_assets_duration_seconds_total][file_ext: file_ext].set(duration.round(4))\n end\n\n Post.pluck(Arel.sql(\"SUM(up_score), ABS(SUM(down_score)), SUM(fav_count), COUNT(*) FILTER (WHERE is_pending), COUNT(*) FILTER (WHERE is_flagged), COUNT(*) FILTER (WHERE is_deleted), COUNT(*)\")).each do |upvote_count, downvote_count, favorite_count, pending_count, flagged_count, deleted_count, total_count|\n metrics[:danbooru_post_votes_total][type: \"up\"].set(upvote_count)\n metrics[:danbooru_post_votes_total][type: \"down\"].set(downvote_count)\n metrics[:danbooru_favorites_total].set(favorite_count)\n\n metrics[:danbooru_posts_total][status: \"pending\"].set(pending_count)\n metrics[:danbooru_posts_total][status: \"flagged\"].set(flagged_count)\n metrics[:danbooru_posts_total][status: \"deleted\"].set(deleted_count)\n metrics[:danbooru_posts_total][status: \"active\"].set(total_count - pending_count - deleted_count - flagged_count)\n end\n\n PostAppeal.group(:status).pluck(Arel.sql(\"status, COUNT(*)\")).each do |status, count|\n metrics[:danbooru_post_appeals_total][status: status].set(count)\n metrics[:danbooru_posts_total][status: \"appealed\"].set(count) if status == \"pending\"\n end\n\n PostFlag.group(:status).pluck(Arel.sql(\"status, COUNT(*)\")).each do |status, count|\n metrics[:danbooru_post_flags_total][status: status].set(count)\n end\n\n Note.group(:is_active).pluck(Arel.sql(\"is_active, COUNT(*)\")).each do |active, count|\n metrics[:danbooru_notes_total][deleted: !active].set(count)\n end\n\n NoteVersion.pluck(Arel.sql(\"COUNT(*)\")).each do |count|\n metrics[:danbooru_note_versions_total].set(count)\n end\n\n Pool.group(:category).pluck(Arel.sql(\"category, COUNT(*), SUM(cardinality(post_ids))\")).each do |category, count, post_count|\n metrics[:danbooru_pools_total][category: category].set(count)\n metrics[:danbooru_pools_post_count_total][category: category].set(post_count)\n end\n\n Tag.nonempty.group(:category).pluck(Arel.sql(\"category, COUNT(*), SUM(post_count)\")).each do |category, count, post_count|\n metrics[:danbooru_tags_total][category: TagCategory.reverse_mapping[category]].set(count)\n metrics[:danbooru_tags_post_count_total][category: TagCategory.reverse_mapping[category]].set(post_count)\n end\n\n Upload.group(:status).pluck(Arel.sql(\"status, COUNT(*)\")).each do |status, count|\n metrics[:danbooru_uploads_total][status: status].set(count)\n end\n\n User.pluck(Arel.sql(\"COUNT(*)\")).each do |count|\n metrics[:danbooru_users_total].set(count)\n end\n\n UserFeedback.active.group(:category).pluck(Arel.sql(\"category, COUNT(*)\")).each do |category, count|\n metrics[:danbooru_user_feedbacks_total][category: category].set(count)\n end\n\n WikiPage.group(:is_deleted).pluck(Arel.sql(\"is_deleted, COUNT(*)\")).each do |deleted, count|\n metrics[:danbooru_wiki_pages_total][deleted: deleted].set(count)\n end\n\n WikiPageVersion.pluck(Arel.sql(\"COUNT(*)\")).each do |count|\n metrics[:danbooru_wiki_page_versions_total].set(count)\n end\n\n metrics\n end",
"def metrics\n @metrics ||= collect_metrics\n end",
"def runtime_metrics(options = nil)\n settings = get_option(:runtime_metrics)\n return settings if options.nil?\n\n # If options were provided (old style) then raise warnings and apply them:\n # TODO: Raise deprecation warning\n settings.enabled = options[:enabled] if options.key?(:enabled)\n settings.statsd = options[:statsd] if options.key?(:statsd)\n settings\n end",
"def gtm_global_statistics\n super\n end",
"def report_global_metrics\n current_stats = sidekiq_stats.new\n GLOBAL_STATS.each do |stat|\n SidekiqPrometheus[\"sidekiq_#{stat}\"]&.set(current_stats.send(stat), labels: {})\n end\n\n sidekiq_queue.all.each do |queue|\n SidekiqPrometheus[:sidekiq_enqueued]&.set(queue.size, labels: {queue: queue.name})\n SidekiqPrometheus[:sidekiq_queue_latency]&.observe(queue.latency, labels: {queue: queue.name})\n end\n end",
"def report_global_metrics\n current_stats = sidekiq_stats.new\n GLOBAL_STATS.each do |stat|\n SidekiqPrometheus[\"sidekiq_#{stat}\"]&.set(current_stats.send(stat), labels: {})\n end\n\n sidekiq_queue.all.each do |queue|\n SidekiqPrometheus[:sidekiq_enqueued]&.set(queue.size, labels: { queue: queue.name })\n SidekiqPrometheus[:sidekiq_queue_latency]&.observe(queue.latency, labels: { queue: queue.name })\n end\n end",
"def global_statistics\n super\n end",
"def send_agent_stats\n curr_time = Time.now\n\n if curr_time - @last_stat_flush > @stats_interval\n t = Process.times\n # amount of user/system cpu time in seconds\n Hastur.gauge(\"hastur.agent.utime\", t.utime, curr_time)\n Hastur.gauge(\"hastur.agent.stime\", t.stime, curr_time)\n # completed child processes' (plugins) user/system cpu time in seconds (always 0 on Windows NT)\n Hastur.gauge(\"hastur.agent.cutime\", t.cutime, curr_time)\n Hastur.gauge(\"hastur.agent.cstime\", t.cstime, curr_time)\n\n @counters.each do |name,count|\n if count > 0\n Hastur.counter(\"hastur.agent.#{name}\", count, curr_time)\n @counters[name] = 0\n end\n end\n\n # reset things\n @last_stat_flush = curr_time\n end\n end",
"def import_active_stats\n\n end",
"def get_stats\n @hashrate = \"%.2f\" % Share.hashrate\n @active_workers = Worker.recently_active\n end",
"def stats!\n info \"STATS\"\n task \"generate chart\" do\n c = Chart::StatsPerCollection.new\n @dbi.execute( File.read( sql_query(:chart) ) ).each{ |date,collection|\n c.add_one(collection, Date.parse(date).day)\n }\n Chart.new(c).write File.join( @config['settings']['output'], '/chart.jpg' )\n end\n end",
"def runtime_metrics(options = nil)\n runtime_metrics = get_option(:tracer).writer.runtime_metrics\n return runtime_metrics if options.nil?\n\n # TODO: Raise deprecation warning\n runtime_metrics.configure(options)\n end",
"def stats_task\n copy_file 'stats.rake', 'lib/tasks/stats.rake', force: true\n end",
"def global_host_statistics\n super\n end",
"def metrics\n @metrics ||= []\n end",
"def registerStats\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
this method will count all of the a specific trip instance has had. I'm guessing I can use a previous method written. Trips method? will give me an integer back.
|
def trip_count
trips.count
end
|
[
"def trip_count\n trips.count\n end",
"def trip_count\n trips.length\n end",
"def trip_count\n trips = Trip.all.select {|trip_instance| trip_instance.listing == self}.length\n end",
"def count \n trips.length\n end",
"def get_trip_num\n user= User.find(self.id)\n num =(user.trips+user.created_trips).length\n return num\n end",
"def trips\n @analysis[:trips]\n end",
"def active_trains\n data = get_and_parse_json\n data['Trips'].length\n end",
"def trips\n Trip.find_for_rider(@rider_id)\n end",
"def trips_stats \n @all = TripRequest.trips.count\n @completed = TripRequest.trips.completed.count\n @cancelled = TripRequest.trips.cancelled.count\n @pending = TripRequest.trips.pending.count\n @on_going = TripRequest.trips.on_going.count\n @active = TripRequest.trips.active.count\n @response = { all: @all, completed: @completed, cancelled: @cancelled, active: @active, pending: @pending, on_going: @on_going}\n json_response(@response)\n end",
"def driver_trips(trip_array)\n num_trips = {}\n trip_array.each do |trip|\n trip_driver = trip[:driver]\n if !num_trips[trip_driver].nil?\n num_trips[trip_driver] += 1\n else\n num_trips[trip_driver] = 1\n end\n end\n num_trips\nend",
"def num_trips(start,finish,steps,use_weight = false,first_call = false)\n count = 0\n if !use_weight\n if steps == 0\n if start == finish then return 1 else return 0 end\n end\n else\n if steps <= 0 then return 0\n elsif start == finish and steps > 0 and !first_call\n count = count + 1 \n end\n end\n\n start_node = get_node(start)\n\n for edge in get_node_edges(start_node)\n curr_char = edge.to_node.get_elt\n\n # Edge weight considered using use_weight variable.\n # We treat an edge as unit distance 1 otherwise.\n next_steps = (use_weight) ? steps-edge.get_weight : steps-1 \n\n count += num_trips(curr_char,finish,next_steps,use_weight)\n end\n\n return count\n end",
"def flight_segment_tally\n all_flights.length\n end",
"def trips\n Trip.find_for_driver(@driver_id)\n end",
"def sum_triples\n puts \"#Number of Triples\"\n nb_of_triples = 0\n @endpoint_stats.each_key do |k|\n next if k == \"_all\"\n q = \"SELECT COUNT(*) as $nb WHERE { GRAPH <#{URI.encode(k)}> { $s $p $o . }}\"\n new_uri = @sparql_url+\"?query=#{q}&format=json\"\n req = @http.request_get(URI(new_uri))\n res = JSON.parse(req.body)\n res[\"results\"][\"bindings\"].each do |tpl|\n @endpoint_stats[k]['c_triples'] = tpl['nb']['value'].to_i\n nb_of_triples += tpl['nb']['value'].to_i\n puts \"Triples\\t[#{k}]\\t#{tpl['nb']['value']}\"\n end\n end \n @endpoint_stats['_all']['c_triples'] = nb_of_triples\n nb_of_triples\n end",
"def num_trips(start,finish,steps,use_weight = false,first_call = false)\n count = 0\n\n if !use_weight\n if steps == 0\n if start == finish then return 1 else return 0 end\n elsif steps < 0\n return 0\n end\n\n else\n if steps <= 0 then return 0\n elsif start == finish and steps > 0 and !first_call\n count = count + 1 \n end\n end\n\n start_node = get_node(start)\n\n for edge in get_node_edges(start_node)\n curr_char = edge.to_node.get_elt\n\n # Edge weight considered using use_weight variable.\n # We treat an edge as unit distance 1 otherwise.\n next_steps = (use_weight) ? steps-edge.get_weight : steps-1 \n\n count += num_trips(curr_char,finish,next_steps,use_weight)\n end\n\n return count\n end",
"def get_num_of_completed_trips\n return @trips.length - 1 if !@trips.empty? && @trips.last.is_in_progress?\n return @trips.length\n end",
"def trips\n get '/gtfs/trips'\n end",
"def count_restaurants\n end",
"def flight_segment_tally\n flights.length\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Specifies the answers to be referred to by the given labels. These labels must match the labels given to Machinesend. def process_answers ary1 = [] ary2 = [] answers.each do |a| ... end label group1: ary1 label group2: ary2 end Use this method inside a process block or inside a Machineprocess_answers method definition.
|
def label (hash)
@labeled_answers.merge! hash
end
|
[
"def answers_labels\n @answer_group && EvaluationAnswerGroup.find(@answer_group).labels\n end",
"def labels\n @answers.collect{|x| x.is_a?(Array) ? x.first : x}\n end",
"def labels(values)\n values.reduce({}) do |labels,value|\n labels[value] = (label_proc || DEFAULT_LABEL_PROC).call(value)\n labels\n end\n end",
"def process_reverse_labeling\n removed = labels_to_remove\n added = labels_to_add\n\n @labels_to_remove = added\n @labels_to_add = removed\n\n process_labeling\n end",
"def find_labels\n @input.each_with_index do |line, i|\n if line.label?(i)\n label = line.split(\":\")[0]\n if !@labels.include?(label)\n @labels[label] = [*@instructions.each_with_index].search{|x, _| x >= i}.last\n else\n Error::message(7, i+1, line) \n end\n end\n end\n end",
"def set_labels\n if labels_as_list.present?\n self.labels = labels_as_list.split(\"\\n\").map(&:strip).reject(&:empty?)\n end\n end",
"def answers=(value)\n @answers = value\n end",
"def labels=(value)\n @labels = value\n end",
"def process_data(df, labels)\n case labels.length\n when 1\n label = labels[0]\n value(label)\n @xrange = df[label].to_a.uniq\n @yrange = [0, df[label].to_a.length]\n when 2\n label_x = labels[0]\n label_y = labels[1]\n x(label_x)\n y(label_y)\n @xrange = df.column(label_x).to_a\n @yrange = [(df[label_y].to_a.min < 0 ? df[label_y].to_a.min : 0), df[label_y].to_a.max]\n end\n end",
"def answers\n @answer_group && EvaluationAnswerGroup.find(@answer_group).answers\n end",
"def parse_answers(result)\n parse_type(result, \"answer\")\n end",
"def answers\n @answers ||= {}\n end",
"def answer question\n\n # find the value that should be entered\n data = request[question[:reference_identifier]]\n\n response_set.responses.where(question_id: question).delete_all\n\n case question.type\n\n when :none\n answer = question.answers.first\n response_set.responses.create({\n answer: answer,\n question: question,\n answer.value_key => data\n })\n\n when :one\n # the value is the reference identifier of the target answer\n answer = question.answers.where(reference_identifier: data).first\n\n unless answer.nil?\n response_set.responses.create({\n answer: answer,\n question: question\n })\n end\n\n when :any\n # the value is an array of the chosen answers\n answers = question.answers.where(reference_identifier: data)\n answers.each do |answer|\n response_set.responses.create({\n answer: answer,\n question: question\n })\n end\n\n when :repeater\n # the value is an array of answers\n answer = question.answers.first\n i = 0\n data.each do |value|\n response_set.responses.create({\n answer: answer,\n question: question,\n answer.value_key => value,\n response_group: i\n })\n i += 1\n end\n\n else\n throw \"not handled> #{question.inspect}\"\n end\n\n end",
"def set_labels(hash, labels)\n labels = [labels] unless labels.is_a? Array\n @server.call('d.set_custom1', hash, labels.join(', '))\n self.torrents[hash].labels = labels\n end",
"def format_answers(answers)\n answers.select { |k, v| v.delete(\"label\") }\n end",
"def agent_human_labels label,&block\n @label=label\n @instance_label_proc=block\n end",
"def process_adding_labels\n label_issue(labels_to_add) unless labels_to_add.empty?\n end",
"def evaluate_answers\n self.answers.each do |a|\n q = a.question\n a.correct = (a.answer_mask == q.answer_mask)\n a.save(:validate=>false)\n end\n end",
"def answers\n [].tap do |a|\n a << teaching_maths_or_physics\n a << current_school\n a << initial_teacher_training_subject\n a << initial_teacher_training_subject_specialism if eligibility.initial_teacher_training_subject_specialism.present?\n a << has_uk_maths_or_physics_degree if eligibility.has_uk_maths_or_physics_degree.present?\n a << qts_award_year\n a << employed_as_supply_teacher\n a << has_entire_term_contract if eligibility.employed_as_supply_teacher?\n a << employed_directly if eligibility.employed_as_supply_teacher?\n a << disciplinary_action\n a << formal_performance_action\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns a hash of the answers currently at this machine, keyed by language
|
def answers_keyed_by_language
hash = Hash.new {|h,k| h[k] = [] }
answers.each {|answer| hash[answer.language] << answer }
hash
end
|
[
"def answers\n @answers ||= {}\n end",
"def language_hash\n HashWithIndifferentAccess.new(PrismicRails.config.languages)\n end",
"def keyword_hash(lang=@lang)\n LANGUAGES[lang]\n end",
"def user_languages_hash\n result = Hash.new\n\n I18n.available_locales.each do |locale|\n result[t(\"languages.#{locale.to_s}\")] = locale.to_s\n end\n \n return result\n end",
"def key_lang\n if @is_result\n @lang[0, @lang.length - RESULT_SUFFIX_LENGTH]\n else\n @lang\n end\n end",
"def language_dist\n @languages = Hash.new(0)\n @repos.each do |repo|\n @languages[repo.language] += 1\n end\n end",
"def answer_dictionary (profile)\n\tanswers = {}\n\tprofile['answers'].each do |answer|\n \t\tanswers[answer['questionId'].to_s] = answer\n \tend\n \tanswers\nend",
"def answer_keys\n [key]\n end",
"def hash(algorithm)\n hashes[algorithm]\n end",
"def languages\n unless @languages_cache\n response = call_request(:get_languages)\n\n languages = response.to_hash[:get_languages_response][:return][:item][1][:value][:item]\n # Create a sorted hash\n @languages_cache = Hash[create_dict(languages).sort_by{|k,v| k.to_i}]\n end\n return @languages_cache\n end",
"def abbreviations\n answers_hash.keys\n end",
"def loaded_languages\n @@cached_language_data.keys\n end",
"def loaded_languages\n @@languages.keys\n end",
"def questions_hash\n questions = {}\n\n Question.where(:id => question_ids).find_each do |question|\n questions[question.id] = question\n end\n\n questions\n end",
"def language_stats(query='the')\n movies = Hash.new\n movie_count = Hash.new [] # key is imdbid\n\n langs = LANGUAGES.reverse\n langs.each do |language|\n q = {'sublanguageid' => language.to_s, 'query' => query}\n movies_data = search(q)['data']\n if not movies_data\n warn \"error finding movies in #{language}\"\n next\n end\n\n\n movies_data.each do |m|\n if not movies[m['IDMovieImdb']] # keep the first match\n movies[m['IDMovieImdb']] = m['MovieName']\n end\n end\n\n ids = Set.new(movies_data.map {|m| m['IDMovieImdb']}.uniq!)\n ids.each do |id|\n movie_count[id] = movie_count[id] + [language]\n end\n\n puts \"checked #{language} (#{ids.size})\"\n end\n\n count = movie_count.to_a\n count.sort! { |a, b| b[1].size <=> a[1].size }\n count[0..20].each do |id, langs|\n puts \"#{langs.size} => #{id}: #{movies[id]}\"\n puts (LANGUAGES - langs).join(\" \")\n end\n\n #movies.values.each {|name| puts name}\n end",
"def langs(m)\r\n m.safe_reply \"Available languages: #{Evalso.languages.keys.join(', ')}\"\r\n end",
"def simhash\n @simhash ||= matcher.simhash(ngrams)\n end",
"def accepted_keys(lang)\n self.keys.translated(lang)\n end",
"def hash\n hash = 17\n hash = 37 * hash + @prob.hash\n hash = 37 * hash + @alias.hash\n hash = 37 * hash + @values.hash\n hash\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns a new answer with the given blueprint and parents. def process_answers answers.each do |a| ary1 << make_answer(a.blueprint, a) ary2 << make_answer(a.blueprint.reverse, a) end label group1: ary1 label group2: ary2 end Use this method inside a process block or inside a Machineprocess_answers method definition.
|
def make_answer (blueprint, *parents)
parent_ids = parents.collect {|answer| answer.id }
Answer.new(nil, blueprint, @location, @location, parent_ids, Factory.cycle, nil)
end
|
[
"def ensure_answers\n self.answers ||= []\n (questioning.level_count || 1).times.each do |i|\n rank = (questioning.level_count || 1) > 1 ? i + 1 : nil\n answers[i] ||= Answer.new(questioning: questioning, rank: rank)\n end\n end",
"def build_prerequisite_answers\n existing_answers = prerequisite_answers.index_by(&:prerequisite_id)\n course.prerequisites.each do |p|\n next if existing_answers.has_key? p.id\n prerequisite_answers.build prerequisite: p\n end\n prerequisite_answers\n end",
"def build_answer(answer_node)\n # A survey must either be passed or already present in self.node_maps\n if survey.nil?\n raise ArgumentError, 'A survey must be passed if ActiveRecordSurvey::Node::Question is not yet added to a survey'\n end\n\n # Cannot mix answer types\n # Check if not match existing - throw error\n unless answers.reject do |answer|\n answer.class == answer_node.class\n end.empty?\n raise ArgumentError, 'Cannot mix answer types on question'\n end\n\n # Answers actually define how they're built off the parent node\n return unless answer_node.send(:build_answer, self)\n\n # If any questions existed directly following this question, insert after this answer\n survey.node_maps.select do |i|\n i.node == answer_node && !i.marked_for_destruction?\n end.each do |answer_node_map|\n survey.node_maps.select do |j|\n # Same parent\n # Is a question\n !j.marked_for_destruction? &&\n j.parent == answer_node_map.parent && j.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n end.each do |j|\n answer_node_map.survey = survey\n j.survey = survey\n\n answer_node_map.children << j\n end\n end\n\n answers.last\n end",
"def export_answers \n answers = Array.new\n self.responses.each do |r|\n r.answers.each do |a|\n answers << a\n end\n end\n answers\n end",
"def setup_answers\n create :answer, question: @question1, response_id: @response.id, answer: 1, comments: 'True_1'\n create :answer, question: @question2, response_id: @response.id, answer: 0, comments: 'False_2'\n create :answer, question: @question3, response_id: @response.id, answer: 0, comments: 'Answer2_3'\n create :answer, question: @question4, response_id: @response.id, answer: 1, comments: 'Answer1_4'\n create :answer, question: @question4, response_id: @response.id, answer: 1, comments: 'Answer3_4'\nend",
"def build_answer(question_node)\n\t\t\t\t\tself.survey = question_node.survey\n\n\t\t\t\t\tquestion_node_maps = self.survey.node_maps.select { |i|\n\t\t\t\t\t\ti.node == question_node && !i.marked_for_destruction?\n\t\t\t\t\t}\n\n\t\t\t\t\tanswer_node_maps = self.survey.node_maps.select { |i|\n\t\t\t\t\t\ti.node == self && i.parent.nil? && !i.marked_for_destruction?\n\t\t\t\t\t}.collect { |i|\n\t\t\t\t\t\ti.survey = self.survey\n\n\t\t\t\t\t\ti\n\t\t\t\t\t}\n\n\t\t\t\t\t# No node_maps exist yet from this question\n\t\t\t\t\tif question_node_maps.length === 0\n\t\t\t\t\t\t# Build our first node-map\n\t\t\t\t\t\tquestion_node_maps << self.survey.node_maps.build(:node => question_node, :survey => self.survey)\n\t\t\t\t\tend\n\n\t\t\t\t\tlast_answer_in_chain = (question_node.answers.last || question_node)\n\n\t\t\t\t\t# Each instance of this question needs the answer hung from it\n\t\t\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\t\t\ti.node == last_answer_in_chain && !i.marked_for_destruction?\n\t\t\t\t\t}.each_with_index { |node_map, index|\n\t\t\t\t\t\tif answer_node_maps[index]\n\t\t\t\t\t\t\tnew_node_map = answer_node_maps[index]\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tnew_node_map = self.survey.node_maps.build(:node => self, :survey => self.survey)\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\t# Hack - should fix this - why does self.survey.node_maps still think... yea somethigns not referenced right\n\t\t\t\t\t\t#curr_children = self.survey.node_maps.select { |j|\n\t\t\t\t\t\t#\tnode_map.children.include?(j) && j != new_node_map\n\t\t\t\t\t\t#}\n\n\t\t\t\t\t\tnode_map.children << new_node_map\n\n\t\t\t\t\t\t#curr_children.each { |c|\n\t\t\t\t\t\t#\tnew_node_map.children << c\n\t\t\t\t\t\t#}\n\t\t\t\t\t}\n\n\t\t\t\t\ttrue\n\t\t\t\tend",
"def answer question\n\n # find the value that should be entered\n data = request[question[:reference_identifier]]\n\n response_set.responses.where(question_id: question).delete_all\n\n case question.type\n\n when :none\n answer = question.answers.first\n response_set.responses.create({\n answer: answer,\n question: question,\n answer.value_key => data\n })\n\n when :one\n # the value is the reference identifier of the target answer\n answer = question.answers.where(reference_identifier: data).first\n\n unless answer.nil?\n response_set.responses.create({\n answer: answer,\n question: question\n })\n end\n\n when :any\n # the value is an array of the chosen answers\n answers = question.answers.where(reference_identifier: data)\n answers.each do |answer|\n response_set.responses.create({\n answer: answer,\n question: question\n })\n end\n\n when :repeater\n # the value is an array of answers\n answer = question.answers.first\n i = 0\n data.each do |value|\n response_set.responses.create({\n answer: answer,\n question: question,\n answer.value_key => value,\n response_group: i\n })\n i += 1\n end\n\n else\n throw \"not handled> #{question.inspect}\"\n end\n\n end",
"def response_to_questions\n opts[:questions].each do |response|\n @obj.response_questions.build(\n question_id: response[:id],\n question: response[:question],\n answer: response[:answer],\n default_question: response[:default_question]\n )\n end\n end",
"def add_responses(form_input: nil)\n @data.each do |data|\n data[:survey_responses] = data[:survey_questions].map do |question|\n value = form_input ? form_input[question.id.to_s] : nil\n\n question.responses.new(\n user_id: @user.id,\n value: value\n )\n end\n end\n end",
"def descendant_questionings(nodes = nil)\n nodes ||= arrange_descendants\n nodes.map do |form_item, children|\n form_item.is_a?(Questioning) ? form_item : descendant_questionings(children)\n end\n end",
"def dup_question_set_and_save\n parent_q = self\n section_q = parent_q.conditions.first.rule.question\n children_qs = section_q.children\n start_sort_order = 10000\n increment_sort_by = 2\n unless children_qs.blank?\n start_sort_order = children_qs.last.sort_order\n # number of new children questions + condition (parent) and children (rule) questions\n increment_sort_by = children_qs.count + 2\n else\n start_sort_order = section_q.sort_order\n end\n\n # remap sort orders leaving space for new questions before saving new question\n parent_q.survey_template.questions.where(\"sort_order > ?\", start_sort_order).each do |q|\n q.sort_order = q.sort_order + increment_sort_by\n q.save\n end\n\n # this will create new question, answer choices and conditions,\n # but the conditions will be pointed to the old rule which we will need to remap\n new_parent_q = parent_q.amoeba_dup\n # now that we have resorted save new_parent_q into open slot\n new_parent_q.sort_order = new_parent_q.sort_order + increment_sort_by\n new_parent_q.save\n\n # this will duplicate the question, will need to create a new rule,\n # and then set the condtions to new rule id\n new_section_q = section_q.amoeba_dup\n new_section_q.sort_order = new_section_q.sort_order + increment_sort_by\n new_section_q.save\n\n # update newly created conditions with rule relationship now that the rule has been created\n # the rule gets created with the section question\n new_rule = new_section_q.rule\n new_parent_q.conditions.each do |c|\n c.rule_id = new_rule.id\n c.save\n end\n\n children_qs.each do |q|\n new_child_q = q.amoeba_dup\n # update ancestry relationship\n new_child_q.parent = new_section_q\n\n # set sort_order\n new_child_q.sort_order = new_child_q.sort_order + increment_sort_by\n new_child_q.save\n end\n end",
"def build_answers\n ActiveRecord::Base.transaction do\n yield\n find_or_create_answers.each do |answer_type, answer_records|\n send(\"#{ answer_type }=\", answer_records)\n end\n raise ActiveRecord::RecordInvalid unless valid?\n end\n end",
"def recreate_current_answers\n current_answers.reject(&:attempting?).each do |current_answer|\n new_answer = current_answer.question.attempt(current_answer.submission, current_answer)\n\n current_answer.current_answer = false\n new_answer.current_answer = true\n # Validations are disabled as we are only updating the current_answer flag and nothing else.\n # There are other answer validations, one example is validate_grade which will make\n # check if the grade of the answer exceeds the maximum grade. In case the maximum grade is reduced\n # but the user keeps the grade unchanged, the validation will fail.\n current_answer.save(validate: false)\n new_answer.save!\n end\n end",
"def answer_hiera\n # Render pretty JSON, because it is a subset of HOCON\n json = JSON.pretty_generate(answers)\n hocon = Hocon::Parser::ConfigDocumentFactory.parse_string(json)\n hocon.render\n end",
"def answers\n return nil if self.operations.count < 1\n @answers ||= self.operations.inject([]){|s,e| s << e.answer}\n end",
"def init_answers(questions)\n questions.each do |q|\n # it's unlikely that these answers exist, but in case the user refresh the browser some might have been inserted.\n answer = Answer.where(response_id: @response.id, question_id: q.id).first\n if answer.nil?\n Answer.create(response_id: @response.id, question_id: q.id, answer: nil, comments: '')\n end\n end\n end",
"def answers\n extracted_answers = []\n\n unless self.qp_values.nil?\n self.qp_values.each do |answer| \n extracted_answers.push(ResponseAnswer.new(answer))\n end \n end\n\n return extracted_answers \n end",
"def answers\n object.answers.collect do |a|\n {\n id: a.id,\n user_id: a.user_id,\n alternative_id: a.alternative_id\n }\n end\n end",
"def build_answer(question_node)\n self.survey = question_node.survey\n\n answer_node_maps = survey.node_maps.select do |i|\n i.node == self && i.parent.nil?\n end.collect do |i|\n i.survey = survey\n\n i\n end\n\n question_node_maps = survey.node_maps.select { |i| i.node == question_node && !i.marked_for_destruction? }\n\n # No node_maps exist yet from this question\n if question_node_maps.length === 0\n # Build our first node-map\n question_node_maps << survey.node_maps.build(node: question_node, survey: survey)\n end\n\n # Each instance of this question needs the answer hung from it\n question_node_maps.each_with_index do |question_node_map, index|\n new_node_map = answer_node_maps[index] || survey.node_maps.build(node: self, survey: survey)\n\n question_node_map.children << new_node_map\n end\n\n true\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns the number of answers currently at this machine without forcing the answers to load. def process_answers if answer_count > 500 ... end label group1: ary1 end Use this method inside a process block or inside a Machineprocess_answers method definition.
|
def answer_count
return @answers.length if @answers
Factory.count_answers_at_machine(@location)
end
|
[
"def answers_count\n self.answer_sets.size\n end",
"def answer_count\n if is_standard?\n respond_to?(:copy_answer_count_col) ? copy_answer_count_col || 0 : copies.inject?(0){|sum, c| sum += c.answer_count}\n else\n respond_to?(:answer_count_col) ? answer_count_col || 0 : questionings.inject(0){|sum, q| sum += q.answers.count}\n end\n end",
"def answers_with_count\n count=Hash.new(0)\n self.list_answers.each {|a| count[a]+=1 }\n count\n end",
"def number_of_responses_from(reader)\n answers.merge(reader.answers).group(:question_id).count(:question_id)\n .values.min || 0\n end",
"def answer_count\n if is_standard?\n respond_to?(:copy_answer_count_col) ? copy_answer_count_col : copies.inject(0){|sum,c| sum += c.answer_count}\n else\n respond_to?(:answer_count_col) ? answer_count_col : answers.count\n end\n end",
"def results_n_plus_one\n answer_choices.each_with_object(Hash.new(0)) do |choice, h|\n # n queries here for responses\n h[choice.text] = choice.responses.count\n end\n end",
"def find_number_of_responses(question)\n empty_response_character=''\n case question.question_type.q_type\n when \"TextBox\", \"TextArea\", \"Rating\" # For ratings, we count responses for comments instead of dropdown\n empty_response_character=''\n when \"DropDown\"\n empty_response_character= @questionnaire.min_question_score\n end\n response_count=Answer.find_by_sql([\"SELECT * FROM answers s, responses r, response_maps rm WHERE s.response_id=r.id AND r.map_id= rm.id AND rm.reviewed_object_id=? AND rm.reviewee_id=? AND s.comments != ? AND s.question_id=?\", @map.reviewed_object_id, @map.reviewee_id, empty_response_character, question.id]).count\n response_count\n end",
"def question_count\n return people.first.answered.size if people.length == 1\n\n people_answering = people.length\n questions = Hash.new 0\n people.each do |person|\n person.answered.each do |char|\n questions[char] += 1\n end\n end\n\n count = 0\n questions.each do |_, value|\n count += 1 if value == people_answering\n end\n count\n end",
"def answer_total\n count = 0\n self.list_answers.each {|a| count +=a.to_i }\n count\n end",
"def answers_completed\n answers_completed = 0\n answers_completed = answers_completed + 1 if self.answer and !self.answer.empty?\n answers_completed = answers_completed + 1 if self.answer2 and !self.answer2.empty?\n answers_completed = answers_completed + 1 if self.answer3 and !self.answer3.empty?\n answers_completed = answers_completed + 1 if self.answer4 and !self.answer4.empty?\n answers_completed = answers_completed + 1 if self.answer5 and !self.answer5.empty?\n answers_completed = answers_completed + 1 if self.answer6 and !self.answer6.empty?\n answers_completed = answers_completed + 1 if self.answer7 and !self.answer7.empty?\n \n answers_completed\n end",
"def response_count\n return @response_count if defined? @response_count\n @response_count ||= if data_empty?\n 0\n else\n related_data.map {|q, r_h|\n r_h.count{|v| !v.to_s.empty? }\n }.each_slice(2).map{|a| a.first}.sum\n end\n end",
"def count_results(answer)\n answer.split(\" \")[1].to_i\n end",
"def number_of_correct_answers_to_create\n number = 0\n @base_data[:answers].each { |answer| number += 1 if answer.correct }\n number == 0 ? 0 : (number * GENERAL_VARIATIONS.sample).floor\n end",
"def answerNum(userQuestion)\n answers = userQuestion.getInput.getCurrentChoices\n if answers == nil || answers.size < 1\n return []\n else\n return getChoiceNum(userQuestion.getInput.getChoices, answers)\n end\n end",
"def number_of_questions\n questions.count\n end",
"def update_answer_count\n\t\tc = 0\n\t\tc = c + changes[:yes_count][1] - changes[:yes_count][0] if yes_count_changed?\n\t\tc = c + changes[:no_count][1] - changes[:no_count][0] if no_count_changed?\n\t\tc = c + changes[:dont_care_count][1] - changes[:dont_care_count][0] if dont_care_count_changed?\n\t\tself.answer_count = self.answer_count + c\n\tend",
"def count_group_responses(questions)\n questions.map{|q| responses.select{|r| (r.question_id.to_i == q.id.to_i) && !r.response_group.nil?}.group_by(&:response_group).size }.max\n end",
"def has_answers?\n answer_count > 0\n end",
"def find_number_of_responses_for_checkbox(checkbox_questions)\n question_ids = []\n checkbox_questions.each do |checkbox_question|\n question_ids << checkbox_question.id\n end\n response_count = Answer.find_by_sql([\"SELECT * FROM answers s, responses r, response_maps rm WHERE s.response_id=r.id AND r.map_id= rm.id AND rm.reviewed_object_id=? AND rm.reviewee_id=? AND s.comments != '0' AND s.question_id IN (?) GROUP BY r.map_id\", @map.reviewed_object_id, @map.reviewee_id, question_ids]).count\n response_count\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PATCH/PUT /pricetypes/1 PATCH/PUT /pricetypes/1.json
|
def update
respond_to do |format|
if @pricetype.update(pricetype_params)
format.html { redirect_to @pricetype, notice: 'Pricetype was successfully updated.' }
format.json { render :show, status: :ok, location: @pricetype }
else
format.html { render :edit }
format.json { render json: @pricetype.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update\n respond_to do |format|\n if @patch_type.update(patch_type_params)\n format.html { redirect_to admin_patch_types_path, notice: 'Patch type was successfully updated.' }\n format.json { render :index, status: :ok, location: @patch_type }\n else\n format.html { render :edit }\n format.json { render json: @patch_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch_entity_type(entity_type_id, request)\n start.uri('/api/entity/type')\n .url_segment(entity_type_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .patch()\n .go()\n end",
"def update\n respond_to do |format|\n if @poa_type.update(poa_type_params)\n format.html { redirect_to @poa_type, notice: 'Poa type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @poa_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @type = Type.find(params[:id])\n\n respond_to do |format|\n if @type.update_attributes(params[:type])\n format.html { redirect_to types_path, notice: 'Type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @perf_type.update(perf_type_params)\n format.html { redirect_to @perf_type, notice: 'Perf type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @perf_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @service_type.update(service_type_params)\n format.json { head :no_content }\n else\n format.json { render json: @service_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @type = Type.find(params[:id])\n\n respond_to do |format|\n if @type.update_attributes(params[:type])\n format.html { redirect_to @type, notice: 'Type was successfully updated!' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n json_update(factType,factType_params, FactType)\n end",
"def update\n respond_to do |format|\n if @pull_type.update(pull_type_params)\n format.html { redirect_to pull_types_path, notice: 'Pull type was successfully updated.' }\n format.json { render :show, status: :ok, location: @pull_type }\n else\n format.html { render :edit }\n format.json { render json: @pull_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @change_type.update(change_type_params)\n format.html { redirect_to @change_type, notice: 'Change type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @change_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @pit_type.update(pit_type_params)\n format.html { redirect_to @pit_type, notice: 'Pit type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @pit_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @ptype = Ptype.find(params[:id])\n\n respond_to do |format|\n if @ptype.update_attributes(params[:ptype])\n format.html { redirect_to(ptypes_url, :notice => 'Property type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @ptype.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @polish_type.update(polish_type_params)\n format.html { redirect_to @polish_type, notice: 'Polish type was successfully updated.' }\n format.json { render :show, status: :ok, location: @polish_type }\n else\n format.html { render :edit }\n format.json { render json: @polish_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @pool_type.update(pool_type_params)\n format.html { redirect_to @pool_type, notice: 'Pool type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @pool_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @generic_type.update(generic_type_params)\n format.html { redirect_to @generic_type, notice: 'Generic type was successfully updated.' }\n format.json { render :show, status: :ok, location: @generic_type }\n else\n format.html { render :edit }\n format.json { render json: @generic_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @spec_type.update(spec_type_params)\n format.html { redirect_to @spec_type, notice: 'Spec type was successfully updated.' }\n format.json { render :show, status: :ok, location: @spec_type }\n else\n format.html { render :edit }\n format.json { render json: @spec_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @novelty_type.update(novelty_type_params)\n format.html { redirect_to @novelty_type, notice: 'Novelty type was successfully updated.' }\n format.json { render :show, status: :ok, location: @novelty_type }\n else\n format.html { render :edit }\n format.json { render json: @novelty_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @specimen_type.update(specimen_type_params)\n format.html { redirect_to @specimen_type, notice: 'Specimen type was successfully updated.' }\n format.json { render :show, status: :ok, location: @specimen_type }\n else\n format.html { render :edit }\n format.json { render json: @specimen_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @optype.update(optype_params)\n format.html { redirect_to @optype, notice: 'Optype was successfully updated.' }\n format.json { render :show, status: :ok, location: @optype }\n else\n format.html { render :edit }\n format.json { render json: @optype.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /pricetypes/1 DELETE /pricetypes/1.json
|
def destroy
@pricetype.destroy
respond_to do |format|
format.html { redirect_to pricetypes_url, notice: 'Pricetype was successfully destroyed.' }
format.json { head :no_content }
end
end
|
[
"def destroy\n @perf_type.destroy\n respond_to do |format|\n format.html { redirect_to perf_types_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @type = Type.find(params[:id])\n @type.destroy\n\n respond_to do |format|\n format.html { redirect_to types_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @poa_type.destroy\n respond_to do |format|\n format.html { redirect_to poa_types_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @poketype.destroy\n respond_to do |format|\n format.html { redirect_to poketypes_url, notice: 'Poketype was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @dishtype.destroy\n respond_to do |format|\n format.html { redirect_to dishtypes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @pit_type.destroy\n respond_to do |format|\n format.html { redirect_to pit_types_url }\n format.json { head :no_content }\n end\n end",
"def delete_type(id)\n delete(\"/types/#{id}\")\n end",
"def destroy\n @ot_type = OtType.find(params[:id])\n @ot_type.destroy\n\n respond_to do |format|\n format.html { redirect_to ot_types_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @devicetype = Devicetype.find(params[:id])\n @devicetype.destroy\n\n respond_to do |format|\n format.html { redirect_to devicetypes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @c_type.destroy\n respond_to do |format|\n format.html { redirect_to c_types_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @generic_type.destroy\n respond_to do |format|\n format.html { redirect_to generic_types_url, notice: 'Generic type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @t_type.destroy\n respond_to do |format|\n format.html { redirect_to t_types_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @pcr_type.destroy\n respond_to do |format|\n format.html { redirect_to pcr_types_url, notice: \"Pcr type was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @realty_type = RealtyType.find(params[:id])\n @realty_type.destroy\n\n respond_to do |format|\n format.html { redirect_to realty_types_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ptype = Ptype.find(params[:id])\n @ptype.destroy\n\n respond_to do |format|\n format.html { redirect_to(ptypes_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @performance_type = PerformanceType.find(params[:id])\n @performance_type.destroy\n\n respond_to do |format|\n format.html { redirect_to performance_types_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @expensetype = Expensetype.find(params[:id])\n @expensetype.destroy\n\n respond_to do |format|\n format.html { redirect_to expensetypes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @api_v1_admin_type.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_admin_types_url, notice: 'Admin type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @appeal_type.destroy\n respond_to do |format|\n format.html { redirect_to appeal_types_url, notice: 'Обращение было успешно удалено.' }\n format.json { head :no_content }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Wraps the deep_cloneable gem deep_clone method to allow using the predefined associations and options from our Cloneable.acts_as_cloneable macro.
|
def deep_clone!(options = {})
processed_options = Para::Cloneable::IncludeTreeBuilder.new(self, cloneable_options).build
options = options.reverse_merge(processed_options)
callback = build_clone_callback(options.delete(:prepare))
deep_clone(options) do |original, clone|
Para::Cloneable::AttachmentsCloner.new(original, clone).clone!
callback&.call(original, clone)
end
end
|
[
"def deep_clone!(options = {})\n dictionary = options[:dictionary] ||= {}\n\n processed_options = Para::Cloneable::IncludeTreeBuilder.new(self).build\n options = options.reverse_merge(processed_options)\n callback = build_clone_callback(options.delete(:prepare))\n\n deep_clone(options) do |original, clone|\n Para::Cloneable::AttachmentsCloner.new(original, clone, dictionary).clone!\n callback&.call(original, clone)\n end\n end",
"def deep_clone\n bi = dup\n bi.save\n feature_selections.each { |fs| bi.feature_selections << fs.dup }\n bi\n end",
"def deep_clone\n cl = clone()\n each do |child|\n if child.kind_of? Parent\n cl << child.deep_clone\n else\n cl << child.clone\n end\n end\n cl\n end",
"def update_cloneable_associations\n associations_for_cloning.each do |association|\n type = @klass.reflect_on_association(association)\n through_record = type.through_reflection\n\n if through_record.present?\n clone_join_relationships(through_record.plural_name)\n else\n clone_has_one_relationship(association,type) if type.macro == :has_one\n clone_has_many_relationships(association) if type.macro == :has_many\n end\n end\n end",
"def deep_clone(object)\n Marshal.load(Marshal.dump(object))\n end",
"def deep_clone(object)\n # TODO: too expensive?\n Marshal.load(Marshal.dump(object))\n end",
"def clone_for_recursion(child, association)\n self.class.new(\n # replication mode\n :mode => mode,\n\n # the new src_obj is of course the child\n :src_obj => child,\n\n # these stay the same\n :dest_mission => dest_mission,\n :deep_copy => deep_copy,\n :retain_link_on_promote => retain_link_on_promote,\n\n # this is always true since we go into a transaction first thing\n :in_transaction => true,\n\n # the current_assoc is the name of the association that is currently being replicated\n :current_assoc => association,\n\n # add the new copy to the list of copy parents\n :ancestors => ancestors + [dest_obj],\n\n # recursed always is true since we're recursing here\n :recursed => true\n )\n end",
"def clone_for_recursion(child, association)\n self.class.new(\n # the new src_obj is of course the child\n :src_obj => child,\n\n # these stay the same\n :to_mission => to_mission,\n :deep_copy => deep_copy,\n\n # this is always true since we go into a transaction first thing\n :in_transaction => true,\n\n # the current_assoc is the name of the association that is currently being replicated\n :current_assoc => association,\n\n # add the new copy to the list of copy parents\n :ancestors => ancestors + [dest_obj],\n\n # recursed always is true since we're recursing here\n :recursed => true\n )\n end",
"def revision_cloned_associations #:nodoc:\n clone_associations = self.revisable_options.clone_associations\n\n self.revisable_cloned_associations ||= \\\n if clone_associations.blank?\n []\n elsif clone_associations.eql? :all\n revisable_class.reflect_on_all_associations.map(&:name)\n elsif clone_associations.is_a? [].class\n clone_associations\n elsif clone_associations[:only]\n [clone_associations[:only]].flatten\n elsif clone_associations[:except]\n revisable_class.reflect_on_all_associations.map(&:name) - [clone_associations[:except]].flatten\n end\n end",
"def deep_clone\n copy = self.clone\n copy.company_info = self.company_info.clone\n copy.partner_info = self.partner_info.clone\n copy.admin_info = self.admin_info.clone\n copy.credit_card = self.credit_card.clone\n copy.account_detail = self.account_detail.clone\n copy.order_summary = self.order_summary.clone\n copy.billing_info = self.billing_info.clone\n copy.billing_info.billing = self.billing_info.billing.clone\n copy\n end",
"def cloneNode(deep = true)\n super(deep, @name)\n end",
"def full_clone(_arg=nil)\r\n self.clone\r\n end",
"def deep_copy(obj); end",
"def clone() end",
"def cloneNode(deep = true)\n attrs = []\n @attr.each do |attr|\n attrs.push(attr.cloneNode(true))\n end\n super(deep, @name, attrs)\n end",
"def deep_clone\n FlowFact.new(scope.dup, lhs.deep_clone, op, rhs, attributes.dup)\n end",
"def cloneNode(deep = true)\n super(deep, @target, @data)\n end",
"def clone\r\n clonepuppy=self.class.new\r\n clonepuppy.clear_fields\r\n self.fields.each {|field|\r\n # this replicates most of the initialize functionality, but we can't\r\n # use initialize by dumping out the string, because of variable length\r\n # fields. The initialize method will greedily fill variable fields which\r\n # might have been left empty during manual construction.\r\n field_copy=field.deep_copy\r\n clonepuppy.fields << field_copy\r\n clonepuppy.add_hash_ref field_copy\r\n clonepuppy.instance_eval do\r\n meta_def field.name do\r\n field_copy.get_value\r\n end\r\n meta_def (field.name.to_s+\"=\").to_sym do |new_val|\r\n field_copy.set_value new_val\r\n end\r\n end\r\n\r\n }\r\n if self.has_parent?\r\n clonepuppy.instance_variable_set :@parent, self.parent\r\n #the results for cloning a structure that isn't the top level in the\r\n # child parent tree is probably a little undefined, but let's allow it\r\n # for now.\r\n end\r\n while clonepuppy.has_children?\r\n clonepuppy.remove_child clonepuppy.children.first\r\n end\r\n self.children.each {|child|\r\n clonepuppy.add_child child.clone\r\n } \r\n clonepuppy\r\n end",
"def dclone(**patch)\n _replicate dupit: false, patch: _patch_at(**patch)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
We ensure that the passed callback is actually callable on the object we're cloning. This is needed for associations because deep_cloneable calls the callback for every associated object.
|
def build_clone_callback(callback)
case callback
when Proc
callback
when Symbol
->(original, clone) {
original.send(callback, clone) if original.respond_to?(callback, true)
}
end
end
|
[
"def cloneable_receiver\n @cloneable_receiver ||= begin\n self.class.cloneable_options[:to].new\n rescue\n self.class.new\n end\n end",
"def safe_clone\r\n self.clone\r\n end",
"def add_callback(type, options, &block)\n options[:bind_to_object] = true\n super\n end",
"def replicate_disable_callbacks(instance)\n if ::ActiveRecord::VERSION::MAJOR >= 3\n # AR 3.1.x, 3.2.x\n def instance.run_callbacks(*args); yield if block_given?; end\n\n # AR 3.0.x\n def instance._run_save_callbacks(*args); yield if block_given?; end\n def instance._run_create_callbacks(*args); yield if block_given?; end\n def instance._run_update_callbacks(*args); yield if block_given?; end\n def instance._run_commit_callbacks(*args); yield if block_given?; end\n else\n # AR 2.x\n def instance.callback(*args)\n end\n def instance.record_timestamps\n false\n end\n end\n end",
"def clone_command\n raise NotImplementedError\n end",
"def _clone_default(obj, mutable_source = false)\n if obj.respond_to? :call then obj.call\n elsif mutable_source then obj\n elsif obj.is_a? MutableHash then obj\n else MutableHash.clone_value(obj)\n end\n end",
"def deep_clone!(options = {})\n processed_options = Para::Cloneable::IncludeTreeBuilder.new(self, cloneable_options).build\n options = options.reverse_merge(processed_options)\n callback = build_clone_callback(options.delete(:prepare))\n \n deep_clone(options) do |original, clone|\n Para::Cloneable::AttachmentsCloner.new(original, clone).clone!\n callback&.call(original, clone)\n end\n end",
"def clone(*) end",
"def maybe_wrap_callback(meth_name, cb)\n return cb unless cb and chrooted? and (meth_name == :create)\n\n lambda do |hash|\n # in this case the string will be the absolute zookeeper path (i.e.\n # with the chroot still prepended to the path). Here's where we strip it off\n hash[:string] = strip_chroot_from(hash[:string])\n\n # call the original callback\n cb.call(hash)\n end\n end",
"def update_cloneable_associations\n associations_for_cloning.each do |association|\n type = @klass.reflect_on_association(association)\n through_record = type.through_reflection\n\n if through_record.present?\n clone_join_relationships(through_record.plural_name)\n else\n clone_has_one_relationship(association,type) if type.macro == :has_one\n clone_has_many_relationships(association) if type.macro == :has_many\n end\n end\n end",
"def initialize_clone( hooked_array_clone )\n \n super\n \n hooked_array_clone.internal_array = hooked_array_clone.internal_array.clone\n \n end",
"def clone() end",
"def clone\n super\n end",
"def clone=(value)\n @clone = value\n end",
"def cloneable?(ref)\n ref[:type] == self[:type]\n end",
"def full_clone(_arg=nil)\r\n self.clone\r\n end",
"def deep_copy(object)\n Proc.send :define_method, :_dump, lambda { |depth|\n @@proc_store ||= {}\n @@proc_key ||= \"000000000\"\n @@proc_key.succ!\n @@proc_store[@@proc_key] = self\n @@proc_key\n }\n Proc.class.send :define_method, :_load, lambda { |key|\n proc = @@proc_store[key]\n @@proc_store.delete key\n proc\n }\n\n Marshal.restore(Marshal.dump(object))\nensure\n Proc.send :remove_method, :_dump if Proc.method_defined? :_dump\n Proc.class.send :remove_method, :_load if Proc.class.method_defined? :_load\nend",
"def clone(&block)\n Cons.construct(self, &block)\n end",
"def vendored\n clone unless cloned?\n super\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns webdriver capabilities for chrome browser
|
def chrome_capabilities
Selenium::WebDriver::Remote::Capabilities.chrome(
logging_prefs: {browser: 'ALL'},
'chromeOptions' => {
'args' => %w[--ignore-certificate-errors],
'w3c' => false
},
'acceptSslCerts' => true,
'acceptInsecureCerts' => true
)
end
|
[
"def capabilities\n execute(:get, 'capabilities')\n end",
"def browserstack\n # Documentation and the code for this class can be found here\n # http://www.rubydoc.info/gems/selenium-webdriver/0.0.28/Selenium/WebDriver/Remote/Capabilities\n # https://github.com/SeleniumHQ/selenium/blob/master/rb/lib/selenium/webdriver/remote/capabilities.rb\n capabilities = Selenium::WebDriver::Remote::Capabilities.new\n\n config.browserstack.capabilities.each do |key, value|\n capabilities[key] = value\n end\n\n capabilities\n end",
"def capabilities\n data[:capabilities]\n end",
"def chrome_browser(*opts)\n options = Selenium::WebDriver::Chrome::Options.new\n opts.each { |n| options.add_argument(n) }\n driver = Selenium::WebDriver.for :chrome, detach: false, options: options\n Watir::Browser.new(driver)\n end",
"def browsers\n all_browser_caps = ENV['SAUCE_ONDEMAND_BROWSERS'] && JSON.parse(ENV['SAUCE_ONDEMAND_BROWSERS'])\n if all_browser_caps && all_browser_caps.size > 0\n all_browser_caps\n else\n [single_browser_caps]\n end\n end",
"def capabilities\n FFI::Libvirt.virConnectGetCapabilities(pointer)\n end",
"def browsers\n [:android, :safari, :phantomjs, :chrome, :firefox, :firebug, :ie] + @data[:sauce_labs][:browsers].keys\n end",
"def capabilities\n Capability.all(uuid)\n end",
"def chrome\n result = []\n\n host = config.proxy['host']\n port = config.proxy['port']\n no_proxy = config.proxy['no_proxy'].tr(',', ';')\n\n result.push(\"--proxy-server=#{host}:#{port}\") if config.use_proxy?\n result.push(\"--proxy-bypass-list=#{no_proxy}\") unless config.proxy['no_proxy'].empty?\n\n result.push(\"--user-agent=#{config.user_agent}\") unless config.user_agent.empty?\n\n result\n end",
"def capabilities\n {\n 'browserName' => '',\n 'platform' => 'Mac',\n 'device' => 'iPhone Simulator',\n 'version' => '6.0',\n 'app' => absolute_app_path\n }\nend",
"def chrome\n no_proxy = config.proxy.no_proxy.tr(\",\", \";\")\n\n args = config.headless ? [\"--headless=new\"] : []\n\n options = Selenium::WebDriver::Options.chrome(args: args)\n\n options.add_argument(\"--proxy-server=#{config.proxy.host}:#{config.proxy.port}\") if config.proxy.use_proxy?\n options.add_argument(\"--proxy-bypass-list=#{no_proxy}\") unless config.proxy.no_proxy.empty?\n\n options.add_argument(\"--user-agent=#{config.user_agent}\") unless config.user_agent.empty?\n\n options\n end",
"def capabilities\n FFI::Libvirt.virConnectGetCapabilities(self)\n end",
"def capabilities; end",
"def sauce_labs_capabilities(options)\n settings = config[:sauce_labs][:browsers][options[:browser]]\n\n capabilities = Selenium::WebDriver::Remote::Capabilities.send(settings[:preset]).tap do |c|\n c.platform = settings[:platform]\n c.version = settings[:version] if settings[:version]\n end\n\n options[:browser] = :remote\n options[:desired_capabilities] = capabilities\n options[:url] = config[:sauce_labs][:base_url] + \"/wd/hub\"\n options\n end",
"def browsers\n @browsers ||= @data[\"agents\"].keys.map{|b| PUBLIC_BROWSER_NAMES[b] }.sort\n end",
"def capabilities\n @manage_sieve.print_capabilities\n end",
"def capabilities\n @stack.capabilities\n end",
"def load_capabilities(scenario_name)\n # Defining desired capabilities hash to be called from selected environment file\n platform_caps = Config.caps[ENV[\"PLATFORM\"]]\n generic_caps = platform_caps[\"generic\"]\n device_farm_caps = platform_caps[ENV[\"DEVICE_FARM\"]]\n unique_caps = platform_caps[ENV[\"OS_VERSION\"]][ENV[\"DEVICE_FARM\"]]\n [*generic_caps, *device_farm_caps, *unique_caps].to_h\n end",
"def open_browser_chrome\n\t\trequire 'watir-webdriver'\n\t\t@browser = Watir::Browser.new :chrome\n\tend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Registers :chrome webdriver options in Capybara framework
|
def register_chrome_driver
Capybara.register_driver :chrome do |app|
if ENV['SELENIUM_GRID'] == 'false'
Capybara::Selenium::Driver.new(app,
browser: :chrome,
desired_capabilities: chrome_capabilities)
else
Capybara::Selenium::Driver.new(app, browser: :remote,
url: hub_url,
desired_capabilities: chrome_capabilities)
end
end
end
|
[
"def use_chrome_to_test\n \t\tclient = Selenium::WebDriver::Remote::Http::Default.new\n \tclient.timeout = 120\n\t Capybara.register_driver :chrome do |app|\n\t Capybara::Selenium::Driver.new(\n\t app,\n\t :browser => :chrome,\n\t :http_client => client,\n\t :switches => %w[—test-type -allow-running-insecure-content])\n\t end\n\t Capybara.javascript_driver = :chrome\n\t\tCapybara.current_driver = :chrome\n \tend",
"def chrome\n no_proxy = config.proxy.no_proxy.tr(\",\", \";\")\n\n args = config.headless ? [\"--headless=new\"] : []\n\n options = Selenium::WebDriver::Options.chrome(args: args)\n\n options.add_argument(\"--proxy-server=#{config.proxy.host}:#{config.proxy.port}\") if config.proxy.use_proxy?\n options.add_argument(\"--proxy-bypass-list=#{no_proxy}\") unless config.proxy.no_proxy.empty?\n\n options.add_argument(\"--user-agent=#{config.user_agent}\") unless config.user_agent.empty?\n\n options\n end",
"def chrome_browser(*opts)\n options = Selenium::WebDriver::Chrome::Options.new\n opts.each { |n| options.add_argument(n) }\n driver = Selenium::WebDriver.for :chrome, detach: false, options: options\n Watir::Browser.new(driver)\n end",
"def initialize(browser = :chrome)\n @driver = Selenium::WebDriver.for browser\n end",
"def supplement_chromium(label, options)\n # Only applies to :chromium\n if :chromium != label\n return label, options\n end\n\n # Try to find a chromium binary\n binary = nil\n require 'ptools'\n CHROMIUM_EXECUTABLES.each do |name|\n location = File.which(name)\n if not location.nil?\n binary = location\n break\n end\n end\n\n # If we found a chromium binary, we can modify the options.\n # Otherwise, we don't do a thing and let selenium fail.\n if binary.nil?\n return label, options\n end\n\n set_binary = options['desired_capabilities.chromeOptions.binary']\n if set_binary and set_binary != binary\n # There's already a binary set. We should warn about this, but\n # otherwise leave this choice.\n warn \"You have the chrome binary '#{set_binary}' set in your \"\\\n \"options, so we're not replacing it with '#{binary}'!\"\n else\n options['desired_capabilities.chromeOptions.binary'] = binary\n end\n\n # Selenium doesn't recognize :chromium, but :chrome with the above\n # options works.\n return :chrome, options\n end",
"def chrome_capabilities\n Selenium::WebDriver::Remote::Capabilities.chrome(\n logging_prefs: {browser: 'ALL'},\n 'chromeOptions' => {\n 'args' => %w[--ignore-certificate-errors],\n 'w3c' => false\n },\n 'acceptSslCerts' => true,\n 'acceptInsecureCerts' => true\n )\n end",
"def common_configuration_for_sauce_web(args)\n\n # Assign the applications path\n content_server = args[:content_server]\n $privly_applications_folder_path = content_server + \"/apps/\"\n\n Capybara.register_driver :sauce_web do |app|\n Capybara::Selenium::Driver.new(\n app,\n :browser => :remote,\n :url => @sauce_url,\n :desired_capabilities => @sauce_caps\n )\n end\n Capybara.default_driver = :sauce_web\n Capybara.current_driver = :sauce_web\nend",
"def sauce_labs_capabilities(options)\n settings = config[:sauce_labs][:browsers][options[:browser]]\n\n capabilities = Selenium::WebDriver::Remote::Capabilities.send(settings[:preset]).tap do |c|\n c.platform = settings[:platform]\n c.version = settings[:version] if settings[:version]\n end\n\n options[:browser] = :remote\n options[:desired_capabilities] = capabilities\n options[:url] = config[:sauce_labs][:base_url] + \"/wd/hub\"\n options\n end",
"def setup(browser_name, url)\n caps = Selenium::WebDriver::Remote::Capabilities.send(browser_name.to_sym)\n\n @driver = Selenium::WebDriver.for(\n :remote,\n url: url.to_s,\n capabilities: caps\n )\nend",
"def open_browser_chrome\n\t\trequire 'watir-webdriver'\n\t\t@browser = Watir::Browser.new :chrome\n\tend",
"def set_browser(app = :chrome, *args)\n @browser = Watir::Browser.new(app, *args)\n Testable.browser = @browser\n end",
"def init_browser(application_source)\n Selenium::WebDriver::Chrome.driver_path = application_source.driverPath\n options = Selenium::WebDriver::Chrome::Options.new\n options.add_argument('--headless')\n options.add_argument('--disable-gpu')\n # TODO Use factory method\n @driver = Selenium::WebDriver.for :chrome, options: options\n # TODO Move to strategy classes\n @driver.manage.timeouts.implicit_wait = application_source.implicitWaitTimeOut\n #@driver.manage.window.maximize\n end",
"def setup_grid(driver)\n if driver == 'chrome'\n capabilities = Selenium::WebDriver::Remote::Capabilities.new\n @browser = Watir::Browser.new(\n :remote,\n url: gridUrl,\n desired_capabilities: capabilities\n )\n end\nend",
"def initialize( config, logger )\n @config = config\n @logger = logger\n\n @logger.debug \"Requested browser config: #{@config.get :global, :browser }\"\n\n type=@config.get :global, :browser, :type\n browser=@config.get :global, :browser, :browser\n port=@config.get :global, :browser, :port\n url=@config.get_default false, :global, :browser, :url\n extra_capabilities=@config.get_default false, :global, :browser, :extras\n if ! extra_capabilities\n extra_capabilities = Hash.new\n end\n\n if browser =~ %r{^\\s*ie\\s*$} or browser =~ %r{^\\s*internet\\s*_?\\s*explorer\\s*$}\n browser = 'internet explorer'\n end\n\n @logger.debug \"Launching some browser; #{type}, #{port}, #{browser}\"\n\n if type == 'remote'\n @logger.info \"Launching remote browser #{browser} on port #{port}\"\n capabilities = Selenium::WebDriver::Remote::Capabilities.new(\n :browser_name => browser,\n :javascript_enabled=>true,\n :css_selectors_enabled=>true,\n :takes_screenshot=>true,\n )\n # Load in any other stuff the user asked for\n @logger.debug \"Requested extra capabilities: #{extra_capabilities.inspect}\"\n extra_capabilities.each do |key, value|\n @logger.debug \"Adding capability #{key} with value #{value}\"\n capabilities[key] = value\n end\n\n if url\n @logger.debug \"Launching with custom url #{url}\"\n else\n url = \"http://127.0.0.1:#{port}/wd/hub\"\n end\n\n client = Selenium::WebDriver::Remote::Http::Default.new\n client.timeout = config.get_default( 600, :global, :browser, :timeout )\n\n @browser = Watir::Browser.new(:remote, :url => url, :desired_capabilities => capabilities, :http_client => client)\n else\n @logger.info \"Launching local browser #{browser}\"\n @browser = Watir::Browser.new browser\n end\n end",
"def setup(browser = BROWSER)\n # Chrome @browser instantiation\n if(browser.downcase().eql? \"chrome\")\n driver = Selenium::WebDriver.for :chrome\n # Firefox @browser instantiation\n elsif (browser.downcase().eql? \"firefox\")\n driver = Selenium::WebDriver.for :firefox\n else\n puts \"Only Chrome and Firefox browsers are supported\"\n end\n if (!driver.nil?)\n # maximize @browser window\n driver.manage.window.maximize\n # Load the mentioned URL\n driver.get \"https://www.upwork.com/\"\n end\n @@driver = driver\n end",
"def configure_browser()\r\n if test_config.browser == \"ie\"\r\n Capybara.register_driver :selenium do |app|\r\n Capybara::Selenium::Driver.new(app, :browser=>:internet_explorer)\r\n end\r\n else\r\n Capybara.register_driver :selenium do |app|\r\n if !(test_config.browserPath.nil? || test_config.browserPath.empty?)\r\n require 'selenium/webdriver'\r\n Selenium::WebDriver::Firefox::Binary.path = test_config.browserPath\r\n end\r\n Capybara::Selenium::Driver.new(app, :browser => :firefox)\r\n end\r\n end\r\n end",
"def launch_browser\n driver_config = Config.webdriver_settings\n browser = driver_config[:browser]\n logger.warn \"Launching #{browser.capitalize}\"\n driver = case browser\n\n when 'chrome'\n options = Selenium::WebDriver::Chrome::Options.new\n options.add_argument('--headless=new') if driver_config[:headless]\n options.add_preference('download.prompt_for_download', false)\n options.add_preference('download.default_directory', Config.download_dir)\n options.add_preference('profile.default_content_setting_values.automatic_downloads', 1)\n Selenium::WebDriver.for :chrome, options: options\n\n when 'firefox'\n options = Selenium::WebDriver::Firefox::Options.new\n options.add_argument '-headless' if driver_config[:headless]\n Selenium::WebDriver.for :firefox, options: options\n\n when 'safari'\n Selenium::WebDriver.for :safari\n\n else\n logger.error 'Designated WebDriver is not supported'\n fail\n end\n driver_config[:headless] ? driver.manage.window.resize_to(1600,900) : driver.manage.window.maximize\n driver.manage.timeouts.page_load = 120\n driver\n end",
"def setup_capybara\n Capybara.run_server = false\n Capybara.current_driver = :webkit\n Capybara.app_host = 'http://www20.gencat.cat'\n end",
"def browser\n (ENV['BROWSER'] ||= 'chrome').to_sym\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns webdriver capabilities for firefox browser
|
def firefox_capabilities
Selenium::WebDriver::Remote::Capabilities.firefox(
logging_prefs: {browser: 'ALL'},
'acceptSslCerts' => true,
'acceptInsecureCerts' => true,
'native_events' => true
)
end
|
[
"def firefox\n options = Selenium::WebDriver::Firefox::Options.new(profile: firefox_profile)\n options.headless! if config.headless\n\n options\n end",
"def firefox\r\n @web_browser.firefox\r\n end",
"def firefox\n @web_browser.firefox\n end",
"def capabilities\n execute(:get, 'capabilities')\n end",
"def capabilities\n {\n 'browserName' => '',\n 'platform' => 'Mac',\n 'device' => 'iPhone Simulator',\n 'version' => '6.0',\n 'app' => absolute_app_path\n }\nend",
"def browser_firefox_version\n if browser_is? 'firefox'\n match = ua.match(%r{\\bfirefox/([\\d\\.]+)\\b})\n match[1].to_f if (match)\n end or 0\n end",
"def browserstack\n # Documentation and the code for this class can be found here\n # http://www.rubydoc.info/gems/selenium-webdriver/0.0.28/Selenium/WebDriver/Remote/Capabilities\n # https://github.com/SeleniumHQ/selenium/blob/master/rb/lib/selenium/webdriver/remote/capabilities.rb\n capabilities = Selenium::WebDriver::Remote::Capabilities.new\n\n config.browserstack.capabilities.each do |key, value|\n capabilities[key] = value\n end\n\n capabilities\n end",
"def browsers\n [:android, :safari, :phantomjs, :chrome, :firefox, :firebug, :ie] + @data[:sauce_labs][:browsers].keys\n end",
"def register_firefox_driver\n Capybara.register_driver :firefox do |app|\n if ENV['SELENIUM_GRID'] == 'false'\n options = Selenium::WebDriver::Firefox::Options.new\n Capybara::Selenium::Driver.new(app, browser: :firefox,\n options: options,\n desired_capabilities: firefox_capabilities)\n else\n Capybara::Selenium::Driver.new(app, browser: :remote,\n url: hub_url,\n desired_capabilities: firefox_capabilities)\n end\n end\n end",
"def browsers\n all_browser_caps = ENV['SAUCE_ONDEMAND_BROWSERS'] && JSON.parse(ENV['SAUCE_ONDEMAND_BROWSERS'])\n if all_browser_caps && all_browser_caps.size > 0\n all_browser_caps\n else\n [single_browser_caps]\n end\n end",
"def firefox\n # For future reference configuring Firefox via Selenium appears to be done\n # via the options argument, and a Selenium::WebDriver::Firefox::Options\n # object.\n # https://github.com/SeleniumHQ/selenium/wiki/Ruby-Bindings\n # https://www.rubydoc.info/gems/selenium-webdriver/3.141.0/Selenium/WebDriver/Firefox/Options\n # http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp\n # http://preferential.mozdev.org/preferences.html\n Capybara.register_driver :firefox do |app|\n # :simplecov_ignore:\n Capybara::Selenium::Driver.new(\n app,\n browser: :firefox,\n options: @driver_config.firefox\n )\n # :simplecov_ignore:\n end\n :firefox\n end",
"def capabilities\n data[:capabilities]\n end",
"def chrome_capabilities\n Selenium::WebDriver::Remote::Capabilities.chrome(\n logging_prefs: {browser: 'ALL'},\n 'chromeOptions' => {\n 'args' => %w[--ignore-certificate-errors],\n 'w3c' => false\n },\n 'acceptSslCerts' => true,\n 'acceptInsecureCerts' => true\n )\n end",
"def firefox\n # For future reference configuring Firefox via Selenium appears to be done\n # via the profile argument, and a Selenium::WebDriver::Firefox::Profile\n # object.\n # https://github.com/SeleniumHQ/selenium/wiki/Ruby-Bindings#firefox\n # http://www.rubydoc.info/gems/selenium-webdriver/0.0.28/Selenium/WebDriver/Firefox/Profile\n # http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp\n # http://preferential.mozdev.org/preferences.html\n Capybara.register_driver :firefox do |app|\n # :simplecov_ignore:\n Capybara::Selenium::Driver.new(app, profile: @driver_config.firefox)\n # :simplecov_ignore:\n end\n :firefox\n end",
"def firefox_browser?\n user_agent = UserAgent.parse(request.user_agent)\n if FirefoxBrowser.detect { |browser| user_agent >= browser }\n true\n else\n false\n end\n end",
"def firefox?\n if @type.downcase == \"firefox\"\n return true\n else\n return false\n end\n end",
"def browsers\n @browsers ||= @data[\"agents\"].keys.map{|b| PUBLIC_BROWSER_NAMES[b] }.sort\n end",
"def capabilities; end",
"def capabilities\n Capability.all(uuid)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Registers :firefox webdriver options in Capybara framework
|
def register_firefox_driver
Capybara.register_driver :firefox do |app|
if ENV['SELENIUM_GRID'] == 'false'
options = Selenium::WebDriver::Firefox::Options.new
Capybara::Selenium::Driver.new(app, browser: :firefox,
options: options,
desired_capabilities: firefox_capabilities)
else
Capybara::Selenium::Driver.new(app, browser: :remote,
url: hub_url,
desired_capabilities: firefox_capabilities)
end
end
end
|
[
"def firefox\n # For future reference configuring Firefox via Selenium appears to be done\n # via the options argument, and a Selenium::WebDriver::Firefox::Options\n # object.\n # https://github.com/SeleniumHQ/selenium/wiki/Ruby-Bindings\n # https://www.rubydoc.info/gems/selenium-webdriver/3.141.0/Selenium/WebDriver/Firefox/Options\n # http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp\n # http://preferential.mozdev.org/preferences.html\n Capybara.register_driver :firefox do |app|\n # :simplecov_ignore:\n Capybara::Selenium::Driver.new(\n app,\n browser: :firefox,\n options: @driver_config.firefox\n )\n # :simplecov_ignore:\n end\n :firefox\n end",
"def firefox\n # For future reference configuring Firefox via Selenium appears to be done\n # via the profile argument, and a Selenium::WebDriver::Firefox::Profile\n # object.\n # https://github.com/SeleniumHQ/selenium/wiki/Ruby-Bindings#firefox\n # http://www.rubydoc.info/gems/selenium-webdriver/0.0.28/Selenium/WebDriver/Firefox/Profile\n # http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp\n # http://preferential.mozdev.org/preferences.html\n Capybara.register_driver :firefox do |app|\n # :simplecov_ignore:\n Capybara::Selenium::Driver.new(app, profile: @driver_config.firefox)\n # :simplecov_ignore:\n end\n :firefox\n end",
"def firefox\n options = Selenium::WebDriver::Firefox::Options.new(profile: firefox_profile)\n options.headless! if config.headless\n\n options\n end",
"def firefox_capabilities\n Selenium::WebDriver::Remote::Capabilities.firefox(\n logging_prefs: {browser: 'ALL'},\n 'acceptSslCerts' => true,\n 'acceptInsecureCerts' => true,\n 'native_events' => true\n )\n end",
"def driver_initialize\n puts \"Step 1: Opening firefox browser\"\n options = Selenium::WebDriver::Firefox::Options.new()\n $web_driver = Selenium::WebDriver.for(:firefox, options: options)\n end",
"def configure_browser()\r\n if test_config.browser == \"ie\"\r\n Capybara.register_driver :selenium do |app|\r\n Capybara::Selenium::Driver.new(app, :browser=>:internet_explorer)\r\n end\r\n else\r\n Capybara.register_driver :selenium do |app|\r\n if !(test_config.browserPath.nil? || test_config.browserPath.empty?)\r\n require 'selenium/webdriver'\r\n Selenium::WebDriver::Firefox::Binary.path = test_config.browserPath\r\n end\r\n Capybara::Selenium::Driver.new(app, :browser => :firefox)\r\n end\r\n end\r\n end",
"def initialize(args = {})\n @driver = args[:driver] || SeleniumFirefoxPool.instance.get_driver\n end",
"def common_configuration_for_firefox_extension\n # Assign the path to find the applications in the extension\n Capybara.app_host = \"chrome://privly\"\n $privly_applications_folder_path = Capybara.app_host + \"/content/privly-applications/\"\n puts \"Packaging the Firefox Extension\"\n system(\"cd ../../../../../ && pwd && jpm xpi && cd chrome/content/privly-applications/test/selenium\")\n # Find out the xpi file name\n json = JSON.load(File.new(\"../../../../../package.json\"))\n xpi_filename = \"privly@priv.ly-\" + json['version'] + \".xpi\"\n # Load the Firefox driver with the extension installed\n @profile = Selenium::WebDriver::Firefox::Profile.new\n @profile[\"extensions.privly.integration_test\"] = \"true\"\n @profile.add_extension(\"../../../../../\" + xpi_filename)\nend",
"def setup_browser(url)\n browser = Watir::Browser.new :firefox, headless: true\n browser.goto url\n return browser\nend",
"def firefox\n @web_browser.firefox\n end",
"def common_configuration_for_sauce_web(args)\n\n # Assign the applications path\n content_server = args[:content_server]\n $privly_applications_folder_path = content_server + \"/apps/\"\n\n Capybara.register_driver :sauce_web do |app|\n Capybara::Selenium::Driver.new(\n app,\n :browser => :remote,\n :url => @sauce_url,\n :desired_capabilities => @sauce_caps\n )\n end\n Capybara.default_driver = :sauce_web\n Capybara.current_driver = :sauce_web\nend",
"def firefox\r\n @web_browser.firefox\r\n end",
"def setup(browser_name, url)\n caps = Selenium::WebDriver::Remote::Capabilities.send(browser_name.to_sym)\n\n @driver = Selenium::WebDriver.for(\n :remote,\n url: url.to_s,\n capabilities: caps\n )\nend",
"def setup_firefox_path\n firefox_app = nil\n IO.popen('mdfind \"kMDItemFSName = Firefox*.app\"') { |io|\n firefox_app = io.gets\n }\n raise \"Can't find Firefox app bundle\" unless firefox_app\n firefox_app.chomp!\n\n Selenium::WebDriver::Firefox::Binary.path = File.join(firefox_app, 'Contents/MacOS/firefox')\nend",
"def setup_capybara\n Capybara.run_server = false\n Capybara.current_driver = :selenium\n Capybara.app_host = 'http://empresa.lacaixa.es'\n Capybara.default_wait_time = 20\n Capybara.ignore_hidden_elements = false\n end",
"def firefox_settings\n settings = {}\n return settings unless use_proxy?\n\n settings[:http] = \"#{host}:#{port}\"\n settings[:ssl] = settings[:http]\n settings[:no_proxy] = no_proxy unless no_proxy.empty?\n\n settings\n end",
"def setup_capybara\n Capybara.run_server = false\n Capybara.current_driver = :selenium\n Capybara.app_host = 'https://www.ono.es'\n end",
"def set_browser(app = :chrome, *args)\n @browser = Watir::Browser.new(app, *args)\n Testable.browser = @browser\n end",
"def setup_capybara\n Capybara.run_server = false\n Capybara.current_driver = :webkit\n Capybara.app_host = 'http://todofp.es'\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return absolute uri for path
|
def absolute_uri_path(path)
"#{root_uri}#{path}"
end
|
[
"def uri(path)\n return nil unless path\n root = asset_roots.detect { |root| Processor.parent_path?(root, path) }\n '/' + path.relative_path_from(root).to_s\n end",
"def absolute_uri(uri)\n uri.relative? ? URI.join(@uri, uri) : uri\n end",
"def absolute_path(path)\n path = Pathname.new(path)\n return Pathname.new(@config.base_path) + path unless path.absolute?\n path\n end",
"def path\n @uri.path if @uri\n end",
"def absolute\n @absolute_path_string ||= absolute_path.to_s\n end",
"def build_uri(path)\n path = path.to_s\n unless path.match(/^\\//)\n path = \"/#{path}\"\n end\n base_uri + path\n end",
"def abs_path; end",
"def absolute_path\n if is_url?\n # Use the last path component without the query string plus the name\n # of the resource in Base64. This should be both mildly readable and\n # also unique per invocation.\n url_part = URI(path).path.split(/\\//).last\n base64_name = Base64.strict_encode64(name).gsub(/\\=/, '')\n ::File.join(Chef::Config[:file_cache_path], \"#{base64_name}_#{url_part}\")\n else\n ::File.expand_path(path, Chef::Config[:file_cache_path])\n end\n end",
"def to_relative_uri\n build_uri.route_from base_value\n end",
"def absolute_url\n end",
"def absolute_uri (uri)\n return uri if @base_uris.empty?\n base = URI.parse(@base_uris.last)\n base.merge(uri).to_s\n end",
"def absolutize(path, base = @base_path)\n return base if path == '.'\n (Pathname.new path).absolute? ? path : base + '/' + path\n end",
"def url\n ::File.join \"/\", path.to_s\n end",
"def get_abs_url(path)\n \"https://#{@api_url}#{path}\"\n end",
"def to_absolute_path\n File.join('', to.path(:default).to_s)\n end",
"def build_uri(path)\n uri = base_uri\n uri.path = path\n uri.to_s\n end",
"def absolute(path = nil)\n return path if path && path[0] != '/'\n abs = if path\n [env['scorched.root_path'], path].join('/').gsub(%r{/+}, '/')\n else\n env['scorched.root_path']\n end\n abs.insert(0, '/') unless abs[0] == '/'\n abs\n end",
"def full_path\n path\n end",
"def absolute_path(options = {})\n if !@absolute_path\n # Pre-conditions\n raise ArgumentError.new(\"No document root set\") if @document_root.nil?\n\n @absolute_path = filename.sub(%r{^#@document_root}, '').sub(/^\\/?/, '/')\n @absolute_path = \"#{Juicer::Asset::Path.host_with_scheme(options[:host])}#@absolute_path\"\n end\n\n path_with_cache_buster(@absolute_path, options)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return host with optional port Only returns port if protocols default port diffes from actual port.
|
def host_with_port
uhost, uport = self.host, self.port
if port != protocol.default_port
"#{uhost}:#{uport}"
else
uhost
end
end
|
[
"def optional_port\n standard_port? ? nil : port\n end",
"def port_string\n (protocol == 'http://' && port == 80) || (protocol == 'https://' && port == 443) ? '' : \":#{port}\"\n end",
"def port_string\n port == standard_port ? '' : \":#{port}\"\n end",
"def port\n if raw_host_with_port =~ /:(\\d+)$/\n $1.to_i\n else\n standard_port\n end\n end",
"def port_string\n standard_port? ? \"\" : \":#{port}\"\n end",
"def port_default?\n self.port == (self.secure? ? HTTPS_PORT_DEFAULT : HTTP_PORT_DEFAULT)\n end",
"def port\n options['resolve_host'] ? (options['port'] || host_dns.port.to_i) : options['port']\n end",
"def default_port?\n port == default_port\n end",
"def non_default_port(scheme,port)\n case scheme\n when /^http$/i then port==80 ? nil : port\n when /^https$/i then port==443 ? nil : port\n else port\n end\n end",
"def host_with_port\n \"#{host}#{port_string}\"\n end",
"def port\n parse_host_header unless @host_header_parsed\n @port\n end",
"def port(port, host=nil)\n host ||= default_host\n bind URI::Generic.build(scheme: 'tcp', host: host, port: Integer(port)).to_s\n end",
"def port\n @port ||= default_port\n end",
"def derive_port name\n begin\n Socket.getservbyname name\n rescue SocketError\n nil\n end\nend",
"def port_from_host_entry\n port_str = NewRelic::Agent.config[:'infinite_tracing.trace_observer.host'].scan(%r{:(\\d+)$}).flatten\n if port = port_str[0]&.to_i\n NewRelic::Agent.logger.warn(\":'infinite_tracing.trace_observer.port' is ignored if present because :'infinite_tracing.trace_observer.host' specifies the port\")\n return port\n end\n end",
"def port\n if @port.to_i == 0\n if self.scheme\n @port = self.class.scheme_mapping[self.scheme.strip.downcase]\n else\n @port = nil\n end\n return @port\n else\n @port = @port.to_i\n return @port\n end\n end",
"def port(opts={})\n # Check if port was specified in options hash\n pnum = opts[:port]\n return pnum if pnum\n\n # Check if we have an SSH forwarded port\n pnum = nil\n env.vm.vm.network_adapters.each do |na|\n pnum = na.nat_driver.forwarded_ports.detect do |fp|\n fp.name == env.config.ssh.forwarded_port_key\n end\n\n break if pnum\n end\n\n return pnum.hostport if pnum\n\n # This should NEVER happen.\n raise Errors::SSHPortNotDetected\n end",
"def default_port?\n port == DEFAULT_PORT\n end",
"def port\n settings[:port] || PROTOCOLS[settings[:protocol]]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Checks if a format is known. Returns the associated content type.
|
def known_format?(f)
FORMAT_TO_CONTENT_TYPE[f]
end
|
[
"def format\n @format ||= Mime.detect_format(content_type, @config)\n end",
"def verify_requested_format!\n mimes = collect_mimes_from_class_level\n collector = ActionController::MimeResponds::Collector.new(mimes, request.variant)\n\n unless collector.negotiate_format(request)\n raise ActionController::UnknownFormat\n end\n end",
"def mime_type_for(format)\n @formats.key(format)\n end",
"def content_type(fmt = nil)\n @_content_type = (fmt || _perform_content_negotiation) unless @_content_type\n @_content_type\n end",
"def format\n @format ||=\n if parameters[:format]\n Mime::Type.lookup_by_extension(parameters[:format])\n elsif ActionController::Base.use_accept_header\n accepts.first\n elsif xhr?\n Mime::Type.lookup_by_extension(\"js\")\n else\n Mime::Type.lookup_by_extension(\"html\")\n end\n end",
"def config_content_type\n format = SF_CONFIG['format']\n if format.blank? || !FORMATS.keys.include?(format.to_sym)\n return self.content_type = FORMATS[:json]\n end\n \n return self.content_type = FORMATS[format.to_sym]\n end",
"def content_type\n @content_type ||= begin\n type = Rack::Mime.mime_type(format_extension)\n type[/^text/] ? \"#{type}; charset=utf-8\" : type\n end\n end",
"def valid_content_type?\n error? || !found? || content_type == expected_content_type\n end",
"def isFormat\n @RecordType == FORMAT\n end",
"def negotiate_mime\n return if request.negotiate_mime(ALLOWED_MEDIA_TYPES)\n raise ::ActionController::UnknownFormat\n end",
"def detect\n empty_file? ? EMPTY_CONTENT_TYPE : content_type_from_content\n end",
"def defined?(format)\n formatters.keys.include?(format)\n end",
"def format\n @format ||= (\n if read\n fmt = self.class.supported_formats.find{ |fm| fm.match?(path, read) }\n raise IOError, \"Version file matches no known format.\"\n else\n PlainFormat\n end\n )\n end",
"def is_format?(); @type == GRT_FORMAT; end",
"def inferred_mime_type\n format_extension = path.format&.to_s\n MIME::Types.type_for(format_extension).first if format_extension\n end",
"def content_type(type)\n @response.content_type == type\n end",
"def perform_content_negotiation # :nodoc:\n raise Merb::ControllerExceptions::NotAcceptable if provided_formats.empty?\n if fmt = params[:format]\n if provided_formats.include?(fmt.to_sym)\n fmt.to_sym\n else\n raise Merb::ControllerExceptions::NotAcceptable\n end\n else\n accepts = Rest::Responder.parse(request.accept).\n collect {|t| t.to_sym}\n if accepts.include?(:all)\n provided_formats.first\n else\n accepts.each do |type|\n return type if provided_formats.include?(type)\n end\n raise Merb::ControllerExceptions::NotAcceptable\n end\n end\n end",
"def mime_type_for(format, temp_object=nil)\n registered_mime_types[file_ext_string(format)] || (temp_object.mime_type if temp_object.respond_to?(:mime_type)) || fallback_mime_type\n end",
"def unknown_format?\n if @unknown_format\n true\n else\n false\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N. Examples [2, 4, 0, 100, 4, 11, 2602, 36] Should return: 11 (the only odd number) [160, 3, 1719, 19, 11, 13, 21] Should return: 160 (the only even number)
|
def find_outlier(array)
odd_array=[]
even_array=[]
array.each do |i|
odd_array << i if i % 2 == 0
even_array << i if i % 2 != 0
end
odd_array.size > even_array.size ? even_array[0] : odd_array[0]
end
|
[
"def find_outlier(arr)\n even = arr.select { |num| num.even? }\n odd = arr.select { |num| num.odd? }\n\n even.count > odd.count ? odd[0] : even[0]\nend",
"def find_outlier(num_arr)\n new_arr = num_arr.select { |num| num.odd? } # [1, 3]\n\n return new_arr.first if new_arr.size == 1\n (num_arr - new_arr).first # 2\nend",
"def outlier(array)\n i = 0\n majority_type = \"\"\n odds = []\n evens = []\n while i < 3\n array[i] % 2 == 0 ? evens << array[i] : odds << array[i]\n i += 1\n end\n if (odds.length != 3 && evens.length != 3)\n odds.length > evens.length ? (return evens[0]) : (return odds[0])\n end\n odds.length > evens.length ? majority_type = \"odd\" : majority_type = \"even\"\n if majority_type == \"odd\"\n while i < array.length\n if array[i] % 2 == 0\n return array[i]\n end\n i += 1 \n end\n end\n if majority_type == \"even\"\n while i < array.length\n if array[i] % 2 != 0\n return array[i]\n end\n i += 1 \n end\n end\n end",
"def even_numbers(arr,n)\n # take all the even numbers from the original array\n even_arr = arr.select { |n| n.even? }\n # return n of last even numbers with index range\n even_arr.last(n)\nend",
"def find_odd_int (arr)\n\n arr.uniq.find{ |num| arr.count(num).odd? }\n\nend",
"def only_odd_low_to_high array\n # select only values that are of class integer\n only_ints = array.select do |num|\n num.class == Integer\n # now select only odd numbers\n end.select do |num|\n num.odd?\n # use sort method to sort from low to high\n end.sort\n # return only the ints that are odd in ascending order\n only_ints\nend",
"def odd_integers(array)\r\n\tarray.select do |item|\r\n\t\titem.odd?\r\n\tend\r\nend",
"def odd_numb array\n new_arr= array.select! do |value|\n value.class == Integer\n end\n new_arr.select { |value| value % 2 != 0 }.sort\nend",
"def oddities(array)\n ret_array = []\n array.each_with_index do |value, index|\n if index.even?\n ret_array << value\n end\n end\n ret_array\nend",
"def oddities(array)\n new_array = []\n count = 1\n array.each do |element|\n new_array << element if count.odd?\n count += 1\n end\n new_array\nend",
"def odd_indexed_integers(array)\n\nend",
"def reject_odds(array)\n\t\n\tnot_odds = array.reject { |num| num.odd?}\nend",
"def oddities(arr)\n index = -1\n every_other_element = arr.map do |element|\n index += 1\n index.even? ? element : nil\n end\n every_other_element.compact\nend",
"def oddities(array)\n index = -1\n array.select do |_| \n index += 1\n index.even?\n end\nend",
"def oddities(arr)\n arr2 = []\n arr.each_with_index { |elem, ndx| arr2 << elem if ndx.even? }\n arr2\nend",
"def oddities(array)\n result = []\n return result if array.empty?\n array.each_with_index { |item, index| result << item if index.even? }\n result\nend",
"def oddities(array)\n counter = 1\n array.select do |element|\n oddity = counter.odd?\n counter += 1\n oddity\n end\nend",
"def even_numbers(num_array)\n\tnum_array.select! { |num| num.even? }\nend",
"def odd_numbers(array)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Public: Checks to see if the LinkedList is empty. Examples
|
def empty?
@head.next == nil
end
|
[
"def is_empty()\n @head == nil\n end",
"def is_empty?\n if self.head == nil\n return true\n else\n return false\n end\n end",
"def empty?\n head.nil? && tail.nil?\n end",
"def empty?\n list.empty?\n end",
"def empty?\n @head.next == @tail && @tail.prev == @head\n end",
"def empty?\n # Funnily enough, an empty list does *not* make a port empty!\n return false if @structure.instance_of? Array\n @structure.empty?\n end",
"def empty?\n self.count == 0\n end",
"def empty?() end",
"def is_empty()\n return true if size == 0\n\n front_index == last_index\n end",
"def empty?\n @smart_listing.count == 0\n end",
"def empty?\n true\n end",
"def empty?\n @objects.length == 0\n end",
"def empty?\n entries.empty?\n end",
"def __empty?\n all?(&:__empty?)\n end",
"def empty?\n @lock.synchronize { @used.size == 0 && @available.size == 0 }\n end",
"def empty?\n @iterator.nil?\n end",
"def is_empty()\n @queue == []\n end",
"def empty?\n current.nil?\n end",
"def empty?\n content.nil? && (children.empty? || children.all?(&:empty?))\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Public: Finds and removes the first occurrence of a Node with the desired value. value the Ruby object value to find and remove from the LinkedList Examples
|
def remove(value)
element = self.head
previous_element = @head
while element.value != value
if element.next.nil?
return nil
else
previous_element = element
element = element.next
end
end
previous_element.next = element.next
element
end
|
[
"def delete_value value\r\n #find the pointer to the wanted node using LIST-SEARCH(value)\r\n #then delete that node with LIST-DELETE-BY-NODE(node)\r\n delete_node(self.search(value))\r\n end",
"def test_it_can_remove_a_node_by_value\n list = LinkedList.new(\"start\")\n list.append(\"chilula\")\n list.append(\"sriracha\")\n list.append(\"tapatio\")\n list.remove_by_data(\"chilula\")\n assert_equal \"tapatio\", list.find_by_index(2)\n end",
"def delete(value)\r\n # Case where the list is empty\r\n return if @head == nil\r\n\r\n # Case where delete the 1st node\r\n if @head.data == value\r\n @head = @head.next\r\n return\r\n end\r\n\r\n curr = @head\r\n # Check that there is another node after current\r\n until curr.next == nil\r\n # If the next node contains the value, have the current node point to next next node\r\n if curr.next.data == value\r\n curr.next = curr.next.next\r\n return\r\n end\r\n\r\n # If not, keep searching the list for the given value.\r\n curr = curr.next\r\n end\r\n\r\n # curr = @head.next\r\n # prev = @head\r\n #\r\n # until curr == nil\r\n # # Value found in the list. Delete that node.\r\n # if curr.data == value\r\n # prev.next = curr.next\r\n # return\r\n # end\r\n #\r\n # # Else, keep searching.\r\n # prev = curr\r\n # curr = curr.next\r\n # end\r\n\r\n return nil # Value not found in the list\r\n end",
"def node_with_value(value)\n current_node = @head\n while current_node.value\n return current_node if current_node.value == value\n current_node = current_node.next_node\n end\n end",
"def delete(value)\n\t\tcurrent_node = @head \n\t\tif current_node.value == value \n\t\t\t@head = current_node.next_node\n\t\tend \n\t\tuntil current_node.next_node.value == value \n\t\t\treturn false if current_node.next_node == nil \n\t\t\tcurrent_node = current_node.next_node\n\t\tend \n\t\tcurrent_node.next_node = current_node.next_node.next_node\n\tend",
"def delete(value)\r\n return nil if !@head\r\n if @head.data == value\r\n @head = @head.next \r\n return nil\r\n end \r\n cursor = @head\r\n while cursor.next && cursor.next.data != value\r\n cursor = cursor.next\r\n end\r\n cursor.next = cursor.next.next if cursor.next\r\n end",
"def remove_val(val)\n node = self.first_node\n\n until node.val == val || node.nil?\n prev_node = node\n node = node.next_node\n end\n\n if node && prev_node\n prev_node.next_node = node.next_node\n\n elsif node\n self.first_node = node.next_node\n end\n\n end",
"def find(value)\n self.each {|node| return node if node.value == value}\n end",
"def delete(value)\n\t\tnode = search(value)\n\t\treturn if node == nil\n\t\tif is_root?(node)\n\t\t\tdelete_root()\n\t\telse\n\t\t\tdelete_node(node)\n\t\tend\n\tend",
"def remove_all value\n\t\tnode = @head\n\t\tif node == nil\n\t\t\treturn false\n\t\telse\n\t\t\n\t\tremove_head if node.value == value\n\t\tprev = node\n\t\tcurr = node.next\n\t\t#Iterate till the value before it\n\t\twhile curr != nil do\n\t\t\tif curr.value == value\n\t\t\t\tprev.next = curr.next\n\t\t\t\tcurr = curr.next\n\t\t\telse\n\t\t\t\tprev = curr\n\t\t\t\tcurr = curr.next\n\t\t\tend\n\t\tend\n\t\tend\n\tend",
"def remove_head(value, node)\n if node.left\n link = max_search(node.left)\n link.right = @head.right\n @head = @head.left\n elsif node.right\n link = min_search(node.right)\n link.left = @head.left\n @head = @head.right\n else\n @head = nil\n end\n end",
"def delete_values(list, value)\n current_node = list.first\n until current_node == nil\n if current_node.value == value\n if current_node == list.first\n list.first = current_node.next\n current_node.prev = nil\n elsif current_node == list.last\n list.pop\n else\n current_node.next.prev = current_node.prev\n current_node.prev.next = current_node.next\n end\n end\n current_node = current_node.next\n end\nend",
"def remove(value)\n return false if @root[:value].nil?\n type_check value\n\n child = search(value, @root)\n return false if is_nil(child)\n\n if is_leaf(child)\n make_nil(child)\n elsif has_one_child(child)\n replacement_value =\n (child[:left] || {})[:value] || child[:right][:value]\n else\n replacement_value = get_replacement_node(child, true)[:value]\n remove(replacement_value)\n end\n child[:value] = replacement_value\n true\n end",
"def search(value)\r\n # If the head is nil the list is empty\r\n if self.head.nil?\r\n return nil\r\n end\r\n # Start with the head\r\n element = self.head\r\n loop do\r\n # Check if the element has the correct value\r\n if element.value == value\r\n return element\r\n end\r\n # Return nil if the tail has been reached\r\n if element == self.tail\r\n return nil\r\n end\r\n # Look at the next element in the list\r\n element = element.next_element\r\n end\r\n end",
"def delete(key, value = nil)\n nodes = find_nodes(key)\n return false unless nodes\n\n return_value = false\n nodes.each do |node|\n if !value || value == node.value\n return_value = remove_tower node\n @length -= 1\n remove_empty_level\n end\n end\n\n return_value\n end",
"def delete_from(value)\n L.log '', \"Attempting to delete #{value} from BST\"\n outcome, new_root = @root_tree.delete_element(@root_tree, Node.new(value))\n @root_tree = new_root\n display_tree\n return outcome\n end",
"def delete(val = nil, &block)\n if val.respond_to?(:to_node)\n node = val.to_node\n __unlink_node(node)\n return node.data\n end\n\n each_node.find(&__to_matcher(val, &block)).tap do |node_to_delete|\n return unless node_to_delete\n __unlink_node(node_to_delete)\n end.data\n end",
"def remove(value)\n node = find_node(value)\n return false if node.nil? # value not found in tree\n\n # if node is a leaf (has no branches)\n # node is deleted or detached\n if node.leaf?\n if node == @root # there is only one value in tree\n @root = nil\n else\n node.detach_from_tree\n end\n\n # if node has a single branch\n # value, left_b, and right_b are replaced with same values from branch node\n elsif node.only_right?\n node.update_with_attrs_from(node.right_b)\n elsif node.only_left?\n node.update_with_attrs_from(node.left_b)\n\n # if node has both branches\n # the node with the value closest to and greater than current node's value\n # replaces it\n else\n closest_node = find_closest_node(node)\n node.value = closest_node.value\n\n # handles closest node detachment from tree or updating\n if closest_node.leaf?\n closest_node.detach_from_tree\n else\n closest_node.update_with_attrs_from(closest_node.right_b)\n end\n end\n true\n end",
"def delete_node(node)\n\n node.val = node.next.val\n node.next = node.next.next\n nil\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
A helper method to validate the state
|
def validate_state(state = {}); end
|
[
"def validate!(state)\n # The state is a Hash-like object (HLO) with a value\n # at key MACHINE_KEY\n unless state[MACHINE_KEY]\n raise InvalidMachine, \"no state machine found: #{state}\"\n end\n\n # The machine has a current state \n unless state[MACHINE_KEY][:current]\n raise InvalidMachine, \"no current state: #{state}\"\n end\n\n # The machine specifies a set of transitions (and hence states)\n unless state[MACHINE_KEY][:transitions]\n raise InvalidMachine, \"you must specify some transitions: #{state}\"\n end\n\n # The transitions table must be a HLO...\n unless state[MACHINE_KEY][:transitions].is_a?(Hash)\n raise InvalidMachine, \"transitions must be a hash: #{state}\"\n end\n\n # ...all of whose values are also HLOs\n unless state[MACHINE_KEY][:transitions].values.map { |v| v.is_a?(Hash) }.inject(:&)\n raise InvalidMachine, \"transitions must be a hash of hashes: #{state}\"\n end\n \n # Callbacks (which are all post-transition; see below) are optional,\n # but if they exist...\n if state[MACHINE_KEY][:callbacks]\n # ...they must be in a HLO...\n unless state[MACHINE_KEY][:callbacks].is_a?(Hash)\n raise InvalidMachine, \"callbacks must be a hash: #{state}\"\n end\n \n # ...whose values are either callables or collections thereof\n valid_callbacks = state[MACHINE_KEY][:callbacks].values.flatten.map do |v| \n v.respond_to?(:call)\n end.inject(:&)\n \n unless valid_callbacks\n raise InvalidMachine, \"callbacks must be callables or arrays thereof: #{state}\"\n end\n end\n \n # Aliases are optional, but if they exist...\n if state[MACHINE_KEY][:aliases]\n # ...they must be in a HLO. This is all we can actually\n # say about aliases, other than this: The keys of this\n # HLO correspond to states, but can be of any type; \n # nonexistent states simply won't be consulted. Similarly,\n # the values are all either names of states or collections \n # thereof, but that doesn't actually place any type limitation\n # on what the values _are_, other than not letting them be\n # arrays, because they will be flattened.\n unless state[MACHINE_KEY][:aliases].is_a?(Hash)\n raise InvalidMachine, \"aliases must be a hash: #{state}\"\n end\n end\n true\n end",
"def validate_state(metrics, user_options)\n OK\n end",
"def validate_progress_state\n errors.add(:progress_state, 'is invalid') unless (PROGRESS_STATE.include? self.progress_state) || (self.progress_state == nil)\n end",
"def is_valid_state(state)\n temp_state = @state\n @state = temp_state\n\n if all_valid\n @state = temp_state\n return true\n else\n @state = temp_state\n return false\n end\n end",
"def validate_state_id\n errors.add(:state_id, \"is invalid\") unless State.exists?(self.state_id)\n end",
"def validate_states(lexer)\n if !lexer.state_info.respond_to?(:each_pair)\n complain(\"States must be defined as a hash\")\n end\n\n lexer.state_info.each do |state_name, state_type|\n if ![:inclusive, :exclusive].include?(state_type)\n complain(\"State type for state #{state_name}\" \\\n \" must be :inclusive or :exclusive\")\n end\n\n if state_type == :exclusive\n if !lexer.state_error.key?(state_name)\n lexer.logger.warn(\"No error rule is defined \" \\\n \"for exclusive state '#{state_name}'\")\n end\n if !lexer.state_ignore.key?(state_name)\n lexer.logger.warn(\"No ignore rule is defined \" \\\n \"for exclusive state '#{state_name}'\")\n end\n end\n end\n end",
"def validate_split_state_type(v); end",
"def validate_state(params)\n if params[\"state\"].nil?\n raise LtiError.new(\"no state found\", :bad_request)\n end\n # match previous state cookie from oidc_login\n return unless cookies[\"lti1p3_#{params['state']}\"] != params[\"state\"]\n\n raise LtiError.new(\"state cookie not found or correct\", :bad_request)\n end",
"def validate_state?(medium)\n find_state(medium).present?\n end",
"def check_state(game)\n raise 'Not implemented'\n end",
"def valid_state?(state_class)\n state_class.is_a?(Class) && state_class < State\n end",
"def valid_state?(state)\n log :debug, \" ------ Expected state #{session[:state]}, received #{state} ------\"\n session[:state] == state\n end",
"def validate_state(*acceptable_states)\n if current_state == :unknown && acceptable_states.include?(:idle)\n idle\n elsif acceptable_states.include?(current_state)\n return\n else\n fail 'JTAG TAP Controller - An invalid state sequence has occurred!'\n end\n end",
"def valid_state?(state_class)\n super && state_class < Ladon::Watir::PageObjectState\n end",
"def test_invalid_state\n owner = people(:valid_person)\n rule = Rule.new(:person_id=>owner.id,\n :rule_name=>\"test\",\n :state=>\"aaaactive\",\n :logic=>\"and\")\n assert !rule.valid?\n # The state field should have validation errors\n assert rule.errors[:state].any?\n end",
"def validate_state_table(table = nil)\n table ||= get_state_table(no_raise: false)\n meths = self.is_a?(Module) ? instance_methods : self.class.methods\n states = table.keys\n errors = []\n table.each_pair do |state, config|\n\n # === Check optional note\n if config.key?(:note)\n item = \"#{state}[:note]\"\n note = config[:note]\n if !note.is_a?(Proc) && !note.is_a?(Symbol) && !note.is_a?(String)\n errors << \"#{item}: invalid class #{note.class}\"\n elsif note.is_a?(Symbol) && !meths.include?(note)\n errors << \"#{item}: invalid method #{note.inspect}\"\n end\n end\n\n # === Check optional method\n if config.key?(:meth)\n item = \"#{state}[:meth]\"\n meth = config[:meth]\n if !meth.is_a?(Proc) && !meth.is_a?(Symbol)\n errors << \"#{item}: invalid class #{meth.class}\"\n elsif meth.is_a?(Symbol) && !meths.include?(meth)\n errors << \"#{item}: invalid method #{meth.inspect}\"\n end\n end\n\n # === Check next states\n item = \"#{state}[:next]\"\n next_states = config[:next]\n if !config.key?(:next)\n errors << \"#{item} missing\"\n elsif next_states.is_a?(FalseClass)\n # Valid terminal state.\n elsif !next_states.is_a?(Array) && !next_states.is_a?(Symbol)\n errors << \"#{item} invalid class #{next_states.class}\"\n elsif next_states.blank?\n errors << \"#{item} empty\"\n else\n (Array.wrap(next_states) - states).each do |invalid|\n errors << \"#{item}: invalid state #{invalid.inspect}\"\n end\n end\n\n end\n raise errors.join(\"; \\n\") if errors.present?\n end",
"def set_validate_checksum_state(opts)\n opts = check_params(opts,[:states])\n super(opts)\n end",
"def validate\n validate_internal\n end",
"def set_accounting_validation_state(opts)\n opts = check_params(opts,[:states])\n super(opts)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Sees in the datacenter exists or not
|
def datacenter_exists?(name)
filter = Com::Vmware::Vcenter::Datacenter::FilterSpec.new(names: Set.new([name]))
dc_obj = Com::Vmware::Vcenter::Datacenter.new(vapi_config)
dc = dc_obj.list(filter)
raise format("Unable to find data center: %s", name) if dc.empty?
end
|
[
"def datacenter_exists?(name)\n filter = Com::Vmware::Vcenter::Datacenter::FilterSpec.new(names: Set.new([name]))\n dc_obj = Com::Vmware::Vcenter::Datacenter.new(vapi_config)\n dc = dc_obj.list(filter)\n\n raise format('Unable to find data center: %s', name) if dc.empty?\n end",
"def datacenter_exists?(name)\n dc_api = VSphereAutomation::VCenter::DatacenterApi.new(api_client)\n dcs = dc_api.list({ filter_names: name }).value\n\n raise format(\"Unable to find data center: %s\", name) if dcs.empty?\n end",
"def datacenter_exists?(folder, name)\n dc_api = VSphereAutomation::VCenter::DatacenterApi.new(api_client)\n raise_if_unauthenticated dc_api, \"checking for datacenter `#{name}`\"\n\n opts = { filter_names: name }\n opts[:filter_folders] = get_folder(folder, \"DATACENTER\") if folder\n dcs = dc_api.list(opts).value\n\n raise_if_missing dcs, format(\"Unable to find data center `%s`\", name)\n end",
"def in_remote_datacenter?\n @host.collins_location != Plugin::JetCollins.datacenter\n end",
"def exists?\n\t\t# Look for cluster\n\t\t@cluster_id = DSMAPIServer.find_server(@resource[:name], @resource[:storagecenter])\n\t\tif @cluster_id == nil\n\t\t\treturn false\n\t\telse\n\t\t\treturn true\n\t\tend\n\tend",
"def cluster_exists?\n not (search(:node, 'recipes:ceph\\:\\:mon').empty?)\n end",
"def exist?\n !@container.nil?\n end",
"def cluster_initialized?(data_dir)\n ::File.exist?(version_file_for(data_dir))\n end",
"def cluster_initialized?(data_dir)\n ::File.exist?(version_file_for(data_dir))\n end",
"def container_exists?(containername)\n response = cfreq(\"HEAD\",@storagehost,\"#{@storagepath}/#{containername}\")\n return (response.code == \"204\")? true : false ;\n end",
"def appdynamics_service_exist?\n @services.one_service?(FILTER, 'host-name')\n end",
"def data_source_exists?(name); end",
"def cluster_initialized?(data_dir)\n ::File.exists?(version_file_for(data_dir))\nend",
"def raise_if_no_exists_in_vcenter\n raise 'vCenter device does not exist at the moment' unless exists?\n end",
"def exists?\n\n\t\tbegin\n\t\t\tdom\n\t\t\tdebug \"Domain %s exists? true\" % [resource[:name]]\n\t\t\ttrue\n\t\trescue Libvirt::RetrieveError => e\n\t\t\tdebug \"Domain %s exists? false\" % [resource[:name]]\n\t\t\tfalse # The vm with that name doesnt exist\n\t\tend\n\n\tend",
"def exist?\n self.class.exists?(dn)\n end",
"def exists?\n\t\t# Find the server id\n\t\t@serv_id = DSMAPIServer.find_server(@resource[:name], @resource[:storagecenter])\n\t\t# Look for an HBA\n\t\t@hba_id = DSMAPIServer.find_hba(@serv_id, @resource[:wwn])\n\t\tif @hba_id == nil\n\t\t\treturn false\n\t\telse\n\t\t\treturn true\n\t\tend\n\tend",
"def mds_fullyconfigured?\n search(:node, 'recipes:ceph\\:\\:mds').any? { |mds| mds[:ceph][:mds] && mds[:ceph][:mds][:key] && mds[:ceph][:mds][:keyring] }\n end",
"def storage_exists?(storage_name)\n domains = sdb.list_domains[:domains]\n domains.detect {|d| d == storage_name }!=nil\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.