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 |
|---|---|---|---|---|
main.rs | extern crate clap;
use clap::{App, Arg};
use std::io::{stderr, stdin, stdout, Write, Read};
use std::time::{Duration, Instant};
use std::net::{SocketAddr, TcpListener, IpAddr};
const DEFAULT_BUFFER_SIZE: usize = 4096;
const DEFAULT_ITERATION_COUNT: usize = 1;
const DEFAULT_ADDRESS: &'static str = "127.0.0.1";
macro_... | (bytes: f64) -> (f64, &'static str) {
const KB: f64 = 1024.0;
const MB: f64 = KB * 1024.0;
const GB: f64 = MB * 1024.0;
const TB: f64 = GB * 1024.0;
if bytes >= TB { (bytes / TB, "TB") }
else if bytes >= GB { (bytes / GB, "GB") }
else if bytes >= MB { (bytes / MB, "MB") }
else if bytes ... | byte_to_mem_units | identifier_name |
zplsc_c_echogram.py | """
@package mi.dataset.driver.zplsc_c
@file mi/dataset/driver/zplsc_c/zplsc_c_echogram.py
@author Craig Risien/Rene Gelinas
@brief ZPLSC Echogram generation for the ooicore
Release notes:
This class supports the generation of ZPLSC-C echograms. It needs matplotlib version 1.3.1 for the code to display
the colorbar a... | (power_dict):
for channel in power_dict:
# Transpose array data so we have time on the x-axis and depth on the y-axis
power_dict[channel] = power_dict[channel].transpose()
# reverse the Y axis (so depth is measured from the surface (at the top) to the ZPLS (at the bottom)
... | _transpose_and_flip | identifier_name |
zplsc_c_echogram.py | """
@package mi.dataset.driver.zplsc_c
@file mi/dataset/driver/zplsc_c/zplsc_c_echogram.py
@author Craig Risien/Rene Gelinas
@brief ZPLSC Echogram generation for the ooicore
Release notes:
This class supports the generation of ZPLSC-C echograms. It needs matplotlib version 1.3.1 for the code to display
the colorbar a... |
sv = []
for chan in range(profile_hdr.num_channels):
# Calculate correction to Sv due to non square transmit pulse
sv_offset = zf.compute_sv_offset(profile_hdr.frequency[chan], profile_hdr.pulse_length[chan])
sv.append(self.cc.EL[chan]-2.5/self.cc.DS[chan] + _N[chan... | for chan in range(profile_hdr.num_channels):
_N.append(np.array(chan_data[chan])) | conditional_block |
zplsc_c_echogram.py | """
@package mi.dataset.driver.zplsc_c
@file mi/dataset/driver/zplsc_c/zplsc_c_echogram.py
@author Craig Risien/Rene Gelinas
@brief ZPLSC Echogram generation for the ooicore
Release notes:
This class supports the generation of ZPLSC-C echograms. It needs matplotlib version 1.3.1 for the code to display
the colorbar a... |
@staticmethod
def _display_colorbar(fig, data_axes):
# Add a colorbar to the specified figure using the data from the given axes
ax = fig.add_axes([0.965, 0.12, 0.01, 0.775])
cb = fig.colorbar(data_axes, cax=ax, use_gridspec=True)
cb.set_label('dB', fontsize=ZPLSCCPlot.font_siz... | time_format = '%Y-%m-%d\n%H:%M:%S'
time_length = data_times.size
# X axis label
# subset the xticks so that we don't plot every one
if time_length < ZPLSCCPlot.num_xticks:
ZPLSCCPlot.num_xticks = time_length
xticks = np.linspace(0, time_length, ZPLSCCPlot.num_xticks)
... | identifier_body |
zplsc_c_echogram.py | """
@package mi.dataset.driver.zplsc_c
@file mi/dataset/driver/zplsc_c/zplsc_c_echogram.py
@author Craig Risien/Rene Gelinas
@brief ZPLSC Echogram generation for the ooicore
Release notes:
This class supports the generation of ZPLSC-C echograms. It needs matplotlib version 1.3.1 for the code to display
the colorbar a... |
sea_absorb = []
for chan in range(profile_hdr.num_channels):
# Calculate absorption coeff for each frequency.
sea_absorb.append(zf.zplsc_c_absorbtion(temperature, self.params.Pressure, self.params.Salinity,
profile_hdr.frequenc... | _m.append(np.array([x for x in range(1, (profile_hdr.num_bins[chan]/self.params.Bins2Avg)+1)]))
depth_range.append(sound_speed*profile_hdr.lockout_index[0]/(2*profile_hdr.digitization_rate[0]) +
(sound_speed/4)*(((2*_m[chan]-1)*profile_hdr.range_samples[0]*self.par... | random_line_split |
index.js | /* eslint-disable no-alert */
import {
YellowBox,
View, Text, TouchableOpacity, Alert, Platform, AsyncStorage
} from 'react-native';
import _ from 'lodash';
/* eslint-disable no-plusplus */
import React, { Component } from 'react';
import DialogInput from 'react-native-dialog-input';
import firebase from 'firebase'... | extends Component {
_isMounted = false
constructor(props) {
super(props);
this.state = {
items: {},
isDialogVisible: false,
notifyEvents: this.notify(props.navigation.state.params.events),
pushNotficationToken: '',
timeToNotify: 1,
synchronizedEvents:
this.struc... | DashboardScreen | identifier_name |
index.js | /* eslint-disable no-alert */
import {
YellowBox,
View, Text, TouchableOpacity, Alert, Platform, AsyncStorage
} from 'react-native';
import _ from 'lodash';
/* eslint-disable no-plusplus */
import React, { Component } from 'react';
import DialogInput from 'react-native-dialog-input';
import firebase from 'firebase'... |
}
});
return notifyArray;
};
/**
* Schedules push notifications to user upon adjusting the timer
*/
sendPushNotification = () => {
Notifications.cancelAllScheduledNotificationsAsync();
this.state.notifyEvents.forEach((element) => {
const localNotification = {
... | {
notifyArray.push({
startDate: element.start.dateTime,
summary: element.summary,
});
} | conditional_block |
index.js | /* eslint-disable no-alert */
import {
YellowBox,
View, Text, TouchableOpacity, Alert, Platform, AsyncStorage
} from 'react-native';
import _ from 'lodash';
/* eslint-disable no-plusplus */
import React, { Component } from 'react';
import DialogInput from 'react-native-dialog-input';
import firebase from 'firebase'... |
/**
* @param {integer} time - time of the event
* restructure time in a certain format
*/
timeToString(time) {
const date = new Date(time);
return date.toISOString().split('T')[0];
}
/**
* @param {object} events - All the events the user has
* Structures all... | {
return r1.name !== r2.name;
} | identifier_body |
index.js | /* eslint-disable no-alert */
import {
YellowBox,
View, Text, TouchableOpacity, Alert, Platform, AsyncStorage
} from 'react-native';
import _ from 'lodash';
/* eslint-disable no-plusplus */
import React, { Component } from 'react';
import DialogInput from 'react-native-dialog-input';
import firebase from 'firebase'... |
/**
*
* @param {object} day - information of the current day
* formats items with information of the day
*/
loadItems = (day) => {
setTimeout(() => {
const uppderBoundForSync = 85;
const lowerBoundForSync = -15;
for (let i = lowerBoundForSync; i < uppderBoundForSync; i++) {
... | { text: 'ok' }
]);
}
} | random_line_split |
browse.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams,LoadingController, ToastController, InfiniteScroll, ActionSheetController, Content, App, IonicApp, PopoverController } from 'ionic-angular';
import { ApiProvider } from '../../../providers/api/api';
import { Sett... | () {
this.loading = await this.loadingController.create({
content: 'Loading. Please wait...',
duration: 2000000000
});
return await this.loading.present();
}
getButtonText(): string {
return `Switch ${ this.isOn ? 'Off' : 'On' }`;
}
setState(): void {
this.isOn = !this.isOn;
... | presentLoading | identifier_name |
browse.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams,LoadingController, ToastController, InfiniteScroll, ActionSheetController, Content, App, IonicApp, PopoverController } from 'ionic-angular';
import { ApiProvider } from '../../../providers/api/api';
import { Sett... |
loadCategory(category){
this.params.group= category;
this.isCategory = false;
this.reloadCourses(1);
}
async presentToast(message:string) {
const toast = await this.toastController.create({
message: message,
duration: 3000
});
toast.present();
}
loadCours... | {
const actionSheet = await this.actionSheetController.create({
title: 'Sort By',
buttons: [{
text: 'Alphabetical (asc)',
icon: 'arrow-round-up',
handler: () => {
this.params.sort = "asc";
this.reloadCourses(1);
}
}, {
... | identifier_body |
browse.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams,LoadingController, ToastController, InfiniteScroll, ActionSheetController, Content, App, IonicApp, PopoverController } from 'ionic-angular';
import { ApiProvider } from '../../../providers/api/api';
import { Sett... |
}, 3000);
});
}
search(){
this.showLoading = true;
this.loadCourses(1).subscribe(resp=>{
this.courses = resp['records'];
this.showLoading = false;
}, err => {
this.showRetry = true;
this.showLoading= false;
this.presentToast('Network error! Please check your Internet ... | {
console.log('we got a wifi connection, woohoo!');
this.networkPresent= true;
} | conditional_block |
browse.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams,LoadingController, ToastController, InfiniteScroll, ActionSheetController, Content, App, IonicApp, PopoverController } from 'ionic-angular';
import { ApiProvider } from '../../../providers/api/api';
import { Sett... | type:''
};
this.sortLib = {
asc : "Alphabetical (asc)",
desc: "Alphabetical (desc)",
recent : "Most Recent",
priceAsc : "Price (Lowest)",
priceDesc : "Price (Highest)",
c : "Online Courses",
"s-b" : "Training Sessions"
};
console.log(this.params);
console.log(this.sortLib... | group:'', | random_line_split |
lib.rs | use itertools::Itertools;
use std::convert::TryFrom;
use std::fmt;
use std::fs;
pub const N_ROUNDS: usize = 6;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Debug, Clone, PartialEq)]
pub struct Position {
coords: Vec<i32>,
}
impl Position {
/// Return linear index of position... |
#[test]
fn test_grid_indexing() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, 0, 1]);
assert_eq!(ConwayCube::Active, grid.cube_at(&pos));
let pos = Position::from(&[1, 1, 0]);
assert_eq!(ConwayCube::Inactive, grid.cube_at(... | {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
assert_eq!(3, grid.edge);
assert_eq!(5, grid.active_cubes());
} | identifier_body |
lib.rs | use itertools::Itertools;
use std::convert::TryFrom;
use std::fmt;
use std::fs;
pub const N_ROUNDS: usize = 6;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Debug, Clone, PartialEq)]
pub struct Position {
coords: Vec<i32>,
}
impl Position {
/// Return linear index of position... | // create empty nD grid, and copy initial 2D grid plane to it
// (in the middle of each dimension beyond the first two):
let max_i = InfiniteGrid::index_size(edge, dim);
let mut cubes: Vec<ConwayCube> = vec![ConwayCube::Void; max_i];
for y in 0..edge {
for x in 0..edg... | .lines()
.flat_map(|line| line.trim().chars().map(ConwayCube::from_char))
.collect(); | random_line_split |
lib.rs | use itertools::Itertools;
use std::convert::TryFrom;
use std::fmt;
use std::fs;
pub const N_ROUNDS: usize = 6;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Debug, Clone, PartialEq)]
pub struct Position {
coords: Vec<i32>,
}
impl Position {
/// Return linear index of position... | () {
// the full N_ROUNDS takes a while so:
let n_rounds = 1; // = N_ROUNDS;
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 4).unwrap();
let mut n_active: usize = 0;
for (i, g) in grid.iter().enumerate() {
if i >= n_rounds - 1 {
n_active = g.active_... | test_6_rounds_4d | identifier_name |
lib.rs | use itertools::Itertools;
use std::convert::TryFrom;
use std::fmt;
use std::fs;
pub const N_ROUNDS: usize = 6;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Debug, Clone, PartialEq)]
pub struct Position {
coords: Vec<i32>,
}
impl Position {
/// Return linear index of position... | else { 848 };
assert_eq!(expect, n_active);
}
}
| { 3*4 + 5 + 3*4 } | conditional_block |
encoder.rs | //! Encoding functionality
//!
//!
pub use crate::encoder_config::{AV1EncoderConfig, AomUsage, BitstreamProfile, TileCodingMode};
use crate::common::AOMCodec;
use crate::ffi::*;
use std::mem::{self, MaybeUninit};
use std::ptr;
use av_data::frame::{Frame, FrameBufferConv, MediaKind};
use av_data::packet::Packet;
use... | (&mut self) -> Result<()> {
if self.enc.is_none() {
self.cfg
.get_encoder()
.map(|enc| {
self.enc = Some(enc);
})
.map_err(|_err| Error::ConfigurationIncomplete)
} else {
... | configure | identifier_name |
encoder.rs | //! Encoding functionality
//!
//!
pub use crate::encoder_config::{AV1EncoderConfig, AomUsage, BitstreamProfile, TileCodingMode};
use crate::common::AOMCodec;
use crate::ffi::*;
use std::mem::{self, MaybeUninit};
use std::ptr;
use av_data::frame::{Frame, FrameBufferConv, MediaKind};
use av_data::packet::Packet;
use... |
}
| {
use super::AV1_DESCR;
use av_codec::common::CodecList;
use av_codec::encoder::*;
use av_codec::error::*;
use std::sync::Arc;
let encoders = Codecs::from_list(&[AV1_DESCR]);
let mut ctx = Context::by_name(&encoders, "av1").unwrap();
let w = 200;
... | identifier_body |
encoder.rs | //! Encoding functionality
//!
//!
pub use crate::encoder_config::{AV1EncoderConfig, AomUsage, BitstreamProfile, TileCodingMode};
use crate::common::AOMCodec;
use crate::ffi::*;
use std::mem::{self, MaybeUninit};
use std::ptr;
use av_data::frame::{Frame, FrameBufferConv, MediaKind};
use av_data::packet::Packet;
use... |
let mut e = setup(w, h, &t);
let mut f = setup_frame(w, h, &t);
let mut out = 0;
// TODO write some pattern
for i in 0..100 {
e.encode(&f).unwrap();
f.t.pts = Some(i);
// println!("{:#?}", f);
loop {
let p = e.get_... | random_line_split | |
example_scenes.py | from manimlib import *
import numpy as np
# To watch one of these scenes, run the following:
# manimgl example_scenes.py OpeningManimExample
# Use -s to skip to the end and just save the final frame
# Use -w to write the animation to a file
# Use -o to write it to a file and open it once done
# Use -n <number> to skip... | self.textbox = Textbox()
self.checkbox = Checkbox()
self.color_picker = ColorSliders()
self.panel = ControlPanel(
Text("Text", font_size=24), self.textbox, Line(),
Text("Show/Hide Text", font_size=24), self.checkbox, Line(),
Text("Color of Text", font_... | def setup(self): | random_line_split |
example_scenes.py | from manimlib import *
import numpy as np
# To watch one of these scenes, run the following:
# manimgl example_scenes.py OpeningManimExample
# Use -s to skip to the end and just save the final frame
# Use -w to write the animation to a file
# Use -o to write it to a file and open it once done
# Use -n <number> to skip... |
class TexTransformExample(Scene):
def construct(self):
# Tex to color map
t2c = {
"A": BLUE,
"B": TEAL,
"C": GREEN,
}
# Configuration to pass along to each Tex mobject
kw = dict(font_size=72, t2c=t2c)
lines = VGroup(
... | text = Text("Here is a text", font="Consolas", font_size=90)
difference = Text(
"""
The most important difference between Text and TexText is that\n
you can change the font more easily, but can't use the LaTeX grammar
""",
font="Arial", font_size=24,
... | identifier_body |
example_scenes.py | from manimlib import *
import numpy as np
# To watch one of these scenes, run the following:
# manimgl example_scenes.py OpeningManimExample
# Use -s to skip to the end and just save the final frame
# Use -w to write the animation to a file
# Use -o to write it to a file and open it once done
# Use -n <number> to skip... |
else:
new_text.set_opacity(0)
old_text.become(new_text)
text.add_updater(text_updater)
self.add(MotionMobject(text))
self.textbox.set_value("Manim")
# self.wait(60)
# self.embed()
# See https://github.com/3b1b/videos for many, many mo... | new_text.set_fill(
color=self.color_picker.get_picked_color(),
opacity=self.color_picker.get_picked_opacity()
) | conditional_block |
example_scenes.py | from manimlib import *
import numpy as np
# To watch one of these scenes, run the following:
# manimgl example_scenes.py OpeningManimExample
# Use -s to skip to the end and just save the final frame
# Use -w to write the animation to a file
# Use -o to write it to a file and open it once done
# Use -n <number> to skip... | (x, y):
# Switch from manim coords to axes coords
xa, ya = axes.point_to_coords(np.array([x, y, 0]))
return xa**4 + ya**4 - 4
new_curve = ImplicitFunction(func)
new_curve.match_style(circle)
circle.rotate(angle_of_vector(new_curve.get_start())) # Align
... | func | identifier_name |
Skycam.py | from __future__ import division
from math import sin, cos, acos, asin, degrees, pi
import serial
from time import sleep
import numpy as np
from scipy.interpolate import splprep, splev, splrep
class Skycam:
''' Represents entire 3-node and camera system. Contains methods to calculate
and initialize paths, c... | (self, ustart, s, dl, tol=.01):
''' Perform a binary search to find parametrized location of point.
Inputs:
ustart: (float)
s: (spline object)
dl: (float)
tol: (float)
Returns:
Reassigns middle and endpoint... | binary_search | identifier_name |
Skycam.py | from __future__ import division
from math import sin, cos, acos, asin, degrees, pi
import serial
from time import sleep
import numpy as np
from scipy.interpolate import splprep, splev, splrep
class Skycam:
''' Represents entire 3-node and camera system. Contains methods to calculate
and initialize paths, c... |
def go_path(self, start):
'''Send appropriate movement commands for loaded path.
Input:
start: (int) index of path at which to begin sending commands
'''
#TODO: Implement save point
while (not self.direct and not self.pause):
for i in xrang... | ''' Generate a new list of points based on waypoints.
Inputs:
waypoints: (list of tuples of floats): points the path should
bring the camera to
steps: (int) number of steps in which to complete the path
Returns:
Calls ... | identifier_body |
Skycam.py | from __future__ import division
from math import sin, cos, acos, asin, degrees, pi
import serial
from time import sleep
import numpy as np
from scipy.interpolate import splprep, splev, splrep
class Skycam:
''' Represents entire 3-node and camera system. Contains methods to calculate
and initialize paths, c... |
return totl
def tighten(self):
''' Calibrate node lengths to current position of camera.
Enter ' ' to tighten
Enter 's' to accept node length
'''
while True:
input = raw_input('Tightening Node A')
if input == ' ':
s... | totl += distance(point, ipoint)
ipoint = point | conditional_block |
Skycam.py | from __future__ import division
from math import sin, cos, acos, asin, degrees, pi
import serial
from time import sleep
import numpy as np
from scipy.interpolate import splprep, splev, splrep
class Skycam:
''' Represents entire 3-node and camera system. Contains methods to calculate
and initialize paths, c... | Calls load_path method on list of generated spline points
'''
xpoints = [point[0] for point in waypoints]
ypoints = [point[1] for point in waypoints]
zpoints = [point[2] for point in waypoints]
# spline parameters
s = 2.0 # smoothness
k = 1 # spl... | steps: (int) number of steps in which to complete the path
Returns: | random_line_split |
kafka.go | // Copyright (c) 2019 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
package messagebus
import (
"crypto/sha512"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"os"
"os/signal"
"syscall"
"github.com... | else {
defer func() {
err := deleteTopic(client.broker, topic)
if err != nil {
logrus.Error("unable to delete topic in kafka : ", err)
return
}
}()
err := createTopic(client.broker, topic)
if err != nil {
logrus.Error("unable to create topic in kafka : ", err)
return
}
// listening... | {
logrus.Warn("topic and message type already registered")
} | conditional_block |
kafka.go | // Copyright (c) 2019 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
package messagebus
import (
"crypto/sha512"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"os"
"os/signal"
"syscall"
"github.com... |
// PublishSync push a message to message broker topic synchronously
func (client *KafkaClient) PublishSync(publishBuilder *PublishBuilder) error {
// send message
_, _, err := client.syncProducer.SendMessage(&sarama.ProducerMessage{
Timestamp: time.Now().UTC(),
Value: &PublishBuilderEntry{
PublishBuilder: *p... | Topic: constructTopic(client.realm, publishBuilder.topic),
}
} | random_line_split |
kafka.go | // Copyright (c) 2019 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
package messagebus
import (
"crypto/sha512"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"os"
"os/signal"
"syscall"
"github.com... | (broker *sarama.Broker, topicName string) error {
request := sarama.DeleteTopicsRequest{
Timeout: time.Second * topicTimeout,
Topics: []string{topicName},
}
_, err := broker.DeleteTopics(&request)
return err
}
// unmarshal unmarshal received message into message struct
func unmarshal(consumerMessage *sarama.... | deleteTopic | identifier_name |
kafka.go | // Copyright (c) 2019 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
package messagebus
import (
"crypto/sha512"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"os"
"os/signal"
"syscall"
"github.com... |
// runCallback run callback function when receive a message
func runCallback(receivedMessage *Message, consumerMessage *sarama.ConsumerMessage) {
callback := subscribeMap[consumerMessage.Topic][receivedMessage.MessageType]
if callback == nil {
logrus.Error(fmt.Sprintf("callback not found for topic : %s, message ... | {
if subscribeMap == nil {
subscribeMap = make(map[string]map[string]func(message *Message, err error))
}
if callbackMap, isTopic := subscribeMap[topic]; isTopic {
if _, isMsgType := callbackMap[messageType]; isMsgType {
return true
}
}
newCallbackMap := make(map[string]func(message *Message, err error)... | identifier_body |
pathfinding.py | import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import cv2
from pathfinder import pathfinder
import random
import time
import math
from multiprocessing import Process, Manager
import os
import argparse
from libtiff import TIFF
from osgeo import osr, ogr
# from tqdm import t... | = 30 # 240
else:
length_part = 5
degree_delta = 90 # 20
print("读取TIFF文件中...")
try:
tif = TIFF.open(args.gridMap, mode='r') # 打開tiff文件進行讀取
except:
print("输入的路径有误!")
im = tif.read_image()
print("正在分析各类地块...")
class4 = cv2.inRange(im, 3.9, 4.1)
class1 = c... | :
length_part = 20
degree_delta | conditional_block |
pathfinding.py | import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import cv2
from pathfinder import pathfinder
import random
import time
import math
from multiprocessing import Process, Manager
import os
import argparse
from libtiff import TIFF
from osgeo import osr, ogr
# from tqdm import t... | , gridMap, background, openset_size, length_part, degree_delta,
roads=None):
# time1 = time.time()
# gridMap = np.load('../res/sampled_sketch.npy')
# gridMap = np.load('map.npy')
# time2 = time.time()
# print("图片加载完毕,耗时{}".format(time2 - time1))
# maze = cv2.inRange(gridMap, 2.9, 3.1)
... | neigh_range | identifier_name |
pathfinding.py | import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import cv2
from pathfinder import pathfinder
import random
import time
import math
from multiprocessing import Process, Manager
import os
import argparse
from libtiff import TIFF
from osgeo import osr, ogr
# from tqdm import t... | t, end, neigh_range, gridMap, background, openset_size, length_part, degree_delta,
roads=None):
# time1 = time.time()
# gridMap = np.load('../res/sampled_sketch.npy')
# gridMap = np.load('map.npy')
# time2 = time.time()
# print("图片加载完毕,耗时{}".format(time2 - time1))
# maze = cv2.inRange(gr... | e_generator(gridMap):
s_x, s_y = point_generator(gridMap, 1)
e_x, e_y = point_generator(gridMap, 1)
return s_x, s_y, e_x, e_y
def run(_ver, _return_dict, star | identifier_body |
pathfinding.py | import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import cv2
from pathfinder import pathfinder
import random
import time
import math
from multiprocessing import Process, Manager
import os
import argparse
from libtiff import TIFF
from osgeo import osr, ogr
# from tqdm import t... | cv2.circle(background, p, 10, (0, 0, 255), 5)
for index, p in enumerate(path):
if index == 0:
continue
p2 = p
cv2.line(background, p1, p2, (255, 0, 0), 40)
p1 = p
for p in path:
cv2.circle(background, p, 10, (0, 0, 0), 40)
# for p in finder.close_s... | random_line_split | |
get_tips_nonlocal.py | #use the nonlocal topological method to detect tips.
# also records topologcially preserved values.
#Tim Tyree
#9.13.2021
from skimage import measure
from numba import jit, njit
from numba.typed import List
import numpy as np, os
from . import *
# from .intersection import *
from scipy.interpolate import interp2d
from... | (mat, pad, channel_no=3):
''''''
return np.pad(array = mat, pad_width = pad, mode = 'wrap')[...,pad:pad+channel_no]
# width, height = mat.shape[:2]
# padded_width = 512 + pad #pixels
# padded_mat = np.pad(array = mat, pad_width = pad, mode = 'wrap')
# return padded_mat[...,2:5]
# @njit
def pad_... | pad_matrix | identifier_name |
get_tips_nonlocal.py | #use the nonlocal topological method to detect tips.
# also records topologcially preserved values.
#Tim Tyree
#9.13.2021
from skimage import measure
from numba import jit, njit
from numba.typed import List
import numpy as np, os
from . import *
# from .intersection import *
from scipy.interpolate import interp2d
from... |
# ################################
# deprecated
# ################################
#deprecated - needs parameters
# def get_contours(img_nxt,img_inc):
# contours_raw = measure.find_contours(img_nxt, level=0.5,fully_connected='low',positive_orientation='low')
# contours_inc = measure.find_contours(img_inc, l... | '''get the gradient direction field, N
out_Nx, out_Ny = get_grad_direction(texture)
'''
height, width = texture.shape
out_Nx = np.zeros_like(texture, dtype=np.float64)
out_Ny = np.zeros_like(texture, dtype=np.float64)
DX = 1/0.025; DY = 1/0.025;
for y in range(height):
for x in range... | identifier_body |
get_tips_nonlocal.py | #use the nonlocal topological method to detect tips.
# also records topologcially preserved values.
#Tim Tyree
#9.13.2021
from skimage import measure
from numba import jit, njit
from numba.typed import List
import numpy as np, os
from . import *
# from .intersection import *
from scipy.interpolate import interp2d
from... | s1_mapped_lst.append(lst_S1)
s2_mapped_lst.append(lst_S2)
else:
#just append to the previous entry in the s1 and s2 lists if the contour isn't already there
s1_mapped_lst[min_index].append(S1)
... | lst_S1 = []#List()
lst_S1.append(S1)
lst_S2 = []#List()
lst_S2.append(S2) | random_line_split |
get_tips_nonlocal.py | #use the nonlocal topological method to detect tips.
# also records topologcially preserved values.
#Tim Tyree
#9.13.2021
from skimage import measure
from numba import jit, njit
from numba.typed import List
import numpy as np, os
from . import *
# from .intersection import *
from scipy.interpolate import interp2d
from... |
return out_Nx, out_Ny
# ################################
# deprecated
# ################################
#deprecated - needs parameters
# def get_contours(img_nxt,img_inc):
# contours_raw = measure.find_contours(img_nxt, level=0.5,fully_connected='low',positive_orientation='low')
# contours_inc = measur... | out_Nx[y,x] = Nx/norm
out_Ny[y,x] = Ny/norm | conditional_block |
details.js | $(function(){
$(".header").load("../html/common/header.html")
$(".footer").load("../html/common/footer02.html")
$(".souS").load("../html/common/shousuolan.html")
$(".nav").load("../html/common/nav2016.html")
})
$(function(e){
// $(".jqzoomDiv ul li").each(function(){
// $(this).mouseover(function(){
// $(".zoom... | min=parseInt(time/3600000*60)%60
var sec=parseInt(time/3600000*24*60)%60
timer.find("em").eq(0).html(hour)
timer.find("em").eq(1).html(min)
timer.find("em").eq(2).html(sec)
// console.log(time)
},500)
})
//添加商品按钮
$(function(){
var oAdd=$(".buyAdd")
var oRed=$(".buyReduce")
var oValue=$("#buyNum")
oAdd.css... | $(".addCart").css("cursor","pointer")
var num1=0;num2=0;
if($.cookie("carList1")){
num1=parseInt(JSON.parse($.cookie("carList1")).iNum)
}
if($.cookie("carList2")){
num2=parseInt(JSON.parse($.cookie("carList2")).iNum)
}
//判断是否存在cookie
// if($.cookie("carList")){
// for(var m in JSON.parse($.cookie("carList")... | identifier_body |
details.js | $(function(){
$(".header").load("../html/common/header.html")
$(".footer").load("../html/common/footer02.html")
$(".souS").load("../html/common/shousuolan.html")
$(".nav").load("../html/common/nav2016.html")
})
$(function(e){
// $(".jqzoomDiv ul li").each(function(){
// $(this).mouseover(function(){
// $(".zoom... | .id
$(".addCart").css("cursor","pointer")
var num1=0;num2=0;
if($.cookie("carList1")){
num1=parseInt(JSON.parse($.cookie("carList1")).iNum)
}
if($.cookie("carList2")){
num2=parseInt(JSON.parse($.cookie("carList2")).iNum)
}
//判断是否存在cookie
// if($.cookie("carList")){
// for(var m in JSON.parse($.cookie("carLi... | odid=cl | identifier_name |
details.js | $(function(){
$(".header").load("../html/common/header.html")
$(".footer").load("../html/common/footer02.html")
$(".souS").load("../html/common/shousuolan.html")
$(".nav").load("../html/common/nav2016.html")
})
$(function(e){
// $(".jqzoomDiv ul li").each(function(){
// $(this).mouseover(function(){
// $(".zoom... | num1=parseInt(JSON.parse($.cookie("carList1")).iNum)
}
if($.cookie("carList2")){
num2=parseInt(JSON.parse($.cookie("carList2")).iNum)
}
//判断是否存在cookie
// if($.cookie("carList")){
// for(var m in JSON.parse($.cookie("carList"))){
// num+=parseInt(JSON.parse($.cookie("carList"))[m].iNum)
// //这里有bug每次累加是2个加起... | $(".addCart").css("cursor","pointer")
var num1=0;num2=0;
if($.cookie("carList1")){ | random_line_split |
reduc_spec.py | import in_out
import numpy as np
from copy import deepcopy as dc
from IPython.core.debugger import Tracer; debug_here=Tracer()
from matplotlib.pyplot import *
# Useful trig functions
def asind(x):
return np.arcsin(x)*180/np.pi
def sind(x):
return np.sin(x*np.pi/180)
def cosd(x):
return np.cos(x*np.pi/180)
... | (self):
"""Scale by P->TRJ factor"""
# Convert to RJ temperature
#fac=planck.I2Ta(self.f*1e6,1).value
fac = planck(self.f*1e6, 1)
fac=fac/fac[0]
self.spec=self.spec*np.tile(fac,(self.spec.shape[0],1))
def _getscanind(self):
"""Identify start/stop indi... | P2T | identifier_name |
reduc_spec.py | import in_out
import numpy as np
from copy import deepcopy as dc
from IPython.core.debugger import Tracer; debug_here=Tracer()
from matplotlib.pyplot import *
# Useful trig functions
def asind(x):
return np.arcsin(x)*180/np.pi
def sind(x):
return np.sin(x*np.pi/180)
def cosd(x):
return np.cos(x*np.pi/180)
... | if ind.size>0:
# If it exists, append it
cblk=np.append(cblk,ind[-1])
# Find trailing cal stare
ind=np.where(cs>=se)[0]
if ind.size>0:
# If it exists, append it
cblk=np.appen... | ind=np.where(ce<=ss)[0] | random_line_split |
reduc_spec.py | import in_out
import numpy as np
from copy import deepcopy as dc
from IPython.core.debugger import Tracer; debug_here=Tracer()
from matplotlib.pyplot import *
# Useful trig functions
def asind(x):
return np.arcsin(x)*180/np.pi
def sind(x):
return np.sin(x*np.pi/180)
def cosd(x):
return np.cos(x*np.pi/180)
... |
return
for k in range(self.nscan):
# Each scan
ind=self.getscanind(k)
for j,val in enumerate(np.unique(self.za[ind])):
# Find contiguous blocks
doind=ind[np.where(self.za[ind]==val)]
dx=doind-np.r... | p=np.polyfit(x[scanind],y[scanind],deg=deg)
# Don't remove mean
p[-1]=0
self.spec[:,k]=self.spec[:,k]-np.poly1d(p)(x) | conditional_block |
reduc_spec.py | import in_out
import numpy as np
from copy import deepcopy as dc
from IPython.core.debugger import Tracer; debug_here=Tracer()
from matplotlib.pyplot import *
# Useful trig functions
def asind(x):
return np.arcsin(x)*180/np.pi
def sind(x):
return np.sin(x*np.pi/180)
def cosd(x):
return np.cos(x*np.pi/180)
... |
def reduc(self,zarange=[20,50]):
"""Main reduction script. Elrange is two element list or tuple over
which to perform airmass regression (inclusive)"""
# First, take out a secular gain drift for each constant elevation
# stare. Fit P(t) to each channel in a contig... | """Zenith angle in degrees to airmass"""
return 1/cosd(x) | identifier_body |
_ToolBar.ts | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information.
/// <reference path="../../Core.d.ts" />
import Animations = require("../../Animations");
import _Base = require("../../Core/_Base");
import _BaseUtils = require("..... |
this._cachedClosedHeight = this._commandingSurface.getBoundingRects().commandingSurface.height;
if (wasOpen) {
this._synchronousOpen();
}
}
return this._cachedClosedHeight;
}
private _updateDomImpl_renderOpened(): void {
// Measure ... | {
this._synchronousClose();
} | conditional_block |
_ToolBar.ts | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information.
/// <reference path="../../Core.d.ts" />
import Animations = require("../../Animations");
import _Base = require("../../Core/_Base");
import _BaseUtils = require("..... |
/// <field type="WinJS.Binding.List" locid="WinJS.UI.ToolBar.data" helpKeyword="WinJS.UI.ToolBar.data">
/// Gets or sets the Binding List of WinJS.UI.Command for the ToolBar.
/// </field>
get data() {
return this._commandingSurface.data;
}
set data(value: BindingList.List<_Command.ICom... | {
return this._dom.root;
} | identifier_body |
_ToolBar.ts | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information.
/// <reference path="../../Core.d.ts" />
import Animations = require("../../Animations");
import _Base = require("../../Core/_Base");
import _BaseUtils = require("..... | if (!label) {
root.setAttribute("aria-label", strings.ariaLabel);
}
// Create element for commandingSurface and reparent any declarative Commands.
// The CommandingSurface constructor will parse child elements as AppBarCommands.
var commandingSurfaceEl = document.cre... | root.setAttribute("role", "menubar");
}
var label = root.getAttribute("aria-label"); | random_line_split |
_ToolBar.ts | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information.
/// <reference path="../../Core.d.ts" />
import Animations = require("../../Animations");
import _Base = require("../../Core/_Base");
import _BaseUtils = require("..... | (id: string): _Command.ICommand {
/// <signature helpKeyword="WinJS.UI.ToolBar.getCommandById">
/// <summary locid="WinJS.UI.ToolBar.getCommandById">
/// Retrieves the command with the specified ID from this ToolBar.
/// If more than one command is found, this method returns the first co... | getCommandById | identifier_name |
update.py | import json
import os
from pathlib import Path
from shutil import rmtree
from subprocess import DEVNULL, PIPE, CalledProcessError, run # nosec
from tempfile import TemporaryDirectory
from typing import Any, Dict, Optional, Set
import click
import typer
from cookiecutter.generate import generate_files
from git import ... | (diff: str, expanded_dir_path: Path):
try:
run(
["git", "apply", "-3"],
input=diff.encode(),
stderr=PIPE,
stdout=PIPE,
check=True,
cwd=expanded_dir_path,
)
except CalledProcessError as error:
typer.secho(error.stderr... | _apply_three_way_patch | identifier_name |
update.py | import json
import os
from pathlib import Path
from shutil import rmtree
from subprocess import DEVNULL, PIPE, CalledProcessError, run # nosec
from tempfile import TemporaryDirectory
from typing import Any, Dict, Optional, Set
import click
import typer
from cookiecutter.generate import generate_files
from git import ... |
def _is_git_repo(directory: Path):
# Taken from https://stackoverflow.com/a/16925062
# This works even if we are in a sub folder in a git
# repo
output = run(
["git", "rev-parse", "--is-inside-work-tree"], stdout=PIPE, stderr=DEVNULL, cwd=directory
)
if b"true" in output.stdout:
... | run(["git", "diff", "--no-index", str(old_main_directory), str(new_main_directory)]) | identifier_body |
update.py | import json
import os
from pathlib import Path
from shutil import rmtree
from subprocess import DEVNULL, PIPE, CalledProcessError, run # nosec
from tempfile import TemporaryDirectory
from typing import Any, Dict, Optional, Set
import click
import typer
from cookiecutter.generate import generate_files
from git import ... |
else:
_apply_patch_with_rejections(diff, expanded_dir_path)
def _apply_project_updates(
old_main_directory: Path,
new_main_directory: Path,
project_dir: Path,
skip_update: bool,
skip_apply_ask: bool,
) -> bool:
diff = _get_diff(old_main_directory, new_main_directory)
if not s... | _apply_three_way_patch(diff, expanded_dir_path) | conditional_block |
update.py | import json
import os
from pathlib import Path
from shutil import rmtree
from subprocess import DEVNULL, PIPE, CalledProcessError, run # nosec
from tempfile import TemporaryDirectory
from typing import Any, Dict, Optional, Set
import click
import typer
from cookiecutter.generate import generate_files
from git import ... | json_dumps,
)
try:
import toml # type: ignore
except ImportError: # pragma: no cover
toml = None # type: ignore
CruftState = Dict[str, Any]
@example(skip_apply_ask=False)
@example()
def update(
project_dir: Path = Path("."),
cookiecutter_input: bool = False,
skip_apply_ask: bool = True,
... | generate_cookiecutter_context,
get_cookiecutter_repo,
get_cruft_file,
is_project_updated, | random_line_split |
main.rs | //#![no_std]
#![feature(termination_trait)]
extern crate megaton_hammer;
extern crate byteorder;
extern crate image;
extern crate math;
use megaton_hammer::ipcdefs as megaton_ipc;
use byteorder::{ReadBytesExt, WriteBytesExt, LE, ByteOrder};
use megaton_hammer::kernel::{TransferMemory, KObject, FromKObject, Event, svc... |
GpuBuffer {
nvmap_handle: create.handle,
size: mem.len() * std::mem::size_of::<BufferMemory>(),
alignment: 0x1000,
kind: 0
}
};
let buffers = {
let mut alloc = NvMapIocAllocArgs {
handle: gpu_buffer.nvmap_handle,
h... | {
return Err(MyError::IoctlError(ret));
} | conditional_block |
main.rs | //#![no_std]
#![feature(termination_trait)]
extern crate megaton_hammer;
extern crate byteorder;
extern crate image;
extern crate math;
use megaton_hammer::ipcdefs as megaton_ipc;
use byteorder::{ReadBytesExt, WriteBytesExt, LE, ByteOrder};
use megaton_hammer::kernel::{TransferMemory, KObject, FromKObject, Event, svc... | (&self) -> &[u32] {
&self.0[..]
}
}
impl std::ops::DerefMut for BufferMemory {
fn deref_mut(&mut self) -> &mut [u32] {
&mut self.0[..]
}
}
const NVMAP_IOC_CREATE: u32 = 0xC0080101;
const NVMAP_IOC_FROM_ID: u32 = 0xC0080103;
const NVMAP_IOC_ALLOC: u32 = 0xC0200104;
const NVMAP_IOC_FREE: u32... | deref | identifier_name |
main.rs | //#![no_std]
#![feature(termination_trait)]
extern crate megaton_hammer;
extern crate byteorder;
extern crate image;
extern crate math;
use megaton_hammer::ipcdefs as megaton_ipc;
use byteorder::{ReadBytesExt, WriteBytesExt, LE, ByteOrder};
use megaton_hammer::kernel::{TransferMemory, KObject, FromKObject, Event, svc... | parcel.write_u32(0x54); parcel.write_u32(0); // unknown, but always those values
parcel.write_u32(0x588bbba9); parcel.write_u32(0); // Timestamp, u64
parcel.write_u32(1); // unknown, but always those values
parcel.write_u32(0);
parcel.write_u32(0);
... | random_line_split | |
main.rs | //#![no_std]
#![feature(termination_trait)]
extern crate megaton_hammer;
extern crate byteorder;
extern crate image;
extern crate math;
use megaton_hammer::ipcdefs as megaton_ipc;
use byteorder::{ReadBytesExt, WriteBytesExt, LE, ByteOrder};
use megaton_hammer::kernel::{TransferMemory, KObject, FromKObject, Event, svc... |
}
impl From<megaton_hammer::error::Error> for MyError {
fn from(err: megaton_hammer::error::Error) -> MyError {
MyError::MegatonError(err)
}
}
fn main() -> std::result::Result<(), MyError> {
// Let's get ferris to show up on my switch.
println!("Initialize NV");
let nvdrv = nns::nvdrv::I... | {
MyError::ImageError(err)
} | identifier_body |
multi.rs | // Copyright 2021 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
//! The multi-threaded worker, which is used when there are multiple worker
//! threads configured. This worker parses buffers to produce requests, sends
//! the requests to the storage worke... | _storage: PhantomData<Storage>,
_request: PhantomData<Request>,
_response: PhantomData<Response>,
}
impl<Storage, Parser, Request, Response> MultiWorkerBuilder<Storage, Parser, Request, Response> {
/// Create a new builder from the provided config and parser.
pub fn new<T: WorkerConfig>(config: &T,... | poll: Poll,
timeout: Duration, | random_line_split |
multi.rs | // Copyright 2021 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
//! The multi-threaded worker, which is used when there are multiple worker
//! threads configured. This worker parses buffers to produce requests, sends
//! the requests to the storage worke... |
// handle write events before read events to reduce write buffer
// growth if there is also a readable event
if event.is_writable() {
WORKER_EVENT_WRITE.increment();
self.do_write(token);
}
// read events are handled last
if event.is_readable() ... | {
WORKER_EVENT_ERROR.increment();
self.handle_error(token);
} | conditional_block |
multi.rs | // Copyright 2021 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
//! The multi-threaded worker, which is used when there are multiple worker
//! threads configured. This worker parses buffers to produce requests, sends
//! the requests to the storage worke... |
}
/// Represents a finalized request/response worker which is ready to be run.
pub struct MultiWorker<Storage, Parser, Request, Response> {
nevent: usize,
parser: Parser,
poll: Poll,
timeout: Duration,
session_queue: Queues<(), Session>,
signal_queue: Queues<(), Signal>,
_storage: PhantomD... | {
MultiWorker {
nevent: self.nevent,
parser: self.parser,
poll: self.poll,
timeout: self.timeout,
signal_queue,
_storage: PhantomData,
storage_queue,
session_queue,
}
} | identifier_body |
multi.rs | // Copyright 2021 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
//! The multi-threaded worker, which is used when there are multiple worker
//! threads configured. This worker parses buffers to produce requests, sends
//! the requests to the storage worke... | (&mut self, sessions: &mut Vec<TrackedItem<Session>>) {
self.session_queue.try_recv_all(sessions);
for session in sessions.drain(..).map(|v| v.into_inner()) {
let pending = session.read_pending();
trace!(
"new session: {:?} with {} bytes pending in read buffer",
... | handle_new_sessions | identifier_name |
scanner.go | package ipv4
import (
"code.google.com/p/go-uuid/uuid"
"fmt"
"github.com/thejerf/suture"
log "gopkg.in/inconshreveable/log15.v2"
logext "gopkg.in/inconshreveable/log15.v2/ext"
"net"
"strconv"
"sync"
"time"
)
const (
numIPv4Checkers = 100
)
var (
ignoredIPv4Interfaces = map[string]struct{}{
// DARWIN
"... |
// Unlock unlocks the provided IP, such that it will no longer be ignored in
// future scans.
func (s *Scanner) Unlock(ip net.IP) {
s.slock.Lock()
defer s.slock.Unlock()
delete(s.activeServicesByIP, ip.String())
s.log.Debug("ipv4 scanner unlocked IP", "ip", ip.String())
}
func (s *Scanner) getMatchingDescription... | {
if len(s.descriptionsByID) == 0 {
s.log.Debug("scanner has no descriptions, ignoring scan")
return map[string][]string{}
}
s.log.Debug("ip4v scanner beginning scan", "interfaces", s.interfaces, "target_descriptions", s.descriptionsByID)
foundServices := make(map[string][]string)
flock := sync.Mutex{} // pro... | identifier_body |
scanner.go | package ipv4
import (
"code.google.com/p/go-uuid/uuid"
"fmt"
"github.com/thejerf/suture"
log "gopkg.in/inconshreveable/log15.v2"
logext "gopkg.in/inconshreveable/log15.v2/ext"
"net"
"strconv"
"sync"
"time"
)
const (
numIPv4Checkers = 100
)
var (
ignoredIPv4Interfaces = map[string]struct{}{
// DARWIN
"... |
s.interfaces = foundInterfaces
if len(newInterfaces) > 0 {
names := make([]string, len(newInterfaces))
i := 0
for name := range newInterfaces {
names[i] = name
i++
}
s.log.Debug("new IPv4 interfaces found", "interfaces", names)
}
return nil
}
// incrementIP increments an IPv4 address
func increme... | {
names := make([]string, len(s.interfaces))
i := 0
for name := range s.interfaces {
names[i] = name
}
s.log.Warn("STUB: IPv4 interfaces have disappeared, but handling logic is unimplemented! Services on the missing interfaces may still be active", "deleted_interfaces", names)
} | conditional_block |
scanner.go | package ipv4
import (
"code.google.com/p/go-uuid/uuid"
"fmt"
"github.com/thejerf/suture"
log "gopkg.in/inconshreveable/log15.v2"
logext "gopkg.in/inconshreveable/log15.v2/ext"
"net"
"strconv"
"sync"
"time"
)
const (
numIPv4Checkers = 100
)
var (
ignoredIPv4Interfaces = map[string]struct{}{
// DARWIN
"... | break
}
}
}
// An IContinuousScanner is a Scanner that scans continuously. Scan results are
// passed to the channel provided by FoundServices()
type IContinuousScanner interface {
suture.Service
IScanner
FoundServices() chan ServiceFoundNotification
}
// ContinuousScanner implements IContinuousScanner. It s... | func incrementIP(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 { | random_line_split |
scanner.go | package ipv4
import (
"code.google.com/p/go-uuid/uuid"
"fmt"
"github.com/thejerf/suture"
log "gopkg.in/inconshreveable/log15.v2"
logext "gopkg.in/inconshreveable/log15.v2/ext"
"net"
"strconv"
"sync"
"time"
)
const (
numIPv4Checkers = 100
)
var (
ignoredIPv4Interfaces = map[string]struct{}{
// DARWIN
"... | () chan ServiceFoundNotification {
return s.foundIPChan
}
// Serve begins serving the ContinuousScanner.
func (s *ContinuousScanner) Serve() {
s.log.Debug("starting continuous ipv4 scanner", "period", s.period)
timer := time.NewTimer(time.Hour)
for {
// Perform a scan
s.log.Debug("doing ipv4 scan")
for ip, s... | FoundServices | identifier_name |
menus.py | #!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENS... | import sys
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_()) | conditional_block | |
menus.py | #!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENS... | self.infoLabel.setText("Invoked <b>Help|About Qt</b>")
def createActions(self):
self.newAct = QAction("&New", self, shortcut=QKeySequence.New,
statusTip="Create a new file", triggered=self.newFile)
self.openAct = QAction("&Open...", self, shortcut=QKeySequence.Open,
... | "The <b>Menu</b> example shows how to create menu-bar menus "
"and context menus.")
def aboutQt(self): | random_line_split |
menus.py | #!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENS... | (self):
self.infoLabel.setText("Invoked <b>File|Open</b>")
def save(self):
self.infoLabel.setText("Invoked <b>File|Save</b>")
def print_(self):
self.infoLabel.setText("Invoked <b>File|Print</b>")
def undo(self):
self.infoLabel.setText("Invoked <b>Edit|Undo</b>")
... | open | identifier_name |
menus.py | #!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENS... |
def contextMenuEvent(self, event):
menu = QMenu(self)
menu.addAction(self.cutAct)
menu.addAction(self.copyAct)
menu.addAction(self.pasteAct)
menu.exec_(event.globalPos())
def newFile(self):
self.infoLabel.setText("Invoked <b>File|New</b>")
def open(self):
... | super(MainWindow, self).__init__()
widget = QWidget()
self.setCentralWidget(widget)
topFiller = QWidget()
topFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.infoLabel = QLabel(
"<i>Choose a menu option, or right-click to invoke a context... | identifier_body |
wasm.rs | //! Wrappers over the Rust part of the IDE codebase.
use crate::prelude::*;
use crate::paths::generated::RepoRootDistWasm;
use crate::paths::generated::RepoRootTargetEnsoglPackLinkedDist;
use crate::project::Context;
use crate::project::IsArtifact;
use crate::project::IsTarget;
use crate::project::IsWatchable;
use cr... |
}
#[derive(Clone, Derivative)]
#[derivative(Debug)]
pub struct WatchInput {
pub cargo_watch_options: Vec<String>,
}
impl IsWatchable for Wasm {
type Watcher = crate::project::Watcher<Self, Child>;
type WatchInput = WatchInput;
fn watch(
&self,
context: Context,
job: WatchTa... | {
let Context { octocrab: _, cache, upload_artifacts: _, repo_root } = context;
let WithDestination { inner, destination } = job;
let span = info_span!("Building WASM.",
repo = %repo_root.display(),
crate = %inner.crate_path.display(),
cargo_opts = ?inner.extr... | identifier_body |
wasm.rs | //! Wrappers over the Rust part of the IDE codebase.
use crate::prelude::*;
use crate::paths::generated::RepoRootDistWasm;
use crate::paths::generated::RepoRootTargetEnsoglPackLinkedDist;
use crate::project::Context;
use crate::project::IsArtifact;
use crate::project::IsTarget;
use crate::project::IsWatchable;
use cr... | if !self.profile.should_check_size() {
warn!("Skipping size check because profile is '{}'.", self.profile,);
} else if self.profiling_level.unwrap_or_default() != ProfilingLevel::Objective {
// TODO? additional leeway as sanity check
warn!(
... | info!("Compressed size of {} is {}.", wasm_path.as_ref().display(), compressed_size);
if let Some(wasm_size_limit) = self.wasm_size_limit {
let wasm_size_limit = wasm_size_limit.get_appropriate_unit(true); | random_line_split |
wasm.rs | //! Wrappers over the Rust part of the IDE codebase.
use crate::prelude::*;
use crate::paths::generated::RepoRootDistWasm;
use crate::paths::generated::RepoRootTargetEnsoglPackLinkedDist;
use crate::project::Context;
use crate::project::IsArtifact;
use crate::project::IsTarget;
use crate::project::IsWatchable;
use cr... | (&self) -> Result {
Cargo
.cmd()?
.apply(&cargo::Command::Check)
.apply(&cargo::Options::Workspace)
.apply(&cargo::Options::Package(INTEGRATION_TESTS_CRATE_NAME.into()))
.apply(&cargo::Options::AllTargets)
.run_ok()
.await
}... | check | identifier_name |
wasm.rs | //! Wrappers over the Rust part of the IDE codebase.
use crate::prelude::*;
use crate::paths::generated::RepoRootDistWasm;
use crate::paths::generated::RepoRootTargetEnsoglPackLinkedDist;
use crate::project::Context;
use crate::project::IsArtifact;
use crate::project::IsTarget;
use crate::project::IsWatchable;
use cr... | else {
copy_file_if_different(&temp_dist.pkg_wasm, &temp_dist.pkg_opt_wasm)?;
}
Ok(())
}
}
| {
let mut wasm_opt_command = WasmOpt.cmd()?;
let has_custom_opt_level = wasm_opt_options.iter().any(|opt| {
wasm_opt::OptimizationLevel::from_str(opt.trim_start_matches('-')).is_ok()
});
if !has_custom_opt_level {
wasm_opt_command.apply(&pr... | conditional_block |
server.rs | use std::thread;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::collections::VecDeque;
use std::io::BufReader;
// MIO
use mio::tcp::{listen, TcpListener, TcpStream};
use mio::util::Slab;
use mio::Socket;
use mio::buf::{RingBuf};
use mio::{Interest, PollOpt, NonBlock, Token, EventLoop, Handler, ReadH... | <S, M>(&mut self, event_loop: &mut EventLoop<Server<S, M>>, replica: &mut Replica<S,M>)
-> Result<()>
where S: Store, M: StateMachine {
// Attempt to write data.
// The `current_write` buffer will be advanced based on how much we wrote.
match self.stream.write(self.curr... | writable | identifier_name |
server.rs | use std::thread;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::collections::VecDeque;
use std::io::BufReader;
// MIO
use mio::tcp::{listen, TcpListener, TcpStream};
use mio::util::Slab;
use mio::Socket;
use mio::buf::{RingBuf};
use mio::{Interest, PollOpt, NonBlock, Token, EventLoop, Handler, ReadH... | -> Result<()>
where S: Store, M: StateMachine {
let mut read = 0;
match self.stream.read(self.current_read.get_mut()) {
Ok(Some(r)) => {
// Just read `r` bytes.
read = r;
},
Ok(None) => panic!("We just got read... | fn readable<S, M>(&mut self, event_loop: &mut EventLoop<Server<S, M>>, replica: &mut Replica<S,M>) | random_line_split |
server.rs | use std::thread;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::collections::VecDeque;
use std::io::BufReader;
// MIO
use mio::tcp::{listen, TcpListener, TcpStream};
use mio::util::Slab;
use mio::Socket;
use mio::buf::{RingBuf};
use mio::{Interest, PollOpt, NonBlock, Token, EventLoop, Handler, ReadH... | ,
None => (),
}
},
_ => unimplemented!(),
}
} else if let Ok(client_req) = reader.get_root::<client_request::Reader>() {
let mut should_die = false;
// We will be responding.
match client... | {
// Won an election!
self.broadcast(builder_message);
} | conditional_block |
group.rs | //! Contains methods to generate many symmetry groups.
// Circumvents rust-analyzer bug.
#[allow(unused_imports)]
use crate::{cox, EPS};
use super::{convex, cox::CoxMatrix, geometry::Point, Concrete};
use approx::{abs_diff_ne, relative_eq};
use nalgebra::{
storage::Storage, DMatrix as Matrix, DVector as Vector, D... |
/// Generates the trivial group of a certain dimension.
pub fn trivial(dim: usize) -> Self {
Self {
dim,
iter: Box::new(std::iter::once(Matrix::identity(dim, dim))),
}
}
/// Generates the group with the identity and a central inversion of a
/// certain dime... | {
let dim = self.dim;
Self {
dim,
iter: Box::new(self.map(move |x| {
let msg = "Size of matrix does not match expected dimension.";
assert_eq!(x.nrows(), dim, "{}", msg);
assert_eq!(x.ncols(), dim, "{}", msg);
x
... | identifier_body |
group.rs | //! Contains methods to generate many symmetry groups.
// Circumvents rust-analyzer bug.
#[allow(unused_imports)]
use crate::{cox, EPS};
use super::{convex, cox::CoxMatrix, geometry::Point, Concrete};
use approx::{abs_diff_ne, relative_eq};
use nalgebra::{
storage::Storage, DMatrix as Matrix, DVector as Vector, D... | let nn = n.norm_squared();
// Reflects every basis vector, builds a matrix from all of their images.
Matrix::from_columns(
&Matrix::identity(dim, dim)
.column_iter()
.map(|v| v - (2.0 * v.dot(&n) / nn) * &n)
.collect::<Vec<_>>(),
)
}
impl GenIter {
/// B... | random_line_split | |
group.rs | //! Contains methods to generate many symmetry groups.
// Circumvents rust-analyzer bug.
#[allow(unused_imports)]
use crate::{cox, EPS};
use super::{convex, cox::CoxMatrix, geometry::Point, Concrete};
use approx::{abs_diff_ne, relative_eq};
use nalgebra::{
storage::Storage, DMatrix as Matrix, DVector as Vector, D... | (self, left: bool) -> Box<dyn GroupIter> {
if self.dim != 3 {
panic!("Quaternions can only be generated from 3D matrices.");
}
Box::new(
self.rotations()
.map(move |el| quat_to_mat(mat_to_quat(el), left)),
)
}
/// Returns the swirl symmet... | quaternions | identifier_name |
connection.py | # SPDX-License-Identifier: Apache-2.0
"""
Provides managed HTTP session to Subaru Starlink mobile app API.
For more details, please refer to the documentation at https://github.com/G-Two/subarulink
"""
import asyncio
import logging
import pprint
import time
import aiohttp
from yarl import URL
from subarulink.except... |
async def _select_vehicle(self, vin):
"""Select active vehicle for accounts with multiple VINs."""
params = {"vin": vin, "_": int(time.time())}
js_resp = await self.get(API_SELECT_VEHICLE, params=params)
_LOGGER.debug(pprint.pformat(js_resp))
if js_resp.get("success"):
... | """Authenticate to Subaru Remote Services API."""
if self._username and self._password and self._device_id:
post_data = {
"env": "cloudprod",
"loginUsername": self._username,
"password": self._password,
"deviceId": self._device_id,
... | identifier_body |
connection.py | # SPDX-License-Identifier: Apache-2.0
"""
Provides managed HTTP session to Subaru Starlink mobile app API.
For more details, please refer to the documentation at https://github.com/G-Two/subarulink
"""
import asyncio
import logging
import pprint
import time
import aiohttp
from yarl import URL
from subarulink.except... |
async def _authenticate(self, vin=None) -> bool:
"""Authenticate to Subaru Remote Services API."""
if self._username and self._password and self._device_id:
post_data = {
"env": "cloudprod",
"loginUsername": self._username,
"password": se... | return await self.__open(url, method=POST, headers=self._head, params=params, json_data=json_data) | conditional_block |
connection.py | # SPDX-License-Identifier: Apache-2.0
"""
Provides managed HTTP session to Subaru Starlink mobile app API.
For more details, please refer to the documentation at https://github.com/G-Two/subarulink
"""
import asyncio
import logging
import pprint
import time
import aiohttp
from yarl import URL
from subarulink.except... | (self):
"""Clear session cookies."""
self._websession.cookie_jar.clear()
async def get(self, url, params=None):
"""
Send HTTPS GET request to Subaru Remote Services API.
Args:
url (str): URL path that will be concatenated after `subarulink.const.MOBILE_API_BASE_... | reset_session | identifier_name |
connection.py | # SPDX-License-Identifier: Apache-2.0
"""
Provides managed HTTP session to Subaru Starlink mobile app API.
For more details, please refer to the documentation at https://github.com/G-Two/subarulink
"""
import asyncio
import logging
import pprint
import time
import aiohttp
from yarl import URL
from subarulink.except... | self._registered = False
self._current_vin = None
self._list_of_vins = []
self._session_login_time = None
self._auth_contact_options = None
async def connect(self):
"""
Connect to and establish session with Subaru Starlink mobile app API.
Returns:
... | "Accept": "*/*",
}
self._websession = websession
self._authenticated = False | random_line_split |
main.go | package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"time"
"cloud.google.com/go/pubsub"
"cloud.google.com/go/trace"
"golang.org/x/oauth2"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"code.cloudfoundry.org/clock"
"code.cloudfoundr... | (addr string, timeout time.Duration) (net.Conn, error) {
d := net.Dialer{
Timeout: timeout,
KeepAlive: 60 * time.Second,
}
return d.Dial("tcp", addr)
}
| keepAliveDial | identifier_name |
main.go | package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"time"
"cloud.google.com/go/pubsub"
"cloud.google.com/go/trace"
"golang.org/x/oauth2"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"code.cloudfoundry.org/clock"
"code.cloudfoundr... |
bs, err := ioutil.ReadFile(string(flagOpts.ConfigFile))
if err != nil {
logger.Error("failed-to-open-config-file", err)
os.Exit(1)
}
cfg, err = config.LoadWorkerConfig(bs)
if err != nil {
logger.Error("failed-to-load-config-file", err)
os.Exit(1)
}
errs := cfg.Validate()
if errs != nil {
for _, er... | {
os.Exit(1)
} | conditional_block |
main.go | package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"time"
"cloud.google.com/go/pubsub"
"cloud.google.com/go/trace"
"golang.org/x/oauth2"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"code.cloudfoundry.org/clock"
"code.cloudfoundr... |
func loadCerts(certificatePath, privateKeyPath, privateKeyPassphrase, caCertificatePath string) (tls.Certificate, *x509.CertPool) {
certificate, err := config.LoadCertificateFromFiles(
certificatePath,
privateKeyPath,
privateKeyPassphrase,
)
if err != nil {
log.Fatalln(err)
}
caCertPool, err := config.L... | {
var cfg *config.WorkerConfig
var flagOpts config.WorkerOpts
var ghClient *revok.GitHubClient
logger := lager.NewLogger("revok-worker")
logger.RegisterSink(lager.NewWriterSink(os.Stdout, lager.DEBUG))
logger.Info("starting")
_, err := flags.Parse(&flagOpts)
if err != nil {
os.Exit(1)
}
bs, err := iouti... | identifier_body |
main.go | package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"time"
"cloud.google.com/go/pubsub"
"cloud.google.com/go/trace"
"golang.org/x/oauth2"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"code.cloudfoundry.org/clock"
"code.cloudfoundr... |
signatureChecker := queue.NewSignatureCheck(crypto.NewRSAVerifier(publicKey), emitter, pushEventProcessor)
members = append(members, grouper.Member{
Name: "github-hint-handler",
Runner: queue.NewPubSubSubscriber(logger, subscription, signatureChecker, emitter),
})
if cfg.GitHub.AccessToken != "" {
repoDi... | random_line_split | |
task.rs | use notifier::Notifier;
use sender::Sender;
use futures::{self, future, Future, Async};
use futures::executor::{self, Spawn};
use std::{fmt, mem, panic, ptr};
use std::cell::Cell;
use std::sync::Arc;
use std::sync::atomic::{self, AtomicUsize, AtomicPtr};
use std::sync::atomic::Ordering::{AcqRel, Acquire, Release, Rel... | (&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Task")
.field("inner", self.inner())
.finish()
}
}
impl Clone for Task {
fn clone(&self) -> Task {
use std::isize;
const MAX_REFCOUNT: usize = (isize::MAX) as usize;
// Using a relaxed ... | fmt | identifier_name |
task.rs | use notifier::Notifier;
use sender::Sender;
use futures::{self, future, Future, Async};
use futures::executor::{self, Spawn};
use std::{fmt, mem, panic, ptr};
use std::cell::Cell;
use std::sync::Arc;
use std::sync::atomic::{self, AtomicUsize, AtomicPtr};
use std::sync::atomic::Ordering::{AcqRel, Acquire, Release, Rel... |
}
impl From<usize> for State {
fn from(src: usize) -> Self {
use self::State::*;
match src {
0 => Idle,
1 => Running,
2 => Notified,
3 => Scheduled,
4 => Complete,
_ => unreachable!(),
}
}
}
impl From<State> for ... | {
State::Idle
} | identifier_body |
task.rs | use notifier::Notifier;
use sender::Sender;
use futures::{self, future, Future, Async};
use futures::executor::{self, Spawn};
use std::{fmt, mem, panic, ptr};
use std::cell::Cell;
use std::sync::Arc;
use std::sync::atomic::{self, AtomicUsize, AtomicPtr};
use std::sync::atomic::Ordering::{AcqRel, Acquire, Release, Rel... |
impl Inner {
fn stub() -> Inner {
Inner {
next: AtomicPtr::new(ptr::null_mut()),
state: AtomicUsize::new(State::stub().into()),
ref_count: AtomicUsize::new(0),
future: Some(TaskFuture::Futures1(executor::spawn(Box::new(future::empty())))),
}
}
... |
// ===== impl Inner ===== | random_line_split |
process_test.py | import json
import netCDF4
import numpy as np
import logging
import os
import argparse
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from glob import glob
# from pyclamps.utils import list_to_masked_array, ray_height
# from pyclamps.vad import calc_vad_3d, calc_homogeneity
# Global Values
F... |
def writeRHI_to_nc(filename, date, vel, rng, elev, az, intensity,up_flag):
if os.path.exists(filename):
# open the netcdf
nc = netCDF4.Dataset(filename, 'r+', format="NETCDF4")
dim = nc.dimensions['t'].size
vel_var = nc.variables['velocity']
rng_var = nc.variables['range'... | logging.debug(filename)
logging.debug(date)
# Create the netcdf
nc = netCDF4.Dataset(filename, 'w', format="NETCDF4")
# Create the height dimension
nc.createDimension('hgt', len(hgt))
nc.createDimension('t', None)
# Add the attributes
nc.setncattr("date", date[0].isoformat())
# C... | identifier_body |
process_test.py | import json
import netCDF4
import numpy as np
import logging
import os
import argparse
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from glob import glob
# from pyclamps.utils import list_to_masked_array, ray_height
# from pyclamps.vad import calc_vad_3d, calc_homogeneity
# Global Values
F... |
logging.debug("Decoding header")
# Read in the header info
header = decode_header(lines[0:11])
ngates = int(header['Number of gates'])
# nrays = int(header['No. of rays in file']) # Cant do this apparently. Not always correct (wtf)
len_data = len(lines[17:])
nrays = len_data / (ngates + ... | lines.append(line) | conditional_block |
process_test.py | import json
import netCDF4
import numpy as np
import logging
import os
import argparse
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from glob import glob
# from pyclamps.utils import list_to_masked_array, ray_height
# from pyclamps.vad import calc_vad_3d, calc_homogeneity
# Global Values
F... |
# add newly processed file to list of processed files
proc_list = open(path_proc + 'processed_files.txt', "a")
proc_list.writelines(in_file+'\n')
proc_list.close() | writeRHI_to_nc(filename, times, vel.transpose(), rng, elev, az, intensity.transpose(), up_flag) | random_line_split |
process_test.py | import json
import netCDF4
import numpy as np
import logging
import os
import argparse
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from glob import glob
# from pyclamps.utils import list_to_masked_array, ray_height
# from pyclamps.vad import calc_vad_3d, calc_homogeneity
# Global Values
F... | (header):
"""
Takes in a list of lines from the raw hpl file. Separates them by
tab and removes unnecessary text
"""
new_header = {}
for item in header:
split = item.split('\t')
new_header[split[0].replace(':', '')] = split[1].replace("\r\n", "")
return new_header
def _to... | decode_header | identifier_name |
sender.go | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package sumologicexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/sumologicexporter"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"go.opentelemetry.io/co... |
// Add headers
switch s.config.CompressEncoding {
case GZIPCompression:
req.Header.Set(headerContentEncoding, contentEncodingGzip)
case DeflateCompression:
req.Header.Set(headerContentEncoding, contentEncodingDeflate)
case NoCompression:
default:
return fmt.Errorf("invalid content encoding: %s", s.config.... | {
return err
} | conditional_block |
sender.go | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package sumologicexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/sumologicexporter"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"go.opentelemetry.io/co... | (record plog.LogRecord) string {
return record.Body().AsString()
}
// logToJSON converts LogRecord to a json line, returns it and error eventually
func (s *sender) logToJSON(record plog.LogRecord) (string, error) {
data := s.filter.filterOut(record.Attributes())
record.Body().CopyTo(data.orig.PutEmpty(logKey))
ne... | logToText | identifier_name |
sender.go | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package sumologicexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/sumologicexporter"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"go.opentelemetry.io/co... | func (s *sender) sendMetrics(ctx context.Context, flds fields) ([]metricPair, error) {
var (
body strings.Builder
errs error
droppedRecords []metricPair
currentRecords []metricPair
)
for _, record := range s.metricBuffer {
var formattedLine string
var err error
switch s.config.Met... |
return droppedRecords, errs
}
// sendMetrics sends metrics in right format basing on the s.config.MetricFormat | random_line_split |
sender.go | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package sumologicexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/sumologicexporter"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"go.opentelemetry.io/co... |
// batchLog adds log to the logBuffer and flushes them if logBuffer is full to avoid overflow
// returns list of log records which were not sent successfully
func (s *sender) batchLog(ctx context.Context, log plog.LogRecord, metadata fields) ([]plog.LogRecord, error) {
s.logBuffer = append(s.logBuffer, log)
if s.c... | {
s.logBuffer = (s.logBuffer)[:0]
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.