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 |
|---|---|---|---|---|
spannerautoscaler_controller.go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License ... | (ctx context.Context, nn types.NamespacedName, projectID, instanceID string, credentials *syncer.Credentials) error {
log := logging.FromContext(ctx)
s, err := syncer.New(ctx, r.ctrlClient, nn, projectID, instanceID, credentials, r.recorder, syncer.WithLog(log))
if err != nil {
return err
}
go s.Start()
r.mu.... | startSyncer | identifier_name |
spannerautoscaler_controller.go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License ... | serviceAccountJSON, ok := secret.Data[iamKeySecret.Key]
if !ok {
return nil, errFetchServiceAccountJSONNoSecretDataFound
}
return syncer.NewServiceAccountJSONCredentials(serviceAccountJSON), nil
case spannerv1beta1.AuthTypeImpersonation:
return syncer.NewServiceAccountImpersonate(impersonateConfig.Targe... | }
| random_line_split |
spannerautoscaler_controller.go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License ... |
func (r *SpannerAutoscalerReconciler) fetchCredentials(ctx context.Context, sa *spannerv1beta1.SpannerAutoscaler) (*syncer.Credentials, error) {
iamKeySecret := sa.Spec.Authentication.IAMKeySecret
impersonateConfig := sa.Spec.Authentication.ImpersonateConfig
// TODO: move this to 'validating' webhook
if iamKeySe... | {
totalCPUProduct1000 := currentCPU * currentProcessingUnits
desiredProcessingUnits := maxInt(nextValidProcessingUnits(totalCPUProduct1000/targetCPU), currentProcessingUnits-scaledownStepSize*1000)
switch {
case desiredProcessingUnits < minProcessingUnits:
return minProcessingUnits
case desiredProcessingUnits... | identifier_body |
spannerautoscaler_controller.go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License ... |
return ctrlreconcile.Result{}, nil
}
// TODO: move this to the defaulting webhook
if sa.Spec.ScaleConfig.ScaledownStepSize == 0 {
sa.Spec.ScaleConfig.ScaledownStepSize = defaultScaledownStepSize
}
log.V(1).Info("resource status", "spannerautoscaler", sa)
credentials, err := r.fetchCredentials(ctx, &sa)
... | {
s.Stop()
r.mu.Lock()
delete(r.syncers, nn)
r.mu.Unlock()
log.Info("stopped syncer")
} | conditional_block |
query.go | package frontend
import (
"fmt"
"math"
"net/http"
"strings"
"sync/atomic"
"time"
"github.com/alpacahq/marketstore/v4/catalog"
"github.com/alpacahq/marketstore/v4/executor"
"github.com/alpacahq/marketstore/v4/planner"
"github.com/alpacahq/marketstore/v4/sqlparser"
"github.com/alpacahq/marketstore/v4/utils"
... | } else {
// Query
resp, err = s.executeQuery(&reqs.Requests[i])
if err != nil {
return err
}
}
response.Responses = append(response.Responses, *resp)
}
return nil
}
func (s *DataService) executeSQL(sqlStatement string) (*QueryResponse, error) {
queryTree, err := sqlparser.BuildQueryTree(sqlSt... | return err
} | random_line_split |
query.go | package frontend
import (
"fmt"
"math"
"net/http"
"strings"
"sync/atomic"
"time"
"github.com/alpacahq/marketstore/v4/catalog"
"github.com/alpacahq/marketstore/v4/executor"
"github.com/alpacahq/marketstore/v4/planner"
"github.com/alpacahq/marketstore/v4/sqlparser"
"github.com/alpacahq/marketstore/v4/utils"
... |
func (qs *QueryService) ExecuteQuery(tbk *io.TimeBucketKey, start, end time.Time, limitRecordCount int,
limitFromStart bool, columns []string,
) (io.ColumnSeriesMap, error) {
query := planner.NewQuery(qs.catalogDir)
/*
Alter timeframe inside key to ensure it matches a queryable TF
*/
tf := tbk.GetItemInCateg... | {
return &QueryService{
catalogDir: catDir,
}
} | identifier_body |
query.go | package frontend
import (
"fmt"
"math"
"net/http"
"strings"
"sync/atomic"
"time"
"github.com/alpacahq/marketstore/v4/catalog"
"github.com/alpacahq/marketstore/v4/executor"
"github.com/alpacahq/marketstore/v4/planner"
"github.com/alpacahq/marketstore/v4/sqlparser"
"github.com/alpacahq/marketstore/v4/utils"
... |
csm := io.NewColumnSeriesMap()
for _, ds := range resp.Responses { // Datasets are packed in a slice, each has a NumpyMultiDataset inside
nmds := ds.Result
for tbkStr, startIndex := range nmds.StartIndex {
cs, err := nmds.ToColumnSeries(startIndex, nmds.Lengths[tbkStr])
if err != nil {
return nil, er... | {
return nil, nil
} | conditional_block |
query.go | package frontend
import (
"fmt"
"math"
"net/http"
"strings"
"sync/atomic"
"time"
"github.com/alpacahq/marketstore/v4/catalog"
"github.com/alpacahq/marketstore/v4/executor"
"github.com/alpacahq/marketstore/v4/planner"
"github.com/alpacahq/marketstore/v4/sqlparser"
"github.com/alpacahq/marketstore/v4/utils"
... | (req *QueryRequest) (*QueryResponse, error) {
/*
Assumption: Within each TimeBucketKey, we have one or more of each category, with the exception of
the AttributeGroup (aka Record Format) and Timeframe
Within each TimeBucketKey in the request, we allow for a comma separated list of items, e.g.:
destination1.it... | executeQuery | identifier_name |
d05.go | package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"runtime/pprof"
"strconv"
"sync"
"unsafe"
)
// area represents an area with its name and code.
type area struct {
name []byte
code []byte
}
// employee represents an employee with associate name, surname, salary and
// area.
type employee ... |
for i, size = 0, uint32(len(byArea.salaries.lowest)); i < size; i++ {
fmt.Printf("area_min|%s|%s %s|%.2f\n", d.areas[areaCode].name, byArea.salaries.lowest[i].name, byArea.salaries.lowest[i].surname, byArea.salaries.lowest[i].salary)
}
fmt.Printf("area_avg|%s|%.2f\n", d.areas[areaCode].name, byArea.salari... | {
fmt.Printf("area_max|%s|%s %s|%.2f\n", d.areas[areaCode].name, byArea.salaries.biggest[i].name, byArea.salaries.biggest[i].surname, byArea.salaries.biggest[i].salary)
} | conditional_block |
d05.go | package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"runtime/pprof"
"strconv"
"sync"
"unsafe"
)
// area represents an area with its name and code.
type area struct {
name []byte
code []byte
}
// employee represents an employee with associate name, surname, salary and
// area.
type employee ... | }
func main() {
var optCPUProfile string
flag.StringVar(&optCPUProfile, "cpuprofile", "", "write cpu profile to file")
flag.Parse()
if len(flag.Args()) < 2 {
log.Fatalf("Usage: %s [-cpuprofile=<profile>] <input file> [number of concurrent blocks]\n", os.Args[0])
}
// Profiling
if optCPUProfile != "" {
f,... | }
wg.Done()
}()
wg.Wait() | random_line_split |
d05.go | package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"runtime/pprof"
"strconv"
"sync"
"unsafe"
)
// area represents an area with its name and code.
type area struct {
name []byte
code []byte
}
// employee represents an employee with associate name, surname, salary and
// area.
type employee ... | (data []byte, block chan *d05) {
var start uint32
partialSolution := newD05()
openbracket := byte('{')
closedbracket := byte('}')
i := uint32(0)
var idx int
for {
if idx = bytes.IndexByte(data[i:], openbracket); idx == -1 {
break
}
start = i + uint32(idx)
i = start
if idx = bytes.IndexByte(data[i... | parseJSONBlock | identifier_name |
d05.go | package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"runtime/pprof"
"strconv"
"sync"
"unsafe"
)
// area represents an area with its name and code.
type area struct {
name []byte
code []byte
}
// employee represents an employee with associate name, surname, salary and
// area.
type employee ... |
// processEmployees receive an employee and updates the associated stats.
func (d *d05) processEmployee(e *employee) {
area := unsafeString(e.areaCode)
surname := unsafeString(e.surname)
d.updateSalaries(&d.salaries, e)
d.calculateSalaries(d.salaryBySurname, &surname, e)
d.calculateSalaries(d.salaryByArea, &are... | {
gs, ok := s[*key]
if !ok {
gs = &groupSalaryStats{}
s[*key] = gs
}
d.updateSalaries(&gs.salaries, e)
} | identifier_body |
tokens.rs | use crate::protocol::input_source::{
InputPosition as InputPosition,
InputSpan
};
/// Represents a particular kind of token. Some tokens represent
/// variable-character tokens. Such a token is always followed by a
/// `TokenKind::SpanEnd` token.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pu... | LessEquals, // <=
ShiftRight, // >>
GreaterEquals, // >=
// Operator-like (three characters)
ShiftLeftEquals,// <<=
ShiftRightEquals, // >>=
// Special marker token to indicate end of variable-character tokens
SpanEnd,
}
impl TokenKind {
/// Returns true if the next expecte... | OrEquals, // |=
EqualEqual, // ==
NotEqual, // !=
ShiftLeft, // << | random_line_split |
tokens.rs | use crate::protocol::input_source::{
InputPosition as InputPosition,
InputSpan
};
/// Represents a particular kind of token. Some tokens represent
/// variable-character tokens. Such a token is always followed by a
/// `TokenKind::SpanEnd` token.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pu... | <'a> {
tokens: &'a Vec<Token>,
cur: usize,
end: usize,
}
impl<'a> TokenIter<'a> {
fn new(buffer: &'a TokenBuffer, start: usize, end: usize) -> Self {
Self{ tokens: &buffer.tokens, cur: start, end }
}
/// Returns the next token (may include comments), or `None` if at the end
/// of ... | TokenIter | identifier_name |
tokens.rs | use crate::protocol::input_source::{
InputPosition as InputPosition,
InputSpan
};
/// Represents a particular kind of token. Some tokens represent
/// variable-character tokens. Such a token is always followed by a
/// `TokenKind::SpanEnd` token.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pu... |
/// See `next_positions`
pub(crate) fn next_span(&self) -> InputSpan {
let (begin, end) = self.next_positions();
return InputSpan::from_positions(begin, end)
}
/// Advances the iterator to the next (meaningful) token.
pub(crate) fn consume(&mut self) {
if let Some(kind) = ... | {
debug_assert!(self.cur < self.end);
let token = &self.tokens[self.cur];
if token.kind.has_span_end() {
let span_end = &self.tokens[self.cur + 1];
debug_assert_eq!(span_end.kind, TokenKind::SpanEnd);
(token.pos, span_end.pos)
} else {
let ... | identifier_body |
tokens.rs | use crate::protocol::input_source::{
InputPosition as InputPosition,
InputSpan
};
/// Represents a particular kind of token. Some tokens represent
/// variable-character tokens. Such a token is always followed by a
/// `TokenKind::SpanEnd` token.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pu... |
}
}
/// Saves the current iteration position, may be passed to `load` to return
/// the iterator to a previous position.
pub(crate) fn save(&self) -> (usize, usize) {
(self.cur, self.end)
}
pub(crate) fn load(&mut self, saved: (usize, usize)) {
self.cur = saved.0;
... | {
self.cur += 1;
} | conditional_block |
value_stability.rs | // Copyright 2018 Developers of the Rand 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 distributed
/... | () {
// Gamma has 3 cases: shape == 1, shape < 1, shape > 1
test_samples(223, Gamma::new(1.0, 5.0).unwrap(), &[
5.398085f32, 9.162783, 0.2300583, 1.7235851,
]);
test_samples(223, Gamma::new(0.8, 5.0).unwrap(), &[
0.5051203f32, 0.9048302, 3.095812, 1.8566116,
]);
test_samples(223,... | gamma_stability | identifier_name |
value_stability.rs | // Copyright 2018 Developers of the Rand 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 distributed
/... | 0.47912589330631555,
0.25323238071138526,
]);
test_samples(223, Beta::new(3.0, 1.2).unwrap(), &[
0.49563509121756827,
0.9551305482256759,
0.5151181353461637,
0.7551732971235077,
]);
}
#[test]
fn exponential_stability() {
test_samples(223, Exp1, &[
... | 0.8134131062097899, | random_line_split |
value_stability.rs | // Copyright 2018 Developers of the Rand 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 distributed
/... |
}
impl<T: ApproxEq> ApproxEq for [T; 3] {
fn assert_almost_eq(&self, rhs: &Self) {
self[0].assert_almost_eq(&rhs[0]);
self[1].assert_almost_eq(&rhs[1]);
self[2].assert_almost_eq(&rhs[2]);
}
}
fn test_samples<F: Debug + ApproxEq, D: Distribution<F>>(
seed: u64, distr: D, expected: &... | {
self[0].assert_almost_eq(&rhs[0]);
self[1].assert_almost_eq(&rhs[1]);
} | identifier_body |
slime_volleyball.js | var SlimeVolleyball,
__hasProp = Object.prototype.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function | () { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
SlimeVolleyball = (function(_super) {
__extends(SlimeVolleyball, _super);
SlimeVolleyball.name = 'SlimeVolleyball';
function SlimeVolleyball() {
return Slime... | ctor | identifier_name |
slime_volleyball.js | var SlimeVolleyball,
__hasProp = Object.prototype.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() | ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
SlimeVolleyball = (function(_super) {
__extends(SlimeVolleyball, _super);
SlimeVolleyball.name = 'SlimeVolleyball';
function SlimeVolleyball() {
return SlimeVolleyball.__super__.constructor... | { this.constructor = child; } | identifier_body |
slime_volleyball.js | var SlimeVolleyball,
__hasProp = Object.prototype.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ ... | return _this.handleMouseDown();
}, true);
};
SlimeVolleyball.prototype.refreshSprites = function() {
var gamepad, gamepadUI;
this.sprites = [];
this.sprites.push(this.bg, this.world.road, this.world.bushes, this.world.building1, this.world.building2, this.world.p1);
gamepad = new GamePad(... | }, true);
return canvas.addEventListener('touchstart', function() { | random_line_split |
text_layout_engine.rs | #![allow(dead_code)]
// XXX: should be no harfbuzz in the interface
use crate::node::NativeWord;
use crate::xetex_font_info::{GlyphBBox, XeTeXFontInst};
//use crate::xetex_font_manager::PlatformFontRef;
use crate::cmd::XetexExtCmd;
use crate::xetex_font_info::GlyphID;
use crate::xetex_layout_interface::FixedPoint;
use... | false
}
/// Not sure what AAT should return, since this is only called with random casts to
/// XeTeXLayoutENgine in xetex0.
fn using_open_type(&self) -> bool {
false
}
unsafe fn is_open_type_math_font(&self) -> bool {
false
}
}
/*
trait GraphiteFontSomething {
... | /// Only relevant if this engine actually uses graphite, hence default impl of { false }
unsafe fn initGraphiteBreaking(&mut self, _txt: &[u16]) -> bool { | random_line_split |
text_layout_engine.rs | #![allow(dead_code)]
// XXX: should be no harfbuzz in the interface
use crate::node::NativeWord;
use crate::xetex_font_info::{GlyphBBox, XeTeXFontInst};
//use crate::xetex_font_manager::PlatformFontRef;
use crate::cmd::XetexExtCmd;
use crate::xetex_font_info::GlyphID;
use crate::xetex_layout_interface::FixedPoint;
use... |
pub fn from_int(i: i32) -> Option<Self> {
Some(match i {
1 => GlyphEdge::Left,
2 => GlyphEdge::Top,
3 => GlyphEdge::Right,
4 => GlyphEdge::Bottom,
_ => return None,
})
}
}
#[enum_dispatch::enum_dispatch]
pub(crate) enum NativeFont {
... | {
match *self {
GlyphEdge::Left | GlyphEdge::Top => options.0,
GlyphEdge::Right | GlyphEdge::Bottom => options.1,
}
} | identifier_body |
text_layout_engine.rs | #![allow(dead_code)]
// XXX: should be no harfbuzz in the interface
use crate::node::NativeWord;
use crate::xetex_font_info::{GlyphBBox, XeTeXFontInst};
//use crate::xetex_font_manager::PlatformFontRef;
use crate::cmd::XetexExtCmd;
use crate::xetex_font_info::GlyphID;
use crate::xetex_layout_interface::FixedPoint;
use... | (node: &'a NativeWord, justify: bool) -> LayoutRequest<'a> {
use crate::xetex_ini::FONT_LETTER_SPACE;
let text = node.text();
let line_width = node.width();
let f = node.font() as usize;
let letter_space_unit = FONT_LETTER_SPACE[f];
LayoutRequest {
text,
... | from_node | identifier_name |
bar_chart_from_csv.py | # bar chart from a CSV
# Written in Python 2.7
# RCK
# 1-10-12
import matplotlib
matplotlib.use('Agg')
import gzip
import numpy as np
import pylab as pl
from scipy import stats
import scipy
import scikits.bootstrap as bootstrap
import math
from optparse import OptionParser
# Set up options
usage = """usage: %prog... |
def bootstrap_error____old( data ):
x = np.array((data))
X = [] ## estimates
mean = np.mean(x)
for xx in xrange(1000): ## do this 1000 times
X.append( np.mean( x[np.random.randint(len(x),size=len(x))] ) )
conf = 0.95
plower = (1-conf)/2.0
pupper = 1-plower
lower_ci, upper_ci ... | if norm_cumul[i] > q:
return bins[i] | conditional_block |
bar_chart_from_csv.py | # bar chart from a CSV
# Written in Python 2.7
# RCK
# 1-10-12
import matplotlib
matplotlib.use('Agg')
import gzip
import numpy as np
import pylab as pl
from scipy import stats
import scipy
import scikits.bootstrap as bootstrap
import math
from optparse import OptionParser
# Set up options
usage = """usage: %prog... | :
Black = (0.0, 0.0, 0.0, 1.0)
DarkGray = (0.65, 0.65, 0.65, 1.0)
Gray = (0.75, 0.75, 0.75, 1.0)
LightGray = (0.85, 0.85, 0.85, 1.0)
VeryLightGray = (0.9, 0.9, 0.9, 1.0)
White = (1.0, 1.0, 1.0, 1.0)
Transparent = (0, 0, 0, 0)
Purple = (0.55, 0.0, 0.55, 1.0)
LightPurple = (0.8, 0.7, ... | Colors | identifier_name |
bar_chart_from_csv.py | # bar chart from a CSV
# Written in Python 2.7
# RCK
# 1-10-12
import matplotlib
matplotlib.use('Agg')
import gzip
import numpy as np
import pylab as pl
from scipy import stats
import scipy
import scikits.bootstrap as bootstrap
import math
from optparse import OptionParser
# Set up options
usage = """usage: %prog... |
mean_X = np.mean(X)
std_X = np.std(X)
## re-sample means are not guaranteed to be quite right.
## Conf 0.95, loc=sample mean, scale = (np.std(X, ddof=1)/np.sqrt(len(X)))
conf_int = stats.norm.interval(0.95, loc=mean_X, scale=stats.sem(X))
#toperr = (mean_X - conf_int[0])
#bo... | for xx in xrange(1000): ## do this 1000 times
X.append( np.mean( x[np.random.randint(len(x),size=len(x))] ) ) | random_line_split |
bar_chart_from_csv.py | # bar chart from a CSV
# Written in Python 2.7
# RCK
# 1-10-12
import matplotlib
matplotlib.use('Agg')
import gzip
import numpy as np
import pylab as pl
from scipy import stats
import scipy
import scikits.bootstrap as bootstrap
import math
from optparse import OptionParser
# Set up options
usage = """usage: %prog... |
if options.legend and len(artists) > 0 and len(legend_labels) > 0:
if options.debug_messages:
print
print "ARTISTS"
print artists
print "LABELS"
print legend_labels
proxies = []
for i in range(0, member_count):
proxies.append( proxy_artist( color_sets[i] )... | p = pl.Rectangle((0,0), 1,1, fc=color)
return p | identifier_body |
server.rs | use crate::api::pos_grpc_service::PosGrpcService;
use crate::{DEFAULT_BITS_PER_INDEX, DEFAULT_INDEXES_PER_CYCLE, DEFAULT_SALT};
use anyhow::{bail, Result};
use pos_api::api::job::JobStatus;
use pos_api::api::pos_data_service_server::PosDataServiceServer;
use pos_api::api::{
AbortJobRequest, AddJobRequest, Config, J... | impl Handler<AddJob> for PosServer {
async fn handle(&mut self, _ctx: &mut Context<Self>, msg: AddJob) -> Result<Job> {
let data = msg.0;
let job = Job {
id: rand::random(),
bits_written: 0,
size_bits: data.post_size_bits,
started: 0,
subm... | random_line_split | |
server.rs | use crate::api::pos_grpc_service::PosGrpcService;
use crate::{DEFAULT_BITS_PER_INDEX, DEFAULT_INDEXES_PER_CYCLE, DEFAULT_SALT};
use anyhow::{bail, Result};
use pos_api::api::job::JobStatus;
use pos_api::api::pos_data_service_server::PosDataServiceServer;
use pos_api::api::{
AbortJobRequest, AddJobRequest, Config, J... |
self.jobs.remove(&req.id);
}
Ok(())
}
}
#[message(result = "Result<()>")]
pub(crate) struct SetConfig(pub(crate) Config);
/// Set the pos compute config
#[async_trait::async_trait]
impl Handler<SetConfig> for PosServer {
async fn handle(&mut self, _ctx: &mut Context<Self>, msg: S... | {
self.pending_jobs.remove(idx);
} | conditional_block |
server.rs | use crate::api::pos_grpc_service::PosGrpcService;
use crate::{DEFAULT_BITS_PER_INDEX, DEFAULT_INDEXES_PER_CYCLE, DEFAULT_SALT};
use anyhow::{bail, Result};
use pos_api::api::job::JobStatus;
use pos_api::api::pos_data_service_server::PosDataServiceServer;
use pos_api::api::{
AbortJobRequest, AddJobRequest, Config, J... | (&mut self, _ctx: &mut Context<Self>) {
info!("PosServer system service stopped");
}
}
impl Service for PosServer {}
impl Default for PosServer {
fn default() -> Self {
PosServer {
providers: vec![],
pending_jobs: vec![],
jobs: Default::default(),
... | stopped | identifier_name |
server.rs | use crate::api::pos_grpc_service::PosGrpcService;
use crate::{DEFAULT_BITS_PER_INDEX, DEFAULT_INDEXES_PER_CYCLE, DEFAULT_SALT};
use anyhow::{bail, Result};
use pos_api::api::job::JobStatus;
use pos_api::api::pos_data_service_server::PosDataServiceServer;
use pos_api::api::{
AbortJobRequest, AddJobRequest, Config, J... |
}
/////////////////////////////////////////////
#[message(result = "Result<()>")]
pub(crate) struct StartGrpcService {
pub(crate) port: u32,
pub(crate) host: String,
}
#[async_trait::async_trait]
impl Handler<StartGrpcService> for PosServer {
async fn handle(&mut self, _ctx: &mut Context<Self>, msg: Star... | {
// create channel for streaming job statuses
let (tx, rx) = mpsc::channel(32);
// store the sender indexed by a new unique id
self.job_status_subscribers.insert(rand::random(), tx);
// return the receiver
Ok(ReceiverStream::new(rx))
} | identifier_body |
mod.rs | use self::constants::*;
use super::*;
mod creature;
mod rock;
pub use self::creature::*;
pub use self::rock::*;
use std::cell::{Ref, RefMut};
#[cfg(multithreading)]
type ReferenceCounter = std::sync::Arc;
#[cfg(not(multithreading))]
type ReferenceCounter<A> = std::rc::Rc<A>;
#[cfg(multithreading)]
type MutPoint = s... | impl<B: Intentions> HLSoftBody<B> {
fn wants_primary_birth(&self, time: f64) -> bool {
let temp = self.borrow();
temp.get_energy() > SAFE_SIZE
&& temp.brain.wants_birth() > 0.0
&& temp.get_age(time) > MATURE_AGE
}
}
impl<B: NeuralNet + Intentions + RecombinationInfinite... | random_line_split | |
mod.rs | use self::constants::*;
use super::*;
mod creature;
mod rock;
pub use self::creature::*;
pub use self::rock::*;
use std::cell::{Ref, RefMut};
#[cfg(multithreading)]
type ReferenceCounter = std::sync::Arc;
#[cfg(not(multithreading))]
type ReferenceCounter<A> = std::rc::Rc<A>;
#[cfg(multithreading)]
type MutPoint = s... |
}
impl<B> Clone for HLSoftBody<B> {
fn clone(&self) -> Self {
HLSoftBody(ReferenceCounter::clone(&self.0))
}
}
impl<B> PartialEq<HLSoftBody<B>> for HLSoftBody<B> {
fn eq(&self, rhs: &HLSoftBody<B>) -> bool {
ReferenceCounter::ptr_eq(&self.0, &rhs.0)
}
}
impl<B> HLSoftBody<B> {
//... | {
HLSoftBody(ReferenceCounter::new(MutPoint::new(sb)))
} | identifier_body |
mod.rs | use self::constants::*;
use super::*;
mod creature;
mod rock;
pub use self::creature::*;
pub use self::rock::*;
use std::cell::{Ref, RefMut};
#[cfg(multithreading)]
type ReferenceCounter = std::sync::Arc;
#[cfg(not(multithreading))]
type ReferenceCounter<A> = std::rc::Rc<A>;
#[cfg(multithreading)]
type MutPoint = s... |
}
}
/// This function requires a reference to a `Board`.
/// This is usually impossible so you'll have to turn to `unsafe`.
pub fn return_to_earth(
&mut self,
time: f64,
board_size: BoardSize,
terrain: &mut Terrain,
climate: &Climate,
sbip: &mut ... | {
let force = combined_radius * COLLISION_FORCE;
let add_vx = (self_px - collider_px) / distance * force / self_mass;
let add_vy = (self_py - collider_py) / distance * force / self_mass;
// This is where self is needed to be borrowed mutably.
... | conditional_block |
mod.rs | use self::constants::*;
use super::*;
mod creature;
mod rock;
pub use self::creature::*;
pub use self::rock::*;
use std::cell::{Ref, RefMut};
#[cfg(multithreading)]
type ReferenceCounter = std::sync::Arc;
#[cfg(not(multithreading))]
type ReferenceCounter<A> = std::rc::Rc<A>;
#[cfg(multithreading)]
type MutPoint = s... | <B = Brain>(ReferenceCounter<MutPoint<SoftBody<B>>>);
impl<B> From<SoftBody<B>> for HLSoftBody<B> {
fn from(sb: SoftBody<B>) -> HLSoftBody<B> {
HLSoftBody(ReferenceCounter::new(MutPoint::new(sb)))
}
}
impl<B> Clone for HLSoftBody<B> {
fn clone(&self) -> Self {
HLSoftBody(ReferenceCounter::... | HLSoftBody | identifier_name |
wal.go | package wal
import (
"bytes"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
"sync"
"time"
"k8s-lx1036/k8s/storage/etcd/raft"
"go.etcd.io/etcd/client/pkg/v3/fileutil"
"go.etcd.io/etcd/pkg/v3/pbutil"
"go.etcd.io/etcd/raft/v3/raftpb"
"go.etcd.io/etcd/server/v3/wal/walpb"
"k8s.io/klog/v2"
)
const ... | w, err := openAtIndex(dirpath, snap, true)
if err != nil {
return nil, err
}
if w.dirFile, err = fileutil.OpenDir(w.dir); err != nil {
return nil, err
}
return w, nil
} | random_line_split | |
wal.go | package wal
import (
"bytes"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
"sync"
"time"
"k8s-lx1036/k8s/storage/etcd/raft"
"go.etcd.io/etcd/client/pkg/v3/fileutil"
"go.etcd.io/etcd/pkg/v3/pbutil"
"go.etcd.io/etcd/raft/v3/raftpb"
"go.etcd.io/etcd/server/v3/wal/walpb"
"k8s.io/klog/v2"
)
const ... | rk to spawn a process while this is
// happening. The fds are set up as close-on-exec by the Go runtime,
// but there is a window between the fork and the exec where another
// process holds the lock.
if err := os.Rename(tmpdirpath, w.dir); err != nil {
if _, ok := err.(*os.LinkError); ok {
return w.renameWALU... | s will fo | identifier_name |
wal.go | package wal
import (
"bytes"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
"sync"
"time"
"k8s-lx1036/k8s/storage/etcd/raft"
"go.etcd.io/etcd/client/pkg/v3/fileutil"
"go.etcd.io/etcd/pkg/v3/pbutil"
"go.etcd.io/etcd/raft/v3/raftpb"
"go.etcd.io/etcd/server/v3/wal/walpb"
"k8s.io/klog/v2"
)
const ... | or {
if err := walpb.ValidateSnapshotForWrite(&e); err != nil {
return err
}
b := pbutil.MustMarshal(&e)
w.mu.Lock()
defer w.mu.Unlock()
rec := &walpb.Record{Type: snapshotType, Data: b}
if err := w.encoder.encode(rec); err != nil {
return err
}
// update enti only when snapshot is ahead of last index
... | lpb.Snapshot) err | conditional_block |
wal.go | package wal
import (
"bytes"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
"sync"
"time"
"k8s-lx1036/k8s/storage/etcd/raft"
"go.etcd.io/etcd/client/pkg/v3/fileutil"
"go.etcd.io/etcd/pkg/v3/pbutil"
"go.etcd.io/etcd/raft/v3/raftpb"
"go.etcd.io/etcd/server/v3/wal/walpb"
"k8s.io/klog/v2"
)
const ... | sible the process will fork to spawn a process while this is
// happening. The fds are set up as close-on-exec by the Go runtime,
// but there is a window between the fork and the exec where another
// process holds the lock.
if err := os.Rename(tmpdirpath, w.dir); err != nil {
if _, ok := err.(*os.LinkError); ok... | err := os.RemoveAll(w.dir); err != nil {
return nil, err
}
// On non-Windows platforms, hold the lock while renaming. Releasing
// the lock and trying to reacquire it quickly can be flaky because
// it's pos | identifier_body |
car_type_management.js | $(document).ready(function(){
initTable();
vadidateModal();
$('#search_text').keydown(function (e) {
if (e.keyCode === 13) {
$('#search_btn').click();
}
});
});
function addCarType() {
$('#add_car_type_form').data('bootstrapValidator').validate();
if(!$('#a... | // height: 300
// }).toDataURL('image/png');
if(document.getElementById('user-photo').src == "") {
alert('请输入图片')
return
}
var car_picture = getBase64Image(document.getElementById('user-photo'))
var data = {
"car_name": car_name,
"car_brand": car_bran... | random_line_split | |
car_type_management.js | $(document).ready(function(){
initTable();
vadidateModal();
$('#search_text').keydown(function (e) {
if (e.keyCode === 13) {
$('#search_btn').click();
}
});
});
function addCarType() {
$('#add_car_type_form').data('bootstrapValidator').validate();
if(!$('#a... | otoInput'),$('#changeModal'));
});
function resetModal() {
$('#add_car_type_form').find('input').val('');
$('#add_car_type_form').data('bootstrapValidator').destroy();
$('#add_car_type_form').data('bootstrapValidator', null);
$('#add_car_type').selectpicker('refresh');
vadidateModal();
} | photo'),$('#ph | identifier_name |
car_type_management.js | $(document).ready(function(){
initTable();
vadidateModal();
$('#search_text').keydown(function (e) {
if (e.keyCode === 13) {
$('#search_btn').click();
}
});
});
function addCarType() | var car_name = $("#search_text").val();
var data = {
"car_name": car_name
};
$.ajax({
type: "post",
url: "searchCarTypeServlet",
data: data,
dataType: "json",
success: function(json){
$('#car_info').bootstrapTable('load', json);
... | {
$('#add_car_type_form').data('bootstrapValidator').validate();
if(!$('#add_car_type_form').data('bootstrapValidator').isValid()){
return ;
}
$('#add_modal').modal('hide');
var car_name = $('#add_car_name').val();
var car_brand = $('#add_car_brand').val();
var daily_rent = $... | identifier_body |
car_type_management.js | $(document).ready(function(){
initTable();
vadidateModal();
$('#search_text').keydown(function (e) {
if (e.keyCode === 13) {
$('#search_btn').click();
}
});
});
function addCarType() {
$('#add_car_type_form').data('bootstrapValidator').validate();
if(!$('#a... | itable: {
title: '输入所需押金',
type: 'text',
validate: function(v) {
if (!v) {
return '所需押金不能为空';
}
else if (parseFloat(v) < 0) {
return '所需押金不能小于0';
... | eposit',
title: '所需押金',
sortable: true,
ed | conditional_block |
calendar.rs | use crate::{FloatNum, Int};
use std::ops::Rem;
#[derive(Clone)]
pub struct Calendar {
pub mondays: [Int; 13],
pub mona365: [Int; 13],
pub monaccu: [Int; 13],
pub ny400d: Int,
pub ny100d: Int,
pub ny004d: Int,
pub ny001d: Int,
pub nud: Int,
// TODO ?
// These values are copied ... |
// kstep ! time step since simulation start
// ktspd ! time steps per day
// kdatim(7) ! year,month,day,hour,min,weekday,leapyear
fn step2cal(kstep: Int, ktspd: Int, kdatim: &mut [Int; 7], mut cal: &mut Calendar) {
let mut iyea: Int; // current year of simulation
let mut imon: Int; // current month... | {
let mut idatim = [0; 7];
if cal.n_days_per_year == 365 {
step2cal(kstep, cal.ntspd, &mut idatim, cal);
return idatim[2] + cal.monaccu[idatim[1] as usize - 1];
} else {
step2cal30(kstep, cal.ntspd, &mut idatim, cal);
return idatim[2] + cal.n_days_per_month * (idatim[1] - 1)... | identifier_body |
calendar.rs | use crate::{FloatNum, Int};
use std::ops::Rem;
#[derive(Clone)]
pub struct Calendar {
pub mondays: [Int; 13],
pub mona365: [Int; 13],
pub monaccu: [Int; 13],
pub ny400d: Int,
pub ny100d: Int,
pub ny004d: Int,
pub ny001d: Int,
pub nud: Int,
// TODO ?
// These values are copied ... | else {
// century year is not leap year
iy100 = (id400 - 1) / cal.ny100d; // century in segment [1,2,3]
id100 = (id400 - 1).rem(cal.ny100d);
if id100 < cal.ny004d - 1 {
iy004 = 0; // tetrade in century [0]
id004 = id100;
leap = false;
iy0... | {
// century year is leap year
iy100 = 0; // century in segment [0]
id100 = id400;
iy004 = id100 / cal.ny004d; // tetrade in century [0..24]
id004 = id100.rem(cal.ny004d);
leap = id004 <= cal.ny001d;
if leap {
iy001 = 0; // year in tetrade [0]
... | conditional_block |
calendar.rs | use crate::{FloatNum, Int};
use std::ops::Rem;
#[derive(Clone)]
pub struct Calendar {
pub mondays: [Int; 13],
pub mona365: [Int; 13],
pub monaccu: [Int; 13],
pub ny400d: Int,
pub ny100d: Int,
pub ny004d: Int,
pub ny001d: Int,
pub nud: Int,
// TODO ?
// These values are copied ... | (
ktspd: Int, // time steps per day
kyea: Int, // current year of simulation
kmon: Int, // current month of simulation
kday: Int, // current day of simulation
khou: Int, // current hour of simulation
kmin: Int, // current minute of simul... | cal2step | identifier_name |
calendar.rs | use crate::{FloatNum, Int};
use std::ops::Rem;
#[derive(Clone)]
pub struct Calendar {
pub mondays: [Int; 13],
pub mona365: [Int; 13],
pub monaccu: [Int; 13],
pub ny400d: Int,
pub ny100d: Int,
pub ny004d: Int,
pub ny001d: Int,
pub nud: Int,
// TODO ?
// These values are copied ... | n_days_per_year: 360,
n_start_step: 0,
ntspd: 1,
solar_day: 86400.0, // sec
}
}
}
fn yday2mmdd(cal: &Calendar, mut kyday: &mut Int, mut kmon: &mut Int, mut kday: &mut Int) {
if cal.n_days_per_year == 365 {
*kmon = 1;
while *kyday > cal.mon... | ny001d: 365,
nud: 6,
n_days_per_month: 30, | random_line_split |
pages.go | package peji
import (
"bytes"
"context"
"strings"
"sync"
"time"
"github.com/influx6/npkg/njson"
"github.com/influx6/sabuhp"
"github.com/influx6/sabuhp/mixer"
"github.com/influx6/npkg/nerror"
"github.com/influx6/npkg/nxid"
"github.com/influx6/groundlayer/pkg/domu"
"github.com/influx6/groundlayer/pkg/styl... |
psm.routes[pageRoute] = true
psm.rl.Unlock()
psm.onAddRoute(pageRoute, p)
}
func (psm *PageSessionManager) manage() {
defer psm.waiter.Done()
var ticker = time.NewTicker(psm.idleCheckInterval)
defer ticker.Stop()
doLoop:
for {
select {
case <-psm.ctx.Done():
return
case doFn := <-psm.doFunc:
doF... | {
psm.rl.Unlock()
return
} | conditional_block |
pages.go | package peji
import (
"bytes"
"context"
"strings"
"sync"
"time"
"github.com/influx6/npkg/njson"
"github.com/influx6/sabuhp"
"github.com/influx6/sabuhp/mixer"
"github.com/influx6/npkg/nerror"
"github.com/influx6/npkg/nxid"
"github.com/influx6/groundlayer/pkg/domu"
"github.com/influx6/groundlayer/pkg/styl... | (pageName string) (*PageSessionManager, error) {
var pageHandle = cleanAllSlashes(handlePath(pageName))
var prefixPage = cleanAllSlashes(handlePath(p.prefix, pageName))
p.sl.RLock()
var manager, exists = p.managers[prefixPage]
if !exists {
manager, exists = p.managers[pageHandle]
}
p.sl.RUnlock()
if !exists... | Get | identifier_name |
pages.go | package peji
import (
"bytes"
"context"
"strings"
"sync"
"time"
"github.com/influx6/npkg/njson"
"github.com/influx6/sabuhp"
"github.com/influx6/sabuhp/mixer"
"github.com/influx6/npkg/nerror"
"github.com/influx6/npkg/nxid"
"github.com/influx6/groundlayer/pkg/domu"
"github.com/influx6/groundlayer/pkg/styl... |
func (psm *PageSessionManager) Wait() {
psm.waiter.Wait()
}
func (psm *PageSessionManager) Stop() {
psm.starter.Do(func() {
psm.canceler()
psm.waiter.Wait()
})
}
func (psm *PageSessionManager) Start() {
psm.starter.Do(func() {
psm.waiter.Add(1)
go psm.manage()
})
}
type SessionStat struct {
PageName ... | {
return psm.routePath
} | identifier_body |
pages.go | package peji
import (
"bytes"
"context"
"strings"
"sync"
"time"
"github.com/influx6/npkg/njson"
"github.com/influx6/sabuhp"
"github.com/influx6/sabuhp/mixer"
"github.com/influx6/npkg/nerror"
"github.com/influx6/npkg/nxid"
"github.com/influx6/groundlayer/pkg/domu"
"github.com/influx6/groundlayer/pkg/styl... | onNewPage *PageNotification
}
func WithPages(
ctx context.Context,
logger Logger,
prefix string,
theme *styled.Theme,
transport sabuhp.Transport,
notFound Handler,
) *Pages {
return NewPages(
ctx,
logger,
prefix,
DefaultMaxPageIdleness,
DefaultPageIdlenessChecksInterval,
theme,
transport,
notFo... | random_line_split | |
helpers.py | import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
from config.utils import *
import lp.db_semisuper as db_semisuper
import lp.db_eval as db_eval
from m... |
return global_step
def validate(eval_loader, model, args, global_step, epoch, num_classes =10):
meters = AverageMeterSet()
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(eval_loader):
batch_size = targets.size(0)
model.eval()
inputs... | aug_images_l,target_l = next(train_loader_l)
target_l = target_l.to(args.device)
target_u = target_u.to(args.device)
target = torch.cat((target_l,target_u),0)
#Create the mix
alpha = args.alpha
index = torch.randperm(args.batch_size,devi... | conditional_block |
helpers.py | import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
from config.utils import *
import lp.db_semisuper as db_semisuper
import lp.db_eval as db_eval
from m... | outputs,_ = model(inputs)
prec1, prec5 = accuracy(outputs, targets, topk=(1, 5))
# measure accuracy and record loss
prec1, prec5 = accuracy(outputs, targets, topk=(1, 5))
meters.update('top1', prec1.item(), batch_size)
meters.update('e... | random_line_split | |
helpers.py | import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
from config.utils import *
import lp.db_semisuper as db_semisuper
import lp.db_eval as db_eval
from m... |
def train_sup(train_loader, model, optimizer, epoch, global_step, args, ema_model = None):
# switch to train mode
model.train()
for i, (aug_images , target) in enumerate(train_loader):
target = target.to(args.device)
#Create the mix
alpha = args.alpha
i... | criterion = nn.CrossEntropyLoss(reduction='none').cuda()
return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b) | identifier_body |
helpers.py | import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
from config.utils import *
import lp.db_semisuper as db_semisuper
import lp.db_eval as db_eval
from m... | (pred, y_a, y_b, lam):
criterion = nn.CrossEntropyLoss(reduction='none').cuda()
return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)
def train_sup(train_loader, model, optimizer, epoch, global_step, args, ema_model = None):
# switch to train mode
model.train()
for i, (aug_imag... | mixup_criterion | identifier_name |
scriptgenerator.py | #!/usr/bin/python3 -i
#
# Copyright 2013-2023 The Khronos Group Inc.
#
# SPDX-License-Identifier: Apache-2.0
from generator import OutputGenerator, enquote, noneStr
def mostOfficial(api, newapi):
"""Return the 'most official' of two related names, api and newapi.
KHR is more official than EXT is more offic... | """This creates the inverse mapping of nonexistent APIs in this
build to their aliases which are supported. Must be called by
language-specific subclasses before emitting that mapping."""
# Map from APIs not supported in this build to aliases that are.
# When there are multiple va... | identifier_body | |
scriptgenerator.py | #!/usr/bin/python3 -i
#
# Copyright 2013-2023 The Khronos Group Inc.
#
# SPDX-License-Identifier: Apache-2.0
from generator import OutputGenerator, enquote, noneStr
def | (api, newapi):
"""Return the 'most official' of two related names, api and newapi.
KHR is more official than EXT is more official than everything else.
If there is ambiguity, return api."""
if api[-3:] == 'KHR':
return api
if newapi[-3:] == 'KHR':
return newapi;
if api[-3:... | mostOfficial | identifier_name |
scriptgenerator.py | #!/usr/bin/python3 -i
#
# Copyright 2013-2023 The Khronos Group Inc.
#
# SPDX-License-Identifier: Apache-2.0
from generator import OutputGenerator, enquote, noneStr
def mostOfficial(api, newapi):
"""Return the 'most official' of two related names, api and newapi.
KHR is more official than EXT is more offic... | elif category == 'define':
self.defines[name] = None
elif category == 'basetype':
# Do not add an entry for base types that are not API types
# e.g. an API Bool type gets an entry, uint32_t does not
if self.a... | self.funcpointers[name] = None
elif category == 'handle':
self.handles[name] = None | random_line_split |
scriptgenerator.py | #!/usr/bin/python3 -i
#
# Copyright 2013-2023 The Khronos Group Inc.
#
# SPDX-License-Identifier: Apache-2.0
from generator import OutputGenerator, enquote, noneStr
def mostOfficial(api, newapi):
"""Return the 'most official' of two related names, api and newapi.
KHR is more official than EXT is more offic... |
if alias:
# Add name -> alias mapping
self.addName(self.alias, name, alias)
else:
# May want to only emit definition on this branch
True
# Otherwise, do not add it to the consts dictionary because it is
# already present. This happens du... | self.addName(self.typeCategory, name, 'consts')
self.consts[name] = None | conditional_block |
process.go | // Copyright 2015 The LUCI 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... | type overrideRoot struct {
Mutation
root *ds.Key
}
func (o overrideRoot) Root(context.Context) *ds.Key {
return o.root
}
func processRoot(c context.Context, cfg *Config, root *ds.Key, banSet stringset.Set, cnt *counter) error {
l := logging.Get(c)
toFetch, err := getBatchByRoot(c, cfg, root, banSet)
switch {
... | return mutKeys, muts, nil
}
| random_line_split |
process.go | // Copyright 2015 The LUCI 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... |
}
return mutKeys, muts, nil
}
type overrideRoot struct {
Mutation
root *ds.Key
}
func (o overrideRoot) Root(context.Context) *ds.Key {
return o.root
}
func processRoot(c context.Context, cfg *Config, root *ds.Key, banSet stringset.Set, cnt *counter) error {
l := logging.Get(c)
toFetch, err := getBatchByRo... | {
return nil, nil, me
} | conditional_block |
process.go | // Copyright 2015 The LUCI 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... |
func loadFilteredMutations(c context.Context, rms []*realMutation) ([]*ds.Key, []Mutation, error) {
mutKeys := make([]*ds.Key, 0, len(rms))
muts := make([]Mutation, 0, len(rms))
err := ds.Get(c, rms)
me, ok := err.(errors.MultiError)
if !ok && err != nil {
return nil, nil, err
}
for i, rm := range rms {
e... | {
q := ds.NewQuery("tumble.Mutation").Eq("TargetRoot", root)
if cfg.DelayedMutations {
q = q.Lte("ProcessAfter", clock.Now(c).UTC())
}
fetchAllocSize := cfg.ProcessMaxBatchSize
if fetchAllocSize < 0 {
fetchAllocSize = 0
}
toFetch := make([]*realMutation, 0, fetchAllocSize)
err := ds.Run(c, q, func(k *ds.Ke... | identifier_body |
process.go | // Copyright 2015 The LUCI 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... | (n int) int { return int(atomic.AddInt32((*int32)(c), int32(n))) }
// processRoundDelay calculates the delay to impose in between processing
// rounds.
type processRoundDelay struct {
cfg *Config
nextDelay time.Duration
}
func (prd *processRoundDelay) reset() {
// Reset our delay to DustSettleTimeout.
prd.n... | add | identifier_name |
server-tcp.ts | import { MatrixService } from './../db/matrix/matrix.service';
import { Trade } from './../common/models/trade';
import { ExchangeService } from './../db/exchange/exchange.service';
import { Order } from './../common/models/order';
const net = require('toa-net');
import { Parser } from './parser';
import { OrderBookSe... | generateOrderAfterCancel(message: any) {
const trades = this.parser.parseTrades(message);
if (trades) {
for (const trade of trades) {
this.orderService.updateStatusOrder(trade.arbitrageId, trade.typeOrder, trade.exchOrderId, 'cancelled', '');
const order: Order[] = this.parser.replaceCan... | }
| random_line_split |
server-tcp.ts | import { MatrixService } from './../db/matrix/matrix.service';
import { Trade } from './../common/models/trade';
import { ExchangeService } from './../db/exchange/exchange.service';
import { Order } from './../common/models/order';
const net = require('toa-net');
import { Parser } from './parser';
import { OrderBookSe... | trade.typeOrder, trade.exchOrderId, 'cancelled', '');
const order: Order[] = this.parser.replaceCancelledOrderByNewOrder(trade);
if (order) {
console.log('generateOrderAfterCancel call sendOrdersToBot :');
this.sendOrdersToBot(order);
}
}
}
}
createTcpServer()... | Order(trade.arbitrageId, | identifier_name |
server-tcp.ts | import { MatrixService } from './../db/matrix/matrix.service';
import { Trade } from './../common/models/trade';
import { ExchangeService } from './../db/exchange/exchange.service';
import { Order } from './../common/models/order';
const net = require('toa-net');
import { Parser } from './parser';
import { OrderBookSe... | identifier_body | ||
server-tcp.ts | import { MatrixService } from './../db/matrix/matrix.service';
import { Trade } from './../common/models/trade';
import { ExchangeService } from './../db/exchange/exchange.service';
import { Order } from './../common/models/order';
const net = require('toa-net');
import { Parser } from './parser';
import { OrderBookSe... | = await this.tradeService.findTrade(trade);
if (!sameTrade) {
console.log('sameTrade :', sameTrade);
const pureTrade = await this.parser.addNewArbitrageTrade(trade);
await this.arbitrageBalanceService.addNewTrade(pureTrade, trade.arbitrageId);
await this.parser.removeCheckerSentOrders(trade... | ) {
console.log(' 91 sendOrdersToBot( :');
await this.sendOrdersFromPromise(newOrder);
}
}
async countPureTrade(trade: Trade) {
const sameTrade | conditional_block |
projection_pushing.go | /*
Copyright 2022 The Vitess 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, soft... | }
func pushProjectionIntoSemiJoin(
ctx *plancontext.PlanningContext,
expr *sqlparser.AliasedExpr,
reuseCol bool,
node *semiJoin,
inner, hasAggregation bool,
) (int, bool, error) {
passDownReuseCol := reuseCol
if !reuseCol {
passDownReuseCol = expr.As.IsEmpty()
}
offset, added, err := pushProjection(ctx, exp... | return 0, false, err
}
}
}
return offset, added, nil | random_line_split |
projection_pushing.go | /*
Copyright 2022 The Vitess 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, soft... |
func rewriteProjectionOfDerivedTable(expr *sqlparser.AliasedExpr, semTable *semantics.SemTable) error {
ti, err := semTable.TableInfoForExpr(expr.Expr)
if err != nil && err != semantics.ErrNotSingleTable {
return err
}
_, isDerivedTable := ti.(*semantics.DerivedTable)
if isDerivedTable {
expr.Expr = semantic... | {
if reuseCol {
if i := checkIfAlreadyExists(expr, rb.Select, ctx.SemTable); i != -1 {
return i, false, nil
}
}
sqlparser.RemoveKeyspaceFromColName(expr.Expr)
sel, isSel := rb.Select.(*sqlparser.Select)
if !isSel {
return 0, false, vterrors.VT12001(fmt.Sprintf("pushing projection '%s' on %T", sqlparser.St... | identifier_body |
projection_pushing.go | /*
Copyright 2022 The Vitess 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, soft... |
column = offset + 1
appended = added
default:
// if an expression has aggregation, then it should not be split up and pushed to both sides,
// for example an expression like count(*) will have dependencies on both sides, but we should not push it
// instead we should return an error
if hasAggregation {
... | {
return 0, false, err
} | conditional_block |
projection_pushing.go | /*
Copyright 2022 The Vitess 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, soft... | (
ctx *plancontext.PlanningContext,
expr *sqlparser.AliasedExpr,
node *simpleProjection,
inner, hasAggregation, reuseCol bool,
) (int, bool, error) {
offset, _, err := pushProjection(ctx, expr, node.input, inner, true, hasAggregation)
if err != nil {
return 0, false, err
}
for i, value := range node.eSimplePr... | pushProjectionIntoSimpleProj | identifier_name |
app.js | $(function () {
var $fullText = $('.admin-fullText');
$('#admin-fullscreen').on('click', function () {
$.AMUI.fullscreen.toggle();
});
$(document).on($.AMUI.fullscreen.raw.fullscreenchange, function () {
$fullText.text($.AMUI.fullscreen.isFullscreen ? '退出全屏' : '开启全屏'); | });
var dataType = $('body').attr('data-type');
for (key in pageData) {
if (key == dataType) {
pageData[key]();
}
}
$('.tpl-switch').find('.tpl-switch-btn-view').on('click', function () {
$(this).prev('.tpl-switch-btn').prop("checked", function () {
... | random_line_split | |
app.js | $(function () {
var $fullText = $('.admin-fullText');
$('#admin-fullscreen').on('click', function () {
$.AMUI.fullscreen.toggle();
});
$(document).on($.AMUI.fullscreen.raw.fullscreenchange, function () {
$fullText.text($.AMUI.fullscreen.isFullscreen ? '退出全屏' : '开启全屏');
});
va... | conditional_block | ||
app.js | $(function () {
var $fullText = $('.admin-fullText');
$('#admin-fullscreen').on('click', function () {
$.AMUI.fullscreen.toggle();
});
$(document).on($.AMUI.fullscreen.raw.fullscreenchange, function () {
$fullText.text($.AMUI.fullscreen.isFullscreen ? '退出全屏' : '开启全屏');
});
va... | irstDate.getMonth());
if (month == "00") {
month = "12";
}
return year + "-" + month + "-" + parse0(firstDate.getDate());
}
/**
* 获取日期中月份的最后一天
* @param data
*/
function getEndDate(endDate) {
endDate.setMonth((endDate.getMonth() + 1));
endDate.setDate(0); //最后一天
return endDate.getF... | Year();
firstDate.setMonth((firstDate.getMonth() + 1));
var month = parse0(f | identifier_body |
app.js | $(function () {
var $fullText = $('.admin-fullText');
$('#admin-fullscreen').on('click', function () {
$.AMUI.fullscreen.toggle();
});
$(document).on($.AMUI.fullscreen.raw.fullscreenchange, function () {
$fullText.text($.AMUI.fullscreen.isFullscreen ? '退出全屏' : '开启全屏');
});
va... | 字串
args = {}, // 保存参数数据的对象
items = qs.length ? qs.split("&") : [], // 取得每一个参数项,
item = null,
len = items.length;
for (var i = 0; i < len; i++) {
item = items[i].split("=");
var name = decodeURIComponent(item[0]),
value = de... | / 获取url中"?"符后的 | identifier_name |
wsr98d_reader.rs | use crate::MetError;
use crate::STRadialData;
use binread::prelude::*;
use chrono::NaiveDateTime;
use encoding_rs::*;
use std::cmp::PartialEq;
use std::collections::HashMap;
use std::io::Cursor;
const DATA_TYPE: [&'static str; 37] = [
"dBT", "dBZ", "V", "W", "SQI", "CPA", "ZDR", "LDR", "CC", "PDP", "KDP", "CP", "R... | // println!("{:?}",own_data);
dt_data.insert(ddd.data_type.clone(), own_data);
}
let key = dd.elev_num;
let el = cut_infos[dd.elev_num as usize - 1].elev;
if !el_az_dt_data.contains_key(&key) {
el_az_dt_data.insert(key, vec![(el, dd.az, dt_data)]);
... | / // let print_data: Vec<&f32> =
// // own_data.iter().filter(|d| d != &&crate::MISSING).collect();
// println!(
// "{:?} {:?} {:?} {:?} ",
// dd.el,
// dd.az,
// ddd.data_type.clone(),
... | conditional_block |
wsr98d_reader.rs | use crate::MetError;
use crate::STRadialData;
use binread::prelude::*;
use chrono::NaiveDateTime;
use encoding_rs::*;
use std::cmp::PartialEq;
use std::collections::HashMap;
use std::io::Cursor;
const DATA_TYPE: [&'static str; 37] = [
"dBT", "dBZ", "V", "W", "SQI", "CPA", "ZDR", "LDR", "CC", "PDP", "KDP", "CP", "R... | let longtitude = h.longtitude;
let antena_height = h.antena_height;
let ground_height = h.ground_height;
let h: TaskInfo = cursor.read_le()?;
let start_date = h.start_date.clone();
let start_time = h.start_time.clone();
// dbg!(&h);
let cut_num = h.cut_num;
... | ude;
| identifier_name |
wsr98d_reader.rs | use crate::MetError;
use crate::STRadialData;
use binread::prelude::*;
use chrono::NaiveDateTime;
use encoding_rs::*;
use std::cmp::PartialEq;
use std::collections::HashMap;
use std::io::Cursor;
const DATA_TYPE: [&'static str; 37] = [
"dBT", "dBZ", "V", "W", "SQI", "CPA", "ZDR", "LDR", "CC", "PDP", "KDP", "CP", "R... | .iter()
.map(|v| {
if *v < 5 {
return crate::MISSING;
}
(*v as f32 - offset as f32) / scale as f32
// *v as f32
})
.... | })
.collect();
} else {
own_data = dt_slice | random_line_split |
user.go | package canvas
import (
"fmt"
"io"
"path"
"path/filepath"
"time"
)
// User is a canvas user
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Bio string `json:"bio"`
SortableName string ... | (opts ...Option) ([]*Course, error) {
return getCourses(u.client, u.id("/users/%d/courses"), optEnc(opts))
}
// FavoriteCourses returns the user's list of favorites courses.
func (u *User) FavoriteCourses(opts ...Option) ([]*Course, error) {
return getCourses(u.client, "/users/favorites/courses", optEnc(opts))
}
//... | Courses | identifier_name |
user.go | package canvas
import (
"fmt"
"io"
"path"
"path/filepath"
"time"
)
// User is a canvas user
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Bio string `json:"bio"`
SortableName string ... | return f, getjson(d, f, opts, "/users/%v/files/%d", userid, id)
}
func (u *User) id(s string) string {
return fmt.Sprintf(s, u.ID)
} | return resp.Body.Close()
}
func getUserFile(d doer, id int, userid interface{}, opts optEnc) (*File, error) {
f := &File{client: d} | random_line_split |
user.go | package canvas
import (
"fmt"
"io"
"path"
"path/filepath"
"time"
)
// User is a canvas user
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Bio string `json:"bio"`
SortableName string ... |
return resp.Body.Close()
}
func getUserFile(d doer, id int, userid interface{}, opts optEnc) (*File, error) {
f := &File{client: d}
return f, getjson(d, f, opts, "/users/%v/files/%d", userid, id)
}
func (u *User) id(s string) string {
return fmt.Sprintf(s, u.ID)
}
| {
return err
} | conditional_block |
user.go | package canvas
import (
"fmt"
"io"
"path"
"path/filepath"
"time"
)
// User is a canvas user
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Bio string `json:"bio"`
SortableName string ... |
func getUserFile(d doer, id int, userid interface{}, opts optEnc) (*File, error) {
f := &File{client: d}
return f, getjson(d, f, opts, "/users/%v/files/%d", userid, id)
}
func (u *User) id(s string) string {
return fmt.Sprintf(s, u.ID)
}
| {
path := fmt.Sprintf("users/%d/colors/%s", u.ID, asset)
if hexcode[0] == '#' {
hexcode = hexcode[1:]
}
resp, err := put(u.client, path, params{"hexcode": {hexcode}})
if err != nil {
return err
}
return resp.Body.Close()
} | identifier_body |
actions.py | # This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from ty... | #SlotSet('location_match', 'one'), SlotSet('rating', rating), SlotSet('address', address), SlotSet('opening_hours', opening_hours)
class ActionHelloWorld(Action):
def name(self) -> Text:
return "action_check_number"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
... | return [] #set returned details as slots | random_line_split |
actions.py | # This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from ty... | (
self,
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any],
) -> List[Dict]:
dispatcher.utter_message("Great! You're registered")
return []
def slot_mappings(self) -> Dict[Text,Union[Dict, List[Dict]]]:
return{
'name': ... | submit | identifier_name |
actions.py | # This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from ty... |
class ActionFallback(Action):
def name(self) -> Text:
return "action_default_fallback"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
dispatcher.utter_message(text="Sorry, I don't understand. Could you... | number=tracker.get_slot("phone")
name=tracker.get_slot("name")
if number in phones:
dispatcher.utter_message(text="You're already registered")
else:
names.append(name)
dispatcher.utter_message(text="You're added to the list!")
return [] | identifier_body |
actions.py | # This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from ty... |
else:
for i in range(0,3):
num=probability_score.nlargest(3,'value')['variable'].index[i]
symptom_list.append(probability_score.nlargest(3,'value')['variable'][num])
buttons = [{'title': symptom_list[0], 'payload': '/picking_specialty'},{'title': ... | num=probability_score.nlargest(3,'value')['variable'].index[i]
symptom_list.append(probability_score.nlargest(3,'value')['variable'][num])
buttons = [{'title': symptom_list[0], 'payload': '/picking_specialty'}] | conditional_block |
suite.go | package testutil
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"reflect"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/baseapp"
sdk "github.com/cosmos/cosmos-sdk/types"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authtypes "github.com/cosmos/cosmos-sdk/x/... |
func RandomEvmAddress() common.Address {
addr, _ := RandomEvmAccount()
return addr
}
func RandomInternalEVMAddress() types.InternalEVMAddress {
return types.NewInternalEVMAddress(RandomEvmAddress())
}
| {
privKey, err := ethsecp256k1.GenerateKey()
if err != nil {
panic(err)
}
addr := common.BytesToAddress(privKey.PubKey().Address())
return addr, privKey
} | identifier_body |
suite.go | package testutil
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"reflect"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/baseapp"
sdk "github.com/cosmos/cosmos-sdk/types"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authtypes "github.com/cosmos/cosmos-sdk/x/... | (addrStr string) types.InternalEVMAddress {
addr, err := types.NewInternalEVMAddressFromString(addrStr)
if err != nil {
panic(err)
}
return addr
}
func RandomEvmAccount() (common.Address, *ethsecp256k1.PrivKey) {
privKey, err := ethsecp256k1.GenerateKey()
if err != nil {
panic(err)
}
addr := common.BytesT... | MustNewInternalEVMAddressFromString | identifier_name |
suite.go | package testutil
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"reflect"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/baseapp"
sdk "github.com/cosmos/cosmos-sdk/types"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authtypes "github.com/cosmos/cosmos-sdk/x/... | abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/tmhash"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
tmtime "github.com/tendermint/tendermint/types/time"
"github.com/tendermint/te... | random_line_split | |
suite.go | package testutil
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"reflect"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/baseapp"
sdk "github.com/cosmos/cosmos-sdk/types"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authtypes "github.com/cosmos/cosmos-sdk/x/... | else {
suite.Truef(foundMatch, "event of type %s not found", expectedEvent.Type)
}
}
// EventsDoNotContain asserts that the event is **not** is in the provided events
func (suite *Suite) EventsDoNotContain(events sdk.Events, eventType string) {
foundMatch := false
for _, event := range events {
if event.Type =... | {
suite.ElementsMatch(expectedAttrs, possibleFailedMatch, "unmatched attributes on event of type %s", expectedEvent.Type)
} | conditional_block |
# WAD SERVER TEST as MULTI-1.py | # WAD SERVER (DRONE JONGHAP GUWANJE SYSTEM)
# Licence Isaac Kim-leader of team RETELLIGENCE
# 2016
import threading
from socket import *
import time
import os
import random
from datetime import datetime
print('**************************************************************************')
print('*... |
time.sleep(10)
if stat == 'e':
disconnect_all()
if (__name__ == "__main__"): # modulize
main()
| prints = False
break | conditional_block |
# WAD SERVER TEST as MULTI-1.py | # WAD SERVER (DRONE JONGHAP GUWANJE SYSTEM)
# Licence Isaac Kim-leader of team RETELLIGENCE
# 2016
import threading
from socket import *
import time
import os
import random
from datetime import datetime
print('**************************************************************************')
print('*... | connectionSocket.send(server_Rx_wad)
def APP(port):
def Make_id_i():
global WAD_pinlist
type_WAD = 'i'
year_WAD = str((time.localtime(time.time()))[0])
pin_WAD = str(int(WAD_pinList[-1]) + 1)
if len(pin_WAD) > 4:
... | random_line_split | |
# WAD SERVER TEST as MULTI-1.py | # WAD SERVER (DRONE JONGHAP GUWANJE SYSTEM)
# Licence Isaac Kim-leader of team RETELLIGENCE
# 2016
import threading
from socket import *
import time
import os
import random
from datetime import datetime
print('**************************************************************************')
print('*... | ():
global WAD_pinlist
type_WAD = 'i'
year_WAD = str((time.localtime(time.time()))[0])
pin_WAD = str(int(WAD_pinList[-1]) + 1)
if len(pin_WAD) > 4:
pin_WAD = pin_WAD[0:4]
ID_WAD = type_WAD + year_WAD[-2] + year_WAD[-1] + '0'*(4-len(pin_WAD)) + str(... | Make_id_i | identifier_name |
# WAD SERVER TEST as MULTI-1.py | # WAD SERVER (DRONE JONGHAP GUWANJE SYSTEM)
# Licence Isaac Kim-leader of team RETELLIGENCE
# 2016
import threading
from socket import *
import time
import os
import random
from datetime import datetime
print('**************************************************************************')
print('*... |
def start_socket():
server_adr = getadr()
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind((server_adr, main_port))
serverSocket.listen(1)
connectionSocket, addr = serverSocket.accept()
##
### RETELLIGENCE WADING IN--on new thread
##class WADING(threading.Tread):
#... | pass | identifier_body |
AlfaReativo.py | import random
import sys
import math
import time
n = 2
num_section = 2
cargo = {1:"ferro", 2:"bauxita", 3:"cobre", 4:"prata"}
#print cargo[3]
# time = [0,0,0,0,0,0,0]
num_time = 1000
section = [0,0]
alpha = 3
alphaV = 20
alphaN = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
pAlphaN = [[0,9],[10,19],[20,29],[30,39],[40,... | n yards:
y.time = 1
def new_heuristic_2opt(vessels, sections, yards, alfaqqr):
# vesselsord = sorted(vessels, key=lambda vessel: vessel.a)
vesselsord = vessels
# for v in vessels:
# v.printing()
columns = []
menor = sections[0]
menorTime = sections[0].t
while(vesselsord != []):
#pegando o melhor navio
... | for y i | conditional_block |
AlfaReativo.py | import random
import sys
import math
import time
n = 2
num_section = 2
cargo = {1:"ferro", 2:"bauxita", 3:"cobre", 4:"prata"}
#print cargo[3]
# time = [0,0,0,0,0,0,0]
num_time = 1000
section = [0,0]
alpha = 3
alphaV = 20
alphaN = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
pAlphaN = [[0,9],[10,19],[20,29],[30,39],[40,... | printing(self):
print("Carga "+self.n)
class Vessel:
def __init__(self, name, cargo_type, lenght, arrival):
self.n = name
self.c_t = cargo_type
self.l = lenght
self.a = arrival
def printing(self):
print ("Vessel "+self.n)
#print (self.c_t, self.l, self.d)
#class Yard has the cargo type, the distanc... | n self.r
def | identifier_body |
AlfaReativo.py | import random
import sys
import math
import time
n = 2
num_section = 2
cargo = {1:"ferro", 2:"bauxita", 3:"cobre", 4:"prata"}
#print cargo[3]
# time = [0,0,0,0,0,0,0]
num_time = 1000
section = [0,0]
alpha = 3
alphaV = 20
alphaN = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
pAlphaN = [[0,9],[10,19],[20,29],[30,39],[40,... | # vesselsord = sorted(vessels, key=lambda vessel: vessel.a)
vesselsord = vessels
# for v in vessels:
# v.printing()
columns = []
menor = sections[0]
menorTime = sections[0].t
while(vesselsord != []):
#pegando o melhor navio
# v = vesselsord.pop(0)
#pegando os alpha melhores navios
melhoresVessels = [... | s.t = 1
for y in yards:
y.time = 1
def new_heuristic_2opt(vessels, sections, yards, alfaqqr): | random_line_split |
AlfaReativo.py | import random
import sys
import math
import time
n = 2
num_section = 2
cargo = {1:"ferro", 2:"bauxita", 3:"cobre", 4:"prata"}
#print cargo[3]
# time = [0,0,0,0,0,0,0]
num_time = 1000
section = [0,0]
alpha = 3
alphaV = 20
alphaN = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
pAlphaN = [[0,9],[10,19],[20,29],[30,39],[40,... | f __init__(self, vessel, section, yard, beta, time):
self.s = section
self.y = yard
self.beta = beta
self.alfa = alfa
self.h_t = alfa + beta #handling time = tempo de load/unload da carga + tempo de transferencia da carga
self.v = vessel
self.s_t = time #starting time
self.c_t = ""
def printing(self):
... | n:
de | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.