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 |
|---|---|---|---|---|
Payment-temp.js | import React, { useState, useEffect } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Stepper from "@material-ui/core/Stepper";
import Step from "@material-ui/core/Step";
import StepLabel from "@material-ui/core/StepLabel";
import Button from "@material-ui/core/Button";
import Typography fro... | (stepIndex, buyerData) {
switch (stepIndex) {
case 0:
return (
<div>
{buyerData && (
<div style={{ background: "#ecf0f1", margin: "auto", width: 630 }}>
<font color="red" style={{ color: "red", fontWieght: "bold" }}>
<b>Delivery Address</b>
... | getStepContent | identifier_name |
Payment-temp.js | import React, { useState, useEffect } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Stepper from "@material-ui/core/Stepper";
import Step from "@material-ui/core/Step";
import StepLabel from "@material-ui/core/StepLabel";
import Button from "@material-ui/core/Button";
import Typography fro... |
// const data = await fetch("http://localhost:5000/buyer/checkout", {
// method: "POST",
// }).then((t) => t.json());
// const data = await axios.post(`http://localhost:5000/buyer/checkout`, {
// headers: { "x-access-token": token },
// });
const data = await fetch(`http://localhost:... | {
alert("razorpay sdk failed to load. are u online");
return;
} | conditional_block |
Payment-temp.js | import React, { useState, useEffect } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Stepper from "@material-ui/core/Stepper";
import Step from "@material-ui/core/Step";
import StepLabel from "@material-ui/core/StepLabel";
import Button from "@material-ui/core/Button";
import Typography fro... |
function getStepContent(stepIndex, buyerData) {
switch (stepIndex) {
case 0:
return (
<div>
{buyerData && (
<div style={{ background: "#ecf0f1", margin: "auto", width: 630 }}>
<font color="red" style={{ color: "red", fontWieght: "bold" }}>
<b>Del... | {
const navigate = useNavigate();
const buyerId = useParams().buyerId;
const [buyerData, setBuyerData] = useState();
const { token } = useAuth();
const [finalMessage, setFinalMessage] = useState(false);
const classes = useStyles();
const [activeStep, setActiveStep] = React.useState(0);
const steps = ge... | identifier_body |
ldacgsmulti.py | from sys import stdout
import multiprocessing as mp
import numpy as np
from ldagibbs import smpl_cat
class LdaCgsMulti(object):
"""
"""
def __init__(self, corpus, context_type,
K=100, top_prior = [], ctx_prior = []):
# The width of the word by topic matrix and the height of the... | """
Note
----
Disable reseeding in `update` before running this test and use
sequential mapping
"""
from vsm.util.corpustools import random_corpus
c = random_corpus(100, 5, 4, 20)
m0 = LdaCgsMulti(c, 'random', K=3)
np.random.seed(0)
m0.train(itr=5, n_proc=2)
m0.train(itr... | identifier_body | |
ldacgsmulti.py | from sys import stdout
import multiprocessing as mp
import numpy as np
from ldagibbs import smpl_cat
class LdaCgsMulti(object):
"""
"""
def __init__(self, corpus, context_type,
K=100, top_prior = [], ctx_prior = []):
# The width of the word by topic matrix and the height of the... |
# Store log probability computations
self.log_prob = []
@staticmethod
def _init_word_top(a):
global _word_top
_word_top = mp.Array('d', _m_words.value*_K.value, lock=False)
_word_top[:] = a
@staticmethod
def _init_top_norms(a):
global _top_norms
... | _train = mp.Value('b', 0, lock=False) | random_line_split |
ldacgsmulti.py | from sys import stdout
import multiprocessing as mp
import numpy as np
from ldagibbs import smpl_cat
class LdaCgsMulti(object):
"""
"""
def __init__(self, corpus, context_type,
K=100, top_prior = [], ctx_prior = []):
# The width of the word by topic matrix and the height of the... |
data = zip(ctx_ls, Z_ls, top_ctx_ls)
# For debugging
# results = map(update, data)
results = p.map(update, data)
if verbose:
stdout.write('\rIteration %d: reducing ' % self.iteration)
stdout.flush()
# Unzip res... | stdout.write('\rIteration %d: mapping ' % self.iteration)
stdout.flush() | conditional_block |
ldacgsmulti.py | from sys import stdout
import multiprocessing as mp
import numpy as np
from ldagibbs import smpl_cat
class LdaCgsMulti(object):
"""
"""
def __init__(self, corpus, context_type,
K=100, top_prior = [], ctx_prior = []):
# The width of the word by topic matrix and the height of the... | ():
from vsm.util.corpustools import random_corpus
from tempfile import NamedTemporaryFile
import os
c = random_corpus(1000, 50, 6, 100)
tmp = NamedTemporaryFile(delete=False, suffix='.npz')
try:
m0 = LdaCgsMulti(c, 'random', K=10)
m0.train(itr=20)
c0 = np.frombuffe... | test_LdaCgsMulti_IO | identifier_name |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 17:46:54 2021
@author: yaredhurisa """
import datetime
import time
import streamlit as st
import pandas as pd
import plotly.express as px
import altair as alt
from sklearn import base
from imblearn.ensemble import EasyEnsembleClassifier
from skl... | ():
"""Application of Kimetrica Conflict Forecasting Model: Myanmar Analytical Activity (MAA)"""
st.sidebar.title("Menu")
choose_model = st.sidebar.selectbox(
"Choose the page or model", [
"Home", "Model description", "Train and Test", "Forecast and Visualize results", "Comment"]
)
... | main | identifier_name |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 17:46:54 2021
@author: yaredhurisa """
import datetime
import time
import streamlit as st
import pandas as pd
import plotly.express as px
import altair as alt
from sklearn import base
from imblearn.ensemble import EasyEnsembleClassifier
from skl... |
if st.checkbox("Forecast and preview the results with the available data"):
if st.checkbox("Preveiw the data with forecasted values"):
y_forecast_binary = model_reg.predict(X_current)
current["conflict_forecast_binary"] = [
"No conflict" if i == 0 else "Conflict" f... | st.write(
f"Note: Currently, the file to be uploaded should have **exactly the same** format with **training dataset** which is **{current.shape[1]}** columns in the following format.",
current.head(2),
)
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
... | conditional_block |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 17:46:54 2021
@author: yaredhurisa """
import datetime
import time
import streamlit as st
import pandas as pd
import plotly.express as px
import altair as alt
from sklearn import base
from imblearn.ensemble import EasyEnsembleClassifier
from skl... |
df2 = df.drop(['Unnamed: 0',
'Unnamed: 0.1',
'admin1',
'admin2',
'geometry',
'location',
'year'], axis=1)
end_date = "2021-01"
mask = (df2['month_year'] < end_date)
df2 = df2.loc[mask]
df3 = df2.drop(['month_year'], axis=1)
X ... | st.title("Kimetrica Conflict Forecasting Model: Myanmar Analytical Activity (MAA)")
st.write("")
st.write("")
st.subheader("INTRODUCTION")
st.write("")
st.write(
"An early-warning system that can meaningfully forecast conflict in its various forms is necessary to respond to crises ahead of t... | identifier_body |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 17:46:54 2021
@author: yaredhurisa """
import datetime
import time
import streamlit as st
import pandas as pd
import plotly.express as px
import altair as alt
from sklearn import base
from imblearn.ensemble import EasyEnsembleClassifier
from skl... |
columns = X_train.shape[1]
def new_data_downloader(df):
st.write("")
st.subheader("Want to new data to perform forecasting?")
if st.checkbox("New data"):
csv = current.to_csv(index=False)
# some strings <-> bytes conversions necessary here
b64 = base64.b64encode(csv.encode()).d... | cc_prediction.plot(column='2019-01', cmap='OrRd',
legend=True, ax=axes[1])
st.pyplot(fig)
| random_line_split |
emacs.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/5/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"));
else if (typeof define == "function" && define.amd) // A... | (cm) {
cm.setExtending(false);
cm.setCursor(cm.getCursor());
}
function makePrompt(msg) {
var fragment = document.createDocumentFragment();
var input = document.createElement("input");
input.setAttribute("type", "text");
input.style.width = "10em";
fragment.appendChild(document.createTe... | clearMark | identifier_name |
emacs.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/5/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"));
else if (typeof define == "function" && define.amd) // A... |
function maybeRemovePrefixMap(cm, arg) {
if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return;
cm.removeKeyMap(prefixMap);
cm.state.emacsPrefixMap = false;
cm.off("keyHandled", maybeRemovePrefixMap);
cm.off("inputRead", maybeRemovePrefixMap);
}
// Utilities
cmds.se... | {
var dup = getPrefix(cm);
if (dup > 1 && event.origin == "+input") {
var one = event.text.join("\n"), txt = "";
for (var i = 1; i < dup; ++i) txt += one;
cm.replaceSelection(txt);
}
} | identifier_body |
emacs.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/5/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"));
else if (typeof define == "function" && define.amd) // A... |
function maybeClearPrefix(cm, arg) {
if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg))
clearPrefix(cm);
}
function clearPrefix(cm) {
cm.state.emacsPrefix = null;
cm.off("keyHandled", maybeClearPrefix);
cm.off("inputRead", maybeDuplicateInput);
}
function maybe... | random_line_split | |
parse.rs | use std::collections::HashSet;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Point {
pub row: usize,
pub col: usize,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct TBox(pub Point, pub Point);
pub struct Lines(pub Vec<Vec<char>>);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {... |
}
| {
let b = TBox(Point { row: 1, col: 1 }, Point { row: 3, col: 4 });
use Direction::*;
assert_eq!(
vec![
(Point { row: 0, col: 1 }, Up),
(Point { row: 0, col: 2 }, Up),
(Point { row: 0, col: 3 }, Up),
(Point { row: 0, col: 4 }, Up),
(Point { row: 4, col: 1 }, Dn),
(Point { row: 4, col: 2... | identifier_body |
parse.rs | use std::collections::HashSet;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Point {
pub row: usize,
pub col: usize,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct TBox(pub Point, pub Point);
pub struct Lines(pub Vec<Vec<char>>);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {... | (lines: &Lines, mut p: Point, d: Direction) -> Option<(Point, char)> {
while let Some((q, c)) = lines.in_dir(p, d) {
// p
// --* < can't connect
//
if !can_go(c, d.rev()) {
return lines.at(p).map(|c| (p, c));
}
p = q;
// p
// --. < can connect, can't continue
//
if !can_go(c, d) {
return S... | scan_dir | identifier_name |
parse.rs | use std::collections::HashSet;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Point {
pub row: usize,
pub col: usize,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct TBox(pub Point, pub Point);
pub struct Lines(pub Vec<Vec<char>>);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {... |
}
}
ret
}
fn scan_dir(lines: &Lines, mut p: Point, d: Direction) -> Option<(Point, char)> {
while let Some((q, c)) = lines.in_dir(p, d) {
// p
// --* < can't connect
//
if !can_go(c, d.rev()) {
return lines.at(p).map(|c| (p, c));
}
p = q;
// p
// --. < can connect, can't continue
//
if ... | {
ret.push((p, c));
} | conditional_block |
parse.rs | use std::collections::HashSet;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Point {
pub row: usize,
pub col: usize,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct TBox(pub Point, pub Point);
pub struct Lines(pub Vec<Vec<char>>);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {... | }
fn scan_path(lines: &Lines, p: Point, d: Direction) -> Vec<Point> {
if !lines.at(p).map(|c| can_go(c, d)).unwrap_or(false) {
return vec![];
}
let mut ret = vec![];
let mut it = PathIter::new(&lines, p, d);
while let Some(next) = it.next() {
if ret.contains(&next) {
return ret;
}
ret.push(next);
}
r... | }
}
} | random_line_split |
client.go | //
// Written by Maxim Khitrov (August 2012)
//
package imap
import (
"errors"
"fmt"
"io"
"net"
"runtime"
"runtime/debug"
"sort"
"strings"
"sync"
"time"
)
// Timeout arguments for Client.recv.
const (
block = time.Duration(-1) // Block until a complete response is received
poll = time.Duration(0) // Ch... | (timeout time.Duration) (rsp *Response, err error) {
if c.state == Closed {
return nil, io.EOF
} else if c.rch == nil && (timeout < 0 || c.cch == nil) {
rsp, err = c.next()
} else {
if c.rch == nil {
rch := make(chan *response, 1)
c.cch <- rch
c.rch = rch
runtime.Gosched()
}
var r *response
i... | recv | identifier_name |
client.go | //
// Written by Maxim Khitrov (August 2012)
//
package imap
import (
"errors"
"fmt"
"io"
"net"
"runtime"
"runtime/debug"
"sort"
"strings"
"sync"
"time"
)
// Timeout arguments for Client.recv.
const (
block = time.Duration(-1) // Block until a complete response is received
poll = time.Duration(0) // Ch... |
// setState changes connection state and performs the associated client updates.
// If the new state is Selected, it is assumed that c.Mailbox is already set.
func (c *Client) setState(s ConnState) {
prev := c.state
if prev == s || prev == Closed {
return
}
c.state = s
if s != Selected {
c.Logf(LogState, "St... | {
mode := poll
if sync {
if err = c.t.Flush(); err != nil {
return
}
mode = block
}
for cmd.InProgress() {
if rsp, err = c.recv(mode); err != nil {
if err == ErrTimeout {
err = nil
}
return
} else if !c.deliver(rsp) {
if rsp.Type == Continue {
if !sync {
err = ResponseError{rsp... | identifier_body |
client.go | //
// Written by Maxim Khitrov (August 2012)
//
package imap
import (
"errors"
"fmt"
"io"
"net"
"runtime"
"runtime/debug"
"sort"
"strings"
"sync"
"time"
)
// Timeout arguments for Client.recv.
const (
block = time.Duration(-1) // Block until a complete response is received
poll = time.Duration(0) // Ch... | caps = "(none)"
}
c.Logln(LogState, "Capabilities:", caps)
}
}
// getCaps returns a sorted list of capabilities that share a common prefix. The
// prefix is stripped from the returned strings.
func (c *Client) getCaps(prefix string) []string {
caps := make([]string, 0, len(c.Caps))
if n := len(prefix); n == ... | if caps == "" { | random_line_split |
client.go | //
// Written by Maxim Khitrov (August 2012)
//
package imap
import (
"errors"
"fmt"
"io"
"net"
"runtime"
"runtime/debug"
"sort"
"strings"
"sync"
"time"
)
// Timeout arguments for Client.recv.
const (
block = time.Duration(-1) // Block until a complete response is received
poll = time.Duration(0) // Ch... |
})
return
}
| {
c.Logln(LogConn, "Close error:", err)
} | conditional_block |
main.ts | import "./styles.css";
import $ from "jquery";
enum CharacterTypes{
Warrior,
Archer,
Thrower
}
let Gear = [
{
type: "Dagger",
cost: 5,
damage: 10,
canUse: "warrior"
},
{
type: "Sword",
cost: 10,
damage: 15,
canUse: "warrior"
},
{
type: "Bow",
cost: 15,
damage: 15,
canUse: "archer"
},
... | }
if($(this).hasClass("archer")||$(this).hasClass("thrower")){
highlight(2, position);
chose = true;
}
}
$("#field td").click(function(){
if(chose && !$(this).html() && $(this).hasClass("highlighted")){
moveChar(cellFrom, $(this));
chose = false;
$("#field td").each(function(){
... |
chose = true; | random_line_split |
main.ts | import "./styles.css";
import $ from "jquery";
enum CharacterTypes{
Warrior,
Archer,
Thrower
}
let Gear = [
{
type: "Dagger",
cost: 5,
damage: 10,
canUse: "warrior"
},
{
type: "Sword",
cost: 10,
damage: 15,
canUse: "warrior"
},
{
type: "Bow",
cost: 15,
damage: 15,
canUse: "archer"
},
... |
get resources(): Character[]{
return this._resources;
}
}
class EnemySquad{
wins: number = 0;
private _resources: Character[] = [];
constructor(){}
addMember(value: Character):void{
this._resources.push(value);
}
deleteMember(value: Character):void{
this._resources.splice(this._resources.indexOf(value)... | {
for(let i=0; i<this._resources.length; i++){
if(this._resources[i].position = position){
return this._resources[i];
};
}
} | identifier_body |
main.ts | import "./styles.css";
import $ from "jquery";
enum CharacterTypes{
Warrior,
Archer,
Thrower
}
let Gear = [
{
type: "Dagger",
cost: 5,
damage: 10,
canUse: "warrior"
},
{
type: "Sword",
cost: 10,
damage: 15,
canUse: "warrior"
},
{
type: "Bow",
cost: 15,
damage: 15,
canUse: "archer"
},
... | (distance: number, position:string): void{
$("#field td").each(function(){
let id = $(this).attr("id");
if(id===position ||
(id[1]===position[1] && Math.abs(+id[0]-+position[0])<=distance) ||
(id[0]===position[0] && Math.abs(+id[1]-+position[1])<=distance)) {
$(this).addClass("clicked");
... | highlight | identifier_name |
image.go | // Portions Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
//
// 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
... | Images []DetailResponse `json:"images"`
}
type imagesResponse struct {
Images []Response `json:"images"`
}
type imagesReserveResponse struct {
Images []Response `json:"images"`
} |
return reqURL, nil
}
type imagesDetailResponse struct { | random_line_split |
image.go | // Portions Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
//
// 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
... |
if queryParameters.Marker != "" {
values.Set("marker", queryParameters.Marker)
}
if queryParameters.SortKey != "" {
values.Set("sort_key", queryParameters.SortKey)
}
if queryParameters.SortDirection != "" {
values.Set("sort_dir", string(queryParameters.SortDirection))
}
if len(values) > 0 {
... | {
values.Set("limit", fmt.Sprintf("%d", queryParameters.Limit))
} | conditional_block |
image.go | // Portions Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
//
// 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
... | (queryParameters *QueryParameters) ([]Response, error) {
imagesContainer := imagesResponse{}
err := imageService.queryImages(false /*includeDetails*/, &imagesContainer, queryParameters)
if err != nil {
return nil, err
}
return imagesContainer.Images, nil
}
// QueryImagesDetail will issue a get request with the... | QueryImages | identifier_name |
image.go | // Portions Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
//
// 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
... |
type imagesDetailResponse struct {
Images []DetailResponse `json:"images"`
}
type imagesResponse struct {
Images []Response `json:"images"`
}
type imagesReserveResponse struct {
Images []Response `json:"images"`
} | {
reqURL, err := url.Parse(imageService.URL)
if err != nil {
return nil, err
}
if queryParameters != nil {
values := url.Values{}
if queryParameters.Name != "" {
values.Set("name", queryParameters.Name)
}
if queryParameters.ContainerFormat != "" {
values.Set("container_format", queryParameters.Cont... | identifier_body |
thread.rs | use {
super::process::Process,
super::*,
crate::object::*,
alloc::{boxed::Box, sync::Arc},
core::{
any::Any,
future::Future,
pin::Pin,
task::{Context, Poll, Waker},
},
spin::Mutex,
};
pub use self::thread_state::*;
mod thread_state;
/// Runnable / computati... | (
self: &Arc<Self>,
entry: usize,
stack: usize,
arg1: usize,
arg2: usize,
) -> ZxResult<()> {
let regs = GeneralRegs::new_fn(entry, stack, arg1, arg2);
self.start_with_regs(regs)
}
/// Start execution with given registers.
pub fn start_with_regs(s... | start | identifier_name |
thread.rs | use {
super::process::Process,
super::*,
crate::object::*,
alloc::{boxed::Box, sync::Arc},
core::{
any::Any,
future::Future,
pin::Pin,
task::{Context, Poll, Waker},
},
spin::Mutex,
};
pub use self::thread_state::*;
mod thread_state;
/// Runnable / computati... |
inner.state = Some(state);
}
#[derive(Default)]
struct ThreadInner {
/// HAL thread handle
///
/// Should be `None` before start or after terminated.
hal_thread: Option<kernel_hal::Thread>,
/// Thread state
///
/// Only be `Some` on suspended.
state: Option<&'static mut ThreadStat... | {
state.general = old_state.general;
} | conditional_block |
thread.rs | use {
super::process::Process,
super::*,
crate::object::*,
alloc::{boxed::Box, sync::Arc},
core::{
any::Any,
future::Future,
pin::Pin,
task::{Context, Poll, Waker},
},
spin::Mutex,
};
pub use self::thread_state::*;
mod thread_state;
/// Runnable / computati... | thread: self.clone(),
}
}
pub fn resume(&self) {
let mut inner = self.inner.lock();
assert_ne!(inner.suspend_count, 0);
inner.suspend_count -= 1;
if inner.suspend_count == 0 {
if let Some(waker) = inner.waker.take() {
waker.wake();... | }
}
}
RunnableChecker { | random_line_split |
thread.rs | use {
super::process::Process,
super::*,
crate::object::*,
alloc::{boxed::Box, sync::Arc},
core::{
any::Any,
future::Future,
pin::Pin,
task::{Context, Poll, Waker},
},
spin::Mutex,
};
pub use self::thread_state::*;
mod thread_state;
/// Runnable / computati... | root_job = Job::root();
let proc = Process::create(&root_job, "proc", 0).expect("failed to create process");
let thread = Thread::create(&proc, "thread", 0).expect("failed to create thread");
let thread1 = Thread::create(&proc, "thread1", 0).expect("failed to create thread");
// allocat... | identifier_body | |
lib.rs | //! [](./LICENSE-MIT)
//! [](./LICENSE-APACHE)
//! [](https://docs.rs/der-parser)
//! [. The only difference is the
//! verification of constraints *during parsing*.
//!
//! ## Rust version requirements
//!
//! The 7.0 series of `der-parser` requires **Rustc version 1.53 o... | //! - macros: these are generally previous (historic) versions of parsers, kept for compatibility.
//! They can sometime reduce the amount of code to write, but are hard to debug.
//! Parsers should be preferred when possible.
//!
//! ## Misc Notes | random_line_split |
lib.rs | //! Shared code for EZO sensor chips. These chips are used for sensing aquatic
//! media.
//!
//! > Currently, only __I2C Mode__ is supported.
#[macro_use]
extern crate failure;
extern crate i2cdev;
#[macro_use]
mod macros;
pub mod command;
pub mod errors;
pub mod response;
use std::ffi::{CStr, CString};
use std::th... | (code_byte: u8) -> ResponseCode {
use self::ResponseCode::*;
match code_byte {
x if x == NoDataExpected as u8 => NoDataExpected,
x if x == Pending as u8 => Pending,
x if x == DeviceError as u8 => DeviceError,
x if x == Success as u8 => Success,
_ => UnknownError,
}
}
... | response_code | identifier_name |
lib.rs | //! Shared code for EZO sensor chips. These chips are used for sensing aquatic
//! media.
//!
//! > Currently, only __I2C Mode__ is supported.
#[macro_use]
extern crate failure;
extern crate i2cdev;
#[macro_use]
mod macros;
pub mod command;
pub mod errors;
pub mod response;
use std::ffi::{CStr, CString};
use std::th... |
#[test]
fn process_pending_response_code() {
assert_eq!(response_code(254), ResponseCode::Pending);
}
#[test]
fn process_error_response_code() {
assert_eq!(response_code(2), ResponseCode::DeviceError);
}
#[test]
fn process_success_response_code() {
assert_eq!(... | {
assert_eq!(response_code(255), ResponseCode::NoDataExpected);
} | identifier_body |
lib.rs | //! Shared code for EZO sensor chips. These chips are used for sensing aquatic
//! media.
//!
//! > Currently, only __I2C Mode__ is supported.
#[macro_use]
extern crate failure;
extern crate i2cdev;
#[macro_use]
mod macros;
pub mod command;
pub mod errors;
pub mod response;
use std::ffi::{CStr, CString};
use std::th... | assert_eq!(data, flipped_data);
}
#[test]
fn converts_valid_response_to_string() {
// empty nul-terminated string
assert_eq!(string_from_response_data(&b"\0"[..]).unwrap(), "");
// non-empty nul-terminated string
assert_eq!(string_from_response_data(&b"hello\0"[..])... | #[test]
fn turns_off_high_bits() {
let data: [u8; 11] = [63, 73, 44, 112, 72, 44, 49, 46, 57, 56, 0];
let mut flipped_data: [u8; 11] = [63, 73, 172, 112, 200, 172, 49, 46, 57, 56, 0];
turn_off_high_bits(&mut flipped_data); | random_line_split |
resource.go | package resource
import (
"context"
"fmt"
"strings"
"time"
"database/sql"
"go-common/app/service/main/resource/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_headerResIds = "142,925,926,927,1576,1580,1584,1588,1592,1596,1600,1604,1608,1612,1616,1620,1622,1634,1920,2210,2260"... | (c context.Context) (asg *model.Assignment, err error) {
row := d.db.QueryRow(c, _defBannerSQL)
asg = &model.Assignment{}
if err = row.Scan(&asg.ID, &asg.Name, &asg.ContractID, &asg.ResID, &asg.Pic, &asg.LitPic,
&asg.URL, &asg.Rule, &asg.Weight, &asg.Agency, &asg.Price, &asg.Atype, &asg.Username); err != nil {
i... | DefaultBanner | identifier_name |
resource.go | package resource
import (
"context"
"fmt"
"strings"
"time"
"database/sql"
"go-common/app/service/main/resource/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_headerResIds = "142,925,926,927,1576,1580,1584,1588,1592,1596,1600,1604,1608,1612,1616,1620,1622,1634,1920,2210,2260"... | } else {
log.Error("d.DefaultBanner.Scan error(%v)", err)
}
}
return
}
// IndexIcon get index icon.
func (d *Dao) IndexIcon(c context.Context) (icons map[int][]*model.IndexIcon, err error) {
rows, err := d.db.Query(c, _indexIconSQL)
if err != nil {
log.Error("d.IndexIcon query error (%v)", err)
return
... | err = nil | random_line_split |
resource.go | package resource
import (
"context"
"fmt"
"strings"
"time"
"database/sql"
"go-common/app/service/main/resource/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_headerResIds = "142,925,926,927,1576,1580,1584,1588,1592,1596,1600,1604,1608,1612,1616,1620,1622,1634,1920,2210,2260"... |
err = rows.Err()
return
}
// PlayerIcon get play icon
func (d *Dao) PlayerIcon(c context.Context) (re *model.PlayerIcon, err error) {
row := d.db.QueryRow(c, _playIconSQL, time.Now(), time.Now())
re = &model.PlayerIcon{}
if err = row.Scan(&re.URL1, &re.Hash1, &re.URL2, &re.Hash2, &re.CTime); err != nil {
if er... | {
var link string
icon := &model.IndexIcon{}
if err = rows.Scan(&icon.ID, &icon.Type, &icon.Title, &icon.State, &link, &icon.Icon,
&icon.Weight, &icon.UserName, &icon.StTime, &icon.EndTime, &icon.DelTime, &icon.CTime, &icon.MTime); err != nil {
log.Error("IndexIcon rows.Scan err (%v)", err)
return
}
... | conditional_block |
resource.go | package resource
import (
"context"
"fmt"
"strings"
"time"
"database/sql"
"go-common/app/service/main/resource/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_headerResIds = "142,925,926,927,1576,1580,1584,1588,1592,1596,1600,1604,1608,1612,1616,1620,1622,1634,1920,2210,2260"... |
// IndexIcon get index icon.
func (d *Dao) IndexIcon(c context.Context) (icons map[int][]*model.IndexIcon, err error) {
rows, err := d.db.Query(c, _indexIconSQL)
if err != nil {
log.Error("d.IndexIcon query error (%v)", err)
return
}
defer rows.Close()
icons = make(map[int][]*model.IndexIcon)
for rows.Next(... | {
row := d.db.QueryRow(c, _defBannerSQL)
asg = &model.Assignment{}
if err = row.Scan(&asg.ID, &asg.Name, &asg.ContractID, &asg.ResID, &asg.Pic, &asg.LitPic,
&asg.URL, &asg.Rule, &asg.Weight, &asg.Agency, &asg.Price, &asg.Atype, &asg.Username); err != nil {
if err == sql.ErrNoRows {
asg = nil
err = nil
} ... | identifier_body |
btrfs_tree_h.go | package btrfs
/*
* This header contains the structure definitions and constants used
* by file system objects that can be retrieved using
* the _BTRFS_IOC_SEARCH_TREE ioctl. That means basically anything that
* is needed to describe a leaf node's key or item contents.
*/
/* holds pointers to all of the tree roo... | (flags uint64) uint64 {
if flags&uint64(_BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 {
flags |= uint64(availAllocBitSingle)
}
return flags
}
func extended_to_chunk(flags uint64) uint64 {
return flags &^ uint64(availAllocBitSingle)
}
type btrfs_block_group_item struct {
used uint64
chunk_objectid uint64
f... | chunk_to_extended | identifier_name |
btrfs_tree_h.go | package btrfs
/*
* This header contains the structure definitions and constants used
* by file system objects that can be retrieved using
* the _BTRFS_IOC_SEARCH_TREE ioctl. That means basically anything that
* is needed to describe a leaf node's key or item contents.
*/
/* holds pointers to all of the tree roo... | flags uint64
refs uint32
drop_progress struct {
objectid uint64
type_ uint8
offset uint64
}
drop_level uint8
level uint8
generation_v2 uint64
uuid UUID
parent_uuid UUID
received_uuid UUID
ctransid uint64
otransid uint64
stransid uint64
rtran... | last_snapshot uint64 | random_line_split |
btrfs_tree_h.go | package btrfs
/*
* This header contains the structure definitions and constants used
* by file system objects that can be retrieved using
* the _BTRFS_IOC_SEARCH_TREE ioctl. That means basically anything that
* is needed to describe a leaf node's key or item contents.
*/
/* holds pointers to all of the tree roo... |
/*
* is subvolume quota turned on?
*/
/*
* RESCAN is set during the initialization phase
*/
/*
* Some qgroup entries are known to be out of date,
* either because the configuration has changed in a way that
* makes a rescan necessary, or because the fs has been mounted
* with a non-qgroup-aware version.
* ... | {
return qgroupid >> uint32(qgroupLevelShift)
} | identifier_body |
btrfs_tree_h.go | package btrfs
/*
* This header contains the structure definitions and constants used
* by file system objects that can be retrieved using
* the _BTRFS_IOC_SEARCH_TREE ioctl. That means basically anything that
* is needed to describe a leaf node's key or item contents.
*/
/* holds pointers to all of the tree roo... |
return flags
}
func extended_to_chunk(flags uint64) uint64 {
return flags &^ uint64(availAllocBitSingle)
}
type btrfs_block_group_item struct {
used uint64
chunk_objectid uint64
flags uint64
}
type btrfs_free_space_info struct {
extent_count uint32
flags uint32
}
func btrfs_qgroup... | {
flags |= uint64(availAllocBitSingle)
} | conditional_block |
wordlattice.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import sys
from bisect import bisect_left, bisect_right
from copy import deepcopy
class WordLattice:
class Node:
def __init__(self, id_arg, time):
self.id = id_arg
self.time = time
self.reference_count = 0
def refer(self):
self.reference_cou... |
tokens = new_tokens
new_tokens = []
for path in tokens:
new_tokens.extend(self.expand_path_to_null_links(path))
tokens = new_tokens
print(len(tokens), "tokens @", word)
if tokens == []:
return []
result = []
for path in tokens:
if path.final_node() == self.end_node:
result.append(p... | new_tokens.extend(self.find_extensions(path, word)) | conditional_block |
wordlattice.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import sys
from bisect import bisect_left, bisect_right
from copy import deepcopy
class WordLattice:
class Node:
def __init__(self, id_arg, time):
self.id = id_arg
self.time = time
self.reference_count = 0
def refer(self):
self.reference_cou... |
# Finds a path from start node to end node through given words.
def find_paths(self, words):
tokens = self.expand_path_to_null_links(self.Path())
for word in words:
new_tokens = []
for path in tokens:
new_tokens.extend(self.find_extensions(path, word))
tokens = new_tokens
new_tokens = []
for... | output_file.write("# Header\n")
output_file.write("VERSION=1.1\n")
output_file.write("base=10\n")
output_file.write("dir=f\n")
output_file.write("lmscale=" + str(self.lm_scale) + "\n")
output_file.write("start=" + str(self.start_node) + "\n")
output_file.write("end=" + str(self.end_node) + "\n")
output_fi... | identifier_body |
wordlattice.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import sys
from bisect import bisect_left, bisect_right
from copy import deepcopy
class WordLattice:
class Node:
def __init__(self, id_arg, time):
self.id = id_arg
self.time = time
self.reference_count = 0
def refer(self):
self.reference_cou... | (self, memo={}):
result = WordLattice()
memo[id(self)] = result
result.__nodes = deepcopy(self.__nodes, memo)
result.__links = deepcopy(self.__links, memo)
result.__start_nodes_of_links = deepcopy(self.__start_nodes_of_links, memo)
result.start_node = self.start_node
result.end_node = self.end_node
resu... | __deepcopy__ | identifier_name |
wordlattice.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import sys
from bisect import bisect_left, bisect_right
from copy import deepcopy
class WordLattice:
class Node:
def __init__(self, id_arg, time):
self.id = id_arg
self.time = time
self.reference_count = 0
def refer(self):
self.reference_cou... | self.links.extend(other.links)
self.nodes.extend(other.nodes)
def __init__(self):
# A regular expression for fields such as E=997788 or W="that is" in an
# SLF file.
self.assignment_re = re.compile(r'(\S+)=(?:"((?:[^\\"]+|\\.)*)"|(\S+))')
def __deepcopy__(self, memo={}):
result = WordLattice()
me... | def __init__(self):
self.links = []
self.nodes = []
def extend(self, other): | random_line_split |
main01.go | package test01
import (
"database/sql"
"encoding/base64"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/julienschmidt/httprouter"
"html/template"
"io/ioutil"
"math/rand"
"net/http"
"reflect"
"runtime"
"time"
)
type HelloHandler struct {
}
func (h *HelloHandler) ServeHTTP(w http.ResponseWriter, r *h... | (w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles(mPath + "test02/src/test/tmpl9.html")
t.Execute(w, r.FormValue("comment"))
}
func form(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles(mPath + "test02/src/test/form.html")
t.Execute(w, nil)
}
func process10(w http.Respons... | process9 | identifier_name |
main01.go | package test01
import ( | "github.com/julienschmidt/httprouter"
"html/template"
"io/ioutil"
"math/rand"
"net/http"
"reflect"
"runtime"
"time"
)
type HelloHandler struct {
}
func (h *HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello!")
}
type WorldHandler struct {
}
func (h *WorldHandler) ServeHT... | "database/sql"
"encoding/base64"
"fmt"
_ "github.com/go-sql-driver/mysql" | random_line_split |
main01.go | package test01
import (
"database/sql"
"encoding/base64"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/julienschmidt/httprouter"
"html/template"
"io/ioutil"
"math/rand"
"net/http"
"reflect"
"runtime"
"time"
)
type HelloHandler struct {
}
func (h *HelloHandler) ServeHTTP(w http.ResponseWriter, r *h... |
return
}
func (post *Post) Create() (err error) {
statement := "insert into posts (content, author) values (? , ?);"
stmt, err := Db.Prepare(statement)
if err != nil {
fmt.Println("err = " + err.Error())
return
}
defer stmt.Close()
res, err := stmt.Exec(post.Content, post.Author)
id, err := res.LastInsert... | {
fmt.Println("err = " + err.Error())
} | conditional_block |
main01.go | package test01
import (
"database/sql"
"encoding/base64"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/julienschmidt/httprouter"
"html/template"
"io/ioutil"
"math/rand"
"net/http"
"reflect"
"runtime"
"time"
)
type HelloHandler struct {
}
func (h *HelloHandler) ServeHTTP(w http.ResponseWriter, r *h... |
func writeExample(w http.ResponseWriter, r *http.Request) {
str := "<html> <head><title>Go web Programming</title></head><body><h1>" +
"hello world</h1></body></html>"
w.Write([]byte(str))
}
func writeHeaderExample(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(501)
fmt.Fprintln(w, "No such service, t... | {
//r.ParseForm()
//fmt.Fprintln(w, r.Form)
r.ParseMultipartForm(1024)
//fmt.Fprintln(w, "(1)", r.FormValue("hello"))
//fmt.Fprintln(w, "(2)", r.PostFormValue("hello"))
//fmt.Fprintln(w, "(3)", r.PostForm)
//fmt.Fprintln(w, "(4)", r.MultipartForm)
//fileHeader := r.MultipartForm.File["uploaded"][0]
//file, er... | identifier_body |
mod.rs | // Copyright 2018 ETH Zurich. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
//... | return Ok(());
}
}
}
}
/// Sends `msg` to all connected subscribers.
fn broadcast(&self, msg: MessageBuf) -> io::Result<()> {
if self.subscribers.len() == 0 {
// nothing to do here
return Ok(());
}
let ... | // all still connected subscribers | random_line_split |
mod.rs | // Copyright 2018 ETH Zurich. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
//... | <'a>(&'a self) -> (::std::sync::MutexGuard<'a, usize>, &'a Condvar) {
let AtomicCounter(ref inner) = *self;
(
inner.0.lock().expect("publisher thread poisioned counter"),
&inner.1,
)
}
fn increment(&self) {
let (mut count, nonzero) = self.lock();
... | lock | identifier_name |
tof_coincidences_jitters_correct_Paola.py | import sys
import argparse
import numpy as np
import pandas as pd
import tables as tb
import pdb
from invisible_cities.core import system_of_units as units
import antea.database.load_db as db
import antea.reco.reco_functions as rf
import antea.reco.mctrue_functions as mcf
import antea.elec.tof_functi... |
### read sensor positions from database
DataSiPM = db.DataSiPMsim_only('petalo', 0)
DataSiPM_idx = DataSiPM.set_index('SensorID')
n_sipms = len(DataSiPM)
first_sipm = DataSiPM_idx.index.min()
### parameters for single photoelectron convolution in SiPM response
tau_sipm = [100, 15000]
time_wind... | parser = argparse.ArgumentParser()
parser.add_argument('first_file' , type = int, help = "first file (inclusive)" )
parser.add_argument('n_files' , type = int, help = "number of files to analize" )
parser.add_argument('thr_r' , type = int, help = "threshold in r coordinate" )
parser.add_arg... | identifier_body |
tof_coincidences_jitters_correct_Paola.py | import sys
import argparse
import numpy as np
import pandas as pd
import tables as tb
import pdb
from invisible_cities.core import system_of_units as units
import antea.database.load_db as db
import antea.reco.reco_functions as rf
import antea.reco.mctrue_functions as mcf
import antea.elec.tof_functi... | evt_tof = evt_tof[evt_tof.sensor_id.isin(-ids_over_thr)]
if len(evt_tof) == 0:
boh2 += 1
continue
pos1, pos2, q1, q2, true_pos1, true_pos2, true_t1, true_t2, sns1, sns2 = rf.reconstruct_coincidences(evt_sns, charge_range, DataSiPM_idx, evt_parts, evt_hits)
if l... | random_line_split | |
tof_coincidences_jitters_correct_Paola.py | import sys
import argparse
import numpy as np
import pandas as pd
import tables as tb
import pdb
from invisible_cities.core import system_of_units as units
import antea.database.load_db as db
import antea.reco.reco_functions as rf
import antea.reco.mctrue_functions as mcf
import antea.elec.tof_functi... | (args):
parser = argparse.ArgumentParser()
parser.add_argument('first_file' , type = int, help = "first file (inclusive)" )
parser.add_argument('n_files' , type = int, help = "number of files to analize" )
parser.add_argument('thr_r' , type = int, help = "threshold in r coordinate" )
pa... | parse_args | identifier_name |
tof_coincidences_jitters_correct_Paola.py | import sys
import argparse
import numpy as np
import pandas as pd
import tables as tb
import pdb
from invisible_cities.core import system_of_units as units
import antea.database.load_db as db
import antea.reco.reco_functions as rf
import antea.reco.mctrue_functions as mcf
import antea.elec.tof_functi... |
pos1_phi = rf.from_cartesian_to_cyl(np.array(pos1r))[:,1]
diff_sign = min(pos1_phi ) < 0 < max(pos1_phi)
if diff_sign & (np.abs(np.min(pos1_phi))>np.pi/2.):
pos1_phi[pos1_phi<0] = np.pi + np.pi + pos1_phi[pos1_phi<0]
mean_phi = np.average(pos1_phi, weights=q1r)
var_... | c1 += 1
continue | conditional_block |
tooltip.directive.ts | import {
Directive,
ElementRef,
Inject,
Input,
NgZone,
OnDestroy,
Renderer2,
ViewContainerRef
} from '@angular/core';
import { first } from 'rxjs/operators/first';
import { merge } from 'rxjs/observable/merge';
import {
CoercionHelper,
ComponentPortal,
ConnectionPositionPair,
FocusMonitorService,
Horizonta... | (): void {
if (this._overlayRef) {
this._overlayRef.dispose();
this._overlayRef = null;
}
this._tooltipInstance = null;
}
/**
* Returns the origin position and a fallback position based on the user's position preference.
* The fallback position is the inverse of the origin (e.g. 'below' -> 'above').... | _disposeTooltip | identifier_name |
tooltip.directive.ts | import {
Directive,
ElementRef,
Inject,
Input,
NgZone,
OnDestroy,
Renderer2,
ViewContainerRef
} from '@angular/core';
import { first } from 'rxjs/operators/first';
import { merge } from 'rxjs/observable/merge';
import {
CoercionHelper,
ComponentPortal,
ConnectionPositionPair,
FocusMonitorService,
Horizonta... |
return { x, y };
}
} | {
if (x === 'end') {
x = 'start';
} else if (x === 'start') {
x = 'end';
}
} | conditional_block |
tooltip.directive.ts | import {
Directive,
ElementRef,
Inject,
Input,
NgZone,
OnDestroy,
Renderer2,
ViewContainerRef
} from '@angular/core';
import { first } from 'rxjs/operators/first';
import { merge } from 'rxjs/observable/merge';
import {
CoercionHelper,
ComponentPortal,
ConnectionPositionPair,
FocusMonitorService,
Horizonta... |
set tooltipClass(value: string | string[] | Set<string> | { [key: string]: any }) {
this._tooltipClass = value;
if (this._tooltipInstance) {
this._setTooltipClass(this._tooltipClass);
}
}
private _enterListener: Function;
private _leaveListener: Function;
constructor (
renderer: Renderer2,
private ... | { return this._tooltipClass; } | identifier_body |
tooltip.directive.ts | import {
Directive,
ElementRef,
Inject,
Input,
NgZone,
OnDestroy,
Renderer2,
ViewContainerRef
} from '@angular/core';
import { first } from 'rxjs/operators/first';
import { merge } from 'rxjs/observable/merge';
import {
CoercionHelper,
ComponentPortal,
ConnectionPositionPair,
FocusMonitorService,
Horizonta... | if (this.position == 'above') {
position = { overlayX: 'center', overlayY: 'bottom' };
} else if (this.position == 'below') {
position = { overlayX: 'center', overlayY: 'top' };
} else if (this.position == 'left') {
position = { overlayX: 'end', overlayY: 'center' };
} else if (this.position == 'right'... | let position: OverlayConnectionPosition;
| random_line_split |
lib.rs | //! Kube is an umbrella-crate for interacting with [Kubernetes](http://kubernetes.io) in Rust.
//!
//! # Overview
//!
//! Kube contains a Kubernetes client, a controller runtime, a custom resource derive, and various tooling
//! required for building applications or controllers that interact with Kubernetes.
//!
//! Th... | else {
Api::all_with(client.clone(), &ar)
};
api.list(&Default::default()).await?;
}
}
// cleanup
crds.delete("testcrs.kube.rs", &DeleteParams::default()).await?;
Ok(())
}
#[tokio::test]
#[ignore = "needs clus... | {
Api::default_namespaced_with(client.clone(), &ar)
} | conditional_block |
lib.rs | //! Kube is an umbrella-crate for interacting with [Kubernetes](http://kubernetes.io) in Rust.
//!
//! # Overview
//!
//! Kube contains a Kubernetes client, a controller runtime, a custom resource derive, and various tooling
//! required for building applications or controllers that interact with Kubernetes.
//!
//! Th... | #[cfg(test)]
#[cfg(all(feature = "derive", feature = "client"))]
mod test {
use crate::{
api::{DeleteParams, Patch, PatchParams},
Api, Client, CustomResourceExt, Resource, ResourceExt,
};
use kube_derive::CustomResource;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
... | pub use kube_core as core;
// Tests that require a cluster and the complete feature set
// Can be run with `cargo test -p kube --lib --features=runtime,derive -- --ignored` | random_line_split |
lib.rs | //! Kube is an umbrella-crate for interacting with [Kubernetes](http://kubernetes.io) in Rust.
//!
//! # Overview
//!
//! Kube contains a Kubernetes client, a controller runtime, a custom resource derive, and various tooling
//! required for building applications or controllers that interact with Kubernetes.
//!
//! Th... | {
#[allow(dead_code)]
image: String,
}
type PodSimple = Object<PodSpecSimple, NotUsed>;
// use known type information from pod (can also use discovery for this)
let ar = ApiResource::erase::<Pod>(&());
let client = Client::try_default().await?;
... | ContainerSimple | identifier_name |
lib.rs | //! Kube is an umbrella-crate for interacting with [Kubernetes](http://kubernetes.io) in Rust.
//!
//! # Overview
//!
//! Kube contains a Kubernetes client, a controller runtime, a custom resource derive, and various tooling
//! required for building applications or controllers that interact with Kubernetes.
//!
//! Th... |
let is_fully_ready = await_condition(
pods.clone(),
"busybox-kube4",
conditions::is_pod_running().and(is_each_container_ready()),
);
let _ = timeout(Duration::from_secs(10), is_fully_ready).await?;
// Delete it - and wait for deletion to complete
... | {
|obj: Option<&Pod>| {
if let Some(o) = obj {
if let Some(s) = &o.status {
if let Some(conds) = &s.conditions {
if let Some(pcond) = conds.iter().find(|c| c.type_ == "ContainersReady") {
... | identifier_body |
testone.py | import random
import string
import steembase
import struct
import steem
from time import sleep
from time import time
from steem.transactionbuilder import TransactionBuilder
from steembase import operations
from steembase.transactions import SignedTransaction
from resultthread import MyThread
from charm.toolbox.pairingg... | entx)
return opentxlist
def tx_broad(tx):
tx.broadcast()
def mul_tx_broad(txlist):
threads = []
for tx in txlist:
t = MyThread(tx_broad, args=(tx,))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
# public parma
nodeTX = 5
k = 2
n = ... | append(op | conditional_block |
testone.py | import random
import string
import steembase
import struct
import steem
from time import sleep
from time import time
from steem.transactionbuilder import TransactionBuilder
from steembase import operations
from steembase.transactions import SignedTransaction
from resultthread import MyThread
from charm.toolbox.pairingg... | def annoy_commit(account, usk, pk, GID, UID, title="paper_title", body="paper_body", groupID="computer"):
annoy_author = 'nya'
# group signature ------title 必须 这里面是对title进行hash 然后使用usk对hash进行签名
sig = group_signature.sign(title, usk, pk, GID, UID, groupID)
permlink = ''.join(random.choices(string.di... | random_line_split | |
testone.py | import random
import string
import steembase
import struct
import steem
from time import sleep
from time import time
from steem.transactionbuilder import TransactionBuilder
from steembase import operations
from steembase.transactions import SignedTransaction
from resultthread import MyThread
from charm.toolbox.pairingg... | (self, usk, vk, pk, GID, UID):
g = pk['g']
g2 = pk['g2']
u0 = pk['u0']
u1 = pk['u1']
u2 = pk['u2']
u3 = pk['u3']
u4 = pk['u4']
b0 = usk['b0']
b5 = usk['b5']
b3 = usk['b3']
b4 = usk['b4']
return pair(g, b0) == (pair(vk, g2)... | verifyUsk | identifier_name |
testone.py | import random
import string
import steembase
import struct
import steem
from time import sleep
from time import time
from steem.transactionbuilder import TransactionBuilder
from steembase import operations
from steembase.transactions import SignedTransaction
from resultthread import MyThread
from charm.toolbox.pairingg... | []
for i in range(n):
# t = MyThread(annoy_commit_tx, args=(accountlist[i], usk, pk, GID, UID, clientlist[i].steemd, clientlist[i].wallet))
t = MyThread(one_mul_annoy_tx,
args=(accountlist[i], usk, pk, UID, clientlist[i].steemd, clientlist[i].wallet))
threads.append(t)
... | args=(account, ssiglistone[i], userID, permlinklistone[i], steemd, wallet))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
def mul_annoy_tx(usk, pk, UID):
ssiglist = []
permlinklist = []
threads = | identifier_body |
app.go | package main
import (
crand "crypto/rand"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"regexp"
"strconv"
"strings"
"time"
"github.com/bradfitz/gomemcache/memcache"
gsm "github.com/bradleypeabody/gorilla-sessions-memcache"
"github.com/go-chi/chi/v5"
_ "github.com/go-sq... | p.StatusOK)
}
func getLogin(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
if isLogin(me) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
template.Must(template.ParseFiles(
getTemplPath("layout.html"),
getTemplPath("login.html")),
).Execute(w, struct {
Me User
Flash strin... | teHeader(htt | identifier_name |
app.go | package main
import (
crand "crypto/rand"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"regexp"
"strconv"
"strings"
"time"
"github.com/bradfitz/gomemcache/memcache"
gsm "github.com/bradleypeabody/gorilla-sessions-memcache"
"github.com/go-chi/chi/v5"
_ "github.com/go-sq... | getTemplPath("user.html"),
getTemplPath("posts.html"),
getTemplPath("post.html"),
)).Execute(w, struct {
Posts []Post
User User
PostCount int
CommentCount int
CommentedCount int
Me User
}{posts, user, postCount, commentCount, commentedCount, me})
}
func getPost... | random_line_split | |
app.go | package main
import (
crand "crypto/rand"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"regexp"
"strconv"
"strings"
"time"
"github.com/bradfitz/gomemcache/memcache"
gsm "github.com/bradleypeabody/gorilla-sessions-memcache"
"github.com/go-chi/chi/v5"
_ "github.com/go-sq... | からファイルのタイプを決定する
contentType := header.Header["Content-Type"][0]
if strings.Contains(contentType, "jpeg") {
mime = "image/jpeg"
} else if strings.Contains(contentType, "png") {
mime = "image/png"
} else if strings.Contains(contentType, "gif") {
mime = "image/gif"
} else {
session := getSession(r)
... | return
}
mime := ""
if file != nil {
// 投稿のContent-Type | conditional_block |
app.go | package main
import (
crand "crypto/rand"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"regexp"
"strconv"
"strings"
"time"
"github.com/bradfitz/gomemcache/memcache"
gsm "github.com/bradleypeabody/gorilla-sessions-memcache"
"github.com/go-chi/chi/v5"
_ "github.com/go-sq... | _, err = db.Exec(query, postID, me.ID, r.FormValue("comment"))
if err != nil {
log.Print(err)
return
}
http.Redirect(w, r, fmt.Sprintf("/posts/%d", postID), http.StatusFound)
}
func getAdminBanned(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
if !isLogin(me) {
http.Redirect(w, r, "/", h... | e)
_, err := w.Write(post.Imgdata)
if err != nil {
log.Print(err)
return
}
return
}
w.WriteHeader(http.StatusNotFound)
}
func postComment(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
if !isLogin(me) {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
if r.FormValue... | identifier_body |
shuffle.py | import random
import os
playList = {}
# playList ={ 1: "titulo cancion", 2: "titulo cancion" ... }
"""libreria = {"California_Uber_Alles":
{"track-number": 3, "artist": "Dead Kennedys", "album": "Dead Kennedys", "location":"/home/ulises/Micarpeta/proyectos/Ejercicios_Pyhton/biblioteca/California_Uber_A... |
"""def creadorIndicesRandom(libreria):
assert isinstance(libreria,dict),"no es un diccionario!"
indices=[]
indiceRandom=random.randrange(1,len(libreria)+1)
indices.append(indiceRandom)
while len(indices)!=len(libreria):
while indiceRandom in indices:
indiceRandom=random.randran... | random_line_split | |
shuffle.py | import random
import os
playList = {}
# playList ={ 1: "titulo cancion", 2: "titulo cancion" ... }
"""libreria = {"California_Uber_Alles":
{"track-number": 3, "artist": "Dead Kennedys", "album": "Dead Kennedys", "location":"/home/ulises/Micarpeta/proyectos/Ejercicios_Pyhton/biblioteca/California_Uber_A... | print (libreria)
return libreria
#break
else:
print("puedes volver a escribirlo")
thepath=path
listfilename=fileList
for fileName in listfilena... | me]={"location":thePath+'/'+fileName}
| conditional_block |
shuffle.py | import random
import os
playList = {}
# playList ={ 1: "titulo cancion", 2: "titulo cancion" ... }
"""libreria = {"California_Uber_Alles":
{"track-number": 3, "artist": "Dead Kennedys", "album": "Dead Kennedys", "location":"/home/ulises/Micarpeta/proyectos/Ejercicios_Pyhton/biblioteca/California_Uber_A... | reria=dict()
musicaPath="/home/ulises/Música/"
musicaArbol=os.walk(musicaPath)
for path,sub,fileList in musicaArbol:
for grupo in sub:
print(grupo)
break
while True:
print("¿Que quieres escuchar?")
NombreGrupo=input()
if os.path.exists(musicaPath+No... | eriaGrupo():
lib | identifier_name |
shuffle.py | import random
import os
playList = {}
# playList ={ 1: "titulo cancion", 2: "titulo cancion" ... }
"""libreria = {"California_Uber_Alles":
{"track-number": 3, "artist": "Dead Kennedys", "album": "Dead Kennedys", "location":"/home/ulises/Micarpeta/proyectos/Ejercicios_Pyhton/biblioteca/California_Uber_A... | erLibreriaGrupo():
libreria=dict()
musicaPath="/home/ulises/Música/"
musicaArbol=os.walk(musicaPath)
for path,sub,fileList in musicaArbol:
for grupo in sub:
print(grupo)
break
while True:
print("¿Que quieres escuchar?")
NombreGrupo=input()
if os... | bprocess
import shlex
import os
linuxPathVLC = "/usr/bin/vlc"
lineaComandoVLC = [linuxPathVLC]
separador = " "
for numeroCancion in sorted(playList.keys()):
tituloCancion = playList[numeroCancion]
try:
rutaAccesoFichero = getLocalización(libreria,titulo... | identifier_body |
GeneticAlgorithm.py | # create new folders by if not os.path.exists(self.experiment_name):
# record_of_all_fitnesses_each_generation stores all fitnesses of all individuals in
# import packages
import os, random, sys
import numpy as np
import sys
import pickle
from Framework.Algorithm import Algorithm
class GeneticAlgorithm(Algorithm):
... |
return parents
# create the children from the selected parents
def breed(self, parents):
children = []
for breeding_group in range(int(len(parents)/self.parents_per_offspring)):
picked_parents = parents[breeding_group*self.parents_per_offspring:breeding_group*self.parents_p... | print('Error: no appropriate parent selection method selected') | conditional_block |
GeneticAlgorithm.py | # create new folders by if not os.path.exists(self.experiment_name):
# record_of_all_fitnesses_each_generation stores all fitnesses of all individuals in
# import packages
import os, random, sys
import numpy as np
import sys
import pickle
from Framework.Algorithm import Algorithm
class GeneticAlgorithm(Algorithm):
... |
# perform a tournament to choose the parents that reproduce
def tournament(self, population_fitness, population):
# match up individuals for tournament
reproductive_individuals = []
random.shuffle(self.integer_list) # randomize the integer_list to determine the tournament opponents
... | self.init_run()
while self.stop_condition():
self.step()
self.record_of_all_fitnesses_each_generation.append(np.ndarray.tolist(self.survived_fitnesses))
#save a record of all fitnesses of all individuals in all generations to a pickle file
pickle_out = open('task_1_GA_' ... | identifier_body |
GeneticAlgorithm.py | # create new folders by if not os.path.exists(self.experiment_name):
# record_of_all_fitnesses_each_generation stores all fitnesses of all individuals in
# import packages
import os, random, sys
import numpy as np
import sys
import pickle
from Framework.Algorithm import Algorithm
class GeneticAlgorithm(Algorithm):
... | self.fitness_type = 0
self.selection_fitness_score = self.fitness_order[self.fitness_type]
# generate an initial population
self.survived_population = np.random.uniform(self.edge_domain[0], self.edge_domain[1], (self.population_size, edges))
# determine and make an array of the f... | edges = self.env.get_num_sensors() * self.hidden_neurons + 5 * self.hidden_neurons # not sure why this should be the right amount of edges
# set the first fitness type to select on | random_line_split |
GeneticAlgorithm.py | # create new folders by if not os.path.exists(self.experiment_name):
# record_of_all_fitnesses_each_generation stores all fitnesses of all individuals in
# import packages
import os, random, sys
import numpy as np
import sys
import pickle
from Framework.Algorithm import Algorithm
class GeneticAlgorithm(Algorithm):
... | (self, children):
# add the children at the end of the population array
oversized_population = np.concatenate((self.survived_population, children))
# add the children's fitnesses at the end of the population_fitness array
new_population_fitness = np.concatenate((self.survived_fitnesses,... | survivor_selection | identifier_name |
test_error_reporting.py | #! /usr/bin/env python
# .. coding: utf-8
# $Id: test_error_reporting.py 7723 2013-09-28 09:17:07Z milde $
# Author: Günter Milde <milde@users.sourceforge.net>
# Copyright: This module has been placed in the public domain.
"""
Test `EnvironmentError` reporting.
In some locales, the `errstr` argument of IOError and OS... |
def test_include(self):
source = ('.. include:: bogus.txt')
self.assertRaises(utils.SystemMessage,
self.parser.parse, source, self.document)
def test_raw_file(self):
source = ('.. raw:: html\n'
' :file: bogus.html\n')
self.assertRai... | ocale.setlocale(locale.LC_ALL, oldlocale)
| conditional_block |
test_error_reporting.py | #! /usr/bin/env python
# .. coding: utf-8
# $Id: test_error_reporting.py 7723 2013-09-28 09:17:07Z milde $
# Author: Günter Milde <milde@users.sourceforge.net>
# Copyright: This module has been placed in the public domain.
"""
Test `EnvironmentError` reporting.
In some locales, the `errstr` argument of IOError and OS... | from io import StringIO, BytesIO
except ImportError: # new in Python 2.6
from StringIO import StringIO
BytesIO = StringIO
import DocutilsTestSupport # must be imported before docutils
from docutils import core, parsers, frontend, utils
from docutils.utils.error_reporting import SafeString, Err... |
import unittest
import sys, os
import codecs
try: # from standard library module `io` | random_line_split |
test_error_reporting.py | #! /usr/bin/env python
# .. coding: utf-8
# $Id: test_error_reporting.py 7723 2013-09-28 09:17:07Z milde $
# Author: Günter Milde <milde@users.sourceforge.net>
# Copyright: This module has been placed in the public domain.
"""
Test `EnvironmentError` reporting.
In some locales, the `errstr` argument of IOError and OS... |
class ErrorOutputTests(unittest.TestCase):
def test_defaults(self):
e = ErrorOutput()
self.assertEqual(e.stream, sys.stderr)
def test_bbuf(self):
buf = BBuf() # buffer storing byte string
e = ErrorOutput(buf, encoding='ascii')
# write byte-string as-is
e.write(b... | ef write(self, data):
# emulate Python 3 handling of stdout, stderr
if isinstance(data, bytes):
raise TypeError('must be unicode, not bytes')
super(UBuf, self).write(data)
| identifier_body |
test_error_reporting.py | #! /usr/bin/env python
# .. coding: utf-8
# $Id: test_error_reporting.py 7723 2013-09-28 09:17:07Z milde $
# Author: Günter Milde <milde@users.sourceforge.net>
# Copyright: This module has been placed in the public domain.
"""
Test `EnvironmentError` reporting.
In some locales, the `errstr` argument of IOError and OS... | self, data):
if isinstance(data, unicode):
data.encode('ascii', 'strict')
super(BBuf, self).write(data)
# Stub: Buffer expecting unicode string:
class UBuf(StringIO, object): # super class object required by Python <= 2.5
def write(self, data):
# emulate Python 3 handling of std... | rite( | identifier_name |
clustering.go | // © 2022 Nokia.
//
// This code is a Contribution to the gNMIc project (“Work”) made under the Google Software Grant and Corporate Contributor License Agreement (“CLA”) and governed by the Apache License 2.0.
// No other rights or licenses in or to any of Nokia’s intellectual property are granted for any other purpose... | .New("missing locker type field")
}
func (a *App) leaderKey() string {
return fmt.Sprintf("gnmic/%s/leader", a.Config.Clustering.ClusterName)
}
func (a *App) inCluster() bool {
if a.Config == nil {
return false
}
return !(a.Config.Clustering == nil)
}
func (a *App) apiServiceRegistration() {
addr, port, _ := ... | intf("starting locker type %q", lockerType)
if initializer, ok := lockers.Lockers[lockerType.(string)]; ok {
lock := initializer()
err := lock.Init(a.ctx, a.Config.Clustering.Locker, lockers.WithLogger(a.Logger))
if err != nil {
return err
}
a.locker = lock
return nil
}
return fmt.Errorf("un... | conditional_block |
clustering.go | // © 2022 Nokia.
//
// This code is a Contribution to the gNMIc project (“Work”) made under the Google Software Grant and Corporate Contributor License Agreement (“CLA”) and governed by the Apache License 2.0.
// No other rights or licenses in or to any of Nokia’s intellectual property are granted for any other purpose... | for _, n := range matchingInstances {
a.Logger.Printf("selected service name: %s", n)
return a.apiServices[fmt.Sprintf("%s-api", n)], nil
}
}
for _, d := range denied {
delete(load, strings.TrimSuffix(d, "-api"))
}
a.Logger.Printf("current instances load after filtering: %+v", load)
// all se... | if len(load) == 0 { | random_line_split |
clustering.go | // © 2022 Nokia.
//
// This code is a Contribution to the gNMIc project (“Work”) made under the Google Software Grant and Corporate Contributor License Agreement (“CLA”) and governed by the Apache License 2.0.
// No other rights or licenses in or to any of Nokia’s intellectual property are granted for any other purpose... | ntext, name string) error {
errs := make([]error, 0, len(a.apiServices))
for _, s := range a.apiServices {
scheme := "http"
client := &http.Client{
Timeout: defaultHTTPClientTimeout,
}
for _, t := range s.Tags {
if strings.HasPrefix(t, "protocol=") {
scheme = strings.Split(t, "=")[1]
break
}
... | x context.Co | identifier_name |
clustering.go | // © 2022 Nokia.
//
// This code is a Contribution to the gNMIc project (“Work”) made under the Google Software Grant and Corporate Contributor License Agreement (“CLA”) and governed by the Apache License 2.0.
// No other rights or licenses in or to any of Nokia’s intellectual property are granted for any other purpose... | updateServices(srvs []*lockers.Service) {
a.configLock.Lock()
defer a.configLock.Unlock()
numNewSrv := len(srvs)
numCurrentSrv := len(a.apiServices)
a.Logger.Printf("received service update with %d service(s)", numNewSrv)
// no new services and no current services, continue
if numNewSrv == 0 && numCurrentSrv ... | := fmt.Sprintf("%s-%s", a.Config.Clustering.ClusterName, apiServiceName)
START:
select {
case <-ctx.Done():
return
default:
membersChan := make(chan []*lockers.Service)
go func() {
for {
select {
case <-ctx.Done():
return
case srvs, ok := <-membersChan:
if !ok {
return
}
... | identifier_body |
views.py | from unidecode import unidecode
import pdb
import os, manage
import re
from datetime import *
import codecs
import csv
import smtplib
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib import... | (request, match):
u1 = User.objects.get(username=request.user.username)
teampk = u1.get_profile().team_member.pk
try:
m = Match.objects.get(id=match)
except Match.DoesNotExist:
raise Http404
if request.method == 'POST' and m.isTeam(teampk):
form = ArrangeSubstitutesForm(... | editMatch | identifier_name |
views.py | from unidecode import unidecode
import pdb
import os, manage
import re
from datetime import *
import codecs
import csv
import smtplib
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib import... |
return render(request, 'savematch.html', {'form': form, 'matches': matches})
def viewMyMatches(request):
u1 = User.objects.get(username=request.user.username)
teampk = u1.get_profile().team_member.pk
matches = Match.objects.get_my_matches(teampk)
presentmatches = {}
for m in matches:
i... | form = importMatchesForm() | conditional_block |
views.py | from unidecode import unidecode
import pdb
import os, manage
import re
from datetime import *
import codecs
import csv
import smtplib
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib import... |
def addMatchPresence(request, matchpk, teampk, playerpk):
match = Match.objects.get(pk=matchpk)
match.addMatchPresence(teampk = teampk, player = Player.objects.get(pk=playerpk))
messages.add_message(request, messages.SUCCESS, 'Je hebt jezelf aangemeld voor deze wedstrijd!!')
# return render(request, ... | match = Match.objects.get(pk=matchpk)
match.removeSubstitute(teampk=teampk, player =Player.objects.get(pk=substitutepk))
# return render(request, 'substitutewilling_cancellation.html')
messages.add_message(request, messages.SUCCESS, 'Je afmelding als mogelijke invaller is doorgegeven.')
# return render(... | identifier_body |
views.py | from unidecode import unidecode
import pdb
import os, manage
import re
from datetime import *
import codecs
import csv
import smtplib
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib import... | if form.is_valid():
cd = form.cleaned_data
# m.substitutesneeded = cd['substitutesneeded']
m.setSubstitutes(team = teampk, amountsubsneeded = cd['substitutesneeded'])
m.save()
return render(request, 'player/editplayer_complete.html')
else:
... | if request.method == 'POST' and m.isTeam(teampk):
form = ArrangeSubstitutesForm(request.POST) | random_line_split |
hotflip.py | from typing import Iterable, Optional, Tuple
import argparse
import collections
import os
import random
import pickle
import torch
import torch.nn as nn
import tqdm
import transformers
from .utils import device, PrefixLoss, PrefixModel
VERBOSE = False # whether to print grads, etc.
TOP_K = 20 # for printing grads,... |
def _set_prefix_ids(self, new_ids: torch.Tensor) -> None:
assert new_ids.ndim == 1, "cannot set prefix with more than 1 dim (need list of IDs)"
# Track steps since new prefix to enable early stopping
if (self.prefix_ids is not None) and (self.prefix_ids == new_ids).all():
... | """Allow prefix models to stop early."""
if self.args.early_stopping_steps == -1:
return False
return self._steps_since_new_prefix >= self.args.early_stopping_steps | identifier_body |
hotflip.py | from typing import Iterable, Optional, Tuple
import argparse
import collections
import os
import random
import pickle
import torch
import torch.nn as nn
import tqdm
import transformers
from .utils import device, PrefixLoss, PrefixModel
VERBOSE = False # whether to print grads, etc.
TOP_K = 20 # for printing grads,... | model: transformers.PreTrainedModel,
tokenizer: transformers.PreTrainedTokenizer,
preprefix: str = ''
):
super().__init__(
args=args, loss_func=loss_func, model=model, tokenizer=tokenizer, preprefix=preprefix
)
# HotFlip-specific parameters... | args: argparse.Namespace,
loss_func: PrefixLoss, | random_line_split |
hotflip.py | from typing import Iterable, Optional, Tuple
import argparse
import collections
import os
import random
import pickle
import torch
import torch.nn as nn
import tqdm
import transformers
from .utils import device, PrefixLoss, PrefixModel
VERBOSE = False # whether to print grads, etc.
TOP_K = 20 # for printing grads,... |
@property
def _prefix_token_grad(self) -> torch.Tensor:
"""Gradient of the prefix tokens wrt the token embedding matrix."""
return torch.einsum('nd,vd->nv', self.prefix_embedding.grad, self.token_embedding.weight)
def compute_loss_and_call_backward(
self,
x... | print("*" * 30)
print(f"Epoch {epoch}. Closest tokens to '{prefix_str}':")
word_distances = ((self.token_embedding.weight - self.prefix_embedding.reshape(1, emb_dim))**2).sum(1)
assert word_distances.shape == (50_257,)
topk_closest_words = word_distances.topk(k=TOP_K, l... | conditional_block |
hotflip.py | from typing import Iterable, Optional, Tuple
import argparse
import collections
import os
import random
import pickle
import torch
import torch.nn as nn
import tqdm
import transformers
from .utils import device, PrefixLoss, PrefixModel
VERBOSE = False # whether to print grads, etc.
TOP_K = 20 # for printing grads,... | (self) -> bool:
"""Allow prefix models to stop early."""
if self.args.early_stopping_steps == -1:
return False
return self._steps_since_new_prefix >= self.args.early_stopping_steps
def _set_prefix_ids(self, new_ids: torch.Tensor) -> None:
assert new_ids.ndim == 1, "c... | check_early_stop | identifier_name |
cartesian.rs | // Copyright 2017 Nico Madysa.
//
// 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 wri... | ator<Item = Self>>(iter: I) -> Self {
iter.fold(SizeHint(0, Some(0)), |acc, x| acc + x)
}
}
impl ::std::iter::Product for SizeHint {
fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(SizeHint(1, Some(1)), |acc, x| acc * x)
}
}
#[cfg(test)]
mod tests {
mod lengths {
... | ter | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.