file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
serde_snapshot.rs
genesis_config::ClusterType, genesis_config::GenesisConfig, hard_forks::HardForks, hash::Hash, inflation::Inflation, pubkey::Pubkey, }, std::{ collections::{HashMap, HashSet}, io::{BufReader, BufWriter, Read, Write}, path::{Path, PathBuf}, ...
<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: serde::ser::Serializer, { C::serialize_bank_and_storage(serializer, self) } } struct SerializableAccountsDB<'a, C> { accounts_db: &'a AccountsDB, slot: Slot, account_storage_entries: &'a [SnapshotStorage]...
serialize
identifier_name
serde_snapshot.rs
genesis_config::ClusterType, genesis_config::GenesisConfig, hard_forks::HardForks, hash::Hash, inflation::Inflation, pubkey::Pubkey, }, std::{ collections::{HashMap, HashSet}, io::{BufReader, BufWriter, Read, Write}, path::{Path, PathBuf}, ...
let mut remaining_slots_to_process = storage.len(); // Remap the deserialized AppendVec paths to point to correct local paths let mut storage = storage .into_iter() .map(|(slot, mut slot_storage)| { let now = Instant::now(); if now.duration_since(last_log_update).as_...
{ let mut accounts_db = AccountsDB::new(account_paths.to_vec(), cluster_type); let AccountsDbFields(storage, version, slot, bank_hash_info) = accounts_db_fields; // convert to two level map of slot -> id -> account storage entry let storage = { let mut map = HashMap::new(); for (slot, ...
identifier_body
control.go
MsgSendertoSMO: MsgSendertoSMO, //subscriber: subscriber, AccessDbagent: AcessDbAgent, Endpoint: endpoint, } return c } func (c *Control) ReadyCB(data interface{}) { if c.MsgSendertoSMO == nil { } } func (c *Control) CreateAndRunMsgServer (grpcAddr string) { svc := service.NewMsgService(c) ep := endpo...
.Info("XappName = %s,XappRequestID = %d,Token = %s /n", RegMsg.XappName,RegMsg.Header.XappRequestID,RegMsg.Header.Token) //第一个消息,xapp还没获取到topic,需要通过grpc来返回注册响应消息 Client2Xapp := msgx.NewMsgSender(RegMsg.XappIpaddr,RegMsg.XappPort) //分配xappID ; 并判断是否重复注册 XappID,err,isRegistered := c.allocXappID(RegMsg) if err !=...
return } xapp.Logger
identifier_name
control.go
//subscriber: subscriber, AccessDbagent: AcessDbAgent, Endpoint: endpoint, } return c } func (c *Control) ReadyCB(data interface{}) { if c.MsgSendertoSMO == nil { } } func (c *Control) CreateAndRunMsgServer (grpcAddr string) { svc := service.NewMsgService(c) ep := endpoint.NewMsgServiceEndpoint(svc) ...
MsgSendertoSMO: MsgSendertoSMO,
random_line_split
control.go
Ready = "false" m.Topic = "Xapp_"+strconv.Itoa(int(XappID))+"_topic" r.MoiTable = m _, err := c.AccessDbagent.Client.MOITableInsert(context.Background(),r) return err } //通知网管该xApp在nRT RIC平台上的部署 func (c *Control) Register2SMO (RegMsg *msgx.XappRegMsg,params *xapp.MsgParams){ RICO1RegMsg,err := proto.Marshal(...
conditional_block
control.go
func (c *Control) ReadyCB(data interface{}) { if c.MsgSendertoSMO == nil { } } func (c *Control) CreateAndRunMsgServer (grpcAddr string) { svc := service.NewMsgService(c) ep := endpoint.NewMsgServiceEndpoint(svc) s := transport.NewMsgServer(ep) // The gRPC listener mounts the Go kit gRPC server we crea...
{ endpoint := make(map[uint32]*msgx.KafkaMsgSender) c := &Control{ //MsgClientToXapp: MsgClientToXapp, MsgSendertoSMO: MsgSendertoSMO, //subscriber: subscriber, AccessDbagent: AcessDbAgent, Endpoint: endpoint, } return c }
identifier_body
daemon.go
a Gateway // for RPC calls liteModeDeps := node.Options() if isLite { gapi, closer, err := lcli.GetGatewayAPI(cctx) if err != nil { return err } defer closer() liteModeDeps = node.Override(new(lapi.Gateway), gapi) } // some libraries like ipfs/go-ds-measure and ipfs/go-ipfs-blockstore ...
removeExistingChain
identifier_name
daemon.go
return xerrors.Errorf("restoring from backup is only possible with a fresh repo!") } if err := restore(cctx, r); err != nil { return xerrors.Errorf("restoring from backup: %w", err) } } if cctx.Bool("remove-existing-chain") { lr, err := repo.NewFS(cctx.String("repo")) if err != nil { ret...
{ log.Errorw("closing zstd reader", "error", err) }
conditional_block
daemon.go
, }, &cli.StringFlag{ Name: "import-chain", Usage: "on first run, load chain from given file or url and validate", }, &cli.StringFlag{ Name: "import-snapshot", Usage: "import chain state from a given chain export file or url", }, &cli.BoolFlag{ Name: "remove-existing-chain", Usage: "rem...
{ dir, err := homedir.Expand(cctx.String("repo")) if err != nil { log.Warnw("could not expand repo location", "error", err) } else { log.Infof("lotus repo: %s", dir) } } r, err := repo.NewFS(cctx.String("repo")) if err != nil { return xerrors.Errorf("opening fs repo: %w", err) } if...
random_line_split
daemon.go
_, err := ulimit.ManageFdLimit(); err != nil { log.Errorf("setting file descriptor limit: %s", err) } } if prof := cctx.String("pprof"); prof != "" { profile, err := os.Create(prof) if err != nil { return err } if err := pprof.StartCPUProfile(profile); err != nil { return err } d...
{ f, err := homedir.Expand(f) if err != nil { return err } hexdata, err := os.ReadFile(f) if err != nil { return err } data, err := hex.DecodeString(strings.TrimSpace(string(hexdata))) if err != nil { return err } var ki types.KeyInfo if err := json.Unmarshal(data, &ki); err != nil { return err }
identifier_body
store.rs
use core::{ cmp::Eq, fmt::{ Binary, Debug, Display, LowerHex, UpperHex, }, mem::size_of, ops::{ BitAnd, BitAndAssign, BitOrAssign, Not, Shl, ShlAssign, Shr, ShrAssign, }, }; #[cfg(feature = "atomic")] use core::sync::atomic::{ self, Ordering::Relaxed, }; #[cfg(not(feature = "atomic")...
use crate::{ cursor::Cursor, indices::BitIdx, };
random_line_split
store.rs
_ones #[inline(always)] fn count_zeros(&self) -> usize { // invert (0 becomes 1, 1 becomes 0), zero-extend, count ones u64::count_ones((!*self).into()) as usize } /// Extends a single bit to fill the entire element. /// /// # Parameters /// /// - `bit`: The bit to extend. /// /// # Returns /// /// An ...
self.fetch_and(!*C::mask(bit), Relaxed); }
identifier_body
store.rs
"32")] pub type Word = u32; /// Type alias to the CPU word element, `u64`. #[cfg(target_pointer_width = "64")] pub type Word = u64; /** Common interface for atomic and cellular shared-mutability wrappers. `&/mut BitSlice` contexts must use the `BitStore::Nucleus` type for all reference production, and must route th...
ad(&
identifier_name
store.rs
`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be set according to `value`. /// - `value`: A Boolean value, which sets the bit on `true` and clears it /// on `false`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a p...
else { *self &= !mask; } } /// Gets a specific bit in an element. /// /// # Safety /// /// This method cannot be called from within a `&BitSlice` context; it may /// only be called by construction of an `&Self` reference from a `Self` /// element directly. /// /// # Parameters /// /// - `place`: A bi...
*self |= mask; }
conditional_block
game.go
ObstructionProgression/2)) } case MistLevel: g.PrintStyled("The air seems dense on this level.", logSpecial) g.StoryPrint("Special event: mist level") for i := 0; i < 20; i++ { g.PushEvent(&posEvent{Action: MistProgression}, g.Turn+DurationMistProgression+RandInt(DurationMistProgression/2)) } case Ea...
if g.Player.HP <= 0 { if g.Wizard { g.Player.HP = g.Player.HPMax() g.PrintStyled("You died.", logSpecial) g.StoryPrint("You died (wizard mode)") } else { g.LevelStats() return true } } return false }
identifier_body
game.go
ml = RandomSmallWalkCaveUrbanised } else if RandInt(10) == 0 { ml = NaturalCave } } g.GenRoomTunnels(ml) } func (g *game) InitPlayer() { g.Player = &player{ HP: DefaultHealth, MP: DefaultMPmax, Bananas: 1, } g.Player.LOS = map[gruid.Point]bool{} g.Player.Statuses = map[status]int{} g.Play...
if RandInt(4) == 0 { if RandInt(2) == 0 { g.Params.Special[3] = roomFrogs } else { g.Params.Special[7] = roomFrogs } } if RandInt(4) == 0 { g.Params.Special[10], g.Params.Special[5] = g.Params.Special[5], g.Params.Special[10] } if RandInt(4) == 0 { g.Params.Special[6], g.Params.Special[7] = g.Para...
{ if g.Params.Special[5] == roomNixes { g.Params.Special[9] = roomVampires } else { g.Params.Special[9] = roomNixes } }
conditional_block
game.go
ml = RandomSmallWalkCaveUrbanised } else if RandInt(10) == 0 { ml = NaturalCave } } g.GenRoomTunnels(ml) } func (g *game) InitPlayer() { g.Player = &player{ HP: DefaultHealth, MP: DefaultMPmax, Bananas: 1, } g.Player.LOS = map[gruid.Point]bool{} g.Player.Statuses = map[status]int{} g.Play...
(m map[int]bool, n int) { for i := 0; i < n; i++ { j := 1 + RandInt(MaxDepth) if !m[j] { m[j] = true } else { i-- } } } func (g *game) InitFirstLevel() { g.Version = Version g.Depth++ // start at 1 g.InitPlayer() g.AutoTarget = invalidPos g.RaysCache = rayMap{} g.GeneratedLore = map[int]bool{} g...
PutRandomLevels
identifier_name
game.go
ml = RandomSmallWalkCaveUrbanised } else if RandInt(10) == 0 { ml = NaturalCave } } g.GenRoomTunnels(ml) } func (g *game) InitPlayer() { g.Player = &player{ HP: DefaultHealth, MP: DefaultMPmax, Bananas: 1, } g.Player.LOS = map[gruid.Point]bool{} g.Player.Statuses = map[status]int{} g.Pla...
} if RandInt(4) == 0 { g.GenPlan[MaxDepth-1], g.GenPlan[MaxDepth] = g.GenPlan[MaxDepth], g.GenPlan[MaxDepth-1] } g.Params.CrazyImp = 2 + RandInt(MaxDepth-2) g.PR = paths.NewPathRange(gruid.NewRange(0, 0, DungeonWidth, DungeonHeight)) g.PRauto = paths.NewPathRange(gruid.NewRange(0, 0, DungeonWidth, DungeonHeight...
g.GenPlan[6], g.GenPlan[7] = g.GenPlan[7], g.GenPlan[6]
random_line_split
gogl.go
, nil) // todo should use gl.RED on OpenGL, gl.ALPHA on OpenGL ES gl.Enable(gl.BLEND) gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) gl.Enable(gl.STENCIL_TEST) gl.StencilMask(0xFF) gl.Clear(gl.STENCIL_BUFFER_BIT) gl.StencilOp(gl.KEEP, gl.KEEP, gl.KEEP) gl.StencilFunc(gl.EQUAL, 0, 0xFF) gl.Disable(gl.SCIS...
return bo, nil } // SetBounds updates the bounds of the canvas. This would // usually be called for example when the window is resized func (b *GoGLBackend) SetBounds(x, y, w, h int) { b.x, b.y = x, y b.fx, b.fy = float64(x), float64(y) b.w, b.h = w, h b.fw, b.fh = float64(w), float64(h) if b == activeContext ...
{ b, err := New(0, 0, w, h, ctx) if err != nil { return nil, err } bo := &GoGLBackendOffscreen{GoGLBackend: *b} bo.offscrBuf.alpha = alpha bo.offscrImg.flip = true bo.activateFn = func() { bo.enableTextureRenderTarget(&bo.offscrBuf) gl.Viewport(0, 0, int32(bo.w), int32(bo.h)) bo.offscrImg.w = bo.offscrB...
identifier_body
gogl.go
, nil) // todo should use gl.RED on OpenGL, gl.ALPHA on OpenGL ES gl.Enable(gl.BLEND) gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) gl.Enable(gl.STENCIL_TEST) gl.StencilMask(0xFF) gl.Clear(gl.STENCIL_BUFFER_BIT) gl.StencilOp(gl.KEEP, gl.KEEP, gl.KEEP) gl.StencilFunc(gl.EQUAL, 0, 0xFF) gl.Disable(gl.SCIS...
} // SetSize updates the size of the offscreen texture func (b *GoGLBackendOffscreen) SetSize(w, h int) { b.GoGLBackend.SetBounds(0, 0, w, h) b.offscrImg.w = b.offscrBuf.w b.offscrImg.h = b.offscrBuf.h } // Size returns the size of the window or offscreen // texture func (b *GoGLBackend) Size() (int, int) { retu...
{ gl.Viewport(0, 0, int32(b.w), int32(b.h)) gl.Clear(gl.STENCIL_BUFFER_BIT) }
conditional_block
gogl.go
, nil) // todo should use gl.RED on OpenGL, gl.ALPHA on OpenGL ES gl.Enable(gl.BLEND) gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) gl.Enable(gl.STENCIL_TEST) gl.StencilMask(0xFF) gl.Clear(gl.STENCIL_BUFFER_BIT) gl.StencilOp(gl.KEEP, gl.KEEP, gl.KEEP) gl.StencilFunc(gl.EQUAL, 0, 0xFF) gl.Disable(gl.SCIS...
(x, y, w, h int, ctx *GLContext) (*GoGLBackend, error) { if ctx == nil { var err error ctx, err = NewGLContext() if err != nil { return nil, err } } b := &GoGLBackend{ w: w, h: h, fw: float64(w), fh: float64(h), GLContext: ctx, } b.activateFn = func() { gl.Bin...
New
identifier_name
gogl.go
= w, h b.fw, b.fh = float64(w), float64(h) if b == activeContext { gl.Viewport(0, 0, int32(b.w), int32(b.h)) gl.Clear(gl.STENCIL_BUFFER_BIT) } } // SetSize updates the size of the offscreen texture func (b *GoGLBackendOffscreen) SetSize(w, h int) { b.GoGLBackend.SetBounds(0, 0, w, h) b.offscrImg.w = b.offscr...
random_line_split
main-ipc.ts
the window */ ipc.on('minimize-window', (event) => { if (BrowserWindow.getFocusedWindow()) { BrowserWindow.getFocusedWindow().minimize(); } }); /** * Open the explorer to the relevant file */ ipc.on('open-in-explorer', (event, fullPath: string) => { shell.showItemInFolder(fullPath);...
/** * Method to replace thumbnail of a particular item */ ipc.on('replace-thumbnail', (event, pathToIncomingJpg: string, item: ImageElement) => { const fileToReplace: string = path.join( GLOBALS.selectedOutputFolder, 'vha-' + GLOBALS.hubName, 'thumbnails', item.hash + '.j...
{ fs.access(fileToDelete, fs.constants.F_OK, (err: any) => { if (err) { console.log('FILE DELETED SUCCESS !!!') event.sender.send('file-deleted', item); } }); }
identifier_body
main-ipc.ts
imize the window */ ipc.on('minimize-window', (event) => { if (BrowserWindow.getFocusedWindow()) { BrowserWindow.getFocusedWindow().minimize(); } }); /** * Open the explorer to the relevant file */ ipc.on('open-in-explorer', (event, fullPath: string) => { shell.showItemInFolder(fullP...
* Method to replace thumbnail of a particular item */ ipc.on('replace-thumbnail', (event, pathToIncomingJpg: string, item: ImageElement) => { const fileToReplace: string = path.join( GLOBALS.selectedOutputFolder, 'vha-' + GLOBALS.hubName, 'thumbnails', item.hash + '.jpg' ...
} }); } /**
random_line_split
main-ipc.ts
the window */ ipc.on('minimize-window', (event) => { if (BrowserWindow.getFocusedWindow()) { BrowserWindow.getFocusedWindow().minimize(); } }); /** * Open the explorer to the relevant file */ ipc.on('open-in-explorer', (event, fullPath: string) => { shell.showItemInFolder(fullPath);...
(event, fileToDelete, item) { fs.access(fileToDelete, fs.constants.F_OK, (err: any) => { if (err) { console.log('FILE DELETED SUCCESS !!!') event.sender.send('file-deleted', item); } }); } /** * Method to replace thumbnail of a particular item */ ipc.on('replace-thumbnai...
notifyFileDeleted
identifier_name
main-ipc.ts
because on windows, the path sometimes is mixing `\` and `/` // shell.openPath(path.normalize(fullFilePath)); // Electron 9 } else { event.sender.send('file-not-found'); } }); }); /** * Open a particular video file clicked inside Angular at particular timestamp */ ipc.on('o...
{ errMsg = 'RIGHTCLICK.errorSomeError'; }
conditional_block
helpers.go
.ParseCIDR(network.PodCIDR()) if err != nil { dPodcidr = nil } _, dServicecidr, err = net.ParseCIDR(network.ServiceCIDR()) if err != nil { dServicecidr = nil } dhostPrefix, _ = network.GetHostPrefix() return dMachinecidr, dPodcidr, dServicecidr, dhostPrefix, computeInstanceType } func (c *Client) LogEvent(k...
func (c *Client) IsCapabilityEnabled(capability string) (enabled bool, err error) { organizationID, _, err := c.GetCurrentOrganization() if err != nil { return } isCapabilityEnable, err := c.isCapabilityEnabled(capability, organizationID) if err != nil { return } if !isCapabilityEnable { return false, nil...
externalID = acctResponse.Organization().ExternalID() return }
random_line_split
helpers.go
segments := version.Segments() return fmt.Sprintf("%d.%d", segments[0], segments[1]) } func CheckSupportedVersion(clusterVersion string, operatorVersion string) (bool, error) { v1, err := semver.NewVersion(clusterVersion) if err != nil { return false, err } v2, err := semver.NewVersion(operatorVersion) if err...
{ return fmt.Errorf("The number of availability zones for a single AZ cluster should be %d, "+ "instead received: %d", singleAZCount, availabilityZonesCount) }
conditional_block
helpers.go
.ParseCIDR(network.PodCIDR()) if err != nil { dPodcidr = nil } _, dServicecidr, err = net.ParseCIDR(network.ServiceCIDR()) if err != nil { dServicecidr = nil } dhostPrefix, _ = network.GetHostPrefix() return dMachinecidr, dPodcidr, dServicecidr, dhostPrefix, computeInstanceType } func (c *Client) LogEvent(k...
func (c *Client) GetCurrentAccount() (*amsv1.Account, error) { response, err := c.ocm.AccountsMgmt().V1(). CurrentAccount(). Get(). Send() if err != nil { if response.Status() == http.StatusNotFound { return nil, nil } return nil, handleErr(response.Error(), err) } return response.Body(), nil } fu...
{ event, err := cmv1.NewEvent().Key(key).Body(body).Build() if err == nil { _, _ = c.ocm.ClustersMgmt().V1(). Events(). Add(). Body(event). Send() } }
identifier_body
helpers.go
gmt().V1(). CurrentAccount(). Get(). Send() if err != nil { if response.Status() == http.StatusNotFound { return nil, nil } return nil, handleErr(response.Error(), err) } return response.Body(), nil } func (c *Client) GetCurrentOrganization() (id string, externalID string, err error) { acctResponse,...
CheckRoleExists
identifier_name
reconciler.go
concileFailed", "Failed to reconcile Data Plane resource(s): %s", err.Error()) return err } ps.Status.MarkDeployed() return nil } func (r *Base) reconcileSubscription(ctx context.Context, ps *v1alpha1.PullSubscription) (string, error) { if ps.Status.ProjectID == "" { projectID, err := utils.ProjectID(ps.Spec...
{ loggingConfig, err := logging.LoggingConfigToJson(r.LoggingConfig) if err != nil { logging.FromContext(ctx).Desugar().Error("Error serializing existing logging config", zap.Error(err)) } if r.MetricsConfig != nil { component := sourceComponent // Set the metric component based on the channel label. if _,...
identifier_body
reconciler.go
ClientFn(ctx, ps.Status.ProjectID) if err != nil { logging.FromContext(ctx).Desugar().Error("Failed to create Pub/Sub client", zap.Error(err)) return "", err } defer client.Close() // Generate the subscription name subID := resources.GenerateSubscriptionName(ps) // Load the subscription. sub := client.Subs...
GetOrCreateReceiveAdapter
identifier_name
reconciler.go
may no longer exist, in which case we stop processing. logging.FromContext(ctx).Desugar().Error("PullSubscription in work queue no longer exists") return nil } else if err != nil { return err } // Don't modify the informers copy ps := original.DeepCopy() // Reconcile this copy of the PullSubscription and ...
else { // If the transformer is nil, mark is as nil and clean up the URI. ps.Status.MarkNoTransformer("TransformerNil", "Transformer is nil") ps.Status.TransformerURI = "" } r.addFinalizer(ps) subscriptionID, err := r.reconcileSubscription(ctx, ps) if err != nil { ps.Status.MarkNoSubscription("Subscripti...
{ transformerURI, err := r.resolveDestination(ctx, *ps.Spec.Transformer, ps) if err != nil { ps.Status.MarkNoTransformer("InvalidTransformer", err.Error()) } else { ps.Status.MarkTransformer(transformerURI) } }
conditional_block
reconciler.go
// If we didn't change anything then don't call updateStatus. // This is important because the copy we loaded from the informer's // cache may be stale and we don't want to overwrite a prior update // to status with this stale state. } else if uErr := r.updateStatus(ctx, original, ps); uErr != nil { logging...
}
random_line_split
utils.py
Options() opts.store_states = True result = sesolve(H_evol, final_state, tlist, e_ops=[observable], options=opts) full_signal = result.expect signal = full_signal[0].real signal_fft = np.fft.fft(signal) freq = np.fft.fftfreq(signal.shape[-1]) freq_normalized = np.abs(f...
@numba.njit def jensen_shannon(hist1, hist2): ''' Returns the Jensen Shannon divergence between two probabilities distribution represented as histograms. Arguments: --------- - hist1: tuple of numpy.ndarray (density, bins), len(bins) = len(density) + 1. The integral...
""" Returns the entropy of a discrete distribution p Arguments: --------- - p: numpy.Ndarray dimension 1 non-negative floats summing to 1 Returns: -------- - float, value of the entropy """ assert (p >= 0).all() assert abs(np.sum(p)-1) < 1e-6 return -np.sum(p*np.log(p+1e-12...
identifier_body
utils.py
, evol='xy'): """ Returns the final state after the following evolution: - start with empty sate with as many qubits as vertices of G - uniform superposition of all states - alternating evolution of H_evol during times, and H_m during pulses Arguments: --------- - G: graph networkx.Grap...
masses1 = distributions1[i] masses2 = distributions2[j] js = entropy((masses1+masses2)/2) -\ entropy(masses1)/2 - entropy(masses2)/2 js_matrix[i, j] = js
conditional_block
utils.py
Options() opts.store_states = True result = sesolve(H_evol, final_state, tlist, e_ops=[observable], options=opts) full_signal = result.expect signal = full_signal[0].real signal_fft = np.fft.fft(signal) freq = np.fft.fftfreq(signal.shape[-1]) freq_normalized = np.abs(f...
- all_states: list of qutip.Qobj final states of evolution, same lenght as graphs_list """ all_states = [] for G in tqdm(graphs_list, disable=verbose==0): all_states.append(return_evolution(G, times, pulses, evol)) return all_states def return_energy_distribution(graphs_li...
--------
random_line_split
utils.py
hist1[1][j]: j += 1 masses1.append((b-bins[i]) * hist1[0][j-1]) if b <= hist2[1][0]: masses2.append(0.) elif b > hist2[1][-1]: masses2.append(0.) else: j = 0 while b > hist2[1][j]: j += 1 ma...
return_js_square_matrix
identifier_name
instance.go
} cmdInstance = &Command{ Name: "instance", Usage: "[OPTION]...", Summary: "Operations to view instances.", Subcommands: []*Command{ cmdInstanceListUpdates, cmdInstanceListAppVersions, cmdInstanceDeis, }, } cmdInstanceListUpdates = &Command{ Name: "instance list-updates", Usage: ...
return req } func (c *Client) MakeRequest(otype, result string, updateCheck, isPing bool) (*omaha.Response, error) { client := &http.Client{} req := c.OmahaRequest(otype, result, updateCheck, isPing) raw, err := xml.MarshalIndent(req, "", " ") if err != nil { return nil, err } resp, err := client.Post(c.co...
{ event := app.AddEvent() event.Type = otype event.Result = result if result == "0" { event.ErrorCode = "2000" } else { event.ErrorCode = "" } }
conditional_block
instance.go
0, "End date filter") cmdInstanceListAppVersions.Flags.Var(&instanceFlags.groupId, "group-id", "Group id") cmdInstanceListAppVersions.Flags.Var(&instanceFlags.appId, "app-id", "App id") cmdInstanceListAppVersions.Flags.Int64Var(&instanceFlags.start, "start", 0, "Start date filter") cmdInstanceListAppVersions.Flags...
{ r := m if m-n > 0 { r = rand.Intn(m-n) + n } time.Sleep(time.Duration(r) * time.Second) }
identifier_body
instance.go
} cmdInstance = &Command{ Name: "instance", Usage: "[OPTION]...", Summary: "Operations to view instances.", Subcommands: []*Command{ cmdInstanceListUpdates, cmdInstanceListAppVersions, cmdInstanceDeis, }, } cmdInstanceListUpdates = &Command{ Name: "instance list-updates", Usage: ...
(otype, result string, updateCheck, isPing bool) *omaha.Request { req := omaha.NewRequest("lsb", "CoreOS", "", "") app := req.AddApp(c.AppId, c.Version) app.MachineID = c.Id app.BootId = c.SessionId app.Track = c.Track app.OEM = instanceFlags.OEM if updateCheck { app.AddUpdateCheck() } if isPing { app.Ad...
OmahaRequest
identifier_name
instance.go
} cmdInstance = &Command{ Name: "instance", Usage: "[OPTION]...", Summary: "Operations to view instances.", Subcommands: []*Command{ cmdInstanceListUpdates, cmdInstanceListAppVersions, cmdInstanceDeis, }, } cmdInstanceListUpdates = &Command{ Name: "instance list-updates", Usage:...
errorRate int pingsRemaining int } func (c *Client) Log(format string, v ...interface{}) { format = c.Id + ": " + format fmt.Printf(format, v...) } func (c *Client) getCodebaseUrl(uc *omaha.UpdateCheck) string { return uc.Urls.Urls[0].CodeBase } func (c *Client) updateservice() { fmt.Println("starting sys...
SessionId string Version string AppId string Track string config *serverConfig
random_line_split
peer.rs
&& version.start_height >= self.min_start_height && version.services & (NODE_BITCOIN_CASH | NODE_NETWORK) != 0 } } /// Node on the network to send and receive messages /// /// It will setup a connection, respond to pings, and store basic properties about the connection, /// but any real log...
{ // Connect over TCP let tcp_addr = SocketAddr::new(self.ip, self.port); let mut tcp_stream = TcpStream::connect_timeout(&tcp_addr, CONNECT_TIMEOUT)?; tcp_stream.set_nodelay(true)?; // Disable buffering tcp_stream.set_read_timeout(Some(HANDSHAKE_READ_TIMEOUT))?; tcp_stre...
identifier_body
peer.rs
all peers except for Bitcoin SV full nodes #[derive(Clone, Default, Debug)] pub struct SVPeerFilter { pub min_start_height: i32, } impl SVPeerFilter { /// Creates a new SV filter that requires a minimum starting chain height pub fn new(min_start_height: i32) -> Arc<SVPeerFilter> { Arc::new(SVPeerF...
// Always check the connected flag right after the blocking read so we exit right away, // and also so that we don't mistake errors with the stream shutting down if !tpeer.connected.load(Ordering::Relaxed) { return; } m...
None => Message::read(&mut tcp_reader, magic), };
random_line_split
peer.rs
all peers except for Bitcoin SV full nodes #[derive(Clone, Default, Debug)] pub struct SVPeerFilter { pub min_start_height: i32, } impl SVPeerFilter { /// Creates a new SV filter that requires a minimum starting chain height pub fn new(min_start_height: i32) -> Arc<SVPeerFilter> { Arc::new(SVPeerF...
(&self) -> Result<Version> { match &*self.version.lock().unwrap() { Some(ref version) => Ok(version.clone()), None => Err(Error::IllegalState("Not connected".to_string())), } } fn connect_internal(peer: &Arc<Peer>, version: Version, filter: Arc<dyn PeerFilter>) { ...
version
identifier_name
peer.rs
id for this connection pub id: ProcessUniqueId, /// IP address pub ip: IpAddr, /// Port pub port: u16, /// Network pub network: Network, pub(crate) connected_event: Single<PeerConnected>, pub(crate) disconnected_event: Single<PeerDisconnected>, pub(crate) messages: Subject<Peer...
{}
conditional_block
mod.rs
extension must be set in /// `enabled_extensions`. /// /// # Panics /// /// - Panics if the `message_severity` or `message_type` members of any element of /// `debug_utils_messengers` are empty. /// /// # Safety /// /// - The `user_callback` of each element of `debug_utils_mes...
/// Returns the Vulkan library used to create this instance. #[inline]
random_line_split
mod.rs
self.enabled_extensions } /// Returns the layers that have been enabled on the instance. #[inline] pub fn enabled_layers(&self) -> &[String] { &self.enabled_layers } /// Returns an iterator that enumerates the physical devices available. /// /// # Examples /// /// ```no...
from
identifier_name
mod.rs
_version) = max_api_version { max_api_version } else if api_version < Version::V1_1 { api_version } else { Version::HEADER_VERSION }; (std::cmp::min(max_api_version, api_version), max_api_version) }; // VUI...
{ &self.enabled_layers }
identifier_body
copy_check.py
try: dirList.remove(copied) except: continue #removing folder names begining with '.' and '$' withDot=[i for i in dirList if i.startswith('.')] withDol=[i for i in dirList if i.startswith('$')] dirList = [item for item in dirList if item not in withDot] dirLis...
(subjFolder): ''' will try getting the name and subj number from the source folder first if it fails, will require user to type in the subjs' name ''' if re.findall('\d{8}',os.path.basename(subjFolder)): subjNum = re.search('(\d{8})',os.path.basename(subjFolder)).group(0) subjNam...
getName
identifier_name
copy_check.py
try: dirList.remove(copied) except: continue #removing folder names begining with '.' and '$' withDot=[i for i in dirList if i.startswith('.')] withDol=[i for i in dirList if i.startswith('$')] dirList = [item for item in dirList if item not in withDot] dirLis...
def getName(subjFolder): ''' will try getting the name and subj number from the source folder first if it fails, will require user to type in the subjs' name ''' if re.findall('\d{8}',os.path.basename(subjFolder)): subjNum = re.search('(\d{8})',os.path.basename(subjFolder)).group(0) ...
possibleGroups = str('BADUK,CHR,DNO,EMO,FEP,GHR,NOR,OCM,ONS,OXY,PAIN,SPR,UMO').split(',') groupName='' while groupName=='': groupName=raw_input('\twhich group ? [BADUK/CHR/DNO/EMO/FEP/GHR/NOR/OCM/ONS/OXY/PAIN/SPR/UMO] :') followUp=raw_input('\tfollow up (if follow up, type the period) ? [baselin...
identifier_body
copy_check.py
: try: dirList.remove(copied) except: continue #removing folder names begining with '.' and '$' withDot=[i for i in dirList if i.startswith('.')] withDol=[i for i in dirList if i.startswith('$')] dirList = [item for item in dirList if item not in withDot] dirL...
def backUpAppend(subjFolder): print '\n' #countFile contains the tuples of image name and count number #countFile=[(image name,count number)] groupName,countFile=countCheck(subjFolder) #groupName=(group,baseline) subjInitial,fullname,subjNum=getName(subjFolder) #if it is a follow up study ...
alreadyCopied.append(folderName) post_check(backUpFrom) else: continue
random_line_split
copy_check.py
try: dirList.remove(copied) except: continue #removing folder names begining with '.' and '$' withDot=[i for i in dirList if i.startswith('.')] withDol=[i for i in dirList if i.startswith('$')] dirList = [item for item in dirList if item not in withDot] dirLis...
def getName(subjFolder): ''' will try getting the name and subj number from the source folder first if it fails, will require user to type in the subjs' name ''' if re.findall('\d{8}',os.path.basename(subjFolder)): subjNum = re.search('(\d{8})',os.path.basename(subjFolder)).group(0) ...
groupName=raw_input('\twhich group ? [BADUK/CHR/DNO/EMO/FEP/GHR/NOR/OCM/ONS/OXY/PAIN/SPR/UMO] :') followUp=raw_input('\tfollow up (if follow up, type the period) ? [baseline/period] :') groupName = groupName.upper() if groupName not in possibleGroups: print 'not in groups, let Kevin ...
conditional_block
client.js
, // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29 emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, name ...
} function checkLength( o, n, min, max ) { if ( o.val().length > max || o.val().length < min ) { o.addClass( "ui-state-error" ); updateTips( "Length of " + n + " must be between " + min + " and " + max + "." ); retu...
random_line_split
client.js
, // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29 emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, name ...
( o, n, min, max ) { if ( o.val().length > max || o.val().length < min ) { o.addClass( "ui-state-error" ); updateTips( "Length of " + n + " must be between " + min + " and " + max + "." ); return false; } else { ...
checkLength
identifier_name
client.js
jQuery(function(){ if(jQuery("#farmers").length > 0){ var dialog, form, // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29 emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,6...
{ var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }
identifier_body
client.js
, // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29 emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, name ...
} }); }); if(jQuery("table#farm").length > 0){ jQuery.get("/api/farm/", function(r){ console.log(r); jQuery.each(r.results, function(i, obj){ obj.name1 = '<a href="#" >'+obj.name+'</a>'; obj.remove = '<a>remove</a>'; ...
{ jQuery( "table#farm tbody" ).append( "<tr>" + "<td>" + r.name + "</td>" + "<td>" + r.details + "</td>" + "<td>" + r.farmer.name + "</td>" + "<td>remove</td>" + "</tr>" ); ...
conditional_block
vcf.rs
x[0] + x[1]).collect(); // Sort possible alleles by reverse numeric order on counts except that the reference base is always first let alleles: Vec<usize> = { let mut ix: Vec<usize> = (0..n_alls).filter(|x| *x != ref_ix).collect(); ix.sort_unstable_by(|a, b| jcts[*b].cmp(&jcts[*a])); ...
// Filter cutoffs let snv_soft_lim = self.cfg.snv_threshold(ThresholdType::Soft); let indel_soft_lim = self.cfg.indel_threshold(ThresholdType::Soft); let desc = vr.adesc.as_ref().unwrap_or(&self.all_desc); // Extra per allele results let mut all_res: Vec<_> = vr.alleles.iter()....
// Reference allele let ref_ix = vr.alleles[0].ix;
random_line_split
vcf.rs
| x[0] + x[1]).collect(); // Sort possible alleles by reverse numeric order on counts except that the reference base is always first let alleles: Vec<usize> = { let mut ix: Vec<usize> = (0..n_alls).filter(|x| *x != ref_ix).collect(); ix.sort_unstable_by(|a, b| jcts[*b].cmp(&jcts[*a])); ...
let snv_soft_lim = self.cfg.snv_threshold(ThresholdType::Soft); let indel_soft_lim = self.cfg.indel_threshold(ThresholdType::Soft); let desc = vr.adesc.as_ref().unwrap_or(&self.all_desc); // Extra per allele results let mut all_res: Vec<_> = vr.alleles.iter().map(|ar| { // Av...
{ let x = vr.x; let raw_depth = cts.iter().fold(0, |t, x| t + x[0] + x[1]); let thresh = 0.05 / (self.seq_len as f64); // Sort alleles by frequency (keeping reference alleles at position 0) vr.alleles[1..].sort_unstable_by(|a1, a2| a2.res.freq.partial_cmp(&a1.res.freq).unwrap()); ...
identifier_body
vcf.rs
{ pub(crate) res: AlleleRes, pub(crate) ix: usize, } pub(crate) struct VcfRes { pub(crate) alleles: Vec<Allele>, pub(crate) adesc: Option<Vec<AllDesc>>, pub(crate) x: usize, pub(crate) phred: u8, } // Additional allele specific results #[derive(Default, Copy, Clone)] struct ExtraRes { flt: u32, ...
Allele
identifier_name
vcf.rs
| x[0] + x[1]).collect(); // Sort possible alleles by reverse numeric order on counts except that the reference base is always first let alleles: Vec<usize> = { let mut ix: Vec<usize> = (0..n_alls).filter(|x| *x != ref_ix).collect(); ix.sort_unstable_by(|a, b| jcts[*b].cmp(&jcts[*a])); ...
else { 1.0 }; // Wilcoxon-Mann-Whitney test for quality bias between the major (most frequent) // allele and all minor alleles let wilcox = if ar.ix != major_idx { mann_whitney(qcts, major_idx, ar.ix).unwrap_or(1.0) } else { 1.0 }; // Set allele freq. flags ...
{ let k = ar.ix; let k1 = major_idx; let all_cts = [cts[k][0], cts[k1][0], cts[k][1], cts[k1][1]]; let fs = self.ftest.fisher(&all_cts); if ar.res.freq < 0.75 && fs <= thresh { flt |= FLT_FS } fs }
conditional_block
Pak.py
cheon/issues/48 if head in unit: continue unit_list.append(unit) produced_unit_list = unit_list if self.stage_name == "build" and not self.is_nested: if self.pak_format == "dpk": is_deleted = False if self.since_reference: Ui.laconic("looking for deleted files") # Unvanquished gam...
# committed file is kept. if os.path.exists(full_path): # FIXME: getmtime reads realpath datetime, not symbolic link datetime. file_date_time = (datetime.fromtimestamp(os.path.getmtime(full_path)))
random_line_split
Pak.py
, input_file_path)): logging.debug("missing prepared files for “" + file_path + "”: " + input_file_path) else: logging.debug("found prepared files for “" + file_path + "”: " + input_file_path) file_list.append(input_file_path) else: file_list = source_tree.
actions: action_list.computeActions(file_list) self.action_list = action_list self.game_profile = Game.Game(source_tree) if not self.map_profile: map_config = MapCompiler.Config(source_tree) self.map_profile = map_config.requireDefaultProfile() def run(self): if self.source_dir == self.test_dir: ...
listFiles() if not self.no_auto_
conditional_block
Pak.py
# also look for deleted files if self.since_reference: is_deps = True if self.deps.read(): is_deps = True if is_deps: # translating DEPS file self.deps.translateTest() self.deps.write() unit = { "head": "DEPS", "body": [ "DEPS" ], } produced_unit_list....
aktrace
identifier_name
Pak.py
produced_unit_list.extend(action.getOldProducedUnitList()) continue if not self.is_parallel or not action_type.is_parallel: # tasks are run sequentially but they can # use multiple threads themselves thread_count = cpu_count else: # this compute is super slow because of process.ch...
e) if pak_subdir == "": pak_subdir = "." if os.path.isdir(pak_subdir): logging.debug("found pak subdir: " + pak_subdir) else: logging.debug("create pak subdir: " + pak_subdir) os.makedirs(pak_subdir, exist_ok=True) def run(self): if not os.path.
identifier_body
patchsBuild.py
utilsConf.open_subprocess(run_commands, stdout=subprocess.PIPE, shell=True,cwd=r'C:\projs') (out, err) = proc.communicate() out=out.replace("\n","").split("\r")[1:-3] fileName=javaFile.split("\\")[-1] fileName=fileName.replace("_","\\") for o in out: if o=="": continue ...
with open(os.path.join(outPath, "before", fileName), "wb") as bef: bef.writelines(befLines) with open(os.path.join(outPath, "after", fileName), "wb") as after: after.writelines(afterLines) with open(os.path.join(outPath, fileName + "_deletsIns.txt"), "wb") as f: ...
afterLines.append(replaced) befLines.append(replaced) delind=delind+1 addind=addind+1
conditional_block
patchsBuild.py
utilsConf.open_subprocess(run_commands, stdout=subprocess.PIPE, shell=True,cwd=r'C:\projs') (out, err) = proc.communicate() out=out.replace("\n","").split("\r")[1:-3] fileName=javaFile.split("\\")[-1] fileName=fileName.replace("_","\\") for o in out: if o=="": continue ...
(diff_lines, outPath, commitID, change): fileName = diff_lines[0].split() if len(fileName)<3: return [] fileName = diff_lines[0].split()[2] fileName = fileName[2:] fileName = os.path.normpath(fileName).replace(os.path.sep,"_") if not ".java" in fileName: return [] fileName = ...
OneClass
identifier_name
patchsBuild.py
(begin),int(end)+1) if methodDir not in methods: methods[methodDir]={} methods[methodDir][key]=len(list(set(rng) & set(inds))) def FileToMethods(beforeFile,AfterFile,deletedInds,addedInds, outPath,commitID): methods={} oneFileParser(methods,beforeFile,deletedInds,"deleted") on...
fileName = fileName.replace("_", os.path.sep)
random_line_split
patchsBuild.py
utilsConf.open_subprocess(run_commands, stdout=subprocess.PIPE, shell=True,cwd=r'C:\projs') (out, err) = proc.communicate() out=out.replace("\n","").split("\r")[1:-3] fileName=javaFile.split("\\")[-1] fileName=fileName.replace("_","\\") for o in out: if o=="": continue ...
inds = [] deleted, insertions = changesDict[(fileName, commitID)] if "before" in file: key = "deletions" inds = deleted if "after" in file: key = "insertions" inds = insertions name, begin, end = data.split("@") rng = map(st...
methods = {} lines = [] with open(checkOut, "r") as f: lines = f.readlines()[1:-3] for line in lines: if line == "": continue if not "@" in line: continue if not len(line.split(" ")) == 2: # case of error continue file, ...
identifier_body
sg_start.go
run-set <commandset>", ShortHelp: "DEPRECATED. Use 'sg start' instead. Run the given commandset.", FlagSet: runSetFlagSet, Exec: runSetExec, } ) func constructStartCmdLongHelp() string { var out strings.Builder fmt.Fprintf(&out, `Runs the given commandset. If no commandset is specified, it starts...
:= os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err }
identifier_body
sg_start.go
.ExitOnError) debugStartServices = startFlagSet.String("debug", "", "Comma separated list of services to set at debug log level.") infoStartServices = startFlagSet.String("info", "", "Comma separated list of services to set at info log level.") warnStartServices = startFlagSet.String("warn", "", "Comma separated l...
string { var out strings.Builder fmt.Fprintf(&out, `Runs the given commandset. If no commandset is specified, it starts the commandset with the name 'default'. Use this to start your Sourcegraph environment! `) // Attempt to parse config to list available commands, but don't fail on // error, because we should ...
structStartCmdLongHelp()
identifier_name
sg_start.go
.ExitOnError) debugStartServices = startFlagSet.String("debug", "", "Comma separated list of services to set at debug log level.") infoStartServices = startFlagSet.String("info", "", "Comma separated list of services to set at info log level.") warnStartServices = startFlagSet.String("warn", "", "Comma separated l...
checks []run.Check for _, name := range set.Checks { check, ok := globalConf.Checks[name] if !ok { out.WriteLine(output.Linef("", output.StyleWarning, "WARNING: check %s not found in config", name)) continue } checks = append(checks, check) } ok, err := run.Checks(ctx, globalConf.Env, checks...) if ...
WriteLine(output.Linef("", output.StyleWarning, "ERROR: dev-private repository not found!")) out.WriteLine(output.Linef("", output.StyleWarning, "It's expected to exist at: %s", devPrivatePath)) out.WriteLine(output.Line("", output.StyleWarning, "If you're not a Sourcegraph employee you probably want to run: sg s...
conditional_block
sg_start.go
.ExitOnError) debugStartServices = startFlagSet.String("debug", "", "Comma separated list of services to set at debug log level.") infoStartServices = startFlagSet.String("info", "", "Comma separated list of services to set at info log level.") warnStartServices = startFlagSet.String("warn", "", "Comma separated l...
} return out.String() } func startExec(ctx context.Context, args []string) error { ok, errLine := parseConf(*configFlag, *overwriteConfigFlag) if !ok { out.WriteLine(errLine) os.Exit(1) } if len(args) > 2 { out.WriteLine(output.Linef("", output.StyleWarning, "ERROR: too many arguments")) return flag.Er...
fmt.Fprint(&out, strings.Join(names, "\n"))
random_line_split
hunk.rs
self.state = match new_line_state(&self.line, &self.raw_line, &self.state, self.config) { Some(HunkMinus(diff_type, raw_line)) => { if let HunkPlus(_, _) = self.state { // We have just entered a new subhunk; process the previous one // and flus...
{ use DiffType::*; use State::*; // A true hunk line should start with one of: '+', '-', ' '. However, handle_hunk_line // handles all lines until the state transitions away from the hunk states. if !self.test_hunk_line() { return Ok(false); } // Don'...
identifier_body
hunk.rs
(&self) -> bool { matches!( self.state, State::HunkHeader(_, _, _, _) | State::HunkZero(_, _) | State::HunkMinus(_, _) | State::HunkPlus(_, _) ) } /// Handle a hunk line, i.e. a minus line, a plus line, or an unchanged line...
test_hunk_line
identifier_name
hunk.rs
Type::*; use State::*; // A true hunk line should start with one of: '+', '-', ' '. However, handle_hunk_line // handles all lines until the state transitions away from the hunk states. if !self.test_hunk_line() { return Ok(false); } // Don't let the line buf...
if let State::HunkHeader(_, parsed_hunk_header, line, raw_line) = &self.state.clone() { self.emit_hunk_header_line(parsed_hunk_header, line, raw_line)?; } self.state = match new_line_state(&self.line, &self.raw_line, &self.state, self.config) { Some(HunkMinus(diff_type, r...
|| self.painter.plus_lines.len() > self.config.line_buffer_size { self.painter.paint_buffered_minus_and_plus_lines(); }
random_line_split
hunk.rs
::*; use State::*; // A true hunk line should start with one of: '+', '-', ' '. However, handle_hunk_line // handles all lines until the state transitions away from the hunk states. if !self.test_hunk_line() { return Ok(false); } // Don't let the line buffers...
// 1. Given the previous line state, compute the new line diff type. These are basically the // same, except that a string prefix is converted into an integer number of parents (prefix // length). let diff_type = match prev_state { HunkMinus(Unified, _) | HunkZero(Unified, _) ...
{ return Some(HunkZero( Unified, maybe_raw_line(new_raw_line, config.zero_style.is_raw, 0, &[], config), )); }
conditional_block
ps_couture.py
[i+1][0][0],p[i+1][0][1]=b2[2] p.insert(i+1,[[b1[2][0],b1[2][1]],[b1[3][0],b1[3][1]],[b2[1][0],b2[1][1]]]) else: d=(box+chord)/2 lengths.append(d) i+=1 new=[p[i][1] for i in range(0,len(p)-1) if lengths[i]>zero] new.append(p[-1][1]) lengths=[l for l in...
if len(self.options.ids)<1 and len(self.options.ids)>1: inkex.errormsg("This extension requires only one selected paths.") return #liste des chemins, preparation idList=self.options.ids idList=pathmodifier.zSort(self.document.getroot(),idList) id = idList[...
random_line_split
ps_couture.py
+1][0][0],p[i+1][0][1]=b2[2] p.insert(i+1,[[b1[2][0],b1[2][1]],[b1[3][0],b1[3][1]],[b2[1][0],b2[1][1]]]) else: d=(box+chord)/2 lengths.append(d) i+=1 new=[p[i][1] for i in range(0,len(p)-1) if lengths[i]>zero] new.append(p[-1][1]) lengths=[l for l in l...
(self,l): ''' Recieves an arc length l, and returns the index of the segment in self.skelcomp containing the coresponding point, to gether with the position of the point on this segment. If the deformer is closed, do computations modulo the toal length. ''' if self.skelc...
lengthtotime
identifier_name
ps_couture.py
self.lengths[i] dy=(self.skelcomp[i+1][1]-self.skelcomp[i][1])/self.lengths[i] vx=0 vy=bpt[1]-self.skelcomp[0][1] bpt[0]=x+vx*dx-vy*dy bpt[1]=y+vx*dy+vy*dx for v in vects: vx=v[0]-self.skelcomp[0][0]-s vy=v[1]-self.skelcomp[0][1] ...
inkex.errormsg("This extension need a path, not groups.")
conditional_block
ps_couture.py
+1][0][0],p[i+1][0][1]=b2[2] p.insert(i+1,[[b1[2][0],b1[2][1]],[b1[3][0],b1[3][1]],[b2[1][0],b2[1][1]]]) else: d=(box+chord)/2 lengths.append(d) i+=1 new=[p[i][1] for i in range(0,len(p)-1) if lengths[i]>zero] new.append(p[-1][1]) lengths=[l for l in l...
self.OptionParser.add_option("-p", "--space", action="store", type="string", dest="space", default="3.0mm") self.OptionParser.add_option("--autoOffset", action="store", type="inkbool", dest="autoOffset", def...
def __init__(self): pathmodifier.Diffeo.__init__(self) self.OptionParser.add_option("--title") self.OptionParser.add_option("--diamlong", action="store", type="string", dest="diamlong", default="1.0mm") self.OptionParser.add_option("--typ...
identifier_body
utils.py
(text, wordtoix, opt, is_cnn = True): sent = [wordtoix[x] for x in text.split()] return prepare_data_for_cnn([sent for i in range(opt.batch_size)], opt) def prepare_data_for_cnn(seqs_x, opt): maxlen=opt.maxlen filter_h=opt.filter_shape lengths_x = [len(s) for s in seqs_x] # pri...
sent2idx
identifier_name
utils.py
seqs_x = new_seqs_x lengths_x = [len(s) for s in seqs_x] if len(lengths_x) < 1 : return None, None n_samples = len(seqs_x) maxlen_x = np.max(lengths_x) x = np.zeros(( n_samples, opt.sent_len)).astype('int32') for idx, s_x in enumerate(seqs_x): if is_add...
if l_x < maxlen-2: new_seqs_x.append(s_x) else: #new_seqs_x.append(s_x[l_x-maxlen+1:]) new_seqs_x.append(s_x[:maxlen-2]+[2])
conditional_block
utils.py
=[wordtoix[x] if x in wordtoix else dp.UNK_ID for x in l.split()] + [2] conv.append(sent) # bp() test.append(conv) return test def tensors_key_in_file(file_name): """Return tensors key in a checkpoint file. Args: file_name: Name of the checkpoint file. "...
"""Clips gradients by global norm.""" gradients, variables = zip(*grads_and_vars) clipped_gradients = [clip_ops.clip_by_norm(grad, clip_gradients) for grad in gradients] return list(zip(clipped_gradients, variables))
identifier_body
utils.py
test file . . ." test = [] with codecs.open(test_file,"r",'utf-8') as f: lines = f.readlines() for line in lines: line = line.rstrip("\n").rstrip("\r").split('\t') conv = [] for l in line: sent=[wordtoix[x] if x in wordtoix else dp.UNK_ID for ...
sent = ' '.join([str(x) for x in sent]) return sent
random_line_split
formatter.rs
' | '%' | 's' | '?' => true, _ => false, } } // get an integer from pos, returning the number of bytes // consumed and the integer fn get_integer(s: &[u8], pos: usize) -> (usize, Option<i64>) { let (_, rest) = s.split_at(pos); let mut consumed: usize = 0; for b in rest { match *b as cha...
{ self.width }
identifier_body
formatter.rs
| 'x' | 'X' | 'e' | 'E' | 'f' | 'F' | '%' | 's' | '?' => true, _ => false, } } // get an integer from pos, returning the number of bytes // consumed and the integer fn get_integer(s: &[u8], pos: usize) -> (usize, Option<i64>) { let (_, rest) = s.split_at(pos); let mut consumed: usize = 0; for ...
if end - pos >= 1 && rest[pos] as char == '#' { format.alternate = true; pos += 1; } // The special case for 0-padding (backwards compat) if !fill_specified && end - pos >= 1 && rest[pos] == '0' as u8 { format.fill = '0'; if !align_specified { format.align = ...
// If the next character is #, we're in alternate mode. This only // applies to integers.
random_line_split
formatter.rs
::<i64>() { Ok(v) => Some(v), Err(_) => None, } }; (consumed, val) } } #[derive(Debug)] /// The format struct as it is defined in the python source struct FmtPy { pub fill: char, pub align: char, pub alternate: bool, pub sign: char, pu...
alternate
identifier_name
formatter.rs
| 'x' | 'X' | 'e' | 'E' | 'f' | 'F' | '%' | 's' | '?' => true, _ => false, } } // get an integer from pos, returning the number of bytes // consumed and the integer fn get_integer(s: &[u8], pos: usize) -> (usize, Option<i64>) { let (_, rest) = s.split_at(pos); let mut consumed: usize = 0; for ...
} } else { // Not having a precision after a dot is an error. if consumed == 0 { return Err(FmtError::Invalid( "Format specifier missing precision".to_string(), )); } } pos += consumed; } ...
{ format.precision = v; }
conditional_block
server.go
) import "fmt" import "net/rpc" import "log" import "paxos" import "sync" import "sync/atomic" import "os" import "syscall" import "encoding/gob" const Debug = false var log_mu sync.Mutex func (sm *ShardMaster) Logf(format string, a ...interface{}) { if !Debug { return } log_mu.Lock() defer log_mu.Unlock() ...
import ( "math/rand" "net" "time"
random_line_split
server.go
2 } else { err = fmt.Errorf("Wait for paxos timeout!1") return } } } func (sm *ShardMaster) applyOp(op Op) { sm.Logf("Applying op to database") switch op.Type { case JoinOp: sm.Logf("Join, you guys!") sm.ApplyJoin(op.GID, op.Servers) case LeaveOp: sm.ApplyLeave(op.GID) sm.Logf("Leave op applie...
{ op := Op{Type: QueryOp, OpID: rand.Int63(), Num: args.Num} opReq := OpReq{op, make(chan Config, 1)} sm.opReqChan <- opReq sm.Logf("Waiting on return channel!") reply.Config = <-opReq.replyChan sm.Logf("Got return!") return nil }
identifier_body
server.go
[op.Num] sm.Logf("Query applied! Feeding value config nr %d through channel. %d", op.Num, seq) } } else { opreq.replyChan <- Config{} } case <-time.After(50 * time.Millisecond): sm.Logf("Ping") seq = sm.ping(seq) } sm.Logf("Calling Done(%d)", seq-2) sm.px.Done(seq - 1) } } //Takes ...
(seq int) int { //TODO: Is this a good dummy OP? dummyOp := Op{} for !sm.isdead() { fate, val := sm.px.Status(seq) if fate == paxos.Decided { sm.applyOp(val.(Op)) seq++ continue } if sm.px.Max() > seq && seq > sm.lastDummySeq { sm.px.Start(seq, dummyOp) sm.waitForPaxos(seq) sm.lastDummyS...
ping
identifier_name
server.go
[op.Num] sm.Logf("Query applied! Feeding value config nr %d through channel. %d", op.Num, seq) } } else { opreq.replyChan <- Config{} } case <-time.After(50 * time.Millisecond): sm.Logf("Ping") seq = sm.ping(seq) } sm.Logf("Calling Done(%d)", seq-2) sm.px.Done(seq - 1) } } //Takes ...
else { return seq } } sm.Logf("ERRRRORR: Ping fallthrough, we are dying! Return seq -1 ") return -1 } func (sm *ShardMaster) addToPaxos(seq int, op Op) (retseq int) { for !sm.isdead() { //Suggest OP as next seq sm.px.Start(seq, op) val, err := sm.waitForPaxos(seq) if err != nil { sm.Logf("ERRR...
{ sm.px.Start(seq, dummyOp) sm.waitForPaxos(seq) sm.lastDummySeq = seq }
conditional_block
scripts_LA_2.py
3() linkToCity = np.genfromtxt('data/LA/link_to_cities.csv', delimiter=',', skiprows=1, dtype='str') links = process_links(graph, node, features, in_order=True) names = ['capacity', 'length', 'fftt'] color = 3 * (linkToCity[:, 1] == city) color = color + 10 * (features...
elif time_unit == 'Second': a = 3600. b = 60. / a speed = a * np.divide(lengths, np.maximum(cost(f, net), 10e-8)) co2 = np.multiply(gas_emission(speed), lengths) out[row, 0] = alpha out[row, 1] = beta out[row, 4] = b * average_cost(f, net, d) out[row, 5] = b * average_cost_subse...
a = 60.0
conditional_block
scripts_LA_2.py
3() linkToCity = np.genfromtxt('data/LA/link_to_cities.csv', delimiter=',', skiprows=1, dtype='str') links = process_links(graph, node, features, in_order=True) names = ['capacity', 'length', 'fftt'] color = 3 * (linkToCity[:, 1] == city) color = color + 10 * (features...
def compute_metrics_beta(alpha, beta, f, net, d, feat, subset, out, row, fs=None, net2=None, length_unit='Mile', time_unit='Minute'): ''' Save in the numpy array 'out' at the specific 'row' the following metrics - average cost for non-routed - average...
net, d, node, features = load_LA_3() # import pdb; pdb.set_trace() d[:, 2] = d[:, 2] / 4000. # modify all small capacity links links_affected = (features[:, 0] < thres) net2 = modify_capacity(net, links_affected, beta) return net2, d, node, features
identifier_body
scripts_LA_2.py
3() linkToCity = np.genfromtxt('data/LA/link_to_cities.csv', delimiter=',', skiprows=1, dtype='str') links = process_links(graph, node, features, in_order=True) names = ['capacity', 'length', 'fftt'] color = 3 * (linkToCity[:, 1] == city) color = color + 10 * (features...
(alphas, input, output, thres, beta): net, d, node, features = LA_metrics_attacks_all(beta, thres) net2, small_capacity = multiply_cognitive_cost(net, features, 1000., 3000.) save_metrics(alphas, net, net2, d, features, small_capacity, input, output, skiprows=1, length_unit...
LA_metrics_attack_2
identifier_name
scripts_LA_2.py
features = extract_features('data/LA_net.txt') # increase capacities of these two links because they have a travel time # in equilibrium that that is too big features[10787, 0] = features[10787, 0] * 1.5 graph[10787, -1] = graph[10787, -1] / (1.5**4) features[3348, :] = features[3348, :] * 1.2 ...
print 'compute for nr = {}, r = {}'.format( 1 - alphas[-1], alphas[-1]) fs = np.loadtxt(input.format(int(alpha * 100),
random_line_split
align.rs
} fn align(&self, x: &[u8], y: &[u8], mode: InternalMode) -> Vec<Op> { if x[..] == y[..] { return vec![Op::Match; x.len()]; } if self.band == Banded::Normal { RustBio.align(self, mode, x, y) } else { align_banded(self, mode, x, y) } ...
}));
random_line_split
align.rs
{ Local, Global, Semiglobal, } impl From<AlignMode> for InternalMode { fn from(value: AlignMode) -> Self { match value { AlignMode::Local => InternalMode::Local, AlignMode::Global | AlignMode::Blockwise(_) => InternalMode::Global, } } } trait Align { fn...
InternalMode
identifier_name
align.rs
addr[0], addr[1]), sender); } [Some(x), None] | [None, Some(x)] => { if x.is_empty() { // selection is empty, does not really make sense to do glocal alignment let [file0, file1] = files; return self.start_align(file0, f...
{ v.push(AlignElement { xaddr, xbyte: Some(x[xaddr]), yaddr, ybyte: None, }); xaddr += 1; }
conditional_block