query
stringlengths 7
9.5k
| document
stringlengths 10
1.07M
| negatives
sequencelengths 19
19
| metadata
dict |
---|---|---|---|
Mimics file creation of /etc/bind/named.conf.options file from network.rb | def get_options_config_string
given_nameserver =(`cat /etc/resolv.conf |grep -v 127 | grep -v '^#' | grep nameserver | awk '{print $2}'`.split("\n")).join(";")
options_config = "options {\n"
options_config += " directory \"/var/cache/bind\";\n";
options_config += " auth-nxdomain no; # conform to RFC1035\n";
options_config += " listen-on-v6 { any; };\n";
options_config += " forward only;\n"
options_config += " forwarders { "+given_nameserver+"; };\n"
options_config += "};\n"
return options_config
end | [
"def build_bind_conf(node)\n node.file(:target => %(/etc/bind/named.conf), :chown => \"bind:bind\") do |file|\n build_bind_main_partial(file)\n build_bind_zone_partial(node, file)\n end\n end",
"def create_dnsmaqs_config_filename\n \"/etc/dnsmasq.d/#{@name}__#{@network_name}.conf\"\n end",
"def config_dhcp\t\n\tsystem(\"echo > /etc/dnsmasq.leases\")\n\tdhcp = File.new(\"conf/#@dhcpfile\",\"w+\")\n\tdhcp.puts(\"interface=#@interface\")\n\tdhcp.puts(\"dhcp-range=192.168.10.5,192.168.10.20\\n\")\n\tdhcp.puts(\"dhcp-leasefile=/etc/dnsmasq.leases\\n\")\n\tdhcp.puts(\"dhcp-authoritative\\n\")\n\tdhcp.puts(\"address=/#/192.168.10.1\\n\")\n\tdhcp.close\n\tsystem(\"killall dnsmasq && dnsmasq -C conf/#@dhcpfile\")\nend",
"def set_sysconfig_network( name )\n # If not already set correctly, backup, delete old line, append\n # new line.\n sudo <<-SH\n if ! grep -q '^HOSTNAME=#{name}$' /etc/sysconfig/network; then\n cp -f /etc/sysconfig/network /etc/sysconfig/network~\n sed -i '/^HOSTNAME=.*/d' /etc/sysconfig/network\n echo 'HOSTNAME=#{name}' >> /etc/sysconfig/network\n hostname #{name}\n fi\n SH\n end",
"def transport_config(opts={})\n if self.refname =~ /reverse_/\n direction = 'reverse'\n else\n direction = 'bind'\n end\n\n if self.refname =~ /_tcp/\n proto = 'tcp'\n elsif self.refname =~ /_https/\n proto = 'https'\n else\n proto = 'http'\n end\n send(\"transport_config_#{direction}_#{proto}\", opts)\n end",
"def nameserver_config\n return unless ENV.key?('MM_DNSRC') && ENV['MM_DNSRC']\n\n address, port = ENV['MM_DNSRC'].split(/:/)\n\n {\n nameserver_port: [[address, port.to_i]]\n }\n rescue StandardError\n {}\n end",
"def host_config\n { 'Binds' => @binds,\n 'Privileged' => @privileged,\n 'NetworkMode' => @networkmode.to_s }\n end",
"def genConf\n conf=\"auto #{@device}\\n\"\n if (ip != nil && netmask != nil)\n conf+=%(iface #{@device} inet static\n address #{@ip}\n netmask #{@netmask}\n)\n else\n conf+=\"iface #{@device} inet dhcp\\n\"\n end\n end",
"def compare_named_conf_options(data)\n rgx = /options {\n directory \"\\/var\\/cache\\/bind\";\n auth-nxdomain no; \\# conform to RFC1035\n listen-on-v6 { any; };\n forward only;\n forwarders { (\\S+) };\n};/\n match_regex(rgx, data)\nend",
"def apply_network_settings container, networking\n OpenNebula.log_debug \"Configuring network\"\n nic_settings = {\n # ifname and host_mac\n :ipadd => networking[:ip]\n }\n\n container.command \"\\\"echo 'nameserver #{networking[:nameserver]}' > /etc/resolv.conf\\\"\"\n container.set nic_settings\n end",
"def config_file\n <<~EOS\n #!/bin/sh\n for opt; do :; done\n case \"$opt\" in\n --version) opt=\"--modversion\";;\n --cflags|--libs) ;;\n *) exit 1;;\n esac\n pkg-config \"$opt\" nss\n EOS\n end",
"def network_config\n return '--net=host' unless @vpn_tunnel\n\n hostname = `hostname`.chomp\n \"--net=container:#{hostname}\"\n end",
"def build_haproxy_file\n write_to_file_for(\"haproxy\") do\n servers=<<-EOS\n#{nodes.collect {|node| node.haproxy_entry}.join(\"\\n\")}\n EOS\n open(Application.haproxy_config_file).read.strip ^ {:servers => servers, :host_port => Application.host_port}\n end\n end",
"def config_client_LDAP\n\t\tldap_conf = File.read('/etc/openldap/ldap.conf')\n\n\t\t# Set the BASE suffix to match the BASE suffix from the slapd conf file\n\t\tldap_conf = ldap_conf.gsub(/#BASE\\tdc=example, dc=com/,\"BASE dc=cit470_Team_4,dc=nku,dc=edu\")\n\n\t\t\n\t\t# Write the ldap.conf file\n\t\tFile.open('/etc/openldap/ldap.conf','w'){|file| file.puts ldap_conf}\n\n\t\t# Configure LDAP ACL to allow password changes\n\n\t\tldap=\"access to attrs=userPassword\\nby self write\\nby anonymous auth\\nby * none\\naccess to *\\nby self write\\nby * read\"\n\t\tFile.open('/etc/openldap/ldap.conf','a') {|file| file.puts ldap}\n\t\t\n\tend",
"def create_ubuntu_lxc_config(options)\n tmp_file = \"/tmp/lxc_\"+options['name']\n options['ip'] = single_install_ip(options)\n options['clientdir'] = options['lxcdir']+\"/\"+options['name']\n config_file = options['clientdir']+\"/config\"\n message = \"Information:\\tCreating configuration for \"+options['name']\n command = \"cp #{config_file} #{tmp_file}\"\n execute_command(options,message,command)\n copy = []\n info = IO.readlines(config_file)\n info.each do |line|\n if line.match(/hwaddr/)\n if options['mac'].to_s.match(/[0-9]/)\n output = \"lxc.network.hwaddr = \"+options['mac']+\"\\n\"\n copy.push(output)\n output = \"lxc.network.ipv4 = \"+options['ip']+\"\\n\"\n copy.push(output)\n else\n copy.push(line)\n output = \"lxc.network.ipv4 = \"+options['ip']+\"\\n\"\n copy.push(output)\n end\n else\n copy.push(line)\n end\n end\n copy = copy.join\n File.open(tmp_file,\"w\") { |file| file.write(copy) }\n message = \"Information:\\tCreating network configuration file \"+config_file\n command = \"cp #{tmp_file} #{config_file} ; rm #{tmp_file}\"\n execute_command(options,message,command)\n print_contents_of_file(options,\"\",config_file)\n file = File.open(tmp_file,\"w\")\n gateway = options['q_struct']['gateway'].value\n broadcast = options['q_struct']['broadcast'].value\n netmask = options['q_struct']['netmask'].value\n network = options['q_struct']['network_address'].value\n nameserver = options['q_struct']['nameserver'].value\n file.write(\"# The loopback network interface\\n\")\n file.write(\"auto lo\\n\")\n file.write(\"iface lo inet loopback\\n\")\n file.write(\"\\n\")\n file.write(\"auto eth0\\n\")\n file.write(\"iface eth0 inet static\\n\")\n file.write(\"address #{options['ip']}\\n\")\n file.write(\"netmask #{netmask}\\n\")\n file.write(\"gateway #{gateway}\\n\")\n file.write(\"network #{network}\\n\")\n file.write(\"broadcast #{broadcast}\\n\")\n file.write(\"dns-nameservers #{nameserver}\\n\")\n file.write(\"post-up route add default gw 192.168.1.#{options['gatewaynode']}\\n\")\n file.write(\"\\n\")\n file.close\n options['clientdir'] = options['clientdir']+\"/rootfs\"\n net_file = options['clientdir']+\"/etc/network/interfaces\"\n message = \"Information:\\tCreating network interface file \"+net_file\n command = \"cp #{tmp_file} #{net_file} ; rm #{tmp_file}\"\n execute_command(options,message,command)\n user_username = options['q_struct']['user_username'].value\n user_uid = options['q_struct']['user_uid'].value\n user_gid = options['q_struct']['user_gid'].value\n user_crypt = options['q_struct']['user_crypt'].value\n root_crypt = options['q_struct']['root_crypt'].value\n user_fullname = options['q_struct']['user_fullname'].value\n user_home = options['q_struct']['user_home'].value\n user_shell = options['q_struct']['user_shell'].value\n passwd_file = options['clientdir']+\"/etc/passwd\"\n shadow_file = options['clientdir']+\"/etc/shadow\"\n info = IO.readlines(passwd_file)\n file = File.open(tmp_file,\"w\")\n info.each do |line|\n field = line.split(\":\")\n if field[0] != \"ubuntu\" and field[0] != \"#{user_username}\"\n file.write(line)\n end\n end\n output = user_username+\":x:\"+user_uid+\":\"+user_gid+\":\"+user_fullname+\":\"+user_home+\":\"+user_shell+\"\\n\"\n file.write(output)\n file.close\n message = \"Information:\\tCreating password file\"\n command = \"cat #{tmp_file} > #{passwd_file} ; rm #{tmp_file}\"\n execute_command(options,message,command)\n print_contents_of_file(options,\"\",passwd_file)\n info = IO.readlines(shadow_file)\n file = File.open(tmp_file,\"w\")\n info.each do |line|\n field = line.split(\":\")\n if field[0] != \"ubuntu\" and field[0] != \"root\" and field[0] != \"#{user_username}\"\n file.write(line)\n end\n if field[0] == \"root\"\n field[1] = root_crypt\n copy = field.join(\":\")\n file.write(copy)\n end\n end\n output = user_username+\":\"+user_crypt+\":::99999:7:::\\n\"\n file.write(output)\n file.close\n message = \"Information:\\tCreating shadow file\"\n command = \"cat #{tmp_file} > #{shadow_file} ; rm #{tmp_file}\"\n execute_command(options,message,command)\n print_contents_of_file(options,\"\",shadow_file)\n client_home = options['clientdir']+user_home\n message = \"Information:\\tCreating SSH directory for \"+user_username\n command = \"mkdir -p #{client_home}/.ssh ; cd #{options['clientdir']}/home ; chown -R #{user_uid}:#{user_gid} #{user_username}\"\n execute_command(options,message,command)\n # Copy admin user keys\n rsa_file = user_home+\"/.ssh/id_rsa.pub\"\n dsa_file = user_home+\"/.ssh/id_dsa.pub\"\n key_file = client_home+\"/.ssh/authorized_keys\"\n if File.exist?(key_file)\n system(\"rm #{key_file}\")\n end\n [rsa_file,dsa_file].each do |pub_file|\n if File.exist?(pub_file)\n message = \"Information:\\tCopying SSH public key \"+pub_file+\" to \"+key_file\n command = \"cat #{pub_file} >> #{key_file}\"\n execute_command(options,message,command)\n end\n end\n message = \"Information:\\tCreating SSH directory for root\"\n command = \"mkdir -p #{options['clientdir']}/root/.ssh ; cd #{options['clientdir']} ; chown -R 0:0 root\"\n execute_command(options,message,command)\n # Copy root keys\n rsa_file = \"/root/.ssh/id_rsa.pub\"\n dsa_file = \"/root/.ssh/id_dsa.pub\"\n key_file = options['clientdir']+\"/root/.ssh/authorized_keys\"\n if File.exist?(key_file)\n system(\"rm #{key_file}\")\n end\n [rsa_file,dsa_file].each do |pub_file|\n if File.exist?(pub_file)\n message = \"Information:\\tCopying SSH public key \"+pub_file+\" to \"+key_file\n command = \"cat #{pub_file} >> #{key_file}\"\n execute_command(options,message,command)\n end\n end\n # Fix permissions\n message = \"Information:\\tFixing SSH permissions for \"+user_username\n command = \"cd #{options['clientdir']}/home ; chown -R #{user_uid}:#{user_gid} #{user_username}\"\n execute_command(options,message,command)\n message = \"Information:\\tFixing SSH permissions for root \"\n command = \"cd #{options['clientdir']} ; chown -R 0:0 root\"\n execute_command(options,message,command)\n # Add sudoers entry\n sudoers_file = options['clientdir']+\"/etc/sudoers.d/\"+user_username\n message = \"Information:\\tCreating sudoers file \"+sudoers_file\n command = \"echo 'administrator ALL=(ALL) NOPASSWD:ALL' > #{sudoers_file}\"\n execute_command(options,message,command)\n # Add default route\n rc_file = options['clientdir']+\"/etc/rc.local\"\n info = IO.readlines(rc_file)\n file = File.open(tmp_file,\"w\")\n info.each do |line|\n if line.match(/exit 0/)\n output = \"route add default gw #{gateway}\\n\"\n file.write(output)\n file.write(line)\n else\n file.write(line)\n end\n end\n file.close\n message = \"Information:\\tAdding default route to \"+rc_file\n command = \"cp #{tmp_file} #{rc_file} ; rm #{tmp_file}\"\n execute_command(options,message,command)\n return\nend",
"def config_slapd\n\t\tslapd_conf = File.read('/etc/openldap/slapd.conf')\n\n\t\t# Disable LDAPv2 connections\n\t\tslapd_conf = slapd_conf.gsub(/allow bind_v2/,\"#allow bind_v2\")\n\t\t# Configure the suffix, rootdn, rootpw\n\t\tslapd_conf = slapd_conf.gsub(/suffix\\t\\t\\\"dc=my-domain,dc=com\\\"/,\"suffix \\\"dc=cit470_Team_4,dc=nku,dc=edu\\\"\")\n\t\tslapd_conf = slapd_conf.gsub(/rootdn\\t\\t\\\"cn=Manager,dc=my-domain,dc=com\\\"/,\"rootdn \\\"cn=Manager,dc=cit470_team_4,dc=nku,dc=edu \\\"\") \n\t\tslapd_conf = slapd_conf.gsub(/# rootpw\\t\\t\\{crypt\\}ijFYNcSNctBYg/,\"\\nrootpw \\{SSHA\\}3YGEc7Na9bdBANZ6nahRKhYxn3XCJED4\")\n\n\t\t# Write the slapd.conf file\n\t\tFile.open('/etc/openldap/slapd.conf','w'){|file| file.puts slapd_conf}\n\n\tend",
"def conf_example(port = 8080)\n <<~EOS\n listen: #{port}\n hosts:\n \"127.0.0.1.xip.io:#{port}\":\n paths:\n /:\n file.dir: #{var}/h2o/\n EOS\n end",
"def network_settings_file\n \"#{@path}#{NETWORK_FILE_SUFFIX}\"\n end",
"def new_bc\n bc = Bind9mgr::NamedConf.new( '/etc/bind/myzones.conf' )\n bc.main_ns = 'ns.example.com'\n bc.main_server_ip = '192.168.1.200'\n bc.support_email = 'support@example.com'\n bc.load_with_zones\n bc\nend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether the list of forwarders ip contain the same elements as named servers in any order | def compare_forwarders(namedservers=[])
temp_array = []
File.foreach('/etc/bind/named.conf.local') do |line|
if line =~ /forwarders/
temp = line.strip
temp = temp.scan(/(forwarders {[\d,.,;]*})/).last.first
temp_array = temp.scan(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)
end
end
if namedservers.sort == temp_array.sort
return temp_array
else
return namedservers
end
end | [
"def validate_list?(args)\n @group.each do |item|\n return false if item[:host] == args[:host] && item[:port] == args[:port]\n end\n return true\n end",
"def ip_address_match?(_server)\n status = Acquia::FieldsStatus.new\n server_rec = fields_xmlrpc.call2('acquia.fields.find.one', 'server', {'external_fqhn' => _server, 'status' => 0})\n ec2_ext_fqhn = server_rec['external_ec2']\n external_ip = server_rec['external_ip']\n ec2_ext_ip = Resolv.getaddress(ec2_ext_fqhn)\n server_ip = Resolv.getaddress(_server)\n if (server_ip != external_ip)\n status.add_fail(\"#{_server} dns entry #{server_ip} does not match the external_ip #{external_ip}\")\n end\n if (server_ip != ec2_ext_ip)\n status.add_fail(\"#{_server} dns entry #{server_ip} does not match the ec2 dns entry #{ec2_ext_ip}\")\n end\n return status\n end",
"def same_entry\n # only if we found the ip in the first place\n # cause if we didn't then \n if @hosts_exists \n # we care about order here so if these things dont match force a rewrite/order\n # make sure we are comparing the same type\n return @entries.join(\" \") == cast_entries\n end \n false\nend",
"def compare_name_servers(name_servers, domain_name)\n\n domain_has_ns = FALSE\n\n name_servers.each do |ns|\n # Note: make hash of vcn.bc.ca and do check in the future\n if ns.split('.', 2).last.to_s == DOMAIN_TO_COMPARE \n domain_has_ns = TRUE\n end\n\n end\n\n if domain_has_ns == FALSE\n puts domain_name.to_s.chomp + \" does not have vcn name servers\"\n end\n\nend",
"def is_forwarded_already(extra_in_use, hostport, hostip)\n hostip = '*' if hostip.nil? || hostip.empty?\n # ret. false if none of the VMs we spun up had this port forwarded.\n return false if not extra_in_use.has_key?(hostport)\n\n # ret. true if the user has requested to bind on all interfaces but\n # we already have a rule in one the VMs we spun up.\n if hostip == '*'\n if extra_in_use.fetch(hostport).size != 0\n return true\n else\n return false\n end\n end\n\n return extra_in_use.fetch(hostport).include?(hostip)\n end",
"def server_in_pool?( host, port )\n server_list = servers\n !server_list.select{ |s| s[:addr] == host and s[:port] == port.to_i}.empty?\n end",
"def known_host_hash?(hostlist, entries); end",
"def nonmatching_hostips_found?\n @project.get_element('networks').each do |network_name, network_data|\n network = network_data[:network]\n host_ip = network_data[:hostip]\n next unless network && host_ip\n\n host_ip_ip = IPAddr.new(host_ip)\n network_ip = IPAddr.new(network)\n\n mark(\"Network Host ip #{host_ip} is not within network range\" \\\n \"#{network} of network #{network_name}\", 'network', network_name) unless\n host_ip_ip.in_range_of?(network_ip)\n end\n end",
"def lists_server?(server)\n servers.include?(server.address.to_s)\n end",
"def ip_used?(ip)\n # select builds a new Array of all the elements of the callee which return\n # true in the given block.\n connection.servers.select {|s| s.state == 'running' && s.private_ip_address == ip}.any?\n end",
"def host_uniqueness?(zone, host_list, vdc_id = -1)\n all_hosts = \"\"\n zone.vdcs.all.each{|vdc|\n if vdc.hosts != nil and !vdc.hosts.empty? and vdc.id != vdc_id\n all_hosts << ',' << vdc.hosts\n end\n }\n\n all_hosts = all_hosts.split(',')\n\n host_list.split(\",\").each{|host|\n return false if all_hosts.include?(host)\n }\n\n return true\n end",
"def verify_servers(servers)\n Log.logger.info(\"Verifying servers: \" + servers.map{|id,s| s['name']}.join(', '))\n servers.each { |id,s|\n\n Log.logger.info(\"Checking server #{id}:#{s['name']} has valid EC2 ID [#{s['ec2_id']}]\")\n assert_match(/^i-[a-f0-9]+$/, s['ec2_id'], \"Server #{s['name']} has an invalid EC2 ID [#{s['ec2_id']}]\")\n\n Log.logger.info(\"Checking server #{id}:#{s['name']} has valid FQHN #{s['external_fqhn']}\")\n assert_not_equal('', s['external_fqhn'], \"Server #{s['name']} has no FQHN\")\n\n # Verify that the server's DNS entry is correct. The TTL is 60 seconds.\n condition = lambda {\n begin\n public_ip = Resolv.getaddress(s['external_fqhn'])\n Log.logger.info(\"#{s['external_fqhn']} resolves to #{public_ip}\")\n s['external_ip'] == public_ip\n rescue Resolv::ResolvTimeout\n Log.logger.info(\"#{site_info['default_fqdn']} resolves to <timeout>\")\n false\n end\n }\n CommonUtil.wait_until(90, 1, condition, true, \"#{s['external_fqhn']} to resolve to #{s['external_ip']}\")\n\n # Verify all servers are up\n server_status = self.server_up?(s['external_fqhn'])\n assert(server_status.passed, \"Server #{s['name']} does not appear to be up: #{server_status.get_fail_message}\")\n\n # Verify puppet on all servers\n status = self.puppet_up?(s['external_fqhn'])\n assert(status.passed, \"Server #{s['name']} does not appear to have puppet properly configured\\n\" + status.get_fail_message)\n\n # Now puppet has finished, verify that the default launch keys are no\n # longer installed. This assumes the person running the tests has a\n # personal key in the authorized_keys file managed by puppet. We've added\n # buildbot's key.\n ssh(s['external_fqhn']) {|ss|\n (ec,out) = ss.attempt('grep -E \"hosting|gardens\" /root/.ssh/authorized_keys*')\n assert_equal(1, ec, \"Server #{s['name']} has no default ssh keys installed\")\n }\n\n # Verify netrc on all servers\n status = self.correct_netrc?(s['external_fqhn'], (s['name'] =~ /^managed/) ? 3 : (s['name'] =~ /^backup/ ? 3 : 1))\n assert(status.passed, \"Server #{s['name']} has an incorrect .netrc:\\n\" + status.get_fail_message)\n\n # Verify splunk on all servers\n # TODO: Remove this? We aren't using splunk.\n # status = self.splunk_up?(s['external_fqhn'])\n # assert(status.passed, \"Server #{s['name']} does not appear to have splunk properly configured\\n\" + status.get_fail_message)\n\n # Verify services based on server type\n if (s['type'] =~ /web|ded|staging|managed/)\n status = self.webserver_up?(s['external_fqhn'])\n assert(status.passed, \"Server #{s['name']} does not appear to have apache httpd properly configured\\n\" + status.get_fail_message)\n end\n\n if (s['type'] =~ /svn/)\n status = self.svnserver_up?(s['external_fqhn'])\n assert(status.passed, \"Server #{s['name']} does not appear to have svn properly configured\\n\" + status.get_fail_message)\n end\n\n if (s['type'] =~ /bal/)\n status = self.balancer_up?(s['external_fqhn'])\n assert(status.passed, \"Server #{s['name']} does not appear to have nginx properly configured\\n\" + status.get_fail_message)\n end\n\n if (s['type'] =~ /ded|staging|dbmaster/)\n status = self.dbserver_up?(s['external_fqhn'])\n assert(status.passed, \"Server #{s['name']} does not appear to have mysqld properly configured\\n\" + status.get_fail_message)\n end\n }\n 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 servers_up\n servers.values.find_all do |server|\n server.up?(name)\n end\n end",
"def is_local_host\n require 'ipaddr'\n begin\n local = IPAddr.new(\"127.0.0.0/8\")\n private1 = IPAddr.new(\"10.0.0.0/8\")\n private2 = IPAddr.new(\"172.16.0.0/12\")\n private3 = IPAddr.new(\"192.168.0.0/16\")\n private4 = IPAddr.new(\"85.230.85.45\")\n private5 = IPAddr.new(\"94.234.170.18\")\n\n if local.include?(request.remote_ip)\n return true\n end\n if private1.include?(request.remote_ip)\n return true\n end\n if private2.include?(request.remote_ip)\n return true\n end\n if private3.include?(request.remote_ip)\n return true\n end\n if private4.include?(request.remote_ip)\n return true\n end\n if private5.include?(request.remote_ip)\n return true\n end\n return false\n rescue\n return false\n end\n end",
"def same_host_as?(db)\n @ip == db.ip\n end",
"def nip_test(a_ip, b_ip)\n 0.upto(3) { |x| return false if (a_ip[x] != b_ip[x]) }\n true\n end",
"def hosts_eql?(a, b) # rubocop:disable Naming/UncommunicativeMethodParamName\n parse_host(a) == parse_host(b)\n rescue IPAddr::InvalidAddressError\n false\n end",
"def check_netdbs\n continue = true\n if (address = @resolver.getaddress(name) rescue false)\n errors.add_to_base \"#{name} is already in DNS with an address of #{address}\"\n continue = false\n end\n if (hostname = @resolver.getname(ip) rescue false)\n errors.add_to_base \"#{ip} is already in the DNS with a name of #{hostname}\"\n continue = false\n end\n if (entry = @dhcp.get subnet.number, mac) and @dhcp.error.empty?\n errors.add_to_base \"#{subnet}/#{mac} is already managed by DHCP and configures #{entry[\"title\"]}\"\n continue = false\n end\n continue\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /operations GET /operations.xml GET /operations.js GET /servers/1/operations GET /servers/1/operations.xml GET /servers/1/operations.js | def index
@server = Server.find(params[:server_id])
joins = 'INNER JOIN instances ON instances.id = operations.instance_id'
conditions = [ 'instances.server_id = ?', @server.id ]
params[:sort] = 'created_at_reverse' if params[:sort].blank?
@operations = Operation.search(params[:search], params[:page], joins, conditions, params[:sort])
respond_to do |format|
if @operations
format.html
format.xml { render :xml => @operations }
format.js { render :partial => 'operations/list', :layout => false }
else
flash[:error] = @error_message
format.html { redirect_to :back }
format.xml { render :xml => @operation.errors, :status => :unprocessable_entity }
format.js { render :partial => 'shared/error', :layout => false }
end
end
end | [
"def index\n @operations = Operation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @operations }\n end\n end",
"def rest_routes\n\t\t\t\t\t[\n\t\t\t\t\t\t{ method: :GET, path: '/', action: :index },\n\t\t\t\t\t\t{ method: :POST, path: '/', action: :create },\n\t\t\t\t\t\t{ method: :GET, path: '/', action: :show },\n\t\t\t\t\t\t{ method: :PUT, path: '/', action: :update },\n\t\t\t\t\t\t{ method: :DELETE, path: '/', action: :delete }\n\t\t\t\t\t]\n\t\t\t\tend",
"def servers(service_id)\n request :get, \"/services/#{service_id}/servers\"\n end",
"def linodeList\n \tmake_request this_method\n end",
"def servers_detailed()\n return get_request(address(\"/servers/detail\"), @token)\n end",
"def list_operations()\n\t\treturn @service.operations\n\tend",
"def do_GET(request, response)\n\t\t\t\tstatus = 400\n\t\t\t\tcontent_type = body = ''\n\t\t\t\tif not trusted(request)\n\t\t\t\t\tstatus = 403\n\t\t\t\telse\n\t\t\t\t\tpath = (request.path[-1,1] == '/' ? request.path.chop : request.path)\n\t\t\t\t\tif path == '/pid' and (request.peeraddr[2] == 'localhost' or request.peeraddr[3] == '127.0.0.1')\n\t\t\t\t\t\tstatus, content_type, body = save_pid\n\n\t\t\t\t\telsif path == '/state'\n\t\t\t\t\t\tstatus, content_type, body = get_state\n\n\t\t\t\t\telsif path == '/sfpstate'\n\t\t\t\t\t\tstatus, content_type, body = get_state({:as_sfp => true})\n\n\t\t\t\t\telsif path =~ /^\\/state\\/.+/\n\t\t\t\t\t\tstatus, content_type, body = get_state({:path => path[7, path.length-7]})\n\n\t\t\t\t\telsif path =~ /^\\/sfpstate\\/.+/\n\t\t\t\t\t\tstatus, content_type, body = get_state({:path => path[10, path.length-10]})\n\n\t\t\t\t\telsif path == '/model'\n\t\t\t\t\t\tstatus, content_type, body = get_model\n\n\t\t\t\t\telsif path =~ /\\/model\\/cache\\/.+/\n\t\t\t\t\t\tstatus, content_type, body = self.get_cache_model({:name => path[13, path.length-13]})\n\n\t\t\t\t\telsif path == '/bsig'\n\t\t\t\t\t\tstatus, content_type, body = get_bsig\n\n\t\t\t\t\telsif path == '/bsig/flaws'\n\t\t\t\t\t\tstatus = 200\n\t\t\t\t\t\tcontent_type = 'application/json'\n\t\t\t\t\t\tbody = JSON.generate(Sfp::Agent.bsig_engine.get_flaws)\n\n\t\t\t\t\telsif path =~ /^\\/sfp\\/.+/\n\t\t\t\t\t\tstatus, content_type, body = get_sfp({:module => path[10, path.length-10]})\n\n\t\t\t\t\telsif path == '/modules'\n\t\t\t\t\t\tmods = {}\n\t\t\t\t\t\tSfp::Agent.get_modules.each { |name,data| mods[name] = data[:hash] }\n\t\t\t\t\t\tstatus, content_type, body = [200, 'application/json', JSON.generate(mods)]\n\n\t\t\t\t\telsif path == '/agents'\n\t\t\t\t\t\tstatus, content_type, body = [200, 'application/JSON', JSON.generate(Sfp::Agent.get_agents)]\n\n\t\t\t\t\telsif path == '/log'\n\t\t\t\t\t\tstatus, content_type, body = [200, 'text/plain', Sfp::Agent.get_log(100)]\n\n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t\tresponse.status = status\n\t\t\t\tresponse['Content-Type'] = content_type\n\t\t\t\tresponse.body = body\n\t\t\tend",
"def GET; end",
"def show\n @operation = Operation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @operation }\n end\n end",
"def show\n @title = \"Show Operations\"\n @operation = Operation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @operation }\n end\n end",
"def op_endpoint; end",
"def resource_operations; end",
"def get endpoint\n do_request :get, endpoint\n end",
"def operation(verb, path)\n @resources.each do |resource|\n resource[\"apis\"].each do |api|\n api[\"operations\"].each do |op|\n return op if op[\"httpMethod\"] == verb.to_s && path == api[\"path\"]\n end\n end\n end\n end",
"def index\n @soaplab_servers = SoaplabServer.paginate(:page => @page,\n :per_page => @per_page, \n :order => 'id DESC')\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @soaplab_servers }\n end\n end",
"def show\n @operation = Operation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @operation }\n end\n end",
"def network_services_all\n begin\n print_verbose \"Retrieving all network services\"\n response = RestClient.get \"#{@url}network/services\", {:params => {:token => @token}}\n details = JSON.parse(response.body)\n print_good \"Retrieved #{details['count']} network services\"\n details\n rescue => e\n print_error \"Could not retrieve network services: #{e.message}\"\n end\nend",
"def get_netconf_operations(node_name)\n get_uri = \"/restconf/operations/opendaylight-inventory:nodes/node/\"\\\n \"#{node_name}/yang-ext:mount\"\n response = @rest_agent.get_request(get_uri)\n check_response_for_success(response) do |body|\n if body.has_key?('operations')\n NetconfResponse.new(NetconfResponseStatus::OK, body['operations'])\n else\n NetconfResponse.new(NetconfResponseStatus::DATA_NOT_FOUND)\n end\n end\n end",
"def method_missing(op, *args)\n if client.operations.include?(op)\n request op, *args\n else\n fail NoMethodError, op\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the next/upcoming show date | def next_show_date
interval = SATURDAY - Date.today().wday
interval = SATURDAY if (interval < 0)
Date.today + interval
end | [
"def next_show(m, opts)\n response = \"\"\n\n event = live_event\n\n if event\n response << \"#{event.summary} is live right now! \"\n end\n\n event = next_event\n\n if event\n response << \"Next show is #{event.summary}\"\n response << \" in #{in_how_long(event, opts[:tz])}\"\n else\n response << \"No upcoming show found in the next week\"\n end\n\n m.reply response\n end",
"def next_date\n return @refdate.advance(@navigator => +1)\n end",
"def next_date\n next_observance.try(:start_on) || 100.years.from_now.to_date\n end",
"def next_date\n if course.is_training?\n self.start_date\n else\n # See http://stackoverflow.com/a/7621385/900301\n today = Date.today\n if week_day > today.wday\n today + (week_day - today.wday)\n else\n (today + (7 - today.wday)).next_day(week_day)\n end\n end\n end",
"def next_active_date\n\t\tget_active_date\n\tend",
"def calculate_next_ship \n\t\tcalculated_date=Date.new\n\t\tif self.next_shipment != nil\n\t\tif self.next_shipment < Date.today\n\t\t\tif subscription_frequency == \"4week\"\n\t\t\t\tcalculated_date = self.next_shipment + 28.day\n\t\t\t\tself.next_shipment = \tcalculated_date\t\t\n\t\t\tend\n\t\t\t\tif subscription_frequency == \"2week\"\n\t\t\t\tcalculated_date = self.next_shipment + 14.day\n\t\t\t\tself.next_shipment = \tcalculated_date\t\t\n\t\t\tend\n\t\tend\n\t\tend\n\tend",
"def set_paystack_next_charge_date\n if @member.account_detail.created_at.to_date < Date.today - 1.day\n date = DateTime.now\n else\n date = @member.account_detail.subscribe_date\n end\n if @member.subscription_plan.duration == \"weekly\"\n start_date = date.next_week.strftime('%FT%T%:z').to_s\n elsif @member.subscription_plan.duration == \"monthly\"\n start_date = date.next_month.strftime('%FT%T%:z').to_s\n elsif @member.subscription_plan.duration == \"quarterly\"\n start_date = (date + 90.days).strftime('%FT%T%:z').to_s\n elsif @member.subscription_plan.duration == \"annually\"\n start_date = date.next_year.strftime('%FT%T%:z').to_s\n end\n return start_date\n end",
"def upcoming_count\n count = 0\n all_shows = Show.where(artist_id: id)\n all_shows.each do |show|\n if show.start_date >= Date.today\n puts show.start_date\n count += 1\n end\n end\n count\n end",
"def upcoming?(date=Time.now)\n date < self.start_date\n end",
"def find_next_date_set\n @next_day = @selected_date + 1\n @next_week = @selected_date + 7\n \n if (@month % 12) == 0\n new_day = @day\n while !Date.valid_civil?(@year + 1, 12, new_day)\n new_day = new_day - 1\n end\n @next_month = Date.new(@year+1, 1, new_day)\n else\n new_day = @day\n while !Date.valid_civil?(@year, @month+1, new_day)\n new_day = new_day - 1\n end\n @next_month = Date.new(@year, @month+1, new_day)\n end\n \n new_day = @day\n while !Date.valid_civil?(@year + 1, @month, new_day)\n new_day = new_day - 1\n end\n @next_year = Date.new(@year+1, @month, new_day) \n end",
"def next_charge_date\n self.paid_through||Date.today\n end",
"def waiting_date (last_promo_item, plan)\n num = ((last_promo_item.validez - last_promo_item.created_at)/60/60/24).round\n case num\n when 7\n if (plan == 'plus')\n last_promo_item.validez + 3.days\n elsif (plan == 'basic')\n last_promo_item.validez + 10.days\n end\n when 3\n if (plan == 'plus')\n last_promo_item.validez + 2.days\n elsif (plan == 'basic')\n last_promo_item.validez + 5.days\n end\n when 1\n if (plan == 'plus')\n last_promo_item.validez + 1.days\n elsif (plan == 'basic')\n last_promo_item.validez + 2.days\n end\n else\n #Error -> Promo lasted and unselectable number of days\n end\n\n end",
"def next_show_url\n show_number = latest_show_link['href'].scan(/\\/(\\d+)\\//)[0][0]\n next_show_number = show_number.to_i.next.to_s\n latest_show_link['href'].sub(show_number, next_show_number)\n end",
"def waiting_date(last_promo_item, plan)\n num = ((last_promo_item.validez - last_promo_item.created_at) / 60 / 60 / 24).round\n case num\n when 7\n if plan == 'plus'\n last_promo_item.validez + 3.days\n elsif plan == 'basic'\n last_promo_item.validez + 10.days\n end\n when 3\n if plan == 'plus'\n last_promo_item.validez + 2.days\n elsif plan == 'basic'\n last_promo_item.validez + 5.days\n end\n when 1\n if plan == 'plus'\n last_promo_item.validez + 1.days\n elsif plan == 'basic'\n last_promo_item.validez + 2.days\n end\n else\n # Error -> Promo lasted and unselectable number of days\n end\n end",
"def next_event(show = nil)\n if show.nil?\n @events\n else\n @events.select do |event|\n event.summary.start_with? show.title\n end\n end.select do |event|\n event.after? Time.now\n end.first\n end",
"def <=>(other)\n return 0 if !next_show_date && !other.next_show_date\n return 1 if !next_show_date\n return -1 if !other.next_show_date\n next_show_date <=> other.next_show_date\n end",
"def get_display_interview_date\n closest_past_interview = nil\n closest_future_interview = nil\n interviews.each do |i|\n if i.interview_date\n if (i.interview_date >= Date.today)\n closest_future_interview ||= i.interview_date \n if (i.interview_date < closest_future_interview)\n closest_future_interview = i.interview_date\n end\n else\n closest_past_interview ||= i.interview_date\n if (i.interview_date > closest_past_interview)\n closest_past_interview = i.interview_date\n end\n end\n end\n end\n\n if closest_future_interview \n return closest_future_interview\n elsif closest_past_interview\n return closest_past_interview\n else\n return nil\n end\n\n end",
"def next_date!\n Kernel.loop do\n @date += 1.day\n return if possible?\n end\n end",
"def next_day\r\n if @next_day.nil?\r\n @next_day = convert_day_to_date(current_day).tomorrow.strftime('%Y%m%d')\r\n end\r\n @next_day\r\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
New method to determine if a particular command dispatcher it already .. enstacked .. gooood | def dispatched_enstacked(dispatcher)
inst = dispatcher.new(self)
dispatcher_stack.each do |disp|
return true if disp.name == inst.name
end
false
end | [
"def has_command?(notification_name)\n @controller.has_command?(notification_name)\n end",
"def dispatch_conflict?\n dispatch_modifier? && active?\n end",
"def command?(name)\n !receiver && method?(name)\n end",
"def has_command?(notification_name)\n !@command_map[notification_name].nil?\n end",
"def run_command?\n @run_with == :command\n end",
"def has_subcommand?(name)\n commands.key?(name)\n end",
"def command_exists? name\n @commands[name.to_s]\n end",
"def has_command!(name, referer = self.class)\n name.split(':').inject(referer){|cur,look|\n cur.const_get(command2module(look))\n }\n rescue NameError => ex\n raise NoSuchCommand, \"No such command #{name}\", ex.backtrace\n end",
"def command_exists?\n COMMANDS.include? @command\n end",
"def plugins_respond_to?(cmd_name)\n\t\t\treturn respond_to?(\"command_#{cmd_name}\".to_sym)\n\t\tend",
"def command_is?(command)\n @command.to_s == command\n end",
"def command_exists?(name)\n @commands[name.to_s]\n end",
"def subcommand? instance, name\n # It doesn't look like {Thor::Group} has `.subcommands`, so test for\n # that first.\n return false unless instance.class.respond_to?( :subcommands )\n \n # See if the names is in the subcommands\n instance.class.subcommands.include? name.to_s\n end",
"def plugins_respond_to?(cmd_name)\n return respond_to?(\"command_#{cmd_name}\".to_sym)\n end",
"def current_dispatcher\n self.dispatcher_stack[0]\n end",
"def current_dispatcher\n\t\tself.dispatcher_stack[0]\n\tend",
"def cmux_cmd?(cmd)\n Commands::CMDS.key?(cmd)\n end",
"def has_shortcuts?(cmd)\n command_shortcuts(cmd)\n end",
"def slack_command?\n @isslack_command ||= (self.slack_command == 'true')\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a rental time in human readable format. If the rental is still active, the value shows for how long it is rented until now, if the rental is already returned it shows the difference between created time and return time === Return | def rental_time
from_date = (self.returned? ? self.returned_at : Time.current).utc
TimeDifference.between(from_date, self.created_at.utc, true).in_general.humanize
end | [
"def last_active_time\n time = replies.any? ? replies.last.created_at.localtime : created_at.localtime\n time.strftime(\"%-m/%d/%Y, %l:%M, %P\")\n end",
"def personal_estimated_seating_time(restaurant)\n user_reservation = restaurant.reservations.for_user(params[:id]).waiting.by_time_reserved.first\n\n # puts \"*** user_reservation is #{user_reservation.inspect}\"\n\n return nil if user_reservation.nil?\n\n waiting_list = restaurant.reservations.waiting.by_time_reserved\n user_spot_on_wl = find_spot_in_line(user_reservation, waiting_list)\n\n # puts '-------- personal estimated seating time user_spot_on_wl is '\n # puts user_spot_on_wl\n\n time = estimated_seating_time(restaurant, user_spot_on_wl)\n\n time.strftime('%Y/%m/%d %H:%M')\n end",
"def lead_time\n if completed_at\n completed_at - created_at\n else\n 0.0\n end\n end",
"def reminder_date_time\n return @reminder_date_time\n end",
"def getTripTime()\n return Trip.new(getPickUpTime(), getDropOffTime()) ;\n end",
"def reviewed_date_time\n return @reviewed_date_time\n end",
"def get_final_time\n meeting_individual_result ? meeting_individual_result.get_timing_instance : \"#{compute_final_time} ***\"\n end",
"def render_remaining_time(expiration_time)\n if expiration_time < Time.now\n \"<h4></br><span id='expiration_status'>This Auction has </span><span class='text-blue'>FINISHED</span></h4>\".html_safe\n else\n \"<h4></br><span id='expiration_status'>Remaining Time: </span><span class='expiration-time-room text-green hidden'>#{time_in_milliseconds(expiration_time)}</span></h4>\".html_safe\n end\n end",
"def getTripPlannedTime()\n return @tripPlannedTimeList.last() ;\n end",
"def alter_time\n return create_time if alteration_date.nil? || alteration_time.nil?\n # should never be true but just in case.\n ad = self.alteration_date\n at = self.alteration_time\n # Note, the creation date and time from the PMR is in the time\n # zone of the specialist who created the PMR. I don't know\n # how to find out who that specialist was and, even if I\n # could, I don't know his time zone. So, I fudge and put the\n # create time according to the time zone of the customer. So\n # this is going to be wrong sometimes. But, it should never\n # be used anyway.\n if customer && customer.tz\n tz = customer.tz\n else\n tz = 0\n end\n DateTime.civil(2000 + ad[1..2].to_i, # not Y2K but who cares?\n ad[4..5].to_i, # month\n ad[7..8].to_i, # day\n at[0..1].to_i, # hour\n at[3..4].to_i, # minute\n 0, # second\n tz) # time zone\n end",
"def renewed_date_time\n return @renewed_date_time\n end",
"def transaction_time\n\t\t\ttime = Time.now\n\t\t\ttime.strftime(\"%m/%d/%Y at %I:%M%p\")\n\t\tend",
"def time_present\n\n t = time_left_in_seconds\n\n if @open \n\n mm, ss = t.divmod(60) #=> [4515, 21]\n hh, mm = mm.divmod(60) #=> [75, 15]\n dd, hh = hh.divmod(24) \n #=> [3, 3]\n return \"%d days, %d hours, %d minutes and %d seconds\" % [dd, hh, mm, ss]\n\n else\n\n return @open\n\n end\n\n end",
"def get_activity_spent_time\n datetime_start = Datetime.get_opened_one(current_user).start\n activity_spent_seconds = Time.now - datetime_start\n [ activity_spent_seconds.to_i / 3600, activity_spent_seconds.to_i / 60 % 60 ].map{ |t| t.to_s.rjust(2, '0') }.join(':')\n end",
"def due_time\n return @due_time\n end",
"def get_time_placed\n self.created_at.strftime(\"%m/%d/%Y at %l:%M%p\")\n end",
"def experienced_time\n Time.parse(rt_date + \"UTC\") rescue nil\n end",
"def race_at_display\n \"#{try(:year)}-#{try(:month)}-#{try(:day)} #{post_time}\".to_s\n end",
"def getDisplayTime\r\n\t\t\t\t\treturn @displayTime\r\n\t\t\t\tend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test accessing inexistent data | def test_data_access_inexistent
data_source = make_data_source
data = data_source.data("Foo")
assert_equal(0, data.size)
data = data_source.data("SimpleText", "noop.txt")
assert_nil(data)
end | [
"def assert_no_data_at data, path, msg=nil\n msg ||= \"Data found at #{path.inspect} for #{data.inspect}\"\n found = false\n\n Path.find path, data do |d,k,p|\n found = true\n break\n end\n\n assert !found, msg\n end",
"def treat_missing_data\n data.treat_missing_data\n end",
"def has_missing_data?\n !indexes(*Daru::MISSING_VALUES).empty?\n end",
"def test_read_NotFound()\n key = \"_Read_NotFound\"\n conn = Scalaroid::TransactionSingleOp.new()\n assert_raises( Scalaroid::NotFoundError ) { conn.read(@testTime.to_s + key) }\n conn.close_connection()\n end",
"def test_read_not_found()\n key = \"_Read_NotFound\"\n t = Scalaroid::Transaction.new()\n assert_raises( Scalaroid::NotFoundError ) { t.read(@testTime.to_s + key) }\n t.close_connection()\n end",
"def testRead_NotFound()\n key = \"_Read_NotFound\"\n t = Scalaris::Transaction.new()\n assert_raise( Scalaris::NotFoundError ) { t.read(@testTime.to_s + key) }\n t.close_connection()\n end",
"def test_nonexistent_predicate\n assert_raises(ArgumentError) { @valid_source.predicate(:idontexist, \"something\") }\n end",
"def if_not_exists; end",
"def test_data_not_found\n deleted_trace_file = create(:trace, :deleted)\n\n # First with a trace that has never existed\n get :data, :params => { :display_name => create(:user).display_name, :id => 0 }\n assert_response :not_found\n\n # Now with a trace that has been deleted\n get :data, :params => { :display_name => deleted_trace_file.user.display_name, :id => deleted_trace_file.id }, :session => { :user => deleted_trace_file.user }\n assert_response :not_found\n end",
"def test_get_nonexisting_bookmark\n bm = @bs.get_bookmark(15000)\n assert(bm.errors.count > 0)\n end",
"def test_book_info__not_present\n library = Library.new(@books)\n book_information = library.book_info(\"fake_book\")\n assert_nil(book_information)\n end",
"def test_load_file_empty\n @s00.load_file(\"test/schedule/empty/empty.dat\")\n assert_equal(0, @s00.plans.size)\n\n #context \"data containing error\" do it \"should interrupt with error line.\" do\n io = StringIO.new\n assert_raise(Sculd::Manager::LoadError){ @s00.load_file(\"test/schedule/error/error.dat\", io)}\n end",
"def data_nil?\n raise 'You must use the parse method to populate the data attribute first' if @data.nil?\n end",
"def test_fetch_nonexistent_input_kind\n assert_nil(@service.inputs[temporary_name()])\n end",
"def has_data\n @data.size > 0\n end",
"def is_no_data?(); @type == GDT_NO_DATA; end",
"def test_api_data_not_found\n deleted_trace_file = create(:trace, :deleted)\n\n # Try first with no auth, as it should require it\n get :api_data, :params => { :id => 0 }\n assert_response :unauthorized\n\n # Login, and try again\n basic_authorization create(:user).display_name, \"test\"\n get :api_data, :params => { :id => 0 }\n assert_response :not_found\n\n # Now try a trace which did exist but has been deleted\n basic_authorization deleted_trace_file.user.display_name, \"test\"\n get :api_data, :params => { :id => deleted_trace_file.id }\n assert_response :not_found\n end",
"def test_book_rental_info__not_present\n library = Library.new(@books)\n book_rental_information = library.rental_info(\"fake_book\")\n assert_nil(book_rental_information)\n end",
"def check_key_value_exists_for_all(response, data, key)\n data.each do |article|\n article[key].should_not be_nil\n article[key].to_s.length.should > 0\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PUT /qualifies/1 PUT /qualifies/1.json | def update
@qualify = Qualify.find(params[:id])
respond_to do |format|
if @qualify.update_attributes(params[:qualify])
format.html { redirect_to @qualify, notice: 'Qualify was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @qualify.errors, status: :unprocessable_entity }
end
end
end | [
"def update\n respond_to do |format|\n if @qualify.update(qualify_params)\n format.html { redirect_to @qualify, notice: 'Qualify was successfully updated.' }\n format.json { render :show, status: :ok, location: @qualify }\n else\n format.html { render :edit }\n format.json { render json: @qualify.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @set_qualification.update(set_qualification_params)\n format.html { redirect_to set_qualifications_path, notice: 'Set qualification was successfully updated.' }\n format.json { render :index, status: :ok, location: @set_qualification }\n else\n format.html { render :edit }\n format.json { render json: @set_qualification.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @needs_qual = NeedsQual.find(params[:id])\n\n respond_to do |format|\n if @needs_qual.update_attributes(params[:needs_qual])\n format.html { redirect_to @needs_qual, notice: 'Needs qual was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @needs_qual.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @qualification = Qualification.find(params[:id])\n\n respond_to do |format|\n if @qualification.update_attributes(params[:qualification])\n format.html { redirect_to @qualification, notice: 'Qualification was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @qualification.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @qualification.update(qualification_params)\n format.html { redirect_to @qualification, notice: 'Qualification was successfully updated.' }\n format.json { render :show, status: :ok, location: @qualification }\n else\n format.html { render :edit }\n format.json { render json: @qualification.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @qualification = Qualification.find(params[:id])\n\n respond_to do |format|\n if @qualification.update_attributes(params[:qualification])\n format.html { redirect_to(@qualification, :notice => 'Qualification was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @qualification.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @qualification = Qualification.find(params[:id])\n\n respond_to do |format|\n if @qualification.update_attributes(params[:qualification])\n format.html { redirect_to(admin_qualification_url(@qualification), :notice => 'Qualification was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @qualification.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @qualify = Qualify.new(qualify_params)\n\n respond_to do |format|\n if @qualify.save\n format.html { redirect_to @qualify, notice: 'Qualify was successfully created.' }\n format.json { render :show, status: :created, location: @qualify }\n else\n format.html { render :new }\n format.json { render json: @qualify.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @qualification_t.update(qualification_t_params)\n format.html { redirect_to @qualification_t, notice: \"Qualification t was successfully updated.\" }\n format.json { render :show, status: :ok, location: @qualification_t }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @qualification_t.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @official_qualifier = OfficialQualifier.find(params[:id])\n\n respond_to do |format|\n if @official_qualifier.update_attributes(params[:official_qualifier])\n format.html { redirect_to @official_qualifier, notice: 'Official qualifier was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @official_qualifier.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @servqual = Servqual.find(params[:id])\n\n respond_to do |format|\n if @servqual.update_attributes(params[:servqual])\n format.html { redirect_to @servqual, notice: 'Servqual was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @servqual.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @qualification_detail.update(qualification_detail_params)\n format.html { redirect_to @qualification_detail, notice: 'Qualification detail was successfully updated.' }\n format.json { render :show, status: :ok, location: @qualification_detail }\n else\n format.html { render :edit }\n format.json { render json: @qualification_detail.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @qualification_detail = QualificationDetail.find(params[:id])\n\n respond_to do |format|\n if @qualification_detail.update_attributes(params[:qualification_detail])\n format.html { redirect_to @qualification_detail, notice: 'Qualification detail was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @qualification_detail.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @qualification_type.update(qualification_type_params)\n format.html { redirect_to @qualification_type, notice: 'Qualification type was successfully updated.' }\n format.json { render :show, status: :ok, location: @qualification_type }\n else\n format.html { render :edit }\n format.json { render json: @qualification_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @qualificacao = Qualificacao.find(params[:id])\n\n respond_to do |format|\n if @qualificacao.update_attributes(params[:qualificacao])\n format.html { redirect_to @qualificacao, notice: 'Qualificacao atualizada com sucesso.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @qualificacao.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @qualicacao.update(qualicacao_params)\n format.html { redirect_to @qualicacao, notice: 'Qualicacao was successfully updated.' }\n format.json { render :show, status: :ok, location: @qualicacao }\n else\n format.html { render :edit }\n format.json { render json: @qualicacao.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @qualify = Qualify.find(params[:id])\n @qualify.destroy\n\n respond_to do |format|\n format.html { redirect_to qualifies_url }\n format.json { head :no_content }\n end\n end",
"def update\n @student_qualification = StudentQualification.find(params[:id])\n\n respond_to do |format|\n if @student_qualification.update_attributes(params[:student_qualification])\n format.html { redirect_to(@student_qualification, :notice => 'Student qualification was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @student_qualification.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @personnel_qualification.update(personnel_qualification_params)\n format.html { redirect_to @personnel_qualification, notice: 'Personnel qualification was successfully updated.' }\n format.json { render :show, status: :ok, location: @personnel_qualification }\n else\n format.html { render :edit }\n format.json { render json: @personnel_qualification.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /qualifies/1 DELETE /qualifies/1.json | def destroy
@qualify = Qualify.find(params[:id])
@qualify.destroy
respond_to do |format|
format.html { redirect_to qualifies_url }
format.json { head :no_content }
end
end | [
"def destroy\n @qualify.destroy\n respond_to do |format|\n format.html { redirect_to qualifies_url, notice: 'Qualify was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @qualification = Qualification.find(params[:id])\n @qualification.destroy\n\n respond_to do |format|\n format.html { redirect_to qualifications_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @set_qualification.destroy\n respond_to do |format|\n format.html { redirect_to set_qualifications_url, notice: 'Set qualification was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @qualification = Qualification.find(params[:id])\n @qualification.destroy\n\n respond_to do |format|\n format.html { redirect_to(qualifications_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @needs_qual = NeedsQual.find(params[:id])\n @needs_qual.destroy\n\n respond_to do |format|\n format.html { redirect_to needs_quals_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @official_qualifier = OfficialQualifier.find(params[:id])\n @official_qualifier.destroy\n\n respond_to do |format|\n format.html { redirect_to official_qualifiers_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @qualification_detail = QualificationDetail.find(params[:id])\n @qualification_detail.destroy\n\n respond_to do |format|\n format.html { redirect_to qualification_details_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @qualification_t.destroy\n respond_to do |format|\n format.html { redirect_to qualification_ts_url, notice: \"Qualification Requst was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @qualification = Qualification.find(params[:id])\n @owner = @qualification.person\n @qualification.destroy\n\n respond_to do |format|\n format.html { redirect_to(qualifications_for_admin_person_url(@owner)) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @qualification_detail.destroy\n respond_to do |format|\n format.html { redirect_to staff_register7_path, notice: 'Qualification was destroy.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @servqual = Servqual.find(params[:id])\n @servqual.destroy\n\n respond_to do |format|\n format.html { redirect_to servquals_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @qualifier.destroy\n respond_to do |format|\n format.html { redirect_to qualifiers_url, notice: 'Qualifier was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @educatioal_qualification.destroy\n respond_to do |format|\n format.html { redirect_to root_path, notice: 'Educatioal qualification was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @qualificacao = Qualificacao.find(params[:id])\n @qualificacao.destroy\n\n respond_to do |format|\n format.html { redirect_to qualificacoes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @qualification_type.destroy\n respond_to do |format|\n format.html { redirect_to qualification_types_url, notice: 'Qualification type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @student_qualification = StudentQualification.find(params[:id])\n @student_qualification.destroy\n\n respond_to do |format|\n format.html { redirect_to(student_qualifications_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @qualificacao.destroy\n respond_to do |format|\n format.html { redirect_to qualificacaos_url }\n format.json { head :no_content }\n end\n end",
"def remove_qualification\n quali = UserQualification.where(:id => params[:qualiID]) \n quali.destroy_all if quali.present?\n @user.save\n @log_msg = \"qualification removed is \"+ (quali.present? ? quali.to_s : \"\")\n render nothing: true\n end",
"def destroy\n @quality = Quality.find(params[:id])\n @quality.destroy\n\n respond_to do |format|\n format.html { redirect_to(qualities_url) }\n format.xml { head :ok }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /report_templates/fetch_row/1 GET /report_templates/fetch_row/1.xml | def fetch_row
@screen = session.active_screen
@report_template = ReportTemplate.find(params[:id], :select => ReportTemplate.select_fields)
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @report_template }
end
end | [
"def fetch_row\n @screen = session.active_screen\n @report = Report.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @report }\n end\n end",
"def get_report_template(args = {}) \n get(\"/reports.json/template/#{args[:templateId]}\", args)\nend",
"def index\n @report_templates = ReportTemplate.find(:all)\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @report_templates }\n end\n end",
"def fetch_row\n @screen_self = session.active_screen\n\n field_id = params[:id].to_s.split(/_/).last.to_i\n @field = Field.find(field_id)\n\n respond_to do |format|\n format.html # fetch_row.html.erb\n format.xml { render :xml => @field }\n end\n end",
"def download\n if params[:template] == \"0\"\n search = @class.search\n @result = search.result\n else\n @result = @class.column_names\n end\n\n\t\trespond_to do |format|\n\t\t\tformat.csv { send_data @result.to_csv }\n\t\tend\n end",
"def fetch_row\n @screen_self = session.active_screen\n \n @user = User.find(params[:user_id])\n\n respond_to do |format|\n format.html # fetch_row.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def result2_data_rows(experiment_id, uri, table, columns)\n data_rows = []\n\n req = Net::HTTP::Post.new(uri.path)\n\n xml = REXML::Document.new\n request = xml.add_element('request', 'id' => 'foo')\n request.add_element('result').add_element('format').add_text('xml')\n query = request.add_element('query')\n query.add_element('repository', 'name' => experiment_id)\n query.add_element('table', 'tname' => table)\n project = query.add_element('project')\n\n columns.each do |m|\n project.add_element('arg').add_element('col', 'name' => m.to_s, 'table' => table)\n end\n\n req.body = xml.to_s\n\n result = Net::HTTP.start(uri.host, uri.port) do |http|\n res = http.request(req)\n res.body\n end\n\n\n result_doc = REXML::Document.new(result)\n REXML::XPath.each(result_doc, '//omf:r', 'omf'=> RESULT2_NAMESPACE).each do |r|\n row = REXML::XPath.each(r, 'omf:c', 'omf'=> RESULT2_NAMESPACE).map {|v| v.text.auto_parse }\n data_rows << row\n end\n\n data_rows\nend",
"def export_by_uuid(uuid)\n return @http.get_xml(\"templates/export?uuid=#{uuid}\")\n end",
"def show\n @report_field_template = ReportFieldTemplate.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @report_field_template }\n end\n end",
"def show\n @comparative_report_template = ComparativeReportTemplate.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @comparative_report_template }\n end\n end",
"def index\n @reports = report_model.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @weekly_reports }\n end\n end",
"def show\n @otrunk_report_template = OtrunkReportTemplate.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @otrunk_report_template }\n end\n end",
"def index\n @program_budge_templates = ProgramBudgeTemplate.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @program_budge_templates }\n end\n end",
"def index\n @fields_reports = FieldsReport.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @fields_reports }\n end\n end",
"def fetch_report_page \n @report_page = client.get(REPORT_URL)\n dump(client, @report_page)\n \n @ajax_id = get_ajax_id(@report_page)\n @report_page\n end",
"def report_get_all ()\n\t\tbegin\n\t\t\txr=report_get_raw(\"format\"=>\"NBE\")\n\t\t\tlist=Array.new\n\t\t\txr.elements.each('//get_reports_response/report') do |report|\n\t\t\t\ttd=Hash.new\n\t\t\t\ttd[\"id\"]=target.attributes[\"id\"]\n\t\t\t\ttd[\"name\"]=target.elements[\"name\"].text\n\t\t\t\ttd[\"comment\"]=target.elements[\"comment\"].text\n\t\t\t\ttd[\"hosts\"]=target.elements[\"hosts\"].text\n\t\t\t\ttd[\"max_hosts\"]=target.elements[\"max_hosts\"].text\n\t\t\t\ttd[\"in_use\"]=target.elements[\"in_use\"].text\n\t\t\t\tlist.push td\n\t\t\tend\n\t\t\treturn list\n\t\trescue \n\t\t\traise OMPResponseError\n\t\tend\n\t\tend",
"def index\n @custom_reports = CustomReport.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @custom_reports }\n end\n end",
"def index\n\t\tload_rows\n\t respond_to do |format|\n\t \tformat.html # index.html.erb\n\t \tformat.xml { render :xml => @logrows }\n\t end\n\tend",
"def show\n @template_outcome_column = TemplateOutcomeColumn.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @template_outcome_column }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Current Balance = Funded Amount SUM(Payments) | def balance
self.payments.map(&:amount).reduce(self.funded_amount, :-)
end | [
"def balance\n res = dollars\n\n fund_transactions.each do |tran|\n res += tran.dollars\n end\n\n return res\n end",
"def balance\n amount_paid - amount_due\n end",
"def balance\n @balance ||= starting_balance + flights.inject(0) do |result, element|\n result + element.profit\n end\n end",
"def balance\n credit = FineBalance.sum('AMOUNT', :conditions=>{:INCURRED_ID=>self.CHARGE_INCURRED_ID})\n return self.AMOUNT-credit\n end",
"def balance\n self.ledger_entries.sum(:value)\n end",
"def outstanding_balance\n paid? ? 0.to_d : price - (amount_paid || 0.to_d)\n end",
"def amount_paid\n accepted_payments.sum(:amount).to_f\n end",
"def outstanding_amount\n total_cost - paid_amount\n end",
"def balance\n # accounts.reduce(0) {|sum, account| sum + account.balance}\n accounts.sum {|account| account.balance}\n\n # total = 0\n # accounts.each {|account| total += account.balance}\n # total\n end",
"def affiliate_balance\n # XXXFIX P3: Faster to do the math in the DB\n affiliate_transactions.inject(0.0) { |sum, t| sum + t.amount }\n end",
"def update_purchase_balance\n update(balance: financial_transactions.sum(:total_amount))\n end",
"def total_amount\n t = amount\n t += sub_transactions.sum(:amount) if recurring_period\n t\n end",
"def balance\n transactions.load.inject(0) do |sum, transaction|\n sum + transaction.amount\n end\n end",
"def compute_balance\n if @transactions.length == 0\n return 0.0\n end\n balance = @transactions.reduce(0.0){|balance, t| balance + t[:amount]}\n safe_float balance #ensure two decimals\n end",
"def balance\n\t\tsum = 0 - self.sum_debits + self.sum_credits\n\t\treturn sum\n\tend",
"def amount_paid\n amount = Monkey::Accounting::Amount.zero\n if paid?\n (e = payment_entry).transactions.select { |t|\n t.account != business_account\n }.each { |t|\n amount += t.amount || e.null_amount\n }\n end\n amount\n end",
"def pending_balance\n transactions.where(pending: true).sum(:amount)\n end",
"def balance\n return false unless Account.exists?(@account_id)\n\n Trade.where(account_id: @account_id).pluck(:amount).reduce(:+) || 0.0\n end",
"def total_debit_amount\n amount_sum_for(:debit?)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the next doc in the result set. If the cache is empty, request more docs from the server. Check if the doc is an error doc before returning. | def fetch_doc
request_docs if @cache.empty?
doc = @cache.shift
doc unless error?(doc)
end | [
"def try_next\n if @documents.nil?\n # Since published versions of Mongoid have a copy of old driver cursor\n # code, our dup call in #process isn't invoked when Mongoid query\n # cache is active. Work around that by also calling dup here on\n # the result of #process which might come out of Mongoid's code.\n @documents = process(@initial_result).dup\n # the documents here can be an empty array, hence\n # we may end up issuing a getMore in the first try_next call\n end\n\n if @documents.empty?\n # On empty batches, we cache the batch resume token\n cache_batch_resume_token\n\n unless closed?\n if exhausted?\n close\n @fully_iterated = true\n raise StopIteration\n end\n @documents = get_more\n else\n @fully_iterated = true\n raise StopIteration\n end\n else\n # cursor is closed here\n # keep documents as an empty array\n end\n\n # If there is at least one document, cache its _id\n if @documents[0]\n cache_resume_token(@documents[0])\n end\n\n # Cache the batch resume token if we are iterating\n # over the last document, or if the batch is empty\n if @documents.size <= 1\n cache_batch_resume_token\n if closed?\n @fully_iterated = true\n end\n end\n\n return @documents.shift\n end",
"def try_next\n raise StopIteration.new if closed?\n begin\n doc = @cursor.try_next\n rescue Mongo::Error => e\n if !e.change_stream_resumable?\n raise\n end\n\n # Rerun initial aggregation.\n # Any errors here will stop iteration and break out of this\n # method.\n\n # Save cursor's resume token so we can use it\n # to create a new cursor\n @resume_token = @cursor.resume_token\n\n close\n create_cursor!\n retry\n end\n\n # We need to verify each doc has an _id, so we\n # have a resume token to work with\n if doc && doc['_id'].nil?\n raise Error::MissingResumeToken\n end\n doc\n end",
"def next_item\n return nil unless more_items?\n return response.cursor if response.respond_to?(:cursor)\n\n response.offset + response.limit\n rescue StandardError\n nil\n end",
"def first\n find.limit(1).next_document\n end",
"def cache_document(doc)\n if !FeatureToggle.enabled?(:efolder_docs_api) && !S3Service.exists?(doc.file_name)\n doc.fetch_content\n @counts[:docs_cached] += 1\n @counts[:consecutive_failures] = 0\n end\n rescue Aws::S3::Errors::ServiceError, VBMS::ClientError => e\n Rails.logger.error \"Failed to retrieve #{doc.file_name}:\\n#{e.message}\"\n @counts[:docs_failed] += 1\n @counts[:consecutive_failures] += 1\n end",
"def first(options = nil)\n old_max = @max_results\n @max_results = 1\n key = execute[0]\n @max_results = old_max\n @document.find(key, options || @options)\n end",
"def next\n return if empty_queue?\n data = CrawlResult.new crawl next_url\n data.result\n end",
"def request_docs\n send_get_more\n close if exhausted?\n end",
"def next!\n update(read: true) ? next_page : false\n end",
"def next_document\n Mongoid::Factory.from_db(@klass, @cursor.next_document)\n end",
"def next_page(path)\n result = http_get(path)\n collection_from(result.body)\n end",
"def next_result()\n #This is a stub, used for indexing\n end",
"def next_document\n Mongoid::Factory.from_db(klass, cursor.next_document)\n end",
"def find_next(response)\n db = init_db\n if last_comic = get_last_comic(response.user)\n last_comic += 1\n comic = get_comic_by_id(db, last_comic)\n reply_with_comic response, comic\n end\n end",
"def get(index_)\n seek_index(index_) ? self.next : nil\n end",
"def process(result)\n documents = super\n if @cursor_id.zero? && !@after_first_batch\n @cached_docs ||= []\n @cached_docs.concat(documents)\n end\n @after_first_batch = true\n documents\n end",
"def next\n if @options[\"page\"] && !cbp_request?\n clear_cache\n @options[\"page\"] = @options[\"page\"].to_i + 1\n elsif (@query = @next_page)\n # Send _only_ url param \"?page[after]=token\" to get the next page\n @options.page&.delete(\"before\")\n fetch(true)\n else\n clear_cache\n @resources = []\n end\n end",
"def reload\n if obj = self.class.find({\"_id\" => @doc[\"_id\"]}).next_document\n @doc = obj.doc; true\n end\n end",
"def first\n # Modify the @next url to set the :limit to 1\n original_next = @next\n @next = @path\n fetch_next!(@options.merge(params: @options.fetch(:params, {}).merge({ limit: 1 })))\n # Restore the @next url to the original\n @next = original_next\n @data.first\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Close the cursor on the server. If there is neither a server set or if the cursor is already closed, return nil. Otherwise, send a kill cursor command. | def close
return nil if @server.nil? || closed?
kill_cursors
end | [
"def close\n @db.send_to_db(KillCursorsMessage.new(@cursor_id)) if @cursor_id\n @cache = []\n @cursor_id = 0\n @closed = true\n end",
"def closeCursor(sCursorHandle)\n \n if (sCursorHandle != getCursorHandle) \n raise \"The Cursor handler is not recognized: \\\"#{sCursorHandle}\\\"\"\n end\n \n @_bReturnValue = true\n \n sParameters = \"&#{TAMINO_OP_HANDLE}=#{sCursorHandle}\"\n \n sMore = \"Content-Disposition: form-data; name=\\\"#{TAMINO_OP_HANDLE}\\\"\\r\\n\";\n sMore << \"\\r\\n\"\n sMore << sCursorHandle\n \n if (@_sHttpRequestMethod == \"GET\") \n _sendRequestUsingGet(@_sCollection, TAMINO_OP_CURSOR, \"close\", sParameters)\n else \n _sendRequestUsingPost(@_sCollection, TAMINO_OP_CURSOR, \"close\", sMore)\n end\n getHeaderResponse\n return @_bReturnValue;\n end",
"def close\n @connection.execute(\"close #{@cursor}\")\n end",
"def kill_cursors\n context = @server.context\n kill_cursors_op.execute(context)\n @cursor_id = 0\n end",
"def close_cursor(name)\n connection.close_cursor(name)\n end",
"def stop\n begin\n @curs.kill\n # Wait for the cursor to die -- can cause problems otherwise\n while @curs.alive? ; end\n # Set cursor to nil so set_banner method only works\n # when cursor is actually running.\n @cursor = nil\n reset_line\n puts (@parsed.message nil)\n # Set parsed to nil so set_message method only works\n # when cursor is actually running.\n @parsed = nil\n\n # Return execution time\n get_exec_time\n rescue NameError\n raise CursorNotRunning.new \"Can't stop, no cursor running.\"\n end\n end",
"def kill_cursors\n # TODO optimize this to batch kill cursor operations for the same\n # server/database/collection instead of killing each cursor\n # individually.\n loop do\n server_address = nil\n\n kill_spec = @mutex.synchronize do\n read_scheduled_kill_specs\n # Find a server that has any cursors scheduled for destruction.\n server_address, specs =\n @to_kill.detect { |_, specs| specs.any? }\n\n if specs.nil?\n # All servers have empty specs, nothing to do.\n return\n end\n\n # Note that this mutates the spec in the queue.\n # If the kill cursor operation fails, we don't attempt to\n # kill that cursor again.\n spec = specs.take(1).tap do |arr|\n specs.subtract(arr)\n end.first\n\n unless @active_cursor_ids.include?(spec.cursor_id)\n # The cursor was already killed, typically because it has\n # been iterated to completion. Remove the kill spec from\n # our records without doing any more work.\n spec = nil\n end\n\n spec\n end\n\n # If there was a spec to kill but its cursor was already killed,\n # look for another spec.\n next unless kill_spec\n\n # We could also pass kill_spec directly into the KillCursors\n # operation, though this would make that operation have a\n # different API from all of the other ones which accept hashes.\n spec = {\n cursor_ids: [kill_spec.cursor_id],\n coll_name: kill_spec.coll_name,\n db_name: kill_spec.db_name,\n }\n op = Operation::KillCursors.new(spec)\n\n server = cluster.servers.detect do |server|\n server.address == server_address\n end\n\n unless server\n # TODO We currently don't have a server for the address that the\n # cursor is associated with. We should leave the cursor in the\n # queue to be killed at a later time (when the server comes back).\n next\n end\n\n options = {\n server_api: server.options[:server_api],\n connection_global_id: kill_spec.connection_global_id,\n }\n op.execute(server, context: Operation::Context.new(options: options))\n\n if session = kill_spec.session\n if session.implicit?\n session.end_session\n end\n end\n end\n end",
"def close_remote_srv_conn\n if @socket_srv\n @socket_srv.close\n @log.debug \"close_remote_srv_conn requested\"\n @cup_gui.log_sometext \"Bye, connessione col server terminata\\n\"\n @rd_sock_thread.join\n @socket_srv = nil\n end\n rescue => detail\n @log.error \"Server connection error (#{$!})\\n\"\n @log.error detail.backtrace.join(\"\\n\")\n ensure\n @socket_srv = nil \n end",
"def kill_cursors_op\n Mongo::Operation::KillCursors.new({ :cursor_ids => [@cursor_id] })\n end",
"def closed?\n # @cursor_id should in principle never be nil\n @cursor_id.nil? || @cursor_id == 0\n end",
"def kill_cursors(cursor_ids)\n process(Protocol::KillCursors.new(cursor_ids))\n end",
"def closed?\n @cursor_id == 0\n end",
"def destroy_cursor(cursor)\n cursor.destroy\n cursors.delete cursor\n end",
"def stop\n begin\n @spinner.kill\n # Wait for the cursor to die -- can cause problems otherwise\n @spinner.join\n # Set cursor to nil so set_banner method only works\n # when cursor is actually running.\n @cursor = nil\n\n restore_stdout_sync_status\n if console_captured?\n $console.print ESC_R_AND_CLR + $stdout.string\n release_console\n end\n show_cursor\n\n reset_line\n puts @parsed.message\n # Set parsed to nil so set_message method only works\n # when cursor is actually running.\n @parsed = nil\n @setup = false\n\n # Return execution time\n @stop_watch.stop\n @stop_watch.timing\n rescue NameError\n raise CursorNotRunning.new \"Can't stop, no cursor running.\"\n end\n end",
"def stop\n server = \"#{STOMP_SERVER[:host]}:#{STOMP_SERVER[:port]}\"\n puts \"Closing connection to #{server}\"\n @client.close\n puts \"Closed connection to #{server}\"\n end",
"def mnu_close_serverconnection(sender, sel, ptr)\n @corelogger.debug \"Menu Close server connection\"\n @control_net_conn.close_remote_srv_conn\n end",
"def mark_to_kill\n CURSORS[@cursor_id] = true if @cursor_id && alive?\n @cursor_id = 0\n end",
"def stmt_close_command(stmt_id)\n synchronize do\n reset\n write [COM_STMT_CLOSE, stmt_id].pack(\"CV\")\n end\n end",
"def hide_cursor!\n Vedeu.bind(:_hide_cursor_) do |name|\n Vedeu::Cursors::Cursor.hide_cursor(name)\n end\n\n Vedeu.bind_alias(:_cursor_hide_, :_hide_cursor_)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Request documents from the server. Close the cursor on the server if all docs have been retreived. | def request_docs
send_get_more
close if exhausted?
end | [
"def documents(params={})\n server.get(\"#{name}/_all_docs\", params)\n end",
"def index_documents\n @params = {}\n @action = 'index_documents'\n \n send_auth_request\n end",
"def batch_get_documents request_pb, options = nil, &block\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n verb, uri, query_string_params, body = ServiceStub.transcode_batch_get_documents_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 is_server_streaming: true,\n &block\n )\n ::Gapic::Rest::TransportOperation.new response\n end",
"def each\n\n # If we already iterated past the first batch (i.e., called get_more\n # at least once), the cursor on the server side has advanced past\n # the first batch and restarting iteration from the beginning by\n # returning initial result would miss documents in the second batch\n # and subsequent batches up to wherever the cursor is. Detect this\n # condition and abort the iteration.\n #\n # In a future driver version, each would either continue from the\n # end of previous iteration or would always restart from the\n # beginning.\n if @get_more_called\n raise Error::InvalidCursorOperation, 'Cannot restart iteration of a cursor which issued a getMore'\n end\n\n # To maintain compatibility with pre-2.10 driver versions, reset\n # the documents array each time a new iteration is started.\n @documents = nil\n\n if block_given?\n # StopIteration raised by try_next ends this loop.\n loop do\n document = try_next\n if explicitly_closed?\n raise Error::InvalidCursorOperation, 'Cursor was explicitly closed'\n end\n yield document if document\n end\n self\n else\n documents = []\n # StopIteration raised by try_next ends this loop.\n loop do\n document = try_next\n if explicitly_closed?\n raise Error::InvalidCursorOperation, 'Cursor was explicitly closed'\n end\n documents << document if document\n end\n documents\n end\n end",
"def browse(options={})\n response = API.instance.send_request('docs.browse', options.merge(:category_id => self.scribd_id))\n documents = []\n response.elements['/rsp/result_set'].elements.each do |doc|\n documents << Document.new(:xml => doc)\n end\n return documents\n end",
"def list_documents \r\n suburl = \"&action=list_documents\"\r\n call_target_url(suburl)\r\n end",
"def each\n @cursor = nil\n session = client.send(:get_session, @options)\n server = cluster.next_primary(nil, session)\n result = send_initial_query(server, session, context: Operation::Context.new(client: client, session: session))\n result = send_fetch_query(server, session) unless inline?\n @cursor = Cursor.new(view, result, server, session: session)\n if block_given?\n @cursor.each do |doc|\n yield doc\n end\n else\n @cursor.to_enum\n end\n end",
"def index\n @doc_requests = DocRequest.all\n end",
"def all_docs(*opts)\n q = \"#{database}/_all_docs\"\n q << build_query_string(opts.first,\"all_docs\") if opts && opts.any? && opts.first.is_a?(Hash)\n\n @conn.query({url_path: q, method: :get})\n end",
"def get_documents(index, query, options={}, *schemas)\n if fields = options.delete(:fields)\n fields = url_pipe_join(fields)\n end\n \n if options[:sort]\n options[:sort] = Array(options[:sort]).flatten.join(',')\n end\n \n request = get(\n build_path(API_PATHS[:documents], \n url_pipe_join(index), \n url_pipe_join(schemas),\n url_pipe_join(query),\n fields\n ),\n options\n )\n send_request request\n end",
"def documents_for_iteration\n docs = documents[skipping || 0, limiting || documents.length] || []\n if eager_loadable?\n eager_load(docs)\n end\n docs\n end",
"def index\n @documents = api.form(\"everything\")\n .page(params[:page] ? params[:page] : \"1\")\n .page_size(params[:page_size] ? params[:page_size] : \"20\")\n .submit(ref)\n end",
"def documents\n @documents ||=\n Array.wrap(options[:documents]).compact.presence ||\n (response['docs'] || []).map do |doc|\n document_factory.build(doc, self, options)\n end\n end",
"def send_initial_query\n response = RequestResponse.new\n message = construct_query_message\n @connection.send_command(EM::Mongo::OP_QUERY, message) do |resp|\n if resp == :disconnected\n response.fail(:disconnected)\n else\n @cache += resp.docs\n @n_received = resp.number_returned\n @cursor_id = resp.cursor_id\n @returned += @n_received\n @query_run = true\n close_cursor_if_query_complete\n response.succeed\n end\n end\n response\n end",
"def findAndFetchDocuments(collection, query)\n return collection.find(query)\n end",
"def get_documents(page, word = nil)\n x = current_user.own_documents(page, DOCUMENTS_FOR_PAGE, SearchOrders::CREATED_AT, word, true)\n @documents = x[:records]\n @tot_pages = x[:pages_amount]\n end",
"def list(filter=KalturaNotImplemented, pager=KalturaNotImplemented)\n\t\t\tkparams = {}\n\t\t\t# Document entry filter\n\t\t\tclient.add_param(kparams, 'filter', filter);\n\t\t\t# Pager\n\t\t\tclient.add_param(kparams, 'pager', pager);\n\t\t\tclient.queue_service_action_call('document_documents', 'list', kparams);\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil;\n\t\t\tend\n\t\t\treturn client.do_queue();\n\t\tend",
"def cloud_search_batch_documents(&block)\n begin\n self.in_cloud_search_batch_documents = true\n yield\n # final flush for any left over documents\n self.cloud_search_document_batcher.flush\n ensure\n self.in_cloud_search_batch_documents = false\n end\n end",
"def search\n @documents = api.form(\"everything\")\n .query(%([[:d = fulltext(document, \"#{params[:q]}\")]]))\n .page(params[:page] ? params[:page] : \"1\")\n .page_size(params[:page_size] ? params[:page_size] : \"20\")\n .submit(ref)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send a +GetMore+ message to a server to get another batch of results. | def send_get_more
raise Exception, 'No server set' unless @server
context = @server.context
response = get_more_op.execute(context)
process_response(response)
end | [
"def get_more\n reply = @node.get_more @database, @collection, @cursor_id, request_limit\n @limit -= reply.count if limited?\n @cursor_id = reply.cursor_id\n reply.documents\n end",
"def more_messages\n log \"Getting more_messages\"\n log \"Old start_index: #@start_index\"\n max = @start_index - 1\n @start_index = [(max + 1 - @limit), 1].max\n log \"New start_index: #@start_index\"\n fetch_ids = search_query? ? @ids[@start_index..max] : (@start_index..max).to_a\n log fetch_ids.inspect\n message_ids = fetch_and_cache_headers(fetch_ids)\n res = get_message_headers message_ids\n with_more_message_line(res)\n end",
"def get_more\n @reserve = get_chain\n last_link = @reserve\n count = @page_size / 100\n count = 15 if count < 15\n while(count > 0)\n last_link = get_next_for(last_link)\n count -= 1\n end\n @next_object = get_next_for(last_link)\n set_next_for( last_link , nil )\n self\n end",
"def get_more_data\n response = @connection.waitfor({\"Match\" => /(\\n|\\r)/}).split(/(\\n|\\r)/)\n filtered response\n end",
"def fetch_more?(options, resp)\n page_size = options[:_pageSize] || options['_pageSize']\n\n return unless page_size && resp.is_a?(Array)\n resp.pop while resp.length > page_size\n\n resp.length < page_size\n end",
"def show_more(num)\n response = FoodTrucks.new.query_response(num)\n return response\n end",
"def fetch_more\n $limit += 5\n $offset_counter = ($offset_counter >= 5? $offset_counter - 5: 0)\n @room_messages = (@room.room_messages.includes(:user).order(:id).limit($limit).offset($offset_counter)).to_a.reverse()\n end",
"def request_docs\n send_get_more\n close if exhausted?\n end",
"def get_more\n @options = {\n :includeFirst => false, :limit => 10, :fetch_mode => 'normal', :fetch_focus_id => 0,\n :handle => \".endless_scroll_inner_wrap\" \n }\n\n if params.has_key? :includeFirst then\n @options[:includeFirst] = params[:includeFirst] == 'true' ? true : false \n end\n\n if params.has_key? :fetch_mode then\n if params[:fetch_mode] == 'following' then\n @options[:fetch_mode] = 'following'\n elsif params[:fetch_mode] == 'followers' then\n @options[:fetch_mode] = 'followers'\n end\n end\n\n if params.has_key? :fetch_focus_id then\n @options[:fetch_focus_id] = params[:fetch_focus_id].to_i\n end\n\n if params.has_key? :handle then\n @options[:handle] = params[:handle]\n end\n\n upper = @options[:includeFirst] ? 0..params[:last_id].to_i : 0..(params[:last_id].to_i - 1)\n\n if @options[:fetch_mode] == 'normal' then\n @next_personas = Persona.where( :id => upper).order('id desc').limit(@options[:limit])\n elsif @options[:fetch_mode] == 'following' then\n persona = Persona.find(@options[:fetch_focus_id])\n @next_personas = Persona.where(\n :id => persona.followers.where(:tracked_object_type => 'persona', \n :tracked_object_id => upper ).pluck(:tracked_object_id) \n ).order('id desc').limit(@options[:limit])\n elsif @options[:fetch_mode] == 'followers' then\n persona = Persona.find(@options[:fetch_focus_id])\n @next_personas = Persona.where(:id => Follower.where(\n :tracked_object_id => persona.id, :tracked_object_type => 'persona').pluck(:persona_id)\n ).order('id desc').group(:id).having(:id => upper)\n end\n end",
"def get_more\n @options = { :includeFirst => false , :limit => 5, :persona => 0..Persona.last.id , \n :featured => [true,false], :viewType => 'normal' }\n \n @options[:includeFirst] = params[:includeFirst] == 'true' ? true : false \n\n if params.has_key? :persona then\n @options[:persona] = params[:persona].to_i\n end\n\n if params.has_key? :limit then\n @options[:limit] = params[:limit].to_i\n end\n\n if params.has_key? :featured then\n if params[:featured] == 'true' then\n @options[:featured] = true\n elsif params[:featured] == 'false' then\n @options[:featured] = false\n end\n end\n\n if params.has_key? :viewType then\n if params[:viewType] == 'tracked' then\n @options[:viewType] = params[:viewType]\n @tracked_persona = current_persona.followers.where(:tracked_object_type => 'persona')\n elsif params[:viewType] == 'trending' then\n @options[:viewType] = params[:viewType]\n end\n end\n\n if @options[:viewType] == 'trending' then\n upper = @options[:includeFirst] ? params[:last_id].to_i : params[:last_id].to_i + 1\n else\n upper = @options[:includeFirst] ? params[:last_id].to_i : params[:last_id].to_i - 1\n end\n\n if @options[:viewType] == 'trending' then\n puts 'getting trendy'\n @next_mediasets = Mediaset.joins{ votings }.order(\" votings.created_at desc\").\n limit(@options[:limit]).offset(params[:last_id]).select('mediasets.*, votings.created_at').uniq\n elsif @options[:viewType] == 'normal' then \n @next_mediasets = Mediaset.find(:all, :conditions => { \n :id => 0..upper, :persona_id => @options[:persona], :featured => @options[:featured], :system_visible => true }, \n :limit => @options[:limit], :order => 'id desc' )\n elsif @options[:viewType] == 'tracked' then\n @next_mediasets = Mediaset.find(:all, :conditions => { \n :id => 0..upper, :persona_id => @tracked_persona.pluck(:tracked_object_id), :system_visible => true,\n :featured => @options[:featured] }, \n :limit => @options[:limit], :order => 'id desc' )\n end\n\n respond_to do |format|\n format.js\n format.html\n end\n end",
"def more_messages(message_id, limit=100)\n log \"more_messages: message_id #{message_id}\"\n message_id = message_id.to_i\n if @all_search \n x = [(message_id - limit), 0].max\n y = [message_id - 1, 0].max\n res = fetch_envelopes((x..y))\n add_more_message_line(res, x)\n else\n # filter search query\n log \"@start_index #@start_index\"\n x = [(@start_index - limit), 0].max\n y = [@start_index - 1, 0].max\n @start_index = x\n res = fetch_envelopes(@ids[x..y]) \n add_more_message_line(res, @ids[x])\n end\n end",
"def get_more_messages\n @messages = @conversation.get_messages_before(params[:before]).reverse\n @has_more_messages = @conversation.has_messages_before?(@messages.first)\n end",
"def more\n limit = Blogpost.limit_blogposts(BLOGPOSTS_PER_REQUEST, more_counter: params[:more])\n\n # Requesting more user-specific posts\n if params[:user_id]\n @user = User.find(params[:user_id])\n blogposts, @has_more = Blogpost.get_blogposts(limit, user: @user)\n # Requesting more unfiltered posts\n else\n blogposts, @has_more = Blogpost.get_blogposts(limit, user: nil)\n end\n\n blogposts_displayed =\n Blogpost.blogposts_displayed(BLOGPOSTS_PER_REQUEST, more_counter: params[:more])\n @blogposts_to_render = blogposts[blogposts_displayed..-1]\n\n respond_to do |format|\n format.js { render partial: 'shared/blogposts/more_blogposts.js.erb' }\n end\n end",
"def more_messages(message_id, limit=100)\n log \"More_messages: message_id #{message_id}\"\n message_id = message_id.to_i\n if @all_search \n x = [(message_id - limit), 0].max\n y = [message_id - 1, 0].max\n\n res = fetch_row_text((x..y))\n add_more_message_line(res, x)\n else # filter search query\n log \"@start_index #@start_index\"\n x = [(@start_index - limit), 0].max\n y = [@start_index - 1, 0].max\n @start_index = x\n res = fetch_row_text(@ids[x..y]) \n add_more_message_line(res, @ids[x])\n end\n end",
"def more\n limit = Blogpost.limit_blogposts(BLOGPOSTS_PER_REQUEST, more_counter: params[:more])\n\n saved_blogposts, @has_more =\n SavedBlogpost.get_saved_blogposts(limit, user: current_user)\n blogposts_displayed =\n Blogpost.max_blogposts_displayed(BLOGPOSTS_PER_REQUEST, more_counter: params[:more])\n @saved_blogposts_to_render = saved_blogposts[blogposts_displayed..-1]\n\n respond_to do |format|\n format.js { render partial: 'shared/blogposts/more_blogposts.js.erb' }\n end\n end",
"def view_more(pages = 1)\n page_num = 0\n loop do\n yield\n\n next_link = @page.link_with(text: 'More')\n break if page_num > pages || !next_link\n\n page_num += 1\n @page = next_link.click\n end\n end",
"def fetch_all(qps=DEFAULT_QUERIES_PER_SECOND)\n response = execute\n items = response['items']\n\n while response['current_page'] < response['total_pages']\n self.page = response['current_page'] + 1\n response = execute\n items = items + response['items']\n \n sleep(1.0/DEFAULT_QUERIES_PER_SECOND)\n end\n\n return items\n end",
"def retrieve_each(count, params:, max_call: 1000)\n offset = params.fetch(:offset, 0)\n calls = 0\n\n loop do\n ret = retrieve(params.merge(count: count, offset: offset))\n if ret.err?\n yield(ret, nil)\n break\n end\n\n json = ret.response.body_json\n calls += 1\n\n yield(ret, json)\n break if json['list'].empty? || max_call <= calls\n\n offset += count\n end\n end",
"def more_results_available\n return @more_results_available\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a +KillCursors+ message using this cursor's id. | def kill_cursors_op
Mongo::Operation::KillCursors.new({ :cursor_ids => [@cursor_id] })
end | [
"def kill_cursors(cursor_ids)\n process(Protocol::KillCursors.new(cursor_ids))\n end",
"def kill_cursors\n context = @server.context\n kill_cursors_op.execute(context)\n @cursor_id = 0\n end",
"def schedule_kill_cursor(id, op_spec, server)\n @mutex.synchronize do\n if @active_cursors.include?(id)\n @to_kill[server] ||= Set.new\n @to_kill[server] << op_spec\n end\n end\n end",
"def kill_cursors\n # TODO optimize this to batch kill cursor operations for the same\n # server/database/collection instead of killing each cursor\n # individually.\n loop do\n server_address = nil\n\n kill_spec = @mutex.synchronize do\n read_scheduled_kill_specs\n # Find a server that has any cursors scheduled for destruction.\n server_address, specs =\n @to_kill.detect { |_, specs| specs.any? }\n\n if specs.nil?\n # All servers have empty specs, nothing to do.\n return\n end\n\n # Note that this mutates the spec in the queue.\n # If the kill cursor operation fails, we don't attempt to\n # kill that cursor again.\n spec = specs.take(1).tap do |arr|\n specs.subtract(arr)\n end.first\n\n unless @active_cursor_ids.include?(spec.cursor_id)\n # The cursor was already killed, typically because it has\n # been iterated to completion. Remove the kill spec from\n # our records without doing any more work.\n spec = nil\n end\n\n spec\n end\n\n # If there was a spec to kill but its cursor was already killed,\n # look for another spec.\n next unless kill_spec\n\n # We could also pass kill_spec directly into the KillCursors\n # operation, though this would make that operation have a\n # different API from all of the other ones which accept hashes.\n spec = {\n cursor_ids: [kill_spec.cursor_id],\n coll_name: kill_spec.coll_name,\n db_name: kill_spec.db_name,\n }\n op = Operation::KillCursors.new(spec)\n\n server = cluster.servers.detect do |server|\n server.address == server_address\n end\n\n unless server\n # TODO We currently don't have a server for the address that the\n # cursor is associated with. We should leave the cursor in the\n # queue to be killed at a later time (when the server comes back).\n next\n end\n\n options = {\n server_api: server.options[:server_api],\n connection_global_id: kill_spec.connection_global_id,\n }\n op.execute(server, context: Operation::Context.new(options: options))\n\n if session = kill_spec.session\n if session.implicit?\n session.end_session\n end\n end\n end\n end",
"def kill_cursors\n to_kill_copy = {}\n active_cursors_copy = []\n\n @mutex.synchronize do\n to_kill_copy = @to_kill.dup\n active_cursors_copy = @active_cursors.dup\n @to_kill = {}\n end\n\n to_kill_copy.each do |server, op_specs|\n op_specs.each do |op_spec|\n if server.features.find_command_enabled?\n Cursor::Builder::KillCursorsCommand.update_cursors(op_spec, active_cursors_copy.to_a)\n if Cursor::Builder::KillCursorsCommand.get_cursors_list(op_spec).size > 0\n Operation::Commands::Command.new(op_spec).execute(server)\n end\n else\n Cursor::Builder::OpKillCursors.update_cursors(op_spec, active_cursors_copy.to_a)\n if Cursor::Builder::OpKillCursors.get_cursors_list(op_spec).size > 0\n Operation::KillCursors.new(op_spec).execute(server)\n end\n end\n end\n end\n end",
"def send_close( sender_id, conn_id )\n\t\tself.log.info \"Sending kill message to connection %d\" % [ conn_id ]\n\t\tself.send( sender_id, conn_id, '' )\n\tend",
"def killLine buffer\n if @frames[buffer].lastCmd.start_with? \"Kill\"\n killLineConcat buffer\n else\n killLineNewEntry buffer\n end\n @frames[buffer].updateLastCmd \"KillLine\"\n @killRingPosition = 0\n end",
"def kill(nickname, comment)\n raw \"KILL #{nickname} :#{comment}\\r\\n\"\n end",
"def kill(nickname, comment = \"Connection killed\")\n send_data(\"KILL #{nickname} :#{comment}\".strip)\n end",
"def mark_to_kill\n CURSORS[@cursor_id] = true if @cursor_id && alive?\n @cursor_id = 0\n end",
"def msg_KILL(source, args)\n return nil\n end",
"def close\n @db.send_to_db(KillCursorsMessage.new(@cursor_id)) if @cursor_id\n @cache = []\n @cursor_id = 0\n @closed = true\n end",
"def cursor_id\n acknowledged? ? replies.last.cursor_id : 0\n end",
"def killer_char\n bot.message(content: bot_killer_char) do |event|\n puts i18n[:bot_killed] % bot_killer_char\n event.user.pm(i18n[:bot_killed] % bot_killer_char)\n bot.stop\n end\n end",
"def kill(pid)\n check_connection\n @protocol.kill_command pid\n self\n end",
"def cancel(id); end",
"def cwAddKillThreadButton\r\n cwAddScriptButton('cwdefault', \"$CMDTHREAD.kill; &\", CWIconLib::NUCLEARICON,\"Kill CoolWatcher ruby command thread (attempts to stop current running command)\")\r\nend",
"def id\n @cursor_id\n end",
"def cmd_kill_help\n print_line(\"Usage: kill [pid1 [pid2 [pid3 ...]]] [-s]\")\n print_line(\"Terminate one or more processes.\")\n print_line(\" -s Kills the pid associated with the current session.\")\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send a +KillCursors+ message to the server and set the cursor id to 0. | def kill_cursors
context = @server.context
kill_cursors_op.execute(context)
@cursor_id = 0
end | [
"def kill_cursors(cursor_ids)\n process(Protocol::KillCursors.new(cursor_ids))\n end",
"def kill_cursors_op\n Mongo::Operation::KillCursors.new({ :cursor_ids => [@cursor_id] })\n end",
"def kill_cursors\n # TODO optimize this to batch kill cursor operations for the same\n # server/database/collection instead of killing each cursor\n # individually.\n loop do\n server_address = nil\n\n kill_spec = @mutex.synchronize do\n read_scheduled_kill_specs\n # Find a server that has any cursors scheduled for destruction.\n server_address, specs =\n @to_kill.detect { |_, specs| specs.any? }\n\n if specs.nil?\n # All servers have empty specs, nothing to do.\n return\n end\n\n # Note that this mutates the spec in the queue.\n # If the kill cursor operation fails, we don't attempt to\n # kill that cursor again.\n spec = specs.take(1).tap do |arr|\n specs.subtract(arr)\n end.first\n\n unless @active_cursor_ids.include?(spec.cursor_id)\n # The cursor was already killed, typically because it has\n # been iterated to completion. Remove the kill spec from\n # our records without doing any more work.\n spec = nil\n end\n\n spec\n end\n\n # If there was a spec to kill but its cursor was already killed,\n # look for another spec.\n next unless kill_spec\n\n # We could also pass kill_spec directly into the KillCursors\n # operation, though this would make that operation have a\n # different API from all of the other ones which accept hashes.\n spec = {\n cursor_ids: [kill_spec.cursor_id],\n coll_name: kill_spec.coll_name,\n db_name: kill_spec.db_name,\n }\n op = Operation::KillCursors.new(spec)\n\n server = cluster.servers.detect do |server|\n server.address == server_address\n end\n\n unless server\n # TODO We currently don't have a server for the address that the\n # cursor is associated with. We should leave the cursor in the\n # queue to be killed at a later time (when the server comes back).\n next\n end\n\n options = {\n server_api: server.options[:server_api],\n connection_global_id: kill_spec.connection_global_id,\n }\n op.execute(server, context: Operation::Context.new(options: options))\n\n if session = kill_spec.session\n if session.implicit?\n session.end_session\n end\n end\n end\n end",
"def kill_cursors\n to_kill_copy = {}\n active_cursors_copy = []\n\n @mutex.synchronize do\n to_kill_copy = @to_kill.dup\n active_cursors_copy = @active_cursors.dup\n @to_kill = {}\n end\n\n to_kill_copy.each do |server, op_specs|\n op_specs.each do |op_spec|\n if server.features.find_command_enabled?\n Cursor::Builder::KillCursorsCommand.update_cursors(op_spec, active_cursors_copy.to_a)\n if Cursor::Builder::KillCursorsCommand.get_cursors_list(op_spec).size > 0\n Operation::Commands::Command.new(op_spec).execute(server)\n end\n else\n Cursor::Builder::OpKillCursors.update_cursors(op_spec, active_cursors_copy.to_a)\n if Cursor::Builder::OpKillCursors.get_cursors_list(op_spec).size > 0\n Operation::KillCursors.new(op_spec).execute(server)\n end\n end\n end\n end\n end",
"def close\n @db.send_to_db(KillCursorsMessage.new(@cursor_id)) if @cursor_id\n @cache = []\n @cursor_id = 0\n @closed = true\n end",
"def mark_to_kill\n CURSORS[@cursor_id] = true if @cursor_id && alive?\n @cursor_id = 0\n end",
"def schedule_kill_cursor(id, op_spec, server)\n @mutex.synchronize do\n if @active_cursors.include?(id)\n @to_kill[server] ||= Set.new\n @to_kill[server] << op_spec\n end\n end\n end",
"def process_cursor_cancel\n Sound.play_cursor\n Input.update\n unselect\n deactivate\n call_cancel_handler\n end",
"def closeCursor(sCursorHandle)\n \n if (sCursorHandle != getCursorHandle) \n raise \"The Cursor handler is not recognized: \\\"#{sCursorHandle}\\\"\"\n end\n \n @_bReturnValue = true\n \n sParameters = \"&#{TAMINO_OP_HANDLE}=#{sCursorHandle}\"\n \n sMore = \"Content-Disposition: form-data; name=\\\"#{TAMINO_OP_HANDLE}\\\"\\r\\n\";\n sMore << \"\\r\\n\"\n sMore << sCursorHandle\n \n if (@_sHttpRequestMethod == \"GET\") \n _sendRequestUsingGet(@_sCollection, TAMINO_OP_CURSOR, \"close\", sParameters)\n else \n _sendRequestUsingPost(@_sCollection, TAMINO_OP_CURSOR, \"close\", sMore)\n end\n getHeaderResponse\n return @_bReturnValue;\n end",
"def destroy_cursor(cursor)\n cursor.destroy\n cursors.delete cursor\n end",
"def close\n return nil if @server.nil? || closed?\n kill_cursors\n end",
"def unregister_cursor(id)\n @mutex.synchronize do\n @active_cursors.delete(id)\n end\n end",
"def clear_cursor\n\t\t@map[@xcur][@ycur][:sym] = \n\t\t@map[@xcur][@ycur][:sym][1] unless\n\t\t@map[@xcur][@ycur][:sym].length == 1\n\tend",
"def hide_cursor!\n Vedeu.bind(:_hide_cursor_) do |name|\n Vedeu::Cursors::Cursor.hide_cursor(name)\n end\n\n Vedeu.bind_alias(:_cursor_hide_, :_hide_cursor_)\n end",
"def reset_cursor_point\n self.cursor_point = @cursor_zero_point\n end",
"def cursor_id\n 0\n end",
"def cancel_attack\n @windows[Win_Status].clear_dmg_preview\n @cursor.active = true \n end",
"def stop\n begin\n @curs.kill\n # Wait for the cursor to die -- can cause problems otherwise\n while @curs.alive? ; end\n # Set cursor to nil so set_banner method only works\n # when cursor is actually running.\n @cursor = nil\n reset_line\n puts (@parsed.message nil)\n # Set parsed to nil so set_message method only works\n # when cursor is actually running.\n @parsed = nil\n\n # Return execution time\n get_exec_time\n rescue NameError\n raise CursorNotRunning.new \"Can't stop, no cursor running.\"\n end\n end",
"def unregister_cursor(id)\n if id.nil?\n raise ArgumentError, 'unregister_cursor called with nil cursor_id'\n end\n if id == 0\n raise ArgumentError, 'unregister_cursor called with cursor_id=0'\n end\n\n @mutex.synchronize do\n @active_cursor_ids.delete(id)\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether the document returned is an error document. | def error?(doc)
# @todo implement this
false
end | [
"def command_failure?\n result = documents[0]\n result[\"ok\"] != 1 || error_message(result)\n end",
"def conversion_error?\n ipaper_document && ipaper_document.conversion_status == 'ERROR'\n end",
"def conversion_error?\n scribd_document && scribd_document.conversion_status == 'ERROR'\n end",
"def error; state == 'failed' ? @doc['error'] : nil; end",
"def conversion_error?\n scribd_document && scribd_document.conversion_status == 'ERROR'\n end",
"def query_failed?\n result = documents[0]\n flags.include?(:query_failure) || (result && (result[\"err\"] || result[\"errmsg\"] || result[\"$err\"]))\n end",
"def error?\n self.body.keys.include?(:err_code)\n end",
"def error?\n non_200? || (parsed.is_a?(Hash) && parsed['error'])\n end",
"def error?\n self.type == :error\n end",
"def _is_response_valid(doc,source)\n if select_node(doc,'//s:Fault').size > 0\n error = \"Unknown error\"\n begin\n reason = select_node_text(doc,'//s:Reason/s:Text')\n details = select_node_text(doc,'//psf:text')\n code = select_node_text(doc,'//psf:code')\n error = \"#{reason} (#{code}): #{details}\" \n rescue; end\n begin\n raise \"#{self.name} error w/ #{source}: #{error}\"\n rescue Exception => ex\n warn \"#{self.name} error: \" + ex.inspect.strip\n ex.backtrace.each { |line| warn 'from ' + line } \n raise ex\n end \n end\n end",
"def error(doc)\n begin\n xml_content xpath(doc,'//error').first\n rescue\n xml_content xpath(doc,'//errors').first\n end\n end",
"def response_is_error?\n is_error = !@parsed_response.dig('errors').nil?\n set_failure_message(FailureMessages::ERROR) if is_error\n is_error\n end",
"def valid?\n Definition.schema.valid?(@document)\n end",
"def validate_document_support!\n return if ['rest-json', 'json'].include?(@service.protocol)\n\n # Check all shapes and raise if any are Document types\n @service.api.fetch('shapes', {}).each do |name, shape|\n if shape['type'] == 'structure' && shape['document']\n raise \"Shape #{name} is a document type. Document types are only supported in json protocols.\"\n end\n end\n end",
"def error?\n get_last_error['err'] != nil\n end",
"def validate(document)\n #This is a stub, used for indexing\n end",
"def has_error_of_member_page?(document)\n document.search(\"//span[@class='error_solution']\").each do |item|\n if item.text =~ /先にコミュニティに/\n return true\n end\n end\n\n document.search(\"//p[@class='TXT12']\").each do |item|\n if item.value =~ /システムの問題により、/\n return true\n end\n end\n return false\n end",
"def parse_error(doc)\n fail ApicErrorResponse,\n sprintf('Error response from APIC (%s): \"%s\"',\n doc['imdata'][0]['error']['attributes']['code'].to_s,\n doc['imdata'][0]['error']['attributes']['text'].to_s) \\\n if doc['imdata'].length > 0 && doc['imdata'][0].include?('error')\n end",
"def error_page?\n popup_msg = get_el(doc.css('div#outsidecontainer'))\n return false if popup_msg.nil?\n return false if popup_msg.css('@style').to_s.match('display: none')\n return true if popup_msg.to_s.match(/error/i)\n return false\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether this query has a limit. | def limited?
limit > 0 if limit
end | [
"def below_limit?\n self.live_count < self::LIMIT\n end",
"def exceeds_queries_limit\n true if @queries.length > 5\n end",
"def more_after_limit?\n more_results == :MORE_RESULTS_AFTER_LIMIT\n end",
"def more_after_limit?\n more_results == :MORE_RESULTS_AFTER_LIMIT\n end",
"def limited?\n @limited\n end",
"def ignore_query_limit?\n !!@ignore_query_limit\n end",
"def validator\n if @queries.length > 10\n raise Exceptions::MaxLimitException, 'The query count entity has a '\\\n 'limit of 10 queries per request.'\n end\n true\n end",
"def limited?\n !!application_limit\n end",
"def equal_limit?\n limit == operand.limit\n end",
"def validator\n true if !exceeds_queries_limit &&\n !exceeds_columns_limit &&\n !exceeds_values_contains_limit\n end",
"def eligible?(n)\n n < @limit\n end",
"def unlimited?\n return @unlimited\n end",
"def over_limit?\n self.plan.limit.to_i > 0 && self.sms_usage >= self.plan.limit\n end",
"def vote_limit_enabled?\n vote_limit.present?\n end",
"def rate_limited?\n @calls.size >= @limit && (Time.now.to_i - @calls[-@limit]) < 1\n end",
"def max_count?\n return false if @smart_listing.max_count.nil?\n @smart_listing.count >= @smart_listing.max_count\n end",
"def at_submission_limit?\n if assessment.max_submissions == -1\n false\n else\n count = assessment.submissions.where(course_user_datum: course_user_datum).count\n count >= assessment.max_submissions\n end\n end",
"def has_more_results?\n\t\treturn true unless self.done_paging?\n\tend",
"def too_many_queries?\n Time.now.to_i - @last_query_time <= $roll_frequency.to_i*10\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether the cursor has been closed on the server. | def closed?
@cursor_id == 0
end | [
"def closed?\n # @cursor_id should in principle never be nil\n @cursor_id.nil? || @cursor_id == 0\n end",
"def closed?()\n @connection.closed?()\n end",
"def closed?\n @connection_state == :closed\n end",
"def closed?\n @connection.closed?\n end",
"def closed?\n return connection.nil?\n end",
"def closed?\n @db.closed?\n end",
"def closed?\n @stmt.closed?\n end",
"def closed?\n @stmt.closed?\n end",
"def alive?\n @cursor_id != CLOSED_CURSOR\n end",
"def closed?\n @closed.true?\n end",
"def closed?\n !server || server.closed?\n end",
"def closed?\n status == :closed\n end",
"def closed?\n stream = @_st_stream\n if stream._equal?(nil)\n true\n else\n stream.closed?\n end\n end",
"def closed?\n self.status.is_closed?\n end",
"def closed?\n @socket.closed?\n end",
"def closed?\n @context.nil? || @context.closed?\n end",
"def closed?\n @sock.closed?\n end",
"def closed?\n advance!\n @stream.closed?\n end",
"def closed?(connection)\n raise \"Should be implemented in child class\"\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The limit setting on the +CollectionView+. | def limit
@view.limit
end | [
"def limit\n options[:limit]\n end",
"def limit=(value)\n @limit = value\n end",
"def limit\n @limit\n end",
"def collections_limit_for_facets\n return if request.query_parameters['f'] && request.query_parameters['f'][blacklight_config.collection_field]\n\n collections_limit\n end",
"def limiting=(value)\n @limiting = value\n end",
"def set_Limit(value)\n set_input(\"Limit\", value)\n end",
"def set_Limit(value)\n set_input(\"Limit\", value)\n end",
"def limit(amount)\n @limit = amount.to_i\n end",
"def selected_limit\n param('limit') || DEFAULT_LIMIT\n end",
"def limit_posts; end",
"def limit(value = 20)\n clone.tap { |crit| crit.options[:limit] = value }\n end",
"def limit=(x); @opts['limit'] = x; end",
"def limit limit\n _clone._tap do |c|\n c.limit_clause = limit\n end\n end",
"def limited?\n @limited\n end",
"def limit(value)\n update_query(:limit => value)\n end",
"def limit(value)\n update_query(:limit => value)\n end",
"def limit\n operation.limit\n end",
"def vote_limit\n return nil if component_settings.vote_limit.zero?\n\n component_settings.vote_limit\n end",
"def limited?\n limit > 0 if limit\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Details: Create a frame! __ __ / \~~~/ \ ,( .. ) / \__ __/ /| (\ |( ^ \ /___\ /\ | |__| |__|.. Given an array of strings and a character to be used as border, output the frame with the content inside. Notes: Always keep a space between the input string and the left and right borders. The biggest string inside the array should always fit in the frame. The input array is never empty. Example frame(['Create', 'a', 'frame'], '+') Output: ++++++++++ + Create + + a + + frame + ++++++++++ | def frame(text, char)
max = text.map { |i| i.length }.max
frame = char * (max + 4)
text.map do |i|
wh = ' ' * (max - i.length).abs
"#{char} #{i} #{wh}#{char}"
end.unshift(frame).push(frame).join("\n")
end | [
"def frame(text, char)\n\n longest_word_length = (text.map { |w| w.length }.max)\n frame_width = longest_word_length + 4\n\n frame_top_bottom = char*(frame_width)\n frame_arr = []\n\n #top of frame\n frame_arr.push(\"#{frame_top_bottom}\\n\")\n\n #middle of frame (content and the sides of the frame)\n text.each do |word|\n diff = longest_word_length - word.length\n spaces = ' '*diff\n frame_arr.push(\"#{char} #{word} #{spaces}#{char}\\n\")\n end\n\n #bottom of frame\n frame_arr.push(\"#{frame_top_bottom}\")\n frame_arr.join\nend",
"def frame(string)\n beam = \"*\" * (string.length + 4)\n \"#{beam}\\n* #{string} *\\n#{beam}\"\nend",
"def draw_frame(args)\r\n # figure out width automatically\r\n text = args[:text]\r\n width = get_max_size_from_array(text)\r\n draw_top_frame(width)\r\n text.each do |t|\r\n t_size = get_real_size(t)\r\n draw_vert_frame_begin\r\n if t.kind_of?(Array)\r\n t.each do |s|\r\n print s\r\n end\r\n else\r\n print t\r\n end\r\n (width - (t_size + 4)).times do\r\n print \" \"\r\n end\r\n draw_vert_frame_end\r\n new_line\r\n end\r\n draw_bottom_frame(width)\r\n end",
"def pad_frame(frame)\n frame = frame.map{ |line| line[[0, (line.length - TOTAL_WIDTH) / 2].max.to_i, TOTAL_WIDTH].center(TOTAL_WIDTH) }\n blank_lines = HEIGHT - frame.size\n [EMPTY_LINE] * (blank_lines / 2.0).ceil + frame + [EMPTY_LINE] * (blank_lines / 2.0).floor\n end",
"def print_in_box(str)\n size = str.size\n border_line = '+-' + ('-' * size) + '-+'\n empty_line = '| ' + (' ' * size) + ' |'\n text_line = '| ' + str + ' |'\n \n puts border_line\n puts empty_line\n puts text_line\n puts empty_line\n puts border_line\nend",
"def create_game_frame(width,height)\n splash = ConsoleSplash.new(height, width)\n\n #Surrounding the game frame with fancy stylized symbols\n splash.write_horizontal_pattern(\"~-~\", {:fg=>:red, :bg=>:white})\n splash.write_left_pattern(\"<\", {:fg=>:red, :bg=>:white})\n splash.write_right_pattern(\">\", {:fg=>:red, :bg=>:white})\n\n return splash\nend",
"def drawBoard(charArr)\n\t\tdelim \t\t= \" | \"\n\t\tdelimDbl \t= \" || \"\n\t\t@baseChars = (\" \" + delimDbl + (\"a\"..\"h\").to_a.join(delim) + delimDbl + \" \")\n\t\t@hLine\t \t= (\"-\" * 41)\n\t\t@hLineDbl \t= (\"=\" * 41)\n\t\tboard \t\t= []\n\t\tboard.push(@baseChars)\n\t\tboard.push(@hLineDbl)\n\t\tfor j in (0..7)\n\t\t\tboard.push(\" #{j+1}#{delimDbl}#{charArr[j].split(\"\").join(delim)}#{delimDbl}#{j+1} \")\n\t\t\tboard.push(@hLine)\n\t\tend\n\t\tboard.pop\n\t\tboard.push(@hLineDbl)\n\t\tboard.push(@baseChars)\n\t\tputs board.reverse\n\tend",
"def print_in_box(str)\n sub_strings = sub_strings(str, 76)\n largest_sub_string = sub_strings.max_by { |str| str.size } # A bug caused by the fact\n # That an array may be \n # empty.\n size = largest_sub_string ? largest_sub_string.size : 0\n \n border_line = '+-' + ('-' * size) + '-+'\n empty_line = '| ' + (' ' * size) + ' |'\n \n puts border_line\n puts empty_line\n sub_strings.each do |str|\n puts '| ' + str.ljust(size) + ' |'\n end\n puts empty_line\n puts border_line\nend",
"def addBorder(picture)\n border = Array.new\n \n for i in 0..(picture[0].length+1)\n border << \"*\"\n end\n \n border = border.join(\"\")\n \n finalArray = Array.new\n \n for i in 0..(picture.count + 1)\n if (i == 0) or (i == (picture.count + 1))\n finalArray << border\n else\n picture[i-1] = \"*#{picture[i-1]}*\"\n finalArray << picture[i-1]\n end\n end\n \n finalArray\nend",
"def print_in_box(text)\n width = text.size\n result = <<EOS\n+-#{'-' * width}-+\n| #{' ' * width} |\n| #{text} |\n| #{' ' * width} |\n+-#{'-' * width}-+\nEOS\n result\nend",
"def tower_builder(n_floors)\n arr = []\n star_counter = 1\n space_counter = n_floors - 1\n n_floors.times do |num|\n arr << ' ' * space_counter + '*' * star_counter + ' ' * space_counter\n star_counter += 2\n space_counter -= 1\n end\n arr\nend",
"def towerBuilder(n_floors)\n floors = []\n width = n_floors * 2 + 1\n n_floors.times do |n|\n blocks = \"*\" * 2 * n + \"*\"\n space = \"\" \n ((width - blocks.length - 1 ) / 2).times do\n space += \" \"\n end\n floors << space + blocks + space\n end\n return floors\nend",
"def make_board(char_string)\nend",
"def pretty_print_buffer\n wrap_frame_with_border(show_buffer)\n end",
"def print_in_box(string)\r\n box_length = string.length\r\n box_walls = '-' * box_length + '--'\r\n box_spaces = ' ' * box_length\r\n boxed_msg = <<-MSG\r\n +#{box_walls}+\r\n | #{box_spaces} |\r\n | #{string} |\r\n | #{box_spaces} |\r\n +#{box_walls}+\r\n MSG\r\n\r\n puts boxed_msg\r\nend",
"def print_in_box(text)\n top_bottom_border = \"+\" + (\"-\" * (text.size + 2)) + \"+\"\n spacer_line = \"|\" + (\" \" * (text.size + 2)) + \"|\"\n message_line = \"| \" + text + \" |\"\n\n puts top_bottom_border\n puts spacer_line\n puts message_line\n puts spacer_line\n puts top_bottom_border\nend",
"def gen_bar(amount, full, width,\n border_char_l=\"[\", border_char_r=\"]\", border_color=:white,\n bar_on_char=\"|\", bar_off_char=\" \", \n bar_colors=[:green, :yellow, :red])\n\n bar_l = border_char_l.send(border_color)\n bar_r = border_char_r.send(border_color)\n\n barN_amount = (1.0)*(amount)/(full)*(width)\n barN_empty = width - barN_amount\n\n bar_use = (bar_on_char * barN_amount)\n bar_space = (bar_off_char * barN_empty)\n\n bar_fill = bar_use + bar_space\n bar_colored = \"\"\n bar_colors.each_index do |index|\n start_i = (width / bar_colors.size) * index\n end_i = (width / bar_colors.size) * (index+1)\n bar_colored += bar_fill[ start_i..end_i ].send( bar_colors[index] )\n end\n \n return \"#{bar_l}#{bar_colored}#{bar_r}\"\nend",
"def border\n buffer = screen_width % @border_character.length\n border_length = (screen_width / @border_character.length)\n @border_character * (border_length + buffer)\n end",
"def print_in_box(text)\n line = '-'\n lines = []\n text.size.times { lines << line }\n space = ' '\n spaces = []\n text.size.times { spaces << space }\n puts \"+#{lines.join}+\"\n puts \"|#{spaces.join}|\"\n puts \"|#{text}|\"\n puts \"|#{spaces.join}|\"\n puts \"+#{lines.join}+\"\nend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a hash return a new contact | def contact_from_hash(contact)
return Contact.new(contact['fname'], contact['lname'], contact['num'], contact['addr'])
end | [
"def create_card_from_hash(c)\n card = set_card_details(Card.new, c)\n card.save!\n card\nend",
"def add_to_hash(hash)\n super\n contact.add_to_hash(hash)\n hash['user_over_13'] = @user_over_13 || !@new_user\n hash['last_logged_in'] = fmt_date_time(@data_object.user_last_logged_in)\n hash['first_logged_in'] = fmt_date_time(@data_object.user_first_logged_in)\n# aff_opts = Affiliate.options\n\n hash\n end",
"def from_hash(hash); end",
"def build_contact(contact = {})\n case contact\n when Contact then contact.gateway = self\n when Hash then contact = Contact.new(contact.merge({:gateway => self}))\n end\n contact\n end",
"def new_from_hash(hash)\n if hash == nil\n self.class.new.assign(self)\n else\n hash_obj = hash\n if hash.instance_of?(Hash)\n hash_obj = self.class.new\n merge_hash_into_object(hash, hash_obj)\n end\n instance = self.class.new\n object_assign(instance, hash_obj)\n end\n end",
"def from_hash( hash )\n new.set( hash )\n end",
"def duplicate\n copy_attributes = self.attributes.symbolize_keys.except(:id, :created_at, :updated_at, :user_id, :emails_attributes)\n copy_attributes[:company] = self.company + \" (COPY)\"\n copy_attributes\n new_contact = Contact.new(copy_attributes)\n return new_contact\n end",
"def hash_to_address address\n call_blockchain_api(\"hashtoaddress/#{address}\")\n end",
"def create_by_kit_and_hash(kit, hash)\n record = new(\n hash: hash,\n source: kit.source,\n hostname: kit.hostname,\n url: kit.decoded_url,\n headers: kit.headers,\n filename: kit.filename,\n filesize: kit.filesize,\n mime_type: kit.mime_type,\n downloaded_as: kit.filepath_to_download\n )\n record.save\n record\n rescue TypeError, ActiveRecord::RecordNotUnique => _e\n nil\n end",
"def account(hash)\n ledger_entry(hash)\n end",
"def create_course_if_not_exists(school, hash)\n course = school.courses.find_by(hash)\n course = school.courses.create!(hash) if course == nil\n course\n end",
"def create_contact(name, telephone, email)\n\t contact = {name: name, telephone: telephone, email: email}\n\tend",
"def hash\n address.hash\n end",
"def add_contact_to_buckets(contact)\n\t\tbucket_for_hash(contact.node_id).push contact\n\tend",
"def find_entry_by_hash(hash)\n payload = db.get_entry_payload_from_hash(hash)\n return nil unless payload\n ChainEntry.parse_from_payload(payload)\n end",
"def create_shared_contact(_entity)\n _contact = SharedContact.create(first_name: first_name, last_name: last_name, company: company,\n fiscal_id: fiscal_id, street_type_id: street_type_id, street_name: street_name,\n street_number: street_number, building: building, floor: floor,\n floor_office: floor_office, zipcode_id: zipcode_id, town_id: town_id,\n province_id: province_id, country_id: country_id, phone: phone,\n extension: _entity.extension, fax: fax, cellular: cellular,\n email: email, shared_contact_type_id: 3, region_id: region_id,\n organization_id: organization_id, created_by: created_by, updated_by: updated_by)\n return _contact\n end",
"def create_shared_contact(_entity)\n _contact = SharedContact.create(first_name: _entity.first_name, last_name: _entity.last_name, company: _entity.company,\n fiscal_id: fiscal_id, street_type_id: street_type_id, street_name: street_name,\n street_number: street_number, building: building, floor: floor,\n floor_office: floor_office, zipcode_id: zipcode_id, town_id: town_id,\n province_id: province_id, country_id: country_id, phone: phone,\n extension: _entity.extension, fax: fax, cellular: cellular,\n email: email, shared_contact_type_id: 2, region_id: region_id,\n organization_id: organization_id, created_by: created_by, updated_by: updated_by)\n return _contact\n end",
"def assign_hash(hash)\n super hash\n create_if_exists hash, 'title', 'de', name: :c_title\n create_if_exists hash, 'title', name: :c_title\n create_if_exists hash, 'detail_url', name: :c_link\n create_if_exists hash, 'url', name: :c_link\n create_if_exists hash, 'short', name: :c_short\n create_if_exists hash, 'objective', 'de', name: :c_short\n create_if_exists hash, 'teachingContent', 'de', name: :c_teaching_content\n create_if_exists hash, 'additionalInformation', 'de', name: :c_additional_information\n create_if_exists hash, 'lectureNotes', 'de', name: :c_lecture_notes\n create_if_exists hash, 'instituteName', 'de', name: :c_institute_name\n create_if_exists hash, 'instituteCode', name: :c_institute_code\n\n end",
"def create_school_if_not_exists(hash)\n school = School.find_by(hash)\n school = School.create!(hash) if school == nil\n school\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get next available id from contacts | def getNextId
db = openDb #Define Db
db_hash = Hash.new
tempId = 0
db.each do |id,contact| #Iterate through and add if present
if Integer(id) > tempId
tempId = Integer(id) + 1
elsif Integer(id) == tempId
tempId += 1
end
end
closeDb(db) #Close daybreak
return tempId
end | [
"def get_next_id\n id = 0\n contacts = read_contacts\n contacts.each do |contact|\n if id < contact[:id]\n id = contact[:id]\n end\n end\n id + 1\nend",
"def read_next_id\n id = nil\n list = current_list\n\n if @co_index <= list.size\n id = list[@co_index - 1][:id]\n end\n\n @co_index += 1\n\n id\n end",
"def next_id\n id = @next_id\n @next_id += 1\n id\n end",
"def next_id\n self[:next_id]\n end",
"def provide_new_id\n all_ids = []\n #Adds all of the IDs into an array for further analysis\n CSV.foreach('contact_list.csv') do |row|\n all_ids << row[0].to_i\n end\n #Locates the highest ID\n highest_id = all_ids.max\n #puts \"Checking the 'highest_id'\"\n #puts highest_id\n new_id = highest_id + 1\n return new_id\n end",
"def next_id(options = {})\n raise \"Needs implementation :-)\"\n end",
"def next_uid\n LdapUser.all(limit: 1, sort_by: :uidnumber, order: :desc).first[:uidnumber]+1\n end",
"def next_cursor\n records.last.id\n end",
"def next_fetch_id\n @next_fetch_index ||= 0\n returning ids_to_fetch[@next_fetch_index] do\n @next_fetch_index += 1\n end\n end",
"def allocate_ID\n SemanticVernacularDataSource.ask_max_ID[0][\"id\"][\"value\"].to_i + 1\n end",
"def next_todo_id(todos)\n max = todos.map { |todo| todo[:id] }.max || 0\n max + 1\nend",
"def find_next_userid\n number = ldap.search(:base => user_dn, :filter => \"cn=*\")\n uids = []\n number.each do |result|\n uids.push(result[:uidnumber])\n end\n next_uid = uids.flatten.last.to_i + 1\n if uids.flatten.include?(next_uid)\n next_uid + 1\n elsif uids.empty?\n next_uid = 20000\n end\n next_uid\n end",
"def next_custom_invoice_id\n begin\n last_custom_invoice_id = Manifest.includes(:sale).where(:sales => { greenhouse_id: self.id }).where.not(:custom_invoice_id => nil).order(:custom_invoice_id => 'DESC').first.custom_invoice_id\n rescue Exception\n last_custom_invoice_id = nil\n end\n\n if last_custom_invoice_id != nil\n next_custom_invoice_id = last_custom_invoice_id + 1\n else\n next_custom_invoice_id = 1\n end\n\n return next_custom_invoice_id\n\n end",
"def contact_id\n addr_type = ALF::AddressType.where('address_type_id', self.address_type).first\n\n # if it is HOME type then base off of household\n if addr_type.address_type == 'Home'\n prev_id = CIVICRM::VineContactPrevId.where(alf_id: self.household).take\n else\n prev_id = CIVICRM::VineContactPrevId.where(alf_id: self.person).take\n end\n\n # if no prev_id then base off of what is found\n if prev_id.nil?\n if self.person.present?\n prev_id = CIVICRM::VineContactPrevId.where(alf_id: self.person).take\n else\n prev_id = CIVICRM::VineContactPrevId.where(alf_id: self.household).take\n end\n end\n\n return if prev_id.nil?\n contact = CIVICRM::Contact.where(id: prev_id.contact_id).take\n\n return if contact.nil?\n return contact.id\n end",
"def contact_id\n if self.person_id.present?\n contact_type = CIVICRM::ContactType.where(name: 'Individual').take\n prev_id = CIVICRM::VineContactPrevId.where(f1_id: self.person_id, contact_type_id: contact_type.id).take\n else\n contact_type = CIVICRM::ContactType.where(name: 'Household').take\n prev_id = CIVICRM::VineContactPrevId.where(f1_id: self.household_id, contact_type_id: contact_type.id).take\n end\n\n return if prev_id.nil?\n contact = CIVICRM::Contact.where(id: prev_id.contact_id).take\n\n return if contact.nil?\n return contact.id\n end",
"def next_id=(value)\n @_next_id = value\n end",
"def load_next_uid\n all_uids = load_ldap_uids\n next_uid = 0\n\n # This accounts for any GIDs that might not be in Active Directory yet\n # as well.\n (all_uids + @uids).uniq.sort.each do |uid|\n if next_uid == 0 || next_uid + 1 == uid\n next_uid = uid\n else\n break\n end\n end\n\n if next_uid == 0\n @min_uid\n else\n next_uid + 1\n end\n end",
"def next_id\n @last_id += 1 while @nodes_by_id.keys.include?(@last_id + 1)\n @last_id += 1\n end",
"def find_next\n PcpItem.where( pcp_subject_id: pcp_subject_id ).where( 'id > ?', id ).first\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates the schemes based on the targets. | def recreate_schemes
@project.targets.each do |t|
create_schemes_for_target(t)
end
end | [
"def create_schemes_for_target(target)\n case target.product_type\n when Xcodeproj::Constants::PRODUCT_TYPE_UTI[:application]\n create_schemes_for_application(target)\n end\n end",
"def create_schemes_for_application(target)\n target.build_configurations.each do |c|\n scheme = Scheme.new\n\n scheme.name = \"#{target.name}-#{c.name}\"\n @xcschememanagement['SuppressBuildableAutocreation'][target.uuid] = {\"primary\" => true}\n\n unit_test_target = project.find_unit_test_target_for_target(target)\n scheme.configure_with_targets(target, unit_test_target)\n\n scheme.test_action.build_configuration = c.name\n scheme.launch_action.build_configuration = c.name\n scheme.profile_action.build_configuration = c.name\n scheme.analyze_action.build_configuration = c.name\n scheme.archive_action.build_configuration = c.name\n\n #TODO: We should structure this stuff out\n if unit_test_target then\n unit_test_target.add_dependency(target)\n @xcschememanagement['SuppressBuildableAutocreation'][unit_test_target.uuid] = {\"primary\" => true}\n end\n\n schemes << scheme\n end\n end",
"def configure_schemes(project, pod_targets, generator_result)\n pod_targets.each do |pod_target|\n share_scheme = pod_target.should_build? && share_scheme_for_development_pod?(pod_target.pod_name) && sandbox.local?(pod_target.pod_name)\n configure_schemes_for_pod_target(project, pod_target, share_scheme, generator_result)\n end\n end",
"def schemes_for_native_targets(project, targets)\n schemes = Dir[File.join(XCScheme.shared_data_dir(project.path), XCSCHEME_EXT)] +\n Dir[File.join(XCScheme.user_data_dir(project.path), XCSCHEME_EXT)]\n\n schemes = schemes.map { |scheme| [scheme, Xcodeproj::XCScheme.new(scheme)] }\n\n targets_names = targets.map(&:name)\n schemes.select do |scheme|\n scheme[1].test_action.testables.any? do |testable|\n testable.buildable_references.any? do |buildable|\n targets_names.include? buildable.target_name\n end\n end\n end\n end",
"def create_scheme_registry\n sr = SchemeRegistry.new\n sr.register( Scheme.new( \"http\", 80, plain_factory ) )\n sr.register( Scheme.new( \"https\", 443, ssl_factory ) )\n sr\n end",
"def buildable_scheme_and_target\n result = []\n\n schemes.each do |each_scheme|\n target = targets.find do |t|\n t.dylib? && t.target_name == each_scheme.target_name && t.platform_type == platform\n end\n\n target = targets.find do |t|\n t.static? && t.target_name == each_scheme.target_name && t.platform_type == platform\n end if target.nil?\n\n result.append(XcodeBuildableInfo.new(each_scheme, target)) if target != nil\n end\n\n result\n end",
"def build_targets(targets)\n targets.to_a.map do |object, row|\n preferences, capacity = parse_target_row(row)\n target(object).tap do |t|\n t.capacity = capacity\n t.prefer(*preferences.map { |c| candidate(c) })\n end\n end\n end",
"def recreate_user_schemes(visible = true)\n schemes_dir = XCScheme.user_data_dir(path)\n FileUtils.rm_rf(schemes_dir)\n FileUtils.mkdir_p(schemes_dir)\n\n xcschememanagement = {}\n xcschememanagement['SchemeUserState'] = {}\n xcschememanagement['SuppressBuildableAutocreation'] = {}\n\n targets.each do |target|\n scheme = XCScheme.new\n\n test_target = target if target.respond_to?(:test_target_type?) && target.test_target_type?\n launch_target = target.respond_to?(:launchable_target_type?) && target.launchable_target_type?\n scheme.configure_with_targets(target, test_target, :launch_target => launch_target)\n\n yield scheme, target if block_given?\n scheme.save_as(path, target.name, false)\n xcschememanagement['SchemeUserState'][\"#{target.name}.xcscheme\"] = {}\n xcschememanagement['SchemeUserState'][\"#{target.name}.xcscheme\"]['isShown'] = visible\n end\n\n xcschememanagement_path = schemes_dir + 'xcschememanagement.plist'\n Plist.write_to_path(xcschememanagement, xcschememanagement_path)\n end",
"def schemes\n @schemes ||= if workspace?\n workspace.schemes.reject do |k, v|\n v.include?(\"Pods/Pods.xcodeproj\")\n end.keys\n else\n Xcodeproj::Project.schemes(path)\n end\n end",
"def schemes=(new_schemes)\n @schemes = new_schemes.map(&:to_s)\n end",
"def generate_targets\n has_metaname = has_version?\n\n %w[clean update fetch configure export build install].each do |target|\n target_name = \"#{@name}_#{target}\".to_sym\n target_metaname = \"#{@metaname}_#{target}\".to_sym if has_metaname\n func = pkg_default_target_func(@name.to_sym, target)\n\n task = Rake::Task.define_task(target_name, &func)\n metatask = Rake::Task.define_task(target_metaname, &func) if has_metaname\n\n # Add per-task dependency\n case target\n when /install/i\n task.enhance([\"#{@name}_build\".to_sym])\n metatask.enhance([\"#{@metaname}_build\".to_sym]) if has_metaname\n when /build/i\n task.enhance([\"#{@name}_export\".to_sym])\n metatask.enhance([\"#{@metaname}_export\".to_sym]) if has_metaname\n\n # Generate package export dependencies\n @build_deps.each do |dep|\n task.enhance([\"#{dep}_export\".to_sym])\n metatask.enhance([\"#{dep}_export\".to_sym]) if has_metaname\n end\n\n # Generate package build dependencies\n @clean_deps.each do |dep|\n task.enhance([\"#{dep}_install\".to_sym])\n metatask.enhance([\"#{dep}_install\".to_sym]) if has_metaname\n end\n when /export/i\n task.enhance([\"#{@name}_configure\".to_sym])\n metatask.enhance([\"#{@metaname}_configure\".to_sym]) if has_metaname\n when /configure/i\n task.enhance([\"#{@name}_fetch\".to_sym])\n metatask.enhance([\"#{@metaname}_fetch\".to_sym]) if has_metaname\n when /clean/i\n # Generate package clean dependencies\n @clean_deps.each do |dep|\n task.enhance([\"#{dep}_clean\".to_sym])\n metatask.enhance([\"#{dep}_clean\".to_sym]) if has_metaname\n end\n end\n\n update_global_task(target, target_name)\n end\n\n # Create the default package task named after the package name\n task = Rake::Task.define_task(\"#{@name}\" => [\"#{@name}_install\".to_sym])\n metatask = Rake::Task.define_task(\"#{@metaname}\" => [\"#{@metaname}_install\".to_sym]) if has_metaname\n end",
"def load_schemes_from_project project_full_path\n schemes = Xcodeproj::Project.schemes project_full_path\n schemes.each do |scheme_name|\n @schemes[scheme_name] = project_full_path\n end\n end",
"def schemes\n results = []\n output = raw_info.split(\"Schemes:\").last.split(\":\").first\n\n if raw_info.include?(\"There are no schemes in workspace\") or raw_info.include?(\"This project contains no schemes\")\n return results\n end\n\n output.split(\"\\n\").each do |current|\n current = current.strip\n\n next if current.length == 0\n results << current\n end\n\n results\n end",
"def targets\n return @targets unless @targets.nil?\n\n expanded_urls = []\n @split_targets.each do |target|\n expanded_urls = (expanded_urls | expand_targets(target))\n end\n @targets = expanded_urls.map do |url|\n config = @conn_options.merge(config_for_target(url))\n TargetHost.new(config.delete(:url), config)\n end\n end",
"def share_development_pod_schemes\n development_pod_targets.select(&:should_build?).each do |pod_target|\n next unless share_scheme_for_development_pod?(pod_target.pod_name)\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.label)\n if pod_target.contains_test_specifications?\n pod_target.test_specs.each do |test_spec|\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.test_target_label(test_spec))\n end\n end\n end\n end",
"def share_development_pod_schemes\n development_pod_targets.select(&:should_build?).each do |pod_target|\n next unless share_scheme_for_development_pod?(pod_target.pod_name)\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.label)\n if pod_target.contains_test_specifications?\n pod_target.supported_test_types.each do |test_type|\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.test_target_label(test_type))\n end\n end\n end\n end",
"def initialize(schemes = nil)\n @schemes = []\n schemes = Array(schemes)\n schemes = DEFAULT if schemes.empty?\n schemes.each do |scheme|\n @schemes << (scheme.is_a?(Daijobu::Parser) ? scheme : Daijobu::Parser.get(scheme))\n end\n @current = 0\n end",
"def scheme_list\n end",
"def create_target_refs_and_links?\n tr_create = [] #node/node-groups that need target ref created\n tr_link = {} #node/node-groups that need to be linked to existing target refs\n tr_link_candidates = []\n\n # ndx_needs_sc is used to find nodes that need a state change object\n # meaning model is annoatted so these when a task is run will cause a node to be created\n # initiallly set ndx_needs_state_change to have all nodes and then in loop below remove ones\n # that are linked to existing nodes\n ndx_needs_sc = {}\n @nodes.each do |node|\n if node.is_node_group?() && !node[:target_refs_exist]\n tr_create << node\n else\n tr_link_candidates << node\n end\n # initiallly set ndx_needs_state_change to have all nodes\n ndx_needs_sc.merge!(node[:id] => node)\n end\n\n Input::BaseNodes.create_linked_target_refs?(@target, @assembly, tr_create)\n\n to_link_array = existing_target_refs_to_link(tr_link_candidates, ndx_needs_sc)\n link_to_target_refs(to_link_array)\n\n # needed target_ref state changes\n ndx_needs_sc.reject { |_node, needs_sc| !needs_sc }.values\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates schemes based on a target. | def create_schemes_for_target(target)
case target.product_type
when Xcodeproj::Constants::PRODUCT_TYPE_UTI[:application]
create_schemes_for_application(target)
end
end | [
"def create_schemes_for_application(target)\n target.build_configurations.each do |c|\n scheme = Scheme.new\n\n scheme.name = \"#{target.name}-#{c.name}\"\n @xcschememanagement['SuppressBuildableAutocreation'][target.uuid] = {\"primary\" => true}\n\n unit_test_target = project.find_unit_test_target_for_target(target)\n scheme.configure_with_targets(target, unit_test_target)\n\n scheme.test_action.build_configuration = c.name\n scheme.launch_action.build_configuration = c.name\n scheme.profile_action.build_configuration = c.name\n scheme.analyze_action.build_configuration = c.name\n scheme.archive_action.build_configuration = c.name\n\n #TODO: We should structure this stuff out\n if unit_test_target then\n unit_test_target.add_dependency(target)\n @xcschememanagement['SuppressBuildableAutocreation'][unit_test_target.uuid] = {\"primary\" => true}\n end\n\n schemes << scheme\n end\n end",
"def recreate_schemes\n @project.targets.each do |t|\n create_schemes_for_target(t)\n end\n end",
"def configure_schemes(project, pod_targets, generator_result)\n pod_targets.each do |pod_target|\n share_scheme = pod_target.should_build? && share_scheme_for_development_pod?(pod_target.pod_name) && sandbox.local?(pod_target.pod_name)\n configure_schemes_for_pod_target(project, pod_target, share_scheme, generator_result)\n end\n end",
"def create_scheme_registry\n sr = SchemeRegistry.new\n sr.register( Scheme.new( \"http\", 80, plain_factory ) )\n sr.register( Scheme.new( \"https\", 443, ssl_factory ) )\n sr\n end",
"def new_target(target)\n native_target = new(Xcodeproj::Project::Object::PBXNativeTarget)\n native_target.name = target.name\n native_target.product_name = target.name\n\n case target.type\n when Symbol\n native_target.product_type = Xcodeproj::Constants::PRODUCT_TYPE_UTI[target.type]\n when String\n native_target.product_type = target.type\n end\n\n native_target.build_configuration_list = new(Xcodeproj::Project::Object::XCConfigurationList)\n\n product = products_group.new_product_ref_for_target(native_target.product_name, target.type)\n native_target.product_reference = product\n\n targets << native_target\n native_target\n end",
"def buildable_scheme_and_target\n result = []\n\n schemes.each do |each_scheme|\n target = targets.find do |t|\n t.dylib? && t.target_name == each_scheme.target_name && t.platform_type == platform\n end\n\n target = targets.find do |t|\n t.static? && t.target_name == each_scheme.target_name && t.platform_type == platform\n end if target.nil?\n\n result.append(XcodeBuildableInfo.new(each_scheme, target)) if target != nil\n end\n\n result\n end",
"def schemes_for_native_targets(project, targets)\n schemes = Dir[File.join(XCScheme.shared_data_dir(project.path), XCSCHEME_EXT)] +\n Dir[File.join(XCScheme.user_data_dir(project.path), XCSCHEME_EXT)]\n\n schemes = schemes.map { |scheme| [scheme, Xcodeproj::XCScheme.new(scheme)] }\n\n targets_names = targets.map(&:name)\n schemes.select do |scheme|\n scheme[1].test_action.testables.any? do |testable|\n testable.buildable_references.any? do |buildable|\n targets_names.include? buildable.target_name\n end\n end\n end\n end",
"def _create_target # :nodoc:\n @target_class.new\n end",
"def build_targets(targets)\n targets.to_a.map do |object, row|\n preferences, capacity = parse_target_row(row)\n target(object).tap do |t|\n t.capacity = capacity\n t.prefer(*preferences.map { |c| candidate(c) })\n end\n end\n end",
"def connect(*target)\n options = (::Hash === target.last ? target.pop : {})\n\n constant = target.first || options[:constant]\n\n command = options[:command] || options[:to]\n feature = options[:feature] || options[:to]\n\n if constant\n connections = (@@constant_connections[constant] ||= [])\n if feature && !command\n old = connections.find{ |c| c[:feature] && !c[:command] }\n connections.delete(old)\n connections << {:feature => feature}\n elsif command && !feature\n connections << {:command=>command}\n else\n connections << {:feature=>feature, :command=>command}\n end\n else\n @@command_connections[command] = feature\n end\n end",
"def create_target_table(context, &block)\n with_logging(:debug, \"Creating target table #{target} (from #{source})\") do\n context.execute \"CREATE TABLE #{target} LIKE #{source}\"\n yield if block_given?\n end\n end",
"def schemes=(new_schemes)\n @schemes = new_schemes.map(&:to_s)\n end",
"def share_development_pod_schemes\n development_pod_targets.select(&:should_build?).each do |pod_target|\n next unless share_scheme_for_development_pod?(pod_target.pod_name)\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.label)\n if pod_target.contains_test_specifications?\n pod_target.test_specs.each do |test_spec|\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.test_target_label(test_spec))\n end\n end\n end\n end",
"def share_development_pod_schemes\n development_pod_targets.select(&:should_build?).each do |pod_target|\n next unless share_scheme_for_development_pod?(pod_target.pod_name)\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.label)\n if pod_target.contains_test_specifications?\n pod_target.supported_test_types.each do |test_type|\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.test_target_label(test_type))\n end\n end\n end\n end",
"def make_shared_scheme(installer)\n scheme = Xcodeproj::XCScheme.new()\n\n installer.pods_project.targets.each do |target|\n if !target.name.start_with?(\"Pods\")\n scheme.add_build_target(target)\n end\n end\n\n scheme.save_as(installer.pods_project.path, \"SharedScheme\")\n puts \"Created shared scheme\"\nend",
"def recreate_user_schemes(visible = true)\n schemes_dir = XCScheme.user_data_dir(path)\n FileUtils.rm_rf(schemes_dir)\n FileUtils.mkdir_p(schemes_dir)\n\n xcschememanagement = {}\n xcschememanagement['SchemeUserState'] = {}\n xcschememanagement['SuppressBuildableAutocreation'] = {}\n\n targets.each do |target|\n scheme = XCScheme.new\n\n test_target = target if target.respond_to?(:test_target_type?) && target.test_target_type?\n launch_target = target.respond_to?(:launchable_target_type?) && target.launchable_target_type?\n scheme.configure_with_targets(target, test_target, :launch_target => launch_target)\n\n yield scheme, target if block_given?\n scheme.save_as(path, target.name, false)\n xcschememanagement['SchemeUserState'][\"#{target.name}.xcscheme\"] = {}\n xcschememanagement['SchemeUserState'][\"#{target.name}.xcscheme\"]['isShown'] = visible\n end\n\n xcschememanagement_path = schemes_dir + 'xcschememanagement.plist'\n Plist.write_to_path(xcschememanagement, xcschememanagement_path)\n end",
"def load_schemes_from_project project_full_path\n schemes = Xcodeproj::Project.schemes project_full_path\n schemes.each do |scheme_name|\n @schemes[scheme_name] = project_full_path\n end\n end",
"def scheme(svc:)\n # Add the DOI service as an IdentifierScheme if it doesn't already exist\n scheme = IdentifierScheme.find_or_create_by(name: svc.name)\n if scheme.new_record?\n scheme.update(description: svc.description, active: true,\n for_identification: true, for_plans: true)\n end\n scheme\n end",
"def create_relation(owner, target)\n relation.new(owner, target, self)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates schemes based on a application target | def create_schemes_for_application(target)
target.build_configurations.each do |c|
scheme = Scheme.new
scheme.name = "#{target.name}-#{c.name}"
@xcschememanagement['SuppressBuildableAutocreation'][target.uuid] = {"primary" => true}
unit_test_target = project.find_unit_test_target_for_target(target)
scheme.configure_with_targets(target, unit_test_target)
scheme.test_action.build_configuration = c.name
scheme.launch_action.build_configuration = c.name
scheme.profile_action.build_configuration = c.name
scheme.analyze_action.build_configuration = c.name
scheme.archive_action.build_configuration = c.name
#TODO: We should structure this stuff out
if unit_test_target then
unit_test_target.add_dependency(target)
@xcschememanagement['SuppressBuildableAutocreation'][unit_test_target.uuid] = {"primary" => true}
end
schemes << scheme
end
end | [
"def create_schemes_for_target(target)\n case target.product_type\n when Xcodeproj::Constants::PRODUCT_TYPE_UTI[:application]\n create_schemes_for_application(target)\n end\n end",
"def recreate_schemes\n @project.targets.each do |t|\n create_schemes_for_target(t)\n end\n end",
"def configure_schemes(project, pod_targets, generator_result)\n pod_targets.each do |pod_target|\n share_scheme = pod_target.should_build? && share_scheme_for_development_pod?(pod_target.pod_name) && sandbox.local?(pod_target.pod_name)\n configure_schemes_for_pod_target(project, pod_target, share_scheme, generator_result)\n end\n end",
"def schemes_for_native_targets(project, targets)\n schemes = Dir[File.join(XCScheme.shared_data_dir(project.path), XCSCHEME_EXT)] +\n Dir[File.join(XCScheme.user_data_dir(project.path), XCSCHEME_EXT)]\n\n schemes = schemes.map { |scheme| [scheme, Xcodeproj::XCScheme.new(scheme)] }\n\n targets_names = targets.map(&:name)\n schemes.select do |scheme|\n scheme[1].test_action.testables.any? do |testable|\n testable.buildable_references.any? do |buildable|\n targets_names.include? buildable.target_name\n end\n end\n end\n end",
"def create_scheme_registry\n sr = SchemeRegistry.new\n sr.register( Scheme.new( \"http\", 80, plain_factory ) )\n sr.register( Scheme.new( \"https\", 443, ssl_factory ) )\n sr\n end",
"def share_development_pod_schemes\n development_pod_targets.select(&:should_build?).each do |pod_target|\n next unless share_scheme_for_development_pod?(pod_target.pod_name)\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.label)\n if pod_target.contains_test_specifications?\n pod_target.test_specs.each do |test_spec|\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.test_target_label(test_spec))\n end\n end\n end\n end",
"def load_schemes_from_project project_full_path\n schemes = Xcodeproj::Project.schemes project_full_path\n schemes.each do |scheme_name|\n @schemes[scheme_name] = project_full_path\n end\n end",
"def buildable_scheme_and_target\n result = []\n\n schemes.each do |each_scheme|\n target = targets.find do |t|\n t.dylib? && t.target_name == each_scheme.target_name && t.platform_type == platform\n end\n\n target = targets.find do |t|\n t.static? && t.target_name == each_scheme.target_name && t.platform_type == platform\n end if target.nil?\n\n result.append(XcodeBuildableInfo.new(each_scheme, target)) if target != nil\n end\n\n result\n end",
"def make_shared_scheme(installer)\n scheme = Xcodeproj::XCScheme.new()\n\n installer.pods_project.targets.each do |target|\n if !target.name.start_with?(\"Pods\")\n scheme.add_build_target(target)\n end\n end\n\n scheme.save_as(installer.pods_project.path, \"SharedScheme\")\n puts \"Created shared scheme\"\nend",
"def share_development_pod_schemes\n development_pod_targets.select(&:should_build?).each do |pod_target|\n next unless share_scheme_for_development_pod?(pod_target.pod_name)\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.label)\n if pod_target.contains_test_specifications?\n pod_target.supported_test_types.each do |test_type|\n Xcodeproj::XCScheme.share_scheme(project.path, pod_target.test_target_label(test_type))\n end\n end\n end\n end",
"def scheme_list\n end",
"def load_schemes_from_project(project_full_path)\n schemes = Xcodeproj::Project.schemes project_full_path\n schemes.each do |scheme_name|\n @schemes[scheme_name] = project_full_path\n end\n end",
"def recreate_user_schemes(visible = true)\n schemes_dir = XCScheme.user_data_dir(path)\n FileUtils.rm_rf(schemes_dir)\n FileUtils.mkdir_p(schemes_dir)\n\n xcschememanagement = {}\n xcschememanagement['SchemeUserState'] = {}\n xcschememanagement['SuppressBuildableAutocreation'] = {}\n\n targets.each do |target|\n scheme = XCScheme.new\n\n test_target = target if target.respond_to?(:test_target_type?) && target.test_target_type?\n launch_target = target.respond_to?(:launchable_target_type?) && target.launchable_target_type?\n scheme.configure_with_targets(target, test_target, :launch_target => launch_target)\n\n yield scheme, target if block_given?\n scheme.save_as(path, target.name, false)\n xcschememanagement['SchemeUserState'][\"#{target.name}.xcscheme\"] = {}\n xcschememanagement['SchemeUserState'][\"#{target.name}.xcscheme\"]['isShown'] = visible\n end\n\n xcschememanagement_path = schemes_dir + 'xcschememanagement.plist'\n Plist.write_to_path(xcschememanagement, xcschememanagement_path)\n end",
"def schemes\n @schemes ||= if workspace?\n workspace.schemes.reject do |k, v|\n v.include?(\"Pods/Pods.xcodeproj\")\n end.keys\n else\n Xcodeproj::Project.schemes(path)\n end\n end",
"def schemes\n results = []\n output = raw_info.split(\"Schemes:\").last.split(\":\").first\n\n if raw_info.include?(\"There are no schemes in workspace\") or raw_info.include?(\"This project contains no schemes\")\n return results\n end\n\n output.split(\"\\n\").each do |current|\n current = current.strip\n\n next if current.length == 0\n results << current\n end\n\n results\n end",
"def choseScheme()\n \tscheme = UI.select(\"Select scheme:\", [\"CIASMovie\", \"ZhongDuMovie\", \"BaoShan\", \"HuaChenMovie\", \"HengDian\"])\n\n\tENV[\"SCHEME\"] = scheme\n\tENV[\"APP_ID\"] = ENV[\"APP_ID_#{scheme}\"]\n\n end",
"def schemes=(new_schemes)\n @schemes = new_schemes.map(&:to_s)\n end",
"def scheme_handlers=(scheme_handlers); end",
"def scheme(svc:)\n # Add the DOI service as an IdentifierScheme if it doesn't already exist\n scheme = IdentifierScheme.find_or_create_by(name: svc.name)\n if scheme.new_record?\n scheme.update(description: svc.description, active: true,\n for_identification: true, for_plans: true)\n end\n scheme\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public: Builds HTML title tag text from current tag and profile username for tags views. Examples page_title => "Rails | simeonwillbanks | My Gists" Returns a String of the page title. | def page_title
super(current_tag.name, profile.username)
end | [
"def page_title\n super(profile.username)\n end",
"def page_title\n title = t(\"#{controller_name}.#{action_name}.title\")\n html = <<-HTML\n <div class=\"page-header\">\n <h1>#{title}</h1>\n </div>\n HTML\n html.html_safe\n end",
"def title_tag\n content_tag :title, title_text.to_s\n end",
"def page_title \n %(<title>#{page_title_raw}My Blog</title>) # Customize this for your blog\n end",
"def page_title \n raw %(<title>#{page_title_raw}My USA Coin</title>)\n end",
"def title\n @title ||= begin\n if site_title && page_title != site_title\n page_title + TITLE_SEPARATOR + site_title\n elsif site_description && site_title\n site_title + TITLE_SEPARATOR + site_tagline_or_description\n else\n page_title || site_title\n end\n end\n\n return page_number + @title if page_number\n\n @title\n end",
"def title\n @title ||= begin\n if site_title && page_title != site_title\n page_title + TITLE_SEPARATOR + site_title\n elsif site_description && site_title\n site_title + TITLE_SEPARATOR + site_description\n else\n page_title || site_title\n end\n end\n end",
"def title(str, container = :h2)\n page_title(str) if @page_title.blank?\n content_tag(container, str) if container\n end",
"def title(str, container = nil)\n @page_title = str\n content_tag(container, str) if container\n end",
"def title\n @title ||= begin\n if site_title && page_title != site_title\n page_title + TITLE_SEPARATOR + site_title\n elsif site_description && site_title\n site_title + TITLE_SEPARATOR + site_title_extention_or_description\n else\n page_title || site_title\n end\n end\n\n return page_number + @title if page_number\n\n @title\n end",
"def title(page_title, options={})\n content_for(:title, page_title.to_s)\n return content_tag(:h1, page_title, options)\n end",
"def page_title(options = {})\n return \"\" if @page.title.blank?\n\n options = {\n prefix: \"\",\n suffix: \"\",\n separator: \"\"\n }.update(options)\n title_parts = [options[:prefix]]\n title_parts << if response.status == 200\n @page.title\n else\n response.status\n end\n title_parts << options[:suffix]\n title_parts.reject(&:blank?).join(options[:separator]).html_safe\n end",
"def page_title(options = {})\n return \"\" if @page.title.blank?\n options = {\n prefix: \"\",\n suffix: \"\",\n separator: \"\"\n }.update(options)\n title_parts = [options[:prefix]]\n if response.status == 200\n title_parts << @page.title\n else\n title_parts << response.status\n end\n title_parts << options[:suffix]\n title_parts.reject(&:blank?).join(options[:separator]).html_safe\n end",
"def page_title title, options = {}\n if defined? set_meta_tags\n set_meta_tags site: t('app.name'), title: title, reverse: true\n end\n content_for(:page_title) { title } if options[:in_page]\n content_for(:head_title) { title }\n end",
"def make_title page_title=nil\n \n if page_title.nil? || page_title.match(/^\\s*$/)\n\n page_title = controller.action_name.titleize\n\n end\n \n page_title + \": \" + BASE_TITLE\n \n end",
"def title(tag)\n UI.bold { \"%15s\" % tag }\n end",
"def title\n @title ||= (Nokogiri::HTML.parse(@html).title).to_s.gsub(/\\n|\\t|\\r/,\"\")\n end",
"def page_title(title, should_prefix = true)\n @unprefixed_title = title\n should_prefix ? @page_title = prefix(title) : @page_title = title\n \"<h1>#{title}</h1>\"\n end",
"def title\n return @title if @title\n if matches = class_const(:TITLE_RE).match(page)\n @title = matches[1].to_s.strip\n title_processor\n @title = decode_entities(@title)\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the WarwickSSO cookie | def sso_cookie
cookies['WarwickSSO']
end | [
"def get_cookie\n resp = @cookie\n if @atl_token != \"\"\n resp = resp + \"; atl.xsrf.token=#{@atl_token}\"\n end\n puts \"Using cookie: #{resp}\".yellow\n resp\n end",
"def get_cookie\n self.headers[\"Cookie\"]\n end",
"def cookie\n headers['Cookie']\n end",
"def get_cookie(name); end",
"def get_cookie(cookie_name)\n return @common['site_type'][self.site_type]['cookies'][cookie_name]\n end",
"def cookie\n { :value => Crypt.encrypt(cookie_value), :expires => 1.year.from_now }\n end",
"def hubssolib_get_secure_cookie_data(name)\n return HubSsoLib::Crypto.decode_object(cookies[name], request.remote_ip)\n end",
"def raw_cookie\n return env_table['HTTP_COOKIE']\n end",
"def raw_cookie\n env_table[\"HTTP_COOKIE\"]\n end",
"def get_session_cookie(response)\n response.get_fields('set-cookie').each do |cookie|\n return cookie if cookie =~ /JSESSIONID/\n end\n end",
"def raw_cookie\n (@response['Set-Cookie'] || '')\n end",
"def fb_cookie\n cookies[\"fbsr_#{ facepalm.app_id }\"]\n end",
"def cookie_info\n authenticated_crowd_call(:get_cookie_info)\n end",
"def daw_cookie_name\n Rdaw.const_defined?('DAW_COOKIE_NAME') ? Rdaw::DAW_COOKIE_NAME : 'myacinfo'\n end",
"def raw_cookie\n (response['Set-Cookie'] || '')\n end",
"def read_cookie\n @session.cgi.cookies[@cookie_options['name']].first\n end",
"def get_w_cookie(api)\n\t\t\tparams = set_default_params_w_cookie(api[:params])\n\t\t\tquery = hash_to_querystring(params)\n\t\t\turl = \"#{api[:path]}?#{query}\"\n\t\t\tresponse = @http.get(url,cookie_hash)\n\t\t\tputs \"#{response.code} - #{response.message}: #{api[:path]} \"\n\t\t\tcheck_cookie(response)\n\t\t\treport_error(response)\n\t\t\tresponse\n\t\tend",
"def cookie\n @cookie ||= Coca::AuthCookie.new(cookies, scope)\n end",
"def fortune_cookie\n fetch('quote.fortune_cookie')\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine what provider is to be used for this platform | def determine_provider
return nil unless node && node['platform_family']
Chef::Provider::ChefDk.const_get(node['platform_family'].split('_')
.map(&:capitalize).join)
end | [
"def get_provider()\n if isWindows()\n return \"hyperv\"\n end\n\n return \"virtualbox\"\nend",
"def provider\n system.provider\n end",
"def guess_provider()\n host = RbConfig::CONFIG['host_os']\n\n case host\n when /darwin/\n vmware = '/Applications/VMware Fusion.app'\n virtualbox = '/Applications/VirtualBox.app'\n return Dir.exists?(vmware) &&\n Vagrant.has_plugin?('vagrant-vmware-fusion') ? :vmware_fusion\n : Dir.exists?(vmware) &&\n Vagrant.has_plugin?('vagrant-vmware-desktop') ? :vmware_desktop\n : Dir.exists?(virtualbox) ? :virtualbox\n : nil\n when /linux/\n kvm = '/usr/bin/kvm'\n virtualbox = '/usr/bin/virtualbox'\n return File.exists?(kvm) &&\n Vagrant.has_plugin?('vagrant-libvirt') ? :libvirt\n : File.exists?(virtualbox) ? :virtualbox\n : nil\n when /mingw/i\n vmware = 'C:\\\\Program Files (x86)\\\\VMware\\\\VMware Workstation\\\\'\n hyperv = 'C:\\\\Program Files\\\\Hyper-V\\\\'\n virtualbox = 'C:\\\\Program Files\\\\Oracle\\\\VirtualBox\\\\'\n return Dir.exists?(vmware) ? :vmware_desktop\n : Dir.exists?(hyperv) ? :hyperv\n : Dir.exists?(virtualbox) ? :virtualbox\n : nil\n end\n\n return :virtualbox\nend",
"def provider\n use_provider('null') unless defined? @provider\n @provider\n end",
"def default_provider\n return nil unless node && node['platform_family']\n Chef::Provider::Dropbox.const_get(node['platform_family'].split('_')\n .map(&:capitalize).join)\n end",
"def provider\n conf['provider'] || 'defaults'\n end",
"def get_service_provider(provider)\n case provider.class.to_s\n when 'Fixnum' then provider_by_id(provider)\n when 'String' then (provider.to_i > 0 ? provider_by_id(provider) : provider_by_name(provider))\n when 'Symbol' then provider_by_name(provider)\n when 'NilClass' then nil\n else\n provider\n end\n end",
"def cloud_provider\n self.cloud? ? self.automatic[:cloud][:provider] : nil \n end",
"def provider_name\n self.dig_for_string(\"providerName\")\n end",
"def get_provider(provider)\n configuration.providers.find { |rp| rp.namespace.casecmp(provider) == 0 }\n end",
"def provider_name\n params[:provider] || provider_name_from_state || browser.providers.each_key.to_a.first\n end",
"def provider\n case fragement_type\n when TYPES[:ssh], TYPES[:https]\n parsed_uri.host\n when TYPES[:org_repo], TYPES[:repo]\n D2::Config.get('git', 'default_provider')\n when TYPES[:undetermined]\n raise UndeterminedError\n end\n end",
"def provider\n return @provider if defined? @provider\n Config.providers.each do |provider, config|\n if config[:exchanger_match] && matches?(config[:exchanger_match])\n return @provider = provider\n end\n end\n @provider = :default\n end",
"def LocateProvider(provider)\n devs = Locate(\"PROVIDER\", provider)\n Ops.greater_than(Builtins.size(devs), 0)\n end",
"def provider_name\n return @provider_name\n end",
"def detect_platform\n unless @use_metadata_service\n @log.info 'use_metadata_service is false; not detecting platform'\n return Platform::OTHER\n end\n\n begin\n open('http://' + METADATA_SERVICE_ADDR) do |f|\n if f.meta['metadata-flavor'] == 'Google'\n @log.info 'Detected GCE platform'\n return Platform::GCE\n end\n if f.meta['server'] == 'EC2ws'\n @log.info 'Detected EC2 platform'\n return Platform::EC2\n end\n end\n rescue StandardError => e\n @log.error 'Failed to access metadata service: ', error: e\n end\n\n @log.info 'Unable to determine platform'\n Platform::OTHER\n end",
"def provider_specifics\n @provider_specifics\n end",
"def built_in_providers\n OhMyEmbed::Providers.constants\n .select { |c| OhMyEmbed::Providers.const_get(c) < OhMyEmbed::Provider }\n end",
"def detect_platform\r\n\t\tprint_status(\"Attempting to automatically detect the platform\")\r\n\t\tres = send_serialized_request(\"osname.bin\")\r\n\r\n\t\tif (res.body =~ /(Linux|FreeBSD|Windows)/i)\r\n\t\t\tos = $1\r\n\t\t\tif (os =~ /Linux/i)\r\n\t\t\t\treturn 'linux'\r\n\t\t\telsif (os =~ /FreeBSD/i)\r\n\t\t\t\treturn 'linux'\r\n\t\t\telsif (os =~ /Windows/i)\r\n\t\t\t\treturn 'win'\r\n\t\t\tend\r\n\t\tend\r\n\t\tnil\r\n\tend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /poets/new GET /poets/new.xml | def new
@poet = Poet.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @poet }
end
end | [
"def new\n @petsitter = Petsitter.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @petsitter }\n end\n end",
"def new\n @pet = Pet.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pet }\n end\n end",
"def new\n @novel = Novel.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @novel }\n end\n end",
"def create\n @poet = Poet.new(params[:poet])\n\n respond_to do |format|\n if @poet.save\n flash[:notice] = 'Poet was successfully created.'\n format.html { redirect_to(@poet) }\n format.xml { render :xml => @poet, :status => :created, :location => @poet }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @poet.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @poet = Poet.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @poet }\n end\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => new_vurl }\n end\n end",
"def new\n @topping = Topping.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @topping }\n end\n end",
"def new\n @pet_type = PetType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pet_type }\n end\n end",
"def new\n @peep = Peep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @peep }\n end\n end",
"def new\n @prices = Prices.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prices }\n end\n end",
"def new\n @vet = Vet.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @vet }\n end\n end",
"def new\n @spot = Spot.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @spot }\n end\n end",
"def new\n @lookup_pettracer = LookupPettracer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @lookup_pettracer }\n end\n end",
"def new\n @pig = Pig.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pig }\n end\n end",
"def new\n @newstuff = Newstuff.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @newstuff }\n end\n end",
"def new\n @pulve = Pulve.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pulve }\n end\n end",
"def new\n @planet_feed = PlanetFeed.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @planet_feed }\n end\n end",
"def new\n @park = Park.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @park }\n end\n end",
"def new\n @price = Price.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @price }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /poets POST /poets.xml | def create
@poet = Poet.new(params[:poet])
respond_to do |format|
if @poet.save
flash[:notice] = 'Poet was successfully created.'
format.html { redirect_to(@poet) }
format.xml { render :xml => @poet, :status => :created, :location => @poet }
else
format.html { render :action => "new" }
format.xml { render :xml => @poet.errors, :status => :unprocessable_entity }
end
end
end | [
"def create\n @poet = Poet.new(params[:poet])\n\n respond_to do |format|\n if @poet.save\n format.html { redirect_to @poet, notice: 'Yay, new poet!' }\n format.json { render json: @poet, status: :created, location: @poet }\n else\n format.html { render action: \"new\" }\n format.json { render json: @poet.errors, status: :unprocessable_entity }\n end\n end\n end",
"def post_expense_xml(xml)\n #request header bekommt Content-type = xml\n header \"Content-Type\", \"text/xml\" \n #expense daten werden alsl xml per Post request an den Server gesendet\n post '/expenses', xml\n #es wird erwartet das dies erfolgreich war\n expect(last_response.status).to eq(200)\n\n parsed = Ox.load(last_response.body, mode: :hash)\n expect(parsed).to include('expense_id' => a_kind_of(Integer))\n #adds an id key to the expense hash, containing the id from the database, after an expense is succesfully stored\n expense.merge('id' => parsed['expense_id'])\nend",
"def post endpoint, data\n do_request :post, endpoint, data\n end",
"def create\n @poet = Poet.new(params[:poet])\n\n respond_to do |format|\n if @poet.save\n format.html { redirect_to slam_path(params[:slam]), notice: 'Poet was successfully created.' }\n format.json { render json: @poet, status: :created, location: @poet }\n else\n format.html { render action: \"new\" }\n format.json { render json: @poet.errors, status: :unprocessable_entity }\n end\n end\n end",
"def save\n # post to API\n url = 'https://petapi-1.herokuapp.com/addPet'\n response = RestClient.post( url, { name: params[:name], type: params[:type], breed: params[:breed], location: params[:location], latitude: params[:latitude], longitude: params[:longitude] })\n\n # if we get an ok response, redirect to main list page\n if response.code <= 200\n # redirect to main page\n redirect_to '/'\n end\n end",
"def create\n @petsitter = Petsitter.new(params[:petsitter])\n\n respond_to do |format|\n if @petsitter.save\n format.html { redirect_to(@petsitter, :notice => 'Petsitter was successfully created.') }\n format.xml { render :xml => @petsitter, :status => :created, :location => @petsitter }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @petsitter.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def post(url, request_xml)\n uri = URI(url)\n\n request = Net::HTTP::Post.new(uri)\n request.body = request_xml\n\n response = Net::HTTP.start(\n uri.hostname,\n uri.port,\n use_ssl: uri.scheme == 'https',\n # TODO MAKE THIS UNSUCK\n verify_mode: OpenSSL::SSL::VERIFY_NONE\n ) do |http|\n http.request(request)\n end\n\n response\n end",
"def post(method, params = {})\n url = make_url method, params\n query = url.query\n url.query = nil\n\n req = Net::HTTP::Post.new url.path\n req.body = query\n req.content_type = 'application/x-www-form-urlencoded'\n\n res = Net::HTTP.start url.host, url.port do |http|\n http.request req\n end\n\n xml = Nokogiri::XML(res.body, nil, nil, 0)\n\n check_error xml\n\n parse_response xml\n rescue SystemCallError, SocketError, Timeout::Error, IOError,\n Nokogiri::XML::SyntaxError => e\n raise CommunicationError.new(e)\n rescue Net::HTTPError => e\n xml = Nokogiri::XML(e.res.body) { |cfg| cfg.strict }\n check_error xml\n raise CommunicationError.new(e)\n end",
"def create\n @pet = Pet.new(params[:pet])\n\n respond_to do |format|\n if @pet.save\n flash[:notice] = 'Pet was successfully added to system.'\n format.html { redirect_to(@pet) }\n format.xml { render :xml => @pet, :lost => :created, :location => @pet }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @pet.errors, :lost => :unprocessable_entity }\n end\n end\n end",
"def post_spoonacular\n # %encode ingredients to url\n encoded_ingr = URI.escape(@translated_recipe[:ingredients_list])\n # post call block :\n url = URI(\"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/parseIngredients?includeNutrition=true\")\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Post.new(url)\n request[\"content-type\"] = \"application/x-www-form-urlencoded\"\n request[\"x-rapidapi-key\"] = ENV[\"X_RAPIDAPI_KEY\"]\n request[\"x-rapidapi-host\"] = \"spoonacular-recipe-food-nutrition-v1.p.rapidapi.com\"\n # body of the call with ingredients and servings\n request.body = \"ingredientList=#{encoded_ingr}&#{@recipe_hash[:servings]}\"\n # response\n response = http.request(request)\n end",
"def post *args\n make_request :post, *args\n end",
"def post_expense_xml(expense, pay, amo, dat) #the best \n=======\n\n# post the expense as xml data\ndef post_expense_xml(expense)\n>>>>>>> b4463bcd9c85b8f14eeaed6c61d804930b145295\n #request header bekommt Content-type = xml\n header \"Content-Type\", \"text/xml\" \n #expense daten werden alsl xml per Post request an den Server gesendet\n xml = create_xml_single(expense)\n post '/expenses', xml\n #es wird erwartet das dies erfolgreich war\n \n expect(last_response.status).to eq(200)\n\n<<<<<<< HEAD\n parsed = # #a hash out of the (last_response.body)(in xml). But how to do this?\n expect(parsed).to include('expense_id' => a_kind_of(Integer))\n #adds an id key to the expense hash, containing the id from the database\n xml_expense_hash = #a hash out of the expense_xml_data generated with Ox. goal: this is not needed, becuse the expense_hash is there already.\n #adds an id key to the expense hash, containing the id from the database\n xml_hash.merge('id' => parsed['expense_id'])\n=======\n parsed = Ox.load(last_response.body, mode: :hash)\n expect(parsed).to include('expense_id' => anything)\n #adds an id key to the expense hash, containing the id from the database, after an expense is succesfully stored\n expense.merge('id' => parsed['expense_id'])\n\n>>>>>>> b4463bcd9c85b8f14eeaed6c61d804930b145295\nend",
"def post(path, params={}); make_request(:post, host, port, path, params); end",
"def create\n @peep = Peep.new(params[:peep])\n\n respond_to do |format|\n if @peep.save\n format.html { redirect_to(@peep, :notice => 'Peep was successfully created.') }\n format.xml { render :xml => @peep, :status => :created, :location => @peep }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @peep.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def do_POST(request, response)\n content_type, params = parse_content_type(request)\n\n # In SOAP 1.1, the action is sent in the SOAPAction header. In\n # SOAP 1.2, it's sent as a parameter to the Content-Type header.\n # Savon sends SOAPAction (even though it's SOAP 1.2), so we need to\n # accept it. That's okay, because it appears Epic InterConnect\n # (WCF) also will accept the SOAP 1.1 method.\n namespaced_action_name = request['SOAPAction'] || params['action']\n action_name = namespaced_action_name.gsub('\"', '').split(':')[-1]\n\n action = @actions[action_name]\n\n if not action then\n # Unknown action; send back a 400\n response.status = 400\n\n else\n body = Nokogiri::XML(request.body)\n @received << body if @keep_received\n\n xml, status = action.call(body, response)\n\n response.status = status\n response['Content-Type'] = 'text/xml'\n response.body = xml\n end\n end",
"def create\n @tiket = Tiket.new(params[:tiket])\n\n respond_to do |format|\n if @tiket.save\n flash[:notice] = 'Tiket was successfully created.'\n format.html { redirect_to(@tiket) }\n format.xml { render :xml => @tiket, :status => :created, :location => @tiket }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @tiket.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @novel = Novel.new(params[:novel])\n upload\n respond_to do |format|\n if @novel.save\n flash[:notice] = 'Novel was successfully created.'\n format.html { redirect_to(@novel) }\n format.xml { render :xml => @novel, :status => :created, :location => @novel }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @novel.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @pet = @species.pets.build(params[:pet])\n\n respond_to do |format|\n if @pet.save\n flash[:notice] = 'Pet was successfully created.'\n format.html { redirect_to([:admin, @pet]) }\n format.xml { render :xml => @pet, :status => :created, :location => @pet }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @pet.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @vet = Vet.new(params[:vet])\n\n respond_to do |format|\n if @vet.save\n format.html { redirect_to(@vet, :notice => 'Vet was successfully created.') }\n format.xml { render :xml => @vet, :status => :created, :location => @vet }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @vet.errors, :status => :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PUT /poets/1 PUT /poets/1.xml | def update
@poet = Poet.find(params[:id])
respond_to do |format|
if @poet.update_attributes(params[:poet])
flash[:notice] = 'Poet was successfully updated.'
format.html { redirect_to(@poet) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @poet.errors, :status => :unprocessable_entity }
end
end
end | [
"def update opts = {}\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'text/xml'\n post 'update', opts\n end",
"def update opts = {}\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'text/xml'\n post opts.fetch(:path, update_path), opts\n end",
"def update\n @poet = Poet.find(params[:id])\n\n respond_to do |format|\n if @poet.update_attributes(params[:poet])\n format.html { redirect_to @poet, notice: 'Poet was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @poet.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @spot = Spot.find(params[:id])\n @tags = @spot.items\n\n respond_to do |format|\n if @spot.update_attributes(params[:spot])\n format.html { redirect_to(spots_url, :notice => 'Spot was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @spot.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @petsitter = Petsitter.find(params[:id])\n\n respond_to do |format|\n if @petsitter.update_attributes(params[:petsitter])\n format.html { redirect_to(@petsitter, :notice => 'Petsitter was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @petsitter.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def put *args\n make_request :put, *args\n end",
"def update\n @spot = Spot.find(params[:id])\n\n respond_to do |format|\n if @spot.update_attributes(params[:spot])\n flash[:notice] = 'Spot was successfully updated.'\n format.html { redirect_to(@spot) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @spot.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def put\n request_method('PUT')\n end",
"def update\n @vet = Vet.find(params[:id])\n\n respond_to do |format|\n if @vet.update_attributes(params[:vet])\n format.html { redirect_to(@vet, :notice => 'Vet was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @vet.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @novel = Novel.find(params[:id])\n\n respond_to do |format|\n if @novel.update_attributes(params[:novel])\n flash[:notice] = 'Novel was successfully updated.'\n format.html { redirect_to(@novel) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @novel.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @topping = Topping.find(params[:id])\n\n respond_to do |format|\n if @topping.update_attributes(params[:topping])\n flash[:notice] = 'Topping was successfully updated.'\n format.html { redirect_to(@topping) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @topping.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def test_put_existing\n request = Http::Request.new('PUT', '/file1', {}, 'bar')\n\n response = self.request(request)\n\n assert_equal(204, response.status)\n\n assert_equal(\n 'bar',\n @server.tree.node_for_path('file1').get\n )\n\n assert_equal(\n {\n 'X-Sabre-Version' => [Version::VERSION],\n 'Content-Length' => ['0'],\n 'ETag' => [\"\\\"#{Digest::MD5.hexdigest('bar')}\\\"\"]\n },\n response.headers\n )\n end",
"def put(path, params={}); make_request(:put, host, port, path, params); end",
"def update_price\n @kit = Kit.find(params[:id])\n @kit.update_attribute(\"price\", params[:value])\n respond_to do |format|\n format.xml { render :xml => @kit }\n end\n end",
"def update\n respond_to do |format|\n # spot = HTTParty.get(\"http://localhost:3000/spots/#{params[:id]}\" )\n if @spot.update(spot_params)\n HTTParty.patch(\"http://localhost:3000/spots/#{params[:id]}?name=#{spot_params[:name]}&lat=#{spot_params[:lat]}&lon=#{spot_params[:lon]}&description=#{spot_params[:description]}&features=#{spot_params[:features]}&spot_type=#{spot_params[:spot_type]}&img=#{spot_params[:img]}\")\n @spot.spot_photos.attach(params[:spot][:spot_photos])\n format.html { redirect_to @spot, notice: 'Spot was successfully updated.' }\n format.json { render :show, status: :ok, location: @spot }\n else\n format.html { render :edit }\n format.json { render json: @spot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @peep = Peep.find(params[:id])\n\n respond_to do |format|\n if @peep.update_attributes(params[:peep])\n format.html { redirect_to(@peep, :notice => 'Peep was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @peep.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @planet = @universe.planets.find(params[:id])\n\n respond_to do |format|\n if @planet.update_attributes(params[:planet])\n format.html { redirect_to([@universe, @planet], :notice => 'Planet was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @planet.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @tiket = Tiket.find(params[:id])\n\n respond_to do |format|\n if @tiket.update_attributes(params[:tiket])\n flash[:notice] = 'Tiket was successfully updated.'\n format.html { redirect_to(@tiket) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @tiket.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n update_resource(@tomato)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /poets/1 DELETE /poets/1.xml | def destroy
@poet = Poet.find(params[:id])
@poet.destroy
respond_to do |format|
format.html { redirect_to(poets_url) }
format.xml { head :ok }
end
end | [
"def destroy\n @poet = Poet.find(params[:id])\n @poet.destroy\n\n respond_to do |format|\n format.html { redirect_to poets_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n #@pet = Pet.find(params[:id])\n @pet.destroy\n\n respond_to do |format|\n format.html { redirect_to(pets_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @pet = Pet.find(params[:id])\n @pet.destroy\n\n respond_to do |format|\n format.html { redirect_to(pets_url) }\n format.xml { head :ok }\n end\n end",
"def pet_delete(pet)\n @db.delete(\"pets\", pet[\"id\"])\n end",
"def destroy\n @peep = Peep.find(params[:id])\n @peep.destroy\n\n respond_to do |format|\n format.html { redirect_to(peeps_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @tiket = Tiket.find(params[:id])\n @tiket.destroy\n\n respond_to do |format|\n format.html { redirect_to(tikets_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @diet = Diet.find(params[:id])\n @diet.destroy\n\n respond_to do |format|\n format.html { redirect_to(diets_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @poem = Poem.find(params[:id])\n @poem.destroy\n\n respond_to do |format|\n format.html { redirect_to(poems_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @pig = Pig.find(params[:id])\n @pig.destroy\n\n respond_to do |format|\n format.html { redirect_to(pigs_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @novel = Novel.find(params[:id])\n @novel.destroy\n\n respond_to do |format|\n format.html { redirect_to(novels_url) }\n format.xml { head :ok }\n end\n end",
"def DeletePeep(peepid)\n RemoveAPeep(peepid)\n end",
"def destroy\n @vet = Vet.find(params[:id])\n @vet.destroy\n\n respond_to do |format|\n format.html { redirect_to(vets_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @prd_etc = PrdEtc.find(params[:id])\n @prd_etc.destroy\n\n respond_to do |format|\n format.html { redirect_to(prd_etcs_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @ppos = Ppos.find(params[:id])\n @ppos.destroy\n\n respond_to do |format|\n format.html { redirect_to(ppos_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @petsitter = Petsitter.find(params[:id])\n @petsitter.destroy\n\n respond_to do |format|\n format.html { redirect_to(petsitters_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @pdig = Pdig.find(params[:id])\n @pdig.destroy\n\n respond_to do |format|\n format.html { redirect_to(pdigs_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @orange = Orange.find(params[:id])\n @orange.destroy\n\n respond_to do |format|\n format.html { redirect_to(oranges_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @transaction_xml = Transaction::Xml.find(params[:id])\n @transaction_xml.destroy\n\n respond_to do |format|\n format.html { redirect_to(transaction_xmls_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @vip = Vip.find(params[:id])\n @vip.update_attributes(:be_delete=>1)\n\n respond_to do |format|\n format.html { redirect_to(vips_url) }\n format.xml { head :ok }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns list of files described in metainfo | def get_files_list
@meta_info.files
end | [
"def files\n return [] unless meta?\n filename = meta['path'] + '/' + meta['filename']\n [\n Inch::Utils::CodeLocation.new('', filename, meta['lineno'])\n ]\n end",
"def files\n @mets.xpath(\"/mets:mets/mets:fileSec/mets:fileGrp[@USE='masters']/mets:file\").map do |f|\n file_info(f)\n end\n end",
"def files\n array = []\n @list.each do |k,v|\n array += v.filename\n end\n array\n end",
"def meta_files(file)\n ret = []\n folders = folder_categories file\n folders.each_with_index do |folder, index|\n f = \"#{folders.take(index+1).join('/')}/#{folder}.txt\"\n ret << f if File.exists? \"#{@dir}/images/#{f}\"\n end\n ret\n end",
"def files_list\n return FileAdapter.files_list(package_location, package_name)\n end",
"def meta_file(file)\n ret = []\n ret << [\"#{file.split('.')[0]}.txt\"] if File.exists? \"#{@dir}/images/#{file.split('.')[0]}.txt\"\n ret\n end",
"def files_on_remote\n metadata = @storage.send(:connection).search(@remote_path, @package.trigger)\n metadata.map {|entry| File.basename(entry['path']) }.sort\n end",
"def metadata_files\n return @metadata_files unless @metadata_files.nil?\n @metadata_files = MetadataFile.all\n @existing_files, @new_files = [], []\n @metadata_files.each do |f|\n if f.cached?\n @existing_files << f\n else\n @new_files << f\n end\n end\n end",
"def files\n [@nuspec_file, @changelog_file, @readme_file]\n end",
"def get_file_list(filepath)\n Dir.entries(filepath)\nend",
"def list_files(command)\n command = create_spec(command)\n return command.load_digest[\"files\"]\n end",
"def files\n entries = []\n Dir.entries(@dir_path).each do |e|\n entries.push e if File.file? \"#{@dir_path}/#{e}\"\n end\n entries\n end",
"def files\n if File.directory?(@package)\n Dir.glob(File.join(File.join(File.expand_path(@package), '**'), '*')).reject {|f|\n File.directory?(f) }.map {|f| f.sub(/^#{File.expand_path(@package)}\\/?/, '') }\n else\n entries = []\n Zip::File::foreach(@package) do |entry|\n entries << entry.name unless entry.name[-1..-1] == '/'\n end\n entries\n end\n end",
"def find_metadata(*args)\n results = []\n @filesets.each do |volid, fileset|\n results += fileset.find_metadata(*args)\n end\n return results\n end",
"def get_files\n files = []\n files.push @version_file if @version_file\n files.push components.flat_map(&:files)\n files.flatten.uniq\n end",
"def tag_manifested_files\n tagmanifest_files.inject([]) do |acc, mf|\n files = File.open(mf) { |io|\n io.readlines.map do |line|\n _digest, path = line.chomp.split(/\\s+/, 2)\n path\n end\n }\n (acc + files).uniq\n end\n end",
"def files\n manifest.inject([]) do |memo, item|\n memo << full_path(item.first)\n end\n end",
"def metadata_paths\n @metadata_paths ||= bag_paths.map do |b|\n Dir.glob(\"#{b}/**/*\").select { |f| File.file?(f) && f.ends_with?(metadata_file_name) }\n end.flatten.compact\n end",
"def file_list\n @file_list\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parse metainfo from given torrent file | def parse_meta_info(torrent_file)
MetaInfo.new(Bencode::Decoder.decode_file(torrent_file))
end | [
"def getMp4Info(file)\n def get_val(string)\n string.split(\":\")[1]\n end\n\n ret = {}\n tagstrings = `AtomicParsley #{file} -t | grep -Pi '(art|alb|nam)'`.split(\"\\n\")\n ret[:artist] = get_val(tagstrings.grep(/ART\" contains/i)[0])\n ret[:title] = get_val(tagstrings.grep(/nam\" contains/i)[0])\n\n tmp = tagstrings.grep(/alb\" contains/i)[0]\n ret[:album] = (tmp.nil?) ? $default_album : tmp.split(\":\")[1]\n if ret[:artist].nil? || ret[:album].nil? || ret[:title].nil?\n raise \"Error parsing m4a tags - is it possible that AtomicParsley output format has changed?\"\n end\n ret\nend",
"def read_meta(node)\n t = decompress_revision(node)\n return {} unless has_metadata?(t)\n \n mt = t[metadata_start..(metadata_end(t) - 1)]\n mt.split(\"\\n\").inject({}) do |hash, line|\n k, v = line.split(\": \", 2)\n hash[k] = v\n hash\n end\n end",
"def parse_file(filename); end",
"def parse_info(info = '')\n rv = { :parts => [] }\n info.each_line do |line|\n line.chomp!\n case line\n when /^(des|type|filename)\\s+(.+)$/\n rv[$1.to_sym] = $2\n when /^compressed\\s+([01])$/\n rv[:compressed] = ($1 == '1')\n when /^(chunks|size)\\s+(\\d+)$/\n rv[$1.to_sym] = $2.to_i\n when /^part\\s+(\\d+)\\s+bytes=(\\d+)\\s+md5=(.+)\\s+paths:\\s+(.+)$/\n rv[:parts][$1.to_i] = {\n :bytes => $2.to_i,\n :md5 => $3.downcase,\n :paths => $4.split(/\\s*,\\s*/),\n }\n end\n end\n\n rv\n end",
"def parse_info(info)\n lines = info.split(\"\\n\")\n info_hash = { package: {} }\n lines.each do |line|\n RPM_INFO_KEY.each do |symbol, query|\n parse_regex = Regexp.new(\"^(#{symbol})+\\s*:{1}\\s{1}(.*)$\")\n parts = parse_regex.match(line)\n info_hash[:package][symbol] = parts[2] if parts\n end\n end\n info_hash\n end",
"def parseMetaData(path)\n #Gitchefsync.logger.debug \"Parsing metadata: #{path}\"\n if !File.exists?(File.join(path, \"metadata.rb\"))\n raise NoMetaDataError\n end\n contents = \"\"\n begin\n file = File.new(File.join(path, \"metadata.rb\"), \"r\")\n\n contents = file.read\n version = attr_val(contents,\"version\")\n name = attr_val(contents,\"name\")\n\n if name.nil?\n Gitchefsync.logger.warn \"event_id=parse_meta_err_name:msg=cannot be resolved, deferring to directory name #{path}\"\n name = File.basename path\n end\n #parse maintainer information\n maintainer = attr_val(contents,\"maintainer\")\n email = attr_val(contents,\"maintainer_email\")\n\n #puts \"matched:#{name}:#{version}\"\n return Cookbook.new(name, version,maintainer,email)\n rescue Exception => e\n puts e.backtrace\n Gitchefsync.logger.error \"#{e.backtrace}\"\n raise KnifeError, \"Unable to parse data: file=#{path}/metadata.rb #{contents}\"\n ensure\n file.close unless file.nil?\n end\n end",
"def set_meta_info(torrent_file_data, force_private = true)\n begin\n meta_info = parse_torrent_file(torrent_file_data, logger) # parse and check if meta-info is valid\n logger.debug ':-) torrent file is valid' if logger\n rescue InvalidTorrentError => e\n logger.debug \":-o torrent parsing error: #{e.message}\" if logger\n valid? # check if other errors in the model\n add_error :torrent_file, 'invalid'\n return false\n end\n meta_info[INFO][PRIVATE] = PRIVATE_FLAG if force_private\n populate_torrent meta_info\n true\n end",
"def parse_metadata(file)\n file_name = File.basename(file)\n puts \"\\n#{Time.now.strftime('%T')} Parsing #{file_name}\" unless Rails.env.test?\n attrs = parser.new(file).attributes\n\n if attrs.blank?\n errors << \"Failed to parse file: #{file_name}\"\n elsif record_exists?(attrs)\n # Don't re-import the record if this record already\n # exists in fedora.\n skipped_imports << file_name\n else\n create_record(attrs.merge(metadata_file: file, visibility: visibility, admin_set: admin_set))\n successful_imports << file_name\n end\n rescue => e\n errors << \"#{file_name}: #{e}\"\n end",
"def getMp3Info(file)\n ret = {}\n tagstrings = `eyeD3 --no-color #{file} | grep -P '(title|artist|album)' | sed 's/\\\\t\\\\+/\\\\n/'`.split(\"\\n\")\n tagstrings.each do |line|\n key_val = line.split(\":\")\n ret[(key_val[0].strip.to_sym)] = key_val[1]\n end\n if ret[:artist].nil? || ret[:album].nil? || ret[:title].nil?\n raise \"Error parsing id3 tags on mp3 file - is it possible that eyeD3 output format has changed?\"\n end\n ret\nend",
"def parse_file_data(metadata_text, content)\n metadata = Hash.new\n required_data = [\"date\", \"summary\", \"title\"]\n required_data << \"content\" if content.empty?\n metadata_text.lines.each do |mdata_line|\n # remove surrounding whitespace. If line is empty or invalid format, skip\n mdata_line.strip!\n next if mdata_line.empty?\n raise Starman::InvalidMetadata.new(@digest_name, mdata_line) unless is_metadata?(mdata_line)\n #delimit on first colon \n key, value = mdata_line.split(/\\s*:\\s*/, 2)\n case key.downcase\n when \"date\"\n # TODO date format localization\n raise Starman::DateError.new(@digest_name) if value.strip.empty?\n begin\n metadata[\"date\"] = DateTime.strptime(value, '%m/%d/%Y') \n rescue ArgumentError\n raise Starman::DateError.new(@digest_name)\n end\n required_data.delete(\"date\")\n when \"summary\"\n if !value.strip.empty?\n metadata[\"summary\"] = value[0..100].strip\n required_data.delete(\"summary\")\n end\n when \"title\"\n if !value.strip.empty?\n metadata[\"title\"] = value[0..40]\n required_data.delete(\"title\")\n end\n end #end case\n end # end do\n\n metadata, content = populate_missing_fields(required_data, metadata, content) unless required_data.empty?\n\n return metadata, content\n end",
"def parse_metadata(io)\n # Simon Chiang wrote this\n current_pos = io.pos\n io.rewind\n\n metadata = {}\n line = io.readline\n unless line =~ /MIME-Version: (\\d+\\.\\d+) \\(Generated by Mascot version (\\d+\\.\\d+)\\)/\n raise \"could not parse mime-version or mascot-version: #{line}\"\n end\n metadata[:mime_version] = $1\n metadata[:mascot_version] = $2\n\n line = io.readline\n unless line =~ /Content-Type: (.*?); boundary=(.*)/\n raise \"could not parse content-type: #{line}\"\n end\n metadata[:content_type] = $1\n metadata[:boundary] = $2\n\n io.pos = current_pos\n metadata\n end",
"def extract_metadata_for_video url\n mfile = metadata_file_for(url)\n unless File.file? mfile\n\n # self << url\n # self << %w[ skip-download write-info-json ignore-errors ]\n # self << { output: mfile.gsub(/\\.info\\.json$/, '') }\n # self.run\n\n # Run directly:\n command = \"#{url} --skip-download --write-info-json --ignore-errors\"\n command += \" -o '#{mfile.gsub(/\\.info\\.json$/, '')}'\"\n delegator.run command\n end\n JSON.parse File.read(mfile) rescue nil\n end",
"def parse_metadata(io)\n current_pos = io.pos\n io.rewind\n \n metadata = {}\n line = io.readline\n unless line =~ /MIME-Version: (\\d+\\.\\d+) \\(Generated by Mascot version (\\d+\\.\\d+)\\)/\n raise \"could not parse mime-version or mascot-version: #{line}\"\n end\n metadata[:mime_version] = $1\n metadata[:mascot_version] = $2\n \n line = io.readline\n unless line =~ /Content-Type: (.*?); boundary=(.*)/\n raise \"could not parse content-type: #{line}\"\n end\n metadata[:content_type] = $1\n metadata[:boundary] = $2\n \n io.pos = current_pos\n metadata\n end",
"def extract_torrent(unparsed_data)\n hsh = Hash.new\n\n hsh[:name] = unparsed_data.css('td')[1].text\n hsh[:magnet_url] = unparsed_data.css('td').css('a')[1].attr('href')\n hsh[:url] = unparsed_data.css('td').css('a').attr('href')\n hsh[:size] = unparsed_data.css('td')[3].text\n hsh[:seeders] = unparsed_data.css('td')[4].text.to_i\n hsh[:leeches] = unparsed_data.css('td')[5].text.to_i\n\n hsh[:tracker] = assigned_site.name\n\n Torrent.new hsh\n end",
"def read_meta_info\n if meta_info_file_pathname.exist?\n inode, bytes_read = meta_info_file_pathname.read.strip.split(':').map(&:to_i)\n {\n inode: inode,\n bytes_read: bytes_read\n }\n else\n {\n inode: nil,\n bytes_read: 0\n }\n end\n end",
"def _parse_info_file\n _read_info_file\n _check_project_name\n _set_project_version\n _set_project_type\n end",
"def parse_track(url)\n data = fetch_data(url)\n track = data['track'] # all the fun bits are in 'track'\n # pp data['track']['artists'].first['name']\n artist = track['artists'].first['name']\n album = track['album']['name']\n released = track['album']['released']\n length = (track['length'] / 60).round # Get ca. length of song\n name = track['name']\n s = Song.new(artist, album, name, length, released) # Fill the struct and return the goods!\n return s \n end",
"def parse_from_file filename\n parse File.open(filename)\n end",
"def set_meta_info(torrent_data, force_private = false)\n begin\n meta_info = parse_torrent_file(torrent_data, logger) # parse and check if meta-info is valid\n logger.debug ':-) torrent file is valid'\n rescue InvalidTorrentError => e\n logger.debug \":-o torrent parsing error: #{e.message}\"\n valid? # check other errors in the model\n add_error :torrent_file, 'invalid'\n return false\n end\n meta_info[INFO][PRIVATE] = PRIVATE_FLAG if force_private\n populate_meta_info meta_info\n true\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
lambda for RequestHandler object | def request_handler
-> { run(@scheduler.request_queue, nil, RequestHandler.new) }
end | [
"def handler(&block)\n set_request_handler(block)\n end",
"def call(request, _next); end",
"def handler_executed(handler); end",
"def request_handler(request_handler)\n @search.request_handler = request_handler\n end",
"def on_request &block\n @on_request << block\n end",
"def handler_method; end",
"def on_request &b\n @request_proc = b\n self\n end",
"def on_request( &block )\n @on_request = block\n end",
"def register_request_callback; end",
"def call(request); end",
"def handler_executed(handler)\n end",
"def on_next_request(&blk); end",
"def on_next_request(&blk)\n _on_next_request << blk\n end",
"def on_global_request(type, &block); end",
"def handler\n @@handler\n end",
"def after_request(&block); end",
"def handle_request( request, &block )\n\t\tif block\n\t\t\treturn block.call( request )\n\t\telse\n\t\t\treturn request.response\n\t\tend\n\tend",
"def call(request, _next)\n @block ? @block.call(request, _next) : _next.call\n end",
"def default_handler\n Proc.new { |response| json.parse(response.body) }\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
lambda for FileLoader and Scheduler objects | def file_loader
-> { run(@incoming_queue, nil, @file_loader, @scheduler) }
end | [
"def _loading\n Threaded.begin_execution(LOAD)\n yield\n ensure\n Threaded.exit_execution(LOAD)\n end",
"def load_files\n end",
"def file_started(file); end",
"def seed_loader=(_arg0); end",
"def listener_callback(callback)\n Proc.new do |modified, added, _|\n ((modified || []) + (added || [])).each { |file| callback.call(file) }\n end\n end",
"def load(options={})\r\n @before_load_proc = options[:before_load]\r\n @after_load_proc = options[:after_load]\r\n files = @file_provider.call \r\n @num_files = files.size\r\n @files_added = []\r\n @files_changed = []\r\n @files_removed = []\r\n @change_detector.check_files(files)\r\n @progress_monitor = ProgressMonitor.new(options[:on_progress], @files_added + @files_changed)\r\n @files_added.each {|f| file_added(f)}\r\n @files_changed.each {|f| file_changed(f)}\r\n @files_removed.each {|f| file_removed(f)}\r\n @resolver.resolve_model(@model)\r\n end",
"def set_load_proc(&proc)\n bean_factory.bean_file_loader.set_load_proc(&proc)\n end",
"def set_get_files(&block)\n @get_files_proc = block\n end",
"def file(*args, &block)\n Rake::FileTask.define_task(*args, &block)\nend",
"def load_and_process_by_date(files, date_spec, &block)\n print_usage unless date_spec and !files.empty?\n\n date_range = date_range_for_argument(date_spec)\n pings_by_date = load_filtered_pings_by_date(files)\n\n date_range.each do |date|\n block.call(date, pings_by_date[date.date_str])\n end\nend",
"def lambda; end",
"def loader\n ::Impressbox::Objects::MassFileLoader.new(\n namespace,\n dir\n )\n end",
"def loading\n use\n yield\n ensure\n unuse\n end",
"def initialize(loader)\n @loader = loader\n end",
"def file_watcher=(_arg0); end",
"def loader\n Loader.new(self)\n end",
"def private_loader\n self\n end",
"def process_files\n Proc.new do\n completed_files = files_queue.select { |k,v| Time.now > v + file_wait_time }\n completed_files.each do |file_path, time|\n CreateOcrRequestJob.perform_later(file_path: file_path)\n files_queue.delete(file_path)\n end\n end\n end",
"def call_actions_with file\n actions.each { |action| action.call file } \n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
run lambda block in a separate Thread | def run_lambda_in_thread(lambda_)
Thread.new { lambda_.call }
end | [
"def execute_in_main_thread(&block)\n EventMachine.schedule(&block)\n end",
"def run(&block); end",
"def lambda(&block)\n ### *** TODO *** ###\n block # dummy\n end",
"def initialize(&blk)\n self.future_thread = Thread.new(&blk)\n end",
"def runInReactorThread(&block)\n @reactor.scheduleTimer(0, [:runproc, block], false, true)\n end",
"def task_run(&block) \n task(&block).start\n end",
"def run_concurrently(&block)\n if config.blocking\n block.call\n else\n super\n end\n end",
"def async_executor; end",
"def runblock\r\n\t\t\t@b.call\r\n\t\tend",
"def run_proc_or_lambda_2(blockblock)\n puts \"station 1 of 3\"\n blockblock.call\n puts \"station 3 of 3\"\nend",
"def lambda; end",
"def then_on(executor, *args, &task); end",
"def async(&payload)\n worker(payload) { }\n end",
"def task_run_later(&block) \n task_later(&block).start\n end",
"def run(&block)\n task('run').tap do |t|\n t.enhance &block if block\n end\n end",
"def run\n Thread.new do\n task\n end\n end",
"def another_lambda\n\tl = lambda {return}\n\tl.call\n\tputs \"After Lambda\"\nend",
"def schedule(&block)\n # Schedule the block to run on a worker thread, and put ourselves to sleep.\n daemon.schedule_work(:callback,\n :hash => user.id,\n :user_id => user.id,\n :block => block,\n :thread => Thread.current)\n\n # Put ourselves to sleep. The worker will call Thread.run to wake us back up.\n sleep\n end",
"def lambda_main(event:, context:)\n _ = context\n process_event(event)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
File.basename path, '.' Basename with ext removed File.basename('/a/b/c.txt', '.') => "c" | def basename_no_ext path
File.basename path, '.*'
end | [
"def basename filename, drop_ext = nil\n if drop_ext\n ::File.basename filename, (drop_ext == true ? (extname filename) : drop_ext)\n else\n ::File.basename filename\n end\n end",
"def get_file_name_without_ext(full_name)\n return File.basename(full_name, File.extname(full_name))\n rescue Exception => exc\n puts exc\n return full_name\n end",
"def basename(file)\n File.basename(file, \".*\")\n end",
"def basename_without_ext\n if not @basename_without_ext\n @basename_without_ext = File.basename(path, '.*')\n if not @is_default_language\n @basename_without_ext ['.' + @language] = ''\n end\n end\n @basename_without_ext\n end",
"def basename\n File.basename(path)\n end",
"def file_name_from_path(path)\n path.split(\"/\")[-1]\n end",
"def basename\n File.basename(source_path, File.extname(source_path))\n end",
"def basename( path )\r\n File.basename( path )\r\n end",
"def chop_basename(path)\n base = File.basename(path)\n if /\\A#{SEPARATOR_PAT}?\\z/o =~ base\n return nil\n else\n return path[0, path.rindex(base)], base\n end\n end",
"def filename_without_extension\n filename.include?('.') ? filename.split('.')[0..-2].join('.') : filename\n end",
"def name(with_extension=true)\n ::File.basename path, (with_extension ? \"\" : \".#{extension}\")\n end",
"def chop_basename(path)\n base = File.basename(path)\n if /\\A#{SEPARATOR_PAT}?\\z/ =~ base\n return nil\n else\n return path[0, path.rindex(base)], base\n end\n end",
"def main_name(path)\n File.basename(path).sub(/\\.[^\\.]+$/,'')\n end",
"def chop_basename(path)\n base = File.basename(path)\n if /\\A#{SEPARATOR_PAT}?\\z/o =~ base\n return nil\n else\n return path[0, path.rindex(base)], base\n end\n end",
"def base\n File.basename @filename, extension_with_delimiter\n end",
"def getFileName( path )\n re = path.match(/(\\/?[[^\\/]+\\/]+)?\\/(\\w*)(\\.\\w+$)?/)\n if re.nil?\n # No match, the file path must be the name as well. Try and remove\n # a file extension, if one is present\n if File.extname( path ).empty?\n # No file extension, file path IS the name\n return path\n else\n extMatch = path.match(/(\\w+)\\./)\n if extMatch.nil?\n raise \"Failed to find file name of #{path}. Detected file extension, but could not parse\"\n else\n # Return the content of the first capture (the file name, with extension removed)\n return extMatch.captures[ 0 ]\n end\n end\n else\n # We matched, return the file name (2nd capture, array[1])\n return re.captures[ 1 ]\n end\nend",
"def file_suffix\n file_name.split('.').last \n end",
"def base_part_of(file_name)\n name = File.basename(file_name)\n name.gsub(/[^\\w._-]/, '')\n end",
"def basename(name)\n _,name = split_name(name)\n name\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve error details based on the id of the job. Useful to check its status. | def get_job_errors(job_id)
raise Auth0::InvalidParameter, 'Must specify a job id' if job_id.to_s.empty?
path = "#{jobs_path}/#{job_id}/errors"
get(path)
end | [
"def get_error_details_for_job(job_id)\n message = { session_id: @session_id, job_id: job_id }\n @soap_client.call(:get_error_details_for_job, message: message).body[:get_error_details_for_job_response][:return]\n end",
"def error\n return unless id.nil?\n @error ||= @response['message']\n end",
"def get_error_by_id(opts = {})\n get_error_by_id_with_http_info(opts)\n nil\n end",
"def load_job(id)\n begin \n Job.find(id)\n rescue Exception => e\n HoptoadNotifier.notify(\n :error_class => \"Invalid Job\", \n :error_message => \"Job Load Error: #{e.message}\", \n :request => { :params => id }\n )\n nil\n end\n end",
"def get_info_enqueued_job(job_id)\n job_info = OodCore::Job::Info.new(id: job_id.to_s, status: :completed)\n argv = ['qstat', '-r', '-xml', '-j', job_id.to_s]\n\n begin\n results = call(*argv)\n listener = QstatXmlJRListener.new\n REXML::Parsers::StreamParser.new(results, listener).parse\n\n job_hash = listener.parsed_job\n\n if job_hash[:id]\n update_job_hash_status!(job_hash)\n else\n job_hash[:id] = job_id\n job_hash[:status] = :completed\n end\n\n job_info = OodCore::Job::Info.new(**job_hash)\n rescue REXML::ParseException => e\n # If the error is something other than a job not being found by qstat re-raise the error\n unless results =~ /unknown_jobs/\n raise e, \"REXML::ParseException error and command '#{argv.join(' ')}' produced results that didn't contain string 'unknown_jobs'. ParseException: #{e.message}\"\n end\n rescue StandardError => e\n # Note that DRMAA is not guaranteed to be defined, hence the tests\n raise e unless ( can_use_drmaa? && e.is_a?(DRMAA::DRMAAInvalidJobError)) # raised when job is not found\n end\n\n job_info\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 get_job_errors(job_path, opts = {})\n url = job_url(job_path, '/live/err')\n headers = gen_headers(opts)\n\n attempt(opts[:attempts]) do\n method = opts[:head] ? :head : :get\n result = @client.send(method, url, nil, headers)\n raise unless result.is_a? HTTP::Message\n\n if result.status == 200\n raise unless result.headers['Content-Type'] ==\n 'application/x-json-stream; type=job-error'\n\n return true, result.headers if method == :head\n\n json_chunks = result.body.split(\"\\n\")\n errors = json_chunks.map { |i| JSON.parse(i) }\n\n return errors, result.headers\n end\n\n raise_error(result)\n end\n end",
"def job_error\n command = params[:command].to_sym\n message = params[:message]\n @project.send(\"#{command}_fail!\", nil, message)\n head :ok\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 get_job_status(job_id)\n api_get(:job, {'job_id' => job_id})\n end",
"def error(job, exception)\n res = ExportResult.where('job_key=?', key).take\n res.status = 1\n res.result = exception.message\n res.save\n end",
"def get_job_status id\n end",
"def get_work_errors\n work_id = params[:work]\n batch_id = params[:batch]\n query = \"select pg_ref_number, results from job_queue \"\n query = query << \" inner join pages on pg_page_id=page_id\"\n query = query << \" where job_status=? and batch_id=? and work_id=?\"\n sql = [query, 6,batch_id,work_id]\n page_errors = JobQueue.find_by_sql( sql )\n out = {}\n out[:work] = work_id\n out[:job] = BatchJob.find(batch_id).name\n out_errors = []\n page_errors.each do | err |\n out_errors << {:page=>err.pg_ref_number, :error=>err.results}\n end\n out[:errors] = out_errors\n render :json => out, :status => :ok\n end",
"def start_job(id)\n msg = TextMessage.find_by!(id: id, status: %i[queued request_failed])\n msg.started!\n msg\n rescue ActiveRecord::RecordNotFound, ActiveRecord::StaleObjectError => e\n Sidekiq.logger.error e.message\n Sidekiq.logger.error e.backtrace.join(\"\\n\")\n nil\n end",
"def get_job_status(job_id)\n raise ArgumentError, \"job_id is required\" unless job_id.present?\n\n request_body = ''\n xml = Builder::XmlMarkup.new(:target => request_body, :indent => 1)\n\n xml.instruct!\n xml.Envelope do\n xml.Body do\n xml.GetJobStatus do\n xml.JOB_ID job_id\n end\n end\n end\n\n doc = send_xml_api_request(request_body)\n status = result_dom(doc)['JOB_STATUS'] rescue nil\n desc = result_dom(doc)['JOB_DESCRIPTION'] rescue nil\n [status, desc]\n end",
"def work_errors\n batch_job = BatchJob.find(params[:batch])\n work = Work.find(params[:work])\n job_queues = JobQueue.where(batch_job: batch_job, status: JobStatus.failed, work: work)\n\n resp = {}\n resp[:work] = params[:work]\n resp[:job] = batch_job.name\n errors = []\n job_queues.each do |job_queue|\n errors << { error: job_queue.results, page: job_queue.page.pg_ref_number }\n end\n resp[:errors] = errors\n\n render json: resp, status: :ok\n end",
"def job_status(job_id)\n raise WebthumbException.new('Job id is required') if job_id == nil || job_id == ''\n Job.from_status_xml(@api_key, @api_endpoint, do_request(build_job_status_xml(job_id)))\n end",
"def get_job_status(job_id)\n @dbh[:progress_bars].filter(:id => job_id).first\n end",
"def job_status_message\n j = jobs_status\n if j\n begin\n return j.last[:status_message]\n rescue StandardError\n 'unknown'\n end\n else\n return 'unknown'\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports users to a connection from a file using a long running job. Documentation for the file format: | def import_users(users_file, connection_id, options = {})
raise Auth0::InvalidParameter, 'Must specify a valid file' if users_file.to_s.empty?
raise Auth0::InvalidParameter, 'Must specify a connection_id' if connection_id.to_s.empty?
request_params = {
users: users_file,
connection_id: connection_id,
upsert: options.fetch(:upsert, false),
external_id: options.fetch(:external_id, nil),
send_completion_email: options.fetch(:send_completion_email, true)
}
path = "#{jobs_path}/users-imports"
post_file(path, request_params)
end | [
"def import_users(users_file, connection_id)\n fail Auth0::InvalidParameter, 'Must specify a valid file' if users_file.to_s.empty?\n fail Auth0::InvalidParameter, 'Must specify a connection_id' if connection_id.to_s.empty?\n request_params = {\n users: users_file,\n connection_id: connection_id\n }\n path = \"#{jobs_path}/users-imports\"\n post_file(path, request_params)\n end",
"def importFile file_name\r\n File.open(file_name, \"r\") do |file|\r\n while (line = file.gets)\r\n @users << User.new(line.chomp.split(','))\r\n end\r\n end\r\n end",
"def load_users(user_file)\n\t\ti = 0\n\t\tuser_file.each_line do |el|\n\t\t\tel = el.split(\"|\")\n\t\t\t@users[i] = User.new(el)\n\t\t\ti += 1\n\t\tend\n\tend",
"def import_uh\n # user hash : tw_user -> bl_user\n @uh = Hash.new\n open(\"userlist.db\").read.split(\"\\n\").each do |line|\n ary = line.split(\" \")\n @uh[ ary[1] ] = ary[0]\n end\n puts \"userlist.db is imported. (#{@uh.size} users)\"\n end",
"def import\n User.import(params[:file])\n #After import, redirect and say if it worked or not.\n redirect_to(root_path, notice: \"Imported User file.\")\n end",
"def import\n uploaded_file = params[:file]\n begin \n dataset = CSV.read(uploaded_file.path, headers: true)\n UserService.new.import_users(dataset)\n redirect_to action: 'index'\n rescue\n flash[:error] = 'The file is invalid.'\n redirect_back fallback_location: root_url\n end\n end",
"def perform(filename, user_id)\n # Check if the user actually exists\n if !User.exists? user_id\n Rails.logger.error \"Trying to import OPML file #{filename} for non-existing user #{user_id}\"\n return\n end\n user = User.find user_id\n\n # Check that user has a opml_import_job_state with state RUNNING\n if user.opml_import_job_state&.state != OpmlImportJobState::RUNNING\n Rails.logger.error \"User #{user.id} - #{user.email} does not have a data import with state RUNNING, aborting OPML import\"\n return\n end\n\n OpmlImporter.process_opml filename, user\n rescue => e\n OPMLImportNotifier.notify_error user, e\n ensure\n Feedbunch::Application.config.uploads_manager.delete user_id, OpmlImporter::FOLDER, filename\n end",
"def import_users\n\t\tread_header = false\n\t\tlast_id = User.last.id\n\t\tActiveRecord::Base.transaction do\n\t\t\t@dataset.each(first_name: 'first_name', last_name: 'last_name', email: 'email', birthdate: 'birthdate') do |hash|\n\t\t\t\tif read_header\n\t\t\t\t\tUser.import_user(hash, role)\n\t\t\t\telse\n\t\t\t\t\tread_header = true\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tUser.find_each(start: last_id + 1) do |user|\n\t\t\tgenerated_password = Devise.friendly_token.first(8)\n\t\t\tuser.password = generated_password\n\t\t\tif user.save!\n\t\t\t\t#UserMailer.password_creation(user, generated_password).deliver\n\t\t\tend\n\t\tend\n \tend",
"def import_hosts(file_path)\n puts \"Importing hosts to database\"\n require 'csv'\n CSV.foreach(file_path, :headers => :true, :encoding => \"UTF-8\") do |row, i|\n next if i == 0 # ignore header row\n ref = get_value(row[0])\n name = get_value(row[1])\n address = get_value(row[2])\n\n Host.create(:ref => ref, :name => name, :address => address)\n end\n end",
"def import_stream(formatter)\n puts \"Importing file #{formatter.file_name}...\"\n start = Time.now\n\n sql = build_sql(formatter.value_str)\n cmd = build_cmd(sql)\n execute_cmd(cmd, formatter)\n\n puts \" -> #{Time.now - start}s\"\n end",
"def import_subscriptions(file)\n OpmlImporter.enqueue_import_job file, self\n end",
"def import\n puts \"Fetching files from remote buckets and local directories\"\n files_to_load = FileFetcher.new(@load_config).fetch\n db_options = get_db_options(@load_config)\n FileLoader.new(db_options, files_to_load)\n Redis.new(db_options.to_h).call(\"save\")\n end",
"def add_import_job(file_name, directory_name, uploaded)\n Import.create(:file_name => file_name, :directory_name => directory_name, :uploaded_at => uploaded, \n :status => Import::STATUS[:pending], :user_id => current_user.id)\n end",
"def import_profile_photo(user, url)\n album = user.profile_album\n user_id = user.id\n album_id = album.id\n current_batch = UploadBatch.factory( user_id, album_id, false )\n photo = Photo.create(\n :id => Photo.get_next_id,\n :caption => 'My Profile Photo',\n :album_id => album_id,\n :user_id => user_id,\n :upload_batch_id => current_batch.id,\n :capture_date => Time.now,\n :source_guid => Photo.generate_source_guid(url),\n :source_thumb_url => url,\n :source_screen_url => url,\n :source => 'user_join',\n :work_priority => ZZ::Async::Priorities.profile_photo\n )\n ZZ::Async::GeneralImport.enqueue(photo.id, url, { :priority => photo.work_priority })\n user.profile_photo_id = photo.id\n current_batch.close_immediate\n end",
"def import_users(data)\n bulk_import('users', data, Teamweek::Api::User)\n end",
"def import_rooms(file_path)\n puts \"Importing room to database\"\n require 'csv'\n CSV.foreach(file_path, :headers => :true, :encoding => \"UTF-8\") do |row, i|\n next if i == 0 # ignore header row\n ref = get_value(row[0])\n host_ref = get_value(row[1])\n capacity = get_value(row[2])\n Room.create(:ref => ref, :host_ref => host_ref, :capacity => capacity)\n end\n end",
"def import_users_from_csv(file)\n tutorial_cache = {}\n success = []\n errors = []\n ignored = []\n\n CSV.foreach(file) do |row|\n # Make sure we're not looking at the header or an empty line\n next if row[0] =~ /(subject|unit)_code/\n # next if row[5] !~ /^LA\\d/\n\n begin\n unit_code, username = row[0..1]\n first_name, last_name = [row[2], row[3]].map{|name| name.titleize unless name.nil? }\n email, tutorial_code = row[4..5]\n\n if unit_code != code\n ignored << { row: row, message: \"Invalid unit code. #{unit_code} does not match #{code}\" }\n next\n end\n\n if ! email =~ /\\A([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})\\z/i\n errors << { row: row, message: \"Invalid email address (#{email})\" }\n next\n end\n\n username = username.downcase\n\n project_participant = User.find_or_create_by(username: username) {|new_user|\n new_user.first_name = first_name\n new_user.last_name = last_name\n new_user.nickname = first_name\n new_user.role_id = Role.student_id\n new_user.email = email\n new_user.encrypted_password = BCrypt::Password.create(\"password\")\n }\n\n if not project_participant.persisted?\n project_participant.password = \"password\"\n project_participant.save\n end\n\n #\n # Only import if a valid user - or if save worked\n #\n if project_participant.persisted?\n user_project = projects.where(user_id: project_participant.id).first\n\n tutorial = tutorial_cache[tutorial_code] || tutorial_with_abbr(tutorial_code)\n tutorial_cache[tutorial_code] ||= tutorial\n\n # Add the user to the project (if not already in there)\n if user_project.nil?\n if not tutorial.nil?\n enrol_student(project_participant, tutorial)\n success << { row: row, message: \"Enrolled student with tutorial.\" }\n else\n enrol_student(project_participant)\n success << { row: row, message: \"Enrolled student without tutorial.\" }\n end\n else\n # update tutorial\n changes = \"\"\n\n if user_project.tutorial != tutorial\n user_project.tutorial = tutorial\n user_project.save\n changes << \"Changed tutorial. \"\n end\n\n if not user_project.enrolled\n user_project.enrolled = true\n user_project.save\n changes << \"Changed enrolment.\"\n end\n\n if changes.length == 0\n ignored << { row: row, message: \"No change.\" }\n else\n success << { row: row, message: changes }\n end\n end\n else\n errors << { row: row, message: \"Student record is invalid.\" }\n end\n rescue Exception => e\n errors << { row: row, message: e.message }\n end\n end\n\n {\n success: success,\n ignored: ignored,\n errors: errors\n }\n end",
"def importar_solicitudes(options)\n file = options[:file]\n campos = options[:campos]\n usuario_id = options[:usuario_id]\n\n WorkerLog.clear\n\n #importamos registros a la tabla\n WorkerLog.log(\"Leyendo archivo CSV...\")\n\n #obtenemos documento\n csv_doc = FasterCSV.new(options[:file].read, {:headers => true, :encoding => 'utf8', :skip_blanks => true})\n WorkerLog.log(\"Importando informacion archivo CSV...\")\n\n self.institucion = preparar_institucion(options[:institucion_id])\n \n # agregar enlaces\n # usar por default el usuario jefe de la unidad de informacion\n self.enlace = institucion.usuarios.activos.supervisores.first\n\n self.importar_registros(csv_doc, campos, usuario_id, self.institucion, self.enlace)\n\n end",
"def import_file\n @table_class = InverseCsvImporter.new(self.csv.path, self.user.login).table_class\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For matrix = [[false, true, true], [true, false, false], [true, false, false]] the output should be graphEdges(matrix) = 2. [execution time limit] 4 seconds (rb) | def graphEdges(matrix)
matrix.uniq.length == 1 ? 0 : matrix.uniq.length
end | [
"def graph_from_matrix(m)\n res = m.map do |row|\n row.map do |el|\n Node.new(el)\n end\n end\n\n res.each.with_index do |row, i|\n row.each.with_index do |el, j|\n el.ns << res[i - 1][j] if (i - 1 >= 0) # up\n el.ns << res[i + 1][j] if (i + 1 <= res.length - 1) # down\n el.ns << res[i][j - 1] if (j - 1 >= 0) # left\n el.ns << res[i][j + 1] if (j + 1 <= res[0].length - 1) # right\n end\n end\nend",
"def detect_cycle_in_graph(edges)\nend",
"def adjancy_matrix\n matrix = GraphViz::Math::Matrix.new( @graph.node_count, @graph.node_count )\n\n @graph.each_edge { |e|\n x = @graph.get_node(e.node_one(false, false)).index\n y = @graph.get_node(e.node_two(false, false)).index\n matrix[x+1, y+1] = 1\n matrix[y+1, x+1] = 1 if @graph.type == \"graph\"\n }\n\n return matrix\n end",
"def list_vertices_with_edges\n result = []\n\n # We search for all the lines that has at least one edge\n lines_with_edge = @matrix.find_all {|line| line.include? 1}\n\n # Because the smallest possible number in the matrix is zero but the smallest possible number in the graph is one,\n # we add one to all elements so the result is correct\n lines_with_edge.each do |line|\n result << (@matrix.find_index(line) + 1)\n end\n\n result\n end",
"def listEdges(matrix)\n edges = {}\n hitList = {}\n\n matrix.each_with_index do |line, i|\n aI = @alphaHash[i]\n line.each_with_index do |node, j|\n dist = matrix[i][j]\n aJ = @alphaHash[j]\n if dist != -1\n edge = (i < j ? \"#{aI}#{aJ}\" : \"#{aJ}#{aI}\")\n edges[aI] = {} if edges[aI].nil?\n edges[aJ] = {} if edges[aJ].nil?\n edges[aI][aJ] = dist\n edges[aJ][aI] = dist\n hitList[edge] = dist\n end\n end\n end\n\n hitList = Hash[hitList.sort_by {|k,v| v*-1}]\n [edges,hitList]\n end",
"def incidence_matrix\n tail = (@graph.type == \"digraph\") ? -1 : 1\n matrix = GraphViz::Math::Matrix.new( @graph.node_count, @graph.edge_count )\n\n @graph.each_edge { |e|\n x = e.index\n\n nstart = @graph.get_node(e.node_one(false, false)).index\n nend = @graph.get_node(e.node_two(false, false)).index\n\n matrix[nstart+1, x+1] = 1\n matrix[nend+1, x+1] = tail\n matrix[nend+1, x+1] = 2 if nstart == nend\n }\n\n return matrix\n end",
"def getGraphEdges(graph)\n edges = Hash.new\n graph.edges.each { |e|\n if @asymetric\n edges[e.source+e.target] = e\n else\n edges[e.source+e.target] = edges[e.target+e.source] = e\n end\n }\n edges\n end",
"def get_adjacency_matrix\n max_index = find_max_index\n adjacency_matrix = [nil] * max_index\n adjacency_matrix.map! { [0] * max_index }\n @edges.each do |edg|\n from_index = edg.node_from.value\n to_index = edg.node_to.value\n adjacency_matrix[from_index][to_index] = edg.value\n end\n adjacency_matrix\n end",
"def algorithm\n # => |V| \n $V.times do\n # => total |E| times, |E| <= |V^2| \n $adjacent_matrix.each.with_index do |sets, u| \n # why |E|? \n # edges can be bidirected so |E| may greater than |V| but must smaller or equal to |V^2|\n sets.each.with_index do |weight, v| # => edge(u, v)\n if weight != nil and weight + $distance[u] < $distance[v]\n $distance[v] = $distance[u] + weight\n $prior[v] = u\n end\n end\n end\n end\nend",
"def amount_of_vertices_with_edges\n\n # The number of vertices it's equal to the number of lines where their inner sum is greater than zero\n number_of_vertices = (@matrix.find_all {|line| line.inject(0){|sum, x| sum + x } > 0}).count\n\n end",
"def neighbours(u, graph)\n arr = []\n number_of_rows = graph.size\n number_of_columns = graph[0].size\n\n if u[0] >= number_of_rows || u[0] < 0\n return arr\n end\n if u[1] >= number_of_columns || u[1] < 0\n return arr\n end\n \n for i in 0...number_of_rows\n for j in 0...number_of_columns\n if neighbour?(u, [i, j])\n arr << [i, j]\n end \n end\n end\n\n return arr\nend",
"def check_negative_cycle\n $adjacent_matrix.each.with_index do |set, u| # => |E|\n set.each.with_index do |weight, v|\n if weight != nil and weight + $distance[u] < $distance[v]\n puts \"This graph include negative cycle for Shortest pathh problem.\"\n puts \"It cause NP-complete case. So cannot find correct answer.\"\n return \n end\n end\n end\nend",
"def adjacencymatrix(mode=:standard, diagonal=false)\n # prepare matrix\n ni = Hash.new\n @nodes.each_with_index { |n,i| ni[n]=i }\n matrix = Array.new(@nodes.length) { Array.new(@nodes.length, 0) }\n @links.each do |(s,d),l| \n i = ni[s]\n j = ni[d]\n if (i!=j) || diagonal\n case mode\n when :standard\n matrix[i][j] = 1 \n matrix[j][i] = 1 unless @directed\n when :linkcount\n matrix[i][j] += 1 \n matrix[j][i] += 1 unless @directed\n when :weight, :reciprocal, :inverted\n matrix[i][j] += l.weight \n matrix[j][i] += l.weight unless @directed\n end\n end\n end\n case mode\n when :reciprocal\n matrix.each do |row|\n row.each_with_index do |v,i|\n row[i] = 1.0/v unless v == 0\n end\n end\n when :inverted\n wmax1 = matrix.flatten.max + 1\n matrix.each do |row|\n row.each_with_index do |v,i|\n row[i] = wmax1 - v unless v == 0\n end\n end\n end\n matrix\n end",
"def adjacency_matrix\n return @adjacency_matrix if @adjacency_matrix\n\n # Convert from adjacency list to a map structure\n g = Hash.new{|h,k| h[k] = []}\n edges.each{|x|\n g[x[1]] << x[0]\n }\n\n @adjacency_matrix = g\n end",
"def identify_neighbours\n @x.times{ |r|\n @y.times{|c| \n #+1,+1 0,+1 +1,0\n @mat[r][c].add_neighbour @mat[r+1][c+1] unless @mat[r+1].nil? || @mat[r+1][c+1].nil?\n @mat[r][c].add_neighbour @mat[r][c+1] unless @mat[r].nil? || @mat[r][c+1].nil?\n @mat[r][c].add_neighbour @mat[r+1][c] unless @mat[r+1].nil? || @mat[r+1][c].nil?\n \n #-1,-1 0,-1 -1,0\n @mat[r][c].add_neighbour @mat[r-1][c-1] unless @mat[r-1].nil? || @mat[r-1][c-1].nil?\n @mat[r][c].add_neighbour @mat[r-1][c] unless @mat[r-1].nil? || @mat[r-1][c].nil?\n @mat[r][c].add_neighbour @mat[r][c-1] unless @mat[r].nil? || @mat[r][c-1].nil?\n \n #+1,-1 -1,+1\n @mat[r][c].add_neighbour @mat[r-1][c+1] unless @mat[r-1].nil? || @mat[r-1][c+1].nil?\n @mat[r][c].add_neighbour @mat[r+1][c-1] unless @mat[r+1].nil? || @mat[r+1][c-1].nil?\n \n }\n \n } \n end",
"def number_of_vertices(matrix)\n # Ignoring the weight element (third element)\n matrix = matrix.collect { |x| [x[0], x[1]] }\n # Merging all the path arrays\n matrix = matrix.zip.flatten.compact\n # All the vertices\n @nodes = matrix.uniq.dup\n # Returning the number of unique elements (vertices)\n matrix.uniq.count\n end",
"def test_add_edge_with_cycles\n @graph.add_edge('a', 'b');\n @graph.add_edge('b', 'c');\n @graph.add_edge('c', 'a');\n\n # 0 and 2 are indexes of vertex a and vertex c respectively\n assert(@graph.vertices[0].neighbours[2] == true && @graph.vertices[2].neighbours[0] == true)\n end",
"def bitmap_holes(arr)\n rows = arr.map { |row| row.chars.map(&:to_i) }\n matrix = rows.flatten\n # rows.first.zip(rows[1..-1])\n count = 0\n connected = false\n while rows.flatten.include?(0)\n rows.each_with_index do |row, row_idx|\n column_idx = 0\n while column_idx < row.size\n if row[column_idx] == 0\n count += 1\n row[column_idx] = 1\n if row[column_idx + 1] == 0\n connected = true\n row[column_idx + 1] = 1\n while connected\n if row[column_idx + 2] == 0\n row[column_idx + 2] = 1\n elsif rows[row_idx + 1]\n else\n connected = false\n end\n end\n end\n end\n column_idx += 1\n end\n end\n end\nend",
"def getConnectedEdges(map)\n return getConnectedEdgeIds().map{|edgeId| map.edgeTable[edgeId]} ;\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stashes the match data somewhere on the system. Returns a string containing userfriendly instructions for accessing the match data. | def stash_data
path = self.class.gamesave_path
FileUtils.mkdir_p path
txt_path = File.join path, data[:uid] + '.txt'
File.open(txt_path, 'wb') { |f| f.write output } unless File.exist?(txt_path)
rms_path = File.join path, data[:uid] + '.rms'
File.open(rms_path, 'wb') { |f| f.write data[:rms] } unless File.exist?(rms_path)
"Output: #{open_binary} #{txt_path}\nReplay: bcpm replay #{rms_path}\n"
end | [
"def matchdata\n @matchdata\n end",
"def hit_string\n # Return hex value\n [@hit.to_s].pack(\"H*\").gsub(\"\\n\", \"\")\n end",
"def escape_key\n return data_battler.escape_key\n end",
"def createMatchDataHash(match_data)\n\tdata_names = match_data.names\n\tdata_values = match_data.captures\n\tdata_hash = {}\n\tdata_names.size.times do |i|\n\t\tdata_hash[data_names[i]] = data_values[i].strip\n\tend \t\n\treturn data_hash\nend",
"def set_match_data(match_data)\n @ephemeral.last.match_data = match_data\n end",
"def hexdump offset = 0\n data = @captured[offset, @capture_length]\n\n data.scan(/.{,16}/m).map.with_index do |chunk, index|\n next nil if chunk.empty?\n hex = chunk.unpack('C*').map { |byte| '%02x' % byte }\n dump = chunk.tr \"\\000-\\037\\177-\\377\", \".\"\n\n length = hex.length\n hex.fill ' ', length, 16 - length if length < 16\n\n \"\\t0x%04x: %s%s %s%s %s%s %s%s %s%s %s%s %s%s %s%s %s\" % [\n index * 16, *hex, dump\n ]\n end.join \"\\n\"\n end",
"def wattball_match_result(match)\n [\n match.team1.teamName,\n [\n match.result.join(\" - \")\n\n ],\n match.team2.teamName\n ].join(\" \")\n end",
"def matchname\n \"#{self.date}: #{self.hometeam.name} V #{self.awayteam.name}\"\n end",
"def hermit_list\n warn(\"Hermits currently in database\")\n @output = \"Location\".ljust(@formatpad) + @hermithash[\"Location\"].rjust(@formatpad)\n warn(@output)\n @hermithash.each_key { |key| \n unless key == \"Location\" \n @output = \"#{key.to_s}\".ljust(@formatpad) + @hermithash[key].to_s.rjust(@formatpad)\n warn(@output)\n end\n }\n end",
"def full_match\n @match_data[0]\n end",
"def segLink(entry)\n metalink = \"http://www.jcvi.org/phylo-metarep/phylodb/seguid/\"\n return metalink + entry.gsub(\":\",\"<>\").gsub(\"/\", \"[]\").gsub(\"+\",\"()\")\nend",
"def hexdump( data )\n\t\t\tdata.bytes.to_a.map {|byte| sprintf('%#02x',byte) }.join( ' ' )\n\t\tend",
"def dump_replay\n type = TYPES[highscoreable.class.to_s.remove('Mappack')]\n\n # Build header\n replay = [type[:rt]].pack('L<') # Replay type (0 lvl/sty, 1 ep)\n replay << [id].pack('L<') # Replay ID\n replay << [highscoreable.inner_id].pack('L<') # Level ID\n replay << [player.metanet_id].pack('L<') # User ID\n\n # Append replay and return\n inputs = dump_demo\n return if inputs.nil?\n replay << Zlib::Deflate.deflate(inputs, 9)\n replay\n rescue => e\n lex(e, \"Failed to dump replay with ID #{id}\")\n return\n end",
"def show_matches mds, msg=nil\n puts msg if msg\n mds.each do |md|\n puts \"#{md[0]}\\t#{md.offset(0)}\"\n end\nend",
"def inspect\n res = \"Hit: #{@subject_id.ljust(10)} #{@ident.to_s.rjust(4)} #{@align_len.to_s.rjust(2)} #{@mismatches.to_s.rjust(2)} #{@gaps.to_s.rjust(2)} #{@q_beg.to_s.rjust(5)} #{@q_end.to_s.rjust(5)} #{@s_beg.to_s.rjust(5)} #{@s_end.to_s.rjust(5)} #{@e_val.to_s.rjust(5)} #{@bit_score.to_s.rjust(5)} #{@reversed.to_s.rjust(5)}\"\n res += \" #{@score.to_s.rjust(5)} #{@acc.ljust(10)} #{@definition.ljust(10)} #{@q_frame.to_s.rjust(2)} #{@s_frame.to_s.rjust(2)} #{@full_subject_length.to_s.rjust(5)} #{@q_seq}.#{@s_seq}.#{@q_len}.#{@s_len}\"\n\n return res\n end",
"def dump\n @captured.tr \"\\000-\\037\\177-\\377\", \".\"\n end",
"def hero_data(hero)\n\t\tname = hero.name.capitalize\n\t\thereStr = \t\"\\n#{name}, the #{hero.title}\\n\" +\n\t\t\t\t\"Role: #{hero.role}\\n\" +\n\t\t\t\t\"Franchise: #{hero.franchise}\\n\"\n\tend",
"def format_debug_info(hash)\n debug_text = \"PeerIP: \" + hash[\"peerip\"].to_s + \"<br>\"\n debug_text += \"RecvIP: \" + hash[\"recvip\"].to_s + \"<br>\"\n debug_text += \"SipFrom: \" + hash[\"sipfrom\"].to_s + \"<br>\"\n debug_text += \"URI: \" + hash[\"uri\"].to_s + \"<br>\"\n debug_text += \"UserAgent: \" + hash[\"useragent\"].to_s + \"<br>\"\n debug_text += \"PeerName: \" + hash[\"peername\"].to_s + \"<br>\"\n debug_text += \"T38Passthrough: \" + hash[\"t38passthrough\"].to_s + \"<br>\"\n debug_text\n end",
"def format_debug_info(hash)\n debug_text = 'PeerIP: ' + hash['peerip'].to_s + '<br>'\n debug_text += 'RecvIP: ' + hash['recvip'].to_s + '<br>'\n debug_text += 'SipFrom: ' + hash['sipfrom'].to_s + '<br>'\n debug_text += 'URI: ' + hash['uri'].to_s + '<br>'\n debug_text += 'UserAgent: ' + hash['useragent'].to_s + '<br>'\n debug_text += 'PeerName: ' + hash['peername'].to_s + '<br>'\n debug_text += 'T38Passthrough: ' + hash['t38passthrough'].to_s + '<br>'\n debug_text\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /acessorios or /acessorios.json | def create
@acessorio = Acessorio.new(acessorio_params)
respond_to do |format|
if @acessorio.save
format.html { redirect_to @acessorio, notice: "Acessorio was successfully created." }
format.json { render :show, status: :created, location: @acessorio }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @acessorio.errors, status: :unprocessable_entity }
end
end
end | [
"def create\n @acessos_api = AcessosApi.new(acessos_api_params)\n\n respond_to do |format|\n if @acessos_api.save\n format.html { redirect_to @acessos_api, notice: \"Acessos api was successfully created.\" }\n format.json { render :show, status: :created, location: @acessos_api }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @acessos_api.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @oferta_academica = OfertaAcademica.new(params[:oferta_academica])\n\n if @oferta_academica.save\n render json: @oferta_academica, status: :created, location: @oferta_academica\n else\n render json: @oferta_academica.errors, status: :unprocessable_entity\n end\n end",
"def create\n @acessorios_rpa = AcessoriosRpa.new(acessorios_rpa_params)\n\n respond_to do |format|\n if @acessorios_rpa.save\n format.html { redirect_to @acessorios_rpa, notice: 'Acessorios rpa was successfully created.' }\n format.json { render :show, status: :created, location: @acessorios_rpa }\n else\n format.html { render :new }\n format.json { render json: @acessorios_rpa.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @accesorio = Accesorio.new(params[:accesorio])\n\n respond_to do |format|\n if @accesorio.save\n format.html { redirect_to @accesorio, notice: 'Accesorio was successfully created.' }\n format.json { render json: @accesorio, status: :created, location: @accesorio }\n else\n format.html { render \"new\" }\n format.json { render json: @accesorio.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @aactio = Aactio.new(params[:aactio])\n\n respond_to do |format|\n if @aactio.save\n format.html { redirect_to @aactio, notice: 'Aactio was successfully created.' }\n format.json { render json: @aactio, status: :created, location: @aactio }\n else\n format.html { render action: \"new\" }\n format.json { render json: @aactio.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @accesorio = Accesorio.new(accesorio_params)\n\n respond_to do |format|\n if @accesorio.save\n format.html { redirect_to @accesorio, notice: 'Accesorio was successfully created.' }\n format.json { render :show, status: :created, location: @accesorio }\n else\n format.html { render :new }\n format.json { render json: @accesorio.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @diocese = Diocese.new(diocese_params)\n\n if @diocese.save\n render json: @diocese, status: :created, location: @diocese\n else\n render json: @diocese.errors, status: :unprocessable_entity\n end\n end",
"def create\n @asesor = Asesor.new(params[:asesor])\n\n respond_to do |format|\n if @asesor.save\n format.html { redirect_to @asesor, notice: 'Asesor was successfully created.' }\n format.json { render json: @asesor, status: :created, location: @asesor }\n else\n format.html { render action: \"new\" }\n format.json { render json: @asesor.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @asesor = Asesor.new(asesor_params)\n\n respond_to do |format|\n if @asesor.save\n format.html { redirect_to @asesor, notice: 'Asesor was successfully created.' }\n format.json { render :show, status: :created, location: @asesor }\n else\n format.html { render :new }\n format.json { render json: @asesor.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @auditorio = Auditorio.new(auditorio_params)\n\n respond_to do |format|\n if @auditorio.save\n format.html { redirect_to @auditorio, notice: 'Auditorio was successfully created.' }\n format.json { render :show, status: :created, location: @auditorio }\n else\n format.html { render :new }\n format.json { render json: @auditorio.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n puts \"=============================================\"\n ap tutoria_params\n @tutoria = Tutoria.new(tutoria_params)\n\n respond_to do |format|\n if @tutoria.save\n format.html { redirect_to @tutoria, notice: 'Tutorias was successfully created.' }\n format.json { render action: 'show', status: :created, location: @tutoria }\n else\n format.html { render action: 'new' }\n format.json { render json: @tutoria.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\n @anuncio = Anuncio.new(anuncio_params)\n\n if @anuncio.save\n render :show, status: :created, location: @anuncio\n else\n render json: @anuncio.errors, status: :unprocessable_entity\n end\n end",
"def post_spoonacular\n # %encode ingredients to url\n encoded_ingr = URI.escape(@translated_recipe[:ingredients_list])\n # post call block :\n url = URI(\"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/parseIngredients?includeNutrition=true\")\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Post.new(url)\n request[\"content-type\"] = \"application/x-www-form-urlencoded\"\n request[\"x-rapidapi-key\"] = ENV[\"X_RAPIDAPI_KEY\"]\n request[\"x-rapidapi-host\"] = \"spoonacular-recipe-food-nutrition-v1.p.rapidapi.com\"\n # body of the call with ingredients and servings\n request.body = \"ingredientList=#{encoded_ingr}&#{@recipe_hash[:servings]}\"\n # response\n response = http.request(request)\n end",
"def create\n @acerca = Acerca.new(params[:acerca])\n\n respond_to do |format|\n if @acerca.save\n format.html { redirect_to @acerca, notice: 'Acerca was successfully created.' }\n format.json { render json: @acerca, status: :created, location: @acerca }\n else\n format.html { render action: \"new\" }\n format.json { render json: @acerca.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @auditoria = Auditoria.new(params[:auditoria])\n\n respond_to do |format|\n if @auditoria.save\n format.html { redirect_to @auditoria, :notice => 'Auditoria was successfully created.' }\n format.json { render :json => @auditoria, :status => :created, :location => @auditoria }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @auditoria.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @astronaut = Astronaut.new(astronaut_params)\n\n if @astronaut.save\n render json: @astronaut, status: :created, location: @astronaut\n else\n render json: @astronaut.errors, status: :unprocessable_entity\n end\n end",
"def create\n @aucrecord = Aucrecord.new(aucrecord_params)\n\n respond_to do |format|\n if @aucrecord.save\n format.html { redirect_to @aucrecord, notice: 'Aucrecord was successfully created.' }\n format.json { render action: 'show', status: :created, location: @aucrecord }\n else\n format.html { render action: 'new' }\n format.json { render json: @aucrecord.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @osoba = Osoba.new(params[:osoba])\n\n if @osoba.save\n render json: @osoba, status: :created, location: @osoba\n else\n render json: @osoba.errors, status: :unprocessable_entity\n end\n end",
"def create\n @apoderado = Apoderado.new(apoderado_params)\n\n respond_to do |format|\n if @apoderado.save\n format.html { redirect_to @apoderado, notice: 'Apoderado was successfully created.' }\n format.json { render :show, status: :created, location: @apoderado }\n else\n format.html { render :new }\n format.json { render json: @apoderado.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PATCH/PUT /acessorios/1 or /acessorios/1.json | def update
respond_to do |format|
if @acessorio.update(acessorio_params)
format.html { redirect_to @acessorio, notice: "Acessorio was successfully updated." }
format.json { render :show, status: :ok, location: @acessorio }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @acessorio.errors, status: :unprocessable_entity }
end
end
end | [
"def update\n respond_to do |format|\n if @acessos_api.update(acessos_api_params)\n format.html { redirect_to @acessos_api, notice: \"Acessos api was successfully updated.\" }\n format.json { render :show, status: :ok, location: @acessos_api }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @acessos_api.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @api_v1_initiative.update(api_v1_initiative_params)\n format.html { redirect_to @api_v1_initiative, notice: 'Initiative was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_initiative }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_initiative.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @aactio = Aactio.find(params[:id])\n\n respond_to do |format|\n if @aactio.update_attributes(params[:aactio])\n format.html { redirect_to @aactio, notice: 'Aactio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @aactio.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @apologetic.update(apologetic_params)\n format.html { redirect_to @apologetic, notice: 'Apologetic was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @apologetic.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @api_v1_initiative_update.update(api_v1_initiative_update_params)\n format.html { redirect_to @api_v1_initiative_update, notice: 'Initiative update was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_initiative_update }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_initiative_update.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @accesorio = Accesorio.find(params[:id])\n\n respond_to do |format|\n if @accesorio.update_attributes(params[:accesorio])\n format.html { redirect_to @accesorio, notice: 'Accesorio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render \"edit\" }\n format.json { render json: @accesorio.errors, status: :unprocessable_entity }\n end\n end\n end",
"def put\n request_method('PUT')\n end",
"def update\n respond_to do |format|\n if @a1c.update(a1c_params)\n format.html { redirect_to @a1c, notice: 'A1c was successfully updated.' }\n format.json { render :show, status: :ok, location: @a1c }\n else\n format.html { render :edit }\n format.json { render json: @a1c.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_aos_version(args = {}) \n put(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend",
"def update\n respond_to do |format|\n if @acessorios_rpa.update(acessorios_rpa_params)\n format.html { redirect_to @acessorios_rpa, notice: 'Acessorios rpa was successfully updated.' }\n format.json { render :show, status: :ok, location: @acessorios_rpa }\n else\n format.html { render :edit }\n format.json { render json: @acessorios_rpa.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @aile.update(aile_params)\n format.html { redirect_to @aile, notice: 'Aile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @aile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @cio.update(cio_params)\n format.html { redirect_to @cio, notice: 'Cio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @cio.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @ato.update(ato_params)\n format.html { redirect_to @ato, notice: 'Ato was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @ato.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @aucrecord.update(aucrecord_params)\n format.html { redirect_to @aucrecord, notice: 'Aucrecord was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @aucrecord.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @aception.update(aception_params)\n format.html { redirect_to @aception, notice: 'Aception was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @aception.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @receipe = Receipe.find(params[:id])\n\n if @receipe.update(receipe_params)\n head :no_content\n else\n render json: @receipe.errors, status: :unprocessable_entity\n end\n end",
"def update\n @retroaspecto = Retroaspecto.find(params[:id])\n\n respond_to do |format|\n if @retroaspecto.update_attributes(params[:retroaspecto])\n format.html { redirect_to @retroaspecto, notice: 'Retroaspecto was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @retroaspecto.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @cajero.update(cajero_params)\n format.html { redirect_to @cajero, notice: 'Cajero was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @cajero.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n\n respond_to do |format|\n if @idioma.update(idioma_params)\n format.html { redirect_to idiomas_path(@idioma, egresso_id: @idioma.egresso_id), notice: 'Idioma atualizado com sucesso.' }\n format.json { render :show, status: :ok, location: idiomas_path }\n else\n format.html { render :edit }\n format.json { render json: @idioma.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the first point with the given color around given coordinates. | def point_with_colour_around(color, origin_point, point_to_ignore = nil)
x, y = origin_point
[
[ x - 1, y - 1 ],
[ x, y - 1 ],
[ x + 1, y - 1 ],
[ x - 1, y ],
[ x + 1, y ],
[ x - 1, y + 1 ],
[ x, y + 1 ],
[ x + 1, y + 1 ]
].each do |point|
return point if point != point_to_ignore && @image.pixel_color(*point) == color
end
nil
end | [
"def point_with_color_around(color, origin_point, points_to_ignore = [])\n x, y = origin_point\n\n [\n [ x - 1, y - 1 ],\n [ x, y - 1 ],\n [ x + 1, y - 1 ],\n [ x - 1, y ],\n [ x + 1, y ],\n [ x - 1, y + 1 ],\n [ x, y + 1 ],\n [ x + 1, y + 1 ]\n ].each do |point|\n return point if !points_to_ignore.include?(point) && @image.pixel_color(*point) == color\n end\n\n nil\n end",
"def closest(color)\n raise TypeError unless color.is_a? Color\n\n c = ::GD2::GD2FFI.send(:gdImageColorClosestAlpha, @image.image_ptr, color.red.to_i, color.green.to_i, color.blue.to_i, color.alpha.to_i)\n c == -1 ? nil : get_color(c)\n end",
"def closest_to(color)\n closest_color = nil\n closest_diff = 100\n\n @items.each do |item|\n diff = ColorDiff.between(color, item)\n if diff < closest_diff\n closest_diff = diff\n closest_color = item\n end\n end\n\n closest_color\n end",
"def pieces_coords(color)\n Board.coords_list.select do |coords|\n piece = at(coords)\n !piece.nil? && piece.color == color\n end\n end",
"def point x, y, c = nil\n if c then\n renderer[x, h-y-1] = color[c]\n else\n renderer[x, h-y-1]\n end\n end",
"def get_color(point)\n @raw_board[point.x][point.y]\n end",
"def color_xy_pixel(x, y, c)\n x_index = x - 1\n y_index = y - 1\n\n @canvas = @canvas.each_with_index.map do |cy, yi|\n cy.each_with_index.map do |cx, xi|\n if x_index == xi && y_index == yi\n c\n else\n cx\n end\n end\n end\n end",
"def closest(color)\n bpc = 4\n bpc *= 2 if color.length > 3\n color = color.to_i(16)\n\n blue = color % (1 << bpc)\n green = ((color - blue) % (1 << (bpc * 2))) >> bpc\n red = (color - (blue + green)) >> (bpc * 2)\n\n # 216 (6**3) colors are mapped in 256 color mode (40 colors are otherwise\n # reserved for normal and bold standard colors from 0x00 to 0x0f in\n # addition to a 24 color gradient from black to white from 0xe8 - 0xff.)\n [blue,green,red].each_with_index.map do |c,i|\n (c/(((1 << bpc)-1)/5)) * 6**i\n end.sum + 0x10\n end",
"def get_rgb_point(hue, chroma, x)\n case hue\n when 0...1 then [chroma, x, 0]\n when 1...2 then [x, chroma, 0]\n when 2...3 then [0, chroma, x]\n when 3...4 then [0, x, chroma]\n when 4...5 then [x, 0, chroma]\n when 5...6 then [chroma, 0, x]\n # HUE will never leave the 0..359 range because we use (hue % 360)\n # else [0, 0, 0]\n end\n end",
"def find_pixel_neighbors(x, y, color)\n # If this comment isn't necessary, don't include it in the submitted code\n # neighbors = [[x-1,y-1],[x,y-1],[x+1,y-1],[x-1,y],[x,y],[x+1,y],[x-1,y+1],[x,y+1],[x+1,y+1]]\n neighbors = [[x,y-1],[x-1,y],[x,y],[x+1,y],[x,y+1]]\n prepare_pixel_neighbors(neighbors, color)\n end",
"def point x, y, color\n self[x, y] = self[x, y].blend(color)\n end",
"def king_position(color)\n each_cell do |cell, column_number, row_number|\n if cell.is_a? Pieces::King and cell.color == color\n return Coordinates.new(column_number, row_number)\n end\n end\n end",
"def nearest_point x, y\n c2 = width**2 + height**2\n # arguably this is a fail condition but return point instead\n if c2 == 0\n [@x1, @y1]\n end\n\n px = x - @x1\n py = y - @y1\n u = (px*width + py*height)/c2\n if u < 0 \n return [@x1, @y1]\n elsif u > 1\n return [@x2, @y2]\n end\n return [@x1 + u*width, @y1 + u*height]\n end",
"def find_pixel_color(x, y)\n @pixels[(x-1)+(y-1)*@m_columns].color\n end",
"def firstpoint\n return self.pointlist()[0]\n end",
"def find_king_coords(color)\n x = 0\n y = 0\n until get_board_coord(x, y).is_a?(King) && get_board_coord(x, y).color == color\n x += 1\n if x == 8\n x = 0\n y += 1\n end\n end\n [x, y]\n end",
"def point( point )\n curve = self.sample( point.y )\n return curve.point( point.x )\n end",
"def color_at_object(object, point)\n color_at(object.to_local(point))\n end",
"def point x, y, c\n screen[x, h-y] = color[c]\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the options hash with basic auth credentials used by the http client | def build_options
if File.exist?(@connection_info[:tmp_pw_file])
username = 'admin'
password = File.read(@connection_info[:tmp_pw_file])
else
username = @connection_info[:username]
password = @connection_info[:password].unwrap
end
{
basic_auth: {
user: username,
password: password
}
}
end | [
"def http_basic_authentication\n @opts[:http_basic_authentication]\n end",
"def build_options!(options)\n options[:basic_auth] = self.basic_auth if self.basic_auth\n if @cookies\n options[:headers] ||= {}\n options[:headers]['cookie'] = @cookies.to_a.collect{|c| \"#{c[0]}=#{c[1]}\"}.join('; ') + ';'\n end\n end",
"def header(options)\n digest = if options[:digest]\n options[:digest]\n elsif @config[:digest]\n @config[:digest]\n else\n false\n end\n {'Authorization' => \"Basic #{digest}\"} if digest\n end",
"def options_for_authentication\n { auth_type: :basic }\n end",
"def default_options\n {\n basic_auth: {\n username: Maestrano[self.class.preset].param('api.id'),\n password: Maestrano[self.class.preset].param('api.key')\n },\n timeout: Maestrano[self.class.preset].param('connec.timeout')\n }\n end",
"def client_options\n opts = uri_options.tap do |opts|\n opts[:database] = @database if @database\n end\n\n @user ? opts.merge(credentials) : opts\n end",
"def client_options\n opts = @txt_options.merge(ssl: true)\n opts = opts.merge(uri_options).merge(:database => database)\n @user ? opts.merge(credentials) : opts\n end",
"def http_authorization_to_creds\n @auth ||= Rack::Auth::Basic::Request.new request.env\n return unless @auth.provided? && @auth.basic?\n\n @auth.credentials\n end",
"def proxy_http_basic_authentication\n @opts[:proxy_http_basic_authentication]\n end",
"def client_options\n opts = uri_options.merge(:database => database)\n @user ? opts.merge(credentials) : opts\n end",
"def request_options\n {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n basic_auth: {\n username: 'api',\n password: ENV.fetch('MAILGUN_API_KEY')\n }\n }\n end",
"def http_options\n headers = {}\n headers[\"If-Modified-Since\"] = @options[:if_modified_since].httpdate if @options.has_key?(:if_modified_since)\n\n headers[\"If-None-Match\"] = @options[:if_none_match] if @options.has_key?(:if_none_match)\n headers[\"Accept-encoding\"] = 'gzip, deflate' if @options.has_key?(:compress)\n headers[\"User-Agent\"] = (@options[:user_agent] || USER_AGENT)\n options = { headers: headers }\n # curl.enable_cookies = options[:enable_cookies] if options.has_key?(:enable_cookies)\n # curl.cookiefile = options[:cookiefile] if options.has_key?(:cookiefile)\n # curl.cookies = options[:cookies] if options.has_key?(:cookies)\n\n # curl.userpwd = options[:http_authentication].join(':') if options.has_key?(:http_authentication)\n # curl.proxy_url = options[:proxy_url] if options.has_key?(:proxy_url)\n # curl.proxy_port = options[:proxy_port] if options.has_key?(:proxy_port)\n # curl.max_redirects = options[:max_redirects] if options[:max_redirects]\n # curl.timeout = options[:timeout] if options[:timeout]\n # curl.ssl_version = options[:ssl_version] if options.has_key?(:ssl_version)\n options[:ssl_verifyhost] = @options[:ssl_verify_host] if @options.has_key?(:ssl_verify_host)\n options[:followlocation] = true\n options[:ssl_verify_peer] = @options[:ssl_verify_peer] if @options.has_key?(:ssl_verify_peer)\n options\n end",
"def open_uri_http_options\n unless RDig::configuration.crawler.open_uri_http_options\n opts = {}\n if RDig::configuration.crawler.http_proxy\n opts[:proxy] = RDig::configuration.crawler.http_proxy\n if user = RDig::configuration.crawler.http_proxy_user\n pass = RDig::configuration.crawler.http_proxy_pass\n opts['Authorization'] = \"Basic \" + Base64.encode64(\"#{user}:#{pass}\")\n end\n end\n RDig::configuration.crawler.open_uri_http_options = opts\n end\n return RDig::configuration.crawler.open_uri_http_options\n end",
"def get_client_config_info(user_hash, user_password, machine, code_name, platform, arch, ver)\n string = \"/client/get_config?arch=#{arch}&codename=#{code_name}&machineid=#{machine}&platform=#{platform}&ver=#{ver}\"\n uri = URI.parse(\"#{QA_ENV['bus_host']}\")\n Log.debug \"curl -k -I -u \\\"#{user_hash}:#{user_password}\\\" \\\"#{uri+string}\\\"\"\n Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|\n http.set_debug_output $stderr\n Log.debug string\n req = Net::HTTP::Get.new(string)\n req.basic_auth(user_hash, user_password)\n response = http.request(req)\n return response.header\n end\n end",
"def basic_auth(login, password)\n client.http.auth.basic(login, password)\n end",
"def basic_auth\n authenticate_or_request_with_http_basic do |username, password|\n username == ENV[\"BASIC_AUTH_USER\"] && password == ENV[\"BASIC_AUTH_PASSWORD\"]\n end\n end",
"def request_http_basic_auth(value = nil)\n rw_config(:request_http_basic_auth, value, false)\n end",
"def http_options; end",
"def options\n # figure out our options for this request\n add_ssl_options(\n # for GETs, we pass the params to Faraday to encode\n {params: get_args}.merge(HTTPService.http_options).merge(raw_options)\n )\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
JSON put request against the given api endpoint | def put_request(_context, endpoint, data)
Puppet.runtime[:http].put(
build_uri(endpoint),
Puppet::Util::Json.dump(data),
headers: {
'Content-Type' => 'application/json'
},
options: build_options,
)
end | [
"def put endpoint, data\n do_request :put, endpoint, data\n end",
"def put(url, endpoint, auth_token, payload)\n uri = URI.parse(\"#{url}\")\n http = Net::HTTP.new(uri.host, uri.port)\n http.read_timeout = 60 * 5\n if url.include?('https://')\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n request = Net::HTTP::Put.new(\"#{BASE_API}#{endpoint}?auth_token=#{auth_token}\")\n request.add_field('Content-Type', 'application/json')\n request.body = payload.to_json\n puts \"PAYLOAD: #{request.body}\"\n http.request(request)\nend",
"def put(id, json)\n with_endpoint do |endpoint|\n url = [endpoint, @resource_name, id].compact.join('/')\n url += \"/\" \n return HTTParty.put(url, :body => json, :timeout => 4, :headers => { 'Content-Type' => 'application/json' })\n end\n end",
"def put\n request_method('PUT')\n end",
"def put *args\n make_request :put, *args\n end",
"def put(path, params={}); make_request(:put, host, port, path, params); end",
"def send_put_request endpoint, params={}, api_key=nil, ssl=false\n uri = URI.parse(endpoint)\n\n Net::HTTP.start(uri.host, uri.port) do |http|\n http.use_ssl = true if ssl\n request = Net::HTTP::Put.new(uri.request_uri)\n request['authorization'] = \"Token token=#{api_key}\" if api_key\n request.set_form_data(params)\n http.request request\n end\n end",
"def put(url, payload = {}, headers = {})\n http :put, \"#{url}.json\", payload.to_json, headers\n end",
"def put url, object = nil\n request url, HTTP::Put, object\n end",
"def _put(url=\"\", params={}, headers={}, payload)\n\t\tif !params.empty? then\n\t\t\theaders[:params] = params\n\t\tend\n\t\tresponse = RestClient.put(url, payload, headers)\n\t\thandle_response(response)\n\tend",
"def put(url, resource_name, options = {})\n build_response(resource_name) do\n connection.put do |req|\n req.url url\n req.body = options.to_json\n end\n end\n end",
"def _put(path, payload, isD2l = true)\n auth_uri = path\n auth_uri = create_authenticated_uri(path, 'PUT') if isD2l == true\n # Perform the put action, updating the data; Provide feedback to client.\n RestClient.put(auth_uri, payload.to_json, content_type: :json) do |response|\n case response.code\n when 200\n return nil if response == \"\"\n JSON.parse(response)\n # ap JSON.parse(response.body)\n else\n display_response_code(response.code)\n ap JSON.parse(response.body) if $debug\n end\n end\nend",
"def update_api_key(api_key_id, request)\n start.uri('/api/api-key')\n .url_segment(api_key_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .put()\n .go()\n end",
"def put(url)\n authsub_http_request(Net::HTTP::Put,url)\n end",
"def put(path, body, options = {})\n options[:body] = body\n json_request('PUT', path, options)\n end",
"def put(url, vars={})\n send_request url, vars, 'PUT'\n end",
"def put(url)\n response = access_token.put(url)\n if url =~ /.json$/\n JSON.parse(response.body)\n else\n response.body\n end\n end",
"def restHttpPut(id, data, format = @format, sessionId = @sessionId)\n # Validate SessionId is not nil\n assert(sessionId != nil, \"Session ID passed into PUT was nil\")\n\n urlHeader = makeUrlAndHeaders('put',id,sessionId,format)\n @res = RestClient.put(urlHeader[:url], data, urlHeader[:headers]){|response, request, result| response }\n\n puts(@res.code,@res.body,@res.raw_headers) if $SLI_DEBUG\nend",
"def put url, body, headers = {}\n http_request(url, Net::HTTP::Put, body, headers)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve facts from the target and return in a hash | def facts(_context)
{}
end | [
"def get_facts_hash\n fact_values = self.fact_values.find(:all, :include => :fact_name)\n return fact_values.inject({}) do | hash, value |\n hash[value.fact_name.name] ||= []\n hash[value.fact_name.name] << value\n hash\n end\n end",
"def facts(facts, nodequery, http = nil)\n if facts.empty?\n q = ['in', 'certname', ['extract', 'certname', ['select-facts', nodequery]]]\n else\n q = ['and', ['in', 'certname', ['extract', 'certname', ['select-facts', nodequery]]], ['or', *facts.collect { |f| ['=', 'name', f]}]]\n end\n facts = {}\n query(:facts, q, http).each do |fact|\n if facts.include? fact['certname']\n facts[fact['certname']][fact['name']] = fact['value']\n else\n facts[fact['certname']] = { fact['name'] => fact['value'] }\n end\n end\n facts\n end",
"def facts\n @facts ||= Puppet::Util::NetworkDevice::Cisco::Facts.new(transport)\n facts = {}\n command do |_ng|\n facts = @facts.retrieve\n end\n facts\n end",
"def fact_values\n Facter.to_hash\n end",
"def facts\n @facts\n end",
"def get_facts\r\n @facts\r\n end",
"def to_hash\n @facts.inject({}) do |h, ary|\n value = ary[1].value\n if ! value.nil?\n # For backwards compatibility, convert the fact name to a string.\n h[ary[0].to_s] = value\n end\n h\n end\n end",
"def populate_facts\n fact_data = hosts.inject({}) do |result, host|\n facts_raw = on host, \"facter -y\"\n facts = YAML.load(facts_raw.stdout)\n result[host.name] = facts\n result\n end\n\n test_config[:facts] = fact_data\n nil\n end",
"def facts_hash(facts)\n facts.reduce({}) do |ret, fact|\n if ret.include? fact['certname']\n ret[fact['certname']][fact['name']] = fact['value']\n else\n ret[fact['certname']] = { fact['name'] => fact['value'] }\n end\n ret\n end\n end",
"def facts\n @facts ||= compute_facts\n end",
"def find(request)\n return nil unless host = ar_model.find_by_name(request.key, :include => {:fact_values => :fact_name})\n\n facts = Puppet::Node::Facts.new(host.name)\n facts.values = host.get_facts_hash.inject({}) do |hash, ary|\n # Convert all single-member arrays into plain values.\n param = ary[0]\n values = ary[1].collect { |v| v.value }\n values = values[0] if values.length == 1\n hash[param] = values\n hash\n end\n\n facts\n end",
"def list\n load_all\n return @facts.keys\n end",
"def node_facts(certname)\n Puppet.debug(\"Querying PuppetDB for Facts for: #{certname}\")\n pql = ['from', 'facts',\n ['extract', ['name', 'value'],\n ['and',\n ['=', 'certname', certname],\n ['=', 'environment', @environment],\n ]\n ]\n ]\n results = query_puppetdb(pql)\n return nil if results.nil?\n Puppet.debug(results)\n facts = {}\n results.each do |fact, _nil|\n facts[fact['name']] = fact['value']\n end\n facts\n end",
"def list\n load_all\n @facts.keys\n end",
"def facts\n spin(facts_cpu_time, facts_wait_time)\n {}\n end",
"def facts\n logger.debug \"get complete data of all VMs in all datacenters: begin\"\n result = Hash[vm_mos_to_h(@vcenter.vms).map do |h|\n [h['name'], Hash[h.map { |k, v| [k.tr('.', '_'), v] }]]\n end]\n logger.debug \"get complete data of all VMs in all datacenters: end\"\n result\n end",
"def node_facts(certname)\n Puppet.debug(\"Querying PuppetDB for Facts for: #{certname}\")\n pql = ['from', 'facts',\n ['extract', ['name', 'value'],\n ['and',\n ['=', 'certname', certname],\n ['=', 'environment', @environment],\n ]\n ]\n ]\n results = query_puppetdb(pql)\n if results.nil?\n Puppet.debug('No result for PuppetDB Query')\n return nil\n end\n if results.empty?\n Puppet.debug('No results for PuppetDB Query')\n end\n Puppet.debug('Begin Query Results')\n Puppet.debug(results)\n Puppet.debug('End Query Results')\n facts = {}\n results.each do |fact, _nil|\n facts[fact['name']] = fact['value']\n end\n facts\n end",
"def facts_from_node(inventory_hash, node_name)\n facts = targets_in_inventory(inventory_hash) do |target|\n next unless target['uri'].casecmp(node_name).zero?\n\n target['facts'] unless target['facts'].nil?\n end\n\n facts.empty? ? nil : facts[0]\n end",
"def by_target\n targets.\n map { |t| [t.object, @matches[t].map { |m| m.candidate.object }] }.\n to_h.\n freeze\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /fixed_deposits/new GET /fixed_deposits/new.json | def new
@fixed_deposit = FixedDeposit.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @fixed_deposit }
end
end | [
"def new\n @fixed_deposit = FixedDeposit.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @fixed_deposit }\n end\n end",
"def new\n @ped = Ped.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ped }\n end\n end",
"def new\n @deltagere = Deltagere.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @deltagere }\n end\n end",
"def new\n @unsolved = Unsolved.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @unsolved }\n end\n end",
"def new\n @depot = Depot.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @depot }\n end\n end",
"def new\n @debt = Debt.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @debt }\n end\n end",
"def new\n @fixed_expense = FixedExpense.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @fixed_expense }\n end\n end",
"def new\n @fix_issue = FixIssue.new\n \n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @fix_issue }\n end\n end",
"def new\n @deposit_check = DepositCheck.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @deposit_check }\n end\n end",
"def new\n @title = t('view.funds.new_title')\n @fund = Fund.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fund }\n end\n end",
"def new\n @m_fix_item = MFixItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @m_fix_item }\n end\n end",
"def new\n @fix_upgrade = FixUpgrade.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fix_upgrade }\n end\n end",
"def new\n @undefind_fee = UndefindFee.new\n @departments = Department.all.collect { |d| [d.name, d.id] }\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @undefind_fee }\n end\n end",
"def new\n #@klass_fee = KlassFee.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @klass_fee }\n end\n end",
"def new\n @fornecedor = Fornecedor.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fornecedor }\n end\n end",
"def new\n doc_no = (RepairRecord.maximum(:doc_no).to_i || 0) + 1\n @repair_record = current_user.reported_repair_records.new(doc_no: doc_no)\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @repair_record }\n end\n end",
"def new\n @posizione = Posizione.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @posizione }\n end\n end",
"def new\n @workaround = Workaround.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @workaround }\n end\n end",
"def new\n @unpaid_debt = UnpaidDebt.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @unpaid_debt }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PUT /fixed_deposits/1 PUT /fixed_deposits/1.json | def update
@fixed_deposit = FixedDeposit.find(params[:id])
respond_to do |format|
if @fixed_deposit.update_attributes(params[:fixed_deposit])
format.html { redirect_to @fixed_deposit, notice: 'Fixed deposit was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @fixed_deposit.errors, status: :unprocessable_entity }
end
end
end | [
"def update\n respond_to do |format|\n if @fixed_deposit.update(fixed_deposit_params)\n format.html { redirect_to @fixed_deposit, notice: 'Fixed deposit was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @fixed_deposit.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @fixed_deposit = FixedDeposit.find(params[:id])\n\n respond_to do |format|\n if @fixed_deposit.update_attributes(params[:fixed_deposit])\n flash[:notice] = 'FixedDeposit was successfully updated.'\n format.html { redirect_to(@fixed_deposit) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @fixed_deposit.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @solideo_depense.update(solideo_depense_params)\n format.html { redirect_to solideo_depenses_path, notice: 'Solideo depense was successfully updated.' }\n format.json { render :show, status: :ok, location: @solideo_depense }\n else\n format.html { render :edit }\n format.json { render json: @solideo_depense.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @fixed_deposit = FixedDeposit.find(params[:id])\n @fixed_deposit.destroy\n\n respond_to do |format|\n format.html { redirect_to fixed_deposits_url }\n format.json { head :ok }\n end\n end",
"def update\n respond_to do |format|\n if @fixed_exp.update(fixed_exp_params)\n format.html { redirect_to @fixed_exp, notice: 'Fixed exp was successfully updated.' }\n format.json { render :show, status: :ok, location: @fixed_exp }\n else\n format.html { render :edit }\n format.json { render json: @fixed_exp.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @fixed_deposit.destroy\n respond_to do |format|\n format.html { redirect_to fixed_deposits_url }\n format.json { head :no_content }\n end\n end",
"def update\n respond_to do |format|\n if @marketing_fixed_expense.update(marketing_fixed_expense_params)\n format.html { redirect_to @marketing_fixed_expense, notice: 'Marketing fixed expense was successfully updated.' }\n format.json { render :show, status: :ok, location: @marketing_fixed_expense }\n else\n format.html { render :edit }\n format.json { render json: @marketing_fixed_expense.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_with Expense.update(params[:id], expense_params), status: 204\n end",
"def update\n @fixed_expense = FixedExpense.for_user(current_user).find(params[:id])\n\n respond_to do |format|\n if @fixed_expense.update_attributes(params[:fixed_expense])\n flash[:notice] = 'FixedExpense was successfully updated.'\n format.html { redirect_to(fixed_expenses_path) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @fixed_expense.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @sivic_discipulo.update(sivic_discipulo_params_netested)\n format.html { redirect_to @sivic_discipulo, notice: 'Registro alterado com sucesso.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @sivic_discipulo.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @depense.update(depense_params)\n format.html { redirect_to @depense, notice: 'Depense was successfully updated.' }\n format.json { render :show, status: :ok, location: @depense }\n else\n format.html { render :edit }\n format.json { render json: @depense.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @drive_fixed = DriveFixed.find(params[:id])\n if params[:sem_data_final]\n @drive_fixed.date_limit = nil\n end\n respond_to do |format|\n if @drive_fixed.update_attributes(params[:drive_fixed])\n flash[:notice] = 'DriveFixed was successfully updated.'\n format.html { redirect_to(@drive_fixed) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @drive_fixed.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def destroy\n @fixed_deposit = FixedDeposit.find(params[:id])\n @fixed_deposit.destroy\n\n respond_to do |format|\n format.html { redirect_to(fixed_deposits_url) }\n format.xml { head :ok }\n end\n end",
"def update\n @unsolved = Unsolved.find(params[:id])\n\n respond_to do |format|\n if @unsolved.update_attributes(params[:unsolved])\n format.html { redirect_to @unsolved, notice: 'Unsolved was successfully updated.' }\n format.json { head :no_content }\n end\n end\n end",
"def update\n opts = {\n desc: params[:desc] || @deed.desc,\n points: params[:points] || @deed.points\n }\n if @deed.update(opts)\n render json: opts, status: :ok, location: @deed\n else\n render json: @deed.errors, status: :unprocessable_entity\n end\n end",
"def update\n if @debt.update(params.permit(:quantity, :description))\n render json: @debt \n else\n\t\t\t\trender json: @debt.errors, status: :unprocessable_entity\n end\n end",
"def update\r\n respond_to do |format|\r\n if @fixed_deposit_investment.update(fixed_deposit_investment_params)\r\n format.html { redirect_to @fixed_deposit_investment, notice: 'Fixed deposit investment was successfully updated.' }\r\n format.json { render :show, status: :ok, location: @fixed_deposit_investment }\r\n else\r\n format.html { render :edit }\r\n format.json { render json: @fixed_deposit_investment.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def update\n respond_to do |format|\n if @what_fixed_to_do.update(what_fixed_to_do_params)\n format.html { redirect_to @what_fixed_to_do, notice: 'What fixed to do was successfully updated.' }\n format.json { render :show, status: :ok, location: @what_fixed_to_do }\n else\n format.html { render :edit }\n format.json { render json: @what_fixed_to_do.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n resource.update(deposit_contract_params)\n respond_with client, resource\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /fixed_deposits/1 DELETE /fixed_deposits/1.json | def destroy
@fixed_deposit = FixedDeposit.find(params[:id])
@fixed_deposit.destroy
respond_to do |format|
format.html { redirect_to fixed_deposits_url }
format.json { head :ok }
end
end | [
"def destroy\n @fixed_deposit.destroy\n respond_to do |format|\n format.html { redirect_to fixed_deposits_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @fixed_deposit = FixedDeposit.find(params[:id])\n @fixed_deposit.destroy\n\n respond_to do |format|\n format.html { redirect_to(fixed_deposits_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @deposit.destroy\n respond_to do |format|\n format.html { redirect_to deposits_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @core_fiel_depositario = Core::FielDepositario.find(params[:id])\n @core_fiel_depositario.destroy\n\n respond_to do |format|\n format.html { redirect_to core_fiel_depositarios_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ref_consult_request = RefConsultRequest.find(params[:id])\n @ref_consult_request.destroy\n\n respond_to do |format|\n format.html { redirect_to ref_consult_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @direct_deposit = DirectDeposit.find(params[:id])\n @direct_deposit.destroy\n\n respond_to do |format|\n format.html { redirect_to direct_deposits_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @dbs_deposit = DbsDeposit.find(params[:id])\n @dbs_deposit.destroy\n\n respond_to do |format|\n format.html { redirect_to(dbs_deposits_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @fixed_exp.destroy\n respond_to do |format|\n format.html { redirect_to fixed_exps_url, notice: 'Fixed exp was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_debt.destroy\n respond_to do |format|\n format.html { redirect_to line_debts_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @expense_entry = ExpenseEntry.with_deleted.find(params[:id])\n @expense_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to expense_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @config_loterica_deposit.destroy\n respond_to do |format|\n format.html { redirect_to config_loterica_deposits_url, notice: 'Config loterica deposit was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\r\n @fixed_deposit_investment.destroy\r\n respond_to do |format|\r\n format.html { redirect_to fixed_deposit_investments_url, notice: 'Fixed deposit investment was successfully destroyed.' }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @factura_distribuidor = FacturaDistribuidor.find(params[:id])\n @factura_distribuidor.destroy\n\n respond_to do |format|\n format.html { redirect_to facturas_distribuidores_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @sword_deposit.destroy\n respond_to do |format|\n format.html { redirect_to sword_deposits_url, notice: 'Sword deposit was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @deposit_check = DepositCheck.find(params[:id])\n @deposit_check.destroy\n\n respond_to do |format|\n format.html { redirect_to deposit_checks_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @deposit.destroy\n respond_to do |format|\n format.html { redirect_to deposits_url, notice: \"Deposit was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @solideo_depense.destroy\n respond_to do |format|\n format.html { redirect_to solideo_depenses_url, notice: 'Solideo depense was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @client_fee.destroy\n respond_to do |format|\n format.html { redirect_to client_fees_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @marketing_fixed_expense.destroy\n respond_to do |format|\n format.html { redirect_to marketing_fixed_expenses_url, notice: 'Marketing fixed expense was successfully destroyed.' }\n format.json { head :no_content }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /ruolis GET /ruolis.json | def index
@ruolis = Ruoli.all
end | [
"def index\n @ruas = Rua.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ruas }\n end\n end",
"def show\n @rua = Rua.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @rua }\n end\n end",
"def show\n @ruku = Ruku.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ruku }\n end\n end",
"def index\n @ramais = Ramal.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ramais }\n end\n end",
"def index\n @rumors = Rumor.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @rumors }\n end\n end",
"def index\n @uchronias = Uchronia.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @uchronias }\n end\n end",
"def index\n @uchronists = Uchronist.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @uchronists }\n end\n end",
"def index\n @lesuurs = Lesuur.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @lesuurs }\n end\n end",
"def show\n @lure = Lure.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lure }\n end\n end",
"def index \n usuario = current_user\n usuario_id = usuario.id\n user = User.find(usuario_id)\n @rubis = user.rubis\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @rubis.to_json(:methods => [:rubi_props], :only => [:rubi_props])}\n end\n end",
"def index\n @roofs = Roof.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @roofs }\n end\n end",
"def show\n @uchronia = Uchronia.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @uchronia }\n end\n end",
"def index\n @universes = Universe.all.page(params[:page]).per(25)\n respond_to do |format|\n format.html\n format.json { render json: @universes }\n end\n end",
"def index\n @rola = find_rola\n @rolarticulos = @rola.rolarticulos\n\n respond_to do |format|\n format.html # index.html.erb\n #format.json { render json: @rolarticulos }\n end\n end",
"def index\n @lemurs = Lemur.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @lemurs }\n end\n end",
"def index\n @interno_unidads = InternoUnidad.all\n render json: @interno_unidads\n end",
"def index\n @riesgos = Riesgo.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @riesgos }\n end\n end",
"def index\n @uranais = Uranai.all\n end",
"def show\n @uchronist = Uchronist.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @uchronist }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /questions/new GET /questions/new.xml | def new
@new_question = Question.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @question }
end
end | [
"def new\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render xml: @question }\n end\n end",
"def new\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question }\n end\n end",
"def new_rest\n @entry_question = EntryQuestion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @entry_question }\n end\n end",
"def new\n @question = @page.questions.new\n session[:breadcrumbs].add \"New\"\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question }\n end\n end",
"def new_rest\n @question_localized = QuestionLocalized.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question_localized }\n end\n end",
"def new\n @quest = Quest.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @quest }\n end\n end",
"def new\n @question = Question.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @admin_question }\n end\n end",
"def new\n @question_topic = QuestionTopic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question_topic }\n end\n end",
"def new\n @differentiator_question = DifferentiatorQuestion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @differentiator_question }\n end\n end",
"def new\n @question_response = QuestionResponse.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question_response }\n end\n end",
"def new\n @quest_template = QuestTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @quest_template }\n end\n end",
"def new\n @questionnaire = Questionnaire.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @questionnaire }\n end\n end",
"def new\n @question_list = QuestionList.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question_list }\n end\n end",
"def new\n @survey_question = SurveyQuestion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @survey_question }\n end\n end",
"def new\n @poll_question = PollQuestion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @poll_question }\n end\n end",
"def new\n @question = Question.find(params[:question_id])\n @answer = @question.answers.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @answer }\n end\n end",
"def new\n @question_attribute = QuestionAttribute.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @question_attribute }\n end\n end",
"def new \n @how_to = HowTo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render xml: @how_to }\n end\n end",
"def new\n @qa = Qa.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @qa }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API retrieves a list of summary information about a subset of the products matching a given product line ID. | def find_by_productline(productline_id)
@request = setup_request "#{@@resource_url}s"
@request.query = { productLineId: productline_id }
@request
end | [
"def find(productline_id)\n setup_request \"#{@@resource_url}/#{productline_id}\"\n end",
"def show\n @line_item_products = LineItemProduct.all\n end",
"def index\n @product_lines = ProductLine.all\n end",
"def index\n @products_lines = ProductsLine.all\n end",
"def find_summaries_by_ids(ids)\n @request = setup_request \"#{@@resource_url}s\"\n @request.query = { productLineIds: ids.to_s }\n @request\n end",
"def show\n @product_line = ProductLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @product_line }\n end\n end",
"def get_stats(product_id)\n request_path = \"/products/#{product_id}/stats\"\n return RestClient.get(@api+request_path)\n end",
"def products_get_product_purchases product_id, page: nil, per_page: nil\n # the base uri for api requests\n query_builder = Configuration.BASE_URI.dup\n\n # prepare query string for API call\n query_builder << \"/v1/products/{product_id}/purchases\"\n\n # process optional query parameters\n query_builder = APIHelper.append_url_with_template_parameters query_builder, {\n \"product_id\" => product_id,\n }\n\n # process optional query parameters\n query_builder = APIHelper.append_url_with_query_parameters query_builder, {\n \"page\" => page,\n \"per_page\" => per_page,\n \"client_id\" => @client_id,\n \"client_secret\" => @client_secret,\n }\n\n # validate and preprocess url\n query_url = APIHelper.clean_url query_builder\n\n # prepare headers\n headers = {\n \"user-agent\" => \"IAMDATA V1\",\n \"accept\" => \"application/json\"\n }\n\n # invoke the API call request to fetch the response\n response = Unirest.get query_url, headers:headers\n\n # Error handling using HTTP status codes\n if response.code == 404\n raise APIException.new \"Not found\", 404, response.raw_body\n elsif response.code == 401\n raise APIException.new \"Unauthorized\", 401, response.raw_body\n elsif !(response.code.between?(200,206)) # [200,206] = HTTP OK\n raise APIException.new \"HTTP Response Not OK\", response.code, response.raw_body\n end\n\n response.body\n end",
"def show\n @line_product = LineProduct.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_product }\n end\n end",
"def show\n @productline = Productline.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @productline }\n end\n end",
"def get_order_lines_by_product_id(product_id)\n @order_lines_by_product_id = @db.execute(\"SELECT * FROM Order_details WHERE product_id = #{product_id}\")\n return @order_lines_by_product_id\n end",
"def get_product_info(product_id)\n run_command :get_product_info, :trust_service, {\n :product_id => product_id,\n :key => 'attributes'\n }\n end",
"def show\n @product_line = ProductLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @product_line }\n end\n end",
"def all(product_id, params = {})\n response, status = BeyondApi::Request.get(@session, \"/products/#{product_id}/variations\", params)\n\n handle_response(response, status)\n end",
"def show_plannable_products(reach_plan_service)\n response = reach_plan_service.list_plannable_products(\n plannable_location_id: LOCATION_ID,\n )\n\n puts \"Plannable Products for Location ID #{LOCATION_ID}:\"\n\n response.product_metadata.each do |product|\n puts \"#{product.plannable_product_code}:\"\n puts \"Age Ranges:\"\n product.plannable_targeting.age_ranges.each do |age_range|\n puts \"\\t- #{age_range}\"\n end\n puts \"Genders:\"\n product.plannable_targeting.genders.each do |gender|\n puts \"\\t- #{gender.type}\"\n end\n puts \"Devices:\"\n product.plannable_targeting.devices.each do |device|\n puts \"\\t- #{device.type}\"\n end\n end\nend",
"def show\n @shop_line_item = current_shop_order.line_items.find(params[:id])\n attr_hash = {\n :include => :product,\n :only => [:id, :quantity]\n }\n \n respond_to do |format|\n format.html { render }\n format.js { render :partial => '/shop/line_items/line_item', :locals => { :line_item => @shop_line_item } }\n format.xml { render :xml => @shop_line_item.to_xml(attr_hash) }\n format.json { render :json => @shop_line_item.to_json(attr_hash) }\n end\n end",
"def show\n @price_list = PriceList.find(params[:price_list_id])\n @price_list_line = ProductPrice.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @price_list_line }\n end\n end",
"def getProduct( product_id)\n params = Hash.new\n params['product_id'] = product_id\n return doCurl(\"get\",\"/product\",params)\n end",
"def view_product\n to_json(\n only: [:id, :title, :description, :key_information],\n methods: [:photo_url, :net_mrp, :mrp_per_unit, :quantity],\n :include => {\n store: {\n only: [:name, :id],\n methods: [:full_address]\n }\n }\n )\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the multirange type input string into a PGMultiRange value. | def parse
raise Sequel::Error, "invalid multirange, doesn't start with {" unless get_byte == '{'
ranges = []
unless scan(/\}/)
while true
raise Sequel::Error, "unfinished multirange" unless range_string = scan_until(/[\]\)]/)
ranges << @converter.call(range_string)
case sep = get_byte
when '}'
break
when ','
# nothing
else
raise Sequel::Error, "invalid multirange separator: #{sep.inspect}"
end
end
end
raise Sequel::Error, "invalid multirange, remaining data after }" unless eos?
ranges
end | [
"def call(string)\n PGMultiRange.new(Parser.new(string, @converter).parse, @type)\n end",
"def parse_range\n args[:range] = true\n str = clean_param(leave_slashes: true)\n return args[:default] if str.blank?\n\n match = str.match(/^((\\\\.|[^\\\\-]+)+)-((\\\\.|[^\\\\-]+)+)$/)\n if match\n @val = match[1]\n from = parse_scalar\n @val = match[3]\n to = parse_scalar\n else\n from = to = parse_scalar\n end\n ordered_range(from, to)\n end",
"def typecast_value_pg_multirange(value, creator, scalar_typecast_method=nil)\n case value\n when PGMultiRange\n return value if value.db_type == creator.type\n when Array\n # nothing\n else\n raise Sequel::InvalidValue, \"invalid value for multirange type: #{value.inspect}\"\n end\n\n if scalar_typecast_method && respond_to?(scalar_typecast_method, true)\n value = value.map{|v| send(scalar_typecast_method, v)}\n end\n PGMultiRange.new(value, creator.type)\n end",
"def parse_range(string, type)\n range = case string\n when /\\A(.+?)\\.\\.\\.(.+)/ # A...B\n lo, hi = [parse_cast($1, type), parse_cast($2, type)].sort\n [:between, (lo...hi)]\n when /\\A(.+?)\\.\\.(.+)/\n lo, hi = [parse_cast($1, type), parse_cast($2, type)].sort\n [:between, (lo..hi)]\n when /\\A<=(.+)/, /\\A\\.\\.(.+)/\n [:lteq, parse_cast($1, type)]\n when /\\A<(.+)/\n [:lt, parse_cast($1, type)]\n when /\\A>=(.+)/, /\\A(.+)\\.\\.\\Z/\n [:gteq, parse_cast($1, type)]\n when /\\A>(.+)/\n [:gt, parse_cast($1, type)]\n when /[, ]/\n [:in, string.split(/[, ]+/).map {|x| parse_cast(x, type)}]\n when \"any\"\n [:not_eq, nil]\n when \"none\"\n [:eq, nil]\n else\n # add a 5% tolerance for float and filesize values\n if type == :float || (type == :filesize && string =~ /[km]b?\\z/i)\n value = parse_cast(string, type)\n [:between, (value * 0.95..value * 1.05)]\n elsif type.in?([:date, :age])\n value = parse_cast(string, type)\n [:between, (value.beginning_of_day..value.end_of_day)]\n else\n [:eq, parse_cast(string, type)]\n end\n end\n\n range = reverse_range(range) if type == :age\n range\n end",
"def parse_range(range)\n unless range.is_a? Range\n range = range.to_s.split '..'\n range = ((range.size == 1) ? '' : range.first)..range.last\n end\n\n range = id_for_ref(range.first)..range.last if range.first != ''\n range.first..id_for_ref(range.last)\n end",
"def typecast_value_pg_range(value, parser)\n case value\n when PGRange\n if value.db_type.to_s == parser.db_type\n value\n elsif value.empty?\n PGRange.empty(parser.db_type)\n else\n PGRange.new(value.begin, value.end, :exclude_begin=>value.exclude_begin?, :exclude_end=>value.exclude_end?, :db_type=>parser.db_type)\n end\n when Range\n PGRange.from_range(value, parser.db_type)\n when String\n parser.call(typecast_check_string_length(value, 100))\n else\n raise Sequel::InvalidValue, \"invalid value for range type: #{value.inspect}\"\n end\n end",
"def parse_range_value(value)\r\n value << nil if value.kind_of?(Array) && value.length == 1\r\n value = [value, nil] if (value.kind_of?(String) || !value.respond_to?(:first))\r\n value\r\n end",
"def parse_normal_range\n if self.normal_range.include?(\"-\")\n @value_min, @value_max = self.normal_range.split(\"-\")\n @value_min = @value_min.to_f\n @value_max = @value_max.to_f\n elsif index = self.normal_range.index(\"<\")\n @value_min = 0\n index ||= self.normal_range.index(\"=\")\n index += 1\n @value_max = self.normal_range[index..-1].to_f\n elsif index = self.normal_range.index(\">\")\n index ||= self.normal_range.index(\"=\")\n index += 1\n @value_min = self.normal_range[index..-1].to_f\n @value_max = Float::INFINITY\n end\n end",
"def parse_array(parse_scalar_or_range)\n args[:list] = true\n str = clean_param(leave_slashes: true)\n return args[:default] if str.blank?\n\n result = []\n while (match = str.match(/^((\\\\.|[^\\\\,]+)+),/))\n str = match.post_match\n @val = match[1]\n result << send(parse_scalar_or_range)\n end\n @val = str\n result << send(parse_scalar_or_range)\n end",
"def parse_range(str)\n ends = str.split(':')\n if ends.empty?\n nil\n elsif ends.length < 2\n (ends[0].to_i..ends[0].to_i)\n else\n (ends[0].to_i..ends[1].to_i)\n end\nend",
"def parse_media_range(thing)\n snippets = thing.split(Utils::SEMICOLON_SPLITTER)\n raise ArgumentError, \"Malformed MIME-Type: #{thing}\" unless MEDIA_RANGE_REGEX === snippets.shift\n\n type = $1\n subtype = $2\n type.downcase!\n subtype.downcase!\n\n raise ArgumentError,\n \"Malformed MIME-Type: #{thing}\" if type == Const::WILDCARD && subtype != Const::WILDCARD\n\n params = {}\n snippets.each do |pair|\n pair.strip!\n k,v = pair.split(Utils::PAIR_SPLITTER,2)\n k.downcase!\n params[k] = v\n end\n\n [type, subtype, params]\n end",
"def parse_allowed_value_range(state_variable)\n range = state_variable.at 'allowedValueRange'\n\n return nil unless range\n\n minimum = range.at 'minimum'\n maximum = range.at 'maximum'\n step = range.at 'step'\n\n range = [minimum, maximum]\n range << step if step\n\n range.map do |value|\n value = value.text\n value =~ /\\./ ? Float(value) : Integer(value)\n end\n end",
"def register_multirange_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:range_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_multirange_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngmultitypid).where(:typname=>db_type.to_s).get([:rngmultitypid, :rngtypid])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :range_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :range_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n raise Error, \"cannot add a multirange type without a convertor (use :converter or :range_oid option or pass block)\" unless converter\n creator = Creator.new(db_type, converter)\n add_conversion_proc(oid, creator)\n\n @pg_multirange_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n scalar_typecast_method = :\"typecast_value_#{opts.fetch(:scalar_typecast, db_type.sub('multirange', 'range'))}\"\n define_method(meth){|v| typecast_value_pg_multirange(v, creator, scalar_typecast_method)}\n private meth\n end\n\n @schema_type_classes[db_type] = PGMultiRange\n nil\n end",
"def string_to_range\n my_temp_range = file[2].delete(\"(\" \")\").split(\", \")\n my_temp_range.map! {|element| element.to_i}\n\n my_temp_range[0]..my_temp_range[1]\n end",
"def parse_range_params(params)\n params.split(';').inject({}) do |m, p|\n k, v = p.split('=', 2)\n m[k] = v if v\n m\n end\n end",
"def parse_range(str)\n delimiters = str.split(/\\.+|-+/)\n r_start, r_end = delimiters[0], delimiters[1]\n # TODO assumes even number pairs for creating a range\n range = r_start.to_i..r_end.to_i\n file_list = []\n range.each do |n|\n file_list << n.to_s\n end\n return file_list\n end",
"def schema_multirange_type(db_type)\n :multirange\n end",
"def do_parse_range(method, key, args={}, &block)\n declare_parameter(key, method, args)\n str = get_param(key, :leave_slashes) or return args[:default]\n args[:range] = true\n if str.match(/^((\\\\.|[^-]+)+)-((\\\\.|[^-]+)+)$/)\n val1, val2 = $1, $3\n return Range.new(send(method, val1, args, &block), send(method, val2, args, &block), args[:leave_order])\n else\n return send(method, str, args, &block)\n end\n end",
"def str_range(str)\n split = str.split(\",\")\n minimum = split.min.to_i\n maximum = split.max.to_i\n range = maximum - minimum\n return range\nend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the string using Parser with the appropriate converter, and return a PGMultiRange with the appropriate database type. | def call(string)
PGMultiRange.new(Parser.new(string, @converter).parse, @type)
end | [
"def parse\n raise Sequel::Error, \"invalid multirange, doesn't start with {\" unless get_byte == '{'\n ranges = []\n\n unless scan(/\\}/)\n while true\n raise Sequel::Error, \"unfinished multirange\" unless range_string = scan_until(/[\\]\\)]/)\n ranges << @converter.call(range_string)\n \n case sep = get_byte\n when '}'\n break\n when ','\n # nothing\n else\n raise Sequel::Error, \"invalid multirange separator: #{sep.inspect}\"\n end\n end\n end\n\n raise Sequel::Error, \"invalid multirange, remaining data after }\" unless eos?\n ranges\n end",
"def typecast_value_pg_range(value, parser)\n case value\n when PGRange\n if value.db_type.to_s == parser.db_type\n value\n elsif value.empty?\n PGRange.empty(parser.db_type)\n else\n PGRange.new(value.begin, value.end, :exclude_begin=>value.exclude_begin?, :exclude_end=>value.exclude_end?, :db_type=>parser.db_type)\n end\n when Range\n PGRange.from_range(value, parser.db_type)\n when String\n parser.call(typecast_check_string_length(value, 100))\n else\n raise Sequel::InvalidValue, \"invalid value for range type: #{value.inspect}\"\n end\n end",
"def typecast_value_pg_multirange(value, creator, scalar_typecast_method=nil)\n case value\n when PGMultiRange\n return value if value.db_type == creator.type\n when Array\n # nothing\n else\n raise Sequel::InvalidValue, \"invalid value for multirange type: #{value.inspect}\"\n end\n\n if scalar_typecast_method && respond_to?(scalar_typecast_method, true)\n value = value.map{|v| send(scalar_typecast_method, v)}\n end\n PGMultiRange.new(value, creator.type)\n end",
"def parse_range(string, type)\n range = case string\n when /\\A(.+?)\\.\\.\\.(.+)/ # A...B\n lo, hi = [parse_cast($1, type), parse_cast($2, type)].sort\n [:between, (lo...hi)]\n when /\\A(.+?)\\.\\.(.+)/\n lo, hi = [parse_cast($1, type), parse_cast($2, type)].sort\n [:between, (lo..hi)]\n when /\\A<=(.+)/, /\\A\\.\\.(.+)/\n [:lteq, parse_cast($1, type)]\n when /\\A<(.+)/\n [:lt, parse_cast($1, type)]\n when /\\A>=(.+)/, /\\A(.+)\\.\\.\\Z/\n [:gteq, parse_cast($1, type)]\n when /\\A>(.+)/\n [:gt, parse_cast($1, type)]\n when /[, ]/\n [:in, string.split(/[, ]+/).map {|x| parse_cast(x, type)}]\n when \"any\"\n [:not_eq, nil]\n when \"none\"\n [:eq, nil]\n else\n # add a 5% tolerance for float and filesize values\n if type == :float || (type == :filesize && string =~ /[km]b?\\z/i)\n value = parse_cast(string, type)\n [:between, (value * 0.95..value * 1.05)]\n elsif type.in?([:date, :age])\n value = parse_cast(string, type)\n [:between, (value.beginning_of_day..value.end_of_day)]\n else\n [:eq, parse_cast(string, type)]\n end\n end\n\n range = reverse_range(range) if type == :age\n range\n end",
"def parse(str)\n # defined in ext/rdo_postgres/arrays.c\n end",
"def register_multirange_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:range_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_multirange_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngmultitypid).where(:typname=>db_type.to_s).get([:rngmultitypid, :rngtypid])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :range_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :range_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n raise Error, \"cannot add a multirange type without a convertor (use :converter or :range_oid option or pass block)\" unless converter\n creator = Creator.new(db_type, converter)\n add_conversion_proc(oid, creator)\n\n @pg_multirange_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n scalar_typecast_method = :\"typecast_value_#{opts.fetch(:scalar_typecast, db_type.sub('multirange', 'range'))}\"\n define_method(meth){|v| typecast_value_pg_multirange(v, creator, scalar_typecast_method)}\n private meth\n end\n\n @schema_type_classes[db_type] = PGMultiRange\n nil\n end",
"def parse_range\n args[:range] = true\n str = clean_param(leave_slashes: true)\n return args[:default] if str.blank?\n\n match = str.match(/^((\\\\.|[^\\\\-]+)+)-((\\\\.|[^\\\\-]+)+)$/)\n if match\n @val = match[1]\n from = parse_scalar\n @val = match[3]\n to = parse_scalar\n else\n from = to = parse_scalar\n end\n ordered_range(from, to)\n end",
"def call(string)\n PGArray.new(Parser.new(string, @converter).parse, @type)\n end",
"def schema_multirange_type(db_type)\n :multirange\n end",
"def _parse(string, type, options={})\n options.reverse_merge!(:strict => true)\n\n sets = if options[:format]\n options[:strict] = true\n [ send(\"#{type}_expressions\").assoc(options[:format]) ]\n else\n expression_set(type, string)\n end\n\n set = sets.find do |format, regexp|\n string =~ wrap_regexp(regexp, type, options[:strict])\n end\n\n if set\n last = options[:include_offset] ? 8 : 7\n values = send(:\"format_#{set[0]}\", *$~[1..last])\n values[0..2] = ValidatesTimeliness.dummy_date_for_time_type if type == :time\n return values\n end\n rescue\n nil\n end",
"def parse(string, type, options={})\n return string unless string.is_a?(String)\n options.reverse_merge!(:strict => true)\n\n sets = if options[:format]\n options[:strict] = true\n [ send(\"#{type}_expressions\").assoc(options[:format]) ]\n else\n expression_set(type, string)\n end\n\n matches = nil\n processor = sets.each do |format, regexp, proc|\n full = /\\A#{regexp}\\Z/ if options[:strict]\n full ||= case type\n when :date then /\\A#{regexp}/\n when :time then /#{regexp}\\Z/\n when :datetime then /\\A#{regexp}\\Z/\n end\n break(proc) if matches = full.match(string.strip)\n end\n last = options[:include_offset] ? 8 : 7\n if matches\n values = processor.call(*matches[1..last]) \n values[0..2] = dummy_date_for_time_type if type == :time\n return values\n end\n end",
"def parse_range(str)\n delimiters = str.split(/\\.+|-+/)\n r_start, r_end = delimiters[0], delimiters[1]\n # TODO assumes even number pairs for creating a range\n range = r_start.to_i..r_end.to_i\n file_list = []\n range.each do |n|\n file_list << n.to_s\n end\n return file_list\n end",
"def schema_range_type(db_type)\n :range\n end",
"def register_range_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:subtype_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_range_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngtypid).where(:typname=>db_type.to_s).get([:rngtypid, :rngsubtype])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :subtype_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :subtype_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n parser = Parser.new(db_type, converter)\n add_conversion_proc(oid, parser)\n\n @pg_range_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n define_method(meth){|v| typecast_value_pg_range(v, parser)}\n private meth\n end\n\n @schema_type_classes[:\"#{opts[:type_symbol] || db_type}\"] = PGRange\n nil\n end",
"def parse_range(range)\n unless range.is_a? Range\n range = range.to_s.split '..'\n range = ((range.size == 1) ? '' : range.first)..range.last\n end\n\n range = id_for_ref(range.first)..range.last if range.first != ''\n range.first..id_for_ref(range.last)\n end",
"def parse_range(str)\n ends = str.split(':')\n if ends.empty?\n nil\n elsif ends.length < 2\n (ends[0].to_i..ends[0].to_i)\n else\n (ends[0].to_i..ends[1].to_i)\n end\nend",
"def parse_array(parse_scalar_or_range)\n args[:list] = true\n str = clean_param(leave_slashes: true)\n return args[:default] if str.blank?\n\n result = []\n while (match = str.match(/^((\\\\.|[^\\\\,]+)+),/))\n str = match.post_match\n @val = match[1]\n result << send(parse_scalar_or_range)\n end\n @val = str\n result << send(parse_scalar_or_range)\n end",
"def date_range_parser(query_string)\n begin\n start_date, end_date = query_string.split(\"to\").map { |date_str| date_str.strip! }. map { |date_str| Date.parse(date_str) }\n rescue\n raise ArgumentError, \"unable to parse date\"\n end\n raise ArgumentError, \"end date must be on or after begin date\" if end_date < start_date\n [start_date, end_date]\n end",
"def parse_media_range(thing)\n snippets = thing.split(Utils::SEMICOLON_SPLITTER)\n raise ArgumentError, \"Malformed MIME-Type: #{thing}\" unless MEDIA_RANGE_REGEX === snippets.shift\n\n type = $1\n subtype = $2\n type.downcase!\n subtype.downcase!\n\n raise ArgumentError,\n \"Malformed MIME-Type: #{thing}\" if type == Const::WILDCARD && subtype != Const::WILDCARD\n\n params = {}\n snippets.each do |pair|\n pair.strip!\n k,v = pair.split(Utils::PAIR_SPLITTER,2)\n k.downcase!\n params[k] = v\n end\n\n [type, subtype, params]\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle PGMultiRange values in bound variables | def bound_variable_arg(arg, conn)
case arg
when PGMultiRange
arg.unquoted_literal(schema_utility_dataset)
else
super
end
end | [
"def bound_variable_arg(arg, conn)\n case arg\n when PGRange \n arg.unquoted_literal(schema_utility_dataset)\n when Range\n PGRange.from_range(arg).unquoted_literal(schema_utility_dataset)\n else\n super\n end\n end",
"def typecast_value_pg_multirange(value, creator, scalar_typecast_method=nil)\n case value\n when PGMultiRange\n return value if value.db_type == creator.type\n when Array\n # nothing\n else\n raise Sequel::InvalidValue, \"invalid value for multirange type: #{value.inspect}\"\n end\n\n if scalar_typecast_method && respond_to?(scalar_typecast_method, true)\n value = value.map{|v| send(scalar_typecast_method, v)}\n end\n PGMultiRange.new(value, creator.type)\n end",
"def bound_variable_arg(arg, conn)\n case arg\n when PGArray\n bound_variable_array(arg.to_a)\n when Array\n bound_variable_array(arg)\n else\n super\n end\n end",
"def bound_variable_array(arg)\n case arg\n when Sequel::Model\n \"\\\"(#{arg.values.values_at(*arg.columns).map{|v| bound_variable_array(v)}.join(',').gsub(/(\"|\\\\)/, '\\\\\\\\\\1')})\\\"\"\n else\n super\n end\n end",
"def typecast_value_pg_range(value, parser)\n case value\n when PGRange\n if value.db_type.to_s == parser.db_type\n value\n elsif value.empty?\n PGRange.empty(parser.db_type)\n else\n PGRange.new(value.begin, value.end, :exclude_begin=>value.exclude_begin?, :exclude_end=>value.exclude_end?, :db_type=>parser.db_type)\n end\n when Range\n PGRange.from_range(value, parser.db_type)\n when String\n parser.call(typecast_check_string_length(value, 100))\n else\n raise Sequel::InvalidValue, \"invalid value for range type: #{value.inspect}\"\n end\n end",
"def bound_variable_arg(arg, conn)\n case arg\n when ArrayRow\n \"(#{arg.map{|v| bound_variable_array(v) if v}.join(',')})\"\n when HashRow\n arg.check_columns!\n \"(#{arg.values_at(*arg.columns).map{|v| bound_variable_array(v) if v}.join(',')})\"\n else\n super\n end\n end",
"def process_field_range(forall)\n forall.range = range_from_field(forall.range)\n process_forall_statement(forall)\n end",
"def bound_variable_arg(arg, conn)\n case arg\n when Sequel::Model\n \"(#{arg.values.values_at(*arg.columns).map{|v| bound_variable_array(v)}.join(',')})\"\n else\n super\n end\n end",
"def input_expression_ranges=(_arg0); end",
"def value_source_range; end",
"def register_multirange_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:range_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_multirange_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngmultitypid).where(:typname=>db_type.to_s).get([:rngmultitypid, :rngtypid])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :range_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :range_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n raise Error, \"cannot add a multirange type without a convertor (use :converter or :range_oid option or pass block)\" unless converter\n creator = Creator.new(db_type, converter)\n add_conversion_proc(oid, creator)\n\n @pg_multirange_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n scalar_typecast_method = :\"typecast_value_#{opts.fetch(:scalar_typecast, db_type.sub('multirange', 'range'))}\"\n define_method(meth){|v| typecast_value_pg_multirange(v, creator, scalar_typecast_method)}\n private meth\n end\n\n @schema_type_classes[db_type] = PGMultiRange\n nil\n end",
"def assignRowRange(rowRange,valueArray)\n end",
"def input_expression_ranges; end",
"def quote_range(value)\n \"#{quote_value(value.first)} AND #{quote_value(value.last)}\"\n end",
"def schema_range_type(db_type)\n :range\n end",
"def one_index_range(range); end",
"def ranges(flat_args)\n ranges = stringify_range_bounds flat_args.select(&Range.method(:===))\n ranges = remove_subranges explode_multi_case_ranges ranges\n\n merge_ranges(ranges.select(&method(:numeric_range?))) +\n merge_ranges(ranges.select(&method(:character_range?)))\n end",
"def query_for_range(relation, attribute, range)\n relation.where(<<-SQL)\n people.#{attribute} BETWEEN '#{range.min}' AND '#{range.max}'\n OR (\n people.#{attribute} is null\n AND rms_people.#{attribute} BETWEEN '#{range.min}' AND '#{range.max}'\n )\n SQL\n end",
"def selection_range_provider; end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Freeze the pg multirange schema types to prevent adding new ones. | def freeze
@pg_multirange_schema_types.freeze
super
end | [
"def freeze\n @pg_range_schema_types.freeze\n super\n end",
"def schema_multirange_type(db_type)\n @pg_multirange_schema_types[db_type] || super\n end",
"def freeze\n @pg_array_schema_types.freeze\n super\n end",
"def schema_multirange_type(db_type)\n :multirange\n end",
"def schema_range_type(db_type)\n @pg_range_schema_types[db_type] || super\n end",
"def freeze\n @pg_typecast_on_load_columns.freeze\n\n super\n end",
"def freeze\n @typecast_on_load_columns.freeze\n\n super\n end",
"def freeze\n @get_column_conflicts.freeze\n @set_column_conflicts.freeze\n\n super\n end",
"def freeze\n @row_types.freeze\n @row_schema_types.freeze\n @row_type_method_module.freeze\n super\n end",
"def reset_schema_dsl!\n type_methods.each { |tm| remove_method tm }\n @registered_types = DEFAULT_TYPES.dup\n define_schema_dsl!\n end",
"def register_multirange_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:range_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_multirange_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngmultitypid).where(:typname=>db_type.to_s).get([:rngmultitypid, :rngtypid])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :range_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :range_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n raise Error, \"cannot add a multirange type without a convertor (use :converter or :range_oid option or pass block)\" unless converter\n creator = Creator.new(db_type, converter)\n add_conversion_proc(oid, creator)\n\n @pg_multirange_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n scalar_typecast_method = :\"typecast_value_#{opts.fetch(:scalar_typecast, db_type.sub('multirange', 'range'))}\"\n define_method(meth){|v| typecast_value_pg_multirange(v, creator, scalar_typecast_method)}\n private meth\n end\n\n @schema_type_classes[db_type] = PGMultiRange\n nil\n end",
"def sorted_schema_check; schema_check(:cast => true); end",
"def schema_range_type(db_type)\n :range\n end",
"def replace_late_bound_types_with_built_in(types)\n GraphQL::Schema::BUILT_IN_TYPES.each do |scalar_name, built_in_scalar|\n existing_type = types[scalar_name]\n if existing_type.is_a?(GraphQL::Schema::LateBoundType)\n types[scalar_name] = built_in_scalar\n end\n end\n end",
"def fix_overwritten(range)\n types = get_expanded_byte_types(range)\n range = types.first.address..types.last.address\n set_type_string(range.min, type_string(:undefined) * range.size)\n end",
"def fix_the_geom_type!(schema_name, table_name)\n qualified_table_name = \"\\\"#{schema_name}\\\".#{table_name}\"\n\n type = nil\n the_geom_data = user.in_database[%Q{\n SELECT a.attname, t.typname\n FROM pg_attribute a, pg_type t\n WHERE attrelid = '#{qualified_table_name}'::regclass\n AND attname = '#{THE_GEOM}'\n AND a.atttypid = t.oid\n AND a.attstattarget < 0\n LIMIT 1\n }].first\n return nil unless the_geom_data\n\n if the_geom_data[:typname] != 'geometry'\n user.in_database.execute %{\n ALTER TABLE #{qualified_table_name} RENAME COLUMN \"#{THE_GEOM}\" TO \"the_geom_str\"\n }\n return nil\n end\n\n geom_type = user.in_database[%Q{\n SELECT GeometryType(#{THE_GEOM})\n FROM #{qualified_table_name}\n WHERE #{THE_GEOM} IS NOT null\n LIMIT 1\n }].first\n\n type = geom_type[:geometrytype].to_s.downcase if geom_type\n\n # if the geometry is MULTIPOINT we convert it to POINT\n if type == 'multipoint'\n user.db_service.in_database_direct_connection(statement_timeout: STATEMENT_TIMEOUT) do |user_database|\n user_database.run(\"SELECT public.AddGeometryColumn('#{schema_name}', '#{table_name}','the_geom_simple',4326, 'GEOMETRY', 2);\")\n user_database.run(%Q{UPDATE #{qualified_table_name} SET the_geom_simple = ST_GeometryN(the_geom,1);})\n user_database.run(\"SELECT DropGeometryColumn('#{schema_name}', '#{table_name}','the_geom');\")\n user_database.run(%Q{ALTER TABLE #{qualified_table_name} RENAME COLUMN the_geom_simple TO the_geom;})\n end\n type = 'point'\n end\n\n # if the geometry is LINESTRING or POLYGON we convert it to MULTILINESTRING or MULTIPOLYGON\n if %w(linestring polygon).include?(type)\n user.db_service.in_database_direct_connection(statement_timeout: STATEMENT_TIMEOUT) do |user_database|\n user_database.run(\"SELECT public.AddGeometryColumn('#{schema_name}', '#{table_name}','the_geom_simple',4326, 'GEOMETRY', 2);\")\n user_database.run(%Q{UPDATE #{qualified_table_name} SET the_geom_simple = ST_Multi(the_geom);})\n user_database.run(\"SELECT DropGeometryColumn('#{schema_name}', '#{table_name}','the_geom');\")\n user_database.run(%Q{ALTER TABLE #{qualified_table_name} RENAME COLUMN the_geom_simple TO the_geom;})\n\n type = user_database[%Q{\n SELECT GeometryType(#{THE_GEOM})\n FROM #{qualified_table_name}\n WHERE #{THE_GEOM} IS NOT null\n LIMIT 1\n }].first[:geometrytype]\n end\n end\n\n type\n end",
"def set_schema_inheritance\n include Og::SchemaInheritanceBase\n end",
"def freeze\n @auto_validate_not_null_columns.freeze\n @auto_validate_explicit_not_null_columns.freeze\n @auto_validate_max_length_columns.freeze\n @auto_validate_unique_columns.freeze\n\n super\n end",
"def replace_late_bound_types_with_built_in(types); end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a database specific multirange type. This can be used to support different multirange types per Database. Options: :converter :: A callable object (e.g. Proc), that is called with the PostgreSQL range string, and should return a PGRange instance. :oid :: The PostgreSQL OID for the multirange type. This is used by Sequel to set up automatic type conversion on retrieval from the database. :range_oid :: Should be the PostgreSQL OID for the multirange subtype (the range type). If given, automatically sets the :converter option by looking for scalar conversion proc. If a block is given, it is treated as the :converter option. | def register_multirange_type(db_type, opts=OPTS, &block)
oid = opts[:oid]
soid = opts[:range_oid]
if has_converter = opts.has_key?(:converter)
raise Error, "can't provide both a block and :converter option to register_multirange_type" if block
converter = opts[:converter]
else
has_converter = true if block
converter = block
end
unless (soid || has_converter) && oid
range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngmultitypid).where(:typname=>db_type.to_s).get([:rngmultitypid, :rngtypid])
soid ||= subtype_oid unless has_converter
oid ||= range_oid
end
db_type = db_type.to_s.dup.freeze
if soid
raise Error, "can't provide both a converter and :range_oid option to register" if has_converter
raise Error, "no conversion proc for :range_oid=>#{soid.inspect} in conversion_procs" unless converter = conversion_procs[soid]
end
raise Error, "cannot add a multirange type without a convertor (use :converter or :range_oid option or pass block)" unless converter
creator = Creator.new(db_type, converter)
add_conversion_proc(oid, creator)
@pg_multirange_schema_types[db_type] = db_type.to_sym
singleton_class.class_eval do
meth = :"typecast_value_#{db_type}"
scalar_typecast_method = :"typecast_value_#{opts.fetch(:scalar_typecast, db_type.sub('multirange', 'range'))}"
define_method(meth){|v| typecast_value_pg_multirange(v, creator, scalar_typecast_method)}
private meth
end
@schema_type_classes[db_type] = PGMultiRange
nil
end | [
"def register_range_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:subtype_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_range_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngtypid).where(:typname=>db_type.to_s).get([:rngtypid, :rngsubtype])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :subtype_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :subtype_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n parser = Parser.new(db_type, converter)\n add_conversion_proc(oid, parser)\n\n @pg_range_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n define_method(meth){|v| typecast_value_pg_range(v, parser)}\n private meth\n end\n\n @schema_type_classes[:\"#{opts[:type_symbol] || db_type}\"] = PGRange\n nil\n end",
"def schema_multirange_type(db_type)\n :multirange\n end",
"def schema_range_type(db_type)\n :range\n end",
"def typecast_value_pg_multirange(value, creator, scalar_typecast_method=nil)\n case value\n when PGMultiRange\n return value if value.db_type == creator.type\n when Array\n # nothing\n else\n raise Sequel::InvalidValue, \"invalid value for multirange type: #{value.inspect}\"\n end\n\n if scalar_typecast_method && respond_to?(scalar_typecast_method, true)\n value = value.map{|v| send(scalar_typecast_method, v)}\n end\n PGMultiRange.new(value, creator.type)\n end",
"def schema_range_type(db_type)\n @pg_range_schema_types[db_type] || super\n end",
"def typecast_value_pg_range(value, parser)\n case value\n when PGRange\n if value.db_type.to_s == parser.db_type\n value\n elsif value.empty?\n PGRange.empty(parser.db_type)\n else\n PGRange.new(value.begin, value.end, :exclude_begin=>value.exclude_begin?, :exclude_end=>value.exclude_end?, :db_type=>parser.db_type)\n end\n when Range\n PGRange.from_range(value, parser.db_type)\n when String\n parser.call(typecast_check_string_length(value, 100))\n else\n raise Sequel::InvalidValue, \"invalid value for range type: #{value.inspect}\"\n end\n end",
"def schema_multirange_type(db_type)\n @pg_multirange_schema_types[db_type] || super\n end",
"def add_range measurement_name, values\n @ranges[measurement_name].add_range({\n maximum: values[:maximum],\n resolution: values[:resolution],\n error: values[:error],\n digits: values[:digits],\n })\n end",
"def create_range_data( rng, minrng=0, type=0, direction=2 )\n return Handlers::Range.createRange( rng, minrng, type, direction )\n end",
"def unsigned_integer_column_type(range)\n max = range.last\n\n if max < 2**8 then 'TINYINT'\n elsif max < 2**16 then 'SMALLINT'\n elsif max < 2**24 then 'MEDIUMINT'\n elsif max < 2**32 then 'INT'\n elsif max < 2**64 then 'BIGINT'\n else\n raise ArgumentError, \"min #{range.first} and max #{max} exceeds supported range\"\n end\n end",
"def range_type(type, start_value, end_value, args, block)\n filter_size_before = filter.size\n range(start_value, end_value, args, block)\n (filter.size - filter_size_before).times { types << type }\n end",
"def range_field_tag(name, value = nil, options = {})\n number_field_tag(name, value, options.stringify_keys.update(\"type\" => \"range\"))\n end",
"def range=(value)\n @range = value\n end",
"def range_field_tag(name, value = nil, options = {})\n number_field_tag(name, value, options.stringify_keys.update(\"type\" => \"range\"))\n end",
"def mark_range_field(range_field)\n # Interface method\n end",
"def parse_range(string, type)\n range = case string\n when /\\A(.+?)\\.\\.\\.(.+)/ # A...B\n lo, hi = [parse_cast($1, type), parse_cast($2, type)].sort\n [:between, (lo...hi)]\n when /\\A(.+?)\\.\\.(.+)/\n lo, hi = [parse_cast($1, type), parse_cast($2, type)].sort\n [:between, (lo..hi)]\n when /\\A<=(.+)/, /\\A\\.\\.(.+)/\n [:lteq, parse_cast($1, type)]\n when /\\A<(.+)/\n [:lt, parse_cast($1, type)]\n when /\\A>=(.+)/, /\\A(.+)\\.\\.\\Z/\n [:gteq, parse_cast($1, type)]\n when /\\A>(.+)/\n [:gt, parse_cast($1, type)]\n when /[, ]/\n [:in, string.split(/[, ]+/).map {|x| parse_cast(x, type)}]\n when \"any\"\n [:not_eq, nil]\n when \"none\"\n [:eq, nil]\n else\n # add a 5% tolerance for float and filesize values\n if type == :float || (type == :filesize && string =~ /[km]b?\\z/i)\n value = parse_cast(string, type)\n [:between, (value * 0.95..value * 1.05)]\n elsif type.in?([:date, :age])\n value = parse_cast(string, type)\n [:between, (value.beginning_of_day..value.end_of_day)]\n else\n [:eq, parse_cast(string, type)]\n end\n end\n\n range = reverse_range(range) if type == :age\n range\n end",
"def add_range(range = (0..-1))\n @ranges << range\n end",
"def SetRange(range)\n @range=range\n end",
"def integer_column_type(range)\n if range.first < 0\n signed_integer_column_type(range)\n else\n unsigned_integer_column_type(range)\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recognize the registered database multirange types. | def schema_multirange_type(db_type)
@pg_multirange_schema_types[db_type] || super
end | [
"def schema_multirange_type(db_type)\n :multirange\n end",
"def register_multirange_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:range_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_multirange_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngmultitypid).where(:typname=>db_type.to_s).get([:rngmultitypid, :rngtypid])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :range_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :range_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n raise Error, \"cannot add a multirange type without a convertor (use :converter or :range_oid option or pass block)\" unless converter\n creator = Creator.new(db_type, converter)\n add_conversion_proc(oid, creator)\n\n @pg_multirange_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n scalar_typecast_method = :\"typecast_value_#{opts.fetch(:scalar_typecast, db_type.sub('multirange', 'range'))}\"\n define_method(meth){|v| typecast_value_pg_multirange(v, creator, scalar_typecast_method)}\n private meth\n end\n\n @schema_type_classes[db_type] = PGMultiRange\n nil\n end",
"def schema_range_type(db_type)\n @pg_range_schema_types[db_type] || super\n end",
"def schema_range_type(db_type)\n :range\n end",
"def typecast_value_pg_multirange(value, creator, scalar_typecast_method=nil)\n case value\n when PGMultiRange\n return value if value.db_type == creator.type\n when Array\n # nothing\n else\n raise Sequel::InvalidValue, \"invalid value for multirange type: #{value.inspect}\"\n end\n\n if scalar_typecast_method && respond_to?(scalar_typecast_method, true)\n value = value.map{|v| send(scalar_typecast_method, v)}\n end\n PGMultiRange.new(value, creator.type)\n end",
"def register_range_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:subtype_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_range_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngtypid).where(:typname=>db_type.to_s).get([:rngtypid, :rngsubtype])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :subtype_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :subtype_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n parser = Parser.new(db_type, converter)\n add_conversion_proc(oid, parser)\n\n @pg_range_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n define_method(meth){|v| typecast_value_pg_range(v, parser)}\n private meth\n end\n\n @schema_type_classes[:\"#{opts[:type_symbol] || db_type}\"] = PGRange\n nil\n end",
"def possible_types; end",
"def typecast_value_pg_range(value, parser)\n case value\n when PGRange\n if value.db_type.to_s == parser.db_type\n value\n elsif value.empty?\n PGRange.empty(parser.db_type)\n else\n PGRange.new(value.begin, value.end, :exclude_begin=>value.exclude_begin?, :exclude_end=>value.exclude_end?, :db_type=>parser.db_type)\n end\n when Range\n PGRange.from_range(value, parser.db_type)\n when String\n parser.call(typecast_check_string_length(value, 100))\n else\n raise Sequel::InvalidValue, \"invalid value for range type: #{value.inspect}\"\n end\n end",
"def supports_ranges?\n postgresql_version >= 90200\n end",
"def schema_column_type(db_type)\n case db_type\n when /\\Ainterval\\z/io\n :interval\n when /\\Acitext\\z/io\n :string\n else\n super\n end\n end",
"def supports_ranges?\n postgresql_version >= 90200\n end",
"def ensure_tagtypes\n mytype = self.typenum\n self.tags.each do |tag|\n # Ensure that all associated tags have the right type, are global, and have a meaning\n unless tag.tagtype == mytype && tag.is_global\n if tag.tagtype != mytype && (tag.tagtype > 0) # ERROR!! Can't convert tag from another type\n errors.add(:tags, \"#{tag.name} is a '#{tag.typename}', not '#{Tag.typename(mytype)}'\")\n else\n tag.tagtype = mytype\n tag.is_global = true\n tag.save\n end\n end\n end\n end",
"def ensure_tagtypes\n mytype = self.typenum\n self.tags.each do |tag|\n # Ensure that all associated tags have the right type, are global, and have a meaning\n unless tag.tagtype == mytype && tag.isGlobal\n if tag.tagtype != mytype && (tag.tagtype > 0) # ERROR!! Can't convert tag from another type\n errors.add(:tags, \"#{tag.name} is a '#{tag.typename}', not '#{Tag.typename(mytype)}'\")\n else\n tag.tagtype = mytype\n tag.primary_meaning = self unless tag.primary_meaning # Give tag this meaning if there's no other\n tag.isGlobal = true\n tag.save\n end\n end\n end\n end",
"def freeze\n @pg_multirange_schema_types.freeze\n super\n end",
"def allowed_types; end",
"def supports?(dbtype)\n (:ctan.eql? dbtype.to_sym)\n end",
"def index\n @range_types = RangeType.all\n end",
"def db_type\n # first, detect any character not number\n case\n when @data.any? { |v| v.to_s =~ DATE_REGEXP }\n 'DATE'\n when @data.any? { |v| v.to_s =~ /[^0-9e.-]/ }\n 'VARCHAR (255)'\n when @data.any? { |v| v.to_s =~ /\\./ }\n 'DOUBLE'\n else\n 'INTEGER'\n end\n end",
"def parse\n raise Sequel::Error, \"invalid multirange, doesn't start with {\" unless get_byte == '{'\n ranges = []\n\n unless scan(/\\}/)\n while true\n raise Sequel::Error, \"unfinished multirange\" unless range_string = scan_until(/[\\]\\)]/)\n ranges << @converter.call(range_string)\n \n case sep = get_byte\n when '}'\n break\n when ','\n # nothing\n else\n raise Sequel::Error, \"invalid multirange separator: #{sep.inspect}\"\n end\n end\n end\n\n raise Sequel::Error, \"invalid multirange, remaining data after }\" unless eos?\n ranges\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a value to typecast and the type of PGMultiRange subclass: If given a PGMultiRange with a matching type, use it directly. If given a PGMultiRange with a different type, return a PGMultiRange with the creator's type. If given an Array, create a new PGMultiRange instance for it, typecasting each instance using the scalar_typecast_method. | def typecast_value_pg_multirange(value, creator, scalar_typecast_method=nil)
case value
when PGMultiRange
return value if value.db_type == creator.type
when Array
# nothing
else
raise Sequel::InvalidValue, "invalid value for multirange type: #{value.inspect}"
end
if scalar_typecast_method && respond_to?(scalar_typecast_method, true)
value = value.map{|v| send(scalar_typecast_method, v)}
end
PGMultiRange.new(value, creator.type)
end | [
"def typecast_value_pg_range(value, parser)\n case value\n when PGRange\n if value.db_type.to_s == parser.db_type\n value\n elsif value.empty?\n PGRange.empty(parser.db_type)\n else\n PGRange.new(value.begin, value.end, :exclude_begin=>value.exclude_begin?, :exclude_end=>value.exclude_end?, :db_type=>parser.db_type)\n end\n when Range\n PGRange.from_range(value, parser.db_type)\n when String\n parser.call(typecast_check_string_length(value, 100))\n else\n raise Sequel::InvalidValue, \"invalid value for range type: #{value.inspect}\"\n end\n end",
"def typecast_value_pg_array(value, creator, scalar_typecast_method=nil)\n case value\n when PGArray\n if value.array_type != creator.type\n PGArray.new(value.to_a, creator.type)\n else\n value\n end\n when Array\n if scalar_typecast_method && respond_to?(scalar_typecast_method, true)\n value = Sequel.recursive_map(value, method(scalar_typecast_method))\n end\n PGArray.new(value, creator.type)\n else\n raise Sequel::InvalidValue, \"invalid value for array type: #{value.inspect}\"\n end\n end",
"def typecast(value)\n if value.kind_of?(Range) then Range.new(typecast(value.first), typecast(value.last))\n elsif value.kind_of?(Array) then value.map{|v| typecast(v)}\n elsif primitive == BigDecimal then super(value).to_f\n elsif primitive == DateTime then Time.parse(super(value).to_s).to_i\n elsif primitive == Date then Time.parse(super(value).to_s).to_i\n elsif primitive == Time then super(value).to_i\n else\n super(value) # Good luck\n end\n end",
"def register_multirange_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:range_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_multirange_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngmultitypid).where(:typname=>db_type.to_s).get([:rngmultitypid, :rngtypid])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :range_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :range_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n raise Error, \"cannot add a multirange type without a convertor (use :converter or :range_oid option or pass block)\" unless converter\n creator = Creator.new(db_type, converter)\n add_conversion_proc(oid, creator)\n\n @pg_multirange_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n scalar_typecast_method = :\"typecast_value_#{opts.fetch(:scalar_typecast, db_type.sub('multirange', 'range'))}\"\n define_method(meth){|v| typecast_value_pg_multirange(v, creator, scalar_typecast_method)}\n private meth\n end\n\n @schema_type_classes[db_type] = PGMultiRange\n nil\n end",
"def register_range_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:subtype_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_range_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngtypid).where(:typname=>db_type.to_s).get([:rngtypid, :rngsubtype])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :subtype_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :subtype_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n parser = Parser.new(db_type, converter)\n add_conversion_proc(oid, parser)\n\n @pg_range_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n define_method(meth){|v| typecast_value_pg_range(v, parser)}\n private meth\n end\n\n @schema_type_classes[:\"#{opts[:type_symbol] || db_type}\"] = PGRange\n nil\n end",
"def typecast_value_pg_array(value, klass)\n case value\n when PGArray\n value\n when Array\n klass.new(value)\n when String\n klass.parse(value)\n else\n raise Sequel::InvalidValue, \"invalid value for #{klass}: #{value.inspect}\"\n end\n end",
"def cast(owner, value)\n if use_casted_array?\n CastedArray.new(owner, self, value)\n else\n build(owner, value)\n end\n end",
"def coerce(value)\n return SpreadSheet.new([value]) if value.is_a?(Numeric)\n return SpreadSheet.new(value) if value.is_a?(Array)\n end",
"def coerce(value)\n return value if union_type?(value)\n coerce_using_attribute(value)\n end",
"def cast_value(value, type)\n return value if type == value.class\n case\n when type == Integer\n value.to_i\n when type == Float\n value.to_f\n when type == String\n value.to_s\n when type == Date\n value.to_date\n when type == Time\n value.to_time\n else\n type.new(value)\n end\n end",
"def coerce(value)\n @base_class.new(value)\n end",
"def range_type(type, start_value, end_value, args, block)\n filter_size_before = filter.size\n range(start_value, end_value, args, block)\n (filter.size - filter_size_before).times { types << type }\n end",
"def bt_coerce_slice(*args)\n case args.size\n when 0\n [vt_range, Time.zone.now]\n when 1\n [ARange[*args], Time.zone.now]\n when 2\n case args.first\n when Range\n args\n else\n [ARange[*args], Time.zone.now]\n end\n when 3\n [ARange[args.at(0),args.at(1)], args.at(2)]\n else\n raise ArgumentError\n end\n end",
"def to_range\n return @range if @range\n raise(Error, \"cannot create ruby range for an empty PostgreSQL range\") if empty?\n raise(Error, \"cannot create ruby range when PostgreSQL range excludes beginning element\") if exclude_begin?\n # :nocov:\n raise(Error, \"cannot create ruby range when PostgreSQL range has unbounded beginning\") if STARTLESS_RANGE_NOT_SUPPORTED && !self.begin\n raise(Error, \"cannot create ruby range when PostgreSQL range has unbounded ending\") if ENDLESS_RANGE_NOT_SUPPORTED && !self.end\n # :nocov:\n @range = Range.new(self.begin, self.end, exclude_end?)\n end",
"def cast_value(value, opts = {})\n case value\n when Array\n value.map { |v| cast_value(v, opts) }\n when String\n cast_uri = RDF::URI.new(value)\n cast_uri.valid? ? cast_uri : RDF::Literal.new(value, opts)\n when Time\n # Cast DateTimes with 00:00:00 or Date stored as Times in Mongoid to xsd:date\n # FIXME: this should NOT be applied for fields that are typed as Time\n value.midnight == value ? RDF::Literal.new(value.to_date) : RDF::Literal.new(value.to_datetime)\n else\n RDF::Literal.new(value, opts)\n end\n end",
"def apply_cast(val, cast_method)\n if val.respond_to?(:map)\n val.map { |v| send(cast_method, v) }\n else\n send(cast_method, val)\n end\n end",
"def type_cast(value)\r\n @column_definition.type_cast(value)\r\n end",
"def typecast(value); end",
"def _explicitly_type_cast(value, type, column_class)\n return nil if value.nil?\n\n return type.call(value) if type.respond_to?(:call)\n\n typecasted = case type\n when :string then value.to_s\n when :text then value.to_s\n when :integer then value.to_i rescue value ? 1 : 0\n when :float then value.to_f\n when :decimal then column_class.value_to_decimal(value)\n when :datetime then _cast_to_time(value, column_class)\n when :timestamp then _cast_to_time(value, column_class)\n when :time then _cast_to_time(value, column_class, true)\n when :date then _cast_to_date(value, column_class)\n when :binary then column_class.binary_to_string(value)\n when :boolean then column_class.value_to_boolean(value)\n else value\n end\n\n raise ArgumentError, \"Unable to typecast #{value} to #{type}\" unless _valid_class?(typecasted, type)\n\n typecasted\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Append the multirange SQL to the given sql string. | def sql_literal_append(ds, sql)
sql << db_type << '('
joiner = nil
conversion_meth = nil
each do |range|
if joiner
sql << joiner
else
joiner = ', '
end
unless range.is_a?(PGRange)
conversion_meth ||= :"typecast_value_#{db_type.sub('multi', '')}"
range = ds.db.send(conversion_meth, range)
end
ds.literal_append(sql, range)
end
sql << ')'
end | [
"def subscript_sql_append(sql, s)\n literal_append(sql, s.f)\n sql << '['\n if s.sub.length == 1 && (range = s.sub.first).is_a?(Range)\n literal_append(sql, range.begin)\n sql << ':'\n e = range.end\n e -= 1 if range.exclude_end? && e.is_a?(Integer)\n literal_append(sql, e)\n else\n expression_list_append(sql, s.sub)\n end\n sql << ']'\n end",
"def subselect_sql_append(sql, ds)\n ds.clone(:append_sql=>sql).sql\n end",
"def subscript_sql(s)\n \"#{s.f}[#{s.sub.join(COMMA_SEPARATOR)}]\"\n end",
"def static_sql(sql)\n if @opts[:append_sql] || @opts[:no_auto_parameterize] || String === sql\n super\n else\n query_string = QueryString.new\n literal_append(query_string, sql)\n query_string\n end\n end",
"def complex_expression_arg_pairs_append(sql, args, &block)\n literal_append(sql, complex_expression_arg_pairs(args, &block))\n end",
"def sql_literal_append(ds, sql)\n sql << ARRAY\n _literal_append(sql, ds, to_a)\n if at = array_type\n sql << DOUBLE_COLON << at.to_s << EMPTY_BRACKET\n end\n end",
"def add_range_to_jql str\n str << \" and created >= '#{@sprint_start_date}' and created <= '#{@sprint_end_date}'\"\n end",
"def sql\n \"(\\n#{@conjunctions.map(&:sql).join(\" OR\\n\")}\\n)\"\n end",
"def quoted_identifier_append(sql, name)\n sql << '[' << name.to_s.gsub(/\\]/, ']]') << ']'\n end",
"def static_sql(sql)\n if append_sql = @opts[:append_sql]\n if sql.is_a?(String)\n append_sql << sql\n else\n literal_append(append_sql, sql)\n end\n else\n if sql.is_a?(String)\n sql\n else\n literal(sql)\n end\n end\n end",
"def sql_literal_append(ds, sql)\n at = array_type\n if empty? && at\n sql << \"'{}'\"\n else\n sql << \"ARRAY\"\n _literal_append(sql, ds, to_a)\n end\n if at\n sql << '::' << at.to_s << '[]'\n end\n end",
"def to_s_append(ds, sql)\n i = -1\n match_len = @values.length - 1\n like_pattern = String.new\n pattern = @pattern\n while true\n previous, q, pattern = pattern.partition('?')\n like_pattern << previous\n\n unless q.empty?\n if i == match_len\n raise Error, \"Mismatched number of placeholders (#{i+1}) and placeholder arguments (#{@values.length}) for escaped like expression: #{@pattern.inspect}\"\n end\n like_pattern << ds.escape_like(@values.at(i+=1))\n end\n\n if pattern.empty?\n unless i == match_len\n raise Error, \"Mismatched number of placeholders (#{i+1}) and placeholder arguments (#{@values.length}) for escaped like expression: #{@pattern.inspect}\"\n end\n break\n end\n end\n ds.literal_append(sql, Sequel.send(@method, @expr, like_pattern))\n end",
"def subselect_sql_append(sql, ds)\n ds.clone(:append_sql=>sql, :prepared_args=>prepared_args, :bind_vars=>@opts[:bind_vars]).\n send(:to_prepared_statement, :select, nil, :extend=>prepared_statement_modules).\n prepared_sql\n end",
"def escaped_sql\n sql % binds.reduce({}) { |a, (col, val)|\n a[col.to_sym] = if val.is_a? Array\n val.map { |x| @conn.quote x }.join(', ')\n else\n @conn.quote val\n end\n a\n }\n end",
"def aliased_expression_sql_append(sql, ae)\n literal_append(sql, ae.expression)\n as_sql_append(sql, ae.alias, ae.columns)\n end",
"def literal_expression_append(sql, v)\n v.to_s_append(self, sql)\n end",
"def multi_insert_sql(columns, values)\n [insert_sql(columns, LiteralString.new(values.map {|r| \"SELECT #{expression_list(r)}\" }.join(\" UNION ALL \")))]\n end",
"def quoted_identifier_append(sql, name)\n sql << '\"' << name.to_s.gsub('\"', '\"\"') << '\"'\n end",
"def to_sql\n \" where #{sql_parts.join(' and ')}\"\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Don't consider multiranges with different database types equal. | def eql?(other)
if PGMultiRange === other
return false unless other.db_type == db_type
other = other.__getobj__
end
__getobj__.eql?(other)
end | [
"def ==(other)\n return false if PGMultiRange === other && other.db_type != db_type\n super\n end",
"def schema_multirange_type(db_type)\n :multirange\n end",
"def schema_multirange_type(db_type)\n @pg_multirange_schema_types[db_type] || super\n end",
"def eql?(other)\n case other\n when PGRange\n if db_type == other.db_type\n if empty?\n other.empty?\n elsif other.empty?\n false\n else\n [:@begin, :@end, :@exclude_begin, :@exclude_end].all?{|v| instance_variable_get(v) == other.instance_variable_get(v)}\n end\n else\n false\n end\n when Range\n if valid_ruby_range?\n to_range.eql?(other)\n else\n false\n end\n else\n false\n end\n end",
"def schema_range_type(db_type)\n @pg_range_schema_types[db_type] || super\n end",
"def schema_range_type(db_type)\n :range\n end",
"def supports_ranges?\n postgresql_version >= 90200\n end",
"def typecast_value_pg_multirange(value, creator, scalar_typecast_method=nil)\n case value\n when PGMultiRange\n return value if value.db_type == creator.type\n when Array\n # nothing\n else\n raise Sequel::InvalidValue, \"invalid value for multirange type: #{value.inspect}\"\n end\n\n if scalar_typecast_method && respond_to?(scalar_typecast_method, true)\n value = value.map{|v| send(scalar_typecast_method, v)}\n end\n PGMultiRange.new(value, creator.type)\n end",
"def supports_ranges?\n postgresql_version >= 90200\n end",
"def register_multirange_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:range_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_multirange_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngmultitypid).where(:typname=>db_type.to_s).get([:rngmultitypid, :rngtypid])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :range_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :range_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n raise Error, \"cannot add a multirange type without a convertor (use :converter or :range_oid option or pass block)\" unless converter\n creator = Creator.new(db_type, converter)\n add_conversion_proc(oid, creator)\n\n @pg_multirange_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n scalar_typecast_method = :\"typecast_value_#{opts.fetch(:scalar_typecast, db_type.sub('multirange', 'range'))}\"\n define_method(meth){|v| typecast_value_pg_multirange(v, creator, scalar_typecast_method)}\n private meth\n end\n\n @schema_type_classes[db_type] = PGMultiRange\n nil\n end",
"def typecast_value_pg_range(value, parser)\n case value\n when PGRange\n if value.db_type.to_s == parser.db_type\n value\n elsif value.empty?\n PGRange.empty(parser.db_type)\n else\n PGRange.new(value.begin, value.end, :exclude_begin=>value.exclude_begin?, :exclude_end=>value.exclude_end?, :db_type=>parser.db_type)\n end\n when Range\n PGRange.from_range(value, parser.db_type)\n when String\n parser.call(typecast_check_string_length(value, 100))\n else\n raise Sequel::InvalidValue, \"invalid value for range type: #{value.inspect}\"\n end\n end",
"def mark_all_range_fields\n # Interface method\n end",
"def supports_is_distinct_from?\n if defined?(super)\n return super\n end\n \n case db.database_type\n when :postgres, :h2\n true\n when :sqlite\n db.sqlite_version >= 33900\n else\n false\n end\n end",
"def ==(other)\n return false unless Range === other \n return self.first == other.first && self.last == other.last && self.exclude_end? == other.exclude_end?\n end",
"def with_range_key?\n key_type?('range')\n end",
"def ==(other)\n\t\tfalse unless other.kind_of? DayRange\n\t\tself.to_a == other.to_a\n\tend",
"def include_range? other_range\n case other_range\n when Range\n if other_range.first >= self.first && other_range.last <= self.last\n return true\n else\n return false\n end\n else\n raise \"unsupported type\"\n end\n end",
"def conflicts\n if new_record?\n query = 'unit_id = ? AND daterange(start_at, end_at) && daterange(?, ?)'\n Reservation.where(query, unit_id, start_at, end_at)\n else\n query = 'id <> ? AND unit_id = ? AND daterange(start_at, end_at) && daterange(?, ?)'\n Reservation.where(query, id, unit_id, start_at, end_at)\n end\n end",
"def arel_exclude(start_column, end_column, start_or_instant_or_range=nil, range_end=nil)\n table = self.arel_table\n if range_end\n table[start_column].gteq(range_end).or(table[end_column].lteq(start_or_instant_or_range))\n elsif Range === start_or_instant_or_range\n table[start_column].gteq(start_or_instant_or_range.db_end).or(table[end_column].lteq(start_or_instant_or_range.db_begin))\n else\n start_or_instant_or_range ||= InfinityLiteral\n table[start_column].gt(start_or_instant_or_range).or(table[end_column].lteq(start_or_instant_or_range))\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Don't consider multiranges with different database types equal. | def ==(other)
return false if PGMultiRange === other && other.db_type != db_type
super
end | [
"def schema_multirange_type(db_type)\n :multirange\n end",
"def eql?(other)\n if PGMultiRange === other\n return false unless other.db_type == db_type\n other = other.__getobj__\n end\n __getobj__.eql?(other)\n end",
"def schema_multirange_type(db_type)\n @pg_multirange_schema_types[db_type] || super\n end",
"def eql?(other)\n case other\n when PGRange\n if db_type == other.db_type\n if empty?\n other.empty?\n elsif other.empty?\n false\n else\n [:@begin, :@end, :@exclude_begin, :@exclude_end].all?{|v| instance_variable_get(v) == other.instance_variable_get(v)}\n end\n else\n false\n end\n when Range\n if valid_ruby_range?\n to_range.eql?(other)\n else\n false\n end\n else\n false\n end\n end",
"def schema_range_type(db_type)\n @pg_range_schema_types[db_type] || super\n end",
"def schema_range_type(db_type)\n :range\n end",
"def supports_ranges?\n postgresql_version >= 90200\n end",
"def typecast_value_pg_multirange(value, creator, scalar_typecast_method=nil)\n case value\n when PGMultiRange\n return value if value.db_type == creator.type\n when Array\n # nothing\n else\n raise Sequel::InvalidValue, \"invalid value for multirange type: #{value.inspect}\"\n end\n\n if scalar_typecast_method && respond_to?(scalar_typecast_method, true)\n value = value.map{|v| send(scalar_typecast_method, v)}\n end\n PGMultiRange.new(value, creator.type)\n end",
"def supports_ranges?\n postgresql_version >= 90200\n end",
"def register_multirange_type(db_type, opts=OPTS, &block)\n oid = opts[:oid]\n soid = opts[:range_oid]\n\n if has_converter = opts.has_key?(:converter)\n raise Error, \"can't provide both a block and :converter option to register_multirange_type\" if block\n converter = opts[:converter]\n else\n has_converter = true if block\n converter = block\n end\n\n unless (soid || has_converter) && oid\n range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngmultitypid).where(:typname=>db_type.to_s).get([:rngmultitypid, :rngtypid])\n soid ||= subtype_oid unless has_converter\n oid ||= range_oid\n end\n\n db_type = db_type.to_s.dup.freeze\n\n if soid\n raise Error, \"can't provide both a converter and :range_oid option to register\" if has_converter \n raise Error, \"no conversion proc for :range_oid=>#{soid.inspect} in conversion_procs\" unless converter = conversion_procs[soid]\n end\n\n raise Error, \"cannot add a multirange type without a convertor (use :converter or :range_oid option or pass block)\" unless converter\n creator = Creator.new(db_type, converter)\n add_conversion_proc(oid, creator)\n\n @pg_multirange_schema_types[db_type] = db_type.to_sym\n\n singleton_class.class_eval do\n meth = :\"typecast_value_#{db_type}\"\n scalar_typecast_method = :\"typecast_value_#{opts.fetch(:scalar_typecast, db_type.sub('multirange', 'range'))}\"\n define_method(meth){|v| typecast_value_pg_multirange(v, creator, scalar_typecast_method)}\n private meth\n end\n\n @schema_type_classes[db_type] = PGMultiRange\n nil\n end",
"def typecast_value_pg_range(value, parser)\n case value\n when PGRange\n if value.db_type.to_s == parser.db_type\n value\n elsif value.empty?\n PGRange.empty(parser.db_type)\n else\n PGRange.new(value.begin, value.end, :exclude_begin=>value.exclude_begin?, :exclude_end=>value.exclude_end?, :db_type=>parser.db_type)\n end\n when Range\n PGRange.from_range(value, parser.db_type)\n when String\n parser.call(typecast_check_string_length(value, 100))\n else\n raise Sequel::InvalidValue, \"invalid value for range type: #{value.inspect}\"\n end\n end",
"def mark_all_range_fields\n # Interface method\n end",
"def supports_is_distinct_from?\n if defined?(super)\n return super\n end\n \n case db.database_type\n when :postgres, :h2\n true\n when :sqlite\n db.sqlite_version >= 33900\n else\n false\n end\n end",
"def ==(other)\n return false unless Range === other \n return self.first == other.first && self.last == other.last && self.exclude_end? == other.exclude_end?\n end",
"def with_range_key?\n key_type?('range')\n end",
"def ==(other)\n\t\tfalse unless other.kind_of? DayRange\n\t\tself.to_a == other.to_a\n\tend",
"def include_range? other_range\n case other_range\n when Range\n if other_range.first >= self.first && other_range.last <= self.last\n return true\n else\n return false\n end\n else\n raise \"unsupported type\"\n end\n end",
"def conflicts\n if new_record?\n query = 'unit_id = ? AND daterange(start_at, end_at) && daterange(?, ?)'\n Reservation.where(query, unit_id, start_at, end_at)\n else\n query = 'id <> ? AND unit_id = ? AND daterange(start_at, end_at) && daterange(?, ?)'\n Reservation.where(query, id, unit_id, start_at, end_at)\n end\n end",
"def arel_exclude(start_column, end_column, start_or_instant_or_range=nil, range_end=nil)\n table = self.arel_table\n if range_end\n table[start_column].gteq(range_end).or(table[end_column].lteq(start_or_instant_or_range))\n elsif Range === start_or_instant_or_range\n table[start_column].gteq(start_or_instant_or_range.db_end).or(table[end_column].lteq(start_or_instant_or_range.db_begin))\n else\n start_or_instant_or_range ||= InfinityLiteral\n table[start_column].gt(start_or_instant_or_range).or(table[end_column].lteq(start_or_instant_or_range))\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls a block until the result does not contain profanity | def without_profanity(limit: 1_000)
limit.times do
word = yield
return word unless profane?(word)
end
raise 'random generator limit'
end | [
"def wait_for_mine(w)\n loop do\n w.refresh\n break unless w.read_text =~ /This mine can be/\n sleep(1)\n end\n end",
"def surprise()\n curr = \"\"\n while true\n # Get the next person to act\n while !(inNames(curr))\n puts \"> Who has the next surprise attack? If nobody does, \" + \n \"type \\\"none\\\".\"\n curr = read().chomp.downcase\n if curr == \"none\"\n return\n end\n end\n\n # Do the person's action\n action(curr)\n curr = \"\"\n end\n end",
"def bad_results\n select {|r| !r.success }\n end",
"def deaf_grandma\n puts \"Say something to grandma!\"\n your_response = gets.chomp\n \n while your_response != your_response.upcase\n puts \"HUH?! SPEAK UP SONNY!\"\n your_response = gets.chomp\n end\n \n puts \"NO, NOT SINCE #{rand(1930..1951)}\"\nend",
"def retry_if\n tries.times.each do\n result = yield\n return result unless unwilling?\n sleep(PsuDir.ldap_unwilling_sleep)\n end\n PsuDir.logger.warn 'LDAP is unwilling to perform this operation, try upping the number of tries'\n nil\n rescue Net::LDAP::Error => e\n PsuDir.logger.warn \"Error getting LDAP response: #{ldap_error_message(e)}\"\n nil\n end",
"def retry_if\n tries.times.each do\n result = yield\n return result unless unwilling?\n sleep(Rails.application.config.ldap_unwilling_sleep)\n end\n Rails.logger.warn 'LDAP is unwilling to perform this operation, try upping the number of tries'\n nil\n rescue Net::LDAP::Error => e\n Rails.logger.warn \"Error getting LDAP response: #{ldap_error_message(e)}\"\n nil\n end",
"def cleverResponse(bot, message)\n # Think of a response\n valid_reply = false\n while( !valid_reply )\n reply = bot.write message\n # The server is denying us\n if /html/i.match(reply) != nil\n puts \"!!!!!! the server won't let us interact with cleverbot. 5min timeout\"\n sleep(300)\n # Check for ads\n elsif (/Clev/i.match(reply) != nil or /ios/i.match(reply) != nil)\n puts \"!!!!!! Cleverbot gave an ad:\" + reply\n else\n valid_reply = true\n end\n end\n return reply\nend",
"def repeat_until_success\n repeat = true\n while repeat\n begin\n result = yield\n repeat = false\n rescue StandardError\n repeat = true\n end\n end\n result\n end",
"def check_security(people)\n found_miscreant(people)\n some_later_code(found)\nend",
"def stop_hooks_unless(result)\n\t\t\t\t\t(result == true) ? continue(true) : stop(false)\n\t\t\t\tend",
"def next_unattempted\n fewest_potential_pairs(unattempted_people)\n end",
"def check_security(people)\n found = false\n people.each do |person|\n if person == \"Don\"\n send_alert\n break\n end\n if person == \"John\"\n send_alert\n break\n end\n end\nend",
"def exists(description, allow_failure = false)\n counter = 0\n while yield.length < 1\n if counter > 9\n if allow_failure\n return []\n else\n raise \"cannot find \" + description\n end \n end\n sleep(0.5)\n counter += 1\n end\n return yield\nend",
"def name_me_ow() #'Gator said this was acceptable and reasonable\n\n happy = false\n\n until happy == true\n\n puts \"If you have a word to include in this cat's name, please type it in.\\n Otherwise, please type n:\".colorize(:blue)\n personal_name = gets.chomp.capitalize\n\n\n if personal_name == \"N\"\n puts \"How many words in your cat name?\".colorize(:blue)\n number_of_words = gets.chomp.to_i\n if number_of_words <= 0 || number_of_words > 7\n puts \"Two names is most common\"\n number_of_words = 2\n end\n\n kitty_called = cat_namer(number_of_words)\n \n\n else\n puts \"How many words in your cat name?\".colorize(:blue)\n number_of_words = gets.chomp.to_i - 1\n if number_of_words < 0 || number_of_words > 6\n puts \"Two names is most common\"\n number_of_words = 1\n end\n kitty_called = cat_namer(number_of_words) + \" \" + personal_name\n \n \n end\n happy = confirm_name(kitty_called)\n end\n return kitty_called\nend",
"def wait_for_text_present(text)\n assert !60.times{ break if (is_text_present(text) rescue false); sleep 1 }\n end",
"def levitation_quiz\n\t#your code here\n\t\n\tloop do \n\t\tputs 'What is the spell that enacts levitation?'\n spell=gets.chomp\n\t\tbreak if spell=='Wingardium Leviosa'\n\tend\n\tputs 'You passed the quiz!'\nend",
"def loop_until_success(&block)\n Combinators::Loop::UntilSuccess.setup!(&block)\n end",
"def signal_wait_until(pr, &block)\n #NOTE: busy waiting!!!\n while true do\n torrent = yield\n break if pr.call torrent\n end\n end",
"def wait_until(timeout = 30, retry_interval = 0.1, &block)\n start = Time.now\n while (result = !block.call)\n break if (Time.now - start).to_i >= timeout\n sleep(retry_interval)\n end\n !result\nend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the string contains profanity inside it ProfanityFilter::Base.profane? splits by word, but this checks all substrings | def profane?(str)
preprocess_if_needed!
str_no_whitespace = str.gsub(/\W/, '').downcase
(min_profanity_length..[str_no_whitespace.length, max_profanity_length].min).each do |size|
profane_regex = @regex_by_length[size]
next if profane_regex.nil?
return true if profane_regex.match?(str_no_whitespace)
end
false
end | [
"def profane_words_in_content\n # Better to set this somewhere configurable. Placing here for example purposes.\n profane_words = %w(poop fart fartface poopface poopbuttface)\n content_words = content.split(/\\W/)\n content_words.select { |word| word.in? profane_words }.presence\n end",
"def profaneWordsFilter(content)\n @cleanContent = true\n @tokenizer = Tokenizer::WhitespaceTokenizer.new\n @content = content.to_s\n @tokenizedContent = @tokenizer.tokenize(@content)\n @tokenizedContent.each do |word|\n if @profaneWords.include?([word])\n @cleanContent = false\n end\n end\n return @cleanContent\n end",
"def check_phrase(phrase)\n return clean_phrase(phrase).split(' ').map{|p_word| words.include?(p_word)}.all?\n end",
"def phrase_is_boring?(phrase)\n words = phrase.words\n boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december}\n number_non_boring_words = 0\n words.each do |word|\n number_non_boring_words += 1 unless boring_words.include?(word.downcase) #Not unicode safe?\n #number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) #Unicode safe\n end\n return true unless number_non_boring_words > 1\n end",
"def resume_contains(string, resume_file)\n string.downcase!\n return true if resume_file.include?(string.delete(' '))\n return true if resume_file.include?(string)\n string_array = string.split(' ')\n string_array.each do |part|\n return true if resume_file.include?(part)\n end\n false\n end",
"def real_phrase?(phrase)\n !!phrase.split.each { |word| return unless real_word?(word) }\n true\n end",
"def has_bad_word(str)\n #Turn string (url or body) into UTF-8 and lower case\n new_str = str.force_encoding(\"UTF-8\").downcase\n bad_words = [\"spongebob\",\n \"britney spears\",\n \"paris hilton\",\n \"norrköping\"]\n return bad_words.any? { |word| new_str.include?(word) }\nend",
"def blacklist_filter?(str)\n @@black_list.each do |badword|\n if str.include?(badword)\n @@blacklist_count+=1\n return false\n end\n end\n true\n end",
"def valid_name(string)\n output = true\n arr = string.split\n output = false unless arr.all? {|word| word == word.capitalize}\n output = false unless arr.all? {|word| word.length > 1}\n output = false if arr.count == 1\n output = false if arr.count > 3\n arr.each do |word|\n if word.length > 2\n output = false if word.end_with?(\".\")\n end\n end\n if arr.length == 3 && arr[0].length == 2\n if arr[1].length > 2\n output = false\n end\n end\n output = false if arr.last.length <= 2\n output\nend",
"def check_string(string)\n\tzombie_apocalypse_supplies = [\"hatchet\", \"rations\", \"water jug\", \"binoculars\",\n \"shotgun\", \"compass\", \"CB radio\", \"batteries\"]\n\tzombie_apocalypse_supplies.each do |item|\n\t\tif string.downcase == item.downcase\n\t\t\treturn true\n\t\tend\n\tend\n false\nend",
"def wordless?\n @results.map do |r|\n return false if r =~ /\\w/\n end\n true\n end",
"def contains_masscan?(str_val)\n return (str_val.downcase.include? \"masscan\" or\n str_val.downcase.include? \"\\6d\\61\\73\\73\\63\\61\\6e\")\nend",
"def excludes_naughty_strings?\n (/(ab|cd|pq|xy)/ =~ @s).nil?\n end",
"def filters?(str); end",
"def includes_all_words?(string, query)\n words = parse_words(string)\n query.all? { |pattern| words.any? { |word| word.ilike?(pattern) }}\n end",
"def is_spammy?(text)\n [\n /(.)\\1{19,}/,\n /[[:punct:]]{10,}/,\n /[asdfghjkl;]{10,}/i,\n /[zxcvbnm,\\.]{10,}/i\n ].collect {|pattern| pattern.match(text)}.select {|result| !result.nil?}.size > 0\n end",
"def first_word_capitalized_and_ends_with_punctuation?(punctuation)\n if punctuation.match(/\\A[A-Z].*\\W\\z/) # if first word of second sentence is not capitalized and/or first\n # sentence does not include punctuation it will still return true. Test only checks the ends of entire string.\n true\n else false\n end\nend",
"def custom_start_with?(string, substring)\n array_of_strings = string.split(\" \")\n array_of_strings.first == substring ? true : false\nend",
"def first_word_capitalized_and_ends_with_punctuation?(text)\n text.match(/\\A[A-Z].+[.!]\\z/) ? true : false\nend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes all driver order times that contain a specific order | def remove_order!(order)
self.driver_order_times = driver_order_times.reject {|driver_order_time| driver_order_time.order.id == order.id }
driver_order_times
end | [
"def remove_order!(order)\n self.driver_order_times = driver_order_times.reject {|driver_order_time| driver_order_time.order == order }\n driver_order_times\n end",
"def orders_unique\n driver_order_times.map{|dto| dto.order}.uniq\n end",
"def drivers_unique\n driver_order_times.map{|dto| dto.order}.uniq\n end",
"def remove_proper_orders\n stmt = <<~SQL\n DELETE FROM orders WHERE DATE(date_created) <= DATE('#{@date}') AND creator IN (#{@users}) AND patient_id NOT IN (#{@patients})\n LIMIT 1000\n SQL\n central_remove(stm: stmt, msg: 'Removing orders that were migrated properly')\n end",
"def prune_times\n now = Time.now.strftime(\"%Y-%m-%d\")\n @times.reject! {|time| time[\"date\"].strftime(\"%Y-%m-%d\") != now}\n end",
"def remove_matched_order_items(order , meal)\n \n (order & meal.items).each do|item|\n order.delete_at(order.index(item))\n end\n order\n\n end",
"def discard_order(order)\n @queue.remove(order)\n end",
"def remove_drug_orders\n condition = <<~SQL\n DELETE FROM drug_order WHERE order_id IN (SELECT order_id FROM orders WHERE patient_id IN (#{@remove}))\n LIMIT 1000\n SQL\n central_remove(stm: condition, msg: 'Removing Drug Orders')\n end",
"def recalculate_driver_time!(driver)\n # Get all the combinations for the driver\n combinations = driver_order_times.select {|driver_order_time| driver_order_time.driver == driver }\n # Recalculate the time for each\n combinations.each do |driver_order_time|\n driver_order_time.time = driver_order_time.driver.complex_tour_time(driver_order_time.order, driver_order_time.time)\n end\n end",
"def parts_with_order_remove part\n self.parts_with_order = self.parts_with_order.reject{|master_file| master_file.pid == part.pid }\n end",
"def remove_times(event)\n\t\tevent.times.each do |t|\n\t\t\tif t[1].to_i-t[0].to_i < event.length\n\t\t\t\tevent.times.delete(t)\n\t\t\tend\n\t\tend\n\tend",
"def remove_proper_drug_orders\n statement = <<~SQL\n DELETE FROM drug_order WHERE order_id IN (SELECT order_id FROM orders WHERE DATE(date_created) <= DATE('#{@date}') AND creator IN (#{@users}) AND patient_id NOT IN (#{@patients}))\n LIMIT 1000\n SQL\n central_remove msg: 'Remove drug_orders that were migrated properly', stm: statement\n end",
"def destroy_associated_order_tour\n order_tours = OrderTour.where(order: self)\n order_tours.each do |order_tour|\n tour = order_tour.tour\n order_tour.destroy\n if tour\n tour.update_place_order_tours\n end\n end\n end",
"def delete_invalid_rule_times(occur_event_times, rule_times)\n rule_times.delete_if do |rule_time|\n !is_time_between?(occur_event_times, rule_time) \n end\n end",
"def getOutstandingOrders(sym = nil, otype = nil, orderID = nil)\n aos = App.EM.broker.getOrderStatus\n aos.delete_if {|os| os.symbol != sym} unless sym.nil?\n aos.delete_if {|os| os.orderStatus != otype} unless otype.nil?\n aos.delete_if {|os| os.orderID != orderID} unless orderID.nil?\n aos\n end",
"def clean_for_period(future_period, notification_times)\n future_period.notifications.all.each do |existing_notification|\n unless notification_times.include?(existing_notification.time.utc)\n existing_notification.delete\n end\n end\n end",
"def team_availability arr\n schedule_arr = [\n ['8:30', '9:00'], ['9:00', '9:30'], ['9:30', '10:00'],\n ['10:00', '10:30'], ['10:30', '11:00'], ['11:30', '12:00'],\n ['1:00', '1:30'], ['1:30', '2:00'], ['2:00', '2:30'],\n ['2:30', '3:00'], ['3:00', '3:30'], ['3:30', '4:00'],\n ]\n\n # schedule_arr.each do |pair|\n # arr.each do |pair_2|\n # if pair_2 == pair\n # schedule_arr.delete(pair)\n # end\n # end\n # end\n\n arr.each do |start_time, end_time|\n schedule_arr.delete_if { |start_time_2, end_time_2| (start_time >= start_time_2 && end_time_2 <= end_time ) }\n end\n\n\n schedule_arr\nend",
"def without_drug_orders\n list = []\n @check_orders.each do |record|\n result = ActiveRecord::Base.connection.select_one <<~SQL\n SELECT count(*) as count FROM orders AS art_order\n INNER JOIN drug_order ON drug_order.order_id = art_order.order_id\n AND drug_order.quantity > 0\n where art_order.patient_id = #{record}\n AND art_order.concept_id IN (SELECT concept_id FROM concept_set WHERE concept_set = 1085)\n AND art_order.order_type_id IN (SELECT order_type_id FROM order_type WHERE name = 'Drug order')\n AND art_order.voided = 0\n SQL\n list << record if result['count'].to_i.positive?\n end\n @we_dont_know = list\n @check_orders - list\nend",
"def orders_with_items() orders.select {|o| o.line_items_unshipped_and_uncancelled.any? } end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all the unique orders. | def orders_unique
driver_order_times.map{|dto| dto.order}.uniq
end | [
"def get_all_orders\n orders = []\n page = 0\n loop do\n orders_page = self.get_orders_page page\n page += 1\n orders.push *orders_page.orders\n break if (page * orders_page.results_per_page >= orders_page.total_count)\n end\n orders\n end",
"def drivers_unique\n driver_order_times.map{|dto| dto.order}.uniq\n end",
"def all\n @orders_list.values.flatten.sort_by { |order| order.num }\n end",
"def get_orders\n orders\n end",
"def get_all_orders_for(seller)\n # all_orders_for = self.orders.dup.clear\n # seller.food_items.each do |food|\n # all_orders_for.push(self.orders.where(food_item_id: food.id))\n # end\n # all_orders_for\n Order.where(food_item: seller.food_items, user: self)\n end",
"def printer_order_ids\n poids = []\n self.order_line_items.each do |li|\n poids << li.printer_order_id unless poids.include?(li.printer_order_id)\n end\n\n return poids\n end",
"def get_orders(status: nil)\n orderitems = self.orderitems\n return {} if orderitems.empty?\n\n allorders = Hash.new\n orderitems.each do |orderitem|\n order = Order.find_by_id(orderitem.order_id)\n # if no status input, will collect everything.\n # if status input, will match by status\n # would be nice if postgresql can hash\n if (status.nil? || order.status.nil?) || order.status.downcase == status\n if allorders.has_key?(order)\n allorders[order] << orderitem\n else\n allorders[order] = [orderitem]\n end\n end\n end\n\n return allorders\n end",
"def company_all_orders_by_users_company\n @user = User.find(session[:user_id]) \n @orders = Order.where(user_id: @user.id, company_id: @user.company_id)\n end",
"def build_a_set_of_orders(number_of_items)\n return @items.repeated_permutation(number_of_items).to_a\n end",
"def collect_possible_orders\n possible_orders = []\n for number_of_items in min_number_of_items..max_number_of_items\n possible_orders += build_a_set_of_orders(number_of_items)\n end\n return possible_orders\n end",
"def ordered_by\n editions.map {|e| e.orders}.flatten.map {|o| o.customer}.uniq\n end",
"def get_orders_missing_items\n\t\torders_missing_items = Array.new\n\t\tself.mws_orders.each do |o|\n\t\t\tif o.get_item_quantity_missing > 0 || o.get_item_quantity_ordered == 0\n\t\t\t\torders_missing_items << o\n\t\t\tend\n\t\tend\n\t\treturn orders_missing_items\n\tend",
"def all_orders(options)\n request :account, :get, 'allOrders', options\n end",
"def find_all_by(opts = {})\n list_all_orders(opts)\n end",
"def list_orders\n Order.list(@current_user)\n end",
"def list_products\n products.to_a.uniq(&:store_id)\n end",
"def to_hash(orders)\n #hashes of orders will be kept in an array\n orderArray = Array.new\n \n #iterate through all orders\n orders.each do |order|\n #convert object to hash\n orderhash = order_hash(order)\n #append to array of orders\n orderArray << orderhash\n end\n \n return orderArray\n end",
"def list_orders()\n get_request('listOrders?'+get_url_parameters({})).body\n end",
"def get_orders(store)\n\n init_session(store)\n\n orders = ShopifyAPI::Order.all\n\n end_session\n\n return map_source_orders(orders)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all the timetable unique drivers | def drivers_unique
driver_order_times.map{|dto| dto.order}.uniq
end | [
"def drivers\n full_attributes.map(&:driver).uniq.reject(&:nil?)\n end",
"def return_all_drivers\n return @trips.map{ |trip| trip.driver }\n end",
"def driver_ids\n\t\tdrivers.map{|d| d.id.to_s + \"_\" + self.id.to_s}\n\tend",
"def available_drivers\n drivers = []\n collect_drivers.each do |key, value|\n drivers.push(\"dbi:#{key}:\")\n end \n return drivers\n end",
"def past_drivers\n trips = RideShare::Trip.by_rider(@id) # all trip instances of Rider\n driver_ids = trips.map { |trip| trip.driver_id }\n driver_ids.uniq.map { |id| RideShare::Driver.find(id) } # removes duplicates\n # returns all Driver instances for this Rider instance\n end",
"def orders_unique\n driver_order_times.map{|dto| dto.order}.uniq\n end",
"def drivers\n rides.map {|ride| ride.driver}\n end",
"def get_unique_device_types client, mediaspot_id, period\r\n\r\n\t\tdate_filter = get_date_filter_per_period(period)\r\n\r\n\t filter = {client_name: client}\r\n \tfilter[:mediaspot_id] = mediaspot_id unless mediaspot_id.blank?\r\n\t\tfilter[:time.gte] = date_filter\r\n\r\n\t\tAnalyticsDeviceTypesPerHour\r\n\t\t.where(filter)\r\n\t\t.distinct(:device_type)\r\n\t\t.to_a\r\n\r\n\tend",
"def nutDeviceTable\n (1..upsc.devices.size).to_a\n end",
"def num_of_drivers(slots)\n drivers = 0\n\n sorted_slots = slots.sort_by { |slot| [slot[0], slot[1]] } # O(N log(N))\n timed_slots = {}\n\n for slot in sorted_slots do # O(N), where N is number of time slots \n start_time = slot[0] \n timed_slots[start_time] = (timed_slots[start_time] || []).push(slot) \n end \n \n for slot in sorted_slots do # O(N)\n start_time = slot[0]\n available_slots = timed_slots[start_time]\n\n if available_slots == []\n next\n end\n\n drivers += 1\n slot = available_slots.shift\n endtime = slot[1]\n\n while (endtime <= 24) # O(1), loops no more than 24 times\n if (timed_slots.has_key?(endtime) && timed_slots[endtime] != [])\n slot = timed_slots[endtime].shift\n endtime = slot[1]\n next\n end\n\n endtime += 1\n end\n end\n\n # Total complexity O(N) + O(N log(N)) => O(N log(N))\n\n return drivers\nend",
"def get_slots_by_drivers()\n\tdrivers_details=%x{lspci -Dvmmkn}\n\tdrivers_lines=drivers_details.split(\"\\n\")\n\tif(drivers_lines[drivers_lines.length-1].include? \":\")\n\t\tdrivers_lines.push(\" \")\n\tend\n\n\tdrivers=Hash.new\n\tslot=\"\"\n\tdriver=\"(none)\"\n\tdrivers_lines.each do |line|\n\t\tif line.include? \":\"\n\t\t\tif line.include? \"Slot\" \n\t\t\t\tline.slice! \"Slot:\"\n\t\t\t\tslot=line.strip\n\t\t\telsif line.include? \"Driver\" \n\t\t\t\tline.slice! \"Driver:\"\n\t\t\t\tdriver=line.strip\n\t\t\tend\n\t\telse\t\n\t\t\tif drivers.key?(driver)\n\t\t\t\tdrivers[driver]=drivers[driver]+\",\"+slot\n\t\t\telsif \n\t\t\t\tdrivers[driver]=slot\n\t\t\tend\t\t\n\t\tend\n\tend\n\treturn drivers\nend",
"def registered_drivers; end",
"def drivers\n rides.map do |i|\n i.driver\n end \n end",
"def get_all_uuids\n ble_uuids = Hardware.all_ble_uuids.map { |hw| hw.identifier }\n \n render :status => 200, :json => { :uuids => ble_uuids }\n end",
"def vehicles_by_driver_age(driver_age)\n registration_numbers = []\n\n @parking_lot.parking_slots.each do |_, parking_slot|\n if parking_slot.vehicle && parking_slot.vehicle.driver_age == driver_age\n registration_numbers << parking_slot.vehicle.registration\n end\n end\n registration_numbers\n end",
"def registered_drivers=(_arg0); end",
"def unique_scanned_hosts\n hosts = []\n scanned_hosts = self.show_scanned_hosts\n scanned_hosts.each do |sh|\n sh.hosts.split(\", \").each do |host|\n if host.scan(\"0/24\").empty?\n hosts << host.gsub(/\\s+/, \"\")\n else\n host = host.gsub(/\\s+/, \"\").gsub(\"0/24\", \"\")\n (0..255).each do |last_digit|\n tmp_host = \"#{host}#{last_digit}\" \n hosts << tmp_host\n end\n end\n end\n end\n return hosts.uniq.sort\n end",
"def getUntappdUnique\n db.execute(\"SELECT name FROM #{@untappdTable} GROUP BY name\")\n end",
"def fetch_cartodbfied_tables\n (fetch_non_raster_cartodbfied_tables + fetch_raster_tables).uniq\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
validate we get iss login_hint params for oidc entrypoint | def validate_oidc_login(params)
# Validate Issuer. Different than other LTI implementations since for now
# we will only support integration with one service, if more than one
# integration enabled, then changed to check a list of issuers
if params['iss'].nil? && params['iss'] != @lti_config_hash["iss"]
raise LtiError.new("Could not find issuer", :bad_request)
end
# Validate Login Hint.
return unless params['login_hint'].nil?
raise LtiError.new("Could not find login hint", :bad_request)
end | [
"def valid_for_params_auth?; end",
"def openid_check_authentication(request); end",
"def verify_iat; end",
"def authorize_net_login_id\n end",
"def signed_open_id_connect_initiation_url(login_hint:)\n URI(open_id_connect_initiation_url).tap do |uri|\n uri.query = {\n iss: Rails.application.secrets.issuer,\n login_hint: login_hint,\n target_link_uri: target_link_uri\n # lti_message_hint: 'xxx'\n }.to_query\n end\n end",
"def oidc_login\n identity_provider_login(\"oidc_login\")\n end",
"def saml_login\n identity_provider_login(\"saml_login\")\n end",
"def validate!\n sts_request = Net::HTTP::Post.new(\"https://#{host}\").tap do |req|\n headers.each do |k, v|\n req[k] = v\n end\n req['authorization'] = authorization\n req['accept'] = 'application/json'\n req.body = STS_REQUEST_BODY\n end\n http = Net::HTTP.new(host, 443)\n http.use_ssl = true\n http.start do\n resp = Timeout.timeout(VALIDATE_TIMEOUT, Error::CredentialCheckError, 'GetCallerIdentity request timed out') do\n http.request(sts_request)\n end\n payload = JSON.parse(resp.body)\n if resp.code != '200'\n aws_code = payload.fetch('Error').fetch('Code')\n aws_message = payload.fetch('Error').fetch('Message')\n msg = \"Credential check for user #{access_key_id} failed with HTTP status code #{resp.code}: #{aws_code}: #{aws_message}\"\n msg += '.' unless msg.end_with?('.')\n msg += \" Please check that the credentials are valid, and if they are temporary (i.e. use the session token) that the session token is provided and not expired\"\n raise Error::CredentialCheckError, msg\n end\n payload.fetch('GetCallerIdentityResponse').fetch('GetCallerIdentityResult')\n end\n end",
"def validate_nrps_access\n # rubocop:disable Layout/LineLength\n if @jwt[:body]['https://purl.imsglobal.org/spec/lti-nrps/claim/namesroleservice'].nil? ||\n @jwt[:body]['https://purl.imsglobal.org/spec/lti-nrps/claim/namesroleservice']['context_memberships_url'].nil? ||\n @jwt[:body]['https://purl.imsglobal.org/spec/lti-nrps/claim/namesroleservice']['context_memberships_url'].empty?\n raise LtiError.new(\"NRPS context membership url not found\", :bad_request)\n end\n # rubocop:enable Layout/LineLength\n end",
"def authorize!\n # Ensure keys match\n if key = params['oauth_consumer_key']\n if secret = $oauth_creds[key]\n @tp = IMS::LTI::ToolProvider.new(key, secret, params)\n else\n @tp = IMS::LTI::ToolProvider.new(nil, nil, params)\n @tp.lti_msg = \"Your consumer didn't use a recognized key.\"\n @tp.lti_errorlog = \"You did it wrong!\"\n return show_error \"Consumer key wasn't recognized\"\n end\n else\n return show_error \"No consumer key\"\n end\n \n # Ensure OAuth signature is valid\n if !@tp.valid_request?(request)\n return show_error \"The OAuth signature was invalid\"\n end\n\n # Ensure timestamp is valid\n if Time.now.utc.to_i - @tp.request_oauth_timestamp.to_i > 5*60\n return show_error \"Your request is too old.\"\n end\n\n # Ensure nonce is valid\n if was_nonce_used?(@tp.request_oauth_nonce)\n return show_error \"Why are you reusing the nonce?\"\n else\n cache_nonce(@tp.request_oauth_nonce, @tp.request_oauth_timestamp.to_i)\n end\n \n # Save the launch parameters for use in later requests\n session[:launch_params] = @tp.to_params\n\n # Get the username, using \"Anonymous\" as a default if none exists\n @username = @tp.username(\"Anonymous\")\nend",
"def check_config_params\n unless params[:redirect_uri] =~ %r{\\Ahttps?://(rapportive\\.com|rapportive\\.jelzo\\.com|localhost)(:\\d+)?/raplets/} &&\n params[:response_type] == 'token' && params[:client_id] == 'rapportive'\n raise \"invalid configuration parameters\"\n end\n end",
"def authenticate_with_rfid_or_pin\n raise Knock::UserNotFound unless entity.present?\n end",
"def valid_principals; end",
"def invalid_identity_credentials?\n params[:provider] == \"identity\" && params.has_key?(:auth_key)\n end",
"def check_juggernaut_params\n render :nothing => true, :status => 401 and return unless params[:client_id]\n render :nothing => true, :status => 401 and return unless params[:session_id]\n end",
"def valid_principals=(_arg0); end",
"def sign_in\n SAML::User::AUTHN_CONTEXTS.fetch(authn_context)\n .fetch(:sign_in)\n .merge(account_type:)\n rescue\n { service_name: 'unknown', account_type: 'N/A' }\n end",
"def login_required?\n !using_open_id?\n end",
"def secretsignin\n # COMMENT OUT THE FOLLOWING THREE LINES TO REENABLE SECRETSIGNIN\n flash[:error] = 'The secretsignin page has been disabled by kyc.'\n redirect_to :root\n return\n\n uid = params[:uid]\n name = params[:name]\n user = User.find_by_uid(uid)\n\n if user\n sign_in user\n else\n params = {name: name, uid: uid}\n user = User.create(params)\n sign_in user\n end\n redirect_to root_url\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check state matches what was already sent in oidc_login | def validate_state(params)
if params["state"].nil?
raise LtiError.new("no state found", :bad_request)
end
# match previous state cookie from oidc_login
return unless cookies["lti1p3_#{params['state']}"] != params["state"]
raise LtiError.new("state cookie not found or correct", :bad_request)
end | [
"def valid_state?(state)\n log :debug, \" ------ Expected state #{session[:state]}, received #{state} ------\"\n session[:state] == state\n end",
"def check_new_credentials(state, context)\n put(:sync, @lock_data)\n validate_new_credentials(state, context)\n send_auth(@user_device)\n get(:show, id: @lock.id)\n validate_new_credentials(state, context)\n end",
"def openid_check_authentication(request); end",
"def update_authorizationstate(update)\n case update.authorization_state\n when TD::Types::AuthorizationState::WaitPhoneNumber # stage 0: set login \n @logger.warn 'Logging in..'\n @telegram.set_authentication_phone_number(@session[:login], PERMISSIONS[:login]) if @session[:login]\n @xmpp.send_message(@jid, nil, 'Please, enter your Telegram login via /login 12345') if not @session[:login]\n when TD::Types::AuthorizationState::WaitCode # stage 1: wait for auth code \n @logger.warn 'Waiting for authorization code..'\n @xmpp.send_message(@jid, nil, 'Please, enter authorization code via /code 12345')\n when TD::Types::AuthorizationState::WaitPassword # stage 2: wait for 2fa\n @logger.warn 'Waiting for 2FA password..'\n @xmpp.send_message(@jid, nil, 'Please, enter 2FA passphrase via /password 12345')\n when TD::Types::AuthorizationState::Ready # stage 3: auth completed\n @session[:login] ||= @me.phone_number \n @logger.warn 'Authorization successful!'\n @telegram.get_me.then{|me| @me = me}.wait\n @telegram.get_chats(TD::Types::ChatList::Main.new, 9223372036854775807, 0, 999).wait\n @xmpp.send_presence(@jid, nil, :subscribe, nil, nil)\n @xmpp.send_presence(@jid, nil, :subscribed, nil, nil)\n @xmpp.send_presence(@jid, nil, nil, nil, \"Logged in as: %s\" % @session[:login])\n end\n end",
"def login_required?\n !using_open_id?\n end",
"def show_login_state?(command)\n command.task != \"login\" && command.user.onboarded?\n end",
"def state?(state)\n @_state == state\n end",
"def passport_update_required?\n self.profile.state != self.passport.state || self.current_state != self.passport.state || self.profile.name != self.passport.full_name\n end",
"def state?(state)\n @state == state\n end",
"def check_online_state(source,nick,srcclist=nil)\n usr = User.first(:nickname=>source)\n return ret_fail(source+' not found') if usr == nil #user not found (can only occur after own account deletion...as a bug)\n\n #if user not in contact list -> request denied\n contact = usr.contacts.first(:userid => User.first(:nickname => nick).id)\n return ret_fail(nick+' not in your contact list') if contact == nil\n\n #check now authorization - if no authorization, dont tell state (no permission) but thats not a ret_fail!\n return {'response'=>true,'state'=>'hidden'} if contact.authgiven != 't'\n\n #everything's fine -> get state\n\n if $sessions.index(nick) != nil #that user has a session running -> online\n state = 'online'\n else\n state = 'offline'\n end\n\n return {'response'=>true, 'state'=>state}\nend",
"def authok?\n @authok\n end",
"def check_vlogin_state\n unless session[:vimeo_token]\n redirect_to vlogin_user_path\n else\n VimeoClient::save_credentials(session[:vimeo_token], session[:vimeo_secret])\n end\n return false\n end",
"def validate_auth_response(code:, state:)\n post_json(\"#{endpoint}/api/oauth2/callback\", code: code, state: state)\n end",
"def check_session_status\n logged_in? ? 'Logged in' : failure_reason\n end",
"def est05_ValidLogin_TC_24862\n\t\t$browser.cookies.clear\n\t\t$browser.goto($patch_login)\n\t\t$login_page_email.set(\"#{$user_1_email}\")\n\t\t$login_page_password.set(\"#{$master_password}\")\n\t\t$login_page_sign_in.click\n\t\t\n\t\tassert $header_profile_avatar.exists?\n\n\tend",
"def login_check(response)\n\t\t\tif response.code == '200'\n\t\t\t\tputs \"#{response.code} - #{response.message} : Logged in\"\n\t\t\telse\n\t\t\t\tputs \"#{response.code} - #{response.body} : Failed to log in\"\n\t\t\t\tabort #if login fails, then abort\n\t\t\tend\n\t\tend",
"def needs_login?() false end",
"def auth_failed?\n @state == ZOO_AUTH_FAILED_STATE\n end",
"def validate_state(state = {}); end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ensure id_token is a valid jwt | def validate_jwt_format(id_token)
if id_token.nil?
raise LtiError.new("no id token found in request", :bad_request)
end
jwt_parts = id_token.split(".")
if jwt_parts.size != 3
raise LtiError.new("JWT not valid", :bad_request)
end
@jwt = { header: JSON.parse(Base64.urlsafe_decode64(jwt_parts[0])),
body: JSON.parse(Base64.urlsafe_decode64(jwt_parts[1])),
sig: JSON.parse(Base64.urlsafe_decode64(jwt_parts[1])) }
end | [
"def validate_token\n begin\n decode_token\n rescue JWT::DecodeError, JWT::ExpiredSignature, InvalidTokenError\n render json: {error: 'Unauthorized'}, status: :unauthorized\n end\n end",
"def validate_id_token(id_token)\n\n id_token_header_raw, id_token_payload_raw, id_token_signature_raw = id_token.split(\".\")\n\n # base 64 decode\n id_token_header_json = JSON.parse(Base64.decode64(id_token_header_raw.strip))\n id_token_payload_json = JSON.parse(Base64.decode64(id_token_payload_raw.strip))\n id_token_signature = Base64.decode64(id_token_signature_raw.strip)\n\n # 1. check if payload's issuer is from Intuit\n issue = id_token_payload_json.fetch('iss')\n unless issue.eql? @client.issuer_uri\n return false\n end\n\n # 2. check if the aud matches the client id\n aud = id_token_payload_json.fetch('aud').first\n unless aud.eql? @client.id\n return false\n end\n\n # 3. check if the expire time is not expired\n exp = id_token_payload_json.fetch('exp')\n if exp < Time.now.to_i\n return false\n end\n\n # 4. check if the signature is correct\n response = IntuitOAuth::Transport.request('GET', @client.jwks_uri, nil, nil, false)\n body = response.body\n\n keys = JSON.parse(body).fetch('keys').first\n standard_kid = keys.fetch('kid')\n kid_in_id_token = id_token_header_json.fetch('kid')\n\n unless standard_kid.eql? kid_in_id_token\n return false\n end\n\n return true\n\n end",
"def validate_jwt(encoded_jwt)\n startAnonymous.uri('/api/jwt/validate')\n .authorization('Bearer ' + encoded_jwt)\n .get()\n .go()\n end",
"def validate_id_token(id_token)\n # The second parameter is the public key to verify the signature.\n # However, that key is overridden by the value of the executed block\n # if one is present.\n claims, header =\n JWT.decode(id_token, nil, true, verify_options) do |header|\n # There should always be one key from the discovery endpoint that\n # matches the id in the JWT header.\n x5c = signing_keys.find do |key|\n key['kid'] == header['kid']\n end['x5c'].first\n # The key also contains other fields, such as n and e, that are\n # redundant. x5c is sufficient to verify the id token.\n OpenSSL::X509::Certificate.new(JWT.base64url_decode(x5c)).public_key\n end\n return claims, header if claims['nonce'] == read_nonce\n fail JWT::DecodeError, 'Returned nonce did not match.'\n end",
"def jwt_authenticate?(jwt_id)\n !(jwt_id == get_jwt_id)\n end",
"def validate_jwt(encoded_jwt)\n start.uri('/api/jwt/validate')\n .authorization('JWT ' + encoded_jwt)\n .get()\n .go()\n end",
"def decode_id_token(id_token)\n decoded = JSON::JWT.decode(id_token, :skip_verification)\n algorithm = decoded.algorithm.to_sym\n\n validate_client_algorithm!(algorithm)\n\n keyset =\n case algorithm\n when :HS256, :HS384, :HS512\n secret\n else\n public_key\n end\n\n decoded.verify!(keyset)\n ::OpenIDConnect::ResponseObject::IdToken.new(decoded)\n rescue JSON::JWK::Set::KidNotFound\n # If the JWT has a key ID (kid), then we know that the set of\n # keys supplied doesn't contain the one we want, and we're\n # done. However, if there is no kid, then we try each key\n # individually to see if one works:\n # https://github.com/nov/json-jwt/pull/92#issuecomment-824654949\n raise if decoded&.header&.key?('kid')\n\n decoded = decode_with_each_key!(id_token, keyset)\n\n raise unless decoded\n\n decoded\n end",
"def user_id_in_token? # Metodo que validad la autenticidad del token\n http_token && auth_token && auth_token[:user_id].to_i\n end",
"def authorized_token?\n begin\n JWT.decode(params[:token], ENV[\"JWT_SECRET\"]) === ENV[\"JWT_ID\"]\n rescue StandardError => e\n @@logger.error \"=================> INVALID AUTHENTICATION TOKEN ERROR: #{e}\"\n return false\n end\n end",
"def validate_token(token)\n object_from_response(Code42::TokenValidation, :get, \"authToken/#{token.to_s}\")\n end",
"def verify_iat; end",
"def validate_token_claims(token)\n raise InvalidJwtError.early_token if token['nbf'] > Time.now\n\n raise InvalidJwtError.bad_issuer if token['iss'] != @config.issuer\n\n raise InvalidJwtError.lousy_audience if token['aud'] != @config.audience\n end",
"def verify_id_token!\n require 'jwt'\n require 'openssl'\n @certificates ||= {}\n if !self.authorization.respond_to?(:id_token)\n raise ArgumentError, (\n \"Current authorization mechanism does not support ID tokens: \" +\n \"#{self.authorization.class.to_s}\"\n )\n elsif !self.authorization.id_token\n raise ArgumentError, (\n \"Could not verify ID token, ID token missing. \" +\n \"Scopes were: #{self.authorization.scope.inspect}\"\n )\n else\n check_cached_certs = lambda do\n valid = false\n for key, cert in @certificates\n begin\n self.authorization.decoded_id_token(cert.public_key)\n valid = true\n rescue JWT::DecodeError, Signet::UnsafeOperationError\n # Expected exception. Ignore, ID token has not been validated.\n end\n end\n valid\n end\n if check_cached_certs.call()\n return true\n end\n response = self.execute!(\n :http_method => :get,\n :uri => 'https://www.googleapis.com/oauth2/v1/certs',\n :authenticated => false\n )\n @certificates.merge!(\n Hash[MultiJson.load(response.body).map do |key, cert|\n [key, OpenSSL::X509::Certificate.new(cert)]\n end]\n )\n if check_cached_certs.call()\n return true\n else\n raise InvalidIDTokenError,\n \"Could not verify ID token against any available certificate.\"\n end\n end\n return nil\n end",
"def authenticate_token\n puts \"AUTHENTICATE JWT\"\n render json: {status: 401, message: \"unauthorized\"} unless decode_token(bearer_token)\n end",
"def verify_access_token\n auth_token = request.headers['Authorization']\n user_id = auth_token.split(':').first\n \n if user_id == params[:id]\n @user = User.find(user_id)\n render json: UserSerializer.new(@user).serialized_json\n else\n render json: { error: I18n.t('unauthorized') }, status: 401\n end\n end",
"def any_authenticity_token_valid?; end",
"def decode_token\n # byebug\n begin\n JWT.decode(get_auth_headers, \"userSecret\")[0][\"user_id\"]\n rescue\n nil\n end\n end",
"def verify(bearer_token)\n JWT.decode(bearer_token, config.secret)\n rescue JWT::VerificationError, JWT::DecodeError\n false\n end",
"def decode_jwt_no_sig_check(token)\n JWT.decode(token, nil, false).first\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Right now, we only allow / validate LtiResourceLinkRequest since this is the message type needed for launches to get course context information needed for syncing | def validate_link_request
message_type = @jwt[:body]["https://purl.imsglobal.org/spec/lti/claim/message_type"]
if message_type.nil? || message_type != "LtiResourceLinkRequest"
raise LtiError.new("LTI launch is not an LtiResourceLinkRequest", :bad_request)
end
id = @jwt[:body]["https://purl.imsglobal.org/spec/lti/claim/resource_link"]["id"]
if id.nil?
raise LtiError.new("Missing Resource Link ID", :bad_request)
end
# checking for required fields of id token
# http://www.imsglobal.org/spec/security/v1p0/#id-token
if @jwt[:body]['sub'].nil?
raise LtiError.new("sub required in LTI launch", :bad_request)
end
# check that claim version is for LTI Advantage
if @jwt[:body]['https://purl.imsglobal.org/spec/lti/claim/version'] != "1.3.0"
raise LtiError.new("launch claim version is not 1.3.0", :bad_request)
end
return unless @jwt[:body]["https://purl.imsglobal.org/spec/lti/claim/roles"].nil?
raise LtiError.new("Roles claim not found", :bad_request)
end | [
"def message\n message = IMS::LTI::Models::Messages::BasicLTILaunchRequest.new(request.request_parameters)\n message.launch_url = request.url\n message\n end",
"def resource_handler\n [{\n 'resource_type' => {\n 'code' => 'lti2_reference_tool_provider'\n },\n 'resource_name' => {\n 'default_value' => 'lti2_reference_tool_provider'\n },\n 'message' => [{\n 'message_type' => 'basic-lti-launch-request',\n 'path' => '/basic-launch',\n 'enabled_capability' => []\n }]\n }]\n end",
"def create\n @link_resource = LinkResource.new(link_resource_params)\n\n respond_to do |format|\n if @link_resource.save\n format.html { redirect_to @lab, notice: 'Link resource was successfully created.' }\n format.json { render action: 'show', status: :created, location: @link_resource }\n else\n format.html { render action: 'new' }\n format.json { render json: @link_resource.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @link_request = LinkRequest.new(link_request_params)\n @link_request.user_id = current_user.id\n respond_to do |format|\n if @link_request.save\n format.html { redirect_to @link_request, notice: 'Link request was successfully created.' }\n format.json { render :show, status: :created, location: @link_request }\n else\n format.html { render :new }\n format.json { render json: @link_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def before_create(linkrequest)\n# self.validate\n# linkrequest.id = UUIDTools::UUID.timestamp_create().to_s\n end",
"def create\n logger.info \"link_requests_controller.create: you have #{link_request_params}\"\n \n @link_request = LinkRequest.new(link_request_params)\n @link_request.user = @user\n respond_to do |format|\n if @link_request.save\n @link_request.initial_approvals(@user) # Approve what you can as the originator\n @link_request.send_approval_request\n format.html { redirect_to @link_request, notice: 'Link request was successfully created.' }\n format.json { render :show, status: :created, location: @link_request }\n else\n format.html { render :new }\n format.json { render json: @link_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def resource_link=(value)\n @resource_link = value\n end",
"def update_lti_link(lti_link_id, create_lti_link_data)\n path = \"/d2l/api/le/#{$le_ver}/lti/link/#{lti_link_id}\"\n payload = {\n 'Title' => '',\n 'Url' => '',\n 'Description' => '',\n 'Key' => '',\n 'PlainSecret' => '',\n 'IsVisible' => false,\n 'SignMessage' => false,\n 'SignWithTc' => false,\n 'SendTcInfo' => false,\n 'SendContextInfo' => false,\n 'SendUserId' => false,\n 'SendUserName' => false,\n 'SendUserEmail' => false,\n 'SendLinkTitle' => false,\n 'SendLinkDescription' => false,\n 'SendD2LUserName' => false,\n 'SendD2LOrgDefinedId' => false,\n 'SendD2LOrgRoleId' => false,\n 'UseToolProviderSecuritySettings' => false,\n 'CustomParameters' => nil # or Array of CustomParameter\n # e.g. [{\"Name\" => \"\", \"Value\" => \"\"},{\"Name\" => \"\", \"Value\" => \"\"}]\n }.merge!(create_lti_link_data)\n check_create_lti_link_data_validity(payload)\n _put(path, payload)\nend",
"def get_lti_link_info(org_unit_id, lti_link_id)\n path = \"/d2l/api/le/#{$le_ver}/lti/link/#{org_unit_id}/#{lti_link_id}\"\n _get(path)\nend",
"def resource_link\n return @resource_link\n end",
"def initialize()\n super\n @odata_type = \"#microsoft.graph.mailAssessmentRequest\"\n end",
"def create\n @link_resource = LinkResource.new(params[:link_resource])\n\n respond_to do |format|\n if @link_resource.save\n format.html { redirect_to([:scaffold, @link_resource], :notice => 'Link resource was successfully created.') }\n format.xml { render :xml => @link_resource, :status => :created, :location => @link_resource }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @link_resource.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new_resource_label\n t('crudible.links.new')\n end",
"def create\n\t\t@course = Course.find_by_id(params[:course_id])\n\t\tunless params[:course].nil?\n\t\t\tparams[:course][:resources_attributes].each do |f|\n\t\t\t\tlink_body = f[1][:link]\n\t\t\t\tunless link_body.nil?\n\t\t\t\t\tif link_body.empty?\n\t\t\t\t\t\tResource.find(f[1][:id]).destroy\n\t\t\t\t\telse\n\t\t\t\t\t\tbegin\n\t\t\t\t\t\t\tpage = MetaInspector.new(link_body,\n\t\t\t\t\t\t\t\t:allow_redirections => :all, :timeout => 50)\n\t\t\t\t\t\t\ttype = page.content_type\n\t\t\t\t\t\t\turl = page.url.chomp(\"\\/\")\n\t\t\t\t\t\t\ttitle = page.meta_og_title || page.title\n\t\t\t\t\t\t\tdescription = (type.eql? \"application/pdf\") ? nil : page.description\n\t\t\t\t\t\t\timages = page.images.slice!(0,8)\n\t\t\t\t\t\t\timages.insert(0,page.image) unless page.image.blank?\n\t\t\t\t\t\t\tresource = { link: url, description: description,\n\t\t\t\t\t\t\t\timg: images.first, link_type: type }\n\t\t\t\t\t\trescue\n\t\t\t\t\t\t\tflash[:notice] =\n\t\t\t\t\t\t\t\t\"link #{link_body} is not valid or check your internet connection!!\"\n\t\t\t\t\t\t\tresource = nil\n\t\t\t\t\t\tend\n\t\t\t\t\t\tunless resource.nil?\n\t\t\t\t\t\t\t@resource = Resource.find_by(id: f[1][:id],\n\t\t\t\t\t\t\t\tcourse_id: @course.id)\n\t\t\t\t\t\t\tif @resource.nil?\n\t\t\t\t\t\t\t\t@resource = Resource.new(resource)\n\t\t\t\t\t\t\t\t@resource.remote_img_url = resource[:img]\n\t\t\t\t\t\t\t\t@course.resources << @resource\n\t\t\t\t\t\t\t\tcurrent_lecturer.resources << @resource\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tunless resource[:link].eql? @resource.link\n\t\t\t\t\t\t\t\t\t@resource.update_attributes(resource)\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\trender action: :index\n\tend",
"def new\n @program_link_resource = ProgramLinkResource.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @program_link_resource }\n end\n end",
"def create\n @program_link_resource = ProgramLinkResource.new(params[:program_link_resource])\n\n respond_to do |format|\n if @program_link_resource.save\n format.html { redirect_to([:scaffold, @program_link_resource], :notice => 'Program link resource was successfully created.') }\n format.xml { render :xml => @program_link_resource, :status => :created, :location => @program_link_resource }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @program_link_resource.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def supported_as_aln_resource (mod)\n if mod.class.eql?(AlnResource)\n mod.supporter = self\n mod\n else\n if mod.respond_to?(:aln_resource) \n mod.aln_resource.supporter = self\n mod.aln_resource\n else\n raise(PlanB::InvalidClass, \"target model is invalid\")\n end\n end\n end",
"def new\n @link_resource = LinkResource.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @link_resource }\n end\n end",
"def update\n respond_to do |format|\n if @link_resource.update(link_resource_params)\n format.html { redirect_to @lab, notice: 'Link resource was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @link_resource.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
make sure that we are given the context_memberships_url otherwise, we can't call / access NRPS | def validate_nrps_access
# rubocop:disable Layout/LineLength
if @jwt[:body]['https://purl.imsglobal.org/spec/lti-nrps/claim/namesroleservice'].nil? ||
@jwt[:body]['https://purl.imsglobal.org/spec/lti-nrps/claim/namesroleservice']['context_memberships_url'].nil? ||
@jwt[:body]['https://purl.imsglobal.org/spec/lti-nrps/claim/namesroleservice']['context_memberships_url'].empty?
raise LtiError.new("NRPS context membership url not found", :bad_request)
end
# rubocop:enable Layout/LineLength
end | [
"def context\n membership_request || position || raise( \"No context is possible\" )\n end",
"def club_protect\n if session[:club_id]\n @current_membership = Membership.find_by_user_id_and_club_id(session[:user_id], session[:club_id], :conditions => [\"status=?\", \"current\"])\n if session[:user_id] == 6\n @current_membership = true\n end\n \n if !@current_membership \n flash[:notice] = \"Sorry, the page you were trying to access is only for approved \" + Club.find(session[:club_id]).initials + \" members.<BR />Request membership below.\"\n redirect_to club_memberships_path(session[:club_id])\n return false\n end\n end\n \n \n end",
"def check_user_before_membership\n if current_user\n ncm_membership = current_user.get_membership(@mother)\n epicenter = Epicenter.find_by_slug(params['epicenter_id'])\n\n if epicenter != @mother and not ncm_membership\n session[:new_ncm_membership] = { \n :epicenter_id => params['epicenter_id'], \n :membership_id => params['membership_id'],\n :t => Time.now\n }\n #\n redirect_to new_epicenter_subscription_path(@mother)\n end\n else\n # it's possible that we can put the logic from \"authenticate\" method below here\n redirect_to epicenters_path\n end\n end",
"def membership_request_for?(user)\n !membership_request_for(user).nil?\n end",
"def check_current_user\n if current_user.membership != \"Club Member\"\n flash[:alert] = \"Only Club Member can book lessons\"\n redirect_to member_profile_path\n end\n end",
"def allow_request_membership?(user = User.current_user)\n user.present? &&\n project_administrators.any? &&\n !has_member?(user) &&\n MessageLog.recent_project_membership_requests(user.try(:person),self).empty?\n end",
"def mband_membership_required\n redirect_to '/' unless @mband.members.include?(current_user)\n end",
"def allow_request_membership?(user = User.current_user)\n user.present? &&\n project_administrators.any? &&\n !has_member?(user) &&\n MessageLog.recent_project_membership_requests(user.try(:person),self).empty?\n end",
"def publicize_membership(org, user, options = T.unsafe(nil)); end",
"def query_nrps\n # Initially use the context membership url to start querying NRPS\n next_page_url = @lti_context_membership_url\n members = []\n while !next_page_url.nil?\n conn = Faraday.new(\n url: next_page_url,\n headers: { 'Content-Type' => 'application/json' }\n )\n # make a GET request to NRPS endpoint using access token from request_access_token\n response = conn.get(\"\") do |req|\n req.headers[\"Authorization\"] = \"Bearer #{@access_token}\"\n req.headers[\"Accept\"] = \"application/vnd.ims.lti-nrps.v2.membershipcontainer+json\"\n # filter on Learners\n req.params[\"role\"] = \"http://purl.imsglobal.org/vocab/lis/v2/membership#Learner\"\n end\n # append member page to array\n members.concat(JSON.parse(response.body)[\"members\"])\n\n # determine if there are more pages\n # More information on member pagination:\n # https://www.imsglobal.org/spec/lti-nrps/v2p0#limit-query-parameter\n next_page_url = nil\n next_page_header = response.headers[\"link\"]\n next if next_page_header.nil?\n\n # regex match for next page link\n # regex string taken from\n # https://github.com/1EdTech/lti-1-3-php-library/blob/master/src/lti/LTI_Names_Roles_Provisioning_Service.php\n matches = /<([^>]*)>;\\s*rel=\"next\"/.match(next_page_header)\n unless matches.nil?\n next_page_url = matches[1]\n end\n end\n members\n end",
"def current_member?\n current_membership.present?\n end",
"def check_for_invite_or_user\n redirect_to invites_path unless doesnt_need_an_invite || allowed_request?\n end",
"def valid?(context = self)\n return false if context.site_name.nil? || context.webex_id.nil?\n return false if context.password.nil? && context.session_ticket.nil?\n true\n end",
"def open_listings_with_missing_payment_info?(user_id, community_id)\n paypal_active?(community_id) &&\n !user_and_community_ready_for_payments?(user_id, community_id) &&\n PaymentHelper.open_listings_with_payment_process?(community_id, user_id)\n end",
"def requirements_for_membership\n Reqs::RequirementsForMembership\n end",
"def validate_membership\n errors.add(\"#{self.sadhak_profile.syid}\", \"is not active member to forum #{self.sy_club.name}.\") unless self.sy_club_member.approve?\n errors.empty?\n end",
"def conceal_membership(org, user, options = T.unsafe(nil)); end",
"def ensure_context_admin\n return true if @lti_launch && token_has_admin_scope(@lti_launch.lti_context_id)\n render :json => { :error => \"Unauthorized for this context\" }, status: :unauthorized\n false\n end",
"def party_memberships\n respond_to?(:partyHasPartyMembership) ? partyHasPartyMembership : []\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
final LTI launch flow endpoint validate id_token, jwt, check we have NRPS access redirect to users/:id/lti_launch_initialize for final linking | def launch
# Code based on:
# https://github.com/IMSGlobal/lti-1-3-php-library/blob/master/src/lti/LTI_Message_Launch.php
unless File.exist?("#{Rails.configuration.lti_config_location}/lti_config.yml")
raise LtiError.new("LTI configuration not found on Autolab Server", :internal_server_error)
end
# load LTI configuration from file
@lti_config_hash =
YAML.safe_load(File.read("#{Rails.configuration.lti_config_location}/lti_config.yml"))
@user = current_user
validate_state(params)
id_token = params["id_token"]
validate_jwt_format(id_token)
validate_jwt_signature(id_token)
validate_nonce
validate_registration
validate_link_request
validate_nrps_access
if !current_user.present?
raise LtiError.new("Not logged in!", :bad_request)
end
redirect_to lti_launch_initialize_user_path(
@user,
course_memberships_url: @jwt[:body]["https://purl.imsglobal.org/spec/lti-nrps/claim/namesroleservice"]["context_memberships_url"],
course_title: @jwt[:body]["https://purl.imsglobal.org/spec/lti/claim/context"]["title"],
platform: @jwt[:body]["https://purl.imsglobal.org/spec/lti/claim/tool_platform"]["name"],
context_id: @jwt[:body]["https://purl.imsglobal.org/spec/lti/claim/context"]["id"],
)
end | [
"def validate_link_request\n message_type = @jwt[:body][\"https://purl.imsglobal.org/spec/lti/claim/message_type\"]\n if message_type.nil? || message_type != \"LtiResourceLinkRequest\"\n raise LtiError.new(\"LTI launch is not an LtiResourceLinkRequest\", :bad_request)\n end\n\n id = @jwt[:body][\"https://purl.imsglobal.org/spec/lti/claim/resource_link\"][\"id\"]\n if id.nil?\n raise LtiError.new(\"Missing Resource Link ID\", :bad_request)\n end\n # checking for required fields of id token\n # http://www.imsglobal.org/spec/security/v1p0/#id-token\n if @jwt[:body]['sub'].nil?\n raise LtiError.new(\"sub required in LTI launch\", :bad_request)\n end\n # check that claim version is for LTI Advantage\n if @jwt[:body]['https://purl.imsglobal.org/spec/lti/claim/version'] != \"1.3.0\"\n raise LtiError.new(\"launch claim version is not 1.3.0\", :bad_request)\n end\n return unless @jwt[:body][\"https://purl.imsglobal.org/spec/lti/claim/roles\"].nil?\n\n raise LtiError.new(\"Roles claim not found\", :bad_request)\n end",
"def launch\n @launch = Launch.find(params[:deep_link_launch_id])\n @form_url = @launch.decoded_jwt[Rails.configuration.lti_claims_and_scopes['deep_linking_claim']]['deep_link_return_url']\n @deep_link_jwt = Lti13Service::DeepLinkJwt.new(@launch, lti_tool_launches_url(@tool), params[:content_items])\n end",
"def generate_launch_data\n raise IMS::LTI::InvalidLTIConfigError, \"Not all required params set for tool launch\" unless has_required_params?\n\n params = self.to_params\n params['lti_version'] ||= 'LTI-1p0'\n params['lti_message_type'] ||= 'basic-lti-launch-request'\n uri = URI.parse(@launch_url)\n\n if uri.port == uri.default_port\n host = uri.host\n else\n host = \"#{uri.host}:#{uri.port}\"\n end\n\n consumer = OAuth::Consumer.new(@consumer_key, @consumer_secret, {\n :site => \"#{uri.scheme}://#{host}\",\n :signature_method => \"HMAC-SHA1\"\n })\n\n path = uri.path\n path = '/' if path.empty?\n if uri.query && uri.query != ''\n CGI.parse(uri.query).each do |query_key, query_values|\n unless params[query_key]\n params[query_key] = query_values.first\n end\n end\n end\n options = {\n :scheme => 'body',\n :timestamp => @timestamp,\n :nonce => @nonce\n }\n request = consumer.create_signed_request(:post, path, nil, options, params)\n\n # the request is made by a html form in the user's browser, so we\n # want to revert the escapage and return the hash of post parameters ready\n # for embedding in a html view\n hash = {}\n request.body.split(/&/).each do |param|\n key, val = param.split(/=/).map { |v| CGI.unescape(v) }\n hash[key] = val\n end\n hash\n end",
"def authenticate_lti_signature(options = {})\n return true if Rails.env == 'development' && request.local?\n \n unless params['oauth_consumer_key'] && params[:context_id] && params[:resource_link_id] && params[:user_id]\n @heading = \"Insufficient LTI parameters received\"\n render :template => \"shared/error\"\n return false\n end\n \n consumer_key = params['oauth_consumer_key']\n secret = OAUTH_CREDS[consumer_key]\n unless secret\n @heading = \"LTI error: unrecognized consumer key\"\n logger.warn \"LTI consumer key for #{consumer_key} has not been configured\"\n render :template => \"shared/error\"\n return false\n end\n \n @tp = IMS::LTI::ToolProvider.new(consumer_key, secret, params)\n \n if !@tp.valid_request?(request)\n @heading = \"LTI error: invalid OAuth signature\"\n render :template => \"shared/error\"\n return false\n end\n \n if @tp.request_oauth_timestamp && (Time.now.utc.to_i - @tp.request_oauth_timestamp.to_i > 60*60)\n @heading = \"LTI error: request too old\"\n render :template => \"shared/error\"\n return false\n end\n \n if was_nonce_used_in_last_x_minutes?(@tp.request_oauth_nonce, 60)\n @heading = \"LTI error: reused nonce\"\n render :template => \"shared/error\"\n return false\n end\n \n return true\n end",
"def lti_setup\n lti_configuration = LtiConfiguration.find_by(consumer_key: request.params[\"oauth_consumer_key\"])\n raise LtiLaunchError.new(nil), \"Configured consumer key is invalid.\" unless lti_configuration\n\n strategy = request.env[\"omniauth.strategy\"]\n raise LtiLaunchError.new(nil), \"Incoming request is not a LTI launch\" unless strategy\n\n strategy.options.consumer_key = lti_configuration.consumer_key\n strategy.options.shared_secret = lti_configuration.shared_secret\n head :ok\n end",
"def populate_launch_context\n populate_payload_for_launch_patient_scope if token.payload['scp'].include?('launch/patient')\n populate_payload_for_launch_scope if token.payload['scp'].include?('launch')\n true\n end",
"def launch\n app_instance = MnoEnterprise::AppInstance.find_by(uid: params[:id])\n MnoEnterprise::EventLogger.info('app_launch', current_user.id, 'App launched', app_instance)\n redirect_to MnoEnterprise.router.launch_url(params[:id], {wtk: MnoEnterprise.jwt(user_id: current_user.uid)}.reverse_merge(request.query_parameters))\n end",
"def validate_nrps_access\n # rubocop:disable Layout/LineLength\n if @jwt[:body]['https://purl.imsglobal.org/spec/lti-nrps/claim/namesroleservice'].nil? ||\n @jwt[:body]['https://purl.imsglobal.org/spec/lti-nrps/claim/namesroleservice']['context_memberships_url'].nil? ||\n @jwt[:body]['https://purl.imsglobal.org/spec/lti-nrps/claim/namesroleservice']['context_memberships_url'].empty?\n raise LtiError.new(\"NRPS context membership url not found\", :bad_request)\n end\n # rubocop:enable Layout/LineLength\n end",
"def authorize!\n # Ensure keys match\n if key = params['oauth_consumer_key']\n if secret = $oauth_creds[key]\n @tp = IMS::LTI::ToolProvider.new(key, secret, params)\n else\n @tp = IMS::LTI::ToolProvider.new(nil, nil, params)\n @tp.lti_msg = \"Your consumer didn't use a recognized key.\"\n @tp.lti_errorlog = \"You did it wrong!\"\n return show_error \"Consumer key wasn't recognized\"\n end\n else\n return show_error \"No consumer key\"\n end\n \n # Ensure OAuth signature is valid\n if !@tp.valid_request?(request)\n return show_error \"The OAuth signature was invalid\"\n end\n\n # Ensure timestamp is valid\n if Time.now.utc.to_i - @tp.request_oauth_timestamp.to_i > 5*60\n return show_error \"Your request is too old.\"\n end\n\n # Ensure nonce is valid\n if was_nonce_used?(@tp.request_oauth_nonce)\n return show_error \"Why are you reusing the nonce?\"\n else\n cache_nonce(@tp.request_oauth_nonce, @tp.request_oauth_timestamp.to_i)\n end\n \n # Save the launch parameters for use in later requests\n session[:launch_params] = @tp.to_params\n\n # Get the username, using \"Anonymous\" as a default if none exists\n @username = @tp.username(\"Anonymous\")\nend",
"def launch\n # Get a completely fresh session for each launch. This is a rails method.\n reset_session\n cookies.clear\n redirect_to home_path, alert: \"Please provide the server_url, client_id, and client_secret.\" and return if !all_credentials_provided?\n # Set auth sessions with params values\n session[:launch] = params[:launch].present? ? params[:launch].strip : \"launch\"\n session[:iss_url] = cookies[:iss_url] = params[:iss_url].strip.delete_suffix(\"/\").delete_suffix(\"/metadata\")\n session[:client_id] = params[:client_id].strip\n session[:client_secret] = params[:client_secret].strip\n session[:scope] = params[:scope]&.strip\n # Get the server metadata\n rcResult = get_server_metadata(session[:iss_url])\n redirect_to home_path, alert: rcResult and return if rcResult.class == String\n # Logic for authenticated access server\n if session[:is_auth_server?]\n begin\n server_auth_url = set_server_auth_url()\n redirect_to server_auth_url\n rescue StandardError => exception\n redirect_back fallback_location: home_path, alert: \"Failed to connect: #{exception.message}\" and return\n end\n # Logic for unauthenticated server access: the user will provide the patient ID in the client_id & client_secret fields.\n else\n session[:patient_id] = session[:client_secret]\n redirect_to dashboard_url, notice: \"Signed in with Patient ID: #{session[:patient_id]}\"\n end\n cookies.clear\n end",
"def login\n login_stage1 #login stage 1, request unauthorized token\n login_stage2 #login stage 2, try to log in ang get the verifier\n if @authorized\n login_stage3 #if we have verifier, we get the access token key\n else #if we not have verifier, authentication or not oob callback selected, request manual login, return the url\n return @request_token.authorize_url\n end\n end",
"def validate_oidc_login(params)\n # Validate Issuer. Different than other LTI implementations since for now\n # we will only support integration with one service, if more than one\n # integration enabled, then changed to check a list of issuers\n if params['iss'].nil? && params['iss'] != @lti_config_hash[\"iss\"]\n raise LtiError.new(\"Could not find issuer\", :bad_request)\n end\n\n # Validate Login Hint.\n return unless params['login_hint'].nil?\n\n raise LtiError.new(\"Could not find login hint\", :bad_request)\n end",
"def relaunch_lti_tool\n @redirect_url = session[:canvas_lti_tool_uri]\n render layout: false\n end",
"def start_url_redirect\n puts \">> start_url_redirect...\"\n # UrlVerifier.new.delay.vu_starter\n UrlVerifier.new.vu_starter\n end",
"def oidc_login\n unless File.exist?(\"#{Rails.configuration.lti_config_location}/lti_config.yml\")\n raise LtiError.new(\"LTI configuration not found on Autolab Server\", :internal_server_error)\n end\n\n # load LTI configuration from file\n @lti_config_hash =\n YAML.safe_load(File.read(\"#{Rails.configuration.lti_config_location}/lti_config.yml\"))\n\n # code based on: https://github.com/IMSGlobal/lti-1-3-php-library/blob/master/src/lti/LTI_OIDC_Login.php\n # validate OIDC\n validate_oidc_login(params)\n # Build OIDC Auth Response\n # Generate State.\n # Set cookie (short lived)\n state = SecureRandom.uuid\n stateCookie = \"lti1p3_#{state}\"\n cookies[stateCookie] = { value: state, expires_in: 1.hour }\n\n # generate nonce, store in cache for user\n @user = current_user\n nonce = \"nonce-#{SecureRandom.uuid}\"\n Rails.cache.write(\"nonce-#{@user.id}\", nonce, expires_in: 3600)\n prefix = \"https://\"\n if ENV[\"DOCKER_SSL\"] == \"false\"\n prefix = \"http://\"\n end\n begin\n hostname = if Rails.env.development?\n request.base_url\n else\n prefix + request.host\n end\n rescue StandardError\n hostname = `hostname`\n hostname = prefix + hostname.strip\n end\n\n # build response\n auth_params = {\n \"scope\": \"openid\", # oidc scope\n \"response_type\": \"id_token\", # oidc response is always an id token\n \"response_mode\": \"form_post\", # oidc response is always a form post\n \"client_id\": @lti_config_hash[\"developer_key\"], # client id (developer key)\n \"redirect_uri\": \"#{hostname}/lti_launch/launch\", # URL to return to after login\n \"state\": state, # state to identify browser session\n \"nonce\": nonce, # nonce to prevent replay attacks\n \"login_hint\": params[\"login_hint\"], # login hint to identify platform session\n \"prompt\": \"none\"\n }\n unless params[\"lti_message_hint\"].nil?\n auth_params[\"lti_message_hint\"] = params[\"lti_message_hint\"]\n end\n\n # put auth params as URL query parameters for redirect\n @encoded_params = URI.encode_www_form(auth_params)\n\n redirect_to \"#{@lti_config_hash['auth_url']}?#{@encoded_params}\"\n end",
"def check_config_params\n unless params[:redirect_uri] =~ %r{\\Ahttps?://(rapportive\\.com|rapportive\\.jelzo\\.com|localhost)(:\\d+)?/raplets/} &&\n params[:response_type] == 'token' && params[:client_id] == 'rapportive'\n raise \"invalid configuration parameters\"\n end\n end",
"def validate_token_and_user\n passed_token = request.headers.fetch('Authorization', nil)\n\n # Navigate a browser elsewhere if there is no token\n redirect_to root_path and return if passed_token.blank?\n\n @token_response = cmr_client.validate_launchpad_token(passed_token)\n\n if @token_response.success?\n auid = @token_response.body.fetch('auid', nil)\n @urs_profile_response = cmr_client.get_urs_uid_from_nams_auid(auid)\n\n if @urs_profile_response.success?\n urs_uid = @urs_profile_response.body.fetch('uid', '')\n @requester_has_approver_permissions = is_non_nasa_draft_approver?(user: User.new(urs_uid: urs_uid), token: passed_token)\n else\n Rails.logger.info \"User with auid #{session[:auid]} does not have an associated URS account or the account could not be located. Cannot validate user for approved proposals: #{@urs_profile_response.clean_inspect}\"\n\n render json: { error: \"Could not locate associated URS account for user with auid #{session[:auid]}\" }, status: :unauthorized\n # TODO: is this the right status to return for this scenario?\n end\n\n else\n Rails.logger.info \"Could not authenticate Launchpad token and verify user to return approved proposals: #{@token_response.clean_inspect}\"\n\n if @token_response.status == 401\n render json: { error: 'Launchpad token unauthorized' }, status: :unauthorized\n else\n false\n end\n end\n end",
"def login_url(prt, opts = {})\n plid = login_request(prt, :requested => opts.delete(:requested), :seed => opts.delete(:seed)).plid\n login_url_from_plid( plid, opts.delete(:demo) )\n end",
"def successful_openid_authentication( identity_url, registration = {} )\n throw \"Implement me in this controller!\"\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
LTI launch entrypoint to initiate open id connect login build our authentication response and redirect back to platform | def oidc_login
unless File.exist?("#{Rails.configuration.lti_config_location}/lti_config.yml")
raise LtiError.new("LTI configuration not found on Autolab Server", :internal_server_error)
end
# load LTI configuration from file
@lti_config_hash =
YAML.safe_load(File.read("#{Rails.configuration.lti_config_location}/lti_config.yml"))
# code based on: https://github.com/IMSGlobal/lti-1-3-php-library/blob/master/src/lti/LTI_OIDC_Login.php
# validate OIDC
validate_oidc_login(params)
# Build OIDC Auth Response
# Generate State.
# Set cookie (short lived)
state = SecureRandom.uuid
stateCookie = "lti1p3_#{state}"
cookies[stateCookie] = { value: state, expires_in: 1.hour }
# generate nonce, store in cache for user
@user = current_user
nonce = "nonce-#{SecureRandom.uuid}"
Rails.cache.write("nonce-#{@user.id}", nonce, expires_in: 3600)
prefix = "https://"
if ENV["DOCKER_SSL"] == "false"
prefix = "http://"
end
begin
hostname = if Rails.env.development?
request.base_url
else
prefix + request.host
end
rescue StandardError
hostname = `hostname`
hostname = prefix + hostname.strip
end
# build response
auth_params = {
"scope": "openid", # oidc scope
"response_type": "id_token", # oidc response is always an id token
"response_mode": "form_post", # oidc response is always a form post
"client_id": @lti_config_hash["developer_key"], # client id (developer key)
"redirect_uri": "#{hostname}/lti_launch/launch", # URL to return to after login
"state": state, # state to identify browser session
"nonce": nonce, # nonce to prevent replay attacks
"login_hint": params["login_hint"], # login hint to identify platform session
"prompt": "none"
}
unless params["lti_message_hint"].nil?
auth_params["lti_message_hint"] = params["lti_message_hint"]
end
# put auth params as URL query parameters for redirect
@encoded_params = URI.encode_www_form(auth_params)
redirect_to "#{@lti_config_hash['auth_url']}?#{@encoded_params}"
end | [
"def login\n login_stage1 #login stage 1, request unauthorized token\n login_stage2 #login stage 2, try to log in ang get the verifier\n if @authorized\n login_stage3 #if we have verifier, we get the access token key\n else #if we not have verifier, authentication or not oob callback selected, request manual login, return the url\n return @request_token.authorize_url\n end\n end",
"def login\n options = {\n type: 'OneView',\n file_env_var: 'ONEVIEW_AUTH_FILE',\n env_var_url: 'ONEVIEW_URL',\n filename: '/login.json'\n }\n credentials = load_authentication_settings(options)\n credentials[:hardware_variant] ||= 'C7000'\n credentials[:hardware_variant] = credentials[:hardware_variant].to_s.capitalize\n credentials\nend",
"def initiate_oidc_login\n javascript_redirect(oidc_protected_page)\n end",
"def login\n openid_url = params[:openid_url]\n\n authenticate_with_open_id(openid_url) { |result, identity_url, sreg|\n if result.successful?\n @open_id_credential = OpenIdCredential.find_by_identity_url(identity_url)\n if @open_id_credential\n @open_id_credential.login!\n session[:user_id] = @open_id_credential.user_id\n set_notice(p_(\"MultiAuth\", \"Logged in successfully.\"))\n redirect_to(root_path)\n else\n set_notice(p_(\"MultiAuth\", \"This OpenID has not been registered yet.\"))\n redirect_to(:controller => \"signup/open_id\", :action => \"index\")\n end\n else\n failed_login(result.message)\n end\n }\n end",
"def login\n validate_arguments!\n\n Turbot::Auth.login\n display \"Authentication successful.\"\n end",
"def daw_login_prompt\n logger.debug '[rdaw] redirecting to login form.'\n rdaw_logout\n\n if respond_to?(:rdaw_login_url, true)\n url = rdaw_login_url\n else\n prefix = Rdaw.const_defined?('DAW_EXTERNAL_URL_PREFIX') ? Rdaw::DAW_EXTERNAL_URL_PREFIX : Rdaw::DAW_URL_PREFIX\n url = [prefix, '/login?appIdKey=', Rdaw::APP_ID_KEY, encoded_daw_return_path].tap do |a|\n a << \"&rv=#{Rdaw::APP_RV}\" if Rdaw.const_defined?('APP_RV')\n end.join\n end\n\n redirect_to(url) and return false\n end",
"def launch\n # Get a completely fresh session for each launch. This is a rails method.\n reset_session\n cookies.clear\n redirect_to home_path, alert: \"Please provide the server_url, client_id, and client_secret.\" and return if !all_credentials_provided?\n # Set auth sessions with params values\n session[:launch] = params[:launch].present? ? params[:launch].strip : \"launch\"\n session[:iss_url] = cookies[:iss_url] = params[:iss_url].strip.delete_suffix(\"/\").delete_suffix(\"/metadata\")\n session[:client_id] = params[:client_id].strip\n session[:client_secret] = params[:client_secret].strip\n session[:scope] = params[:scope]&.strip\n # Get the server metadata\n rcResult = get_server_metadata(session[:iss_url])\n redirect_to home_path, alert: rcResult and return if rcResult.class == String\n # Logic for authenticated access server\n if session[:is_auth_server?]\n begin\n server_auth_url = set_server_auth_url()\n redirect_to server_auth_url\n rescue StandardError => exception\n redirect_back fallback_location: home_path, alert: \"Failed to connect: #{exception.message}\" and return\n end\n # Logic for unauthenticated server access: the user will provide the patient ID in the client_id & client_secret fields.\n else\n session[:patient_id] = session[:client_secret]\n redirect_to dashboard_url, notice: \"Signed in with Patient ID: #{session[:patient_id]}\"\n end\n cookies.clear\n end",
"def login\n if current_user and params[:return_to]\n # Already logged in; just need to send a token to the requesting\n # API client.\n #\n # FIXME: if current_user has never authorized this app before,\n # ask for confirmation here!\n\n send_api_token_to(params[:return_to], current_user)\n elsif params[:return_to]\n redirect_to \"/auth/joshid?return_to=#{CGI.escape(params[:return_to])}\"\n else\n redirect_to \"/auth/joshid\"\n end\n end",
"def login\n redirect_to esdl_suite_service.auth_uri(new_nonce), allow_other_host: true\n end",
"def oidc_login\n identity_provider_login(\"oidc_login\")\n end",
"def login\n validate_arguments!\n\n Pebbles::Auth.login\n display \"Authentication successful.\"\n end",
"def start_web_authn_login(request)\n start.uri('/api/webauthn/start')\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .post()\n .go()\n end",
"def auth\n authorization_url = WorkOS::SSO.authorization_url(\n domain: params[:domain],\n client_id: CLIENT_ID,\n redirect_uri: ENV['WORKOS_REDIRECT_URI'],\n )\n\n redirect_to authorization_url\n end",
"def handle\n self.login\n end",
"def login\n #Clear buf from initial socket creation/opening\n response \n # Send auth string to FreeSWITCH\n self << \"auth #{@auth}\"\n #Return response, clear buf for rest of commands\n response \n end",
"def login\n backend = config_backend == 'local' ? '--local' : config_backend\n ::Kitchen::Pulumi::ShellOut.run(\n cmd: \"login #{backend}\",\n logger: logger,\n )\n end",
"def login_do\n api_key = params[:api_key]\n api_secret = params[:api_secret]\n if api_key.blank? || api_secret.blank?\n redirect_to root_url, alert: \"Api credentials are invalid...\"\n return\n end\n @existing_apps = NexmoApi.apps(api_key, api_secret)\n if @existing_apps == nil\n redirect_to root_url, alert: \"Api credentials are invalid.\"\n else\n session[:api_key] = api_key\n session[:api_secret] = api_secret\n redirect_to app_url, notice: \"Logged in!\"\n end\n end",
"def complete_web_authn_login(request)\n startAnonymous.uri('/api/webauthn/login')\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .post()\n .go()\n end",
"def open_auth_url()\n # link = \"Insert desired link location here\"\n if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/\n system \"start #{@auth_response}\"\n elsif RbConfig::CONFIG['host_os'] =~ /darwin/\n system('open', @auth_response)\n elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/\n system \"xdg-open #{@auth_response}\"\n end \n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this method iterates through all events and creates a hash with different lists of points sorted by metric | def createPointHash(chunk)
pointHash = Hash.new
# add each event to our hash, sorted by metrics as key
chunk.msgpack_each {|(tag, time, record)|
timestamp = time.to_i
metric = record["metric"]
# if there is no list for the current metric -> create a new one
if pointHash[metric] == nil
if record["chronix_type"] == "strace"
pointHash[metric] = {"startTime" => timestamp, "lastTimestamp" => 0, "points" => Chronix::StracePoints.new, "prevDelta" => 0, "timeSinceLastDelta" => 0, "lastStoredDate" => timestamp}
else
pointHash[metric] = {"startTime" => timestamp, "lastTimestamp" => 0, "points" => Chronix::Points.new, "prevDelta" => 0, "timeSinceLastDelta" => 0, "lastStoredDate" => timestamp}
end
end
if pointHash[metric]["lastTimestamp"] == 0
delta = 0
else
delta = timestamp - pointHash[metric]["lastTimestamp"]
end
if (almostEquals(delta, pointHash[metric]["prevDelta"]) && noDrift(timestamp, pointHash[metric]["lastStoredDate"], pointHash[metric]["timeSinceLastDelta"]))
# insert the current point in our list
pointHash[metric]["points"].p << createChronixPoint(0, record["values"][0], record["chronix_type"])
pointHash[metric]["timeSinceLastDelta"] += 1
else
# insert the current point in our list
pointHash[metric]["points"].p << createChronixPoint(delta, record["values"][0], record["chronix_type"])
pointHash[metric]["timeSinceLastDelta"] = 1
pointHash[metric]["lastStoredDate"] = timestamp
end
# save current timestamp as lastTimestamp and the previousOffset
pointHash[metric]["lastTimestamp"] = timestamp
pointHash[metric]["prevDelta"] = delta
} #end each
return pointHash
end | [
"def index\n\n # Load events\n @event_points = []\n\n # Look up point values, or assign the default value of 0\n # events.each do |event|\n Event.order(:start_time).all.reverse.each do |event|\n event_points = EventPoints.where(event_id: event.id).first\n points = event_points ? event_points.value : 0\n\n @event_points << { event: event, points: points }\n end\n\n end",
"def mapOfAllEvents\n events = self.getAllEvents\n result = Hash.new\n\n events.each do |sport, evs|\n evs.each do |eventID, event|\n result[eventID] = event\n end\n end\n result\n end",
"def make_histograms_by_hour\n _by_hour = samples_by_hour.dup\n _by_hour.each_key do |hour|\n hour_samples = _by_hour[hour]\n next if hour_samples.length < 2\n histogram = PointHistogram.new(hour_samples)\n buckets = histogram.calculate\n\n point_infos = buckets.map do |bucket|\n {\n :name => bucket[:count],\n :lat => bucket[:lat],\n :lon => bucket[:lon]\n }\n end\n\n _by_hour[hour] = point_infos\n end\n\nrequire 'pry'; binding.pry\n _by_hour\n end",
"def unique_events_data\n categories.each_with_object({}) do |category, category_results|\n events_names = events_for_category(category)\n\n event_results = events_names.each_with_object({}) do |event, hash|\n hash[\"#{event}_weekly\"] = unique_events(**weekly_time_range.merge(event_names: [event])) unless event == \"i_package_composer_deploy_token\"\n hash[\"#{event}_monthly\"] = unique_events(**monthly_time_range.merge(event_names: [event]))\n end\n\n if eligible_for_totals?(events_names) && CATEGORIES_FOR_TOTALS.include?(category)\n event_results[\"#{category}_total_unique_counts_weekly\"] = unique_events(**weekly_time_range.merge(event_names: events_names))\n event_results[\"#{category}_total_unique_counts_monthly\"] = unique_events(**monthly_time_range.merge(event_names: events_names))\n end\n\n category_results[\"#{category}\"] = event_results\n end\n end",
"def build_event_hash\n\t\t@event_hash = {}\n\t\t\n\t\teach_event { |event| @event_hash[event.id] = event }\n\tend",
"def events_by_prio(events_per_source)\n @p_idx ||= SOURCES.keys.inject({}) {|hsh, s| hsh[SOURCES[s][:prio]] = s; hsh}\n @p_idx.keys.sort.reverse.collect {|prio| events_per_source[@p_idx[prio]] || [] }\n end",
"def process_event_hash(events)\n unless events.nil?\n events\n .values\n .reject { |i| i.nil? || is_out_of_range(i.time)}\n .sort_by! { |i| i.time }\n .reverse\n end\nend",
"def sort\n\t@events = @events.sort_by { | e | e.time_from_start }\n\trecalc_delta_from_times()\n end",
"def get_datapoints_hash\n dps = self.outcome_data_points.select([\"arm_id\",\"outcome_measure_id\",\"value\",\"is_calculated\",\"footnote_number\"])\n retVal = Hash.new\n unless dps.empty?\n dps.each do |dp|\n arm_id = dp.arm_id\n measure_id = dp.outcome_measure_id\n key = \"#{self.outcome_id}_#{self.timepoint_id}_#{arm_id}_#{measure_id}\"\n retVal[key] = [dp.value,dp.is_calculated,dp.footnote_number]\n end\n end\n return retVal\n end",
"def metrics_as_points\n ts = Time.now.to_i\n\n metrics.each_with_object([]) do |(category, metric), aggr|\n metric.values.each do |v|\n aggr.<< ({ path: [PATH_BASE, category, v[0]].join('.'),\n value: v[2],\n ts: ts })\n end\n end\n end",
"def group_by_date(events)\n grouped_events = ActiveSupport::OrderedHash.new\n\n events.each do |event|\n if event.created_at.today?\n grouped_events[:today] ||= []\n grouped_events[:today] << event\n\n elsif yesterday?(event.created_at)\n grouped_events[:yesterday] ||= []\n grouped_events[:yesterday] << event\n\n else\n key = event.created_at.strftime('%d %b %Y')\n grouped_events[key] ||= []\n grouped_events[key] << event\n end\n end\n\n grouped_events\n end",
"def sort_events(all_events)\n all_events.group_by(&:pod).sort_by { |name, ev| [ev.last.stamp, name] }\nend",
"def events\n metadata['events'].sort_by! { |event| event['timestamp'] }\n end",
"def generate_unique_events(n_events)\n (1..n_events).map do |i|\n { service: 's', metric: 'm', period: 'year', timestamp: '20150101', value: i }\n end\n end",
"def points\n @points ||= begin\n h = Hash.new\n Point::ABS_POINTS_DATA.each do |pt_name|\n h.merge!(pt_name => Point.new(film, pt_name))\n end\n h\n end\n end",
"def sorted_events\n events.sort_by { |ev| ev.event_point || CollectionProtocolEvent::DEFAULT_EVENT_POINT }\n end",
"def events\n self.metadata['events'].sort_by! {|event| event['timestamp'] }\n end",
"def all_events_with_stat\n events\n .map { |name, arr| [name, arr.size] }\n .flatten\n end",
"def parse_events(events)\n events.map do |k, v|\n begin\n Stats::StatsParser.parse(k, v)\n rescue Stats::StatsParser::StatsKeyValueInvalid\n logger.notify(\"Invalid stats key-value. k: #{k}. v: #{v}\")\n nil\n end\n end.reject(&:nil?)\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks if there is a drift | def noDrift(timestamp, lastStoredDate, timeSinceLastDelta)
calcMaxOffset = @threshold * timeSinceLastDelta
drift = lastStoredDate + calcMaxOffset - timestamp.to_i
return (drift <= (@threshold / 2))
end | [
"def need_tock?\n if @second == 60\n @second = 0\n tock\n end\n end",
"def trial_over?\n unless self.trial_started_at.blank?\n return Time.now - APP_CONFIG['trial_length'].days > self.trial_started_at\n else\n return false\n end\n end",
"def allowed_clock_drift\n return options[:allowed_clock_drift] || 0\n end",
"def timed_mission?\n return !duration.nil?\n end",
"def verify_with_drift(otp, drift, time = Time.now)\n time = time.to_i\n times = (time-drift..time+drift).step(interval).to_a\n times << time + drift if times.last < time + drift\n times.any? { |ti| verify(otp, ti) }\n end",
"def miss_time?\n\t\t !due_date.nil? && ((estimated_hours.to_f - spent_hours.to_f) / Setting.plugin_redmine_advanced_issues['hours_in_day'].to_f) > (due_date - Date.today)\n\t\tend",
"def timestamping?\n !timeless\n end",
"def check_duration\n calculate_duration if self.duration != get_duration\n end",
"def clock_sec?\n true\n end",
"def charged?\n return (@time <= 0)\n end",
"def is_clocked_in\n if @lp.timers(@workspace).count == 0\n return false\n else\n return true\n end\n end",
"def check_for_time_difference\n if self.actual_duration.present?\n if self.start_time.present? && self.end_time.present?\n duration =(self.end_time - self.start_time)/3600\n val1 = duration.to_f.roundf2(2).to_s\n val2 = self.actual_duration.to_f.roundf2(2).to_s\n if duration > 0 && !val1.eql?(val2)\n errors.add_to_base(:tne_valid_time)\n end\n end\n end\n end",
"def check_downtime\n if @downtime = SfmoltenPost.check_downtime_interval\n render(:layout => 'blank', :template => 'scheduled_maintenance/show')\n return false\n end\n end",
"def right_time\n scheduled_time = self.time_of_day.seconds_since_midnight\n now_time = Time.now.seconds_since_midnight\n seconds_past_scheduled = now_time - scheduled_time\n if seconds_past_scheduled > 0 && seconds_past_scheduled < location.department.department_config.task_leniency.minutes #needs doing if not done within an hour\n return true\n elsif self.kind == \"Hourly\" #not exactly valid interpretation, since hourly tasks shouldn't have a time_of_day; to prevent nil value errors\n return true\n else\n return false\n end\n end",
"def offduty_time?\n return true if [0, 6].include?(Time.now.wday)\n if @monitor_config['onduty_time_start'] and @monitor_config['onduty_time_end']\n return !(@monitor_config['onduty_time_start'] < Time.now.hour \\\n and @monitor_config['onduty_time_end'] > Time.now.hour)\n end\n end",
"def need_tick_tock?\n if @minute == 60\n @minute = 0\n tick_tock\n end\n end",
"def later?(target_time, ref_time)\n target_time.to_f - ref_time.to_f > 0.01\n end",
"def zero_hour?\n # if the times differ more than 1 minute we probably have more important issues\n needs_view && (ends_at.to_i - updated_at.to_i) < 60\n end",
"def enough_time? now\n (now - last_time) > time_interval if time_interval\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Acquire a lock with the current session, or initialize a new session | def lock(path)
Diplomat::Lock.wait_to_acquire(path, session.id)
end | [
"def acquire\n lock = lockSession\n if lock\n return resource[:acquire]\n else\n return false\n end\n end",
"def get_session_with_lock(env, sid)\n expires_at = nil\n result = nil\n max_attempt_date = Time.now.to_f + @config.lock_max_wait_time\n while result.nil?\n exceeded_wait_time?(max_attempt_date)\n begin\n result = attempt_set_lock(sid)\n rescue Aws::DynamoDB::Errors::ConditionalCheckFailedException\n expires_at ||= get_expire_date(sid)\n next if expires_at.nil?\n result = bust_lock(sid, expires_at)\n wait_to_retry(result)\n end\n end\n get_data(env, result)\n end",
"def acquire_lock\n\t\t@@logger.info { \"Acquiring a lock in the database.\" } if have_logger?\n\t\tTournament.dataset.filter(:id => self.id, :locked => false).update(:locked => true) != 0\n\tend",
"def try_lock() end",
"def set_locking_strategy\n if @config.enable_locking\n @lock = Aws::SessionStore::DynamoDB::Locking::Pessimistic.new(@config)\n else\n @lock = Aws::SessionStore::DynamoDB::Locking::Null.new(@config)\n end\n end",
"def acquire_lock!(lock_name = table_name, wait_timeout = 0, &block)\n acquire_lock(lock_name, table_name, &block) or raise LockTimeout, 'Timeout waiting for lock'\n end",
"def try_lock\n raise AlreadyAcquiredLockError if locked?\n\n uuid = SecureRandom.uuid\n set_opts = {:nx => true}\n set_opts[:px] = Integer(@expiry * 1000) if @expiry\n\n if @redis.set(@lock_key, uuid, set_opts)\n @lock_uuid = uuid\n true\n else\n false\n end\n end",
"def test\n create_lock\n acquire_lock\n end",
"def lock!\n lock_or_unlock!(action: Smartcar::LOCK)\n end",
"def acquire\n # Ensure the locks_dir directory exists\n FileUtils.mkdir_p(self.class.locks_dir)\n\n # Open PID file and attempt to obtain a filesystem lock (non-blocking)\n @lock_file ||= File.open(lock_file_path, File::RDWR|File::CREAT, 0644)\n acquired = !! @lock_file.flock(File::LOCK_EX|File::LOCK_NB)\n\n close_file unless acquired\n acquired\n end",
"def lock\n @@lock ||= Monitor.new\n end",
"def acquire\n df = EM::DefaultDeferrable.new\n expiry = new_expiry\n @redis.setnx(@key, expiry).callback { |setnx|\n if setnx == 1\n lock_acquired(expiry)\n EM::Hiredis.logger.debug \"#{to_s} Acquired new lock\"\n df.succeed(expiry)\n else\n attempt_to_acquire_existing_lock(df)\n end\n }.errback { |e|\n df.fail(e)\n }\n return df\n end",
"def acquire_shared_lock(&block)\n\t\tlockfile = config.pluginconf['chef.lockfile'] || \"/var/cache/chef/chef-client-running.pid\"\n\t\t@lockfile = File.open(lockfile, 'a+')\n\t\tif Fcntl.const_defined?('F_SETFD') and Fcntl.const_defined?('FD_CLOEXEC')\n\t\t\t@logger.debug(\"Calling fcntl on lockfile #{lockfile}\")\n\t\t\t@lockfile.fcntl(Fcntl::F_SETFD, lockfile.fcntl(Fcntl::F_GETFD, 0) | Fcntl::FD_CLOEXEC)\n\t\tend\n\n\t\t@logger.debug(\"Trying to lock lockfile #{lockfile} using flock\")\n\t\tlock_aqcuired = (!! @lockfile.flock(File::LOCK_NB | File::LOCK_SH))\n\t\tif lock_aqcuired\n\t\t\t@logger.debug(\"Lock obtained on lockfile #{lockfile}, calling block\")\n\t\t\tres = block.call\n\t\t\trelease_shared_lock\n\t\t\t@logger.debug(\"Lock released\")\n\t\telse\n\t\t\t@logger.debug(\"Failed to lock lockfile #{lockfile}\")\n\t\t\tres = false\n\t\tend\n\t\treturn res\n\tend",
"def lock\n @privkey = nil\n @locked = true\n end",
"def try_get_seed_lock\n if @semaphore.nil?\n name = \"#{@cluster_name}/#{data_center}-#{rack}\"\n @semaphore = DaemonRunner::Semaphore.lock(name, 1)\n end\n\n if @renew_thread.nil?\n @renew_thread = @semaphore.renew\n end\n end",
"def lock\n auth_state_model.transaction do\n record = auth_state_model.\n lock(true).\n find(authentication.id)\n\n yield record\n\n record\n end\n end",
"def session_begin(cred, mode)\n #This is a stub, used for indexing\n end",
"def acquire_lock\n if @lock < 1\n return 1\n else\n c_ts = Time.new\n curr_ts = c_ts.to_i\n if (@ts - curr_ts > 10)\n @ts = curr_ts # Time out lock if another client waiting too long\n return 1\n else\n return 0\n end\n end\n end",
"def lock\n raise Destroyed.new(self.name) if (self.destroyed?)\n return true if (@locked_by_us)\n #\n # TODO: Another instance of poor-man's-cache-location; see #reset\n #\n sts = InstantCache.cache.add(self.lock_name, @identity)\n @locked_by_us = (sts.to_s =~ %r!^STORED!) ? true : false\n return @locked_by_us\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if there is an active renew thread | def renew?
@renew.is_a?(Thread) && @renew.alive?
end | [
"def live_thread?\n threads.any?(&:alive?)\n end",
"def active?\n @thread&.alive?\n end",
"def lock_expired?\n now > get_lock_expiration\n end",
"def is_reschedule_request?\n status == 'reschedule_request'\n end",
"def holds_lock?\n payload = get_payload\n payload['token'] == @token && payload['state'] == 'processing'\n end",
"def any_waiting_threads?\n waiting_threads_count >= 1\n end",
"def ok?\n @threads_lock.synchronize { @threads.all? {|_, thr| thr.alive?} }\n end",
"def background_check_pending?\n !background_check_authorized_at.nil? && (!passed_background_check? && background_check_run_at.nil?)\n end",
"def active\n @locked && Time.now.to_i < @expiry\n end",
"def run_again?\n refresh_token_and_retry? ||\n server_error? && sleep_and_retry?(3) ||\n exceeded_quota? && sleep_and_retry?(3)\n end",
"def on_refresh_runnable?\n !on_refresh.nil? && on_refresh != :nothing\n end",
"def refresh_scheduled?\n next_refresh_at && next_refresh_at <= Time.current\n end",
"def renewable?\n if self.pem_exist?\n if remaining_lifetime <= renew_days or renew_days == 0\n return true\n else\n return false\n end\n else\n true\n end\n end",
"def has_lock?\n @has_lock || false\n end",
"def refresh_needed?\n if self.config.include? 'interval'\n if self.config.include? 'last_refresh_attempt'\n return Clock.time.to_i > (self.config['interval'] + self.config['last_refresh_attempt'])\n else\n return true\n end\n else\n return false\n end\n end",
"def alive?\n @thread ? @thread.alive? : false\n end",
"def lock_expired?; end",
"def running?\n @activity_thread_running\n end",
"def pending_refresh?\n last_check = checked_at || DateTime.new\n time_offset = Time.now - refresh_interval\n\n last_check.to_time < time_offset\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a thread to periodically renew the lock session | def renew!
return if renew?
@renew = Thread.new do
## Wakeup every TTL/2 seconds and renew the session
loop do
sleep ttl / 2
begin
logger.debug(" - Renewing Consul session #{id}")
Diplomat::Session.renew(id)
rescue Faraday::ResourceNotFound
logger.warn("Consul session #{id} has expired!")
init
rescue StandardError => e
## Keep the thread from exiting
logger.error(e)
end
end
end
self
end | [
"def start_cache_renew_job\n\t\tThread.new do\n\t\t\tloop do\n\t\t\t\tupdate_cache\n\t\t\t\tsleep(CONFIG[\"cache_interval\"]*60) #the cache is valid for this period of time\n\t\t\tend\n\t\tend\n\tend",
"def start_timer\n Thread.new do\n loop {\n sleep @session_ttl\n reap_old_sessions\n } \n end \n end",
"def start_timer\n Thread.new do\n loop {\n sleep @session_ttl\n reap_expired_sessions\n } \n end \n end",
"def initialize\n lock = Mutex.new\n \n Thread.new {\n thread_sleep = 3600 \n while true\n sleep thread_sleep.to_i\n lock.synchronize { \n # TODO uncomment at end of development\n #FacadeSession.delete_all(created_at.to_i.minutes > Time.now - SLEEP.to_i.minutes)\n }\n end\n }\n end",
"def refresh_lock(ttl)\n check_exists\n SideJob.redis.expire \"#{redis_key}:lock\", ttl\n end",
"def start_lock_touch_thread(logger,queue,worker_id,shard,ttl)\n t = Thread.new do\n loop do\n sleep(ttl - 5)\n begin\n queue.touch_lock(worker_id,shard,ttl)\n rescue StandardError => e\n @logger.error(\"Unable to touch lock, aborting processing immediately. #{e}\")\n exit 1\n end\n end\n end\n return t\nend",
"def spawn_update_thread\n Thread.new do\n loop do\n sleep @cache_expiration\n update_cache\n end\n end\n end",
"def renew!(holder:)\n if held_by?(holder)\n touch\n\n Lux::LOCK_OK\n else\n Lux::LOCK_NOT_OWNED\n end\n end",
"def release_seed_lock\n unless @renew_thread.nil?\n @renew_thread.kill\n @renew_thread = nil\n end\n\n unless @semaphore.nil?\n while @semaphore.locked?\n @semaphore.try_release\n sleep 0.1\n end\n @semaphore = nil\n end\n end",
"def renew_ticket(env)\n if @configuration['renew'] && env['global_session'] &&\n env['global_session'].directory.local_authority_name &&\n env['global_session'].expired_at < renew.to_i.minutes.from_now.utc\n env['global_session'].renew!\n end\n end",
"def start_timer\n synchronize do\n @timer = Thread.new do\n sleep(@period)\n release_permits\n end\n end\n end",
"def restart_check_idle_thread\n stop_idle_check_thread\n start_idle_check_thread\n end",
"def refresh_lock\n raise NotImplementedError\n end",
"def start_timeout\n timeout=Thread.new {\n sleep 300\n @session = nil\n }\n end",
"def try_get_seed_lock\n if @semaphore.nil?\n name = \"#{@cluster_name}/#{data_center}-#{rack}\"\n @semaphore = DaemonRunner::Semaphore.lock(name, 1)\n end\n\n if @renew_thread.nil?\n @renew_thread = @semaphore.renew\n end\n end",
"def try_lock() end",
"def lock_time\n 60\n end",
"def start_supernode_watch_thread\n Thread.new do \n while true\n sleep(@config['supernode_watch_interval'])\n # update online hours\n # TODO better to do this in application layer?\n user_dao = DAO::UserDAO.new(@user_db)\n user = use_dao.find\n user.online_hours += 1\n user_dao.add_or_update(user)\n\n if supernode_capable?\n # update the routing properties\n update_routing do |routing|\n routing.supernode = true\n end\n\n promote_to_supernode\n break\n end\n end\n end\n end",
"def lock_expired?; end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is an instance method that Takes all of the instance variables for an object and inserts the name of each attribute as a key and the value of that attribute as the value in a hash. This hash is then run through the .join(', ') and used to update data in the database. | def save
table = self.class.to_s.pluralize.underscore
# Uses self.instance_variables to sets instance_variables to the attributes of the object
# Without this line there would be no keys to add to the attribute_hash
instance_variables = self.instance_variables
attribute_hash = {}
# Adds the attributes to the attribute_hash as keys
#
# self.send gets the value of each attribute by using its getter method
#
# variable.slice takes of the "@" part of the attributes
instance_variables.each do |variable|
attribute_hash["#{variable.slice(1..-1)}"] = self.send("#{variable.slice(1..-1)}")
end
individual_instance_variables = []
# Adds the values of the attributes to the values of their corresponding keys
#
# value.is.a?(string) checks if the value is a string so it can put quotes around it as needed.
attribute_hash.each do |key, value|
if value.is_a?(String)
individual_instance_variables << "#{key} = '#{value}'"
else
individual_instance_variables << "#{key} = #{value}"
end
end
# Returns a string created by converting each element of the array to a string, separated by a comma and a space
for_sql = individual_instance_variables.join(', ')
CONNECTION.execute("UPDATE #{table} SET #{for_sql} WHERE id = #{self.id}")
return self
end | [
"def save\n table = self.class.to_s.pluralize.underscore\n\n # Uses self.instance_variables to sets instance_variables to the attributes of the object\n # Without this line there would be no keys to add to the attribute_hash\n\n instance_variables = self.instance_variables\n\n attribute_hash = {}\n\n # Adds the attributes to the attribute_hash as keys\n #\n # self.send gets the value of each attribute by using its getter method\n #\n # variable.slice takes of the \"@\" part of the attributes\n\n instance_variables.each do |variable|\n attribute_hash[\"#{variable.slice(1..-1)}\"] = self.send(\"#{variable.slice(1..-1)}\")\n end\n\n individual_instance_variables = []\n\n # Adds the values of the attributes to the values of their corresponding keys\n #\n # value.is.a?(string) checks if the value is a string so it can put quotes around it as needed.\n\n attribute_hash.each do |key, value|\n if value.is_a?(String)\n individual_instance_variables << \"#{key} = '#{value}'\"\n elsif\n individual_instance_variables << \"#{key} = #{value}\"\n end\n end\n # Returns a string created by converting each element of the array to a string, separated by a comma and a space\n\n for_sql = individual_instance_variables.join(', ')\n\n CONNECTION.execute(\"UPDATE #{table} SET #{for_sql} WHERE id = #{self.id}\")\n return self\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 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 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 stringify_fields\n self[:context] = self[:context].to_s if self[:context].present?\n self[:key] = self[:key].to_s if self[:key].present?\n end",
"def to_hash\n fattrs.inject({}){|h,a| h.update a => send(a)}\n end",
"def persisted_m_update_str\n ph=self.persisted_hash\n ph['marshal']=self.class.marshal.dump(self)\n ph.to_a.collect{|x| \"#{x[0]}=#{PersistentObject.sqlite_field(x[1])}\" }.join(',')\n end",
"def attributesToString\n str = \"\"\n counter = 0\n @SQLAttributes.each { |attribute| \n str += attribute[0] + \" \" + attribute[1] + \",\"\n }\n # remove the trailing comma\n str.chop!\n\n str += \",\"\n str += primaryKeysToString\n\n str += \",\"\n str += foreignKeysToString\n\n return str\n end",
"def store_attributes name, meters, rate, cost, uom, usage, confidence, invoice_rate, days=nil\r\n hash = {}\r\n if !name.blank?\r\n hash[:name] = name\r\n end\r\n if !meters.blank?\r\n hash[:meters] = meters\r\n end\r\n if !rate.blank?\r\n if(rate.class.eql?(String) && rate[0].eql?('$'))\r\n rate = rate[1...rate.size]\r\n end\r\n hash[:rate] = rate.to_f\r\n end\r\n if !cost.blank?\r\n hash[:cost] = cost\r\n end\r\n if !uom.blank?\r\n hash[:uom] = uom\r\n end\r\n if !usage.blank?\r\n hash[:usage] = usage\r\n end \r\n if !confidence.blank?\r\n hash[:confidence] = confidence\r\n end \r\n if !invoice_rate.blank?\r\n hash[:invoice_rate] = invoice_rate\r\n end \r\n if !days.blank?\r\n hash[:days] = days\r\n end\r\n self.charge_attributes = hash\r\n end",
"def dynamic_attributes_hash\n @dynamic_attributes.inject({}) { |h, da| h[da.name] = da; h}\n end",
"def attributes_with_quotes\n columns_hash = self.class.columns_hash\n @attributes.inject({}) do |attrs_quoted, pair| \n attrs_quoted[pair.first] = quote(pair.last, columns_hash[pair.first])\n attrs_quoted\n end\n end",
"def build_attribute_list#:nodoc:\r\n if options[:only]\r\n options[:attributes] = Array(options[:only])\r\n else\r\n options[:attributes] = @klass.column_names - Array(options[:except]).collect { |e| e.to_s }\r\n end\r\n \r\n options[:attributes] = options[:attributes].collect{|attr| \"#{attr}\"} \r\n options[:methods] = options[:methods].is_a?(Hash) ? options[:methods].values : Array(options[:methods])\r\n \r\n #if procs are specified as an array separate the headers(keys) from the procs(values)\r\n if options[:procs].is_a?(Hash)\r\n options[:proc_headers]= options[:procs].keys\r\n options[:procs]= options[:procs].values\r\n else\r\n options[:procs] = Array(options[:procs])\r\n options[:proc_headers]||= Array.new\r\n 0.upto(options[:procs].size - options[:proc_headers].size - 1) {|idx| options[:proc_headers] << \"proc_#{idx}\" }\r\n end\r\n \r\n end",
"def save(options) \n table = options[\"table\"] \n attributes = []\n item_id = options[\"item_id\"]\n \n instance_variables.each do |i| \n attributes << i.to_s.delete(\"@\") \n end \n \n query_components_array = [] \n \n attributes.each do |a| \n value = self.send(a) \n \n if value.is_a?(Integer) \n query_components_array << \"#{a} = #{value}\" \n else \n query_components_array << \"#{a} = '#{value}'\" \n end \n end \n \n query_components_array.shift \n \n query_string = query_components_array.join(\", \")\n\n\n DATABASE.execute(\"UPDATE #{table} SET #{query_string} WHERE id = #{item_id}\")\n \n end",
"def save(table)\n attributes = []\n\n # Example [:@serial_number, :@name, :@description]\n instance_variables.each do |i|\n # Example :@name\n attributes << i.to_s.delete(\"@\") # \"name\"\n end\n \n query_components_array = []\n\n attributes.each do |a|\n value = self.send(a)\n\n if value.is_a?(Integer)\n query_components_array << \"#{a} = #{value}\"\n else\n query_components_array << \"#{a} = '#{value}'\"\n end\n end\n\n query_string = query_components_array.join(\", \")\n\n DATABASE.execute(\"UPDATE #{table} SET #{query_string} WHERE id = #{id}\")\n end",
"def attributes=(hash={})\n assignable_fields.each do |field|\n send(\"#{field}=\", hash[field]) if hash[field]\n end\n end",
"def merge_attributes attrs\n attrs.each do |key, val|\n send(\"#{key}=\", val)\n end\n end",
"def attributes_to_save # :doc:\n attrs_to_save = attributes.clone.delete_if do |k, v|\n [:id, :password, crypted_password_field, password_salt_field, :persistence_token, :perishable_token, :single_access_token, :login_count, \n :failed_login_count, :last_request_at, :current_login_at, :last_login_at, :current_login_ip, :last_login_ip, :created_at,\n :updated_at, :lock_version].include?(k.to_sym)\n end\n attrs_to_save.merge!(:password => password, :password_confirmation => password_confirmation)\n end",
"def prepare_instance_data(hash)\n {\n \"db_instance_identifier\" => hash.fetch(:db_instance_identifier),\n \"endpoint\" => stringify_keys(hash.fetch(:endpoint)),\n \"engine\" => hash.fetch(:engine)\n }\n end",
"def meta_attributes\n a = [:id]\n instance_variables.each do |v|\n n = v.to_s.gsub('@','').to_sym\n a << n if self.respond_to?(n)\n end\n a\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /business_users/1 GET /business_users/1.xml | def show
@business_user = BusinessUser.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @business_user }
end
end | [
"def index\n @users = LinkedData::Client::Models::User.all\n respond_to do |format|\n format.html\n format.xml { render xml: @users.to_xml }\n end\n end",
"def folder_users(path)\n make_request(:get,\"#{folders_url(path)}/users.xml\")\n end",
"def show\n @users = User.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @users }\n end\n end",
"def show\n @user = User.find(params[:id])\n render :xml => @user.to_xml(:except => [ :password ])\n end",
"def list_users\n\t\t@users = User.paginate :page => params[:page], :per_page => User.per_page\n\n\t\trespond_to do |format|\n\t\t\tformat.html\n\t\t\t#format.xml\t{ render :xml => @users }\n\t\tend\n\tend",
"def get_users\n Resources::User.parse(request(:get, \"Users\"))\n end",
"def index\n @user_feeds = @feed_account.user_feeds\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @user_feeds }\n end\n end",
"def index\n @user_budges = UserBudge.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @user_budges }\n end\n end",
"def index\n @business_staffs = BusinessStaff.find(:all, :conditions => {:business_id => current_user.business.id}, :order => 'created_at desc')\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @business_staffs }\n end\n end",
"def index\n @organization_users = OrganizationUser.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @organization_users }\n end\n end",
"def to_xml\n raise WebexXmlApi::NotEnoughArguments, 'User::GetUser' unless valid?\n body_content = {}\n PARAMETER_MAPPING.each_pair do |k, v|\n body_content[v] = send(k) if send(k)\n end\n create_xml_request(@security_context.to_xml, REQUEST_TYPE,\n body_content)\n end",
"def live\n users = WebmasterTools::Verification::Config.authorized_accounts(:live).map(&:last)\n xml = %Q{<?xml version=\"1.0\"?><users><user>#{users.join(\"</user><user>\")}</user></users>}\n render :xml => xml\n end",
"def query_users(options={}) path = \"/api/v2/users\"\n get(path, options, AvaTax::VERSION) end",
"def index\n if params[:single]\n\t url = \"#{API_BASE_URL}/users/#{params[:id]}.json\"\n\t response = RestClient.get(url)\n\t @user = JSON.parse(response.body)\n\telse\n\t url = \"#{API_BASE_URL}/users.json\"\t \n response = RestClient.get(url)\n @users = JSON.parse(response.body)\t\t \n\tend\n end",
"def index\n @user_attributes = UserAttribute.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @user_attributes }\n end\n end",
"def get_users(request)\n # --- Get Users Pool ---\n user_pool = UserPoolOCCI.new(@client)\n\n # --- Prepare XML Response ---\n rc = user_pool.info\n if OpenNebula.is_error?(rc)\n return rc, CloudServer::HTTP_ERROR_CODE[rc.errno]\n end\n\n return to_occi_xml(user_pool, :code=>200, :verbose=>request.params['verbose'])\n end",
"def new\n @business_user = BusinessUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @business_user }\n end\n end",
"def index\n @iwiw_users = IwiwUser.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @iwiw_users }\n end\n end",
"def index\n @user_bills = UserBill.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @user_bills }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /business_users/new GET /business_users/new.xml | def new
@business_user = BusinessUser.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @business_user }
end
end | [
"def new\n @user = User.new\n\n respond_to do |format|\n format.xml { render xml: @user}\n end\n end",
"def new\n logger.debug(\"Create a new user\")\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = user.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = V1::User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @external_user = ExternalUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @external_user }\n end\n end",
"def new\n @boat_user_name = BoatUserName.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @boat_user_name }\n end\n end",
"def new\n @user = @client.users.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user_name = UserName.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_name }\n end\n end",
"def create\n @business_user = BusinessUser.new(params[:business_user])\n\n respond_to do |format|\n if @business_user.save\n format.html { redirect_to(@business_user, :notice => 'Business user was successfully created.') }\n format.xml { render :xml => @business_user, :status => :created, :location => @business_user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @business_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new_rest\n @dialogix_user = DialogixUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @dialogix_user }\n end\n end",
"def new\n @user_accounts = UserAccounts.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_accounts }\n end\n end",
"def new\n @boat_user_email = BoatUserEmail.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @boat_user_email }\n end\n end",
"def new\n @business = Business.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @business }\n end\n end",
"def new\n @usr = Usr.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @usr }\n end\n end",
"def new\n @user_addon = UserAddon.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_addon }\n end\n end",
"def new\n @facebook_user = FacebookUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @facebook_user }\n end\n end",
"def new\n @user_budge = UserBudge.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_budge }\n end\n end",
"def new\n @new_user = NewUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @new_user }\n end\n end",
"def new\n @business_staff = BusinessStaff.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @business_staff }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /business_users POST /business_users.xml | def create
@business_user = BusinessUser.new(params[:business_user])
respond_to do |format|
if @business_user.save
format.html { redirect_to(@business_user, :notice => 'Business user was successfully created.') }
format.xml { render :xml => @business_user, :status => :created, :location => @business_user }
else
format.html { render :action => "new" }
format.xml { render :xml => @business_user.errors, :status => :unprocessable_entity }
end
end
end | [
"def create_user payload\n\t\t\t\t\tFreshdesk::Api::Client.convert_to_hash( @connection.post USERS, payload )\n\t\t\t\tend",
"def new\n @business_user = BusinessUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @business_user }\n end\n end",
"def create_users(accountId, model) path = \"/api/v2/accounts/#{accountId}/users\"\n post(path, model, {}, AvaTax::VERSION) end",
"def to_xml\n raise WebexXmlApi::NotEnoughArguments, 'User::GetUser' unless valid?\n body_content = {}\n PARAMETER_MAPPING.each_pair do |k, v|\n body_content[v] = send(k) if send(k)\n end\n create_xml_request(@security_context.to_xml, REQUEST_TYPE,\n body_content)\n end",
"def create_user\n params = {\n :client_id => Swiftype.platform_client_id,\n :client_secret => Swiftype.platform_client_secret\n }\n post(\"users.json\", params)\n end",
"def users_to_xml(users)\n users_to_hash(users, :xml).to_xml(:root => 'users')\n end",
"def user_to_xml(user)\n user_to_hash(user, :xml).to_xml(:root => 'user')\n end",
"def createuserxml(useremail, username, roleid, restrictionid, groupids)\n userxml = Document.new\n userxml.add_element(\"user\")\n email = Element.new(\"email\")\n email.text= useremail\n userxml.root.add_element(email)\n name = Element.new(\"name\")\n name.text = username\n userxml.root.add_element(name)\n role = Element.new(\"roles\")\n role.text = roleid\n userxml.root.add_element(role)\n restriction_id = Element.new(\"restriction_id\")\n restriction_id.text = restrictionid\n userxml.root.add_element(restriction_id)\n groups = Element.new(\"groups\")\n userxml.root.add_element(groups, {\"type\" => \"array\"})\n # we can have or more of the groupIds\n groupids.each { |groupid|\n group = Element.new(\"group\")\n group.text = groupid\n groups.add_element(group)\n }\n\n return userxml # need to explicitly return in in this case because we want to return the entire xml we just built\n end",
"def create_rest\n @dialogix_user = DialogixUser.new(params[:dialogix_user])\n\n respond_to do |format|\n if @dialogix_user.save\n flash[:notice] = 'DialogixUser was successfully created.'\n format.html { redirect_to(@dialogix_user) }\n format.xml { render :xml => @dialogix_user, :status => :created, :location => @dialogix_user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @dialogix_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @wuserbusiness = Wuserbusiness.new(wuserbusiness_params)\n\n respond_to do |format|\n if @wuserbusiness.save\n format.html { redirect_to @wuserbusiness, notice: 'Wuserbusiness was successfully created.' }\n format.json { render :show, status: :created, location: @wuserbusiness }\n else\n format.html { render :new }\n format.json { render json: @wuserbusiness.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_user(**args)\n request_post('/user', **args)\n end",
"def create_user\n response = ApiCall.new('api/v1/users', :post, patient_params).make_call\n flash[\"notice\"] = response[\"error\"] ? response[\"error\"] : \"User created successfully.\"\n redirect_to('/')\n rescue\n render :template => \"errors/server_unavailable\"\n end",
"def create\n @business_profile = BusinessProfile.new(params[:business_profile])\n @business_profile.users << current_user\n @business_profile.owner = current_user.id\n \n respond_to do |format|\n if @business_profile.save\n format.html { redirect_to @business_profile, notice: 'Business profile was successfully created.' }\n format.json { render json: @business_profile, status: :created, location: @business_profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @business_profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user_business_profile = UserBusinessProfile.new(user_business_profile_params)\n\n respond_to do |format|\n if @user_business_profile.save\n format.html { redirect_to @user_business_profile, notice: 'User business profile was successfully created.' }\n format.json { render :show, status: :created, location: @user_business_profile }\n else\n format.html { render :new }\n format.json { render json: @user_business_profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @boat_user_email = BoatUserEmail.new(params[:boat_user_email])\n\n respond_to do |format|\n if @boat_user_email.save\n format.html { redirect_to(@boat_user_email, :notice => 'Boat user email was successfully created.') }\n format.xml { render :xml => @boat_user_email, :status => :created, :location => @boat_user_email }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @boat_user_email.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n doc = Nokogiri::XML(request.body.read)\n bNode = doc.xpath('elwak/benutzer')\n\n @benutzer = Benutzer.new(benutzer_params(bNode))\n if @benutzer.save\n if bNode.xpath('objekt_zuordnungs').length > 0\n objekt_ids = bNode.xpath('objekt_zuordnungs/objekt_id').map{|oz| oz.text.to_s.to_i}\n @benutzer.setze_objekt_zuordnungen(objekt_ids)\n end\n success(@benutzer.id)\n else\n error(@benutzer.errors)\n end\n end",
"def create\n @user = @users.new(params[:user])\n\n respond_to do |format|\n if @user.save\n UserMailer.deliver_join_email_to(@user)\n flash[:notice] = 'User was successfully created.'\n format.html { redirect_to(line_user_url(@line, @user)) }\n format.xml { render :xml => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @business = @user.businesses.build(business_params)\n\n respond_to do |format|\n if @business.save\n format.html { redirect_to root_path(@user), notice: 'Business was successfully created.' }\n format.json { render :show, status: :created, location: @business }\n else\n format.html { render :new }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @external_user = ExternalUser.new(params[:external_user])\n\n respond_to do |format|\n if @external_user.save\n flash[:notice] = 'ExternalUser was successfully created.'\n format.html { redirect_to(@external_user) }\n format.xml { render :xml => @external_user, :status => :created, :location => @external_user }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @external_user.errors, :status => :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PUT /business_users/1 PUT /business_users/1.xml | def update
@business_user = BusinessUser.find(params[:id])
respond_to do |format|
if @business_user.update_attributes(params[:business_user])
format.html { redirect_to(@business_user, :notice => 'Business user was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @business_user.errors, :status => :unprocessable_entity }
end
end
end | [
"def update!\n @authorize = nil\n update_plan! &&\n resp = put(\"/users/#{username}.xml\", {\n :user_key => apikey,\n \"user[first_name]\" => first_name,\n \"user[last_name]\" => last_name\n })\n end",
"def update\n @user = V1::User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = 'V1::User was successfully updated.'\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_rest\n @dialogix_user = DialogixUser.find(params[:id])\n\n respond_to do |format|\n if @dialogix_user.update_attributes(params[:dialogix_user])\n flash[:notice] = 'DialogixUser was successfully updated.'\n format.html { redirect_to(@dialogix_user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @dialogix_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @api_user = ApiUser.find(params[:id])\n\n respond_to do |format|\n if @api_user.update_attributes(params[:api_user])\n format.html { redirect_to(@api_user, :notice => 'Api user was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @api_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @external_user = ExternalUser.find(params[:id])\n\n respond_to do |format|\n if @external_user.update_attributes(params[:external_user])\n flash[:notice] = 'ExternalUser was successfully updated.'\n format.html { redirect_to(@external_user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @external_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_user id, payload\n\t\t\t\t\t(@connection.put USERS, id, payload).code\n\t\t\t\tend",
"def update\n @business = @user.businesses.find(params[:id])\n respond_to do |format|\n if @business.update(business_params)\n format.html { redirect_to edit_user_business_path(@user, @business), notice: 'Business was successfully updated.' }\n format.json { render :show, status: :ok, location: @business }\n else\n format.html { render :edit }\n format.json { render json: @business.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n setupExternalUser\n respond_to do |format|\n if @portal_external_user.update_attributes(params[:external_user])\n flash[:notice] = 'ExternalUser was successfully updated.'\n format.html { redirect_to(@portal_external_user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @portal_external_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @facebook_user = FacebookUser.find(params[:id])\n\n respond_to do |format|\n if @facebook_user.update_attributes(params[:facebook_user])\n flash[:notice] = 'FacebookUser was successfully updated.'\n format.html { redirect_to(@facebook_user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @facebook_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @company_user = CompanyUser.find(params[:id])\n\n respond_to do |format|\n if @company_user.update_attributes(params[:company_user])\n format.html { redirect_to(@company_user, :notice => 'Company user was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @company_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @boat_user_email = BoatUserEmail.find(params[:id])\n\n respond_to do |format|\n if @boat_user_email.update_attributes(params[:boat_user_email])\n format.html { redirect_to(@boat_user_email, :notice => 'Boat user email was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @boat_user_email.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @organization_user = OrganizationUser.find(params[:id])\n\n respond_to do |format|\n if @organization_user.update_attributes(params[:organization_user])\n flash[:notice] = 'OrganizationUser was successfully updated.'\n format.html { redirect_to(@organization_user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @organization_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @contract_user = ContractUser.find(params[:id])\n\n respond_to do |format|\n if @contract_user.update_attributes(params[:contract_user])\n format.html { redirect_to(@contract_user, :notice => 'ContractUser was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @contract_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @big_auth_user = BigAuth::User.find(params[:id])\n\n respond_to do |format|\n if @big_auth_user.update_attributes(params[:big_auth_user])\n format.html { redirect_to(@big_auth_user, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @big_auth_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @weibo_user = WeiboUser.find(params[:id])\n\n respond_to do |format|\n if @weibo_user.update_attributes(params[:weibo_user])\n format.html { redirect_to(@weibo_user, :notice => 'Weibo user was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @weibo_user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n if @api_v1_user.update(api_v1_user_params)\n render json: @api_v1_user\n else\n render json: @api_v1_user.errors, status: :unprocessable_entity\n end\n end",
"def update\n @user1 = User1.find(params[:id])\n\n respond_to do |format|\n if @user1.update_attributes(params[:user1])\n format.html { redirect_to(@user1, :notice => 'User1 was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user1.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @boat_user_name = BoatUserName.find(params[:id])\n\n respond_to do |format|\n if @boat_user_name.update_attributes(params[:boat_user_name])\n format.html { redirect_to(@boat_user_name, :notice => 'Boat user name was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @boat_user_name.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_user\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /business_users/1 DELETE /business_users/1.xml | def destroy
@business_user = BusinessUser.find(params[:id])
@business_user.destroy
respond_to do |format|
format.html { redirect_to(business_users_url) }
format.xml { head :ok }
end
end | [
"def delete\n @user = User.find(params[:id])\n @user.rvsps.delete_all()\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user1 = User1.find(params[:id])\n @user1.destroy\n\n respond_to do |format|\n format.html { redirect_to(user1s_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n setupExternalUser\n @portal_external_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(portal_external_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = V1::User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to(v1_users_url) }\n format.xml { head :ok }\n end\n end",
"def delete_users\n delete(users_path)\n end",
"def delete_user\n begin\n @user = User.find(params[:id])\n if(@user)\n #@sections = get_sections_for_user(@user.id);\n if @user.destroy\n #if(@sections)\n #@sections.each do |section|\n #section.destroy\n #end\n #end\n render_xml_output(\"Success\")\n else\n render_xml_output(\"Failure\")\n end\n else\n render_xml_output(\"user doesn\\'t exist\")\n end\n rescue ActiveRecord::RecordNotFound\n render_xml_output(\"No record found\")\n end\nend",
"def delete_silo_user(user_id)\n r = execute(make_xml('MultiTenantUserDeleteRequest', { 'user-id' => user_id }), '1.2')\n r.success\n end",
"def destroy\n @bb_auth_user = BbAuthUser.find(params[:id])\n @bb_auth_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(bb_auth_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @external_user = ExternalUser.find(params[:id])\n @external_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(external_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @backend_user = Backend::User.find(params[:id])\n @backend_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(backend_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @api_user = ApiUser.find(params[:id])\n @api_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(api_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @users = User.find(params[:id])\n @users.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @devex_user = DevexUser.find(params[:id])\n @devex_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(devex_users_url) }\n format.xml { head :ok }\n end\n end",
"def deleteUser\n end",
"def destroy\n @big_auth_user = BigAuth::User.find(params[:id])\n @big_auth_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(big_auth_users_url) }\n format.xml { head :ok }\n end\n end",
"def delete_user_for_tenant(args = {}) \n delete(\"/tenants.json/#{args[:tenantId]}/users/#{args[:userId]}\", args)\nend",
"def destroy\n @boat_user_email = BoatUserEmail.find(params[:id])\n @boat_user_email.destroy\n\n respond_to do |format|\n format.html { redirect_to(boat_user_emails_url) }\n format.xml { head :ok }\n end\n end",
"def delete(user)\n Rails.logger.debug \"Call to user.delete\"\n reqUrl = \"/api/user/#{self.email}\" #Set the request url\n rest_response = MwHttpRequest.http_delete_request(reqUrl,user['email'],user['password']) #Make the DELETE request to the server with the required parameters\n Rails.logger.debug \"Response from server: #{rest_response.code} #{rest_response.message}: #{rest_response.body}\"\n if rest_response.code == \"200\" #Validate if the response from the server is 200, which means OK\n return true, rest_response #Return success\n else\n return false, \"#{rest_response.code}\", \"#{rest_response.message}\" #Return error\n end\n end",
"def destroy\n @facebook_user = FacebookUser.find(params[:id])\n @facebook_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(facebook_users_url) }\n format.xml { head :ok }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /tense_entries GET /tense_entries.json | def index
@tense_entries = TenseEntry.all
end | [
"def index\n @entries = Entry.all\n\n render json: @entries\n end",
"def index\n @expense_entries = ExpenseEntry.all\n end",
"def index\n @reloud_entries = ReloudEntry.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @reloud_entries }\n end\n end",
"def index\n @exercise_entries = ExerciseEntry.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @exercise_entries }\n end\n end",
"def index\n @time_entries = TimeEntry.all\n render :json => @time_entries, status: :ok\n end",
"def get_entries(entryids)\n call_api('feed/entry', 'entry_id' => entryids)['entries']\n end",
"def index\n @entry_types = EntryType.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @entry_types }\n end\n end",
"def index\n @entries = Entry.all;\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @entries }\n end\n end",
"def index\n @entries = Entry.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @entries }\n end\n end",
"def get_entries\n @page.all(input_elements[:entries])\n end",
"def index\n @ents = Ent.all\n end",
"def index\n @timetable_entries = TimetableEntry.all\n end",
"def index\n @entries = SourceGlossaryEntry.eager_load(:locale_glossary_entries).sort_by { |e| e.source_copy.downcase }\n\n respond_with @entries do |format|\n format.json { render json: decorate(@entries).to_json }\n end\n end",
"def __entries__\n @entries\n end",
"def index\n @contestant_entries = ContestantEntry.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @contestant_entries }\n end\n end",
"def index\n @tallies = Tally.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @tallies }\n end\n end",
"def index\n @ads_entries = AdsEntry.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ads_entries }\n end\n end",
"def index\n @teleport_incenses = TeleportIncense.all\n end",
"def index\n @task_entries = TaskEntry.all\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /tense_entries POST /tense_entries.json | def create
@tense_entry = TenseEntry.new(tense_entry_params)
respond_to do |format|
if @tense_entry.save
format.html { redirect_to @tense_entry, notice: 'Tense entry was successfully created.' }
format.json { render :show, status: :created, location: @tense_entry }
else
format.html { render :new }
format.json { render json: @tense_entry.errors, status: :unprocessable_entity }
end
end
end | [
"def post_entity_entries(eid, entries)\n endpoint_url = URI.join(self.engine.base_url, \"entities/#{eid}/entries?v=#{self.engine.version}\")\n\n self.post(endpoint_url, entries.to_json)\n end",
"def index\n @tense_entries = TenseEntry.all\n end",
"def create\n @expense_entry = ExpenseEntry.new(params[:expense_entry])\n\n respond_to do |format|\n if @expense_entry.save\n format.html { redirect_to @expense_entry, notice: 'Expense entry was successfully created.' }\n format.json { render json: @expense_entry, status: :created, location: @expense_entry }\n else\n format.html { render action: \"new\" }\n format.json { render json: @expense_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @expense_entry = ExpenseEntry.new(expense_entry_params)\n\n respond_to do |format|\n if @expense_entry.save\n format.html { redirect_to @expense_entry, notice: 'Expense entry was successfully created.' }\n format.json { render :show, status: :created, location: @expense_entry }\n else\n format.html { render :new }\n format.json { render json: @expense_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @entry = list.entries.build(params[:entry])\n\n respond_to do |format|\n if entry.save\n format.html { redirect_to list, notice: 'Entry was successfully created.' }\n format.json { render json: entry, status: :created, location: [list, entry] }\n else\n format.html { render action: \"new\" }\n format.json { render json: entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n new_entry = Entry.create!(entry_params)\n json_response(new_entry, :created)\n end",
"def create\n @data_entry = @dataset.data_entries.build(data_entry_params)\n\n respond_to do |format|\n if @data_entry.save\n format.turbo_stream { redirect_to app_dataset_data_entries_path(@app, @dataset) }\n format.html { redirect_to @data_entry, notice: \"Data entry was successfully created.\" }\n format.json { render :show, status: :created, location: @data_entry }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @data_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def post_expense(expense)\n post '/expenses', JSON.generate(expense)\n #check the post attempt was a success\n expect(last_response.status).to eq(200)\n\n #check the data is in JSON structure\n parsed = JSON.parse(last_response.body)\n\n #check the data includes an expense_id\n #passing a matcher into another = composing matchers\n expect(parsed).to include('expense_id' => a_kind_of(Integer))\n\n #add an id key to the hash\n expense.merge('id' => parsed['expense_id'])\n end",
"def create\n model = params[:model]\n #NOTE: Pay attention how the data is passed as a hash. This is how locomotive expects it. Not obvious.\n # req.set_form_data('content_entry[name]' => data['name'], 'content_entry[summary]' => data['summary'], 'model' => model)\n form_data = {}\n params[:content_entry].each do |key,val|\n form_data[\"content_entry[#{key}]\"] = val\n end\n #data = params[:content_entry]\n\n uri = URI(\"#{@cms_url}/locomotive/api/content_types/#{model}/entries.json?auth_token=#{APP_CONFIG['locomotive']['auth_token']}\")\n\n req = Net::HTTP::Post.new(uri)\n req.set_form_data(form_data)\n res = Net::HTTP.start(uri.hostname, uri.port) do |http|\n http.request(req)\n end\n case res\n when Net::HTTPSuccess, Net::HTTPRedirection\n render :json => res.body\n else\n # examine response code and generate appropriate error message\n render :json => res.value\n end\n\n end",
"def create\n @event = Event.find(params[:event_id])\n @event_entry = @event.event_entries.build(params[:event_entry])\n\n respond_to do |format|\n if @event_entry.save\n format.html { redirect_to @event, :notice => 'Event entry was successfully created.' }\n format.json { render :json => @event, :status => :created, :location => @event_entry }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @event_entry.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @text_entry = TextEntry.new(params[:text_entry])\n\n respond_to do |format|\n if @text_entry.save\n format.html { redirect_to statute_type_url(@text_entry.statute_type_id), notice: 'Text entry was successfully created.' }\n format.json { render json: @text_entry, status: :created, location: @text_entry }\n else\n format.html { render action: \"new\" }\n format.json { render json: @text_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @expense_entries = ExpenseEntry.all\n end",
"def save_dictionary_entries(dictionary, dictionary_entries, opts = {})\n response = @transporter.write(\n :POST,\n path_encode('/1/dictionaries/%s/batch', dictionary),\n { clearExistingDictionaryEntries: false, requests: chunk('addEntry', dictionary_entries) },\n opts\n )\n\n DictionaryResponse.new(self, response)\n end",
"def destroy\n @tense_entry.destroy\n respond_to do |format|\n format.html { redirect_to tense_entries_url, notice: 'Tense entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def add_entries(entries)\n entries.each do |entry|\n description = entry.content || entry.summary\n Article.create!(\n :title => entry.title,\n :description => description,\n :link => entry.url,\n :pubDate => entry.published,\n :guid => entry.id,\n :channel_id => self.id,\n :starred => false)\n end\n end",
"def index\n @entries = Entry.all\n\n render json: @entries\n end",
"def create\n @task_entry = TaskEntry.new(task_entry_params)\n\n respond_to do |format|\n if @task_entry.save\n format.json { render action: 'show', status: :created, location: @task_entry }\n else\n format.json { render json: @task_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @press_kit_entry = @press_kit.press_kit_entries.new(press_kit_entry_params)\n\n respond_to do |format|\n if @press_kit_entry.save\n format.html { redirect_to backstage_press_kit_entries_url, notice: 'press_kit_entry was successfully created.' }\n # format.json { render :show, status: :created, location: @press_kit_entry }\n else\n format.html { render :new }\n # format.json { render json: @press_kit_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n #@incident = @quote.incidents.new(incident_params)\n logger.info params[:incident]\n params[:incident].each do |incident|\n @incident = @quote.incidents.new(incident)\n @incident.save\n end\n respond_to do |format|\n format.json { render :json => { :code => \"201\", :description => \"Created incidents\"} }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PATCH/PUT /tense_entries/1 PATCH/PUT /tense_entries/1.json | def update
respond_to do |format|
if @tense_entry.update(tense_entry_params)
format.html { redirect_to @tense_entry, notice: 'Tense entry was successfully updated.' }
format.json { render :show, status: :ok, location: @tense_entry }
else
format.html { render :edit }
format.json { render json: @tense_entry.errors, status: :unprocessable_entity }
end
end
end | [
"def update\n respond_to do |format|\n if @task_entry.update(task_entry_params)\n format.json { head :no_content }\n else\n format.json { render json: @task_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @entry = Entry.find(params[:id])\n\n if @entry.update_attributes(params[:entry])\n head :no_content\n else\n render json: @entry.errors, status: :unprocessable_entity\n end\n end",
"def update\n @entry = Entry.find(params[:id])\n\n respond_to do |format|\n if @entry.update_attributes(params[:entry])\n format.json { render json: @entry, status: :created, location: @entry }\n else\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_rest\n @entry_item = EntryItem.find(params[:id])\n\n respond_to do |format|\n if @entry_item.update_attributes(params[:entry_item])\n flash[:notice] = 'EntryItem was successfully updated.'\n #format.html { redirect_to(@entry_item) }\n format.xml { head :ok }\n else\n #format.html { render :action => \"edit\" }\n format.xml { render :xml => @entry_item.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @expense_entry = current_firm.all_expense_entries.find(params[:id])\n\n respond_to do |format|\n if @expense_entry.update_attributes(params[:expense_entry])\n format.html { redirect_to firm_expense_entry_path(current_firm, @expense_entry), notice: 'Expense entry was successfully updated.' }\n format.json { head :ok }\n else\n format.html { index }\n format.json { render json: @expense_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @entry.update(entry_params)\n format.json { render :show, status: :ok, location: @entry }\n else\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @options[:body] = @entity.attrs[:body]\n @options[:headers]['Content-Type'] = 'application/json'\n url = @url_helper.entity_url\n request(:patch, url)\n end",
"def update_rest\n @entry_answer = EntryAnswer.find(params[:id])\n\n respond_to do |format|\n if @entry_answer.update_attributes(params[:entry_answer])\n flash[:notice] = 'EntryAnswer was successfully updated.'\n format.html { redirect_to(@entry_answer) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @entry_answer.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @treq = Treq.find(params[:id])\n\n respond_to do |format|\n unless params[:treq_files].blank?\n params[:treq_files]['file'].each do |a|\n @treq_file = @treq.treq_files.create!(:file => a, :treq_id => @treq.id)\n end\n end\n if @treq.update_attributes(params[:treq])\n format.html { redirect_to @treq, notice: 'Treq was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @treq.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def update_rest\n @entry_question = EntryQuestion.find(params[:id])\n\n respond_to do |format|\n if @entry_question.update_attributes(params[:entry_question])\n flash[:notice] = 'EntryQuestion was successfully updated.'\n format.html { redirect_to(@entry_question) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @entry_question.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @text_entry = TextEntry.find(params[:id])\n\n respond_to do |format|\n if @text_entry.update_attributes(params[:text_entry])\n format.html { redirect_to statute_type_url(@text_entry.statute_type_id), notice: 'Text entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @text_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!\n entity_json = [{ name: @source_file.entity_name, entries: expanded_entries }]\n\n response = @api_client.update_entities_request(entity_json)\n\n handle_response(response, :entity)\n end",
"def update\n @exercise_entry = ExerciseEntry.find(params[:id])\n\n respond_to do |format|\n if @exercise_entry.update_attributes(params[:exercise_entry])\n format.html { redirect_to @exercise_entry, notice: 'Exercise entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @exercise_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @lense = Lense.find(params[:id])\n\n respond_to do |format|\n if @lense.update_attributes(params[:lense])\n format.html { redirect_to @lense, notice: 'Lense was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @lense.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n json_update(factType,factType_params, FactType)\n end",
"def update\n keystone.update_tenant({:id=>params[:id],:name=>params[:name],:description=>params[:description],:enabled=>params[:enabled]})\n respond_to do |format|\n format.html { redirect_to tenants_path, :notice => 'Tenant was successfully updated.' }\n format.json { head :ok }\n end\n end",
"def update\n respond_with Expense.update(params[:id], expense_params), status: 204\n end",
"def update\n respond_to do |format|\n if @big_time_entry.update(big_time_entry_params)\n format.html { redirect_to @big_time_entry, notice: 'Big time entry was successfully updated.' }\n format.json { render :show, status: :ok, location: @big_time_entry }\n else\n format.html { render :edit }\n format.json { render json: @big_time_entry.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /tense_entries/1 DELETE /tense_entries/1.json | def destroy
@tense_entry.destroy
respond_to do |format|
format.html { redirect_to tense_entries_url, notice: 'Tense entry was successfully destroyed.' }
format.json { head :no_content }
end
end | [
"def destroy\n @expense_entry = ExpenseEntry.with_deleted.find(params[:id])\n @expense_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to expense_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n debugger\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @reloud_entry = ReloudEntry.find(params[:id])\n @reloud_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to reloud_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n Entry.delete(params[:id])\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @top_standing_entry.destroy\n respond_to do |format|\n format.html { redirect_to top_standing_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n entry.destroy\n\n respond_to do |format|\n format.html { redirect_to list_entries_url(list) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @income_entry = IncomeEntry.find(params[:id])\n @income_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to income_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @budget_entry.destroy\n respond_to do |format|\n format.html { redirect_to budget_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @contest_entry = ContestEntry.find(params[:id])\n @contest_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to contest_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy_rest\n @entry_item = EntryItem.find(params[:id])\n @entry_item.destroy\n\n respond_to do |format|\n #format.html { redirect_to(entry_items_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @foodlog_entry = FoodlogEntry.find(params[:id])\n @foodlog_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to foodlog_entries_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @concordance_entry = ConcordanceEntry.find(params[:id])\n @concordance_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to concordance_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @contestant_entry = ContestantEntry.find(params[:id])\n @contestant_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(contestant_entries_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @lense = Lense.find(params[:id])\n @lense.destroy\n\n respond_to do |format|\n format.html { redirect_to lenses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @task_entry.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n @r_entry.destroy\n respond_to do |format|\n format.html { redirect_to r_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @time_entry = TimeEntry.with_deleted.find(params[:id])\n @time_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to time_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @quest_entry = QuestEntry.find(params[:id])\n @quest_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(quest_entries_url) }\n format.xml { head :ok }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /order_requests/1 DELETE /order_requests/1.json | def destroy
@order_request.destroy
respond_to do |format|
format.html { redirect_to order_requests_url, notice: 'Order request was successfully destroyed.' }
format.json { head :no_content }
end
end | [
"def delete\n RestClient.delete \"#{@uri}/api/requests/request/#{@data['requestId']||@data['id']}\"\n puts ' Deleted request: '.red + \"#{@data['requestId']||@data['id']}\".light_blue\n end",
"def destroy\n @order_item_request.destroy\n respond_to do |format|\n format.html { redirect_to order_item_requests_url, notice: 'Order item request was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @order.destroy\n\n render json: { operation: 'OK' }, status: :ok\n end",
"def destroy\n @v1_order = V1::Order.find(params[:id])\n @v1_order.destroy\n\n head :no_content\n end",
"def destroy\n @order1 = Order1.find(params[:id])\n @order1.destroy\n\n respond_to do |format|\n format.html { redirect_to order1s_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @order_item.destroy\n\n render json: { operation: 'OK' }, status: :ok\n end",
"def delete_request\n client.create_request('DELETE', url_path)\n end",
"def destroy\n @req = Req.find(params[:id])\n @req.destroy\n\n respond_to do |format|\n format.html { redirect_to reqs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @order_request_item.destroy\n respond_to do |format|\n format.html { redirect_to order_request_items_url, notice: 'Order request item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @purchase_request.destroy\n\n respond_to do |format|\n format.html { redirect_to purchase_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @request.destroy\n respond_to do |format|\n format.html { redirect_to admin_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @original_order = OriginalOrder.find(params[:id])\n @original_order.destroy\n\n respond_to do |format|\n format.html { redirect_to original_orders_url }\n format.json { head :no_content }\n end\n end",
"def delete endpoint\n do_request :delete, endpoint\n end",
"def destroy\n @cust_iti_request.destroy\n respond_to do |format|\n format.html { redirect_to cust_iti_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @pending_request = PendingRequest.find(params[:id])\n @pending_request.destroy\n\n respond_to do |format|\n format.html { redirect_to pending_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n render status: 200, json: @request_item.destroy\n end",
"def destroy\n @order_line = OrderLine.find(params[:id])\n @order_line.destroy\n\n respond_to do |format|\n format.html { redirect_to orders_url }\n format.json { head :no_content }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Note that we will only send emails here if the registration has pending convictions or pending payments. In the case when the registration can be completed, the registration activation email is sent from the RegistrationActivationService. | def send_confirmation_email
if registration.pending_worldpay_payment?
send_worldpay_pending_payment_email
elsif registration.unpaid_balance?
send_pending_payment_email
elsif registration.conviction_check_required?
send_pending_conviction_check_email
end
rescue StandardError => e
Airbrake.notify(e, registration_no: registration.reg_identifier) if defined?(Airbrake)
end | [
"def send_signup_notification\n deliver_activation_email(:signup, :subject => (MaSA[:activation_subject] || \"Please Activate Your Account\") )\n end",
"def send_signup_notification\n deliver_email(:signup, :subject => (MaSM[:activation_subject] || \"Please Activate Your Account\") )\n end",
"def signup_email\n MnoEnterprise::SystemNotificationMailer.registration_instructions(params.require(:user).require(:email)).deliver_later\n\n head :no_content\n end",
"def resend_activation_email!\n self.send_activation_needed_email!\n end",
"def send_post_registration_email\n IdealsMailer.account_registered(self).deliver_now\n end",
"def send_activation_email\n DoctorMailer.account_activation(self).deliver_now\n end",
"def deliver_activation\n if self.state != \"active\" && !self.email.blank?\n Mailers::User.deliver_activation(self) unless !!skip_activation\n end\n end",
"def deliver_signup_notification\n if !self.email.blank?\n Mailers::User.deliver_signup_notification(self) if self.recently_activated?\n end\n end",
"def send_activation_mail\n StudentMailer.account_activation(self).deliver_now\n end",
"def send_activation_email\n\t\tUserMailer.user_activation(self).deliver_now\n\tend",
"def send_activation_notification\n deliver_activation_email(:activation, :subject => (MaSA[:welcome_subject] || \"Welcome\" ))\n end",
"def send_activation_notification\n deliver_email(:activation, :subject => (MaSM[:welcome_subject] || \"Welcome\" ))\n end",
"def send_registration(reg)\n @user = reg.user\n @tenant = reg.tenant\n to = [@user.email]\n\n mail(to: to, subject: I18n.t(\"email.registration.send\", app_name: APP_NAME, email: reg.email) )\n end",
"def deliver_activation_confirmation!\n reset_perishable_token!\n Mailer.deliver_activation_confirmation(self)\n end",
"def resend_activation_email\n create_activation_digest\n save\n send_activation_email\n end",
"def resend_activation_emails\n User.where.not(person: nil).where.not(activation_code: nil).each do |user|\n if user.person\n logs = user.person.activation_email_logs\n if logs.count < MAX_ACTIVATION_EMAILS && (logs.empty? || logs.last.created_at < RESEND_ACTIVATION_EMAIL_DELAY.ago)\n Mailer.activation_request(user).deliver_later\n MessageLog.log_activation_email(user.person)\n end\n else\n Rails.logger.info(\"User with invalid person - #{user.id}\")\n end \n end\n end",
"def deliver_confirmation_email_instructions!\n # TODO\n end",
"def dispatch_emails( options = {})\n unless email.blank? # cannot send without valid email\n # Fri Dec 10 21:04:14 IST 2010, ramonrails\n # * \"resend\" needs options \n if (!activation_email_sent? && !activated?) || (options.is_a?( Hash) && options.has_key?(:force) && (options[:force] == true))\n if can_send_email?\n if self.is_caregiver?\n # * Only caregiver email will dispatch when subscriber is caregiver\n # * emails for caregivers\n _recent_senior = is_caregiver_of_what.last\n UserMailer.deliver_caregiver_invitation( self, _recent_senior)\n else\n # * emails for \"non-caregivers\". admins, subscribers, halousers and everybody else\n UserMailer.deliver_signup_notification( self)\n end\n #\n # * Now mark the dispatch of email, for next time\n self.update_attribute( :activation_sent_at, Time.now)\n end # can send email\n # end # user type?\n end # activation_email_sent?\n #\n # activation email gets delivered anyways\n UserMailer.deliver_activation(self) if recently_activated?\n end # cannot send without valid email\n #\n # Tue Dec 21 00:33:39 IST 2010, ramonrails\n # * return a status whether activation was sent\n return !activation_sent_at.blank? # when this is filled, activation was sent\n end",
"def registration_instructions(email)\n MnoEnterprise::MailClient.deliver(\n 'registration-instructions',\n default_sender,\n {email: email},\n {registration_link: new_user_registration_url}\n )\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PATCH/PUT /attachments_encryption_disable_emails/1 PATCH/PUT /attachments_encryption_disable_emails/1.json | def update
respond_to do |format|
if @attachments_encryption_disable_email.update(attachments_encryption_disable_email_params)
format.html { redirect_to attachments_encryption_disable_emails_url, notice: 'Attachments encryption disable email was successfully updated.' }
format.json { render :show, status: :ok, location: @attachments_encryption_disable_email }
else
format.html { render :edit }
format.json { render json: @attachments_encryption_disable_email.errors, status: :unprocessable_entity }
end
end
end | [
"def update\n respond_to do |format|\n if @attachments_encryption_disable_domain_to.update(attachments_encryption_disable_domain_to_params)\n format.html { redirect_to attachments_encryption_disable_domain_tos_url, notice: 'Attachments encryption disable domain to was successfully updated.' }\n format.json { render :show, status: :ok, location: @attachments_encryption_disable_domain_to }\n else\n format.html { render :edit }\n format.json { render json: @attachments_encryption_disable_domain_to.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @attachments_encryption_disable_email.destroy\n respond_to do |format|\n format.html { redirect_to attachments_encryption_disable_emails_url, notice: 'Attachments encryption disable email was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def disable_email\n self.recieve_email = false\n end",
"def patch_email_template(email_template_id, request)\n start.uri('/api/email/template')\n .url_segment(email_template_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .patch()\n .go()\n end",
"def update\n if @email_attachment.update(email_attachment_params)\n render :show, status: :ok, location: @email_attachment\n else\n render json: @email_attachment.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @mail_attachment.update(mail_attachment_params)\n format.html { redirect_to @mail_attachment, notice: 'Mail attachment was successfully updated.' }\n format.json { render :show, status: :ok, location: @mail_attachment }\n else\n format.html { render :edit }\n format.json { render json: @mail_attachment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @key.blocked\n @key.blocked = false\n if @key.save\n render json: @key\n else\n render json: @key.errors, status: :unprocessable_entity\n end\n else\n render json: @key\n end\n end",
"def update\n respond_to do |format|\n if @alternative_email.update(alternative_email_params)\n format.html { redirect_to @alternative_email, notice: 'Alternative email was successfully updated.' }\n format.json { render :show, status: :ok, location: @alternative_email }\n else\n format.html { render :edit }\n format.json { render json: @alternative_email.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n base64_password = Base64.encode64(user_smtp_params['password'])\n if @user_smtp.update(user_smtp_params.merge(password: base64_password))\n format.html { redirect_to user_smtps_url, notice: 'User smtp was updated.' }\n format.json { render :index, status: :ok }\n else\n format.html { render :edit }\n format.json { render json: @user_smtp.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @attachments_encryption_disable_domain_tos = Setting.current.attachments_encryption_disable_domain_tos\n end",
"def ajax_disable_app\n\n # Get the Current App\n current_app = MailfunnelsUtil.get_app\n\n # If the User is not an admin return error response\n if !current_app.is_admin or current_app.is_admin === 0\n response = {\n success: false,\n message: 'You do not have admin privileges!'\n }\n render json: response\n end\n\n # Get the App we are disabling\n app = App.find(params[:app_id])\n\n # Set disables status to 1\n app.is_disabled = 1\n\n app.put('', {\n :is_disabled => app.is_disabled,\n })\n\n\n # Return Success Response\n response = {\n success: true,\n message: 'App Disabled!'\n }\n render json: response\n\n\n end",
"def skip_email_changed_notification!; end",
"def attachments_to_forget\n return [] unless self.class.remember_attachments?\n (self.database.get(self.id)[\"_attachments\"] || {}).keys.reject do |a| \n a.match(VERSION_REGEX) || \n (self.class.remember_attachments.map { |attachment_name_pattern|\n a.match attachment_name_pattern\n }.inject(false) {|b, sum| sum || b})\n end \n end",
"def cancel_change_email\n\t\t\trender json: User.cancel_change_email(params[:id])\n\t\tend",
"def disable_alert_feature \n put(\"/globalsettings.json/alerts/disable\")\nend",
"def update\n @request_attachment = RequestAttachment.find(params[:id])\n\n respond_to do |format|\n if @request_attachment.update_attributes(params[:request_attachment])\n format.html { redirect_to @request_attachment, notice: 'Request attachment was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @request_attachment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def email_kyc_deny\n @service_response = UserManagement::SendEmail::Deny.new(params).perform\n format_service_response\n end",
"def email_deny(params)\n http_helper.send_post_request(\"#{@url_prefix}/#{get_user_id!(params)}/email/deny\", params)\n end",
"def send_unlock_instructions\n return unless EMAILS_ENABLED && !deleted?\n\n super\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /attachments_encryption_disable_emails/1 DELETE /attachments_encryption_disable_emails/1.json | def destroy
@attachments_encryption_disable_email.destroy
respond_to do |format|
format.html { redirect_to attachments_encryption_disable_emails_url, notice: 'Attachments encryption disable email was successfully destroyed.' }
format.json { head :no_content }
end
end | [
"def destroy\n @attachments_encryption_disable_domain_to.destroy\n respond_to do |format|\n format.html { redirect_to attachments_encryption_disable_domain_tos_url, notice: 'Attachments encryption disable domain to was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @attachments_encryption_disable_domain_from.destroy\n respond_to do |format|\n format.html { redirect_to attachments_encryption_disable_domain_froms_url, notice: 'Attachments encryption disable domain from was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy_attachments\n send_to_attachments(:destroy)\n end",
"def delete id, options={}, headers={}\n @connection.delete \"pending_attachments/#{id}.json\", options, headers\n end",
"def destroy\n @mail_attachment.destroy\n respond_to do |format|\n format.html { redirect_to mail_attachments_url, notice: 'Mail attachment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @request_attachment = RequestAttachment.find(params[:id])\n @request_attachment.destroy\n\n respond_to do |format|\n format.html { redirect_to request_attachments_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @email_content.destroy\n respond_to do |format|\n format.html { redirect_to email_contents_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @attachment.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n @subject_attachment.destroy\n respond_to do |format|\n format.html { redirect_to subject_attachments_url, notice: 'Subject attachment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @message_attachment = MessageAttachment.find(params[:id])\n @message_attachment.destroy\n\n respond_to do |format|\n format.html { redirect_to message_attachments_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @offices_attachment = OfficesAttachment.find(params[:id])\n @offices_attachment.destroy\n\n respond_to do |format|\n format.html { redirect_to offices_attachments_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ab_email.destroy\n respond_to do |format|\n format.html { redirect_to ab_emails_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @admin_system_email.destroy\n respond_to do |format|\n format.html { redirect_to admin_system_emails_url }\n format.json { head :no_content }\n end\n end",
"def delete_attachments\n delete_attachment_queue.each {|k,v| delete_grid_attachment(k,v)}\n end",
"def destroy\n id = @request_attachment.request_id\n @request_attachment.destroy\n flash[:success] = \"Attachment was successfully deleted.\"\n respond_to do |format|\n format.html { redirect_to controller: \"requests\", action: \"edit\", id: \"#{id}\"}\n format.json { head :no_content }\n end\n end",
"def delete_attachment\n Log.add_info(request, params.inspect)\n\n raise(RequestPostOnlyException) unless request.post?\n\n begin\n attachment = MailAttachment.find(params[:attachment_id])\n @email = Email.find(params[:id])\n\n if attachment.email_id == @email.id\n attachment.destroy\n\n update_attrs = ActionController::Parameters.new({updated_at: Time.now})\n if @email.status == Email::STATUS_TEMPORARY\n update_attrs[:status] = Email::STATUS_DRAFT\n end\n @email.update_attributes(update_attrs.permit(Email::PERMIT_BASE))\n end\n rescue => evar\n Log.add_error(request, evar)\n end\n\n render(:partial => 'ajax_mail_attachments', :layout => false)\n end",
"def delete_email(email_id)\n params = {'key' => @api_key}\n RestClient.post(\"#{@base_url}/emails/#{email_id}/delete\", nil, {:params => params})\n end",
"def destroy\n @attachment = Attachment.find(params[:id])\n @attachment.destroy\n\n respond_to do |format|\n format.html { redirect_to attachments_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @email = @recipient.emails.find(params[:id])\n @email.destroy\n\n respond_to do |format|\n format.html { redirect_to recipient_emails_path }\n format.json { head :no_content }\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /transaksi_histories GET /transaksi_histories.json | def index
@transaksi_histories = TransaksiHistory.all
end | [
"def index\n @settlement_histories = Settlement::History.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @settlement_histories }\n end\n end",
"def index\n @molpay_transaction_histories = MolpayTransactionHistory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @molpay_transaction_histories }\n end\n end",
"def index\n @histories = History.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @histories }\n end\n end",
"def index\n @histories = History.all\n respond_with(@histories)\n end",
"def index\n @thermostat_histories = ThermostatHistory.all\n end",
"def index\n @sales_tax_exemption_customer_histories = SalesTaxExemptionCustomerHistory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sales_tax_exemption_customer_histories }\n end\n end",
"def index\n @ste_customer_histories = SteCustomerHistory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ste_customer_histories }\n end\n end",
"def index\n @transaction_histories = current_user.transaction_histories.paginate(:page => params[:page], :per_page =>25)\n end",
"def index\n past_histories = PastHistory.where(user_id: params[:user_id])\n render json: past_histories.as_json(include: :recipe, only: :created_at)\n end",
"def index\n @histories = History.all_by_user(current_user).order_by_happened_at\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @histories }\n end\n end",
"def index\n @purchase_histories = PurchaseHistory.all\n end",
"def index\n @service_histories = ServiceHistory.all.order(\"updated_at DESC\").order(\"created_at DESC\")\n\n render json: @service_histories\n end",
"def index\n @ste_supplier_histories = SteSupplierHistory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ste_supplier_histories }\n end\n end",
"def index\n @fundamentals_histories = @company.fundamentals_histories.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @fundamentals_histories }\n end\n end",
"def get_wiki_histories(wiki_id, params = {})\n get(\"wikis/#{wiki_id}/history\", params)\n end",
"def histories_show\n @gallery = Gallery.find(params[:id])\n @ads = @gallery.ads\n @history_info = @ads.map do |ad|\n has_seen_total = ad.histories.count { |e| e.has_been_seen == true }\n has_notseen_total = ad.histories.count { |e| e.has_been_seen == false }\n total = has_seen_total + has_notseen_total\n history = {\n has_seen_total: has_seen_total,\n has_notseen_total: has_notseen_total,\n total: total\n }\n\n end\n\n if @history_info\n render json: {\n gallery: @gallery,\n ads: @ads,\n history_info: @history_info,\n }\n else\n render json: {\n status: 500,\n errors: ['no histories found']\n }\n end\n end",
"def index\n @fertilizer_histories = FertilizerHistory.all\n end",
"def index\n @penarikan_histories = PenarikanHistory.all\n end",
"def index\n @historials = Historial.all\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
POST /transaksi_histories POST /transaksi_histories.json | def create
@transaksi_history = TransaksiHistory.new(transaksi_history_params)
respond_to do |format|
if @transaksi_history.save
format.html { redirect_to @transaksi_history, notice: 'Transaksi history was successfully created.' }
format.json { render :show, status: :created, location: @transaksi_history }
else
format.html { render :new }
format.json { render json: @transaksi_history.errors, status: :unprocessable_entity }
end
end
end | [
"def index\n @transaksi_histories = TransaksiHistory.all\n end",
"def post_to_historical(data_hash, title_number)\n\n response = rest_post_call($HISTORIAN_URL + '/' + title_number, data_hash.to_json)\n\n if (response.code != '200') then\n raise \"Failed to create the historical data: \" + response.body\n end\n\n return response.body\nend",
"def index\n @settlement_histories = Settlement::History.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @settlement_histories }\n end\n end",
"def create\n @histroal = Historial.new(histroal_params)\n\n respond_to do |format|\n if @histroal.save\n format.html { redirect_to @histroal, notice: 'Historial was successfully created.' }\n format.json { render :show, status: :created, location: @histroal }\n else\n format.html { render :new }\n format.json { render json: @histroal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n megam_rest.post_billedhistories(to_hash)\n end",
"def create\n # @transaction_history = TransactionHistory.new(transaction_history_params)\n @transaction_history = current_user.transaction_histories.build(transaction_history_params)\n\n respond_to do |format|\n if @transaction_history.save\n format.html { redirect_to transaction_histories_url, notice: 'Transaction history was successfully created.' }\n format.json { render :show, status: :created, location: @transaction_history }\n else\n format.html { render :new }\n format.json { render json: @transaction_history.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @historial = Historial.new(historial_params)\n\n respond_to do |format|\n if @historial.save\n format.html { redirect_to @historial, notice: 'Historial was successfully created.' }\n format.json { render :show, status: :created, location: @historial }\n else\n format.html { render :new }\n format.json { render json: @historial.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @hourly_histogram = HourlyHistogram.new(hourly_histogram_params)\n\n respond_to do |format|\n if @hourly_histogram.save\n format.html { redirect_to @hourly_histogram, notice: 'Hourly histogram was successfully created.' }\n format.json { render :show, status: :created, location: @hourly_histogram }\n else\n format.html { render :new }\n format.json { render json: @hourly_histogram.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @molpay_transaction_histories = MolpayTransactionHistory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @molpay_transaction_histories }\n end\n end",
"def create\n @historial = Historial.new(params[:historial])\n\n respond_to do |format|\n if @historial.save\n format.html { redirect_to(@historial, :notice => 'Historial was successfully created.') }\n format.xml { render :xml => @historial, :status => :created, :location => @historial }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @historial.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @historial_odt = HistorialOdt.new(params[:historial_odt])\n\n respond_to do |format|\n if @historial_odt.save\n format.html { redirect_to @historial_odt, notice: 'Historial odt was successfully created.' }\n format.json { render json: @historial_odt, status: :created, location: @historial_odt }\n else\n format.html { render action: \"new\" }\n format.json { render json: @historial_odt.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @votaciones_hist = VotacionesHist.new(votaciones_hist_params)\n\n respond_to do |format|\n if @votaciones_hist.save\n format.html { redirect_to @votaciones_hist, notice: 'Votaciones hist was successfully created.' }\n format.json { render :show, status: :created, location: @votaciones_hist }\n else\n format.html { render :new }\n format.json { render json: @votaciones_hist.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create \n\n respond_to do |format|\n if @historium.save\n format.html { redirect_to @historium, notice: 'Historia fue creada satisfactoriamente.' }\n format.json { render :show, status: :created, location: @historium }\n else\n format.html { render :new }\n format.json { render json: @historium.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @aircraft = Aircraft.find(params[:aircraft_id])\n @aircraft_history = @aircraft.aircraft_histories.create(params[:aircraft_history])\n redirect_to aircraft_path(@aircraft)\n end",
"def create\n @historia = Historia.new(historia_params)\n\n respond_to do |format|\n if @historia.save\n format.html { redirect_to @historia, notice: 'Historium was successfully created.' }\n format.json { render :show, status: :created, location: @historia }\n else\n format.html { render :new }\n format.json { render json: @historia.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @histories = History.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @histories }\n end\n end",
"def create\n @historico_equipamento = HistoricoEquipamento.new(historico_equipamento_params)\n\n respond_to do |format|\n if @historico_equipamento.save\n format.html { redirect_to @historico_equipamento, notice: 'Historico equipamento was successfully created.' }\n format.json { render :show, status: :created, location: @historico_equipamento }\n else\n format.html { render :new }\n format.json { render json: @historico_equipamento.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @historial_oct = HistorialOct.new(params[:historial_oct])\n\n respond_to do |format|\n if @historial_oct.save\n format.html { redirect_to @historial_oct, notice: 'Historial oct was successfully created.' }\n format.json { render json: @historial_oct, status: :created, location: @historial_oct }\n else\n format.html { render action: \"new\" }\n format.json { render json: @historial_oct.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @purchase_history = PurchaseHistory.new(purchase_history_params)\n\n respond_to do |format|\n if @purchase_history.save\n format.html { redirect_to @purchase_history, notice: 'Purchase history was successfully created.' }\n format.json { render :show, status: :created, location: @purchase_history }\n else\n format.html { render :new }\n format.json { render json: @purchase_history.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DELETE /transaksi_histories/1 DELETE /transaksi_histories/1.json | def destroy
@transaksi_history.destroy
respond_to do |format|
format.html { redirect_to transaksi_histories_url, notice: 'Transaksi history was successfully destroyed.' }
format.json { head :no_content }
end
end | [
"def destroy\n @historial = Historial.find(params[:id])\n @historial.destroy\n\n respond_to do |format|\n format.html { redirect_to historials_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @pur_hist = PurHist.find(params[:id])\n @pur_hist.destroy\n\n respond_to do |format|\n format.html { redirect_to pur_hists_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @molpay_transaction_history.destroy\n respond_to do |format|\n format.html { redirect_to molpay_transaction_histories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @historial_odt = HistorialOdt.find(params[:id])\n @historial_odt.destroy\n\n respond_to do |format|\n format.html { redirect_to historial_odts_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @historial = Historial.find(params[:id])\n @historial.destroy\n\n respond_to do |format|\n format.html { redirect_to(historials_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @settlement_history = Settlement::History.find(params[:id])\n @settlement_history.destroy\n\n respond_to do |format|\n format.html { redirect_to settlement_histories_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @historial_odc = HistorialOdc.find(params[:id])\n @historial_odc.destroy\n\n respond_to do |format|\n format.html { redirect_to historial_odcs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @transaction_history.destroy\n respond_to do |format|\n format.html { redirect_to transaction_histories_url, notice: 'Transaction history was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @purchase_historic.destroy\n respond_to do |format|\n format.html { redirect_to purchase_historics_url, notice: 'Venda cancelada com sucesso' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @transactionhistory.destroy\n respond_to do |format|\n format.html { redirect_to transactionhistories_url, notice: \"Transactionhistory was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @histoire = Histoire.find(params[:id])\n @histoire.destroy\n\n respond_to do |format|\n format.html { redirect_to(histoires_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @historial.destroy\n respond_to do |format|\n format.html { redirect_to historials_url, notice: 'Historial was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @unified_history.destroy\n respond_to do |format|\n format.html { redirect_to unified_histories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @votaciones_hist.destroy\n respond_to do |format|\n format.html { redirect_to votaciones_hists_url, notice: 'Votaciones hist was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @thermostat_history.destroy\n respond_to do |format|\n format.html { redirect_to thermostat_histories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @operation_history = OperationHistory.find(params[:id])\n @operation_history.destroy\n\n respond_to do |format|\n format.html { redirect_to operation_histories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @history.destroy\n\n respond_to do |format|\n format.html { redirect_to histories_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @loan_history = LoanHistory.find(params[:id])\n @loan_history.destroy\n\n respond_to do |format|\n format.html { redirect_to loan_histories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @resource_history = Resource::History.find(params[:id])\n @resource_history.destroy\n\n respond_to do |format|\n format.html { redirect_to resource_histories_url }\n format.json { head :ok }\n end\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.