Dataset Viewer
Auto-converted to Parquet Duplicate
anchor
stringlengths
10
233k
positive
stringlengths
1
289k
negative
stringlengths
1
140k
What is the total production quantity for each country in 2016?
SELECT cp.country, cp.element, SUM(cp.quantity) as total_quantity FROM country_production cp WHERE cp.year = 2016 GROUP BY cp.country, cp.element;
path = '/'.join(['zone', zone_id]) return self.rachio.get(path)
func MetaBucketName(bucketName []byte) DBConfiguration { return func(c *CyclePDB) error {
c.metaBucket = bucketName return nil } }
// MetaBucketName is the sub bucket we put our metadata
public function addInline($path, $name = null, $mime = true, $encoding = true) { $cid = static::generateId($this->client()); $filename = basename($path); $this->_inlines[$path] = [ 'filename' => $name ?: $filename,
'disposition' => 'attachment', 'mime' => $mime, 'headers' => ['Content-ID: ' . $cid] ]; return $cid; }
not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=...
Symbol findMethod(Env<AttrContext> env, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes, boolean allowBoxing, boolean useVarargs, boolean operator)...
Symbol bestSoFar = methodNotFound; bestSoFar = findMethod(env, site, name, argtypes, typeargtypes, site.tsym.type, bestSoFar, allo...
Find best qualified method matching given name, type and value arguments. @param env The current environment. @param site The original type from where the selection takes place. @param name The method's name. @param argtypes The method's value arguments. @param typeargtypes The method's type arguments ...
func (a *AuthServer) GetRemoteCluster(clusterName string) (services.RemoteCluster, error) { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) remoteCluster, err := a.Presence.GetRemoteCluster(clusterName) if err != nil {
return nil, trace.Wrap(err) } if err := a.updateRemoteClusterStatus(remoteCluster); err != nil { return nil, trace.Wrap(err) } return remoteCluster, nil }
_clusterMap.putIfAbsent(clusterName, cluster); cluster = _clusterMap.get(clusterName); } return cluster; }
def replace(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): """ Returns a new datetime.datetime or asn1crypto.util.extended_datetime object with the specified components replaced :return: A datetime....
microsecond = self.microsecond if tzinfo is None: tzinfo = self.tzinfo if year > 0: cls = datetime else: cls = extended_datetime return cls( year, month, day, hour, minute, secon...
datetime(year, month, day, hour, minute, second, microsecond, fold=1) ) return self.convert( datetime(year, month, day, hour, minute, second, microsecond), dst_rule=POST_TRANSITION, )
function findOneMatchBy($property, $value) { switch ($property) { case 'owner_identifier': return $this->federation->getAccountInfoByUid($value); break; default:
throw new \Exception(sprintf( 'Identity Provider Can`t Attain with (%s).' , $property )); } }
Pattern p = Pattern.compile(expr); Matcher m = p.matcher(str); while(m.find()) ++ret; return ret; }
def update_current_retention_level(self, value): """Set a new value for the current retention level. This updates the value of self.retain_files for an updated value of the retention level. Parameters ----------- value : int The new value to use for the rete...
Set a new value for the current retention level. This updates the value of self.retain_files for an updated value of the retention level. Parameters ----------- value : int The new value to use for the retention level.
if retentions < 1 { return } writer.retentions = retentions }
public function compile($stub, $modelName, $modelData, stdClass $scaffolderConfig, $hash, ScaffolderThemeExtensionInterface $themeExtension, array $extensions, $extra = null) { $this->stub = $stub; return $this->setPageTitle($scaffolderConfig) ->setAppName($scaffolderConfig) ...
->replaceRoutePrefix($scaffolderConfig->routing->prefix) ->store($modelName, $scaffolderConfig, $themeExtension->runAfterPageLayoutIsCompiled($this->stub, $scaffolderConfig), new FileToCompile(null, null)); }
null) { $this->stub = $stub; return $this->store(null, $scaffolderConfig, $themeExtension->runAfterEditLayoutIsCompiled($this->stub, $scaffolderConfig), new FileToCompile(null, null)); }
public final boolean addStringCaseClosure(String s, UnicodeSet set) { int i, length, start, limit, result, unfoldOffset, unfoldRows, unfoldRowWidth, unfoldStringWidth; if(unfold==null || s==null) { return false; /* no reverse case folding data, or no string */ } length=s.len...
unfoldOffset=((i+1)*unfoldRowWidth); // +1 to skip the header values above result=strcmpMax(s, unfoldOffset, unfoldStringWidth); if(result==0) { /* found the string: add each code point, and its case closure */ int c; for(i=unfoldStringWidth; i<u...
$unfolded->fmap(function($value) use ($unfolder) { return self::ana($unfolder, $value); }) ); }
func (w *Writer) WriteColNames(st interface{}) error { cols, err := w.e.GetColNames(st) if err != nil { return err } w.r++ return w.w.Write(cols) }
// WriteColNames writes out the column names of the CSV field.
if col.Writeable { w.Cols[col.Name] = col } } return w }
protected function sendInit() { $this->sendCommand('set grid'); if ($this->title) { $this->sendCommand('set title "'.$this->title.'"'); } if ($this->xlabel) { $this->sendCommand('set xlabel "'.$this->xlabel.'"'); } if ($this->timeFormat) { ...
if ($this->timeFormatString) { $this->sendCommand('set format x "'.$this->timeFormatString.'"'); } } if ($this->ylabel) { $this->sendCommand('set ylabel "'.$this->ylabel.'"'); } if ($this->yformat) { $this->sendCommand('set format y "...
$this->sendCommand('plot '.$this->getUsings()); } $this->plotted = true; $this->sendData(); }
function (options) { // return early if options is empty or invalid if (!_.isObject(options)) { return; } _.mergeDefined(this, /** @lends Certificate.prototype */ { /** * Unique identifier * @type {String} */ id:...
* @type {{ src: (string) }} */ cert: _.isObject(options.cert) ? options.cert : { src: options.cert }, /** * PFX or PKCS12 Certificate * @type {{ src: (string) }} */ pfx: _.isObject(options.pfx) ? options.pfx : { src: options.pfx },...
options.rootAssetPath || './'; this.options.ignorePaths = options.ignorePaths || []; this.options.extensionsRegex = options.extensionsRegex || null; this.options.format = options.format || 'general'; }
public void execute(InputStream input, OutputStream output) throws IOException {
execute(input, output, null); }
Process the output. @param outputStream the output stream to write to. @param element the element to serialize. @throws IOException in the case of IO error.
Replace every character in a given string with its corresponding ASCII code, remove any duplicate characters, and reverse the resulting string. The input string should only contain alphabetic characters. The program should also handle uppercase and lowercase characters as separate entities. Additionally, the program sh...
Here is a Python program that satisfies the given requirements: ```python def convert_string(input_string): # Remove special characters and whitespace from input string input_string = ''.join(filter(str.isalpha, input_string)) # Convert characters to ASCII codes and remove duplicates ascii_codes = lis...
Here is a Ruby function that removes all special characters and numbers from a given string, except for alphabetic characters, and also removes any duplicate alphabetic characters in the resulting string: ```ruby def remove_special_characters(string) # Remove special characters and numbers string = string.gsub(/[^...
Embarking on a sophisticated expedition through the intricate maze of scrupulously arranged hexadecimal digits, your mission is to excavate a particular sequence of these digits, ingeniously concealed within the matrix. The mathematical operation of multiplication, when astutely applied to these unique digits, should g...
In simpler terms, your task is to find a hidden sequence in a huge block of hexadecimal numbers, or digits, which are arranged in a particular way. This sequence will, when multiplied correctly, lead you to a certain result. You'll need a thorough understanding of hexadecimals and how to multiply them, including the ru...
The objective is to discover the particular sequence that, when the hexadecimal digits are multiplied, yields a predetermined output. In doing so, you will venture into a realm of cryptographic conundrums, where patterns hide in plain sight and mathematical conundrums await eager minds. As an individual with exception...
function(vec){ var cx = this.y * vec.z - vec.y * this.z; var cy = this.z * vec.x
- vec.z * this.x; this.z = this.x * vec.y - vec.x * this.y; this.y = cy; this.x = cx; return this; }
self.z * vec.x - self.x * vec.z, self.x * vec.y - self.y * vec.x)
def ask_for_board_id(self): """Factored out in case interface isn't keyboard""" board_id = raw_input("paste in board id or url: ").strip() m = re.search(r"(?:https?://)?(?:trello.com)?/?b?/?([a-zA-Z]{8})/(?:.*)", board_id) if m: board_id = m.group(1) return board_id
Factored out in case interface isn't keyboard
error { p.mu.Lock() p.Points = append(p.Points, points...) err := p.Err p.mu.Unlock() return err }
func fetchUserEKStatements(mctx libkb.MetaContext, uids []keybase1.UID) ( statements map[keybase1.UID]*keybase1.UserEkStatement, err error) { defer mctx.TraceTimed(fmt.Sprintf("fetchUserEKStatements: numUids: %v", len(uids)), func() error { return err })() apiArg := libkb.APIArg{ Endpoint: "user/get_user_ek_ba...
= res.Body.UnmarshalAgain(&parsedResponse) if err != nil { return nil, err } statements = make(map[keybase1.UID]*keybase1.UserEkStatement) for uid, sig := range parsedResponse.Sigs { statement, _, wrongKID, err := verifySigWithLatestPUK(mctx, uid, *sig) // Check the wrongKID condition before checking the err...
libkb.AddUserEKReBoxServerArg(payload, reboxArg) mctx := e.mctx.WithAPITokener(e) arg := libkb.APIArg{ Endpoint: "key/multi", SessionType: libkb.APISessionTypeREQUIRED, JSONPayload: payload, } // MerkleCheckPostedUserSig was not added here. Changing kex2 is risky and there's no obvious attack. _, err :=...
You are tasked with implementing a function store system in Rust. The function store is responsible for executing functions and indirect functions based on their indices. You need to create a struct `FunctionStore` and implement the trait `FunctionStore` for it. The trait contains two methods: `execute_function` and `e...
```rust pub trait DataStore { // Define any required methods for the DataStore trait } pub struct Stack { // Define the Stack struct and its methods } pub struct FunctionStore { // Define the FunctionStore struct and its methods } impl FunctionStore for FunctionStore { fn execute_function( &s...
```rust impl<T> std::ops::DerefMut for CustomSmartPointer<T> { fn deref_mut(&mut self) -> &mut T { &mut self._value } } fn main() { let mut data = CustomSmartPointer::new(42); *data = 10; // This modifies the inner value of the smart pointer println!("{}", *data); // This prints 10 } ``` I...
public static function notValidParameter($parameterName, array $allowedValues, $actualValue) { return new static( sprintf( 'Parameter: "%s" can only be one of: "%s" Received: "%s"', $parameterName, static::stringify($allowedValues), ...
Static constructor to create from when a parameter should be one of a set of allowed values, but was not. @param string $parameterName @param mixed[] $allowedValues @param mixed $actualValue @return static
static::stringify($allowedValues), static::stringify($actualValue) ) ); }
void addCSSIfAvailable(final Parent parent) { // Read global css when available: final List<String> list = PropertyReaderHelper.get(applicationContext.getEnvironment(), "javafx.css"); if (!list.isEmpty()) { list.forEach(css
-> parent.getStylesheets().add(getClass().getResource(css).toExternalForm())); } addCSSFromAnnotation(parent); final URL uri = getClass().getResource(getStyleSheetName()); if (uri == null) { return; } final String uriToCss = uri.toExternalForm(); parent.getStylesheets().add(uriToCss); }
adds css to the css list @param $link
def cybox_csv_handler(self, enrichment, fact, attr_info, add_fact_kargs): """ Handler for dealing with comma-separated values. Unfortunately, CybOX et al. sometimes use comma-separated value lists. Or rather, since Cybox 2.0.1, '##comma##'-separated lists. At least now we can ...
we first check whether '##comma##' occurs -- if so, we take # that as separator; if not, we take ',' if '##comma##' in fact['value']: separator = '##comma##' else: separator = ',' value_list = map(lambda x: x.strip(), fact['value'].split(separator)) add...
Process comma separated list
public static sslpolicy_sslglobal_binding[] get(nitro_service service, String name) throws Exception{ sslpolicy_sslglobal_binding obj = new sslpolicy_sslglobal_binding(); obj.set_name(name);
sslpolicy_sslglobal_binding response[] = (sslpolicy_sslglobal_binding[]) obj.get_resources(service); return response; }
Use this API to fetch sslpolicy_sslglobal_binding resources of given name .
def sed_conversion(energy, model_unit, sed): """ Manage conversion between differential spectrum and SED """ model_pt = model_unit.physical_type ones = np.ones(energy.shape) if sed: # SED f_unit = u.Unit("erg/s") if model_pt == "power" or model_pt == "flux" or model_pt...
# From SED to differential sedf = 1 / (energy ** 2) else: raise u.UnitsError( "Model physical type ({0}) is not supported".format(model_pt), "Supported physical types are: power, flux, differential" " power, differential flux", ...
Manage conversion between differential spectrum and SED
public function getResults(EntityManager $em, Request $request, $page) { $query = $this->buildResultQuery($em, $request, $page); return $query->getResult(); }
Get results for request @param EntityManager $em @param Request $request @param int $page @return array
Build result query @param EntityManager $em @param Request $request @param int $page @return \Doctrine\ORM\NativeQuery
func (s *BlockDeviceMapping) SetVirtualName(v string) *BlockDeviceMapping { s.VirtualName = &v return s }
// SetVirtualName sets the VirtualName field's value.
{ s.VirtualMFADeviceName = &v return s }
func httpClient(projID string) *http.Client { if *gceJWTFile == "" { log.Fatal("Cannot initialize an authorized http Client without --gce_jwt_file") } jsonSlurp, err := ioutil.ReadFile(*gceJWTFile) if err != nil { log.Fatalf("Error reading --gce_jwt_file value: %v", err) } jwtConf, err := google.JWTConfigFrom...
// httpClient returns an http Client suitable for Google Cloud Storage or Google Cloud // Logging calls with the projID project ID.
""" params = {'identifier': identifier} return self.client.get(self._url(), params=params)
public function leastCheck(float $valence, array $tokens, int $index) : float { if($index === 0) { return $valence; } $inLexicon = isset($this->getLexicon()[strtolower($tokens[$index-1])]); if($inLexicon) { return $valence; ...
check for negation case using "least" @param float $valence @param array $tokens @param int $index @return float
else{ $index = \mb_stripos($this->_Value, $str->_Value, $offset, $this->_Encoding); } return $index !== false ? $index : static::NO_INDEX; }
func WithNewline(ctx context.Context, nl bool) context.Context { return
context.WithValue(ctx, ctxKeyNewline, nl) }
context = context[key] if context is None: break return context
public function hydrate($puppetModules, $group) { $availableClasses = []; if (!empty($puppetModules)) { foreach ($puppetModules as $puppetModule) { if ($puppetModule->hasClasses()) { foreach ($puppetModule->getClasses() as $puppetClass) { ...
Hydrate group with the provided puppet modules data. @param PuppetModule[] $puppetModules @param GroupInterface $group @return GroupInterface
if i not in actual_classes: self['puppetclasses'].append(i) self.reload() return set(classes).issubset(set((self['puppetclasses'].keys())))
func (s *GenericAPIServer) AddPostStartHook(name string, hook PostStartHookFunc) error { if len(name) == 0 { return fmt.Errorf("missing name") } if hook == nil { return nil } if s.disabledPostStartHooks.Has(name) { return nil } s.postStartHookLock.Lock() defer s.postStartHookLock.Unlock() if s.postStar...
} // done is closed when the poststarthook is finished. This is used by the health check to be able to indicate // that the poststarthook is finished done := make(chan struct{}) if err := s.AddHealthzChecks(postStartHookHealthz{name: "poststarthook/" + name, done: done}); err != nil { return err } s.postStart...
// AddPostStartHook allows you to add a PostStartHook.
def get_model(self): """ Get PMML text of the current model. Note that model file obtained via this method might be incomplete due to size limitations. """ url = self.resource() params = {'data': ''} resp = self._client.get(url, params=params) return resp...
Get PMML text of the current model. Note that model file obtained via this method might be incomplete due to size limitations.
Get model url
public function toArray() { $properties = get_object_vars($this); foreach($properties as $var => &$value) { if(gettype($value) === 'object') { unset($properties[$var]); } } return $properties; }
Get properties as array view @return array
return ((MaterialDialog.Builder) dialogBuilder).create(); }
function(data){ if (data === undefined) { data = ''; } var $msgbar = $('#message-bar'); $msgbar.removeClass('message-fail'); $msgbar.addClass('message-success'); $msgbar.text(data); if(window.SwaggerTranslator) { window.SwaggerTranslator.translate($msgbar); } }
Shows message on topbar of the ui
// the 'layout' of the bar $bar->setFormat(' [%bar%] '); $bar->setBarWidth(20); return $bar; }
public SoapFault locale(String locale) { LocaleEditor localeEditor = new LocaleEditor(); localeEditor.setAsText(locale); this.locale = (Locale) localeEditor.getValue(); return this; }
Sets the locale used in SOAP fault. @param locale
// DriverName returns the driver name of the given interface name.
private static void checkNonDebugLabel(final Label label) { Field f = getLabelStatusField(); int status = 0; try { status = f == null ? 0 : ((Integer) f.get(label)).intValue(); } catch (IllegalAccessException e) { throw new Error("Internal error"); } ...
Checks that the given label is not a label used only for debug purposes. @param label the label to be checked.
Gets the index of the given label. The label must exist, otherwise a runtime exception is thrown. @param labelText label to check @return index of the label
func (t *TableMap) setupHooks(i interface{}) { // These hooks must be implemented on a pointer, so if a value is passed in // we have to get a pointer for a new value of that type in order for the // type assertions to pass. ptr := i if reflect.ValueOf(i).Kind() == reflect.Struct { ptr = reflect.New(reflect.Valu...
// Determine which hooks are supported by the mapper struct i
// commit prunes all entries marked modified that are now fully spent and marks // all entries as unmodified.
private function interpretResponseJSON() { $this->debug_echo("\n\nResponse (json):\n"); $this->debug_print_r($this->state['response']['body_raw']); // Convert response from json to array format if required if ($this->config['dataFormat'] == 'array') { try { ...
throw new ApiException($msg, $this->state); } $this->debug_echo("\n\nResponse (array):\n"); $this->debug_print_r($this->state['response']['body']); } else { $this->state['response']['body'] = $this->state['response']['body_raw']; } if ($this->st...
@response = JSON.parse(api_response.body) end
function hashNumber(n) { if (n !== n || n === Infinity) { return 0; } let hash = n | 0; if (hash !== n) { hash ^= n * 0xffffffff; } while (n > 0xffffffff) { n /= 0xffffffff; hash ^= n; } return smi(hash); }
Compress arbitrarily large numbers into smi hashes.
hash += ~(hash << 11); hash ^= (hash >>> 16); return hash & (table.length - 1); }
def get_tag_value(resource, tag, utf_8=False): """Get the resource's tag value.""" tags = {k.lower(): v for k, v in resource.get('tags', {}).items()} value = tags.get(tag, False)
if value is not False: if utf_8: value = value.encode('utf8').decode('utf8') return value
SELECT request_date, request_type, request_date - LAG(request_date) OVER (PARTITION BY contractor_id ORDER BY request_date) as days_since_previous FROM contractor_maintenance;
'user': Explain the importance and use of a divide and conquer algorithm in solving complex computational problems. Provide a detailed example of a divide and conquer algorithm for solving a specific problem, and analyze its time and space complexity., 'assistant': A divide and conquer algorithm is a problem-solving ap...
The divide and conquer algorithm provided above was successful in finding the maximum element in the sample array, which is 99. The comments in the code explain each step in the divide and conquer process: 1. Base case: The function stops recursing when it reaches an array of size 1 and simply returns the single eleme...
The Divide-and-Conquer algorithm is a problem-solving approach that involves breaking down a complex problem into smaller, more manageable subproblems, solving each subproblem independently, and then combining the solutions to solve the original problem. It follows three basic steps: 1. Divide: The problem is divided ...
protected function fireFinalEvent($name = null, $resource = null) { if (empty($name)) { $name = $this->getEventName(); } if (empty($resource)) { $resource = $this->getEventResource(); } /** @noinspection PhpUnusedLocalVariableInspection */ $res...
Fires last event before responding @param string|null $name Optional name to append @param string|null $resource Optional override for resource
Returns the resource event name. @param ResourceInterface $resource @param string $suffix @return string|null
def upload( self, pdf, title=None, source=None, description=None, related_article=None, published_url=None, access='private', project=None, data=None, secure=False, force_ocr=False ): """ Upload a PDF or other image file to DocumentCloud. You can submit either a pdf ...
params['source'] = source if description: params['description'] = description if related_article: params['related_article'] = related_article if published_url: params['published_url'] = published_url if access: params['access'] = access ...
Returns an instantiated FormSet if available. If `self.can_submit` is False then no formset is returned.
function isSameMonth(d1, d2) { if (!d1 || !d2) { return false;
} return d1.getMonth() === d2.getMonth() && d1.getFullYear() === d2.getFullYear(); }
return d1.getDate() == d2.getDate() && d1.getMonth() == d2.getMonth() && d1.getYear() == d2.getYear(); }
def next_joystick_device(): """Finds the next available js device name.""" for i in range(100):
dev = "/dev/input/js{0}".format(i) if not os.path.exists(dev): return dev
small hackisch workaround for unicode problems with the picflash api
public function getBlacklist() { if (isset($this->raw->blacklist)) { $blacklist = (array) $this->raw->blacklist; array_walk( $blacklist, function (&$file) { $file = Path::canonical($file); } ); ...
Returns the list of blacklisted relative file paths. @return array The list of paths.
Returns a status object if the given name is not visible. Args: value: The value to check. The actual value here is not important but the value's metadata (e.g. package and type) will be checked. Returns: None if the value is visible. A variable structure with an error status if the ...
public function getData() { if (is_null($this->data)) { try { $this->data = $this->getParser()->parse($this->getYmlData()); } catch (ParseException $exp) { throw new RoutesFileParseException( "Fail to parse routes file: ". ...
Returns parsed data from YML If no data is present the YML parser parses it and its values are assigned to the data field. @return mixed
// Convert_v1_LoadBalancerIngress_To_core_LoadBalancerIngress is an autogenerated conversion function.
func (c oauthClient) SubtaskPositions() ([]wl.Position, error) { lists, err := c.Lists() if err != nil { return nil, err } listCount := len(lists) c.logger.Debug( "subtaskPositions", map[string]interface{}{"listCount": listCount}, ) subtaskPositionsChan := make(chan []wl.Position, listCount) idErrChan :...
// SubtaskPositions gets all subtask positions for all lists.
getting taskPositions for list", map[string]interface{}{"listID": idErr.id, "err": err}, ) e.addError(idErr) } } totalTaskPositions := []wl.Position{} for i := 0; i < listCount; i++ { taskPositions := <-taskPositionsChan totalTaskPositions = append(totalTaskPositions, taskPositions...) } if len(e...
function pollTexture(storageId) { var url = getNoCdnUrlFromStorageId(storageId) return poll(function (resolve, reject, next) { checkIfFileExists(url).then(function(exists){ exists ? resolve() : next() }) }) }
poll for DDS storageIds
// Exists checks if the given file is in the storage
private static void setStorageEngine(Dataframe dataset) { //create a single storage engine for all the MapRealMatrixes if (storageEngine == null) { synchronized(DataframeMatrix.class) { if (storageEngine == null) {
String storageName = "mdf" + RandomGenerator.getThreadLocalRandomUnseeded().nextLong(); storageEngine = dataset.configuration.getStorageConfiguration().createStorageEngine(storageName); } } } }
engine; if (newEngine == null) { engine = new JavaPhysicsEngine(); } else { engine = newEngine; } return oldEngine; }
Who is the top donor in the state of California?
SELECT name, MAX(amount) FROM donors WHERE state = 'California';
UPDATE teachers SET email = CASE WHEN state = 'California' THEN CONCAT(name, '@californiateachers.org') ELSE email END WHERE state = 'California';
def get_tick(self, index): """Get a tick's interval. Args: index (int): The index of the tick that you want to fetch. Returns: int, int: Error code and The tick's interval in seconds. A value of 0 means that the tick is disabled. """
name = self.tick_name(index) if name is None: return [pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY), 0] return [Error.NO_ERROR, self.ticks[name]]
x, y = self.view((r, self._x_pos[0])) x -= 5 text = self.svg.node( guides, 'text', x=x, y=y, class_='major' if major else '' ) text.text = label if self.y_label_rotation: text.attrib[ 'transform' ...
func NewCoreScheduler(srv *Server, snap *state.StateSnapshot) scheduler.Scheduler { s := &CoreScheduler{ srv: srv, snap: snap,
logger: srv.logger.ResetNamed("core.sched"), } return s }
for n, _ in enumerate(self.l): if where[n]: self.l[n] = src.l[n]
public function read(string $format = null) : string { $input = array_shift($this->stack); if (isset($format, $input)) { $input = sprintf($format, $input); } return $input ?? ''; }
Fake input reader. Shifts elements off the stack. @param string|null $format Optional format @return string
$input = new Input($this->expression('input'), $options); return $input; }
protected function requireToken($token) { if ($token) { return $this->setToken($token); } elseif ($this->token) { return $this; } else
{ throw new JWTException('A token is required', 400); } }
word = normalize_text(word) if word: result.append(word) return delim.join(result)
public function where($condition, $parameters = []) { $this->emptyResult();
$this->queryBuilder->addWhere($condition, $parameters); return $this; }
defined if ($this->get_parent() && $this->get_parent()->get_parent() && $conditionparam !== null) { $this->procconditionparam = $this->find_element($conditionparam); } $this->conditionparam = $conditionparam; $this->conditionvalue = $conditionvalue; }
def kill_ghosts(): """ Kill process from previous GNS3 session """ detect_process = ["vpcs", "ubridge", "dynamips"] for proc in psutil.process_iter(): try: name = proc.name().lower().split(".")[0] if name in detect_process:
proc.kill() log.warning("Killed ghost process %s", name) except (psutil.NoSuchProcess, psutil.AccessDenied): pass
if self._process: try: self._process.kill() except ProcessLookupError: pass if self._process.returncode is None: log.warn('QEMU VM "{}" PID={} is still running'.for...
&lt;p&gt; Consider the number $12$. The divisors of $12$ are: $1,2,3,4,6$ and $12$.&lt;br&gt; Every number from $1$ up to and including $12$ can be written as a sum of distinct divisors of $12$:&lt;br&gt; $1=1$, $2=2$, $3=3$, $4=4$, $5=1+4$, $6=6$, $7=1+6$, $8=2+6$, $9=3+6$, $10=4+6$, $11=1+2+3+5$, $12=12$.&lt;br&gt; A...
We need a brute force approach to solve this problem with the following steps: - Divide a large range, say 1,000,000,000 into smaller parts. - Use multiprocessing on each part. - Create a helper function to check if a pair of numbers are primes. - Create another function to check super practical numbers. - Inside the ...
This problem cannot be directly calculated without significant computational resources. Direct calculation involves generating a number with the multiplication of approximately 900,000 prime numbers raised to the power of 10^12, finding its divisors, and forming unique tuple pairs of these divisors which satisfy the co...
private void initNotificationBuilder(Context context) { // inti builder. mNotificationBuilder = new NotificationCompat.Builder(context); mNotificationView = new RemoteViews(context.getPackageName(), R.layout.simple_sound_cloud_notification); mNotificationExpandedView = n...
icon for action bar. mNotificationBuilder.setSmallIcon(mNotificationConfig.getNotificationIcon()); // set the remote view. mNotificationBuilder.setContent(mNotificationView); // set the notification priority. mNotificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH); ...
notificationView.setImageViewResource(R.id.simple_sound_cloud_notification_icon, mNotificationConfig.getNotificationIcon()); }
def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, cmap:str='tab20', alpha:float=0.5, **kwargs): "Show the `ImageSegment` on `ax`." ax = show_image(self, ax=ax, hide_axis=hide_axis, cmap=cmap, figsize=figsize, interpolatio...
Show the `ImageSegment` on `ax`.
// whitespace .replace(/-+/g, '-') // duplicated hyphen .replace(/^-+|-+$/g, '') // heading/ tailing hyphen return text }
def get_current_ontology_date(): """Get the release date of the current Gene Ontolgo release.""" with closing(requests.get( 'http://geneontology.org/ontology/go-basic.obo', stream=True)) as r: for i, l in enumerate(r.iter_lines(decode_unicode=True)): if i == 1: ...
Get the release date of the current Gene Ontolgo release.
Get the last modification date of the ontology.
func (c *CNIConfig) CheckNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) error { // CHECK was added in CNI spec version 0.4.0 and higher if gtet, err := version.GreaterThanOrEqualTo(list.CNIVersion, "0.4.0"); err != nil { return err } else if !gtet { return fmt.Errorf("configuration ve...
return fmt.Errorf("failed to get network %q cached result: %v", list.Name, err) } for _, net := range list.Plugins { if err := c.checkNetwork(ctx, list.Name, list.CNIVersion, net, cachedResult, rt); err != nil { return err } } return nil }
err = NewResult(conf.CNIVersion, resultBytes) if err != nil { return fmt.Errorf("could not parse prevResult: %v", err) } return nil }
protected function processDateConversions() { $events = (isset($this->cal['VEVENT'])) ? $this->cal['VEVENT'] : array(); if (!empty($events)) { foreach ($events as $key => $anEvent) { if (!$this->isValidDate($anEvent['DTSTART'])) { unset($events[$key])...
Processes date conversions using the time zone Add keys `DTSTART_tz` and `DTEND_tz` to each Event These keys contain dates adapted to the calendar time zone depending on the event `TZID`. @return void
Returns a VEVENT for the current iterations of the event. This VEVENT will have a recurrence id, and its DTSTART and DTEND altered. @return VEvent
func (c *Config) BuildNameToCertificate() { c.NameToCertificate = make(map[string]*Certificate) for i := range c.Certificates { cert := &c.Certificates[i] x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) if err != nil { continue } if len(x509Cert.Subject.CommonName)
> 0 { c.NameToCertificate[x509Cert.Subject.CommonName] = cert } for _, san := range x509Cert.DNSNames { c.NameToCertificate[san] = cert } } }
// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate // from the CommonName and SubjectAlternateName fields of each of the leaf // certificates.
public static function requireId($parameters, $UINTEGER = true) { //Work with arrays if (is_object($parameters)) { $parameters = (array)$parameters; } if (isset($parameters['resource_id']) && preg_match(Validate::REGEXP_RESOURCE_ID, $parameters['resource_id']...
Require id parameter, it uses `resource_id` or `id` parameter if available @param array|object $parameters The request paramters @param boolean $UINTEGER *[Optional]*, Check id's type to be unsigned integer, default is true @throws \Phramework\Exceptions\IncorrectParameters When value is not correct @throws \Ph...
Require id parameter if it's set else return NULL, it uses `resource_id` or `id` parameter if available @param array|object $parameters The request parameters @param boolean $UINTEGER *[Optional]*, Check id's type to be unsigned integer @throws \Phramework\Exceptions\IncorrectParameters When value is not corre...
protected function applyStyleMethods($name, $method_search = null) { // Get all of the possible style attributes $method_search = $method_search ?: array_keys($this->style->all()); $new_name = $this->searchForStyleMethods($name, $method_search); // While we still have a name left a...
Search for any style methods within the name and apply them @param string $name @param array $method_search @return string Anything left over after applying styles
Search for style methods in the current name @param string $name @param array $search @return string
public static <T> Constraint checking(Function<String, T> check, String messageOrKey, boolean isKey, String... extraMessageArgs) { return mkSimpleConstraint(((label, vString, messages) -> { logger.debug("checking for {}", vString); if (isEmptyStr(vString)) return null; ...
make a Constraint which will try to check and collect errors
if (heapsForThisClient != null) { for (String s : heapsForThisClient.keySet()) { terminateSubscriptions(session, s, reason); } } }
protected static function detectIP() { // Normally the $_SERVER superglobal is set if (isset($_SERVER)) { // Do we have an x-forwarded-for HTTP header (e.g. NginX)? if (self::$allowIpOverrides && array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) { return $_SERVER['HTTP_X_FORWARDED_FOR']; } ...
// Do we have an x-forwarded-for HTTP header? if (self::$allowIpOverrides && getenv('HTTP_X_FORWARDED_FOR')) { return getenv('HTTP_X_FORWARDED_FOR'); } // Do we have a client-ip header? if (self::$allowIpOverrides && getenv('HTTP_CLIENT_IP')) { return getenv('HTTP_CLIENT_IP'); } // Normal, non-p...
} if (isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && self::validateIp($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) { return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP']; } if (isset($_SERVER['HTTP_FORWARDED_FOR']) && self::validateIp($_SERVER['HTTP_FORWARDED_FOR'])) { return $_SER...
def ebeam(self, context): """ ebeam cube data source """ if context.shape != self.shape: raise ValueError("Partial feeding of the " "beam cube is not yet supported %s %s." % (context.shape, self.shape)) ebeam = np.empty(context.shape, context.dtype) # Iterat...
# otherwise zeroing the correlation for i, (re, im) in enumerate(self._files.itervalues()): ebeam[:,:,:,i].real[:] = 0 if re is None else re[0].data.T ebeam[:,:,:,i].imag[:] = 0 if im is None else im[0].data.T return ebeam
# PCA is possible msg = ("Y must be of shape either " "(n, {}) or (n, {})").format( self.data.shape[1], self.data_nu.shape[1]) else: # no PCA, only one choice of shape msg = "Y must be of shape...
def capture(command, input=None, cwd=None, shell=False, raiseOnError=False): """ Executes a child process and captures its output """ # Attempt to execute the child process proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, shell=shell, universa...
!= 0: raise Exception( 'child process ' + str(command) + ' failed with exit code ' + str(proc.returncode) + '\nstdout: "' + stdout + '"' + '\nstderr: "' + stderr + '"' ) return CommandOutput(proc.returncode, stdout, stderr)
Runs a command in an out-of-process shell, returning the output of that command. Working directory is ROOT.
def get_best_routes_internal( chain_state: ChainState, token_network_id: TokenNetworkID, from_address: InitiatorAddress, to_address: TargetAddress, amount: int, previous_address: Optional[Address], ) -> List[RouteState]: """ Returns a list of channels that can be used...
Returns a list of channels that can be used to make a transfer. This will filter out channels that are not open and don't have enough capacity.
unset( $this->members[$key] ); } return $this; }
static function templateXlate($in_string) { if (!$in_string) { return $in_string; } $out_string = "T_" . $in_string; $local = ReporticoApp::get("locale"); if ($local) { if (array_key_exists($out_string, $local["template"])) { $out_stri...
Fetched translation for a template string
unset($field[0]); $this->addField($name, $field); continue; } } return $this; }
public function render(RendererInterface $renderer = null) { $renderer = $renderer ?: $this->getDefaultRenderer(); $form = $this->header(); foreach ($this->rows as $row) { $form .= $row->render($renderer); } $form .= '</form>'; return $form; }
Render the entire Form.
listeners: listeners, client: &http.Client{ Transport: &headerRoundTripper{ Transport: transport, headers: headers, }, Timeout: timeout, }, } }
public void defineFrom(InputProblemReporter rep, DTDElement definedElem, boolean fullyValidate) throws XMLStreamException { if (fullyValidate) { verifyUndefined(); } mValidator = definedElem.mValidator; mAllowedContent = definedElem.mAll...
Method called to "upgrade" a placeholder using a defined element, including adding attributes.
== b.sortval) return 0; else return 1; }
def ungroup_unique(unique_items, groupxs, maxval=None): """ Ungroups unique items to correspond to original non-unique list Args: unique_items (list): groupxs (list): maxval (int): (default = None) Returns: list: ungrouped_items CommandLine: python -m utool...
Ungroups unique items to correspond to original non-unique list Args: unique_items (list): groupxs (list): maxval (int): (default = None) Returns: list: ungrouped_items CommandLine: python -m utool.util_alg ungroup_unique Example: >>> # ENABLE_DOCTEST ...
%s' % (ut.repr2(ungrouped_items),)) >>> print(result) ungrouped_items = [1, 2, 1, 2, 3, 3] """ if maxval is None: maxpergroup = [max(xs) if len(xs) else 0 for xs in groupxs] maxval = max(maxpergroup) if len(maxpergroup) else 0 ungrouped_items = [None] * (maxval + 1) for i...
function next( ret ) { if( ret.done ) { return resolve( ret.value ); } var value = toPromise.call( ctx, ret.value ); if( value && isPromise( value ) ) { return value.then( onFulfilled, onRejected ); } return onReject...
yield a function, promise, generator, array, or object, ' + 'but the following object was passed: "' + String( ret.value ) + '"' ) ); }
SVG or Scalable Vector Graphics is an XML markup language for describing two-dimensional graphics. The `<path>`, `<circle>`, and `<rect>` elements represent different visual shapes in SVG. The `<path>` element is used to define a path. The following commands are available for path data: M = moveto, L = lineto, H = ho...
function renderParagraphSeparationField( $args ) { unset( $args['label_for'], $args['class'] ); $this->renderRadioButtons( [ 'id' => 'pdf_paragraph_separation', 'name' => 'pressbooks_theme_options_' . $this->getSlug(), 'option' => 'pdf_paragraph_separation', 'value' => getset( $this->options, 'pd...
Render the pdf_paragraph_separation radio buttons. @param array $args
Render the ebook_paragraph_separation radio buttons. @param array $args
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { logger.debug("Handling HttpServletRequest {}", request); response.setContentType(contentType); OutputStream output = response.getOutputStream(); InputStream input = getRequestStream(request); int result = ErrorRe...
{ logger.debug("Bad request: empty contents!"); } else { logger.error(t.getMessage(), t); } } int httpStatusCode = httpStatusCodeProvider == null ? DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(result) : httpStatusCodeProvider.getHttpStatusCode(result); response.setStatus(httpStatusCo...
elif isinstance(value, (dict, list)) and len(str(value)) > constants.MAX_VALUE_LABEL_TEXT_LENGTH: value_text = str(value)[:constants.MAX_VALUE_LABEL_TEXT_LENGTH] + "..." final_string = " " + value_text + " " else: final_string = " " + str(value) + " " return final_string
private void addMessageToSitesTree(final HistoryReference historyReference, final HttpMessage message) { if (View.isInitialised() && !EventQueue.isDispatchThread()) { EventQueue.invokeLater(new Runnable() { @Override public void run() { addMessageToSitesTree(historyReference, message); } }); ...
!= null) { try { addUriToAddedNodesModel(SessionStructure.getNodeName(message), message.getRequestHeader().getMethod(), ""); } catch (URIException e) { log.error("Error while adding node to added nodes model: " + e.getMessage(), e); } } }
|| historyType == HistoryReference.TYPE_AUTHENTICATION || historyType == HistoryReference.TYPE_PROXY_CONNECT; }
Write an SQL query to return the customers whose purchases include at least one product with productid 100 and at least one product with productid 101. Additionally, provide a piece of erroneous code that does not fulfill the prompt requirements and explain what's wrong with it. **Erroneous Code:** ``` SELECT custome...
**Correct Code:** ``` SELECT customer_id FROM orders WHERE customer_id IN ( SELECT customer_id FROM orders WHERE productid = 100 ) AND customer_id IN ( SELECT customer_id FROM orders WHERE productid = 101 ) ``` **Explanation:** This query operates by looking for `customer_id` values that ...
Corrected SQL query: ```sql SELECT product_id, product_name, ROUND(AVG(product_price), 2) AS average_price FROM products INNER JOIN orders ON products.product_id = orders.product_id WHERE product_price > 10 GROUP BY product_id, product_name HAVING COUNT(*) > 100 ``` Explanation: In the corrected query, the WHERE clau...
public function getSnippets( $locale, $type = null, $offset = null, $max = null, $search = null, $sortBy = null, $sortOrder = null ) { $query = $this->getSnippetsQuery($locale, $type, $offset, $max, $search, $sortBy, $sortOrder); $documents = $...
Return snippets. If $type is given then only return the snippets of that type. @param string $locale @param string $type Optional snippet type @param int $offset Optional offset @param int $max Optional max @param string $search @param string $sortBy @param string $sortOrder @throws \InvalidArgumentException @retur...
Query for documents with given locale. @param string $locale @return QueryResultInterface
private File getConfigIni(File galaxyRoot) { if (isPre20141006Release(galaxyRoot)) { return new File(galaxyRoot, "universe_wsgi.ini"); } else { File configDirectory = new
File(galaxyRoot, CONFIG_DIR_NAME); return new File(configDirectory, "galaxy.ini"); } }
Gets the config ini for this Galaxy installation. @param galaxyRoot The root directory of Galaxy. @return A File object for the config ini for Galaxy.
func (db *DB) NodeSeq(id ID) uint64 { return
db.fetchUint64(nodeItemKey(id, zeroIP, dbNodeSeq)) }
// ID returns the ID of a given Conn.
protected function registerProviders(Collection $providers) { // loop through providers to be registered. $providers->each(function ($providerClass) {
// register a provider class. $this->app->register($providerClass); }); }
Wrapper that converts PHP errors to exceptions and passes them to the standard error50x handler.
public ListenableFuture<SegmentsAndMetadata> publishAll(final TransactionalSegmentPublisher publisher) { final Map<String, SegmentsForSequence> snapshot; synchronized (segments) { snapshot = ImmutableMap.copyOf(segments); } return publishInBackground( new SegmentsAndMetadata( ...
Publish all segments. @param publisher segment publisher @return a {@link ListenableFuture} for the publish task
} // Commit all segment-related transactional changes to their respective sources. this.segmentUpdates.values().forEach(txn -> { UpdateableSegmentMetadata targetSegmentMetadata = target.getStreamSegmentMetadata(txn.getId()); if (targetSegmentMetadata == null) { t...
func (b *BigIP) VirtualAddresses() (*VirtualAddresses, error) { var va VirtualAddresses err, _ := b.getForEntity(&va, uriLtm, uriVirtualAddress) if err != nil { return nil, err } return &va, nil }
// VirtualAddresses returns a list of virtual addresses.
b.getForEntity(&va, uriLtm, uriVirtualAddress) if err != nil { return nil, err } return &va, nil }
func (s *Health) Status() string { s.mu.Lock() defer s.mu.Unlock() // This happens when the monitor has yet to be setup.
if s.Health.Status == "" { return types.Unhealthy } return s.Health.Status }
} log.Infof("HA state transition %v -> %v complete", state, s) } now := time.Now() h.statusLock.Lock() h.status.State = s h.status.Since = now h.status.LastUpdate = now h.statusLock.Unlock() }
public <T> RestBuilder provide(ContextProvider<T> provider) { Assert.notNull(provider, "Missing context provider!");
contextProviders.add(provider); return this; }
Remove a provider @param provider The provider
public function handle($request = null, $echo = true, $sendHeader = true) { if ($request === null) { $request = $_REQUEST; } $op = 'find'; if (isset($request['op'])) { $op = $request['op']; if (!in_array($op, array('find', 'get', 'clear'))) { ...
Handles the current request @param array $request Request data @param bool $echo @param bool $sendHeader @return string @throws DebugBarException
'Content-Type' => 'application/json' )); } $response = json_encode(call_user_func(array($this, $op), $request)); if ($echo) { echo $response; } return $response; }
@SuppressWarnings("unchecked") public T tags(final Collection<String> tags) { if (this.tags == null) { this.tags = new HashSet<>(); } this.tags.addAll(tags); return (T) this; }
Specify the tags associated with the sound. @param tags The tags associated with the sound @return The current {@link UploadSound} instance
Write an unsigned short to the byte array starting at the given offset @param bytes The byte array @param value The short to write @param offset The offset to begin writing at
function(type, factory) { var key_parameters = {}, __type = parse_type(type, key_parameters) .toLowerCase(); // normalize prop name, remove lead '/' for(var prop in key_parameters) if (prop[0] === '/') { key_parameters[prop.slice(1)] = key...
subtypes_array.push(key_parameters); } else { // register as standalone type // check name conflict if (this[__type]) throw new TypeError('Type ' + type + ' already registered!'); this[__type] = factory; } ...
Maps type parameters in a type to their values. @param toMapType Type possibly containing type arguments @param typeAndParams must be either ParameterizedType, or (in case there are no type arguments, or it's a raw type) Class @return toMapType, but with type parameters from typeAndParams replaced.
calc a log distribution in python
def glog(x,l = 2): """ Generalised logarithm :param x: number :param p: number added befor logarithm """ return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)
Cumulative distribution function for two-sided Gaussian Parameters ---------- x : float Input values at which to calculate CDF. p : array-like Parameters of distribution: (mu: mode of distribution, sig1: LH width, ...
func (s *Action) OTP(ctx context.Context, c *cli.Context) error { name := c.Args().First() if name == "" { return ExitError(ctx, ExitUsage, nil, "Usage: %s otp <NAME>", s.Name) } qrf := c.String("qr") clip := c.Bool("clip") return s.otp(ctx, c, name, qrf, clip, true) }
// OTP implements OTP token handling for TOTP and HOTP
ExitError(ctx, ExitUsage, nil, "Usage: %s edit secret", s.Name) } return s.edit(ctx, c, name) }
func (rc *RequestConfig) OPTIONS(path string) *RequestConfig { rc.Path =
path rc.Method = "OPTIONS" return rc }
{ rc.Path = p return rc }
def solar_term(self, year, degrees, timezone='UTC'): """ Returns the date of the solar term for the given longitude and the given year. Solar terms are used for Chinese and Taiwanese holidays (e.g. Qingming Festival in Taiwan). More information: - https://en.wik...
# Find approximately the right time of year. target_longitude = degrees * ephem.degree difference = (target_longitude - current_longitude) % twopi t0 = ephem.Date(str(year)) + 365.25 * difference / twopi # Zero in on the exact moment. def f(t): sun.compute(t) ...
Geometric calculation of solar sunrise, sunset, and transit. .. warning:: The geometric calculation assumes a circular earth orbit with the sun as a point source at its center, and neglects the effect of atmospheric refraction on zenith. The error depends on location and time of year but is...
def _getInterfaces(self): """ Load application communication interfaces. :return: <dict> """ interfaces = {} interfacesPath = os.path.join("application", "interface") interfaceList = os.listdir(interfacesPath) for file in interfaceList: inte...
Load application communication interfaces. :return: <dict>
method: "DELETE", api: "_mappings/" + typeName, } return r.Run() }
public function getProcessedMetricsById() { $processedMetrics = $this->processedMetrics ?: array(); $result = array(); foreach ($processedMetrics as $processedMetric) { if ($processedMetric instanceof ProcessedMetric || $processedMetric instanceof ArchivedMetric) { // instanceof...
Returns an array mapping the ProcessedMetrics served by this report by their string names. @return ProcessedMetric[]
$metrics = array_merge($metrics, $report->getProcessedMetricsById()); } $result = array(); /** @var Metric $metric */ foreach ($metrics as $metric) { if (!($metric instanceof $baseType)) { continue; } $result[$metric->getName()] = $m...
func GetString(key string, defaultValue string) string { result, err := factory.GetValue(key).ToString()
if err != nil { return defaultValue } return result }
GCSRegionalLocations[loc] _, multiRegional := GCSMultiRegionalLocations[loc] if !(regional || multiRegional) { return ErrUnknownLocation } if _, ok := GCSStorageClass[c.StorageClass]; !ok { return ErrUnknownStorageClass } return validLocationStorageClass(loc, c.StorageClass) }
def configuration(ctx): """ Show configuration variables """ t = [["Key", "Value"]] for key in ctx.bitshares.config: t.append([key, ctx.bitshares.config[key]]) print_table(t)
Show configuration variables
Slice config for printing as defined in key. :param ConfigManager config: configuration dictionary :param str key: dotted key, by which config should be sliced for printing :returns: sliced config :rtype: dict
End of preview. Expand in Data Studio

coir-train-hard-negatives

2,090,845 (anchor, positive, negative) triplets from the train splits of 9 CoIR tasks (StackOverflowQA has no train split), used to train blink-code-16M.

Decontamination. CoIR shares data between its train and test splits: for example, 76% of CosQA's relevant test documents are also train positives. Starting from 2,109,918 train pairs, we remove:

  1. 10,016 pairs whose query is a test query;
  2. 8,429 pairs whose positive is a relevant test document (exact match);
  3. 628 more after whitespace-normalized matching against test queries and relevant test documents, now also checking the mined negatives (620 for the coderankembed subset, whose negatives differ).

Hard negatives. For each query we rank the top 50 documents with a model. The negative is the highest-ranked document that scores below the positive and isn't another positive of the same query; when none of the top 50 qualifies, the negative is a random document. We mine in two rounds:

  1. coderankembed: mined with CodeRankEmbed (88% of pairs get a hard negative). We train a model on these with blink-code-16M's recipe.
  2. default: mined again with the model from round 1 (78% of pairs get a hard negative). blink-code-16M is trained on this subset.
from datasets import load_dataset

train = load_dataset("minishlab/coir-train-hard-negatives", split="train")  # what blink-code-16M is trained on
round1 = load_dataset("minishlab/coir-train-hard-negatives", "coderankembed", split="train")

The source tasks have their own licenses, which apply to this data; see the CoIR repository.

Downloads last month
26

Models trained or fine-tuned on minishlab/coir-train-hard-negatives