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 |
|---|---|---|---|---|
ospf_sh_request_list.pb.go | eighborAddress
}
return ""
}
type OspfShLsaSum struct {
HeaderLsaType string `protobuf:"bytes,1,opt,name=header_lsa_type,json=headerLsaType,proto3" json:"header_lsa_type,omitempty"`
HeaderLsaAge uint32 `protobuf:"varint,2,opt,name=header_lsa_age,json=headerLsaAge,proto3" json:"header_lsa_a... |
func (m *OspfShRequestList) GetRequestInterfaceName() string {
if m != nil {
return m.RequestInterfaceName
}
return ""
}
func (m *OspfShRequestList) GetRequest() []*OspfShLsaSum {
if m != nil {
return m.Request
}
return nil
}
func init() {
proto.RegisterType((*OspfShRequestList_KEYS)(nil), "cisco_ios_xr_... | {
if m != nil {
return m.RequestNeighborAddress
}
return ""
} | identifier_body |
ospf_sh_request_list.pb.go | () string {
if m != nil {
return m.InterfaceName
}
return ""
}
func (m *OspfShRequestList_KEYS) GetNeighborAddress() string {
if m != nil {
return m.NeighborAddress
}
return ""
}
type OspfShLsaSum struct {
HeaderLsaType string `protobuf:"bytes,1,opt,name=header_lsa_type,json=headerLsaType,proto... | GetInterfaceName | identifier_name | |
login.go | WriteLogFile(err)
return err
}
if len(results.Entries) < 1 {
return errors.New("not found")
}
// attempt auth
log.Println(results.Entries)
//role = strings.Join(results.Entries[0].Attributes[3].Values, "")
return conn.Bind(results.Entries[0].DN, password)
}
// New client with the provided config
// If th... | (w http.ResponseWriter, r *http.Request) {
fmt.Println("123")
SetupResponse(&w, r)
if (*r).Method == "OPTIONS" {
w.Header().Set("Access-Control-Max-Age", "86400")
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("Content-Type", "application/json")
claims := &model.Claims{}
type refresh struct {
Acces... | Refresh | identifier_name |
login.go |
defer conn.Close()
// perform initial read-only bind
if err = conn.Bind(c.ROUser.Name, c.ROUser.Password); err != nil {
WriteLogFile(err)
return err
}
// find the user attempting to login
results, err := conn.Search(ldap.NewSearchRequest(
c.BaseDN, ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases,
0, 0... | {
WriteLogFile(err)
return err
} | conditional_block | |
login.go | WriteLogFile(err)
return err
}
if len(results.Entries) < 1 {
return errors.New("not found")
}
// attempt auth
log.Println(results.Entries)
//role = strings.Join(results.Entries[0].Attributes[3].Values, "")
return conn.Bind(results.Entries[0].DN, password)
}
// New client with the provided config
// If th... | defer selDB.Close()
if err != nil {
WriteLogFile(err)
w.WriteHeader(http.StatusBadRequest)
return
}
if selDB.Next() == false {
w.WriteHeader(http.StatusUnauthorized)
error.Message = "Unauthorized user role"
json.NewEncoder(w).Encode(error)
return
}
} else {
w.WriteHeader(http.StatusUna... | {
var error model.Error
db := database.DbConn()
defer db.Close()
if Role == "project manager" {
selDB, err := db.Query("SELECT project_manager_email from project_manager WHERE project_manager_email =? ", username)
defer selDB.Close()
if err != nil {
WriteLogFile(err)
w.WriteHeader(http.StatusBadRequest)... | identifier_body |
login.go | be validated")
}
if config.Filter == "" {
config.Filter = "sAMAccountName"
}
return config, nil
}
func token(w http.ResponseWriter, username string) {
var error model.Error
db := database.DbConn()
defer db.Close()
if Role == "project manager" {
selDB, err := db.Query("SELECT project_manager_email from pro... | "abcdefghijklmnopqrstuvwxyz%*" +
"0123456789") | random_line_split | |
shotsAlarm_asynchronous_with_hue.py | .nIntensity}
kitchenCommand = {'transitiontime': tTime, 'xy': self.orange, 'bri': self.nIntensity}
elif lrColor == self.lblue:
lrCommand = {'transitiontime': tTime, 'xy': self.green, 'bri': self.nIntensity}
doorCommand = {'transitiontime': tTime, 'xy': self.yellow, 'bri': sel... | with self.lock:
# make sure shots is activated
if self.shotsFired:
# make sure we haven't been counting longer than the song length
if (self.count <= self.songLength):
# update queue with count if countdown stage or go stage... | conditional_block | |
shotsAlarm_asynchronous_with_hue.py | , trackContext]
def playWithContext(self, context):
# double check that we are logged in
self.spLogin()
# double check to make sure we have a context URI
# if we do, go ahead and play with context
if context[2]:
self.sp.start_playback(None, context[2], None, {"ur... |
def updateDoor(self, command):
self.b.set_group(5, command)
def updateHW(self, command):
self.b.set_group(6, command)
def updateKitchen(self, command):
self.b.set_group(2, command)
def flashLights(self, color, delay, seconds):
command = {'transitiontime': 1, 'xy': co... | self.b.set_group(4, command) | identifier_body |
shotsAlarm_asynchronous_with_hue.py | () / 2)
self.frame.grid()
self.frame.master.protocol("WM_DELETE_WINDOW", self.cancel)
def processIncoming(self, cdLen, goHold, songLen):
"""Handle all messages currently in the queue, if any."""
while self.queue.qsize():
try:
count = self.queue.get(0)
... | with self.lock:
self.count = 0
def alarmCancel(self): | random_line_split | |
shotsAlarm_asynchronous_with_hue.py | bri': self.nIntensity}
hwCommand = {'transitiontime': tTime, 'xy': self.blue, 'bri': self.nIntensity}
kitchenCommand = {'transitiontime': tTime, 'xy': self.lblue, 'bri': self.nIntensity}
self.updateLR(lrCommand)
self.updateDoor(doorCommand)
self.updateHW(hwCommand)
... | GUIshow | identifier_name | |
spark-recordcount.py |
import pybgpstream
import sys
try:
import urllib.request as urllib_request
except:
import urllib2 as urllib_request
# Output one data point per day
RESULT_GRANULARITY = 3600*24
# When processing RIBs, split days into 4hr chunks for RV, 8hrs for RIS
RV_RIB_PROCESSING_GRANULARITY = 3600*4
RIS_RIB_PROCESSING_GR... |
peers_data[sig][1] += 1
# the time in the output row is truncated down to a multiple of
# RESULT_GRANULARITY so that slices can be merged correctly
start_time = \
int(math.floor(start_time/RESULT_GRANULARITY) * RESULT_GRANULARITY)
# for each peer that we processed data for, cr... | peers_data[sig][2] += 1 # increment the coll_record_cnt
first = False | conditional_block |
spark-recordcount.py | this peer
# done with elems, increment the 'coll_record_cnt' field for just
# one peer that was present in this record (allows a true, per-collector
# count of records since each record can contain elems for many peers)
if len(peer_signatures):
first = True
for ... | main | identifier_name | |
spark-recordcount.py |
import pybgpstream
import sys
try:
import urllib.request as urllib_request
except:
import urllib2 as urllib_request
# Output one data point per day
RESULT_GRANULARITY = 3600*24
# When processing RIBs, split days into 4hr chunks for RV, 8hrs for RIS
RV_RIB_PROCESSING_GRANULARITY = 3600*4
RIS_RIB_PROCESSING_GR... |
def analyze(start_time, end_time, data_type, outdir,
collector=None, num_cores=None, memory=None):
# round start time down to nearest day
start_time = \
int(math.floor(start_time/RESULT_GRANULARITY) * RESULT_GRANULARITY)
# round end time up to nearest day
rounded = int(math.floor... | return (row[0][0]), row[1] | identifier_body |
spark-recordcount.py | _cnt, peer_record_cnt, coll_record_cnt)
if sig not in peers_data:
peers_data[sig] = [0, 0, 0]
peers_data[sig][0] += 1 # increment elem cnt for this peer
# done with elems, increment the 'coll_record_cnt' field for just
# one peer that was present in this record ... | for key in final_time:
(ts) = key
(elems, records) = final_time[key] | random_line_split | |
battle_traits.ts | `Masters of Destiny`,
desc: `Before rolling any dice for a TZEENTCH unit, you can use one or more of the remaining Destiny Dice from your pool in their stead; the result of the roll you would have made is automatically substituted with the result shown on the Destiny Dice you have chosen to use.
Each ... | desc: `At the start of your hero phase, you can say that your army intends to complete one of the following agendas before the start of your next hero phase. You must tell your opponent which agenda you intend to complete, and you cannot complete the same agenda more than once per battle.
If a friendly... | name: `Agendas of Anarchy`, | random_line_split |
Logistic regression.py | ` package because we want easy access to all the statistical indicators that logistic regression can lead to.
# In[10]:
X = data_encoded.loc[:, list(data_encoded.loc[:, rfe.support_])]
y = data_encoded.loc[:, target]
logit_model=sm.Logit(y, X)
result=logit_model.fit(method='bfgs')
print(result.summary2())
# ### P... | show();
# | conditional_block | |
Logistic regression.py | Id')
print('Selecting {} features'.format(len(features)))
data_complete = data.filter(features + [target])
data_complete = data_complete[data_complete[target].notnull()]
meta_complete = dataframe_metainformation(data_complete)
print_metainformation(meta_complete)
dummy_columns = meta_complete['categorical_features']
... | plot_descriptive | identifier_name | |
Logistic regression.py |
def print_metainformation(meta):
print('Available types:', meta['description']['dtype'].unique())
print('{} Features'.format(meta['description'].shape[0]))
print('{} categorical features'.format(len(meta['categorical_features'])))
print('{} numerical features'.format(len(meta['numerical_features'])))
... | meta = dict()
descr = pd.DataFrame({'dtype': df.dtypes, 'NAs': df.isna().sum()})
categorical_features = descr.loc[descr['dtype'] == 'object'].index.values.tolist()
numerical_features = descr.loc[descr['dtype'] != 'object'].index.values.tolist()
numerical_features_na = descr.loc[(descr['dtype'] != 'objec... | identifier_body | |
Logistic regression.py | # In[11]:
to_remove = result.pvalues[result.pvalues > 0.05].index.tolist()
X.drop(to_remove, inplace=True, axis=1)
logit_model=sm.Logit(y, X)
result=logit_model.fit(method='bfgs')
print(result.summary2())
# ### The Logit model
#
# Here we train the model and evaluate on the test set. The interpretation of the res... | print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred)) | random_line_split | |
common.pb.go | LocationSource_GPS LocationSource = 1
// Manually configured.
LocationSource_CONFIG LocationSource = 2
// Geo resolver (TDOA).
LocationSource_GEO_RESOLVER_TDOA LocationSource = 3
// Geo resolver (RSSI).
LocationSource_GEO_RESOLVER_RSSI LocationSource = 4
// Geo resolver (GNSS).
LocationSource_GEO_RESOLVER_GNSS... |
return ""
}
func (m *KeyEnvelope) GetAesKey() []byte {
if m != nil {
return m.AesKey
}
return nil
}
type Location struct {
// Latitude.
Latitude float64 `protobuf:"fixed64,1,opt,name=latitude,proto3" json:"latitude,omitempty"`
// Longitude.
Longitude float64 `protobuf:"fixed64,2,opt,name=longitude,proto3" ... | {
return m.KekLabel
} | conditional_block |
common.pb.go |
type Region int32
const (
// EU868
Region_EU868 Region = 0
// US915
Region_US915 Region = 2
// CN779
Region_CN779 Region = 3
// EU433
Region_EU433 Region = 4
// AU915
Region_AU915 Region = 5
// CN470
Region_CN470 Region = 6
// AS923
Region_AS923 Region = 7
// KR920
Region_KR920 Region = 8
// IN865
... | {
return fileDescriptor_8f954d82c0b891f6, []int{0}
} | identifier_body | |
common.pb.go | LocationSource_GPS LocationSource = 1
// Manually configured.
LocationSource_CONFIG LocationSource = 2
// Geo resolver (TDOA).
LocationSource_GEO_RESOLVER_TDOA LocationSource = 3
// Geo resolver (RSSI).
LocationSource_GEO_RESOLVER_RSSI LocationSource = 4
// Geo resolver (GNSS).
LocationSource_GEO_RESOLVER_GNSS... | () {
xxx_messageInfo_Location.DiscardUnknown(m)
}
var xxx_messageInfo_Location proto.InternalMessageInfo
func (m *Location) GetLatitude() float64 {
if m != nil {
return m.Latitude
}
return 0
}
func (m *Location) GetLongitude() float64 {
if m != nil {
return m.Longitude
}
return 0
}
func (m *Location) Get... | XXX_DiscardUnknown | identifier_name |
common.pb.go | LocationSource_GPS LocationSource = 1
// Manually configured.
LocationSource_CONFIG LocationSource = 2
// Geo resolver (TDOA).
LocationSource_GEO_RESOLVER_TDOA LocationSource = 3
// Geo resolver (RSSI).
LocationSource_GEO_RESOLVER_RSSI LocationSource = 4
// Geo resolver (GNSS).
LocationSource_GEO_RESOLVER_GNSS... | XXX_sizecache int32 `json:"-"`
}
func (m *KeyEnvelope) Reset() { *m = KeyEnvelope{} }
func (m *KeyEnvelope) String() string { return proto.CompactTextString(m) }
func (*KeyEnvelope) ProtoMessage() {}
func (*KeyEnvelope) Descriptor() ([]byte, []int) {
return fileDescriptor_8f954d82c0b891f6, []int... | // 'Key Transport Security' section.
AesKey []byte `protobuf:"bytes,2,opt,name=aes_key,json=aesKey,proto3" json:"aes_key,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"` | random_line_split |
lib.rs | 256::from(self.denominator)).as_u128()
}
}
#[derive(BorshDeserialize, BorshSerialize)]
pub struct WinnerInfo {
pub user: AccountId, // winner
pub amount: Balance, // win prize
pub height: BlockHeight,
pub ts: u64,
}
#[derive(Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct ... | (&mut self, target: u8) -> HumanReadableDiceResult {
// check called by real user NOT from other contracts
let account_id = env::predecessor_account_id();
assert_eq!(
account_id.clone(),
env::signer_account_id(),
"This method must be called directly from user... | roll_dice | identifier_name |
lib.rs | 256::from(self.denominator)).as_u128()
}
}
#[derive(BorshDeserialize, BorshSerialize)]
pub struct WinnerInfo {
pub user: AccountId, // winner
pub amount: Balance, // win prize
pub height: BlockHeight,
pub ts: u64,
}
#[derive(Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct ... | else {
self.accounts.insert(&account_id, &leftover);
}
// always update jack_pod before rolling dice
self.jack_pod += self.rolling_fee;
// rolling dice here
let random_u8: u8 = env::random_seed().iter().fold(0_u8, |acc, x| acc.wrapping_add(*x));
let dice_poi... | {
self.accounts.remove(&account_id);
} | conditional_block |
lib.rs | 256::from(self.denominator)).as_u128()
}
}
#[derive(BorshDeserialize, BorshSerialize)]
pub struct WinnerInfo {
pub user: AccountId, // winner
pub amount: Balance, // win prize
pub height: BlockHeight,
pub ts: u64,
}
#[derive(Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct ... |
//***********************/
// view functions
//***********************/
fn get_hr_info(&self, index: u64) -> HumanReadableWinnerInfo {
let info = self.win_history.get(index).expect("Error: no this item in winner history!");
HumanReadableWinnerInfo {
user: info.user.clone()... | {
let account_id = env::signer_account_id();
// Use env::log to record logs permanently to the blockchain!
env::log(format!("Saving greeting '{}' for account '{}'", message, account_id,).as_bytes());
} | identifier_body |
lib.rs | 256::from(self.denominator)).as_u128()
}
}
#[derive(BorshDeserialize, BorshSerialize)]
pub struct WinnerInfo {
pub user: AccountId, // winner
pub amount: Balance, // win prize
pub height: BlockHeight,
pub ts: u64,
}
#[derive(Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct ... | // always update jack_pod before rolling dice
self.jack_pod += self.rolling_fee;
// rolling dice here
let random_u8: u8 = env::random_seed().iter().fold(0_u8, |acc, x| acc.wrapping_add(*x));
let dice_point = self.dice_number as u16 * 6_u16 * random_u8 as u16 / 0x100_u16 + 1;
... | if leftover == 0 {
self.accounts.remove(&account_id);
} else {
self.accounts.insert(&account_id, &leftover);
} | random_line_split |
lambda_function.py | (soup, jobs, rows):
for div in rows:
for a in div.find_all(name='a', attrs={'data-tn-element': 'jobTitle'}):
jobs.append(a['title'])
return (jobs)
def extract_company(soup, companies, rows):
for div in rows:
company = div.find_all(name='span', attrs={'class': 'company'})
... | extract_job_title | identifier_name | |
lambda_function.py |
def extract_company(soup, companies, rows):
for div in rows:
company = div.find_all(name='span', attrs={'class': 'company'})
if len(company) > 0:
for b in company:
companies.append(b.text.strip())
else:
sec_try = div.find_all(name='span', attrs={'cl... | for div in rows:
for a in div.find_all(name='a', attrs={'data-tn-element': 'jobTitle'}):
jobs.append(a['title'])
return (jobs) | identifier_body | |
lambda_function.py | ())
return (companies)
def extract_location(soup, locations, rows):
for div in rows:
try:
location_div = div.find(name='div', attrs={'class': 'recJobLoc'})
locations.append(location_div['data-rc-loc'])
except:
locations.append(np.nan)
return (locations)... | job_data['job_title'] = job_data['job_title'].str.lower()
job_data.loc[job_data['job_title'].str.contains(
'data scientist|data science|data science & insights|data science and insights'), 'Job_Title_Category'] = 'Data Scientist'
job_data.loc[job_data['job_title'].str.contains(
'analyst|ana... | def extract_specialization(job_data):
# Categorizing job titles into specialization type.
job_data['Job_Title_Category'] = np.nan | random_line_split |
lambda_function.py |
return (jobs)
def extract_company(soup, companies, rows):
for div in rows:
company = div.find_all(name='span', attrs={'class': 'company'})
if len(company) > 0:
for b in company:
companies.append(b.text.strip())
else:
sec_try = div.find_all(name=... | for a in div.find_all(name='a', attrs={'data-tn-element': 'jobTitle'}):
jobs.append(a['title']) | conditional_block | |
store.go | we'll walk back numHeaders distance to collect each header,
// then return the final header specified by the stop hash. We'll also return
// the starting height of the header range as well so callers can compute the
// height of each header without knowing the height of the stop hash.
//
// NOTE: Part of the BlockHead... | break
} else if hdr.Height == 0 {
break
}
height | {
hdrhash := hdr.Header.blockHeader.BlockHash()
he := hdr.Header
if bh, err := nhs.FetchBlockHeaderByHeight1(tx, hdr.Height); err != nil {
if ErrHashNotFound.Is(err) {
log.Warnf("We have filter header number %v but no block header, "+
"resetting filter headers", hdr.Height)
failed = true
... | conditional_block |
store.go | blockchain.BlockLocator
hash := he.blockHeader.BlockHash()
// Append the initial hash
locator = append(locator, &hash)
// If hash isn't found in DB or this is the genesis block, return the
// locator as is
hewh, err := h.headerEntryByHash(tx, &hash)
if err != nil {
//???
}
height := hewh.Height
if height ... |
/////
///// | random_line_split | |
store.go | we'll walk back numHeaders distance to collect each header,
// then return the final header specified by the stop hash. We'll also return
// the starting height of the header range as well so callers can compute the
// height of each header without knowing the height of the stop hash.
//
// NOTE: Part of the BlockHead... | (
tx walletdb.ReadWriteTx,
headerStateAssertion *FilterHeader,
nhs *NeutrinoDBStore,
) (bool, er.R) {
failed := false
if headerStateAssertion != nil {
// First, we'll attempt to locate the header at this height. If no such
// header is found, then we'll exit early.
assertedHeader, err := f.FetchFilterHeade... | maybeResetHeaderState | identifier_name |
store.go | we'll walk back numHeaders distance to collect each header,
// then return the final header specified by the stop hash. We'll also return
// the starting height of the header range as well so callers can compute the
// height of each header without knowing the height of the stop hash.
//
// NOTE: Part of the BlockHead... | hdr, err := f.chainTip(tx, bucketNameFilterTip)
if err != nil {
return false, err
}
for {
hdrhash := hdr.Header.blockHeader.BlockHash()
he := hdr.Header
if bh, err := nhs.FetchBlockHeaderByHeight1(tx, hdr.Height); err != nil {
if ErrHashNotFound.Is(err) {
log.Warnf("We have filter header nu... | {
failed := false
if headerStateAssertion != nil {
// First, we'll attempt to locate the header at this height. If no such
// header is found, then we'll exit early.
assertedHeader, err := f.FetchFilterHeaderByHeight(headerStateAssertion.Height)
if assertedHeader == nil {
if !ErrHeaderNotFound.Is(err) {
... | identifier_body |
algo_2_2.py | (df):
global NRML
result = {}
for g1,n1 in df.groupby([df.index.month]) :
result[g1] = {}
mxs = {}
for g2,n2 in n1.groupby([n1.index.weekday]) :
result[g1][g2] = {}
for g3,n3 in n2.groupby([n2.index.hour]) :
result[g1][g2][g3] = {}
... | group_A | identifier_name | |
algo_2_2.py | discomforts for every x load sheds!
DISCOMS = [] ## To calculate discomforts for every x load sheds!
discomforts = {} ##
for a,b in date_hour_groups.groups :
print ('*'*60)
print ('{} - {} - {}'.format(loads,a,b))
try :
avg_h_cons = df.loc[df['date'] == a]['value'].m... | # plt.ylim([0, max(y)* 1.3])
# plt.show() | random_line_split | |
algo_2_2.py | ]
groups = []
#Get the right normalized group
nrml = NRML[houses[0][2].month][houses[0][2].weekday()][houses[0][2].hour]
nrml = {x:nrml[x] for x in nrml if x in [y[0] for y in houses]}
nrml = list([list(x) for x in sorted(nrml.items(), key=operator.itemgetter(1))])
for x in nr... | global take_always
take_always = None
if NO_LISTS:
houses = [[row['house_id'],row['value'],datetime.strptime(row['date']+'-'+str(row['hour']),DATE_FORMAT)] for index,row in date_hour_group.iterrows()]
else :
#Iterate the rows
if len(exclude_a) == len(date_hour_group.index) :
... | identifier_body | |
algo_2_2.py | ( [h[1] for h in houses]) < cut :
exclude_a.clear()
take_always = houses
houses = [[row['house_id'],row['value'],datetime.strptime(row['date']+'-'+str(row['hour']),DATE_FORMAT)] for index,row in date_hour_group.iterrows() if \
row['house_id'] not in exclude_a and ... |
groups.append(group)
if sum([ h[1] for h in groups[-1] ]) < cut :
groups = groups[:-1]
return groups[:1],shedding
def load_set():
'''
Load the data
'''
df = pd.read_hdf(FILE_PATH)
calc_normalized()
'''
Calculate the hourly average
'''
... | i = 0
group.append(houses[i]+[shedding.get(houses[i][0],0)])
shedding[houses[i][0]] = shedding.get(houses[i][0],0)
del houses[i] | conditional_block |
api.go | aturity: int32(api.node.node.Params.CoinbaseMaturity),
Modules: []string{cmds.DefaultServiceNameSpace, cmds.MinerNameSpace, cmds.TestNameSpace, cmds.LogNameSpace},
}
ret.GraphState = GetGraphStateResult(best.GraphState)
hostdns := api.node.node.peerServer.HostDNS()
if hostdns != nil {
ret.DNS = hostdns... | gsups[p.Network][0] = gsups[p.Network][0] + p.GraphStateDur
if p.GraphStateDur > gsups[p.Network][1] { | random_line_split | |
api.go | 00000*version.Major + 10000*version.Minor + 100*version.Patch),
BuildVersion: version.String(),
ProtocolVersion: int32(protocol.ProtocolVersion),
TotalSubsidy: best.TotalSubsidy,
TimeOffset: int64(api.node.blockManager.GetChain().TimeSource().Offset().Seconds()),
Connections: int32(len(api.node... |
return jrs, nil
}
func GetGraphStateResult(gs *blockdag.GraphState) *json.GetGraphStateResult {
if gs != nil {
mainTip := gs.GetMainChainTip()
tips := []string{mainTip.String() + " main"}
for k := range gs.GetTips().GetMap() {
if k.IsEqual(mainTip) {
continue
}
tips = append(tips, k.String())
}... | {
jrs = append(jrs, v.ToJson())
} | conditional_block |
api.go | Result{
ID: p.PeerID,
Name: p.Name,
Address: p.Address,
BytesSent: p.BytesSent,
BytesRecv: p.BytesRecv,
Circuit: p.IsCircuit,
Bads: p.Bads,
}
info.Protocol = p.Protocol
info.Services = p.Services.String()
if p.Genesis != nil {
info.Genesis = p.Genesis.String()
}
... | {
err := common.ParseAndSetDebugLevels(level)
if err != nil {
return nil, err
}
return level, nil
} | identifier_body | |
api.go | owType == pow.CRYPTONIGHT {
if target.Cmp(big.NewInt(0)) > 0 {
difficulty = new(big.Rat).SetFrac(base, target)
}
} else {
difficulty = new(big.Rat).SetFrac(target, base)
}
outString := difficulty.FloatString(8)
diff, err := strconv.ParseFloat(outString, 64)
if err != nil {
log.Error(fmt.Sprintf("Cannot... | Banlist | identifier_name | |
createHeatmap.py | ypassing summary file creation'
os.system('cat ' + headJobName + ' > ' + verboseSummaryFile)
# Defined by 'print_crossCorrBinaryline_to_str' in CrossCorrToplist.c
# Not by the CrossCorrBinaryOutputEntry struct in CrossCorrToplist, h, confusingly
dataDTypes = np.dtype({'names':['freq','tp','argp','... | def takeAxisAndRotate(threeDarray, zIndex, takeAxisIndex, flipAxes):
firstTwoDarray = np.take(threeDarray, zIndex, takeAxisIndex)
if (flipAxes == 1):
twoDarray = firstTwoDarray.T
elif (flipAxes == 0): | random_line_split | |
createHeatmap.py | Search band, or standalone: make plots appropriate for a 5 Hz band')
parser.add_argument('--elsewhere', help='Path to directory containing the output files')
parser.add_argument('--massiveSummary',action='store_true', help='Deal with large output directories')
parser.add_argument('--plotSkyContour',type=float, help='Pl... | (args):
headJobName = args.nameToplist
verboseSummaryFile = 'verbose_summary-' + str(args.fCenter) +'.txt'
if args.bypassSummary:
print 'Bypassing summary file creation'
os.system('cat ' + headJobName + ' > ' + verboseSummaryFile)
# Defined by 'print_crossCorrBinaryline_to_str' in Cro... | summarizer | identifier_name |
createHeatmap.py | # Defined by 'print_crossCorrBinaryline_to_str' in CrossCorrToplist.c
# Not by the CrossCorrBinaryOutputEntry struct in CrossCorrToplist, h, confusingly
dataDTypes = np.dtype({'names':['freq','tp','argp','asini','ecc','period','estSens','evSquared','rho'],'formats':['f8','f8','f8','f8','f8','f8','f8','f8','... | firstTwoDarray = np.take(threeDarray, zIndex, takeAxisIndex)
if (flipAxes == 1):
twoDarray = firstTwoDarray.T
elif (flipAxes == 0):
twoDarray = firstTwoDarray
else:
'flipAxes not configured correctly'
return twoDarray | identifier_body | |
createHeatmap.py | templateSearch band, or standalone: make plots appropriate for a 5 Hz band')
parser.add_argument('--elsewhere', help='Path to directory containing the output files')
parser.add_argument('--massiveSummary',action='store_true', help='Deal with large output directories')
parser.add_argument('--plotSkyContour',type=float,... |
else:
print 'Incompatible options'
# In the toplist, columns change from the right (big-endian)
# They are listed f, t, a,
# Python reads in entries in the order f0t0a0, f0t0a1, f0t1a0,...
FLen = len(np.unique(fArray))
TLen = len(np.unique(tpArray))
... | xArray = fArray
yArray = modArray
zArray = tpArray
zIndex = args.TIndex
takeAxisIndex = 1
flipAxes = 0 | conditional_block |
entitymap.go | r err os.Error
var num int
entity = entity[2 : len(entity)-1]
if num, err = strconv.Atoi(entity); err != nil {
return "&#" + entity + ";"
}
var arr [4]byte
if size := utf8.EncodeRune(arr[:], num); size == 0 {
return "&#" + entity + ";"
}
return string(arr[:])
}
// Converts a single Go utf8-token... | eturn "&" + entity[2:len(entity)-1] + ";"
}
va | conditional_block | |
entitymap.go | em["euml"] = "\u00eb"
em["Kappa"] = "\u039a"
em["nbsp"] = "\u00a0"
em["Eacute"] = "\u00c9"
em["brvbar"] = "\u00a6"
em["otimes"] = "\u2297"
em["ndash"] = "\u2013"
em["thinsp"] = "\u2009"
em["nu"] = "\u03bd"
em["Upsilon"] = "\u03a5"
em["upsih"] = "\u03d2"
em["raquo"] = "\u00bb"
em["yacute"] = "\u00fd"
em["d... | "pi"] = "\u03c0"
em["nabla"] = "\u2207"
em["isin"] = "\u2208"
em["loz"] = "\u25ca"
em["prop"] = "\u221d"
em["para"] = "\u00b6"
em["Aring"] = "\u00c5"
em["euro"] = "\u20ac"
em["sup3"] = "\u00b3"
em["sup2"] = "\u00b2"
em["sup1"] = "\u00b9"
em["prod"] = "\u220f"
em["gamma"] = "\u03b3"
em["perp"] = "\u22a5"
e... | identifier_body | |
entitymap.go | ty string) string {
var ok bool
if ok = reg_entnamed.MatchString(entity); ok {
return namedEntityToUtf8(entity[1 : len(entity)-1])
}
if ok = reg_entnumeric.MatchString(entity); !ok {
return "&" + entity[2:len(entity)-1] + ";"
}
var err os.Error
var num int
entity = entity[2 : len(entity)-1]
if num, ... | yToUtf8(enti | identifier_name | |
entitymap.go | 135"
em["notin"] = "\u2209"
em["Pi"] = "\u03a0"
em["sdot"] = "\u22c5"
em["upsilon"] = "\u03c5"
em["iota"] = "\u03b9"
em["hArr"] = "\u21d4"
em["Sigma"] = "\u03a3"
em["lang"] = "\u2329"
em["curren"] = "\u00a4"
em["Theta"] = "\u0398"
em["lArr"] = "\u21d0"
em["Phi"] = "\u03a6"
em["Nu"] = "\u039d"
em["rho"] = ... | case "tilde":
return "\u02dc"
case "Uuml":
return "\u00dc" | random_line_split | |
parser.rs | inator::opt(character::line_ending)(i)?;
Ok((i, ln))
}
#[derive(Debug, Deserialize, Clone)]
pub enum IssueProvider {
GitHub,
}
#[derive(Debug, Clone)]
pub enum ParsingSource {
MarkdownFile,
SourceCode,
IssueAt(IssueProvider),
}
#[derive(Debug, Clone)]
pub struct IssueHead<K> {
pub title: Stri... | let desc_lines = todo
.desc_lines
.iter()
.map(|s| s.to_string())
.collect::<Vec<_>>();
issue.body.descs_and_srcs.push((desc_lines, loc));
}
pub fn from_files_in_directory(
dir: &str,
excludes: &Vec<String>,
) -> Result<IssueMa... | random_line_split | |
parser.rs | inator::opt(character::line_ending)(i)?;
Ok((i, ln))
}
#[derive(Debug, Deserialize, Clone)]
pub enum IssueProvider {
GitHub,
}
#[derive(Debug, Clone)]
pub enum ParsingSource {
MarkdownFile,
SourceCode,
IssueAt(IssueProvider),
}
#[derive(Debug, Clone)]
pub struct IssueHead<K> {
pub title: Stri... | (&mut self, todo: &ParsedTodo, loc: FileTodoLocation) {
let title = todo.title.to_string();
let issue = self
.todos
.entry(title.clone())
.or_insert(Issue::new((), title));
if let Some(assignee) = todo.assignee.map(|s| s.to_string()) {
if !issue.h... | add_parsed_todo | identifier_name |
parser.rs | ::opt(character::line_ending)(i)?;
Ok((i, ln))
}
#[derive(Debug, Deserialize, Clone)]
pub enum IssueProvider {
GitHub,
}
#[derive(Debug, Clone)]
pub enum ParsingSource {
MarkdownFile,
SourceCode,
IssueAt(IssueProvider),
}
#[derive(Debug, Clone)]
pub struct IssueHead<K> {
pub title: String,
... |
let languages = languages.expect("impossible!");
// Open the file and load the contents
let mut file = File::open(path)
.map_err(|e| format!("could not open file: {}\n{}", path.display(), e))?;
let mut contents = String::new();
file.read_to_s... | {
// TODO: Deadletter the file name as unsupported
println!("possible TODO found in unsupported file: {:#?}", path);
continue;
} | conditional_block |
nvm_buffer.rs | 指す」という点では`position`フィールドと似ているが、
// `position`は読み書きやシーク操作の度に値が更新されるのに対して、
// `write_buf_offset`は、書き込みバッファの内容がフラッシュされるまでは、
// 固定の値が使用され続ける。
write_buf_offset: u64,
// 書き込みバッファ内にデータが溜まっているかどうかを判定するためのフラグ
//
// 一度でも書き込みバッファにデータが書かれたら`true`に設定され、
// 内部NVMにバッファ内のデータがフラッシュされた後は`false`に設定される。
... | tState,
"self.position={}, write_len={}, self.len={}",
self.position(),
write_len,
self.capacity()
);
Ok(())
}
}
impl<N: NonVolatileMemory> NonVolatileMemory for JournalNvmBuffer<N> {
fn sync(&mut self) -> Result<()> {
track!(self.flush_wri... | ),
ErrorKind::Inconsisten | conditional_block |
nvm_buffer.rs | バッファの内容がフラッシュされるまでは、
// 固定の値が使用され続ける。
write_buf_offset: u64,
// 書き込みバッファ内にデータが溜まっているかどうかを判定するためのフラグ
//
// 一度でも書き込みバッファにデータが書かれたら`true`に設定され、
// 内部NVMにバッファ内のデータがフラッシュされた後は`false`に設定される。
maybe_dirty: bool,
// 読み込みバッファ
//
// ジャーナル領域が発行した読み込み要求を、
// 内部NVMのブロック境界に合うようにアライメントするため... | lush( | identifier_name | |
nvm_buffer.rs | // - 書き込みバッファのカバー範囲に重複する領域に対して、読み込み要求が発行された場合:
// - 書き込みバッファの内容をフラッシュして、内部NVMに同期した後に、該当読み込み命令を処理
// - 書き込みバッファのカバー範囲に重複しない領域に対して、書き込み要求が発行された場合:
// - 現状の書き込みバッファのデータ構造では、ギャップ(i.e., 連続しない複数部分領域)を表現することはできない
// - そのため、一度古いバッファの内容をフラッシュした後に、該当書き込み要求を処理するためのバッファを作成する
//
// ジャーナル領域が発行した書き込み... | // - ジャーナル領域は定期的に本メソッドを呼び出す | random_line_split | |
nvm_buffer.rs | 指す」という点では`position`フィールドと似ているが、
// `position`は読み書きやシーク操作の度に値が更新されるのに対して、
// `write_buf_offset`は、書き込みバッファの内容がフラッシュされるまでは、
// 固定の値が使用され続ける。
write_buf_offset: u64,
// 書き込みバッファ内にデータが溜まっているかどうかを判定するためのフラグ
//
// 一度でも書き込みバッファにデータが書かれたら`true`に設定され、
// 内部NVMにバッファ内のデータがフラッシュされた後は`false`に設定される。
... | ite_buf.aligned_resize(end);
(&mut self.write_buf[start..end]).copy_from_slice(buf);
self.position += buf.len() as u64;
self.maybe_dirty = true;
Ok(buf.len())
} else {
// 領域に重複がないので、一度バッファの中身を書き戻す
track!(self.flush_write_buf())?;
... | et) as usize;
let end = start + buf.len();
self.wr | identifier_body |
bootstrap.py | , path, requirements, hgrc, heads):
"""Wraps process_hg_sync to provide logging"""
logger.info('syncing repo: %s' % path)
try:
return process_hg_sync(config, path, requirements, hgrc, heads, create=True)
finally:
logger.info('exiting sync for: %s' % path)
def seqmap(message_handler, ev... | 'enable_auto_commit': False, # We don't actually commit but this is just for good measure
}
consumer = KafkaConsumer(**consumer_config)
# This call populates topic metadata for all topics in the cluster.
# Needed as missing topic metadata can cause the below call to retrieve
# partition in... | random_line_split | |
bootstrap.py | type=int,
default=multiprocessing.cpu_count())
parser.add_argument('--output', help='Output file path for hgssh JSON')
args = parser.parse_args()
config = Config(filename=args.config)
topic = config.get('replicationproducer', 'topic')
# Create consumer to gather partition... | logger.info('processing messages for partition %s' % partition)
for message in messages:
payload = message.value
# Ignore heartbeat messages
if payload['name'] == 'heartbeat-1':
continue
if payload['path'] in repositories_... | conditional_block | |
bootstrap.py | , path, requirements, hgrc, heads):
"""Wraps process_hg_sync to provide logging"""
logger.info('syncing repo: %s' % path)
try:
return process_hg_sync(config, path, requirements, hgrc, heads, create=True)
finally:
logger.info('exiting sync for: %s' % path)
def seqmap(message_handler, ev... | ():
'''hgweb component of the vcsreplicator bootstrap procedure. Takes a
vcsreplicator config path on the CLI and takes a JSON data structure
on stdin'''
import argparse
# Parse CLI args
parser = argparse.ArgumentParser()
parser.add_argument('config', help='Path of config file to load')
... | hgweb | identifier_name |
bootstrap.py | , path, requirements, hgrc, heads):
"""Wraps process_hg_sync to provide logging"""
logger.info('syncing repo: %s' % path)
try:
return process_hg_sync(config, path, requirements, hgrc, heads, create=True)
finally:
logger.info('exiting sync for: %s' % path)
def seqmap(message_handler, ev... |
def hgssh():
'''hgssh component of the vcsreplicator bootstrap procedure.'''
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('config', help='Path to config file')
parser.add_argument('hg', help='Path to hg executable for use in bootstrap process')
parser.add_argument('... | '''Process events using the message handler in the order they
arrived in the queue
'''
for config, payload in events:
message_handler(config, payload) | identifier_body |
linked_list.rs | <L> {
pub fn empty() -> ListLink<L> {
ListLink {
push_lock: AtomicBool::new(true),
next: Cell::new(None),
prev: Cell::new(None),
_pd: PhantomData,
}
}
pub fn is_in_use(&self) -> bool {
match (self.next.get(), self.prev.get()) {
... |
link.prev.set(self.tail);
link.next.set(None);
self.tail = Some(link_ptr);
Ok(())
}
}
/// Pops the element at the beginning of the list. `O(1)`.
pub fn pop_front(&mut self) -> Option<L::Elem> {
match self.head {
Some(head) => uns... | {
self.head = Some(link_ptr);
} | conditional_block |
linked_list.rs | //!
//! let mut threads = List::<ThreadsNode>::new();
//! let thread1 = Arc::new(Thread { id: 1, link: Default::default() });
//! threads.push_back(thread1);
//! ```
//!
use core::cell::Cell;
use core::fmt::{self, Debug, Formatter};
use core::marker::PhantomData;
use core::ops::ControlFlow;
use core::ptr::NonNull;
use ... | //! link: ListLink<ThreadsNode>,
//! }
//!
//! define_list_node!(ThreadsNode, Arc<Thread>, link); | random_line_split | |
linked_list.rs | Link<L> {
pub fn empty() -> ListLink<L> {
ListLink {
push_lock: AtomicBool::new(true),
next: Cell::new(None),
prev: Cell::new(None),
_pd: PhantomData,
}
}
pub fn is_in_use(&self) -> bool {
match (self.next.get(), self.prev.get()) {
... | (&self) -> Iter<'_, L> {
Iter {
current: self.head,
_pd: &PhantomData,
}
}
}
impl<L: ListNode> Default for List<L> {
fn default() -> Self {
Self::new()
}
}
pub struct Iter<'a, L: ListNode> {
current: Option<NonNull<ListLink<L>>>,
_pd: &'a PhantomData... | iter | identifier_name |
view.rs | (ImageViewType::Dim2dArray, ImageDimensions::Dim3d { .. }, _, 1)
if flags.array_2d_compatible =>
{
()
}
_ => return Err(ImageViewCreationError::IncompatibleType),
}
let inner =
unsafe { UnsafeImageView::new(image_inner, ty... | can_be_sampled | identifier_name | |
view.rs | Type::Cubemap, ImageDimensions::Dim2d { .. }, 6, _)
if flags.cube_compatible =>
{
()
}
(ImageViewType::CubemapArray, ImageDimensions::Dim2d { .. }, n, _)
if flags.cube_compatible && n % 6 == 0 =>
{
()
... | fn array_layers(&self) -> Range<u32>;
/// Returns the format of this view. This can be different from the parent's format.
fn format(&self) -> Format; | random_line_split | |
view.rs | of the required usages](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#valid-imageview-imageusage)
/// for image views.
InvalidImageUsage,
}
impl error::Error for ImageViewCreationError {
#[inline]
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match... | {
(**self).array_layers()
} | identifier_body | |
documentDeltaConnection.ts | extends EventEmitterWithErrorHandling<IDocumentDeltaConnectionEvents>
implements IDocumentDeltaConnection, IDisposable
{
static readonly eventsToForward = ["nack", "op", "signal", "pong"];
// WARNING: These are critical events that we can't miss, so registration for them has to be in place at all times!
// Includ... | */
export class DocumentDeltaConnection | random_line_split | |
documentDeltaConnection.ts | () {
assert(
this._disposed || this.socket.connected,
0x244 /* "Socket is closed, but connection is not!" */,
);
return this._disposed;
}
/**
* Flag to indicate whether the DocumentDeltaConnection is expected to still be capable of sending messages.
* After disconnection, we flip this to prevent any ... | disposed | identifier_name | |
documentDeltaConnection.ts | * @param reason - reason for disconnect
*/
protected disconnectCore() {
this.socket.disconnect();
}
protected async initialize(connectMessage: IConnect, timeout: number) {
this.socket.on("op", this.earlyOpHandler);
this.socket.on("signal", this.earlySignalHandler);
this.earlyOpHandlerAttached = true;
... | {
this.socket.on(event, listener);
assert(!this.trackedListeners.has(event), 0x20e /* "double tracked listener" */);
this.trackedListeners.set(event, listener);
} | identifier_body | |
documentDeltaConnection.ts | 0x20a /* "register for event on disposed object" */);
// Some events are already forwarded - see this.addTrackedListener() calls in initialize().
if (DocumentDeltaConnection.eventsAlwaysForwarded.includes(event)) {
assert(this.trackedListeners.has(event), 0x245 /* "tracked listener" */);
return;
}
... |
this.closeSocketCore(error);
}
protected closeSocketCore(error: IAnyDriverError) {
this.disconnect(error);
}
/**
* Disconnect from the websocket, and permanently disable this DocumentDeltaConnection and close the socket.
* However the OdspDocumentDeltaConnection differ in dispose as in there we don't clo... | {
// This would be rare situation due to complexity around socket emitting events.
return;
} | conditional_block |
acc.js | ();
return saveOwnership();
};
}
// 登记信息保存更新操作
function saveDjxx() {
var result =true;
var djbh = $("#djbh").val();
var djlx = $('input[name="djlx"]').val();
var djd = $('input[name="djd"]').val();
var ywms = $("#ywms").val();
var xmmc = $("#xmmc").val();
$("#djbh1").val(djbh);
$("#djlx1").val(djlx... | 1.string5){
// alert($("#add_app_form").serialize());
var djjk = $("#djjk").val();
var qdfs = $('input[name="get_mode"]').val();
var synx = $("#synx").val();
var qsrq = $('input[name="start_date"]').val();
var zzrq = $('input[name="end_date"]').val();
var fwxz = $('input[name="house_attr"]').val();
var ... | identifier_body | |
acc.js | _name'
}, {
title : '申请人类型',
field : 'app_type',formatter : dicts.format.app_type_format
}, {
title : '证件类型',
field : 'app_cer_type',formatter : dicts.format.app_cer_type_format
}, {
title : '证件编号',
field : 'app_cer_no'
}, {
title : '份额',
field : 'app_port'
}, {
... | field : 'app_tel'
}, {
title : '法定代表人',
field : 'legal_name'
}, {
title : '代理人',
field : 'agent_name'
},
{
title : '代理人证件类型',
field : 'agent_cer_type',
formatter : function(value) {
if(value == '001'){
return '身份证';
};
if(value == '002'){
... |
}, {
title : '联系电话', | random_line_split |
acc.js | _name'
}, {
title : '申请人类型',
field : 'app_type',formatter : dicts.format.app_type_format
}, {
title : '证件类型',
field : 'app_cer_type',formatter : dicts.format.app_cer_type_format
}, {
title : '证件编号',
field : 'app_cer_no'
}, {
title : '份额',
field : 'app_port'
}, {
... | 名称: dowatch
*功能说明: 查看登记单元详细信息
*参数说明: 无
*返 回 值: 无
*函数作者: xuzz
*创建日期: 2014-03-27
*修改历史:
***********************************************************************************/
function dowatch(button){
var row = $('#table_house').datagrid('getSelected');
var obj={};
obj.WHERE_CODE=row.CODE;
obj.REG_... | *
*函数 | identifier_name |
acc.js | ��口高
height : 600,
modal : true,
// 窗口中iframe的window对象的onLoad回调函数设置
onLoad : function() {
// 此处将本窗口window对象赋值为打开的新窗口window对象的openerWindow属性。
// 因此,在新窗口中,可通过openerWindow属性调用本窗口,从而实现多窗口间的交互、传值。
this.openerWindow = window;
// 将参数传入打开窗口对象的parenter属性中,从而实现窗口间传递参数调用
this.args = {
... | nership.action?time="+new Date()+"&proc_id="+proc_id,
success:function(data){
| conditional_block | |
PerceptronClassifier.py | self.max_iter = max_iter
self.learnRate = 1
if training_data is not None:
self.fit(training_data, devel_data)
def fit(self, training_data, devel_data=None):
'''
Estimate the parameters for perceptron model. For multi-class perceptron, parameters can be
treated a... | # print '初始预测:', Z, self._score(X, Z), 'Y的分数', self._score(X, Y)
# print self.W[Y]
tmp = self._score(X,Y)
# Your code here. If the predict is incorrect, perform the perceptron update
n_errors += 1
fo... | Z = self._predict(X)
if Z != Y: | random_line_split |
PerceptronClassifier.py | .max_iter = max_iter
self.learnRate = 1
if training_data is not None:
self.fit(training_data, devel_data)
def fit(self, training_data, devel_data=None):
'''
Estimate the parameters for perceptron model. For multi-class perceptron, parameters can be
treated as a T... | # print '调整后:',self._predict(X),'正确:',Y,'Y的分数',self._score(X,Y)
print('training error %d' % n_errors)
if devel_data is not None:
# Test accuracy on the development set if provided.
n_corr, n_total = 0, 0
for words, tags in deve... | rors = 0
print('training iteration #%d' % it)
for X, Y in instances:
# Your code here, ake a prediction and give it to Z
Z = self._predict(X)
if Z != Y:
# print '初始预测:', Z, self._score(X, Z), 'Y的分数', self._score(X, Y)
... | conditional_block |
PerceptronClassifier.py | .max_iter = max_iter
self.learnRate = 1
if training_data is not None:
self.fit(training_data, devel_data)
def fit(self, training_data, devel_data=None):
'''
Estimate the parameters for perceptron model. For multi-class perceptron, parameters can be
treated as a T... | ):
'''
Extract features from words and prev POS tag, if `add` is True, also insert the feature
string to the feature_alphabet.
Parameters
----------
words: list(str)
The words list
i: int
The position
prev_tag: str
Prev... | g=None, add=True | identifier_name |
PerceptronClassifier.py | _iter = max_iter
self.learnRate = 1
if training_data is not None:
self.fit(training_data, devel_data)
def fit(self, training_data, devel_data=None):
'''
Estimate the parameters for perceptron model. For multi-class perceptron, parameters can be
treated as a T \ti... | if value > best_score:
best_score = value
best_y = index
# print 'best:',best_score,best_y
# print max([math.fabs(sc - 10) for sc in pred_scores])
return best_y
def predict(self, words, i, prev_t
ag=None):
'''
Make prediction on l... | n features and label t
Parameters
----------
features: list(int)
The hashed features
t: int
The index of label
Return
------
best_y: int
The highest scored label's index
'''
pred_scores = [self._score(features,... | identifier_body |
contSpec.py | GexpFile'])
if par['verbose']:
print('(*) Initial Set up...', end="")
# Set up some internal variables
n = len(t)
ns = par['ns'] # discretization of 'tau'
tmin = t[0];
tmax = t[n-1];
# determine frequency window
if par['FreqEnd'] == 1:
smin = np.exp(-np.... | # Read input parameters from file "inp.dat" | random_line_split | |
contSpec.py | len(Gexp)
ns = len(H)
nl = ns - 2
logPmax = -np.inf # so nothing surprises me!
Hlambda = np.zeros((ns, npoints))
# Error Analysis: Furnish A_matrix
Amat = getAmatrix(len(H))
_, LogDetN = np.linalg.slogdet(Amat)
#
# This is the costliest step
#
f... | kernelD | identifier_name | |
contSpec.py | this here for now because storing lamC for sometime only
#
if par['plotting']:
plt.clf()
# plt.axvline(x=lamC, c='k', label=r'$\lambda_c$')
plt.axvline(x=lamM, c='gray', label=r'$\lambda_m$')
plt.ylim(-20,1)
plt.plot(lam, logP, 'o-')
plt.xscale('log')
plt... | lamC, lam, rho, eta, logP, Hlam = lcurve(Gexp, wexp, Hgs, kernMat, par, G0) | conditional_block | |
contSpec.py | 0]
npoints = int(par['lamDensity'] * (np.log10(par['lam_max']) - np.log10(par['lam_min'])))
hlam = (par['lam_max']/par['lam_min'])**(1./(npoints-1.))
lam = par['lam_min'] * hlam**np.arange(npoints)
eta = np.zeros(npoints)
rho = np.zeros(npoints)
logP = np.zeros(npoin... | Kmatrix = np.dot((wexp/Gexp).reshape(n,1), np.ones((1,ns)));
if len(H) > ns:
G0 = H[-1]
H = H[:-1]
Jr = np.zeros((n + nl, ns+1))
Jr[0:n, 0:ns] = -kernelD(H, kernMat) * Kmatrix;
# Jr[0:n, ns] = -1./Gexp # column for dr_i/dG0
... | """
HELPER FUNCTION for optimization: Get Jacobian J
returns a (n+nl * ns) matrix Jr; (ns + 1) if G0 is also supplied.
Jr_(i, j) = dr_i/dH_j
It uses kernelD, which approximates dK_i/dH_j, where K is the kernel
"""
n = kernMat.shape[0];
ns = kernMat.shape[1];
nl = ... | identifier_body |
cipher_functions.py |
def swap_cards(deck_of_crds, index):
'''
(list of int, int) -> NoneType
REQ: len(d_of_crds) >= 1
REQ: 0 < index < len(d_of_crds)
>>> swap_cards([1,2,4,6], 2)
[1,2,6,4]
>>> swap_cards([1,2,4,5,6,7,8,9,10,12,21], 10)
[21, 2, 4, 5, 6, 7, 8, 9, 10, 12, 1]
Return... | decripted_vlue = chr(decripted_vlue + 65)
return decripted_vlue | random_line_split | |
cipher_functions.py | _joker_1 < last_idx_vlue):
# Store the values before JOKER1 and place them at top of deck.
values_bfr_JOKER1 = deck_of_crds.pop()
deck_of_crds.insert(0, values_bfr_JOKER1)
last_idx_vlue -= 1
def insert_top_to_bottom(deck_of_crds):
'''(lis... | '''(file open for reading) -> list of int
REQ: len(file) > 0
REQ: file must contain atleast 1 line, and must all be int
Read and return the contents of the file as a list of int.
'''
counter = 0
# create a empty list
list_of_str = list()
# Read through all the lines in the file
... | identifier_body | |
cipher_functions.py | _crds, index):
'''
(list of int, int) -> NoneType
REQ: len(d_of_crds) >= 1
REQ: 0 < index < len(d_of_crds)
>>> swap_cards([1,2,4,6], 2)
[1,2,6,4]
>>> swap_cards([1,2,4,5,6,7,8,9,10,12,21], 10)
[21, 2, 4, 5, 6, 7, 8, 9, 10, 12, 1]
Return the swap of the card at the giv... |
# Find the last index number and store it
last_idx_vlue = (len(deck_of_crds) -1)
while (index_joker_1 < last_idx_vlue):
# Store the values before JOKER1 and place them at top of deck.
values_bfr_JOKER1 = deck_of_crds.pop()
deck_of_crds.... | values_bfr_JOKER1 = deck_of_crds.pop(0)
# Insert those values before JOKER1
deck_of_crds.insert(index_joker_1, values_bfr_JOKER1)
counter +=1 | conditional_block |
cipher_functions.py | Type
REQ: JOKER2 in deck_of_crds
REQ: len(deck_of_crds) >= 2
>>> move_joker_2([1,2,4,28,6])
[28,2,4,6,1]
>>> move_joker_2([28,2,4,6,1])
[2,4,28,6,1]
>>> move_joker_2([2,4,28,6,1])
[2,4,6,1,28]
>>> move_joker_2([28,2])
[28,2]
Return the swap of JOKER2,... | get_next_value | identifier_name | |
types.rs | WITH TIME ZONE
TIME_TZ = 186,
/// TIMESTAMP
TIMESTAMP = 187,
/// TIMESTAMP WITH TIME ZONE
TIMESTAMP_TZ = 188,
/// INTERVAL YEAR TO MONTH
INTERVAL_YM = 189,
/// INTERVAL DAY TO SECOND
INTERVAL_DS = 190,
/// /* */
TIMESTAMP_LTZ = 232,
/// pl/sql representation of named ty... | /// Specifies the various modes of operation
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(dead_code)]
pub enum AuthMode {
/// In this mode, the user session context returned can only ever be set with the server context
/// specified in `svchp`. For encoding, the server handle uses the setting in the environ... | }
impl Default for AttachMode {
fn default() -> Self { AttachMode::Default }
} | random_line_split |
types.rs | WITH TIME ZONE
TIME_TZ = 186,
/// TIMESTAMP
TIMESTAMP = 187,
/// TIMESTAMP WITH TIME ZONE
TIMESTAMP_TZ = 188,
/// INTERVAL YEAR TO MONTH
INTERVAL_YM = 189,
/// INTERVAL DAY TO SECOND
INTERVAL_DS = 190,
/// /* */
TIMESTAMP_LTZ = 232,
/// pl/sql representation of named ty... | /// For encoding, this value tells the server handle to use the setting in the environment handle.
Default = 0,
/// Use connection pooling.
CPool = 1 << 9,
}
impl Default for AttachMode {
fn default() -> Self { AttachMode::Default }
}
/// Specifies the various modes of operation
#[derive(Clone, Copy, Debug, P... | de {
| identifier_name |
traits.rs | From<Pointer<AR::PtrVal>>,
{
}
/// Trait which represents all of the analysis methods an architecture
/// must provide in order to be supported.
pub trait Architecture
where
Self: 'static
+ Copy
+ Debug
+ PartialEq
+ Eq
+ PartialOrd
+ Ord
+ Serialize
... | &self, | random_line_split | |
api.py | close(self):
# if self.store is not None:
# self.store.close()
#
# def __open(self):
# if self.store is None:
# self.store = pd.HDFStore(self.filename, format='table')
# return self.store
#
# def keys(self):
# self.__open()
# return self.store.keys()
#
# ... | # TURNOVER = 'turnover'
# VWAP = 'vwap'
# OI = 'oi'
# SETTLE = 'settle'
#
# def __init__(self, df):
# BaseDataFrame.__init__(self, df)
# self.set_index(BarDataFrame.TRADE_DATE)
#
def singleton(cls):
instance = {}
def geninstance(*args, **kwargs):
if cls not in instance:
... | # CLOSE = 'close'
# VOLUME = 'volume' | random_line_split |
api.py | 'status' # 上市状态,1:上市 3:退市 8:暂停上市
# BUYLOT = 'bylot' # INT 最小买入单位
# SELLLOT = 'selllot' # INT 最大买入单位
# PRICETICK = 'pricetick' # double 最小变动单位
# PRODUCT = 'product' # 合约品种
# UNDERLYING = 'underlying' # 对应标的
# MULTIPLIER = 'multiplier' # int 合约乘数
#
# def __init__(self, df):
# BaseDataF... | y_login()
df, msg = self.__api.bar(symbol=_symbol,
trade_date=_trade_date,
freq=_freq,
| identifier_body | |
api.py | _storer(key).attrs[meta_info] = kwargs
# else:
# try:
# dic = self.store.get_storer(key).attrs[meta_info]
# return {} if dic is None else dic
# except KeyError:
# return {}
# else:
# return {}
#class Ba... | def instrumentinfo(self, _fields="", _filter="inst_type=1&status=1&market=SH,SZ"):
self.__lazy_login()
df, msg = self.__api.query(view="jz.instrumentInfo", fields=_fields,
filter=_filter,
| conditional_block | |
api.py | # 上市状态,1:上市 3:退市 8:暂停上市
# BUYLOT = 'bylot' # INT 最小买入单位
# SELLLOT = 'selllot' # INT 最大买入单位
# PRICETICK = 'pricetick' # double 最小变动单位
# PRODUCT = 'product' # 合约品种
# UNDERLYING = 'underlying' # 对应标的
# MULTIPLIER = 'multiplier' # int 合约乘数
#
# def __init__(self, df):
# BaseDataFrame.__ini... | ields)
| identifier_name | |
ChineseCheckersBoard.py | 46])
self.squareList[ 57 ].setAdjacent([56,66,67,58,48,47])
self.squareList[ 58 ].setAdjacent([57,67,68,59,49,48])
self.squareList[ 59 ].setAdjacent([58,68,69,60,50,49])
self.squareList[ 60 ].setAdjacent([59,69,70,61,51,50])
self.squareList[ 61 ].setAdjacent([60,70,71,62,52,51])
... | setState | identifier_name | |
ChineseCheckersBoard.py | 3,62])
self.squareList[ 73 ].setAdjacent([72,83,84,74,64,63])
self.squareList[ 74 ].setAdjacent([73,84,85,None,None,64])
self.squareList[ 75 ].setAdjacent([None,86,87,76,65,None])
self.squareList[ 76 ].setAdjacent([75,87,88,77,66,65])
self.squareList[ 77 ].setAdjacent([76,88,89,7... | self.adjacent.append(x)
def getAdjacent(self): | random_line_split | |
ChineseCheckersBoard.py | 62 ].setAdjacent([61,71,72,63,53,52])
self.squareList[ 63 ].setAdjacent([62,72,73,64,54,53])
self.squareList[ 64 ].setAdjacent([63,73,74,None,55,54])
self.squareList[ 65 ].setAdjacent([None,75,76,66,56,None])
self.squareList[ 66 ].setAdjacent([65,76,77,67,57,56])
self.squareList... | self.squareList[x].setState(squares[x]) | conditional_block | |
ChineseCheckersBoard.py | ].setAdjacent([57,67,68,59,49,48])
self.squareList[ 59 ].setAdjacent([58,68,69,60,50,49])
self.squareList[ 60 ].setAdjacent([59,69,70,61,51,50])
self.squareList[ 61 ].setAdjacent([60,70,71,62,52,51])
self.squareList[ 62 ].setAdjacent([61,71,72,63,53,52])
self.squareList[ 63 ].se... | self.squareList[squareNum-1].setState(newState) | identifier_body | |
routes.go | aggerfiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
_ "github.com/Tencent/bk-bcs/bcs-services/bcs-monitor/docs" // docs xxx
"github.com/Tencent/bk-bcs/bcs-services/bcs-monitor/pkg/api/logrule"
"github.com/Tencent/bk-bcs/bcs-services/bcs-monitor/pkg/api/metrics"
"github.com/Tencent/bk-b... | route.GET("/nodes/:node/cpu_usage", rest.RestHandlerFunc(metrics.GetNodeCPUUsage))
route.GET("/nodes/:node/cpu_request_usage", rest.RestHandlerFunc(metrics.GetNodeCPURequestUsage))
route.GET("/nodes/:node/memory_usage", rest.RestHandlerFunc(metrics.GetNodeMemoryUsage))
route.GET("/nodes/:node/memory_request_usa... | route.GET("/disk_usage", rest.RestHandlerFunc(metrics.ClusterDiskUsage))
route.GET("/diskio_usage", rest.RestHandlerFunc(metrics.ClusterDiskioUsage))
route.GET("/pod_usage", rest.RestHandlerFunc(metrics.ClusterPodUsage))
route.GET("/nodes/:node/info", rest.RestHandlerFunc(metrics.GetNodeInfo))
route.GET("/nod... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.