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 |
|---|---|---|---|---|
switch.go | package output
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/Jeffail/benthos/v3/internal/batch"
"github.com/Jeffail/benthos/v3/internal/bloblang/mapping"
"github.com/Jeffail/benthos/v3/internal/component/output"
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/inter... | }
o.continues[i] = cConf.Continue
}
o.outputTSChans = make([]chan types.Transaction, len(o.outputs))
for i := range o.outputTSChans {
if mif, ok := output.GetMaxInFlight(o.outputs[i]); ok && mif > o.maxInFlight {
o.maxInFlight = mif
}
o.outputTSChans[i] = make(chan types.Transaction)
if err := o.outp... | }
if len(cConf.Check) > 0 {
if o.checks[i], err = interop.NewBloblangMapping(mgr, cConf.Check); err != nil {
return nil, fmt.Errorf("failed to parse case '%v' check mapping: %v", i, err)
} | random_line_split |
HAPServiceNode2.ts | import { logger } from '@nrchkb/logger'
import { uuid } from 'hap-nodejs'
import { NodeAPI } from 'node-red'
import NRCHKBError from './NRCHKBError'
import { FlowTypeType } from './types/FlowType'
import HAPHostNodeType from './types/HAPHostNodeType'
import HAPService2ConfigType from './types/HAPService2ConfigType'
im... |
// Service node properties
self.name = self.config.name
// Find a unique identifier for the current service
if (
self.hasOwnProperty('_flow') &&
self.hasOwnProperty('_alias') &&
self._flow.hasOwnProperty('TYPE') &&
FlowTypeType.Subflow ==... |
self.accessory = self.parentNode.accessory
} | random_line_split |
HAPServiceNode2.ts | import { logger } from '@nrchkb/logger'
import { uuid } from 'hap-nodejs'
import { NodeAPI } from 'node-red'
import NRCHKBError from './NRCHKBError'
import { FlowTypeType } from './types/FlowType'
import HAPHostNodeType from './types/HAPHostNodeType'
import HAPService2ConfigType from './types/HAPService2ConfigType'
im... | else {
resolve(self.config)
}
})
.then((newConfig) => {
init.call(self, newConfig)
})
.catch((error: any) => {
log.error(`Error while starting Service due to ${error}`)
})
}
const init = functio... | {
log.debug(
'Waiting for Setup message. It should be of format {"payload":{"nrchkb":{"setup":{}}}}'
)
self.setupDone = false
self.nodeStatusUtils.setStatus({
fill: 'blue',
shape: 'dot',
... | conditional_block |
fvp.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: fvp.proto
package fvp
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
math "math"
)
// Reference imports to suppre... | () int32 {
if m != nil {
return m.Counter
}
return 0
}
type EmptyMessage struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *EmptyMessage) Reset() { *m = EmptyMessage{} }
func (m *EmptyMessage) String() string {... | GetCounter | identifier_name |
fvp.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: fvp.proto
package fvp
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
math "math"
)
// Reference imports to suppre... |
func (m *SendMsg) String() string { return proto.CompactTextString(m) }
func (*SendMsg) ProtoMessage() {}
func (*SendMsg) Descriptor() ([]byte, []int) {
return fileDescriptor_9e36e933c92912d0, []int{0}
}
func (m *SendMsg) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SendMsg.Unmarshal(m, b)
}
func (m *S... | { *m = SendMsg{} } | identifier_body |
fvp.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: fvp.proto
package fvp
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
math "math"
)
// Reference imports to suppre... | Methods: []grpc.MethodDesc{
{
MethodName: "Send",
Handler: _Server_Send_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "fvp.proto",
} | var _Server_serviceDesc = grpc.ServiceDesc{
ServiceName: "fvp.Server",
HandlerType: (*ServerServer)(nil), | random_line_split |
fvp.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: fvp.proto
package fvp
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
math "math"
)
// Reference imports to suppre... |
return ""
}
func (m *SendMsg_State) GetVotedFor() []string {
if m != nil {
return m.VotedFor
}
return nil
}
func (m *SendMsg_State) GetAccepted() []string {
if m != nil {
return m.Accepted
}
return nil
}
func (m *SendMsg_State) GetConfirmed() []string {
if m != nil {
return m.Confirmed
}
return nil
... | {
return m.Id
} | conditional_block |
cli.py | """! \file
Utilities for command line interfaces.
The default interface can be set up using isle.cli.init().
More control is available through the lower level functions.
"""
from abc import ABCMeta, abstractmethod
import argparse
import contextlib
import logging
from pathlib import Path
import random
import shutil
im... | , nargs="+", type=Path)
parser.add_argument("-r", "--report", action=_ReportAction, metavar="", default=["overview"],
help="Comma separated list of reporters to use. Allowed values are ["
+",".join(reporters)+",all] Defaults to overview.")
return parser
def _make... | __call__(self, parser, namespace, values, option_string=None):
if "all" in values:
setattr(namespace, self.dest, reporters)
else:
setattr(namespace, self.dest, values.split(","))
parser.add_argument("input", help="Input file" | identifier_body |
cli.py | """! \file
Utilities for command line interfaces.
The default interface can be set up using isle.cli.init().
More control is available through the lower level functions.
"""
from abc import ABCMeta, abstractmethod
import argparse
import contextlib
import logging
from pathlib import Path
import random
import shutil
im... | ""
if _activeBar is not None:
# The c++ logger sends spurious empty lines,
# just gobble them up.
if msg.strip():
_activeBar.write(msg)
else:
sys.stderr.write(msg)
class ColorFormatter(logging.Formatter):
"""!
A logging formatter ... | rr`." | identifier_name |
cli.py | """! \file
Utilities for command line interfaces.
The default interface can be set up using isle.cli.init().
More control is available through the lower level functions.
"""
from abc import ABCMeta, abstractmethod
import argparse
import contextlib
import logging
from pathlib import Path
import random
import shutil
im... | > 2:
# can't be any noisier than that
verbosity = 2
# need at least this level so all messages get out
minLoglevel = logging.DEBUG if verbosity == 2 else logging.INFO
# No need for keeping track of threads in Python.
# In C++, all bets are off.
logging.logThreads = 0
# configu... | ng a second time."
"This function must be called *exactly* once.")
raise RuntimeError("Logging already set up")
_suppressGoogleLogWarning()
if verbosity | conditional_block |
cli.py | """! \file
Utilities for command line interfaces.
The default interface can be set up using isle.cli.init().
More control is available through the lower level functions.
"""
from abc import ABCMeta, abstractmethod
import argparse
import contextlib
import logging
from pathlib import Path
import random
import shutil
im... | args = argParser.parse_args()
defaultLog = None if not hasattr(args, "log") or args.log.lower() == "none" else args.log
verbosity = args.verbose if hasattr(args, "verbose") else 0
else:
# don't parse anything, use default values
args = None
setupLogging(defaultLog,... | if isinstance(argParser, str):
# construct new parser based on command name
args = _makeParser(argParser, **kwargs).parse_args()
else:
# use provided parser | random_line_split |
report.rs | //! Coverage report generation.
//!
//! # Template directory structure
//!
//! The coverage report produce two classes of files:
//!
//! * One summary page
//! * Source file pages, one page per source.
//!
//! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this
... | eport_path: &Path, report_files: &[ReportFileEntry], tera: &Tera, crate_path: &str, config: &FileConfig) -> Result<PathBuf> {
let path = report_path.join(config.output);
let mut context = Context::new();
let files = report_files
.iter()
.map(|entry| {
json!({
"sy... | ite_summary(r | identifier_name |
report.rs | //! Coverage report generation.
//!
//! # Template directory structure
//!
//! The coverage report produce two classes of files:
//!
//! * One summary page
//! * Source file pages, one page per source.
//!
//! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this
... | //! }
//! },
//! ...
//! ]
//! }
//! ```
use error::{Result, ResultExt};
use sourcepath::{SourceType, identify_source_path};
use template::new as new_template;
use utils::{clean_dir, parent_3};
use copy_dir::copy_dir;
use cov::{self, Gcov, Graph, Interner, Report, Symbol};
use serde_js... | //! "branches_count": 250,
//! "branches_executed": 225,
//! "branches_taken": 219 | random_line_split |
report.rs | //! Coverage report generation.
//!
//! # Template directory structure
//!
//! The coverage report produce two classes of files:
//!
//! * One summary page
//! * Source file pages, one page per source.
//!
//! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this
... | /// Renders the `report` into `report_path` using a template.
///
/// If the template has a summary page, returns the path of the rendered summary.
fn render(report_path: &Path, template_name: &OsStr, allowed_source_types: SourceType, report: &Report, interner: &Interner) -> Result<Option<PathBuf>> {
use toml::de::... | let mut graph = Graph::default();
for extension in &["gcno", "gcda"] {
progress!("Parsing", "*.{} files", extension);
for entry in read_dir(cov_build_path.join(extension))? {
let path = entry?.path();
if path.extension() == Some(OsStr::new(extension)) {
t... | identifier_body |
report.rs | //! Coverage report generation.
//!
//! # Template directory structure
//!
//! The coverage report produce two classes of files:
//!
//! * One summary page
//! * Source file pages, one page per source.
//!
//! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this
... | }
}
graph.analyze();
Ok(graph)
}
/// Renders the `report` into `report_path` using a template.
///
/// If the template has a summary page, returns the path of the rendered summary.
fn render(report_path: &Path, template_name: &OsStr, allowed_source_types: SourceType, report: &Report, interner: &Int... | trace!("merging {} {:?}", extension, path);
graph.merge(Gcov::open(path, interner)?)?;
}
| conditional_block |
main.rs | #[cfg(feature = "pulse")] extern crate libpulse_sys;
#[cfg(feature = "tokio")] extern crate ctrlc;
#[cfg(feature = "tokio")] extern crate futures;
#[cfg(feature = "tokio")] extern crate tokio_core;
#[cfg(feature = "tokio")] extern crate tokio_io;
#[cfg(feature = "tokio")] extern crate tokio_uds;
#[macro_use] extern cra... | else { None };
if active &&
self.notify.map(|notify| (idle.unwrap() + notify) >= self.time).unwrap_or(idle.unwrap() >= self.time) {
let idle = idle.unwrap();
if self.not_when_fullscreen && self.fullscreen.is_none() {
let mut focus = 0u64;
let... | {
Some(match get_idle(self.display, self.info) {
Ok(idle) => idle / 1000, // Convert to seconds
Err(_) => return Some(false)
})
} | conditional_block |
main.rs | #[cfg(feature = "pulse")] extern crate libpulse_sys;
#[cfg(feature = "tokio")] extern crate ctrlc;
#[cfg(feature = "tokio")] extern crate futures;
#[cfg(feature = "tokio")] extern crate tokio_core;
#[cfg(feature = "tokio")] extern crate tokio_io;
#[cfg(feature = "tokio")] extern crate tokio_uds;
#[macro_use] extern cra... | }
#[cfg(feature = "tokio")] {
#[cfg(feature = "pulse")]
let not_when_audio = matches.is_present("not-when-audio");
let socket = matches.value_of("socket");
let app = Rc::new(RefCell::new(app));
let mut core = Core::new().unwrap();
let handle = Rc::new(core.hand... |
thread::sleep(app.delay);
} | random_line_split |
main.rs | #[cfg(feature = "pulse")] extern crate libpulse_sys;
#[cfg(feature = "tokio")] extern crate ctrlc;
#[cfg(feature = "tokio")] extern crate futures;
#[cfg(feature = "tokio")] extern crate tokio_core;
#[cfg(feature = "tokio")] extern crate tokio_io;
#[cfg(feature = "tokio")] extern crate tokio_uds;
#[macro_use] extern cra... |
let mut playing = 0;
let app = Rc::clone(&app);
handle.spawn(rx.for_each(move |event| {
match event {
Event::Clear => playing = 0,
Event::New => playing += 1,
Event::Finish => {... | {
unsafe {
let state = pa_context_get_state(ctx);
if state == PA_CONTEXT_READY {
pa_context_set_subscribe_callback(ctx, Some(subscribe_callback), userdata);
pa_context_subscribe(ctx, PA_SUBSCRIPT... | identifier_body |
main.rs | #[cfg(feature = "pulse")] extern crate libpulse_sys;
#[cfg(feature = "tokio")] extern crate ctrlc;
#[cfg(feature = "tokio")] extern crate futures;
#[cfg(feature = "tokio")] extern crate tokio_core;
#[cfg(feature = "tokio")] extern crate tokio_io;
#[cfg(feature = "tokio")] extern crate tokio_uds;
#[macro_use] extern cra... | (display: *mut Display, info: *mut XScreenSaverInfo) -> Result<u64, ()> {
if unsafe { XScreenSaverQueryInfo(display, XDefaultRootWindow(display), info) } == 0 {
eprintln!("failed to query screen saver info");
return Err(());
}
Ok(unsafe { (*info).idle })
}
fn invoke(cmd: &str) {
if let ... | get_idle | identifier_name |
install.go | package cmd
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"docker.io/go-docker"
"docker.io/go-docker/api/types"
"docker.io/go-docker/api/types/filters"
"github.com/appcelerator/amp/docker/cli/cli/command"
"github.com/appcelerator/amp/docke... | if os.IsNotExist(err) {
return false, nil
}
return true, err
}
func createInitialSecrets() error {
// Computing secret path
secretPath := path.Join("/", defaultSecretsPath)
pe, err := pathExists(secretPath)
if err != nil {
return err
}
if !pe {
secretPath = defaultSecretsPath
}
secretPath, err = filep... | return true, nil
} | random_line_split |
install.go | package cmd
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"docker.io/go-docker"
"docker.io/go-docker/api/types"
"docker.io/go-docker/api/types/filters"
"github.com/appcelerator/amp/docker/cli/cli/command"
"github.com/appcelerator/amp/docke... |
func deploy(d *command.DockerCli, stackfile string, namespace string) error {
if namespace == "" {
// use the stackfile basename as the default stack namespace
namespace = filepath.Base(stackfile)
namespace = strings.TrimSuffix(namespace, filepath.Ext(namespace))
}
options := stack.DeployOptions{
Namespac... | {
if path == "" {
path = "./stacks"
}
path += "/" + deploymentMode
// a bit more work but we can't just use filepath.Glob
// since we need to match both *.yml and *.yaml
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
stackfiles := []string{}
for _, f := range files {
name := f.Nam... | identifier_body |
install.go | package cmd
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"docker.io/go-docker"
"docker.io/go-docker/api/types"
"docker.io/go-docker/api/types/filters"
"github.com/appcelerator/amp/docker/cli/cli/command"
"github.com/appcelerator/amp/docke... |
// Remove volumes
for _, volume := range volumes {
log.Printf("Removing volume [%s]... ", volume.Name)
if err := Docker.RemoveVolume(volume.Name, false, timeout); err != nil {
log.Println("Failed")
return err
}
}
return nil
}
| {
return nil
} | conditional_block |
install.go | package cmd
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"docker.io/go-docker"
"docker.io/go-docker/api/types"
"docker.io/go-docker/api/types/filters"
"github.com/appcelerator/amp/docker/cli/cli/command"
"github.com/appcelerator/amp/docke... | (path string, deploymentMode string) ([]string, error) {
if path == "" {
path = "./stacks"
}
path += "/" + deploymentMode
// a bit more work but we can't just use filepath.Glob
// since we need to match both *.yml and *.yaml
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
stackfiles :... | getStackFiles | identifier_name |
decoder.rs | use std::cmp;
use std::io::{self, Read};
use encoding_rs::{Decoder, Encoding, UTF_8};
/// A BOM is at least 2 bytes and at most 3 bytes.
///
/// If fewer than 2 bytes are available to be read at the beginning of a
/// reader, then a BOM is `None`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Bom {
bytes: [... | Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(nread)
}
/// A reader that transcodes to UTF-8. The source encoding is determined by
/// inspecting the BOM from the stream read from `R`, if one exists. If a
/// UTF-16 BOM exists, then t... | Ok(n) => {
nread += n;
let tmp = buf;
buf = &mut tmp[n..];
} | random_line_split |
decoder.rs | use std::cmp;
use std::io::{self, Read};
use encoding_rs::{Decoder, Encoding, UTF_8};
/// A BOM is at least 2 bytes and at most 3 bytes.
///
/// If fewer than 2 bytes are available to be read at the beginning of a
/// reader, then a BOM is `None`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Bom {
bytes: [... |
}
Ok(nwrite)
}
#[inline(never)] // impacts perf...
fn detect(&mut self) -> io::Result<()> {
let bom = self.rdr.peek_bom()?;
self.decoder = bom.decoder();
Ok(())
}
}
impl<R: io::Read, B: AsMut<[u8]>> io::Read for DecodeReader<R, B> {
fn read(&mut self, buf: ... | {
self.pos = 0;
self.last = true;
let (_, _, nout, _) =
self.decoder.as_mut().unwrap().decode_to_utf8(
&[], buf, true);
return Ok(nout);
} | conditional_block |
decoder.rs | use std::cmp;
use std::io::{self, Read};
use encoding_rs::{Decoder, Encoding, UTF_8};
/// A BOM is at least 2 bytes and at most 3 bytes.
///
/// If fewer than 2 bytes are available to be read at the beginning of a
/// reader, then a BOM is `None`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Bom {
bytes: [... | () {
let srcbuf = vec![0xFF, 0xFE];
let mut dstbuf = vec![0; 8 * (1<<10)];
let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None);
let n = rdr.read(&mut dstbuf).unwrap();
assert_eq!(&*srcbuf, &dstbuf[..n]);
let srcbuf = vec![0xFE, 0xFF];
let mut rd... | trans_utf16_bom | identifier_name |
decoder.rs | use std::cmp;
use std::io::{self, Read};
use encoding_rs::{Decoder, Encoding, UTF_8};
/// A BOM is at least 2 bytes and at most 3 bytes.
///
/// If fewer than 2 bytes are available to be read at the beginning of a
/// reader, then a BOM is `None`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Bom {
bytes: [... |
}
/// `BomPeeker` wraps `R` and satisfies the `io::Read` interface while also
/// providing a peek at the BOM if one exists. Peeking at the BOM does not
/// advance the reader.
struct BomPeeker<R> {
rdr: R,
bom: Option<Bom>,
nread: usize,
}
impl<R: io::Read> BomPeeker<R> {
/// Create a new BomPeeker.... | {
let bom = self.as_slice();
if bom.len() < 3 {
return None;
}
if let Some((enc, _)) = Encoding::for_bom(bom) {
if enc != UTF_8 {
return Some(enc.new_decoder_with_bom_removal());
}
}
None
} | identifier_body |
action.go | // Copyright (c) 2022 IoTeX Foundation
// This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
// or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
// This source code is governed by Apache Licen... | }
func registerPasswordFlag(client ioctl.Client, cmd *cobra.Command) {
flag.NewStringVarP(passwordFlagLabel, passwordFlagShortLabel, passwordFlagDefault, selectTranslation(client, _flagPasswordUsages)).RegisterCommand(cmd)
}
func selectTranslation(client ioctl.Client, trls map[config.Language]string) string {
txt, ... |
func registerAssumeYesFlag(client ioctl.Client, cmd *cobra.Command) {
flag.BoolVarP(assumeYesFlagLabel, assumeYesFlagShortLabel, assumeYesFlagDefault, selectTranslation(client, _flagAssumeYesUsages)).RegisterCommand(cmd) | random_line_split |
action.go | // Copyright (c) 2022 IoTeX Foundation
// This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
// or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
// This source code is governed by Apache Licen... | gisterAssumeYesFlag(client ioctl.Client, cmd *cobra.Command) {
flag.BoolVarP(assumeYesFlagLabel, assumeYesFlagShortLabel, assumeYesFlagDefault, selectTranslation(client, _flagAssumeYesUsages)).RegisterCommand(cmd)
}
func registerPasswordFlag(client ioctl.Client, cmd *cobra.Command) {
flag.NewStringVarP(passwordFlagL... | VarP(bytecodeFlagLabel, bytecodeFlagShortLabel, bytecodeFlagDefault, selectTranslation(client, _flagBytecodeUsages)).RegisterCommand(cmd)
}
func re | identifier_body |
action.go | // Copyright (c) 2022 IoTeX Foundation
// This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
// or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
// This source code is governed by Apache Licen... | l.Client, cmd *cobra.Command) {
flag.NewUint64VarP(nonceFlagLabel, nonceFlagShortLabel, nonceFlagDefault, selectTranslation(client, _flagNonceUsages)).RegisterCommand(cmd)
}
func registerSignerFlag(client ioctl.Client, cmd *cobra.Command) {
flag.NewStringVarP(signerFlagLabel, signerFlagShortLabel, SignerFlagDefault,... | onceFlag(client ioct | identifier_name |
action.go | // Copyright (c) 2022 IoTeX Foundation
// This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
// or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
// This source code is governed by Apache Licen... | conditional_block | ||
content_preservation.py | """EVALUATION OF CONTENT PRESERVATION
This code can be used for evaluation of content preservation between input and output sentiment texts of a style transfer model.
Word Mover's Distance (WMD) on texts with style masking (i.e. placeholders used in place of style words)
exhibited the highest correlation with human ... |
# def load_wmd_scores(model_name, param_val):
# '''
# Load pre-computed WMD scores for input and output texts under
# the style masking setting. (Style masking exhibited higher
# correlation with human scores than other settings).
# Parameters
# ----------
# model_name : str
# Nam... | '''
Calculate Word Mover's Distance for each (reference, candidate)
pair in a list of reference texts and candidate texts.
The lower the distance, the more similar the texts are.
Parameters
----------
references : list
Input texts
candidates : list
Output texts (e.g. fr... | identifier_body |
content_preservation.py | """EVALUATION OF CONTENT PRESERVATION
This code can be used for evaluation of content preservation between input and output sentiment texts of a style transfer model.
Word Mover's Distance (WMD) on texts with style masking (i.e. placeholders used in place of style words)
exhibited the highest correlation with human ... | (references, candidates, wmd_model):
'''
Calculate Word Mover's Distance for each (reference, candidate)
pair in a list of reference texts and candidate texts.
The lower the distance, the more similar the texts are.
Parameters
----------
references : list
Input texts
candid... | calculate_wmd_scores | identifier_name |
content_preservation.py | """EVALUATION OF CONTENT PRESERVATION
This code can be used for evaluation of content preservation between input and output sentiment texts of a style transfer model.
Word Mover's Distance (WMD) on texts with style masking (i.e. placeholders used in place of style words)
exhibited the highest correlation with human ... | tokenized_texts = []
for text in texts:
tokenized_texts.append(tokenize(text))
model = Word2Vec(tokenized_texts)
model.save(path)
def load_word2vec_model(path):
model = Word2Vec.load(path)
model.init_sims(replace=True) # normalize vectors
return model
def calculate_wmd_scores(refer... | return unmasked_texts, texts_with_style_removed, texts_with_style_masked
## MODELS / SCORING OF WMD
def train_word2vec_model(texts, path): | random_line_split |
content_preservation.py | """EVALUATION OF CONTENT PRESERVATION
This code can be used for evaluation of content preservation between input and output sentiment texts of a style transfer model.
Word Mover's Distance (WMD) on texts with style masking (i.e. placeholders used in place of style words)
exhibited the highest correlation with human ... |
edited_texts.append(' '.join(edited_tokens))
return edited_texts
def generate_style_modified_texts(texts, style_lexicon):
# ensure consistent tokenization under different style modification settings
unmasked_texts = mask_style_words(texts, style_tokens={}, mask_style=False)
tex... | if token.lower() in style_tokens:
if mask_style:
edited_tokens.append(CUSTOM_STYLE)
else:
edited_tokens.append(token) | conditional_block |
query.rs | use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::fmt;
use std::iter::FromIterator;
use std::hash::{BuildHasher, Hash};
use std::rc::Rc;
use std::sync::Arc;
use serde::de;
use serde::Deserializer;
/// Allows access to the query parameters in an url or a body.
///
/// Use one of the listed implem... | self.0.insert_or_poison(key.into(), value.into())
}
Ok(self.0)
}
}
let visitor = Visitor(NormalizedParameter::default());
deserializer.deserialize_seq(visitor)
}
}
impl<K, V> FromIterator<(K, V)> for NormalizedParameter
where... | while let Some((key, value)) = access.next_element::<(String, String)>()? { | random_line_split |
query.rs | use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::fmt;
use std::iter::FromIterator;
use std::hash::{BuildHasher, Hash};
use std::rc::Rc;
use std::sync::Arc;
use serde::de;
use serde::Deserializer;
/// Allows access to the query parameters in an url or a body.
///
/// Use one of the listed implem... |
}
/// Return a reference to value in a collection if it is the only one.
///
/// For example, a vector of string like types returns a reference to its first
/// element if there are no other, else it returns `None`.
///
/// If this were done with slices, that would require choosing a particular
/// value type of the ... | {
self.normalize()
} | identifier_body |
query.rs | use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::fmt;
use std::iter::FromIterator;
use std::hash::{BuildHasher, Hash};
use std::rc::Rc;
use std::sync::Arc;
use serde::de;
use serde::Deserializer;
/// Allows access to the query parameters in an url or a body.
///
/// Use one of the listed implem... | else {
self.get(0).and_then(V::get_unique)
}
}
}
mod test {
use super::*;
/// Compilation tests for various possible QueryParameter impls.
#[allow(unused)]
#[allow(dead_code)]
fn test_query_parameter_impls() {
let _ = (&HashMap::<String, String>::new()) as &dyn Que... | {
None
} | conditional_block |
query.rs | use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::fmt;
use std::iter::FromIterator;
use std::hash::{BuildHasher, Hash};
use std::rc::Rc;
use std::sync::Arc;
use serde::de;
use serde::Deserializer;
/// Allows access to the query parameters in an url or a body.
///
/// Use one of the listed implem... | (&self, key: &str) -> Option<Cow<str>> {
self.inner
.get(key)
.and_then(|val| val.as_ref().map(Cow::as_ref).map(Cow::Borrowed))
}
fn normalize(&self) -> NormalizedParameter {
self.clone()
}
}
impl NormalizedParameter {
/// Create an empty map.
pub fn new() -... | unique_value | identifier_name |
Graph.ts | import * as acorn from 'acorn';
import injectClassFields from 'acorn-class-fields';
import injectExportNsFrom from 'acorn-export-ns-from';
import injectImportMeta from 'acorn-import-meta';
import injectStaticClassFeatures from 'acorn-static-class-features';
import GlobalScope from './ast/scopes/GlobalScope';
import { P... | vate link(entryModules: Module[]) {
for (const module of this.modules) {
module.linkDependencies();
}
const { orderedModules, cyclePaths } = analyseModuleExecution(entryModules);
for (const cyclePath of cyclePaths) {
this.warn({
code: 'CIRCULAR_DEPENDENCY',
cycle: cyclePath,
importer: cyclePat... | (activeDeprecation || this.strictDeprecations) {
const warning = errDeprecation(deprecation);
if (this.strictDeprecations) {
return error(warning);
}
this.warn(warning);
}
}
pri | identifier_body |
Graph.ts | import * as acorn from 'acorn';
import injectClassFields from 'acorn-class-fields';
import injectExportNsFrom from 'acorn-export-ns-from';
import injectImportMeta from 'acorn-import-meta';
import injectStaticClassFeatures from 'acorn-static-class-features';
import GlobalScope from './ast/scopes/GlobalScope';
import { P... | this.pluginDriver = new PluginDriver(this, options.plugins!, this.pluginCache);
if (watcher) {
const handleChange = (id: string) => this.pluginDriver.hookSeqSync('watchChange', [id]);
watcher.on('change', handleChange);
watcher.once('restart', () => {
watcher.removeListener('change', handleChange);
... | random_line_split | |
Graph.ts | import * as acorn from 'acorn';
import injectClassFields from 'acorn-class-fields';
import injectExportNsFrom from 'acorn-export-ns-from';
import injectImportMeta from 'acorn-import-meta';
import injectStaticClassFeatures from 'acorn-static-class-features';
import GlobalScope from './ast/scopes/GlobalScope';
import { P... |
return Object.keys(entryModules).map(name => ({
fileName: null,
id: entryModules[name],
importer: undefined,
name
}));
}
export default class Graph {
acornOptions: acorn.Options;
acornParser: typeof acorn.Parser;
cachedModules: Map<string, ModuleJSON>;
contextParse: (code: string, acornOptions?: acorn.O... | {
return entryModules.map(id => ({ fileName: null, name: null, id, importer: undefined }));
} | conditional_block |
Graph.ts | import * as acorn from 'acorn';
import injectClassFields from 'acorn-class-fields';
import injectExportNsFrom from 'acorn-export-ns-from';
import injectImportMeta from 'acorn-import-meta';
import injectStaticClassFeatures from 'acorn-static-class-features';
import GlobalScope from './ast/scopes/GlobalScope';
import { P... | (
entryModules: string | string[] | Record<string, string>,
manualChunks: ManualChunksOption | void,
inlineDynamicImports: boolean
): Promise<Chunk[]> {
// Phase 1 – discovery. We load the entry module and find which
// modules it imports, and import those, until we have all
// of the entry module's depend... | build | identifier_name |
reg_adv_train_loop.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import models.drn as drn
from models.DRNSeg import DRNSeg
from models.FCN32s import FCN32s
import data_transforms as transforms
import json
import math
import os
from os.path import exists, join, split
import threading
import time, datetime
import numpy as np
import shut... | element_same_class = element_same_class.view(-1, y_pred.size(1))
element_same_class = element_same_class / (torch.norm(element_same_class, dim=1, keepdim=True) + epsilon) #TODO: divided , you need epsilon to prevent NAN
matrix = torch.mm(element_same_class,
... | #TODO: check how to reshape this back !!!!!!!!! | random_line_split |
reg_adv_train_loop.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import models.drn as drn
from models.DRNSeg import DRNSeg
from models.FCN32s import FCN32s
import data_transforms as transforms
import json
import math
import os
from os.path import exists, join, split
import threading
import time, datetime
import numpy as np
import shut... | ():
pass
#TODO: this is a local logdet loss
def log_det_cuda(y_pred, y_class_true, args, neglect = 255): # We need to max Diversity for each class
# TODO: we should first down sampling before move on (like dropout 99%)
delta_det = 1e-3
drop_ratio = 1 - args.drop_ratio
# y_true need to be one ho... | log_det_global_cuda | identifier_name |
reg_adv_train_loop.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import models.drn as drn
from models.DRNSeg import DRNSeg
from models.FCN32s import FCN32s
import data_transforms as transforms
import json
import math
import os
from os.path import exists, join, split
import threading
import time, datetime
import numpy as np
import shut... |
return det_loss
#TODO: Can we use GAN to align the variance? Use Pang et al? Maximum the overall entropy?
def train_seg_reg(args):
batch_size = args.batch_size
num_workers = args.workers
crop_size = args.crop_size
# print(' '.join(sys.argv))
for k, v in args.__dict__.items():
... | element_same_class = mask_non_y_pred[flat_ind_select]
#TODO: check how to reshape this back !!!!!!!!!
element_same_class = element_same_class.view(-1, y_pred.size(1))
element_same_class = element_same_class / (torch.norm(element_same_class, dim=1, keepdim=True... | conditional_block |
reg_adv_train_loop.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import models.drn as drn
from models.DRNSeg import DRNSeg
from models.FCN32s import FCN32s
import data_transforms as transforms
import json
import math
import os
from os.path import exists, join, split
import threading
import time, datetime
import numpy as np
import shut... |
# def log_det(y_true, y_pred, num_model=FLAGS.num_models):
# bool_R_y_true = tf.not_equal(tf.ones_like(y_true) - y_true, zero) # batch_size X (num_class X num_models), 2-D
# mask_non_y_pred = tf.boolean_mask(y_pred, bool_R_y_true) # batch_size X (num_class-1) X num_models, 1-D
# mask_non_y_pred = tf.resh... | num_pred = y_pred.size(2) * y_pred.size(3)
entropy_type = "sum_entropy"
if entropy_type == "all_entropy":
flag_pred = y_pred.view(y_pred.size(0), -1)
entropy = torch.sum(-flag_pred * torch.log(flag_pred + log_epsilon)) #TODO: here, even sum the batch dim
elif entropy_type == "sum_entropy": ... | identifier_body |
resnet_trainer.py | #!/usr/bin/python
import os
import shutil
import time
from IPython.display import Image
# import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
imp... | # Training parameters
# architecture = 'resnet34'
# architecture = 'vgg16_bn'
# architecture = 'dense'
lr = 0.1 # densenet default = 0.1,
lr_init = 0.1
momentum = 0.90 # densenet default = 0.9
weight_decay = 1e-3 # densenet default = 1e-4
num_epochs = 125
dummy_text_file = open("dummy_text.txt", "w")
def construct... | fine_size = 224
c = 3
data_mean = np.asarray([0.45834960097,0.44674252445,0.41352266842])
| random_line_split |
resnet_trainer.py | #!/usr/bin/python
import os
import shutil
import time
from IPython.display import Image
# import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
imp... |
def adjust_learning_rate(lr, optimizer, epoch):
"""Calculates a learning rate of the initial LR decayed by 10 every 30 epochs"""
lr = lr_init * (0.1 ** (epoch // 10))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
# def adjust_learning_rate(lr, optimizer, ... | """Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
... | identifier_body |
resnet_trainer.py | #!/usr/bin/python
import os
import shutil
import time
from IPython.display import Image
# import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
imp... | (filename, lr, momentum, weight_decay):
# filename = "resnet34"
# model = models.__dict__[filename](num_classes=100, pretrained=False)
model = torch.load("results/"+filename+".pt")
if use_cuda:
model = model.cuda()
optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=momentum, w... | trainer | identifier_name |
resnet_trainer.py | #!/usr/bin/python
import os
import shutil
import time
from IPython.display import Image
# import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
imp... |
train_loader, val_loader = construct_dataloader_disk()
trainval_loader = construct_dataloader_disk_trainval()
def trainer(filename, lr, momentum, weight_decay):
# filename = "resnet34"
# model = models.__dict__[filename](num_classes=100, pretrained=False)
model = torch.load("results/"+filename+".pt")... | criterion = criterion.cuda() | conditional_block |
token.go | // Copyright 2018 Google LLC
//
// 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 ... |
if t.ServerConfig != nil {
t.clientID = t.ServerConfig.Tenant.Key
t.clientSecret = t.ServerConfig.Tenant.Secret
}
missingFlagNames := []string{}
if t.clientID == "" {
missingFlagNames = append(missingFlagNames, "key")
}
if t.clientSecret == "" {
missingFlagNames = append(missingFlag... | {
return fmt.Errorf("only valid for legacy or hybrid, use create-secret for hybrid")
} | conditional_block |
token.go | // Copyright 2018 Google LLC
//
// 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 ... | (t *token, printf shared.FormatFn) *cobra.Command {
c := &cobra.Command{
Use: "create",
Short: "Create a new OAuth token",
Long: "Create a new OAuth token",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
token, err := t.createToken(printf)
if err != nil {
return errors.... | cmdCreateToken | identifier_name |
token.go | // Copyright 2018 Google LLC
//
// 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 ... | { return a[i].KeyID() < a[j].KeyID() } | identifier_body | |
token.go | // Copyright 2018 Google LLC
//
// 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 ... | "time"
"github.com/apigee/apigee-remote-service-cli/cmd/provision"
"github.com/apigee/apigee-remote-service-cli/shared"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwk"
"github.com/lestrrat-go/jwx/jws"
"github.com/lestrrat-go/jwx/jwt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"gopkg.i... | "sort" | random_line_split |
seq2seq_trainer.py | import os
import sys
from argparse import ArgumentParser
import random
# # python.dataScience.notebookFileRoot=${fileDirname}
# wdir = os.path.abspath(os.getcwd() + "/../../")
# sys.path.append(wdir)
# print(sys.path)
# print(wdir)
import text_loaders as tl
import rnn_encoder_decoder as encdec
import torch
impor... |
else:
nn.init.constant_(param.data, 0)
def create_mask(self, src):
mask = (src != self.pad_idx).permute(1, 0)
return mask
def forward(self, src, src_len, trg, teacher_forcing_ratio=0.5):
# src = [src len, batch size]
# src_len = [batch size]
... | nn.init.normal_(param.data, mean=0, std=0.01) | conditional_block |
seq2seq_trainer.py | import os
import sys
from argparse import ArgumentParser
import random
# # python.dataScience.notebookFileRoot=${fileDirname}
# wdir = os.path.abspath(os.getcwd() + "/../../")
# sys.path.append(wdir)
# print(sys.path)
# print(wdir)
import text_loaders as tl
import rnn_encoder_decoder as encdec
import torch
impor... | (self, logits, target):
return self._loss(logits, target)
def configure_optimizers(self):
# return optim.Adam(self.parameters(), lr=5e-4)
# optimizer = optim.Adam(self.parameters(), lr=1e-3)
# scheduler = optim.LambdaLR(optimizer, ...)
# return [optimizer], [scheduler]
... | loss | identifier_name |
seq2seq_trainer.py | import os
import sys
from argparse import ArgumentParser
import random
# # python.dataScience.notebookFileRoot=${fileDirname}
# wdir = os.path.abspath(os.getcwd() + "/../../")
# sys.path.append(wdir)
# print(sys.path)
# print(wdir)
import text_loaders as tl
import rnn_encoder_decoder as encdec
import torch
impor... | self.log(
"val_acc",
acc,
on_step=False,
on_epoch=True,
prog_bar=True,
logger=True,
sync_dist=True,
)
self.log(
"val_bleu_idx",
bleu_score,
on_step=False,
on_epoch=... | sync_dist=True,
) | random_line_split |
seq2seq_trainer.py | import os
import sys
from argparse import ArgumentParser
import random
# # python.dataScience.notebookFileRoot=${fileDirname}
# wdir = os.path.abspath(os.getcwd() + "/../../")
# sys.path.append(wdir)
# print(sys.path)
# print(wdir)
import text_loaders as tl
import rnn_encoder_decoder as encdec
import torch
impor... |
def validation_step(self, batch, batch_idx):
"""validation is in eval mode so we do not have to use
placeholder input tensors
"""
src_batch, trg_batch = batch
src_seq = src_batch["src_ids"]
# change from [batch, seq_len] -> to [seq_len, batch]
src_seq = sr... | src_batch, trg_batch = batch
src_seq = src_batch["src_ids"]
# change from [batch, seq_len] -> to [seq_len, batch]
src_seq = src_seq.transpose(0, 1)
src_lengths = src_batch["src_lengths"]
trg_seq = trg_batch["trg_ids"]
# change from [batch, seq_len] -> to [seq_len, batch... | identifier_body |
PropDetCode.py | # -*- coding: utf-8 -*-
import pickle
import pathlib
from pathlib import Path
from typing import List, Tuple, Dict
import numpy as np
import torch
import torch.nn as nn
from torch.optim import SGD, Adam
from torch.utils.data import Dataset, DataLoader
from torchtext.data import get_tokenizer
from matplotlib import py... | (txt: List[Tuple]):
tokenizer = get_tokenizer("spacy")
list_v = []
for i in txt:
tok = tokenizer(i)
for j in tok:
if list_v.count(j) == 0:
list_v.append(j)
vocab = Vocabulary(tokens=list_v)
return vocab
full_text = train_txt + dev_txt
vocab = fill_vocab(f... | fill_vocab | identifier_name |
PropDetCode.py | # -*- coding: utf-8 -*-
import pickle
import pathlib
from pathlib import Path
from typing import List, Tuple, Dict
import numpy as np
import torch
import torch.nn as nn
from torch.optim import SGD, Adam
from torch.utils.data import Dataset, DataLoader
from torchtext.data import get_tokenizer
from matplotlib import py... |
else:
visit[label[0]:label[1]] = 1
res.append(label)
return res
else:
return labels
def clean_text(articles, ids):
texts = []
for article, id in zip(articles, ids):
sentences = article.split('\n')
end = -1
res = []
fo... | label[3] = 1 | conditional_block |
PropDetCode.py | # -*- coding: utf-8 -*-
import pickle
import pathlib
from pathlib import Path
from typing import List, Tuple, Dict
import numpy as np
import torch
import torch.nn as nn
from torch.optim import SGD, Adam
from torch.utils.data import Dataset, DataLoader
from torchtext.data import get_tokenizer
from matplotlib import py... | self.train_data = train_data
self.dev_data = dev_data
self.vocab = vocab
# self.device = torch.device('cuda:0')
if hyperparams['learning_algo'] == 'adam':
self.optimizer = Adam(params=self.model.parameters(),
lr=hyperparams['learning_... | dev_data: torch.LongTensor,
vocab: Vocabulary,
hyperparams: Dict):
self.model = model | random_line_split |
PropDetCode.py | # -*- coding: utf-8 -*-
import pickle
import pathlib
from pathlib import Path
from typing import List, Tuple, Dict
import numpy as np
import torch
import torch.nn as nn
from torch.optim import SGD, Adam
from torch.utils.data import Dataset, DataLoader
from torchtext.data import get_tokenizer
from matplotlib import py... |
def get_token_at_index(self, idx: int):
return self.idx_to_word[idx]
def get_index_of_token(self, token: str):
return self.word_to_idx[token]
def size(self):
return len(self.word_to_idx)
class PropagandaDataset(Dataset):
def __init__(self,
fold: str,
... | self.word_to_idx = {'<PAD>': 0}
for idx, tok in enumerate(tokens, 1):
self.word_to_idx[tok] = idx
# dictionary that maps indices to words
self.idx_to_word = {}
for tok, idx in self.word_to_idx.items():
self.idx_to_word[idx] = tok | identifier_body |
deduction_engine_extended.py | """
This module contains the rule-based inference (rulebased_deduction engine)
"""
import itertools
from collections import defaultdict
from itertools import chain
from excut.explanations_mining.descriptions import dump_explanations_to_file
from excut.explanations_mining.descriptions_new import Description2, Atom, loa... |
def _merge_and_sort_cut(self, per_entity_prediction, threshold=0, topk=-1):
"""
Merge the the inferred facts in case of functional predicates
:param per_entity_prediction:
:return:
"""
def quality_method(p):
return p.get_quality(self.quality, self.qual... | """
Combine predictions from different rules
:param predictions: list of generated predictions
:return: combined single prediction with several sources for equivalent predictions
:rtype: dict
"""
# per_var_predictions = defaultdict(lambda: defaultdict(list))
# f... | identifier_body |
deduction_engine_extended.py | """
This module contains the rule-based inference (rulebased_deduction engine)
"""
import itertools
from collections import defaultdict
from itertools import chain
from excut.explanations_mining.descriptions import dump_explanations_to_file
from excut.explanations_mining.descriptions_new import Description2, Atom, loa... | (self, other):
return other.triple == self.triple
def __hash__(self):
return hash(self.triple)
class DeductionEngine():
"""
Abstract rulebased_deduction/inference engine.
"""
def __init__(self, **kwargs):
pass
def infer(self, descriptions, recursive=False, topk=-1):
... | __eq__ | identifier_name |
deduction_engine_extended.py | """
This module contains the rule-based inference (rulebased_deduction engine)
"""
import itertools
from collections import defaultdict
from itertools import chain
from excut.explanations_mining.descriptions import dump_explanations_to_file
from excut.explanations_mining.descriptions_new import Description2, Atom, loa... |
if target_entities and clear_target_entities:
self.labels_indexer.drop()
return per_entity_predictions
def consolidate(self, predictions):
"""
Combine predictions from different rules
:param predictions: list of generated predictions
:return: combined... | dump_predictions_map(per_entity_predictions, output_filepath, triple_format=True, topk=topk, with_weight=True,
with_description=False, quality=self.quality) | conditional_block |
deduction_engine_extended.py | """
This module contains the rule-based inference (rulebased_deduction engine)
"""
import itertools
from collections import defaultdict
from itertools import chain
from excut.explanations_mining.descriptions import dump_explanations_to_file
from excut.explanations_mining.descriptions_new import Description2, Atom, loa... | :param with_description:
:return:
"""
out_file_parsable = out_filepath + '.parsable'
out_filepath_with_type = out_filepath + ('.%s' % quality if len(quality) > 0 else '')
with open(out_filepath_with_type, 'w') as out_file:
for var, predictions in per_var_predictions.items():
... | random_line_split | |
system.rs | use crate::simulation::agent_shader::ty::PushConstantData;
use crate::simulation::blur_fade_shader;
use crate::simulation::Simulation;
use imgui::{Context, Ui};
use imgui_vulkano_renderer::Renderer;
use imgui_winit_support::{HiDpiMode, WinitPlatform};
use std::sync::Arc;
use std::time::{Duration, Instant};
use vulkano:... | sensor_radius: 1,
// In the range [0 - PI]
sensor_angle_spacing: 0.18,
// Seconds per frame. (60fps)
delta_time: 0.016667,
};
let mut fade_parameters: blur_fade_shader::ty::PushConstantData =
blur_fade_shader::ty::PushConstantData ... | random_line_split | |
system.rs | use crate::simulation::agent_shader::ty::PushConstantData;
use crate::simulation::blur_fade_shader;
use crate::simulation::Simulation;
use imgui::{Context, Ui};
use imgui_vulkano_renderer::Renderer;
use imgui_winit_support::{HiDpiMode, WinitPlatform};
use std::sync::Arc;
use std::time::{Duration, Instant};
use vulkano:... |
pub fn main_loop<
F: FnMut(
&mut bool,
&mut PushConstantData,
&mut blur_fade_shader::ty::PushConstantData,
&mut Ui,
) + 'static,
>(
self,
simulation: Simulation,
mut run_ui: F,
) {
let Syste... | {
// Basic commands taken from the vulkano imgui examples:
// https://github.com/Tenebryo/imgui-vulkano-renderer/blob/master/examples/support/mod.rs
let instance = {
let extensions = vulkano_win::required_extensions();
Instance::new(None, &extensions, None).expect("Faile... | identifier_body |
system.rs | use crate::simulation::agent_shader::ty::PushConstantData;
use crate::simulation::blur_fade_shader;
use crate::simulation::Simulation;
use imgui::{Context, Ui};
use imgui_vulkano_renderer::Renderer;
use imgui_winit_support::{HiDpiMode, WinitPlatform};
use std::sync::Arc;
use std::time::{Duration, Instant};
use vulkano:... | <
F: FnMut(
&mut bool,
&mut PushConstantData,
&mut blur_fade_shader::ty::PushConstantData,
&mut Ui,
) + 'static,
>(
self,
simulation: Simulation,
mut run_ui: F,
) {
let System {
event_... | main_loop | identifier_name |
dl_ocr_API.py | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 7 15:24:56 2018
@author: kboosam
"""
'''
@@ API TO CAPTURE THE DRIVING LICENSE DETAILS FROM GOOGLE VISION API
'''
# Importing libraries
#import pandas as pd
from flask import Flask, jsonify, request
import logging
from flask_cors import CORS
#import numpy as np
from ra... | DLN_valid = False if EXP_datetime <= datetime.datetime.now() else True ## check if DL is still valid
else:
imp_DATES = sorted(imp_DATES, key=lambda x: datetime.datetime.strptime(x, '%m-%d-%Y'))
EXP_datetime = datetime.datetime.strptime(imp_DATES[-1], "%m-%d-%Y")
DLN_valid = False if ... | imp_DATES = sorted(imp_DATES, key=lambda x: datetime.datetime.strptime(x, '%m/%d/%Y'))
EXP_datetime = datetime.datetime.strptime(imp_DATES[-1], "%m/%d/%Y") | random_line_split |
dl_ocr_API.py | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 7 15:24:56 2018
@author: kboosam
"""
'''
@@ API TO CAPTURE THE DRIVING LICENSE DETAILS FROM GOOGLE VISION API
'''
# Importing libraries
#import pandas as pd
from flask import Flask, jsonify, request
import logging
from flask_cors import CORS
#import numpy as np
from ra... |
#### END OF function
# main function
if __name__ == '__main__':
## DISABLE CERITIFACATE VERIFICATION FOR SSL.. some issue in Capgemini network..
'''
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS cer... | """API Call
Pandas dataframe (sent as a payload) from API Call
"""
#print("\n\n Started processing the GET request..\n")
##################
# REQUEST STRCUTRE
# imgurl
#################
try:
#req = request.json
img_path = request.args.get('imgurl', type=... | identifier_body |
dl_ocr_API.py | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 7 15:24:56 2018
@author: kboosam
"""
'''
@@ API TO CAPTURE THE DRIVING LICENSE DETAILS FROM GOOGLE VISION API
'''
# Importing libraries
#import pandas as pd
from flask import Flask, jsonify, request
import logging
from flask_cors import CORS
#import numpy as np
from ra... | ():
"""API Call
Pandas dataframe (sent as a payload) from API Call
"""
#print("\n\n Started processing the GET request..\n")
##################
# REQUEST STRCUTRE
# imgurl
#################
try:
#req = request.json
img_path = request.args.get('imgur... | get_DL | identifier_name |
dl_ocr_API.py | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 7 15:24:56 2018
@author: kboosam
"""
'''
@@ API TO CAPTURE THE DRIVING LICENSE DETAILS FROM GOOGLE VISION API
'''
# Importing libraries
#import pandas as pd
from flask import Flask, jsonify, request
import logging
from flask_cors import CORS
#import numpy as np
from ra... |
### END OF IF ELSE STRUCTURE
except Exception as e:
print(e)
print('###@@@@### Error occured while building address from SmartyStreets API response')
sentry.captureMessage(message=e, level=logging.FATAL) #printing all exceptions to the log
## make a continuous string w... | address = SSresp['addresses'][0]['api_output'][0]
## fomulate address
postal_address = {
"add_ln1": address['delivery_line_1'],
"add_ln2": '',
"city": address['components']['city_name'],
... | conditional_block |
LIST.py | #coding=utf-8
# ========================================
# 注意0:列表、字符串和元组都属于序列,但仅列表是可变对象
# 注意1:列表是一种可变(mutable)对象
# 注意2:列表方法,将直接改变列表结构
# 注意3:对列表的引用被修改,将直接改变原列表
# 注意4:在函数中引用列表,也将改变原列表
# 注意5:如果要禁止修改原列表,可在函数中生成对列表的完全拷贝
# 注意6:列表的插入和删除除非尾部元素时会涉及列表中大量元素的移动,效率较低
# 警告0:列表的可变性可能造成意想不到的bug!
# =====================================... | identifier_name | ||
LIST.py | #coding=utf-8
# ========================================
# 注意0:列表、字符串和元组都属于序列,但仅列表是可变对象
# 注意1:列表是一种可变(mutable)对象
# 注意2:列表方法,将直接改变列表结构
# 注意3:对列表的引用被修改,将直接改变原列表
# 注意4:在函数中引用列表,也将改变原列表
# 注意5:如果要禁止修改原列表,可在函数中生成对列表的完全拷贝
# 注意6:列表的插入和删除除非尾部元素时会涉及列表中大量元素的移动,效率较低
# 警告0:列表的可变性可能造成意想不到的bug!
# =====================================... | identifier_body | ||
LIST.py | #coding=utf-8
# ========================================
# 注意0:列表、字符串和元组都属于序列,但仅列表是可变对象
# 注意1:列表是一种可变(mutable)对象
# 注意2:列表方法,将直接改变列表结构
# 注意3:对列表的引用被修改,将直接改变原列表
# 注意4:在函数中引用列表,也将改变原列表
# 注意5:如果要禁止修改原列表,可在函数中生成对列表的完全拷贝
# 注意6:列表的插入和删除除非尾部元素时会涉及列表中大量元素的移动,效率较低
# 警告0:列表的可变性可能造成意想不到的bug!
# =====================================... | for i in L:
if not isinstance(i,list):
new_list.append(i)
else:
flattenList(i,new_list)
return new_list
print(flattenList(L))
# 方法三:用递归中的奇技淫巧。
func = lambda L: sum(map(func,L),[]) if isinstance(L,list) else [L]
new_str = func(L)
print(new_str)
s = [["a","b",["c",[1,[2],... | L = [["a","b",["c",[1,[2],"d"],"e"]],[3,'f'],4,"g",5]
# 递归遍历。
def flattenList(L,new_list=[]):
# 展平多重列表 | random_line_split |
LIST.py | #coding=utf-8
# ========================================
# 注意0:列表、字符串和元组都属于序列,但仅列表是可变对象
# 注意1:列表是一种可变(mutable)对象
# 注意2:列表方法,将直接改变列表结构
# 注意3:对列表的引用被修改,将直接改变原列表
# 注意4:在函数中引用列表,也将改变原列表
# 注意5:如果要禁止修改原列表,可在函数中生成对列表的完全拷贝
# 注意6:列表的插入和删除除非尾部元素时会涉及列表中大量元素的移动,效率较低
# 警告0:列表的可变性可能造成意想不到的bug!
# =====================================... | conditional_block | ||
part2.py | ################################################################################
#Michael Guerzhoy, 2016
#AlexNet implementation in TensorFlow, with weights
#Details:
#http://www.cs.toronto.edu/~guerzhoy/tf_alexnet/
#
#With code from https://github.com/ethereon/caffe-tensorflow
#Model from https://github.com/BVLC/caf... |
train_matrix = create_new_input(train_dir, 70, i)
valid_matrix = create_new_input(valid_dir, 20, i)
test_matrix = create_new_input(test_dir, counter, i)
mdict["train"+str(i)] = train_matrix
mdict["valid"+str(i)] = valid_matrix
mdict["test"+str(i)] = test_matrix
s... | counter += 1 | conditional_block |
part2.py | ################################################################################
#Michael Guerzhoy, 2016
#AlexNet implementation in TensorFlow, with weights
#Details:
#http://www.cs.toronto.edu/~guerzhoy/tf_alexnet/
#
#With code from https://github.com/ethereon/caffe-tensorflow
#Model from https://github.com/BVLC/caf... | conv3b = tf.Variable(net_data["conv3"][1])
conv3_in = conv(maxpool2, conv3W, conv3b, k_h, k_w, c_o, s_h, s_w, padding="SAME", group=group)
conv3 = tf.nn.relu(conv3_in)
#conv4
#conv(3, 3, 384, 1, 1, group=2, name='conv4')
k_h = 3; k_w = 3; c_o = 384; s_h = 1; s_w = 1; group = 2
conv4W = t... | #conv(3, 3, 384, 1, 1, name='conv3')
k_h = 3; k_w = 3; c_o = 384; s_h = 1; s_w = 1; group = 1
conv3W = tf.Variable(net_data["conv3"][0]) | random_line_split |
part2.py | ################################################################################
#Michael Guerzhoy, 2016
#AlexNet implementation in TensorFlow, with weights
#Details:
#http://www.cs.toronto.edu/~guerzhoy/tf_alexnet/
#
#With code from https://github.com/ethereon/caffe-tensorflow
#Model from https://github.com/BVLC/caf... |
def create_M_for_actor(actor, test_dir):
''' This function creates a .mat file which stores all faces
'''
mdict = {}
counter = 0
for i in range(6):
if act[i] == actor:
break
for filename in os.listdir(test_dir+actor+"/"):
counter += 1
test_matrix = creat... | ''' This function creates a .mat file which stores all faces
'''
mdict = {}
i = 0
for actor in act:
counter = 0
for filename in os.listdir(test_dir+actor+"/"):
counter += 1
train_matrix = create_new_input(train_dir, 70, i)
valid_matrix = create_new_input(valid... | identifier_body |
part2.py | ################################################################################
#Michael Guerzhoy, 2016
#AlexNet implementation in TensorFlow, with weights
#Details:
#http://www.cs.toronto.edu/~guerzhoy/tf_alexnet/
#
#With code from https://github.com/ethereon/caffe-tensorflow
#Model from https://github.com/BVLC/caf... | (dataset, datasize, n):
'''This function takes in all images in a given data set with given size and n is used to indicate the index of actor from the act list.
'''
actor_dir = act[n]+"/"
x_dummy = (random.random((datasize,)+ xdim)/255.).astype(float32)
i = x_dummy.copy()
if datasize == 70:
... | create_new_input | identifier_name |
action.py | import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.transforms
from typing import Union, List, Tuple, TypeVar, Callable, NewType, Optional
from func_helper import pip
import func_helper.func_helper.iterator as it
DataSource = Union[dict, pd.DataFrame, pd.Series]
A... |
default_kwargs = {}
_tick_params_each = {
"labelsize": 12,
"rotation": 0,
"which": "both",
"direction": "in",
"color": "black",
"labelcolor": "black"
}
_tick_params_kwargs = {
**_tick_params_each,
"labelbottom": None,
"labelleft": None,
"labeltop": None,
"labelright": No... | """
Select coordinate transform method for x and y axis.
"""
return matplotlib.transforms.blended_transform_factory(
ax.transAxes if xcoordinate is "axes" else ax.transData,
ax.transAxes if ycoordinate is "axes" else ax.transData
) | identifier_body |
action.py | import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.transforms
from typing import Union, List, Tuple, TypeVar, Callable, NewType, Optional
from func_helper import pip
import func_helper.func_helper.iterator as it
DataSource = Union[dict, pd.DataFrame, pd.Series]
A... |
elif type(d) in [list, dict]:
return pd.DataFrame(d)
else:
raise TypeError(f"{type(d)} is not available for data source.")
def generate_arg_and_kwags():
"""
Setup positional arguments and keyword arguments for plotter.
"""
def gen_func(
#df: DataSource,
option:... | return d | conditional_block |
action.py | import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.transforms
from typing import Union, List, Tuple, TypeVar, Callable, NewType, Optional
from func_helper import pip
import func_helper.func_helper.iterator as it
DataSource = Union[dict, pd.DataFrame, pd.Series]
A... | kwarg_filter = filter_dict(default_kwargs.keys())
def presetting(setting={}, **setting_kwargs):
def set_data(data_source: DataSource, option: dict={}, **option_kwargs):
"""
Parameters
----------
df: pandas.DataFrame | dict
option: dict, option... | arg_filter = get_values_by_keys(["data"]+arg_names, None) | random_line_split |
action.py | import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.transforms
from typing import Union, List, Tuple, TypeVar, Callable, NewType, Optional
from func_helper import pip
import func_helper.func_helper.iterator as it
DataSource = Union[dict, pd.DataFrame, pd.Series]
A... | (_, k, v):
"""
Return value.
"""
return v if v is not None else default
return f
def is_iterable(o):
return type(o) in [list, tuple]
def to_flatlist(d: dict) -> List[dict]:
"""
Usage
-----
d = {
"x" : (0,1,2),
"y" : [1,2],
"z" : 0
}... | f | identifier_name |
transformer.go | package transformer
import (
"sort"
"strings"
"github.com/bblfsh/sdk/v3/uast"
"github.com/bblfsh/sdk/v3/uast/nodes"
)
const optimizeCheck = true
// Transformer is an interface for transformations that operates on AST trees.
// An implementation is responsible for walking the tree and executing transformation on... |
func MapObj(src, dst ObjectOp) ObjMapping {
return objMapping{src: src, dst: dst}
}
func MapPart(vr string, m ObjMapping) ObjMapping {
src, dst := m.ObjMapping()
_, sok := src.Fields()
_, dok := dst.Fields()
if !sok && !dok {
// both contain partial op, ignore current label
return MapObj(src, dst)
} else i... | {
return mapping{src: src, dst: dst}
} | identifier_body |
transformer.go | package transformer
import (
"sort"
"strings"
"github.com/bblfsh/sdk/v3/uast"
"github.com/bblfsh/sdk/v3/uast/nodes"
)
const optimizeCheck = true
// Transformer is an interface for transformations that operates on AST trees.
// An implementation is responsible for walking the tree and executing transformation on... | }
// SetStateVar sets a sub-state variable. It returns ErrVariableRedeclared if the variable with this name already exists.
func (st *State) SetStateVar(name string, sub []*State) error {
cur, ok := st.states[name]
if ok {
return ErrVariableRedeclared.New(name, cur, sub)
}
if st.states == nil {
st.states = mak... |
// GetStateVar returns a stored sub-state from a named variable.
func (st *State) GetStateVar(name string) ([]*State, bool) {
n, ok := st.states[name]
return n, ok | random_line_split |
transformer.go | package transformer
import (
"sort"
"strings"
"github.com/bblfsh/sdk/v3/uast"
"github.com/bblfsh/sdk/v3/uast/nodes"
)
const optimizeCheck = true
// Transformer is an interface for transformations that operates on AST trees.
// An implementation is responsible for walking the tree and executing transformation on... | else if !ok {
return n, false
}
nn, err := dst.Construct(st, nil)
if err != nil {
errs = append(errs, errConstruct.Wrap(err))
return n, false
}
return nn, true
})
err := NewMultiError(errs...)
if ok {
return nn, err
}
return root, err
}
// Mappings takes multiple mappings and optimizes the p... | {
errs = append(errs, errCheck.Wrap(err))
return n, false
} | conditional_block |
transformer.go | package transformer
import (
"sort"
"strings"
"github.com/bblfsh/sdk/v3/uast"
"github.com/bblfsh/sdk/v3/uast/nodes"
)
const optimizeCheck = true
// Transformer is an interface for transformations that operates on AST trees.
// An implementation is responsible for walking the tree and executing transformation on... | () {
st.vars = nil
st.unused = nil
st.states = nil
}
// Validate should be called after a successful transformation to check if there are any errors related to unused state.
func (st *State) Validate() error {
if len(st.unused) == 0 {
return nil
}
names := make([]string, 0, len(st.unused))
for name := range s... | Reset | identifier_name |
base-chart.component.ts | import { AfterViewInit, Component, HostListener, OnDestroy } from '@angular/core';
import * as Chart from 'chart.js';
import 'rxjs-compat/add/observable/of';
import {ChartDataSets} from 'chart.js';
import { VisState } from '../_ngrx/vis.state';
import { select, Store } from '@ngrx/store';
import { IXAxis, TEMP, FIELD, ... | this.onDestroy.next(true);
this.onDestroy.unsubscribe();
}
@HostListener('window:resize')
onResize() {
this.windowWidth = window.innerWidth;
const currentPosition = this.chart.config.options.legend.position;
const newPosition = this.getLegendPosition();
if (currentPosition !== newPositi... | random_line_split | |
base-chart.component.ts | import { AfterViewInit, Component, HostListener, OnDestroy } from '@angular/core';
import * as Chart from 'chart.js';
import 'rxjs-compat/add/observable/of';
import {ChartDataSets} from 'chart.js';
import { VisState } from '../_ngrx/vis.state';
import { select, Store } from '@ngrx/store';
import { IXAxis, TEMP, FIELD, ... |
public orderPoints(array) {
return array.sort((a, b) => (a.x > b.x) ? 1 : ((b.x > a.x) ? -1 : 0));
}
private switchAxisScale(log: boolean, axis: string) {
if (!this.chart) { return; }
if (log) {
this.chart.config.options.scales[axis + 'Axes'][0].type = 'logarithmic';
this.chart.config.o... | {
const xyPoints = xVals.map( (e, i) => [e, yVals[i]] ).map( (xs) => {
return { x: xs[0], y: xs[1] };
} );
return this.orderPoints(xyPoints);
} | identifier_body |
base-chart.component.ts | import { AfterViewInit, Component, HostListener, OnDestroy } from '@angular/core';
import * as Chart from 'chart.js';
import 'rxjs-compat/add/observable/of';
import {ChartDataSets} from 'chart.js';
import { VisState } from '../_ngrx/vis.state';
import { select, Store } from '@ngrx/store';
import { IXAxis, TEMP, FIELD, ... | () {
return this.windowWidth >= 800 ? 'right' : 'bottom';
}
public updateChartAndMetaData() {
if (this.chart) {
this.switchAxisScale(this.logScaleY, 'y');
this.switchAxisScale(this.logScaleX, 'x');
this.chart.config.options.title.text = this.title;
this.chart.config.options.scales.x... | getLegendPosition | identifier_name |
base-chart.component.ts | import { AfterViewInit, Component, HostListener, OnDestroy } from '@angular/core';
import * as Chart from 'chart.js';
import 'rxjs-compat/add/observable/of';
import {ChartDataSets} from 'chart.js';
import { VisState } from '../_ngrx/vis.state';
import { select, Store } from '@ngrx/store';
import { IXAxis, TEMP, FIELD, ... |
}
public updateChart() {
if (this.chart) {
this.chart.data.datasets = this.datasets;
this.chart.update({
duration:0});
}
}
public updateChartWidth() {
this.chart.config.options.legend.position = this.getLegendPosition();
this.chart.update({
duration:0});
}
pub... | {
this.switchAxisScale(this.logScaleY, 'y');
this.switchAxisScale(this.logScaleX, 'x');
this.chart.config.options.title.text = this.title;
this.chart.config.options.scales.xAxes[0].scaleLabel.labelString = this.xAxisLabel;
this.chart.config.options.scales.yAxes[0].scaleLabel.labelString = ... | conditional_block |
api.py | # -*- coding: utf-8 -*-
"""
API documentation
https://api.crossref.org/swagger-ui/index.html
"""
"""
/funders/{funder_id} returns metadata for specified funder and its suborganizations
/prefixes/{owner_prefix} returns metadata for the DOI owner prefix
/members/{member_id} returns metadata for a CrossRef member
/types/... | return doi | random_line_split | |
api.py | # -*- coding: utf-8 -*-
"""
API documentation
https://api.crossref.org/swagger-ui/index.html
"""
"""
/funders/{funder_id} returns metadata for specified funder and its suborganizations
/prefixes/{owner_prefix} returns metadata for the DOI owner prefix
/members/{member_id} returns metadata for a CrossRef member
/types/... |
elif key_name == 'filter':
pass
elif key_name == 'n_rows':
return None
elif key_name == 'n_random':
return None
elif key_name == 'offset':
return None
elif key_name == 'order':
return sv.order
elif key_name == '... | pass | conditional_block |
api.py | # -*- coding: utf-8 -*-
"""
API documentation
https://api.crossref.org/swagger-ui/index.html
"""
"""
/funders/{funder_id} returns metadata for specified funder and its suborganizations
/prefixes/{owner_prefix} returns metadata for the DOI owner prefix
/members/{member_id} returns metadata for a CrossRef member
/types/... |
def _options_to_dict(self,filter=None,n_rows=None,n_random=None,
offset=None,query=None,sort_by=None,order=None,
facet=None,cursor=None,select=None):
#https://github.com/CrossRef/rest-api-doc#parameters
#I'm not thrilled about order ...
... | """
This function is the entry point for making requests.
"""
if params is None:
params = {}
if extras is None:
extras = {}
#Polite Pool Work
#---------------------------------------
#Example
... | identifier_body |
api.py | # -*- coding: utf-8 -*-
"""
API documentation
https://api.crossref.org/swagger-ui/index.html
"""
"""
/funders/{funder_id} returns metadata for specified funder and its suborganizations
/prefixes/{owner_prefix} returns metadata for the DOI owner prefix
/members/{member_id} returns metadata for a CrossRef member
/types/... | (self,filter=None,n_rows=None,n_random=None,
offset=None,query=None,sort_by=None,order=None,
facet=None,cursor=None,select=None):
#https://github.com/CrossRef/rest-api-doc#parameters
#I'm not thrilled about order ...
#
params = {
... | _options_to_dict | identifier_name |
scaledobject_controller.go | package controllers
import (
"context"
"fmt"
"sync"
"github.com/go-logr/logr"
autoscalingv2beta2 "k8s.io/api/autoscaling/v2beta2"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/... | const labelScaledObjectName = "scaledObjectName"
if scaledObject.Labels == nil {
scaledObject.Labels = map[string]string{labelScaledObjectName: scaledObject.Name}
} else {
value, found := scaledObject.Labels[labelScaledObjectName]
if found && value == scaledObject.Name {
return nil
}
scaledObject.Label... | }
// ensureScaledObjectLabel ensures that scaledObjectName=<scaledObject.Name> label exist in the ScaledObject
// This is how the MetricsAdapter will know which ScaledObject a metric is for when the HPA queries it.
func (r *ScaledObjectReconciler) ensureScaledObjectLabel(logger logr.Logger, scaledObject *kedav1alpha1.... | random_line_split |
scaledobject_controller.go | package controllers
import (
"context"
"fmt"
"sync"
"github.com/go-logr/logr"
autoscalingv2beta2 "k8s.io/api/autoscaling/v2beta2"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/... |
if err := kedacontrollerutil.UpdateScaledObjectStatus(r.Client, logger, scaledObject, status); err != nil {
return gvkr, err
}
logger.Info("Detected resource targeted for scaling", "resource", gvkString, "name", scaledObject.Spec.ScaleTargetRef.Name)
}
return gvkr, nil
}
// ensureHPAForScaledObjectExists... | {
status.OriginalReplicaCount = &scale.Spec.Replicas
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.