identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/lyminhnghia/Multiple-Language-Menu/blob/master/client/src/redux/error.redux.js
|
Github Open Source
|
Open Source
|
MIT
| null |
Multiple-Language-Menu
|
lyminhnghia
|
JavaScript
|
Code
| 121
| 258
|
import { createReducer, createActions } from "reduxsauce";
import { getError } from "../utils";
/* ------------- Types and Action Creators ------------- */
const { Types, Creators } = createActions({
resetError: [],
failure: ["data"],
});
export const ErrorTypes = Types;
export default Creators;
/* ------------- Initial State ------------- */
export const INITIAL_STATE = {
error: null, // Detail content of error
status: null,
};
/* ------------- Reducers ------------- */
export const raise = (state, action) => {
const data = action.data ? action.data : {};
let error = getError(data);
return { ...state, ...data, error: error };
};
export const reset = () => INITIAL_STATE;
/* ------------- Hookup Reducers To Types ------------- */
export const reducer = createReducer(INITIAL_STATE, {
[Types.FAILURE]: raise,
[Types.RESET_ERROR]: reset,
});
| 22,132
|
https://github.com/yume-chan/node-svn/blob/master/src/uv/future.hpp
|
Github Open Source
|
Open Source
|
MIT
| null |
node-svn
|
yume-chan
|
C++
|
Code
| 120
| 373
|
#include <future>
namespace uv {
template <class T>
class future {
public:
using value_type = T;
future(std::future<T>& future)
: value(std::move(future)) {}
T get() {
return value.get();
}
private:
std::future<T> value;
};
template <class T>
class future<T&> {
public:
using value_type = T&;
future(std::future<T&>& future)
: value(std::move(future)) {}
T& get() {
return value.get();
}
private:
std::future<T&> value;
};
template <>
class future<void> {
public:
using value_type = void;
future() = default;
future(future&&) = default;
future& operator=(future&&) = default;
future(std::future<void>&& value)
: value(std::move(value)) {}
void get() {
value.get();
}
private:
std::future<void> value;
};
template <class T>
struct is_future : std::false_type {};
template <class T>
struct is_future<future<T>> : std::true_type {};
template <class T>
inline constexpr bool is_future_v = is_future<T>::value;
} // namespace uv
| 27,543
|
https://github.com/axkibe/node-vtk/blob/master/wrappers/7.0.0/vtkAreaPickerWrap.cc
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,020
|
node-vtk
|
axkibe
|
C++
|
Code
| 994
| 5,349
|
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkAbstractPropPickerWrap.h"
#include "vtkAreaPickerWrap.h"
#include "vtkObjectWrap.h"
#include "vtkRendererWrap.h"
#include "vtkAbstractMapper3DWrap.h"
#include "vtkDataSetWrap.h"
#include "vtkProp3DCollectionWrap.h"
#include "vtkPlanesWrap.h"
#include "vtkPointsWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkAreaPickerWrap::ptpl;
VtkAreaPickerWrap::VtkAreaPickerWrap()
{ }
VtkAreaPickerWrap::VtkAreaPickerWrap(vtkSmartPointer<vtkAreaPicker> _native)
{ native = _native; }
VtkAreaPickerWrap::~VtkAreaPickerWrap()
{ }
void VtkAreaPickerWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkAreaPicker").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("AreaPicker").ToLocalChecked(), ConstructorGetter);
}
void VtkAreaPickerWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkAreaPickerWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkAbstractPropPickerWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkAbstractPropPickerWrap::ptpl));
tpl->SetClassName(Nan::New("VtkAreaPickerWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "AreaPick", AreaPick);
Nan::SetPrototypeMethod(tpl, "areaPick", AreaPick);
Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "GetClipPoints", GetClipPoints);
Nan::SetPrototypeMethod(tpl, "getClipPoints", GetClipPoints);
Nan::SetPrototypeMethod(tpl, "GetDataSet", GetDataSet);
Nan::SetPrototypeMethod(tpl, "getDataSet", GetDataSet);
Nan::SetPrototypeMethod(tpl, "GetFrustum", GetFrustum);
Nan::SetPrototypeMethod(tpl, "getFrustum", GetFrustum);
Nan::SetPrototypeMethod(tpl, "GetMapper", GetMapper);
Nan::SetPrototypeMethod(tpl, "getMapper", GetMapper);
Nan::SetPrototypeMethod(tpl, "GetProp3Ds", GetProp3Ds);
Nan::SetPrototypeMethod(tpl, "getProp3Ds", GetProp3Ds);
Nan::SetPrototypeMethod(tpl, "IsA", IsA);
Nan::SetPrototypeMethod(tpl, "isA", IsA);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "Pick", Pick);
Nan::SetPrototypeMethod(tpl, "pick", Pick);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "SetPickCoords", SetPickCoords);
Nan::SetPrototypeMethod(tpl, "setPickCoords", SetPickCoords);
Nan::SetPrototypeMethod(tpl, "SetRenderer", SetRenderer);
Nan::SetPrototypeMethod(tpl, "setRenderer", SetRenderer);
#ifdef VTK_NODE_PLUS_VTKAREAPICKERWRAP_INITPTPL
VTK_NODE_PLUS_VTKAREAPICKERWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkAreaPickerWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
vtkSmartPointer<vtkAreaPicker> native = vtkSmartPointer<vtkAreaPicker>::New();
VtkAreaPickerWrap* obj = new VtkAreaPickerWrap(native);
obj->Wrap(info.This());
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkAreaPickerWrap::AreaPick(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() > 2 && info[2]->IsNumber())
{
if(info.Length() > 3 && info[3]->IsNumber())
{
if(info.Length() > 4 && info[4]->IsObject() && (Nan::New(VtkRendererWrap::ptpl))->HasInstance(info[4]))
{
VtkRendererWrap *a4 = ObjectWrap::Unwrap<VtkRendererWrap>(info[4]->ToObject());
int r;
if(info.Length() != 5)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->AreaPick(
info[0]->NumberValue(),
info[1]->NumberValue(),
info[2]->NumberValue(),
info[3]->NumberValue(),
(vtkRenderer *) a4->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
}
}
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkAreaPickerWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetClassName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkAreaPickerWrap::GetClipPoints(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
vtkPoints * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetClipPoints();
VtkPointsWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkPointsWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkPointsWrap *w = new VtkPointsWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkAreaPickerWrap::GetDataSet(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
vtkDataSet * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetDataSet();
VtkDataSetWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkDataSetWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkDataSetWrap *w = new VtkDataSetWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkAreaPickerWrap::GetFrustum(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
vtkPlanes * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetFrustum();
VtkPlanesWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkPlanesWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkPlanesWrap *w = new VtkPlanesWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkAreaPickerWrap::GetMapper(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
vtkAbstractMapper3D * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMapper();
VtkAbstractMapper3DWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkAbstractMapper3DWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkAbstractMapper3DWrap *w = new VtkAbstractMapper3DWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkAreaPickerWrap::GetProp3Ds(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
vtkProp3DCollection * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetProp3Ds();
VtkProp3DCollectionWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkProp3DCollectionWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkProp3DCollectionWrap *w = new VtkProp3DCollectionWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkAreaPickerWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->IsA(
*a0
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkAreaPickerWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
vtkAreaPicker * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkAreaPickerWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkAreaPickerWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkAreaPickerWrap *w = new VtkAreaPickerWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkAreaPickerWrap::Pick(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() > 2 && info[2]->IsNumber())
{
if(info.Length() > 3 && info[3]->IsObject() && (Nan::New(VtkRendererWrap::ptpl))->HasInstance(info[3]))
{
VtkRendererWrap *a3 = ObjectWrap::Unwrap<VtkRendererWrap>(info[3]->ToObject());
int r;
if(info.Length() != 4)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Pick(
info[0]->NumberValue(),
info[1]->NumberValue(),
info[2]->NumberValue(),
(vtkRenderer *) a3->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
}
}
}
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Pick();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkAreaPickerWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
vtkAreaPicker * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObject *) a0->native.GetPointer()
);
VtkAreaPickerWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkAreaPickerWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkAreaPickerWrap *w = new VtkAreaPickerWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkAreaPickerWrap::SetPickCoords(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() > 2 && info[2]->IsNumber())
{
if(info.Length() > 3 && info[3]->IsNumber())
{
if(info.Length() != 4)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPickCoords(
info[0]->NumberValue(),
info[1]->NumberValue(),
info[2]->NumberValue(),
info[3]->NumberValue()
);
return;
}
}
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkAreaPickerWrap::SetRenderer(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkAreaPickerWrap *wrapper = ObjectWrap::Unwrap<VtkAreaPickerWrap>(info.Holder());
vtkAreaPicker *native = (vtkAreaPicker *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkRendererWrap::ptpl))->HasInstance(info[0]))
{
VtkRendererWrap *a0 = ObjectWrap::Unwrap<VtkRendererWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetRenderer(
(vtkRenderer *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
| 42,021
|
https://github.com/elveahuang/platform/blob/master/platform-commons/platform-commons/src/main/java/cn/elvea/platform/commons/utils/CollectionUtils.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
platform
|
elveahuang
|
Java
|
Code
| 119
| 424
|
package cn.elvea.platform.commons.utils;
import com.google.common.collect.Lists;
import org.springframework.lang.Nullable;
import java.util.*;
import java.util.stream.Collectors;
/**
* CollectionUtils
*
* @author elvea
* @since 0.0.1
*/
public abstract class CollectionUtils extends org.springframework.util.CollectionUtils {
/**
* 如果第一个参数为空,则返回第二个参数
*/
public static <E> List<E> nvl(final List<E> object) {
return isEmpty(object) ? Collections.emptyList() : object;
}
/**
* 是否不为空
*/
public static boolean isNotEmpty(@Nullable Collection<?> collection) {
return !isEmpty(collection);
}
/**
* 是否不为空
*/
public static boolean isNotEmpty(@Nullable Map<?, ?> map) {
return !isEmpty(map);
}
/**
* 移除重复元素
*/
public static <E> List<E> removeDuplicates(List<E> list) {
if (isEmpty(list)) {
return Lists.newArrayList();
}
return list.stream().distinct().collect(Collectors.toList());
}
public static <E> List<E> toArrayList(final Iterable<E> iterable) {
return Lists.newArrayList(iterable);
}
public static <E> List<E> toArrayList(final Iterator<E> iterator) {
return Lists.newArrayList(iterator);
}
}
| 47,620
|
https://github.com/warsier/nstore/blob/master/misc/linux-examples/icount/icount.c
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
nstore
|
warsier
|
C
|
Code
| 1,050
| 2,465
|
/*
* Copyright (c) 2013, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* icount.c -- quick & dirty instruction count
*/
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/ptrace.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <setjmp.h>
#include "util/util.h"
#include "icount/icount.h"
static pid_t Tracer_pid; /* PID of tracer process */
static int Tracerpipe[2]; /* pipe from tracer to parent */
static unsigned long Total; /* instruction count */
static unsigned long Nothing;
static jmp_buf Trigjmp;
/*
* handler -- catch SIGRTMIN+15 in tracee once tracer is established
*/
static void
handler()
{
longjmp(Trigjmp, 1);
}
/*
* pretrigger -- internal function used to detect start of tracing
*
* This function must immediately precede trigger() in this file.
*/
static void
pretrigger(void)
{
int x = getpid();
/*
* this is just a few instructions to make sure
* this function doesn't get optimized away into
* nothing. the tracer will find us here and send
* us a signal, causing us to longjmp out.
*/
while (1) {
x++; /* wait for tracer to attach */
Nothing += x;
}
}
/*
* trigger -- internal function used to detect start of tracing
*/
static void
trigger(void)
{
Nothing = 0; /* avoid totally empty function */
}
/*
* tracer -- internal function used in child process to trace parent
*/
static void
tracer(unsigned long ttl)
{
pid_t ppid = getppid();
int status;
int triggered = 0;
int signaled = 0;
if (ptrace(PTRACE_ATTACH, ppid, 0, 0) < 0)
FATALSYS("PTRACE_ATTACH");
while (1) {
if (waitpid(ppid, &status, 0) < 0)
FATALSYS("waitpid(pid=%d)", ppid);
if (WIFSTOPPED(status)) {
struct user_regs_struct regs;
if (triggered)
Total++;
if (ttl && Total >= ttl) {
if (kill(ppid, SIGKILL) < 0)
FATAL("SIGKILL %d", ppid);
printf("Program terminated after %lu "
"instructions\n",
Total);
fflush(stdout);
_exit(0);
}
if (ptrace(PTRACE_GETREGS, ppid, 0, ®s) < 0)
FATALSYS("PTRACE_GETREGS");
if ((unsigned long)regs.rip >=
(unsigned long)pretrigger &&
(unsigned long)regs.rip <
(unsigned long)trigger) {
if (!signaled) {
if (ptrace(PTRACE_SYSCALL, ppid, 0,
SIGRTMIN+15) < 0)
FATALSYS("PTRACE_SYSCALL");
signaled = 1;
continue;
}
} else if ((unsigned long) regs.rip ==
(unsigned long) trigger) {
triggered = 1;
} else if ((unsigned long) regs.rip ==
(unsigned long) icount_stop) {
if (ptrace(PTRACE_DETACH, ppid, 0, 0) < 0)
FATALSYS("PTRACE_DETACH");
break;
}
if (ptrace(PTRACE_SINGLESTEP, ppid, 0, 0) < 0)
FATALSYS("PTRACE_SINGLESTEP");
} else if (WIFEXITED(status))
FATAL("tracee: exit %d", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
FATAL("tracee: %s", strsignal(WTERMSIG(status)));
else
FATAL("unexpected wait status: 0x%x", status);
}
/*
* our counting is done, send the count back to the tracee
* via the pipe and exit.
*/
if (write(Tracerpipe[1], &Total, sizeof(Total)) < 0)
FATALSYS("write to pipe");
close(Tracerpipe[1]);
_exit(0);
}
/*
* icount_start -- begin instruction counting
*
* Inputs:
* life_remaining -- simulate a crash after counting this many
* instructions. pass in 0ull to disable this
* feature.
*
* There is some variability on how far the parent can get before the child
* attaches to it for tracing, especially when the system is loaded down
* (e.g. due to zillions of parallel icount traces happening at once).
* To coordinate this, we use a multi-step procedure where the tracee
* runs until it gets to the function pretrigger() and the tracer() detects
* that and raises a signal (SIGRTMIN+15) in the tracee, who then catches
* it and longjmps out of signal handler, back here, and then calls trigger().
*
* The multi-step coordination sounds complex, but it handles the
* surprisingly common cases where the tracer attached to the tracee
* before it even finished executing the libc fork() wrapper, and the
* other end of the spectrum where the tracee ran way too far ahead
* before the tracer attached and the tracer missed the call to trigger().
*/
void
icount_start(unsigned long life_remaining)
{
if (Tracer_pid) {
/* nested call not allowed */
icount_stop();
FATAL("icount_start called while counting already active");
}
Total = 0ull;
if (pipe(Tracerpipe) < 0)
FATALSYS("pipe");
if (signal(SIGRTMIN+15, handler) == SIG_ERR)
FATALSYS("signal: SIGRTMIN+15");
if ((Tracer_pid = fork()) < 0)
FATALSYS("fork");
else if (Tracer_pid) {
/* parent */
close(Tracerpipe[1]);
if (!setjmp(Trigjmp))
pretrigger();
close(-1); /* harmless syscall for tracer */
trigger();
return;
} else {
/* child */
close(Tracerpipe[0]);
tracer(life_remaining);
}
}
/*
* icount_stop -- stop counting instructions
*/
void
icount_stop(void)
{
int status;
if (read(Tracerpipe[0], &Total, sizeof(Total)) < 0)
FATALSYS("read from pipe");
close(Tracerpipe[0]);
/* wait for child */
if (waitpid(Tracer_pid, &status, 0) < 0)
FATALSYS("waitpid(pid=%d)", Tracer_pid);
Tracer_pid = 0;
}
/*
* icount_total -- return total from last count exercise
*
* Outputs:
* The return value is the total count of instructions
* executed between the last calls to icount_start()
* and icount_stop().
*
* This function only returns valid counts when counting is not
* active and when a count has previously been started and stopped.
*/
unsigned long
icount_total(void)
{
return Total;
}
| 19,386
|
https://github.com/otvorenesudy/otvorenesudy/blob/master/app/serializers/legislation_area_serializer.rb
|
Github Open Source
|
Open Source
|
ECL-1.0
| 2,020
|
otvorenesudy
|
otvorenesudy
|
Ruby
|
Code
| 7
| 19
|
class LegislationAreaSerializer < ActiveModel::Serializer
attributes :value
end
| 11,657
|
https://github.com/Md-shefat-masum/laravel_custom_autentication/blob/master/app/Http/Controllers/CAuth.php
|
Github Open Source
|
Open Source
|
MIT
| null |
laravel_custom_autentication
|
Md-shefat-masum
|
PHP
|
Code
| 19
| 59
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CAuth extends Controller
{
public static function AuthInfo()
{
return session()->get('user_info');
}
}
| 14,637
|
https://github.com/rijwanc007/accounting/blob/master/app/Http/Controllers/Admin/JournalController.php
|
Github Open Source
|
Open Source
|
MIT
| null |
accounting
|
rijwanc007
|
PHP
|
Code
| 446
| 2,820
|
<?php
namespace App\Http\Controllers\Admin;
use App\Activity;
use App\Chartofaccount;
use App\Http\Controllers\Controller;
use App\Journal;
use App\SisterConcern;
use DateTime;
use DateTimeZone;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
class JournalController extends Controller
{
public function index()
{
$from = null;
$journals = Journal::orderBy('id', 'DESC')->paginate(10);
return view('journal.index', compact('journals', 'from'));
}
public function create()
{
if(Auth::user()->sister_concern_id == 0){
$sister_concerns = SisterConcern::orderBy('id', 'DESC')->get();
}
else{
$sister_concerns = SisterConcern::where('id', Auth::user()->sister_concern_id)->orderBy('id', 'DESC')->get();
}
$journals = Journal::orderBy('id', 'DESC')->get();
$data = array();
foreach($sister_concerns as $concern){
$heads[$concern->id] = Chartofaccount::where('sister_concern_id', $concern->id)->where('sub_head_id', 0)->orderBy('id', 'DESC')->get();
$sub_heads[$concern->id] = Chartofaccount::where('sister_concern_id', $concern->id)->where('sub_head_id','!=', 0)->orderBy('id', 'DESC')->get();
}
foreach($sister_concerns as $concern){
for($i = 0 ; $i<count($heads[$concern->id]) ; $i++){
$data[$concern->id][$i]['id'] = $heads[$concern->id][$i]->head_id;
$data[$concern->id][$i]['type'] = 0;
$data[$concern->id][$i]['name'] = $heads[$concern->id][$i]->head_name;
}
$j = count($data[$concern->id]);
for($i = 0 ; $i<count($sub_heads[$concern->id]) ; $i++){
$data[$concern->id][$j]['id'] = $sub_heads[$concern->id][$i]->sub_head_id;
$data[$concern->id][$j]['type'] = 1;
$data[$concern->id][$j]['name'] = $sub_heads[$concern->id][$i]->sub_head_name;
++$j;
}
}
return view('journal.create', compact('sister_concerns', 'journals', 'data'));
}
public function store(Request $request)
{
$dt = new DateTime('now', new DateTimezone('Asia/Dhaka'));
if(count($request->debit_id) > 1){
for($i =0 ; $i<count($request->debit_id) ; $i++){
Journal::create([
'sister_concern_id'=>$request->sister_concern_id,
'voucher_no'=>$request->voucher_no,
'voucher_type'=>0,
'date'=>$request->date,
'time'=>$dt->format('H:i:s'),
'debit_id'=>$request->debit_id[$i],
'debit_amount'=>$request->debit_amount[$i],
'credit_id'=>$request->credit_id[0],
'credit_amount'=>$request->debit_amount[$i],
'naration'=>$request->naration,
'transfer_amount_to'=>$request->transfer_amount_to[$i],
'debit_overview'=>$request->debit_overview[$i],
'debit_amount_overview'=>$request->debit_amount_overview[$i],
'transfer_amount_from'=>$request->transfer_amount_from[0],
'credit_overview'=>$request->credit_overview[0],
'credit_amount_overview'=>$request->debit_amount_overview[$i],
'status'=>0,
]);
}
}
else{
for($i =0 ; $i<count($request->credit_id) ; $i++){
Journal::create([
'sister_concern_id'=>$request->sister_concern_id,
'voucher_no'=>$request->voucher_no,
'voucher_type'=>0,
'date'=>$request->date,
'time'=>$dt->format('H:i:s'),
'debit_id'=>$request->debit_id[0],
'debit_amount'=>$request->credit_amount[$i],
'credit_id'=>$request->credit_id[$i],
'credit_amount'=>$request->credit_amount[$i],
'naration'=>$request->naration,
'transfer_amount_to'=>$request->transfer_amount_to[0],
'debit_overview'=>$request->debit_overview[0],
'debit_amount_overview'=>$request->credit_amount_overview[$i],
'transfer_amount_from'=>$request->transfer_amount_from[$i],
'credit_overview'=>$request->credit_overview[$i],
'credit_amount_overview'=>$request->credit_amount_overview[$i],
'status'=>0,
]);
}
}
Activity::create([
'user_id'=>Auth::user()->id,
'date'=>$dt->format('Y-m-d'),
'time'=>$dt->format('H:i:s'),
'message'=>'Created Journal Voucher for ' . SisterConcern::find($request->sister_concern_id)->name,
]);
Session::flash('success', 'Journal Created Successfully');
return redirect()->route('journal.index');
}
public function show($id)
{
$show = Journal::find($id);
return view('journal.show',compact('show'));
}
public function edit($id)
{
if(Auth::user()->sister_concern_id == 0){
$sister_concerns = SisterConcern::orderBy('id', 'DESC')->get();
}
else{
$sister_concerns = SisterConcern::where('id', Auth::user()->sister_concern_id)->orderBy('id', 'DESC')->get();
}
$edit = Journal::find($id);
$data = array();
foreach($sister_concerns as $concern){
$heads[$concern->id] = Chartofaccount::where('sister_concern_id', $concern->id)->where('sub_head_id', 0)->orderBy('id', 'DESC')->get();
$sub_heads[$concern->id] = Chartofaccount::where('sister_concern_id', $concern->id)->where('sub_head_id','!=', 0)->orderBy('id', 'DESC')->get();
}
foreach($sister_concerns as $concern){
for($i = 0 ; $i<count($heads[$concern->id]) ; $i++){
$data[$concern->id][$i]['id'] = $heads[$concern->id][$i]->head_id;
$data[$concern->id][$i]['type'] = 0;
$data[$concern->id][$i]['name'] = $heads[$concern->id][$i]->head_name;
}
$j = count($data[$concern->id]);
for($i = 0 ; $i<count($sub_heads[$concern->id]) ; $i++){
$data[$concern->id][$j]['id'] = $sub_heads[$concern->id][$i]->sub_head_id;
$data[$concern->id][$j]['type'] = 1;
$data[$concern->id][$j]['name'] = $sub_heads[$concern->id][$i]->sub_head_name;
++$j;
}
}
return view('journal.edit', compact('sister_concerns', 'edit', 'data'));
}
public function update(Request $request, $id)
{
$dt = new DateTime('now', new DateTimezone('Asia/Dhaka'));
$update = Journal::find($id);
$update->update([
'sister_concern_id'=>$request->sister_concern_id,
'voucher_no'=>$request->voucher_no,
'date'=>$request->date,
'time'=>$dt->format('H:i:s'),
'debit_id'=>$request->debit_id,
'debit_amount'=>$request->debit_amount,
'credit_id'=>$request->credit_id,
'credit_amount'=>$request->credit_amount,
'naration'=>$request->naration,
'transfer_amount_to'=>$request->transfer_amount_to,
'debit_overview'=>$request->debit_overview,
'debit_amount_overview'=>$request->debit_amount_overview,
'transfer_amount_from'=>$request->transfer_amount_from,
'credit_overview'=>$request->credit_overview,
'credit_amount_overview'=>$request->credit_amount_overview,
]);
Activity::create([
'user_id'=>Auth::user()->id,
'date'=>$dt->format('Y-m-d'),
'time'=>$dt->format('H:i:s'),
'message'=>'Updated Journal Voucher for ' . SisterConcern::find($update->sister_concern_id)->name,
]);
Session::flash('success', 'Journal Updated Successfully');
return redirect()->route('journal.index');
}
public function destroy($id)
{
$journal = Journal::find($id);
Journal::find($id)->delete();
$dt = new DateTime('now', new DateTimezone('Asia/Dhaka'));
Activity::create([
'user_id'=>Auth::user()->id,
'date'=>$dt->format('Y-m-d'),
'time'=>$dt->format('H:i:s'),
'message'=>'Updated Journal Voucher for ' . SisterConcern::find($journal->sister_concern_id)->name,
]);
Session::flash('success', 'Journal Updated Successfully');
return redirect()->route('journal.index');
}
public function date_search(Request $request){
$from = $request->date_from;
$to = $request->date_to;
$journals = Journal::whereDate('date', '>=', $from)->whereDate('date', '<=', $to)->orderBy('date', 'DESC')->paginate(10);
return view('journal.index', compact('journals', 'from', 'to'));
}
public function accept($id){
$update = Journal::find($id);
$update->update([
'status'=>1,
]);
Session::flash('success', 'Voucher Accepted Successfully');
return redirect()->back();
}
}
| 1,912
|
https://github.com/azu/Surikae/blob/master/test/SurikaeTest/iUnitTest/Tests/Foo.h
|
Github Open Source
|
Open Source
|
BSD-2-Clause, BSD-3-Clause
| 2,012
|
Surikae
|
azu
|
Objective-C
|
Code
| 38
| 104
|
//
// Foo.h
// SurikaeTest
//
// Created by Ito Katsuyoshi on 12/02/19.
// Copyright (c) 2012年 ITO SOFT DESIGN Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Foo : NSObject
+ (NSString *)foo;
- (NSString *)foo;
@end
| 29,994
|
https://github.com/sunmoon11/greenaira/blob/master/tpl-edit-item.php
|
Github Open Source
|
Open Source
|
MIT
| null |
greenaira
|
sunmoon11
|
PHP
|
Code
| 736
| 2,131
|
<?php
/*
* Template Name: User Edit Item
*
* This template must be assigned to the edit-item page
* in order for it to work correctly
*
*/
global $wpdb;
$debugOn = array();
$current_user = wp_get_current_user(); // grabs the user info and puts into vars
// get the ad id from the querystring.
$aid = appthemes_numbers_only($_GET['aid']);
// make sure the ad id is legit otherwise set it to zero which will return no results
if (!empty($aid)) $aid = $aid; else $aid = '0';
// select post information and also category with joins.
// filtering based off current user id which prevents people from trying to hack other peoples ads
$sql = $wpdb->prepare("SELECT wposts.*, $wpdb->term_taxonomy.term_id "
. "FROM $wpdb->posts wposts "
. "LEFT JOIN $wpdb->term_relationships ON($aid = $wpdb->term_relationships.object_id) "
. "LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) "
. "LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id) "
. "WHERE ID = %s AND $wpdb->term_taxonomy.taxonomy = '".APP_TAX_CAT."' "
//. "AND post_status <> 'draft' "// turned off to allow "paused" ads to be editable, uncomment to disable editing of paused ads
. "AND post_author = %s", $aid, $current_user->ID);
// pull ad fields from db
$getad = $wpdb->get_row($sql);
?>
<script type='text/javascript'>
// <![CDATA[
jQuery(document).ready(function(){
/* setup the form validation */
jQuery("#mainform").validate({
errorClass: 'invalid',
errorPlacement: function(error, element) {
if (element.attr('type') == 'checkbox' || element.attr('type') == 'radio') {
element.closest('ol').before(error);
} else {
error.insertBefore(element);
}
error.css('display', 'block');
}
});
/* setup the tooltip */
jQuery("#mainform a").easyTooltip();
});
/* General Trim Function Based on Fastest Executable Trim */
function trim (str) {
var str = str.replace(/^\s\s*/, ''),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}
/* Used for enabling the image for uploads */
function enableNextImage($a, $i) {
jQuery('#upload'+$i).removeAttr("disabled");
}
// ]]>
</script>
<?php
// call tinymce init code if html is enabled
if ( get_option('cp_allow_html') == 'yes' )
appthemes_tinymce( 490, 300 );
?>
<div class="content">
<div class="content_botbg">
<div class="content_res">
<!-- left block -->
<div class="content_left">
<div class="shadowblock_out">
<div class="shadowblock">
<h1 class="single dotted"><?php _e( 'Edit Your Ad', APP_TD ); ?></h1>
<?php if ($getad && (get_option('cp_ad_edit') == 'yes') ): ?>
<?php do_action( 'appthemes_notices' ); ?>
<p><?php _e( 'Edit the fields below and click save to update your ad. Your changes will be updated instantly on the site.', APP_TD ); ?></p>
<form name="mainform" id="mainform" class="form_edit" action="" method="post" enctype="multipart/form-data">
<?php wp_nonce_field( 'cp-edit-item' ); ?>
<ol>
<?php
// we first need to see if this ad is using a custom form
// so lets search for a catid match and return the id if found
$fid = cp_get_form_id($getad->term_id);
// if there's no form id it must mean the default form is being used so let's go grab those fields
if(!($fid)) {
// use this if there's no custom form being used and give us the default form
$sql = "SELECT field_label, field_name, field_type, field_values, field_tooltip, field_req FROM $wpdb->cp_ad_fields WHERE field_core = '1' ORDER BY field_id asc";
} else {
// now we should have the formid so show the form layout based on the category selected
$sql = $wpdb->prepare("SELECT f.field_label, f.field_name, f.field_type, f.field_values, f.field_perm, f.field_tooltip, m.meta_id, m.field_pos, m.field_req, m.form_id "
. "FROM $wpdb->cp_ad_fields f "
. "INNER JOIN $wpdb->cp_ad_meta m "
. "ON f.field_id = m.field_id "
. "WHERE m.form_id = %s "
. "ORDER BY m.field_pos asc", $fid);
}
$results = $wpdb->get_results($sql);
if ($results) {
// build the edit ad form
cp_formbuilder($results, $getad);
}
// check and make sure images are allowed
if ( get_option('cp_ad_images') == 'yes' ) {
if ( appthemes_plupload_is_enabled() ) {
echo appthemes_plupload_form($getad->ID);
} else {
$imagecount = cp_get_ad_images($getad->ID);
// print out image upload fields. pass in count of images allowed
echo cp_ad_edit_image_input_fields($imagecount);
}
} else { ?>
<div class="pad10"></div>
<li>
<div class="labelwrapper">
<label><?php _e( 'Images:', APP_TD ); ?></label><?php _e( 'Sorry, image editing is not supported for this ad.', APP_TD ); ?>
</div>
</li>
<div class="pad25"></div>
<?php } ?>
<p class="submit center">
<input type="button" class="btn_orange" onclick="window.location.href='<?php echo CP_DASHBOARD_URL; ?>'" value="<?php _e( 'Cancel', APP_TD ); ?>" />
<input type="submit" class="btn_orange" value="<?php _e( 'Update Ad »', APP_TD ); ?>" name="submit" />
</p>
</ol>
<input type="hidden" name="action" value="cp-edit-item" />
<input type="hidden" name="ad_id" value="<?php echo $getad->ID; ?>" />
</form>
<?php else : ?>
<p class="text-center"><?php _e( 'You have entered an invalid ad id or do not have permission to edit that ad.', APP_TD ); ?></p>
<?php endif; ?>
</div><!-- /shadowblock -->
</div><!-- /shadowblock_out -->
</div><!-- /content_left -->
<?php get_sidebar( 'user' ); ?>
<div class="clr"></div>
</div><!-- /content_res -->
</div><!-- /content_botbg -->
</div><!-- /content -->
| 39,688
|
https://github.com/XtremeGood/Mailer/blob/master/src/mailer/main.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Mailer
|
XtremeGood
|
Python
|
Code
| 186
| 1,183
|
import os
import smtplib
import subprocess
import sys
from time import sleep
from PyQt5 import QtWidgets
from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import QFileDialog, QToolTip
from PyQt5.QtGui import QFont, QValidator
from mailer.sendmailer import sendMail
from mailer.UIdesign import Ui_MainWindow
def authenticateuser(host, port, user, passwd):
with smtplib.SMTP(host,
port) as smtp:
smtp.login(user=user,
password=passwd)
class MainMailer(Ui_MainWindow):
def __init__(self, MainWindow):
super().setupUi(MainWindow)
MainWindow.setWindowFlags(QtCore.Qt.WindowCloseButtonHint
| QtCore.Qt.WindowMinimizeButtonHint)
MainWindow.show()
self.textBrowser.setStyleSheet(
"color:#1A1B41;font-size:14px;background:white;")
self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit_2.setAlignment(QtCore.Qt.AlignCenter)
self.Fire.setDisabled(True)
self.FileBrowse.clicked.connect(self.browse_File) # Browse Button
self.textEdit.textChanged.connect(self.activateredbtn)
def browse_File(self):
self.textBrowser.setText("")
self.progressBar.setValue(0)
file_name, _ = QFileDialog.getOpenFileName(
filter="Excel (*.xlsx);;CSV (*.csv) ")
if file_name:
self.textEdit.setText(file_name)
subprocess.run(["start", "excel", file_name], shell=True)
self.Fire.setEnabled(True)
self.Fire.clicked.connect(self.executeMailer)
def activateredbtn(self):
if self.textEdit.toPlainText().endswith(".csv") or self.textEdit.toPlainText().endswith(".xlsx") :
self.Fire.setEnabled(True)
self.Fire.clicked.connect(self.executeMailer)
def print_send(self, value1, value2):
if value2 > 0:
self.progressBar.setValue(value2)
self.textBrowser.append(f"<em>{value1}</em>")
def executeMailer(self):
if self.lineEdit.text() and self.lineEdit_2.text():
try:
authenticateuser(host=self.lineEdit_3.text(),
port=587,
user=self.lineEdit.text(),
passwd=self.lineEdit_2.text())
except smtplib.SMTPAuthenticationError:
self.textBrowser.setHtml(
"<strong>Invalid Username or Password !!</strong>")
except Exception as e:
self.textBrowser.setText(getattr(e, 'message', repr(e)))
else:
self.textEdit.disconnect()
self.textEdit.setReadOnly(True)
self.Fire.setEnabled(False)
self.Fire.clicked.disconnect()
self.FileBrowse.clicked.disconnect()
self.FileBrowse.setDisabled(True)
self.textBrowser.setText("Process Started...")
self.obj = sendMail(settings={
"smtphost": self.lineEdit_3.text(),
"smtpuser": self.lineEdit.text(),
"smtppass": self.lineEdit_2.text(),
"mailfrom": self.lineEdit.text(),
"smtpport": 587
},
excel_file=self.textEdit.toPlainText())
self.obj.sent_to.connect(self.print_send)
self.obj.finished.connect(self.obj.deleteLater)
self.obj.finished.connect(self.finished_sending)
self.obj.start()
def finished_sending(self):
self.textEdit.setReadOnly(False)
self.textEdit.textChanged.connect(self.activateredbtn)
self.FileBrowse.setEnabled(True)
self.FileBrowse.clicked.connect(self.browse_File)
self.textBrowser.append("<strong>Process Finished...<strong>")
def main():
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = MainMailer(MainWindow)
return app.exec()
| 12,857
|
https://github.com/prasantkumar123/smash-problems/blob/master/main.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
smash-problems
|
prasantkumar123
|
JavaScript
|
Code
| 683
| 2,604
|
window.addEventListener('load', function(){
// console.log('hi')
var count = 0;
var searchIcon = document.getElementById('searchIcon');
var searchBox = document.getElementById('searchBox');
searchIcon.addEventListener('click', function(){
count++;
if(count % 2 != 0){
searchBox.style.height = '8rem';
searchBox.style.padding = '15px';
}else{
searchBox.style.height = '0px';
searchBox.style.padding = '0px';
}
// console.log(count);
});
// collecting problems and solutions in an array
//array for problems
var problemArr = problem.split('### Problem')
//array for solutions
var solutionArr = [];
for(let i = 0; i < problemArr.length; i++){
if (i < 10) {
solutionArr.push(`https://raw.githubusercontent.com/vineetjohn/daily-coding-problem/master/solutions/problem_00${i}.py`);
} else if (i >= 10 && i < 100) {
solutionArr.push(`https://raw.githubusercontent.com/vineetjohn/daily-coding-problem/master/solutions/problem_0${i}.py`);
} else {
solutionArr.push(`https://raw.githubusercontent.com/vineetjohn/daily-coding-problem/master/solutions/problem_${i}.py`);
}
}
//getting html elements
var mainProblem = document.getElementById('mainProblem');
var numSearch = document.getElementById('numSearch');
var strSearch = document.getElementById('strSearch');
var num = document.getElementById('num');
var str = document.getElementById('str');
var solution = document.getElementById('solution');
var solLink = document.getElementById('solLink');
// Function for search by number
numSearch.addEventListener('click', function () {
var numVal = parseInt(num.value);
if(problemArr[numVal] != undefined){
mainProblem.innerText = problemArr[numVal];
solution.style.display = 'flex';
if(numVal < 10){
solLink.href = `https://raw.githubusercontent.com/vineetjohn/daily-coding-problem/master/solutions/problem_00${numVal}.py`;
}else if(numVal >= 10 && numVal < 100){
solLink.href = `https://raw.githubusercontent.com/vineetjohn/daily-coding-problem/master/solutions/problem_0${numVal}.py`;
}else{
solLink.href = `https://raw.githubusercontent.com/vineetjohn/daily-coding-problem/master/solutions/problem_${numVal}.py`;
}
// console.log(solutionArr[numVal]);
// console.log(solLink.href)
}else{
mainProblem.innerHTML = `
<p class='err' align='center'>Please enter an integer from 1 to ${problemArr.length - 1}</p>
<div class="landPage">
<div class="heads">
<h1 class="mainHead" align="center">Smash Problems</h1>
<p class="subhead" align="center">smash at a glance</p>
</div>
<p class="info" align="center">
Click the search icon at the top right corner to search a problem.
</p>
</div>
`;
solution.style.display = 'none';
}
num.value = '';
str.value = '';
searchBox.style.height = '0px';
searchBox.style.padding = '0px';
count++;
//console.log(problemArr.length)
})
// Function for search by string
strSearch.addEventListener('click', function(){
mainProblem.innerHTML = '';
solution.style.display = 'none';
var userRegex = str.value;
if(str.value.includes('.') || str.value.includes('*')){
//console.log('includes !');
userRegex = str.value.replace(/\./g, "\\.").replace(/\*/g, "\\*");
//console.log(userRegex);
}
// var regStr = new RegExp(userRegex, 'ig');
//console.log(regStr);
var textStr = '';
var userText = str.value.replace(/^\s+/, '').replace(/\s+$/, '');
if(userText == ''){
mainProblem.innerHTML = `
<p class='err' align='center'> Hey ! what are you looking for ? You are searching an empty string hehe </p>
<div class="landPage">
<div class="heads">
<h1 class="mainHead" align="center">Smash Problems</h1>
<p class="subhead" align="center">smash at a glance</p>
</div>
<p class="info" align="center">
Click the search icon at the top right corner to search a problem.
</p>
</div>
`;
//console.log(mainProblem.innerHTML)
num.value = '';
str.value = '';
searchBox.style.height = '0px';
//console.log(searchBox.style.height);
searchBox.style.padding = '0px';
count++;
return;
}else if(userText == '.' || userText.match(/^[a-zA-Z0-9]$/) || userText.length < 2 || userText.match(/\\/) || userText.includes('\\')){
// console.log('only dot used');
mainProblem.innerHTML = ` <p class='err' align='center'> Please use more than one character and don't use backslash (\\) </p>
<div class="landPage">
<div class="heads">
<h1 class="mainHead" align="center">Smash Problems</h1>
<p class="subhead" align="center">smash at a glance</p>
</div>
<p class="info" align="center">
Click the search icon at the top right corner to search a problem.
</p>
</div>`;
num.value = '';
str.value = '';
searchBox.style.height = '0px';
// console.log(searchBox.style.height);
searchBox.style.padding = '0px';
count++;
return;
}else if (userText.match(/problem(?!s)/ig)) {
mainProblem.innerHTML = ` <p class='err' align='center'>Please don't search for Problem... All are problems here... Don't add more problems in life Haha ! <br>
Actually the "problem" word is in every problem, so it may hang your phone for few seconds... It will show results though...
</p>
<div class="landPage">
<div class="heads">
<h1 class="mainHead" align="center">Smash Problems</h1>
<p class="subhead" align="center">smash at a glance</p>
</div>
<p class="info" align="center">
Click the search icon at the top right corner to search a problem.
</p>
</div>`;
num.value = '';
str.value = '';
searchBox.style.height = '0px';
// console.log(searchBox.style.height);
searchBox.style.padding = '0px';
count++;
return;
}
//regEx and for loop to add problem on match
var regStr = new RegExp(userRegex, 'ig');
for(let i = 0; i < problemArr.length; i++){
if(problemArr[i].match(regStr) != null){
textStr = problemArr[i].replace(regStr, strReplacer).replace(/ /mg," ").replace(/(\r\n|\n|\r)/gm, "<br>");
mainProblem.innerHTML += textStr +'<br>' +
` <a href='${solutionArr[i]}' class="strSolLink" > <div class="strSolution">Solution (python) <br />
</div>
</a>` +
'<br> <hr> <br>';
}
}
if(textStr == ''){
mainProblem.innerHTML = ` <p class='err' align='center'> Oops ! No matches found !</p>
<div class="landPage">
<div class="heads">
<h1 class="mainHead" align="center">Smash Problems</h1>
<p class="subhead" align="center">smash at a glance</p>
</div>
<p class="info" align="center">
Click the search icon at the top right corner to search a problem.
</p>
</div>`;
}
num.value = '';
str.value = '';
searchBox.style.height = '0px';
//console.log(searchBox.style.height);
searchBox.style.padding = '0px';
count++;
});
function strReplacer(inp) {
return "<mark>" + inp + "</mark>"
}
});
| 16,986
|
https://github.com/madiepev/mslearn-deep-learning/blob/master/Allfiles/Labs/01-preprocess-data/script/preprocess-rapids.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
mslearn-deep-learning
|
madiepev
|
Python
|
Code
| 446
| 1,605
|
# import libraries
import os
import argparse
import cudf
import mlflow
# define functions
def main():
# Set the columns and their datatypes for conversion and parsing
cols = ['Flight_Number_Reporting_Airline', 'Year', 'Quarter', 'Month', 'DayOfWeek', 'DOT_ID_Reporting_Airline', 'OriginCityMarketID', 'DestCityMarketID', 'DepTime', 'DepDelay', 'DepDel15', 'ArrTime', 'ArrDelay', 'ArrDel15', 'CRSDepTime', 'CRSArrTime', 'AirTime', 'Distance', 'Reporting_Airline', 'IATA_CODE_Reporting_Airline', 'Origin', 'OriginCityName', 'Dest', 'DestCityName', 'Cancelled']
dtypes = {'Flight_Number_Reporting_Airline': 'float32', 'Year': 'float32', 'Quarter': 'float32', 'Month': 'float32', 'DayOfWeek': 'float32', 'DOT_ID_Reporting_Airline': 'float32', 'OriginCityMarketID': 'float32', 'DestCityMarketID': 'float32', 'DepTime': 'float32', 'DepDelay': 'float32', 'DepDel15': 'int', 'ArrTime': 'float32', 'ArrDelay': 'float32', 'ArrDel15': 'int', 'CRSDepTime': 'float32', 'CRSArrTime': 'float32', 'AirTime': 'float32', 'Distance': 'float32', 'Reporting_Airline': 'str', 'IATA_CODE_Reporting_Airline': 'str', 'Origin': 'str', 'OriginCityName': 'str', 'Dest': 'str', 'DestCityName': 'str', 'Cancelled': 'str'}
categorical_columns = ['Flight_Number_Reporting_Airline', 'DepTime', 'ArrTime', 'CRSDepTime', 'CRSArrTime', 'Reporting_Airline', 'Origin', 'OriginCityName', 'Dest', 'DestCityName', 'Airline']
# Process the full dataset and save it to file
processed_data = process_data(cols, dtypes, categorical_columns)
count_rows = len(processed_data)
mlflow.log_metric("processed rows", count_rows)
processed_data.to_csv('outputs/processed_data.csv', index=False)
# Define a function to process an entire dataset
def process_data(cols, dtypes, categorical_columns):
# Ingest - Read the CSV files into the DataFrame
data = cudf.read_csv('./data/airlines_raw.csv', cols=cols, dtypes=dtypes)[cols] # Read in data, ignoring any column not in cols
carriers = cudf.read_csv('./data/carriers.csv')
airports = cudf.read_csv('./data/airports.csv', usecols=['iata_code', 'latitude_deg', 'longitude_deg', 'elevation_ft'])
# Merge - Combine the external data with the airline data
data = cudf.merge(data, carriers, left_on='IATA_CODE_Reporting_Airline', right_on='Code', how='left')
data = cudf.merge(data, airports, left_on='Dest', right_on='iata_code', how='left')
data = cudf.merge(data, airports, left_on='Origin', right_on='iata_code', how='left')
# Rename - Add clarity to the combined dataset by renaming columns
data = data.rename(columns= { 'latitude_deg_x' : 'dest_lat', 'longitude_deg_x': 'dest_long',
'latitude_deg_y' : 'origin_lat', 'longitude_deg_y': 'origin_long',
'elevation_ft_x' : 'dest_elevation', 'elevation_ft_y' : 'origin_elevation',
'Description' : 'Airline'})
# Remove duplicates columns
data = data.drop(['iata_code_x', 'iata_code_y','IATA_CODE_Reporting_Airline', 'Code'], axis=1)
print(f'Added the following columns/features:\n { set(data.columns).difference(cols) }\n')
print(f'Data currently has {data.shape[0]} rows and {data.shape[1]} columns\n')
# Remove rows missing data
data = data.dropna()
print(f'Dropping rows with missing or NA values, data now has {data.shape[0]} rows and {data.shape[1]} columns\n')
# Encode - Convert human-readable names to corresponding computer-readable integers
encodings, mappings = data['OriginCityName'].factorize() # encode/categorize a sample feature
print("Example encoding:")
numeric_columns = []
for colname in data.columns:
if colname in categorical_columns:
values = data[colname].astype('category').cat.codes.astype('float32')
colname = 'enc_' + colname
data.insert(0, colname, values)
numeric_columns += [colname]
print(list(zip(data['OriginCityName'][0:3].values_host, encodings[0:3])))
# Remove redundant, surrogate, and unwanted columns from the data
remove_cols = set (['Year', 'Cancelled', 'DOT_ID_Reporting_Airline', 'enc_IATA_CODE_Reporting_Airline', 'ArrTime']);
output_columns = list(set(numeric_columns).difference(remove_cols))
# Add back additional columns that are used for data visualization, but not training
output_columns = output_columns + ['OriginCityName', 'DestCityName']
data = data[output_columns]
print(f'Encoded and removed extra columns, data now has {data.shape[0]} rows and {data.shape[1]} columns\n')
print(f'Removed: {remove_cols}')
print(f'Returning: {output_columns}')
return data
# run script
if __name__ == "__main__":
# add space in logs
print("\n\n")
print("*" * 60)
# run main function
main()
# add space in logs
print("*" * 60)
print("\n\n")
| 34,792
|
https://github.com/unix8net/sayhi/blob/master/src/sayhiservice/web/common/Uploader/UploadConfigInfo.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
sayhi
|
unix8net
|
C#
|
Code
| 228
| 565
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace common
{
public class WaterPosition
{
public float X { get; set; }
public float Y { get; set; }
}
public enum ThumbnailMode
{
/// <summary>
/// 按指定宽高适应缩小
/// </summary>
HW = 0,
/// <summary>
/// 按宽度等比缩小
/// </summary>
W = 1,
/// <summary>
/// 按高度等比缩小
/// </summary>
H = 2,
/// <summary>
/// 按指定宽高等比剪切缩小
/// </summary>
Cut = 3,
Ration = 4,
/// <summary>
/// 按指定宽高填充(不剪切)缩小
/// </summary>
Fill = 5,
Orgion
}
public enum WaterPositionOptions
{
LeftTop = 0,
RightTop = 1,
Middle = 2,
LeftBottom = 3,
RightBottom = 4
}
public class UploadConfigInfo : ICloneable
{
public string Key { get; set; }
public string URL { get; set; }
public bool IsImg { get; set; }
public string FileNamePrefix { get; set; }
public string FileExt { get; set; }
public int MaxSize { get; set; }
public bool ToThumbnail { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public ThumbnailMode ThumbnailMode { get; set; }
public string OtherThumbnail { get; set; }
public int MaxModeSize { get; set; }
public ThumbnailMode MaxMode { get; set; }
public bool ToWater { get; set; }
public WaterPositionOptions WaterPosition { get; set; }
#region ICloneable 成员
public object Clone()
{
return MemberwiseClone();
}
#endregion
}
}
| 26,998
|
https://github.com/Noorbakht/Offensive-Tweet-Detection/blob/master/node_modules/rainbow-node-sdk/lib/services/ImsService.js
|
Github Open Source
|
Open Source
|
MIT
| null |
Offensive-Tweet-Detection
|
Noorbakht
|
JavaScript
|
Code
| 4,015
| 11,072
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const ErrorManager_1 = require("../common/ErrorManager");
const Conversation_1 = require("../common/models/Conversation");
const Emoji_1 = require("../common/Emoji");
const XMPPUtils_1 = require("../common/XMPPUtils");
const Utils_1 = require("../common/Utils");
const Utils_2 = require("../common/Utils");
const LOG_ID = "IM/SVCE - ";
let IMService =
/**
* @module
* @name IMService
* @version 1.69.0-debug-24th-03-2020--03-54-58.0
* @public
* @description
* This module manages Instant Messages. It allows to send messages to a user or a bubble.
* <br><br>
* The main methods proposed in that module allow to: <br>
* - Send a message to a user <br>
* - Send a message to a bubble <br>
* - Mark a message as read <br>
*/
class IMService {
constructor(_eventEmitter, _logger, _imOptions, _startConfig) {
this.ready = false;
this._startConfig = _startConfig;
this._xmpp = null;
this._rest = null;
this._s2s = null;
this._options = {};
this._useXMPP = false;
this._useS2S = false;
this._conversations = null;
this._logger = _logger;
this._eventEmitter = _eventEmitter;
this._pendingMessages = {};
this._imOptions = _imOptions;
this._eventEmitter.on("evt_internal_onreceipt", this._onmessageReceipt.bind(this));
this.ready = false;
}
get startConfig() {
return this._startConfig;
}
start(_options, _core) {
let that = this;
return new Promise(function (resolve, reject) {
try {
that._xmpp = _core._xmpp;
that._rest = _core._rest;
that._options = _options;
that._s2s = _core._s2s;
that._useXMPP = that._options.useXMPP;
that._useS2S = that._options.useS2S;
that._conversations = _core.conversations;
that._bulles = _core.bubbles;
that._fileStorage = _core.fileStorage;
that._presence = _core.presence;
that.ready = true;
resolve();
}
catch (err) {
return reject(err);
}
});
}
stop() {
let that = this;
return new Promise(function (resolve, reject) {
try {
that._xmpp = null;
that.ready = false;
resolve();
}
catch (err) {
return reject(err);
}
});
}
/**
* @public
* @since 1.39
* @method getMessagesFromConversation
* @instance
* @description
* <b>(beta)</b> Retrieve the list of messages from a conversation <br/>
* Calling several times this method will load older message from the history (pagination) <br/>
* @param {Conversation} conversation The conversation
* @param {Number} intNbMessage The number of messages to retrieve. Optional. Default value is 30. Maximum value is 100
* @async
* @return {Promise<Conversation, ErrorManager>}
* @fulfil {Conversation, ErrorManager} Return the conversation updated with the list of messages requested or an error (reject) if there is no more messages to retrieve
* @category async
*/
getMessagesFromConversation(conversation, intNbMessage) {
if (!conversation) {
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'conversation' is missing or null" }));
}
intNbMessage = intNbMessage
? Math.min(intNbMessage, 100)
: 30;
return this
._conversations
.getHistoryPage(conversation, intNbMessage);
}
/**
* @public
* @since 1.39
* @method getMessageFromConversationById
* @instance
* @description
* <b>(beta)</b> Retrieve a specific message in a conversation using its id <br/>
* @param {Conversation} conversation The conversation where to search for the message
* @param {String} strMessageId The message id
* @return {Message} The message if found or null
*/
getMessageFromConversationById(conversation, strMessageId) {
return __awaiter(this, void 0, void 0, function* () {
let that = this;
if (!conversation) {
return Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'conversation' is missing or null" });
}
if (!strMessageId) {
return Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'strMessageId' is missing or empty" });
}
that._logger.log("internal", LOG_ID + "(getMessageFromConversationById) conversation : ", conversation, ", strMessageId : ", strMessageId);
let message = conversation.getMessageById(strMessageId);
// Add FileDescriptor if needed
if (message && message.oob && message.oob.url) {
message.shortFileDescriptor = yield that._fileStorage.getFileDescriptorById(message.oob.url.substring(message.oob.url.lastIndexOf("/") + 1));
}
return message;
});
}
/**
* @public
* @since 1.39
* @method getMessageFromBubbleById
* @instance
* @description
* Retrieve a specific message in a bubble using its id <br/>
* @param {Bubble} bubble The bubble where to search for the message
* @param {String} strMessageId The message id
* @return {Message} The message if found or null
*/
getMessageFromBubbleById(bubble, strMessageId) {
return __awaiter(this, void 0, void 0, function* () {
let that = this;
if (!bubble) {
return Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'bubble' is missing or null" });
}
if (!strMessageId) {
return Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'strMessageId' is missing or empty" });
}
let conversation = yield that._conversations.getConversationByBubbleId(bubble.id);
if (!conversation) {
return Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'bubble' don't have a conversation" });
}
if (conversation.type !== Conversation_1.Conversation.Type.ROOM) {
return Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'conversation' is not a bubble conversation" });
}
that._logger.log("internal", LOG_ID + "(getMessageFromBubbleById) conversation : ", conversation, ", strMessageId : ", strMessageId);
let message = conversation.getMessageById(strMessageId);
if (message && message.oob && message.oob.url) {
let fileDescriptorId = message.oob.url.substring(message.oob.url.lastIndexOf("/") + 1);
that._logger.log("internal", LOG_ID + "(getMessageFromBubbleById) oob url defined so build shortFileDescriptor :", fileDescriptorId);
message.shortFileDescriptor = yield that._fileStorage.getFileDescriptorById(fileDescriptorId);
}
return message;
});
}
/**
* @public
* @since 1.39
* @method sendMessageToConversation
* @instance
* @description
* <b>(beta)</b> Send a instant message to a conversation<br>
* This method works for sending messages to a one-to-one conversation or to a bubble conversation
* @param {Conversation} conversation The conversation recipient
* @param {String} message The message to send
* @param {String} [lang=en] The content language used
* @param {Object} [content] Allow to send alternative text base content
* @param {String} [content.type=text/markdown] The content message type
* @param {String} [content.message] The content message body
* @param {String} [subject] The message subject
* @async
* @return {Promise<Message, ErrorManager>}
* @fulfil {Message} the message sent, or null in case of error, as parameter of the resolve
* @category async
*/
sendMessageToConversation(conversation, message, lang, content, subject) {
return __awaiter(this, void 0, void 0, function* () {
let that = this;
if (!conversation) {
this._logger.log("warn", LOG_ID + "(sendMessageToContact) bad or empty 'conversation' parameter.");
this._logger.log("internalerror", LOG_ID + "(sendMessageToContact) bad or empty 'conversation' parameter : ", conversation);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'conversation' is missing or null" }));
}
if (!message) {
this._logger.log("warn", LOG_ID + "(sendMessageToContact) bad or empty 'message' parameter.");
this._logger.log("internalerror", LOG_ID + "(sendMessageToContact) bad or empty 'message' parameter : ", message);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'message' is missing or null" }));
}
if (message.length > that._imOptions.messageMaxLength) {
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'strMessage' should be lower than " + that._imOptions.messageMaxLength + " characters" }));
}
let msgSent = undefined; //Promise.reject(Object.assign(ErrorManager.getErrorManager().BAD_REQUEST, {msg: " sent message failed."}));
if (this._useXMPP) {
msgSent = conversation.type === Conversation_1.Conversation.Type.ONE_TO_ONE ? this.sendMessageToJid(message, conversation.id, lang, content, subject) : this.sendMessageToBubbleJid(message, conversation.id, lang, content, subject, undefined);
}
if ((this._useS2S)) {
/*
{
"message": {
"subject": "Greeting",
"lang": "en",
"contents": [
{
"type": "text/markdown",
"data": "## Hello Bob"
}
],
"body": "Hello world"
}
}
*/
let msg = {
"message": {
"subject": subject,
"lang": lang,
"contents": content,
// [
// {
// "type": "text/markdown",
// "data": "## Hello Bob"
// }
// ],
"body": message
}
};
if (!conversation.dbId) {
conversation = yield this._conversations.createServerConversation(conversation);
this._logger.log("internal", LOG_ID + "(sendMessageToConversation) conversation : ", conversation);
}
msgSent = this._s2s.sendMessageInConversation(conversation.dbId, msg);
}
return msgSent.then((messageSent) => {
this._conversations.storePendingMessage(conversation, messageSent);
//conversation.messages.push(messageSent);
//this.conversations.getServerConversations();
return messageSent;
});
});
}
/**
* @public
* @method sendMessageToContact
* @instance
* @description
* Send a one-2-one message to a contact
* @param {String} message The message to send
* @param {Contact} contact The contact (should have at least a jid_im property)
* @param {String} [lang=en] The content language used
* @param {Object} [content] Allow to send alternative text base content
* @param {String} [content.type=text/markdown] The content message type
* @param {String} [content.message] The content message body
* @param {String} [subject] The message subject
* @async
* @return {Promise<Message, ErrorManager>}
* @fulfil {Message} the message sent, or null in case of error, as parameter of the resolve
* @category async
*/
sendMessageToContact(message, contact, lang, content, subject) {
if (!contact || !contact.jid_im) {
this._logger.log("warn", LOG_ID + "(sendMessageToContact) bad or empty 'contact' parameter.");
this._logger.log("internalerror", LOG_ID + "(sendMessageToContact) bad or empty 'contact' parameter : ", contact);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'contact' is missing or null" }));
}
return this.sendMessageToJid(message, contact.jid_im, lang, content, subject);
}
/**
* @private
* @description
* Store the message in a pending list. This pending list is used to wait the "_onReceipt" event from server when a message is sent.
* It allow to give back the status of the sending process.
* @param conversation
* @param message
*/
/*storePendingMessage(message) {
this._pendingMessages[message.id] = {
// conversation: conversation,
message: message
};
} // */
/**
* @private
* @description
* delete the message in a pending list. This pending list is used to wait the "_onReceipt" event from server when a message is sent.
* It allow to give back the status of the sending process.
* @param message
*/
/* removePendingMessage(message) {
delete this._pendingMessages[message.id];
} // */
_onmessageReceipt(receipt) {
let that = this;
return;
/*if (this._pendingMessages[receipt.id]) {
let messagePending = this._pendingMessages[receipt.id].message;
that._logger.log("warn", LOG_ID + "(_onmessageReceipt) the pending message received from server, so remove from pending", messagePending);
this.removePendingMessage(messagePending);
}
that._logger.log("warn", LOG_ID + "(_onmessageReceipt) the pending messages : ", that._pendingMessages);
// */
}
/**
* @public
* @method sendMessageToJid
* @instance
* @description
* Send a one-2-one message to a contact identified by his Jid
* @param {String} message The message to send
* @param {String} jid The contact Jid
* @param {String} [lang=en] The content language used
* @param {Object} [content] Allow to send alternative text base content
* @param {String} [content.type=text/markdown] The content message type
* @param {String} [content.message] The content message body
* @param {String} [subject] The message subject
* @async
* @return {Promise<Message, ErrorManager>}
* @fulfil {Message} - the message sent, or null in case of error, as parameter of the resolve
* @category async
*/
sendMessageToJid(message, jid, lang, content, subject) {
return __awaiter(this, void 0, void 0, function* () {
let that = this;
if (!lang) {
lang = "en";
}
if (!message) {
this._logger.log("warn", LOG_ID + "(sendMessageToJid) bad or empty 'message' parameter.");
this._logger.log("internalerror", LOG_ID + "(sendMessageToJid) bad or empty 'message' parameter : ", message);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad or empty 'message' parameter" }));
}
// Check size of the message
let messageSize = message.length;
if (content && content.message && typeof content.message === "string") {
messageSize += content.message.length;
}
if (messageSize > that._imOptions.messageMaxLength) {
this._logger.log("warn", LOG_ID + "(sendMessageToJid) message not sent. The content is too long (" + messageSize + ")", jid);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'strMessage' should be lower than " + that._imOptions.messageMaxLength + " characters" }));
}
if (!jid) {
this._logger.log("warn", LOG_ID + "(sendMessageToJid) bad or empty 'jid' parameter", jid);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad or empty 'jid' parameter" }));
}
let messageUnicode = Emoji_1.shortnameToUnicode(message);
jid = XMPPUtils_1.XMPPUTils.getXMPPUtils().getBareJIDFromFullJID(jid);
let messageSent = Promise.reject();
if (this._useXMPP) {
messageSent = yield this._xmpp.sendChatMessage(messageUnicode, jid, lang, content, subject, undefined);
}
/*
this.storePendingMessage(messageSent);
await utils.until(() => {
return this._pendingMessages[messageSent.id] === undefined;
}
, "Wait for the send chat message to be received by server", 30000);
this.removePendingMessage(messageSent);
this._logger.log("debug", LOG_ID + "(sendMessageToJid) _exiting_");
// */
return messageSent;
});
}
/**
* @public
* @method sendMessageToJidAnswer
* @instance
* @description
* Send a reply to a one-2-one message to a contact identified by his Jid
* @param {String} message The message to send
* @param {String} jid The contact Jid
* @param {String} [lang=en] The content language used
* @param {Object} [content] Allow to send alternative text base content
* @param {String} [content.type=text/markdown] The content message type
* @param {String} [content.message] The content message body
* @param {String} [subject] The message subject
* @param {String} [answeredMsg] The message answered
* @async
* @return {Promise<Message, ErrorManager>}
* @fulfil {Message} - the message sent, or null in case of error, as parameter of the resolve
* @category async
*/
sendMessageToJidAnswer(message, jid, lang, content, subject, answeredMsg) {
return __awaiter(this, void 0, void 0, function* () {
let that = this;
if (!lang) {
lang = "en";
}
if (!message) {
this._logger.log("warn", LOG_ID + "(sendMessageToJidAnswer) bad or empty 'message' parameter.");
this._logger.log("internalerror", LOG_ID + "(sendMessageToJidAnswer) bad or empty 'message' parameter : ", message);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad or empty 'message' parameter" }));
}
let typofansweredMsg = answeredMsg instanceof Object;
if (!typofansweredMsg && answeredMsg !== null) {
that._logger.log("warn", LOG_ID + "(sendMessageToJidAnswer) bad 'answeredMsg' parameter.");
that._logger.log("internalerror", LOG_ID + "(sendMessageToJidAnswer) bad 'answeredMsg' parameter : ", answeredMsg);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad 'answeredMsg' parameter" }));
}
// Check size of the message
let messageSize = message.length;
if (content && content.message && typeof content.message === "string") {
messageSize += content.message.length;
}
if (messageSize > that._imOptions.messageMaxLength) {
that._logger.log("warn", LOG_ID + "(sendMessageToJidAnswer) message not sent. The content is too long (" + messageSize + ")", jid);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'strMessage' should be lower than " + that._imOptions.messageMaxLength + " characters" }));
}
if (!jid) {
that._logger.log("warn", LOG_ID + "(sendMessageToJidAnswer) bad or empty 'jid' parameter", jid);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad or empty 'jid' parameter" }));
}
let messageUnicode = Emoji_1.shortnameToUnicode(message);
jid = XMPPUtils_1.XMPPUTils.getXMPPUtils().getBareJIDFromFullJID(jid);
let messageSent = yield this._xmpp.sendChatMessage(messageUnicode, jid, lang, content, subject, answeredMsg);
/*
this.storePendingMessage(messageSent);
await utils.until(() => {
return this._pendingMessages[messageSent.id] === undefined;
}
, "Wait for the send chat message to be received by server", 30000);
this.removePendingMessage(messageSent);
this._logger.log("debug", LOG_ID + "(sendMessageToJid) _exiting_");
// */
return messageSent;
});
}
/**
* @public
* @method sendMessageToBubble
* @instance
* @description
* Send a message to a bubble
* @param {String} message The message to send
* @param {Bubble} bubble The bubble (should at least have a jid property)
* @param {String} [lang=en] The content language used
* @param {Object} [content] Allow to send alternative text base content
* @param {String} [content.type=text/markdown] The content message type
* @param {String} [content.message] The content message body
* @param {String} [subject] The message subject
* @param {array} mentions array containing a list of JID of contact to mention or a string containing a sigle JID of the contact.
* @async
* @return {Promise<Message, ErrorManager>}
* @fulfil {Message} the message sent, or null in case of error, as parameter of the resolve
* @category async
*/
sendMessageToBubble(message, bubble, lang, content, subject, mentions) {
if (!bubble || !bubble.jid) {
this._logger.log("warn", LOG_ID + "(sendMessageToBubble) bad or empty 'bubble' parameter.");
this._logger.log("internalerror", LOG_ID + "(sendMessageToBubble) bad or empty 'bubble' parameter : ", bubble);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad or empty 'bubble' parameter" }));
}
return this.sendMessageToBubbleJid(message, bubble.jid, lang, content, subject, mentions);
}
/**
* @public
* @method sendMessageToBubbleJid
* @instance
* @description
* Send a message to a bubble identified by its JID
* @param {String} message The message to send
* @param {String} jid The bubble JID
* @param {String} [lang=en] The content language used
* @param {Object} [content] Allow to send alternative text base content
* @param {String} [content.type=text/markdown] The content message type
* @param {String} [content.message] The content message body
* @param {String} [subject] The message subject
* @param {array} mentions array containing a list of JID of contact to mention or a string containing a sigle JID of the contact.
* @async
* @return {Promise<Message, ErrorManager>}
* @fulfil {Message} the message sent, or null in case of error, as parameter of the resolve
* @category async
*/
sendMessageToBubbleJid(message, jid, lang, content, subject, mentions) {
return __awaiter(this, void 0, void 0, function* () {
let that = this;
if (!lang) {
lang = "en";
}
if (!message) {
that._logger.log("warn", LOG_ID + "(sendMessageToBubbleJid) bad or empty 'message' parameter.");
that._logger.log("internalerror", LOG_ID + "(sendMessageToBubbleJid) bad or empty 'message' parameter : ", message);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad or empty 'message' parameter" }));
}
// Check size of the message
let messageSize = message.length;
if (content && content.message && typeof content.message === "string") {
messageSize += content.message.length;
}
if (messageSize > that._imOptions.messageMaxLength) {
that._logger.log("warn", LOG_ID + "(sendMessageToBubbleJid) message not sent. The content is too long (" + messageSize + ")", jid);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'strMessage' should be lower than " + that._imOptions.messageMaxLength + " characters" }));
}
if (!jid) {
that._logger.log("debug", LOG_ID + "(sendMessageToBubbleJid) bad or empty 'jid' parameter", jid);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad or empty 'jid' parameter" }));
}
let messageUnicode = Emoji_1.shortnameToUnicode(message);
jid = XMPPUtils_1.XMPPUTils.getXMPPUtils().getRoomJIDFromFullJID(jid);
let bubble = yield that._bulles.getBubbleByJid(jid);
that._logger.log("internal", LOG_ID + "(sendMessageToBubbleJid) getBubbleByJid ", bubble);
if (bubble.isActive) {
let messageSent1 = that._xmpp.sendChatMessageToBubble(messageUnicode, jid, lang, content, subject, undefined, mentions);
return messageSent1;
}
else {
try {
that._logger.log("debug", LOG_ID + "(sendMessageToBubbleJid) bubble is not active, so resume it before send the message.");
that._logger.log("internal", LOG_ID + "(sendMessageToBubbleJid) bubble is not active, so resume it before send the message. bubble : ", bubble);
yield that._presence.sendInitialBubblePresence(bubble.jid);
//that._logger.log("debug", LOG_ID + "(sendMessageToBubbleJid) sendInitialBubblePresence succeed ");
yield Utils_1.until(() => {
return bubble.isActive === true;
}, "Wait for the Bubble " + bubble.jid + " to be active");
//that._logger.log("debug", LOG_ID + "(sendMessageToBubbleJid) until succeed, so the bubble is now active, send the message.");
let messageSent = that._xmpp.sendChatMessageToBubble(messageUnicode, jid, lang, content, subject, undefined, mentions);
return messageSent;
}
catch (err) {
return Promise.reject({ message: "The sending message process failed!", error: err });
}
}
});
}
/**
* @public
* @method sendMessageToBubbleJidAnswer
* @instance
* @description
* Send a message to a bubble identified by its JID
* @param {String} message The message to send
* @param {String} jid The bubble JID
* @param {String} [lang=en] The content language used
* @param {Object} [content] Allow to send alternative text base content
* @param {String} [content.type=text/markdown] The content message type
* @param {String} [content.message] The content message body
* @param {String} [subject] The message subject
* @param {String} [answeredMsg] The message answered
* @param {array} mentions array containing a list of JID of contact to mention or a string containing a sigle JID of the contact.
* @async
* @return {Promise<Message, ErrorManager>}
* @fulfil {Message} the message sent, or null in case of error, as parameter of the resolve
* @category async
*/
sendMessageToBubbleJidAnswer(message, jid, lang, content, subject, answeredMsg, mentions) {
return __awaiter(this, void 0, void 0, function* () {
let that = this;
if (!lang) {
lang = "en";
}
if (!message) {
that._logger.log("warn", LOG_ID + "(sendMessageToBubbleJidAnswer) bad or empty 'message' parameter.");
that._logger.log("internalerror", LOG_ID + "(sendMessageToBubbleJidAnswer) bad or empty 'message' parameter : ", message);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad or empty 'message' parameter" }));
}
let typofansweredMsg = answeredMsg instanceof Object;
if (!typofansweredMsg && answeredMsg !== null) {
that._logger.log("warn", LOG_ID + "(sendMessageToBubbleJidAnswer) bad 'answeredMsg' parameter.");
that._logger.log("internalerror", LOG_ID + "(sendMessageToBubbleJidAnswer) bad 'answeredMsg' parameter : ", answeredMsg);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad 'answeredMsg' parameter" }));
}
// Check size of the message
let messageSize = message.length;
if (content && content.message && typeof content.message === "string") {
messageSize += content.message.length;
}
if (messageSize > that._imOptions.messageMaxLength) {
that._logger.log("warn", LOG_ID + "(sendMessageToBubbleJidAnswer) message not sent. The content is too long (" + messageSize + ")", jid);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'strMessage' should be lower than " + that._imOptions.messageMaxLength + " characters" }));
}
if (!jid) {
that._logger.log("debug", LOG_ID + "(sendMessageToBubbleJidAnswer) bad or empty 'jid' parameter", jid);
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad or empty 'jid' parameter" }));
}
let messageUnicode = Emoji_1.shortnameToUnicode(message);
jid = XMPPUtils_1.XMPPUTils.getXMPPUtils().getRoomJIDFromFullJID(jid);
let bubble = yield that._bulles.getBubbleByJid(jid);
that._logger.log("internal", LOG_ID + "(sendMessageToBubbleJidAnswer) getBubbleByJid ", bubble);
if (bubble.isActive) {
let messageSent = that._xmpp.sendChatMessageToBubble(messageUnicode, jid, lang, content, subject, answeredMsg, mentions);
return messageSent;
}
else {
try {
that._logger.log("debug", LOG_ID + "(sendMessageToBubbleJidAnswer) bubble is not active, so resume it before send the message.");
that._logger.log("internal", LOG_ID + "(sendMessageToBubbleJidAnswer) bubble is not active, so resume it before send the message. bubble : ", bubble);
yield that._xmpp.sendInitialBubblePresence(bubble.jid);
//that._logger.log("debug", LOG_ID + "(sendMessageToBubbleJidAnswer) sendInitialBubblePresence succeed ");
yield Utils_1.until(() => {
return bubble.isActive === true;
}, "Wait for the Bubble " + bubble.jid + " to be active");
//that._logger.log("debug", LOG_ID + "(sendMessageToBubbleJidAnswer) until succeed, so the bubble is now active, send the message.");
let messageSent = that._xmpp.sendChatMessageToBubble(messageUnicode, jid, lang, content, subject, answeredMsg, mentions);
return messageSent;
}
catch (err) {
return Promise.reject({ message: "The sending message process failed!", error: err });
}
}
});
}
/**
* @public
* @method sendIsTypingStateInBubble
* @instance IMService
* @description
* Switch the "is typing" state in a bubble/room<br>
* @param {Bubble} bubble The destination bubble
* @param {boolean} status The status, true for setting "is Typing", false to remove it
* @return {Object} Return a promise with no parameter when succeed.
*/
sendIsTypingStateInBubble(bubble, status) {
let that = this;
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
if (!bubble) {
return reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'bubble' is missing or null" }));
}
/* else if (!status) {
reject(Object.assign( ErrorManager.getErrorManager().BAD_REQUEST, {msg: "Parameter 'status' is missing or null"}));
} // */
else {
if (!bubble.jid) {
return reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'bubble': this bubble isn't a valid one" }));
}
else {
that._logger.log("internal", LOG_ID + "sendIsTypingStateInBubble - bubble : ", bubble, "status : ", status);
that._conversations.getBubbleConversation(bubble.jid, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined).then(function (conversation) {
return __awaiter(this, void 0, void 0, function* () {
if (!conversation) {
return reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().OTHERERROR("ERRORNOTFOUND", "ERRORNOTFOUND"), { msg: "No 'conversation' found for this bubble" }));
}
else {
yield that._xmpp.sendIsTypingState(conversation, status);
//conversationService.sendIsTypingState(conversation, status);
resolve();
}
});
}).catch((err) => {
return reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().OTHERERROR("ERRORNOTFOUND", "ERRORNOTFOUND"), { msg: "No 'conversation' found for this bubble : " + err }));
});
}
}
}));
} // */
/**
* @public
* @method sendIsTypingStateInConversation
* @instance IMService
* @description
* Switch the "is typing" state in a conversation<br>
* @param {Conversation} conversation The conversation recipient
* @param {boolean} status The status, true for setting "is Typing", false to remove it
* @return Return a promise with no parameter when succeed
*/
sendIsTypingStateInConversation(conversation, status) {
let that = this;
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
if (!conversation) {
return reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Parameter 'conversation' is missing or null" }));
}
/* else if (!status) {
reject(Object.assign( ErrorManager.getErrorManager().BAD_REQUEST, {msg: "Parameter 'status' is missing or null"}));
} // */
else {
conversation = conversation.id ? that._conversations.getConversationById(conversation.id) : null;
if (!conversation) {
return reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().OTHERERROR("ERRORNOTFOUND", "ERRORNOTFOUND"), { msg: "Parameter 'conversation': this conversation doesn't exist" }));
}
else {
yield that._xmpp.sendIsTypingState(conversation, status);
resolve();
}
}
}));
}
/**
* @public
* @method markMessageAsRead
* @instance
* @description
* Send a 'read' receipt to the recipient
* @param {Message} messageReceived The message received to mark as read
* @async
* @return {Promise}
* @fulfil {} return nothing in case of success or an ErrorManager Object depending the result
* @category async
*/
markMessageAsRead(messageReceived) {
if (!messageReceived) {
this._logger.log("warn", LOG_ID + "(markMessageAsRead) bad or empty 'messageReceived' parameter");
return Promise.reject(Object.assign(ErrorManager_1.ErrorManager.getErrorManager().BAD_REQUEST, { msg: "Bad or empty 'messageReceived' parameter" }));
}
if (messageReceived.isEvent) {
this._logger.log("warn", LOG_ID + "(markMessageAsRead) No receipt for 'event' message");
return ErrorManager_1.ErrorManager.getErrorManager().OK;
}
this._logger.log("internal", LOG_ID + "(markMessageAsRead) 'messageReceived' parameter : ", messageReceived);
if (this._useXMPP) {
return this._xmpp.markMessageAsRead(messageReceived);
}
if ((this._useS2S)) {
if (messageReceived.conversation) {
let conversationId = messageReceived.conversation.dbId ? messageReceived.conversation.dbId : messageReceived.conversation.id;
let messageId = messageReceived.id;
return this._rest.markMessageAsRead(conversationId, messageId);
}
else {
return Promise.reject('No conversation found in message.');
}
}
}
/**
* @private
* @method enableCarbon
* @instance
* @description
* Enable message carbon XEP-0280
* @async
* @return {Promise}
* @fulfil {} return nothing in case of success or an ErrorManager Object depending the result
* @category async
*/
enableCarbon() {
let that = this;
return new Promise((resolve) => {
if (this._useXMPP) {
that._eventEmitter.once("rainbow_oncarbonactivated", function fn_oncarbonactivated() {
that._logger.log("info", LOG_ID + "(enableCarbon) XEP-280 Message Carbon activated");
that._eventEmitter.removeListener("rainbow_oncarbonactivated", fn_oncarbonactivated);
resolve();
});
that._xmpp.enableCarbon();
}
else if (this._useS2S) {
resolve();
}
else {
resolve();
}
});
}
};
IMService = __decorate([
Utils_1.logEntryExit(LOG_ID),
Utils_2.isStarted([])
/**
* @module
* @name IMService
* @version 1.69.0-debug-24th-03-2020--03-54-58.0
* @public
* @description
* This module manages Instant Messages. It allows to send messages to a user or a bubble.
* <br><br>
* The main methods proposed in that module allow to: <br>
* - Send a message to a user <br>
* - Send a message to a bubble <br>
* - Mark a message as read <br>
*/
], IMService);
exports.IMService = IMService;
module.exports.IMService = IMService;
//# sourceMappingURL=ImsService.js.map
| 42,544
|
https://github.com/JohnSodium/tflite-micro/blob/master/tensorflow/lite/micro/integration_tests/seanet/transpose_conv/Makefile.inc
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
tflite-micro
|
JohnSodium
|
Makefile
|
Code
| 51
| 835
|
integration_tests_seanet_transpose_conv_GENERATOR_INPUTS := \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv0.tflite \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv1.tflite \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv2.tflite \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv3.tflite \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv4.tflite \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv0_input0_int32.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv0_input1_int16.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv0_golden_int16.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv1_input0_int32.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv1_input1_int16.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv1_golden_int16.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv2_input0_int32.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv2_input1_int16.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv2_golden_int16.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv3_input0_int32.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv3_input1_int16.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv3_golden_int16.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv4_input0_int32.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv4_input1_int16.csv \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/transpose_conv4_golden_int16.csv \
integration_tests_seanet_transpose_conv_SRCS := \
tensorflow/lite/micro/integration_tests/seanet/transpose_conv/integration_tests.cc
$(eval $(call microlite_test,integration_tests_seanet_transpose_conv_test,\
$(integration_tests_seanet_transpose_conv_SRCS),,$(integration_tests_seanet_transpose_conv_GENERATOR_INPUTS)))
| 7,141
|
https://github.com/shihyu/golang/blob/master/goWebActualCombat/chapter7/picShow.go
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
golang
|
shihyu
|
Go
|
Code
| 137
| 703
|
//++++++++++++++++++++++++++++++++++++++++
// 《Go Web编程实战派从入门到精通》源码
//++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// 仓库地址:https://gitee.com/shirdonl/goWebActualCombat
// 仓库地址:https://github.com/shirdonl/goWebActualCombat
//++++++++++++++++++++++++++++++++++++++++
package main
import (
"fmt"
"image"
"image/color"
"image/jpeg"
"io/ioutil"
"log"
"os"
"github.com/golang/freetype"
)
func main() {
//需要加水印的图片
imgfile, _ := os.Open("./pic.jpg")
defer imgfile.Close()
jpgimg, _ := jpeg.Decode(imgfile)
img := image.NewNRGBA(jpgimg.Bounds())
for y := 0; y < img.Bounds().Dy(); y++ {
for x := 0; x < img.Bounds().Dx(); x++ {
img.Set(x, y, jpgimg.At(x, y))
}
}
//拷贝一个字体文件到运行目录
fontBytes, err := ioutil.ReadFile("simsun.ttc")
if err != nil {
log.Println(err)
}
font, err := freetype.ParseFont(fontBytes)
if err != nil {
log.Println(err)
}
f := freetype.NewContext()
f.SetDPI(72)
f.SetFont(font)
f.SetFontSize(12)
f.SetClip(jpgimg.Bounds())
f.SetDst(img)
f.SetSrc(image.NewUniform(color.RGBA{R: 255, G: 0, B: 0, A: 255}))
pt := freetype.Pt(img.Bounds().Dx()-200, img.Bounds().Dy()-12)
_, err = f.DrawString("Shirdon", pt)
//draw.Draw(img,jpgimg.Bounds(),jpgimg,image.ZP,draw.Over)
//保存到新文件中
newfile, _ := os.Create("./aaa.jpg")
defer newfile.Close()
err = jpeg.Encode(newfile, img, &jpeg.Options{100})
if err != nil {
fmt.Println(err)
}
}
| 16,391
|
https://github.com/ngquerol/DockerStatsMenu/blob/master/DockerStatsMenu/CompletionsWindow.swift
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
DockerStatsMenu
|
ngquerol
|
Swift
|
Code
| 61
| 179
|
//
// CompletionsWindow.swift
// DockerStatsMenu
//
// Created by Nicolas Gaulard-Querol on 29/12/2016.
// Copyright © 2016 Nicolas Gaulard-Querol. All rights reserved.
//
import Cocoa
class CompletionsWindow: NSWindow {
override init(contentRect: NSRect, styleMask style: NSWindowStyleMask, backing bufferingType: NSBackingStoreType, defer flag: Bool) {
super.init(contentRect: contentRect, styleMask: style, backing: bufferingType, defer: flag)
self.hasShadow = true
self.backgroundColor = .clear
self.isOpaque = false
}
}
| 22,525
|
https://github.com/lonisletend/smartblog/blob/master/app/models/record.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
smartblog
|
lonisletend
|
Python
|
Code
| 49
| 200
|
from app import db
from datetime import datetime
class Record(db.Model):
id = db.Column(db.Integer, primary_key=True)
art_id = db.Column(db.Integer, index=True)
user_id = db.Column(db.Integer, index=True)
username = db.Column(db.String(32))
rtime = db.Column(db.DateTime, index=True, default=datetime.now)
ip = db.Column(db.String(32))
platform = db.Column(db.String(32))
browser = db.Column(db.String(32))
version = db.Column(db.String(32))
language = db.Column(db.String(32))
is_deleted = db.Column(db.Integer, default=0)
| 13,660
|
https://github.com/nlysenko/Triplr/blob/master/components/@triplr/mobile/src/app/components/TripName/index.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
Triplr
|
nlysenko
|
TypeScript
|
Code
| 56
| 203
|
/**
*
* TripName
*
*/
import { View, Text } from 'react-native'
import { Trip } from '@/app/types/Trip'
import { styles } from './styles'
interface Props {
trip: Trip
}
export function TripName({ trip }: Props) {
return (
<View>
<Text style={styles.tripName}>{trip.name}</Text>
<View style={styles.tripDuration}>
<Text style={styles.tripDate}>{trip.dateEnd}</Text>
<Text style={[styles.tripDate, styles.tab]}>-</Text>
<Text style={styles.tripDate}>{trip.dateStart}</Text>
</View>
</View>
)
}
| 28,300
|
https://github.com/hbussell/pinax-tracker/blob/master/apps/pyvcal/revisionproperties.py
|
Github Open Source
|
Open Source
|
MIT
| 2,010
|
pinax-tracker
|
hbussell
|
Python
|
Code
| 90
| 260
|
class RevisionProperties(object):
"""Metadata for a revision"""
def get_revision(self):
"""Return the revision to which these properties apply."""
pass
def get_commit_message(self):
"""Return a unicode string containing the commit message for the Revision."""
pass
def get_committer(self):
"""Get the User who committed the Revision"""
pass
def get_time(self):
"""Return the datetime of the revision"""
pass
def get_revision_id(self):
"""Return the revision identifier of the revision."""
pass
## See get_revision
revision = property(get_revision)
## See get_commit_message
commit_message = property(get_commit_message)
## See get_committer
committer = property(get_committer)
## See get_time
time = property(get_time)
## See get_revision_id
revision_id = property(get_revision_id)
| 18,729
|
https://github.com/pradeeplx/giving-impact/blob/master/application/views/donate/index.php
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
giving-impact
|
pradeeplx
|
PHP
|
Code
| 745
| 2,667
|
<?php $this->load->view('components/_external_header', array( 'title_action' => 'Donate' )) ?>
<div class="row main">
<div class="small-12 medium-7 medium-push-5 columns">
<div class="row">
<header>
<div class="small-12 columns">
<div class="logo">
<?php if ($account->image_url) : ?><img src="<?php echo $account->image_url ?>" class="org-logo" /><?php endif ?>
</div>
<h1>
You are donating to <strong><?php echo $campaign->title ?></strong>.
</h1>
</div>
</header>
</div>
<?php if( empty($campaign->status) === true || ($campaign->campaign && !$campaign->campaign->status) ) : ?>
<div class="box donation">
<p class="inactive-alert">This campaign is not currently accepting donations.</p>
</div>
<?php else : ?>
<form method="post" action="<?php echo site_url('donate/'.$hash.'/checkout') ?>?utm_source=<?php echo $this->input->get('utm_source') ? $this->input->get('utm_source') : 'direct' ?>&utm_medium=<?php echo $this->input->get('utm_medium') ? $this->input->get('utm_medium') : 'link' ?>&utm_campaign=<?php echo $campaign->campaign ? $campaign->campaign->title : $campaign->title ?>" id="form-donation-donate">
<div class="box donation clearfix<?php if ($campaign->enable_donation_levels) { echo ' box-donation-levels'; }?>">
<h4>Donation Amount</h4>
<p>
Donation must be made in US dollars. Minimum donation is <?php echo money_format('%n', $campaign->minimum_donation_amount/100) ?>.
</p>
<?php if( $this->session->flashdata('error') ) : ?>
<small class="error"><?php echo $this->session->flashdata('error') ?></small>
<?php endif ?>
<?php if( !$campaign->enable_donation_levels ) : ?>
<div class="row">
<div class="small-6 columns">
<div class="row collapse">
<div class="small-2 columns">
<span class="prefix"><?php echo CURRENCY_SYMBOL ?></span>
</div>
<div class="small-6 columns">
<input type="text" name="donation_amount" value="<?php echo $this->session->flashdata('amt') ? $this->session->flashdata('amt') : '' ?>" class="input-text" />
</div>
<div class="small-2 columns end">
<span class="postfix">.00</span>
</div>
</div>
</div>
</div>
<?php else : ?>
<?php foreach( $campaign->donation_levels as $level ) : ?>
<?php if( !$level['status'] ) { continue; } ?>
<label id="level-<?php echo $level['level_id'] ?>">
<input type="radio" name="donation_level" value="<?php echo $level['level_id'] ?>" <?php if( ($this->session->flashdata('level') && $this->session->flashdata('level') == $level['level_id']) || ($this->input->post('donation_level') && $this->input->post('donation_level') == $level['level_id']) ) : ?> checked<?php endif ?> />
<?php echo money_format('%n', $level['amount']/100) ?> - <?php echo $level['label'] ?>
</label>
<?php if( $this->session->flashdata('level') && $this->session->flashdata('level') == $level['level_id']) : ?>
<div class="row additional_donation_container">
<div class="small-12 columns">
<div class="row collapse">
<div class="small-1 columns">
<span class="prefix"><?php echo CURRENCY_SYMBOL ?></span>
</div>
<div class="small-6 columns end">
<input type="text" name="additional_donation" value="<?php echo $this->session->flashdata('addtl') ? $this->session->flashdata('addtl') : '' ?>" />
</div>
</div>
<div class="row collapse">
<div class="small-12 columns">
<small>Use this field to make an additional donation</small>
</div>
</div>
</div>
</div>
<?php endif ?>
<?php endforeach ?>
<label id="level-open">
<input type="radio" name="donation_level" value="open" <?php if( !$this->session->flashdata('level') ) : ?> checked<?php endif ?> />
Other Amount:
</label>
<?php if( !$this->session->flashdata('level') ) : ?>
<div class="row additional_donation_container">
<div class="small-12 columns">
<div class="row collapse">
<div class="small-1 columns">
<span class="prefix"><?php echo CURRENCY_SYMBOL ?></span>
</div>
<div class="small-6 columns end">
<input type="text" name="additional_donation" value="<?php echo $this->session->flashdata('addtl') ? $this->session->flashdata('addtl') : '' ?>" />
</div>
</div>
<div class="row collapse">
<div class="small-12 columns">
<small>Use this field to make an additional donation</small>
</div>
</div>
</div>
</div>
<?php endif ?>
<?php endif ?>
<?php if( $campaign->custom_fields ) : ?>
<div class="row">
<div class="small-12 columns">
<?php
$existing = array();
if( $this->session->flashdata('fields') ) {
$existing = unserialize($this->session->flashdata('fields'));
}
?>
<!-- errors -->
<?php if( $this->session->flashdata('customerror') ) : ?>
<hr>
<div class="row">
<div class="small-12 columns">
<small class="error">
<?php echo $this->session->flashdata('customerror') ?>
</small>
</div>
</div>
<?php endif ?>
<?php foreach( $campaign->custom_fields as $field ) : ?>
<hr>
<?php if( !$field['status'] ) { continue; } ?>
<label class="donation-field" id="field-<?php echo $field['field_id'] ?>"><?php echo $field['field_label'] ?><?php if ($field['required'] == '1') : ?>*<?php endif ?></label>
<?php if( $field['field_type'] == 'dropdown' ) : ?>
<select id="field-<?php echo $field['field_id'] ?>" class="six" name="fields[<?php echo $field['field_id'] ?>]">
<option value="">Select One</option>
<?php foreach( $field['options'] as $v ) : ?>
<option value="<?php echo $v ?>"<?php if( array_key_exists($field['field_id'], $existing) && $existing[$field['field_id']] && $v == $existing[$field['field_id']] ) : ?> selected<?php endif ?>><?php echo $v ?></option>
<?php endforeach ?>
</select>
<?php else : ?>
<input type="text" class="six" id="field-<?php echo $field['field_id'] ?>" name="fields[<?php echo $field['field_id'] ?>]" value="<?php echo array_key_exists($field['field_id'], $existing) ? $existing[$field['field_id']] : '' ?>" />
<?php endif ?>
<?php endforeach ?>
</div>
</div>
<?php endif ?>
<hr>
<div class="row">
<div class="small-12 columns right">
<input type="submit" value="Checkout" />
</div>
</div>
</div> <!-- eo box -->
<?php endif ?>
</div>
<div class="small-12 medium-5 medium-pull-7 columns">
<div class="box campaign">
<div class="row">
<?php if ($campaign->youtube || $campaign->image_url) : ?>
<div class="small-12 columns">
<?php if( $campaign->youtube ) : ?>
<div class="campaign_video flex-video">
<iframe src="//www.youtube.com/embed/<?php echo $campaign->youtube ?>" frameborder="0" allowfullscreen></iframe>
</div>
<?php elseif( $campaign->image_url ) : ?>
<img src="<?php echo $campaign->image_url ?>" class="campaign-thumb"/>
<?php endif ?>
</div>
<?php endif ?>
<div class="small-12 columns">
<div class="description">
<?php echo $this->typography->auto_typography($campaign->description) ?>
</div>
<ul class="unstyled">
<?php if( ($campaign->campaign && $campaign->campaign->display_donation_target) || (!$campaign->campaign && $campaign->display_donation_target) ) : ?>
<li>
Goal:
<strong><?php echo money_format('%n', $campaign->target/100) ?></strong>
</li>
<?php endif ?>
<?php if( ($campaign->campaign && $campaign->campaign->display_donation_total) || (!$campaign->campaign && $campaign->display_donation_total) ) : ?>
<li>
Current Total:
<strong><?php echo money_format('%n', $campaign->current/100) ?></strong>
</li>
<?php endif ?>
</ul>
</div>
</div><!-- eo row -->
</div>
</div>
</div>
</form>
<?php $this->load->view('components/_external_footer') ?>
| 22,271
|
https://github.com/rickintveld/daytrading-journal-api/blob/master/src/Domain/Builder/UserBuilder.php
|
Github Open Source
|
Open Source
|
Unlicense
| null |
daytrading-journal-api
|
rickintveld
|
PHP
|
Code
| 51
| 184
|
<?php
namespace App\Domain\Builder;
use App\Domain\Model\User;
use Symfony\Component\Uid\Uuid;
/**
* @package App\Infrastructure\Builder
*/
class UserBuilder implements Builder
{
/**
* @param array<string, string|int> $arguments
* @return \App\Domain\Model\User
* @throws \Exception
*/
public function build(array $arguments): User
{
$user = new User(
Uuid::v4(),
$arguments['email'],
$arguments['password'],
$arguments['firstName'],
$arguments['lastName'],
$arguments['capital'],
);
return $user;
}
}
| 46,811
|
https://github.com/bouzuya/rally-cli/blob/master/src/Data/GetSpotsResponse.purs
|
Github Open Source
|
Open Source
|
MIT
| null |
rally-cli
|
bouzuya
|
PureScript
|
Code
| 128
| 286
|
module Data.GetSpotsResponse (GetSpotsItem(..), GetSpotsResponse(..)) where
import Data.Foreign.Class (class IsForeign, read, readProp)
import Data.Foreign.Index (prop)
import Data.Show (class Show, show)
import Prelude (($), (<>), bind, map, pure)
data GetSpotsItem = GetSpotsItem { id :: Int }
data GetSpotsResponse = GetSpotsResponse { ids :: Array GetSpotsItem }
instance getSpotsItemShow :: Show GetSpotsItem where
show (GetSpotsItem { id }) = "{ \"id\": " <> show id <> " }"
instance getSpotsItemIsForeign :: IsForeign GetSpotsItem where
read value = do
id <- readProp "id" value
pure $ GetSpotsItem { id }
instance getSpotsResponseShow :: Show GetSpotsResponse where
show (GetSpotsResponse { ids }) = show (map show ids)
instance getSpotsResponseIsForeign :: IsForeign GetSpotsResponse where
read value = do
spotsForeign <- prop "spots" value
ids <- read spotsForeign
pure $ GetSpotsResponse { ids }
| 14,015
|
https://github.com/tnnfnc/apps/blob/master/src/main/java/it/tnnfnc/apps/application/undo/ObjectStatus.java
|
Github Open Source
|
Open Source
|
MIT
| null |
apps
|
tnnfnc
|
Java
|
Code
| 425
| 993
|
/*
* Copyright (c) 2015, Franco Toninato. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
*
* THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
* EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
* PARTIES PROVIDE THE PROGRAM �AS IS� WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
* QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
* DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
*/
package it.tnnfnc.apps.application.undo;
import java.text.DateFormat;
import java.util.Date;
/**
* Generic object status.
*
* @author Franco Toninato
*
*/
public class ObjectStatus<T> implements I_Status<T> {
private T memento;
private Object command;
private long timestamp = new Date().getTime();
/**
* Construct an empty object with null reference.
*/
public ObjectStatus() {
}
/**
* Construct an object from a status, and a command.
*
* @param status
* the memento status.
* @param command
* the command.
*/
public ObjectStatus(T status, Object command) {
setStatus(status, command);
}
/**
* Construct an object from a status, a command and a time stamp.
*
* @param status
* the object status.
* @param command
* the command.
* @param timestamp
* the time stamp when the status was changed.
*/
public ObjectStatus(T status, Object command, Date timestamp) {
this.timestamp = timestamp.getTime();
setStatus(status, command);
}
private void setStatus(T status, Object command) {
this.memento = status;
this.command = command;
}
/*
* (non-Javadoc)
*
* @see net.catode.model.I_ObjectTrace#getStatus()
*/
@Override
public T getStatus() {
return this.memento;
}
/*
* (non-Javadoc)
*
* @see net.catode.model.I_ObjectTrace#getCommand()
*/
@Override
public Object getCommand() {
return this.command;
}
/*
* (non-Javadoc)
*
* @see net.catode.model.I_ObjectTrace#getTimeStamp()
*/
@Override
public Date getTimeStamp() {
Date d = new Date();
d.setTime(timestamp);
return d;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return DateFormat.getDateInstance(DateFormat.SHORT).format(
getTimeStamp())
+ "-"
+ DateFormat.getTimeInstance(DateFormat.MEDIUM).format(
getTimeStamp())
+ " "
+ getCommand()
+ " "
+ getStatus().toString();
}
}
| 17,271
|
https://github.com/fuzzywy/QAT/blob/master/app/Http/Controllers/DataController.php
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
QAT
|
fuzzywy
|
PHP
|
Code
| 100
| 430
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\LteTddQueryHandler;
use App\Http\Controllers\LteFddQueryHandler;
use App\Http\Controllers\NbiotQueryHandler;
use App\Http\Controllers\NbmQueryHandler;
use App\Http\Controllers\GsmQueryHandler;
use App\Http\Controllers\KpiQueryHandler;
use App\Http\Controllers\KpiNbmQueryHandler;
class DataController extends Controller
{
public function getQatData(Request $request) {
$type = Input::get("dataType");
$datasoure = Input::get("dataSource");
switch($datasoure) {
case "ENIQ":
switch ($type) {
case 'TDD':
$query = new LteTddQueryHandler();
break;
case 'FDD':
$query = new LteFddQueryHandler();
break;
case 'NBIOT':
$query = new NbiotQueryHandler();
break;
case 'GSM':
$query = new GsmQueryHandler();
break;
default:
# code...
break;
}
break;
case "NBM":
$query = new NbmQueryHandler();
break;
case "ALARM":
$query = new AlarmQueryHandler();
break;
}
$result = $query->templateQuery($request);
return $result;
}
}
| 23,424
|
https://github.com/djrtwo/teku/blob/master/data/beaconrestapi/src/integration-test/java/tech/pegasys/teku/beaconrestapi/validator/GetNewBlockDataBackedIntegrationTest.java
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-free-unknown, Apache-2.0
| 2,020
|
teku
|
djrtwo
|
Java
|
Code
| 277
| 1,238
|
/*
* Copyright 2020 ConsenSys AG.
*
* 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 writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package tech.pegasys.teku.beaconrestapi.validator;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static tech.pegasys.teku.beaconrestapi.RestApiConstants.RANDAO_REVEAL;
import static tech.pegasys.teku.beaconrestapi.RestApiConstants.SLOT;
import static tech.pegasys.teku.util.async.SafeFuture.completedFuture;
import com.google.common.primitives.UnsignedLong;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import okhttp3.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import tech.pegasys.teku.api.ValidatorDataProvider;
import tech.pegasys.teku.api.schema.BLSSignature;
import tech.pegasys.teku.beaconrestapi.AbstractDataBackedRestAPIIntegrationTest;
import tech.pegasys.teku.beaconrestapi.handlers.validator.GetNewBlock;
import tech.pegasys.teku.beaconrestapi.schema.BadRequest;
import tech.pegasys.teku.datastructures.blocks.BeaconBlock;
import tech.pegasys.teku.datastructures.util.DataStructureUtil;
import tech.pegasys.teku.util.async.SafeFuture;
public class GetNewBlockDataBackedIntegrationTest extends AbstractDataBackedRestAPIIntegrationTest {
private final UnsignedLong SIX_HUNDRED = UnsignedLong.valueOf(600L);
private final tech.pegasys.teku.bls.BLSSignature signatureInternal =
tech.pegasys.teku.bls.BLSSignature.random(1234);
private BLSSignature signature = new BLSSignature(signatureInternal);
@BeforeEach
public void setup() {
startRestAPIAtGenesis();
}
@Test
void shouldProduceBlockForNextSlot() throws Exception {
final DataStructureUtil dataStructureUtil = new DataStructureUtil();
createBlocksAtSlotsAndMapToApiResult(SEVEN);
BeaconBlock block = dataStructureUtil.randomBeaconBlock(EIGHT);
SafeFuture<Optional<BeaconBlock>> futureBlock = completedFuture(Optional.of(block));
when(validatorApiChannel.createUnsignedBlock(any(), any(), any())).thenReturn(futureBlock);
Response response = getUnsignedBlock(EIGHT);
verify(validatorApiChannel).createUnsignedBlock(eq(EIGHT), any(), any());
assertThat(response.code()).isEqualTo(SC_OK);
}
@Test
void shouldNotProduceBlockForFarFutureSlot() throws Exception {
createBlocksAtSlotsAndMapToApiResult(SIX);
Response response = getUnsignedBlock(SIX_HUNDRED);
assertThat(response.code()).isEqualTo(SC_BAD_REQUEST);
BadRequest badRequest = jsonProvider.jsonToObject(response.body().string(), BadRequest.class);
assertThat(badRequest.getMessage())
.isEqualTo(ValidatorDataProvider.CANNOT_PRODUCE_FAR_FUTURE_BLOCK);
}
@Test
void shouldNotProduceBlockForHistoricSlot() throws Exception {
createBlocksAtSlotsAndMapToApiResult(SEVEN);
Response response = getUnsignedBlock(SIX);
assertThat(response.code()).isEqualTo(SC_BAD_REQUEST);
BadRequest badRequest = jsonProvider.jsonToObject(response.body().string(), BadRequest.class);
assertThat(badRequest.getMessage())
.isEqualTo(ValidatorDataProvider.CANNOT_PRODUCE_HISTORIC_BLOCK);
}
private Response getUnsignedBlock(final UnsignedLong slot) throws IOException {
return getResponse(
GetNewBlock.ROUTE, Map.of(SLOT, slot.toString(), RANDAO_REVEAL, signature.toHexString()));
}
}
| 2,327
|
https://github.com/BEUTIFULSKIN/python-design/blob/master/Decorate/yiwang_decorate.py
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
python-design
|
BEUTIFULSKIN
|
Python
|
Code
| 113
| 464
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-05-03 17:15:08
# @Author : Yi Wang (gzytemail@126.com)
# @Link : https://github.com/wang2222qq
# @des : 装饰器模式
"""
案例:
在咖啡店中
1.咖啡有很多种类.
2.咖啡搭配的调味品也有很多种
3.要获取客户的消费
"""
# Abstract class
class Coffee:
def cost(self):
pass
class Cappuccino(Coffee):
"""
卡布奇诺
"""
def cost(self):
return 2.5
class Latte(Coffee):
"""
拿铁
"""
def cost(self):
return 2.2
class Dressing():
"""调味料"""
def __init__(self, office):
self._office = office
def cost(self):
return self._office.cost()
class Milkshake(Dressing):
"""奶昔"""
def cost(self):
return self._office.cost() + 0.2
class Suger(Dressing):
"""白糖"""
def cost(self):
return self._office.cost() + 0.1
def client():
coffee = Cappuccino()
coffee = Milkshake(coffee)
coffee = Milkshake(coffee)
coffee = Suger(coffee)
print("total money:%s" % coffee.cost())
if __name__ == '__main__':
client()
| 33,213
|
https://github.com/runningbar/ERC20Token/blob/master/StandardToken.sol
|
Github Open Source
|
Open Source
|
MIT
| null |
ERC20Token
|
runningbar
|
Solidity
|
Code
| 375
| 1,002
|
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Interface {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
function allowance(address _owner, address _spender) public view returns (uint256);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is ERC20Interface {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
string internal name_ = "WTYToken";
string internal symbol_ = "WTY";
uint256 internal decimals_ = 6;
uint256 internal totalSupply_ = 2100 * (10 ** 4) * (10 ** decimals_);
constructor (address _firstHolder) public {
balances[_firstHolder] = totalSupply_;
emit Transfer(0x0, _firstHolder, totalSupply_);
}
function name() public view returns (string) {
return name_;
}
function symbol() public view returns (string) {
return symbol_;
}
function decimals() public view returns (uint256) {
return decimals_;
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require(_value == 0 || allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
}
| 4,814
|
https://github.com/CISecurity/IETF104-Client/blob/master/src/main/java/org/cisecurity/oval/sc/win/InterfaceItem.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
IETF104-Client
|
CISecurity
|
Java
|
Code
| 757
| 2,381
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.11.21 at 11:38:58 AM EST
//
package org.cisecurity.oval.sc.win;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.cisecurity.oval.sc.CollectedItemIPAddressStringType;
import org.cisecurity.oval.sc.CollectedItemIntType;
import org.cisecurity.oval.sc.CollectedItemStringType;
import org.cisecurity.oval.sc.CollectedItemType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://oval.cisecurity.org/XMLSchema/oval-system-characteristics-6}CollectedItemType">
* <sequence>
* <element name="name" type="{http://oval.cisecurity.org/XMLSchema/oval-system-characteristics-6}CollectedItemStringType" minOccurs="0"/>
* <element name="index" type="{http://oval.cisecurity.org/XMLSchema/oval-system-characteristics-6}CollectedItemIntType" minOccurs="0"/>
* <element name="type" type="{http://oval.cisecurity.org/XMLSchema/oval-system-characteristics-6#windows}EntityItemInterfaceTypeType" minOccurs="0"/>
* <element name="hardware_addr" type="{http://oval.cisecurity.org/XMLSchema/oval-system-characteristics-6}CollectedItemStringType" minOccurs="0"/>
* <element name="inet_addr" type="{http://oval.cisecurity.org/XMLSchema/oval-system-characteristics-6}CollectedItemIPAddressStringType" minOccurs="0"/>
* <element name="broadcast_addr" type="{http://oval.cisecurity.org/XMLSchema/oval-system-characteristics-6}CollectedItemIPAddressStringType" minOccurs="0"/>
* <element name="netmask" type="{http://oval.cisecurity.org/XMLSchema/oval-system-characteristics-6}CollectedItemIPAddressStringType" minOccurs="0"/>
* <element name="addr_type" type="{http://oval.cisecurity.org/XMLSchema/oval-system-characteristics-6#windows}EntityItemAddrTypeType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"name",
"index",
"type",
"hardwareAddr",
"inetAddr",
"broadcastAddr",
"netmask",
"addrType"
})
public class InterfaceItem
extends CollectedItemType
{
protected CollectedItemStringType name;
protected CollectedItemIntType index;
protected EntityItemInterfaceTypeType type;
@XmlElement(name = "hardware_addr")
protected CollectedItemStringType hardwareAddr;
@XmlElement(name = "inet_addr")
protected CollectedItemIPAddressStringType inetAddr;
@XmlElement(name = "broadcast_addr")
protected CollectedItemIPAddressStringType broadcastAddr;
protected CollectedItemIPAddressStringType netmask;
@XmlElement(name = "addr_type")
protected List<EntityItemAddrTypeType> addrType;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link CollectedItemStringType }
*
*/
public CollectedItemStringType getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link CollectedItemStringType }
*
*/
public void setName(CollectedItemStringType value) {
this.name = value;
}
/**
* Gets the value of the index property.
*
* @return
* possible object is
* {@link CollectedItemIntType }
*
*/
public CollectedItemIntType getIndex() {
return index;
}
/**
* Sets the value of the index property.
*
* @param value
* allowed object is
* {@link CollectedItemIntType }
*
*/
public void setIndex(CollectedItemIntType value) {
this.index = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link EntityItemInterfaceTypeType }
*
*/
public EntityItemInterfaceTypeType getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link EntityItemInterfaceTypeType }
*
*/
public void setType(EntityItemInterfaceTypeType value) {
this.type = value;
}
/**
* Gets the value of the hardwareAddr property.
*
* @return
* possible object is
* {@link CollectedItemStringType }
*
*/
public CollectedItemStringType getHardwareAddr() {
return hardwareAddr;
}
/**
* Sets the value of the hardwareAddr property.
*
* @param value
* allowed object is
* {@link CollectedItemStringType }
*
*/
public void setHardwareAddr(CollectedItemStringType value) {
this.hardwareAddr = value;
}
/**
* Gets the value of the inetAddr property.
*
* @return
* possible object is
* {@link CollectedItemIPAddressStringType }
*
*/
public CollectedItemIPAddressStringType getInetAddr() {
return inetAddr;
}
/**
* Sets the value of the inetAddr property.
*
* @param value
* allowed object is
* {@link CollectedItemIPAddressStringType }
*
*/
public void setInetAddr(CollectedItemIPAddressStringType value) {
this.inetAddr = value;
}
/**
* Gets the value of the broadcastAddr property.
*
* @return
* possible object is
* {@link CollectedItemIPAddressStringType }
*
*/
public CollectedItemIPAddressStringType getBroadcastAddr() {
return broadcastAddr;
}
/**
* Sets the value of the broadcastAddr property.
*
* @param value
* allowed object is
* {@link CollectedItemIPAddressStringType }
*
*/
public void setBroadcastAddr(CollectedItemIPAddressStringType value) {
this.broadcastAddr = value;
}
/**
* Gets the value of the netmask property.
*
* @return
* possible object is
* {@link CollectedItemIPAddressStringType }
*
*/
public CollectedItemIPAddressStringType getNetmask() {
return netmask;
}
/**
* Sets the value of the netmask property.
*
* @param value
* allowed object is
* {@link CollectedItemIPAddressStringType }
*
*/
public void setNetmask(CollectedItemIPAddressStringType value) {
this.netmask = value;
}
/**
* Gets the value of the addrType property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the addrType property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAddrType().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link EntityItemAddrTypeType }
*
*
*/
public List<EntityItemAddrTypeType> getAddrType() {
if (addrType == null) {
addrType = new ArrayList<EntityItemAddrTypeType>();
}
return this.addrType;
}
}
| 45,079
|
https://github.com/nonoillora/printcolor/blob/master/resources/views/pedidos/pendientes.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
printcolor
|
nonoillora
|
PHP
|
Code
| 42
| 258
|
@extends('administracion.adminTemplate')
@section('adminContent')
<div class="breadcrumb">
<a href="{{url('admin')}}">Administración</a> <span class="glyphicon glyphicon-chevron-right"></span> <a href="{{url('admin/pedidos/pendientes')}}">Pedidos Pendientes</a>
<div class="pull-right">
@if(true)
<span class="animated infinite swing glyphicon glyphicon-bell"></span> <b
class="label label-success" data-toggle="tooltip" data-placement="bottom"
title="3 Notificaiones Nuevas">3</b>
@endif
</div>
</div>
pedidos pendientes here
<ul class="list-group">
@for($i=0;$i<5;$i++)
<li class="list-group-item">{{$i+1}}</li>
@endfor
</ul>
@endsection
| 48,884
|
https://github.com/Ishakkangah/Band/blob/master/resources/views/layouts/app.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Band
|
Ishakkangah
|
Blade
|
Code
| 22
| 123
|
@extends('layouts.base')
@section('baseStyles')
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
@endsection
@section('baseScripts')
<script src="{{ asset('js/app.js') }}" defer></script>
@endsection
@section('body')
<x-navbar></x-navbar>
<div class="mt-4">
@yield('content')
</div>
@endsection
| 18,693
|
https://github.com/narenarjun/learn-scala/blob/master/book-code/src/script/scala/progscala3/patternmatching/MatchVariable2.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
learn-scala
|
narenarjun
|
Scala
|
Code
| 53
| 153
|
// src/script/scala/progscala3/patternmatching/MatchVariable2.scala
val seq2 = Seq(1, 2, 3.14, "one", (6, 7))
val result2 = seq2.map { x => x match
case _: Int => s"int: $x" // <1>
case _ => s"unexpected value: $x" // <2>
}
assert(result2 == Seq(
"int: 1", "int: 2", "unexpected value: 3.14",
"unexpected value: one", "unexpected value: (6,7)"))
| 45,540
|
https://github.com/Dutchosintguy/telegram-osint-lib/blob/master/examples/proxy.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
telegram-osint-lib
|
Dutchosintguy
|
PHP
|
Code
| 80
| 261
|
<?php
use TelegramOSINT\Scenario\StatusWatcherScenario;
use TelegramOSINT\Tools\Proxy;
require_once __DIR__.'/../vendor/autoload.php';
if (!isset($argv[1]) || $argv[1] == '--help' || $argv[1] == '--info') {
$msg = <<<'MSG'
Usage: php proxy.php numbers
numbers: 79061231231,79061231232,...
MSG;
die($msg);
}
// here we get contact list and get contact online status
// avatars are saved to current directory using proxy
// this is a dummy proxy
// use `node ../vendor/postuf/socks-proxy-async/node/proxy.js 1080` to start
$proxy = new Proxy('127.0.0.1:1080');
$numbers = explode(',', $argv[1]);
/* @noinspection PhpUnhandledExceptionInspection */
(new StatusWatcherScenario($numbers, [], null, $proxy))->startActions();
| 18,073
|
https://github.com/molon/gomsg/blob/master/cmd/boat/main.go
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
gomsg
|
molon
|
Go
|
Code
| 468
| 2,270
|
package main
import (
"context"
"fmt"
"io"
"net"
"os"
"os/signal"
"runtime"
"syscall"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
"github.com/molon/gomsg/internal/pkg/resource"
"github.com/molon/pkg/grpc/timeout"
"github.com/molon/pkg/registry"
"github.com/molon/pkg/server"
"github.com/molon/pkg/tracing/otgrpc"
"github.com/molon/gomsg/internal/app/boat"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"github.com/molon/gomsg/internal/pb/stationpb"
"github.com/rs/xid"
etcd "github.com/coreos/etcd/clientv3"
etcdnaming "github.com/coreos/etcd/clientv3/naming"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
)
var dialOptions = []grpc.DialOption{
grpc.WithInsecure(),
grpc.WithInitialWindowSize(1 << 24),
grpc.WithInitialConnWindowSize(1 << 24),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1 << 24)),
grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(1 << 24)),
grpc.WithBackoffMaxDelay(time.Second * 3),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: time.Second * 10,
Timeout: time.Second * 3,
PermitWithoutStream: true,
}),
grpc.WithUnaryInterceptor(
grpc_middleware.ChainUnaryClient(
timeout.UnaryClientInterceptorWhenCall(time.Second*10),
otgrpc.UnaryClientInterceptor(
otgrpc.WithRequstBody(true),
otgrpc.WithResponseBody(true),
),
),
),
}
var serverKeepaliveOptions = []grpc.ServerOption{
grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionIdle: 0, // infinity
MaxConnectionAge: 0, // infinity
MaxConnectionAgeGrace: 0, // infinity
Time: time.Duration(time.Second * 10),
Timeout: time.Duration(time.Second * 3),
}),
grpc.KeepaliveEnforcementPolicy(
keepalive.EnforcementPolicy{
MinTime: time.Second * 5, // 必须要小于调用者的ClientParameters.Time配置
PermitWithoutStream: true, // 一般要和调用者保持一致
},
),
}
var loopServerKeepaliveOptions = []grpc.ServerOption{
grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionIdle: 0, // infinity
MaxConnectionAge: 0, // infinity
MaxConnectionAgeGrace: 0, // infinity
Time: time.Duration(time.Second * 300),
Timeout: time.Duration(time.Second * 20),
}),
grpc.KeepaliveEnforcementPolicy(
keepalive.EnforcementPolicy{
MinTime: time.Second * 200, // 必须要小于调用者的ClientParameters.Time配置
PermitWithoutStream: true, // 为true表示即使客户端在idle时候发送心跳也不会被踢出
},
),
}
func GRPCServer(logger *logrus.Logger) (*server.Server, net.Listener) {
grpcServer, err := boat.NewGRPCServer(serverKeepaliveOptions...)
if err != nil {
logger.Fatalln(err)
}
s, err := server.NewServer(
server.WithGRPCServer(grpcServer),
)
if err != nil {
logger.Fatalln(err)
}
grpcL, err := net.Listen("tcp", fmt.Sprintf("%s:%d", viper.GetString("grpc.address"), viper.GetInt("grpc.port")))
if err != nil {
logger.Fatalln(err)
}
logger.Infof("Serving boat gRPC at %v", grpcL.Addr())
return s, grpcL
}
func LoopServer(ctx context.Context, logger *logrus.Logger) (*server.Server, io.Closer, net.Listener) {
grpcServer, closer, err := boat.NewLoopServer(ctx, loopServerKeepaliveOptions...)
if err != nil {
logger.Fatalln(err)
}
s, err := server.NewServer(
server.WithGRPCServer(grpcServer),
)
if err != nil {
logger.Fatalln(err)
}
grpcL, err := net.Listen("tcp", fmt.Sprintf("%s:%d", viper.GetString("loop.address"), viper.GetInt("loop.port")))
if err != nil {
logger.Fatalln(err)
}
logger.Infof("Serving loop gRPC at %v", grpcL.Addr())
return s, closer, grpcL
}
func NewStationClient(ctx context.Context, logger *logrus.Logger, etcdCli *etcd.Client) (stationpb.StationClient, *grpc.ClientConn) {
r := &etcdnaming.GRPCResolver{Client: etcdCli}
b := grpc.RoundRobin(r)
conn, err := grpc.DialContext(ctx,
viper.GetString("station.name"),
append(dialOptions, grpc.WithBalancer(b))...,
)
if err != nil {
logger.Fatalln("Dial station gRPC failed:", err)
}
logger.Infof("Dial station gRPC at %s", viper.GetString("station.name"))
return stationpb.NewStationClient(conn), conn
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
logger := resource.NewLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// 服务唯一标识
applicationId := xid.New().String()
logger.Infof("Application ID: %s", applicationId)
// 连接etcd
etcdCli := resource.NewEtcdClient(ctx, logger)
defer etcdCli.Close()
// 连接jaeger
tracer := resource.NewJaegerTracer(logger)
defer tracer.Close()
// 连接gRPC服务
stationCli, stationConn := NewStationClient(ctx, logger, etcdCli)
defer stationConn.Close()
// 初始化boat
boat.Init(applicationId, logger, stationCli)
// 启动server
sigC := make(chan os.Signal, 1)
doneC := make(chan error, 4)
grpcS, grpcL := GRPCServer(logger)
loopS, loopCloser, loopL := LoopServer(ctx, logger)
go func() { doneC <- grpcS.Serve(grpcL, nil) }()
go func() { doneC <- loopS.Serve(loopL, nil) }()
defer server.GracefulStop(grpcS, loopS)
defer loopCloser.Close() // 这个是为了主动要求stream立即关闭,否则grpc.GracefulStop会一直等待
// 服务注册
register := registry.NewRegister(logger, etcdCli, fmt.Sprintf("%s%s", viper.GetString("registry.name-prefix"), applicationId), grpcL.Addr().String(), viper.GetInt("registry.ttl"))
defer register.Close()
// 健康检查
healthS, healthL := resource.NewHealthChecker(logger, nil)
go func() { doneC <- healthS.Serve(nil, healthL) }()
defer server.GracefulStop(healthS)
// 结束清理
signal.Notify(sigC, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
go func() {
<-sigC
doneC <- nil
}()
if err := <-doneC; err != nil {
logger.Errorln(err)
}
}
| 42,204
|
https://github.com/Tillerdawg/Blockchain_TicTacToe_Java2/blob/master/noobchain/src/noobchain/NoobChain.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Blockchain_TicTacToe_Java2
|
Tillerdawg
|
Java
|
Code
| 725
| 2,417
|
package noobchain;
import java.security.Security;
import java.util.ArrayList;
//import java.util.Base64;
import java.util.HashMap;
import java.util.Scanner;
import game.TicTacToe;
public class NoobChain {
public static ArrayList<Block> blockchain = new ArrayList<Block>();
public static HashMap<String, TransactionOutput> UTXOs = new HashMap<String, TransactionOutput>();
public static int difficulty = 3;
public static float minimumTransaction = 0.1f;
public static Wallet walletX;
public static Wallet walletO;
public static Transaction genesisTransaction;
public static Transaction anotherTransaction;
public static Scanner in;
public static void main(String[] args) {
// add our blocks to the blockchain ArrayList:
// Set up BouncyCastle as a security provider
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// Create wallets:
walletX = new Wallet();
walletO = new Wallet();
Wallet coinbase = new Wallet();
in = new Scanner(System.in);
// create genesis transaction, which sends 100 NoobCoin to WalletX:
// this adds funds to X's wallet
genesisTransaction = new Transaction(coinbase.publicKey, walletX.publicKey, 100f, null);
// Manually sign the genesis transaction
genesisTransaction.generateSignature(coinbase.privateKey);
// Manually set the transaction id
genesisTransaction.transactionId = "0";
// Manually add the Transactions Output
genesisTransaction.outputs.add(new TransactionOutput(genesisTransaction.recipient, genesisTransaction.value,
genesisTransaction.transactionId));
// It is important to store our first transaction in the UTXOs list
UTXOs.put(genesisTransaction.outputs.get(0).id, genesisTransaction.outputs.get(0));
System.out.println("Creating and Mining Genesis block... ");
Block genesis = new Block("0");
// this adds funds to O's wallet
anotherTransaction = new Transaction(coinbase.publicKey, walletO.publicKey, 100f, null);
anotherTransaction.generateSignature(coinbase.privateKey);
anotherTransaction.transactionId = "0";
anotherTransaction.outputs.add(new TransactionOutput(anotherTransaction.recipient, anotherTransaction.value,
anotherTransaction.transactionId));
UTXOs.put(anotherTransaction.outputs.get(0).id, anotherTransaction.outputs.get(0));
genesis.addTransaction(genesisTransaction);
genesis.addTransaction(anotherTransaction);
addBlock(genesis);
placeBet();
}
private static void placeBet() {
// cannot bet more than you have, check both x and o
int betX;
do {
System.out.println("\nWalletX Value: " + walletX.getBalance());
System.out.println("\"X\" Place Your Bet: ");
betX = in.nextInt();
if (genesisTransaction.getOutputsValue() >= betX) {
break;
}
} while (true);
int betO;
do {
System.out.println("\nWalletO Value: " + walletO.getBalance());
System.out.println("\"O\" Place Your Bet: ");
betO = in.nextInt();
if (anotherTransaction.getOutputsValue() >= betO) {
break;
}
} while (true);
playGame(betX, betO);
in.close();
}
private static void playGame(int betX, int betO) {
// play the game
TicTacToe ttt = new TicTacToe();
String winner = ttt.play();
String lastBlock = blockchain.get(blockchain.size() - 1).hash;
System.out.println("\nWalletX's beginning balance is: " + walletX.getBalance());
System.out.println("\nWalletO's beginning balance is: " + walletO.getBalance());
if (winner.equals("X")) {
Block block1 = new Block(lastBlock);
System.out.println("\nWalletO is attempting to send funds (" + betO + ") to WalletX...");
block1.addTransaction(walletO.sendFunds(walletX.publicKey, betO));
addBlock(block1);
} else if (winner.equals("O")) {
Block block1 = new Block(lastBlock);
System.out.println("\nWalletX is attempting to send funds (" + betX + ") to WalletO...");
block1.addTransaction(walletX.sendFunds(walletO.publicKey, betX));
addBlock(block1);
} else if (winner.equals("Draw")) {
System.out.println("\nIt's a DRAW, bets are off");
}
System.out.println("\nWalletX's balance is: " + walletX.getBalance());
System.out.println("\nWalletO's balance is: " + walletO.getBalance());
isChainValid();
playAgain();
}
private static void playAgain() {
System.out.println("\nPlay Again? Y-Yes N-No");
String choice = in.next();
if (choice.equalsIgnoreCase("Y") || choice.equalsIgnoreCase("Yes")) {
placeBet();
} else {
System.out.println("\nThank you for playing Tic-Tac-Toe!");
in.close();
}
}
public static Boolean isChainValid() {
Block currentBlock;
Block previousBlock;
String hashTarget = new String(new char[difficulty]).replace('\0', '0');
// A temporary working list of unspent transactions at a given block state
HashMap<String, TransactionOutput> tempUTXOs = new HashMap<String, TransactionOutput>();
tempUTXOs.put(genesisTransaction.outputs.get(0).id, genesisTransaction.outputs.get(0));
tempUTXOs.put(anotherTransaction.outputs.get(0).id, anotherTransaction.outputs.get(0));
// loop through blockchain to check hashes:
for (int i = 1; i < blockchain.size(); i++) {
currentBlock = blockchain.get(i);
previousBlock = blockchain.get(i - 1);
// compare registered hash and calculated hash:
if (!currentBlock.hash.equals(currentBlock.calculateHash())) {
System.out.println("#Current Hashes not equal");
return false;
}
// compare previous hash and registered previous hash
if (!previousBlock.hash.equals(currentBlock.previousHash)) {
System.out.println("#Previous Hashes not equal");
return false;
}
// check if hash is solved
if (!currentBlock.hash.substring(0, difficulty).equals(hashTarget)) {
System.out.println("#This block hasn't been mined");
return false;
}
// loop thru blockchains transactions:
TransactionOutput tempOutput;
for (int t = 0; t < currentBlock.transactions.size(); t++) {
Transaction currentTransaction = currentBlock.transactions.get(t);
if (!currentTransaction.verifySignature()) {
System.out.println("#Signature on Transaction(" + t + ") is Invalid");
return false;
}
if (currentTransaction.getInputsValue() != currentTransaction.getOutputsValue()) {
System.out.println("#Inputs are note equal to outputs on Transaction(" + t + ")");
return false;
}
for (TransactionInput input : currentTransaction.inputs) {
tempOutput = tempUTXOs.get(input.transactionOutputId);
if (tempOutput == null) {
System.out.println("#Referenced input on Transaction(" + t + ") is Missing");
return false;
}
if (input.UTXO.value != tempOutput.value) {
System.out.println("#Referenced input Transaction(" + t + ") value is Invalid");
return false;
}
tempUTXOs.remove(input.transactionOutputId);
}
for (TransactionOutput output : currentTransaction.outputs) {
tempUTXOs.put(output.id, output);
}
if (currentTransaction.outputs.get(0).recipient != currentTransaction.recipient) {
System.out.println("#Transaction(" + t + ") output recipient is not who it should be");
return false;
}
if (currentTransaction.outputs.get(1).recipient != currentTransaction.sender) {
System.out.println("#Transaction(" + t + ") output 'change' is not sender.");
return false;
}
}
}
System.out.println("Blockchain is valid");
return true;
}
public static void addBlock(Block newBlock) {
newBlock.mineBlock(difficulty);
blockchain.add(newBlock);
}
}
| 39,102
|
https://github.com/tarantool/spring-data-tarantool/blob/master/src/main/java/org/springframework/data/tarantool/core/mapping/TarantoolIdClass.java
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,020
|
spring-data-tarantool
|
tarantool
|
Java
|
Code
| 160
| 394
|
package org.springframework.data.tarantool.core.mapping;
import org.springframework.data.annotation.Persistent;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specifies a composite primary key for this entity (marked as {@link Tuple}.
*
* The specified class must contain all properties
* that are parts of primary index of the tuple.
* These properties must be present in the entity
* and may marked with {@link org.springframework.data.annotation.Id}.
* @Id annotation on properties is optional but It is recommended to use it
* to make code more clear.
* Types of properties in primary key class and the entity must correspond.
*
* Example:
*
* <pre>{@code
*
* public class BookId {
* String name;
* String author;
* }
*
* @TarantoolIdClass(io.tarantool.example.BookId)
* @Tuple(table="book")
* public class Book {
* @Id String name;
* @Id String author;
* ...
* }
*
* }</pre>
*
* @author Vladimir Rogach
*/
@Persistent
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface TarantoolIdClass {
Class<?> value();
}
| 40,291
|
https://github.com/TrendingTechnology/hspylib/blob/master/src/app/kafman/src/main/core/__init__.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
hspylib
|
TrendingTechnology
|
Python
|
Code
| 20
| 64
|
# _*_ coding: utf-8 _*_
#
# HSPyLib v0.11.1
#
# Package: app.kafman.src.main.core
"""Package initialization."""
__all__ = [
'constants'
]
| 33,166
|
https://github.com/thesli/backuplaptop/blob/master/pella/tryGrunt/node_modules/grunt-js2coffee/test/result/each/mout/src/number/pad.coffee
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
backuplaptop
|
thesli
|
CoffeeScript
|
Code
| 25
| 66
|
define ["../string/lpad"], (lpad) ->
###
Add padding zeros if n.length < minLength.
###
pad = (n, minLength) ->
lpad "" + n, minLength, "0"
pad
| 20,414
|
https://github.com/IkariMeister/Rosie/blob/master/sample/src/androidTest/java/com/karumi/rosie/sample/characters/view/activity/CharacterDetailsActivityTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
Rosie
|
IkariMeister
|
Java
|
Code
| 374
| 1,507
|
/*
* Copyright (C) 2015 Karumi.
*
* 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 writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.karumi.rosie.sample.characters.view.activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.test.espresso.intent.rule.IntentsTestRule;
import android.support.test.espresso.matcher.ViewMatchers;
import com.karumi.marvelapiclient.MarvelApiException;
import com.karumi.rosie.sample.InjectedInstrumentationTest;
import com.karumi.rosie.sample.R;
import com.karumi.rosie.sample.characters.domain.model.Character;
import com.karumi.rosie.sample.characters.repository.CharactersRepository;
import dagger.Module;
import dagger.Provides;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.junit.Rule;
import org.junit.Test;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.not;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CharacterDetailsActivityTest extends InjectedInstrumentationTest {
private static final int ANY_CHARACTER_ID = 1;
private static final String ANY_EXCEPTION = "AnyException";
@Rule public IntentsTestRule<CharacterDetailsActivity> activityRule =
new IntentsTestRule<>(CharacterDetailsActivity.class, true, false);
@Inject CharactersRepository charactersRepository;
@Test public void shouldShowCharacterDetailWhenCharacterIsLoaded() throws Exception {
Character character = givenAValidCharacter();
startActivity();
onView(withId(R.id.tv_character_name)).check(matches(withText(character.getName())));
onView(withId(R.id.tv_description)).check(matches(withText(character.getDescription())));
}
@Test public void shouldHideLoadingWhenCharacterIsLoaded() throws Exception {
givenAValidCharacter();
startActivity();
onView((withId(R.id.loading))).check(matches(not(isDisplayed())));
}
@Test public void shouldShowsErrorIfSomethingWrongHappend() throws Exception {
givenExceptionObtainingACharacter();
startActivity();
onView(allOf(withId(android.support.design.R.id.snackbar_text), withText("¯\\_(ツ)_/¯"))).check(
matches(isDisplayed()));
}
@Test public void shouldShowsConnectionErrorIfHasConnectionTroubles() throws Exception {
givenConnectionExceptionObtainingACharacter();
startActivity();
onView(allOf(withId(android.support.design.R.id.snackbar_text),
withText("Connection troubles. Ask to Ironman!"))).check(
matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
}
private Character givenAValidCharacter() throws Exception {
Character character = getCharacter(ANY_CHARACTER_ID);
when(charactersRepository.getByKey(anyString())).thenReturn(character);
return character;
}
private void givenExceptionObtainingACharacter() throws Exception {
when(charactersRepository.getByKey(anyString())).thenThrow(new Exception());
}
private void givenConnectionExceptionObtainingACharacter() throws Exception {
when(charactersRepository.getByKey(anyString())).thenThrow(
new MarvelApiException(ANY_EXCEPTION, new UnknownHostException()));
}
@NonNull private Character getCharacter(int id) {
Character character = new Character();
character.setKey("" + id);
character.setName("SuperHero - " + id);
character.setDescription("Description Super Hero - " + id);
character.setThumbnailUrl("https://id.annihil.us/u/prod/marvel/id/mg/c/60/55b6a28ef24fa.jpg");
return character;
}
private CharacterDetailsActivity startActivity() {
Intent intent = new Intent();
intent.putExtra("CharacterDetailsActivity.CharacterKey", ANY_CHARACTER_ID);
return activityRule.launchActivity(intent);
}
@Override public List<Object> getTestModules() {
return Arrays.asList((Object) new TestModule());
}
@Module(overrides = true, library = true, complete = false,
injects = {
CharacterDetailsActivity.class, CharacterDetailsActivityTest.class
}) class TestModule {
@Provides @Singleton public CharactersRepository provideCharactersRepository() {
return mock(CharactersRepository.class);
}
}
}
| 42,735
|
https://github.com/codacy-badger/Je-Marche/blob/master/src/screens/polls/PollsScreenViewModelMapper.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
Je-Marche
|
codacy-badger
|
TypeScript
|
Code
| 53
| 154
|
import { Poll } from '../../core/entities/Poll'
import Theme from '../../themes/Theme'
import { PollRowViewModelMapper } from './PollRowViewModelMapper'
import { PollsHeaderViewModelMapper } from './PollsHeaderViewModelMapper'
import { PollsScreenViewModel } from './PollsScreenViewModel'
export const PollsScreenViewModelMapper = {
map: (theme: Theme, polls: Array<Poll>): PollsScreenViewModel => {
return {
header: PollsHeaderViewModelMapper.map(polls),
rows: polls.map((poll) => PollRowViewModelMapper.map(theme, poll)),
}
},
}
| 34,676
|
https://github.com/ahmedAdel77/NOhandicap/blob/master/storage/framework/views/af718c25b0724a223c6f95a91240fccf51a26a33.php
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
NOhandicap
|
ahmedAdel77
|
PHP
|
Code
| 129
| 595
|
<?php $__env->startSection('content'); ?>
<div class="section">
<div class="col s12 m6">
<div class="card darken-1">
<div class="card-content">
<span class="card-title center">Users</span>
<?php if(count($users)): ?>
<table class="centered stripped highlight">
<thead>
<tr>
<th>Name</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<?php $__currentLoopData = $users; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $user): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<tr>
<td><a href=""> <?php echo e($user->name); ?></a>
</td>
<td>
<a href="" class="btn blue ">
<span>Edit</span>
<i class="material-icons left">edit</i>
</a>
</td>
<td>
<form action="" method="POST" enctype="multipart/form-data">
<?php echo method_field("DELETE"); ?>
<?php echo csrf_field(); ?>
<button type="submit" class="btn red darken-2">
<span>Delete</span>
<i class="material-icons left">delete</i>
</button>
</form>
</td>
</tr>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</tbody>
</table>
<?php else: ?>
<p class="section">No Users Listed.</p>
<?php endif; ?>
</div>
</div>
</div>
</div>
</div>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\nohandicap\resources\views/admin/showUsers.blade.php ENDPATH**/ ?>
| 39,902
|
https://github.com/Shashi-rk/azure-sdk-for-java/blob/master/sdk/logic/azure-resourcemanager-logic/src/main/java/com/azure/resourcemanager/logic/models/RunActionCorrelation.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
azure-sdk-for-java
|
Shashi-rk
|
Java
|
Code
| 184
| 536
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.logic.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The workflow run action correlation properties. */
@Fluent
public final class RunActionCorrelation extends RunCorrelation {
@JsonIgnore private final ClientLogger logger = new ClientLogger(RunActionCorrelation.class);
/*
* The action tracking identifier.
*/
@JsonProperty(value = "actionTrackingId")
private String actionTrackingId;
/**
* Get the actionTrackingId property: The action tracking identifier.
*
* @return the actionTrackingId value.
*/
public String actionTrackingId() {
return this.actionTrackingId;
}
/**
* Set the actionTrackingId property: The action tracking identifier.
*
* @param actionTrackingId the actionTrackingId value to set.
* @return the RunActionCorrelation object itself.
*/
public RunActionCorrelation withActionTrackingId(String actionTrackingId) {
this.actionTrackingId = actionTrackingId;
return this;
}
/** {@inheritDoc} */
@Override
public RunActionCorrelation withClientTrackingId(String clientTrackingId) {
super.withClientTrackingId(clientTrackingId);
return this;
}
/** {@inheritDoc} */
@Override
public RunActionCorrelation withClientKeywords(List<String> clientKeywords) {
super.withClientKeywords(clientKeywords);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
@Override
public void validate() {
super.validate();
}
}
| 37,330
|
https://github.com/kzx1025/spark_improve/blob/master/core/target/java/org/apache/spark/network/netty/client/BlockFetchingClient.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
spark_improve
|
kzx1025
|
Java
|
Code
| 213
| 495
|
package org.apache.spark.network.netty.client;
/**
* Client for fetching data blocks from {@link org.apache.spark.network.netty.server.BlockServer}.
* Use {@link BlockFetchingClientFactory} to instantiate this client.
* <p>
* The constructor blocks until a connection is successfully established.
* <p>
* See {@link org.apache.spark.network.netty.server.BlockServer} for client/server protocol.
* <p>
* Concurrency: thread safe and can be called from multiple threads.
*/
private class BlockFetchingClient implements org.apache.spark.Logging {
public BlockFetchingClient (org.apache.spark.network.netty.client.BlockFetchingClientFactory factory, java.lang.String hostname, int port) { throw new RuntimeException(); }
private org.apache.spark.network.netty.client.BlockFetchingClientHandler handler () { throw new RuntimeException(); }
/** Netty Bootstrap for creating the TCP connection. */
private io.netty.bootstrap.Bootstrap bootstrap () { throw new RuntimeException(); }
/** Netty ChannelFuture for the connection. */
private io.netty.channel.ChannelFuture cf () { throw new RuntimeException(); }
/**
* Ask the remote server for a sequence of blocks, and execute the callback.
* <p>
* Note that this is asynchronous and returns immediately. Upstream caller should throttle the
* rate of fetching; otherwise we could run out of memory.
* <p>
* @param blockIds sequence of block ids to fetch.
* @param listener callback to fire on fetch success / failure.
*/
public void fetchBlocks (scala.collection.Seq<java.lang.String> blockIds, org.apache.spark.network.netty.client.BlockClientListener listener) { throw new RuntimeException(); }
public void waitForClose () { throw new RuntimeException(); }
public void close () { throw new RuntimeException(); }
}
| 49,184
|
https://github.com/JosephWoodward/SpecsFor/blob/master/SpecsFor.Autofac.Tests/ComposingContext/ComposingContextConfig.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
SpecsFor
|
JosephWoodward
|
C#
|
Code
| 36
| 253
|
using NUnit.Framework;
using SpecsFor.Autofac.Tests.ComposingContext.TestDomain;
using SpecsFor.Core.Configuration;
namespace SpecsFor.Autofac.Tests.ComposingContext
{
[SetUpFixture]
public class ComposingContextConfig : SpecsForConfiguration
{
public ComposingContextConfig()
{
WhenTesting<ILikeMagic>().EnrichWith<ProvideMagicByInterface>();
WhenTesting<SpecsFor<Widget>>().EnrichWith<ProvideMagicByConcreteType>();
WhenTesting(t => t.Name.Contains("running_tests_decorated")).EnrichWith<ProvideMagicByTypeName>();
WhenTesting(t => t.Name.Contains("junk that does not exist")).EnrichWith<DoNotProvideMagic>();
WhenTestingAnything().EnrichWith<ProvideMagicForEveryone>();
WhenTestingAnything().EnrichWith<MyTestLogger>();
}
}
}
| 26,456
|
https://github.com/curiousjgeorge/aws-sdk-cpp/blob/master/aws-cpp-sdk-health/include/aws/health/model/DescribeEventDetailsResult.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
aws-sdk-cpp
|
curiousjgeorge
|
C
|
Code
| 462
| 1,279
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/health/Health_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/health/model/EventDetails.h>
#include <aws/health/model/EventDetailsErrorItem.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace Health
{
namespace Model
{
class AWS_HEALTH_API DescribeEventDetailsResult
{
public:
DescribeEventDetailsResult();
DescribeEventDetailsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
DescribeEventDetailsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>Information about the events that could be retrieved.</p>
*/
inline const Aws::Vector<EventDetails>& GetSuccessfulSet() const{ return m_successfulSet; }
/**
* <p>Information about the events that could be retrieved.</p>
*/
inline void SetSuccessfulSet(const Aws::Vector<EventDetails>& value) { m_successfulSet = value; }
/**
* <p>Information about the events that could be retrieved.</p>
*/
inline void SetSuccessfulSet(Aws::Vector<EventDetails>&& value) { m_successfulSet = std::move(value); }
/**
* <p>Information about the events that could be retrieved.</p>
*/
inline DescribeEventDetailsResult& WithSuccessfulSet(const Aws::Vector<EventDetails>& value) { SetSuccessfulSet(value); return *this;}
/**
* <p>Information about the events that could be retrieved.</p>
*/
inline DescribeEventDetailsResult& WithSuccessfulSet(Aws::Vector<EventDetails>&& value) { SetSuccessfulSet(std::move(value)); return *this;}
/**
* <p>Information about the events that could be retrieved.</p>
*/
inline DescribeEventDetailsResult& AddSuccessfulSet(const EventDetails& value) { m_successfulSet.push_back(value); return *this; }
/**
* <p>Information about the events that could be retrieved.</p>
*/
inline DescribeEventDetailsResult& AddSuccessfulSet(EventDetails&& value) { m_successfulSet.push_back(std::move(value)); return *this; }
/**
* <p>Error messages for any events that could not be retrieved.</p>
*/
inline const Aws::Vector<EventDetailsErrorItem>& GetFailedSet() const{ return m_failedSet; }
/**
* <p>Error messages for any events that could not be retrieved.</p>
*/
inline void SetFailedSet(const Aws::Vector<EventDetailsErrorItem>& value) { m_failedSet = value; }
/**
* <p>Error messages for any events that could not be retrieved.</p>
*/
inline void SetFailedSet(Aws::Vector<EventDetailsErrorItem>&& value) { m_failedSet = std::move(value); }
/**
* <p>Error messages for any events that could not be retrieved.</p>
*/
inline DescribeEventDetailsResult& WithFailedSet(const Aws::Vector<EventDetailsErrorItem>& value) { SetFailedSet(value); return *this;}
/**
* <p>Error messages for any events that could not be retrieved.</p>
*/
inline DescribeEventDetailsResult& WithFailedSet(Aws::Vector<EventDetailsErrorItem>&& value) { SetFailedSet(std::move(value)); return *this;}
/**
* <p>Error messages for any events that could not be retrieved.</p>
*/
inline DescribeEventDetailsResult& AddFailedSet(const EventDetailsErrorItem& value) { m_failedSet.push_back(value); return *this; }
/**
* <p>Error messages for any events that could not be retrieved.</p>
*/
inline DescribeEventDetailsResult& AddFailedSet(EventDetailsErrorItem&& value) { m_failedSet.push_back(std::move(value)); return *this; }
private:
Aws::Vector<EventDetails> m_successfulSet;
Aws::Vector<EventDetailsErrorItem> m_failedSet;
};
} // namespace Model
} // namespace Health
} // namespace Aws
| 16,824
|
https://github.com/backpackcloud/captain-hook/blob/master/src/main/java/io/backpackcloud/captain_hook/impl/UnirestCannon.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
captain-hook
|
backpackcloud
|
Java
|
Code
| 320
| 763
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Marcelo Guimarães <ataxexe@backpackcloud.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.backpackcloud.captain_hook.impl;
import io.backpackcloud.captain_hook.Cannon;
import io.backpackcloud.captain_hook.Notification;
import io.backpackcloud.captain_hook.Serializer;
import io.backpackcloud.captain_hook.TemplateEngine;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import java.util.HashMap;
import java.util.Map;
public class UnirestCannon implements Cannon {
private final Serializer serializer;
private final TemplateEngine templateEngine;
public UnirestCannon(Serializer serializer, TemplateEngine templateEngine) {
this.serializer = serializer;
this.templateEngine = templateEngine;
}
@Override
public LoadedCannon load(Notification notification) {
return new LoadedCannon() {
Map<String, String> headers = new HashMap<>();
@Override
public LoadedCannon add(Map<String, String> additionalHeaders) {
this.headers.putAll(additionalHeaders);
return this;
}
@Override
public ReadyCannon aimAt(String url) {
return payload -> {
Map<String, ?> context = notification.context();
HttpResponse httpResponse = Unirest.post(templateEngine.evaluate(url, context))
.headers(templateEngine.evaluate(headers, context))
.header("Content-Type", "application/json")
.body(serializer.json().serialize(templateEngine.evaluate(payload, context)))
.asEmpty();
return new Cannon.Response() {
@Override
public int status() {
return httpResponse.getStatus();
}
@Override
public String message() {
return httpResponse.getStatusText();
}
};
};
}
};
}
}
| 20,681
|
https://github.com/SSSVT/ChatApp-Android/blob/master/ChatApplication/app/src/main/java/schweika/chatapplication/ViewModels/Interfaces/GenericViewModelListener.java
|
Github Open Source
|
Open Source
|
MIT
| null |
ChatApp-Android
|
SSSVT
|
Java
|
Code
| 15
| 55
|
package schweika.chatapplication.ViewModels.Interfaces;
public interface GenericViewModelListener<T>
{
public void onActionFailure(String message);
public void onActionSuccess(T item);
}
| 9,328
|
https://github.com/jeremyschlatter/augur/blob/master/packages/augur-simplified/src/modules/market/market-view.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
augur
|
jeremyschlatter
|
TypeScript
|
Code
| 567
| 1,953
|
import React, { useState, useEffect, useMemo } from 'react';
import { useLocation } from 'react-router';
import Styles from './market-view.styles.less';
import classNames from 'classnames';
import SimpleChartSection from '../common/charts';
import {
AddLiquidity,
CategoryIcon,
CategoryLabel,
NetworkMismatchBanner,
CurrencyLabel,
AddCurrencyLiquidity,
ReportingStateLabel,
InvalidFlagTipIcon
} from '../common/labels';
import {
PositionsLiquidityViewSwitcher,
TransactionsTable,
} from '../common/tables';
import TradingForm, {
DefaultMarketOutcomes,
OutcomesGrid,
} from './trading-form';
import { useAppStatusStore } from '../stores/app-status';
import { USDC, YES_NO, BUY, MARKET_ID_PARAM_NAME, ETH } from '../constants';
import parseQuery from '../routes/helpers/parse-query';
import { AmmExchange, MarketInfo } from '../types';
import { formatDai } from '../../utils/format-number';
import {
getMarketEndtimeFull,
getMarketEndtimeDate,
} from '../../utils/date-utils';
import { getCurrentAmms } from '../stores/app-status-hooks';
import { getWinningOutcome } from '../markets/markets-view';
import { ConfirmedCheck } from '../common/icons';
const WinningOutcomeLabel = ({ winningOutcome }) => (
<span className={Styles.WinningOutcomeLabel}>
<span>Winning Outcome</span>
<span>{winningOutcome.name}{ConfirmedCheck}</span>
</span>
);
const getDetails = (market) => {
const rawInfo = market?.extraInfoRaw || '{}';
const { longDescription } = JSON.parse(rawInfo, (key, value) => {
if (key === 'longDescription') {
// added to handle edge case were details are defined as an empty string.
const processDesc = value?.length !== 0 ? value.split('\n') : [];
return processDesc;
} else {
return value;
}
});
return longDescription || [];
};
const useMarketQueryId = () => {
const location = useLocation();
const { [MARKET_ID_PARAM_NAME]: marketId } = parseQuery(location.search);
return marketId;
};
const MarketView = ({ defaultMarket = null }) => {
const [showMoreDetails, setShowMoreDetails] = useState(false);
const marketId = useMarketQueryId();
const {
isMobile,
showTradingForm,
actions: { setShowTradingForm },
processed: { markets },
} = useAppStatusStore();
useEffect(() => {
// initial render only.
document.getElementById('mainContent')?.scrollTo(0, 0);
window.scrollTo(0, 1);
}, []);
const market: MarketInfo = !!defaultMarket
? defaultMarket
: markets[marketId];
const endTimeDate = useMemo(
() => getMarketEndtimeDate(market?.endTimestamp),
[market?.endTimestamp]
);
const [selectedOutcome, setSelectedOutcome] = useState(
market ? market.outcomes[2] : DefaultMarketOutcomes[2]
);
// add end time data full to market details when design is ready
const endTimeDateFull = useMemo(
() => getMarketEndtimeFull(market?.endTimestamp),
[market?.endTimestamp]
);
const amm: AmmExchange = market?.amm;
if (!market) return <div className={Styles.MarketView} />;
const details = getDetails(market);
const currentAMMs = getCurrentAmms(market, markets);
const { reportingState, outcomes } = market;
const winningOutcomes = getWinningOutcome(amm?.ammOutcomes, outcomes);
return (
<div className={Styles.MarketView}>
<section>
<NetworkMismatchBanner />
{isMobile && <ReportingStateLabel {...{ reportingState, big: true }} />}
<div className={Styles.topRow}>
<CategoryIcon big categories={market.categories} />
<CategoryLabel big categories={market.categories} />
{!isMobile && <ReportingStateLabel {...{ reportingState, big: true }} />}
<InvalidFlagTipIcon {...{ market, big: true }} />
<CurrencyLabel name={amm?.cash?.name} />
</div>
<h1>{market.description}</h1>
{winningOutcomes.length > 0 && <WinningOutcomeLabel winningOutcome={winningOutcomes[0]} />}
<ul className={Styles.StatsRow}>
<li>
<span>24hr Volume</span>
<span>{formatDai(amm?.volume24hrTotalUSD || '0.00').full}</span>
</li>
<li>
<span>Total Volume</span>
<span>{formatDai(amm?.volumeTotalUSD || '0.00').full}</span>
</li>
<li>
<span>Liquidity</span>
<span>{formatDai(amm?.liquidityUSD || '0.00').full}</span>
</li>
<li>
<span>Expires</span>
<span>{endTimeDate}</span>
</li>
</ul>
<OutcomesGrid
outcomes={amm?.ammOutcomes}
selectedOutcome={amm?.ammOutcomes[2]}
showAllHighlighted
setSelectedOutcome={(outcome) => {
setSelectedOutcome(outcome);
setShowTradingForm(true);
}}
marketType={YES_NO}
orderType={BUY}
ammCash={amm?.cash}
showAsButtons
/>
<SimpleChartSection {...{ market, cash: amm?.cash }} />
<PositionsLiquidityViewSwitcher ammExchange={amm} />
<article className={Styles.MobileLiquidSection}>
<AddLiquidity market={market} />
{currentAMMs.length === 1 && (
<AddCurrencyLiquidity
market={market}
currency={currentAMMs[0] === USDC ? ETH : USDC}
/>
)}
</article>
<div
className={classNames(Styles.Details, {
[Styles.isClosed]: !showMoreDetails,
})}
>
<h4>Market Details</h4>
<h5>Market Expiration: {endTimeDateFull}</h5>
{details.map((detail, i) => (
<p key={`${detail.substring(5, 25)}-${i}`}>{detail}</p>
))}
{details.length > 1 && (
<button onClick={() => setShowMoreDetails(!showMoreDetails)}>
{showMoreDetails ? 'Read Less' : 'Read More'}
</button>
)}
{details.length === 0 && (
<p>There are no additional details for this Market.</p>
)}
</div>
<div className={Styles.TransactionsTable}>
<span>Transactions</span>
<TransactionsTable transactions={amm?.transactions} />
</div>
</section>
<section className={classNames({
[Styles.ShowTradingForm]: showTradingForm,
})}>
<TradingForm initialSelectedOutcome={selectedOutcome} amm={amm} />
<AddLiquidity market={market} />
{currentAMMs.length === 1 && (
<AddCurrencyLiquidity
market={market}
currency={currentAMMs[0] === USDC ? ETH : USDC}
/>
)}
</section>
</div>
);
};
export default MarketView;
| 48,662
|
https://github.com/kuroneko/AFV-Native/blob/master/src/afv/dto/Transceiver.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
AFV-Native
|
kuroneko
|
C++
|
Code
| 329
| 821
|
/* afv/dto/Transceiver.cpp
*
* This file is part of AFV-Native.
*
* Copyright (c) 2019 Christopher Collins
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "afv-native/afv/dto/Transceiver.h"
#include <nlohmann/json.hpp>
using namespace afv_native::afv::dto;
using json = nlohmann::json;
Transceiver::Transceiver(uint16_t id, uint32_t freq, double lat, double lon, double msl, double agl):
ID(id),
Frequency(freq),
LatDeg(lat),
LonDeg(lon),
HeightMslM(msl),
HeightAglM(agl)
{
}
void afv_native::afv::dto::from_json(const json &j, Transceiver &ar)
{
j.at("ID").get_to(ar.ID);
j.at("Frequency").get_to(ar.Frequency);
j.at("LatDeg").get_to(ar.LatDeg);
j.at("LonDeg").get_to(ar.LonDeg);
j.at("HeightMslM").get_to(ar.HeightMslM);
j.at("HeightAglM").get_to(ar.HeightAglM);
};
void afv_native::afv::dto::to_json(json &j, const Transceiver &ar)
{
j = nlohmann::json{
{"ID", ar.ID},
{"Frequency", ar.Frequency},
{"LatDeg", ar.LatDeg},
{"LonDeg", ar.LonDeg},
{"HeightMslM", ar.HeightMslM},
{"HeightAglM", ar.HeightAglM},
};
}
| 47,898
|
https://github.com/TencentBlueKing/bk-nodeman/blob/master/frontend/src/common/freezing-page.ts
|
Github Open Source
|
Open Source
|
MIT, LicenseRef-scancode-free-unknown
| 2,023
|
bk-nodeman
|
TencentBlueKing
|
TypeScript
|
Code
| 232
| 766
|
import { DirectiveBinding, DirectiveOptions } from 'vue/types/options';
import { VueConstructor } from 'vue';
interface IValue {
include: string[] // 需要加滤镜的dom元素
exclude: string[] // 不被遮罩盖住的元素
disabled?: boolean // 是否禁用
}
const zIndex = () => {
// eslint-disable-next-line no-underscore-dangle
if (window.__bk_zIndex_manager && window.__bk_zIndex_manager.nextZIndex) {
// eslint-disable-next-line no-underscore-dangle
return window.__bk_zIndex_manager.nextZIndex();
}
return 2000;
};
const toggleFreezingPage = (el: HTMLElement, value: IValue = { include: [], exclude: [] }) => {
const { include = [], exclude = [], disabled = false } = value;
const index = zIndex();
const overlayId = '__freezing_page_id__';
if (!include.length) {
el.style.filter = disabled ? 'none' : 'grayscale(1)';
}
// 设置或者取消滤镜元素
include.forEach((selector) => {
const ele = el.querySelector(selector) as HTMLElement;
ele && (ele.style.filter = disabled ? 'none' : 'grayscale(1)');
});
// 设置或者取消不在遮罩里面元素的z-index
exclude.forEach((selector) => {
const ele = el.querySelector(selector) as HTMLElement;
ele && (ele.style.zIndex = disabled ? 'unset' : index);
});
const overlayDom = document.querySelector(`#${overlayId}`) as Node;
if (!disabled) {
if (overlayDom) return;
const overlay = document.createElement('div');
overlay.id = overlayId;
overlay.style.zIndex = String(index - 1);
overlay.style.cssText = 'position: absolute;top: 0;left: 0;'
+ 'background-color: rgba(255,255,255,.4);height: 100%;width: 100%';
el.style.position = 'relative';
el.appendChild(overlay);
} else if (overlayDom) {
el.removeChild(overlayDom);
}
};
const freezingPage: DirectiveOptions = {
inserted(el: HTMLElement, bind: DirectiveBinding) {
toggleFreezingPage(el, bind.value);
},
update(el: HTMLElement, bind: DirectiveBinding) {
toggleFreezingPage(el, bind.value);
},
unbind(el: HTMLElement, bind: DirectiveBinding) {
toggleFreezingPage(el, bind.value);
},
};
export default {
install: (Vue: VueConstructor) => Vue.directive('freezing-page', freezingPage),
directive: freezingPage,
};
| 22,927
|
https://github.com/gismya/svgomg/blob/master/src/css/components/_svg-output.scss
|
Github Open Source
|
Open Source
|
MIT
| null |
svgomg
|
gismya
|
SCSS
|
Code
| 78
| 251
|
.svg-output {
@include user-select(none);
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 0;
&.transition {
transition: opacity 0.2s ease-in-out;
}
&.active {
opacity: 1;
}
}
.svg-container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
transform-origin: 0 0;
transform: translateZ(0);
}
.svg-frame {
border: none;
overflow: hidden;
position: absolute;
top: 50%;
left: 50%;
pointer-events: none;
transform: translate(-50%, -50%);
}
.svg-clickjacker {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
| 32,217
|
https://github.com/ebt-hpc/cca-ebt/blob/master/python/src/cca/ebt/classify_loops.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
cca-ebt
|
ebt-hpc
|
Python
|
Code
| 415
| 1,377
|
#!/usr/bin/env python3
'''
A script for loop classification
Copyright 2013-2018 RIKEN
Copyright 2018-2020 Chiba Institute of Technology
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 writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
__author__ = 'Masatomo Hashimoto <m.hashimoto@stair.center>'
import csv
import numpy as np
from sklearn import preprocessing as pp
import joblib
import logging
from .make_loop_classifier import META, METRICS, fromstring, get_derived, Data
from .make_loop_classifier import SELECTED_MINAMI, DERIVED_MINAMI
from .make_loop_classifier import SELECTED_TERAI, DERIVED_TERAI
from .make_loop_classifier import SELECTED_MIX, DERIVED_MIX
logger = logging.getLogger()
def import_test_set(path,
selected=SELECTED_MINAMI,
derived=DERIVED_MINAMI,
filt={}):
_X = []
meta = []
try:
with open(path, newline='') as f:
reader = csv.DictReader(f)
count = 0
for row in reader:
d = dict((k, fromstring(row[k])) for k in METRICS)
skip = False
for k0, f in filt.items():
v0 = d[k0]
b0 = f(v0)
sub = row['sub']
logger.debug(f'k0={k0} d[k0]={v0} f(d[k0])={b0} sub={sub}')
if not b0:
skip = True
x = [d[k] for k in selected]
for k in derived:
v = get_derived(k, d)
try:
f = filt[k]
if not f(v):
skip = True
except Exception:
pass
x.append(v)
logger.debug('skip=%s' % skip)
if skip:
continue
m = dict((k, row[k]) for k in META)
_X.append(x)
meta.append(m)
count += 1
logger.info('%d rows' % count)
except Exception as e:
logger.warning(str(e))
X = np.array(_X)
data = Data(X, None, meta)
return data
def classify(path, clf_path, model='minami', filt={}, verbose=True):
clf = joblib.load(clf_path)
selected = SELECTED_MINAMI
derived = DERIVED_MINAMI
if model == 'minami':
selected = SELECTED_MINAMI
derived = DERIVED_MINAMI
elif model == 'terai':
selected = SELECTED_TERAI
derived = DERIVED_TERAI
elif model == 'mix':
selected = SELECTED_MIX
derived = DERIVED_MIX
else:
logger.warning(f'"{model}" is not supported. using default model')
data = import_test_set(path, selected=selected, derived=derived, filt=filt)
data_pred = None
if len(data.X) > 0:
X = pp.scale(data.X)
y_pred = clf.predict(X)
data_pred = Data(X, y_pred, data.meta)
if verbose:
for i in range(len(y_pred)):
m = data.meta[i]
m['pred'] = y_pred[i]
print('[{proj}][{ver}][{path}:{lnum}][{sub}] --> {pred}'.format(**m))
logger.info('[{proj}][{ver}][{path}:{lnum}][{sub}] --> {pred}'.format(**m))
return data_pred
if __name__ == '__main__':
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description='classify loops',
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('-d', '--debug', dest='debug', action='store_true',
help='enable debug printing')
parser.add_argument('-m', '--model', dest='model', metavar='MODEL',
type=str, default='minami',
help='model (minami|terai|mix)')
parser.add_argument('clf', metavar='CLF_PATH',
type=str, default='a.pkl', help='dumped classifier')
parser.add_argument('dpath', metavar='DATA_PATH', type=str,
help='test dataset')
args = parser.parse_args()
classify(args.dpath, args.clf, model=args.model)
| 43,367
|
https://github.com/saifsafwan/umapp/blob/master/resources/views/users/accountant/item/new.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
umapp
|
saifsafwan
|
PHP
|
Code
| 299
| 1,110
|
@extends('layouts.app')
@section('content')
<div class="flex items-center">
<div class="md:w-1/4 md:mx-auto">
{{-- @if (session('status'))
<div class="text-sm border border-t-8 rounded text-green-700 border-green-600 bg-green-100 px-3 py-4 mb-4" role="alert">
{{ session('status') }}
</div>
@endif --}}
<div class="flex flex-col break-words bg-white border-2 rounded shadow-md">
<div class="font-semibold bg-gray-200 text-gray-700 py-3 px-6 mb-0">
Add Item to Budget : {{$budget->title}}
</div>
<form action="{{route('item.store')}}" method="POST">
@csrf
<div class="w-3/4 p-6 mx-auto">
<label class="block">
<span class="text-gray-700 block mb-2 font-semibold">Item Name</span>
<input type="text" name="name" class="form-input mt-1 block w-full" placeholder="Budget for ...">
</label>
<label for="item_type" class="block text-gray-700 font-semibold mb-2 my-4">
Item Type
</label>
<div class="flex">
<select name="item_type" id="item_type" class="form-select block w-1/2" required>
<option value="" selected="selected">Please select ...</option>
<option value="asset">Asset</option>
<option value="service">Service</option>
</select>
<select id="type2" name="type2" class="form-select block w-1/2">
</select>
</div>
<label class="block mt-4">
<span class="text-gray-700 block mb-2 font-semibold">Price per Unit</span>
<div class="flex">
<span class="flex items-center rounded rounded-r-none border bg-gray-200 border-r-0 px-3 whitespace-no-wrap">RM</span>
<input type="number" step="0.10" name="unit_price" class="form-input block w-full" placeholder="10.00">
</div>
</label>
<label class="block mt-4">
<span class="text-gray-700 block mb-2 font-semibold">Quantity</span>
<input type="number" name="quantity" class="form-input mt-1 block w-full" placeholder="15">
</label>
<label class="block mt-4">
<span class="text-gray-700 block mb-2 font-semibold">Unit of measurement</span>
<input type="text" name="uom" class="form-input mt-1 block w-full" placeholder="pcs/mm/inches">
</label>
<input type="hidden" name="budget_id" value="{{$budget->id}}">
<button class="mt-4 p-4 rounded-md bg-accountant text-white" type="submit">Add Item to This Budget</button>
<a class="mt-4 p-4 rounded-md bg-gray-300 text-gray-600" href="{{ url()->previous() }}">Cancel</a>
</div>
</form>
</div>
</div>
</div>
<script>
// $("#item_type").on("change", function() {
// $("#" + $(this).val()).show().siblings().hide();
// })
var type2List = {
asset: ["New Purchase", "Replace Old Assets"],
service: ["Maintenance", "Training", "Consultation", "Honorarium", "Reimbursement", "Etc"]
}
// bind change event handler
$('#item_type').change(function() {
// get the second dropdown
$('#type2').html(
// get array by the selected value
type2List[this.value]
// iterate and generate options
.map(function(v) {
// generate options with the array element
return $('<option/>', {
value: v,
text: v
})
})
)
// trigger change event to generate second select tag initially
}).change()
</script>
@endsection
| 22,433
|
https://github.com/nhoizey/nicolas-hoizey.com/blob/master/_scripts/deploy-branch.sh
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
nicolas-hoizey.com
|
nhoizey
|
Shell
|
Code
| 18
| 100
|
#!/bin/sh
echo "Sync branch on server from local"
/usr/local/bin/rsync -arvu --delete-delay --iconv=UTF8-MAC,UTF-8 ./_site/ nhoizey@ssh-nhoizey.alwaysdata.net:/home/nhoizey/www/nicolas-hoizey.com/branch/ 2>&1 | tee ./_logs/deploy.log
| 16,394
|
https://github.com/refirser/needsomespace/blob/master/gamemodes/refn/entities/entities/nss_explosion_fx/shared.lua
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
needsomespace
|
refirser
|
Lua
|
Code
| 45
| 158
|
ENT.Base = "base_anim";
ENT.Type = "anim";
function ENT:Initialize()
self:SetModel( "models/props_combine/combine_interface00" .. math.random( 1, 3 ) .. ".mdl" );
self:PhysicsInit( SOLID_NONE );
self:SetMoveType( MOVETYPE_NONE );
self:SetSolid( SOLID_NONE );
if( CLIENT ) then
self:SetRenderBounds( Vector( -16384, -16384, -16384 ), Vector( 16384, 16384, 16384 ) );
end
end
| 31,484
|
https://github.com/roschler/ethereum-band-battles/blob/master/web-site/utility/check-balances-on-ganache.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ethereum-band-battles
|
roschler
|
JavaScript
|
Code
| 970
| 2,796
|
// FILE: check-balances-on-ganache.js
// This utility queries the current contract Ether Band Battles instance on
// Ganache for certain accounts and owner IDs (i.e. - YouTube channel ID
// etc.) so we can validate the results of playing a TBB game.
// This utility script simply shell executes truffle with various command line
// parameters and environment variables. It was created solely for the purpose
// of allowing us to keep our environment variables in the WebStorm IDE
// run/debug configurations.
const uuidV4 = require('uuid/v4');
const argv = require('minimist')(process.argv);
const common_routines = require('../common/common-routines');
const misc_shared_lib = require('../public/javascripts/misc/misc-shared');
const logging_helpers_lib = require('../common/logging-helpers');
const solidity_helpers_misc = require('../common/solidity-helpers-misc');
const EthereumGlobals = require('../ethereum/ethereum-globals').EthereumGlobals;
const { exec } = require("child_process");
let errPrefix = `(check-balances-on-ganache.js) `;
/**
* Simple object to hold an ID string and the blockchain balance
* associated with that ID.
*
* @constructor
*/
function ID_And_Balance() {
const self = this;
let methodName = self.constructor.name + '::' + `constructor`;
let errPrefix = '(' + methodName + ') ';
/** @property {string} - A randomly generated unique ID for this object. */
this.id = uuidV4();
/** @property {Date} - The date/time this object was created. */
this.dtCreated = Date.now();
/** @property {String} - The ID of the entity that is associated with the balance. */
this.idOfOwner = null;
/** @property {Number} - The amount of value associated with the
* public blockchain address this object holds. */
this.balance = null;
/**
* Show the relevant contents of this object in a formatted string.
*/
this.toString = function() {
return `Address: ${self.idOfOwner}, Balance: ${self.balance}`;
}
}
/**
* Get the balances from the ThetaBandBattles smart contract for
* each of the addresses in the given array of public addresses
* given to us.
*
* @param {Array<string>} aryidOfOwner - An array of public addresses.
*
* @return {Promise<Array<ID_And_Balance>} - Returns and array of
* ID_And_Balance objects, one for each public address given to us.
*/
async function getMultipleBalances(aryidOfOwner) {
let errPrefix = `(getMultipleBalances) `;
if (!Array.isArray(aryidOfOwner))
throw new Error(errPrefix + `The aryidOfOwner parameter value is not an array.`);
if (aryidOfOwner.length < 1)
throw new Error(errPrefix + `The aryidOfOwner array is empty.`);
let retAryIdAndBalance = new Array();
for (let ndx = 0; ndx < aryidOfOwner.length; ndx++)
{
let idOfOwner = aryidOfOwner[ndx];
// Query the smart contract for each balance.
let actualAccountBalance = await EthereumGlobals.web3Global.eth.getBalance(idOfOwner)
.catch(err => {
let errMsg =
errPrefix + misc_shared_lib.conformErrorObjectMsg(err);
console.error(errMsg + `Unable to fetch balance for public address: ${idOfOwner}. promise/catch.`);
});
// Accumulate the result.
let idAndBalance = new ID_And_Balance();
idAndBalance.balance = actualAccountBalance;
idAndBalance.idOfOwner = idOfOwner;
retAryIdAndBalance.push(idAndBalance);
}
return retAryIdAndBalance;
}
/**
* Get the balances from the ThetaBandBattles smart contract for
* each of the addresses in the given array of public addresses
* given to us.
*
* @param {Object} - A smart contract instance.
* @param {Array<string>} aryOwnerIDs - An array of owner IDs.
*
* @return {Promise<Array<ID_And_Balance>} - Returns and array of
* ID_And_Balance objects, one for each owner ID given to us.
*/
async function getMultipleEscrowAmounts(contractInstance, aryOwnerIDs) {
let errPrefix = `(getMultipleEscrowAmounts) `;
if (!misc_shared_lib.isNonNullObjectAndNotArray(contractInstance))
throw new Error(errPrefix + `The value in the contractInstance parameter is invalid.`);
if (!Array.isArray(aryOwnerIDs))
throw new Error(errPrefix + `The aryOwnerIDs parameter value is not an array.`);
if (aryOwnerIDs.length < 1)
throw new Error(errPrefix + `The aryOwnerIDs array is empty.`);
let retAryIdAndBalance = new Array();
for (let ndx = 0; ndx < aryOwnerIDs.length; ndx++)
{
let ownerID = aryOwnerIDs[ndx];
// Format the owner ID for Solidity's use.
let formattedOwnerID = EthereumGlobals.web3Global.utils.fromAscii(ownerID);
// Query the smart contract for each escrow amount.
let actualAccountBalance = await contractInstance.methods.getEscrowBalance(formattedOwnerID).call()
.catch(err => {
let errMsg =
errPrefix + misc_shared_lib.conformErrorObjectMsg(err);
console.error(errMsg + `Unable to fetch escrow amount for owner ID: ${ownerID}. promise/catch.`);
});
// Accumulate the result.
let idAndBalance = new ID_And_Balance();
idAndBalance.balance = actualAccountBalance;
idAndBalance.idOfOwner = ownerID;
retAryIdAndBalance.push(idAndBalance);
}
return retAryIdAndBalance;
}
try {
let contractInstance = EthereumGlobals.ebbContractInstance;
// Test our access to the contract.
/*
contractInstance.methods.testReturnTuple().call()
.then(result => {
console.log('TUPLE RETURNED: ' + result);
// Get the total number of games created.
return contractInstance.methods.getNumGamesCreated().call();
})
.then(result => {
console.log(`Num games created call result: ${result}.`);
// Get our address as another test using the testReturnAddress()
// method.
return contractInstance.methods.testReturnAddress().call();
})
.then(result => {
console.log(`testReturnAddress() call result: ${result}.`);
// Get the contract balance.
return contractInstance.methods.getContractBalance().call();
})
*/
// Array of test account public addresses.
let aryTestAccounts = [
"0xfF44E797E2EcDDd497f958B3F985e3f25Fc248a1",
"0xd867c5512566ef75F797B31Dd623B450e43725Ff",
"0xE9bd36ae910c229f44310E8A9B4FdEB0f9f686a5"
];
// Array of YouTube channel IDs we use for testing.
let aryChannelIDs = [
"UCqK_GSMbpiV8spgD3ZGloSw", // Coin Bureau
"UCMtJYS0PrtiUwlk6zjGDEMA", // EllioTrades Crypto
"UCObk_g1hQBy0RKKriVX_zOQ" // Netflix is a Jok
];
console.log('=================== BEGIN: REPORT ===============');
contractInstance.methods.getContractBalance().call()
.then(result => {
let str = `Current balance of Ether Band Battles contract: ${result}.`;
console.log(str);
// Get the balances for test accounts we use.
return getMultipleBalances(aryTestAccounts);
})
.then(result => {
if (!Array.isArray(result))
throw new Error(errPrefix + `The result parameter value is not an array.`);
let aryIdAndBalance = result;
// Show all the addresses and balances.
for (let ndx = 0; ndx < aryIdAndBalance.length; ndx++)
{
let idAndBalanceElement = aryIdAndBalance[ndx];
if (!(idAndBalanceElement instanceof ID_And_Balance))
throw new Error(errPrefix + `The value found at array index(${ndx}) is not an ID_And_Balance object.`);
let str = idAndBalanceElement.toString();
console.log(str);
}
return getMultipleEscrowAmounts(contractInstance, aryChannelIDs);
})
.then(result => {
if (!Array.isArray(result))
throw new Error(errPrefix + `The result parameter value is not an array.`);
let aryIdAndBalance = result;
// Show all the addresses and balances.
for (let ndx = 0; ndx < aryIdAndBalance.length; ndx++)
{
let idAndBalanceElement = aryIdAndBalance[ndx];
if (!(idAndBalanceElement instanceof ID_And_Balance))
throw new Error(errPrefix + `The value found at array index(${ndx}) is not an ID_And_Balance object.`);
let str = idAndBalanceElement.toString();
console.log(str);
}
console.log('=================== END : REPORT ===============');
process.exit(0);
return;
})
.catch(err => {
let errMsg =
errPrefix + misc_shared_lib.conformErrorObjectMsg(err);
console.log(`[ERROR: ${errMsg}] Error during promise -> ${errMsg}`);
process.exit(1);
});
}
catch (err)
{
let errMsg =
errPrefix + misc_shared_lib.conformErrorObjectMsg(err);
console.log(`[ERROR: ${errMsg}] Error during try/catch -> ${errMsg}`);
process.exit(1);
} // try/catch
| 42,262
|
https://github.com/JSTransformationBenchmarks/lively4-core/blob/master/src/components/halo/lively-halo-connectors-item.js
|
Github Open Source
|
Open Source
|
MIT
| null |
lively4-core
|
JSTransformationBenchmarks
|
JavaScript
|
Code
| 458
| 1,935
|
"enable aexpr";
import HaloItem from 'src/components/halo/lively-halo-item.js';
import {pt} from 'src/client/graphics.js';
import ContextMenu from "src/client/contextmenu.js";
import Connection from "./Connection.js";
export default class LivelyHaloConnectorsItem extends HaloItem {
async initialize() {
this.windowTitle = "LivelyHaloConnectorsItem";
this.registerEvent('click', 'onClick');
}
onClick(evt) {
this.source = window.that;
this.showStartingConnectorsMenuFor(evt);
this.hideHalo();
}
async showMenu(evt, menuItems) {
const menu = await ContextMenu.openIn(document.body, evt, undefined, document.body, menuItems);
}
async showStartingConnectorsMenuFor(evt) {
let connections = []
Connection.allConnections.forEach(connection => {
connections.push(connection)
})
let existingConnectionsMenu = connections.map(connection => [connection.getLabel(), () => this.openConnectionEditor(connection)]);
let myConnectionsMenu = Connection.allConnectionsFor(this.source).map(connection => [connection.getLabel(), () => this.openConnectionEditor(connection)]);
const menuItems = [
['Value', () => this.startCreatingConnectionFor(evt, 'value', false)],
['Width', () => this.startCreatingConnectionFor(evt, 'style.width', false)],
['Height', () => this.startCreatingConnectionFor(evt, 'style.height', false)],
['Events', this.getAllEventsFor(this.source, evt)],
['Style', this.getAllStylesFor(this.source, evt)],
['On custom...', () => this.startCreatingConnectionCustom(evt)],
['My Connections', myConnectionsMenu, '', '<i class="fa fa-arrow-right" aria-hidden="true"></i>'],
['All Connections', existingConnectionsMenu, '', '<i class="fa fa-arrow-right" aria-hidden="true"></i>']
];
this.showMenu(evt, menuItems);
}
//More events https://developer.mozilla.org/en-US/docs/Web/Events
getAllEventsFor(object, evt) {
return [['Click', () => this.startCreatingConnectionFor(evt, 'click', true)],
['DoubleClick', () => this.startCreatingConnectionFor(evt, 'dblclick', true)],
['MouseDown', () => this.startCreatingConnectionFor(evt, 'mousedown', true)],
['MouseEnter', () => this.startCreatingConnectionFor(evt, 'mouseenter', true)],
['MouseLeave', () => this.startCreatingConnectionFor(evt, 'mouseleave', true)],
['MouseMove', () => this.startCreatingConnectionFor(evt, 'mousemove', true)],
['MouseOver', () => this.startCreatingConnectionFor(evt, 'mouseover', true)],
['MouseOut', () => this.startCreatingConnectionFor(evt, 'mouseout', true)],
['MouseUp', () => this.startCreatingConnectionFor(evt, 'mouseup', true)]]
}
getAllStylesFor(object, evt, isFinishing = false) {
let result = [];
let styles = window.getComputedStyle(object);
let stylesLength = styles.length;
for(let i = 0; i < stylesLength; i++){
if(isFinishing){
result.push([styles.item(i), event => this.finishCreatingConnection(object, 'style.' + styles.item(i), event)]);
} else {
result.push([styles.item(i), () => this.startCreatingConnectionFor(evt, 'style.' + styles.item(i), false)]);
}
}
return result;
}
async showFinishingConnectorsMenuFor(evt, morph) {
const menuItems = [
['Value', event => this.finishCreatingConnection(morph, 'value', event)],
['Width', event => this.finishCreatingConnection(morph, 'style.width', event)],
['Height', event => this.finishCreatingConnection(morph, 'style.height', event)],
['InnerHTML', event => this.finishCreatingConnection(morph, 'innerHTML', event)],
// Hook for chained events
//['Events', this.getAllEventsFor(morph, evt, true)],
['Style', this.getAllStylesFor(morph, evt, true)],
['On custom...', event => this.finishCreatingConnectionCustom(morph, event)]];
this.showMenu(evt, menuItems);
}
elementUnderHand(evt) {
var path = evt.composedPath().slice(evt.composedPath().indexOf(evt.srcElement))
return path[0]
}
onPointerMove(evt) {
if (this.dropIndicator) this.dropIndicator.remove()
this.dropTarget = this.elementUnderHand(evt)
if (this.dropTarget) {
this.dropIndicator = lively.showElement(this.dropTarget)
this.dropIndicator.style.border = "3px dashed rgba(0,100,0,0.5)"
this.dropIndicator.innerHTML = ""
}
if (this.valueIndicator) this.valueIndicator.remove();
this.valueIndicator = <span>{this.sourceProperty}</span>;
this.valueIndicator.style.zIndex = 200;
lively.setGlobalPosition(this.valueIndicator, pt(lively.getPosition(evt).x+1, lively.getPosition(evt).y+1));
document.body.appendChild(this.valueIndicator);
}
onPointerUp(evt) {
lively.removeEventListener("Connectors")
if (this.dropIndicator) this.dropIndicator.remove()
if (this.valueIndicator) this.valueIndicator.remove()
var morph = this.elementUnderHand(evt)
this.showFinishingConnectorsMenuFor(evt, morph);
}
async openConnectionEditor(connection) {
let editor = await lively.openComponentInWindow('lively-connection-editor')
editor.setConnection(connection)
}
async startCreatingConnectionCustom(evt) {
var userinput = await lively.prompt("Enter something", "value");
this.startCreatingConnectionFor(evt, userinput, false);
}
startCreatingConnectionFor(evt, property, isEvent) {
this.sourceProperty = property;
this.isEvent = isEvent;
lively.addEventListener("Connectors", document.body.parentElement, "pointermove",
e => this.onPointerMove(e), { capture: true });
lively.addEventListener("Connectors", document.body.parentElement, "pointerup",
e => this.onPointerUp(e), { capture: true });
}
async finishCreatingConnectionCustom(target, event) {
var userinput = await lively.prompt("Enter something", "style.width");
this.finishCreatingConnection(target, userinput, event);
}
finishCreatingConnection(target, targetProperty, event) {
let connection = new Connection(target, targetProperty, this.source, this.sourceProperty, this.isEvent);
connection.activate();
connection.drawConnectionLine();
if(!event.shiftKey){
this.openConnectionEditor(connection);
}
}
}
| 19,541
|
https://github.com/kiva/Mikoba/blob/master/mikoba/Services/OtpCredentialsService.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
Mikoba
|
kiva
|
C#
|
Code
| 258
| 785
|
using Newtonsoft.Json;
using System;
using System.Net;
using System.Threading.Tasks;
namespace mikoba.Services
{
public class OtpCredentialsService
{
private const string AUTH0_DOMAIN = "kiva-protocol.auth0.com";
private const string CLIENT_ID = "dn2GNhnpOViDG1P1prNAt5UBoN6YEEHu";
private const string USERNAME = "";
private const string PASSWORD = "";
// ReSharper disable once UnusedMember.Global
public async Task<TokenResponse> GetAccessInfo()
{
var endpoint = AUTH0_DOMAIN + "/oauth/token";
var method = "POST";
var json = JsonConvert.SerializeObject(new
{
username = USERNAME,
password = PASSWORD,
client_id = CLIENT_ID,
grant_type = "password",
});
var wc = new WebClient {Headers = {["Content-Type"] = "application/json"}};
try
{
var response =await wc.UploadStringTaskAsync(endpoint, method, json);
var userResult = JsonConvert.DeserializeObject<TokenResponse>(response);
return userResult;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return null;
}
}
// ReSharper disable once UnusedMember.Global
public async Task<OtpResponse> RequestOTPCode(string nin, string phoneNumber)
{
var endpoint = AUTH0_DOMAIN + "/oauth/token";
var method = "POST";
var json = JsonConvert.SerializeObject(new
{
username = USERNAME,
password = PASSWORD,
client_id = CLIENT_ID,
grant_type = "password",
});
var wc = new WebClient {Headers = {["Content-Type"] = "application/json"}};
try
{
var response = await wc.UploadStringTaskAsync(endpoint, method, json);
var userResult = JsonConvert.DeserializeObject<OtpResponse>(response);
return userResult;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
public async Task<KycResponse> FetchKYCData(string otpNumber)
{
var endpoint = AUTH0_DOMAIN + "/oauth/token";
var method = "POST";
var json = JsonConvert.SerializeObject(new
{
username = USERNAME,
password = PASSWORD,
client_id = CLIENT_ID,
grant_type = "password",
});
var wc = new WebClient {Headers = {["Content-Type"] = "application/json"}};
try
{
var response = await wc.UploadStringTaskAsync(endpoint, method, json);
var userResult = JsonConvert.DeserializeObject<KycResponse>(response);
return userResult;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return null;
}
}
}
}
| 44,615
|
https://github.com/z424brave/Arachnid-Robotics/blob/master/test/RobotControl_spec.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Arachnid-Robotics
|
z424brave
|
TypeScript
|
Code
| 501
| 1,458
|
import { expect } from "chai";
import { MarsSurface } from "../src/MarsSurface";
import { RobotControl } from "../src/RobotControl";
import { Wall } from "../src/Wall";
describe("RobotControl", () => {
interface ITest {
command: string;
finalPosition: string;
height?: number;
title: string;
width?: number;
}
describe("RobotControl Mk1", () => {
const tests: ITest[] = [
{
command: "0,0,FRFRFRF",
finalPosition: "(3, 4)",
title: "start at (0, 0) and move to (3, 4)",
},
{
command: "5,5,FLFFF",
finalPosition: "(4, 9)",
title: "start at (5, 5) and move to (4, 9)",
},
];
tests.forEach((test: ITest) => {
it(`should ${test.title}`, () => {
const robotControl: RobotControl = new RobotControl(
test.command,
"Mk1",
);
const result: string = robotControl.executeCommands();
expect(result).eql(test.finalPosition);
});
});
});
describe("RobotControl Mk2", () => {
const tests: ITest[] = [
{
command: "0,0,north,FRFRFRF",
finalPosition: "(0, 0)",
title: "start at (0, 0) and move to (0, 0)",
},
{
command: "5,5,east,FLFFF",
finalPosition: "(6, 8)",
title: "start at (5, 5) and move to (6, 8)",
},
{
command: "0,7,north,FFFRFFFLF",
finalPosition: "(3, 11)",
title: "start at (0, 7) and move to (3, 11)",
},
{
command: "0,0,north,FFFRFFFLF",
finalPosition: "(3, 4)",
height: 5,
title: "start at (0, 0) and move to (3, 4)",
width: 5,
},
{
command: "0,0,north,FFFRRFFFLF",
finalPosition: "(1, 0)",
title: "start at (0, 0) and move to (1, 0)",
},
{
command: "0,0,north,FFFFFFFFFF",
finalPosition: "(0, 5)",
height: 5,
title: "start at (0, 0) and move to (0, 5)",
width: 5,
},
{
command: "0,5",
finalPosition: "(0, 0)",
title: "not move if command does not have 4 valid parts",
},
{
command: "abc",
finalPosition: "(0, 0)",
title: "not move if command does not have 4 valid parts",
},
{
command: "a,b,c,d",
finalPosition: "(0, 0)",
title: "not move if command does not have numeric coordinates",
},
{
command: undefined,
finalPosition: "(0, 0)",
title: "not move if command is undefined",
},
];
tests.forEach((test: ITest) => {
it(`should ${test.title}`, () => {
const robotControl: RobotControl = new RobotControl(
test.command,
"Mk2",
new Wall(test.height, test.width),
);
const result: string = robotControl.executeCommands();
expect(result).eql(test.finalPosition);
});
});
});
describe("RobotControl Mk3", () => {
const tests: ITest[] = [
{
command: "0,0,north,FRFRFR",
finalPosition: "(1, 0)",
title: "start at (0, 0) and move to (1, 0)",
},
{
command: "5,5,north,FLFFF",
finalPosition: "(2, 6)",
title: "start at (5, 5) and move to (2, 6)",
},
{
command: "0,0,north,5F5F5F",
finalPosition: "(0, 15)",
title: "start at (0, 0) and move to (0, 15) using boost",
},
{
command: "0,0,north,6F",
finalPosition: "(0, 1)",
title: "start at (0, 0) and move to (0, 1) - boost > 6 replaced with a single move",
},
{
command: "0,0,north,5F5F5F5F5F5F5F",
finalPosition: "(0, 31)",
title: "start at (0, 0) and move to (0, 30) fuel exhausted after 6 boosts of 5",
},
{
command: "0,0,north,5F5F5F5F5F5FF",
finalPosition: "(0, 31)",
title: "start at (0, 0) and move to (0, 31) non boost move still available after fuel exhausted",
},
];
tests.forEach((test: ITest) => {
it(`should ${test.title}`, () => {
const robotControl: RobotControl = new RobotControl(
test.command,
"Mk3",
new MarsSurface(),
);
const result: string = robotControl.executeCommands();
expect(result).eql(test.finalPosition);
});
});
});
});
| 16,138
|
https://github.com/cliveyao/TestRepository/blob/master/src/main/java/org/lf/admin/db/pojo/JRW.java
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
TestRepository
|
cliveyao
|
Java
|
Code
| 339
| 993
|
package org.lf.admin.db.pojo;
import java.util.Date;
public class JRW extends PagedPojo {
private Integer id;
private Integer appId;
private Integer lx;
private String lxmc;
private Date kssj;
private Date jssj;
private String czr;
private String czrmc;
private String czRemark;
private String ysr;
private String ysrmc;
private String ysRemark;
private Date yssj;
private Integer total;
private Integer finishCount;
private Integer finish;
public String getCzrmc() {
return czrmc;
}
public void setCzrmc(String czrmc) {
this.czrmc = czrmc;
}
public String getYsrmc() {
return ysrmc;
}
public void setYsrmc(String ysrmc) {
this.ysrmc = ysrmc;
}
public String getLxmc() {
return lxmc;
}
public void setLxmc(String lxmc) {
this.lxmc = lxmc;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAppId() {
return appId;
}
public void setAppId(Integer appId) {
this.appId = appId;
}
public Integer getLx() {
return lx;
}
public void setLx(Integer lx) {
this.lx = lx;
}
public Date getKssj() {
return kssj;
}
public void setKssj(Date kssj) {
this.kssj = kssj;
}
public Date getJssj() {
return jssj;
}
public void setJssj(Date jssj) {
this.jssj = jssj;
}
public String getCzr() {
return czr;
}
public void setCzr(String czr) {
this.czr = czr == null ? null : czr.trim();
}
public String getCzRemark() {
return czRemark;
}
public void setCzRemark(String czRemark) {
this.czRemark = czRemark == null ? null : czRemark.trim();
}
public String getYsr() {
return ysr;
}
public void setYsr(String ysr) {
this.ysr = ysr == null ? null : ysr.trim();
}
public String getYsRemark() {
return ysRemark;
}
public void setYsRemark(String ysRemark) {
this.ysRemark = ysRemark == null ? null : ysRemark.trim();
}
public Date getYssj() {
return yssj;
}
public void setYssj(Date yssj) {
this.yssj = yssj;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getFinishCount() {
return finishCount;
}
public void setFinishCount(Integer finishCount) {
this.finishCount = finishCount;
}
public Integer getFinish() {
return finish;
}
public void setFinish(Integer finish) {
this.finish = finish;
}
}
| 10,237
|
https://github.com/Blasco9/Course-Reviews/blob/master/app/models/user.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Course-Reviews
|
Blasco9
|
Ruby
|
Code
| 99
| 410
|
class User < ApplicationRecord
after_create :attach_default_img
has_many :reviews, foreign_key: :author_id, dependent: :destroy
has_many :comments, foreign_key: :author_id, dependent: :destroy
has_many :followings, foreign_key: :followed_id, dependent: :destroy
has_many :inverse_followings, class_name: 'Following', foreign_key: :follower_id, dependent: :destroy
has_many :followers, through: :followings
has_many :followeds, through: :inverse_followings
validates :username, presence: true, uniqueness: true
validates :full_name, presence: true
has_one_attached :photo
has_one_attached :cover_image
def users_to_follow
if followeds.any?
User.where("id NOT IN (#{id}, ?)", followeds.ids)
else
User.where.not(id: id)
end
end
# rubocop: disable Style/GuardClause
def attach_default_img
unless photo.attached?
photo.attach(io: File.open('app/assets/images/user_img.png'),
filename: 'user_img.png', content_type: 'image/png')
end
unless cover_image.attached?
cover_image.attach(io: File.open('app/assets/images/cover_img.jpg'),
filename: 'cover_img.jpg', content_type: 'image/jpg')
end
end
# rubocop: enable Style/GuardClause
end
| 736
|
https://github.com/ivansukach/protobuf/blob/master/test/oneof/combos/unmarshaler/one.pb.go
|
Github Open Source
|
Open Source
|
BSD-2-Clause, 0BSD
| null |
protobuf
|
ivansukach
|
Go
|
Code
| 20,000
| 53,162
|
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: combos/unmarshaler/one.proto package one import ( bytes "bytes" compress_gzip "compress/gzip" encoding_binary "encoding/binary" fmt "fmt" _ "github.com/ivansukach/protobuf/gogoproto" github_com_gogo_protobuf_proto "github.com/ivansukach/protobuf/proto" proto "github.com/ivansukach/protobuf/proto" github_com_gogo_protobuf_protoc_gen_gogo_descriptor "github.com/ivansukach/protobuf/protoc-gen-gogo/descriptor" github_com_gogo_protobuf_test_casttype "github.com/ivansukach/protobuf/test/casttype" github_com_gogo_protobuf_test_custom "github.com/ivansukach/protobuf/test/custom" io "io" io_ioutil "io/ioutil" math "math" math_bits "math/bits" reflect "reflect" strings "strings" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type Subby struct { Sub *string `protobuf:"bytes,1,opt,name=sub" json:"sub,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Subby) Reset() { *m = Subby{} } func (*Subby) ProtoMessage() {} func (*Subby) Descriptor() ([]byte, []int) { return fileDescriptor_9eef12518f7c4f58, []int{0} } func (m *Subby) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *Subby) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Subby.Marshal(b, m, deterministic) } func (m *Subby) XXX_Merge(src proto.Message) { xxx_messageInfo_Subby.Merge(m, src) } func (m *Subby) XXX_Size() int { return xxx_messageInfo_Subby.Size(m) } func (m *Subby) XXX_DiscardUnknown() { xxx_messageInfo_Subby.DiscardUnknown(m) } var xxx_messageInfo_Subby proto.InternalMessageInfo type AllTypesOneOf struct { // Types that are valid to be assigned to TestOneof: // *AllTypesOneOf_Field1 // *AllTypesOneOf_Field2 // *AllTypesOneOf_Field3 // *AllTypesOneOf_Field4 // *AllTypesOneOf_Field5 // *AllTypesOneOf_Field6 // *AllTypesOneOf_Field7 // *AllTypesOneOf_Field8 // *AllTypesOneOf_Field9 // *AllTypesOneOf_Field10 // *AllTypesOneOf_Field11 // *AllTypesOneOf_Field12 // *AllTypesOneOf_Field13 // *AllTypesOneOf_Field14 // *AllTypesOneOf_Field15 // *AllTypesOneOf_SubMessage TestOneof isAllTypesOneOf_TestOneof `protobuf_oneof:"test_oneof"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *AllTypesOneOf) Reset() { *m = AllTypesOneOf{} } func (*AllTypesOneOf) ProtoMessage() {} func (*AllTypesOneOf) Descriptor() ([]byte, []int) { return fileDescriptor_9eef12518f7c4f58, []int{1} } func (m *AllTypesOneOf) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *AllTypesOneOf) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_AllTypesOneOf.Marshal(b, m, deterministic) } func (m *AllTypesOneOf) XXX_Merge(src proto.Message) { xxx_messageInfo_AllTypesOneOf.Merge(m, src) } func (m *AllTypesOneOf) XXX_Size() int { return xxx_messageInfo_AllTypesOneOf.Size(m) } func (m *AllTypesOneOf) XXX_DiscardUnknown() { xxx_messageInfo_AllTypesOneOf.DiscardUnknown(m) } var xxx_messageInfo_AllTypesOneOf proto.InternalMessageInfo type isAllTypesOneOf_TestOneof interface { isAllTypesOneOf_TestOneof() Equal(interface{}) bool VerboseEqual(interface{}) error Size() int Compare(interface{}) int } type AllTypesOneOf_Field1 struct { Field1 float64 `protobuf:"fixed64,1,opt,name=Field1,oneof" json:"Field1,omitempty"` } type AllTypesOneOf_Field2 struct { Field2 float32 `protobuf:"fixed32,2,opt,name=Field2,oneof" json:"Field2,omitempty"` } type AllTypesOneOf_Field3 struct { Field3 int32 `protobuf:"varint,3,opt,name=Field3,oneof" json:"Field3,omitempty"` } type AllTypesOneOf_Field4 struct { Field4 int64 `protobuf:"varint,4,opt,name=Field4,oneof" json:"Field4,omitempty"` } type AllTypesOneOf_Field5 struct { Field5 uint32 `protobuf:"varint,5,opt,name=Field5,oneof" json:"Field5,omitempty"` } type AllTypesOneOf_Field6 struct { Field6 uint64 `protobuf:"varint,6,opt,name=Field6,oneof" json:"Field6,omitempty"` } type AllTypesOneOf_Field7 struct { Field7 int32 `protobuf:"zigzag32,7,opt,name=Field7,oneof" json:"Field7,omitempty"` } type AllTypesOneOf_Field8 struct { Field8 int64 `protobuf:"zigzag64,8,opt,name=Field8,oneof" json:"Field8,omitempty"` } type AllTypesOneOf_Field9 struct { Field9 uint32 `protobuf:"fixed32,9,opt,name=Field9,oneof" json:"Field9,omitempty"` } type AllTypesOneOf_Field10 struct { Field10 int32 `protobuf:"fixed32,10,opt,name=Field10,oneof" json:"Field10,omitempty"` } type AllTypesOneOf_Field11 struct { Field11 uint64 `protobuf:"fixed64,11,opt,name=Field11,oneof" json:"Field11,omitempty"` } type AllTypesOneOf_Field12 struct { Field12 int64 `protobuf:"fixed64,12,opt,name=Field12,oneof" json:"Field12,omitempty"` } type AllTypesOneOf_Field13 struct { Field13 bool `protobuf:"varint,13,opt,name=Field13,oneof" json:"Field13,omitempty"` } type AllTypesOneOf_Field14 struct { Field14 string `protobuf:"bytes,14,opt,name=Field14,oneof" json:"Field14,omitempty"` } type AllTypesOneOf_Field15 struct { Field15 []byte `protobuf:"bytes,15,opt,name=Field15,oneof" json:"Field15,omitempty"` } type AllTypesOneOf_SubMessage struct { SubMessage *Subby `protobuf:"bytes,16,opt,name=sub_message,json=subMessage,oneof" json:"sub_message,omitempty"` } func (*AllTypesOneOf_Field1) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field2) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field3) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field4) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field5) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field6) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field7) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field8) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field9) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field10) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field11) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field12) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field13) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field14) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field15) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_SubMessage) isAllTypesOneOf_TestOneof() {} func (m *AllTypesOneOf) GetTestOneof() isAllTypesOneOf_TestOneof { if m != nil { return m.TestOneof } return nil } func (m *AllTypesOneOf) GetField1() float64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field1); ok { return x.Field1 } return 0 } func (m *AllTypesOneOf) GetField2() float32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field2); ok { return x.Field2 } return 0 } func (m *AllTypesOneOf) GetField3() int32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field3); ok { return x.Field3 } return 0 } func (m *AllTypesOneOf) GetField4() int64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field4); ok { return x.Field4 } return 0 } func (m *AllTypesOneOf) GetField5() uint32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field5); ok { return x.Field5 } return 0 } func (m *AllTypesOneOf) GetField6() uint64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field6); ok { return x.Field6 } return 0 } func (m *AllTypesOneOf) GetField7() int32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field7); ok { return x.Field7 } return 0 } func (m *AllTypesOneOf) GetField8() int64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field8); ok { return x.Field8 } return 0 } func (m *AllTypesOneOf) GetField9() uint32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field9); ok { return x.Field9 } return 0 } func (m *AllTypesOneOf) GetField10() int32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field10); ok { return x.Field10 } return 0 } func (m *AllTypesOneOf) GetField11() uint64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field11); ok { return x.Field11 } return 0 } func (m *AllTypesOneOf) GetField12() int64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field12); ok { return x.Field12 } return 0 } func (m *AllTypesOneOf) GetField13() bool { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field13); ok { return x.Field13 } return false } func (m *AllTypesOneOf) GetField14() string { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field14); ok { return x.Field14 } return "" } func (m *AllTypesOneOf) GetField15() []byte { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field15); ok { return x.Field15 } return nil } func (m *AllTypesOneOf) GetSubMessage() *Subby { if x, ok := m.GetTestOneof().(*AllTypesOneOf_SubMessage); ok { return x.SubMessage } return nil } // XXX_OneofWrappers is for the internal use of the proto package. func (*AllTypesOneOf) XXX_OneofWrappers() []interface{} { return []interface{}{ (*AllTypesOneOf_Field1)(nil), (*AllTypesOneOf_Field2)(nil), (*AllTypesOneOf_Field3)(nil), (*AllTypesOneOf_Field4)(nil), (*AllTypesOneOf_Field5)(nil), (*AllTypesOneOf_Field6)(nil), (*AllTypesOneOf_Field7)(nil), (*AllTypesOneOf_Field8)(nil), (*AllTypesOneOf_Field9)(nil), (*AllTypesOneOf_Field10)(nil), (*AllTypesOneOf_Field11)(nil), (*AllTypesOneOf_Field12)(nil), (*AllTypesOneOf_Field13)(nil), (*AllTypesOneOf_Field14)(nil), (*AllTypesOneOf_Field15)(nil), (*AllTypesOneOf_SubMessage)(nil), } } type TwoOneofs struct { // Types that are valid to be assigned to One: // *TwoOneofs_Field1 // *TwoOneofs_Field2 // *TwoOneofs_Field3 One isTwoOneofs_One `protobuf_oneof:"one"` // Types that are valid to be assigned to Two: // *TwoOneofs_Field34 // *TwoOneofs_Field35 // *TwoOneofs_SubMessage2 Two isTwoOneofs_Two `protobuf_oneof:"two"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *TwoOneofs) Reset() { *m = TwoOneofs{} } func (*TwoOneofs) ProtoMessage() {} func (*TwoOneofs) Descriptor() ([]byte, []int) { return fileDescriptor_9eef12518f7c4f58, []int{2} } func (m *TwoOneofs) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *TwoOneofs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_TwoOneofs.Marshal(b, m, deterministic) } func (m *TwoOneofs) XXX_Merge(src proto.Message) { xxx_messageInfo_TwoOneofs.Merge(m, src) } func (m *TwoOneofs) XXX_Size() int { return xxx_messageInfo_TwoOneofs.Size(m) } func (m *TwoOneofs) XXX_DiscardUnknown() { xxx_messageInfo_TwoOneofs.DiscardUnknown(m) } var xxx_messageInfo_TwoOneofs proto.InternalMessageInfo type isTwoOneofs_One interface { isTwoOneofs_One() Equal(interface{}) bool VerboseEqual(interface{}) error Size() int Compare(interface{}) int } type isTwoOneofs_Two interface { isTwoOneofs_Two() Equal(interface{}) bool VerboseEqual(interface{}) error Size() int Compare(interface{}) int } type TwoOneofs_Field1 struct { Field1 float64 `protobuf:"fixed64,1,opt,name=Field1,oneof" json:"Field1,omitempty"` } type TwoOneofs_Field2 struct { Field2 float32 `protobuf:"fixed32,2,opt,name=Field2,oneof" json:"Field2,omitempty"` } type TwoOneofs_Field3 struct { Field3 int32 `protobuf:"varint,3,opt,name=Field3,oneof" json:"Field3,omitempty"` } type TwoOneofs_Field34 struct { Field34 string `protobuf:"bytes,34,opt,name=Field34,oneof" json:"Field34,omitempty"` } type TwoOneofs_Field35 struct { Field35 []byte `protobuf:"bytes,35,opt,name=Field35,oneof" json:"Field35,omitempty"` } type TwoOneofs_SubMessage2 struct { SubMessage2 *Subby `protobuf:"bytes,36,opt,name=sub_message2,json=subMessage2,oneof" json:"sub_message2,omitempty"` } func (*TwoOneofs_Field1) isTwoOneofs_One() {} func (*TwoOneofs_Field2) isTwoOneofs_One() {} func (*TwoOneofs_Field3) isTwoOneofs_One() {} func (*TwoOneofs_Field34) isTwoOneofs_Two() {} func (*TwoOneofs_Field35) isTwoOneofs_Two() {} func (*TwoOneofs_SubMessage2) isTwoOneofs_Two() {} func (m *TwoOneofs) GetOne() isTwoOneofs_One { if m != nil { return m.One } return nil } func (m *TwoOneofs) GetTwo() isTwoOneofs_Two { if m != nil { return m.Two } return nil } func (m *TwoOneofs) GetField1() float64 { if x, ok := m.GetOne().(*TwoOneofs_Field1); ok { return x.Field1 } return 0 } func (m *TwoOneofs) GetField2() float32 { if x, ok := m.GetOne().(*TwoOneofs_Field2); ok { return x.Field2 } return 0 } func (m *TwoOneofs) GetField3() int32 { if x, ok := m.GetOne().(*TwoOneofs_Field3); ok { return x.Field3 } return 0 } func (m *TwoOneofs) GetField34() string { if x, ok := m.GetTwo().(*TwoOneofs_Field34); ok { return x.Field34 } return "" } func (m *TwoOneofs) GetField35() []byte { if x, ok := m.GetTwo().(*TwoOneofs_Field35); ok { return x.Field35 } return nil } func (m *TwoOneofs) GetSubMessage2() *Subby { if x, ok := m.GetTwo().(*TwoOneofs_SubMessage2); ok { return x.SubMessage2 } return nil } // XXX_OneofWrappers is for the internal use of the proto package. func (*TwoOneofs) XXX_OneofWrappers() []interface{} { return []interface{}{ (*TwoOneofs_Field1)(nil), (*TwoOneofs_Field2)(nil), (*TwoOneofs_Field3)(nil), (*TwoOneofs_Field34)(nil), (*TwoOneofs_Field35)(nil), (*TwoOneofs_SubMessage2)(nil), } } type CustomOneof struct { // Types that are valid to be assigned to Custom: // *CustomOneof_Stringy // *CustomOneof_CustomType // *CustomOneof_CastType // *CustomOneof_MyCustomName Custom isCustomOneof_Custom `protobuf_oneof:"custom"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *CustomOneof) Reset() { *m = CustomOneof{} } func (*CustomOneof) ProtoMessage() {} func (*CustomOneof) Descriptor() ([]byte, []int) { return fileDescriptor_9eef12518f7c4f58, []int{3} } func (m *CustomOneof) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *CustomOneof) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_CustomOneof.Marshal(b, m, deterministic) } func (m *CustomOneof) XXX_Merge(src proto.Message) { xxx_messageInfo_CustomOneof.Merge(m, src) } func (m *CustomOneof) XXX_Size() int { return xxx_messageInfo_CustomOneof.Size(m) } func (m *CustomOneof) XXX_DiscardUnknown() { xxx_messageInfo_CustomOneof.DiscardUnknown(m) } var xxx_messageInfo_CustomOneof proto.InternalMessageInfo type isCustomOneof_Custom interface { isCustomOneof_Custom() Equal(interface{}) bool VerboseEqual(interface{}) error Size() int Compare(interface{}) int } type CustomOneof_Stringy struct { Stringy string `protobuf:"bytes,34,opt,name=Stringy,oneof" json:"Stringy,omitempty"` } type CustomOneof_CustomType struct { CustomType github_com_gogo_protobuf_test_custom.Uint128 `protobuf:"bytes,35,opt,name=CustomType,oneof,customtype=github.com/ivansukach/protobuf/test/custom.Uint128" json:"CustomType,omitempty"` } type CustomOneof_CastType struct { CastType github_com_gogo_protobuf_test_casttype.MyUint64Type `protobuf:"varint,36,opt,name=CastType,oneof,casttype=github.com/ivansukach/protobuf/test/casttype.MyUint64Type" json:"CastType,omitempty"` } type CustomOneof_MyCustomName struct { MyCustomName int64 `protobuf:"varint,37,opt,name=CustomName,oneof" json:"CustomName,omitempty"` } func (*CustomOneof_Stringy) isCustomOneof_Custom() {} func (*CustomOneof_CustomType) isCustomOneof_Custom() {} func (*CustomOneof_CastType) isCustomOneof_Custom() {} func (*CustomOneof_MyCustomName) isCustomOneof_Custom() {} func (m *CustomOneof) GetCustom() isCustomOneof_Custom { if m != nil { return m.Custom } return nil } func (m *CustomOneof) GetStringy() string { if x, ok := m.GetCustom().(*CustomOneof_Stringy); ok { return x.Stringy } return "" } func (m *CustomOneof) GetCastType() github_com_gogo_protobuf_test_casttype.MyUint64Type { if x, ok := m.GetCustom().(*CustomOneof_CastType); ok { return x.CastType } return 0 } func (m *CustomOneof) GetMyCustomName() int64 { if x, ok := m.GetCustom().(*CustomOneof_MyCustomName); ok { return x.MyCustomName } return 0 } // XXX_OneofWrappers is for the internal use of the proto package. func (*CustomOneof) XXX_OneofWrappers() []interface{} { return []interface{}{ (*CustomOneof_Stringy)(nil), (*CustomOneof_CustomType)(nil), (*CustomOneof_CastType)(nil), (*CustomOneof_MyCustomName)(nil), } } func init() { proto.RegisterType((*Subby)(nil), "one.Subby") proto.RegisterType((*AllTypesOneOf)(nil), "one.AllTypesOneOf") proto.RegisterType((*TwoOneofs)(nil), "one.TwoOneofs") proto.RegisterType((*CustomOneof)(nil), "one.CustomOneof") } func init() { proto.RegisterFile("combos/unmarshaler/one.proto", fileDescriptor_9eef12518f7c4f58) } var fileDescriptor_9eef12518f7c4f58 = []byte{ // 606 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0xd3, 0xbf, 0x4f, 0x1b, 0x3f, 0x14, 0x00, 0x70, 0x3f, 0x42, 0x42, 0x70, 0xc2, 0x97, 0x7c, 0x6f, 0x72, 0x51, 0x65, 0xac, 0xb4, 0x95, 0x3c, 0x94, 0x84, 0x5c, 0x12, 0x7e, 0x8c, 0x3d, 0xa4, 0x2a, 0x0b, 0x45, 0x3a, 0x60, 0x46, 0x39, 0x6a, 0x42, 0xa4, 0xe4, 0x8c, 0xe2, 0x3b, 0xa1, 0x6c, 0xfc, 0x0d, 0xfd, 0x2b, 0x18, 0x3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c, 0x06, 0xf2, 0x17, 0x09, 0xc7, 0xc7, 0x38, 0x7f, 0x55, 0x9f, 0xf0, 0xbc, 0x13, 0x6f, 0xfb, 0xdb, 0x7c, 0xf3, 0xed, 0x1f, 0x6f, 0x90, 0xfe, 0x76, 0xcd, 0xf3, 0x6c, 0x4d, 0xe3, 0x74, 0x18, 0x46, 0x2d, 0x77, 0x4f, 0x7f, 0x60, 0x5b, 0xc5, 0x39, 0xc5, 0xe5, 0x83, 0xbe, 0x8a, 0xb2, 0x8a, 0xba, 0xf5, 0x65, 0x6f, 0xf7, 0xc7, 0x7c, 0xb3, 0xfd, 0x97, 0x8a, 0x7d, 0x15, 0x45, 0xd3, 0x2b, 0xd1, 0x38, 0x9c, 0xea, 0xaa, 0x3b, 0x1d, 0xbd, 0xbc, 0x87, 0x7c, 0x53, 0xca, 0x71, 0x17, 0xad, 0x7e, 0xe8, 0x8f, 0x05, 0x79, 0xa3, 0xaf, 0x8b, 0x57, 0x4b, 0xe7, 0x9b, 0xd5, 0xc3, 0xa9, 0xcd, 0xdb, 0x56, 0x74, 0xe4, 0x95, 0x71, 0x29, 0x6f, 0xd5, 0xeb, 0xdd, 0x25, 0x14, 0xcd, 0x12, 0x8a, 0xbe, 0x26, 0x14, 0xdd, 0x27, 0x14, 0x1e, 0x13, 0x0a, 0x4f, 0x09, 0x85, 0x9b, 0x94, 0xc2, 0x6d, 0x4a, 0xe1, 0x73, 0x4a, 0xe1, 0x4b, 0x4a, 0xe1, 0x2e, 0xa5, 0x68, 0x96, 0x52, 0xb8, 0x4f, 0x29, 0x7c, 0x4f, 0x29, 0x7a, 0x4c, 0x29, 0x3c, 0xa5, 0x14, 0xdd, 0x3c, 0x50, 0x74, 0xfb, 0x40, 0xe1, 0x67, 0x00, 0x00, 0x00, 0xff, 0xff, 0xf7, 0xcb, 0x68, 0xec, 0x80, 0x04, 0x00, 0x00, } func (this *Subby) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*Subby) if !ok { that2, ok := that.(Subby) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Sub != nil && that1.Sub != nil { if *this.Sub != *that1.Sub { if *this.Sub < *that1.Sub { return -1 } return 1 } } else if this.Sub != nil { return 1 } else if that1.Sub != nil { return -1 } if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { return c } return 0 } func (this *AllTypesOneOf) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf) if !ok { that2, ok := that.(AllTypesOneOf) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if that1.TestOneof == nil { if this.TestOneof != nil { return 1 } } else if this.TestOneof == nil { return -1 } else { thisType := -1 switch this.TestOneof.(type) { case *AllTypesOneOf_Field1: thisType = 0 case *AllTypesOneOf_Field2: thisType = 1 case *AllTypesOneOf_Field3: thisType = 2 case *AllTypesOneOf_Field4: thisType = 3 case *AllTypesOneOf_Field5: thisType = 4 case *AllTypesOneOf_Field6: thisType = 5 case *AllTypesOneOf_Field7: thisType = 6 case *AllTypesOneOf_Field8: thisType = 7 case *AllTypesOneOf_Field9: thisType = 8 case *AllTypesOneOf_Field10: thisType = 9 case *AllTypesOneOf_Field11: thisType = 10 case *AllTypesOneOf_Field12: thisType = 11 case *AllTypesOneOf_Field13: thisType = 12 case *AllTypesOneOf_Field14: thisType = 13 case *AllTypesOneOf_Field15: thisType = 14 case *AllTypesOneOf_SubMessage: thisType = 15 default: panic(fmt.Sprintf("compare: unexpected type %T in oneof", this.TestOneof)) } that1Type := -1 switch that1.TestOneof.(type) { case *AllTypesOneOf_Field1: that1Type = 0 case *AllTypesOneOf_Field2: that1Type = 1 case *AllTypesOneOf_Field3: that1Type = 2 case *AllTypesOneOf_Field4: that1Type = 3 case *AllTypesOneOf_Field5: that1Type = 4 case *AllTypesOneOf_Field6: that1Type = 5 case *AllTypesOneOf_Field7: that1Type = 6 case *AllTypesOneOf_Field8: that1Type = 7 case *AllTypesOneOf_Field9: that1Type = 8 case *AllTypesOneOf_Field10: that1Type = 9 case *AllTypesOneOf_Field11: that1Type = 10 case *AllTypesOneOf_Field12: that1Type = 11 case *AllTypesOneOf_Field13: that1Type = 12 case *AllTypesOneOf_Field14: that1Type = 13 case *AllTypesOneOf_Field15: that1Type = 14 case *AllTypesOneOf_SubMessage: that1Type = 15 default: panic(fmt.Sprintf("compare: unexpected type %T in oneof", that1.TestOneof)) } if thisType == that1Type { if c := this.TestOneof.Compare(that1.TestOneof); c != 0 { return c } } else if thisType < that1Type { return -1 } else if thisType > that1Type { return 1 } } if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { return c } return 0 } func (this *AllTypesOneOf_Field1) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field1) if !ok { that2, ok := that.(AllTypesOneOf_Field1) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field1 != that1.Field1 { if this.Field1 < that1.Field1 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field2) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field2) if !ok { that2, ok := that.(AllTypesOneOf_Field2) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field2 != that1.Field2 { if this.Field2 < that1.Field2 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field3) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field3) if !ok { that2, ok := that.(AllTypesOneOf_Field3) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field3 != that1.Field3 { if this.Field3 < that1.Field3 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field4) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field4) if !ok { that2, ok := that.(AllTypesOneOf_Field4) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field4 != that1.Field4 { if this.Field4 < that1.Field4 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field5) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field5) if !ok { that2, ok := that.(AllTypesOneOf_Field5) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field5 != that1.Field5 { if this.Field5 < that1.Field5 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field6) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field6) if !ok { that2, ok := that.(AllTypesOneOf_Field6) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field6 != that1.Field6 { if this.Field6 < that1.Field6 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field7) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field7) if !ok { that2, ok := that.(AllTypesOneOf_Field7) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field7 != that1.Field7 { if this.Field7 < that1.Field7 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field8) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field8) if !ok { that2, ok := that.(AllTypesOneOf_Field8) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field8 != that1.Field8 { if this.Field8 < that1.Field8 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field9) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field9) if !ok { that2, ok := that.(AllTypesOneOf_Field9) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field9 != that1.Field9 { if this.Field9 < that1.Field9 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field10) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field10) if !ok { that2, ok := that.(AllTypesOneOf_Field10) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field10 != that1.Field10 { if this.Field10 < that1.Field10 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field11) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field11) if !ok { that2, ok := that.(AllTypesOneOf_Field11) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field11 != that1.Field11 { if this.Field11 < that1.Field11 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field12) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field12) if !ok { that2, ok := that.(AllTypesOneOf_Field12) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field12 != that1.Field12 { if this.Field12 < that1.Field12 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field13) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field13) if !ok { that2, ok := that.(AllTypesOneOf_Field13) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field13 != that1.Field13 { if !this.Field13 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field14) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field14) if !ok { that2, ok := that.(AllTypesOneOf_Field14) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field14 != that1.Field14 { if this.Field14 < that1.Field14 { return -1 } return 1 } return 0 } func (this *AllTypesOneOf_Field15) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_Field15) if !ok { that2, ok := that.(AllTypesOneOf_Field15) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if c := bytes.Compare(this.Field15, that1.Field15); c != 0 { return c } return 0 } func (this *AllTypesOneOf_SubMessage) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*AllTypesOneOf_SubMessage) if !ok { that2, ok := that.(AllTypesOneOf_SubMessage) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if c := this.SubMessage.Compare(that1.SubMessage); c != 0 { return c } return 0 } func (this *TwoOneofs) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*TwoOneofs) if !ok { that2, ok := that.(TwoOneofs) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if that1.One == nil { if this.One != nil { return 1 } } else if this.One == nil { return -1 } else { thisType := -1 switch this.One.(type) { case *TwoOneofs_Field1: thisType = 0 case *TwoOneofs_Field2: thisType = 1 case *TwoOneofs_Field3: thisType = 2 default: panic(fmt.Sprintf("compare: unexpected type %T in oneof", this.One)) } that1Type := -1 switch that1.One.(type) { case *TwoOneofs_Field1: that1Type = 0 case *TwoOneofs_Field2: that1Type = 1 case *TwoOneofs_Field3: that1Type = 2 default: panic(fmt.Sprintf("compare: unexpected type %T in oneof", that1.One)) } if thisType == that1Type { if c := this.One.Compare(that1.One); c != 0 { return c } } else if thisType < that1Type { return -1 } else if thisType > that1Type { return 1 } } if that1.Two == nil { if this.Two != nil { return 1 } } else if this.Two == nil { return -1 } else { thisType := -1 switch this.Two.(type) { case *TwoOneofs_Field34: thisType = 3 case *TwoOneofs_Field35: thisType = 4 case *TwoOneofs_SubMessage2: thisType = 5 default: panic(fmt.Sprintf("compare: unexpected type %T in oneof", this.Two)) } that1Type := -1 switch that1.Two.(type) { case *TwoOneofs_Field34: that1Type = 3 case *TwoOneofs_Field35: that1Type = 4 case *TwoOneofs_SubMessage2: that1Type = 5 default: panic(fmt.Sprintf("compare: unexpected type %T in oneof", that1.Two)) } if thisType == that1Type { if c := this.Two.Compare(that1.Two); c != 0 { return c } } else if thisType < that1Type { return -1 } else if thisType > that1Type { return 1 } } if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { return c } return 0 } func (this *TwoOneofs_Field1) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*TwoOneofs_Field1) if !ok { that2, ok := that.(TwoOneofs_Field1) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field1 != that1.Field1 { if this.Field1 < that1.Field1 { return -1 } return 1 } return 0 } func (this *TwoOneofs_Field2) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*TwoOneofs_Field2) if !ok { that2, ok := that.(TwoOneofs_Field2) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field2 != that1.Field2 { if this.Field2 < that1.Field2 { return -1 } return 1 } return 0 } func (this *TwoOneofs_Field3) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*TwoOneofs_Field3) if !ok { that2, ok := that.(TwoOneofs_Field3) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field3 != that1.Field3 { if this.Field3 < that1.Field3 { return -1 } return 1 } return 0 } func (this *TwoOneofs_Field34) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*TwoOneofs_Field34) if !ok { that2, ok := that.(TwoOneofs_Field34) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Field34 != that1.Field34 { if this.Field34 < that1.Field34 { return -1 } return 1 } return 0 } func (this *TwoOneofs_Field35) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*TwoOneofs_Field35) if !ok { that2, ok := that.(TwoOneofs_Field35) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if c := bytes.Compare(this.Field35, that1.Field35); c != 0 { return c } return 0 } func (this *TwoOneofs_SubMessage2) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*TwoOneofs_SubMessage2) if !ok { that2, ok := that.(TwoOneofs_SubMessage2) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if c := this.SubMessage2.Compare(that1.SubMessage2); c != 0 { return c } return 0 } func (this *CustomOneof) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*CustomOneof) if !ok { that2, ok := that.(CustomOneof) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if that1.Custom == nil { if this.Custom != nil { return 1 } } else if this.Custom == nil { return -1 } else { thisType := -1 switch this.Custom.(type) { case *CustomOneof_Stringy: thisType = 0 case *CustomOneof_CustomType: thisType = 1 case *CustomOneof_CastType: thisType = 2 case *CustomOneof_MyCustomName: thisType = 3 default: panic(fmt.Sprintf("compare: unexpected type %T in oneof", this.Custom)) } that1Type := -1 switch that1.Custom.(type) { case *CustomOneof_Stringy: that1Type = 0 case *CustomOneof_CustomType: that1Type = 1 case *CustomOneof_CastType: that1Type = 2 case *CustomOneof_MyCustomName: that1Type = 3 default: panic(fmt.Sprintf("compare: unexpected type %T in oneof", that1.Custom)) } if thisType == that1Type { if c := this.Custom.Compare(that1.Custom); c != 0 { return c } } else if thisType < that1Type { return -1 } else if thisType > that1Type { return 1 } } if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { return c } return 0 } func (this *CustomOneof_Stringy) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*CustomOneof_Stringy) if !ok { that2, ok := that.(CustomOneof_Stringy) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.Stringy != that1.Stringy { if this.Stringy < that1.Stringy { return -1 } return 1 } return 0 } func (this *CustomOneof_CustomType) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*CustomOneof_CustomType) if !ok { that2, ok := that.(CustomOneof_CustomType) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if c := this.CustomType.Compare(that1.CustomType); c != 0 { return c } return 0 } func (this *CustomOneof_CastType) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*CustomOneof_CastType) if !ok { that2, ok := that.(CustomOneof_CastType) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.CastType != that1.CastType { if this.CastType < that1.CastType { return -1 } return 1 } return 0 } func (this *CustomOneof_MyCustomName) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*CustomOneof_MyCustomName) if !ok { that2, ok := that.(CustomOneof_MyCustomName) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if this.MyCustomName != that1.MyCustomName { if this.MyCustomName < that1.MyCustomName { return -1 } return 1 } return 0 } func (this *Subby) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func (this *AllTypesOneOf) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func (this *TwoOneofs) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func (this *CustomOneof) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func OneDescription() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { d := &github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet{} var gzipped = []byte{ // 4318 bytes of a gzipped FileDescriptorSet 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x5b, 0x6b, 0x70, 0x1b, 0xd7, 0x75, 0xe6, 0xe2, 0x41, 0x02, 0x07, 0x20, 0xb8, 0x5c, 0xd2, 0x12, 0x44, 0xdb, 0x90, 0x04, 0xdb, 0x31, 0xfd, 0x22, 0x6d, 0x8a, 0xa4, 0x24, 0xa8, 0x89, 0x0b, 0x82, 0x10, 0x45, 0x97, 0x24, 0x98, 0x05, 0x19, 0x3f, 0x32, 0x9d, 0x9d, 0xe5, 0xe2, 0x12, 0x5c, 0x69, 0xb1, 0xbb, 0xd9, 0x5d, 0x48, 0x86, 0xa6, 0x3f, 0xd4, 0x71, 0x1f, 0x93, 0xe9, 0x3b, 0xed, 0x4c, 0x13, 0xd7, 0x71, 0x9b, 0x74, 0x5a, 0xbb, 0xe9, 0x2b, 0xe9, 0x23, 0x4d, 0xd2, 0x3f, 0xfd, 0x93, 0xd6, 0xbf, 0x3a, 0xce, 0xbf, 0x4e, 0xa7, 0xe3, 0xb1, 0x68, 0xcf, 0x34, 0x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xd7, 0x13, 0x2b, 0xe7, 0xff, 0xf7, 0xad, 0xd3, 0xe7, 0x22, 0x18, 0xd9, 0x36, 0x3d, 0xb7, 0xd9, 0xc1, 0xac, 0xcb, 0x8b, 0x18, 0x7e, 0x65, 0x44, 0xf6, 0xa9, 0xa4, 0x05, 0xee, 0xea, 0x96, 0xda, 0xa2, 0xbf, 0x36, 0x8b, 0xaf, 0x88, 0x87, 0x6f, 0x9d, 0xce, 0x6e, 0x76, 0x02, 0x79, 0xe0, 0x0a, 0x7e, 0x5a, 0x49, 0xc1, 0x28, 0x75, 0x75, 0xe5, 0xca, 0x1b, 0xb7, 0x0b, 0x23, 0x6f, 0xde, 0x2e, 0x8c, 0xfc, 0xc3, 0xed, 0xc2, 0xc8, 0xdb, 0xb7, 0x0b, 0xc2, 0xfb, 0xb7, 0x0b, 0xc2, 0x07, 0xb7, 0x0b, 0xc2, 0xad, 0xc3, 0x82, 0xf0, 0xfa, 0x61, 0x41, 0xf8, 0xfa, 0x61, 0x41, 0xf8, 0xd6, 0x61, 0x41, 0x78, 0xe3, 0xb0, 0x30, 0xf2, 0xe6, 0x61, 0x41, 0x78, 0xfb, 0xb0, 0x20, 0x7c, 0xff, 0xb0, 0x30, 0xf2, 0xfe, 0x61, 0x41, 0xf8, 0xe0, 0xb0, 0x30, 0x72, 0xeb, 0x9d, 0xc2, 0xc8, 0xeb, 0xef, 0x14, 0x84, 0xff, 0x0b, 0x00, 0x00, 0xff, 0xff, 0x28, 0x4b, 0xba, 0xa0, 0xbc, 0x37, 0x00, 0x00, } r := bytes.NewReader(gzipped) gzipr, err := compress_gzip.NewReader(r) if err != nil { panic(err) } ungzipped, err := io_ioutil.ReadAll(gzipr) if err != nil { panic(err) } if err := github_com_gogo_protobuf_proto.Unmarshal(ungzipped, d); err != nil { panic(err) } return d } func (this *Subby) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*Subby) if !ok { that2, ok := that.(Subby) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *Subby") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *Subby but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *Subby but is not nil && this == nil") } if this.Sub != nil && that1.Sub != nil { if *this.Sub != *that1.Sub { return fmt.Errorf("Sub this(%v) Not Equal that(%v)", *this.Sub, *that1.Sub) } } else if this.Sub != nil { return fmt.Errorf("this.Sub == nil && that.Sub != nil") } else if that1.Sub != nil { return fmt.Errorf("Sub this(%v) Not Equal that(%v)", this.Sub, that1.Sub) } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized) } return nil } func (this *Subby) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*Subby) if !ok { that2, ok := that.(Subby) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Sub != nil && that1.Sub != nil { if *this.Sub != *that1.Sub { return false } } else if this.Sub != nil { return false } else if that1.Sub != nil { return false } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return false } return true } func (this *AllTypesOneOf) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf) if !ok { that2, ok := that.(AllTypesOneOf) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf but is not nil && this == nil") } if that1.TestOneof == nil { if this.TestOneof != nil { return fmt.Errorf("this.TestOneof != nil && that1.TestOneof == nil") } } else if this.TestOneof == nil { return fmt.Errorf("this.TestOneof == nil && that1.TestOneof != nil") } else if err := this.TestOneof.VerboseEqual(that1.TestOneof); err != nil { return err } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized) } return nil } func (this *AllTypesOneOf_Field1) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field1) if !ok { that2, ok := that.(AllTypesOneOf_Field1) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field1") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field1 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field1 but is not nil && this == nil") } if this.Field1 != that1.Field1 { return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", this.Field1, that1.Field1) } return nil } func (this *AllTypesOneOf_Field2) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field2) if !ok { that2, ok := that.(AllTypesOneOf_Field2) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field2") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field2 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field2 but is not nil && this == nil") } if this.Field2 != that1.Field2 { return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", this.Field2, that1.Field2) } return nil } func (this *AllTypesOneOf_Field3) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field3) if !ok { that2, ok := that.(AllTypesOneOf_Field3) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field3") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field3 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field3 but is not nil && this == nil") } if this.Field3 != that1.Field3 { return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", this.Field3, that1.Field3) } return nil } func (this *AllTypesOneOf_Field4) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field4) if !ok { that2, ok := that.(AllTypesOneOf_Field4) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field4") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field4 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field4 but is not nil && this == nil") } if this.Field4 != that1.Field4 { return fmt.Errorf("Field4 this(%v) Not Equal that(%v)", this.Field4, that1.Field4) } return nil } func (this *AllTypesOneOf_Field5) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field5) if !ok { that2, ok := that.(AllTypesOneOf_Field5) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field5") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field5 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field5 but is not nil && this == nil") } if this.Field5 != that1.Field5 { return fmt.Errorf("Field5 this(%v) Not Equal that(%v)", this.Field5, that1.Field5) } return nil } func (this *AllTypesOneOf_Field6) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field6) if !ok { that2, ok := that.(AllTypesOneOf_Field6) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field6") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field6 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field6 but is not nil && this == nil") } if this.Field6 != that1.Field6 { return fmt.Errorf("Field6 this(%v) Not Equal that(%v)", this.Field6, that1.Field6) } return nil } func (this *AllTypesOneOf_Field7) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field7) if !ok { that2, ok := that.(AllTypesOneOf_Field7) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field7") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field7 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field7 but is not nil && this == nil") } if this.Field7 != that1.Field7 { return fmt.Errorf("Field7 this(%v) Not Equal that(%v)", this.Field7, that1.Field7) } return nil } func (this *AllTypesOneOf_Field8) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field8) if !ok { that2, ok := that.(AllTypesOneOf_Field8) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field8") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field8 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field8 but is not nil && this == nil") } if this.Field8 != that1.Field8 { return fmt.Errorf("Field8 this(%v) Not Equal that(%v)", this.Field8, that1.Field8) } return nil } func (this *AllTypesOneOf_Field9) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field9) if !ok { that2, ok := that.(AllTypesOneOf_Field9) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field9") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field9 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field9 but is not nil && this == nil") } if this.Field9 != that1.Field9 { return fmt.Errorf("Field9 this(%v) Not Equal that(%v)", this.Field9, that1.Field9) } return nil } func (this *AllTypesOneOf_Field10) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field10) if !ok { that2, ok := that.(AllTypesOneOf_Field10) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field10") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field10 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field10 but is not nil && this == nil") } if this.Field10 != that1.Field10 { return fmt.Errorf("Field10 this(%v) Not Equal that(%v)", this.Field10, that1.Field10) } return nil } func (this *AllTypesOneOf_Field11) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field11) if !ok { that2, ok := that.(AllTypesOneOf_Field11) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field11") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field11 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field11 but is not nil && this == nil") } if this.Field11 != that1.Field11 { return fmt.Errorf("Field11 this(%v) Not Equal that(%v)", this.Field11, that1.Field11) } return nil } func (this *AllTypesOneOf_Field12) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field12) if !ok { that2, ok := that.(AllTypesOneOf_Field12) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field12") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field12 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field12 but is not nil && this == nil") } if this.Field12 != that1.Field12 { return fmt.Errorf("Field12 this(%v) Not Equal that(%v)", this.Field12, that1.Field12) } return nil } func (this *AllTypesOneOf_Field13) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field13) if !ok { that2, ok := that.(AllTypesOneOf_Field13) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field13") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field13 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field13 but is not nil && this == nil") } if this.Field13 != that1.Field13 { return fmt.Errorf("Field13 this(%v) Not Equal that(%v)", this.Field13, that1.Field13) } return nil } func (this *AllTypesOneOf_Field14) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field14) if !ok { that2, ok := that.(AllTypesOneOf_Field14) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field14") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field14 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field14 but is not nil && this == nil") } if this.Field14 != that1.Field14 { return fmt.Errorf("Field14 this(%v) Not Equal that(%v)", this.Field14, that1.Field14) } return nil } func (this *AllTypesOneOf_Field15) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field15) if !ok { that2, ok := that.(AllTypesOneOf_Field15) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field15") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field15 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field15 but is not nil && this == nil") } if !bytes.Equal(this.Field15, that1.Field15) { return fmt.Errorf("Field15 this(%v) Not Equal that(%v)", this.Field15, that1.Field15) } return nil } func (this *AllTypesOneOf_SubMessage) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_SubMessage) if !ok { that2, ok := that.(AllTypesOneOf_SubMessage) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_SubMessage") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_SubMessage but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_SubMessage but is not nil && this == nil") } if !this.SubMessage.Equal(that1.SubMessage) { return fmt.Errorf("SubMessage this(%v) Not Equal that(%v)", this.SubMessage, that1.SubMessage) } return nil } func (this *AllTypesOneOf) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf) if !ok { that2, ok := that.(AllTypesOneOf) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if that1.TestOneof == nil { if this.TestOneof != nil { return false } } else if this.TestOneof == nil { return false } else if !this.TestOneof.Equal(that1.TestOneof) { return false } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return false } return true } func (this *AllTypesOneOf_Field1) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field1) if !ok { that2, ok := that.(AllTypesOneOf_Field1) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field1 != that1.Field1 { return false } return true } func (this *AllTypesOneOf_Field2) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field2) if !ok { that2, ok := that.(AllTypesOneOf_Field2) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field2 != that1.Field2 { return false } return true } func (this *AllTypesOneOf_Field3) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field3) if !ok { that2, ok := that.(AllTypesOneOf_Field3) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field3 != that1.Field3 { return false } return true } func (this *AllTypesOneOf_Field4) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field4) if !ok { that2, ok := that.(AllTypesOneOf_Field4) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field4 != that1.Field4 { return false } return true } func (this *AllTypesOneOf_Field5) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field5) if !ok { that2, ok := that.(AllTypesOneOf_Field5) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field5 != that1.Field5 { return false } return true } func (this *AllTypesOneOf_Field6) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field6) if !ok { that2, ok := that.(AllTypesOneOf_Field6) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field6 != that1.Field6 { return false } return true } func (this *AllTypesOneOf_Field7) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field7) if !ok { that2, ok := that.(AllTypesOneOf_Field7) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field7 != that1.Field7 { return false } return true } func (this *AllTypesOneOf_Field8) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field8) if !ok { that2, ok := that.(AllTypesOneOf_Field8) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field8 != that1.Field8 { return false } return true } func (this *AllTypesOneOf_Field9) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field9) if !ok { that2, ok := that.(AllTypesOneOf_Field9) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field9 != that1.Field9 { return false } return true } func (this *AllTypesOneOf_Field10) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field10) if !ok { that2, ok := that.(AllTypesOneOf_Field10) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field10 != that1.Field10 { return false } return true } func (this *AllTypesOneOf_Field11) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field11) if !ok { that2, ok := that.(AllTypesOneOf_Field11) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field11 != that1.Field11 { return false } return true } func (this *AllTypesOneOf_Field12) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field12) if !ok { that2, ok := that.(AllTypesOneOf_Field12) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field12 != that1.Field12 { return false } return true } func (this *AllTypesOneOf_Field13) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field13) if !ok { that2, ok := that.(AllTypesOneOf_Field13) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field13 != that1.Field13 { return false } return true } func (this *AllTypesOneOf_Field14) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field14) if !ok { that2, ok := that.(AllTypesOneOf_Field14) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field14 != that1.Field14 { return false } return true } func (this *AllTypesOneOf_Field15) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_Field15) if !ok { that2, ok := that.(AllTypesOneOf_Field15) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if !bytes.Equal(this.Field15, that1.Field15) { return false } return true } func (this *AllTypesOneOf_SubMessage) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*AllTypesOneOf_SubMessage) if !ok { that2, ok := that.(AllTypesOneOf_SubMessage) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if !this.SubMessage.Equal(that1.SubMessage) { return false } return true } func (this *TwoOneofs) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs) if !ok { that2, ok := that.(TwoOneofs) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs but is not nil && this == nil") } if that1.One == nil { if this.One != nil { return fmt.Errorf("this.One != nil && that1.One == nil") } } else if this.One == nil { return fmt.Errorf("this.One == nil && that1.One != nil") } else if err := this.One.VerboseEqual(that1.One); err != nil { return err } if that1.Two == nil { if this.Two != nil { return fmt.Errorf("this.Two != nil && that1.Two == nil") } } else if this.Two == nil { return fmt.Errorf("this.Two == nil && that1.Two != nil") } else if err := this.Two.VerboseEqual(that1.Two); err != nil { return err } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized) } return nil } func (this *TwoOneofs_Field1) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_Field1) if !ok { that2, ok := that.(TwoOneofs_Field1) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_Field1") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_Field1 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_Field1 but is not nil && this == nil") } if this.Field1 != that1.Field1 { return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", this.Field1, that1.Field1) } return nil } func (this *TwoOneofs_Field2) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_Field2) if !ok { that2, ok := that.(TwoOneofs_Field2) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_Field2") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_Field2 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_Field2 but is not nil && this == nil") } if this.Field2 != that1.Field2 { return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", this.Field2, that1.Field2) } return nil } func (this *TwoOneofs_Field3) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_Field3) if !ok { that2, ok := that.(TwoOneofs_Field3) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_Field3") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_Field3 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_Field3 but is not nil && this == nil") } if this.Field3 != that1.Field3 { return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", this.Field3, that1.Field3) } return nil } func (this *TwoOneofs_Field34) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_Field34) if !ok { that2, ok := that.(TwoOneofs_Field34) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_Field34") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_Field34 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_Field34 but is not nil && this == nil") } if this.Field34 != that1.Field34 { return fmt.Errorf("Field34 this(%v) Not Equal that(%v)", this.Field34, that1.Field34) } return nil } func (this *TwoOneofs_Field35) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_Field35) if !ok { that2, ok := that.(TwoOneofs_Field35) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_Field35") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_Field35 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_Field35 but is not nil && this == nil") } if !bytes.Equal(this.Field35, that1.Field35) { return fmt.Errorf("Field35 this(%v) Not Equal that(%v)", this.Field35, that1.Field35) } return nil } func (this *TwoOneofs_SubMessage2) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_SubMessage2) if !ok { that2, ok := that.(TwoOneofs_SubMessage2) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_SubMessage2") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_SubMessage2 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_SubMessage2 but is not nil && this == nil") } if !this.SubMessage2.Equal(that1.SubMessage2) { return fmt.Errorf("SubMessage2 this(%v) Not Equal that(%v)", this.SubMessage2, that1.SubMessage2) } return nil } func (this *TwoOneofs) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*TwoOneofs) if !ok { that2, ok := that.(TwoOneofs) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if that1.One == nil { if this.One != nil { return false } } else if this.One == nil { return false } else if !this.One.Equal(that1.One) { return false } if that1.Two == nil { if this.Two != nil { return false } } else if this.Two == nil { return false } else if !this.Two.Equal(that1.Two) { return false } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return false } return true } func (this *TwoOneofs_Field1) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*TwoOneofs_Field1) if !ok { that2, ok := that.(TwoOneofs_Field1) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field1 != that1.Field1 { return false } return true } func (this *TwoOneofs_Field2) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*TwoOneofs_Field2) if !ok { that2, ok := that.(TwoOneofs_Field2) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field2 != that1.Field2 { return false } return true } func (this *TwoOneofs_Field3) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*TwoOneofs_Field3) if !ok { that2, ok := that.(TwoOneofs_Field3) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field3 != that1.Field3 { return false } return true } func (this *TwoOneofs_Field34) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*TwoOneofs_Field34) if !ok { that2, ok := that.(TwoOneofs_Field34) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Field34 != that1.Field34 { return false } return true } func (this *TwoOneofs_Field35) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*TwoOneofs_Field35) if !ok { that2, ok := that.(TwoOneofs_Field35) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if !bytes.Equal(this.Field35, that1.Field35) { return false } return true } func (this *TwoOneofs_SubMessage2) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*TwoOneofs_SubMessage2) if !ok { that2, ok := that.(TwoOneofs_SubMessage2) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if !this.SubMessage2.Equal(that1.SubMessage2) { return false } return true } func (this *CustomOneof) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*CustomOneof) if !ok { that2, ok := that.(CustomOneof) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *CustomOneof") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *CustomOneof but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *CustomOneof but is not nil && this == nil") } if that1.Custom == nil { if this.Custom != nil { return fmt.Errorf("this.Custom != nil && that1.Custom == nil") } } else if this.Custom == nil { return fmt.Errorf("this.Custom == nil && that1.Custom != nil") } else if err := this.Custom.VerboseEqual(that1.Custom); err != nil { return err } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized) } return nil } func (this *CustomOneof_Stringy) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*CustomOneof_Stringy) if !ok { that2, ok := that.(CustomOneof_Stringy) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *CustomOneof_Stringy") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *CustomOneof_Stringy but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *CustomOneof_Stringy but is not nil && this == nil") } if this.Stringy != that1.Stringy { return fmt.Errorf("Stringy this(%v) Not Equal that(%v)", this.Stringy, that1.Stringy) } return nil } func (this *CustomOneof_CustomType) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*CustomOneof_CustomType) if !ok { that2, ok := that.(CustomOneof_CustomType) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *CustomOneof_CustomType") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *CustomOneof_CustomType but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *CustomOneof_CustomType but is not nil && this == nil") } if !this.CustomType.Equal(that1.CustomType) { return fmt.Errorf("CustomType this(%v) Not Equal that(%v)", this.CustomType, that1.CustomType) } return nil } func (this *CustomOneof_CastType) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*CustomOneof_CastType) if !ok { that2, ok := that.(CustomOneof_CastType) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *CustomOneof_CastType") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *CustomOneof_CastType but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *CustomOneof_CastType but is not nil && this == nil") } if this.CastType != that1.CastType { return fmt.Errorf("CastType this(%v) Not Equal that(%v)", this.CastType, that1.CastType) } return nil } func (this *CustomOneof_MyCustomName) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*CustomOneof_MyCustomName) if !ok { that2, ok := that.(CustomOneof_MyCustomName) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *CustomOneof_MyCustomName") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *CustomOneof_MyCustomName but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *CustomOneof_MyCustomName but is not nil && this == nil") } if this.MyCustomName != that1.MyCustomName { return fmt.Errorf("MyCustomName this(%v) Not Equal that(%v)", this.MyCustomName, that1.MyCustomName) } return nil } func (this *CustomOneof) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*CustomOneof) if !ok { that2, ok := that.(CustomOneof) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if that1.Custom == nil { if this.Custom != nil { return false } } else if this.Custom == nil { return false } else if !this.Custom.Equal(that1.Custom) { return false } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return false } return true } func (this *CustomOneof_Stringy) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*CustomOneof_Stringy) if !ok { that2, ok := that.(CustomOneof_Stringy) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.Stringy != that1.Stringy { return false } return true } func (this *CustomOneof_CustomType) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*CustomOneof_CustomType) if !ok { that2, ok := that.(CustomOneof_CustomType) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if !this.CustomType.Equal(that1.CustomType) { return false } return true } func (this *CustomOneof_CastType) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*CustomOneof_CastType) if !ok { that2, ok := that.(CustomOneof_CastType) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.CastType != that1.CastType { return false } return true } func (this *CustomOneof_MyCustomName) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*CustomOneof_MyCustomName) if !ok { that2, ok := that.(CustomOneof_MyCustomName) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.MyCustomName != that1.MyCustomName { return false } return true } func (this *Subby) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 5) s = append(s, "&one.Subby{") if this.Sub != nil { s = append(s, "Sub: "+valueToGoStringOne(this.Sub, "string")+",\n") } if this.XXX_unrecognized != nil { s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") } s = append(s, "}") return strings.Join(s, "") } func (this *AllTypesOneOf) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 20) s = append(s, "&one.AllTypesOneOf{") if this.TestOneof != nil { s = append(s, "TestOneof: "+fmt.Sprintf("%#v", this.TestOneof)+",\n") } if this.XXX_unrecognized != nil { s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") } s = append(s, "}") return strings.Join(s, "") } func (this *AllTypesOneOf_Field1) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field1{` + `Field1:` + fmt.Sprintf("%#v", this.Field1) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field2) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field2{` + `Field2:` + fmt.Sprintf("%#v", this.Field2) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field3) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field3{` + `Field3:` + fmt.Sprintf("%#v", this.Field3) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field4) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field4{` + `Field4:` + fmt.Sprintf("%#v", this.Field4) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field5) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field5{` + `Field5:` + fmt.Sprintf("%#v", this.Field5) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field6) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field6{` + `Field6:` + fmt.Sprintf("%#v", this.Field6) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field7) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field7{` + `Field7:` + fmt.Sprintf("%#v", this.Field7) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field8) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field8{` + `Field8:` + fmt.Sprintf("%#v", this.Field8) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field9) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field9{` + `Field9:` + fmt.Sprintf("%#v", this.Field9) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field10) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field10{` + `Field10:` + fmt.Sprintf("%#v", this.Field10) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field11) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field11{` + `Field11:` + fmt.Sprintf("%#v", this.Field11) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field12) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field12{` + `Field12:` + fmt.Sprintf("%#v", this.Field12) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field13) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field13{` + `Field13:` + fmt.Sprintf("%#v", this.Field13) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field14) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field14{` + `Field14:` + fmt.Sprintf("%#v", this.Field14) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field15) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field15{` + `Field15:` + fmt.Sprintf("%#v", this.Field15) + `}`}, ", ") return s } func (this *AllTypesOneOf_SubMessage) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_SubMessage{` + `SubMessage:` + fmt.Sprintf("%#v", this.SubMessage) + `}`}, ", ") return s } func (this *TwoOneofs) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 10) s = append(s, "&one.TwoOneofs{") if this.One != nil { s = append(s, "One: "+fmt.Sprintf("%#v", this.One)+",\n") } if this.Two != nil { s = append(s, "Two: "+fmt.Sprintf("%#v", this.Two)+",\n") } if this.XXX_unrecognized != nil { s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") } s = append(s, "}") return strings.Join(s, "") } func (this *TwoOneofs_Field1) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_Field1{` + `Field1:` + fmt.Sprintf("%#v", this.Field1) + `}`}, ", ") return s } func (this *TwoOneofs_Field2) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_Field2{` + `Field2:` + fmt.Sprintf("%#v", this.Field2) + `}`}, ", ") return s } func (this *TwoOneofs_Field3) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_Field3{` + `Field3:` + fmt.Sprintf("%#v", this.Field3) + `}`}, ", ") return s } func (this *TwoOneofs_Field34) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_Field34{` + `Field34:` + fmt.Sprintf("%#v", this.Field34) + `}`}, ", ") return s } func (this *TwoOneofs_Field35) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_Field35{` + `Field35:` + fmt.Sprintf("%#v", this.Field35) + `}`}, ", ") return s } func (this *TwoOneofs_SubMessage2) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_SubMessage2{` + `SubMessage2:` + fmt.Sprintf("%#v", this.SubMessage2) + `}`}, ", ") return s } func (this *CustomOneof) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 8) s = append(s, "&one.CustomOneof{") if this.Custom != nil { s = append(s, "Custom: "+fmt.Sprintf("%#v", this.Custom)+",\n") } if this.XXX_unrecognized != nil { s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") } s = append(s, "}") return strings.Join(s, "") } func (this *CustomOneof_Stringy) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.CustomOneof_Stringy{` + `Stringy:` + fmt.Sprintf("%#v", this.Stringy) + `}`}, ", ") return s } func (this *CustomOneof_CustomType) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.CustomOneof_CustomType{` + `CustomType:` + fmt.Sprintf("%#v", this.CustomType) + `}`}, ", ") return s } func (this *CustomOneof_CastType) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.CustomOneof_CastType{` + `CastType:` + fmt.Sprintf("%#v", this.CastType) + `}`}, ", ") return s } func (this *CustomOneof_MyCustomName) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.CustomOneof_MyCustomName{` + `MyCustomName:` + fmt.Sprintf("%#v", this.MyCustomName) + `}`}, ", ") return s } func valueToGoStringOne(v interface{}, typ string) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) } func NewPopulatedSubby(r randyOne, easy bool) *Subby { this := &Subby{} if r.Intn(5) != 0 { v1 := string(randStringOne(r)) this.Sub = &v1 } if !easy && r.Intn(10) != 0 { this.XXX_unrecognized = randUnrecognizedOne(r, 2) } return this } func NewPopulatedAllTypesOneOf(r randyOne, easy bool) *AllTypesOneOf { this := &AllTypesOneOf{} oneofNumber_TestOneof := []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}[r.Intn(16)] switch oneofNumber_TestOneof { case 1: this.TestOneof = NewPopulatedAllTypesOneOf_Field1(r, easy) case 2: this.TestOneof = NewPopulatedAllTypesOneOf_Field2(r, easy) case 3: this.TestOneof = NewPopulatedAllTypesOneOf_Field3(r, easy) case 4: this.TestOneof = NewPopulatedAllTypesOneOf_Field4(r, easy) case 5: this.TestOneof = NewPopulatedAllTypesOneOf_Field5(r, easy) case 6: this.TestOneof = NewPopulatedAllTypesOneOf_Field6(r, easy) case 7: this.TestOneof = NewPopulatedAllTypesOneOf_Field7(r, easy) case 8: this.TestOneof = NewPopulatedAllTypesOneOf_Field8(r, easy) case 9: this.TestOneof = NewPopulatedAllTypesOneOf_Field9(r, easy) case 10: this.TestOneof = NewPopulatedAllTypesOneOf_Field10(r, easy) case 11: this.TestOneof = NewPopulatedAllTypesOneOf_Field11(r, easy) case 12: this.TestOneof = NewPopulatedAllTypesOneOf_Field12(r, easy) case 13: this.TestOneof = NewPopulatedAllTypesOneOf_Field13(r, easy) case 14: this.TestOneof = NewPopulatedAllTypesOneOf_Field14(r, easy) case 15: this.TestOneof = NewPopulatedAllTypesOneOf_Field15(r, easy) case 16: this.TestOneof = NewPopulatedAllTypesOneOf_SubMessage(r, easy) } if !easy && r.Intn(10) != 0 { this.XXX_unrecognized = randUnrecognizedOne(r, 17) } return this } func NewPopulatedAllTypesOneOf_Field1(r randyOne, easy bool) *AllTypesOneOf_Field1 { this := &AllTypesOneOf_Field1{} this.Field1 = float64(r.Float64()) if r.Intn(2) == 0 { this.Field1 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field2(r randyOne, easy bool) *AllTypesOneOf_Field2 { this := &AllTypesOneOf_Field2{} this.Field2 = float32(r.Float32()) if r.Intn(2) == 0 { this.Field2 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field3(r randyOne, easy bool) *AllTypesOneOf_Field3 { this := &AllTypesOneOf_Field3{} this.Field3 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field3 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field4(r randyOne, easy bool) *AllTypesOneOf_Field4 { this := &AllTypesOneOf_Field4{} this.Field4 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field4 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field5(r randyOne, easy bool) *AllTypesOneOf_Field5 { this := &AllTypesOneOf_Field5{} this.Field5 = uint32(r.Uint32()) return this } func NewPopulatedAllTypesOneOf_Field6(r randyOne, easy bool) *AllTypesOneOf_Field6 { this := &AllTypesOneOf_Field6{} this.Field6 = uint64(uint64(r.Uint32())) return this } func NewPopulatedAllTypesOneOf_Field7(r randyOne, easy bool) *AllTypesOneOf_Field7 { this := &AllTypesOneOf_Field7{} this.Field7 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field7 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field8(r randyOne, easy bool) *AllTypesOneOf_Field8 { this := &AllTypesOneOf_Field8{} this.Field8 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field8 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field9(r randyOne, easy bool) *AllTypesOneOf_Field9 { this := &AllTypesOneOf_Field9{} this.Field9 = uint32(r.Uint32()) return this } func NewPopulatedAllTypesOneOf_Field10(r randyOne, easy bool) *AllTypesOneOf_Field10 { this := &AllTypesOneOf_Field10{} this.Field10 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field10 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field11(r randyOne, easy bool) *AllTypesOneOf_Field11 { this := &AllTypesOneOf_Field11{} this.Field11 = uint64(uint64(r.Uint32())) return this } func NewPopulatedAllTypesOneOf_Field12(r randyOne, easy bool) *AllTypesOneOf_Field12 { this := &AllTypesOneOf_Field12{} this.Field12 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field12 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field13(r randyOne, easy bool) *AllTypesOneOf_Field13 { this := &AllTypesOneOf_Field13{} this.Field13 = bool(bool(r.Intn(2) == 0)) return this } func NewPopulatedAllTypesOneOf_Field14(r randyOne, easy bool) *AllTypesOneOf_Field14 { this := &AllTypesOneOf_Field14{} this.Field14 = string(randStringOne(r)) return this } func NewPopulatedAllTypesOneOf_Field15(r randyOne, easy bool) *AllTypesOneOf_Field15 { this := &AllTypesOneOf_Field15{} v2 := r.Intn(100) this.Field15 = make([]byte, v2) for i := 0; i < v2; i++ { this.Field15[i] = byte(r.Intn(256)) } return this } func NewPopulatedAllTypesOneOf_SubMessage(r randyOne, easy bool) *AllTypesOneOf_SubMessage { this := &AllTypesOneOf_SubMessage{} this.SubMessage = NewPopulatedSubby(r, easy) return this } func NewPopulatedTwoOneofs(r randyOne, easy bool) *TwoOneofs { this := &TwoOneofs{} oneofNumber_One := []int32{1, 2, 3}[r.Intn(3)] switch oneofNumber_One { case 1: this.One = NewPopulatedTwoOneofs_Field1(r, easy) case 2: this.One = NewPopulatedTwoOneofs_Field2(r, easy) case 3: this.One = NewPopulatedTwoOneofs_Field3(r, easy) } oneofNumber_Two := []int32{34, 35, 36}[r.Intn(3)] switch oneofNumber_Two { case 34: this.Two = NewPopulatedTwoOneofs_Field34(r, easy) case 35: this.Two = NewPopulatedTwoOneofs_Field35(r, easy) case 36: this.Two = NewPopulatedTwoOneofs_SubMessage2(r, easy) } if !easy && r.Intn(10) != 0 { this.XXX_unrecognized = randUnrecognizedOne(r, 37) } return this } func NewPopulatedTwoOneofs_Field1(r randyOne, easy bool) *TwoOneofs_Field1 { this := &TwoOneofs_Field1{} this.Field1 = float64(r.Float64()) if r.Intn(2) == 0 { this.Field1 *= -1 } return this } func NewPopulatedTwoOneofs_Field2(r randyOne, easy bool) *TwoOneofs_Field2 { this := &TwoOneofs_Field2{} this.Field2 = float32(r.Float32()) if r.Intn(2) == 0 { this.Field2 *= -1 } return this } func NewPopulatedTwoOneofs_Field3(r randyOne, easy bool) *TwoOneofs_Field3 { this := &TwoOneofs_Field3{} this.Field3 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field3 *= -1 } return this } func NewPopulatedTwoOneofs_Field34(r randyOne, easy bool) *TwoOneofs_Field34 { this := &TwoOneofs_Field34{} this.Field34 = string(randStringOne(r)) return this } func NewPopulatedTwoOneofs_Field35(r randyOne, easy bool) *TwoOneofs_Field35 { this := &TwoOneofs_Field35{} v3 := r.Intn(100) this.Field35 = make([]byte, v3) for i := 0; i < v3; i++ { this.Field35[i] = byte(r.Intn(256)) } return this } func NewPopulatedTwoOneofs_SubMessage2(r randyOne, easy bool) *TwoOneofs_SubMessage2 { this := &TwoOneofs_SubMessage2{} this.SubMessage2 = NewPopulatedSubby(r, easy) return this } func NewPopulatedCustomOneof(r randyOne, easy bool) *CustomOneof { this := &CustomOneof{} oneofNumber_Custom := []int32{34, 35, 36, 37}[r.Intn(4)] switch oneofNumber_Custom { case 34: this.Custom = NewPopulatedCustomOneof_Stringy(r, easy) case 35: this.Custom = NewPopulatedCustomOneof_CustomType(r, easy) case 36: this.Custom = NewPopulatedCustomOneof_CastType(r, easy) case 37: this.Custom = NewPopulatedCustomOneof_MyCustomName(r, easy) } if !easy && r.Intn(10) != 0 { this.XXX_unrecognized = randUnrecognizedOne(r, 38) } return this } func NewPopulatedCustomOneof_Stringy(r randyOne, easy bool) *CustomOneof_Stringy { this := &CustomOneof_Stringy{} this.Stringy = string(randStringOne(r)) return this } func NewPopulatedCustomOneof_CustomType(r randyOne, easy bool) *CustomOneof_CustomType { this := &CustomOneof_CustomType{} v4 := github_com_gogo_protobuf_test_custom.NewPopulatedUint128(r) this.CustomType = *v4 return this } func NewPopulatedCustomOneof_CastType(r randyOne, easy bool) *CustomOneof_CastType { this := &CustomOneof_CastType{} this.CastType = github_com_gogo_protobuf_test_casttype.MyUint64Type(uint64(r.Uint32())) return this } func NewPopulatedCustomOneof_MyCustomName(r randyOne, easy bool) *CustomOneof_MyCustomName { this := &CustomOneof_MyCustomName{} this.MyCustomName = int64(r.Int63()) if r.Intn(2) == 0 { this.MyCustomName *= -1 } return this } type randyOne interface { Float32() float32 Float64() float64 Int63() int64 Int31() int32 Uint32() uint32 Intn(n int) int } func randUTF8RuneOne(r randyOne) rune { ru := r.Intn(62) if ru < 10 { return rune(ru + 48) } else if ru < 36 { return rune(ru + 55) } return rune(ru + 61) } func randStringOne(r randyOne) string { v5 := r.Intn(100) tmps := make([]rune, v5) for i := 0; i < v5; i++ { tmps[i] = randUTF8RuneOne(r) } return string(tmps) } func randUnrecognizedOne(r randyOne, maxFieldNumber int) (dAtA []byte) { l := r.Intn(5) for i := 0; i < l; i++ { wire := r.Intn(4) if wire == 3 { wire = 5 } fieldNumber := maxFieldNumber + r.Intn(100) dAtA = randFieldOne(dAtA, r, fieldNumber, wire) } return dAtA } func randFieldOne(dAtA []byte, r randyOne, fieldNumber int, wire int) []byte { key := uint32(fieldNumber)<<3 | uint32(wire) switch wire { case 0: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) v6 := r.Int63() if r.Intn(2) == 0 { v6 *= -1 } dAtA = encodeVarintPopulateOne(dAtA, uint64(v6)) case 1: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) case 2: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) ll := r.Intn(100) dAtA = encodeVarintPopulateOne(dAtA, uint64(ll)) for j := 0; j < ll; j++ { dAtA = append(dAtA, byte(r.Intn(256))) } default: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) } return dAtA } func encodeVarintPopulateOne(dAtA []byte, v uint64) []byte { for v >= 1<<7 { dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80)) v >>= 7 } dAtA = append(dAtA, uint8(v)) return dAtA } func (m *Subby) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Sub != nil { l = len(*m.Sub) n += 1 + l + sovOne(uint64(l)) } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n } func (m *AllTypesOneOf) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.TestOneof != nil { n += m.TestOneof.Size() } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n } func (m *AllTypesOneOf_Field1) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 9 return n } func (m *AllTypesOneOf_Field2) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 5 return n } func (m *AllTypesOneOf_Field3) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 1 + sovOne(uint64(m.Field3)) return n } func (m *AllTypesOneOf_Field4) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 1 + sovOne(uint64(m.Field4)) return n } func (m *AllTypesOneOf_Field5) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 1 + sovOne(uint64(m.Field5)) return n } func (m *AllTypesOneOf_Field6) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 1 + sovOne(uint64(m.Field6)) return n } func (m *AllTypesOneOf_Field7) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 1 + sozOne(uint64(m.Field7)) return n } func (m *AllTypesOneOf_Field8) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 1 + sozOne(uint64(m.Field8)) return n } func (m *AllTypesOneOf_Field9) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 5 return n } func (m *AllTypesOneOf_Field10) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 5 return n } func (m *AllTypesOneOf_Field11) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 9 return n } func (m *AllTypesOneOf_Field12) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 9 return n } func (m *AllTypesOneOf_Field13) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 2 return n } func (m *AllTypesOneOf_Field14) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Field14) n += 1 + l + sovOne(uint64(l)) return n } func (m *AllTypesOneOf_Field15) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Field15 != nil { l = len(m.Field15) n += 1 + l + sovOne(uint64(l)) } return n } func (m *AllTypesOneOf_SubMessage) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.SubMessage != nil { l = m.SubMessage.Size() n += 2 + l + sovOne(uint64(l)) } return n } func (m *TwoOneofs) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.One != nil { n += m.One.Size() } if m.Two != nil { n += m.Two.Size() } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n } func (m *TwoOneofs_Field1) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 9 return n } func (m *TwoOneofs_Field2) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 5 return n } func (m *TwoOneofs_Field3) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 1 + sovOne(uint64(m.Field3)) return n } func (m *TwoOneofs_Field34) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Field34) n += 2 + l + sovOne(uint64(l)) return n } func (m *TwoOneofs_Field35) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Field35 != nil { l = len(m.Field35) n += 2 + l + sovOne(uint64(l)) } return n } func (m *TwoOneofs_SubMessage2) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.SubMessage2 != nil { l = m.SubMessage2.Size() n += 2 + l + sovOne(uint64(l)) } return n } func (m *CustomOneof) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Custom != nil { n += m.Custom.Size() } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n } func (m *CustomOneof_Stringy) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Stringy) n += 2 + l + sovOne(uint64(l)) return n } func (m *CustomOneof_CustomType) Size() (n int) { if m == nil { return 0 } var l int _ = l l = m.CustomType.Size() n += 2 + l + sovOne(uint64(l)) return n } func (m *CustomOneof_CastType) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 2 + sovOne(uint64(m.CastType)) return n } func (m *CustomOneof_MyCustomName) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 2 + sovOne(uint64(m.MyCustomName)) return n } func sovOne(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozOne(x uint64) (n int) { return sovOne(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (this *Subby) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&Subby{`, `Sub:` + valueToStringOne(this.Sub) + `,`, `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf{`, `TestOneof:` + fmt.Sprintf("%v", this.TestOneof) + `,`, `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field1) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field1{`, `Field1:` + fmt.Sprintf("%v", this.Field1) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field2) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field2{`, `Field2:` + fmt.Sprintf("%v", this.Field2) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field3) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field3{`, `Field3:` + fmt.Sprintf("%v", this.Field3) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field4) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field4{`, `Field4:` + fmt.Sprintf("%v", this.Field4) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field5) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field5{`, `Field5:` + fmt.Sprintf("%v", this.Field5) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field6) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field6{`, `Field6:` + fmt.Sprintf("%v", this.Field6) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field7) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field7{`, `Field7:` + fmt.Sprintf("%v", this.Field7) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field8) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field8{`, `Field8:` + fmt.Sprintf("%v", this.Field8) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field9) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field9{`, `Field9:` + fmt.Sprintf("%v", this.Field9) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field10) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field10{`, `Field10:` + fmt.Sprintf("%v", this.Field10) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field11) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field11{`, `Field11:` + fmt.Sprintf("%v", this.Field11) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field12) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field12{`, `Field12:` + fmt.Sprintf("%v", this.Field12) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field13) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field13{`, `Field13:` + fmt.Sprintf("%v", this.Field13) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field14) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field14{`, `Field14:` + fmt.Sprintf("%v", this.Field14) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field15) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field15{`, `Field15:` + fmt.Sprintf("%v", this.Field15) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_SubMessage) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_SubMessage{`, `SubMessage:` + strings.Replace(fmt.Sprintf("%v", this.SubMessage), "Subby", "Subby", 1) + `,`, `}`, }, "") return s } func (this *TwoOneofs) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TwoOneofs{`, `One:` + fmt.Sprintf("%v", this.One) + `,`, `Two:` + fmt.Sprintf("%v", this.Two) + `,`, `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s } func (this *TwoOneofs_Field1) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TwoOneofs_Field1{`, `Field1:` + fmt.Sprintf("%v", this.Field1) + `,`, `}`, }, "") return s } func (this *TwoOneofs_Field2) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TwoOneofs_Field2{`, `Field2:` + fmt.Sprintf("%v", this.Field2) + `,`, `}`, }, "") return s } func (this *TwoOneofs_Field3) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TwoOneofs_Field3{`, `Field3:` + fmt.Sprintf("%v", this.Field3) + `,`, `}`, }, "") return s } func (this *TwoOneofs_Field34) String() string { if this ==
| 4,715
|
https://github.com/NicholasAnthony/YARB/blob/master/src/components/Example.js
|
Github Open Source
|
Open Source
|
MIT
| null |
YARB
|
NicholasAnthony
|
JavaScript
|
Code
| 52
| 163
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
class Example extends Component {
toUpper(text) {
return text.toUpperCase();
}
render() {
const {examplePropText} = this.props;
return (
<div className="example">
<span className="example-text">{this.toUpper(examplePropText)}</span>
</div>
);
}
}
Example.propTypes = {
examplePropText: PropTypes.string.isRequired
};
Example.defaultProps = {
examplePropText: 'example prop text'
};
export default Example;
| 18,500
|
https://github.com/cocosip/AutoS3/blob/master/samples/AutoS3.Sample/SampleAppService.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
AutoS3
|
cocosip
|
C#
|
Code
| 876
| 3,799
|
using Amazon.S3;
using Amazon.S3.Model;
using AmazonKS3;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace AutoS3.Sample
{
public class SampleAppService
{
private readonly ILogger _logger;
private readonly SampleAppOptions _options;
private readonly IS3ClientFactory _s3ClientFactory;
public SampleAppService(ILogger<SampleAppService> logger, IOptions<SampleAppOptions> options, IS3ClientFactory s3ClientFactory)
{
_logger = logger;
_options = options.Value;
_s3ClientFactory = s3ClientFactory;
}
protected IAmazonS3 GetClient()
{
return _s3ClientFactory.GetOrAdd("default", () =>
{
var configuration = new S3ClientConfiguration()
{
Vendor = _options.S3Vendor,
AccessKeyId = _options.AccessKeyId,
SecretAccessKey = _options.SecretAccessKey,
MaxClient = 10
};
if (_options.S3Vendor == S3VendorType.Amazon)
{
configuration.Config = new AmazonS3Config()
{
ServiceURL = _options.ServerUrl,
ForcePathStyle = _options.ForcePathStyle,
SignatureVersion = _options.SignatureVersion
};
}
else
{
configuration.Config = new AmazonKS3Config()
{
ServiceURL = _options.ServerUrl,
ForcePathStyle = _options.ForcePathStyle,
SignatureVersion = _options.SignatureVersion
};
}
return configuration;
});
}
/// <summary>列出Bucket
/// </summary>
public async Task ListBucketsAsync()
{
var listBucketsResponse = await GetClient().ListBucketsAsync();
_logger.LogInformation("---列出Buckets---,OwnerId:{0}", listBucketsResponse.Owner.Id);
foreach (var bucket in listBucketsResponse.Buckets)
{
_logger.LogInformation("BucketName:{0},创建时间:{1}", bucket.BucketName, bucket.CreationDate.ToString("yyyy-MM-dd HH:mm"));
}
}
/// <summary>获取Bucket权限
/// </summary>
public async Task GetAclAsync()
{
_logger.LogInformation("---获取当前Bucket的权限---");
var getACLResponse = await GetClient().GetACLAsync(new GetACLRequest()
{
BucketName = _options.DefaultBucket
});
foreach (var grant in getACLResponse.AccessControlList.Grants)
{
_logger.LogInformation("当前Bucket权限:{0}", grant.Permission.Value);
}
}
/// <summary>列出对象
/// </summary>
public async Task ListObjectsV2Async(string prefix = "", string delimiter = "", int count = 10)
{
//查询文件
_logger.LogInformation("---列出Bucket,'Prefix:{0}','Delimiter:{1}','Count:{2}'---", prefix, delimiter, count);
var listObjectsV2Response = await GetClient().ListObjectsV2Async(new ListObjectsV2Request()
{
BucketName = _options.DefaultBucket,
Prefix = prefix,
Delimiter = delimiter,
MaxKeys = count
});
foreach (var s3Object in listObjectsV2Response.S3Objects)
{
_logger.LogInformation("S3对象Key:{0}", s3Object.Key);
}
}
/// <summary>列出对象
/// </summary>
public async Task ListObjectsAsync(string prefix = "", string delimiter = "", int count = 10)
{
//查询文件
_logger.LogInformation("---列出Bucket前10个文件---");
var listObjectsResponse = await GetClient().ListObjectsAsync(new ListObjectsRequest()
{
BucketName = _options.DefaultBucket,
//Prefix = prefix,
//Delimiter = delimiter,
MaxKeys = count
});
foreach (var s3Object in listObjectsResponse.S3Objects)
{
_logger.LogInformation("S3对象Key:{0}", s3Object.Key);
}
}
/// <summary>获取指定的文件
/// </summary>
private async Task GetObjectAsync(string key)
{
//查询文件
_logger.LogInformation("---获取指定的文件---");
var getObjectResponse = await GetClient().GetObjectAsync(new GetObjectRequest()
{
BucketName = _options.DefaultBucket,
Key = key,
});
_logger.LogInformation("获取对象返回:对象Key:{0},ETag:{1}", getObjectResponse?.Key, getObjectResponse?.ETag);
}
/// <summary>简单上传文件
/// </summary>
public async Task<string> SimpleUploadAsync()
{
var ext = ".txt";
if (_options.UseLocalFile)
{
ext = _options.SimpleUploadFilePath.Substring(_options.SimpleUploadFilePath.LastIndexOf('.'));
}
var key = $"test/{Guid.NewGuid()}{ext}";
_logger.LogInformation("---上传简单文件,上传Key:{0}---", key);
var putObjectRequest = new PutObjectRequest()
{
BucketName = _options.DefaultBucket,
AutoCloseStream = true,
Key = key,
UseChunkEncoding = _options.UseChunkEncoding,
};
//使用本地测试文件
if (_options.UseLocalFile)
{
putObjectRequest.FilePath = _options.SimpleUploadFilePath;
}
else
{
var ms = new MemoryStream(Encoding.UTF8.GetBytes("Hello AutoS3!"));
ms.Seek(0, SeekOrigin.Begin);
//自动生成流
putObjectRequest.InputStream = ms;
}
//进度条
putObjectRequest.StreamTransferProgress += (sender, args) =>
{
_logger.LogInformation("ProgressCallback - Progress: {0}%, TotalBytes:{1}, TransferredBytes:{2} ",
args.TransferredBytes * 100 / args.TotalBytes, args.TotalBytes, args.TransferredBytes);
};
var putObjectResponse = await GetClient().PutObjectAsync(putObjectRequest);
_logger.LogInformation("简单上传成功,Etag:{0}", putObjectResponse.ETag);
return key;
}
/// <summary>简单下载文件
/// </summary>
public async Task SimpleGetObjectAsync(string key)
{
_logger.LogInformation("---简单下载文件,Key:{0}---", key);
var getObjectRequest = new GetObjectRequest()
{
BucketName = _options.DefaultBucket,
Key = key
};
var getObjectResponse = await GetClient().GetObjectAsync(getObjectRequest);
_logger.LogInformation("简单下载文件成功,Key:{0}", getObjectResponse.Key);
}
/// <summary>获取预授权地址
/// </summary>
public string GetPreSignedURL(string key)
{
//获取文件下载地址
_logger.LogInformation("---获取预授权地址---");
var url = GetClient().GetPreSignedURL(new GetPreSignedUrlRequest()
{
BucketName = _options.DefaultBucket,
Key = key,
Expires = DateTime.Now.AddMinutes(5),
});
_logger.LogInformation("获取预授权地址:{0}", url);
return url;
}
/// <summary>生成预授权地址
/// </summary>
public string GeneratePreSignedURL(string key)
{
_logger.LogInformation("---生成预授权地址---");
var url = GetClient().GeneratePreSignedURL(_options.DefaultBucket, key, DateTime.Now.AddMinutes(10), null);
_logger.LogInformation("生成预授权地址:{0}", url);
return url;
}
/// <summary>拷贝文件
/// </summary>
public async Task<string> CopyObjectAsync(string key)
{
var ext = ".txt";
if (!string.IsNullOrWhiteSpace(key))
{
ext = key.Substring(key.LastIndexOf('.'));
}
var destinationKey = $"copyfiles/{Guid.NewGuid()}{ext}";
_logger.LogInformation("---拷贝文件,目标:{0}---", destinationKey);
var copyObjectRequest = new CopyObjectRequest()
{
SourceBucket = _options.DefaultBucket,
DestinationBucket = _options.DefaultBucket,
SourceKey = key,
DestinationKey = destinationKey,
};
var copyObjectResponse = await GetClient().CopyObjectAsync(copyObjectRequest);
_logger.LogInformation("拷贝文件成功,RequestId:{0},拷贝目标Key:{1}", copyObjectResponse.ResponseMetadata.RequestId, destinationKey);
return destinationKey;
}
/// <summary>删除文件
/// </summary>
public async Task DeleteObject(string key)
{
_logger.LogInformation("---删除文件---,Key:{0}", key);
var deleteObjectResponse = await GetClient().DeleteObjectAsync(new DeleteObjectRequest()
{
BucketName = _options.DefaultBucket,
Key = key
});
_logger.LogInformation("删除文件成功,DeleteMarker:{0}", deleteObjectResponse.DeleteMarker);
}
/// <summary>分片上传
/// </summary>
public async Task<string> MultipartUploadAsync()
{
var key = $"test/{Guid.NewGuid()}.dcm";
_logger.LogInformation("---分片上传文件,上传Key:{0}---", key);
//初始化分片上传
var initiateMultipartUploadResponse = await GetClient().InitiateMultipartUploadAsync(new InitiateMultipartUploadRequest()
{
BucketName = _options.DefaultBucket,
Key = key,
});
//上传Id
var uploadId = initiateMultipartUploadResponse.UploadId;
// 计算分片总数。
var partSize = 5 * 1024 * 1024;
var fi = new FileInfo(_options.MultipartUploadFilePath);
var fileSize = fi.Length;
var partCount = fileSize / partSize;
if (fileSize % partSize != 0)
{
partCount++;
}
// 开始分片上传。partETags是保存partETag的列表,OSS收到用户提交的分片列表后,会逐一验证每个分片数据的有效性。 当所有的数据分片通过验证后,OSS会将这些分片组合成一个完整的文件。
var partETags = new List<PartETag>();
var uploadPartTasks = new List<Task>();
using (var fs = File.Open(_options.MultipartUploadFilePath, FileMode.Open))
{
for (var i = 0; i < partCount; i++)
{
var skipBytes = (long)partSize * i;
// 定位到本次上传起始位置。
//fs.Seek(skipBytes, 0);
// 计算本次上传的片大小,最后一片为剩余的数据大小。
var size = (int)((partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes));
byte[] buffer = new byte[size];
fs.Read(buffer, 0, size);
uploadPartTasks.Add(Task.Run<UploadPartResponse>(() =>
{
return GetClient().UploadPartAsync(new UploadPartRequest()
{
BucketName = _options.DefaultBucket,
UploadId = uploadId,
Key = key,
InputStream = new MemoryStream(buffer),
PartSize = size,
PartNumber = i + 1
});
}).ContinueWith(t =>
{
partETags.Add(new PartETag(t.Result.PartNumber, t.Result.ETag));
_logger.LogInformation("finish {0}/{1}", partETags.Count, partCount);
}));
//分片上传
//var uploadPartResponse = await Client.UploadPartAsync(new UploadPartRequest()
//{
// BucketName = BucketName,
// UploadId = uploadId,
// Key = key,
// InputStream = new MemoryStream(buffer),
// PartSize = size,
// PartNumber = i + 1
//});
//partETags.Add(new PartETag(uploadPartResponse.PartNumber, uploadPartResponse.ETag));
//Console.WriteLine("finish {0}/{1}", partETags.Count, partCount);
}
//Console.WriteLine("分片上传完成");
}
Task.WaitAll(uploadPartTasks.ToArray());
_logger.LogInformation("共:{0}个PartETags", partETags.Count);
//列出所有分片
_logger.LogInformation("---列出所有分片,UploadId:{0}---", uploadId);
var listPartsResponse = await GetClient().ListPartsAsync(new ListPartsRequest()
{
BucketName = _options.DefaultBucket,
Key = key,
UploadId = uploadId
});
foreach (var part in listPartsResponse.Parts)
{
_logger.LogInformation("分片序号:{0},分片ETag:{1}", part.PartNumber, part.ETag);
}
var completeMultipartUploadResponse = await GetClient().CompleteMultipartUploadAsync(new CompleteMultipartUploadRequest()
{
BucketName = _options.DefaultBucket,
Key = key,
UploadId = uploadId,
PartETags = partETags
});
_logger.LogInformation("分片上传完成,Key:{0}", completeMultipartUploadResponse.Key);
return completeMultipartUploadResponse.Key;
}
}
}
| 22,625
|
https://github.com/breathe/ship-hold/blob/master/src/doc/service-worker.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
ship-hold
|
breathe
|
JavaScript
|
Code
| 99
| 309
|
const CACHE = 'ship-hold-documentation';
// On install, cache some resources.
self.addEventListener('install', function (evt) {
console.log('The service worker is being installed.');
evt.waitUntil(precache());
});
self.addEventListener('fetch', async function (evt) {
console.log('The service worker is serving the asset.');
let response = (await fromCache(evt.request));
if (!response) {
response = await fetch(evt.request);
}
evt.respondWith(response);
});
async function precache() {
const cache = await caches.open(CACHE);
return cache.addAll([
'./resources/app.js',
'./resources/darkula.css',
'./resources/ship-hold-logo.svg',
'./resources/theme.css'
]);
}
async function fromCache(request) {
const cache = await caches.open(CACHE);
return await cache.match(request);
}
async function eventuallyUpdate(request) {
const cache = await caches.open(CACHE);
const response = await fetch(request);
await cache.put(request, response);
return response;
}
| 18,264
|
https://github.com/rallias/pam-faithful/blob/master/src/pam-faithful.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
pam-faithful
|
rallias
|
C++
|
Code
| 103
| 943
|
#include <napi.h>
#include <security/pam_appl.h>
Napi::Value PamStart(const Napi::CallbackInfo &info)
{
return info.Env().Undefined();
}
Napi::Object init(Napi::Env env, Napi::Object exports)
{
exports.Set(Napi::String::New(env, "pam_start"), Napi::Function::New(env, PamStart));
exports.Set(Napi::String::New(env, "PAM_PROMPT_ECHO_OFF"), Napi::Number::New(env, PAM_PROMPT_ECHO_OFF));
exports.Set(Napi::String::New(env, "PAM_PROMPT_ECHO_ON"), Napi::Number::New(env, PAM_PROMPT_ECHO_ON));
exports.Set(Napi::String::New(env, "PAM_ERROR_MSG"), Napi::Number::New(env, PAM_ERROR_MSG));
exports.Set(Napi::String::New(env, "PAM_TEXT_INFO"), Napi::Number::New(env, PAM_TEXT_INFO));
exports.Set(Napi::String::New(env, "PAM_SILENT"), Napi::Number::New(env, PAM_SILENT));
exports.Set(Napi::String::New(env, "PAM_DISALLOW_NULL_AUTHTOK"), Napi::Number::New(env, PAM_DISALLOW_NULL_AUTHTOK));
exports.Set(Napi::String::New(env, "PAM_SUCCESS"), Napi::Number::New(env, PAM_SUCCESS));
exports.Set(Napi::String::New(env, "PAM_ABORT"), Napi::Number::New(env, PAM_ABORT));
exports.Set(Napi::String::New(env, "PAM_AUTHINFO_UNAVAIL"), Napi::Number::New(env, PAM_AUTHINFO_UNAVAIL));
exports.Set(Napi::String::New(env, "PAM_AUTH_ERR"), Napi::Number::New(env, PAM_AUTH_ERR));
exports.Set(Napi::String::New(env, "PAM_BAD_ITEM"), Napi::Number::New(env, PAM_BAD_ITEM));
exports.Set(Napi::String::New(env, "PAM_BUF_ERR"), Napi::Number::New(env, PAM_BUF_ERR));
exports.Set(Napi::String::New(env, "PAM_CONV_ERR"), Napi::Number::New(env, PAM_CONV_ERR));
exports.Set(Napi::String::New(env, "PAM_CRED_INSUFFICIENT"), Napi::Number::New(env, PAM_CRED_INSUFFICIENT));
exports.Set(Napi::String::New(env, "PAM_MAXTRIES"), Napi::Number::New(env, PAM_MAXTRIES));
exports.Set(Napi::String::New(env, "PAM_PERM_DENIED"), Napi::Number::New(env, PAM_PERM_DENIED));
exports.Set(Napi::String::New(env, "PAM_SERVICE_ERR"), Napi::Number::New(env, PAM_SERVICE_ERR));
exports.Set(Napi::String::New(env, "PAM_SYSTEM_ERR"), Napi::Number::New(env, PAM_SYSTEM_ERR));
exports.Set(Napi::String::New(env, "PAM_USER_UNKNOWN"), Napi::Number::New(env, PAM_USER_UNKNOWN));
return exports;
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, init);
| 35,034
|
https://github.com/seewpx/actor-framework/blob/master/libcaf_core/caf/ref_counted.hpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
actor-framework
|
seewpx
|
C++
|
Code
| 117
| 305
|
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include <atomic>
#include <cstddef>
#include "caf/detail/atomic_ref_counted.hpp"
#include "caf/detail/core_export.hpp"
namespace caf {
/// Base class for reference counted objects with an atomic reference count.
/// Serves the requirements of {@link intrusive_ptr}.
/// @note *All* instances of `ref_counted` start with a reference count of 1.
/// @relates intrusive_ptr
class CAF_CORE_EXPORT ref_counted : public detail::atomic_ref_counted {
public:
using super = detail::atomic_ref_counted;
using super::super;
~ref_counted() override;
friend void intrusive_ptr_add_ref(const ref_counted* p) noexcept {
p->ref();
}
friend void intrusive_ptr_release(const ref_counted* p) noexcept {
p->deref();
}
};
} // namespace caf
| 47,458
|
https://github.com/PatricioIribarneCatella/helicopter/blob/master/src/shaders/simple/vertex.glsl
|
Github Open Source
|
Open Source
|
MIT
| null |
helicopter
|
PatricioIribarneCatella
|
GLSL
|
Code
| 25
| 77
|
// VERTEX SHADER
attribute vec3 aVertexPosition;
attribute vec3 aVertexColor;
varying highp vec4 vColor;
void main(void) {
gl_Position = vec4(aVertexPosition, 1.0);
vColor = vec4(aVertexColor, 1.0);
}
| 13,619
|
https://github.com/greearb/vocal-ct/blob/master/rtsp/rtspstack/CharDataParser.hxx
|
Github Open Source
|
Open Source
|
VSL-1.0, BSD-2-Clause
| 2,023
|
vocal-ct
|
greearb
|
C++
|
Code
| 665
| 1,401
|
#ifndef CharDataParser_Hxx
#define CharDataParser_Hxx
/* ====================================================================
* The Vovida Software License, Version 1.0
*
* Copyright (c) 2000 Vovida Networks, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The names "VOCAL", "Vovida Open Communication Application Library",
* and "Vovida Open Communication Application Library (VOCAL)" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact vocal@vovida.org.
*
* 4. Products derived from this software may not be called "VOCAL", nor
* may "VOCAL" appear in their name, without prior written
* permission of Vovida Networks, Inc.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
* NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA
* NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
* IN EXCESS OF 281421,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* ====================================================================
*
* This software consists of voluntary contributions made by Vovida
* Networks, Inc. and many individuals on behalf of Vovida Networks,
* Inc. For more information on Vovida Networks, Inc., please see
* <http://www.vovida.org/>.
*
*/
static const char* const CharDataParser_hxx_Version =
"$Id: CharDataParser.hxx,v 1.1 2004/05/01 04:15:23 greear Exp $";
#include "CharData.hxx"
/** */
class CharDataParser
{
public:
/** */
CharDataParser(CharData *dataBuf)
: myCurPtr(dataBuf == NULL ? NULL : dataBuf->getPtr()),
myEndPtr(dataBuf == NULL ? NULL :
dataBuf->getPtr() + dataBuf->getLen())
{}
/** */
~CharDataParser() {}
/* All following methods will return 1 if it finds the stopchar or
the char meets the mask, and put the chars before stop condition
in outbuf; return 0 if it cannot find the stop chars
*/
/** Get all chars, and stop before the stopChar */
int parseUntil(CharData* outBuf, char stopChar);
/** Get all chars and stop before the char that mask[char]=1 */
int parseUntil(CharData* outBuf, u_int8_t* stopMask);
/** Get all chars and stop after the stopChar */
int parseThru(CharData* outBuf, char stopChar);
/** Get all chars if mask[char]=1, and stop otherwise */
int parseThru(CharData* outBuf, u_int8_t* stopMask);
/** Get all the chars before \r or \n or \r\n, inclusive */
int getNextLine(CharData* outBuf);
/** Get all the chars before a non-letter */
int getNextWord(CharData* outBuf)
{ return parseUntil(outBuf, myMaskNonWord); }
/** Get the interger value of the digit chars, only support unsigned */
int getNextInteger(u_int32_t& num);
/** Get the double value of the digit and '.' chars */
int getNextDouble(double& doubleNum);
/** Get all the chars before a non space char */
int getThruSpaces(CharData* outBuf)
{ return parseUntil(outBuf, myMaskNonSpace); }
/** Get thru length of chars */
int getThruLength(CharData* outBuf, int length);
/** Get the current char but not advance curPtr */
char getCurChar() { return *myCurPtr; }
static u_int8_t myMaskNonWord[];
static u_int8_t myMaskDigit[];
static u_int8_t myMaskNonSpace[];
static u_int8_t myMaskEol[];
static u_int8_t myMaskEolSpace[];
private:
const char* myCurPtr;
const char* myEndPtr;
};
/* Local Variables: */
/* c-file-style: "stroustrup" */
/* indent-tabs-mode: nil */
/* c-file-offsets: ((access-label . -) (inclass . ++)) */
/* c-basic-offset: 4 */
/* End: */
#endif
| 1,673
|
https://github.com/russellremple/bson-adt/blob/master/bson-adt-core/src/main/scala/adt/bson/BsonValue.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
bson-adt
|
russellremple
|
Scala
|
Code
| 1,261
| 2,942
|
package adt.bson
import org.bson.BsonType
import org.bson.types.ObjectId
import org.joda.time.{DateTime, DateTimeZone}
import scala.util.Try
import scala.util.matching.Regex
/**
* Generic Bson value.
*
* This is a closed algebraic data type for all values that can be stored in Mongo.
*
* See {@link http://bsonspec.org/spec.html}
*
* (Currently) Unsupported Types:
* Undefined \x06 / 6 (deprecated)
* DBPointer \x0C / 12 (deprecated)
* JavaScript \x0D / 13 (javascript in the database? are you sure you want this noose?)
* Symbol \x0E / 14 (deprecated)
* JavaScript (with scope) \x0F / 15 (javascript in the database? with scope? really?)
* Timestamp \x11 / 17 (used for internal increment values)
* Min key \xFF / 255 (used internally)
* Max key \x7F / 127 (used internally)
*/
sealed trait BsonValue {
@deprecated("Use (???: BsonValue).ScalaType instead.", "1.3.0")
type $type = ScalaType
@deprecated("Use (???: BsonValue).Type.getValue instead.", "1.3.0")
def $type: Int = Type.getValue
type ScalaType
def Type: BsonType
def value: ScalaType
/**
* Tries to convert the value into a [[T]], throwing an exception if it can't.
* An implicit [[BsonReads]] of [[T]] must be defined.
*/
def as[T](implicit reader: BsonReads[T]): T = reader reads this
/**
* Tries to convert the value into a [[T]]. An implicit [[BsonReads]] of [[T]] must be defined.
* Any error is mapped to None
*
* @return Some[T] if it succeeds, None if it fails.
*/
def asOpt[T](implicit reader: BsonReads[T]): Option[T] = Try(reader reads this).toOption.filter {
case BsonUndefined() => false
case _ => true
}
/**
* Return the property corresponding to the fieldName, supposing we have a [[BsonObject]].
*
* @param fieldName the name of the property to lookup
* @return the resulting [[BsonValue]].
* If the current node is not a [[BsonObject]] or doesn't have the property,
* a [[BsonUndefined]] will be returned.
*/
def \(fieldName: String): BsonValue = BsonUndefined(s"'$fieldName' is undefined on object: $this")
/**
* Whether {{{value == null}}} would be true in JavaScript / Mongo.
*/
def equalsNull: Boolean = false
/**
* Strips out any `null` values from arrays and `null` fields from objects.
*
* @note This does not remove empty arrays or objects.
*/
def pruned: BsonValue = this
}
/**
* Any [[BsonValue]] that can exist inside of another [[BsonContainer]], but has no children itself.
*/
sealed trait BsonPrimitive extends BsonValue
object BsonPrimitive {
def apply[T <: AnyVal : BsonWrites](value: T): BsonPrimitive = {
val bson = Bson.toBson(value)
bson match {
case BsonPrimitive(prim) => prim
case other => throw new IllegalArgumentException(
s"BsonWrites for value $value did not produce a BsonPrimitive, but instead produced $bson")
}
}
def unapply(bson: BsonValue): Option[BsonPrimitive] = bson match {
case prim: BsonPrimitive => Some(prim)
case _ => None
}
}
@deprecated("Use BsonDouble instead.", "1.3.1")
object BsonNumber {
@deprecated("Use BsonDouble(value) instead.", "1.3.1")
def apply(value: Double): BsonDouble = BsonDouble(value)
@deprecated("Use case BsonDouble(value) instead", "1.3.1")
def unapply(bson: BsonNumber): Option[Double] = bson match {
case BsonDouble(value) => Some(value)
case _ => None
}
}
/**
* Any [[BsonValue]] that can potentially contain [[BsonPrimitive]] children.
*/
sealed trait BsonContainer extends BsonValue {
def children: Iterable[BsonValue]
}
case class BsonBoolean(value: Boolean) extends BsonPrimitive {
override type ScalaType = Boolean
@inline final override def Type: BsonType = BsonType.BOOLEAN
}
case class BsonDouble(value: Double) extends BsonPrimitive {
override type ScalaType = Double
@inline final override def Type: BsonType = BsonType.DOUBLE
}
case class BsonInt(value: Int) extends BsonPrimitive {
override type ScalaType = Int
@inline final override def Type: BsonType = BsonType.INT32
}
case class BsonLong(value: Long) extends BsonPrimitive {
override type ScalaType = Long
@inline final override def Type: BsonType = BsonType.INT64
}
case class BsonString(value: String) extends BsonPrimitive {
override type ScalaType = String
@inline final override def Type: BsonType = BsonType.STRING
}
case class BsonBinary(value: Array[Byte]) extends BsonPrimitive with Proxy {
override type ScalaType = Array[Byte]
@inline final override def Type: BsonType = BsonType.BINARY
val utf8: String = new String(value, "UTF-8")
@inline final override def self: Any = utf8
}
/**
* A Regular Expression value.
*
* @note this extends [[Proxy]] to allow the underlying immutable pattern String
* determine equals and hashCode rather than [[Regex]], which does not define
* equality based on the value of the compiled pattern
*
* @param value the regex value
*/
case class BsonRegex(value: Regex) extends BsonPrimitive with Proxy {
override type ScalaType = Regex
@inline final override def Type: BsonType = BsonType.REGULAR_EXPRESSION
@inline final override def self: Any = pattern
val pattern: String = value.pattern.pattern()
}
case class BsonObjectId(value: ObjectId) extends BsonPrimitive {
override type ScalaType = ObjectId
@inline final override def Type: BsonType = BsonType.OBJECT_ID
}
/**
* Represents a DateTime in UTC.
*
* @param value the DateTime in UTC.
*/
class BsonDate private[BsonDate] (override val value: DateTime) extends BsonPrimitive with Proxy {
override type ScalaType = DateTime
@inline final override def Type: BsonType = BsonType.DATE_TIME
@inline final override def self: Any = value
}
object BsonDate extends (DateTime => BsonDate) {
override def apply(value: DateTime): BsonDate = {
val utc = if (value.getZone == DateTimeZone.UTC) value else value.withZone(DateTimeZone.UTC)
new BsonDate(utc)
}
def apply(millis: Long): BsonDate = new BsonDate(new DateTime(millis, DateTimeZone.UTC))
def unapply(bson: BsonDate): Option[DateTime] = Some(bson.value)
}
// This is currently not integrated into the ADT, but it will be soon, so this is a placeholder
case class BsonTimestamp(millis: Int, inc: Int) /* extends BsonPrimitive */ {
type ScalaType = BsonTimestamp // there isn't a good Scala equivalent, so we'll use this class
@inline final def value: ScalaType = this
@inline final def Type: BsonType = BsonType.TIMESTAMP
}
// This is currently not integrated into the ADT as it is a rare use case and requires additional validation logic.
class BsonJavaScript private (val value: String) extends Proxy /* with BsonPrimitive */ {
type ScalaType = String
@inline final def Type: BsonType = BsonType.JAVASCRIPT
@inline final override def self: Any = value
}
object BsonJavaScript extends (String => BsonJavaScript) {
override def apply(js: String): BsonJavaScript = parse(js)
def unapply(js: BsonJavaScript): Option[String] = {
if (js eq null) None
else Some(js.value)
}
def parse(js: String): BsonJavaScript = {
if (isValid(js)) new BsonJavaScript(js)
else throw new IllegalArgumentException(s"Invalid JavaScript: '$js'")
}
// TODO: Implement or require a parser
def isValid(js: String): Boolean = true
}
case class BsonArray(value: Seq[BsonValue] = Nil) extends BsonContainer {
override type ScalaType = Seq[BsonValue]
@inline final override def Type: BsonType = BsonType.ARRAY
@inline final override def children: Iterable[BsonValue] = value
override def pruned: BsonArray = BsonArray(
value filterNot (_.equalsNull) map (_.pruned)
)
}
case class BsonObject(value: Map[String, BsonValue] = Map.empty) extends BsonContainer {
override type ScalaType = Map[String, BsonValue]
@inline final override def Type: BsonType = BsonType.OBJECT_ID
override def children: Iterable[BsonValue] = value.values
def ++(that: BsonObject): BsonObject = BsonObject(this.value ++ that.value)
override def \(fieldName: String): BsonValue = {
value.getOrElse(fieldName, super.\(fieldName))
}
override def pruned: BsonObject = BsonObject(
value filterNot (_._2.equalsNull) mapValues (_.pruned)
)
}
/**
* Represents a Bson `null` value.
*/
case object BsonNull extends BsonPrimitive {
override def value: Null = null // throw new NullPointerException?
override type ScalaType = Null
@inline final override def Type: BsonType = BsonType.NULL
override def asOpt[T](implicit reader: BsonReads[T]): Option[T] = None
override def equalsNull: Boolean = true
}
/**
* Represent a missing Bson value.
*/
class BsonUndefined(err: => String) extends BsonValue {
override type ScalaType = Nothing
override def value: Nothing = throw new NoSuchElementException("Cannot read value of undefined")
@inline final override def Type: BsonType = BsonType.UNDEFINED
def error = err
override def toString = "BsonUndefined(" + err + ")"
override def asOpt[T](implicit reader: BsonReads[T]): Option[T] = None
override def equalsNull: Boolean = true
}
object BsonUndefined {
def apply(err: => String): BsonUndefined = new BsonUndefined(err)
def unapply(value: Object): Boolean = value.isInstanceOf[BsonUndefined]
}
| 50,085
|
https://github.com/happylai/hryj-otc/blob/master/src/views/user/store.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
hryj-otc
|
happylai
|
Vue
|
Code
| 677
| 2,943
|
<template>
<div class="tab-container">
<div class="filter-container" style="margin-bottom: 10px;">
<el-input v-model="fliterQuery.query" placeholder="用户ID/代理ID/姓名/手机号" style="width: 300px;" class="filter-item" @keyup.enter.native="handleFilter" />
<el-select v-model="fliterQuery.active" placeholder="账号状态" clearable style="width: 140px" class="filter-item">
<el-option v-for="item in AccountStatus" :key="item.id" :label="item.label" :value="item.name" />
</el-select>
<el-date-picker class="filter-item"
v-model="fliterQuery.date"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
/>
<el-button v-waves class="filter-item" style="margin-left: 40px" type="primary" icon="el-icon-search" @click="handleFilter">
搜索
</el-button>
<el-button v-waves class="filter-item" style="margin-left: 40px" type="primary" icon="el-icon-plus" @click="dialogVisible=true">
添加
</el-button>
</div>
<el-table v-loading="loading" stripe :data="list" border fit highlight-current-row style="width: 100%">
<el-table-column
align="center"
label="用户ID"
width="180px"
element-loading-text="请给我点时间!"
>
<template slot-scope="scope">
<span>{{ scope.row.uuid }}</span>
</template>
</el-table-column>
<el-table-column width="180px" align="center" label="手机号">
<template slot-scope="scope">
<span>{{ scope.row.mobileContact }}</span>
</template>
</el-table-column>
<el-table-column width="180px" align="center" label="邮箱">
<template slot-scope="scope">
<span>{{ scope.row.emailContact }}</span>
</template>
</el-table-column>
<el-table-column width="180px" align="center" label="所属代理商">
<template slot-scope="scope">
<span>{{ scope.row.parentAgent||'无' }}</span>
</template>
</el-table-column>
<el-table-column width="120px" align="center" label="交易额">
<template slot-scope="scope">
<span>{{ scope.row.amount||'-' }}</span>
</template>
</el-table-column>
<el-table-column align="center" label="账号状态" width="80px">
<template slot-scope="scope">
<span>{{ scope.row.active?'正常':'冻结' }}</span>
<!-- <span>{{ scope.row.active?'正常':'冻结' }}</span> -->
</template>
</el-table-column>
<el-table-column align="center" label="注册时间" minwidth="300">
<template slot-scope="scope">
<span>{{ scope.row.createTime }}</span>
</template>
</el-table-column>
<el-table-column align="center" class-name="status-col" label="操作" width="110">
<template slot-scope="scope">
<el-button type="primary" size="small" @click="goDetail(scope.row.id)">详情</el-button>
</template>
</el-table-column>
</el-table>
<pagination v-show="paginationMeta.total>0" :total="paginationMeta.total" :page.sync="meta.current" :limit.sync="meta.size" @pagination="paginationChange" />
<el-dialog :visible.sync="dialogVisible" title="添加用户">
<el-form ref="regForm" :model="regForm" :rules="loginRules" class="login-form" label-width="120px" auto-complete="on" label-position="right">
<el-form-item label="邀请人UUID" class="addUserItem" prop="parent">
<el-input ref="parent" v-model="regForm.parent" autocomplete="off" placeholder="请输入邀请人uuid" name="uuid" type="text" tabindex="1" auto-complete="on" />
</el-form-item>
<el-form-item label="邮箱" class="addUserItem" prop="emailContact">
<el-input ref="emailContact" v-model="regForm.emailContact" autocomplete="off" placeholder="请输入邮箱" name="emailContact" type="text" tabindex="1" auto-complete="on" />
</el-form-item>
<el-form-item label="密码" class="addUserItem" prop="password">
<el-input ref="password" v-model="regForm.password" autocomplete="off" show-password :type="passwordType" placeholder="请输入密码" name="password" tabindex="2" auto-complete="on" />
</el-form-item>
<el-form-item label="" class="addUserItem">
<el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handlAdd">添加</el-button>
</el-form-item>
</el-form>
</el-dialog>
</div>
</template>
<script>
// import tabPane from './components/TabPane'
import { mapState, mapGetters, mapActions } from 'vuex' // 先要引入
import pagination from '@/components/Pagination'
import tip from '@/components/Tip'
import { groupsConstName, userRolesConstName, adminRolesConstName } from '@/utils'
import waves from '@/directive/waves' // waves directive
import { Groups, UserType, KycLevel, emptySelect, PayType, AccountStatus } from '@/utils/enumeration'
import { users_b, user_b_save } from '@/api/usermanage'
import { validateUsername, validateEamil, validatePassword } from '@/utils/validate'
export default {
name: 'Tab',
components: { pagination, tip },
directives: { waves },
data() {
const validateConfirm = (rule, value, callback) => {
if (!value) {
callback(new Error('请重复密码'))
} else if (value.length < 6) {
callback(new Error('密码必须大于6位数'))
} else if (this.regForm.password !== value) {
callback(new Error('密码不一致'))
} else {
callback()
}
}
return {
groupsConstName,
userRolesConstName,
adminRolesConstName,
AccountStatus,
PayType,
activeType: '0',
UserType,
KycLevel,
Groups: [emptySelect, ...Groups],
loginRules: {
username: [{ required: true, trigger: 'blur', validator: validateUsername }],
emailContact: [{ required: true, trigger: 'blur', validator: validateEamil }],
password: [{ required: true, trigger: 'blur', validator: validatePassword }],
confirm: [{ required: true, trigger: 'blur', validator: validateConfirm }]
},
fliterQuery: {
page: 1,
size: 20,
date: null,
query: undefined,
payType: undefined,
groupId: undefined,
kycLevel: undefined
},
meta: {
current: 1,
size: 10
},
dialogVisible: false,
loading: false,
list: [],
paginationMeta: {
total: 10,
pages: 1
},
regForm: {
parent:undefined,
emailContact: undefined,
password: undefined,
active: true
}
}
},
computed: {
...mapState({
allList: state => state.order.allList,
allListMeta: state => state.order.allMeta
}),
...mapGetters([
'groupsConst',
'userRolesConst',
'adminRolesConst'
])
},
mounted() {
this.getList()
},
methods: {
paginationChange(e) {
console.log('paginationChange', e)
this.meta.size = e.limit
this.meta.current = e.page
this.getList()
},
getList(meta, data) {
this.listLoading = true
users_b(meta || this.meta, data).then(res => {
console.log('res', res)
if (res.code === 0) {
this.list = res.data.records
this.meta.current = res.data.current
this.paginationMeta.total = res.data.total
this.paginationMeta.pages = res.data.pages
}
})
},
handleFilter() {
const fliterQuery = this.fliterQuery
console.log('fliterQuery', this.fliterQuery)
const data = {
active: fliterQuery.active,
query: fliterQuery.query
}
if (fliterQuery.date) {
data.start = this.$moment(fliterQuery.date[0]).format('YYYY-MM-DD HH:mm:ss')
// data.start = '2019-10-16 12:11:11'
data.end = this.$moment(fliterQuery.date[1]).format('YYYY-MM-DD') + ' 23:59:59'
}
const meta = this.meta
meta.current = 1
this.getList(meta, data)
},
goDetail(id) {
this.$router.push({ path: `/user/store/${id}` })
},
handlAdd() {
console.log('click')
this.$refs.regForm.validate(valid => {
console.log('valid', valid)
if (valid) {
this.loading = true
const data = this.regForm
user_b_save(data).then(res => {
this.loading = false
if (res.code === 0) {
this.dialogVisible = false
this.$message({
message: '保存成功',
type: 'success'
})
this.dialogVisible = false
this.getList()
this.regForm = {
emailContact: undefined,
password: undefined,
active: true
}
} else {
this.$message.error(res.message || '操作失败')
}
}).catch(err => {
this.loading = false
this.$message.error(err || '操作失败')
})
} else {
console.log('error submit!!')
return false
}
})
}
}
}
</script>
<style scoped>
.tab-container {
margin: 30px;
}
</style>
| 16,490
|
https://github.com/TimoDeus/MyStravaDashboard/blob/master/src/app/reducers/state.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
MyStravaDashboard
|
TimoDeus
|
TypeScript
|
Code
| 23
| 85
|
import {RouterState} from 'react-router-redux';
import {AuthorizationState} from "app/reducers/authorization";
import {AthleteState} from "../../../types/athlete";
export interface RootState {
router: RouterState;
authorization: AuthorizationState;
athlete: AthleteState;
}
| 46,100
|
https://github.com/CelsoAntunesNogueira/Phyton3/blob/master/ex028 - Aknator numerico.py
|
Github Open Source
|
Open Source
|
MIT
| null |
Phyton3
|
CelsoAntunesNogueira
|
Python
|
Code
| 46
| 116
|
import random
from time import sleep
num = int(input('Digite um número de 1 a 5 que irei tentar advinhar:'))
a = random.randint(0, 5)
print('Pensando ..')
sleep(2)
print("O número foi {}".format(num))
print('E pensei no número {}'.format(a))
if num == a :
print("Eu acertei! ")
else:
print('Você ganhou!!')
| 29,688
|
https://github.com/Wizard-collab/wizard/blob/master/App/softwares_env/wizard/wsd/main.py
|
Github Open Source
|
Open Source
|
MIT
| null |
wizard
|
Wizard-collab
|
Python
|
Code
| 22
| 81
|
import yaml
class wsd():
def __init__(self, file, dict):
self.file = file
self.dict = dict
def write_sd(self):
with open(self.file, 'w') as f:
f.write(yaml.dump(self.dict))
| 597
|
https://github.com/kotoran/ProjectBlueSky/blob/master/ProjectBlueSky/Assets/Prefabs/Player.meta
|
Github Open Source
|
Open Source
|
Unlicense
| 2,017
|
ProjectBlueSky
|
kotoran
|
Unity3D Asset
|
Code
| 14
| 70
|
fileFormatVersion: 2
guid: f3e97286987f43e4dae8e851971a059f
folderAsset: yes
timeCreated: 1507108751
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| 14,218
|
https://github.com/gildas/go-icws/blob/master/status_message.go
|
Github Open Source
|
Open Source
|
MIT
| null |
go-icws
|
gildas
|
Go
|
Code
| 73
| 263
|
package icws
// StatusMessage describes a Status Message
type StatusMessage struct {
ID string `json:"statusId"`
SystemID string `json:"systemId"`
Text string `json:"messageText"`
IconURI string `json:"iconUri"`
GroupTag string `json:"groupTag"`
CanHaveDate bool `json:"canHaveDate"`
CanHaveTime bool `json:"canHaveTime"`
IsDoNotDisturb bool `json:"isDoNotDisturbStatus"`
IsSelectable bool `json:"isSelectableStatus"`
IsPersistent bool `json:"isPersistentStatus"`
IsForward bool `json:"isForwardStatus"`
IsAfterCallWork bool `json:"isAfterCallWorkStatus"`
IsACD bool `json:"isACDStatus"`
IsAllowFollowUp bool `json:"isAllowFollowUpStatus"`
}
// GetID tells the ID
//
// implements Identifiable
func (status StatusMessage) GetID() string {
return status.ID
}
| 39,210
|
https://github.com/dfsilva/database-streamer/blob/master/frontend/lib/store/hud_store.g.dart
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
database-streamer
|
dfsilva
|
Dart
|
Code
| 146
| 567
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'hud_store.dart';
// **************************************************************************
// StoreGenerator
// **************************************************************************
// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic
mixin _$HudStore on _HudStore, Store {
final _$loadingAtom = Atom(name: '_HudStore.loading');
@override
bool get loading {
_$loadingAtom.reportRead();
return super.loading;
}
@override
set loading(bool value) {
_$loadingAtom.reportWrite(value, super.loading, () {
super.loading = value;
});
}
final _$textAtom = Atom(name: '_HudStore.text');
@override
String get text {
_$textAtom.reportRead();
return super.text;
}
@override
set text(String value) {
_$textAtom.reportWrite(value, super.text, () {
super.text = value;
});
}
final _$_HudStoreActionController = ActionController(name: '_HudStore');
@override
dynamic showHud(String text) {
final _$actionInfo =
_$_HudStoreActionController.startAction(name: '_HudStore.showHud');
try {
return super.showHud(text);
} finally {
_$_HudStoreActionController.endAction(_$actionInfo);
}
}
@override
dynamic hideHud() {
final _$actionInfo =
_$_HudStoreActionController.startAction(name: '_HudStore.hideHud');
try {
return super.hideHud();
} finally {
_$_HudStoreActionController.endAction(_$actionInfo);
}
}
@override
String toString() {
return '''
loading: ${loading},
text: ${text}
''';
}
}
| 23,242
|
https://github.com/The-Ludwig/DAP2_BL/blob/master/Blatt7/LGS.java
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
DAP2_BL
|
The-Ludwig
|
Java
|
Code
| 220
| 853
|
import java.util.Random;
class LGS
{
public static void main(String[] args)
{
int len = 0;
try
{
len = Integer.parseInt(args[0]);
}catch(NumberFormatException e)
{
System.out.println(e.toString());
return;
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e.toString());
return;
}
String rand1 = "AsdfljksdfoihB";
String rand2 = "A235346346B";
System.out.println("Folge 1: "+rand1+"\nFolge 2: "+rand2);
long t = System.currentTimeMillis();
String res = lks(rand1, rand2);
t = System.currentTimeMillis() - t;
System.out.println("Die längste gemeinsame SubFolge ist: \""+ res + "\" Dies zu berechnen hat "+(double)t/1000+ " Sekunden gedauert");
System.out.println("Die lanege der Laengsten war " + res.length());
}
public static String lks(String s1, String s2)
{
int l1 = s1.length();
int l2 = s2.length();
int[][] c = new int[l1+1][l2+1];
for(int i = 0; i <= l1; i++) c[i][0] = 0;
for(int i = 0; i <= l2; i++) c[0][i] = 0;
for(int i = 1; i <= l1; i++)
for(int j = 1; j <= l2; j++)
if(s1.charAt(i-1) == s2.charAt(j-1))
c[i][j] = c[i-1][j-1]+1;
else
if(c[i-1][j] >= c[i][j-1])
c[i][j] = c[i-1][j];
else
c[i][j] = c[i][j-1];
StringBuilder res = new StringBuilder(c[l1][l2]);
while(l1 != 0 && l2 != 0)
if(s1.charAt(l1-1) == s2.charAt(l2-1))
{
res.append(s2.charAt(--l2));
l1--;
}
else if (c[l1][l2-1] >= c[l1-1][l2])
l2--;
else
l1--;
return res.reverse().toString();
}
public static String randStr(int n)
{
Random r = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuilder res = new StringBuilder(n);
while(--n >= 0)
{
res.append(alphabet.charAt(r.nextInt(alphabet.length())));
}
return res.toString();
}
}
| 13,417
|
https://github.com/rrhett/ngae/blob/master/deploy.js
|
Github Open Source
|
Open Source
|
0BSD
| 2,017
|
ngae
|
rrhett
|
JavaScript
|
Code
| 441
| 1,090
|
#!/usr/bin/env node
'use strict';
const execSync = require('child_process').execSync;
const path = require('path');
const spawnSync = require('child_process').spawnSync;
const deployAppEngine = (config, step) => {
const tag = spawnSync('git', ['tag', '-l', '--contains']).stdout.toString().trim();
// We generate a version based on the git tag of the commit.
// TODO: maybe allow a version to be passed in and use it to git tag?
// Or allow a prefix or something, so e.g. it looks for ngae-version?
// For this we verify we have only one tag.
// Also, appengine requires that the version:
// - matches [a-z0-9-]* (we'll impose starts with [a-z] for best practices so
// it doesn't conflict with possibly accessing an instance, per their
// recommendations)
// - doesn't start with ah-
// - isn't default or latest
// And for safety we'll further impose:
// - isn't in use by the app already
if (tag.includes('\n') || tag.length == 0) {
step.error('The current commit must contain exactly one tag');
}
if (tag.startsWith('ah-')) {
step.error('Tag cannot start with ah-');
}
if (tag === 'default' || tag === 'latest') {
step.error(`The label ${tag} is reserved.`);
}
const requiredRegex = /^[a-z][a-z0-9-]*$/;
if (!requiredRegex.test(tag)) {
step.error(`${tag} must match ${requiredRegex}`);
}
const versions = spawnSync('gcloud',
['app', 'versions', 'describe', tag, '-s', 'default', '--project',
projectId]);
// If gcloud app versions describes exits with status 1, it found the app with
// the given version. We don't want to accidentally overwrite the app version,
// so abort here.
if (versions.status === 0) {
step.error(
`gcloud app versions exited with error; make sure ${tag} isn't an existing version`);
}
// Note: gcloud app deploy will additionally prompt.
console.log(`About to deploy version ${tag}.`);
try {
// stdio: [0, 1, 2] uses this process' stdio, effectively running this
// script inline.
execSync(
`gcloud app deploy --version ${tag} --project ${projectId}`,
{cwd: dir, stdio: [0, 1, 2]});
} catch (e) {
step.error('');
}
};
const deployFirebase = (config, step) => {
const hash = spawnSync('git', ['show', '--no-patch', '--format="%H"']).stdout.toString().trim();
// TODO: integrate tags from the commit into the deploy message.
//const tag = spawnSync('git', ['tag', '--contains']).stdout.toString().trim();
const deployMessage = `Deployed from commit ${hash}`;
console.log(`About to deploy from commit ${hash}.`);
try {
// stdio: [0, 1, 2] uses this process' stdio, effectively running this
// script inline.
execSync(
`firebase deploy -m "${deployMessage}"`,
{stdio: [0, 1, 2]});
} catch (e) {
step.error('');
}
};
const deploy = (config) => {
require('./compile').compile(config);
const step = require('./status.js').status('Deploying');
if (config.firebase) {
deployFirebase(config, step);
} else {
deployAppEngine(config, step);
}
step.done();
};
exports.deploy = deploy;
if (require.main == module) {
const program = require('commander');
program.arguments('')
.option('-c, --config [file]', 'Configuration file', 'ngae.conf.json')
.action(() => { });
program.parse(process.argv);
const config = require('./config.js').config(program.config);
deploy(config);
}
| 3,509
|
https://github.com/ceekay1991/AliPayForDebug/blob/master/AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/NineReuseBoxDataProvider.h
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
AliPayForDebug
|
ceekay1991
|
C
|
Code
| 88
| 300
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
@class NSMutableArray, NSString;
@interface NineReuseBoxDataProvider : NSObject
{
long long _sectionCount;
NSMutableArray *_itemList;
NSString *_itemCellClassName;
CDUnknownBlockType _itemSize;
id _originData;
}
@property(retain, nonatomic) id originData; // @synthesize originData=_originData;
@property(copy, nonatomic) CDUnknownBlockType itemSize; // @synthesize itemSize=_itemSize;
@property(retain, nonatomic) NSString *itemCellClassName; // @synthesize itemCellClassName=_itemCellClassName;
@property(retain, nonatomic) NSMutableArray *itemList; // @synthesize itemList=_itemList;
@property(nonatomic) long long sectionCount; // @synthesize sectionCount=_sectionCount;
- (void).cxx_destruct;
@end
| 10,957
|
https://github.com/ecojuntak/proctor/blob/master/migrations/7_CreateJobsScheduleTable.up.sql
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
proctor
|
ecojuntak
|
SQL
|
Code
| 33
| 79
|
CREATE TABLE jobs_schedule (
id uuid not null primary key,
name text,
args text,
tags text,
notification_emails text,
time text,
user_email text,
enabled bool,
created_at timestamp default now(),
updated_at timestamp default now()
);
| 35,439
|
https://github.com/AllardQuek/tp/blob/master/src/main/java/seedu/programmer/ui/components/LabResultCard.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
tp
|
AllardQuek
|
Java
|
Code
| 192
| 514
|
package seedu.programmer.ui.components;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.programmer.model.student.Lab;
import seedu.programmer.ui.UiPart;
/**
* An UI component that displays information of the lab result.
*/
public class LabResultCard extends UiPart<Region> {
private static final String FXML = "LabResultCard.fxml";
/**
* Note: Certain keywords such as "location" and "resources" are reserved keywords in JavaFX.
* As a consequence, UI elements' variable names cannot be set to such keywords
* or an exception will be thrown by JavaFX during runtime.
*
*/
public final Lab result;
@FXML
private HBox cardPane;
@FXML
private Label labTitle;
@FXML
private Label studentScore;
@FXML
private Label totalScore;
/**
* Creates a {@code labResultCode} with the given {@code labResult} and index to display.
*/
public LabResultCard(Lab result) {
super(FXML);
this.result = result;
labTitle.setText(result.toString());
totalScore.setText("Total Score: " + result.getLabTotal().toString());
if (!result.isMarked()) {
studentScore.setText("Actual Score: -");
} else {
studentScore.setText("Actual Score: " + result.getLabResult().toString());
}
}
@Override
public boolean equals(Object other) {
// short circuit if same object
if (other == this) {
return true;
}
// instanceof handles nulls
if (!(other instanceof LabResultCard)) {
return false;
}
// state check
LabResultCard card = (LabResultCard) other;
return result.equals(card.result);
}
}
| 39,434
|
https://github.com/ChoSeyoung/simple-boot-front/blob/master/test/typescript/typescript_basic.test.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
simple-boot-front
|
ChoSeyoung
|
TypeScript
|
Code
| 232
| 682
|
/* eslint-disable */
// import * as request from 'supertest'
import {of} from 'rxjs'
import {mergeMap} from 'rxjs/operators'
import * as ts from "typescript";
// typescript decorator
// https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators
describe('typescript basic', () => {
test('typescript basic test', async (done) => {
const source = "let x: string = 'string'";
let result = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS }});
console.log(JSON.stringify(result));
done()
})
test('instanceof test', async (done) => {
const s = 'aa';
const a = {name:'aa'}
const aa = (a: object) => {
if (a instanceof Object) {
console.log('-->')
}
}
aa(a);
// console.log( (a instanceof Object))
// console.log( (a instanceof object))
done()
})
test('typescript promise test', async (done) => {
const a = async (s: string) => {
console.log('---------')
return '--------->';
}
a('aa').then(it => console.log(it));
done()
})
})
const data = {
title: '과제명',
scopes: [
// {type: 'all', startDt: '2012-01-01', endDt: '2022-01-02'},
{type: 'define', startDt: '2012-01-01', endDt: '2022-01-02'},
{type: 'idea', startDt: '2012-01-01', endDt: '2022-01-02'},
{type: 'test', startDt: '2012-01-01', endDt: '2022-01-02'},
],
type: 'team',
desc: 'desc'
}
// test('did not rain', () => {
// const index = new Index()
// console.log(index)
// expect(0).toBe(0)
// })
// import { expect } from 'chai';
//
// console.log('--->')
// // eslint-disable-next-line no-undef
// describe('Calculator', () => {
// // eslint-disable-next-line no-undef
// it('should return sum of two number.', () => {
// console.log('--->')
// expect(20).to.equal(20);
// });
// });
// // eslint-disable-next-line no-undef
| 7,601
|
https://github.com/Evalir/research/blob/master/archive/merkleslash/merkleslash_test.go
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
research
|
Evalir
|
Go
|
Code
| 891
| 2,199
|
package main
import "testing"
import "log"
import "github.com/cbergoon/merkletree"
func TestBasicGood(t *testing.T) {
// Pre-compute expected tree
var list []merkletree.Content
list = append(list, TestContent{x: "1"})
list = append(list, TestContent{x: "2"})
list = append(list, TestContent{x: "3"})
list = append(list, TestContent{x: "4"})
mt, _ := merkletree.NewTree(list)
trustedRoot := toHex(mt.MerkleRoot())
// Local node setup, partial
// Assume has access to trustedRoot
var contents []merkletree.Content
contents = append(contents, TestContent{x: "1"})
contents = append(contents, TestContent{x: "2"})
contents = append(contents, TestContent{x: "3"})
// Byzantine case, currently sending nothing
// TODO: Since haves is empty it should return full contents?
// XXX: Doesn't make sense to have tree hardcoded in other code
var haves []string
untrustedPayloads := pull("good", trustedRoot, haves)
content := TestContent{x: untrustedPayloads[0]}
contents = append(contents, content)
// XXX: is there no way to append to tree?
untrusted := mt
_ = untrusted.RebuildTreeWith(contents)
untrustedRoot := toHex(untrusted.MerkleRoot())
expect := (untrustedRoot == trustedRoot)
if !expect {
t.Errorf("Good basic: Untrusted root %s and trusted root %s should match", untrustedRoot, trustedRoot)
}
}
func TestBasicByzantine(t *testing.T) {
// Pre-compute expected tree
var list []merkletree.Content
list = append(list, TestContent{x: "1"})
list = append(list, TestContent{x: "2"})
list = append(list, TestContent{x: "3"})
list = append(list, TestContent{x: "4"})
mt, _ := merkletree.NewTree(list)
trustedRoot := toHex(mt.MerkleRoot())
// Local node setup, partial
// Assume has access to trustedRoot
var contents []merkletree.Content
contents = append(contents, TestContent{x: "1"})
contents = append(contents, TestContent{x: "2"})
contents = append(contents, TestContent{x: "3"})
// Byzantine case, currently sending nothing
// TODO: Since haves is empty it should return full contents?
// XXX: Doesn't make sense to have tree hardcoded in other code
var haves []string
untrustedPayloads := pull("byzantine", trustedRoot, haves)
content := TestContent{x: untrustedPayloads[0]}
contents = append(contents, content)
// XXX: is there no way to append to tree?
untrusted := mt
_ = untrusted.RebuildTreeWith(contents)
untrustedRoot := toHex(untrusted.MerkleRoot())
expect := (untrustedRoot != trustedRoot)
if !expect {
t.Errorf("Byzantine basic: Untrusted root %s and trusted root %s shouldn't match", untrustedRoot, trustedRoot)
}
}
// Here's what I want to test:
// Full tree: C->A; C->B; B->h(3); B->h(4); h(4)->4
// Trusted root: C
// Get from untrusted root: A, h(3) ("small") and 4 ("big"). Through these pieces of data we can verify.
// What does this mean if you have or don't have e.g. A branch? (which can hide a lot of data)
// I guess this is difference between thin and full client.
// See: https://bitcoin.stackexchange.com/questions/50674/why-is-the-full-merkle-path-needed-to-verify-a-transaction
//
// Next question: how do we specify path? Index [0 1], etc.
// Lets try GetMerklePath
// Not clear exactly how it maps or changes as we rebuild tree but ok for now
// Now, how can we do partial rebuild here?
//
// As a client, I say I have A [x, y], h(3) [x, y]. And a trusted root hash.
// So I guess there are two ways the query can go: for a specific piece of data (how know?) and diff.
// Lets graph: https://notes.status.im/MLGgpdgqRzeyTqVWkl7gjg#
// Can use Whisper/mailservers as well for compatibility before Swarm Feeds ready, boom new topic
func printPath(mt merkletree.MerkleTree, item merkletree.Content, name string) {
_, x, err := mt.GetMerklePath(item)
log.Println("Path to", name, x)
if err != nil {
log.Fatal(err)
}
}
// 4 nodes
// 2019/04/18 11:49:07 Path to 1 [1 1]
// 2019/04/18 11:49:07 Path to 2 [0 1]
// 2019/04/18 11:49:07 Path to 3 [1 0]
// 2019/04/18 11:49:07 Path to 4 [0 0]
// 5 nodes
// 2019/04/18 11:54:36 Path to 1 [1 1 1]
// 2019/04/18 11:54:36 Path to 2 [0 1 1]
// 2019/04/18 11:54:36 Path to 3 [1 0 1]
// 2019/04/18 11:54:36 Path to 4 [0 0 1]
// 2019/04/18 11:54:36 Path to 5 [1 1 0]
// XXX: Probably need a less naive implementation
// Yellow paper quote:
// > The core of the trie, and its sole requirement in termsof the protocol specification,
// > is to provide a single value that identifies a given set of key-value pairs, which may be
// > either a 32-byte sequence or the empty byte sequence.
//
// So let's start there and happily rebuild
func TestPartialVerification(t *testing.T) {
// Pre-compute expected tree
// XXX: Have you heard of for loops
var list []merkletree.Content
item1 := TestContent{x: "1"}
item2 := TestContent{x: "2"}
item3 := TestContent{x: "3"}
item4 := TestContent{x: "4"}
item5 := TestContent{x: "5"}
list = append(list, item1)
list = append(list, item2)
list = append(list, item3)
list = append(list, item4)
list = append(list, item5)
mt, _ := merkletree.NewTree(list)
//trustedRoot := toHex(mt.MerkleRoot())
printPath(*mt, item1, "1")
printPath(*mt, item2, "2")
printPath(*mt, item3, "3")
printPath(*mt, item4, "4")
printPath(*mt, item5, "5")
// print tree
log.Print("TREE", mt.String())
// // Local node setup, partial
// // Assume has access to trustedRoot
// var contents []merkletree.Content
// contents = append(contents, TestContent{x: "1"})
// contents = append(contents, TestContent{x: "2"})
// contents = append(contents, TestContent{x: "3"})
// // Byzantine case, currently sending nothing
// // TODO: Since haves is empty it should return full contents?
// // XXX: Doesn't make sense to have tree hardcoded in other code
// var haves []string
// untrustedPayloads := pull("good", trustedRoot, haves)
// content := TestContent{x: untrustedPayloads[0]}
// contents = append(contents, content)
// // XXX: is there no way to append to tree?
// untrusted := mt
// _ = untrusted.RebuildTreeWith(contents)
// untrustedRoot := toHex(untrusted.MerkleRoot())
// expect := (untrustedRoot == trustedRoot)
// if !expect {
// t.Errorf("Good basic: Untrusted root %s and trusted root %s should match", untrustedRoot, trustedRoot)
// }
}
| 5,314
|
https://github.com/jeffhain/jolikit/blob/master/src/main/java/net/jolikit/bwd/impl/sdl2/jlib/SdlEventType.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
jolikit
|
jeffhain
|
Java
|
Code
| 733
| 1,938
|
/*
* Copyright 2019 Jeff Hain
*
* 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 writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.jolikit.bwd.impl.sdl2.jlib;
import net.jolikit.bwd.impl.utils.basics.IntValuedHelper;
import net.jolikit.bwd.impl.utils.basics.IntValuedHelper.InterfaceIntValued;
/**
* enum SDL_EventType
*
* \brief The types of events that can be delivered.
*/
public enum SdlEventType implements InterfaceIntValued {
SDL_FIRSTEVENT(0), /**< Unused (do not remove) */
/* Application events */
SDL_QUIT(0x100), /**< User-requested quit */
/* These application events have special meaning on iOS, see README-ios.md for details */
SDL_APP_TERMINATING(0x100 + 1), /**< The application is being terminated by the OS
Called on iOS in applicationWillTerminate()
Called on Android in onDestroy()
*/
SDL_APP_LOWMEMORY(0x100 + 2), /**< The application is low on memory, free memory if possible.
Called on iOS in applicationDidReceiveMemoryWarning()
Called on Android in onLowMemory()
*/
SDL_APP_WILLENTERBACKGROUND(0x100 + 3), /**< The application is about to enter the background
Called on iOS in applicationWillResignActive()
Called on Android in onPause()
*/
SDL_APP_DIDENTERBACKGROUND(0x100 + 4), /**< The application did enter the background and may not get CPU for some time
Called on iOS in applicationDidEnterBackground()
Called on Android in onPause()
*/
SDL_APP_WILLENTERFOREGROUND(0x100 + 5), /**< The application is about to enter the foreground
Called on iOS in applicationWillEnterForeground()
Called on Android in onResume()
*/
SDL_APP_DIDENTERFOREGROUND(0x100 + 6), /**< The application is now interactive
Called on iOS in applicationDidBecomeActive()
Called on Android in onResume()
*/
/* Window events */
SDL_WINDOWEVENT(0x200), /**< Window state change */
SDL_SYSWMEVENT(0x200 + 1), /**< System specific event */
/* Keyboard events */
SDL_KEYDOWN(0x300), /**< Key pressed */
SDL_KEYUP(0x300 + 1), /**< Key released */
SDL_TEXTEDITING(0x300 + 2), /**< Keyboard text editing (composition) */
SDL_TEXTINPUT(0x300 + 3), /**< Keyboard text input */
SDL_KEYMAPCHANGED(0x300 + 4), /**< Keymap changed due to a system event such as an
input language or keyboard layout change.
*/
/* Mouse events */
SDL_MOUSEMOTION(0x400), /**< Mouse moved */
SDL_MOUSEBUTTONDOWN(0x400 + 1), /**< Mouse button pressed */
SDL_MOUSEBUTTONUP(0x400 + 2), /**< Mouse button released */
SDL_MOUSEWHEEL(0x400 + 3), /**< Mouse wheel motion */
/* Joystick events */
SDL_JOYAXISMOTION(0x600), /**< Joystick axis motion */
SDL_JOYBALLMOTION(0x600 + 1), /**< Joystick trackball motion */
SDL_JOYHATMOTION(0x600 + 2), /**< Joystick hat position change */
SDL_JOYBUTTONDOWN(0x600 + 3), /**< Joystick button pressed */
SDL_JOYBUTTONUP(0x600 + 4), /**< Joystick button released */
SDL_JOYDEVICEADDED(0x600 + 5), /**< A new joystick has been inserted into the system */
SDL_JOYDEVICEREMOVED(0x600 + 6), /**< An opened joystick has been removed */
/* Game controller events */
SDL_CONTROLLERAXISMOTION(0x650), /**< Game controller axis motion */
SDL_CONTROLLERBUTTONDOWN(0x650 + 1), /**< Game controller button pressed */
SDL_CONTROLLERBUTTONUP(0x650 + 2), /**< Game controller button released */
SDL_CONTROLLERDEVICEADDED(0x650 + 3), /**< A new Game controller has been inserted into the system */
SDL_CONTROLLERDEVICEREMOVED(0x650 + 4), /**< An opened Game controller has been removed */
SDL_CONTROLLERDEVICEREMAPPED(0x650 + 5), /**< The controller mapping was updated */
/* Touch events */
SDL_FINGERDOWN(0x700),
SDL_FINGERUP(0x700 + 1),
SDL_FINGERMOTION(0x700 + 2),
/* Gesture events */
SDL_DOLLARGESTURE(0x800),
SDL_DOLLARRECORD(0x800 + 1),
SDL_MULTIGESTURE(0x800 + 2),
/* Clipboard events */
SDL_CLIPBOARDUPDATE(0x900), /**< The clipboard changed */
/* Drag and drop events */
SDL_DROPFILE(0x1000), /**< The system requests a file open */
/* Audio hotplug events */
SDL_AUDIODEVICEADDED(0x1100), /**< A new audio device is available */
SDL_AUDIODEVICEREMOVED(0x1100 + 1), /**< An audio device has been removed. */
/* Render events */
SDL_RENDER_TARGETS_RESET(0x2000), /**< The render targets have been reset and their contents need to be updated */
SDL_RENDER_DEVICE_RESET(0x2000 + 1), /**< The device has been reset and all textures need to be recreated */
/** Events ::SDL_USEREVENT through ::SDL_LASTEVENT are for your use,
* and should be allocated with SDL_RegisterEvents()
*/
SDL_USEREVENT(0x8000),
/**
* This last event is only for bounding internal arrays
*/
SDL_LASTEVENT(0xFFFF);
private static final IntValuedHelper<SdlEventType> HELPER =
new IntValuedHelper<SdlEventType>(SdlEventType.values());
private final int intValue;
private SdlEventType(int intValue) {
this.intValue = intValue;
}
@Override
public int intValue() {
return this.intValue;
}
/**
* @param intValue An int value.
* @return The corresponding instance, or null if none.
*/
public static SdlEventType valueOf(int intValue) {
return HELPER.instanceOf(intValue);
}
}
| 29,402
|
https://github.com/articstranger/main/blob/master/src/main/java/seedu/address/logic/commands/SortCommand.java
|
Github Open Source
|
Open Source
|
MIT
| null |
main
|
articstranger
|
Java
|
Code
| 115
| 276
|
//@@author articstranger
package seedu.address.logic.commands;
import static java.util.Objects.requireNonNull;
import seedu.address.logic.CommandHistory;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.Model;
/**
* Sorts the current list of volunteers and returns a list of volunteers
* in descending order of points given by the map command
*/
public class SortCommand extends Command {
public static final String COMMAND_WORD = "sort";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Sorts and presents a list of volunteers who best fulfill "
+ "the criteria given in the map command, up to the number specified in this command.\n"
+ "Parameters: MAX_NUMBER\n"
+ "Example: sort 10";
private int maxVol;
@Override
public CommandResult execute(Model model, CommandHistory history) throws CommandException {
requireNonNull(model);
model.sortVolunteers();
return new CommandResult(String.format("Sorted!"));
}
}
| 15,879
|
https://github.com/bracedotto/monorepo/blob/master/packages/web/src/components/CardItem.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
monorepo
|
bracedotto
|
JavaScript
|
Code
| 687
| 2,922
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { retryDiedLinks, cancelDiedLinks } from '../actions';
import {
PIN_LINK, PIN_LINK_ROLLBACK, UNPIN_LINK, UNPIN_LINK_ROLLBACK,
MOVE_PINNED_LINK_ADD_STEP, MOVE_PINNED_LINK_ADD_STEP_ROLLBACK,
} from '../types/actionTypes';
import { ADDING, MOVING, PINNED } from '../types/const';
import { makeGetPinStatus } from '../selectors';
import { ensureContainUrlProtocol, isDiedStatus, isEqual } from '../utils';
import CardItemContent from './CardItemContent';
import CardItemSelector from './CardItemSelector';
class CardItem extends React.Component {
constructor(props) {
super(props);
this.didClick = false;
}
componentDidUpdate(prevProps) {
if (!isDiedStatus(prevProps.link.status) && isDiedStatus(this.props.link.status)) {
this.didClick = false;
}
}
shouldComponentUpdate(nextProps, nextState) {
if (
this.props.link.status !== nextProps.link.status ||
!isEqual(this.props.link.extractedResult, nextProps.link.extractedResult) ||
this.props.pinStatus !== nextProps.pinStatus
) {
return true;
}
return false;
}
onRetryRetryBtnClick = () => {
if (this.didClick) return;
this.props.retryDiedLinks([this.props.link.id]);
this.didClick = true;
}
onRetryCancelBtnClick = () => {
this.props.cancelDiedLinks([this.props.link.id]);
}
renderRetry() {
const { url } = this.props.link;
return (
<React.Fragment>
<div className="absolute inset-0 bg-black bg-opacity-75" />
<div className="px-4 absolute inset-0 flex flex-col justify-center items-center bg-transparent">
<h3 className="text-base text-white font-semibold text-center">Oops..., something went wrong!</h3>
<div className="pt-4 flex justify-center items-center">
<button onClick={this.onRetryRetryBtnClick} className="px-4 py-1 bg-white text-sm text-gray-500 font-medium rounded-full border border-white hover:bg-gray-700 hover:text-gray-50 focus:outline-none focus:ring focus:ring-blue-300">Retry</button>
<button onClick={this.onRetryCancelBtnClick} className="ml-4 px-3 py-1 text-sm text-gray-100 font-medium rounded-full border border-gray-100 hover:bg-gray-700 hover:text-gray-50 focus:outline-none focus:ring focus:ring-blue-300">Cancel</button>
</div>
<a className="block mt-4 w-full text-sm text-white font-medium text-center tracking-wide hover:underline focus:outline-none focus:ring focus:ring-blue-300" href={ensureContainUrlProtocol(url)} target="_blank" rel="noreferrer">Go to the link</a>
</div>
</React.Fragment>
);
}
renderBusy() {
const svgStyle = { top: '66px', left: '34px' };
return (
<div className="absolute top-0 right-0 w-16 h-16 bg-transparent overflow-hidden">
<div className="relative w-16 h-16 bg-white overflow-hidden transform rotate-45 translate-x-1/2 -translate-y-1/2">
<svg style={svgStyle} className="relative w-6 h-6 text-gray-700 transform -rotate-45 -translate-x-1/2 -translate-y-full" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M19.479 10.092C19.267 6.141 16.006 3 12 3s-7.267 3.141-7.479 7.092A5.499 5.499 0 005.5 21h13a5.499 5.499 0 00.979-10.908zM18.5 19h-13C3.57 19 2 17.43 2 15.5c0-2.797 2.479-3.833 4.433-3.72C6.266 7.562 8.641 5 12 5c3.453 0 5.891 2.797 5.567 6.78 1.745-.046 4.433.751 4.433 3.72 0 1.93-1.57 3.5-3.5 3.5zm-4.151-2h-2.77l3-3h2.77l-3 3zm-4.697-3h2.806l-3 3H6.652l3-3zM20 15.5a1.5 1.5 0 01-1.5 1.5h-2.03l2.788-2.788c.442.261.742.737.742 1.288zm-16 0A1.5 1.5 0 015.5 14h2.031l-2.788 2.788A1.495 1.495 0 014 15.5z" />
</svg>
</div>
</div>
);
}
renderPinning() {
const svgStyle = { top: '46px', left: '54px' };
return (
<div className="absolute top-0 left-0 w-16 h-16 bg-transparent overflow-hidden">
<div className="relative w-16 h-16 bg-white overflow-hidden transform rotate-45 -translate-x-1/2 -translate-y-1/2">
<svg style={svgStyle} className="relative w-6 h-6 text-gray-700 transform -rotate-45 -translate-x-1/2 -translate-y-full" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M19.479 10.092C19.267 6.141 16.006 3 12 3s-7.267 3.141-7.479 7.092A5.499 5.499 0 005.5 21h13a5.499 5.499 0 00.979-10.908zM18.5 19h-13C3.57 19 2 17.43 2 15.5c0-2.797 2.479-3.833 4.433-3.72C6.266 7.562 8.641 5 12 5c3.453 0 5.891 2.797 5.567 6.78 1.745-.046 4.433.751 4.433 3.72 0 1.93-1.57 3.5-3.5 3.5zm-4.151-2h-2.77l3-3h2.77l-3 3zm-4.697-3h2.806l-3 3H6.652l3-3zM20 15.5a1.5 1.5 0 01-1.5 1.5h-2.03l2.788-2.788c.442.261.742.737.742 1.288zm-16 0A1.5 1.5 0 015.5 14h2.031l-2.788 2.788A1.495 1.495 0 014 15.5z" />
</svg>
</div>
</div>
);
}
renderPin() {
const svgStyle = { top: '42px', left: '54px' };
return (
<div className="absolute top-0 left-0 w-16 h-16 bg-transparent overflow-hidden">
<div className="relative w-16 h-16 bg-white overflow-hidden transform rotate-45 -translate-x-1/2 -translate-y-1/2">
<svg style={svgStyle} className="relative w-4 h-4 text-gray-500 transform -rotate-45 -translate-x-1/2 -translate-y-full" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M20.2349 14.61C19.8599 12.865 17.8929 11.104 16.2249 10.485L15.6809 5.53698L17.1759 3.29498C17.3329 3.05898 17.3479 2.75698 17.2129 2.50798C17.0789 2.25798 16.8209 2.10498 16.5379 2.10498H7.39792C7.11392 2.10498 6.85592 2.25898 6.72192 2.50798C6.58792 2.75798 6.60192 3.06098 6.75992 3.29598L8.25792 5.54298L7.77392 10.486C6.10592 11.106 4.14092 12.866 3.76992 14.602C3.72992 14.762 3.75392 15.006 3.90192 15.196C4.00492 15.328 4.20592 15.486 4.58192 15.486H8.63992L11.5439 22.198C11.6219 22.382 11.8039 22.5 12.0019 22.5C12.1999 22.5 12.3819 22.382 12.4619 22.198L15.3649 15.485H19.4219C19.7979 15.485 19.9979 15.329 20.1019 15.199C20.2479 15.011 20.2739 14.765 20.2369 14.609L20.2349 14.61Z" />
</svg>
</div>
</div>
);
}
render() {
const { link, pinStatus } = this.props;
const { status } = link;
const isPinning = [
PIN_LINK, PIN_LINK_ROLLBACK, UNPIN_LINK, UNPIN_LINK_ROLLBACK,
MOVE_PINNED_LINK_ADD_STEP, MOVE_PINNED_LINK_ADD_STEP_ROLLBACK,
].includes(pinStatus);
return (
<div className="mx-auto relative max-w-md bg-white border border-gray-200 rounded-lg overflow-hidden shadow-sm sm:max-w-none">
<CardItemContent link={link} />
{[ADDING, MOVING].includes(status) && this.renderBusy()}
{isPinning && this.renderPinning()}
{[PINNED].includes(pinStatus) && this.renderPin()}
{![ADDING, MOVING].includes(status) && <CardItemSelector linkId={link.id} />}
{isDiedStatus(status) && this.renderRetry()}
</div>
);
}
}
CardItem.propTypes = {
link: PropTypes.object.isRequired,
};
const makeMapStateToProps = () => {
const getPinStatus = makeGetPinStatus();
const mapStateToProps = (state, props) => {
const pinStatus = getPinStatus(state, props.link);
return {
pinStatus,
};
};
return mapStateToProps;
};
const mapDispatchToProps = { retryDiedLinks, cancelDiedLinks };
export default connect(makeMapStateToProps, mapDispatchToProps)(CardItem);
| 10,909
|
https://github.com/rminnich/contest/blob/master/pkg/xcontext/bundles/zapctx/new_context.go
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
contest
|
rminnich
|
Go
|
Code
| 197
| 784
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package zapctx
import (
"context"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/facebookincubator/contest/pkg/xcontext"
"github.com/facebookincubator/contest/pkg/xcontext/bundles"
"github.com/facebookincubator/contest/pkg/xcontext/logger"
zapadapter "github.com/facebookincubator/contest/pkg/xcontext/logger/logadapter/zap"
prometheusadapter "github.com/facebookincubator/contest/pkg/xcontext/metrics/prometheus"
)
// NewContext is a simple-to-use function to create a context.Context
// using zap as the logger.
//
// See also: https://github.com/uber-go/zap
func NewContext(logLevel logger.Level, opts ...bundles.Option) xcontext.Context {
cfg := bundles.GetConfig(opts...)
loggerCfg := zap.Config{
Level: zap.NewAtomicLevelAt(zapadapter.Adapter.Level(logLevel)),
Development: true,
Encoding: "console",
EncoderConfig: zap.NewProductionEncoderConfig(),
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
switch cfg.Format {
case bundles.LogFormatPlainText, bundles.LogFormatPlainTextCompact:
loggerCfg.Encoding = "console"
case bundles.LogFormatJSON:
loggerCfg.Encoding = "json"
}
if cfg.TimestampFormat != "" {
loggerCfg.EncoderConfig.EncodeTime = timeEncoder(cfg.TimestampFormat)
}
// TODO: cfg.VerboseCaller is currently ignored, fix it.
var zapOpts []zap.Option
stdCtx := context.Background()
loggerRaw, err := loggerCfg.Build(zapOpts...)
if err != nil {
panic(err)
}
loggerInstance := logger.ConvertLogger(loggerRaw.Sugar())
ctx := xcontext.NewContext(
stdCtx, "",
loggerInstance, prometheusadapter.New(prometheus.DefaultRegisterer), cfg.Tracer,
nil, nil)
return ctx
}
func timeEncoder(layout string) func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
return func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
type appendTimeEncoder interface {
AppendTimeLayout(time.Time, string)
}
if enc, ok := enc.(appendTimeEncoder); ok {
enc.AppendTimeLayout(t, layout)
return
}
enc.AppendString(t.Format(layout))
}
}
| 21,565
|
https://github.com/nikneem/keez-online-frontend/blob/master/src/app/services/users.service.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
keez-online-frontend
|
nikneem
|
TypeScript
|
Code
| 94
| 329
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { UserProfileDto } from '@store/user-state/user.models';
@Injectable({
providedIn: 'root'
})
export class UsersService {
private backendApi: string;
constructor(private http: HttpClient) {
this.backendApi = environment.backendApi;
}
public postProfile(
defaultProfile: UserProfileDto
): Observable<HttpResponse<UserProfileDto>> {
const url = `${this.backendApi}/api/users`;
return this.http.post<UserProfileDto>(url, defaultProfile, {
observe: 'response'
});
}
public getProfile(): Observable<UserProfileDto> {
const url = `${this.backendApi}/api/users`;
return this.http.get<UserProfileDto>(url);
}
public putProfile(dto: UserProfileDto): Observable<UserProfileDto> {
const url = `${this.backendApi}/api/users/${dto.id}`;
return this.http.put<UserProfileDto>(url, dto);
}
}
| 4,248
|
https://github.com/AMReX-Astro/Castro/blob/master/Diagnostics/DustCollapse/dustcollapse_util.F90
|
Github Open Source
|
Open Source
|
BSD-3-Clause-LBNL, LicenseRef-scancode-unknown-license-reference
| 2,023
|
Castro
|
AMReX-Astro
|
Fortran Free Form
|
Code
| 732
| 2,233
|
! Process a group of n-d plotfiles from the dustcollapse problem
! and output the position of the interface as a function of time.
!
! The initial dense sphere is assumed to be centered a r = 0 (x = 0).
! We take as default that it is centered vertically at y = 0, but
! this can be overridden with --yctr.
!
! The --profile option will write out the average density vs. radius
! profile to a file (plotfile name + '.profile')
subroutine fdustcollapse1d(lo, hi, p, plo, phi, nc_p, nbins, dens, &
imask, mask_size, r1, dens_comp, cnt) bind(C, name='fdustcollapse1d')
use amrex_fort_module, only : rt => amrex_real
implicit none
integer, intent(in) :: lo(3), hi(3)
integer, intent(in) :: plo(3), phi(3), nc_p
integer, intent(in), value :: nbins
real(rt), intent(in) :: p(plo(1):phi(1),plo(2):phi(2),plo(3):phi(3),0:nc_p-1)
real(rt), intent(inout) :: dens(0:nbins-1)
integer, intent(inout) :: imask(0:mask_size-1)
integer, intent(in), value :: mask_size, r1, dens_comp
integer, intent(inout) :: cnt
integer :: i, j, k
! loop over all of the zones in the patch. Here, we convert
! the cell-centered indices at the current level into the
! corresponding RANGE on the finest level, and test if we've
! stored data in any of those locations. If we haven't then
! we store this level's data and mark that range as filled.
j = lo(2)
k = lo(3)
do i = lo(1), hi(1)
if (any(imask(i*r1:(i+1)*r1-1) .eq. 1)) then
dens(cnt) = p(i,j,k,dens_comp)
imask(i*r1:(i+1)*r1-1) = 0
cnt = cnt + 1
end if
enddo
end subroutine fdustcollapse1d
subroutine fdustcollapse2d(lo, hi, p, plo, phi, nc_p, nbins, dens, &
volcount, imask, mask_size, r1, dx, dx_fine, yctr, dens_comp) &
bind(C, name='fdustcollapse2d')
use amrex_fort_module, only : rt => amrex_real
implicit none
integer, intent(in) :: lo(3), hi(3)
integer, intent(in) :: plo(3), phi(3), nc_p
integer, intent(in), value :: nbins
real(rt), intent(in) :: p(plo(1):phi(1),plo(2):phi(2),plo(3):phi(3),0:nc_p-1)
real(rt), intent(inout) :: dens(0:nbins-1)
real(rt), intent(inout) :: volcount(0:nbins-1)
integer, intent(inout) :: imask(0:mask_size-1,0:mask_size-1)
integer, intent(in), value :: mask_size, r1, dens_comp
real(rt), intent(in) :: dx(3)
real(rt), intent(in), value :: yctr, dx_fine
integer :: i, j, k, index
real(rt) :: xx, xl, xr, yy, yl, yr, r_zone, vol
! loop over all of the zones in the patch. Here, we convert
! the cell-centered indices at the current level into the
! corresponding RANGE on the finest level, and test if we've
! stored data in any of those locations. If we haven't then
! we store this level's data and mark that range as filled.
k = lo(3)
do j = lo(2), hi(2)
yy = (dble(j) + 0.5d0)*dx(2)
yl = (dble(j))*dx(2)
yr = (dble(j) + 1.d0)*dx(2)
do i = lo(1), hi(1)
xx = (dble(i) + 0.5d0)*dx(1)
xl = (dble(i))*dx(1)
xr = (dble(i) + 1.d0)*dx(1)
if ( any(imask(i*r1:(i+1)*r1-1, &
j*r1:(j+1)*r1-1) .eq. 1) ) then
r_zone = sqrt((xx)**2 + (yy-yctr)**2)
index = r_zone/dx_fine
vol = (xr**2 - xl**2)*(yr - yl)
! weight the zone's data by its size
dens(index) = dens(index) + p(i,j,k,dens_comp) * vol
volcount(index) = volcount(index) + vol
imask(i*r1:(i+1)*r1-1, &
j*r1:(j+1)*r1-1) = 0
end if
enddo
enddo
end subroutine fdustcollapse2d
subroutine fdustcollapse3d(lo, hi, p, plo, phi, nc_p, nbins, dens, &
ncount, imask, mask_size, r1, dx, dx_fine, xctr, yctr, zctr, dens_comp) &
bind(C, name='fdustcollapse3d')
use amrex_fort_module, only : rt => amrex_real
implicit none
integer, intent(in) :: lo(3), hi(3)
integer, intent(in) :: plo(3), phi(3), nc_p
integer, intent(in), value :: nbins
real(rt), intent(in) :: p(plo(1):phi(1),plo(2):phi(2),plo(3):phi(3),0:nc_p-1)
real(rt), intent(inout) :: dens(0:nbins-1)
real(rt), intent(inout) :: ncount(0:nbins-1)
integer, intent(inout) :: imask(0:mask_size-1,0:mask_size-1,0:mask_size-1)
integer, intent(in), value :: mask_size, r1, dens_comp
real(rt), intent(in) :: dx(3)
real(rt), intent(in), value :: xctr, yctr, zctr, dx_fine
integer :: i, j, k, index
real(rt) :: xx, yy, zz, r_zone
! loop over all of the zones in the patch. Here, we convert
! the cell-centered indices at the current level into the
! corresponding RANGE on the finest level, and test if we've
! stored data in any of those locations. If we haven't then
! we store this level's data and mark that range as filled.
do k = lo(3), hi(3)
zz = (dble(k) + 0.5d0)*dx(3)
do j = lo(2), hi(2)
yy = (dble(j) + 0.5d0)*dx(2)
do i = lo(1), hi(1)
xx = (dble(i) + 0.5d0)*dx(1)
if ( any(imask(i*r1:(i+1)*r1-1, &
j*r1:(j+1)*r1-1, &
k*r1:(k+1)*r1-1) .eq. 1) ) then
r_zone = sqrt((xx-xctr)**2 + (yy-yctr)**2 + (zz-zctr)**2)
index = r_zone/dx_fine
! weight the zone's data by its size
dens(index) = dens(index) + p(i,j,k,dens_comp)*r1**3
ncount(index) = ncount(index) + r1**3
imask(i*r1:(i+1)*r1-1, &
j*r1:(j+1)*r1-1, &
k*r1:(k+1)*r1-1) = 0
end if
enddo
enddo
enddo
end subroutine fdustcollapse3d
| 3,143
|
https://github.com/221B-io/databrary.org/blob/master/client/src/components/pam/Projects.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
databrary.org
|
221B-io
|
Vue
|
Code
| 79
| 444
|
<template>
<q-list>
<q-expansion-item
group="bookmarks"
expand-separator
default-opened
>
<template v-slot:header>
<q-item-section avatar>
<q-icon color="primary" name="art_track" />
</q-item-section>
<q-item-section class="text-bold">
Pages
</q-item-section>
<q-item-section side>
<q-icon
name="add_circle_outline"
@click.stop="$emit('update:createAssetType', 'project')"
/>
</q-item-section>
</template>
<q-item
clickable
v-ripple
v-for="project in projects"
:key="project.id"
@click="$emit('update:selectedProject', project.id)"
:active="selectedProject == project.id"
active-class="bg-teal-1 text-grey-8"
class="col-12 q-pl-md"
>
<q-item-section avatar>
<q-icon color="primary" name="preview" />
</q-item-section>
<q-item-section>
<q-item-label lines="1">{{project.name}}</q-item-label>
</q-item-section>
</q-item>
</q-expansion-item>
</q-list>
</template>
<script>
import _ from 'lodash'
export default {
name: 'PageIndex',
props: [
'createAssetType',
'selectedProject',
'projects'
]
}
</script>
| 398
|
https://github.com/PeerHerholz/guideline_jupyter_book/blob/master/venv/Lib/site-packages/nbdime/tests/test_merge_notebooks_inline.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
guideline_jupyter_book
|
PeerHerholz
|
Python
|
Code
| 4,479
| 12,588
|
# coding: utf-8
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import pytest
import nbformat
from nbformat.v4 import new_notebook, new_code_cell
from collections import defaultdict
from nbdime import merge_notebooks, diff
from nbdime.diff_format import op_patch
from nbdime.utils import Strategies
from nbdime.merging.generic import decide_merge, decide_merge_with_diff
from nbdime.merging.decisions import apply_decisions
from nbdime.merging.strategies import _cell_marker_format
from .utils import outputs_to_notebook, sources_to_notebook
def test_decide_merge_strategy_fail(reset_log):
"""Check that "fail" strategy results in proper exception raised."""
# One level dict
base = {"foo": 1}
local = {"foo": 2}
remote = {"foo": 3}
strategies = Strategies({"/foo": "fail"})
with pytest.raises(RuntimeError):
# pylint: disable=unused-variable
conflicted_decisions = decide_merge(base, local, remote, strategies)
# Nested dicts
base = {"foo": {"bar": 1}}
local = {"foo": {"bar": 2}}
remote = {"foo": {"bar": 3}}
strategies = Strategies({"/foo/bar": "fail"})
with pytest.raises(RuntimeError):
# pylint: disable=unused-variable
decisions = decide_merge(base, local, remote, strategies)
# We don't need this for non-leaf nodes and it's currently not implemented
# strategies = Strategies({"/foo": "fail"})
# with pytest.raises(RuntimeError):
# decisions = decide_merge(base, local, remote, strategies)
def test_decide_merge_strategy_clear1():
"""Check strategy "clear" in various cases."""
# One level dict, clearing item value (think foo==execution_count)
base = {"foo": 1}
local = {"foo": 2}
remote = {"foo": 3}
strategies = Strategies({"/foo": "clear"})
decisions = decide_merge(base, local, remote, strategies)
assert apply_decisions(base, decisions) == {"foo": None}
assert not any([d.conflict for d in decisions])
def test_decide_merge_strategy_clear2():
base = {"foo": "1"}
local = {"foo": "2"}
remote = {"foo": "3"}
strategies = Strategies({"/foo": "clear"})
decisions = decide_merge(base, local, remote, strategies)
#assert decisions == []
assert apply_decisions(base, decisions) == {"foo": ""}
assert not any([d.conflict for d in decisions])
# We don't need this for non-leaf nodes and it's currently not implemented
# base = {"foo": [1]}
# local = {"foo": [2]}
# remote = {"foo": [3]}
# strategies = Strategies({"/foo": "clear"})
# decisions = decide_merge(base, local, remote, strategies)
# assert apply_decisions(base, decisions) == {"foo": []}
# assert not any([d.conflict for d in decisions])
def test_decide_merge_strategy_clear_all():
base = {"foo": [1, 2]}
local = {"foo": [1, 4, 2]}
remote = {"foo": [1, 3, 2]}
strategies = Strategies({"/foo": "clear-all"})
decisions = decide_merge(base, local, remote, strategies)
assert apply_decisions(base, decisions) == {"foo": []}
base = {"foo": [1, 2]}
local = {"foo": [1, 4, 2]}
remote = {"foo": [1, 2, 3]}
strategies = Strategies({"/foo": "clear-all"})
decisions = decide_merge(base, local, remote, strategies)
assert apply_decisions(base, decisions) == {"foo": [1, 4, 2, 3]}
def test_decide_merge_strategy_remove():
base = {"foo": [1, 2]}
local = {"foo": [1, 4, 2]}
remote = {"foo": [1, 3, 2]}
strategies = Strategies({"/foo": "remove"})
decisions = decide_merge(base, local, remote, strategies)
assert apply_decisions(base, decisions) == {"foo": [1, 2]}
assert decisions[0].local_diff != []
assert decisions[0].remote_diff != []
strategies = Strategies({})
decisions = decide_merge(base, local, remote, strategies)
assert apply_decisions(base, decisions) == {"foo": [1, 2]}
assert decisions[0].local_diff != []
assert decisions[0].remote_diff != []
def test_decide_merge_strategy_use_foo_on_dict_items():
base = {"foo": 1}
local = {"foo": 2}
remote = {"foo": 3}
strategies = Strategies({"/foo": "use-base"})
decisions = decide_merge(base, local, remote, strategies)
assert not any([d.conflict for d in decisions])
assert apply_decisions(base, decisions) == {"foo": 1}
strategies = Strategies({"/foo": "use-local"})
decisions = decide_merge(base, local, remote, strategies)
assert not any([d.conflict for d in decisions])
assert apply_decisions(base, decisions) == {"foo": 2}
strategies = Strategies({"/foo": "use-remote"})
decisions = decide_merge(base, local, remote, strategies)
assert not any([d.conflict for d in decisions])
assert apply_decisions(base, decisions) == {"foo": 3}
base = {"foo": {"bar": 1}}
local = {"foo": {"bar": 2}}
remote = {"foo": {"bar": 3}}
strategies = Strategies({"/foo/bar": "use-base"})
decisions = decide_merge(base, local, remote, strategies)
assert not any([d.conflict for d in decisions])
assert apply_decisions(base, decisions) == {"foo": {"bar": 1}}
strategies = Strategies({"/foo/bar": "use-local"})
decisions = decide_merge(base, local, remote, strategies)
assert not any([d.conflict for d in decisions])
assert apply_decisions(base, decisions) == {"foo": {"bar": 2}}
strategies = Strategies({"/foo/bar": "use-remote"})
decisions = decide_merge(base, local, remote, strategies)
assert not any([d.conflict for d in decisions])
assert apply_decisions(base, decisions) == {"foo": {"bar": 3}}
def test_decide_merge_simple_list_insert_conflict_resolution():
# local and remote adds an entry each
b = [1]
l = [1, 2]
r = [1, 3]
strategies = Strategies({"/*": "use-local"})
decisions = decide_merge(b, l, r, strategies)
assert apply_decisions(b, decisions) == l
assert not any(d.conflict for d in decisions)
strategies = Strategies({"/*": "use-remote"})
decisions = decide_merge(b, l, r, strategies)
assert apply_decisions(b, decisions) == r
assert not any(d.conflict for d in decisions)
strategies = Strategies({"/*": "use-base"})
decisions = decide_merge(b, l, r, strategies)
assert apply_decisions(b, decisions) == b
assert not any(d.conflict for d in decisions)
strategies = Strategies({"/": "clear-all"})
decisions = decide_merge(b, l, r, strategies)
assert apply_decisions(b, decisions) == []
assert not any(d.conflict for d in decisions)
@pytest.mark.skip
def test_decide_merge_simple_list_insert_conflict_resolution__union():
# local and remote adds an entry each
b = [1]
l = [1, 2]
r = [1, 3]
strategies = Strategies({"/": "union"})
decisions = decide_merge(b, l, r, strategies)
assert apply_decisions(b, decisions) == [1, 2, 3]
assert not any(d.conflict for d in decisions)
def test_decide_merge_list_conflicting_insertions_separate_chunks_v1():
# local and remote adds an equal entry plus a different entry each
# First, test when insertions DO NOT chunk together:
b = [1, 9]
l = [1, 2, 9, 11]
r = [1, 3, 9, 11]
# Check strategyless resolution
strategies = Strategies({})
resolved = decide_merge(b, l, r, strategies)
expected_partial = [1, 9, 11]
assert apply_decisions(b, resolved) == expected_partial
assert len(resolved) == 2
assert resolved[0].conflict
assert not resolved[1].conflict
strategies = Strategies({"/*": "use-local"})
resolved = decide_merge(b, l, r, strategies)
assert apply_decisions(b, resolved) == l
assert not any(d.conflict for d in resolved)
strategies = Strategies({"/*": "use-remote"})
resolved = decide_merge(b, l, r, strategies)
assert apply_decisions(b, resolved) == r
assert not any(d.conflict for d in resolved)
strategies = Strategies({"/*": "use-base"})
resolved = decide_merge(b, l, r, strategies)
# Strategy is only applied to conflicted decisions:
assert apply_decisions(b, resolved) == expected_partial
assert not any(d.conflict for d in resolved)
strategies = Strategies({"/": "clear-all"})
resolved = decide_merge(b, l, r, strategies)
assert apply_decisions(b, resolved) == []
assert not any(d.conflict for d in resolved)
# from _merge_concurrent_inserts:
# FIXME: This function doesn't work out so well with new conflict handling,
# when an insert (e.g. [2,7] vs [3,7]) gets split into agreement on [7] and
# conflict on [2] vs [3], the ordering gets lost. I think this was always
# slightly ambiguous in the decision format, as the new inserts will get
# the same key and decisions are supposed to be possible to reorder (sort)
# without considering original ordering of decisions. To preserve the
# ordering, perhaps we can add relative local/remote indices to the decisions?
# We had this, where ordering made it work out correctly:
# "conflicting insert [2] vs [3] at 1 (base index);
# insert [7] at 1 (base index)"
# instead we now have this which messes up the ordering:
# "insert [7] at 1 (base index);
# conflicting insert [2] vs [3] at 1 (base index)"
# perhaps change to this:
# "insert [7] at key=1 (base index) lkey=1 rkey=1;
# conflicting insert [2] vs [3] at key=1 (base index) lkey=0 rkey=0"
# then decisions can be sorted on (key,lkey) or (key,rkey) depending on chosen side.
# This test covers the behaviour:
# py.test -k test_shallow_merge_lists_insert_conflicted -s -vv
#DEBUGGING = 1
#if DEBUGGING: import ipdb; ipdb.set_trace()
# Example:
# b l r
# 1 a x
# 2 b y
# 3 c 3
# 4 4 4
# Diffs:
# b/l: insert a, b, c; remove 1-3
# b/r: insert x, y; remove 1-2
# The current chunking splits the removes here:
# [insert a, b, c; remove 1-2]; [remove 3]
# [insert x, y; remove 1-2]
# That results in remove 3 not being conflicted.
def test_decide_merge_list_conflicting_insertions_separate_chunks_v2():
# local and remote adds an equal entry plus a different entry each
# First, test when insertions DO NOT chunk together:
b = [1, 9]
l = [1, 2, 9, 11]
r = [1, 3, 9, 11]
# Check strategyless resolution
strategies = Strategies({})
resolved = decide_merge(b, l, r, strategies)
expected_partial = [1, 9, 11]
assert apply_decisions(b, resolved) == expected_partial
assert len(resolved) == 2
assert resolved[0].conflict
assert not resolved[1].conflict
@pytest.mark.skip
def test_decide_merge_list_conflicting_insertions_separate_chunks__union():
# local and remote adds an equal entry plus a different entry each
# First, test when insertions DO NOT chunk together:
b = [1, 9]
l = [1, 2, 9, 11]
r = [1, 3, 9, 11]
strategies = Strategies({"/": "union"})
resolved = decide_merge(b, l, r, strategies)
assert apply_decisions(b, resolved) == [1, 2, 3, 9, 11]
assert not any(d.conflict for d in resolved)
def test_decide_merge_list_conflicting_insertions_in_chunks():
# Next, test when insertions DO chunk together:
b = [1, 9]
l = [1, 2, 7, 9]
r = [1, 3, 7, 9]
# Check strategyless resolution
strategies = Strategies({})
resolved = decide_merge(b, l, r, strategies)
expected_partial = [1, 7, 9]
assert apply_decisions(b, resolved) == expected_partial
strategies = Strategies({"/*": "use-local"})
resolved = decide_merge(b, l, r, strategies)
assert apply_decisions(b, resolved) == l
assert not any(d.conflict for d in resolved)
strategies = Strategies({"/*": "use-remote"})
resolved = decide_merge(b, l, r, strategies)
assert apply_decisions(b, resolved) == r
assert not any(d.conflict for d in resolved)
strategies = Strategies({"/*": "use-base"})
resolved = decide_merge(b, l, r, strategies)
assert apply_decisions(b, resolved) == expected_partial
assert not any(d.conflict for d in resolved)
strategies = Strategies({"/": "clear-all"})
resolved = decide_merge(b, l, r, strategies)
assert apply_decisions(b, resolved) == []
assert not any(d.conflict for d in resolved)
@pytest.mark.skip
def test_decide_merge_list_conflicting_insertions_in_chunks__union():
# Next, test when insertions DO chunk together:
b = [1, 9]
l = [1, 2, 7, 9]
r = [1, 3, 7, 9]
strategies = Strategies({"/": "union"})
resolved = decide_merge(b, l, r, strategies)
assert apply_decisions(b, resolved) == [1, 2, 3, 7, 9]
assert not any(d.conflict for d in resolved)
def test_decide_merge_list_transients():
# For this test, we need to use a custom predicate to ensure alignment
common = {'id': 'This ensures alignment'}
predicates = defaultdict(lambda: [operator.__eq__], {
'/': [lambda a, b: a['id'] == b['id']],
})
# Setup transient difference in base and local, deletion in remote
b = [{'transient': 22}]
l = [{'transient': 242}]
b[0].update(common)
l[0].update(common)
r = []
# Make decisions based on diffs with predicates
ld = diff(b, l, path="", predicates=predicates)
rd = diff(b, r, path="", predicates=predicates)
# Assert that generic merge without strategies gives conflict:
strategies = Strategies()
decisions = decide_merge_with_diff(b, l, r, ld, rd, strategies)
assert len(decisions) == 1
assert decisions[0].conflict
assert apply_decisions(b, decisions) == b
# Supply transient list to autoresolve, and check that transient is ignored
strategies = Strategies(transients=[
'/*/transient'
])
decisions = decide_merge_with_diff(b, l, r, ld, rd, strategies)
assert apply_decisions(b, decisions) == r
assert not any(d.conflict for d in decisions)
def test_decide_merge_dict_transients():
# Setup transient difference in base and local, deletion in remote
b = {'a': {'transient': 22}}
l = {'a': {'transient': 242}}
r = {}
# Assert that generic merge gives conflict
strategies = Strategies()
decisions = decide_merge(b, l, r, strategies)
assert apply_decisions(b, decisions) == b
assert len(decisions) == 1
assert decisions[0].conflict
# Supply transient list to autoresolve, and check that transient is ignored
strategies = Strategies(transients=[
'/a/transient'
])
decisions = decide_merge(b, l, r, strategies)
assert apply_decisions(b, decisions) == r
assert not any(d.conflict for d in decisions)
def test_decide_merge_mixed_nested_transients():
# For this test, we need to use a custom predicate to ensure alignment
common = {'id': 'This ensures alignment'}
predicates = defaultdict(lambda: [operator.__eq__], {
'/': [lambda a, b: a['id'] == b['id']],
})
# Setup transient difference in base and local, deletion in remote
b = [{'a': {'transient': 22}}]
l = [{'a': {'transient': 242}}]
b[0].update(common)
l[0].update(common)
r = []
# Make decisions based on diffs with predicates
ld = diff(b, l, path="", predicates=predicates)
rd = diff(b, r, path="", predicates=predicates)
# Assert that generic merge gives conflict
strategies = Strategies()
decisions = decide_merge_with_diff(b, l, r, ld, rd, strategies)
assert apply_decisions(b, decisions) == b
assert len(decisions) == 1
assert decisions[0].conflict
# Supply transient list to autoresolve, and check that transient is ignored
strategies = Strategies(transients=[
'/*/a/transient'
])
decisions = decide_merge_with_diff(b, l, r, ld, rd, strategies)
assert apply_decisions(b, decisions) == r
assert not any(d.conflict for d in decisions)
def test_inline_merge_empty_notebooks():
"Missing fields all around passes through."
base = {}
local = {}
remote = {}
expected = {}
merged, decisions = merge_notebooks(base, local, remote)
assert expected == merged
def test_inline_merge_dummy_notebooks():
"Just the basic empty notebook passes through."
base = new_notebook()
local = new_notebook()
remote = new_notebook()
expected = new_notebook()
merged, decisions = merge_notebooks(base, local, remote)
assert expected == merged
def test_inline_merge_notebook_version():
"Minor version gets bumped to max."
base = new_notebook(nbformat=4, nbformat_minor=0)
local = new_notebook(nbformat=4, nbformat_minor=1)
remote = new_notebook(nbformat=4, nbformat_minor=2)
expected = new_notebook(nbformat=4, nbformat_minor=2)
merged, decisions = merge_notebooks(base, local, remote)
assert expected == merged
def test_inline_merge_notebook_metadata(reset_log):
"""Merging a wide range of different value types
and conflict types in the root /metadata dicts.
The goal is to exercise a decent part of the
generic diff and merge functionality.
"""
untouched = {
"string": "untouched string",
"integer": 123,
"float": 16.0,
"list": ["hello", "world"],
"dict": {"first": "Hello", "second": "World"},
}
md_in = {
1: {
"untouched": untouched,
"unconflicted": {
"int_deleteme": 7,
"string_deleteme": "deleteme",
"list_deleteme": [7, "deleteme"],
"dict_deleteme": {"deleteme": "now", "removeme": True},
"list_deleteitem": [7, "deleteme", 3, "notme", 5, "deletemetoo"],
"string": "string v1",
"integer": 456,
"float": 32.0,
"list": ["hello", "universe"],
"dict": {"first": "Hello", "second": "World", "third": "!"},
},
"conflicted": {
"int_delete_replace": 3,
"string_delete_replace": "string that will be deleted and modified",
"list_delete_replace": [1],
"dict_delete_replace": {"k":"v"},
# "string": "string v1",
# "integer": 456,
# "float": 32.0,
# "list": ["hello", "universe"],
# "dict": {"first": "Hello", "second": "World"},
}
},
2: {
"untouched": untouched,
"unconflicted": {
"dict_deleteme": {"deleteme": "now", "removeme": True},
"list_deleteitem": [7, 3, "notme", 5, "deletemetoo"],
"string": "string v1 equal addition",
"integer": 123, # equal change
"float": 16.0, # equal change
# Equal delete at beginning and insert of two values at end:
"list": ["universe", "new items", "same\non\nboth\nsides"],
# cases covered: twosided equal value change, onesided delete, onesided replace, onesided insert, twosided insert of same value
"dict": {"first": "changed", "second": "World", "third": "!", "newkey": "newvalue", "otherkey": "othervalue"},
},
"conflicted": {
"int_delete_replace": 5,
"list_delete_replace": [2],
# "string": "another text",
#"integer": 456,
# "float": 16.0,
# "list": ["hello", "world"],
# "dict": {"new": "value", "first": "Hello"}, #"second": "World"},
# "added_string": "another text",
# "added_integer": 9,
# "added_float": 16.0,
# "added_list": ["another", "multiverse"],
# "added_dict": {"1st": "hey", "2nd": "there"},
}
},
3: {
"untouched": untouched,
"unconflicted": {
"list_deleteme": [7, "deleteme"],
"list_deleteitem": [7, "deleteme", 3, "notme", 5],
"string": "string v1 equal addition",
"integer": 123, # equal change
"float": 16.0, # equal change
# Equal delete at beginning and insert of two values at end:
"list": ["universe", "new items", "same\non\nboth\nsides"],
"dict": {"first": "changed", "third": ".", "newkey": "newvalue"},
},
"conflicted": {
"string_delete_replace": "string that is modified here and deleted in the other version",
"dict_delete_replace": {"k":"x","q":"r"},
# "string": "different message",
# "integer": 456,
# #"float": 16.0,
# "list": ["hello", "again", "world"],
# "dict": {"new": "but different", "first": "Hello"}, #"second": "World"},
# "added_string": "but not the same string",
# #"added_integer": 9,
# "added_float": 64.0,
# "added_list": ["initial", "values", "another", "multiverse", "trailing", "values"],
# "added_dict": {"3rt": "mergeme", "2nd": "conflict"},
}
}
}
def join_dicts(dicta, dictb):
d = {}
d.update(dicta)
d.update(dictb)
return d
shared_unconflicted = {
"list_deleteitem": [7, 3, "notme", 5],
"string": "string v1 equal addition",
"integer": 123,
"float": 16.0,
"list": ["universe", "new items", "same\non\nboth\nsides"],
"dict": {"first": "changed", "third": ".", "newkey": "newvalue", "otherkey": "othervalue"},
}
shared_conflicted = {
"int_delete_replace": 3,
"string_delete_replace": "string that will be deleted and modified",
"list_delete_replace": [1],
"dict_delete_replace": {"k":"v"},
# #"string": "string v1",
# "string": "another textdifferent message",
# "float": 32.0,
# "list": ["hello", "universe"],
# "dict": {"first": "Hello", "second": "World"},
# # FIXME
}
md_out = {
(1,2,3): {
"untouched": untouched,
"unconflicted": join_dicts(shared_unconflicted, {
# ...
}),
"conflicted": join_dicts(shared_conflicted, {
# ...
}),
},
(1,3,2): {
"untouched": untouched,
"unconflicted": join_dicts(shared_unconflicted, {
# ...
}),
"conflicted": join_dicts(shared_conflicted, {
# ...
}),
},
}
# Fill in expected conflict records
for triplet in sorted(md_out.keys()):
i, j, k = triplet
local_diff = diff(md_in[i]["conflicted"], md_in[j]["conflicted"])
remote_diff = diff(md_in[i]["conflicted"], md_in[k]["conflicted"])
# This may not be a necessary test, just checking my expectations
assert local_diff == sorted(local_diff, key=lambda x: x.key)
assert remote_diff == sorted(remote_diff, key=lambda x: x.key)
c = {
# These are patches on the /metadata dict
"local_diff": [op_patch("conflicted", local_diff)],
"remote_diff": [op_patch("conflicted", remote_diff)],
}
md_out[triplet]["nbdime-conflicts"] = c
# Fill in the trivial merge results
for i in (1, 2, 3):
for j in (1, 2, 3):
for k in (i, j):
# For any combination i,j,i or i,j,j the
# result should be j with no conflicts
md_out[(i,j,k)] = md_in[j]
tested = set()
# Check the trivial merge results
for i in (1, 2, 3):
for j in (1, 2, 3):
for k in (i, j):
triplet = (i, j, k)
tested.add(triplet)
base = new_notebook(metadata=md_in[i])
local = new_notebook(metadata=md_in[j])
remote = new_notebook(metadata=md_in[k])
# For any combination i,j,i or i,j,j the result should be j
expected = new_notebook(metadata=md_in[j])
merged, decisions = merge_notebooks(base, local, remote)
assert "nbdime-conflicts" not in merged["metadata"]
assert not any([d.conflict for d in decisions])
assert expected == merged
# Check handcrafted merge results
for triplet in sorted(md_out.keys()):
i, j, k = triplet
tested.add(triplet)
base = new_notebook(metadata=md_in[i])
local = new_notebook(metadata=md_in[j])
remote = new_notebook(metadata=md_in[k])
expected = new_notebook(metadata=md_out[triplet])
merged, decisions = merge_notebooks(base, local, remote)
if "nbdime-conflicts" in merged["metadata"]:
assert any([d.conflict for d in decisions])
else:
assert not any([d.conflict for d in decisions])
assert expected == merged
# At least try to run merge without crashing for permutations
# of md_in that we haven't constructed expected results for
for i in (1, 2, 3):
for j in (1, 2, 3):
for k in (1, 2, 3):
triplet = (i, j, k)
if triplet not in tested:
base = new_notebook(metadata=md_in[i])
local = new_notebook(metadata=md_in[j])
remote = new_notebook(metadata=md_in[k])
merged, decisions = merge_notebooks(base, local, remote)
def test_inline_merge_notebook_metadata_reproduce_bug(reset_log):
md_in = {
1: {
"unconflicted": {
"list_deleteitem": [7, "deleteme", 3, "notme", 5, "deletemetoo"],
},
"conflicted": {
"dict_delete_replace": {"k":"v"},
}
},
2: {
"unconflicted": {
"list_deleteitem": [7, 3, "notme", 5, "deletemetoo"],
},
"conflicted": {
}
},
3: {
"unconflicted": {
"list_deleteitem": [7, "deleteme", 3, "notme", 5],
},
"conflicted": {
"dict_delete_replace": {"k":"x"},
}
}
}
shared_unconflicted = {
"list_deleteitem": [7, 3, "notme", 5],
}
shared_conflicted = {
"dict_delete_replace": {"k":"v"},
}
md_out = {
(1,2,3): {
"unconflicted": shared_unconflicted,
"conflicted": shared_conflicted
},
}
# Fill in expected conflict records
for triplet in sorted(md_out.keys()):
i, j, k = triplet
local_diff = diff(md_in[i]["conflicted"], md_in[j]["conflicted"])
remote_diff = diff(md_in[i]["conflicted"], md_in[k]["conflicted"])
# This may not be a necessary test, just checking my expectations
assert local_diff == sorted(local_diff, key=lambda x: x.key)
assert remote_diff == sorted(remote_diff, key=lambda x: x.key)
c = {
# These are patches on the /metadata dict
"local_diff": [op_patch("conflicted", local_diff)],
"remote_diff": [op_patch("conflicted", remote_diff)],
}
md_out[triplet]["nbdime-conflicts"] = c
# Check handcrafted merge results
triplet = (1,2,3)
i, j, k = triplet
base = new_notebook(metadata=md_in[i])
local = new_notebook(metadata=md_in[j])
remote = new_notebook(metadata=md_in[k])
expected = new_notebook(metadata=md_out[triplet])
merged, decisions = merge_notebooks(base, local, remote)
if "nbdime-conflicts" in merged["metadata"]:
assert any([d.conflict for d in decisions])
else:
assert not any([d.conflict for d in decisions])
assert expected == merged
def test_inline_merge_source_empty():
base = new_notebook()
local = new_notebook()
remote = new_notebook()
expected = new_notebook()
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
def code_nb(sources):
return new_notebook(cells=[new_code_cell(s) for s in sources])
def test_inline_merge_source_all_equal():
base = code_nb([
"first source",
"other text",
"yet more content",
])
local = base
remote = base
expected = base
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
def test_inline_merge_source_cell_deletions():
"Cell deletions on both sides, onesided and agreed."
base = code_nb([
"first source",
"other text",
"yet more content",
"and a final line",
])
local = code_nb([
#"first source",
"other text",
#"yet more content",
#"and a final line",
])
remote = code_nb([
"first source",
#"other text",
"yet more content",
#"and a final line",
])
empty = code_nb([])
for a in [base, local, remote, empty]:
for b in [base, local, remote, empty]:
merged, decisions = merge_notebooks(base, a, b)
if a is b:
assert merged == a
elif a is base:
assert merged == b
elif b is base:
assert merged == a
else:
# All other combinations will delete all cells
assert merged == empty
def test_inline_merge_source_onesided_only():
"A mix of changes on one side (delete, patch, remove)."
base = code_nb([
"first source",
"other text",
"yet more content",
])
changed = code_nb([
#"first source", # deleted
"other text v2",
"a different cell inserted",
"yet more content",
])
merged, decisions = merge_notebooks(base, changed, base)
assert merged == changed
merged, decisions = merge_notebooks(base, base, changed)
assert merged == changed
def test_inline_merge_source_replace_line():
"More elaborate test of cell deletions on both sides, onesided and agreed."
# Note: Merge rendering of conflicted sources here will depend on git/diff/builtin params and availability
base = code_nb([
"first source",
"other text",
"this cell will be deleted and patched",
"yet more content",
"and a final line",
])
local = code_nb([
"1st source", # onesided change
"other text",
#"this cell will be deleted and patched",
"some more content", # twosided equal change
"And a Final line", # twosided conflicted change
])
remote = code_nb([
"first source",
"other text?", # onesided change
"this cell will be deleted and modified",
"some more content", # equal
"and The final Line", # conflicted
])
expected = code_nb([
"1st source",
"other text?",
#'<<<<<<< local <CELL DELETED>\n\n=======\nthis cell will be deleted and modified\n>>>>>>> remote'
'<<<<<<< LOCAL CELL DELETED >>>>>>>\nthis cell will be deleted and modified',
"some more content", # equal
'<<<<<<< local\nAnd a Final line\n=======\nand The final Line\n>>>>>>> remote'
])
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
expected = code_nb([
"1st source",
"other text?",
#'<<<<<<< local\nthis cell will be deleted and modified\n=======\n>>>>>>> remote <CELL DELETED>'
'<<<<<<< REMOTE CELL DELETED >>>>>>>\nthis cell will be deleted and modified',
"some more content",
'<<<<<<< local\nand The final Line\n=======\nAnd a Final line\n>>>>>>> remote'
])
merged, decisions = merge_notebooks(base, remote, local)
assert merged == expected
def test_inline_merge_source_add_to_line():
"More elaborate test of cell deletions on both sides, onesided and agreed."
# Note: Merge rendering of conflicted sources here will depend on git/diff/builtin params and availability
base = code_nb([
"first source",
"other text",
"this cell will be deleted and patched\nhere we add",
"yet more content",
"and a final line",
])
local = code_nb([
"1st source", # onesided change
"other text",
#"this cell will be deleted and patched",
"some more content", # twosided equal change
"And a Final line", # twosided conflicted change
])
remote = code_nb([
"first source",
"other text?", # onesided change
"this cell will be deleted and patched\nhere we add text to a line",
"some more content", # equal
"and The final Line", # conflicted
])
expected = code_nb([
"1st source",
"other text?",
#'<<<<<<< local <CELL DELETED>\n\n=======\nthis cell will be deleted and modified\n>>>>>>> remote'
'<<<<<<< LOCAL CELL DELETED >>>>>>>\nthis cell will be deleted and patched\nhere we add text to a line',
"some more content", # equal
'<<<<<<< local\nAnd a Final line\n=======\nand The final Line\n>>>>>>> remote'
])
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
expected = code_nb([
"1st source",
"other text?",
#'<<<<<<< local\nthis cell will be deleted and modified\n=======\n>>>>>>> remote <CELL DELETED>'
'<<<<<<< REMOTE CELL DELETED >>>>>>>\nthis cell will be deleted and patched\nhere we add text to a line',
"some more content",
'<<<<<<< local\nand The final Line\n=======\nAnd a Final line\n>>>>>>> remote'
])
merged, decisions = merge_notebooks(base, remote, local)
assert merged == expected
def test_inline_merge_source_patches_both_ends():
"More elaborate test of cell deletions on both sides, onesided and agreed."
# Note: Merge rendering of conflicted sources here will depend on git/diff/builtin params and availability
base = code_nb([
"first source will be modified",
"other text",
"this cell will be untouched",
"yet more content",
"and final line will be changed",
])
local = code_nb([
"first source will be modified locally",
"other text",
"this cell will be untouched",
"yet more content",
"and final line will be changed locally",
])
remote = code_nb([
"first source will be modified remotely",
"other text",
"this cell will be untouched",
"yet more content",
"and final line will be changed remotely",
])
expected = code_nb([
'<<<<<<< local\nfirst source will be modified locally\n=======\nfirst source will be modified remotely\n>>>>>>> remote',
"other text",
"this cell will be untouched",
"yet more content",
'<<<<<<< local\nand final line will be changed locally\n=======\nand final line will be changed remotely\n>>>>>>> remote',
])
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
expected = code_nb([
'<<<<<<< local\nfirst source will be modified remotely\n=======\nfirst source will be modified locally\n>>>>>>> remote',
"other text",
"this cell will be untouched",
"yet more content",
'<<<<<<< local\nand final line will be changed remotely\n=======\nand final line will be changed locally\n>>>>>>> remote',
])
merged, decisions = merge_notebooks(base, remote, local)
assert merged == expected
def test_inline_merge_source_patch_delete_conflicts_both_ends():
"More elaborate test of cell deletions on both sides, onesided and agreed."
# Note: Merge rendering of conflicted sources here will depend on git/diff/builtin params and availability
base = code_nb([
"first source will be modified",
"other text",
"this cell will be untouched",
"yet more content",
"and final line will be changed",
])
local = code_nb([
"first source will be modified on one side",
"other text",
"this cell will be untouched",
"yet more content",
#"and final line will be deleted locally",
])
remote = code_nb([
#"first source will be deleted remotely",
"other text",
"this cell will be untouched",
"yet more content",
"and final line will be changed on one side",
])
expected = code_nb([
'<<<<<<< REMOTE CELL DELETED >>>>>>>\nfirst source will be modified on one side',
"other text",
"this cell will be untouched",
"yet more content",
'<<<<<<< LOCAL CELL DELETED >>>>>>>\nand final line will be changed on one side',
])
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
expected = code_nb([
'<<<<<<< LOCAL CELL DELETED >>>>>>>\nfirst source will be modified on one side',
"other text",
"this cell will be untouched",
"yet more content",
'<<<<<<< REMOTE CELL DELETED >>>>>>>\nand final line will be changed on one side',
])
merged, decisions = merge_notebooks(base, remote, local)
assert merged == expected
def test_inline_merge_attachments():
# FIXME: Use output creation utils Vidar wrote in another test file
base = new_notebook()
local = new_notebook()
remote = new_notebook()
expected = new_notebook()
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
def test_inline_merge_outputs():
# One cell with two outputs:
base = outputs_to_notebook([['unmodified', 'base']])
local = outputs_to_notebook([['unmodified', 'local']])
remote = outputs_to_notebook([['unmodified', 'remote']])
expected = outputs_to_notebook([[
'unmodified',
nbformat.v4.new_output(
output_type='stream', name='stderr',
text='<<<<<<< local <modified: text/plain>\n'),
'local',
nbformat.v4.new_output(
output_type='stream', name='stderr',
text='=======\n'),
'remote',
nbformat.v4.new_output(
output_type='stream', name='stderr',
text='>>>>>>> remote <modified: text/plain>\n'),
]])
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
def test_inline_merge_cells_insertion_similar():
base = sources_to_notebook([['unmodified']], cell_type='markdown')
local = sources_to_notebook([['unmodified'], ['local']], cell_type='markdown')
remote = sources_to_notebook([['unmodified'], ['remote']], cell_type='markdown')
expected = sources_to_notebook([
'unmodified',
[
("<"*7) + ' local\n',
'local\n',
("="*7) + '\n',
'remote\n',
(">"*7) + ' remote'
]
], cell_type='markdown')
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
def test_inline_merge_cells_insertion_unsimilar():
base = sources_to_notebook([['unmodified']], cell_type='markdown')
local = sources_to_notebook([['unmodified'], ['local\n', 'friendly faces\n', '3.14']], cell_type='markdown')
remote = sources_to_notebook([['unmodified'], ['remote\n', 'foo bar baz\n']], cell_type='markdown')
expected = sources_to_notebook([
['unmodified'],
[_cell_marker_format(("<"*7) + ' local')],
['local\n', 'friendly faces\n', '3.14'],
[_cell_marker_format("="*7)],
['remote\n', 'foo bar baz\n'],
[_cell_marker_format((">"*7) + ' remote')],
], cell_type='markdown')
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
def test_inline_merge_cells_replacement_similar():
base = sources_to_notebook([['unmodified'], ['base']], cell_type='markdown')
local = sources_to_notebook([['unmodified'], ['local']], cell_type='markdown')
remote = sources_to_notebook([['unmodified'], ['remote']], cell_type='markdown')
expected = sources_to_notebook([
['unmodified'],
[
("<"*7) + ' local\n',
'local\n',
("="*7) + '\n',
'remote\n',
(">"*7) + ' remote'
]
], cell_type='markdown')
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
def test_inline_merge_cells_replacement_unsimilar():
base = sources_to_notebook([['unmodified'], ['base']], cell_type='markdown')
local = sources_to_notebook([['unmodified'], ['local\n', 'friendly faces\n', '3.14']], cell_type='markdown')
remote = sources_to_notebook([['unmodified'], ['remote\n', 'foo bar baz\n']], cell_type='markdown')
expected = sources_to_notebook([
['unmodified'],
[_cell_marker_format(("<"*7) + ' local')],
['local\n', 'friendly faces\n', '3.14'],
[_cell_marker_format("="*7)],
['remote\n', 'foo bar baz\n'],
[_cell_marker_format((">"*7) + ' remote')],
], cell_type='markdown')
merged, decisions = merge_notebooks(base, local, remote)
assert merged == expected
| 27,095
|
https://github.com/dvsa/olcs-backend/blob/master/module/Api/src/Domain/Repository/ErruRequest.php
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
olcs-backend
|
dvsa
|
PHP
|
Code
| 84
| 310
|
<?php
/**
* Erru Request
*
* @author Ian Lindsay <ian@hemera-business-services.co.uk>
*/
namespace Dvsa\Olcs\Api\Domain\Repository;
use Doctrine\ORM\Query;
use Dvsa\Olcs\Api\Domain\Exception;
use Dvsa\Olcs\Api\Entity\Si\ErruRequest as Entity;
/**
* Erru Request
*
* @author Ian Lindsay <ian@hemera-business-services.co.uk>
*/
class ErruRequest extends AbstractRepository
{
protected $entity = Entity::class;
/**
* Returns whether erru requests exists in the database for this workflow id
*
* @param string $workflowId
* @return bool
*/
public function existsByWorkflowId($workflowId)
{
$qb = $this->createQueryBuilder();
$qb->where($qb->expr()->eq($this->alias .'.workflowId', ':workflowId'));
$qb->setParameter('workflowId', $workflowId);
$qb->setMaxResults(1);
return count($qb->getQuery()->getResult()) === 1;
}
}
| 43,434
|
https://github.com/algolia/algoliasearch-magento-2/blob/master/Test/Integration/SearchTest.php
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
algoliasearch-magento-2
|
algolia
|
PHP
|
Code
| 43
| 195
|
<?php
namespace Algolia\AlgoliaSearch\Test\Integration;
use Algolia\AlgoliaSearch\Helper\Data;
use Algolia\AlgoliaSearch\Model\Indexer\Product;
class SearchTest extends TestCase
{
public function testSearch()
{
/** @var Product $indexer */
$indexer = $this->getObjectManager()->create(Product::class);
$indexer->executeFull();
$this->algoliaHelper->waitLastTask();
/** @var Data $helper */
$helper = $this->getObjectManager()->create(Data::class);
list($results, $totalHits, $facetsFromAlgolia) = $helper->getSearchResult('', 1);
$this->assertNotEmpty($results);
}
}
| 19,041
|
https://github.com/MaSch0212/headless-web-container/blob/master/src/HeadlessWebContainer/Models/GuiSettings.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
headless-web-container
|
MaSch0212
|
C#
|
Code
| 59
| 156
|
using MaSch.Presentation.Wpf.Common;
using System.Collections.Generic;
namespace HeadlessWebContainer.Models
{
public class GuiSettings
{
public List<WindowPosition> WindowPositions { get; set; }
public bool IsTitlePinned { get; set; }
public string? BrowserWindowTitle { get; set; }
public string? BrowserHomeUrl { get; set; }
public string? IconHash { get; set; }
public GuiSettings()
{
WindowPositions = new List<WindowPosition>();
IsTitlePinned = true;
}
}
}
| 15,826
|
https://github.com/zqqq/Goku-plugin-basic-auth/blob/master/go.mod
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
Goku-plugin-basic-auth
|
zqqq
|
Go Module
|
Code
| 7
| 55
|
module github.com/eolinker/goku/app/plugins/goku-basic_auth
go 1.12
require github.com/eolinker/goku-plugin v0.1.3
| 34,232
|
https://github.com/Tomabage/easy/blob/master/docs/.vuepress/components/align-demo.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
easy
|
Tomabage
|
Vue
|
Code
| 82
| 402
|
<template>
<div class="align-wrapper">
<e-row class="row" align="left">
<e-col class="item" span="8">left</e-col>
<e-col class="item" span="8">left</e-col>
</e-row>
<e-row class="row" align="center">
<e-col class="item" span="8">center</e-col>
<e-col class="item" span="8">center</e-col>
</e-row>
<e-row class="row" align="right">
<e-col class="item" span="8">right</e-col>
<e-col class="item" span="8">right</e-col>
</e-row>
</div>
</template>
<script>
import Col from '../../../src/col'
import Row from '../../../src/row'
export default {
components:{
'e-col':Col,
'e-row':Row
}
}
</script>
<style lang="scss" scoped>
@import "../styles/helper";
.align-wrapper{
text-align: center;
color: $font-color;
.row{
padding-top: $wrapper-top;
> .item{
text-align: center;
&:nth-child(odd){
background: $background;}
&:nth-child(even){
background: lighten($background,20%);
color:$font-color;
}
}
}
}
</style>
| 27,338
|
https://github.com/smeenai/llvm-project/blob/master/lldb/source/Plugins/Process/Linux/IntelPTMultiCoreTrace.h
|
Github Open Source
|
Open Source
|
NCSA, LLVM-exception, Apache-2.0
| 2,023
|
llvm-project
|
smeenai
|
C++
|
Code
| 347
| 1,193
|
//===-- IntelPTMultiCoreTrace.h ------------------------------- -*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef liblldb_IntelPTMultiCoreTrace_H_
#define liblldb_IntelPTMultiCoreTrace_H_
#include "IntelPTProcessTrace.h"
#include "IntelPTSingleBufferTrace.h"
#include "lldb/Host/common/NativeProcessProtocol.h"
#include "lldb/Utility/TraceIntelPTGDBRemotePackets.h"
#include "lldb/lldb-types.h"
#include "llvm/Support/Error.h"
#include <memory>
#include <optional>
namespace lldb_private {
namespace process_linux {
class IntelPTMultiCoreTrace : public IntelPTProcessTrace {
using ContextSwitchTrace = PerfEvent;
public:
/// Start tracing all CPU cores.
///
/// \param[in] request
/// Intel PT configuration parameters.
///
/// \param[in] process
/// The process being debugged.
///
/// \param[in] cgroup_fd
/// A file descriptor in /sys/fs associated with the cgroup of the process to
/// trace. If not \a std::nullopt, then the trace sesion will use cgroup
/// filtering.
///
/// \return
/// An \a IntelPTMultiCoreTrace instance if tracing was successful, or
/// an \a llvm::Error otherwise.
static llvm::Expected<std::unique_ptr<IntelPTMultiCoreTrace>>
StartOnAllCores(const TraceIntelPTStartRequest &request,
NativeProcessProtocol &process,
std::optional<int> cgroup_fd = std::nullopt);
/// Execute the provided callback on each core that is being traced.
///
/// \param[in] callback.cpu_id
/// The core id that is being traced.
///
/// \param[in] callback.core_trace
/// The single-buffer trace instance for the given core.
void ForEachCore(std::function<void(lldb::cpu_id_t cpu_id,
IntelPTSingleBufferTrace &core_trace)>
callback);
/// Execute the provided callback on each core that is being traced.
///
/// \param[in] callback.cpu_id
/// The core id that is being traced.
///
/// \param[in] callback.intelpt_trace
/// The single-buffer intel pt trace instance for the given core.
///
/// \param[in] callback.context_switch_trace
/// The perf event collecting context switches for the given core.
void ForEachCore(std::function<void(lldb::cpu_id_t cpu_id,
IntelPTSingleBufferTrace &intelpt_trace,
ContextSwitchTrace &context_switch_trace)>
callback);
void ProcessDidStop() override;
void ProcessWillResume() override;
TraceIntelPTGetStateResponse GetState() override;
bool TracesThread(lldb::tid_t tid) const override;
llvm::Error TraceStart(lldb::tid_t tid) override;
llvm::Error TraceStop(lldb::tid_t tid) override;
llvm::Expected<std::optional<std::vector<uint8_t>>>
TryGetBinaryData(const TraceGetBinaryDataRequest &request) override;
private:
/// This assumes that all underlying perf_events for each core are part of the
/// same perf event group.
IntelPTMultiCoreTrace(
llvm::DenseMap<lldb::cpu_id_t,
std::pair<IntelPTSingleBufferTrace, ContextSwitchTrace>>
&&traces_per_core,
NativeProcessProtocol &process, bool using_cgroup_filtering)
: m_traces_per_core(std::move(traces_per_core)), m_process(process),
m_using_cgroup_filtering(using_cgroup_filtering) {}
llvm::DenseMap<lldb::cpu_id_t,
std::pair<IntelPTSingleBufferTrace, ContextSwitchTrace>>
m_traces_per_core;
/// The target process.
NativeProcessProtocol &m_process;
bool m_using_cgroup_filtering;
};
} // namespace process_linux
} // namespace lldb_private
#endif // liblldb_IntelPTMultiCoreTrace_H_
| 2,266
|
https://github.com/PavelPawlowski/PPSqlClr/blob/master/PP.SqlClr.Safe/Strings/StringSpliting.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
PPSqlClr
|
PavelPawlowski
|
C#
|
Code
| 659
| 1,814
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.Collections;
/// <summary>
/// Class constains functions fro string splitting
/// </summary>
public class StringSplitting
{
/// <summary>
/// represents returned row
/// </summary>
private struct StrRow
{
public StrRow(int rowId, SqlChars value)
{
RowId = rowId;
Value = value;
}
public int RowId;
public SqlChars Value;
}
private struct StrRowString
{
public StrRowString(int rowId, SqlString value)
{
RowId = rowId;
Value = value;
}
public int RowId;
public SqlString Value;
}
/// <summary>
/// Splits CSV string using specified delimiter and bufferSize
/// </summary>
/// <param name="sourceString">Source string to be split</param>
/// <param name="delimiter">Delimiter to be used to split source string</param>
/// <param name="bufferSize">Buffer size (maximum length of item)</param>
/// <returns>IEnumerable</returns>
[SqlFunction(FillRowMethodName = "FillSplitString")]
public static IEnumerable SplitStringBuffer(SqlString sourceString, SqlString delimiter, int bufferSize)
{
char[] buffer = new char[bufferSize];
char delim = delimiter.Value[0];
int rowNumber = 0;
int chars = 0;
char[] finalString;
foreach (char chr in sourceString.Value)
{
if (chr == delim)
{
finalString = new char[chars];
Array.Copy(buffer, finalString, chars);
yield return new StrRow(++rowNumber, new SqlChars(finalString));
chars = 0;
}
else
{
buffer[chars++] = chr;
}
}
if (chars > 0)
{
finalString = new char[chars];
Array.Copy(buffer, finalString, chars);
yield return new StrRow(++rowNumber, new SqlChars(finalString));
}
}
[SqlFunction(FillRowMethodName = "FillSplitStrings")]
public static IEnumerable SplitStrings([SqlFacet(MaxSize = -1)]SqlChars sourceString, [SqlFacet(MaxSize = 128)]SqlChars delimiters)
{
char[] delims = delimiters.Value;
int bufferSize = 10;
int rowNumber = 0;
int chars = 0;
char[] buffer = new char[bufferSize];
bool isDelim = false;
if (delims.Length == 1)
{
char delim = delims[0];
foreach (char chr in sourceString.Value)
{
if (chr == delim)
{
if (chars > 0)
{
yield return new StrRowString(++rowNumber, new SqlString(new string(buffer, 0, chars)));
buffer = new char[bufferSize];
chars = 0;
}
}
else
{
if (chars == bufferSize)
{
bufferSize = chars + chars / 2;
char[] newBuffer = new char[bufferSize];
buffer.CopyTo(newBuffer, 0);
buffer = newBuffer;
}
buffer[chars++] = chr;
}
}
if (chars > 0)
yield return new StrRow(++rowNumber, new SqlChars(buffer));
}
else
{
foreach (char chr in sourceString.Value)
{
foreach (char delim in delims)
{
if (chr == delim && chars > 0)
{
yield return new StrRowString(++rowNumber, new SqlString(new string(buffer, 0, chars)));
buffer = new char[bufferSize];
chars = 0;
}
isDelim = true;
break;
}
if (isDelim)
continue;
if (chars == bufferSize)
{
bufferSize = chars + chars / 2;
char[] newBuffer = new char[bufferSize];
buffer.CopyTo(newBuffer, 0);
buffer = newBuffer;
}
buffer[chars++] = chr;
}
if (chars > 0)
yield return new StrRow(++rowNumber, new SqlChars(buffer));
}
}
/// <summary>
/// Splits CSV string using specified delimiter
/// This function auto allocates necessary buffer
/// </summary>
/// <param name="sourceString">Source string to be split</param>
/// <param name="delimiter">Delimiter to be used to split source string</param>
/// <returns>IEnumerable</returns>
[SqlFunction(FillRowMethodName = "FillSplitString")]
public static IEnumerable SplitString(SqlString sourceString, SqlString delimiter)
{
char[] buffer = new char[10];
char delim = delimiter.Value[0];
int rowNumber = 0;
int chars = 0;
char[] finalString;
foreach (char chr in sourceString.Value)
{
if (chr == delim)
{
finalString = new char[chars];
Array.Copy(buffer, finalString, chars);
yield return new StrRow(++rowNumber, new SqlChars(finalString));
chars = 0;
}
else
{
//increase buffer by half of it's current size
if (chars == buffer.Length)
{
char[] newBuffer = new char[chars + chars / 2];
buffer.CopyTo(newBuffer, 0);
buffer = newBuffer;
}
buffer[chars++] = chr;
}
}
if (chars > 0)
{
finalString = new char[chars];
Array.Copy(buffer, finalString, chars);
yield return new StrRow(++rowNumber, new SqlChars(finalString));
}
}
/// <summary>
/// FillRow method to populate the output table
/// </summary>
/// <param name="obj">StrRow passed as object</param>
/// <param name="rowId">rowID of returned string part (item number in the parsed string)</param>
/// <param name="value">item of the splitted string</param>
public static void FillSplitString(object obj, out int rowId, out SqlChars value)
{
StrRow r = (StrRow)obj;
rowId = r.RowId;
value = r.Value;
}
//public static void FillSplitString(object obj, out int rowId, out SqlString value)
//{
// StrRowString r = (StrRowString)obj;
// rowId = r.RowId;
// value = r.Value;
//}
}
| 9,517
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.