file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
simpleLSTM.py | _weight(options['dim_proj']),
ortho_weight(options['dim_proj']),
ortho_weight(options['dim_proj']),
ortho_weight(options['dim_proj'])], axis=1)
params[_p(prefix, 'W')] = W
U = numpy.concatenate([ortho_weight(options['dim_proj']),
... | for k, p in tparams.iteritems()]
running_grads2 = [theano.shared(p.get_value() * numpy_floatX(0.),
name='%s_rgrad2' % k)
for k, p in tparams.iteritems()]
zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]
rg2up = [(rg2, 0.95 *... | sk: Theano variable
Sequence mask
y: Theano variable
Targets
cost: Theano variable
Objective fucntion to minimize
Notes
-----
For more information, see [ADADELTA]_.
.. [ADADELTA] Matthew D. Zeiler, *ADADELTA: An Adaptive Learning
Rate Method*, arXiv:1212.5701.
... | identifier_body |
general.rs | Says pong on \"§ping\"\n"]
async fn ping(ctx: &Context, msg: &Message) -> CommandResult {
msg.reply(&ctx, "Pong§§§").await?;
Ok(())
}
#[command]
#[description = "Just react to your hi\n"]
#[aliases(hello, Hello, Hi)]
async fn hi(ctx: &Context, msg: &Message) -> CommandResult {
let phrase = format!("HIIII... |
if let Some(description) = &guild.description {
e.field("Description",description,false);
};
e.field("Members",number_users,true)
// .field("MSG",number_msgs,true)
.field("Channels",number_channels,true)
.field("Role... | et guild = match ctx.cache.guild(&msg.guild_id.unwrap()).await {
Some(guild) => guild,
None => {
msg.reply(ctx, "Error" ).await;
return Ok(());
}
};
let number_users = guild.member_count;
// let number_msgs = channel.message_count;
let number_cha... | identifier_body |
general.rs | "Bot will reply with pretty embed containing title and description of bot"]
async fn about(ctx: & Context, msg: &Message) -> CommandResult {
// Obtain Bot's profile pic: cache -> current info -> bot user -> bot icon
// let cache_http = &ctx.http;
// let current_info = cache_http.get_current_application_inf... | ap());
}
else {
e.title(&person[0].name);
e.image(person[0].av | conditional_block | |
general.rs | Says pong on \"§ping\"\n"]
async fn ping(ctx: &Context, msg: &Message) -> CommandResult {
msg.reply(&ctx, "Pong§§§").await?;
Ok(())
}
#[command]
#[description = "Just react to your hi\n"]
#[aliases(hello, Hello, Hi)]
async fn hi(ctx: &Context, msg: &Message) -> CommandResult {
let phrase = format!("HIIII... | // }
// #[check]
// #[name = "Bot"]
// async fn bot_check(ctx: &Context, msg: &Message) -> CheckResult {
// if let Some(member) = msg.member(&ctx.cache) {
// let user = member.user.read();
// user.bot.into()
// } else {
// false.into()
// }
// }
#[command]
#[description = "Bot will... | random_line_split | |
general.rs | Says pong on \"§ping\"\n"]
async fn ping(ctx: &Context, msg: &Message) -> CommandResult {
msg.reply(&ctx, "Pong§§§").await?;
Ok(())
}
#[command]
#[description = "Just react to your hi\n"]
#[aliases(hello, Hello, Hi)]
async fn hi(ct | &Context, msg: &Message) -> CommandResult {
let phrase = format!("HIIII {}",&msg.author.name);
msg.reply(&ctx, phrase).await?;
// msg.reply(&ctx, msg.author_nick(&ctx).await.unwrap()).await?;
// msg.reply(&ctx, &msg.author.name).await?;
// msg.reply(&ctx, &msg.member.unwrap().nick.unwrap()).await?;... | x: | identifier_name |
xmlReportBuilder.go | Contents string `xml:",chardata"`
}
// JUnitSkipMessage contains the reason why a testcase was skipped.
type JUnitSkipMessage struct {
Message string `xml:"message,attr"`
}
// JUnitProperty represents a key/value pair used to define properties.
type JUnitProperty struct {
Name string `xml:"name,attr"`
Value str... | formatTime | identifier_name | |
xmlReportBuilder.go | // testcases.
type JUnitTestSuite struct {
XMLName xml.Name `xml:"testsuite"`
Id int `xml:"id,attr"`
Tests int `xml:"tests,attr"`
Failures int `xml:"failures,attr"`
Package string `xml:"package,attr"`
Time ... | {
errInfo := []StepFailure{}
for _, item := range items {
stepInfo := StepFailure{Message: "", Err: ""}
if item.GetItemType() == gauge_messages.ProtoItem_Step {
preHookFailure := item.GetStep().GetStepExecutionResult().GetPreHookFailure()
postHookFailure := item.GetStep().GetStepExecutionResult().GetPostHoo... | identifier_body | |
xmlReportBuilder.go | es struct {
XMLName xml.Name `xml:"testsuites"`
Suites []JUnitTestSuite `xml:"testsuite"`
}
// JUnitTestSuite is a single JUnit test suite which may contain many
// testcases.
type JUnitTestSuite struct {
XMLName xml.Name `xml:"testsuite"`
Id int `xml:"id,attr"`
... | ts := x.getTestSuite(result, hostName)
if hasParseErrors(result.Errors) {
ts.Failures++
ts.TestCases = append(ts.TestCases, getErrorTestCase(result))
} else {
s := result.GetProtoSpec()
ts.Failures += len(s.GetPreHookFailures()) + len(s.GetPostHookFailures())
for _, test := range result.GetProtoSpec().GetI... | hostName = hostname
} | random_line_split |
xmlReportBuilder.go | struct {
XMLName xml.Name `xml:"testsuites"`
Suites []JUnitTestSuite `xml:"testsuite"`
}
// JUnitTestSuite is a single JUnit test suite which may contain many
// testcases.
type JUnitTestSuite struct {
XMLName xml.Name `xml:"testsuite"`
Id int `xml:"id,attr"`
Te... |
failures = append(failures, fmt.Sprintf("[%s Error] %s", t, e.Message))
}
return JUnitTestCase{
Classname: getSpecName(result.GetProtoSpec()),
Name: getSpecName(result.GetProtoSpec()),
Time: formatTime(int(result.GetExecutionTime())),
Failure: &JUnitFailure{
Message: "Parse/Validation Errors"... | {
t = "Validation"
} | conditional_block |
index.js | // calculate the new cursor position:
x0 = x1 - ev.clientX;
y0 = y1 - ev.clientY;
x1 = ev.clientX;
y1 = ev.clientY;
// set the element's new position:
modalPosition = [(modal.offsetLeft - x0) + "px", (modal.offsetTop - y0) + "px"];
[modal.style.left, modal.style.... | let ev = document.createEvent("MouseEvents");
ev.initMouseEvent(eventType, true, true, window, | random_line_split | |
index.js | const col1Box = document.getElementById(`contrast-col1`);
const contrastDetails = document.getElementById(`contrast-details`);
function displayContrastInfo() {
dragBar.innerText = `Contrast Info`;
const col0 = palette[selectedColours[0]].style.backgroundColor;
const col1 = palette[selectedColours[1]].style... | y0 = y1 - ev.clientY;
x1 = ev.clientX;
y1 = ev.clientY;
// set the element's new position:
modalPosition = [(modal.offsetLeft - x0) + "px", (modal.offsetTop - y0) + "px"];
[modal.style.left, modal.style.top] = modalPosition;
}
function closeDragElement() {
... | {
let [x0, y0, x1, y1] = [0, 0, 0, 0];
dragBar.onmousedown = dragMouseDown;
function dragMouseDown(ev) {
ev = ev || window.event;
ev.preventDefault();
// get the mouse cursor position at startup:
x1 = ev.clientX;
y1 = ev.clientY;
document.onmouseup = closeDr... | identifier_body |
index.js | const col1Box = document.getElementById(`contrast-col1`);
const contrastDetails = document.getElementById(`contrast-details`);
function | () {
dragBar.innerText = `Contrast Info`;
const col0 = palette[selectedColours[0]].style.backgroundColor;
const col1 = palette[selectedColours[1]].style.backgroundColor;
col0Box.style.backgroundColor = col0;
col1Box.style.backgroundColor = col1;
col0Box.style.color = getLuminance(col0) > 0.3 ? B... | displayContrastInfo | identifier_name |
index.js | const col1Box = document.getElementById(`contrast-col1`);
const contrastDetails = document.getElementById(`contrast-details`);
function displayContrastInfo() {
dragBar.innerText = `Contrast Info`;
const col0 = palette[selectedColours[0]].style.backgroundColor;
const col1 = palette[selectedColours[1]].style... |
}
// We only want the two most recent, or one if user changed between RGB and HSL groups.
function setSwitches() {
for (let i = 0; i < 6; i++) {
let sliderIsActive = activeSliders.has(i);
onSwitches[i].checked = sliderIsActive;
offSwitches[i].checked = !sliderIsActive;
switchboxes[... | {
for (let i = 0; i < W; i++) {
let cell = document.createElement("div");
cell.x = i;
cell.y = j;
// Set some initial colours for the cells...
cell.style.backgroundColor = setCellColour(i, j);
colourGrid.appendChild(cell);
}
... | conditional_block |
haystack.rs | ///
/// The `parent` range should be a valid range relative to a hay *a*, which
/// was used to slice out *self*: `self == &a[parent]`.
///
/// Similarly, the `original` range should be a valid range relative to
/// another hay *b* used to slice out *a*: `a == &b[original]`.
///
/// The dis... | aystack, range }
}
}
impl<'h> Span< | identifier_body | |
haystack.rs | ::empty())
}
#[inline]
default fn from_span(span: Span<Self>) -> Self {
span.haystack
}
#[inline]
default fn borrow_range(&self, _: Range<<Self::Target as Hay>::Index>) -> Range<<Self::Target as Hay>::Index> {
self.start_index()..self.end_index()
}
#[inline]
defaul... | identifier_name | ||
haystack.rs | all valid indices `i` of `self`, we have
/// `i <= self.end_index()`.
fn end_index(&self) -> Self::Index;
/// Returns the next immediate index in this haystack.
///
/// # Safety
///
/// The `index` must be a valid index, and also must not equal to
/// `self.end_index()`.
///
//... | &self,
range: Range<<Self::Target as Hay>::Index>,
subrange: Range<<Self::Target as Hay>::Index>,
) -> Range<<Self::Target as Hay>::Index>;
}
impl<H: Haystack> SpanBehavior | &self,
range: Range<<Self::Target as Hay>::Index>,
) -> Range<<Self::Target as Hay>::Index>;
fn do_restore_range( | random_line_split |
googleMapsImplementation.ts | /**
* insers the map to the dom of the html document
*/
displayMap(): void {
this.parentElement.style.display = "";
this.isDisplayed = true;
}
/**
* hides the map
*/
hideMap(): void {
this.parentElement.style.display = "none";
this.isDisplayed = false;
}
/**
* remove the ma... | random_line_split | ||
googleMapsImplementation.ts | }
/**
* gets the geo map
*/
getMap() : GeoMap {
return this.map;
}
/**
* returns a serialize version of this marker
*/
toSerializedMarker(): SerializedMarker {
return {
visibility: this.visibility,
iconPath: this.iconPath,
location: this.location,
data: this.data
... | /**
* sets the new zoom of/for the map
* @param newZoom the new zoom
*/
setZoom(newZoom: number): void {
this.map.setZoom(newZoom);
}
/**
* returns the current zoom
*/
getZoom(): number {
return this.map.getZoom();
}
/**
* sets the center of the map
* @param lat the latit... | this.parentElement.innerHTML = "";
this.parentElement.removeAttribute("style")
this.map = null;
this.markers = {};
//this.eventTokens = [];
this.isDeleted = true;
this.isDisplayed = false;
this.isInitialized = false;
}
| identifier_body |
googleMapsImplementation.ts | }
/**
* gets the geo map
*/
getMap() : GeoMap {
return this.map;
}
/**
* returns a serialize version of this marker
*/
toSerializedMarker(): SerializedMarker {
return {
visibility: this.visibility,
iconPath: this.iconPath,
location: this.location,
data: this.data
... | ocation: LatLng, iconPath: string = "", displayOnMap: boolean = true, data: any = null): GoogleMapsMarker {
var googleMarker: google.maps.Marker = new google.maps.Marker ({
position: new google.maps.LatLng(location.lat | dMarkerFromGeoLocation(l | identifier_name |
context.go | Value()
JSSrc() Value
// Reports whether the app has been updated in background. Use app.Reload()
// to load the updated version.
AppUpdateAvailable() bool
// Reports whether the app is installable.
IsAppInstallable() bool
// Shows the app install prompt if the app is installable.
ShowAppInstallPrompt()
//... | func (ctx uiContext) IsAppInstallable() bool {
if Window().Get("goappIsAppInstallable").Truthy() {
return Window().Call("goappIsAppInstallable").Bool()
}
return false
}
func (ctx uiContext) IsAppInstalled() bool {
if Window().Get("goappIsAppInstalled").Truthy() {
return Window().Call("goappIsAppInstalled").Boo... | }
| random_line_split |
context.go | ()
JSSrc() Value
// Reports whether the app has been updated in background. Use app.Reload()
// to load the updated version.
AppUpdateAvailable() bool
// Reports whether the app is installable.
IsAppInstallable() bool
// Shows the app install prompt if the app is installable.
ShowAppInstallPrompt()
// Retu... |
}
func (ctx uiContext) Page() Page {
return ctx.page
}
func (ctx uiContext) Dispatch(fn func(Context)) {
ctx.Dispatcher().Dispatch(Dispatch{
Mode: Update,
Source: ctx.Src(),
Function: fn,
})
}
func (ctx uiContext) Defer(fn func(Context)) {
ctx.Dispatcher().Dispatch(Dispatch{
Mode: Defer,
Sou... | {
Window().Call("goappShowInstallPrompt")
} | conditional_block |
context.go | ()
JSSrc() Value
// Reports whether the app has been updated in background. Use app.Reload()
// to load the updated version.
AppUpdateAvailable() bool
// Reports whether the app is installable.
IsAppInstallable() bool
// Shows the app install prompt if the app is installable.
ShowAppInstallPrompt()
// Retu... |
func (ctx uiContext) Handle(actionName string, h ActionHandler) {
ctx.Dispatcher().Handle(actionName, ctx.Src(), h)
}
func (ctx uiContext) NewAction(name string, tags ...Tagger) {
ctx.NewActionWithValue(name, nil, tags...)
}
func (ctx uiContext) NewActionWithValue(name string, v any, tags ...Tagger) {
var tagMap... | {
ctx.Dispatcher().Dispatch(Dispatch{
Mode: Defer,
Source: ctx.Src(),
Function: fn,
})
} | identifier_body |
context.go | ()
JSSrc() Value
// Reports whether the app has been updated in background. Use app.Reload()
// to load the updated version.
AppUpdateAvailable() bool
// Reports whether the app is installable.
IsAppInstallable() bool
// Shows the app install prompt if the app is installable.
ShowAppInstallPrompt()
// Retu... | (fn func()) {
ctx.Dispatcher().Emit(ctx.Src(), fn)
}
func (ctx uiContext) Reload() {
if IsServer {
return
}
ctx.Defer(func(ctx Context) {
Window().Get("location").Call("reload")
})
}
func (ctx uiContext) Navigate(rawURL string) {
ctx.Defer(func(ctx Context) {
navigate(ctx.Dispatcher(), rawURL)
})
}
func... | Emit | identifier_name |
tokio_ct.rs | // We can spawn !Send futures here.
/// //
/// let join_handle = exec.spawn_handle_local( not_send ).expect( "spawn" );
///
/// join_handle.await;
/// });
///```
///
/// ## Unwind Safety.
///
/// When a future spawned on this wrapper panics, the panic will be caught by tokio in the poll function.
///
/// You ... | ( &self, future: FutureObj<'static, ()> ) -> Result<(), SpawnError>
{
// We drop the tokio JoinHandle, so the task becomes detached.
//
drop( self.local.spawn_local(future) );
Ok(())
}
}
impl LocalSpawn for TokioCt
{
fn spawn_local_obj( &self, future: LocalFutureObj<'static, ()> ) -> Result<(), SpawnErro... | spawn_obj | identifier_name |
tokio_ct.rs | ( not_send ).expect( "spawn" );
///
/// join_handle.await;
/// });
///```
///
/// ## Unwind Safety.
///
/// When a future spawned on this wrapper panics, the panic will be caught by tokio in the poll function.
///
/// You must only spawn futures to this API that are unwind safe. Tokio will wrap spawned tasks in
/// ... | let handle = self.local.spawn_local( future );
Ok( JoinHandle::tokio(handle) )
} | random_line_split | |
tokio_ct.rs | // We can spawn !Send futures here.
/// //
/// let join_handle = exec.spawn_handle_local( not_send ).expect( "spawn" );
///
/// join_handle.await;
/// });
///```
///
/// ## Unwind Safety.
///
/// When a future spawned on this wrapper panics, the panic will be caught by tokio in the poll function.
///
/// You ... |
}
impl TokioCt
{
/// Create a new `TokioCt`. Uses a default current thread [`Runtime`] setting timers and io depending
/// on the features enabled on _async_executors_.
//
pub fn new() -> Result<Self, TokioCtErr>
{
let mut builder = Builder::new_current_thread();
#[ cfg( feature = "tokio_io" ) ]
//
b... | {
match handle.runtime_flavor()
{
RuntimeFlavor::CurrentThread => Ok( Self
{
spawner: Spawner::Handle( handle ) ,
local: Rc::new( LocalSet::new() ) ,
}),
_ => Err( handle ),
}
} | identifier_body |
lib.rs | Use [`MmapBuffer`](struct.MmapBuffer.html) unless:
- [slice-deque](https://github.com/gnzlbg/slice_deque) is not available for your platform (e.g. no support for `mmap`),
- you need very small buffers (smaller than 1 memory page),
- you're about to create a lot of buffers in a short period of time ([`new()`](trait.Buf... |
}
impl<R: Read, B: Buffer> BufRefReader<R, B>
where Error: From<B::Error>
{
/// Creates buffered reader with default options. Look for [`BufRefReaderBuilder`](struct.BufRefReaderBuilder.html) for tweaks.
pub fn new(src: R) -> Result<BufRefReader<R, B>, B::Error> {
BufRefReaderBuilder::new(src)
.build()
}
//... | {
unimplemented!()
} | identifier_body |
lib.rs |
Use [`MmapBuffer`](struct.MmapBuffer.html) unless:
- [slice-deque](https://github.com/gnzlbg/slice_deque) is not available for your platform (e.g. no support for `mmap`),
- you need very small buffers (smaller than 1 memory page),
- you're about to create a lot of buffers in a short period of time ([`new()`](trait.B... | Error: From<B::Error>,
{
// two spaces, three spaces, two spaces
let mut r = BufRefReaderBuilder::new(&b" lorem ipsum "[..])
.capacity(4)
.build::<B>()
.unwrap();
assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..]));
assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..]));
assert_eq!(r.re... | use std::fmt::Debug;
fn read_until_empty_lines<B: Buffer>()
where
B::Error: Debug, | random_line_split |
lib.rs | VecBuffer,
MmapBuffer,
};
use slice_deque::AllocError;
use std::convert::From;
/**
Buffering reader.
See [module-level docs](index.html) for examples.
*/
pub struct BufRefReader<R, B> {
src: R,
buf: B,
}
/**
Builder for [`BufRefReader`](struct.BufRefReader.html).
See [module-level docs](index.html) for example... | read_mmap | identifier_name | |
lrp_processor.go | Request))
desired, err := builder.BuildReplicationController(&desireAppRequest)
if err != nil {
logger.Error("failed-building-create-desired-lrp-request", err, lager.Data{"process-guid": desireAppRequest.ProcessGuid})
errc <- err
return
}
logger.Debug("succeeded-building-create-de... | {
out := make(chan error)
wg := sync.WaitGroup{}
for _, ch := range channels {
wg.Add(1)
go func(c <-chan error) {
for e := range c {
out <- e
}
wg.Done()
}(ch)
}
go func() {
wg.Wait()
close(out)
}()
| identifier_body | |
lrp_processor.go | (desireAppRequests))
for i, desireAppRequest := range desireAppRequests {
desireAppRequest := desireAppRequest
builder := l.furnaceBuilders["buildpack"]
if desireAppRequest.DockerImageUrl != "" {
builder = l.furnaceBuilders["docker"]
}
works[i] = func() {
logger.Debug("building-creat... | count <- errorCount
close(count)
}()
| random_line_split | |
lrp_processor.go | -cc"),
cancelCh,
l.httpClient,
appDiffer.Stale(),
)
updateErrorCh := l.updateStaleDesiredLRPs(logger, cancelCh, staleAppCh, existingSchedulingInfoMap, &invalidsFound)
bumpFreshness := true
success := true
fingerprintErrorCh, fingerprintErrorCount := countErrors(fingerprintErrorCh)
// closes errors when ... | {
logger.Error("failed-getting-desired-lrps-from-kube", err)
return nil, err
} | conditional_block | |
lrp_processor.go | err := syncDesiredLRPsDuration.Send(duration)
if err != nil {
logger.Error("failed-to-send-sync-desired-lrps-duration-metric", err)
}
err = invalidLRPsFound.Send(int(invalidsFound))
if err != nil {
logger.Error("failed-to-send-sync-invalid-lrps-found-metric", err)
}
}()
defer logger.Info("done")
e... | (
logger lager.Logger,
cancel <-chan struct{},
missing <-chan []cc_messages.DesireAppRequestFromCC,
invalidCount *int32,
) <-chan error {
logger = logger.Session("create-missing-desired-lrps")
errc := make(chan error, 1)
go func() {
defer close(errc)
for {
var desireAppRequests []cc_messages.DesireAppR... | createMissingDesiredLRPs | identifier_name |
Main.go | ализирован нулём, p больше не содержит nil
s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов
s[3] = 7 // Присвоить значение одному из них
r := -2 // определить ещё одну локальную переменную
return &s[3], &r // Амперсанд(&) обозначает получение адреса переменной
}
fun... | identifier_name | ||
Main.go | x + y, x * y // возврат двух значений
}
func learnTypes() {
// тип string
s := "Learn Go!"
s2 := `"Чистый" строковый литерал
может содержать переносы строк`
// Символы не из ASCII
g := 'Σ' // тип rune - алиас для типа int32, содержит символ юникода
f := 3.141595 // float64, 64-х битное число с плавающей точк... | fmt.Sprintf("(%d, %d)", p.x, p.y)
}
func learnInterfaces() {
// синтаксис с фигурными скобками это "литерал структуры". Он возвращает
// проинициализированную структуру, а оператор := присваивает её p
p := pair{3, 4}
fmt.Println(p.String()) // вызов метода String у переменной p типа pair
var i Stringer /... | полям p через точчку
return | conditional_block |
Main.go | return x + y, x * y // возврат двух значений
}
func learnTypes() {
// тип string
s := "Learn Go!"
s2 := `"Чистый" строковый литерал
может содержать переносы строк`
// Символы не из ASCII
g := 'Σ' // тип rune - алиас для типа int32, содержит символ юникода
f := 3.141595 // float64, 64-х битное число с плавающ... | с Stringer
func (p pair) String() string { // p в данном случае называют receiver-ом
// Sprintf - ещё одна функция из пакета fmt
// Обращение к полям p через точчку
return fmt.Sprintf("(%d, %d)", p.x, p.y)
}
func learnInterfaces() {
// синтаксис с фигурными скобками это "литерал структуры". Он возвращает
// проин... | ir реализует интерфей | identifier_body |
Main.go | return x + y, x * y // возврат двух значений
}
func learnTypes() {
// тип string
s := "Learn Go!"
s2 := `"Чистый" строковый литерал
может содержать переносы строк`
// Символы не из ASCII
g := 'Σ' // тип rune - алиас для типа int32, содержит символ юникода
f := 3.141595 // float64, 64-х битное число с плавающ... |
learnVariadicParams("Learn", "learn", "learn again")
}
// функции могут иметь варьируемое количество параметров
func learnVariadicParams(myStrings ...interface{}) {
// вывести все параметры с помощью итерации
for _, param := range myStrings {
fmt.Println("param:", param)
}
// передать все варьируемые параметр... |
// Функция в пакете fmt сами всегда вызывают метод String у объектов для
// получения их строкового представления
fmt.Println(p) // вывод такой-же, как и выше
fmt.Println(i) // вывод такой-же, как и выше | random_line_split |
descriptive_stats_04022018.py | ['YearBuilt'].between(1940, 2015)]
df = df.drop_duplicates(['YearBuilt', 'Single Family Homes'])
df_cluster = Main[['YearBuilt', 'hoa_neigh', 'YearBuilt_mode']].dropna()
df_cluster = df_cluster[df_cluster['hoa_neigh'].isin([0,1])]
df_cluster['mode_dist'] = df_cluster['YearBuilt'] - df_cluster['YearBuilt_mode']
d... |
isol.to_csv(r'G:\Zillow\Created\Figures\ | chars['{}_hoa_wt'.format(color)] = chars['{}'.format(color)] * chars['hoa_geoid']
chars['{}_nonhoa_wt'.format(color)] = chars['{}'.format(color)] * (1-chars['hoa_geoid'])
isol_hoa = np.average(chars[colors_geoid], axis=0, weights=chars['{}_hoa_wt'.format(color)])
isol_nonhoa = np.average(c... | conditional_block |
descriptive_stats_04022018.py | ['YearBuilt'].between(1940, 2015)]
df = df.drop_duplicates(['YearBuilt', 'Single Family Homes'])
df_cluster = Main[['YearBuilt', 'hoa_neigh', 'YearBuilt_mode']].dropna()
df_cluster = df_cluster[df_cluster['hoa_neigh'].isin([0,1])]
df_cluster['mode_dist'] = df_cluster['YearBuilt'] - df_cluster['YearBuilt_mode']
d... |
chars = Main[['geoid', 'hoa_geoid', 'records_n']].dropna().drop_duplicates()
chars = chars[chars['records_n']>=30]
# Merge to Census data
# Load data
census_chars = pd.read_csv(r'C:\Users\wyatt\Research\Zillow\IPUMS_blockgrp_07012017.csv')
census_chars = census_chars[census_chars['total_pop']>0]
# Ref... |
# Create summary measures by geoid
Main['geoid'] = Main['PropertyAddressCensusTractAndBlock'].astype(str).str[:9] + Main['PropertyAddressCensusTractAndBlock'].astype(str).str[10:13]
Main['records_n'] = Main.groupby(['geoid'])['RowID'].transform(pd.Series.count)
Main['hoa_geoid'] = Main.groupby(['geoid'])['hoa'].tr... | random_line_split |
game_engine.py | or json type provided')
# CLASS Game
# stores screen resolution and background color
# initializes the players starting location
# define control and drawing methods
# TODO: add wall member as array of tiles
# TODO: add floor member as array of tiles
class Game:
current_level = None
current_map = No... | (y - self.player.y_pos + self.screen_y_buffer) * 32))
elif self.current_map[y][x] > 60:
self.screen.blit(self.wall[0], ((x - self.player.x_pos + self.screen_x_buffer) * 32,
| random_line_split | |
game_engine.py | 1):
# print("north")
# pos_north = 61
# # collide with npc to the north
# elif npc.y_pos == self.player.y_pos:
# if npc.x_pos == (self.player.x_pos + 1):
# print("east")
# pos_east = 61
# # collide with npc to the east
# elif npc.x_pos == (self.player.x_pos - 1):
# ... | if event.key == K_1:
self.screen_size = resolution_672_480
res_menu = False
elif event.key == K_2:
self.screen_size = resolution_1056_608
res_menu = False
elif event.key == K_3:
self.screen_size = resolution_1440_736
res_menu = False | conditional_block | |
game_engine.py |
# Class Level
# this stores the information for a level in one class
# this class should be treated like a singleton
class Level(object):
_map_name = None
_map = []
_object_matrix = []
object_list = []
_json = {}
def __init__(self):
self._map = None
def __load_json(self, file_name):
with o... | __instance = None
@staticmethod
def getInstance():
if Wall.__instance == None:
Wall()
return Wall.__instance
def __init__(self):
if Wall.__instance != None:
raise Exception("this class is a singleton. use getinstance() instead")
else:
Wall.__instance = self | identifier_body | |
game_engine.py | ._json["name"]
self._map = self._json['map']
self._object_matrix = [[None] * len(self._map[0]) for i in range(len(self._map))] # sets objects matrix to a matrix of all None the size of _map
for i in range(len(self._json['objects'])):
if self._json['objects'][i]['type'] == 'warp':
self.object_list.appe... | (self):
pygame.init()
self.font_1 = pygame.font.Font('fonts/victor-pixel.ttf', 32)
pygame.key.set_repeat(self.key_delay, self.key_repeat)
flags = DOUBLEBUF | HWACCEL
self.screen = pygame.display.set_mode(self.screen_resolution,flags)
pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP])
# setup disp... | __init__ | identifier_name |
mod.rs | _specs!` macro to generate such arrays.
Complex(&'static [&'static dyn UntypedProperty]),
// /// Same a `Complex`, but with a callback function used to set the default block state.
// ComplexWithDefault(&'static [&'static dyn UntypedProperty], fn(&BlockState) -> &BlockState)
}
impl Block {
/// Constr... |
/// Get the block state from the given save ID.
pub fn get_state_from(&self, sid: u32) -> Option<&'static BlockState> {
self.ordered_states.get(sid as usize).copied()
}
/// Get the default state from the given block name.
pub fn get_block_from_name(&self, name: &str) -> Option<&'static Blo... | /// Get the save ID from the given state.
pub fn get_sid_from(&self, state: &'static BlockState) -> Option<u32> {
let (_, block_offset) = *self.block_to_indices.get(&state.get_block().get_key())?;
Some(block_offset + state.get_index() as u32)
} | random_line_split |
mod.rs | ], fn(&BlockState) -> &BlockState)
}
impl Block {
/// Construct a new block, this method should be used to define blocks statically.
/// The preferred way of defining static blocks is to use the `blocks!` macro.
pub const fn new(name: &'static str, spec: BlockSpec) -> Self {
Self {
na... | register_tag_type | identifier_name | |
mod.rs | _complex(properties);
BlockStorage::Complex {
states,
properties,
default_state_index: 0
}
}
}
// let mut default_supplier = None;
let mut storage = match self.spec {
BlockSpec... | {
const MAX_SMALL_LEN: usize = 8;
let store = self.tag_stores.get_mut(&tag_type.get_key()).ok_or(())?;
for block in blocks {
if let TagStore::Small(vec) = store {
let idx = vec.iter().position(move |&b| b == block);
if enabled {
... | identifier_body | |
convert.py | 1 :].replace(" ", "").strip()
)
if re.match(reg_str, new_text_test) and el_text.lower().startswith(value_name):
return el_text[: len(value_name)] + "\u2028" + v
else:
el_new = get_replacement_mapping_value(k, v, el_text)
if el_new:
... | gging.basicConfig(
format="%(asctime)s %(filename)s | %(levelname)s | %(funcName)s | %(message)s",
)
if convert_vars.args.debug:
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.getLogger().setLevel(logging.INFO)
| identifier_body | |
convert.py | .debug(f" --- suit_key = {suit_key}")
for suit, suit_tag in zip(input_data[key], suit_tags):
logging.debug(f" --- suit [name] = {suit['name']}")
logging.debug(f" --- suit_tag = {suit_tag}")
tag_for_suit_name = get_tag_for_suit_name(suit, suit_tag)
data.update(tag... |
def get_valid_styles() -> List[str]: | random_line_split | |
convert.py | URL will be suffixed with / and the card ID). "
),
)
args = parser.parse_args(input_args)
return args
def get_card_ids(language_data: Union[Dict[Any, Any], List[Any]], key: str = "id") -> Generator[str, None, None]:
if isinstance(language_data, dict):
for k, v in language_data.items()... | get_replacement_mapping_value | identifier_name | |
convert.py | _en_static." + sfile_ext]
)
else:
template_doc = os.path.normpath(
convert_vars.BASE_PATH + os.sep + convert_vars.DEFAULT_TEMPLATE_FILENAME + "_" + style + "." + sfile_ext
)
template_doc = template_doc.replace("\\ ", " ")
if os.path.isfile(template_do... | runs[i].text = ""
| conditional_block | |
lib.rs |
///////////////////////////////////////////////////////////////////////////////
// TESTS
///////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
use super::*;
use num_bigint::{Sign, ToBigInt};
#[test]
fn should_hash_strings() {
let str_claim =... | {
let mut claim_bytes = num.to_bytes_be().1;
while claim_bytes.len() < 32 {
claim_bytes = [&[0], &claim_bytes[..]].concat();
}
claim_bytes
} | identifier_body | |
lib.rs | () {
let hex_claim = "0x045a126cbbd3c66b6d542d40d91085e3f2b5db3bbc8cda0d59615deb08784e4f833e0bb082194790143c3d01cedb4a9663cb8c7bdaaad839cb794dd309213fcf30";
let b64_hash = digest_hex_claim(hex_claim);
assert_eq!(b64_hash, "nGOYvS4aqqUVAT9YjWcUzA89DlHPWaooNpBTStOaHRA=");
let hex_claim = ... | should_hash_hex_claims | identifier_name | |
lib.rs | 48f8ddff704ebcd1d8a982dc5ba8be7458c677b17";
let b64_hash = digest_hex_claim(hex_claim);
assert_eq!(b64_hash, "k0UwNtWW4UQifisXuoDiO/QGRZNNTY7giWK1Nx/hoSo=");
let hex_claim = "0x04020d62c94296539224b885c6cdf79d0c2dd437471425be26bf62ab522949f83f3eed34528b0b9a7fbe96e50ca85471c894e1aa819bbf12ff78ad... | assert_eq!(len, 32);
| random_line_split | |
OutMMOperationCtrl.js | else {
$scope.changeSelection($scope.order.product[key]);
keepGoing = false;
}
}
});
$scope.tableParams = new ngTableParams({//未完成料号名称规格及剩余数量表格
page: 1,
count: 10,
filter: { },
sorting: {
'PD_PDNO': 'asc'
... | e};}
}
});
modalInstance.result.then(function(s){
if(s) {//判断数量是否需要拆分
OutOper.ifNeedBatch({},{bar_code:$scope.bi_barcode,pr_fbzs:$scope.pr_fbzs, whcode:$scope.order.PI_WHCODE},function(data){
},function(res){
if(res.data.exceptionInfo.indexOf('拆批') >=0){
... | boxcode,"bi_outboxcode")){
toaster.pop('error',"条码所在的箱号在已采集列表中存在!");
return ;
}
}else if(message.isMsd){//湿敏元件弹出显示湿敏元件的相关记录 MSDlog
//拆分湿敏元件提示剩余寿命等信息
var modalInstance = $modal.open({
templateUrl: 'resources/tpl/output/msdConfirm.html',
controller: 'SplitModalCtrl',
... | conditional_block |
OutMMOperationCtrl.js | }else {
$scope.changeSelection($scope.order.product[key]);
keepGoing = false;
}
}
});
$scope.tableParams = new ngTableParams({//未完成料号名称规格及剩余数量表格
page: 1,
count: 10,
filter: { },
sorting: {
'PD_PDNO': 'asc'
... | defer.reject(data.exceptionInfo);
}else
defer.resolve(data.message);
}, function(response){
if(response.status == 0){ //无网络错误
Online.setOnline(false);//修改网络状态
toaster.pop('error', '失败',"网络连接不可用,请稍后再试");
}
defer.reject(response.data.exceptionInfo);
});
};
v... | }
var checkBar = function(defer) {
OutOper.checkOutqty({},{pi_id:$scope.order.PI_ID,pd_id:$scope.pd_id,pr_fbzs:$scope.pr_fbzs, barcode:$scope.bi_barcode, whcode:$scope.order.PI_WHCODE,prodcode:$scope.bi_prodcode}, function(data){
if(data.exceptionInfo){ | random_line_split |
cronjob.go | Find(&jobs).
Error
})
eg.Go(func() error {
pagination.Total = int64(page)
return query.Count(&pagination.Total).Error
})
err = eg.Wait()
if err != nil {
return
}
for _, job := range jobs {
timers := make([]view.CronJobTimer, 0)
for _, timer := range job.Timers {
timers = append(timers, view.C... | Job
var timers = make([]db.CronJobTimer, len(params.Timers))
var oldTimers []db.CronJobTimer
for idx, timer := range params.Timers {
_, err := cronParser.Parse(timer.Cron)
if err != nil {
return errors.Wrapf(err, "parse cron failed: %s", timer.Cron)
}
timers[idx] = db.CronJobTimer{
Cron: timer.Cron,
... | b.Cron | identifier_name |
cronjob.go | page = 1 // from 1 on
}
pageSize := params.PageSize
if pageSize > 100 {
pageSize = 100
}
offset := (page - 1) * pageSize
query := j.db.Model(&db.CronJob{})
if params.Enable != nil {
query = query.Where("enable = ?", *params.Enable)
}
if params.Name != nil {
query = query.Where("name like ?", "%"+*para... | if page == 0 { | random_line_split | |
cronjob.go | Find(&jobs).
Error
})
eg.Go(func() error {
pagination.Total = int64(page)
return query.Count(&pagination.Total).Error
})
err = eg.Wait()
if err != nil {
return
}
for _, job := range jobs {
timers := make([]view.CronJobTimer, 0)
for _, timer := range job.Timers {
timers = append(timers, view.C... | obPayload, node)
if err != nil {
tx.Rollback()
return err
}
}
return tx.Commit().Error
}
// ListTask 任务列表
func (j *CronJob) ListTask(params view.ReqQueryTasks) (list []view.CronTask, pagination view.Pagination, err error) {
var tasks []db.CronTask
page := params.Page
if page == 0 {
page = 1
}
page... | err = j.dispatcher.dispatchOnceJob(j | conditional_block |
cronjob.go | username := "%" + *params.User + "%"
query = query.Joins("left join user on cron_job.uid = user.uid")
query = query.Where("user.username like ? or user.nickname like ?", username, username)
}
eg := errgroup.Group{}
eg.Go(func() error {
return query.Table("cron_job").Offset(offset).
Preload("Timers").
... | if page == 0 {
page = 1 // from 1 on
}
pageSize := params.PageSize
if pageSize > 100 {
pageSize = 100
}
offset := (page - 1) * pageSize
query := j.db.Model(&db.CronJob{})
if params.Enable != nil {
query = query.Where("enable = ?", *params.Enable)
}
if params.Name != nil {
query = query.Where("name lik... | identifier_body | |
config.go | initialize a PkgrConfig passed in by caller
func NewConfig(cfgPath string, cfg *PkgrConfig) {
err := loadConfigFromPath(cfgPath)
if err != nil {
log.Fatal("could not detect config at supplied path: " + cfgPath)
}
err = viper.Unmarshal(cfg)
if err != nil {
log.Fatalf("error parsing pkgr.yml: %s\n", err)
}
i... |
// IsCustomizationSet ...
func IsCustomizationSet(key string, elems []interface{}, elem string) bool {
for _, v := range elems {
for k, iv := range v.(map[interface{}]interface{}) {
if k == elem {
for k2 := range iv.(map[interface{}]interface{}) {
if k2 == key {
return true
}
}
}
}
... | {
// should be one of Debug,Info,Warn,Error,Fatal,Panic
viper.SetDefault("loglevel", "info")
// path to R on system, defaults to R in path
viper.SetDefault("rpath", "R")
// setting this to GOMAXPROCS(0) because NumCPU() won't work well with the scheduler.
viper.SetDefault("threads", runtime.GOMAXPROCS(0))
} | identifier_body |
config.go | initialize a PkgrConfig passed in by caller
func NewConfig(cfgPath string, cfg *PkgrConfig) {
err := loadConfigFromPath(cfgPath)
if err != nil {
log.Fatal("could not detect config at supplied path: " + cfgPath)
}
err = viper.Unmarshal(cfg)
if err != nil {
log.Fatalf("error parsing pkgr.yml: %s\n", err)
}
i... |
return expanded
}
/// For a list of repos, expand the ~ at the beginning of each path to the home directory.
/// consider any problems a fatal error.
func expandTildes(paths []string) []string {
var expanded []string
for _, p := range paths {
newPath := expandTilde(p)
expanded = append(expanded, newPath)
}
r... | {
log.WithFields(log.Fields{
"path": p,
"error": err,
}).Fatal("problem parsing config file -- could not expand path")
} | conditional_block |
config.go | Config initialize a PkgrConfig passed in by caller
func NewConfig(cfgPath string, cfg *PkgrConfig) {
err := loadConfigFromPath(cfgPath)
if err != nil {
log.Fatal("could not detect config at supplied path: " + cfgPath)
}
err = viper.Unmarshal(cfg)
if err != nil {
log.Fatalf("error parsing pkgr.yml: %s\n", err)
... | return library
}
// loadConfigFromPath loads pkc configuration into the global Viper
func loadConfigFromPath(configFilename string) error {
if configFilename == "" {
configFilename = "pkgr.yml"
}
viper.SetEnvPrefix("pkgr")
err := viper.BindEnv("rpath")
if err != nil {
log.Fatalf("error binding env: %s\n", er... | if library == "" {
log.Fatal("must specify either a Lockfile Type or Library path")
} | random_line_split |
config.go | initialize a PkgrConfig passed in by caller
func NewConfig(cfgPath string, cfg *PkgrConfig) {
err := loadConfigFromPath(cfgPath)
if err != nil {
log.Fatal("could not detect config at supplied path: " + cfgPath)
}
err = viper.Unmarshal(cfg)
if err != nil {
log.Fatalf("error parsing pkgr.yml: %s\n", err)
}
i... | (lockfileType string, rpath string, rversion cran.RVersion, platform string, library string) string {
switch lockfileType {
case "packrat":
library = filepath.Join("packrat", "lib", packratPlatform(platform), rversion.ToFullString())
case "renv":
var err error
library, err = getRenvLibrary(rpath)
if err != n... | getLibraryPath | identifier_name |
groups.component.ts | -column';
import { FilterService } from '../../services/filter-service/filter.service';
import { AuthService } from './../../services/auth.service';
import { BlockingGroupResponseDTO, GroupDataService, GroupResponseDTO } from './../../services/dataServices/group-data.service';
import { NO_LOGO, DELETE_SUCCESSFUL, ERROR... |
primaryColor: string = '';
accentColor: string = '';
warnColor = '';
sheetMode: SheetMode = SheetMode.Closed;
fields: DetailedField[];
title: string = 'Group';
userName: string;
userToken: any;
private memberID: string;
sysAdmin: boolean = false;
disableSaveButton: boolean = false;
showBlocks: ... | name: string,
description: string
};
deletionState: boolean = false; | random_line_split |
groups.component.ts | : string = 'Group';
userName: string;
userToken: any;
private memberID: string;
sysAdmin: boolean = false;
disableSaveButton: boolean = false;
showBlocks: boolean = false;
blockingGroupsLists: BlockingGroupResponseDTO;
selectedAvatar: string = './../../assets/avatar/round default.svg';
logoPath: strin... | closeSheet | identifier_name | |
groups.component.ts | -column';
import { FilterService } from '../../services/filter-service/filter.service';
import { AuthService } from './../../services/auth.service';
import { BlockingGroupResponseDTO, GroupDataService, GroupResponseDTO } from './../../services/dataServices/group-data.service';
import { NO_LOGO, DELETE_SUCCESSFUL, ERROR... |
});
this.subscriptions.add(this.route.paramMap.subscribe((params: ParamMap) => {
this.memberID = this.authService.getUserID();
if (params.get('showBlocks') && params.get('showBlocks').toLowerCase() === 'true') {
this.groupDataService.getAllBlockingGroupsOfUser(this.memberID).then((value: B... | {
this.themeDataService.getThemeByID(value).then(value => {
if (value !== null) {
let color: string = value.colors;
let parts = color.split('_');
this.primaryColor = parts[0];
this.accentColor = parts[1];
this.warnColor = parts[2];
... | conditional_block |
groups.component.ts | title: string = 'Group';
userName: string;
userToken: any;
private memberID: string;
sysAdmin: boolean = false;
disableSaveButton: boolean = false;
showBlocks: boolean = false;
blockingGroupsLists: BlockingGroupResponseDTO;
selectedAvatar: string = './../../assets/avatar/round default.svg';
logoPath... | {
this.disableSaveButton = false;
let id: string;
if (this.group) {
id = this.group.id;
}
this.sheetMode = DetailedSheetUtils.toggle(id, data.entity.id, this.sheetMode, data.mode);
this.group = {
id: data.entity.id, description: data.entity.description, name: data.entity.name
};
... | identifier_body | |
genjobs.go | .Name)
}
// remove volumes from spec
filteredVolumes := []coreapi.Volume{}
for _, volume := range pod.Volumes {
if !removeVolumeNames.Has(volume.Name) {
filteredVolumes = append(filteredVolumes, volume)
}
}
pod.Volumes = filteredVolumes
// remove env and volume mounts from containers
for i := range pod... | {
// fallback to copying the file instead
src, err := os.Open(srcPath)
if err != nil {
return err
}
dst, err := os.OpenFile(destPath, os.O_WRONLY, 0666)
if err != nil {
return err
}
_, err = io.Copy(dst, src)
if err != nil {
return err
}
dst.Sync()
dst.Close()
src.Close()
return nil
} | identifier_body | |
genjobs.go | ")
var jobsPath = flag.String("jobs", "", "path to prowjobs, defaults to $PWD/../")
var outputPath = flag.String("output", "", "path to output the generated jobs to, defaults to $PWD/generated-security-jobs.yaml")
// remove merged presets from a podspec
func undoPreset(preset *config.Preset, labels map[string]string, ... | }
// NOTE: this needs to be before the bare -- and then bootstrap args so we prepend it
container.Args = append([]string{"--ssh=/etc/ssh-security/ssh-security"}, container.Args...)
// check for scenario specific tweaks
// NOTE: jobs are remapped to their original name in bootstrap to de-dupe config
scena... | {
if arg == "--" {
endsWithScenarioArgs = true
// handle --repo substitution for main repo
} else if arg == "--repo=k8s.io/kubernetes" || strings.HasPrefix(arg, "--repo=k8s.io/kubernetes=") || arg == "--repo=k8s.io/$(REPO_NAME)" || strings.HasPrefix(arg, "--repo=k8s.io/$(REPO_NAME)=") {
container.Arg... | conditional_block |
genjobs.go | ")
var jobsPath = flag.String("jobs", "", "path to prowjobs, defaults to $PWD/../")
var outputPath = flag.String("output", "", "path to output the generated jobs to, defaults to $PWD/generated-security-jobs.yaml")
// remove merged presets from a podspec
func undoPreset(preset *config.Preset, labels map[string]string, ... | needStagingFlag := false
isGCPe2e := false
for i, arg := range container.Args {
if arg == "--" {
endsWithScenarioArgs = true
// handle --repo substitution for main repo
} else if arg == "--repo=k8s.io/kubernetes" || strings.HasPrefix(arg, "--repo=k8s.io/kubernetes=") || arg == "--repo=k8s.io/$(REPO... | random_line_split | |
genjobs.go | }
// remove volumes from spec
filteredVolumes := []coreapi.Volume{}
for _, volume := range pod.Volumes {
if !removeVolumeNames.Has(volume.Name) {
filteredVolumes = append(filteredVolumes, volume)
}
}
pod.Volumes = filteredVolumes
// remove env and volume mounts from containers
for i := range pod.Contai... | main | identifier_name | |
UserRole.ts | Equips[i][j] &&
tempChangeEquips[i][j].handle != SubRoles.ins().getSubRoleByIndex(i).equipsData[j].item.handle) {
if (isWear && roleIndex == i) {
UserEquip.ins().sendWearEquipment(tempChangeEquips[i][j].handle, j, roleIndex);
this.canChangeEquips[i][j] = false;
}
else {
this.canCha... |
lv | identifier_name | |
UserRole.ts | item, item);
}
}
let len = tempChangeEquips.length;
for (let i: number = 0; i < len; i++) {
for (let j: number = 0; j < tempChangeEquips[i].length; j++) {
this.canChangeEquips[i][j] = false;
if (tempChangeEquips[i][j] &&
tempChangeEquips[i][j].handle != SubRoles.ins().getSubRoleByIndex(i).equ... | break;
}
}
return isReturn;
}
/**
* 角色提示
*/
public roleHint(type: number): boolean {
let len: number = SubRoles.ins().subRolesLen;
let flag: boolean = false;
for (let i: number = 0; i < len; i++) {
let role: Role = SubRoles.ins().getSubRoleByIndex(i);
flag = this.roleHintCheck(role, type)... | identifier_body | |
UserRole.ts | this.canChangeEquips[i][j]) {
return true;
}
}
}
return false;
}
/** 检查是否需要显示红点 */
public showNavBtnRedPoint(b: boolean = false): void {
//是否有装备可以穿戴
for (let i: number = 0; i < this.canChangeEquips.length; i++) {
for (let j: number = 0; j < this.canChangeEquips[i].length; j++) {
if (this.... | le.shieldData.level;
let shieldConfig: ShieldConfig = GlobalConfig.ShieldConfig[lv];
| conditional_block | |
UserRole.ts | BtnRedPoint(b: boolean = false): void {
//是否有装备可以穿戴
for (let i: number = 0; i < this.canChangeEquips.length; i++) {
for (let j: number = 0; j < this.canChangeEquips[i].length; j++) {
if (this.canChangeEquips[i][j]) {
b = true;
break;
}
}
if (b)
break;
}
if (!b && SamsaraModel.ins(... | lv += role.shieldData.level;
let shieldConfig: ShieldConfig = GlobalConfig.ShieldConfig[lv];
let shieldStageConfig: LoongSoulStageConfig = GlobalConfig.ShieldStageConfig[role.loongSoulData.stage];
if (shieldConfig) {
costNum = shieldStageConfig.normalCost; | random_line_split | |
reader.rs | : [u8; BUFFER_SIZE],
/// Offset of the first byte within the internal buffer that is valid
start : usize,
/// `Offset of the last byte + 1 within the internal buffer that is valid
end : usize,
/// `valid_end` is the last byte + 1 within the internal buffer
/// used by a valid UTF-8 ... | { // no valid data - check it is just incomplete, or an actual error
match e.error_len() {
None => { // incomplete UTF-8 fetch more
match self.fetch_input()? {
0 => { // ... and eof reached when incom... | conditional_block | |
reader.rs | `valid_end` <= `end` If `start` < `valid_end`
/// then the bytes in the buffer between the two are a valid UTF-8
/// byte stream; this should perhaps be kept in a string inside
/// the structure for performance
valid_end : usize,
/// position in the file
stream_pos : StreamPosition,
}
//ip Re... | impl <'a, R:std::io::Read> Iterator for &'a mut Reader<R> {
// we will be counting with usize | random_line_split | |
reader.rs | that implements the [std::io::Read] stream trait.
///
/// It utilizes an internal buffer of bytes that are filled as
/// required from the read stream; it maintains a position with the
/// stream (line and character) for the next character, and provides
/// the ability to get a stream of characters from the stream wit... | (&self) -> bool {
self.start == self.end
}
//mp borrow_buffer
/// Borrow the data held in the [Reader]'s buffer.
pub fn borrow_buffer(&self) -> &[u8] {
&self.current[self.start..self.end]
}
//mp borrow_pos
/// Borrow the stream position of the next character to be returned
... | buffer_is_empty | identifier_name |
reader.rs | ip Reader
impl <R:std::io::Read> Reader<R> {
//fp new
/// Returns a new UTF-8 character [Reader], with a stream position
/// set to the normal start of the file - byte 0, line 1,
/// character 1
///
/// The [Reader] will default to handling zero bytes returned by
/// the stream as an EOF; t... | {
match self.next_char() {
Ok(Char::Char(ch)) => Some(Ok(ch)),
Ok(_) => None,
Err(x) => Some(Err(x)),
}
} | identifier_body | |
address.rs | //bech32
#[derive(Debug)]
pub enum AddressError {
InvalidAddressVersion,
InvalidAddressSize,
InvalidNetworkPrefix,
InvalidHash,
Bech32(bech32::Error),
}
impl From<bech32::Error> for AddressError {
fn from(e: bech32::Error) -> Self {
AddressError::Bech32(e)
}
}
impl From<AddressErr... | }
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct AddressVisitor;
impl<'de> Visitor<'de> for AddressVisitor {
type Value = Address;
fn expecting(&self, formatter: &mut fmt::Formatter) -> f... | {
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`version` or `hash`")
}
... | identifier_body |
address.rs | //bech32
#[derive(Debug)]
pub enum AddressError {
InvalidAddressVersion,
InvalidAddressSize,
InvalidNetworkPrefix,
InvalidHash,
Bech32(bech32::Error),
}
impl From<bech32::Error> for AddressError {
fn from(e: bech32::Error) -> Self {
AddressError::Bech32(e)
}
}
impl From<AddressErr... | #[cfg(feature = "json")]
impl serde::Serialize for Address {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
let mut state = s.serialize_struct("Address", 2)?;
state.serialize_field("version", &self.version)?;
state.serialize_field("hash", &self.hash... | }
(version[0].to_u8(), hash)
}
| random_line_split |
address.rs | //bech32
#[derive(Debug)]
pub enum AddressError {
InvalidAddressVersion,
InvalidAddressSize,
InvalidNetworkPrefix,
InvalidHash,
Bech32(bech32::Error),
}
impl From<bech32::Error> for AddressError {
fn from(e: bech32::Error) -> Self {
AddressError::Bech32(e)
}
}
impl From<AddressErr... |
version = Some(map.next_value()?);
}
| {
return Err(de::Error::duplicate_field("version"));
} | conditional_block |
address.rs | //bech32
#[derive(Debug)]
pub enum AddressError {
InvalidAddressVersion,
InvalidAddressSize,
InvalidNetworkPrefix,
InvalidHash,
Bech32(bech32::Error),
}
impl From<bech32::Error> for AddressError {
fn from(e: bech32::Error) -> Self {
AddressError::Bech32(e)
}
}
impl From<AddressErr... | (&self) -> bool {
self.version == 31
}
pub fn is_unspendable(&self) -> bool {
self.is_null_data()
}
pub fn to_bech32(&self) -> String {
//Also todo this should probably just be in toString, and should use writers so that we
//don't allocate.
//@todo this should ... | is_null_data | identifier_name |
path.py | _direction(self, DIRECTIONS=DIRECTIONS):
"""
Get the current facing direction of the map_obstacle.
"""
return self.map_obstacle.get_current_facing_direction(DIRECTIONS=DIRECTIONS)
# this isn't used anywhere yet
def is_map_obstacle_in_screen_range(self):
"""
Deter... | iterable of nodes to visit in (y, x) format.
"""
palettes = pokemontools.map_gfx.read_palettes(self.config) | random_line_split | |
path.py | _graph = main_graph
self.sight_range = self.calculate_sight_range()
self.top_left_y = None
self.top_left_x = None
self.bottom_right_y = None
self.bottom_right_x = None
self.height = None
self.width = None
self.size = self.calculate_size()
# node... | penalty += PENALTIES["THREAT_ZONE"]
if consider_sight_range:
if self.is_node_in_sight_range(y, x, skip_range_check=True):
penalty += PENALTIES["SIGHT_RANGE"]
params = {
"skip_sight_range_check": True,
"... | conditional_block | |
path.py | the map.
"""
def __init__(self, some_map, identifier, sight_range=None, movement=None, turn=None, simulation=False, facing_direction=DIRECTIONS["DOWN"]):
"""
:param some_map: a reference to the map that this object belongs to
:param identifier: which object on the map does this corresp... |
def _get_movement(self):
"""
Figures out the "movement" variable. Also, this converts from the
internal game's format into True or False for whether or not the object
is capable of moving.
"""
raise NotImplementedError
@property
def movement(self):
... | """
Get the current facing direction of the map_obstacle.
"""
if not self.simulation:
self.facing_direction = self._get_current_facing_direction(DIRECTIONS=DIRECTIONS)
return self.facing_direction | identifier_body |
path.py | the map.
"""
def __init__(self, some_map, identifier, sight_range=None, movement=None, turn=None, simulation=False, facing_direction=DIRECTIONS["DOWN"]):
"""
:param some_map: a reference to the map that this object belongs to
:param identifier: which object on the map does this corresp... | (self, y, x):
"""
Applies a boundary of one around the threat zone, then checks if the
player is inside. This is how the threatzone activates to calculate an
updated graph or set of penalties for each step.
"""
y_condition = (self.top_left_y - 1) <= y < (self.bottom_right... | is_player_near | identifier_name |
time_driver.rs | DRIVER.on_interrupt()
}
};
(TIM4, timer, $block:ident, UP, $irq:ident) => {
#[cfg(time_driver_tim4)]
#[interrupt]
fn $irq() {
DRIVER.on_interrupt()
}
};
(TIM5, timer, $block:ident, UP, $irq:ident) => {
#[cfg(time_driver_tim5)]
#[interr... | set_alarm_callback | identifier_name | |
time_driver.rs | cfg(time_driver_tim3)]
type T = peripherals::TIM3;
#[cfg(time_driver_tim4)]
type T = peripherals::TIM4;
#[cfg(time_driver_tim5)]
type T = peripherals::TIM5;
#[cfg(time_driver_tim12)]
type T = peripherals::TIM12;
#[cfg(time_driver_tim15)]
type T = peripherals::TIM15;
foreach_interrupt! {
(TIM2, timer, $block:ident... | #[cfg(time_driver_tim15)]
#[interrupt]
fn $irq() {
DRIVER.on_interrupt()
}
};
}
// Clock timekeeping works with something we call "periods", which are time intervals
// of 2^15 ticks. The Clock counter value is 16 bits, so one "overflow cycle" is 2 periods.
//
// A `peri... | random_line_split | |
time_driver.rs | $irq() {
DRIVER.on_interrupt()
}
};
(TIM4, timer, $block:ident, UP, $irq:ident) => {
#[cfg(time_driver_tim4)]
#[interrupt]
fn $irq() {
DRIVER.on_interrupt()
}
};
(TIM5, timer, $block:ident, UP, $irq:ident) => {
#[cfg(time_driver_ti... | {
let id = self.alarm_count.fetch_update(Ordering::AcqRel, Ordering::Acquire, |x| {
if x < ALARM_COUNT as u8 {
Some(x + 1)
} else {
None
}
});
match id {
Ok(id) => Some(AlarmHandle::new(id)),
Err(_) => N... | identifier_body | |
mathMode.ts | ',
inline: 'yes',
notation: 'auto',
precision: '4',
align: 'left',
};
function truthy(s: string) {
s = s.toLowerCase();
return s.startsWith('t') || s.startsWith('y') || s === '1';
}
function falsey(s: string) {
s = s.toLowerCase();
return s.startsWith('f') || s.startsWith('n') || s === '0';
}
/... | (line: string): string {
return line.replace(inline_math_regex, '');
}
function process_block(cm: any, block: Block, noteConfig: any) {
// scope is global to the note
let scope = cm.state.mathMode.scope;
let config = Object.assign({}, noteConfig);
const math = mathjs.create(mathjs.all, { number: 'BigNumber... | get_line_equation | identifier_name |
mathMode.ts | inline: 'yes',
notation: 'auto',
precision: '4',
align: 'left',
};
function truthy(s: string) {
s = s.toLowerCase();
return s.startsWith('t') || s.startsWith('y') || s === '1';
}
function falsey(s: string) {
s = s.toLowerCase();
return s.startsWith('f') || s.startsWith('n') || s === '0';
}
// i... |
// On each change we're going to scan for
function on_change(cm: any, change: any) {
clean_up(cm);
// Most changes are the user typing a single character
// If this doesn't happen inside a math block, we shouldn't re-process
// +input means the user input the text (as opposed to joplin/plugin | {
for (let i = cm.firstLine(); i < cm.lineCount(); i++) {
if (!find_math(cm, i)) {
const line = cm.lineInfo(i);
clear_math_widgets(cm, line);
}
}
} | identifier_body |
mathMode.ts | inline: 'yes',
notation: 'auto',
precision: '4',
align: 'left',
};
function truthy(s: string) {
s = s.toLowerCase();
return s.startsWith('t') || s.startsWith('y') || s === '1';
}
function falsey(s: string) {
s = s.toLowerCase();
return s.startsWith('f') || s.startsWith('n') || s === '0';
}
// i... |
continue;
}
// Process one line
let result = '';
try {
const p = math.parse(get_line_equation(line));
if (falsey(config.simplify))
result = p.evaluate(scope);
else
result = math.simplify(p)
result = math.format(result, {
precision: Number(config.precision),
notat... | {
math.config({
number: 'number'
});
} | conditional_block |
mathMode.ts | ',
inline: 'yes',
notation: 'auto',
precision: '4',
align: 'left',
};
function truthy(s: string) {
s = s.toLowerCase();
return s.startsWith('t') || s.startsWith('y') || s === '1';
}
function falsey(s: string) {
s = s.toLowerCase();
return s.startsWith('f') || s.startsWith('n') || s === '0';
}
/... | // This is necessary to get the cursor to be placed in the right location ofter
// clicking on a widget
// The downside is that it breaks copying of widget text (for textareas, it never
// works on contenteditable)
// I'm okay with this because I want the user to be able to select a block
// without a... | if (lineData.alignRight)
res.setAttribute('class', 'math-result-right');
// handleMouseEvents gives control of mouse handling for the widget to codemirror | random_line_split |
activity.go | (float64(from.Y)*pixelToTuxelScaleY),
input.TouchCoord(float64(to.X)*pixelToTuxelScaleX),
input.TouchCoord(float64(to.Y)*pixelToTuxelScaleY),
t); err != nil {
return errors.Wrap(err, "failed to start the swipe gesture")
}
if err := testing.Sleep(ctx, delayToPreventGesture); err != nil {
return errors.Wrap(... | {
*dst, err = strconv.Atoi(s[i])
if err != nil {
return Rect{}, errors.Wrapf(err, "could not parse %q", s[i])
}
} | conditional_block | |
activity.go | json:"width"`
Height int `json:"height"`
}
// String returns the string representation of Rect.
func (r *Rect) String() string {
return fmt.Sprintf("(%d, %d) - (%d x %d)", r.Left, r.Top, r.Width, r.Height)
}
// NewActivity returns a new Activity instance.
// The caller is responsible for closing a.
// Returned Acti... | (ctx context.Context, to Point, t time.Duration) error {
task, err := ac.getTaskInfo(ctx)
if err != nil {
return errors.Wrap(err, "could not get task info")
}
if task.windowState != WindowStateNormal && task.windowState != WindowStatePIP {
return errors.Errorf("cannot move window in state %d", int(task.windowS... | MoveWindow | identifier_name |
activity.go | .Wrap(err, "failed to launch dumpsys")
}
// Looking for:
// Window #0 Window{a486f07 u0 com.android.settings/com.android.settings.Settings}:
// mDisplayId=0 stackId=2 mSession=Session{dd34b88 2586:1000} mClient=android.os.BinderProxy@705e146
// mHasSurface=true isReadyForDisplay()=true mWindowRemovalAll... | {
if err := ac.initTouchscreenLazily(ctx); err != nil {
return errors.Wrap(err, "could not initialize touchscreen device")
}
stw, err := ac.tew.NewSingleTouchWriter()
if err != nil {
return errors.Wrap(err, "could not get a new TouchEventWriter")
}
defer stw.Close()
// TODO(ricardoq): Fetch stableSize dire... | identifier_body | |
activity.go | json:"width"`
Height int `json:"height"`
}
// String returns the string representation of Rect.
func (r *Rect) String() string {
return fmt.Sprintf("(%d, %d) - (%d x %d)", r.Left, r.Top, r.Width, r.Height)
}
// NewActivity returns a new Activity instance.
// The caller is responsible for closing a.
// Returned Acti... |
// ResizeWindow resizes the activity's window.
// border represents from where the resize should start.
// to represents the coordinates for for the new border's position, in pixels.
// t represents the duration of the resize.
// ResizeWindow only works with WindowStateNormal and WindowStatePIP windows. Will fail othe... | return ac.swipe(ctx, from, to, t)
} | random_line_split |
planner.go | .Collection
}
// InternalPlannerParamsOption is an option that can be passed to
// NewInternalPlanner.
type InternalPlannerParamsOption func(*internalPlannerParams)
// WithDescCollection configures the planner with the provided collection
// instead of the default (creating a new one from scratch).
func WithDescColle... | EvalContext | identifier_name | |
planner.go | "github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/cancelchecker"
"github.com/cockroachdb/cockroach/pkg/util/... | "github.com/cockroachdb/cockroach/pkg/sql/opt/exec"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/querycache"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/sem/transform" | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.