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 |
|---|---|---|---|---|
marketplace.js | var parms = [];
var languageId = 1;
var instanceId = 1;
String.prototype.format = function () {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
var regexp = new RegExp('\\{' + i + '\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
ret... | (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function filterSearch() {
var fs = {};
fs.CompanyName = '';
fs.Products = [];
fs.ProductCategories = []
fs.ProducingCountries = [];
fs.ProducingRegions = [];
fs.StandardsCertified = []
fs.StandardsAssessed = [];
fs.Compliance = ... | isNumber | identifier_name |
marketplace.js | var parms = [];
var languageId = 1;
var instanceId = 1;
String.prototype.format = function () {
var formatted = this;
for (var i = 0; i < arguments.length; i++) |
return formatted;
};
var searchReports = function(search, callback) {
$.ajax({
url: './handlers/MarketplaceReportSearchHandler.ashx',
data: { language: languageId, instance: instanceId, search: JSON.stringify(search) },
success: function (d) {
if (callback) callback(d);
... | {
var regexp = new RegExp('\\{' + i + '\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
} | conditional_block |
marketplace.js | var parms = [];
var languageId = 1;
var instanceId = 1;
String.prototype.format = function () {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
var regexp = new RegExp('\\{' + i + '\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
ret... |
csv = csv.split(/\n/);
var countries = {},
mapChart,
countryChart,
numRegex = /^[0-9\.]+$/,
quoteRegex = /\"/g,
categories = CSVtoArray(csv[1]).slice(4);
// Parse the CSV into arrays, one array each country
$.each(csv.slice(2... | return text.replace(/^"/, '')
.replace(/",$/, '')
.split('","');
};
| identifier_body |
marketplace.js | var parms = [];
var languageId = 1;
var instanceId = 1;
String.prototype.format = function () {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
var regexp = new RegExp('\\{' + i + '\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
return ... | type: 'POST'
});
}
var getCompanyDetails = function (companyId, profileId, languageId, callback) {
$.ajax({
url: './handlers/MarketplaceCompanyDetailsHandler.ashx',
data: { company: companyId, profile: profileId, language: languageId },
success: function (d) {
if (ca... | data: { report: reportId, standard: standardId, profile: profileId },
success: function (d) {
if (callback) callback(d);
},
dataType: 'json', | random_line_split |
copy.go | /*
Copyright The ORAS Authors.
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
distrib... |
// copyCachedNodeWithReference copies a single content with a reference from the
// source cache to the destination ReferencePusher.
func copyCachedNodeWithReference(ctx context.Context, src *cas.Proxy, dst registry.ReferencePusher, desc ocispec.Descriptor, dstRef string) error {
rc, err := src.FetchCached(ctx, desc... | {
if opts.PreCopy != nil {
if err := opts.PreCopy(ctx, desc); err != nil {
if err == errSkipDesc {
return nil
}
return err
}
}
if err := doCopyNode(ctx, src, dst, desc); err != nil {
return err
}
if opts.PostCopy != nil {
return opts.PostCopy(ctx, desc)
}
return nil
} | identifier_body |
copy.go | /*
Copyright The ORAS Authors.
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
distrib... | (ctx context.Context, src content.ReadOnlyStorage, dst content.Storage, desc ocispec.Descriptor) error {
rc, err := src.Fetch(ctx, desc)
if err != nil {
return err
}
defer rc.Close()
err = dst.Push(ctx, desc, rc)
if err != nil && !errors.Is(err, errdef.ErrAlreadyExists) {
return err
}
return nil
}
// copyN... | doCopyNode | identifier_name |
copy.go | /*
Copyright The ORAS Authors.
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
distrib... |
}
return nil
}
// find successors while non-leaf nodes will be fetched and cached
successors, err := opts.FindSuccessors(ctx, proxy, desc)
if err != nil {
return err
}
successors = removeForeignLayers(successors)
if len(successors) != 0 {
// for non-leaf nodes, process successors and wait f... | {
return err
} | conditional_block |
copy.go | /*
Copyright The ORAS Authors.
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
distrib... | // reference will be passed to MapRoot, and the mapped descriptor will be
// used as the root node for copy.
MapRoot func(ctx context.Context, src content.ReadOnlyStorage, root ocispec.Descriptor) (ocispec.Descriptor, error)
}
// WithTargetPlatform configures opts.MapRoot to select the manifest whose
// platform ma... | random_line_split | |
alumniMap-controller.js | // create alumniMap controller
app.controller('alumniMap-controller', function($scope, $firebaseArray) {
$scope.id = "alumniMap";
$scope.title = "alumni map";
});
// Alumni Map js functions: ----------------------------------------------------
async function get_lat_and_lon(location) {
try {
const url =... |
function create_popup(location, alumns) {
alumns_html = 'Residents:'
alumns_html += '<br><ul class="popup">\n'
for (var i=0; i<alumns.length; i++){
alumn = alumns[i];
alumns_html += "<li>"+alumn+"</li>\n";
}
alumns_html += "</ul>"
return "<b>"+location+"</b>"+"<br>"+alumns_html;
}
... | {
let id = "12lGrmIhj2dlLHt2GNucD69IktFoOA5k9Zi9rnLR0OoI";
let bubble_list = await convert_sheet_to_bubble_list(id);
return bubble_list;
} | identifier_body |
alumniMap-controller.js | // create alumniMap controller
app.controller('alumniMap-controller', function($scope, $firebaseArray) {
$scope.id = "alumniMap";
$scope.title = "alumni map";
});
// Alumni Map js functions: ----------------------------------------------------
async function get_lat_and_lon(location) {
try {
const url =... |
bubble_list = []
for ( let [loc, alumn_list] of Object.entries(organized_by_location)) {
// let geo = await get_lat_and_lon(loc+", US");
let lat = location_dict[loc][0];
let lon = location_dict[loc][1];
bubble_list.push({location: loc, latitude: lat,
longitude: lon, radi... | }
} | random_line_split |
alumniMap-controller.js | // create alumniMap controller
app.controller('alumniMap-controller', function($scope, $firebaseArray) {
$scope.id = "alumniMap";
$scope.title = "alumni map";
});
// Alumni Map js functions: ----------------------------------------------------
async function get_lat_and_lon(location) {
try {
const url =... | (id) {
const options = {
sheetId: id,
sheetNumber: 1,
returnAllResults: true
};
return await gsheetProcessor(options, process_results);
}
async function create_bubble_list() {
let id = "12lGrmIhj2dlLHt2GNucD69IktFoOA5k9Zi9rnLR0OoI";
let bubble_list = await convert_sheet_to_bubble_list(id);
return bu... | convert_sheet_to_bubble_list | identifier_name |
alumniMap-controller.js | // create alumniMap controller
app.controller('alumniMap-controller', function($scope, $firebaseArray) {
$scope.id = "alumniMap";
$scope.title = "alumni map";
});
// Alumni Map js functions: ----------------------------------------------------
async function get_lat_and_lon(location) {
try {
const url =... |
}else{
name_list[alumn] = {
"location": place,
"timestamp": timestamp,
"year": year,
"lat": lat,
"lon":lon
};
}
}
});
organized_by_location = {};
for (let [alumn, val] of Object.entries(organized_by_alumn))... | {
name_list[alumn] = {
"location": place,
"timestamp": timestamp,
"year": year,
"lat": lat,
"lon":lon
};
} | conditional_block |
db.go | package libpack
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"sync"
"time"
git "github.com/libgit2/git2go"
)
// DB is a simple git-backed database.
type DB struct {
repo *git.Repository
commit *git.Commit
ref string
scope string
tree *git.Tree
parent *DB
l sy... | {
builder, err := repo.TreeBuilder()
if err != nil {
return nil, err
}
return builder.Write()
} | identifier_body | |
db.go | package libpack
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"sync"
"time"
git "github.com/libgit2/git2go"
)
// DB is a simple git-backed database.
type DB struct {
repo *git.Repository
commit *git.Commit
ref string
scope string
tree *git.Tree
parent *DB
l sy... | defer func() {
if err != nil {
os.RemoveAll(dir)
}
}()
}
stderr := new(bytes.Buffer)
args := []string{
"--git-dir", db.repo.Path(), "--work-tree", dir,
"checkout", head.String(), ".",
}
cmd := exec.Command("git", args...)
cmd.Stderr = stderr
if err := cmd.Run(); err != nil {
return "", fmt.Er... | if dir == "" {
dir, err = ioutil.TempDir("", "libpack-checkout-")
if err != nil {
return "", err
} | random_line_split |
db.go | package libpack
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"sync"
"time"
git "github.com/libgit2/git2go"
)
// DB is a simple git-backed database.
type DB struct {
repo *git.Repository
commit *git.Commit
ref string
scope string
tree *git.Tree
parent *DB
l sy... |
return db, nil
}
func newRepo(repo *git.Repository, ref string) (*DB, error) {
db := &DB{
repo: repo,
ref: ref,
}
if err := db.Update(); err != nil {
db.Free()
return nil, err
}
return db, nil
}
// Free must be called to release resources when a database is no longer
// in use.
// This is required in ... | {
return nil, err
} | conditional_block |
db.go | package libpack
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"sync"
"time"
git "github.com/libgit2/git2go"
)
// DB is a simple git-backed database.
type DB struct {
repo *git.Repository
commit *git.Commit
ref string
scope string
tree *git.Tree
parent *DB
l sy... | (r *git.Repository, refname string) *git.Commit {
ref, err := r.LookupReference(refname)
if err != nil {
return nil
}
commit, err := lookupCommit(r, ref.Target())
if err != nil {
return nil
}
return commit
}
// lookupCommit looks up an object at hash `id` in `repo`, and returns
// it as a git commit. If the... | lookupTip | identifier_name |
file_hook.rs | use std::ffi::CStr;
use std::ptr::null_mut;
use arrayvec::ArrayVec;
use lazy_static::lazy_static;
use libc::c_void;
use super::scr;
use super::thiscall::Thiscall;
pub fn open_file_hook(
out: *mut scr::FileHandle,
path: *const u8,
params: *const scr::OpenParams,
orig: unsafe extern fn(
*mut sc... |
unsafe extern fn read_file(file: *mut scr::FileRead, out: *mut u8, size: u32) -> u32 {
let file = (*file).inner as *mut FileAllocation;
let buf = std::slice::from_raw_parts_mut(out, size as usize);
(*file).file.read(buf)
}
unsafe extern fn skip(file: *mut scr::FileRead, size: u32) {
let file = (*file... | {
let read = (*file).read;
let vtable = (*read).vtable;
(*vtable).skip.call2(read, size)
} | identifier_body |
file_hook.rs | use std::ffi::CStr;
use std::ptr::null_mut;
use arrayvec::ArrayVec;
use lazy_static::lazy_static;
use libc::c_void;
use super::scr;
use super::thiscall::Thiscall;
pub fn open_file_hook(
out: *mut scr::FileHandle,
path: *const u8,
params: *const scr::OpenParams,
orig: unsafe extern fn(
*mut sc... | true => match c_path.iter().rev().position(|&x| x == b'.') {
Some(period) => &c_path[..c_path.len() - period - 1],
None => c_path,
},
false => c_path,
};
if let Err(_) = buffer.try_extend_from_slice(c_path_for_switched_extension) {
return None;
}
i... | let c_path_for_switched_extension = match alt_extension.is_some() { | random_line_split |
file_hook.rs | use std::ffi::CStr;
use std::ptr::null_mut;
use arrayvec::ArrayVec;
use lazy_static::lazy_static;
use libc::c_void;
use super::scr;
use super::thiscall::Thiscall;
pub fn open_file_hook(
out: *mut scr::FileHandle,
path: *const u8,
params: *const scr::OpenParams,
orig: unsafe extern fn(
*mut sc... | (buffer: &'static [u8], handle: *mut scr::FileHandle) {
let inner = Box::new(FileAllocation {
file: FileState {
buffer,
pos: 0,
},
read: scr::FileRead {
vtable: &*FILE_READ_VTABLE,
inner: null_mut(),
},
peek: scr::FilePeek {
... | memory_buffer_to_bw_file_handle | identifier_name |
evaluate.ts | import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController, AlertController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { HttpService } from './../../providers/HttpService';
import { NativeService } from './../../providers/NativeServic... | sole.info("不成功" + result)
});
}
getImg() {
if (!this.nativeService.isMobile()) {
this.addWxPicture();
}
}
onChange1(event: any) {
if(this.fileObjList.length<6){
}else{
this.nativeService.showToast("最多只能上传6张图片");
return
}
let files = event.target.files;
var fil... | }
//con | identifier_name |
evaluate.ts | import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController, AlertController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { HttpService } from './../../providers/HttpService';
import { NativeService } from './../../providers/NativeServic... |
givestaar(i) {
this.list = [{ "statue": false }, { "statue": false }, { "statue": false }, { "statue": false }, { "statue": false },];
for (var n = 0; n < (i + 1); n++) {
this.list[n].statue = true;
};
this.num = (i + 1)
if (i == 0) {
this.status = "非常差";
} else if (i == 1) {
... | {
} | identifier_body |
evaluate.ts | import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController, AlertController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { HttpService } from './../../providers/HttpService';
import { NativeService } from './../../providers/NativeServic... | // for (var i = 0; i < localIds.length; i++) {
that.WxUpLoad(localIds);
// }
// wx.getLocalImgData({
// localId: localIds, // 图片的localID
// success: function (res) {
// var localData = res.localData;
// that.localIds = localData; // localData是图... | sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
var localIds = res.localIds;
that.len = localIds.length; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 | random_line_split |
evaluate.ts | import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController, AlertController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { HttpService } from './../../providers/HttpService';
import { NativeService } from './../../providers/NativeServic... | }
}
}
}
login(filearray: any[]) {
//console.info(this.fileObjList[0])
var userInfo = {
Userid: this.userID,
goodsID: this.goodsDetail.ProductID,
Detail: this.textarea,
anonymity: 0,
Degree: this.num,
orderID: this.goodslist.ID,
file: this.fileObjLis... |
this.login(this.imgUrl);
| conditional_block |
activity.py | """
Mask R-CNN
Configurations and data loading code for MS COCO.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
------------------------------------------------------------
Usage: run from the command line as such:
# Train a new model start... |
if return_coco:
return coco
def auto_download(self, dataDir, dataType, dataYear):
"""Download the COCO dataset/annotations if requested.
dataDir: The root directory of the COCO dataset.
dataType: What to load (train, val, minival, valminusminival)
dataYear: What... | self.add_image(
"coco", image_id=i,
path=os.path.join(image_dir, coco.imgs[i]['file_name']),
width=coco.imgs[i]["width"],
height=coco.imgs[i]["height"],
annotations=coco.loadAnns(coco.getAnnIds(imgIds=[i], catIds=class_ids, iscrowd=None))) | conditional_block |
activity.py | """
Mask R-CNN
Configurations and data loading code for MS COCO.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
------------------------------------------------------------
Usage: run from the command line as such:
# Train a new model start... | # Import Mask RCNN
#sys.path.append(ROOT_DIR) # To find local version of the library
sys.path.append("third_party/Mask_RCNN/") # To find local version of the library
from mrcnn.config import Config
from mrcnn import model as modellib, utils
import common
#from train import ActivityConfig, ActivityDataset
# Path to t... | random_line_split | |
activity.py | """
Mask R-CNN
Configurations and data loading code for MS COCO.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
------------------------------------------------------------
Usage: run from the command line as such:
# Train a new model start... |
def image_reference(self, image_id):
"""Return a link to the image in the COCO Website."""
info = self.image_info[image_id]
if info["source"] == "coco":
return "http://cocodataset.org/#explore?id={}".format(info["id"])
else:
super(CocoDataset, self).image_re... | """Load instance masks for the given image.
Different datasets use different ways to store masks. This
function converts the different mask format to one format
in the form of a bitmap [height, width, instances].
Returns:
masks: A bool array of shape [height, width, instance co... | identifier_body |
activity.py | """
Mask R-CNN
Configurations and data loading code for MS COCO.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
------------------------------------------------------------
Usage: run from the command line as such:
# Train a new model start... | (self, dataDir, dataType, dataYear):
"""Download the COCO dataset/annotations if requested.
dataDir: The root directory of the COCO dataset.
dataType: What to load (train, val, minival, valminusminival)
dataYear: What dataset year to load (2014, 2017) as a string, not an integer
... | auto_download | identifier_name |
net.rs | // Copyright 2020 - developers of the `grammers` project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distr... |
}
}
| {
// `Client` is already dropped, no need to disconnect again.
} | conditional_block |
net.rs | // Copyright 2020 - developers of the `grammers` project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distr... | <R: tl::RemoteCall>(
&mut self,
request: &R,
) -> Result<R::Return, InvocationError> {
let (response, rx) = oneshot::channel();
// TODO add a test this (using handle with client dropped)
if let Err(_) = self.tx.send(Request::Rpc {
request: request.to_bytes(),
... | invoke | identifier_name |
net.rs | // Copyright 2020 - developers of the `grammers` project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distr... | }
} | } | random_line_split |
net.rs | // Copyright 2020 - developers of the `grammers` project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distr... |
/// Method implementations directly related with network connectivity.
impl Client {
/// Creates and returns a new client instance upon successful connection to Telegram.
///
/// If the session in the configuration did not have an authorization key, a new one
/// will be created and the session will b... | {
let transport = transport::Full::new();
let addr = DC_ADDRESSES[dc_id as usize];
let mut sender = if let Some(auth_key) = config.session.auth_key.as_ref() {
info!(
"creating a new sender with existing auth key to dc {} {:?}",
dc_id, addr
);
sender::connect... | identifier_body |
Props.ts | import React, { ReactNode } from 'react'
import { FormError } from '../utils/errors'
import FormDatum from '../Datum/Form'
import { ForceAdd, ObjectType, StandardProps, RegularAttributes, PartialKeys } from '../@types/common'
import { FormItemRule } from '../Rule/Props'
import { ButtonProps } from '../Button/Props'
imp... | identifier_name | ||
Props.ts | import React, { ReactNode } from 'react' | import { CardConsumerType } from '../Card/Props'
import { GetDatumFormProps } from '../Datum/Props'
export interface RuleObject {
[name: string]: FormItemRule<any> | RuleObject
}
/** ----------------fieldSet-----------------------* */
export interface FieldSetChildrenFunc<Value = any> {
(
params: {
list... | import { FormError } from '../utils/errors'
import FormDatum from '../Datum/Form'
import { ForceAdd, ObjectType, StandardProps, RegularAttributes, PartialKeys } from '../@types/common'
import { FormItemRule } from '../Rule/Props'
import { ButtonProps } from '../Button/Props' | random_line_split |
views.py | from django.http import JsonResponse
from django.contrib.auth.views import LoginView, LogoutView
from django.urls import reverse_lazy
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from res... | esponse(request.GET['dt'])
| conditional_block | |
views.py | from django.http import JsonResponse
from django.contrib.auth.views import LoginView, LogoutView
from django.urls import reverse_lazy
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from res... | identifier_name | ||
views.py | from django.http import JsonResponse
from django.contrib.auth.views import LoginView, LogoutView
from django.urls import reverse_lazy
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from res... | clients = Client.objects.all()
products = Product.objects.all()
# Добавляем новые заказы
today = date.today()
for i in range(0, orders_count):
client = random.choice(clients)
product = random.choice(products)
t_delta = timedelta(days=random.randint(0, 10))
dt_create... |
# Получаем списки клиентов и товаров | random_line_split |
views.py | from django.http import JsonResponse
from django.contrib.auth.views import LoginView, LogoutView
from django.urls import reverse_lazy
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from res... | ers(request):
count = Order.objects.all().delete()[0]
return Response(f'Удалено заказов: {count}')
# Контроллер для быстрого тестирования различных фишек django / drf
# @api_view(['GET'])
def test(request):
from django.http import HttpResponse
return HttpResponse(request.GET['dt'])
| sion])
def test_permission(request):
return Response('Тест разрешений выполнен успешно')
@api_view(['GET'])
def clear_ord | identifier_body |
main.rs | use crate::{
config::{save_config, Config},
repo::Repo,
};
use anyhow::{anyhow, bail, Context, Result};
use clap::{AppSettings, Clap};
use lazy_static::lazy_static;
use regex::Regex;
use std::env;
use std::io::{self, Read};
use url::Url;
mod config;
mod git;
mod github;
mod gitlab;
mod repo;
lazy_static! {
... | {
Git,
Saved,
}
impl ScriptSource {
fn parse(script: &str, action: ScriptAction) -> Result<ScriptSource> {
if let Some(matches) = API_SOURCE_REGEX.captures(script) {
let repo = matches
.name("alias")
.expect("No alias matched")
.as_str()
... | SourceType | identifier_name |
main.rs | use crate::{
config::{save_config, Config},
repo::Repo,
};
use anyhow::{anyhow, bail, Context, Result};
use clap::{AppSettings, Clap};
use lazy_static::lazy_static;
use regex::Regex;
use std::env;
use std::io::{self, Read};
use url::Url;
mod config;
mod git;
mod github;
mod gitlab;
mod repo;
lazy_static! {
... | SourceType::Git => git::GitRepo::from_src(&self),
};
let rref = self.rref.clone().unwrap_or("HEAD".to_owned());
Ok(repo.fetch_script(&self.script_name, &rref, fresh).await?)
}
}
async fn validate_api_repo(
uri: &str,
username: Option<String>,
password: Password,
) -... | .get(&self.repo)
.ok_or(anyhow!("Repo `{}` was not found", &self.repo))?
.box_clone(), | random_line_split |
main.rs | use crate::{
config::{save_config, Config},
repo::Repo,
};
use anyhow::{anyhow, bail, Context, Result};
use clap::{AppSettings, Clap};
use lazy_static::lazy_static;
use regex::Regex;
use std::env;
use std::io::{self, Read};
use url::Url;
mod config;
mod git;
mod github;
mod gitlab;
mod repo;
lazy_static! {
... |
RepoCommand::Remove { name } => {
if !config.repo.contains_key(&name) {
bail!("Repo `{}` was not found", &name);
}
config.repo.remove(&name);
save_config(&config)
.await
.context("Fa... | {
if config.repo.contains_key(&name) {
bail!("A repository with the name `{}` already exists", &name);
}
let password_for_parse = match (password, password_env, password_stdin) {
(Some(pass), _, _) => Password::Saved(pass),
... | conditional_block |
ledger_manager.rs | use crate::crypto::hash::{H256, Hashable};
use crate::blockchain::Blockchain;
use crate::block::Content;
use crate::transaction::SignedTransaction;
use crate::utxo::UtxoState;
use std::collections::{HashMap, HashSet};
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use std::sync::{Arc, Mutex};
use... |
}
for (proposer, votes) in num_confirmed_votes.iter() {
println!("proposer {:?} votes {}", proposer, *votes);
if *votes > (num_voter_chains / 2) {
new_leader = Some(*proposer);
break;
}
}
new_leader
}
// ne... | {
//TODO: We might also need number of voter blocks at a particular level of a voter chain
//This is not urgent as we can **assume**, there is one block at each level
let voters_info = &locked_blockchain.proposer2voterinfo[block];
if voter... | conditional_block |
ledger_manager.rs | use crate::crypto::hash::{H256, Hashable};
use crate::blockchain::Blockchain;
use crate::block::Content;
use crate::transaction::SignedTransaction;
use crate::utxo::UtxoState;
use std::collections::{HashMap, HashSet};
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use std::sync::{Arc, Mutex};
use... | {
pub last_level_processed: u32,
pub leader_sequence: Vec<H256>,
pub proposer_blocks_processed: HashSet<H256>,
pub tx_confirmed: HashSet<H256>,
pub tx_count: usize,
}
//ledger-manager will periodically loop and confirm the transactions
pub struct LedgerManager {
pub ledger_manager_state: Ledg... | LedgerManagerState | identifier_name |
ledger_manager.rs | use crate::crypto::hash::{H256, Hashable};
use crate::blockchain::Blockchain;
use crate::block::Content;
use crate::transaction::SignedTransaction;
use crate::utxo::UtxoState;
use std::collections::{HashMap, HashSet};
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use std::sync::{Arc, Mutex};
use... |
fn get_leader_sequence(&mut self) -> Vec<H256> {
let locked_blockchain = self.blockchain.lock().unwrap();
let mut leader_sequence: Vec<H256> = vec![];
//TODO: This is a workaround for now till we have some DS which asserts that
//all voter chains at a particular level has... | {
loop{
//Step 1
//let leader_sequence = self.get_leader_sequence();
//This one uses the algorithm described in Prism Paper
let leader_sequence = self.get_confirmed_leader_sequence();
//Step 2
let tx_sequence = sel... | identifier_body |
ledger_manager.rs | use crate::crypto::hash::{H256, Hashable};
use crate::blockchain::Blockchain;
use crate::block::Content;
use crate::transaction::SignedTransaction;
use crate::utxo::UtxoState;
use std::collections::{HashMap, HashSet};
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use std::sync::{Arc, Mutex};
use... | }
fn confirm_transactions(&mut self, tx_sequence: &Vec<SignedTransaction>) {
self.ledger_manager_state.tx_count += tx_sequence.len();
// println!("Number of transactions considered yet {}", self.ledger_manager_state.tx_count);
let mut locked_utxostate = self.utxo_state.lock().unwrap();
... | self.ledger_manager_state.proposer_blocks_processed.insert(*leader);
}
tx_sequence | random_line_split |
PredictionRuntimeInspector.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... |
def _runButton_fired(self):
self.pause = False
wx.CallLater(self.runInterval, self._run)
def _pauseButton_fired(self):
#from dbgp.client import brk; brk(port=9011)
self.pause = True
#wx.CallLater(self.runInterval, self._pause)
def _stepButton_fired(self):
wx.CallLater(self.runInterval... | try:
self._setProgress()
except:
# may fail when switching from training to inference
from dbgp.client import brk; brk(port=9011)
pass | conditional_block |
PredictionRuntimeInspector.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... | pauseTarget = Str
backwardButton = Button('Back',
image=ImageResource(getNTAImage('backward_36_26')))
runButton = Button('Run',
image=ImageResource(getNTAImage('play_36_26')))
pauseButton = Button('Pause',
image=ImageResource(... | targetButtonLabel = Str(targetButtonLabels[0])
customTargetButton = Button('Custom...') | random_line_split |
PredictionRuntimeInspector.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... |
def _stopButton_fired(self):
#self.stopping = True
wx.CallLater(self.runInterval, self.stop) | wx.CallLater(self.runInterval, self._step) | identifier_body |
PredictionRuntimeInspector.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... | (self):
d = self.experiment.description
for name in 'spTrain', 'tpTrain', 'classifierTrain', 'infer':
if not name in d:
continue
phase = d[name]
if len(phase) > 0:
assert self.onPhaseSetup not in phase[0]['setup']
phase[0]['setup'].append(self.onPhaseSetup)
phas... | _registerCallbacks | identifier_name |
04-aruco_calibration.py | import numpy as np
import cv2
import argparse
import sys
import pandas as pd
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# define names of each possible ArUco tag OpenCV supports
ARUCO_DICT = {
"DICT_4X4_50": cv2.aruco.DICT_4X4_50,
"DICT_4X4_100": cv2.aruco.DICT_4X4_100,
"DI... |
def capture_img(image_dir, image_name, image_format):
cam = cv2.VideoCapture(1)
cam.set(3,3840)
cam.set(4,2160)
# cam.set(3,640)
# cam.set(4,480)
print("Hit SPACE key to capture, Hit ESC key to continue")
img_name = image_dir + "/" + image_name + "." + image_format
cv2.namedWindow("... | """ Loads camera matrix and distortion coefficients. """
# FILE_STORAGE_READ
cv_file = cv2.FileStorage(path, cv2.FILE_STORAGE_READ)
# note we also have to specify the type to retrieve other wise we only get a
# FileNode object back instead of a matrix
camera_matrix = cv_file.getNode("K").mat()
... | identifier_body |
04-aruco_calibration.py | import numpy as np
import cv2
import argparse
import sys
import pandas as pd
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# define names of each possible ArUco tag OpenCV supports
ARUCO_DICT = {
"DICT_4X4_50": cv2.aruco.DICT_4X4_50,
"DICT_4X4_100": cv2.aruco.DICT_4X4_100,
"DI... |
elif k%256 == 32:
# SPACE pressed
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
cam.release()
cv2.destroyAllWindows()
return img
def save_coefficients(R_op, R_po, T_op, T_po, RMSE, path):
""" Save the camera matrix and the distortion ... | print("Escape hit, closing...")
img = cv2.imread(img_name)
break | conditional_block |
04-aruco_calibration.py | import numpy as np
import cv2
import argparse
import sys
import pandas as pd
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# define names of each possible ArUco tag OpenCV supports
ARUCO_DICT = {
"DICT_4X4_50": cv2.aruco.DICT_4X4_50,
"DICT_4X4_100": cv2.aruco.DICT_4X4_100,
"DI... | (R_op, R_po, T_op, T_po, RMSE, path):
""" Save the camera matrix and the distortion coefficients to given path/file. """
cv_file = cv2.FileStorage(path, cv2.FILE_STORAGE_WRITE)
# Rotation matrix
print("R_op: " + str(R_op))
cv_file.write("R_op", R_op )
print("R_po: " + str(R_po))
cv_fi... | save_coefficients | identifier_name |
04-aruco_calibration.py | import numpy as np
import cv2
import argparse
import sys
import pandas as pd
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# define names of each possible ArUco tag OpenCV supports
ARUCO_DICT = {
"DICT_4X4_50": cv2.aruco.DICT_4X4_50,
"DICT_4X4_100": cv2.aruco.DICT_4X4_100,
"DI... |
frame = capture_img(image_dir, image_name, image_format)
# try undistorted image
# h, w = frame.shape[:2]
# newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))
# undistort
# # frame = cv2.undistort(frame, mtx, dist, None, newcameramtx)
frame = cv2.undistort(f... | random_line_split | |
huff_algorithm.py | # -*- coding: utf-8 -*-
#############################################################################
# @file huff_algorithm.py
# @author J.Kiec
# @version 1.0
# @date 03.05.2014
# @brief Huffman's Code operational code
#
#############################################################################
import py... | (self):
if (self.lvl ==None):
return "\t%.3d=%c id:%0.3d : %.3f\r\n" % (self.symbol, self.symbol,\
self.id,self.prob)
else :
return "\t%.3d=%c id:%0.3d : %.3f (%d)\r\n" % (self.symbol,self.symbol,\
self.id,self.prob, self.lvl)
# @brief Binary tree leaf constructor specific class prototype contains symbol_v... | __repr__ | identifier_name |
huff_algorithm.py | # -*- coding: utf-8 -*-
#############################################################################
# @file huff_algorithm.py
# @author J.Kiec
# @version 1.0
# @date 03.05.2014
# @brief Huffman's Code operational code
#
#############################################################################
import py... |
def fLvlUpdate(CurrentNode, CurrentLevel):
CurrentNode.UpdateLvl(CurrentLevel)
if ( CurrentNode.__class__.__name__ == 'TBinTree_Node'):
fLvlUpdate(CurrentNode.b_zero,CurrentLevel+1)
fLvlUpdate(CurrentNode.b_one,CurrentLevel+1)
################################################################################... | print "Generating Soure tree implementing bottom-up algorithm."
print LeavesList.__class__.__name__
print LeavesList
while (len(LeavesList)>1):
for leafIndex in range(0,len(LeavesList)-1) :
if (LeavesList[leafIndex].prob>LeavesList[leafIndex+1].prob):
temp = LeavesList.pop(leafIndex)
LeavesList.insert(l... | identifier_body |
huff_algorithm.py | # -*- coding: utf-8 -*-
#############################################################################
# @file huff_algorithm.py
# @author J.Kiec
# @version 1.0
# @date 03.05.2014
# @brief Huffman's Code operational code
#
#############################################################################
import py... |
def Pop2Prob(self): # takes total population into consideration and tranlates it into probability
for x in range(0,len(self.pSymbolsList_sorted)):
tempItem = list(self.pSymbolsList_sorted.pop(x))
tempItem[1]=float(tempItem[1])/self.pPopulation
print tempItem
self.pSymbolsList_sorted.insert(x,tempItem)
... | for key, value in sorted(self.pSymbolsDict.iteritems(), key=lambda (k,v): (v,k),reverse=False):
self.pSymbolsList_sorted.append((key,value)) | random_line_split |
huff_algorithm.py | # -*- coding: utf-8 -*-
#############################################################################
# @file huff_algorithm.py
# @author J.Kiec
# @version 1.0
# @date 03.05.2014
# @brief Huffman's Code operational code
#
#############################################################################
import py... |
elif (CodedMsg[0]=='1') :
return fDecodeBit(CurrentNode.b_one, CodedMsg[1:])
else :
print "DecodeError 2 Message!"
else:
print "DecodeError 1 Message!"
# @brief Indepednent function with implementation of suboptimal top-down method of source tree generation
# algorithm
# @param List of BTLeaves re... | return fDecodeBit(CurrentNode.b_zero, CodedMsg[1:]) | conditional_block |
rtc_api.rs | #![allow(dead_code)]
use bitflags::*;
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub enum Weekday {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
impl Default for Weekday {
fn default() -> Self { Weekday::Sunday }
}
#[derive(Deb... | (settings: &[u8]) -> Option<u64> {
const CTL3: usize = 0;
const SECS: usize = 1;
const MINS: usize = 2;
const HOURS: usize = 3;
const DAYS: usize = 4;
// note 5 is skipped - this is weekdays, and is unused
const MONTHS: usize = 6;
const YEARS: usize = 7;
if ((settings[CTL3] & 0xE0) !... | rtc_to_seconds | identifier_name |
rtc_api.rs | #![allow(dead_code)]
use bitflags::*;
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub enum Weekday {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
impl Default for Weekday {
fn default() -> Self { Weekday::Sunday }
}
#[derive(Deb... |
pub fn to_binary(bcd: u8) -> u8 {
(bcd & 0xf) + ((bcd >> 4) * 10)
} | } | random_line_split |
mod.rs | //! Extensions to [`Target`](super::Target) which add support for various
//! subsets of the GDB Remote Serial Protocol.
//!
//! ### Note: Missing Protocol Extensions
//!
//! `gdbstub`'s development is guided by the needs of its contributors, with
//! new features being added on an "as-needed" basis.
//!
//! If there's... | //! methods!
//!
//! Aside from the cognitive complexity of having so many methods on a single
//! trait, this approach had numerous other drawbacks as well:
//!
//! - Implementations that did not implement all available protocol extensions
//! still had to "pay" for the unused packet parsing/handler code, resultin... | //! to the extreme, would have resulted in literally _hundreds_ of associated | random_line_split |
main.rs | extern crate cgmath;
extern crate euclid;
extern crate gleam;
extern crate glutin;
extern crate image;
extern crate lodepng;
extern crate offscreen_gl_context;
#[macro_use]
extern crate vulkano;
extern crate vulkano_win;
extern crate winit;
use euclid::Size2D;
use gleam::gl;
use offscreen_gl_context::{ColorAttachmentT... | gl_Position = scale * vec4(0.5 * a_Pos, 0.0, 1.0);
}
";
const FS_SHADER: &'static str = "
#version 150 core
in vec4 v_Color;
out vec4 Target0;
void main() {
Target0 = v_Color;
}
";
const VERTICES: &'static [[f32;2];3] = &[
[-1.0, -0.57],
[ 1.0, -0.57],
... | v_Color = vec4(a_Color, 1.0); | random_line_split |
main.rs | extern crate cgmath;
extern crate euclid;
extern crate gleam;
extern crate glutin;
extern crate image;
extern crate lodepng;
extern crate offscreen_gl_context;
#[macro_use]
extern crate vulkano;
extern crate vulkano_win;
extern crate winit;
use euclid::Size2D;
use gleam::gl;
use offscreen_gl_context::{ColorAttachmentT... | () -> GlHandles {
GlHandles {
vao: Cell::new(0 as gl::GLuint),
vbos: Cell::new([0,0]),
program: Cell::new(0 as gl::GLuint),
scale: Cell::new(0.0),
}
}
}
const CLEAR_COLOR: (f32, f32, f32, f32) = (0.0, 0.2, 0.3, 1.0);
const WIN_WIDTH: i32 = 256;
const ... | new | identifier_name |
main.rs | extern crate cgmath;
extern crate euclid;
extern crate gleam;
extern crate glutin;
extern crate image;
extern crate lodepng;
extern crate offscreen_gl_context;
#[macro_use]
extern crate vulkano;
extern crate vulkano_win;
extern crate winit;
use euclid::Size2D;
use gleam::gl;
use offscreen_gl_context::{ColorAttachmentT... |
}
fn compile_shaders(handles: &GlHandles) {
handles.program.set(gl::create_program());
if handles.program.get() == (0 as gl::GLuint) {
panic!("Failed to create shader program");
}
add_shader(handles.program.get(), VS_SHADER, gl::VERTEX_SHADER);
add_shader(handles.program.get(), FS_SHADER,... | {
if !log.is_empty() {
println!("Warnings detected on shader:\n{}", log);
}
gl::attach_shader(program, id);
} | conditional_block |
main.go | /*
* Copyright (c) 2013 Ihsan Junaidi Ibrahim <ihsan.junaidi@gmail.com>
*/
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
type RequestMsg struct {
Id int64
UserId int64
MsgId int64
Command... | {
var str = fmt.Sprintf("%v-%v\nusage: %v [-d] [-h] [-c config file]\n",
APPNAME, APPVER, APPNAME)
fmt.Fprintf(os.Stderr, str)
os.Exit(1)
} | identifier_body | |
main.go | /*
* Copyright (c) 2013 Ihsan Junaidi Ibrahim <ihsan.junaidi@gmail.com>
*/
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
type RequestMsg struct {
Id int64
UserId int64
MsgId int64
Command... | () (err error) {
var data = &RebanaRequestMsg{UserId: 102, Command: "server-info",
Data: app.HostName}
var buf, _ = json.Marshal(data)
var url = app.RebanaUrl + "/v/info"
var rd = bytes.NewReader(buf)
var req *http.Request
if req, err = http.NewRequest("POST", url, rd); err != nil {
return
}
var loc = &... | serverInfo | identifier_name |
main.go | /*
* Copyright (c) 2013 Ihsan Junaidi Ibrahim <ihsan.junaidi@gmail.com>
*/
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
type RequestMsg struct {
Id int64
UserId int64
MsgId int64
Command... | Opt string
}
type IdList struct {
Id int64
Entry []Id
}
type ServerInfo struct {
Id int64
TunSrc string
PpPrefix string
RtPrefix string
Session []Session
}
type Session struct {
Id int64
Dst string
Idx int64
}
type BindInfo struct {
Host string
Port string
}
type AppConfig struct {
Hos... | Id int64
ErrNo int | random_line_split |
main.go | /*
* Copyright (c) 2013 Ihsan Junaidi Ibrahim <ihsan.junaidi@gmail.com>
*/
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
type RequestMsg struct {
Id int64
UserId int64
MsgId int64
Command... |
}
func usage() {
var str = fmt.Sprintf("%v-%v\nusage: %v [-d] [-h] [-c config file]\n",
APPNAME, APPVER, APPNAME)
fmt.Fprintf(os.Stderr, str)
os.Exit(1)
}
| {
event(lognotice, li, "Terminating..")
os.Remove(PIDFILE)
os.Exit(0)
} | conditional_block |
digits_DG_Gphi_projection.py | # coding: utf-8
# In[ ]:
from torch.utils.data import Dataset, DataLoader
import os
import torchvision
import torch
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet18, alexnet
import PIL
from torchlars import LARS
import cv2
impor... | #print(h.shape)
h = h.view(-1, 1, 16,16)
#print(h.shape)
h=h.detach()
recon_batch, mu, logvar = vae(h)
loss = loss_function(recon_batch, h, mu, logvar)
loss.backward()
train_loss += loss.item()
VAEoptim.step()
print('====> Epoch: {} Average l... | VAEoptim.zero_grad()
h = digits_fnet(image_batch).to(dev) | random_line_split |
digits_DG_Gphi_projection.py |
# coding: utf-8
# In[ ]:
from torch.utils.data import Dataset, DataLoader
import os
import torchvision
import torch
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet18, alexnet
import PIL
from torchlars import LARS
import cv2
impo... | (nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class UnFlatten(nn.Module):
def forward(self, input, size=64):
return input.view(input.size(0), size, 1, 1)
class VAE_Digits(nn.Module):
def __init__(self, image_channels=1, h_dim=64, z_dim=32):
su... | Flatten | identifier_name |
digits_DG_Gphi_projection.py |
# coding: utf-8
# In[ ]:
from torch.utils.data import Dataset, DataLoader
import os
import torchvision
import torch
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet18, alexnet
import PIL
from torchlars import LARS
import cv2
impo... |
else:
self.transform = transform
# make a list of all the files in the root_dir
# and read the labels
self.img_files = []
self.labels = []
self.domain_labels = []
for domain in self.domains:
for category in self.categories:
for image in os.listdir(self.root_dir+domain+'/... | self.transform = transforms.ToTensor() | conditional_block |
digits_DG_Gphi_projection.py |
# coding: utf-8
# In[ ]:
from torch.utils.data import Dataset, DataLoader
import os
import torchvision
import torch
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet18, alexnet
import PIL
from torchlars import LARS
import cv2
impo... |
class ConvNet(Backbone):
def __init__(self, c_hidden=64):
super().__init__()
self.conv1 = Convolution(3, c_hidden)
self.conv2 = Convolution(c_hidden, c_hidden)
self.conv3 = Convolution(c_hidden, c_hidden)
self.conv4 = Convolution(c_hidden, c_hidden)
self._out_fea... | def __init__(self, c_in, c_out):
super().__init__()
self.conv = nn.Conv2d(c_in, c_out, 3, stride=1, padding=1)
self.relu = nn.ReLU(True)
def forward(self, x):
return self.relu(self.conv(x)) | identifier_body |
script.js | document.addEventListener('DOMContentLoaded', function(){
$('body').on('click','[data-anchor=true]', function() {
var elementClick = $(this).attr("href")
var destination = ($(elementClick).offset().top - 74);
jQuery("html:not(:animated),body:not(:animated)").animate({
scrollTop:... | if($('div').is('.post-nav-container')){
if($(window).width() > 768){
$(".sp-text-col h2,.sp-text-col h3,.sp-text-col h4").each(function(i) {
var current = $(this);
current.attr("id", "title" + i);
$(".sp-links .post-nav-container").append("<a calass='post-nav-link' id='link" + i + "' href='#title" + i + "... | //post-nav | random_line_split |
script.js | document.addEventListener('DOMContentLoaded', function(){
$('body').on('click','[data-anchor=true]', function() {
var elementClick = $(this).attr("href")
var destination = ($(elementClick).offset().top - 74);
jQuery("html:not(:animated),body:not(:animated)").animate({
scrollTop:... | () {
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
return 100 - widthWithScroll;
};
//tabs
$(".tab-t").on("click",function(e){
$('.tab-t').removeClass('tab-t... | getScrollBarWidth | identifier_name |
script.js | document.addEventListener('DOMContentLoaded', function(){
$('body').on('click','[data-anchor=true]', function() {
var elementClick = $(this).attr("href")
var destination = ($(elementClick).offset().top - 74);
jQuery("html:not(:animated),body:not(:animated)").animate({
scrollTop:... |
$(".close-modal, .modal-overley").on("click",function(e){
hideModal()
})
$(document).keydown(function(eventObject){
if (eventObject.which == 27)
hideModal()
});
$('[data-modal-open]').on("click",function(e){
event.preventDefault()
$('[data-modal='+ $(this).attr('data-modal-open') +']').addClass('visible-modal'... | {
$('[data-modal]').removeClass('visible-modal');
$('.modal-overley').removeClass('modal-overley-show');
setTimeout(function(){
$('body').removeClass('stop-scroll');
$('body').css('padding-right',0+'px');
$('.site-header').css('padding-right',0+'px')
}, 300);
} | identifier_body |
script.js | document.addEventListener('DOMContentLoaded', function(){
$('body').on('click','[data-anchor=true]', function() {
var elementClick = $(this).attr("href")
var destination = ($(elementClick).offset().top - 74);
jQuery("html:not(:animated),body:not(:animated)").animate({
scrollTop:... |
if(curentStage==2){
$('.c-q-c-c-item-selected').each(function(i) {
var values = $('[data-field-id=field--2]').val();
values += $(this).find('.c-q-c-c-item-descr').text();
$('[data-field-id=field--2]').val(values.replace(/\s/g, '')+',');
});
}
if(curentStage==3){
$('[data-stage='+curentStage+'] .c-check input:ch... | {
$('[data-stage='+curentStage+'] .c-check input:checked').each(function(i) {
var values = $('[data-field-id=field--1]').val();
values += $(this).parent('.c-check').text();
$('[data-field-id=field--1]').val(values.replace(/\s/g, '')+',');
});
} | conditional_block |
CORAL_train.py | # -*- coding: utf-8 -*-
# https://github.com/Raschka-research-group/coral-cnn/tree/master/model-code/resnet34
from absl import flags, app
from Rank_consistent_model_fix import *
from Rank_consistent_model import *
from random import shuffle, random
import tensorflow as tf
import numpy as np
# import cv2
import os
impo... |
@tf.function
def train_step(model, images, levels, imp):
with tf.GradientTape() as tape:
logits, probs = run_model(model, images)
#total_loss = (-tf.reduce_sum((tf.nn.log_softmax(logits, axis=2)[:,:,1]*levels + tf.nn.log_softmax(logits, axis=2)[:,:,0]*(1-levels))*imp, 1))
... | logits, probs = model(images, training=True)
return logits, probs | identifier_body |
CORAL_train.py | # -*- coding: utf-8 -*-
# https://github.com/Raschka-research-group/coral-cnn/tree/master/model-code/resnet34
from absl import flags, app
from Rank_consistent_model_fix import *
from Rank_consistent_model import *
from random import shuffle, random
import tensorflow as tf
import numpy as np
# import cv2
import os
impo... |
if __name__ == '__main__':
app.run(main)
| data_name = np.loadtxt(FLAGS.test_txt, dtype='<U100', skiprows=0, usecols=0)
data_name = [FLAGS.test_img + data_name_ for data_name_ in data_name]
data_label = np.loadtxt(FLAGS.txt_path, dtype=np.float32, skiprows=0, usecols=1)
data_generator = tf.data.Dataset.from_tensor_slices((data_name, dat... | conditional_block |
CORAL_train.py | # -*- coding: utf-8 -*-
# https://github.com/Raschka-research-group/coral-cnn/tree/master/model-code/resnet34
from absl import flags, app
from Rank_consistent_model_fix import *
from Rank_consistent_model import *
from random import shuffle, random
import tensorflow as tf
import numpy as np
# import cv2
import os
impo... | (model, images):
logits, probs = model(images, training=True)
return logits, probs
@tf.function
def train_step(model, images, levels, imp):
with tf.GradientTape() as tape:
logits, probs = run_model(model, images)
#total_loss = (-tf.reduce_sum((tf.nn.log_softmax(logits, axis=2)[:,:,1]*... | run_model | identifier_name |
CORAL_train.py | # -*- coding: utf-8 -*-
# https://github.com/Raschka-research-group/coral-cnn/tree/master/model-code/resnet34
from absl import flags, app
from Rank_consistent_model_fix import *
from Rank_consistent_model import *
from random import shuffle, random
import tensorflow as tf
import numpy as np
# import cv2
import os
impo... |
val_idx = len(val_img) // 1
val_it = iter(val_data_generator)
AE = 0
for i in range(val_idx):
img, lab = next(val_it)
pre_age = test_MAE(train_model, img, lab)
... | val_data_generator = val_data_generator.prefetch(tf.data.experimental.AUTOTUNE) | random_line_split |
sales-component.component.ts | import { Component, ElementRef, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { fuseAnimations } from '@fuse/animations';
import { TranslateService } from '@ngx-translate/core... | {
// 0 means Erkek, 1 means Kadin
return gender ? "Kadın" : "Erkek"
}
openSatisDialog() {
const dialogRef = this.dialog.open(PaymentScreenComponent, {
height: '600px',
width: '800px',
data: { Total: this.ProductsToSellTotalPrice = this.ProductsToSellDataSource.map(t => t.SellingPrice)... | : number) | identifier_name |
sales-component.component.ts | import { Component, ElementRef, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { fuseAnimations } from '@fuse/animations';
import { TranslateService } from '@ngx-translate/core... | : void {
this.unsubscribe.forEach(sb => sb.unsubscribe());
}
InitilizeProductAndPriceForm() {
this.ProductAndPriceFormGroup = this.fb.group({
ProductBarcode: ['', Validators.compose([
Validators.required
])
],
SellingPrice: ['', Validators.compose([
Validators.requi... | roy() | identifier_body |
sales-component.component.ts | import { Component, ElementRef, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { fuseAnimations } from '@fuse/animations';
import { TranslateService } from '@ngx-translate/core... | this.isProductExist = false;
this.ProductAndPriceFormGroup.controls.SellingPrice.setValue(0);
}
}
}
// onToolbarPreparing(e) {
// e.toolbarOptions.items.unshift(
// {
// location: "before",
// template: "calendar"
// },
// {
// location: "befo... | asCampaign = false;
}
} else {
| conditional_block |
sales-component.component.ts | import { Component, ElementRef, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { fuseAnimations } from '@fuse/animations';
import { TranslateService } from '@ngx-translate/core... | hasCampaign = false;
isProductCountEnough = false;
async productCodeFocusOut() {
this.PriceInput.nativeElement.focus();
const productCode = this.ProductAndPriceFormGroup.controls.ProductBarcode.value;
if (productCode && productCode.length == 12) {
let res: UIResponse<ProductView> = await this.no... |
isProductExist = false;
lowProductCount = false; | random_line_split |
doc_zh_CN.go | // Copyright The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ingore
// Package rsa implements RSA encryption as specified in PKCS#1.
// rsa包实现了PKCS#1规定的RSA加密算法。
package rsa
const (
// PSSSaltLengthAuto causes the... | func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out []byte, err error)
// DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding
// scheme from PKCS#1 v1.5. If rand != nil, it uses RSA blinding to avoid timing
// side-channel attacks. It returns an error if the ciphertext... | // attacks.
// DecryptPKCS1v15使用PKCS#1
// v1.5规定的填充方案和RSA算法解密密文。如果random不是nil,函数会注意规避时间侧信道攻击。 | random_line_split |
doc_zh_CN.go | // Copyright The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ingore
// Package rsa implements RSA encryption as specified in PKCS#1.
// rsa包实现了PKCS#1规定的RSA加密算法。
package rsa
const (
// PSSSaltLengthAuto causes the... | length
// or if the ciphertext is greater than the public modulus. Otherwise, no error is
// returned. If the padding is valid, the resulting plaintext message is copied
// into key. Otherwise, key is unchanged. These alternatives occur in constant
// time. It is intended that the user of this function generate a rando... | t is the wrong | identifier_name |
types.rs | extern crate "rustc-serialize" as rustc_serialize;
extern crate uuid;
use uuid::Uuid;
use rustc_serialize::{json, Encodable, Decodable};
use rustc_serialize::base64::{ToBase64, FromBase64, Config, CharacterSet, Newline};
use types::NodeState::{Leader, Follower, Candidate};
use types::TransactionState::{Polling, Accept... | <T: Encodable + Decodable + Send + Clone> {
current_term: u64,
voted_for: Option<u64>, // request_vote cares if this is `None`
log: File,
last_index: u64, // The last index of the file.
last_term: u64, // The last index of the file.
marker: marker::PhantomData<T>, /... | PersistentState | identifier_name |
types.rs | extern crate "rustc-serialize" as rustc_serialize;
extern crate uuid;
use uuid::Uuid;
use rustc_serialize::{json, Encodable, Decodable};
use rustc_serialize::base64::{ToBase64, FromBase64, Config, CharacterSet, Newline};
use types::NodeState::{Leader, Follower, Candidate};
use types::TransactionState::{Polling, Accept... | // Add 2,3 again. (4 should be purged)
assert_eq!(state.append_entries(1, 2,
vec![(2, "Two".to_string()),
(3, "Three".to_string())]),
Ok(()));
assert_eq!(state.get_last_index(), 3);
fs::remove_file(&path.clone());
} | (3, "Three".to_string()),
(4, "Four".to_string())]),
Ok(()));
assert_eq!(state.get_last_index(), 4); | random_line_split |
types.rs | extern crate "rustc-serialize" as rustc_serialize;
extern crate uuid;
use uuid::Uuid;
use rustc_serialize::{json, Encodable, Decodable};
use rustc_serialize::base64::{ToBase64, FromBase64, Config, CharacterSet, Newline};
use types::NodeState::{Leader, Follower, Candidate};
use types::TransactionState::{Polling, Accept... | ;
self.last_term = last_term;
Ok(())
}
fn encode(entry: T) -> String {
let json_encoded = json::encode(&entry)
.unwrap(); // TODO: Don't unwrap.
json_encoded.as_bytes().to_base64(Config {
char_set: CharacterSet::UrlSafe,
newline: Newline::LF,
... | { prev_log_index + number as u64 } | conditional_block |
sync.go | /*
Copyright 2011 Google Inc.
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
di... |
bytesCopied := int64(0) // TODO: data race, accessed without locking in statusFunc below.
set(statusFunc(func() string {
return fmt.Sprintf("copying: %d/%d bytes", bytesCopied, sb.Size)
}))
newsb, err := sh.to.ReceiveBlob(sb.Ref, readerutil.CountingReader{rc, &bytesCopied})
if err != nil {
return errorf("des... | {
return errorf("source fetch size mismatch: get=%d, enumerate=%d", fromSize, sb.Size)
} | conditional_block |
sync.go | /*
Copyright 2011 Google Inc.
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
di... | if sh.idle {
return
}
fmt.Fprintf(rw, "<h2>Stats:</h2><ul>")
fmt.Fprintf(rw, "<li>Blobs copied: %d</li>", sh.totalCopies)
fmt.Fprintf(rw, "<li>Bytes copied: %d</li>", sh.totalCopyBytes)
if !sh.recentCopyTime.IsZero() {
fmt.Fprintf(rw, "<li>Most recent copy: %s</li>", sh.recentCopyTime.Format(time.RFC3339))
... | fmt.Fprintf(rw, "<h1>%s to %s Sync Status</h1><p><b>Current status: </b>%s</p>",
sh.fromName, sh.toName, html.EscapeString(sh.status)) | random_line_split |
sync.go | /*
Copyright 2011 Google Inc.
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
di... | (ctx *context.Context, src blobserver.BlobEnumerator) func(chan<- blob.SizedRef, <-chan struct{}) error {
return func(dst chan<- blob.SizedRef, intr <-chan struct{}) error {
return blobserver.EnumerateAll(ctx, src, func(sb blob.SizedRef) error {
select {
case dst <- sb:
case <-intr:
return errors.New("i... | blobserverEnumerator | identifier_name |
sync.go | /*
Copyright 2011 Google Inc.
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
di... |
func (sh *SyncHandler) enumerateQueuedBlobs(dst chan<- blob.SizedRef, intr <-chan struct{}) error {
defer close(dst)
it := sh.queue.Find("", "")
for it.Next() {
br, ok := blob.Parse(it.Key())
size, err := strconv.ParseInt(it.Value(), 10, 64)
if !ok || err != nil {
sh.logf("ERROR: bogus sync queue entry: %... | {
return func(dst chan<- blob.SizedRef, intr <-chan struct{}) error {
return blobserver.EnumerateAll(ctx, src, func(sb blob.SizedRef) error {
select {
case dst <- sb:
case <-intr:
return errors.New("interrupted")
}
return nil
})
}
} | identifier_body |
feature_table.rs | //! # Feature Table
//!
//! Data model and parsers for the DDBJ/ENA/GenBank Feature Table.
//!
//! See: http://www.insdc.org/files/feature_table.html
use nom::{
IResult,
branch::{
alt,
},
bytes::complete::{
tag,
take_while_m_n,
take_while,
take_while1,
},
character::{
is_alphanumeri... | expect(
"340..565",
LocOp::Loc(Loc::Local(Local::Span {
from: Position::Point(Point(340)),
to: Position::Point(Point(565)),
before_from: false,
after_to: false
})));
expect(
"<345..500",
LocOp::Loc(Loc::Local(Local::Span {
from: Position::... | random_line_split | |
feature_table.rs | //! # Feature Table
//!
//! Data model and parsers for the DDBJ/ENA/GenBank Feature Table.
//!
//! See: http://www.insdc.org/files/feature_table.html
use nom::{
IResult,
branch::{
alt,
},
bytes::complete::{
tag,
take_while_m_n,
take_while,
take_while1,
},
character::{
is_alphanumeri... |
}
#[derive(Debug, PartialEq, Eq)]
pub enum Loc {
Remote { within: String, at: Local },
Local(Local)
}
impl <'a, E : ParseError<&'a str>> Nommed<&'a str, E> for Loc {
fn nom(input: &'a str) -> IResult<&'a str, Loc, E> {
let parse_accession = take_while1(|c| {
let b = c as u8;
is_alphanumeric(b) || b ==... | {
let parse_within = map(
tuple((Point::nom, tag("."), Point::nom)),
|(from, _, to)| Local::Within { from, to });
let parse_span = map(
tuple((
opt(tag("<")), Position::nom, tag(".."), opt(tag(">")), Position::nom)),
|(before_from, from, _, after_to, to)| Local::Span {
f... | identifier_body |
feature_table.rs | //! # Feature Table
//!
//! Data model and parsers for the DDBJ/ENA/GenBank Feature Table.
//!
//! See: http://www.insdc.org/files/feature_table.html
use nom::{
IResult,
branch::{
alt,
},
bytes::complete::{
tag,
take_while_m_n,
take_while,
take_while1,
},
character::{
is_alphanumeri... | {
key: String,
location: LocOp,
qualifiers: Vec<Qualifier>
}
// impl <'a, E : ParseError<&'a str>> Nommed<&'a str, E> for FeatureRecord {
// fn nom(input: &'a str) -> IResult<&'a str, FeatureRecord, E> {
// }
// }
/// An ID that's valid within the feature table.
///
/// This is:
/// * At least one let... | FeatureRecord | identifier_name |
room_list_item.go | package main
import (
"fmt"
"gopp"
"log"
"runtime"
"strings"
"time"
"go-purple/msgflt-prpl/bridges"
thscli "tox-homeserver/client"
thscom "tox-homeserver/common"
store "tox-homeserver/store"
"tox-homeserver/thspbs"
humanize "github.com/dustin/go-humanize"
"github.com/kitech/qt.go/qtcore"
"github.com/ki... | g string, tm time.Time, eventId int64) {
if this.LastMsgEventId > eventId {
return
}
this.LastMsgEventId = eventId
refmter := func(s string) string {
// s = gopp.StrSuf4ui(s, 36)
return strings.Replace(s, "\n", " ", -1)
}
cmsg := refmter(msg)
this.Label_3.SetText(cmsg)
this.Label_3.SetToolTip(msg)
SetQL... | ).Seconds())
cqzone := time.FixedZone("Chongqing", secondsEastOfUTC)
time.Local = cqzone
}
}
// 两类时间,server time, client time
func (this *RoomListItem) SetLastMsg(ms | identifier_body |
room_list_item.go | package main
import (
"fmt"
"gopp"
"log"
"runtime"
"strings"
"time"
"go-purple/msgflt-prpl/bridges"
thscli "tox-homeserver/client"
thscom "tox-homeserver/common"
store "tox-homeserver/store"
"tox-homeserver/thspbs"
humanize "github.com/dustin/go-humanize"
"github.com/kitech/qt.go/qtcore"
"github.com/ki... |
onMousePress := func(event *qtgui.QMouseEvent) {
uictx.gtreco.onMousePress(this, event)
// log.Println(event)
if event.Button() == qtcore.Qt__LeftButton {
for _, room := range uictx.ctitmdl {
if room != this {
room.SetPressState(false)
}
}
this.SetPressState(true)
}
}
onMouseRelease :=... | this.ToolButton_2.SetMouseTracking(true)
w := this.ContactItemView
w.SetMouseTracking(true) | random_line_split |
room_list_item.go | package main
import (
"fmt"
"gopp"
"log"
"runtime"
"strings"
"time"
"go-purple/msgflt-prpl/bridges"
thscli "tox-homeserver/client"
thscom "tox-homeserver/common"
store "tox-homeserver/store"
"tox-homeserver/thspbs"
humanize "github.com/dustin/go-humanize"
"github.com/kitech/qt.go/qtcore"
"github.com/ki... | IdentIcon(frndpk)
this.ToolButton_2.SetIcon(this.cticon)
uictx.msgwin.SetIconForItem(this)
}
func (this *RoomListItem) SetAvatar(idico *qtgui.QIcon) {
this.cticon = idico
this.ToolButton_2.SetIcon(this.cticon)
uictx.msgwin.SetIconForItem(this)
}
func (this *RoomListItem) SetAvatarForId(frndpk string) {
locfname... | ticon = Get | identifier_name |
room_list_item.go | package main
import (
"fmt"
"gopp"
"log"
"runtime"
"strings"
"time"
"go-purple/msgflt-prpl/bridges"
thscli "tox-homeserver/client"
thscom "tox-homeserver/common"
store "tox-homeserver/store"
"tox-homeserver/thspbs"
humanize "github.com/dustin/go-humanize"
"github.com/kitech/qt.go/qtcore"
"github.com/ki... | this.SetContactInfo(this.frndInfo)
// this.Label_2.SetText(gopp.StrSuf4ui(name, 26))
// this.Label_2.SetToolTip(name)
// this.ToolButton_2.SetToolTip(name + "." + this.GetId()[:7])
}
}
}
func (this *RoomListItem) UpdateStatusMessage(statusText string) {
if !this.isgroup {
if this.frndInfo.Stmsg != sta... | this.Label_2.SetText(gopp.StrSuf4ui(name, 26))
// this.Label_2.SetToolTip(name)
// this.ToolButton_2.SetToolTip(name + "." + this.GetId()[:7])
}
} else {
if this.frndInfo.Name != name {
this.frndInfo.Name = name
| conditional_block |
bibtexParser.ts | export class RootNode {
type = 'root' as const;
constructor(public children: (TextNode | BlockNode)[] = []) {}
}
export class TextNode {
type = 'text' as const;
constructor(public parent: RootNode, public text: string) {
parent.children.push(this);
}
}
export class BlockNode {
type = 'block' as const;
public ... | (string: string): boolean {
return /^[ \t\n\r]*$/.test(string);
}
/**
* Certain characters are special in latex: {}%#$~. These cannot be used in
* \cite without error. See https://tex.stackexchange.com/a/408548
*/
function isValidKeyCharacter(char: string): boolean {
return !/[#%{}~$,]/.test(char);
}
function is... | isWhitespace | identifier_name |
bibtexParser.ts | export class RootNode {
type = 'root' as const;
constructor(public children: (TextNode | BlockNode)[] = []) {}
}
export class TextNode {
type = 'text' as const;
constructor(public parent: RootNode, public text: string) {
parent.children.push(this);
}
}
export class BlockNode {
type = 'block' as const;
public ... | node.parent.children.push(node);
}
node.command = '';
} else if (char === '{' || char === '(') {
const commandTrimmed = node.command.trim();
if (commandTrimmed === '' || /\s/.test(commandTrimmed)) {
// A block without a command is invalid. It's sometimes used in comments though, e.g.... | new TextNode(node.parent, '@' + node.command); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.