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 |
|---|---|---|---|---|
index.js | import {
CreateConvertToBooleanFeedbackUpgradeScript,
InstanceBase,
Regex,
runEntrypoint,
TCPHelper,
} from '@companion-module/base'
import { updateActions } from './actions.js'
import { updateFeedbacks } from './feedback.js'
import { updatePresets } from './presets.js'
import { updateVariables } from './variables... | else if (this.receiveBuffer.match(/[P|p]assword:/)) {
this.receiveBuffer = ''
this.socket.send(this.config.password + '\r\n')
} else if (this.receiveBuffer.match(/>/)) {
this.loggedIn = true
if (this.deviceName == '') {
this.receiveBuffer = ''
this.socket.send('version\r\n')
... | {
this.receiveBuffer = ''
this.socket.send(this.config.username + '\r\n')
} | conditional_block |
index.js | import {
CreateConvertToBooleanFeedbackUpgradeScript,
InstanceBase,
Regex,
runEntrypoint,
TCPHelper,
} from '@companion-module/base'
import { updateActions } from './actions.js'
import { updateFeedbacks } from './feedback.js'
import { updatePresets } from './presets.js'
import { updateVariables } from './variables... | } else if (data.startsWith('backlight_compensation')) {
data = data.replace('backlight_compensation', '').trim()
this.state.backlight_compensation = data
this.checkFeedbacks('backlight_compensation')
} else if (data.startsWith('blue_gain')) {
data = data.replace('blue_gain', '').trim()
this.state.blu... | random_line_split | |
index.js | import {
CreateConvertToBooleanFeedbackUpgradeScript,
InstanceBase,
Regex,
runEntrypoint,
TCPHelper,
} from '@companion-module/base'
import { updateActions } from './actions.js'
import { updateFeedbacks } from './feedback.js'
import { updatePresets } from './presets.js'
import { updateVariables } from './variables... | () {
this.receiveBuffer = ''
if (this.socket !== undefined) {
this.socket.destroy()
delete this.socket
}
if (this.pollTimer !== undefined) {
clearInterval(this.pollTimer)
}
if (this.config.port === undefined) {
this.config.port = 23
}
if (this.config.host) {
this.socket = new TCPHelpe... | initTCP | identifier_name |
index.js | import {
CreateConvertToBooleanFeedbackUpgradeScript,
InstanceBase,
Regex,
runEntrypoint,
TCPHelper,
} from '@companion-module/base'
import { updateActions } from './actions.js'
import { updateFeedbacks } from './feedback.js'
import { updatePresets } from './presets.js'
import { updateVariables } from './variables... |
/**
* Process an updated configuration array.
*
* @param {Object} config - the new configuration
* @access public
* @since 1.0.0
*/
async configUpdated(config) {
let resetConnection = false
if (this.config.host != config.host) {
resetConnection = true
}
this.config = config
this.updateAc... | {
super(internal)
this.updateActions = updateActions.bind(this)
this.updateFeedbacks = updateFeedbacks.bind(this)
this.updatePresets = updatePresets.bind(this)
this.updateVariables = updateVariables.bind(this)
} | identifier_body |
court.py | #!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
"""
Das Pong-Spielfeld wird simuliert.
Court moduliert ein anpassbares Spielfeld für Pong mit einem standardmäßigen Seitenverhältnis von 16:9.
Jenes Spielfeld verfügt über einen Ball und zwei Schläger, jeweils links und rechts am Spielfeldrand,
sowie einen Punktestand ... | e Zurücksetzen der Ballposition
# -> Der Schläger den Ball getroffen hat
if self.infinite or self._bathit[1]:
# 2 Spielfeldlängen - aktuellem X-Betrag ergibt neue X-Position
self.posVec[0] = 2 * self.x_max - self.posVec[0] # Einfallswinklel = Ausfallswinkel
... | er Ball außerhalb des Spielfelds
# war, z.B. für out(player)
# Ball abprallen lassen, falls:
# -> Das infinite true ist, also das Spiel endlos dauern soll ohn | conditional_block |
court.py | #!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
"""
Das Pong-Spielfeld wird simuliert.
Court moduliert ein anpassbares Spielfeld für Pong mit einem standardmäßigen Seitenverhältnis von 16:9.
Jenes Spielfeld verfügt über einen Ball und zwei Schläger, jeweils links und rechts am Spielfeldrand,
sowie einen Punktestand ... | des Ortsvektors des Balles skaliert von -1 bis +1 mit Rauschen zurück
(Rauschen kommt von __sensor_y())
:return float, skalierter Y-Anteil vom Ortsvektor
"""
return self.__sensor_y() / (self.y_max / 2.0) - 1.0
def scaled_sensor_bat(self, player):
"""
Gibt die Posit... | 1 bis +1 mit Rauschen zurück
(Rauschen kommt von __sensor_x())
:return float, skalierter X-Anteil vom Ortsvektor
"""
return self.__sensor_x() / (self.x_max / 2.0) - 1.0
def scaled_sensor_y(self):
"""
Gibt den Y-Anteil | identifier_body |
court.py | #!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
"""
Das Pong-Spielfeld wird simuliert.
Court moduliert ein anpassbares Spielfeld für Pong mit einem standardmäßigen Seitenverhältnis von 16:9.
Jenes Spielfeld verfügt über einen Ball und zwei Schläger, jeweils links und rechts am Spielfeldrand,
sowie einen Punktestand ... | r Ball bewegt, die Überschreitung einer der Torauslinien
oder die Kollision mit einem Schläger auf False initialisiert, außerdem
die Ballposition zurückgesetzt, falls die Spieler den Ball zu oft hin und
her gespielt haben ohne Tor (Endlosspiel verhindern).
Ebenso wird überprüft, ob der B... | d de | identifier_name |
court.py | #!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
"""
Das Pong-Spielfeld wird simuliert.
Court moduliert ein anpassbares Spielfeld für Pong mit einem standardmäßigen Seitenverhältnis von 16:9.
Jenes Spielfeld verfügt über einen Ball und zwei Schläger, jeweils links und rechts am Spielfeldrand,
sowie einen Punktestand ... | # Um ein solches "Endlosspiel" zu verhindern, wird der Ball nach 10 Treffern resettet,
# das Spielfeld also zurückgesetzt mit einer initialen Ballposition auf der Spielfeldmitte und
# neuem, zufallskalkuliertem Winkel.
self.bouncecount = 0
# Startvorbereitung
# Initialis... | # Die KNNs sollen unterschiedliche Winkel lernen (der Winkel wird immer zufallsinitialisiert),
# bei ausreichender Lerndauer bzw. stark minimiertem Fehler jedoch sind die KNNs manchmal auf
# einigen Winkeln derart talentiert, dass der Ball nie mehr über die Torlinie gehen würde. | random_line_split |
accounts.rs | use nimiq_account::{
Account, Accounts, BlockLogger, BlockState, RevertInfo, TransactionOperationReceipt,
};
use nimiq_block::{Block, BlockError, SkipBlockInfo};
use nimiq_blockchain_interface::PushError;
use nimiq_database::{traits::Database, TransactionProxy};
use nimiq_keys::Address;
use nimiq_primitives::{
... | block.block_number(),
&body.fork_proofs,
skip_block_info,
Some(txn),
);
// Get the revert info for this block.
let revert_info = self
.chain_store
.get_revert_info(block.block_number(), Some(txn))
.expect("Faile... | random_line_split | |
accounts.rs | use nimiq_account::{
Account, Accounts, BlockLogger, BlockState, RevertInfo, TransactionOperationReceipt,
};
use nimiq_block::{Block, BlockError, SkipBlockInfo};
use nimiq_blockchain_interface::PushError;
use nimiq_database::{traits::Database, TransactionProxy};
use nimiq_keys::Address;
use nimiq_primitives::{
... |
/// Reverts the accounts given a block. This only applies to micro blocks and skip blocks, since
/// macro blocks are final and can't be reverted.
pub(crate) fn revert_accounts(
&self,
accounts: &Accounts,
txn: &mut WriteTransactionProxy,
block: &Block,
block_logger... | {
// Get the accounts from the state.
let accounts = &state.accounts;
let block_state = BlockState::new(block.block_number(), block.timestamp());
// Check the type of the block.
match block {
Block::Macro(ref macro_block) => {
// Initialize a vector t... | identifier_body |
accounts.rs | use nimiq_account::{
Account, Accounts, BlockLogger, BlockState, RevertInfo, TransactionOperationReceipt,
};
use nimiq_block::{Block, BlockError, SkipBlockInfo};
use nimiq_blockchain_interface::PushError;
use nimiq_database::{traits::Database, TransactionProxy};
use nimiq_keys::Address;
use nimiq_primitives::{
... | {
/// The end of the chunk. The end key is exclusive.
/// When set to None it means that it is the last trie chunk.
pub end_key: Option<KeyNibbles>,
/// The set of accounts retrieved.
pub accounts: Vec<(Address, Account)>,
}
/// Implements methods to handle the accounts.
impl Blockchain {
/// ... | AccountsChunk | identifier_name |
gen.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
package main
import (
"bytes"
"encoding/xml"
"errors"
"flag"
"fmt"
"go/format"
"io"
"log"
"os"
"path"
"path/filepath"
"sort"
"s... |
func normalize(args *[6]float32, n int, op byte, size float32, offset f32.Vec2, relative bool) {
for i := 0; i < n; i++ {
args[i] *= outSize / size
if relative {
continue
}
args[i] -= outSize / 2
switch {
case n != 1:
args[i] -= offset[i&0x01]
case op == 'H':
args[i] -= offset[0]
case op == ... | {
f, err := strconv.ParseFloat(string(s), 32)
if err != nil {
return 0, fmt.Errorf("could not parse %q as a float32: %v", s, err)
}
return float32(f), err
} | identifier_body |
gen.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
package main
import (
"bytes"
"encoding/xml"
"errors"
"flag"
"fmt"
"go/format"
"io"
"log"
"os"
"path"
"path/filepath"
"sort"
"s... | fInfo, err := os.Stat(filepath.Join(fqPNGDirName,
fmt.Sprintf("ic_%s_black_%ddp.png", baseName, size)))
if err != nil {
continue
}
return int(fInfo.Size())
}
failures = append(failures,
fmt.Sprintf("no PNG found for %s/1x_web/ic_%s_black_{48,24,18}dp.png", dirName, baseName))
return 0
}
type SVG str... | random_line_split | |
gen.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
package main
import (
"bytes"
"encoding/xml"
"errors"
"flag"
"fmt"
"go/format"
"io"
"log"
"os"
"path"
"path/filepath"
"sort"
"s... | () {
flag.Parse()
out.WriteString("// generated by go run gen.go; DO NOT EDIT\n\npackage icons\n\n")
f, err := os.Open(*mdicons)
if err != nil {
log.Fatalf("%v\n\nDid you override the -mdicons flag in icons.go?\n\n", err)
}
defer f.Close()
infos, err := f.Readdir(-1)
if err != nil {
log.Fatal(err)
}
nam... | main | identifier_name |
gen.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
package main
import (
"bytes"
"encoding/xml"
"errors"
"flag"
"fmt"
"go/format"
"io"
"log"
"os"
"path"
"path/filepath"
"sort"
"s... |
defer f.Close()
infos, err := f.Readdir(-1)
if err != nil {
log.Fatal(err)
}
names := []string{}
for _, info := range infos {
if !info.IsDir() {
continue
}
name := info.Name()
if name[0] == '.' {
continue
}
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
ge... | {
log.Fatalf("%v\n\nDid you override the -mdicons flag in icons.go?\n\n", err)
} | conditional_block |
envconfig.go | // Copyright (c) 2013 Kelsey Hightower. All rights reserved.
// Copyright (c) 2020 Oleg Zaytsev. All rights reserved.
//
// Use of this source code is governed by the MIT License that can be found in
// the LICENSE file.
package envconfig
import (
"encoding"
"errors"
"fmt"
"os"
"reflect"
"regexp"
"strconv"
"s... | else {
var err error
// let's find out how many are defined by the env vars, and gather info of each one of them
if l, err = sliceLen(info.Key, env); err != nil {
return nil, err
}
prefixFormat = processPrefix(info.Key)
// if no keys, check the alternative keys, unless we're inside of a sl... | {
// it's just for usage so we don't know how many of them can be out there
// so we'll print one info with a generic [N] index
l = 1
prefixFormat = usagePrefix{info.Key, "[N]"}
} | conditional_block |
envconfig.go | // Copyright (c) 2013 Kelsey Hightower. All rights reserved.
// Copyright (c) 2020 Oleg Zaytsev. All rights reserved.
//
// Use of this source code is governed by the MIT License that can be found in
// the LICENSE file.
package envconfig
import (
"encoding"
"errors"
"fmt"
"os"
"reflect"
"regexp"
"strconv"
"s... | (v reflect.Value) bool {
return v.Kind() == reflect.Slice &&
v.Type().Elem().Kind() == reflect.Struct
}
func isSliceOfStructPtrs(v reflect.Value) bool {
return v.Kind() == reflect.Slice &&
v.Type().Elem().Kind() == reflect.Ptr &&
v.Type().Elem().Elem().Kind() == reflect.Struct
}
func environment() map[string]... | isSliceOfStructs | identifier_name |
envconfig.go | // Copyright (c) 2013 Kelsey Hightower. All rights reserved.
// Copyright (c) 2020 Oleg Zaytsev. All rights reserved.
//
// Use of this source code is governed by the MIT License that can be found in
// the LICENSE file.
package envconfig
import (
"encoding"
"errors"
"fmt"
"os"
"reflect"
"regexp"
"strconv"
"s... | err := processField(val, sl.Index(i))
if err != nil {
return err
}
}
}
field.Set(sl)
case reflect.Map:
mp := reflect.MakeMap(typ)
if len(strings.TrimSpace(value)) != 0 {
pairs := strings.Split(value, ",")
for _, pair := range pairs {
kvpair := strings.Split(pair, ":")
if len(k... | sl = reflect.ValueOf([]byte(value))
} else if len(strings.TrimSpace(value)) != 0 {
vals := strings.Split(value, ",")
sl = reflect.MakeSlice(typ, len(vals), len(vals))
for i, val := range vals { | random_line_split |
envconfig.go | // Copyright (c) 2013 Kelsey Hightower. All rights reserved.
// Copyright (c) 2020 Oleg Zaytsev. All rights reserved.
//
// Use of this source code is governed by the MIT License that can be found in
// the LICENSE file.
package envconfig
import (
"encoding"
"errors"
"fmt"
"os"
"reflect"
"regexp"
"strconv"
"s... |
func gatherInfoForProcessing(prefix string, spec interface{}, env map[string]string) ([]varInfo, error) {
return gatherInfo(prefix, spec, env, false, false)
}
// gatherInfo gathers information about the specified struct, use gatherInfoForUsage or gatherInfoForProcessing for calling it
func gatherInfo(prefix string,... | {
return gatherInfo(prefix, spec, map[string]string{}, false, true)
} | identifier_body |
scan_nosmooth.py | ###############################################################################
# simple_scan.py
###############################################################################
#
# Simple scan in an object ROI to get background norms and then LL profile for
# a DM halo.
#
##############################################... | n.add_poiss_model('bub', '$A_\mathrm{bub}$', [0,10], False)
# # Add PS at halo location
# ps_halo_map = np.zeros(hp.nside2npix(self.nside))
# ps_halo_idx = hp.ang2pix(self.nside, np.pi/2. - b*np.pi/180., l*np.pi/180.) # ell and b are in rad
# ps_halo_map[... |
n.add_poiss_model(self.diff, '$A_\mathrm{dif}$', [0,10], False)
n.add_poiss_model('iso', '$A_\mathrm{iso}$', [0,20], False)
if (np.sum(bub*np.logical_not(analysis_mask)) != 0): | random_line_split |
scan_nosmooth.py | ###############################################################################
# simple_scan.py
###############################################################################
#
# Simple scan in an object ROI to get background norms and then LL profile for
# a DM halo.
#
##############################################... | def __init__(self, perform_scan=0, perform_postprocessing=0, save_dir="", load_dir=None,imc=0, iobj=0, emin=0, emax=39, channel='b', nside=128, eventclass=5, eventtype=0, diff='p7', catalog_file='DarkSky_ALL_200,200,200_v3.csv', Burkert=0, use_boost=0, boost=1, float_ps_together=1, Asimov=0, floatDM=1, verbose=0, noJpr... | identifier_body | |
scan_nosmooth.py | ###############################################################################
# simple_scan.py
###############################################################################
#
# Simple scan in an object ROI to get background norms and then LL profile for
# a DM halo.
#
##############################################... | (self, perform_scan=0, perform_postprocessing=0, save_dir="", load_dir=None,imc=0, iobj=0, emin=0, emax=39, channel='b', nside=128, eventclass=5, eventtype=0, diff='p7', catalog_file='DarkSky_ALL_200,200,200_v3.csv', Burkert=0, use_boost=0, boost=1, float_ps_together=1, Asimov=0, floatDM=1, verbose=0, noJprof=0, mc_dm=... | __init__ | identifier_name |
scan_nosmooth.py | ###############################################################################
# simple_scan.py
###############################################################################
#
# Simple scan in an object ROI to get background norms and then LL profile for
# a DM halo.
#
##############################################... |
else:
LL_inten_file = np.load(self.load_dir+'LL_inten_o'+str(self.iobj)+self.mc_tag+'.npz')
LL_inten_ary, inten_ary = LL_inten_file['LL'], LL_inten_file['intens']
xsecs = np.logspace(-33,-18,301)
LL2_xsec_m_ary = np.zeros((len(m_ary),len(xsecs))) # 2 x LL, ready for TS
... | rep_angext = np.array([0.02785567,0.12069876,0.21354185,0.30638494,0.39922802,0.49207111,0.5849142,0.67775728,0.77060037,0.86344346,0.95628654,1.04912963,1.14197272,1.2348158,1.32765889,1.42050198,1.51334507,1.60618815,1.69903124,1.79187433])
obj_angext = 2*self.catalog[u'rs'].values[self.iobj] / \
... | conditional_block |
exploratory_analysis.py | #!/usr/bin/env python3 -w ignore DataConversionWarning
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.svm import SVC
from sklearn.metrics import class... |
def plotHist(column, title, x_label, y_label):
# plots a histogram. Note: update bin width as appropriate
binwidth = [x for x in range(0,800000, 2000)]
ex = plt.hist(column, bins=binwidth)
plt.title(title)
plt.xlabel(x_label)
plt.ylabel(y_label)
return plt.show()
def plotHistTwo(colA, col... | return 0 | identifier_body |
exploratory_analysis.py | #!/usr/bin/env python3 -w ignore DataConversionWarning
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.svm import SVC
from sklearn.metrics import class... | main() | conditional_block | |
exploratory_analysis.py | #!/usr/bin/env python3 -w ignore DataConversionWarning
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.svm import SVC
from sklearn.metrics import class... | (column, title, x_label, y_label):
# plots a histogram. Note: update bin width as appropriate
binwidth = [x for x in range(0,800000, 2000)]
ex = plt.hist(column, bins=binwidth)
plt.title(title)
plt.xlabel(x_label)
plt.ylabel(y_label)
return plt.show()
def plotHistTwo(colA, colB, title="", x... | plotHist | identifier_name |
exploratory_analysis.py | #!/usr/bin/env python3 -w ignore DataConversionWarning
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.svm import SVC
from sklearn.metrics import class... | # # svm.gamma = gamma
# # this_scores = cross_val_score(svm, X, y, cv=5)
# # scores.append(np.mean(this_scores))
# # scores=np.array(scores)
# # scores=scores.reshape(C_s.shape)
# # fig2, ax2 = plt.subplots(figsize=(12,8))
# # c=ax2.contourf(C_s,gamma_s,scores)
# # ax2.set_xl... | random_line_split | |
Program.ts | import * as assert from 'assert';
import { EventEmitter } from 'events';
import * as fsExtra from 'fs-extra';
import * as path from 'path';
import { StandardizedFileEntry } from 'roku-deploy';
import { CompletionItem, Location, Position, Range } from 'vscode-languageserver';
import { BsConfig } from './BsConfig';
impo... |
});
await Promise.all(promises);
}
public dispose() {
this.emitter.removeAllListeners();
for (let filePath in this.files) {
this.files[filePath].dispose();
}
for (let name in this.scopes) {
this.scopes[name].dispose();
}
t... | {
let result = file.transpile();
let filePathObj = fileEntries.find(x => util.standardizePath(x.src) === util.standardizePath(file.pathAbsolute));
if (!filePathObj) {
throw new Error(`Cannot find fileMap record in fileMaps for '${file.pathAbsolute}'`);... | conditional_block |
Program.ts | import * as assert from 'assert';
import { EventEmitter } from 'events';
import * as fsExtra from 'fs-extra';
import * as path from 'path';
import { StandardizedFileEntry } from 'roku-deploy';
import { CompletionItem, Location, Position, Range } from 'vscode-languageserver';
import { BsConfig } from './BsConfig';
impo... | return [];
}
let results = [] as Location[];
let scopes = this.getScopesForFile(file);
for (let scope of scopes) {
results = results.concat(...scope.getDefinition(file, position));
}
return results;
}
public async getHover(pathAbsolute: st... | random_line_split | |
Program.ts | import * as assert from 'assert';
import { EventEmitter } from 'events';
import * as fsExtra from 'fs-extra';
import * as path from 'path';
import { StandardizedFileEntry } from 'roku-deploy';
import { CompletionItem, Location, Position, Range } from 'vscode-languageserver';
import { BsConfig } from './BsConfig';
impo... | (pathAbsolute: string) {
pathAbsolute = util.standardizePath(pathAbsolute);
for (let filePath in this.files) {
if (filePath.toLowerCase() === pathAbsolute.toLowerCase()) {
return this.files[filePath];
}
}
}
/**
* Get a file with the specified... | getFileByPathAbsolute | identifier_name |
Program.ts | import * as assert from 'assert';
import { EventEmitter } from 'events';
import * as fsExtra from 'fs-extra';
import * as path from 'path';
import { StandardizedFileEntry } from 'roku-deploy';
import { CompletionItem, Location, Position, Range } from 'vscode-languageserver';
import { BsConfig } from './BsConfig';
impo... |
/**
* Given a position in a file, if the position is sitting on some type of identifier,
* go to the definition of that identifier (where this thing was first defined)
*/
public getDefinition(pathAbsolute: string, position: Position): Location[] {
let file = this.getFile(pathAbsolute);
... | {
let file = this.getFile(pathAbsolute);
if (!file) {
return [];
}
//wait for the file to finish loading
await file.isReady();
//find the scopes for this file
let scopes = this.getScopesForFile(file);
//if there are no scopes, include the pl... | identifier_body |
si5324.py | """
SI5324 - device access class for the SI5324 Clock Multiplier
Class to drive the SI5324 Clock Multiplier IC. Settings should primarily
be created using the DSPLLsim software for PC, which can be uploaded using
the apply_register_map() function. From there, some settings can be tweaked
and the input clock can be swi... | (self, register, startbit, length):
self.register = register
self.startbit = startbit
self.length = length
def get_endbit(self):
return (self.startbit - (self.length - 1))
class Alarms:
"""
Alarms Class:
Holds a collection of alarms states for the class, including both... | __init__ | identifier_name |
si5324.py | """
SI5324 - device access class for the SI5324 Clock Multiplier
Class to drive the SI5324 Clock Multiplier IC. Settings should primarily
be created using the DSPLLsim software for PC, which can be uploaded using
the apply_register_map() function. From there, some settings can be tweaked
and the input clock can be swi... | raise I2CException(
"Write of byte to register {} failed.".format(register))
# ICAL-sensitive registers will have been modified during this process
self.iCAL_required = True
self.calibrate()
def export_register_map(self, mapfi... | logger.debug("Verifying value written ({:b}) against re-read: {:b}".format(
value,verify_value))
if verify_value != value: | random_line_split |
si5324.py | """
SI5324 - device access class for the SI5324 Clock Multiplier
Class to drive the SI5324 Clock Multiplier IC. Settings should primarily
be created using the DSPLLsim software for PC, which can be uploaded using
the apply_register_map() function. From there, some settings can be tweaked
and the input clock can be swi... |
logger.info("iCAL done in {}s".format(latest_time-start_time))
self.iCAL_required = False
return 0
def calibrate(self):
"""
Wrapper function for the above internal iCAL function above. It will only execute
the iCAL if it has been set as required (by writing to a r... | time.sleep(0.100)
logger.debug("iCAL waiting...")
# Check for LOL timeout (not necessarily fatal, since the input
# could just be inactive when selected. However, iCAL should be
# performed after the input is provided, or the output will be
# unstable).
... | conditional_block |
si5324.py | """
SI5324 - device access class for the SI5324 Clock Multiplier
Class to drive the SI5324 Clock Multiplier IC. Settings should primarily
be created using the DSPLLsim software for PC, which can be uploaded using
the apply_register_map() function. From there, some settings can be tweaked
and the input clock can be swi... |
def export_register_map(self, mapfile_location):
"""
Generate a register map file using the current settings in device control
registers. This file can then be loaded using apply_register_map(filename).
:param mapfile_location: location of register map file that will be written to... | """
Write configuration from a register map generated with DSPLLsim.
Since the map is register rather than value-based, there is no need to make use
of the _Field access functions.
:param mapfile_location: location of register map file to be read
:param verify: Boolean. If true,... | identifier_body |
mysql_insert_query_test.go | package main
import (
"database/sql"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/stretchr/testify/assert"
"log"
"testing"
"time"
)
/*
gorm的坑:
1. db.Model(&table_struct).Find(&other_struct) 会查到已被删除的记录,还是用回Find(&table_struct)
Mysql的注意点:
1. rows affected这个属性在update时,如果新旧数据一致,... | ord) // true, 检测记录的主键是否零值,不插数据,也不会与db交互.
assert.True(t, ok)
db.Create(&record) // insert, db生成的id将会写入record
assert.NotEqual(t, record.ID, 0)
ok = db.NewRecord(record) // false, because record.id already exists in db.
assert.False(t, ok)
record.ID = 0
record.Age = sql.NullInt64{Valid: true, Int64: 0}
record.E... | db.NewRecord(rec | conditional_block |
mysql_insert_query_test.go | package main
import (
"database/sql"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/stretchr/testify/assert"
"log"
"testing"
"time"
)
/*
gorm的坑:
1. db.Model(&table_struct).Find(&other_struct) 会查到已被删除的记录,还是用回Find(&table_struct)
Mysql的注意点:
1. rows affected这个属性在update时,如果新旧数据一致,... | me = 'jinzhu'").Or(map[string]interface{}{"u_name": "jinzhu 2"}).Find(&users)
// SELECT * FROM users WHERE u_name = 'jinzhu' OR u_name = 'jinzhu 2';
assert.True(t, len(users) == 0)
}
// gorm称之为inline condition,内联查询,我看来就是更简单的一种查询写法
func MoreSimpleQueryTest(t *testing.T, db *gorm.DB) {
var users []User
var user User... | t all records
db.Find(&users)
assert.True(t, len(users) > 1)
// Get record with primary key (后面参数只会传递给整型主键)
db.First(&user, 10)
// where可以自定义字符串形式的条件,使用问号占位参数
// 还可以传入带值的struct,其中的值作为条件查询
// 还可以传入map类型,其中的k-v作为条件查询
// 还可以传入slice类型,不过元素只能是整型,作为主键字段参数,执行IN查询(如果主键不是整型,应该会报错)
var user1 User
// where
db.Where(... | identifier_body |
mysql_insert_query_test.go | package main
import (
"database/sql"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/stretchr/testify/assert"
"log"
"testing"
"time"
)
/*
gorm的坑:
1. db.Model(&table_struct).Find(&other_struct) 会查到已被删除的记录,还是用回Find(&table_struct)
Mysql的注意点:
1. rows affected这个属性在update时,如果新旧数据一致,... | CommonQueryTest(t, db)
//QueryNotTest(t, db)
//QueryOrTest(t, db)
//MoreSimpleQueryTest(t, db)
//FirstOrInitQueryTest(t, db)
//FirstOrCreateQueryTest(t, db)
//SubQueryTest(t, db)
//SelectTest(t, db)
//LimitTest(t, db)
//OffsetTest(t, db)
//CountTest(t, db)
//JoinTest(t, db)
//ScanTest(t, db)
UpdateAllFie... | InsertTest(t, db) | random_line_split |
mysql_insert_query_test.go | package main
import (
"database/sql"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/stretchr/testify/assert"
"log"
"testing"
"time"
)
/*
gorm的坑:
1. db.Model(&table_struct).Find(&other_struct) 会查到已被删除的记录,还是用回Find(&table_struct)
Mysql的注意点:
1. rows affected这个属性在update时,如果新旧数据一致,... | on_existing")
// 针对存在的数据,另外的2种写法
db.Where(User{Name: "x"}).FirstOrInit(&user)
db.FirstOrInit(&user, map[string]interface{}{"u_name": "x"})
assert.True(t, user.Age.Int64 == 18)
var user1 User
// 使用Attrs方法,是FirstOrInit的扩展,它将仅作为初始化的参数与查询参数隔离开
// 针对不存在的数据
db.Where(User{Name: "non_existing"}).Attrs(User{Age: sql... | && user.Name == "n | identifier_name |
ioWkr.go | /*
Copyright (c) Facebook, Inc. and its affiliates.
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... | {
rxStartDone := make(chan bool)
for rxwkr := 0; rxwkr < cfg.NumRXWorkers; rxwkr++ {
func(i int) {
cfg.Eg.Go(func() error {
doneChan := make(chan error, 1)
go func() {
var profiler Profiler
profiler.Init(cfg.Eg, cfg.Ctx, true, fmt.Sprintf("RX Worker %d", i))
cfg.PerfProfilers = append(cfg.... | identifier_body | |
ioWkr.go | /*
Copyright (c) Facebook, Inc. and its affiliates.
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... | txTSworker[workerNum].Tock()
}
}(j)
select {
case <-txTSStartDone:
if cfg.DebugPrint || cfg.DebugIoWkrTX {
log.Infof("TX %d TS worker %d running", txwkr, j)
}
continue
case <-(*cfg.Ctx).Done():
log.Errorf("Tx TS worker startup error")
ret... | atomic.AddUint64(&txTSBytesReceived, uint64(pktSentLen)) | random_line_split |
ioWkr.go | /*
Copyright (c) Facebook, Inc. and its affiliates.
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... |
ifInfo, err := net.InterfaceByName(cfg.Iface)
if err != nil {
log.Errorf("Interface by name failed in start tx worker")
doneChan <- err
return
}
var haddr [8]byte
copy(haddr[0:7], ifInfo.HardwareAddr[0:7])
addr := syscall.SockaddrLinklayer{
Protocol: syscall.ETH_P... | {
txTSworker[j].Init(cfg.Eg, cfg.Ctx, true, fmt.Sprintf("TX worker %d TSRead worker %d", i, j))
cfg.PerfProfilers = append(cfg.PerfProfilers, &txTSworker[j])
} | conditional_block |
ioWkr.go | /*
Copyright (c) Facebook, Inc. and its affiliates.
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... | (cfg *ClientGenConfig) {
rxStartDone := make(chan bool)
for rxwkr := 0; rxwkr < cfg.NumRXWorkers; rxwkr++ {
func(i int) {
cfg.Eg.Go(func() error {
doneChan := make(chan error, 1)
go func() {
var profiler Profiler
profiler.Init(cfg.Eg, cfg.Ctx, true, fmt.Sprintf("RX Worker %d", i))
cfg.Perf... | startIOWorker | identifier_name |
dcrd_test.go | //go:build dev
// +build dev
package dcrdnotify
import (
"bytes"
"context"
"io/ioutil"
"testing"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/txscript/v4/stdscript"
"github.com/decred/dcrd/wire"
"github... | (t *testing.T, h *rpctest.Harness) *DcrdNotifier {
hintCache := initHintCache(t)
rpcConfig := h.RPCConfig()
notifier, err := New(&rpcConfig, netParams, hintCache, hintCache)
if err != nil {
t.Fatalf("unable to create notifier: %v", err)
}
if err := notifier.Start(); err != nil {
t.Fatalf("unable to start not... | setUpNotifier | identifier_name |
dcrd_test.go | //go:build dev
// +build dev
package dcrdnotify
import (
"bytes"
"context"
"io/ioutil"
"testing"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/txscript/v4/stdscript"
"github.com/decred/dcrd/wire"
"github... | {
t.Parallel()
harness, err := testutils.NewSetupRPCTest(
t, 5, netParams, nil, []string{"--txindex"}, true, 25,
)
require.NoError(t, err)
defer harness.TearDown()
notifier := setUpNotifier(t, harness)
defer notifier.Stop()
// Create an output and subsequently spend it.
outpoint, txout, privKey := chainnt... | identifier_body | |
dcrd_test.go | //go:build dev
// +build dev
package dcrdnotify
import (
"bytes"
"context"
"io/ioutil"
"testing"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/txscript/v4/stdscript"
"github.com/decred/dcrd/wire"
"github... |
}
if testTx == nil {
t.Fatalf("test transaction was not mined")
}
minedHeight := int64(block.Header.Height)
prevOutputHeight := minedHeight - 1
// Generate a few blocks after mining to test some conditions.
if _, err := rpctest.AdjustedSimnetMiner(context.Background(), harness.Node, 20); err != nil {
t.Fat... | {
testTx = tx
break
} | conditional_block |
dcrd_test.go | //go:build dev
// +build dev
package dcrdnotify
import (
"bytes"
"context"
"io/ioutil"
"testing"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/txscript/v4/stdscript"
"github.com/decred/dcrd/wire"
"github... | if err != nil {
t.Fatalf("unable to retrieve historical conf details: %v", err)
}
// Since the backend node's txindex is enabled and the transaction has
// confirmed, we should be able to retrieve it using the txindex.
switch txStatus {
case chainntnfs.TxFoundIndex:
default:
t.Fatal("should have found the t... | random_line_split | |
refcounteddb.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at yo... | (&self) -> HashMap<H256, i32> {
self.forward.keys()
}
}
#[cfg(test)]
mod tests {
use keccak_hash::keccak;
use hash_db::{HashDB, EMPTY_PREFIX};
use super::*;
use kvdb_memorydb;
use crate::{JournalDB, inject_batch, commit_batch};
fn new_db() -> RefCountedDB {
let backing = Arc::new(kvdb_memorydb::create(0));... | keys | identifier_name |
refcounteddb.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at yo... | .expect("rlp read from db; qed");
trace!(target: "rcdb", "delete journal for time #{}.{}=>{}, (canon was {}): deleting {:?}", end_era, db_key.index, our_id, canon_id, to_remove);
for i in &to_remove {
self.forward.remove(i, EMPTY_PREFIX);
}
batch.delete(self.column, &last);
db_key.index += 1;
}
... | {
view.inserts()
} | conditional_block |
refcounteddb.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at yo... | fn mem_used(&self) -> usize {
let mut ops = new_malloc_size_ops();
self.inserts.size_of(&mut ops) + self.removes.size_of(&mut ops)
}
fn is_empty(&self) -> bool {
self.latest_era.is_none()
}
fn backing(&self) -> &Arc<dyn KeyValueDB> {
&self.backing
}
fn latest_era(&self) -> Option<u64> { self.latest_e... | })
}
| random_line_split |
refcounteddb.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at yo... |
#[test]
fn long_history() {
// history is 3
let mut jdb = new_db();
let h = jdb.insert(EMPTY_PREFIX, b"foo");
commit_batch(&mut jdb, 0, &keccak(b"0"), None).unwrap();
assert!(jdb.contains(&h, EMPTY_PREFIX));
jdb.remove(&h, EMPTY_PREFIX);
commit_batch(&mut jdb, 1, &keccak(b"1"), None).unwrap();
asser... | {
let backing = Arc::new(kvdb_memorydb::create(0));
RefCountedDB::new(backing, None)
} | identifier_body |
main.rs | use std::collections::HashMap;
fn main() {
let test_one_input = "Today is Monday";
let max_chars = one(test_one_input);
println!("1) the most of a char(first appearing) in '{}' is '{}', appearing {} times", test_one_input, max_chars.0, max_chars.1);
let test_two_input = "supracalafragalisticexpealadoc... |
fn fifteen(i: &str) -> isize {
let mut i = i.to_uppercase();
let mut r = 0;
let mut to_long = 0;
while i.len() > 0 {
for (rn, an) in ROMANS.iter().rev() {
if i.starts_with(rn) {
r = r + an;
i = i.replacen(rn,"",1);
break;
... | {
let mut i = String::from(i);
let is_negative = i.contains('-');
if is_negative {
i = i.replace("-", "");
}
let mut r = 0;
for c in i.chars() {
let d = c.to_digit(10).unwrap();
r = d + (r * 10);
}
let mut r = r as isize;
if is_negative {
r = r * -1;
... | identifier_body |
main.rs | use std::collections::HashMap;
fn main() {
let test_one_input = "Today is Monday";
let max_chars = one(test_one_input);
println!("1) the most of a char(first appearing) in '{}' is '{}', appearing {} times", test_one_input, max_chars.0, max_chars.1);
let test_two_input = "supracalafragalisticexpealadoc... | println!("9) the first unrepeated char in '{}' is '{}'", test_nine_input, test_nine_output);
let test_ten_input = "best is Rust";
let test_ten_output = ten(test_ten_input);
println!("10) reversed sentence '{}' is '{}'", test_ten_input, test_ten_output);
let test_eleven_input1 = "this is a test str... | println!("8) '{}' has {} permutations {:?}", test_eight_input, test_eight_output.len(), test_eight_output);
let test_nine_input = "uprasupradupra";
let test_nine_output = nine(test_nine_input); | random_line_split |
main.rs | use std::collections::HashMap;
fn main() {
let test_one_input = "Today is Monday";
let max_chars = one(test_one_input);
println!("1) the most of a char(first appearing) in '{}' is '{}', appearing {} times", test_one_input, max_chars.0, max_chars.1);
let test_two_input = "supracalafragalisticexpealadoc... |
while l > 0 && r < m && i[l].0 == i[r].0 {
l = l - 1;
r = r + 1;
}
l = std::cmp::max(0, l);
r = std::cmp::min(i.len() - 1, r);
let begin = i[l+1].1;
let end = std::cmp::min(input.len() - 1,i[r].1);
let result = String::from(&input[begin..end]);
result
}
fn twentyone(i: ... | { // we are not the same assume a center "pivot" character center
r = r + 1;
} | conditional_block |
main.rs | use std::collections::HashMap;
fn main() {
let test_one_input = "Today is Monday";
let max_chars = one(test_one_input);
println!("1) the most of a char(first appearing) in '{}' is '{}', appearing {} times", test_one_input, max_chars.0, max_chars.1);
let test_two_input = "supracalafragalisticexpealadoc... | (input: &str) -> String {
let mut r = String::new();
input.chars().for_each( | c | {
r = format!("{}{}", c, r);
});
r
}
fn seven(i1: &str, i2: &str) -> String {
let mut r2 = String::from(i2);
if i1.len() == 0 {
return r2;
}
r2.push(i1.chars().last().unwrap());
let si... | six | identifier_name |
sqlite.go | package sqlite
import (
"database/sql"
"encoding/json"
"fmt"
"sync"
_ "github.com/mattn/go-sqlite3"
"github.com/prometheus/common/log"
"github.com/prometheus/common/model"
"github.com/prometheus/alertmanager/provider"
"github.com/prometheus/alertmanager/types"
)
const createAlertsTable = `
CREATE TABLE IF ... |
tx, err := db.Begin()
if err != nil {
return nil, err
}
if _, err := tx.Exec(createSilencesTable); err != nil {
tx.Rollback()
return nil, err
}
tx.Commit()
return &Silences{db: db, marker: mk}, nil
}
// Mutes implements the Muter interface.
func (s *Silences) Mutes(lset model.LabelSet) bool {
sils, err... | defer dbmtx.Unlock() | random_line_split |
sqlite.go | package sqlite
import (
"database/sql"
"encoding/json"
"fmt"
"sync"
_ "github.com/mattn/go-sqlite3"
"github.com/prometheus/common/log"
"github.com/prometheus/common/model"
"github.com/prometheus/alertmanager/provider"
"github.com/prometheus/alertmanager/types"
)
const createAlertsTable = `
CREATE TABLE IF ... | () provider.AlertIterator {
var (
ch = make(chan *types.Alert, 200)
done = make(chan struct{})
)
alerts, err := a.getPending()
go func() {
defer close(ch)
for _, a := range alerts {
select {
case ch <- a:
case <-done:
return
}
}
}()
return provider.NewAlertIterator(ch, done, err)
}... | GetPending | identifier_name |
sqlite.go | package sqlite
import (
"database/sql"
"encoding/json"
"fmt"
"sync"
_ "github.com/mattn/go-sqlite3"
"github.com/prometheus/common/log"
"github.com/prometheus/common/model"
"github.com/prometheus/alertmanager/provider"
"github.com/prometheus/alertmanager/types"
)
const createAlertsTable = `
CREATE TABLE IF ... |
<-done
}()
return provider.NewAlertIterator(ch, done, err)
}
// GetPending implements the Alerts interface.
func (a *Alerts) GetPending() provider.AlertIterator {
var (
ch = make(chan *types.Alert, 200)
done = make(chan struct{})
)
alerts, err := a.getPending()
go func() {
defer close(ch)
for _... | {
select {
case ch <- a:
case <-done:
return
}
} | conditional_block |
sqlite.go | package sqlite
import (
"database/sql"
"encoding/json"
"fmt"
"sync"
_ "github.com/mattn/go-sqlite3"
"github.com/prometheus/common/log"
"github.com/prometheus/common/model"
"github.com/prometheus/alertmanager/provider"
"github.com/prometheus/alertmanager/types"
)
const createAlertsTable = `
CREATE TABLE IF ... |
// Del implements the Silences interface.
func (s *Silences) Del(sid uint64) error {
dbmtx.Lock()
defer dbmtx.Unlock()
tx, err := s.db.Begin()
if err != nil {
return err
}
if _, err := tx.Exec(`DELETE FROM silences WHERE id == $1`, sid); err != nil {
tx.Rollback()
return err
}
tx.Commit()
return nil... | {
dbmtx.Lock()
defer dbmtx.Unlock()
mb, err := json.Marshal(sil.Silence.Matchers)
if err != nil {
return 0, err
}
tx, err := s.db.Begin()
if err != nil {
return 0, err
}
res, err := tx.Exec(`
INSERT INTO silences(matchers, starts_at, ends_at, created_at, created_by, comment)
VALUES ($1, $2, $3, $4, ... | identifier_body |
main.py | #!/usr/bin/python3
"""
This is an example which grabs a spreadsheet (that follows a certain format)
from Google Docs and uploads the data into Zenobase.
Example spreadsheet will be available at a later date.
"""
# TODO: Ability to only send updates (events with dates later than the latest in bucket)
imp... |
else:
for event in events:
self.zapi.create_event(bucket_id, event)
logging.debug("Done!".format(len(events)))
def get_raw_table(self, sheetname):
start = time.time()
sheet = self.ll.worksheet(sheetname)
raw_table = sheet.get_all_values()
... | self.zapi.create_events(bucket_id, events) | conditional_block |
main.py | #!/usr/bin/python3
"""
This is an example which grabs a spreadsheet (that follows a certain format)
from Google Docs and uploads the data into Zenobase.
Example spreadsheet will be available at a later date.
"""
# TODO: Ability to only send updates (events with dates later than the latest in bucket)
imp... | (category, label):
ci = categories.index(category)
i = labels.index(label, ci)
cells = {}
for j, d in enumerate(dates):
cell = raw_table[j+2][i]
if cell and cell != "#VALUE!":
cells[d] = cell
return cells
... | get_label_cells | identifier_name |
main.py | #!/usr/bin/python3
"""
This is an example which grabs a spreadsheet (that follows a certain format)
from Google Docs and uploads the data into Zenobase.
Example spreadsheet will be available at a later date.
"""
# TODO: Ability to only send updates (events with dates later than the latest in bucket)
imp... |
class Lifelogger_to_Zenobase():
def __init__(self, google_oauth_json_path, zenobase_username, zenobase_password,
streaks_bucket_name="Streaks", supplements_bucket_name="Supplements - New"):
json_key = json.load(open(google_oauth_json_path))
scope = ['https://spreadsheets.google.c... | return list(map(lambda t: pyzenobase.fmt_datetime(datetime.datetime.combine(d, t)), times)) | identifier_body |
main.py | #!/usr/bin/python3
"""
This is an example which grabs a spreadsheet (that follows a certain format)
from Google Docs and uploads the data into Zenobase.
Example spreadsheet will be available at a later date.
"""
# TODO: Ability to only send updates (events with dates later than the latest in bucket)
imp... | if not raw_table[j+2][i]:
continue
try:
weight = float(raw_table[j+2][i])
except ValueError:
logging.warning("Invalid data '{}' (not a number) in cell: {}. Skipping..."
.forma... | random_line_split | |
PointCode.js | "use strict";
var ua = detect.parse(navigator.userAgent);
// console.log("Browser:" + ua.browser.family + " Device:" + ua.device.family + " Device type:" + ua.device.type);
// alert("Browser family:" + ua.browser.family + " Device family:" + ua.device.family + " Device type:" + ua.device.type + " OS family:" + ua.os.f... | Point.colors[Point.count % Point.colors.length][0][i],
Point.colors[Point.count % Point.colors.length][1][i]
);
rgbText[i] = randInt(
Point.colors[Point.count % Point.colors.length][0][i] + 100,
Point.colors[Point.count % Point.colors.length][1][i] + 100
);
}
// console.log(Point.colors[Poi... | random_line_split | |
PointCode.js | "use strict";
var ua = detect.parse(navigator.userAgent);
// console.log("Browser:" + ua.browser.family + " Device:" + ua.device.family + " Device type:" + ua.device.type);
// alert("Browser family:" + ua.browser.family + " Device family:" + ua.device.family + " Device type:" + ua.device.type + " OS family:" + ua.os.f... |
Point.switch();
}
else if(!Point.mainTask.running) {
Point.clearTo([0,0,0]);
Point.init();
Point.flicker();
}
};
Point.stop = function() {
Point.mainTask.stop();
Point.metaTask.stop();
Point.clearTo([0,0,0]);
Point.flicker('stop');
};
Point.flicker = function(mode) {
var interval = 100, tuple = [0,0];
... | {
btns[i].style.width = width;
} | conditional_block |
policymap.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package policymap
import (
"fmt"
"strconv"
"strings"
"unsafe"
"github.com/cilium/ebpf"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/byteorder"
"github.com/cilium/cilium/pkg/policy/trafficdirection"
"github.com/cilium/... | sb.WriteString(fmt.Sprintf("%20s: %s\n",
entry.Key.String(), entry.PolicyEntry.String()))
}
return sb.String()
}
// Less is a function used to sort PolicyEntriesDump by Policy Type
// (Deny / Allow), TrafficDirection (Ingress / Egress) and Identity
// (ascending order).
func (p PolicyEntriesDump) Less(i, j int)... | random_line_split | |
policymap.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package policymap
import (
"fmt"
"strconv"
"strings"
"unsafe"
"github.com/cilium/ebpf"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/byteorder"
"github.com/cilium/cilium/pkg/policy/trafficdirection"
"github.com/cilium/... | () bool {
return pe.Flags.is(policyFlagDeny)
}
func (pe *PolicyEntry) String() string {
return fmt.Sprintf("%d %d %d", pe.GetProxyPort(), pe.Packets, pe.Bytes)
}
func (pe *PolicyEntry) New() bpf.MapValue { return &PolicyEntry{} }
// PolicyKey represents a key in the BPF policy map for an endpoint. It must
// match... | IsDeny | identifier_name |
policymap.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package policymap
import (
"fmt"
"strconv"
"strings"
"unsafe"
"github.com/cilium/ebpf"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/byteorder"
"github.com/cilium/cilium/pkg/policy/trafficdirection"
"github.com/cilium/... |
func (k *CallKey) New() bpf.MapKey { return &CallKey{} }
// String converts the value into a human readable string format.
func (v *CallValue) String() string { return strconv.FormatUint(uint64(v.progID), 10) }
func (v *CallValue) New() bpf.MapValue { return &CallValue{} }
func (pe *PolicyEntry) Add(oPe PolicyEnt... | { return strconv.FormatUint(uint64(k.index), 10) } | identifier_body |
policymap.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package policymap
import (
"fmt"
"strconv"
"strings"
"unsafe"
"github.com/cilium/ebpf"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/byteorder"
"github.com/cilium/cilium/pkg/policy/trafficdirection"
"github.com/cilium/... | else {
str = append(str, "Allow")
}
if pef.is(policyFlagWildcardNexthdr) {
str = append(str, "WildcardProtocol")
}
if pef.is(policyFlagWildcardDestPort) {
str = append(str, "WildcardPort")
}
return strings.Join(str, ", ")
}
var (
// MaxEntries is the upper limit of entries in the per endpoint policy
//... | {
str = append(str, "Deny")
} | conditional_block |
output.rs | use super::Token;
pub use json::object::Object;
pub use json::JsonValue;
use nom::{
alt, call, do_parse, error_position, is_not, many0, map, named, opt, separated_list, tag, value,
};
use log::{error, info};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResultClass {
Done,
Running,
Connected,
... | let byte = input[0];
if byte == b'\"' {
IResult::Error(::nom::ErrorKind::Custom(1)) //what are we supposed to return here??
} else {
IResult::Done(&input[1..], byte)
}
}
named!(
escaped_character<u8>,
alt!(
value!(b'\n', tag!("\\n"))
| value!(b'\r', tag!("\\r... | | value!(ResultClass::Exit, tag!("exit"))
)
);
fn non_quote_byte(input: &[u8]) -> IResult<&[u8], u8> { | random_line_split |
output.rs | use super::Token;
pub use json::object::Object;
pub use json::JsonValue;
use nom::{
alt, call, do_parse, error_position, is_not, many0, map, named, opt, separated_list, tag, value,
};
use log::{error, info};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResultClass {
Done,
Running,
Connected,
... |
}
result_pipe.send(record).expect("send result to pipe");
}
Output::OutOfBand(record) => {
if let OutOfBandRecord::AsyncRecord {
class: AsyncClass::Stopped,
... | {} | conditional_block |
output.rs | use super::Token;
pub use json::object::Object;
pub use json::JsonValue;
use nom::{
alt, call, do_parse, error_position, is_not, many0, map, named, opt, separated_list, tag, value,
};
use log::{error, info};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResultClass {
Done,
Running,
Connected,
... | (line: &str) -> Result<Self, String> {
match output(line.as_bytes()) {
IResult::Done(_, c) => Ok(c),
IResult::Incomplete(e) => Err(format!("parsing line: incomplete {:?}", e)), //Is it okay to read the next bytes then?
IResult::Error(e) => Err(format!("parse error: {}", e)),
... | parse | identifier_name |
runAffEffModSweap.py | import sys
sys.path.append('../code')
import subprocess
import matplotlib.gridspec as gridspec
import numpy as np
import matplotlib.pyplot as plt
import pickle
import fnmatch
import os
from scipy import interpolate
from scipy.interpolate import interp1d
import colormaps as cmaps
from tools import general_tools as gt
im... | nActiveCells = {}
nActiveCells["MnS"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])
# nActiveCells["MnFf"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])
# nActiveCells["MnFr"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])
nActiveCells["Iaf"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])... | # populationFr["MnFf"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])
# populationFr["MnFr"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])
populationFr["Iaf"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])
| random_line_split |
runAffEffModSweap.py | import sys
sys.path.append('../code')
import subprocess
import matplotlib.gridspec as gridspec
import numpy as np
import matplotlib.pyplot as plt
import pickle
import fnmatch
import os
from scipy import interpolate
from scipy.interpolate import interp1d
import colormaps as cmaps
from tools import general_tools as gt
im... |
def transform_amp_perc_to_curr(eesAmplitude):
f = load_rec_data()
current = find_corrisponding_amplitude(eesAmplitude,f)
return current
if __name__ == '__main__':
main()
| tp = (target, f)
current,error = minimize(target, f,x0=150)
return current | identifier_body |
runAffEffModSweap.py | import sys
sys.path.append('../code')
import subprocess
import matplotlib.gridspec as gridspec
import numpy as np
import matplotlib.pyplot as plt
import pickle
import fnmatch
import os
from scipy import interpolate
from scipy.interpolate import interp1d
import colormaps as cmaps
from tools import general_tools as gt
im... |
if error>errTol:raise Exception("minimization failed")
print "out:",x0," target:",target," error:",error
return x0,error
def find_corrisponding_amplitude(target,f):
tp = (target, f)
current,error = minimize(target, f,x0=150)
return current
def transform_amp_perc_to_curr(eesAmplitude):
f = load_rec_data()
c... | break | conditional_block |
runAffEffModSweap.py | import sys
sys.path.append('../code')
import subprocess
import matplotlib.gridspec as gridspec
import numpy as np
import matplotlib.pyplot as plt
import pickle
import fnmatch
import os
from scipy import interpolate
from scipy.interpolate import interp1d
import colormaps as cmaps
from tools import general_tools as gt
im... | (eesAmplitudes,eesFrequencies,simTime,name):
populationFr = {}
populationFr["MnS"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])
# populationFr["MnFf"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])
# populationFr["MnFr"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])
populationFr["Iaf"] = np.z... | plot_stats | identifier_name |
miopoll.rs | use crate::mio::event::{Event, Source};
use crate::mio::{Events, Interest, Poll, Token, Waker};
use slab::Slab;
use stakker::{fwd_nop, Fwd, Stakker};
use std::cell::RefCell;
use std::io::{Error, ErrorKind, Result};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
const WAK... | waker: Arc<Waker>,
}
impl Control {
#[inline]
fn del(&mut self, token: Token, handle: &mut impl Source) -> Result<()> {
let rv = retry(|| self.poll.registry().deregister(handle));
if self.token_map.contains(token.into()) {
self.token_map.remove(token.into());
return ... | // only for 0..=9
queues: [Vec<QueueEvent>; MAX_PRI as usize],
max_pri: u32,
events: Events,
errors: Vec<Error>, | random_line_split |
miopoll.rs | use crate::mio::event::{Event, Source};
use crate::mio::{Events, Interest, Poll, Token, Waker};
use slab::Slab;
use stakker::{fwd_nop, Fwd, Stakker};
use std::cell::RefCell;
use std::io::{Error, ErrorKind, Result};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
const WAK... |
}
self.events.clear();
if !done {
for qu in self.queues.iter_mut().rev() {
if !qu.is_empty() {
for qev in qu.drain(..) {
if let Some(ref mut entry) = self.token_map.get_mut(qev.token) {
done = tr... | {
// Fast-path for highest priority level present in
// registrations, so if user uses only one priority level,
// there is no queuing necessary here.
let ready = Ready::new(ev);
if entry.pri == self.max_pri {
done = tru... | conditional_block |
miopoll.rs | use crate::mio::event::{Event, Source};
use crate::mio::{Events, Interest, Poll, Token, Waker};
use slab::Slab;
use stakker::{fwd_nop, Fwd, Stakker};
use std::cell::RefCell;
use std::io::{Error, ErrorKind, Result};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
const WAK... | {
token_map: Slab<Entry>,
poll: Poll,
// Highest priority in use goes on a fast path so we need queues
// only for 0..=9
queues: [Vec<QueueEvent>; MAX_PRI as usize],
max_pri: u32,
events: Events,
errors: Vec<Error>,
waker: Arc<Waker>,
}
impl Control {
#[inline]
fn del(&mut ... | Control | identifier_name |
xgboost.go | // Copyright 2020 The SQLFlow Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicab... |
func init() {
// xgboost.gbtree, xgboost.dart, xgboost.gblinear share the same parameter set
fullAttrValidator = attribute.NewDictionaryFromModelDefinition("xgboost.gbtree", "")
fullAttrValidator.Update(attributeDictionary)
}
// -----------------------------------------------------------------------------
| {
params := map[string]map[string]interface{}{"": {}, "train.": {}}
paramPrefix := []string{"train.", ""} // use slice to assure traverse order, this is necessary because all string starts with ""
for key, attr := range attrs {
for _, pp := range paramPrefix {
if strings.HasPrefix(key, pp) {
params[pp][key[... | identifier_body |
xgboost.go | // Copyright 2020 The SQLFlow Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicab... | (session *pb.Session) string {
if session.Submitter != "" {
return session.Submitter
}
submitter := os.Getenv("SQLFLOW_submitter")
if submitter != "" {
return submitter
}
return "local"
}
func generateFeatureColumnCode(fcMap map[string][]ir.FeatureColumn) string {
allFCCodes := make([]string, 0)
for targe... | getSubmitter | identifier_name |
xgboost.go | // Copyright 2020 The SQLFlow Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicab... | Batch size for each iteration, -1 means use all data at once.
range: [-1, Infinity]`, attribute.IntLowerBoundChecker(-1, true)).
Int("train.epoch", 1, `[default=1]
Number of rounds to run the training.
range: [1, Infinity]`, attribute.IntLowerBoundChecker(1, true)).
String("validation.select", "", `[default=""]
Speci... | The number of rounds for boosting.
range: [1, Infinity]`, attribute.IntLowerBoundChecker(1, true)).
Int("train.batch_size", -1, `[default=-1] | random_line_split |
xgboost.go | // Copyright 2020 The SQLFlow Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicab... |
return "local"
}
func generateFeatureColumnCode(fcMap map[string][]ir.FeatureColumn) string {
allFCCodes := make([]string, 0)
for target, fcList := range fcMap {
if len(fcList) == 0 {
continue
}
codeList := make([]string, 0)
for _, fc := range fcList {
codeList = append(codeList, fc.GenPythonCode())
... | {
return submitter
} | conditional_block |
internals.rs | use rustfft::FftPlanner;
use crate::utils::buffer::ComplexComponent;
use crate::utils::buffer::{copy_complex_to_real, square_sum};
use crate::utils::buffer::{copy_real_to_complex, BufferPool};
use crate::utils::peak::choose_peak;
use crate::utils::peak::correct_peak;
use crate::utils::peak::detect_peaks;
use crate::ut... | <T>
where
T: Float,
{
pub frequency: T,
pub clarity: T,
}
/// Data structure to hold any buffers needed for pitch computation.
/// For WASM it's best to allocate buffers once rather than allocate and
/// free buffers repeatedly, so we use a `BufferPool` object to manage the buffers.
pub struct DetectorInte... | Pitch | identifier_name |
internals.rs | use rustfft::FftPlanner;
use crate::utils::buffer::ComplexComponent;
use crate::utils::buffer::{copy_complex_to_real, square_sum};
use crate::utils::buffer::{copy_real_to_complex, BufferPool};
use crate::utils::peak::choose_peak;
use crate::utils::peak::correct_peak;
use crate::utils::peak::detect_peaks;
use crate::ut... | // adding this to our sum.
square_error
.iter_mut()
.enumerate()
.skip(1)
.for_each(|(i, a)| {
sum = sum + *a;
*a = *a * T::from_usize(i + 1).unwrap() / sum;
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windowed_autocorrela... | square_error[0] = T::one();
// square_error[0] should always be zero, so we don't need to worry about | random_line_split |
internals.rs | use rustfft::FftPlanner;
use crate::utils::buffer::ComplexComponent;
use crate::utils::buffer::{copy_complex_to_real, square_sum};
use crate::utils::buffer::{copy_real_to_complex, BufferPool};
use crate::utils::peak::choose_peak;
use crate::utils::peak::correct_peak;
use crate::utils::peak::detect_peaks;
use crate::ut... |
#[test]
fn windowed_square_error_test() {
let signal: Vec<f64> = vec![0., 1., 2., 0., -1., -2.];
let window_size: usize = 3;
let buffers = &mut BufferPool::new(signal.len());
let result: Vec<f64> = (0..window_size)
.map(|i| {
signal[..window_size]
... | {
let signal: Vec<f64> = vec![0., 1., 2., 0., -1., -2.];
let window_size: usize = 3;
let buffers = &mut BufferPool::new(signal.len());
let result: Vec<f64> = (0..window_size)
.map(|i| {
signal[..window_size]
.iter()
.z... | identifier_body |
main.rs | #![cfg_attr(feature = "with-bench", feature(test))]
extern crate actix_net;
extern crate actix_web;
extern crate bech32;
extern crate bincode;
extern crate bytes;
extern crate cardano;
extern crate cardano_storage;
extern crate cbor_event;
extern crate chain_addr;
extern crate chain_core;
extern crate chain_crypto;
ext... |
fn gen_priv_key_bech32<K: AsymmetricKey>() -> Bech32 {
let rng = ChaChaRng::from_rng(EntropyRng::new()).unwrap();
let secret = K::generate(rng);
let hrp = K::SECRET_BECH32_HRP.to_string();
Bech32::new(hrp, secret.to_base32()).unwrap()
}
fn gen_pub_key_bech32<K: AsymmetricKey>(priv_key_bech32: &[u5]) ... | {
let command = match Command::load() {
Err(err) => {
eprintln!("{}", err);
std::process::exit(1);
}
Ok(v) => v,
};
match command {
Command::Start(start_settings) => {
if let Err(error) = start(start_settings) {
eprintln!("... | identifier_body |
main.rs | #![cfg_attr(feature = "with-bench", feature(test))]
extern crate actix_net;
extern crate actix_web;
extern crate bech32;
extern crate bincode;
extern crate bytes;
extern crate cardano;
extern crate cardano_storage;
extern crate cbor_event;
extern crate chain_addr;
extern crate chain_core;
extern crate chain_crypto;
ext... | match command {
Command::Start(start_settings) => {
if let Err(error) = start(start_settings) {
eprintln!("jormungandr error: {}", error);
std::process::exit(1);
}
}
Command::GeneratePrivKey(args) => {
let priv_key_bech32 = ... | random_line_split | |
main.rs | #![cfg_attr(feature = "with-bench", feature(test))]
extern crate actix_net;
extern crate actix_web;
extern crate bech32;
extern crate bincode;
extern crate bytes;
extern crate cardano;
extern crate cardano_storage;
extern crate cbor_event;
extern crate chain_addr;
extern crate chain_core;
extern crate chain_crypto;
ext... |
Ok(v) => v,
};
match command {
Command::Start(start_settings) => {
if let Err(error) = start(start_settings) {
eprintln!("jormungandr error: {}", error);
std::process::exit(1);
}
}
Command::GeneratePrivKey(args) => {
... | {
eprintln!("{}", err);
std::process::exit(1);
} | conditional_block |
main.rs | #![cfg_attr(feature = "with-bench", feature(test))]
extern crate actix_net;
extern crate actix_web;
extern crate bech32;
extern crate bincode;
extern crate bytes;
extern crate cardano;
extern crate cardano_storage;
extern crate cbor_event;
extern crate chain_addr;
extern crate chain_core;
extern crate chain_crypto;
ext... | (
gd: &GenesisData,
blockchain: &Blockchain<Cardano>,
_settings: &settings::start::Settings,
) {
println!(
"k={} tip={}",
gd.epoch_stability_depth,
blockchain.get_tip()
);
}
// Expand the type with more variants
// when it becomes necessary to represent different error cases... | startup_info | identifier_name |
qualify_textgrid.py | # -*- coding: utf-8 -*-
# qualify_textgrid.py - usage: python qualify_textgrid src_file[src_root] [timeit]
# to validate the format of a textgrid
# or to calculate the sum time of text in respectively categories
# author: Xiao Yang <xiaoyang0117@gmail.com>
# date: 2016.02.16
import os
import sys
import re
import codecs... |
PATTERN_KEYS = ('pattern', 'key', 'type')
def __init__(self, coding='utf-8'):
super(TextgridParser, self).__init__()
self.default_coding = coding
self.intervals = []
self.original_duration_sum = 0
def reset(self):
self.intervals = []
def read(self, filename):
self.filename = filename
with open(fil... | (re.compile('^(?P<text>.*)$'), 'text', str), # to adapt the new line
(re.compile('^(?P<text>.*)"\s*$'), 'text', str),
) | random_line_split |
qualify_textgrid.py | # -*- coding: utf-8 -*-
# qualify_textgrid.py - usage: python qualify_textgrid src_file[src_root] [timeit]
# to validate the format of a textgrid
# or to calculate the sum time of text in respectively categories
# author: Xiao Yang <xiaoyang0117@gmail.com>
# date: 2016.02.16
import os
import sys
import re
import codecs... | )).group('category')
time_len = interval['xmax'] - interval['xmin']
if time_len < 0:
logtime(u'错误: 在第%d行检测到xmax的值大于xmin值' % interval['lineno'], stdout=True)
else:
assoeted_intervals[category] += time_len
except KeyError, e:
assoeted_intervals[category] = time_len
except AttributeError, e:
con... | False
if legal:
validated.append(interval)
if not quiet:
print(u'验证完成,检测到%d个错误' % error_no)
if error_no == 0:
loginfo(u'Succeed')
else:
loginfo(u'共%d个错误被检测到' % error_no)
loginfo('') # extra space line
return validated
def timeit(intervals, title=None):
assoeted_intervals = {}
for interval in in... | conditional_block |
qualify_textgrid.py | # -*- coding: utf-8 -*-
# qualify_textgrid.py - usage: python qualify_textgrid src_file[src_root] [timeit]
# to validate the format of a textgrid
# or to calculate the sum time of text in respectively categories
# author: Xiao Yang <xiaoyang0117@gmail.com>
# date: 2016.02.16
import os
import sys
import re
import codecs... | odecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)),
)
# for textgrid header
HEADER_PATTERN = (
re.compile('xmin = (?P<start>[\d\.]+)\s*xmax = (?P<end>[\d\.]+)\s*tiers\? <exists>'),
lambda x: float(x.group('end')) - float(x.group('start')),
)
BLOCK_PATTERNS = (
(re.compile('^\s*intervals \[(?P<slice>\d+)\]:'), 'sl... | ', (c | identifier_name |
qualify_textgrid.py | # -*- coding: utf-8 -*-
# qualify_textgrid.py - usage: python qualify_textgrid src_file[src_root] [timeit]
# to validate the format of a textgrid
# or to calculate the sum time of text in respectively categories
# author: Xiao Yang <xiaoyang0117@gmail.com>
# date: 2016.02.16
import os
import sys
import re
import codecs... | urn interval
def match(self, item_pattern, line):
return item_pattern['pattern'].match(line)
def search(self, parser, fn):
return fn(parser.search(self.content))
def parse(self):
print(u'正在解析{filename}...'.format(filename=self.filename))
loginfo(u'>>文件:%s' % self.filename)
original_duration = self.searc... | ip['key']))
else:
interval.update({ ip['key']: ip['type'](ip['pattern'].match(line).group(ip['key'])) })
ret | identifier_body |
table.rs | use std::convert::TryFrom;
use std::io::{self, Write};
#[derive(Debug)]
#[derive(Clone)]
pub struct Table {
// A vector of columns (vectors) of rows. Each column represents an implicant set.
entries: Vec<Vec<Row>>,
// the SOP min-term list
all_implicants: Vec<u32>,
// bit size of the data
bit... |
// Put together the base implicants of the candidate new implicant
temp_implicants = [work_set[i].implicants.clone(), work_set[a].implicants.clone()].concat();
// LOgic not right!!!!!!
// Test to see if the i... | {
continue;
} | conditional_block |
table.rs | use std::convert::TryFrom;
use std::io::{self, Write};
#[derive(Debug)]
#[derive(Clone)]
pub struct Table {
// A vector of columns (vectors) of rows. Each column represents an implicant set.
entries: Vec<Vec<Row>>,
// the SOP min-term list
all_implicants: Vec<u32>,
// bit size of the data
bit... |
pub fn initialize_table (sop: & Vec<u32>) -> Table {
// Get the bit size needed to hold all of the SOP implicants
let bit_size = max_n(&sop);
// initialze a temporary row
let mut the_row = Row {
bin: vec![0,0,0,0],
ones: 0,
implicants: vec![0],
};
// initialize a vect... | {
// If the array has a length less than or equal to one then it is already sorted
if & table.len() <= & 1 {
return table
}
// delare the three vectors
let mut smaller: Vec<Row> = Vec::new();
let mut equal: Vec<Row> = Vec::new();
let mut larger: Vec<Row> = Vec::new();
// Get ... | identifier_body |
table.rs | use std::convert::TryFrom;
use std::io::{self, Write};
#[derive(Debug)]
#[derive(Clone)]
pub struct Table {
// A vector of columns (vectors) of rows. Each column represents an implicant set.
entries: Vec<Vec<Row>>,
// the SOP min-term list
all_implicants: Vec<u32>,
// bit size of the data
bit... | };
// initialize a vector of row
let mut vec_of_rows: Vec<Row> = Vec::new();
// Throw a row into the vector of rows
for i in sop {
the_row.bin = dec_2_bin_vec(i, &bit_size);
the_row.ones = sum_bin_vec(& the_row.bin);
the_row.implicants = vec![*i];
vec_of_rows.pu... | bin: vec![0,0,0,0],
ones: 0,
implicants: vec![0], | random_line_split |
table.rs | use std::convert::TryFrom;
use std::io::{self, Write};
#[derive(Debug)]
#[derive(Clone)]
pub struct Table {
// A vector of columns (vectors) of rows. Each column represents an implicant set.
entries: Vec<Vec<Row>>,
// the SOP min-term list
all_implicants: Vec<u32>,
// bit size of the data
bit... | (mut table: Table) -> Table {
// imps is a vector of rows that houses the new column of implicants
let mut imps: Vec<Row> = Vec::new();
// num_dashes is a u32 that contains the number of dashes (don't cares) in a row. If
// there is more or less than one then the rows cannot be combined.
let mut ... | initial_comparison | identifier_name |
gobuild.go | // Copyright 2009-2010 by Maurice Gilden. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
gobuild - build tool to automate building go programs/libraries
*/
package main
// import "fmt"
import (
"os"
"runtime"
"exec"
"flag"
path "p... | else {
packLib(pack)
}
}
}
/*
Creates a new file called _testmain.go and compiles/links it to _testmain.
If the -run command line option is given it will also run the tests. In this
case -benchmarks/-match/-v are also passed on.
*/
func buildTestExecutable() {
// this will create a file called "_testmain.go... | {
logger.Error("Can't create library because of compile errors.\n")
compileErrors = true
} | conditional_block |
gobuild.go | // Copyright 2009-2010 by Maurice Gilden. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
gobuild - build tool to automate building go programs/libraries
*/
package main
// import "fmt"
import (
"os"
"runtime"
"exec"
"flag"
path "p... |
/*
Executes goyacc for a single .y file. The new .go files is prefixed with
an underscore and returned as a string for further use.
*/
func goyacc(filepath string) string {
// construct output file path
var outFilepath string
l_idx := strings.LastIndex(filepath, "/")
if l_idx >= 0 {
outFilepath = filepath[0:l... | {
var argc int
var argv []string
var argvFilled int
var objDir string = "" //outputDirPrefix + getObjDir();
// build the command line for the linker
argc = 4
if *flagIncludePaths != "" {
argc += 2
}
if pack.NeedsLocalSearchPath() {
argc += 2
}
if pack.Name == "main" {
argc += 2
}
argv = make([]stri... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.