file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
models.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from datetime import datetime
from django.conf import settings
from django.db import models
from django_extensions.db.f... | :
abstract = True
def save(self, *args, **kwargs):
if kwargs.pop('modified', True):
self.modified = datetime.now()
super(TimeStampedModel, self).save(*args, **kwargs)
class Release(TimeStampedModel):
CHANNELS = ('Nightly', 'Aurora', 'Beta', 'Release', 'ESR')
PRODUCTS =... | Meta | identifier_name |
cmd_user.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import isValidIdent, trimStringToByteLength
from zope.interface import implementer
from typing import Any, Dict, List, Optional, Tuple
@implementer... | (self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[Any, Any]]:
if len(params) < 4:
user.sendSingleError("UserCmd", irc.ERR_NEEDMOREPARAMS, "USER", "Not enough parameters")
return None
if not params[3]: # Make sure the gecos isn't an empty string
user.se... | parseParams | identifier_name |
cmd_user.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import isValidIdent, trimStringToByteLength
from zope.interface import implementer
from typing import Any, Dict, List, Optional, Tuple
@implementer... |
def userCommands(self) -> List[Tuple[str, int, Command]]:
return [ ("USER", 1, self) ]
def parseParams(self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[Any, Any]]:
if len(params) < 4:
user.sendSingleError("UserCmd", irc.ERR_NEEDMOREPARAMS, "USER", "Not... | forRegistered = False | random_line_split |
cmd_user.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import isValidIdent, trimStringToByteLength
from zope.interface import implementer
from typing import Any, Dict, List, Optional, Tuple
@implementer... |
def parseParams(self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[Any, Any]]:
if len(params) < 4:
user.sendSingleError("UserCmd", irc.ERR_NEEDMOREPARAMS, "USER", "Not enough parameters")
return None
if not params[3]: # Make sure the gecos isn't an empt... | return [ ("USER", 1, self) ] | identifier_body |
cmd_user.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import isValidIdent, trimStringToByteLength
from zope.interface import implementer
from typing import Any, Dict, List, Optional, Tuple
@implementer... |
return {
"ident": params[0],
"gecos": params[3]
}
def execute(self, user: "IRCUser", data: Dict[Any, Any]) -> bool:
user.changeIdent(data["ident"])
user.changeGecos(data["gecos"])
user.register("USER")
return True
cmd_user = UserCommand() | user.sendSingleError("UserCmd", irc.ERR_NEEDMOREPARAMS, "USER", "Your username is not valid") # The RFC is dumb.
return None | conditional_block |
note-search.component.ts | import { Component, OnInit, OnChanges } from '@angular/core';
import 'rxjs/add/observable/of';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operat... | (term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.getNotes();
}
ngOnChanges() {
this.getNotes();
}
getNotes() {
this.notes = this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.switchMap(term => term ?
this.nAPI.getNotes({where: {fullTe... | search | identifier_name |
note-search.component.ts | import { Component, OnInit, OnChanges } from '@angular/core';
import 'rxjs/add/observable/of';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operat... |
ngOnChanges() {
this.getNotes();
}
getNotes() {
this.notes = this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.switchMap(term => term ?
this.nAPI.getNotes({where: {fullTextSearch: term}}) : Observable.of<Note[]>([]))
.catch(err => {
console.log(err);
return Ob... | {
this.getNotes();
} | identifier_body |
note-search.component.ts | import { Component, OnInit, OnChanges } from '@angular/core';
import 'rxjs/add/observable/of';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operat... |
@Component({
selector: 'app-note-search',
templateUrl: './note-search.component.html',
styleUrls: ['./note-search.component.css']
})
export class NoteSearchComponent implements OnInit, OnChanges {
selectedNote: Note;
notes: Observable<Note[]>;
private searchTerms = new Subject<string>();
constructor(pr... | import { Note } from '../data.model';
import { NoteApi } from '../shared/sdk/services/custom/Note';
import {NoteService} from "../shared/services/note.service"; | random_line_split |
Profile.tsx | import React, { FunctionComponent } from 'react';
import classnames from 'classnames';
import { ContactModel } from 'ringcentral-integration/models/Contact.model';
import { extensionStatusTypes } from 'ringcentral-integration/enums/extensionStatusTypes';
import { PresenceModel } from 'ringcentral-integration/models/Pre... | currentLocale={currentLocale}
/>
</div>
</div>
</div>
);
};
Profile.defaultProps = {
sourceNodeRenderer: () => null,
}; | presence={presence} | random_line_split |
Profile.tsx | import React, { FunctionComponent } from 'react';
import classnames from 'classnames';
import { ContactModel } from 'ringcentral-integration/models/Contact.model';
import { extensionStatusTypes } from 'ringcentral-integration/enums/extensionStatusTypes';
import { PresenceModel } from 'ringcentral-integration/models/Pre... |
if (presence) {
const { presenceStatus, dndStatus } = presence;
const presenceName = getPresenceStatusName(
presenceStatus,
dndStatus,
currentLocale,
);
return (
<div className={styles.status}>
<div className={styles.presence}>
<PresenceStatusIcon
... | {
return (
<div className={styles.status}>
<div>
<span className={styles.inactiveText}>
{i18n.getString('notActivated', currentLocale)}
</span>
</div>
</div>
);
} | conditional_block |
SnapshotObjectFactory.js | // Copyright 2017 The TIE Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by appl... | */
tie.factory('SnapshotObjectFactory', [
function() {
var Snapshot = function(codePrereqCheckResult, codeEvalResult, feedback) {
this._codePrereqCheckResult = codePrereqCheckResult;
this._codeEvalResult = codeEvalResult;
this._feedback = feedback;
this._timestamp = '';
};
// In... | random_line_split | |
cmd_interface.py | import cmd
import json
import termcolor
from struct_manager import createEmptyCommandGroup, createEmptyStruct, createEmptyCommand
from populator import populateDict
class EditorShell ( cmd.Cmd ) :
def __init__ ( self, file ) :
cmd.Cmd.__init__(self)
self.file = file
# self.struct = json.load ( self.file )
... |
line = line.strip()
toks = line.split()
codename, group = createEmptyCommandGroup( toks[0] )
populateDict(group)
print group
self.struct['CommandGroups'][ codename ] = group
def do_add_command( self, line ) :
if not line :
print "Need a 'group code name' "
return
line = line.strip()
toks = l... | print "Need a 'name' "
return | conditional_block |
cmd_interface.py | import cmd
import json
import termcolor
from struct_manager import createEmptyCommandGroup, createEmptyStruct, createEmptyCommand
from populator import populateDict
class EditorShell ( cmd.Cmd ) :
def __init__ ( self, file ) :
cmd.Cmd.__init__(self)
self.file = file
# self.struct = json.load ( self.file )
... |
def do_list_commands( self, line ) :
for gname, group in self.struct['CommandGroups'].iteritems() :
print "=========== %s ===========" % group['name']
for k, v in group['Commands'].iteritems() :
print '''{0:24} -| {1:<64}\n-> {2:<64}
'''.format( k, v['command'].encode('utf8'), v['description'].encode('ut... | for group in self.struct['CommandGroups'].keys() :
print group | identifier_body |
cmd_interface.py | import cmd
import json
import termcolor
from struct_manager import createEmptyCommandGroup, createEmptyStruct, createEmptyCommand
from populator import populateDict
class EditorShell ( cmd.Cmd ) :
def __init__ ( self, file ) :
cmd.Cmd.__init__(self)
self.file = file
# self.struct = json.load ( self.file )
... | return
def do_list( self, line ) :
for group in self.struct['CommandGroups'].keys() :
print group
def do_list_commands( self, line ) :
for gname, group in self.struct['CommandGroups'].iteritems() :
print "=========== %s ===========" % group['name']
for k, v in group['Commands'].iteritems() :
pr... | populateDict( group )
if not comm :
print "Identifier '%s' doesn't exist" % comm | random_line_split |
cmd_interface.py | import cmd
import json
import termcolor
from struct_manager import createEmptyCommandGroup, createEmptyStruct, createEmptyCommand
from populator import populateDict
class EditorShell ( cmd.Cmd ) :
def __init__ ( self, file ) :
cmd.Cmd.__init__(self)
self.file = file
# self.struct = json.load ( self.file )
... | ( self, line ) :
if not line :
print "Need a 'name' "
return
line = line.strip()
toks = line.split()
dep = toks[0]
self.struct['DependencyTokens'].append( dep )
def do_d_list( self, line ) :
for group in self.struct.keys() :
print group
def do_d_show( self, line ) :
print json.dumps( self.s... | do_create_dependency | identifier_name |
is_negative_zero.rs | use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
use malachite_base_test_util::generators::primitive_float_gen;
fn is_negative_zero_helper<T: PrimitiveFloat>() {
let test = |n: T, out| {
assert_eq!(n.is_negative_zero(), out);
};
test(T::ZERO, false)... | test(T::from(1.234), false);
test(T::from(-1.234), false);
}
#[test]
fn test_is_negative_zero() {
apply_fn_to_primitive_floats!(is_negative_zero_helper);
}
fn is_negative_zero_properties_helper<T: PrimitiveFloat>() {
primitive_float_gen::<T>().test_properties(|x| {
assert_eq!(
x.is... | test(T::POSITIVE_INFINITY, false);
test(T::NEGATIVE_INFINITY, false);
test(T::ONE, false);
test(T::NEGATIVE_ONE, false); | random_line_split |
is_negative_zero.rs | use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
use malachite_base_test_util::generators::primitive_float_gen;
fn is_negative_zero_helper<T: PrimitiveFloat>() {
let test = |n: T, out| {
assert_eq!(n.is_negative_zero(), out);
};
test(T::ZERO, false)... |
#[test]
fn is_negative_zero_properties() {
apply_fn_to_primitive_floats!(is_negative_zero_properties_helper);
}
| {
primitive_float_gen::<T>().test_properties(|x| {
assert_eq!(
x.is_negative_zero(),
NiceFloat(x) != NiceFloat(x.abs_negative_zero())
);
});
} | identifier_body |
is_negative_zero.rs | use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
use malachite_base_test_util::generators::primitive_float_gen;
fn is_negative_zero_helper<T: PrimitiveFloat>() {
let test = |n: T, out| {
assert_eq!(n.is_negative_zero(), out);
};
test(T::ZERO, false)... | () {
apply_fn_to_primitive_floats!(is_negative_zero_helper);
}
fn is_negative_zero_properties_helper<T: PrimitiveFloat>() {
primitive_float_gen::<T>().test_properties(|x| {
assert_eq!(
x.is_negative_zero(),
NiceFloat(x) != NiceFloat(x.abs_negative_zero())
);
});
}
#... | test_is_negative_zero | identifier_name |
borrowck-borrowed-uniq-rvalue.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut buggy_map: HashMap<usize, &usize> = HashMap::new();
buggy_map.insert(42, &*box 1); //~ ERROR borrowed value does not live long enough
// but it is ok if we use a temporary
let tmp = box 2;
buggy_map.insert(43, &*tmp);
}
| main | identifier_name |
borrowck-borrowed-uniq-rvalue.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let mut buggy_map: HashMap<usize, &usize> = HashMap::new();
buggy_map.insert(42, &*box 1); //~ ERROR borrowed value does not live long enough
// but it is ok if we use a temporary
let tmp = box 2;
buggy_map.insert(43, &*tmp);
} | identifier_body | |
borrowck-borrowed-uniq-rvalue.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let mut buggy_map: HashMap<usize, &usize> = HashMap::new();
buggy_map.insert(42, &*box 1); //~ ERROR borrowed value does not live long enough
// but it is ok if we use a temporary
let tmp = box 2;
buggy_map.insert(43, &*tmp);
} | use std::collections::HashMap; | random_line_split |
grpc-namespaces.ts | import { Observable } from 'rxjs';
/**
* Namespace sample.
* @exports sample
* @namespace
*/
export namespace sample {
/**
* Contains all the RPC service clients.
* @exports sample.ClientFactory
* @interface
*/
export interface ClientFactory {
/**
* Returns the Greet... | */
export interface Greeter {
/**
* Calls SayHello.
* @param {sample.HelloRequest} request HelloRequest message or plain object
* @returns {Observable<sample.HelloReply>}
*/
sayHello(request: sample.HelloRequest): Observable<sample.HelloReply>;
}
/... | * @exports sample.Greeter
* @interface | random_line_split |
playlist_track.rs | use std::collections::BTreeMap;
use uuid::Uuid;
use chrono::{NaiveDateTime, Utc};
use postgres;
use error::Error;
use super::{conn, Model};
use model::track::{Track, PROPS as TRACK_PROPS};
use model::playlist::Playlist;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PlaylistTrack {
pub playlist_id: U... |
fn row_to_item(row: postgres::rows::Row) -> Self {
let offset = TRACK_PROPS.len();
PlaylistTrack {
playlist_id: row.get(offset),
track_id: row.get(offset + 1),
created_at: row.get(offset + 2),
updated_at: row.get(offset + 3),
track: ... | {
PROPS
.iter()
.map(|&p| format!("{}{}", prefix, p))
.collect::<Vec<String>>().join(",")
} | identifier_body |
playlist_track.rs | use std::collections::BTreeMap;
use uuid::Uuid;
use chrono::{NaiveDateTime, Utc};
use postgres;
use error::Error;
use super::{conn, Model};
use model::track::{Track, PROPS as TRACK_PROPS};
use model::playlist::Playlist;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct | {
pub playlist_id: Uuid,
pub track_id: Uuid,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub track: Track,
}
static PROPS: [&'static str; 4] = ["playlist_id",
"track_id",
"created_at",
... | PlaylistTrack | identifier_name |
playlist_track.rs | use std::collections::BTreeMap;
use uuid::Uuid;
use chrono::{NaiveDateTime, Utc};
use postgres;
use error::Error;
use super::{conn, Model};
use model::track::{Track, PROPS as TRACK_PROPS};
use model::playlist::Playlist;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PlaylistTrack {
pub playlist_id: U... |
};
Ok(items)
}
pub fn upsert(playlist: &Playlist, track: &Track) -> Result<PlaylistTrack, Error> {
let conn = conn()?;
let stmt = conn.prepare("INSERT INTO playlist_tracks
(track_id, playlist_id, created_at, updated_at)
VALUES ($1, $2,... | {
let pt = PlaylistTrack::row_to_item(row);
playlist_tracks.push(pt);
} | conditional_block |
playlist_track.rs | use std::collections::BTreeMap;
use uuid::Uuid;
use chrono::{NaiveDateTime, Utc};
use postgres;
use error::Error;
use super::{conn, Model};
use model::track::{Track, PROPS as TRACK_PROPS};
use model::playlist::Playlist;
| #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PlaylistTrack {
pub playlist_id: Uuid,
pub track_id: Uuid,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub track: Track,
}
static PROPS: [&'static str; 4] = ["playlist_id",
... | random_line_split | |
net-filters.ts | /**
* Neural net chatfilters.
* These are in a separate file so that they don't crash the other filters.
* (issues with globals, etc)
* by Mia.
* @author mia-pi-git
*/
import {QueryProcessManager} from '../../lib/process-manager';
import {FS, Utils} from '../../lib/';
import {Config} from '../config-loader';
imp... | ,
async test(target, room, user) {
checkAllowed(this);
const result = await PM.query({type: 'run', data: target});
return this.sendReply(`Result for '${target}': ${result}`);
},
enable: 'disable',
disable(target, room, user, connection, cmd) {
checkAllowed(this);
let logMessage;
if (cmd === 'd... | {
checkAllowed(this);
const backup = FS(PATH + '.backup');
if (!backup.existsSync()) return this.errorReply(`No backup exists.`);
await backup.copyFile(PATH);
const result = await PM.query({type: "load", data: PATH});
if (result && result !== 'success') {
return this.errorReply(`Rollback failed: $... | identifier_body |
net-filters.ts | /** | * (issues with globals, etc)
* by Mia.
* @author mia-pi-git
*/
import {QueryProcessManager} from '../../lib/process-manager';
import {FS, Utils} from '../../lib/';
import {Config} from '../config-loader';
import {Repl} from '../../lib/repl';
import {linkRegex} from '../chat-formatter';
const PATH = "config/chat-p... | * Neural net chatfilters.
* These are in a separate file so that they don't crash the other filters. | random_line_split |
net-filters.ts | /**
* Neural net chatfilters.
* These are in a separate file so that they don't crash the other filters.
* (issues with globals, etc)
* by Mia.
* @author mia-pi-git
*/
import {QueryProcessManager} from '../../lib/process-manager';
import {FS, Utils} from '../../lib/';
import {Config} from '../config-loader';
imp... | (content: string, result: string): TrainingLine[] {
return content.split('\n').map(line => {
const message = this.parseChatLine(line);
if (!message) return null;
return {output: `|${result}`, input: message};
}).filter(Boolean) as TrainingLine[];
}
static sanitizeLine(content: string) {
return content.... | sanitizeChatLines | identifier_name |
dosta_abcdjm_mmp_cds_recovered_driver.py | #!/usr/bin/env python
##
# OOIPLACEHOLDER
#
# Copyright 2014 Raytheon Co.
##
from mi.core.log import get_logger
from mi.core.versioning import version
from mi.dataset.dataset_driver import DataSetDriver
from mi.dataset.dataset_parser import DataSetDriverConfigKeys
from mi.dataset.parser.mmp_cds_base import MmpCdsParse... |
with open(source_file_path, 'rb') as stream_handle:
parser = MmpCdsParser(parser_config, stream_handle, exception_callback)
driver = DataSetDriver(parser, particle_data_handler)
driver.processFileStream()
return particle_data_handler
| log.debug("ERROR: %r", exception)
particle_data_handler.setParticleDataCaptureFailure() | identifier_body |
dosta_abcdjm_mmp_cds_recovered_driver.py | #!/usr/bin/env python
##
# OOIPLACEHOLDER
#
# Copyright 2014 Raytheon Co.
##
from mi.core.log import get_logger
from mi.core.versioning import version
from mi.dataset.dataset_driver import DataSetDriver
from mi.dataset.dataset_parser import DataSetDriverConfigKeys
from mi.dataset.parser.mmp_cds_base import MmpCdsParse... | (exception):
log.debug("ERROR: %r", exception)
particle_data_handler.setParticleDataCaptureFailure()
with open(source_file_path, 'rb') as stream_handle:
parser = MmpCdsParser(parser_config, stream_handle, exception_callback)
driver = DataSetDriver(parser, particle_data_handler)
... | exception_callback | identifier_name |
dosta_abcdjm_mmp_cds_recovered_driver.py | #!/usr/bin/env python
##
# OOIPLACEHOLDER
#
# Copyright 2014 Raytheon Co.
##
from mi.core.log import get_logger
from mi.core.versioning import version
from mi.dataset.dataset_driver import DataSetDriver
from mi.dataset.dataset_parser import DataSetDriverConfigKeys
from mi.dataset.parser.mmp_cds_base import MmpCdsParse... | __author__ = 'Joe Padula'
@version("0.0.3")
def parse(unused, source_file_path, particle_data_handler):
parser_config = {
DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.dosta_abcdjm_mmp_cds',
DataSetDriverConfigKeys.PARTICLE_CLASS: 'DostaAbcdjmMmpCdsParserDataParticle'
}
def ... | log = get_logger()
| random_line_split |
code.js | /**
* All these assets are being added just after the JQUERY, the JQUERY UI, BOOTSTRAP and some others.
* So, we can be sure that the JQuery is already loaded for this page, except that we were using
* the Unframed View.
*/
$( document ).ready(function(e){
/**
* Lets start the Datatable plugin (included i... | $( ".specialquote_elements_bottom" ).css("font-size","10px");
$( ".specialquote_elements_bottom" ).html( "Esta cita fue añadida el " + data.created + " y actualizada por última vez el " + data.updated );
});
e.preventDefault();
});
}); |
$.getJSON( url ).done(function( data ) { | random_line_split |
CharacterSelectionMenu.d.ts | /*!
* Copyright Unlok, Vaughn Royko 2011-2019
* http://www.unlok.ca
*
* Credits & Thanks:
* http://www.unlok.ca/credits-thanks/
*
* Wayward is a copyrighted and licensed work. Modification and/or distribution of any source files is prohibited. If you wish to modify the game in any way, please refer to the moddin... | extends Menu {
gameOptions: Partial<IPlayOptions>;
private sortRow;
private headingNoCharacters;
private characterRows;
private characterCreationMenu;
constructor(uiApi: UiApi);
create(): void;
refresh(): void;
private onShow;
private sortCharacters;
private getCharacterCrea... | CharacterSelectionMenu | identifier_name |
CharacterSelectionMenu.d.ts | /*!
* Copyright Unlok, Vaughn Royko 2011-2019
* http://www.unlok.ca
*
* Credits & Thanks:
* http://www.unlok.ca/credits-thanks/ | *
* Wayward is a copyrighted and licensed work. Modification and/or distribution of any source files is prohibited. If you wish to modify the game in any way, please refer to the modding guide:
* https://waywardgame.github.io/
*/
import { IPlayOptions } from "game/IGame";
import { UiApi } from "newui/INewUi";
impor... | random_line_split | |
analyticsLogger.ts | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... |
logProjectionChanged(projection: ProjectionType) {
if (this.eventLogging) {
ga('send', {
hitType: 'event',
eventCategory: 'Projection',
eventAction: 'click',
eventLabel: projection,
});
}
}
logWebGLDisabled() {
if (this.eventLogging) {
ga('send', {
... | {
if (this.pageViewLogging) {
// Always send a page view.
ga('send', {hitType: 'pageview', page: `/v/${pageTitle}`});
}
} | identifier_body |
analyticsLogger.ts | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... |
}
logWebGLDisabled() {
if (this.eventLogging) {
ga('send', {
hitType: 'event',
eventCategory: 'Error',
eventAction: 'PageLoad',
eventLabel: 'WebGL_disabled',
});
}
}
}
| {
ga('send', {
hitType: 'event',
eventCategory: 'Projection',
eventAction: 'click',
eventLabel: projection,
});
} | conditional_block |
analyticsLogger.ts | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | {
private eventLogging: boolean;
private pageViewLogging: boolean;
/**
* Constructs an event logger using Google Analytics. It assumes there is a
* Google Analytics script added to the page elsewhere. If there is no such
* script, the logger acts as a no-op.
*
* @param pageViewLogging Whether to l... | AnalyticsLogger | identifier_name |
analyticsLogger.ts | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | if (this.eventLogging) {
ga('send', {
hitType: 'event',
eventCategory: 'Error',
eventAction: 'PageLoad',
eventLabel: 'WebGL_disabled',
});
}
}
} | random_line_split | |
n_animal.ts | // common animal names
// http://dictionary.reference.com/writing/styleguide/animal.html
export const n_animal = [
"aardvark",
"albatross",
"alligator",
"alpaca",
"ant",
"antelope",
"ape",
"ass",
"auk",
"baboon",
"badger",
"barracuda",
"bass",
"bat",
"bear",
... | "rabbit",
"racoon",
"raptor",
"rat",
"raven",
"reindeer",
"rhinoceros",
"rook",
"salmon",
"sardine",
"scorpion",
"sea horse",
"seal",
"shark",
"sheep",
"skunk",
"snail",
"snake",
"snipe",
"sparrow",
"spider",
"squirrel",
"starli... | random_line_split | |
crateresolve8.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
assert_eq!(crateresolve8::f(), 20);
} | identifier_body | |
crateresolve8.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert_eq!(crateresolve8::f(), 20);
}
| main | identifier_name |
crateresolve8.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
// aux-build:crateresolve8-1.rs
#[pkgid="crateresolve8#0.1"];
extern mod crateresolve8(vers = "0.1", package_id="crateresolve8#0.1");
//extern mod crateresolve8(vers = "0.1");
pub fn main() {
asser... | random_line_split | |
mod_power_of_2_square.rs | use malachite_base::num::arithmetic::traits::{Square, WrappingSquare};
use malachite_base::num::conversion::traits::SplitInHalf;
use malachite_nz::natural::arithmetic::add_mul::limbs_slice_add_mul_limb_same_length_in_place_left;
use malachite_nz::natural::arithmetic::mod_power_of_2_square::limbs_square_diagonal_shl_add... | {
let n = xs.len();
let out = &mut out[..n];
assert_ne!(n, 0);
let xs_0 = xs[0];
match n {
1 => out[0] = xs_0.wrapping_square(),
2 => {
let (p_hi, p_lo) = DoubleLimb::from(xs_0).square().split_in_half();
out[0] = p_lo;
out[1] = (xs_0.wrapping_mul(x... | identifier_body | |
mod_power_of_2_square.rs | use malachite_base::num::arithmetic::traits::{Square, WrappingSquare};
use malachite_base::num::conversion::traits::SplitInHalf;
use malachite_nz::natural::arithmetic::add_mul::limbs_slice_add_mul_limb_same_length_in_place_left;
use malachite_nz::natural::arithmetic::mod_power_of_2_square::limbs_square_diagonal_shl_add... | (out: &mut [Limb], xs: &[Limb]) {
let n = xs.len();
let out = &mut out[..n];
assert_ne!(n, 0);
let xs_0 = xs[0];
match n {
1 => out[0] = xs_0.wrapping_square(),
2 => {
let (p_hi, p_lo) = DoubleLimb::from(xs_0).square().split_in_half();
out[0] = p_lo;
... | limbs_square_low_basecase_unrestricted | identifier_name |
mod_power_of_2_square.rs | use malachite_base::num::arithmetic::traits::{Square, WrappingSquare};
use malachite_base::num::conversion::traits::SplitInHalf;
use malachite_nz::natural::arithmetic::add_mul::limbs_slice_add_mul_limb_same_length_in_place_left;
use malachite_nz::natural::arithmetic::mod_power_of_2_square::limbs_square_diagonal_shl_add... | use malachite_nz::platform::{DoubleLimb, Limb};
pub fn limbs_square_low_basecase_unrestricted(out: &mut [Limb], xs: &[Limb]) {
let n = xs.len();
let out = &mut out[..n];
assert_ne!(n, 0);
let xs_0 = xs[0];
match n {
1 => out[0] = xs_0.wrapping_square(),
2 => {
let (p_hi,... | use malachite_nz::natural::arithmetic::mul::limb::limbs_mul_limb_to_out; | random_line_split |
current_page_table.rs | //! Handles interactions with the current page table.
use super::inactive_page_table::InactivePageTable;
use super::page_table::{Level1, Level4, PageTable};
use super::page_table_entry::*;
use super::page_table_manager::PageTableManager;
use super::{Page, PageFrame};
use core::cell::UnsafeCell;
use core::ops::{Deref, ... | ///
/// Note that this is only valid if the level 4 table is mapped recursively on
/// the last entry.
const L4_TABLE: *mut PageTable<Level4> = 0xfffffffffffff000 as *mut PageTable<Level4>;
/// The base address for all temporary addresses.
const TEMPORARY_ADDRESS_BASE: VirtualAddress = VirtualAddress::from_const(0xfff... | random_line_split | |
current_page_table.rs | //! Handles interactions with the current page table.
use super::inactive_page_table::InactivePageTable;
use super::page_table::{Level1, Level4, PageTable};
use super::page_table_entry::*;
use super::page_table_manager::PageTableManager;
use super::{Page, PageFrame};
use core::cell::UnsafeCell;
use core::ops::{Deref, ... |
/// Switches to the new page table returning the current one.
///
/// The old page table will not be mapped into the new one. This should be
/// done manually.
pub unsafe fn switch(&mut self, new_table: InactivePageTable) -> InactivePageTable {
let old_frame =
PageFrame::from_a... | {
self.with_temporary_page(&PageFrame::from_address(physical_address), |page| {
let virtual_address =
page.get_address().as_usize() | (physical_address.offset_in_page());
unsafe { ptr::read(virtual_address as *mut T) }
})
} | identifier_body |
current_page_table.rs | //! Handles interactions with the current page table.
use super::inactive_page_table::InactivePageTable;
use super::page_table::{Level1, Level4, PageTable};
use super::page_table_entry::*;
use super::page_table_manager::PageTableManager;
use super::{Page, PageFrame};
use core::cell::UnsafeCell;
use core::ops::{Deref, ... |
// Perform the action.
let result: T = action(&mut Page::from_address(virtual_address));
// Unlock this entry.
entry.unlock(&preemption_state);
result
}
/// Writes the given value to the given physical address.
pub fn write_at_physical<T: Sized + Copy>(
&... | {
tlb::flush(::x86_64::VirtualAddress(virtual_address.as_usize()));
entry.set_address(frame.get_address());
entry.set_flags(PRESENT | WRITABLE | DISABLE_CACHE | NO_EXECUTE);
} | conditional_block |
current_page_table.rs | //! Handles interactions with the current page table.
use super::inactive_page_table::InactivePageTable;
use super::page_table::{Level1, Level4, PageTable};
use super::page_table_entry::*;
use super::page_table_manager::PageTableManager;
use super::{Page, PageFrame};
use core::cell::UnsafeCell;
use core::ops::{Deref, ... | (&mut self, new_table: InactivePageTable) -> InactivePageTable {
let old_frame =
PageFrame::from_address(PhysicalAddress::from_usize(control_regs::cr3().0 as usize));
let old_table = InactivePageTable::from_frame(old_frame.copy(), &new_table);
let new_frame = new_table.get_frame();
... | switch | identifier_name |
Sink.js | Sink = function(baseX, baseY) {
var sender = this;
var _baseX = baseX;
var _baseY = baseY;
var _group = new Kinetic.Group();
var sinkIsFull = false;
var _empty = new Kinetic.Image({
x: baseX,
y: baseY,
image: resourceManager.getImage("sink-empty"),
width: 191,
height: 98
});
_group.add(_empty);
... |
redraw();
});
_tapClickArea.on('mouseover', function() {
if(!sinkIsFull) {
document.body.style.cursor = "pointer";
}
});
_tapClickArea.on('mouseout', function() {
document.body.style.cursor = "default";
});
var _plugClickArea = new Kinetic.Rect({
x: baseX + 42,
y: baseY + 74.... | {
audioManager.Play("fillSink");
showNotification("Filled the sink");
sinkIsFull = true;
document.body.style.cursor = "default";
_full.show();
_empty.hide();
} | conditional_block |
Sink.js | Sink = function(baseX, baseY) {
var sender = this;
var _baseX = baseX;
var _baseY = baseY;
var _group = new Kinetic.Group();
var sinkIsFull = false;
var _empty = new Kinetic.Image({
x: baseX,
y: baseY,
image: resourceManager.getImage("sink-empty"),
width: 191,
height: 98
});
_group.add(_empty);
... | xPos = (xPos + message.getWidth()) > 1023 ? (xPos - ((xPos + message.getWidth()) - 1023)) - 10 : xPos;
message.setX(xPos);
message.setY((_empty.getY()) - 20 - message.getHeight());
notificationBackground.setX(message.getX() - 10);
notificationBackground.setY(message.getY() - 8);
_empty.getLayer().add(... | var xPos = (_empty.getX() + (_empty.getWidth() / 2)) - (message.getWidth() / 2);
xPos = xPos < 0 ? 10 : xPos; | random_line_split |
lib.rs | // Copyright 2018 Stichting Organism
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
//given a series of bytes match emojis
pub fn from_bytes(&self, tosum: &[u8]) -> Option<String> {
//check that it is 32bytes
if tosum.len() < 32 { return None }
let mut result = String::new();
for byte in tosum {
result.push_str(&(self.emojiwords[*byte as ... | {
let json_file_path = Path::new(file_path);
let json_file = File::open(json_file_path).expect("file not found");
let deserialized: Emojisum =
serde_json::from_reader(json_file).expect("error while reading json");
return deserialized;
} | identifier_body |
lib.rs | // Copyright 2018 Stichting Organism
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | (file_path: &str) -> Emojisum {
let json_file_path = Path::new(file_path);
let json_file = File::open(json_file_path).expect("file not found");
let deserialized: Emojisum =
serde_json::from_reader(json_file).expect("error while reading json");
return deserialized;
}
//g... | init | identifier_name |
lib.rs | // Copyright 2018 Stichting Organism
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// | // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.... | random_line_split | |
lib.rs | // Copyright 2018 Stichting Organism
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
let mut result = String::new();
for byte in tosum {
result.push_str(&(self.emojiwords[*byte as usize])[0])
}
return Some(result);
}
//given a vector of bytes, we hash and return checksum
pub fn hash_to_emojisum(&self, data: Vec<u8>) -> Option<String>... | { return None } | conditional_block |
balance.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
function getRangeToBalanceOut(document: vscode.TextDocument, rootNode: HtmlFlatNode, selection: vscode.Selection): vscode.Selection {
const offset = document.offsetAt(selection.start);
const nodeToBalance = getHtmlFlatNode(document.getText(), rootNode, offset, false);
if (!nodeToBalance) {
return selection;
}
... | {
if (!validate(false) || !vscode.window.activeTextEditor) {
return;
}
const editor = vscode.window.activeTextEditor;
const document = editor.document;
const rootNode = <HtmlFlatNode>getRootNode(document, true);
if (!rootNode) {
return;
}
const rangeFn = out ? getRangeToBalanceOut : getRangeToBalanceIn;
l... | identifier_body |
balance.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | return selection;
}
if (!nodeToBalance.open || !nodeToBalance.close) {
return offsetRangeToSelection(document, nodeToBalance.start, nodeToBalance.end);
}
const innerSelection = offsetRangeToSelection(document, nodeToBalance.open.end, nodeToBalance.close.start);
const outerSelection = offsetRangeToSelection(do... | const nodeToBalance = getHtmlFlatNode(document.getText(), rootNode, offset, false);
if (!nodeToBalance) { | random_line_split |
balance.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | () {
balance(false);
}
function balance(out: boolean) {
if (!validate(false) || !vscode.window.activeTextEditor) {
return;
}
const editor = vscode.window.activeTextEditor;
const document = editor.document;
const rootNode = <HtmlFlatNode>getRootNode(document, true);
if (!rootNode) {
return;
}
const rangeF... | balanceIn | identifier_name |
balance.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
for (let i = 0; i < a.length; i++) {
if (!a[i].isEqual(b[i])) {
return false;
}
}
return true;
}
| {
return false;
} | conditional_block |
gulpfile.js | 'use strict';
var gulp = require('gulp');
var gutil = require('gulp-util');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
// Style Dependencies
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var minify = require('gulp-minify-css');
// Js Dependencies
va... | var scss = gulp.src(sassFiles)
.pipe(sass({
includePaths: require('node-normalize-scss').includePaths
}).on('error', sass.logError))
.pipe(autoprefixer())
.pipe(concat('main.css'))
.pipe(minify())
.pipe(gulp.dest('./css'));
});
gulp.task('js', function() {
return gulp.src([jquery, ... | random_line_split | |
S15.1.3.2_A3_T1.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* Let reservedURIComponentSet be the empty string
*
* @path ch15/15.1/15.1.3/15.1.3.2/S15.1.3.2_A3_T1.js
* @description uriReserved and "#" not in reservedURIComponentSet. HexDigi... |
//CHECK#11
if (decodeURIComponent("%23") !== "#") {
$ERROR('#11: decodeURIComponent("%23") equal "#", not "%23"');
}
| {
$ERROR('#10: decodeURIComponent("%2C") equal ",", not "%2C"');
} | conditional_block |
S15.1.3.2_A3_T1.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* Let reservedURIComponentSet be the empty string
*
* @path ch15/15.1/15.1.3/15.1.3.2/S15.1.3.2_A3_T1.js
* @description uriReserved and "#" not in reservedURIComponentSet. HexDigi... |
//CHECK#2
if (decodeURIComponent("%2F") !== "/") {
$ERROR('#2: decodeURIComponent("%2F") equal "/", not "%2F"');
}
//CHECK#3
if (decodeURIComponent("%3F") !== "?") {
$ERROR('#3: decodeURIComponent("%3F") equal "?", not "%3F"');
}
//CHECK#4
if (decodeURIComponent("%3A") !== ":") {
$ERROR('#4: decodeURIComponent... | if (decodeURIComponent("%3B") !== ";") {
$ERROR('#1: decodeURIComponent("%3B") equal ";", not "%3B"');
} | random_line_split |
qengine.js | // This script, and the YUI libraries that it needs, are inluded by
// the require_js calls in get_html_head_contributions in lib/questionlib.php.
question_flag_changer = {
flag_state_listeners: new Object(),
init_flag: function(checkboxid, postdata) {
// Create a hidden input - you can't just repurpo... |
question_flag_changer.flag_state_listeners[key].push(listener);
},
questionid_from_inputid: function(inputid) {
return inputid.replace(/resp(\d+)__flagged/, '$1');
},
fire_state_changed: function(input) {
var questionid = question_flag_changer.questionid_from_inputid(input.id)... | {
question_flag_changer.flag_state_listeners[key] = [];
} | conditional_block |
qengine.js | // This script, and the YUI libraries that it needs, are inluded by
// the require_js calls in get_html_head_contributions in lib/questionlib.php.
question_flag_changer = {
flag_state_listeners: new Object(),
init_flag: function(checkboxid, postdata) {
// Create a hidden input - you can't just repurpo... | // Add the event handler.
YAHOO.util.Event.addListener(image, 'click', this.flag_state_change);
},
init_flag_save_form: function(submitbuttonid) {
// With JS on, we just want to remove all visible traces of the form.
var button = document.getElementById(submitbuttonid);
... | random_line_split | |
template.ts | import {
ReducerFunction,
ITemplateReducerState,
TemplateReducerFunction
} from "../api/common";
import { ActionType } from '../constants/actions';
import { IElementState, ViewerAction } from '../actions/defs';
export const TEMPLATE_INITIAL_STATE: ITemplateReducerState = {
initialInfoPaneWidth: 250,
... | else {
//If no template present (they would've overridden this reducer), at least service the actions we know affect this
//particular state branch
switch (action.type) {
case ActionType.FUSION_SET_ELEMENT_STATE:
{
if (isElementState(action.payloa... | {
return _ovReducer(origState, state, action);
} | conditional_block |
template.ts | import {
ReducerFunction,
ITemplateReducerState,
TemplateReducerFunction
} from "../api/common";
import { ActionType } from '../constants/actions';
import { IElementState, ViewerAction } from '../actions/defs';
export const TEMPLATE_INITIAL_STATE: ITemplateReducerState = {
initialInfoPaneWidth: 250,
... | {
let state = origState;
//Whether this reducer has been overridden or not, service the MAP_SET_SELECTION action and
//if we get modified state, pass that down to the rest of the reducer
if (action.type == ActionType.MAP_SET_SELECTION) {
const { selection } = action.payload;
if (selectio... | identifier_body | |
template.ts | import {
ReducerFunction,
ITemplateReducerState,
TemplateReducerFunction
} from "../api/common";
import { ActionType } from '../constants/actions';
import { IElementState, ViewerAction } from '../actions/defs';
export const TEMPLATE_INITIAL_STATE: ITemplateReducerState = {
initialInfoPaneWidth: 250,
... | export function templateReducer(origState = TEMPLATE_INITIAL_STATE, action: ViewerAction) {
let state = origState;
//Whether this reducer has been overridden or not, service the MAP_SET_SELECTION action and
//if we get modified state, pass that down to the rest of the reducer
if (action.type == ActionTy... | random_line_split | |
template.ts | import {
ReducerFunction,
ITemplateReducerState,
TemplateReducerFunction
} from "../api/common";
import { ActionType } from '../constants/actions';
import { IElementState, ViewerAction } from '../actions/defs';
export const TEMPLATE_INITIAL_STATE: ITemplateReducerState = {
initialInfoPaneWidth: 250,
... | (origState = TEMPLATE_INITIAL_STATE, action: ViewerAction) {
let state = origState;
//Whether this reducer has been overridden or not, service the MAP_SET_SELECTION action and
//if we get modified state, pass that down to the rest of the reducer
if (action.type == ActionType.MAP_SET_SELECTION) {
... | templateReducer | identifier_name |
response.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The [Response](https://fetch.spec.whatwg.org/#responses) object
//! resulting from a [fetch operation](https:/... |
}
/// Convert to a filtered response, of type `filter_type`.
/// Do not use with type Error or Default
pub fn to_filtered(self, filter_type: ResponseType) -> Response {
match filter_type {
ResponseType::Default | ResponseType::Error(..) => panic!(),
_ => (),
}
... | {
self
} | conditional_block |
response.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The [Response](https://fetch.spec.whatwg.org/#responses) object
//! resulting from a [fetch operation](https:/... | (e: NetworkError) -> Response {
Response {
response_type: ResponseType::Error(e),
termination_reason: None,
url: None,
url_list: RefCell::new(vec![]),
status: None,
raw_status: None,
headers: Headers::new(),
body: Ar... | network_error | identifier_name |
response.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The [Response](https://fetch.spec.whatwg.org/#responses) object
//! resulting from a [fetch operation](https:/... |
ResponseType::Basic => {
let headers = old_headers.iter().filter(|header| {
match &*header.name().to_ascii_lowercase() {
"set-cookie" | "set-cookie2" => false,
_ => true
}
}).collect();
... |
match response.response_type {
ResponseType::Default | ResponseType::Error(..) => unreachable!(), | random_line_split |
response.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The [Response](https://fetch.spec.whatwg.org/#responses) object
//! resulting from a [fetch operation](https:/... | ;
if let Some(error) = self.get_network_error() {
return Err(error.clone());
}
let metadata = self.url.as_ref().map(|url| init_metadata(self, url));
if let Some(ref response) = self.internal_response {
match response.url {
Some(ref url) => {
... | {
let mut metadata = Metadata::default(url.clone());
metadata.set_content_type(match response.headers.get() {
Some(&ContentType(ref mime)) => Some(mime),
None => None
});
metadata.headers = Some(Serde(response.headers.clone()));
... | identifier_body |
sessions.rs | use iron::headers::ContentType;
use iron::prelude::*;
use iron::status;
use serde_json;
use authentication::{authenticate_user, delete_session};
use super::common::*;
pub fn | (request: &mut Request) -> IronResult<Response> {
use models::NewSession;
let email = get_param(request, "email")?;
let password = get_param(request, "password")?;
let (user, session) = authenticate_user(&email, &password)?;
let new_session = NewSession {
token: session.token,
use... | login | identifier_name |
sessions.rs | use iron::headers::ContentType;
use iron::prelude::*;
use iron::status;
use serde_json;
use authentication::{authenticate_user, delete_session};
use super::common::*;
pub fn login(request: &mut Request) -> IronResult<Response> |
pub fn logout(request: &mut Request) -> IronResult<Response> {
use models::Session;
let current_session = request.extensions.get::<Session>().unwrap();
delete_session(current_session.token.as_str())?;
Ok(Response::with((ContentType::json().0, status::NoContent)))
}
| {
use models::NewSession;
let email = get_param(request, "email")?;
let password = get_param(request, "password")?;
let (user, session) = authenticate_user(&email, &password)?;
let new_session = NewSession {
token: session.token,
user_id: user.id,
expired_at: session.expir... | identifier_body |
sessions.rs | use iron::headers::ContentType;
use iron::prelude::*;
use iron::status;
use serde_json;
use authentication::{authenticate_user, delete_session};
use super::common::*;
pub fn login(request: &mut Request) -> IronResult<Response> {
use models::NewSession;
let email = get_param(request, "email")?;
let passwo... | user_id: user.id,
expired_at: session.expired_at,
};
let payload = serde_json::to_string(&new_session).unwrap();
Ok(Response::with((ContentType::json().0, status::Created, payload)))
}
pub fn logout(request: &mut Request) -> IronResult<Response> {
use models::Session;
let current... | token: session.token, | random_line_split |
service.rs | use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use crate::futures;
use crate::jsonrpc::{middleware, MetaIoHandler, Metadata, Middleware};
pub struct Service<M: Metadata = (), S: Middleware<M> = middleware::Noop> {
handler: Arc<MetaIoHandler<M... | (&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
// Produce a future for computing a response from a request.
fn call(&mut self, req: String) -> Self::Future {
use futures::FutureExt;
trace!(target: "tcp", "Accepted request from peer {}: {}", &self.peer_addr, req);
B... | poll_ready | identifier_name |
service.rs | use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use crate::futures;
use crate::jsonrpc::{middleware, MetaIoHandler, Metadata, Middleware};
pub struct Service<M: Metadata = (), S: Middleware<M> = middleware::Noop> {
handler: Arc<MetaIoHandler<M... | use futures::FutureExt;
trace!(target: "tcp", "Accepted request from peer {}: {}", &self.peer_addr, req);
Box::pin(self.handler.handle_request(&req, self.meta.clone()).map(Ok))
}
} | Poll::Ready(Ok(()))
}
// Produce a future for computing a response from a request.
fn call(&mut self, req: String) -> Self::Future { | random_line_split |
service.rs | use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use crate::futures;
use crate::jsonrpc::{middleware, MetaIoHandler, Metadata, Middleware};
pub struct Service<M: Metadata = (), S: Middleware<M> = middleware::Noop> {
handler: Arc<MetaIoHandler<M... |
}
impl<M: Metadata, S: Middleware<M>> tower_service::Service<String> for Service<M, S>
where
S::Future: Unpin,
S::CallFuture: Unpin,
{
// These types must match the corresponding protocol types:
type Response = Option<String>;
// For non-streaming protocols, service errors are always io::Error
type Error = ();
... | {
Service {
handler,
peer_addr,
meta,
}
} | identifier_body |
test_wsse.py | # -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distri... | sername_token = None
def setup(self):
self.username_token = UsernameToken(
username=b"foouser",
password=b"barpasswd",
)
def test_setnonce_null(self):
self.setup()
self.username_token.setnonce()
assert self.username_token.nonce != None... | identifier_body | |
test_wsse.py | # -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distri... | self):
self.username_token = UsernameToken(
username=b"foouser",
password=b"barpasswd",
)
def test_setnonce_null(self):
self.setup()
self.username_token.setnonce()
assert self.username_token.nonce != None
def test_setnonce_text(self):
... | etup( | identifier_name |
test_wsse.py | # -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distri... |
from suds.wsse import UsernameToken
class TestUsernameToken:
username_token = None
def setup(self):
self.username_token = UsernameToken(
username=b"foouser",
password=b"barpasswd",
)
def test_setnonce_null(self):
self.setup()
s... | mport __init__
__init__.runUsingPyTest(globals())
| conditional_block |
test_wsse.py | # -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distri... | # You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jurko Gospodnetić ( jurko.gospodnetic@pke.hr )
"""
Implemented using the 'pytest' tes... | # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
| random_line_split |
Dictionary.ts | // Adarts\Dictionary #e6a9
// check private => array (6)
// | 0 => 0
// | 3 => 1
// | 4 => 1
// | 5 => 2
// | 6 => 3
// | 8 => 4
// base private => array (6)
// | 0 => 1
// | 3 => 2
// | 5 => 3
// | 6 => -3
// | 4 => 4
// | 8 => -4
// index private => array (3)
/... | readonly name: string = 'dictionary';
/**
*
*
* @private
* @type {(Spliter | null)}
* @memberof Dictionary
*/
private readonly spliter: Spliter | null;
/**
*
*
* @private
* @type {(Tries | null)}
* @memberof Dictionary
*/
private readonly tr... | public | identifier_name |
Dictionary.ts | // Adarts\Dictionary #e6a9
// check private => array (6)
// | 0 => 0
// | 3 => 1
// | 4 => 1
// | 5 => 2
// | 6 => 3
// | 8 => 4
// base private => array (6)
// | 0 => 1
// | 3 => 2
// | 5 => 3
// | 6 => -3
// | 4 => 4
// | 8 => -4
// index private => array (3)
/... |
public division(x: number, y: number): number {
if (y === 0) {
throw new Error('除数不可以为 0');
}
return x / y;
}
} | this.spliter = null;
this.tries = null;
} | random_line_split |
Dictionary.ts | // Adarts\Dictionary #e6a9
// check private => array (6)
// | 0 => 0
// | 3 => 1
// | 4 => 1
// | 5 => 2
// | 6 => 3
// | 8 => 4
// base private => array (6)
// | 0 => 1
// | 3 => 2
// | 5 => 3
// | 6 => -3
// | 4 => 4
// | 8 => -4
// index private => array (3)
/... | r('除数不可以为 0');
}
return x / y;
}
}
| conditional_block | |
1527203351639-InitItems.ts | import { MigrationInterface, QueryRunner } from "typeorm";
/**
* Initialized all Item related entities
*/
export class InitItems1527203351639 implements MigrationInterface {
public async | (queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(
`CREATE TABLE "item" (` +
`"uuid" uuid NOT NULL DEFAULT uuid_generate_v4(), ` +
`"content" character varying, ` +
`"contentType" citext, ` +
`"encItemKey" character varying, ` +
`"deleted" boolean NOT N... | up | identifier_name |
1527203351639-InitItems.ts | import { MigrationInterface, QueryRunner } from "typeorm";
/**
* Initialized all Item related entities
*/
export class InitItems1527203351639 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> |
public async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(
`ALTER TABLE "item_closure" DROP ` +
`CONSTRAINT "FK_edb78b7860fe58f92332fd1bbc7"`
);
await queryRunner.query(
`ALTER TABLE "item_closure" DROP ` +
`CONSTRAINT "FK_3e6a5639e2695ce8b5564f3f5fe... | {
await queryRunner.query(
`CREATE TABLE "item" (` +
`"uuid" uuid NOT NULL DEFAULT uuid_generate_v4(), ` +
`"content" character varying, ` +
`"contentType" citext, ` +
`"encItemKey" character varying, ` +
`"deleted" boolean NOT NULL DEFAULT false, ` +
`"createdA... | identifier_body |
1527203351639-InitItems.ts | import { MigrationInterface, QueryRunner } from "typeorm";
/**
* Initialized all Item related entities
*/
export class InitItems1527203351639 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(
`CREATE TABLE "item" (` +
`"uuid" uuid N... | await queryRunner.query(
`CREATE INDEX "IDX_ff12c3d8bc453de869e7b8b317" ON ` +
`"item"("createdAt", "userUuid", "uuid") `
);
await queryRunner.query(
`CREATE TABLE "item_closure" (` +
`"ancestor" uuid NOT NULL, ` +
`"descendant" uuid NOT NULL, ` +
`"depth" integer... | random_line_split | |
history.selectors.ts | import { ClueState } from '../../core/store/state';
import { PlayerSelectors } from '../../player/store/player.selectors';
import { Round } from '../round/round';
import { Turn } from '../turn-form/turn';
export const HistorySelectors = {
currentRound: currentRoundSelector,
nextRound: nextRoundSelector,
loaded: ... |
return {
round: nextRound,
turn: nextTurn,
playerId: PlayerSelectors.all(state).find(p => p.order === nextTurn).id,
};
}
export function historyLoadedSelector(state: ClueState) {
return state.historyLoaded;
}
export function roundsSelector(state: ClueState): Round[] {
const rounds = turnsSelecto... | {
++nextRound;
nextTurn = 1;
} | conditional_block |
history.selectors.ts | import { ClueState } from '../../core/store/state';
import { PlayerSelectors } from '../../player/store/player.selectors';
import { Round } from '../round/round';
import { Turn } from '../turn-form/turn';
export const HistorySelectors = {
currentRound: currentRoundSelector,
nextRound: nextRoundSelector,
loaded: ... | (state: ClueState): Round[] {
const rounds = turnsSelector(state).groupBy(t => t.round);
return Object.keys(rounds).map(id => ({ number: +id, turns: rounds[id] }));
}
export function turnsSelector(state: ClueState): Turn[] {
return Object.values(state.history).map(
t =>
({
...t,
player... | roundsSelector | identifier_name |
history.selectors.ts | import { ClueState } from '../../core/store/state';
import { PlayerSelectors } from '../../player/store/player.selectors';
import { Round } from '../round/round';
import { Turn } from '../turn-form/turn';
export const HistorySelectors = {
currentRound: currentRoundSelector,
nextRound: nextRoundSelector,
loaded: ... |
export function historyLoadedSelector(state: ClueState) {
return state.historyLoaded;
}
export function roundsSelector(state: ClueState): Round[] {
const rounds = turnsSelector(state).groupBy(t => t.round);
return Object.keys(rounds).map(id => ({ number: +id, turns: rounds[id] }));
}
export function turnsSel... | {
const currentRound = currentRoundSelector(state);
const playerCount = PlayerSelectors.count(state) || 6;
const currentTurn = turnsSelector(state)
.sortBy(t => t.order)
.reverse()
.find(t => t.round === currentRound) || { order: 0 };
let nextRound = currentRound;
let nextTurn = currentTurn.order... | identifier_body |
history.selectors.ts | import { ClueState } from '../../core/store/state';
import { PlayerSelectors } from '../../player/store/player.selectors';
import { Round } from '../round/round';
import { Turn } from '../turn-form/turn';
export const HistorySelectors = {
currentRound: currentRoundSelector,
nextRound: nextRoundSelector,
loaded: ... | round: nextRound,
turn: nextTurn,
playerId: PlayerSelectors.all(state).find(p => p.order === nextTurn).id,
};
}
export function historyLoadedSelector(state: ClueState) {
return state.historyLoaded;
}
export function roundsSelector(state: ClueState): Round[] {
const rounds = turnsSelector(state).grou... | }
return { | random_line_split |
TableCtrl.js | restularIndex.controller('TableCtrl', function($scope, $filter, $compile, $interpolate){
$scope.interpolate = function(value) {
return $interpolate(value)($scope)
}
// route template | $scope.resource = "articles"
$scope.nestedResource = ""
// updates variables and template on resource or nestedResource update
$scope.$watchGroup(['resource', 'nestedResource'], function (newValues){
// newValues[0] == resource
// newValues[1] == nestedResource
// singular resource variables
d... | $scope.routes = singularRoutes
//resources | random_line_split |
TableCtrl.js | restularIndex.controller('TableCtrl', function($scope, $filter, $compile, $interpolate){
$scope.interpolate = function(value) {
return $interpolate(value)($scope)
}
// route template
$scope.routes = singularRoutes
//resources
$scope.resource = "articles"
$scope.nestedResource = ""
// updates var... |
});
}); | {
// show singularRoutes IF !nestedResource
$scope.routes = singularRoutes
} | conditional_block |
view-engine.ts | import core from 'core-js';
import * as LogManager from 'aurelia-logging';
import {Origin} from 'aurelia-metadata';
import {Loader,TemplateRegistryEntry} from 'aurelia-loader';
import {Container} from 'aurelia-dependency-injection';
import {ViewCompiler} from './view-compiler';
import {ResourceRegistry, ViewResources} ... |
}
| {
return this.loader.loadAllModules(moduleIds).then(imports => {
var i, ii, analysis, normalizedId, current, associatedModule,
container = this.container,
moduleAnalyzer = this.moduleAnalyzer,
allAnalysis = new Array(imports.length);
//analyze and register all resources fi... | identifier_body |
view-engine.ts | import core from 'core-js';
import * as LogManager from 'aurelia-logging';
import {Origin} from 'aurelia-metadata';
import {Loader,TemplateRegistryEntry} from 'aurelia-loader';
import {Container} from 'aurelia-dependency-injection';
import {ViewCompiler} from './view-compiler';
import {ResourceRegistry, ViewResources} ... | dependencies = viewRegistryEntry.dependencies,
importIds, names;
if(dependencies.length === 0 && !associatedModuleId){
return Promise.resolve(resources);
}
importIds = dependencies.map(x => x.src);
names = dependencies.map(x => x.name);
logger.debug(`importing resources for $... |
loadTemplateResources(viewRegistryEntry, associatedModuleId){
var resources = new ViewResources(this.appResources, viewRegistryEntry.id), | random_line_split |
view-engine.ts | import core from 'core-js';
import * as LogManager from 'aurelia-logging';
import {Origin} from 'aurelia-metadata';
import {Loader,TemplateRegistryEntry} from 'aurelia-loader';
import {Container} from 'aurelia-dependency-injection';
import {ViewCompiler} from './view-compiler';
import {ResourceRegistry, ViewResources} ... |
importIds = dependencies.map(x => x.src);
names = dependencies.map(x => x.name);
logger.debug(`importing resources for ${viewRegistryEntry.id}`, importIds);
return this.importViewResources(importIds, names, resources, associatedModuleId);
}
importViewModelResource(moduleImport, moduleMember){
... | {
return Promise.resolve(resources);
} | conditional_block |
view-engine.ts | import core from 'core-js';
import * as LogManager from 'aurelia-logging';
import {Origin} from 'aurelia-metadata';
import {Loader,TemplateRegistryEntry} from 'aurelia-loader';
import {Container} from 'aurelia-dependency-injection';
import {ViewCompiler} from './view-compiler';
import {ResourceRegistry, ViewResources} ... | (viewRegistryEntry, associatedModuleId){
var resources = new ViewResources(this.appResources, viewRegistryEntry.id),
dependencies = viewRegistryEntry.dependencies,
importIds, names;
if(dependencies.length === 0 && !associatedModuleId){
return Promise.resolve(resources);
}
importI... | loadTemplateResources | identifier_name |
launch_suite.js | ;(function($){
var page_container, current_select = null;
$(document).ready(function(){
page_container = $('#launch_suite_pages');
$('#funnel_select').change(function(){
if(parseInt($('#funnel_id').val()) > 0){
if($(this).val() != $('#funnel_id').val()){
... |
var funnel_id = $('#funnel_select').val();
if (!confirm('Are you sure you want to delete this funnel?')) {
return false;
}
$.post(
OptimizePress.ajaxurl,
{
action: OptimizePress.SN + '-la... | });
};
function init_funnel_switch(){
$('#funnel_delete').click(function(e) {
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.